Anda di halaman 1dari 53

Microcontroller

IR sensor

pin 2 of the 74HC14N is the counter's input

U1 1 74LS90 TTL BCD Counter IC 7490,74HC90 Output of counter will go to the microcontroller..

TIMER IN MICROCONTROLLER
The 8051 comes equipped with two timers, both of which may be controlled, set, read, and configured individually. The 8051 timers have three general functions: 1) Keeping time and/or calculating the amount of time between events, 2) Counting the events themselves, or 3) Generating baud rates for the serial port. The three timer uses are distinct so we will talk about each of them separately. The first two uses will be discussed in this chapter while the use of timers for baud rate generation will be discussed in the chapter relating to serial ports.

How does a timer count?


How does a timer count? The answer to this question is very simple: A timer always counts up. It doesnt matter whether the timer is being used as a timer, a counter, or a baud rate generator: A timer is always incremented by the microcontroller. Programming Tip: Some derivative chips actually allow the program to configure whether the timers count up or down. However, since this option only exists on some derivatives it is beyond the scope of this tutorial which is aimed at the standard 8051. It is only mentioned here in the event that you absolutely need a timer to count backwards, you will know that you may be able to find an 8051-compatible microcontroller that does it.

USING TIMERS TO MEASURE TIME


Obviously, one of the primary uses of timers is to measure time. We will discuss this use of timers first and will subsequently discuss the use of timers to count events. When a timer is used to measure time it is also called an "interval timer" since it is measuring the time of the interval between two events.

How long does a timer take to count?


First, its worth mentioning that when a timer is in interval timer mode (as opposed to event counter mode) and correctly configured, it will increment by 1 every machine cycle. As you will recall from the previous chapter, a single machine cycle consists of 12 crystal pulses. Thus a running timer will be incremented:

11,059,000 / 12 = 921,583 921,583 times per second. Unlike instructions--some of which require 1 machine cycle, others 2, and others 4--the timers are consistent: They will always be incremented once per machine cycle. Thus if a timer has counted from 0 to 50,000 you may calculate: 50,000 / 921,583 = .0542 .0542 seconds have passed. In plain English, about half of a tenth of a second, or one-twentieth of a second. Obviously its not very useful to know .0542 seconds have passed. If you want to execute an event once per second youd have to wait for the timer to count from 0 to 50,000 18.45 times. How can you wait "half of a time?" You cant. So we come to another important calculation. Lets say we want to know how many times the timer will be incremented in .05 seconds. We can do simple multiplication: .05 * 921,583 = 46,079.15. This tells us that it will take .05 seconds (1/20th of a second) to count from 0 to 46,079. Actually, it will take it .049999837 seconds--so were off by . 000000163 seconds--however, thats close enough for government work. Consider that if you were building a watch based on the 8051 and made the above assumption your watch would only gain about one second every 2 months. Again, I think thats accurate enough for most applications--I wish my watch only gained one second every two months! Obviously, this is a little more useful. If you know it takes 1/20th of a second to count from 0 to 46,079 and you want to execute some event every second you simply wait for the timer to count from 0 to 46,079 twenty times; then you execute your event, reset the timers, and wait for the timer to count up another 20 times. In this manner you will effectively execute your event once per second, accurate to within thousandths of a second. Thus, we now have a system with which to measure time. All we need to review is how to control the timers and initialize them to provide us with the information we need.

Timer SFRs
As mentioned before, the 8051 has two timers which each function essentially the same way. One timer is TIMER0 and the other is TIMER1. The two timers share two SFRs (TMOD and TCON) which control the timers, and each timer also has two SFRs dedicated solely to itself (TH0/TL0 and TH1/TL1). Weve given SFRs names to make it easier to refer to them, but in reality an SFR has a numeric address. It is often useful to know the numeric address that corresponds to an SFR name. The SFRs relating to timers are:
SFR Name TH0 TL0 TH1 TL1 TCON TMOD Description Timer 0 High Byte Timer 0 Low Byte Timer 1 High Byte Timer 1 Low Byte Timer Control Timer Mode SFR Address 8Ch 8Ah 8Dh 8Bh 88h 89h

When you enter the name of an SFR into an assembler, it internally converts it to a number. For example, the command: MOV TH0,#25h moves the value 25h into the TH0 SFR. However, since TH0 is the same as SFR address 8Ch this command is equivalent to: MOV 8Ch,#25h Now, back to the timers. First, lets talk about Timer 0. Timer 0 has two SFRs dedicated exclusively to itself: TH0 and TL0. Without making things too complicated to start off with, you may just think of this as the high and low byte of the timer. That is to say, when Timer 0 has a value of 0, both TH0 and TL0 will contain 0. When Timer 0 has the value 1000, TH0 will hold the high byte of the value (3 decimal) and TL0 will contain the low byte of the value (232 decimal). Reviewing low/high byte notation, recall that you must multiply the high byte by 256 and add the low byte to calculate the final value. That is to say: TH0 * 256 + TL0 = 1000 3 * 256 + 232 = 1000

Timer 1 works the exact same way, but its SFRs are TH1 and TL1. Since there are only two bytes devoted to the value of each timer it is apparent that the maximum value a timer may have is 65,535. If a timer contains the value 65,535 and is subsequently incremented, it will reset--or overflow--back to 0.

The TMOD SFR


Lets first talk about our first control SFR: TMOD (Timer Mode). The TMOD SFR is used to control the mode of operation of both timers. Each bit of the SFR gives the microcontroller specific information concerning how to run a timer. The high four bits (bits 4 through 7) relate to Timer 1 whereas the low four bits (bits 0 through 3) perform the exact same functions, but for timer 0. The individual bits of TMOD have the following functions: TMOD (89h) SFR
Bit Name 7 Explanation of Function Timer 1 When this bit is set the timer will only run when INT1 (P3.3) is GATE1 high. When this bit is clear the timer will run regardless of the state of INT1. C/T1 T1M1 T1M0 When this bit is set the timer will count events on T1 (P3.5). When this bit is clear the timer will be incremented every machine cycle. Timer mode bit (see below) Timer mode bit (see below)

6 5 4 3

1 1 1 0

When this bit is set the timer will only run when INT0 (P3.2) is GATE0 high. When this bit is clear the timer will run regardless of the state of INT0. C/T0 T0M1 T0M0 When this bit is set the timer will count events on T0 (P3.4). When this bit is clear the timer will be incremented every machine cycle. Timer mode bit (see below) Timer mode bit (see below)

2 1 0

0 0 0

As you can see in the above chart, four bits (two for each timer) are used to specify a mode of operation. The modes of operation are:
TxM1 0 0 1 1 TxM0 0 1 0 1 Timer Mode 0 1 2 3 Description of Mode 13-bit Timer. 16-bit Timer 8-bit auto-reload Split timer mode

13-bit Time Mode (mode 0)

Timer mode "0" is a 13-bit timer. This is a relic that was kept around in the 8051 to maintain compatability with its predecesor, the 8048. Generally the 13bit timer mode is not used in new development. When the timer is in 13-bit mode, TLx will count from 0 to 31. When TLx is incremented from 31, it will "reset" to 0 and increment THx. Thus, effectively, only 13 bits of the two timer bytes are being used: bits 0-4 of TLx and bits 0-7 of THx. This also means, in essence, the timer can only contain 8192 values. If you set a 13-bit timer to 0, it will overflow back to zero 8192 machine cycles later. Again, there is very little reason to use this mode and it is only mentioned so you wont be surprised if you ever end up analyzing archaeic code which has been passed down through the generations (a generation in a programming shop is often on the order of about 3 or 4 months).

16-bit Time Mode (mode 1)


Timer mode "1" is a 16-bit timer. This is a very commonly used mode. It functions just like 13-bit mode except that all 16 bits are used. TLx is incremented from 0 to 255. When TLx is incremented from 255, it resets to 0 and causes THx to be incremented by 1. Since this is a full 16-bit timer, the timer may contain up to 65536 distinct values. If you set a 16-bit timer to 0, it will overflow back to 0 after 65,536 machine cycles.

8-bit Time Mode (mode 2)


Timer mode "2" is an 8-bit auto-reload mode. What is that, you may ask? Simple. When a timer is in mode 2, THx holds the "reload value" and TLx is the timer itself. Thus, TLx starts counting up. When TLx reaches 255 and is subsequently incremented, instead of resetting to 0 (as in the case of modes 0 and 1), it will be reset to the value stored in THx. For example, lets say TH0 holds the value FDh and TL0 holds the value FEh. If we were to watch the values of TH0 and TL0 for a few machine cycles this is what wed see:

Machine Cycle TH0 Value TL0 Value 1 FDh FEh

2 3 4 5 6 7

FDh FDh FDh FDh FDh FDh

FFh FDh FEh FFh FDh FEh

As you can see, the value of TH0 never changed. In fact, when you use mode 2 you almost always set THx to a known value and TLx is the SFR that is constantly incremented. Whats the benefit of auto-reload mode? Perhaps you want the timer to always have a value from 200 to 255. If you use mode 0 or 1, youd have to check in code to see if the timer had overflowed and, if so, reset the timer to 200. This takes precious instructions of execution time to check the value and/or to reload it. When you use mode 2 the microcontroller takes care of this for you. Once youve configured a timer in mode 2 you dont have to worry about checking to see if the timer has overflowed nor do you have to worry about resetting the value--the microcontroller hardware will do it all for you. The auto-reload mode is very commonly used for establishing a baud rate which we will talk more about in the Serial Communications chapter.

Split Timer Mode (mode 3)


Timer mode "3" is a split-timer mode. When Timer 0 is placed in mode 3, it essentially becomes two separate 8-bit timers. That is to say, Timer 0 is TL0 and Timer 1 is TH0. Both timers count from 0 to 255 and overflow back to 0. All the bits that are related to Timer 1 will now be tied to TH0. While Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be put into modes 0, 1 or 2 normally--however, you may not start or stop the real timer 1 since the bits that do that are now linked to TH0. The real timer 1, in this case, will be incremented every machine cycle no matter what. The only real use I can see of using split timer mode is if you need to have two separate timers and, additionally, a baud rate generator. In such case you can use the real Timer 1 as a baud rate generator and use TH0/TL0 as two separate timers.

The TCON SFR

Finally, theres one more SFR that controls the two timers and provides valuable information about them. The TCON SFR has the following structure: TCON (88h) SFR
Bit Name 7 6 5 4 TF1 TR1 TF0 TR0 Bit Address 8Fh 8Eh 8Dh 8Ch Explanation of Function Timer 1 Overflow. This bit is set by the microcontroller when Timer 1 overflows. Timer 1

Timer 1 Run. When this bit is set Timer 1 is turned on. When this 1 bit is clear Timer 1 is off. Timer 0 Overflow. This bit is set by the microcontroller when Timer 0 overflows. 0

Timer 0 Run. When this bit is set Timer 0 is turned on. When this 0 bit is clear Timer 0 is off.

As you may notice, weve only defined 4 of the 8 bits. Thats because the other 4 bits of the SFR dont have anything to do with timers--they have to do with Interrupts and they will be discussed in the chapter that addresses interrupts. A new piece of information in this chart is the column "bit address." This is because this SFR is "bit-addressable." What does this mean? It means if you want to set the bit TF1--which is the highest bit of TCON--you could execute the command: MOV TCON, #80h ... or, since the SFR is bit-addressable, you could just execute the command: SETB TF1 This has the benefit of setting the high bit of TCON without changing the value of any of the other bits of the SFR. Usually when you start or stop a timer you dont want to modify the other values in TCON, so you take advantage of the fact that the SFR is bit-addressable.

Initializing a Timer
Now that weve discussed the timer-related SFRs we are ready to write code that will initialize the timer and start it running. As youll recall, we first must decide what mode we want the timer to be in. In this case we want a 16-bit timer that runs continuously; that is to say, it is not dependent on any external pins.

We must first initialize the TMOD SFR. Since we are working with timer 0 we will be using the lowest 4 bits of TMOD. The first two bits, GATE0 and C/T0 are both 0 since we want the timer to be independent of the external pins. 16-bit mode is timer mode 1 so we must clear T0M1 and set T0M0. Effectively, the only bit we want to turn on is bit 0 of TMOD. Thus to initialize the timer we execute the instruction: MOV TMOD,#01h Timer 0 is now in 16-bit timer mode. However, the timer is not running. To start the timer running we must set the TR0 bit We can do that by executing the instruction: SETB TR0 Upon executing these two instructions timer 0 will immediately begin counting, being incremented once every machine cycle (every 12 crystal pulses).

Reading the Timer


There are two common ways of reading the value of a 16-bit timer; which you use depends on your specific application. You may either read the actual value of the timer as a 16-bit number, or you may simply detect when the timer has overflowed.

Reading the value of a Timer


If your timer is in an 8-bit mode--that is, either 8-bit AutoReload mode or in split timer mode--then reading the value of the timer is simple. You simply read the 1-byte value of the timer and youre done. However, if youre dealing with a 13-bit or 16-bit timer the chore is a little more complicated. Consider what would happen if you read the low byte of the timer as 255, then read the high byte of the timer as 15. In this case, what actually happened was that the timer value was 14/255 (high byte 14, low byte 255) but you read 15/255. Why? Because you read the low byte as 255. But when you executed the next instruction a small amount of time passed--but enough for the timer to increment again at which time the value rolled over from 14/255 to 15/0. But in the process youve read the timer as being 15/255. Obviously theres a problem there.

The solution? Its not too tricky, really. You read the high byte of the timer, then read the low byte, then read the high byte again. If the high byte read the second time is not the same as the high byte read the first time you repeat the cycle. In code, this would appear as:
REPEAT: MOV A,TH0 MOV R0,TL0 CJNE A,TH0,REPEAT ...

In this case, we load the accumulator with the high byte of Timer 0. We then load R0 with the low byte of Timer 0. Finally, we check to see if the high byte we read out of Timer 0--which is now stored in the Accumulator--is the same as the current Timer 0 high byte. If it isnt it means weve just "rolled over" and must reread the timers value--which we do by going back to REPEAT. When the loop exits we will have the low byte of the timer in R0 and the high byte in the Accumulator. Another much simpler alternative is to simply turn off the timer run bit (i.e. CLR TR0), read the timer value, and then turn on the timer run bit (i.e. SETB TR0). In that case, the timer isnt running so no special tricks are necessary. Of course, this implies that your timer will be stopped for a few machine cycles. Whether or not this is tolerable depends on your specific application.

Detecting Timer Overflow


Often it is necessary to just know that the timer has reset to 0. That is to say, you are not particularly interest in the value of the timer but rather you are interested in knowing when the timer has overflowed back to 0. Whenever a timer overflows from its highest value back to 0, the microcontroller automatically sets the TFx bit in the TCON register. This is useful since rather than checking the exact value of the timer you can just check if the TFx bit is set. If TF0 is set it means that timer 0 has overflowed; if TF1 is set it means that timer 1 has overflowed. We can use this approach to cause the program to execute a fixed delay. As youll recall, we calculated earlier that it takes the 8051 1/20th of a second to count from 0 to 46,079. However, the TFx flag is set when the timer overflows back to 0. Thus, if we want to use the TFx flag to indicate when 1/20th of a second has passed we must set the timer initially to 65536 less 46079, or 19,457. If we set the timer to 19,457, 1/20th of a second later the timer will

overflow. Thus we come up with the following code to execute a pause of 1/20th of a second: MOV TH0,#76;High byte of 19,457 (76 * 256 = 19,456) MOV TL0,#01;Low byte of 19,457 (19,456 + 1 = 19,457) MOV TMOD,#01;Put Timer 0 in 16-bit mode SETB TR0;Make Timer 0 start counting JNB TF0,$;If TF0 is not set, jump back to this same instruction In the above code the first two lines initialize the Timer 0 starting value to 19,457. The next two instructions configure timer 0 and turn it on. Finally, the last instruction JNB TF0,$, reads "Jump, if TF0 is not set, back to this same instruction." The "$" operand means, in most assemblers, the address of the current instruction. Thus as long as the timer has not overflowed and the TF0 bit has not been set the program will keep executing this same instruction. After 1/20th of a second timer 0 will overflow, set the TF0 bit, and program execution will then break out of the loop. Timing the length of events The 8051 provides another cool toy that can be used to time the length of events. For example, let's say we're trying to save electricity in the office and we're interested in how long a light is turned on each day. When the light is turned on, we want to measure time. When the light is turned off we don't. One option would be to connect the lightswitch to one of the pins, constantly read the pin, and turn the timer on or off based on the state of that pin. While this would work fine, the 8051 provides us with an easier method of accomplishing this. Looking again at the TMOD SFR, there is a bit called GATE0. So far we've always cleared this bit because we wanted the timer to run regardless of the state of the external pins. However, now it would be nice if an external pin could control whether the timer was running or not. It can. All we need to do is connect the lightswitch to pin INT0 (P3.2) on the 8051 and set the bit GATE0. When GATE0 is set Timer 0 will only run if P3.2 is high. When P3.2 is low (i.e., the lightswitch is off) the timer will automatically be stopped. Thus, with no control code whatsoever, the external pin P3.2 can control whether or not our timer is running or not.

USING TIMERS AS EVENT COUNTERS

We've discussed how a timer can be used for the obvious purpose of keeping track of time. However, the 8051 also allows us to use the timers to count events. How can this be useful? Let's say you had a sensor placed across a road that would send a pulse every time a car passed over it. This could be used to determine the volume of traffic on the road. We could attach this sensor to one of the 8051's I/O lines and constantly monitor it, detecting when it pulsed high and then incrementing our counter when it went back to a low state. This is not terribly difficult, but requires some code. Let's say we hooked the sensor to P1.0; the code to count cars passing would look something like this:
JNB P1.0,$ ;If a car hasn't raised the signal, keep waiting JB P1.0,$ ;The line is high which means the car is on the sensor right now INC COUNTER ;The car has passed completely, so we count it

As you can see, it's only three lines of code. But what if you need to be doing other processing at the same time? You can't be stuck in the JNB P1.0,$ loop waiting for a car to pass if you need to be doing other things. Of course, there are ways to get around even this limitation but the code quickly becomes big, complex, and ugly. Luckily, since the 8051 provides us with a way to use the timers to count events we don't have to bother with it. It is actually painfully easy. We only have to configure one additional bit. Let's say we want to use Timer 0 to count the number of cars that pass. If you look back to the bit table for the TCON SFR you will there is a bit called "C/T0"--it's bit 2 (TCON.2). Reviewing the explanation of the bit we see that if the bit is clear then timer 0 will be incremented every machine cycle. This is what we've already used to measure time. However, if we set C/T0 timer 0 will monitor the P3.4 line. Instead of being incremented every machine cycle, timer 0 will count events on the P3.4 line. So in our case we simply connect our sensor to P3.4 and let the 8051 do the work. Then, when we want to know how many cars have passed, we just read the value of timer 0--the value of timer 0 will be the number of cars that have passed. So what exactly is an event? What does timer 0 actually "count?" Speaking at the electrical level, the 8051 counts 1-0 transitions on the P3.4 line. This means that when a car first runs over our sensor it will raise the input to a high ("1") condition. At that point the 8051 will not count anything since this is a 0-1 transition. However, when the car has passed the sensor will fall back to a low

("0") state. This is a 1-0 transition and at that instant the counter will be incremented by 1. It is important to note that the 8051 checks the P3.4 line each instruction cycle (12 clock cycles). This means that if P3.4 is low, goes high, and goes back low in 6 clock cycles it will probably not be detected by the 8051. This also means the 8051 event counter is only capable of counting events that occur at a maximum of 1/24th the rate of the crystal frequency. That is to say, if the crystal frequency is 12.000 Mhz it can count a maximum of 500,000 events per second (12.000 Mhz * 1/24 = 500,000). If the event being counted occurs more than 500,000 times per second it will not be able to be accurately counted by the 8051.

BASIC PROGRAMMING OF 89S52 IN KEIL


The C source code is very high level language, meaning that it is far from being at the base level of the machine language that can be executed by a processor. This machine language is basically just zero's and one's and is written in Hexadecimal format, that why they are called HEX files.

There are several types of HEX files; we are going to produce machine code in the INTEL HEX-80 format, since this is the output of the KEIL IDE that we are going to use. Figure 2.1.A shows that to convert a C program to machine language, it takes several steps depending on the tool you are using, however, the main idea is to produce a HEX file at the end. This HEX file will be then used by the 'burner' to write every byte of data at the appropriate place in the EEPROM of the 89S52.

figure 2.1.A

2.2. Variables and constants


Variables
One of the most basic concepts of programming is to handle variables. knowing the exact type and size of a variable is a very important issue for microcontroller programmers, because the RAM is usually limited is size. There are two main design considerations to be taken in account when choosing the variables types: the occupied space in ram and the processing speed. Logically, a variable that occupies a big number of registers in RAM will be more slowly processed than a small variable that fits on a single register. For you to chose the right variable type for each one of your applications, you will have to refer to the following table:

Data Type bit signed char unsigned char signed int unsigned int signed long unsigned long float

Bits 1 8 8 16 16 32 32 32

Bytes -1 1 2 2 4 4 4

Value Range 0 to 1 -128 to +127 0 to 255 -32768 to +32767 0 to 65535 -2147483648 to 2147483647 0 to 4294967295 1.175494E-38 to 3.402823E+38

This table shows the number of bits and bytes occupied by each types of variables, noting that each byte will fit into a register. You will notice that most variables can be either 'signed' or unsigned 'unsigned', and the major difference between the two types is the range, but both will occupy the same exact space in memory. The names of the variables shown in the table are the same that are going to be used in the program for variables declarations. Note that in C programming language, any variable have to be declared to be used. Declaring a variable, will attribute a specific location in the RAM or FLASH memory to that variable. The size of that location will depend on the type of the variable that have been declared. To understand the difference between those types, consider the following example source code where we start by declaring three 'unsigned char' variables, and one 'signed char' and then perform some simple operations: unsigned char a,b,c; signed char d; a = 100; b = 200; c = a - b; d = a - b; In that program the values of 'c' will be equal to '155'! and not '-100' as you though, because the variable 'c' is an unsigned type, and when a the value to be stored in a variable is bigger than the maximum value range of this variable, it overflows and rolls back to the other limit. Back to our example, the program is trying to store '100' in 'c', but since 'c' is unsigned, its range of values is from '0 to 255' so, trying to store a value below zero, will cause the the variable to overflow, and the compiler will subtract the '-100' from the other limit plus 1, from '255 + 1' giving '156'. We add 1 to the range because the overflow and roll back operation from 0 to 255 counts for the subtraction of one bit. On the other hand, the value of 'd' will be equal to '-100' as expected, because it is a 'signed' variable. Generally, we try to avoid storing value that are out of range, because sometime, even if the compiler doesn't halt on that error, the results can be sometimes totally un-expected. Note that in the C programming language, any code line is ended with a semicolon ';', except for the lines ending with brackets '{' '}'. Like in any programming language, the concept of a variables 'array' can also be

used for microcontrollers programming. an array is like a table or a group of variables of the same type, each one can be called by a specific number, for example an array can be declared this way: char display[10]; this will create a group of 10 variables. Each one of them is accessible by its number, example: display[0] = 100; display[3] = 60; display[1] = display[0] - display[3]; where 'display[1]' will be equal to '40'. Note that 'display' contains 10 different variables, numbered from 0 to 9. In that previous example, according to the variable declaration, there is not such variable location as 'display[10]', and using it will cause an error in the compiler.

Constants
Sometimes, you want to store a very large amount of constant values, that wouldn't fit in the RAM or simply would take too much space. you can store this DATA in the FLASH memory reserved for the code, but it wont be editable, once the program is burned on your chip. The advantage of this technique is that it can be used to store a huge amount of variables, noting that the FLASH memory of the 89S52 is 8K bytes, 32 times bigger than the RAM memory. It is, however, your responsibility to distribute this memory between your program and your DATA. To specify that a variable is to be stored in the FLASH memory, we use exactly the same variable types names but we add the prefix 'code' before it. Example: code unsigned char message[500]; This line would cause this huge array to be stored in the FLASH memory. This can be interesting for displaying messages on an LCD screen. To access the pins and the ports through programming, there are a number of predefined variables (defined in the header file, as you shall see later) that dramatically simplifies that task. There are 4 ports, Port 0 to Port 3, each one of them can be accessed using the char variablesP0, P1, P2 and P3 respectively. In those char types variables, each one of the 8 bits represents a pin on the port. Additionally, you can access a single pin of a port using the bit type variablesPX_0 to PX_7, where X takes a value between 0 and 3, depending on the port being accessed. For example P1_3 is the pin number 3 of port 1. You can also define your own names, using the '#define' directive. Note that this is compiler directive, meaning that the compiler will use this directive to read and understand the code, but it is not a statement or command that can be translated to machine language. For example, you could define the following:

#define LED1 P1_0

With the definition above, the compiler will replace every occurrence of LED1 by P1_0. This makes your code much more easier to read, especially when the new names you give make more sense. You could also define a numeric constant value like this: #define led_on_time 184 Then, each time you write led_on_time, it will be replaced by 184. Note that this is not a variable and accordingly, you cannot write something like: led_on_time = 100; //That's wrong, you cannot change a constant's value in code. The utility of using defined constants, appears when you want to adjust some delays in your code, or some constant variables that are re-used many times within the code: With a predefined constant, you only change it's value once, and it's applied to the whole code. that's for sure apart from the fact that a word like led_on_time is much more comprehensive than simply '184'! Along this tutorial you will see how port names, and special function registers are used exactly as variables, to control input/output operations and other features of the microcontroller like timers, counters and interrupts.

2.3. Mathematical & logic operations


Now that you know how to declare variables, it is time to know how to handle them in your program using mathematical and logic operations.

Mathematical operations:
The most basic concept about mathematical operations in programming languages, is the '=' operator which is used to store the content of the expression at its right, into the variable at its left. For example the following code will store the value of 'b' into 'a' : a = b; And subsequently, the following expression in totally invalid: 5 = b; Since 5 in a constant, trying to store the content of 'b' in it will cause an error. You can then perform all kind of mathematical operations, using the operators '+','-','*' and '/'. You can also use brackets '( )' when needed. Example: a =(5*b)+((a/b)*(a+b)); If you include 'math.h' header file, you will be able to use more advanced functions in your equations like Sin, Cos and Tan trigonometric functions, absolute values and logarithmic calculations like in the following example:

a =(c*cos(b))+sin(b); To be able to successfully use those functions in your programs, you have to know the type of variables that those functions take as parameter and return as a result. For example a Cosine function takes an angle in radians whose value is a float number between -65535 and 65535 and it will return a float value as a result. You can usually know those data types from the 'math.h' file itself, for example, the cosine function, like all the others is declared in the top of the math header file, and you can read the line: extern float cos (float val); from this line you can deduce that the 'cos' function returns a float data type, and takes as a parameter a float too. (the parameter is always between brackets.). Using the same technique, you can easily know how to deal with the rest of the functions of the math header file. the following table shows a short description of those functions:

Function char cabs (char val); int abs (int val); long labs (long val); float fabs (float val); float sqrt (float val); float exp (float val); float float float float float float float float float float float float float float float float log (float val); log10 (float val); sin (float val); cos (float val); tan (float val); asin (float val); acos (float val); atan (float val); sinh (float val); cosh (float val); tanh (float val);

Description Return an the absolute value of a char variable. Return an the absolute value of a int variable. Return an the absolute value of a long variable. Return an the absolute value of a float variable. Returns the square root of a float variable. Returns the value of the Euler number 'e' to the power of val Returns the natural logarithm of val Returns the common logarithm of val

A set of standard trigonometric functions. They all take angles measured in radians whose value have to be between -65535 and 65535.

This function calculates the arc tan of the ratio y / x, using the signs of both x and y to determine the atan2 (float y, float x); quadrant of the angle and return a number ranging from -pi to pi. Calculates the smallest integer that is bigger than val. ceil (float val); Example: ceil(4.3) = 5. Calculates the largest integer that is smaller than val. floor (float val); Example: ceil(4.8) = 4. Returns the remainder of x / y. For example: fmod (float x, float y); fmod(15.0,4.0) = 3. pow (float x, float y); Returns x to the power y.

Logical operations:
You can also perform logic operations with variables, like AND, OR and NOT

operations, using the following operators: Operator ! ~ & | Description NOT (bit level) Example: P1_0 = !P1_0; NOT (byte level) Example: P1 = ~P1; AND OR

Note that those logic operation are performed on the bit level of the registers. To understand the effect of such operation on registers, it's easier to look at the bits of a variable (which is composed of one or more register). For example, a NOT operation will invert all the bit of a register. Those logic operators can be used in many ways to merge different bits of different registers together. For example, consider the variable 'P1', which is of type 'char', and hence stored in an 8-bit register. Actually P1 is an SFR, whose 8 bits represents the 8 I/O pins of Port 1. It is required in that example to clear the 4 lower bits of that register without changing the state of the 4 other which may be used by other equipment. This can be done using logical operators according to the following code: P1 = P1 & 0xF0; (Adding '0x' before a number indicates that it is a hexadecimal one) Here, the value of P1 is ANDed with the variable 0xF0, which in the binary base is '11110000'. Recalling the two following relations: 1 AND X = X 0 AND X = 0 (where 'X' can be any binary value) You can deduce that the 4 higher bits of P1 will remain unchanged, while the 4 lower bits will be cleared to 0. By the way, note that you could also perform the same operation using a decimal variable instead of a hexadecimal one, for example, the following code will have exactly the same effect than the previous one (because 240 = F0 in HEX): P1 = P1 & 240; A similar types of operations that can be performed on a port, is to to set some of its bits to 1 without affecting the others. For example, to set the first and last bit of P1, without affecting the other, the following source code can be used: P1 = P1 | 0x81; Here, P1 is ORed with the value 0x81, which is '10000001' in binary. Recalling the two following relations: 1 OR X = 1 0 OR X = X (where 'X' can be any binary value) You can deduce that the first and last pins of P1 will be turned on, without affecting

the state of the other pins of port 1. Those are just a few example of the manipulations that can be done to registers using logical operators. Logic operators can also be used to define very specific conditions, as you shall see in the next section. The last types of logic operation studied in this tutorial is the shifting. It can be useful the shift the bit of a register the right or to the left in various situations. this can be done using the following two operators: Operator >> << Description Shift to the right Shift to the left

The syntax is is quite intuitive, for example: P1 = 0x01; // After that operation, in binary, P1 = 0000 0001 P1 = (P1 << 7) // After that operation, in binary P1 = 1000 0000 You can clearly notice that the content of P1 have been shifted 8 steps to the left.

2.4. Conditions and loops


In most programs, it is required at a certain time, to differentiate between different situations, to make decision according to specific input, or to direct the flow of the code depending on some criteria. All the above situation describe an indispensable aspect of programming: 'conditions'. In other words, this feature allows to execute a block of code only under certain conditions, and otherwise execute another code block or continue with the flow of the program. The most famous way to do that is to use the 'if' statement, according to the following syntax. if (expression) { ... code to be executed ... } It is important to see how the code is organized in this part. The 'expression' is the condition that shall be valid for the 'code block' to be executed. the code block is all delimited by the two brackets '{' and '}'. In other words, all the code between those two brackets will be executed if and only if the expression is valid. The expression can be any combination of mathematical and logical expressions, as you can see in the following example: if ( (P1 == 0) & (a <= 128) ){ ... code to be executed ...

} Notice the use of the two equal signs (==) between two variables or constants, In C language, this means that you are asking whether P1 equals 0 or not. writing this expression with only one equal sign, would cause the the compiler to store 0 in P1. This issue is a source of logical error for many beginners in C language, this error wont generate any alert from the compiler and is very hard to identify in a big program, so pay attention, it can save you lot of debugging time. Otherwise it is clear that in that previous example, the code block is only executed if both the two expressions are true. Here is a list of all the operators you can use to write an expression describing a certain condition:

Operator == <, > <=, >= !=

Description Equal to Smaller than, bigger than. Smaller than or equal to, bigger than or equal to. Not equal to

The 'If' code block can get a little more sophisticated by introducing the 'else' and 'else if' statement. Observe the following example source code: if (expression_1) { ... code block 1 ... }else if(expression_2) { ... code block 2 ... }else if(expression_3) { ... code block 3 ... }else{ ... code block 4 ... } Here, There are four different code blocks, only one shall be executed if and only if the corresponding condition is true. The last code block will only be executed if none of the previous expression is valid. Note that you can have as many 'else if' blocks as you need, each one with its corresponding condition, BUT you can only have one 'else' block, which is completely logical. However you can chose not to have and 'else' block at all if you want. There are some other alternatives to the 'if...else' code block, that can provide faster execution speeds, but also have some limitations and restrictions like the 'Select...case' code block. For now, it is enough to understand the 'if...else' code block, whose performance is quite fair and have a wide range of applications. Another very important tool in the programming languages is the loop. In C

language like in many others, loops are usually restricted to certain number of loops like in the 'for' code block or restricted to a certain condition like the 'while' block. Let's start with the 'for' code block, which is a highly controllable and configurable loop. consider the following example source code:

for(i=0;i<10;i++){ P0 = i; } Here the code between the the two brackets '{' '}' will be be executed a certain number of times, each time with the counting variable 'i' increasing by 1 according to the statement 'i++'. The code will keep looping as long as the condition 'i<10' is true. Usually the counting value 'i' is reused in the body of the loop, which makes the particularity of this loop. The 'for' loop functioning can be recapitulated by the following syntax: for(start;condition;step){ ... code block ... } Where start represents the start value assigned to the count value before the loop begins. Thecondition is the expression that is is to remain true for the loop to continue; as long as this conditions is satisfied, the code will keep looping. Finally, step is the increase or decrease of the counting variable, it can be any statement that changes its value, whether by an addition or subtraction. The second type of loop that we are going to study is the 'while' loop. the syntax of this one is simpler than the previous one, as you can observe in the following example source code, that is equivalent to the previous method: while(i < 10){ P0 = i; i = i +1; } Here there is only one parameter to be defined, which is the condition to keep this loop alive, which is 'i < 10' in our example. Then, it is the responsibility of the programmer to design the software carefully to provide an exit for that loop, or to make it an infinite loop. Both techniques are commonly used in microcontroller programs, as you shall see later on along this tutorial.

2.5. Functions
Functions are way of organizing your code, reducing its size, and increasing its overall performance, by grouping relatively small parts of code to be reused many

times in the same program. A new function can be created according to the following syntax: Function_name(parameter_1, Parameter_2, Parameter_3){ ... function body ... return value (optional) ... } This is the general form of a function. The number of parameters of the function can be more than the three parameters of the examples above, as it can be zero, all depends on the type and use of the function. The function's body is usually a sub program that implies the parameters to produce the required result. some functions will also generate an output, like the cos() function, through the 'return' command, which will output the value next to it. Usually the 'return' command is used at the end of the function. A very common use of functions without return value is to create delays in a software, consider the following function: delay(unsigned int y){ unsigned int i; for(i=0;i<y;i++){ ; } } In this last piece of code a function named 'delay' is created, with an unsigned integer 'y' as a parameter, and implying a locally defined unsigned int 'i'. the function will repeat a loop for a couple hundreds or thousand of times to generate precise delays in a program. A function like this can be called from anywhere in the program according to the following syntax: delay(30000); this line of code would cause the program to pause for approximately one second on a 12 MHz clock on a 8051 microcontroller. A common example of a function with a return value, is a function that will calculate the angle in radian of a given angle in degrees, as all the trigonometric functions that are included by default take angles in radians. This function can be as the following: deg_to_rad(float deg){ float rad; rad = (deg * 3.14)/180; retrun rad; } This function named 'deg_to_rad' will take as a parameter an angle in degrees and output an angle in radians. It can be called in your program according to this syntax:

angle = deg_to_rad(102,18); where angle should be already defined as a float, and where will be stored the value returnedby the function, which is the angle in radians equivalent to 102.18 Another important note about functions in the 'main' function. Any C program must contain a function named 'main' which is the place where the program's execution will start. more precisely, for microcontrollers, it were the execution will start after a reset operation, or when a microcontroller circuit is turned ON. The 'main' function has no parameters, and is written like this: main(){ ... code of the main functions ... }

2.6. Organization of a C program


All C programs have this common organization scheme, sometimes it's followed, sometimes it's not, however, it is imperative for this category of programming that this organization scheme be followed in order to be able to develop your applications successfully. Any application can be divided into the following parts, noting that is should be written in this order: a. Headers Includes and constants definitions In this part, header files (.h) are included into your source code. those headers files can be system headers to declare the name of SFRs, to define new constants, or to include mathematical functions like trigonometric functions, root square calculations or numbers approximations. Header files can also contain your own functions that would be shared by various programs. b. Variables declarations More precisely, this part is dedicated to 'Global Variables' declarations. Variables declared in this place can be used anywhere in the code. Usually in microcontroller programs, variables are declared as global variables instead of local variables, unless your are running short of RAM memory and want to save some space, so we use local variables, whose values will be lost each time you switch from a function to another. To summarize, global variables as easier to use and implement than local variables, but they consume more memory space. d. functions' body Here you group all your functions. Those functions can be simple ones that can be called from another place in your program, as they can be called from an 'interrupt vector'. In other words, the sub-programs to be executed when an interrupt occurs is also written in this place. e. Initialization The particularity of this part is that it is executed only one time when the microcontroller was just subjected to a 'RESET' or when power is just switched ON, then the processor continue executing the rest of the program but never executes

this part again. This particularity makes it the perfect place in a program to initialize the values of some constants, or to define the mode of operation of the timers, counters, interrupts, and other features of the microcontroller. f. Infinite loop An infinite loop in a microcontroller program is what is going to keep it alive, because a processor have to be allays running for the system to function, exactly like a heart have to be always beating for a person to live. Usually this part is the core of any program, and its from here that all the other functions are called and executed.

2.7. Simple C program for 89S52


Here is a very simple but complete example program to blink a LED. Actually it is the source code of the example project that we are going to construct in the next part of the tutorial, but for now it is important to concentrate on the programming to summarize the notions discussed above. #include <REGX52.h> #include <math.h> delay(unsigned int y){ unsigned int i; for(i=0;i<y;i++){;} } main(){ while(1){ delay(30000); P1_0 = 0; delay(30000); P1_0 = 1; } } After including basic headers for the SFR definitions of the 8952 microcontroller (REGX52.h) and for mathematical functions (math.h), a function named 'delay' is created, which is simple a function to create a delay controlled via the parameter 'y'. Then comes the main function, with an infinite loop (the condition for that loop to remain will always be satisfied as it is '1'). Inside that loop, the pin number 0 of port 1 is constantly turned ON and OFF with a delay of approximately one second. As you will see in the next part, A simple circuit can be constructed and a LED can be connected to the pin P1_0 to see how software and hardware adjustments can affect the behavior of you circuits.

2.8. Using the KEIL environment


KEIL uVision is the name of a software dedicated to the development and testing of a family of microcontrollers based on 8051 technology, like the 89S52 which we are going to use along this tutorial. You can can download an evaluation version of KEIL at their website:http://www.keil.com/c51/. Most versions share merely the same

interface, this tutorial uses KEIL C51 uVision 3 with the C51 compiler v8.05a. To create a project, write and test the previous example source code, follow the following steps: Open Keil and start a new project:

Figure: 2.8.a

You will prompted to chose a name for your new project, Create a separate folder where all the files of your project will be stored, chose a name and click save. The following window will appear, where you will be asked to select a device for Target 'Target 1':

Figure: 2.8.b

From the list at the left, seek for the brand name ATMEL, then under ATMEL, select AT89S52. You will notice that a brief description of the device appears on the right. Leave the two upper check boxes unchecked and click OK. The AT89S52 will be called your 'Target device', which is the final destination of your source code. You will be asked whether to 'copy standard 8051 startup code' click No. click File, New, and something similar to the following window should appear. The box named 'Text1' is where your code should be written later.

Figure: 2.8.c

Now you have to click 'File, Save as' and chose a file name for your source code ending with the letter '.c'. You can name is 'code.c' for example, and click save. Then you have to add this file to your project work space at the left as shown in the following screen shot:

Figure: 2.8.d

After right-clicking on 'source group 1', click on 'Add files to group...', then you will be prompted to browse the file to add to 'source group 1', chose the file that you just saved, eventually 'code.c' and add it to the source group. You will notice that the file is added to the project tree at the left. In some versions of this software you have to turn ON manually the option to generate HEX files. make sure it is turned ON, by right-clicking on target 1, Options for target 'target 1', then under the 'output' tab, by checking the box 'generate HEX file'. This step is very important as the HEX file is the compiled output of your project that is going to be transferred to the microcontroller. You can then start to write the source code in the window titled 'code.c' then before testing your source code, you have to compile your source code, and correct eventual syntax errors. In KEIL IDE, this step is called 'rebuild all targets' and has

this icon:

Figure: 2.8.e

You can use the output window to track eventual syntax errors, but also to check the FLASH memory occupied by the program (code = 49) as well as the registers occupied in the RAM (data = 9). If after rebuilding the targets, the 'output window' shows that there is 0 error, then you are ready to test the performance of your code. In keil, like in most development environment, this step is called Debugging, and has this icon: . After clicking on the debug icon, you will notice that some part of the user interface will change, some new icons will appear, like the run icon circled in the following figure:

Figure: 2.8.f

You can click on the 'Run' icon and the execution of the program will start. In our example, you can see the behavior of the pin 0 or port one, but clicking on 'peripherals, I/O ports, Port 1'. You can always stop the execution of the program by clicking on the stop button ( 'reset' button . ) and you can simulate a reset by clicking on the

You can also control the execution of the program using the following icons: which allows you to follow the execution step by step. Then, when you're finished with the debugging, you can always return to the programming interface by clicking again on the debug button ( ).

There are many other features to discover in the KEIL IDE. You will easily discover them in first couple hours of practice, and the more important of them will be presented along the rest of this tutorial.

3.1. I/O port detailed structure


It is important to have some basic notions about the structure of an I/O port in the 8051 architecture. You will notice along this tutorial how this will affect our choices when it comes to connect I/O devices to the ports. Actually, the I/O ports configuration and mechanism of the 8051 can be confusing, due to the fact that a pin acts as an output pin as well as an input pin in the same time. Figure 3.1.A shows the internal diagram of a single I/O pin of port 1. The first thing you have to notice, is that there are two different direction for the data flow from the microcontroller's processor and the external pin: The Latch value and the Pin value. The latch value is the value that the microcontroller tries to output on the pin, while the pin value, is the actual logic state of the pin, regardless of the latch value that was set by the processor in the first place. The microcontroller reads the state of a pin through the Pin value line, and writes through the latch value line. If you imagine the behavior of the simple circuit in figure 3.1.A, you'll notice that the I/O pin should follow the voltage of the Latch value, providing 5V through the pull-up resistor, or 0V by connecting the pin directly to the GND through the transistor. When the pin is pulled high by the pull-up resistor, the pin can output 5V but can also be used as an input pin, because there is no any risk of short-circuit due to the presence of a resistor. This can be easily verified by connecting the pin to 0V or to 5V, the two possible outcomes are both unharmful for the microcontroller, and the PIN value line will easily follow the value imposed by the external connection. Now imagine the opposite configuration, where the latch value would be low, causing the pin to provide 0V, being directly connected to GND through the transistor. If in this situation, an external device tries to raise the pin's voltage to 5V, a short circuit will occur and some damage may be
figure 3.1.A: Basic I/O pin internal diagram

made to the microcontroller's port or to the external device connected to that pin. To summarize, in the 8051 architecture, to use a PIN as an input pin, you have to output '1', and the pin value will follow the value imposed by the device connected to it (switch, sensor, etc...). If you plan to use the pin as an output pin, then just output the required value without taking any of this in consideration. Even if some ports like P3 and P0 can have a slightly different internal composition than P1, due to the dual functions they assure, understanding the structure and functioning of port 1 as described above is fairly enough to use all the ports for basic I/O operations.

3.2 Simple output project: Blinking a led.


A first simple project to experiment with the output operations is to blink a LED. Assuming you have successfully written and compiled the code as explained in the previous part of the tutorial, now we are going to transfer the HEX file corresponding to that code on the 89s52 microcontroller. Let us recall that the HEX file is a machine language file, generated by the compiler, originally from a C code. The code for blinking a LED is as follow: #include <REGX52.h> #include <math.h> delay(unsigned int y){ unsigned int i; for(i=0;i<y;i++){;} } main(){ while(1){ delay(30000); P1_0 = 0; delay(30000); P1_0 = 1; } } Before transferring the HEX file to the target microcontroller, the hardware have to be constructed. First you have to provide a clean (noiseless) 5V power supply, by connecting the Vcc pin (40) to 5V and the GND pin (20) to 0V. Then you have provide a mean of regulating or generating the clock of the processor. The easiest and most efficient way to do this is to add a crystal resonator and 2 decoupling capacitors of approximately 30pF (see the crystal X1 and the capacitors C1 and C2 on figure 3.1). Then, you have connect pin 31 (EA) to 5V. The EA pin is an active low' pin that indicate the presence of an external memory. Activating this pin by providing 0V on it will tell the internal processor to use external memories and ignore the internal built-in memory of the chip. By providing 5V on the EA pin, its functionality is deactivated and the processor uses the internal memories (RAM and FLASH). At last, you have to connect a standard reset circuitry on pin 9 composed of the 10Kohm resistor R2 and the 10 uF capacitor C3, as you can see in the schematic. You can also add a switch to short-circuit pin 9 (RST) and 5V giving you the ability to reset the microcontroller by pressing on the switch (the processor resets in a high level is provided on the RST pin for more than 2 machine cycles). Those were the minimum connections to be made for the microcontroller to be functional and able to operate correctly. According to the fact that we are going to use an ISP programmer, A connector is added by default to allow easy in system programming. For our simple output project, a LED is connected to P1.0 through a 220 ohm resistor R1, as you can see in figure 3.2.A below. Note that there are other ways to connect the LED, but now that you understand the internal structure of the port, you can easily deduce that this is the only way to connect the LED so that the current is fully

controlled by the external resistor R1. Any other connection scheme would involve the internal resistor of the port, which is 'uncontrollable'.

figure 3.2.A LED blinking project hardware

In order get rid of any confusion, a picture of the implementation of this simple project on a bread board is provided to help you visualize the hardware part of the project:

Note that the reset switch and R/C filter are not present on this breadboard, the resetfunctionality of the ISP cable was used instead. At this stage, you can finally connect your ISP programmer, launch the ISPprog software, browse the HEX file for programming the FLASH, and transfer it to the microcontroller, as described in theISP page. You can eventually use any other available programming hardware and/or software. If all your connections are correct, you should see the LED blinking as soon as the programming (transfer) is finished. You can experiment with different delay in the code to change the blinking frequency. Don't forget that for any change to take place, you have to rebuild your source code, generating a new hex file (replacing the old one) and retransfer the freshly generated HEX file to the microcontroller.

figure 3.2.B: LED blinking project hardware implementation

3.3 Simple Input/Output project


The most simple input operation you can implement to the previous project is a push button, to control the LED. The schematic below (figure 3.3) shows how a switch is added on another pin of Port 1. We could have connected the switch on another port, but i preferred to stress on capability of the 8051 architecture to share input and output pins on the same port. Notice how the switch is connected to ground, and without a pull up resistor. recalling the internal structure of a pin, you'll notice that this is the simplest way to connect a switch, and also the most adapted to the 8051 architecture, making use of the internal pull up resistor, and preventing any eventual short circuits if the port is not well configured.

figure 3.3: LED blinking project hardware implementation

Now, that the hardware is finalized, an adequate software have to be designed and written to assure the correct functioning of the system. To control a led, there are many possible solutions. The first one I propose is the simplest one: a software that turns on the LED as long as the push button is pressed and turn it off otherwise and whose source code would be as the following: #include <REGX52.h> #include <math.h> delay(unsigned int y){ unsigned int i; for(i=0;i<y;i++){;} } main(){ P1_3 = 1; //Setup P1_3 as input pin while(1){ if(P1_3 == 0){

P1_0 = 0; //Turn ON the LED }else{ P1_0 = 1; //Turn OFF the LED } } } The other solution I propose is a software that turns ON the LED for a couple of seconds each time the switch is pressed, then turn it off automatically. The source code would be as the following: #include <REGX52.h> #include <math.h> unsigned long time, ON_time; //Global Variables void main(){ P1_3 = 1; //Set up P1_3 as input pin ON_time = 100000; while(1){ if (time < ON_time){ time++; // start or continue counting P1_0 = 0; //Turn ON the LED }else{ P1_0 = 1; // Turn OFF the LED } if (P1_3 == 0){ // if the switch is pressed, time = 0; // reset 'time' to 0 } } } The source code above may need some explanation: First you can notice that there is no 'delay' function, as it is not needed anymore. Two variables are defined 'time' and 'ON_time', they are both 'usigned long' type, so that they can manage relatively huge numbers, required to generate dozens of seconds delays. The variable 'time' will be used to count the elapsed time (in number of code cycles), while the 'ON_time' is used to store the fixed time period which the LED should stay ON after the push button is released. Then those two variables as constantly compared, and as soon as the elapsed time reaches the required 'ON_time', the led switches off, and the 'time' counting stops, to prevent eventual overflow. A push on the button would set the 'time' back to 0, and the whole process can start again. You can try on your own to figure out other ways of optimizing the control of a LED or a number of LEDs.

4.1. Introduction to 89S52 Peripherals


Figure 4.1 below shows a simplified diagram of the main peripherals present in the 89S52 and their interaction with the CPU and with the external I/O pins. You can notice that there are 3 timers/Counters. We use the expression "Timer/Counter" because this unit can be a counterwhen it counts external pulses on it's corresponding pin, and it can be a timer when it counts the pulses provided by the main clock oscillator of the microcontroller. Timer/Counter 2 is a special counter, that

does not behave like the two others, because it have a couple of extra functionality. The serial port, using a UART (Universal Asynchronous Receive Transmit) protocol can be used in a wide range of communication applications. With the UART provided in the 89S52 you can easily communicate with a serial port equipped computer, as well as communicate with another microcontroller. This last application, called Multiprocessor communication, is quite interesting, and can be easily implemented with 2 89S52 microcontrollers to build a very powerful multi-processor controllers. If all the peripherals described above can generate interrupt signals in the CPU according to some specific events, it can be useful to generate an interrupt signal from an external device, that may be a sensor or a Digital to Analog converter. For that purpose there are 2 External Interrupt sources (INT0 and INT1).

figure 4.1: 89s52 Peripherals

This was a presentation of the available peripheral features in a 89S52 microcontroller. Through this tutorial, we are going to study how to setup and use external interrupts and the 2 standard timers (T0 and T1). For simplicity, and to keep this tutorial a quick and straight forward one, The UART and the Timer/Counter 2 shall be discussed in separate tutorials.

4.2 External Interrupts


Let's start with the simplest peripheral which is the external interrupt, which can be used to cause interruptions on external events (a pin changing its state from 0 to 1 or vice-versa). In case you don't know, interruption is a mean of stopping the flow of a program, as a response to a certain event, to execute a small program called

'interrupt routine'. As you noticed in figure 4.1, in the 89S52, there are two external interrupt sources, one connected to the pin P3.2 and the other to P3.3. They are configured using a number of SFRs (Special Function Registers). Most of those SFRs are shared by other peripherals as you shall see in the rest of the tutorial.

The IE register

figure 4.2.A: IE Register The first register you have to configure (by turning On or Off the right bits) is the IE register, shown in figure 4.2.A. IE stands for 'Interrupt Enable', and it is used to allow different peripherals to cause software interruption. To use any of the interrupts, the bit EA (Enable ALL) must be set to 1, then, you have enable each one of the interrupts to be used with its individual enable bit. For the external interrupts, the two bits EX0 and EX1 are used for External Interrupt 0 and External Interrupt 1.

Using the C programming language under KEIL, it is extremely simple to set those bits, simply by using their name as any global variables, Using the following syntax: EA = 1; EX0 = 1; EX1 = 1; The rest of the bits of IE register are used for other interrupt sources like the 3 timers overflow (ETx) and the serial interface (ES).

The TCON register

figure 4.2.B: TCON Register Similarly, you have to set the bits IT0 and IT1 in the TCON register, shown in figure 4.2.B. The bits IT0/IT1 are used to configure the type of signal on the corresponding pins (P3.2/P3.3) that generated an interrupt according to the following table:

IT0/IT1 = 1 IT0/IT1 = 0

External interrupt caused by a falling edge signal on P3.2/P3.3 External interrupt caused by a low level signal on P3.2/P3.3

If IT0 or IT1 is set to 0, an interruption will keep reoccurring as long as P3.2 or P3.3 is set to 0. This mode isn't easy to mange, and most programmers tends to use external interrupts triggered by a falling edge (transition from 1 to 0). Again, this register is 'bit addressable' meaning you can set or clear each bit individually using their names, like in the following example:

IT0 = 1; IT1 = 1;

Example Program
Here is an example program to demonstrate the External Interrupt peripheral feature of the 89s52. We are going to build a simple digital low pass filter. External Interrupt 0 is set in 'Falling Edge' mode, and is used to check for noise on a signal and reset a counter in case noise is detected. Since the noise is interpreted by digital devices as a succession of high and low levels, any 'high to low' level transition is easily detected in the 'Falling edge' mode. If the counter reaches a pre-calibrated value, then the signal is considered to be stable, and can be sampled, otherwise, if the signal bounces between 0 and 1 before the counter reaches the pre-defined value, the external interrupt resets the counter, and the signal is not taken in account. Since we will be using External Interrupt 0, the signal to be checked for noise and sampled is imperatively connected to pin P3.2, and the clean, filtered output signal is to be generated on P1.0. // Include standard headers #include <REGX52.h> #include <math.h> unsigned int counter; //Variable used for our counter setup_interrupts () // Function to setup the External interrupt 0 in the required mode { EA = 1; EX0 = 1; IT0 = 1; } filter () interrupt 0 //The function the be executed when external interrupt occurs { counter = 0; //Reset the counter to 0 } main() { time_constant = 40000; //Define the response time of our filter setup_interrupts (); //setup the External interrupt while(1) { if (counter < time_constant) // Count until the pre-defined time_constant { counter++; } if (counter == time_constant) // if the counter was not interrupted by any noise,

{ P1_0 = P3_2; // output the valid signal on P1_0 } } }

Exercise:
To make sure you've correctly assimilated the functioning of the external interrupts, try to build a program that decodes the pulses coming from an incremental encoder to determine an absolute position. Incremental encoder are rotational encoder that generate 2 square waves, shifted by 90 degrees (or by a quarter of a period), as you can see in figure 4.2.C. The main idea of operation is that for a same direction of rotation, the falling edges of signal A will occur at the same time with respect to the signal B. In other words, during clockwise rotation, the falling edge of signal will always occur while signal B is at high level. On the other hand, during counterclockwise rotation, the falling edges of signal A will always occur while signal B is at a low level. This mechanism can be used to detect the 'quantity' of rotation in number of pulses as well as direction of the rotation Using this method, build a program to decode the signals coming from an incremental encoder, and update the position of the encoder at each falling edge. You will need
figure 4.2.C: Incremental Encoders wave forms

only one External interruption. You can try your source code by simulating it in KEIL IDE, or by testing it directly on your breadboard. IF you can't find the solution, you can seek for help in the forums.

4.3 Timer/Counter
For this part, I'll often use the notation 1/0 adjacent to a register name, which means that there are two of that register, one of them for timer/counter 0, and the other for timer/counter 1, and that the description applies to both of them. The timer is a very interesting peripheral, that is imperatively present in every microcontroller. It can be used in two distinct modes: Timer: Counting internal clock pulses, which are fixed with time, hence, we can say that it is very precise timer, whose resolution depends on the frequency of the main CPU clock (note that CPU clock equals the crystal frequency over 12). Counter: Counting external pulses (on the corresponding I/O pin), which can be

provided by a rotational encoder, an IR-barrier sensor, or any device that provide pulses, whose number would be of some interest. Sure, the CPU of a microcontroller could provide the required timing or counting, but the timer/counter peripheral relieves the CPU from that redundant and repetitive task, allowing it to allocate maximum processing power for more complex calculations. So, like any other peripheral, a Timer/Counter can ask for an interruption of the program, which - if enabled - occurs when the counting registers of the Timer/Counter are full and overflow. More precisely, the interruption will occur at the same time the counting register will be reinitialized to its initial value. So to control the behavior of the timers/counters, a set of SFR are used, most of them have already been seen at the top of this tutorial.

The IE register
First, you have to Enable the corresponding interrupts, but writing 1's to the corresponding bits in the IE register. The following table shows the names and definitions of the concerned bits of the IR register (you can always take a look at the complete IE register in figure 4.2.A): EA Enable All interrupts ET2 Enable Timer 2 interrupts (will not be treated in this tutorial) ET1 Enable Timer 1 interrupts ET0 Enable Timer 0 interrupts You can access those special bits by their names, as simply as it seems, example: ET0 = 1;

The TCON register


The TCON register is also shared between more than one peripherals. It can be used to configure timers or, as you saw before, external interrupts. The following table shows the names and definitions of the concerned bits of the TCON register (available in figure 4.2.B): TF1 Overflow interrupt flag, used by the processor. TR1 Timer/counter 1 RUN bit, set it to 1 to enable the timer to count, 0 to stop counting. TF0 Overflow interrupt flag, used by the processor. TR0 Timer/counter 0 RUN bit, set it to 1 to enable the timer to count, 0 to stop counting. As the IE register, TCON is also bit-addressable, so you can set its bit using its names, like we did before. Example TR0 = 1;

The TMOD register


Before explaining the TMOD register, let us agree and make it clear that the register IS NOT BIT-ADDRESSABLE, meaning you have to write the 8 bits of the register in a single instruction, by coding those bits into a decimal or hexadecimal number, as you shall see later. So, as you can see in figure 4.2.C, the TMOD register can be divided into two similar set of bits, each group being used to configure the mode of operation of one of the two timers.

figure 4.2.C: TCON Register

For the a given Timer/Counter, the corresponding bits of TMOD can be defined as in the following table: Gate signal. For normal operation clear this bit to 0. G If you want to use the timers to capture external events's length, set it to 1, and the timer 1/0 will stop counting when External Interrupt 1/0 pin is low (set to 0 V). Note that this feature involves both a timer and an external interrupt, It you're responsibility to write the code to manage the operation of those two peripherals. Set to 1 to use the timer/counter 1/0 as a Counter, counting external events on P3_4/P3_5, cleared to 0 to use it as timer, counting the main oscillator frequency divided by 12. Timer MODE: Those two last bits combine as 2 bit word that defines the mode of operation, defined as the table below.

C/T' M1 M0

Timer/counter modes of operation Each timer/counter has two SFR called TL0 and TH0 (for timer/counter0) and TL1 and TH1 (for timer/counter 1). TL stands for timer LOW, and is used to store the lower bits of the number being counted by the timer/counter. TH stands for TH, and is used to store the higher bits of the number being counted by the timer/counter. M1 M0 Mode Description Only TH0/1 is used, forming an 8bit timer/counter. Timer/counter will count up from the value initially stored in TH0/1 to 255, and then overflow back to 0. 0 0 0 If an interrupt is enabled, an interrupt will occur upon overflow. If used as timer, pulses from the processor are divided by 32 (after being divided by 12). The result is the main oscillator frequency divided by 384. If used as counter, external pulses are only divided by 32. Both TH0/1 and TL0/1 are used, forming a 16 bit timer/counter. Timer/counter will count up from the 16 bit value initially stored in TH0/1 and TL0/1 to 65535, and then overflow back to 0. 0 1 1 If an interrupt is enabled, an interrupt will occur upon overflow. If used as timer, pulses from the processor are only divided by 12. If used as counter, external pulses are not divided, but the maximum frequency that can be accurately counted equals the oscillator frequency divided by 24. TL0/1 is used for counting, forming an 8 bit timer/counter. TH0/1 is used to hold the value to be restored in TL upon overflow. Timer/counter will count up from the 8 bit value initially stored in TL0/1 and to 255, and then overflow, setting the value of TH0/1 in TL0/1. This is called the auto-reload 1 0 2 function. If an interrupt is enabled, an interrupt will occur upon overflow. If used as timer, pulses from the processor are only divided by 12. If used as counter, external pulses are not divided, but the maximum frequency that can be accurately counted equals the oscillator frequency divided by 24. 1 1 3 This mode is beyond the scope of this tutorial.

Timer modes 1 and 2 are the most used in 8051 microcontroller projects, since they offer a wide range of possible customizations.

4.3 Exercise project


To conclude this tutorial, a simple project is proposed, to help you assimilate the functioning of the timers, counter and interrupts. Consider the following problem. A motor is being operated by an outdated motor controller. We want to add some security to the system, by stopping the whole system in case the motor heats up too much, or turns too fast. A temperature sensor is already set up and give a low signal 0 when the temperature is too high, and an optical encoder output a pulse for each revolution of the motor. We need to write the code to stop the motor incase it heats up or in case it reached 10 000 r.p.m. Considering that the temperature sensor is connected to P3.2 (External interrupt 0), the encoder is connected to P3.5 (Timer/Counter 1), that the system can be stopped by a high level signal on P1_0, and that we are using a 24MHz crystal oscillator, the software for that controller would be like the following: // Include standard headers #include <REGX52.h> #include <math.h> #define limit 12 #define stop_signal P1_0

unsigned char sub_counter; setup_peripherals(){ //setup external interrupt EA = 1; EX0 = 1; IT0 = 1; TMOD = 0x52; // timer 0 mode 2, counter 1 mode 1 //setup timer 0 TR0 = 1; TH0 = 5; //makes the timer to overflow every 125 uS (divide by 250). ET0 = 1; //setup timer 1 TR1 = 1 ; } timer_0 () interrupt 1{

sub_counter++ ; if (sub_counter == 10){ // divide the overflow frequency further more by 10 sub_counter = 0; // this part is executed every 1.25 mS if ((TL1 + (TH1 * 256)) > limit){ // 12/0.00125 = 9600 (~ 10000)s //Stop the motor stop_signal = 1; TL1 = 0; TH1 = 0; } } } over_heat_alarm () interrupt 0{ stop_signal = 1; } void main(){ stop_signal = 0; // the motor runs normally setup_peripherals(); while(1){ // Do nothing, the whole program is carried out by interrupts! } }

EXAMPLE

Contact less tachometer principle of operation


The idea behind most digital counting device, frequency meters and tachometers, is a microcontroller, used to count the pulses coming from a sensor or any other electronic device. In the case of this tachometer, the counted pluses will come from proximity sensor, which will detect any reflective element passing infront of it, and thus, will give an output pulse for each and every rotation of the shaft, as show in the picture. Those pulses will be fed to the microcontroller and counted. To understand how a micro controller counts pulses, and deduce the frequency of those pulse, please refer to this tutorial about building a frequency meter, that elaborates the process of frequency counting. The main difference between this tutorial about tachometer and frequency meters, is that we need the reading in pulses per minutes (to count revolutions per minutes), but in the same time, we don't want to wait a whole minute before getting a correct reading. Thus we need some additional processing to predict the number of revolutions per minute in less than a second.

Instantaneous measurement algorithm


To be able to deduce an RPM reading in less than second, while constantly refining the reading's accuracy, a simple algorithm have been developed, where a counter and a timer are used. Counter and timers are part of the internal features of a microcontroller, (like the AT89C52 used in this project) and they can be easily configured through programming. The schematic below, shows how the timer and the counter are used for this task; The counter is connected i such a way to count pulses coming from the proximity sensor, while the timer is used to precisely feed the counted value to the microcontroller every filth of a second, and

reset the counter to 0. The microcontroller can now take an average of the last 3 readings (saved in C1, C2 and C3) and calculate the average numbers of pulses per fifth second, then multiply this value by 5, to get the number of pulses per second, then multiply this value by 60 to get the number of pulses per minute, which C1, C2 and C3 are used to store the last 3 reading represents the measured RPM. The only purpose of calculating an average reading is that it will allow to get more stable reading and prevent display flickering.

This device is composed of 2 electronic circuits: the Sensor, which is a slightly modifiedproximity sensor, and the microcontroller board, which analyses pulses coming from the sensor, process them and display the result on the LCD display. The microcontroller board:

The electronic Circuits

Circuit explanation: The LCD connections in the green shading is a standard for most of alpha numeric LCDs, the only feature I added is to be able to control the back light via the 80c52 microcontroller. The LCD protocol can seem complicated to some of you, and an article should be released soon to explain it. The part in the blue shading is also standard in any 8051 microcontroller circuit, which includes the reset circuitry along with the crystal resonator that generates the

clock pulses required. The power supply, shaded in light red, regulates a 9V rechargeable Ni-CD battery and also provides a very simple battery monitor, with a green and a red LED, showing whether the battery need to be recharged or not. The switch SW1, shown in the upper yellow circle, is used to enable/disable the measurement or the counting process. When the switch is pressed, the device measures the RPM of the shaft under test, and constantly updates the reading on the LCD, when the switch is released, the last reading is held unchanged on the display, as long as the device stays on. When the switch is pressed again the old reading is replaced by the new one. The wire connection P1, which is connected to the output of the sensor, is connected to the pin 3.4 of the microcontroller, this pin has a dual function which is to count incoming pulses and increment a 8, 13, or 16 bit register according to the configuration of the timer T0. As you may have noticed, this schematics misses tow important items to be called a tachometer: The C code loaded into the microcontroller, which will be discussed later, and the proximity sensor, which will feed the pulses to be counted. The modified IR proximity sensor:

This schematic show the slight modification over the one proposed in this tutorial, which is the fact that the emitter LED uses a current limiting resistor of a higher value, to allow it to be turned on for a long period of time, because in this specific application, we need to turn the IR emissions on or off, but we don't need to inject high currents to reach high ranges... I recommend the reading of this article that

fully covers all the aspects of this sensor. The CTRL line, is an input coming from the microcontroller (at the wire connection: P4), turning the IR emissions ON and OFF, and the OUT line, is the output of the sensor, which is fed to the microcontroller (at the wire connection: P1). After analyzing both the main board holding the microcontroller and the sensor, here is a simple diagram showing how they are connected together. You will have to refer to the above schematics to see where P1, P2, P3 and P4 goes in the main board, as well as the other lines concerning the sensor.

This picture also shows what is meant by the connection of the sensor to the main board. The reason for separating the sensor from the main board, is to allow better performance sensors, or even other types of sensors to be connected to the device. In general, modular designs cost more, but is more useful in the prototyping phase...

The software
Here are only small relevant parts of the full C program, that was loaded into the microcontroller after being compiled to a HEX file. Those part of the code were selected as the ones that emphasize the main purpose of a microcontroller in such an application. For examples, function dealing with the LCD operation are not included in this description. Comments in green explains the program. The full code is available in the Project folder, downloadable at the bottom of this article. #include <REGX51.h> #include <math.h> unsigned int clk_tmp,clk_tmp2,clk_sec,clk_sec2; unsigned intex_pulses,rps,rps_tmp,temp,rps_avg,rps_max; unsigned int rps_his[5]; char a,b,c,d,e; unsigned char count1,count2;

unsigned char scale = 4; delay(y){ // A function to make software delays unsigned int i; for(i=0;i<y;i++){;} } setup_interrupts(){ // This function initialises the TIMER and the COUNTER to EA = 1; // be used in in the trachometre ET0 = 1; //set the Timer/counter 0 TR0 = 1; //Enable Timer/counter 0 to count TMOD = 0X25; //counter 0 in mode 1 (16 bit counter), //timer 1 in mode 2 (auto reload from TH1) TH1 = 0; //start counter from 0 ET1 = 1; //enable timer 1 TR1 = 1; //Enable Timer/counter 1 to count PT0 = 1; //Setup the priorities of timer 1 and timer 0, a 0 gives a PT1 = 0; //higher priority. } void int_to_digits(unsigned int number){ //store the 5 digits of an integer float itd_a,itd_b; //number in the variable a,b,c,d,e itd_a = number / 10.0; e = floor((modf(itd_a,&itd_b)* 10)+0.5); itd_a = itd_b / 10.0; d = floor((modf(itd_a,&itd_b)* 10)+0.5); itd_a = itd_b / 10.0; c = floor((modf(itd_a,&itd_b)* 10)+0.5); itd_a = itd_b / 10.0; b = floor((modf(itd_a,&itd_b)* 10)+0.5); itd_a = itd_b / 10.0; a = floor((modf(itd_a,&itd_b)* 10)+0.5); }

clk() interrupt 3 //timer 1 interrupt { clk_tmp++; //Software counter for the timing of the tachometer readings clk_tmp2++; //Software counter for the display refresh rate if (clk_tmp2 > (1236)){ // update display clk_tmp2 = 0; rps_avg = floor(((rps_his[0] + rps_his[1] + rps_his[2] + rps_his[3] + ___ ___rps_his[4])/5)*60); } if (clk_tmp > (6584/scale)){ // update the measured RPM clk_tmp = 0; if (P2_0 == 0){ rps = TL0; temp = TH0; temp = temp * 256;

rps = (rps rps_his[4] rps_his[3] rps_his[2] rps_his[1] rps_his[0] } TL0 = 0; TH0 = 0; } }

+ = = = = =

temp)* scale; rps_his[3]; rps_his[2]; rps_his[1]; rps_his[0]; rps;

count_pulses() interrupt 1 //counter 0 interrupt { if (scale < 10) // If the pulses are so fast that the internal counter scale++; // overflows, increase the variable 'scale' so that } // so that readings are recorded at a higher rate void main(){ scale = 10 ; P3_3 = 0; // ini proximity sensor, OFF P3_4 = 1; // ini sensor input P1_1 = 0; //turn LCD backlight ON P2_0 = 1; //ini count/hold button ini_lcd(); // ini the LCD setup_interrupts(); while(1){ P3_3 = ~P2_0; if (P2_0 == 1){ scale= 4; } }

Anda mungkin juga menyukai