Microcontroller
Microcontroller
Objectives
Upon completion of this chapter, you will be able to:
The 8051 has two timers/counters. They can be used either as timers to generate a time delay or as
counters to count events happening outside the microcontroller. In Section 9.1 we see how these timers are
used to generate time delays. In Section 9.2 we show how they are used as event counters. In Section 9.3
we use C language to program the 8051 timers.
1
Figure 2: Timer 1 Registers
2
1.1.3 TMOD (Timer Mode) Register
Both timers 0 and 1 use the same register, called TMOD, to set the various timer operation modes. TMOD
is an 8-bit register in which the lower 4 bits are set aside for Timer 0 and the upper 4 bits for Timer 1. In
each case, the lower 2 bits are used to set the timer mode and the upper 2 bits to specify the operation.
These options are discussed next.
1.1.4 M1, M0
M0 and M1 select the timer mode. As shown in Figure 3, there are three modes: 0, 1, and 2. Mode 0 is a
13-bit timer, mode 1 is a 16-bit timer, and mode 2 is an 8-bit timer. We will concentrate on modes 1 and
2 since they are the ones used most widely. We will soon describe the characteristics of these modes, after
describing the rest of the TMOD register.
Clock Source for Timer As you know, every timer needs a clock pulse to tick. What is the source of
the clock pulse for the 8051 timers? If C/T = 0, the crystal frequency attached to the 8051 is the source of
the clock for the timer. This means that the size of the crystal frequency attached to the 8051 also decides
the speed at which the 8051 timer ticks. The frequency for the timer is always 1/12th the frequency of the
crystal attached to the 8051. See Example 9-2.
[Example 9-2] Find the timer’s clock frequency and its period for various 8051-based systems, with the
following crystal frequencies.
(a) 12 MHz (b) 16 MHz (c) 11.0592 MHz
Solution:
XTAL oscillator ÷12
(a) 1/12 × 12 MHz = 1 MHz and T = 1/1 MHz = 1 µs
(b) 1/12 × 16 MHz = 1.333 MHz and T = 1/1.333 MHz = 0.75 µs
(c) 1/12 × 11.0592 MHz = 921.6 kHz; T = 1/921.6 kHz = 1.085 µs
NOTE THAT 8051 TIMERS USE 1/12 OF XTAL FREQUENCY, REGARDLESS OF MA-
CHINE CYCLE TIME.
Although various 8051-based systems have an XTAL frequency of 10 MHz to 40 MHz, we will concentrate
on the XTAL frequency of 11.0592 MHz. The reason behind such an odd number has to do with the baud
rate for serial communication of the 8051. XTAL = 11.0592 MHz allows the 8051 system to communicate
with the IBM PC with no errors, as we will see in Chapter 10.
1.1.6 GATE
The other bit of the TMOD register is the GATE bit. Notice in the TMOD register of Figure 3 that both
Timers 0 and 1 have the GATE bit. What is its purpose? Every timer has a means of starting and stopping.
Some timers do this by software, some by hardware, and some have both software and hardware controls.
The timers in the 8051 have both. The start and stop of the timer are controlled by way of software by the
TR (timer start) bits TR0 and TR1. This is achieved by the instructions “SETB TR1” and “CLR TR1” for
3
Timer 1, and “SETB TR0” and “CLR TR0” for Timer 0. The SETB instruction starts it, and it is stopped
by the CLR instruction. These instructions start and stop the timers as long as GATE = 0 in the TMOD
register. The hardware way of starting and stopping the timer by an external source is achieved by making
GATE = 1 in the TMOD register. However, to avoid further confusion for now, we will make GATE = 0,
meaning that no external hardware is needed to start and stop the timers. In using software to start and
stop the timer where GATE = 0, all we need are the instructions “SETB TRx” and “CLR TRx”. The use
of external hardware to stop or start the timer is discussed in Chapter 11 when interrupts are discussed.
[Example 9-3] Find the value for TMOD if we want to program Timer 0 in mode 2, use 8051 XTAL for
the clock source, and use instructions to start and stop the timer.
Solution:
TMOD = 00000010: Timer 0, mode 2, C/T = 0 to use XTAL clock source, and gate = 0 to use internal
(software) start and stop method.
Now that we have this basic understanding of the role of the TMOD register, we will look at the timer’s
modes and how they are programmed to create a time delay. Because modes 1 and 2 are so widely used, we
describe each of them in detail.
1. It is a 16-bit timer; therefore, it allows values of 0000 to FFFFH to be loaded into the timer’s registers
TL and TH.
2. After TH and TL are loaded with a 16-bit initial value, the timer must be started. This is done by
“SETB TR0” for Timer 0 and “SETB TR1” for Timer 1.
3. After the timer is started, it starts to count up. It counts up until it reaches its limit of FFFFH. When
it rolls over from FFFFH to 0000, it sets high a flag bit called TF (timer flag). This timer flag can be
monitored. When this timer flag is raised, one option would be to stop the timer with the instructions
“CLR TR0” or “CLR TR1”, for Timer 0 and Timer 1, respectively. Again, it must be noted that each
timer has its own timer flag: TF0 for Timer 0, and TF1 for Timer 1.
4. After the timer reaches its limit and rolls over, in order to repeat the process the registers TH and TL
must be reloaded with the original value, and TF must be reset to 0.
1. Load the TMOD value register indicating which timer (Timer 0 or Timer 1) is to be used and which
timer mode (0 or 1) is selected.
2. Load registers TL and TH with initial count values.
4
4. Keep monitoring the timer flag (TF) with the “JNB TFx, target” instruction to see if it is raised. Get
out of the loop when TF becomes high.
5. Stop the timer.
6. Clear the TF flag for the next round.
To calculate the exact time delay and the square wave frequency generated on pin P1.5, we need to know
the XTAL frequency. See Example 9-5.
From Example 9-6 we can develop a formula for delay calculations using mode 1 (16-bit) of the timer
for a crystal frequency of XTAL = 11.0592 MHz. This is given in Figure 5. The scientific calculator in
the Accessories directory of Microsoft Windows can help you to find the TH, TL values. This calculator
supports decimal, hex, and binary calculations.
5
Instruction Cycles
HERE: MOV TL0,#0F2H 2
MOV TH0,#0FFH 2
CPL P1.5 1
ACALL DELAY 2
SJMP HERE 2
DELAY: SETB TR0 1
AGAIN: JNB TF0,AGAIN 14
CLR TR0 1
CLR TF0 1
RET 2
Total 28
T = 2 × 28 × 1.085 µs = 60.76 µs and F = 16458.2 Hz.
[Example 9-7] Find the delay generated by Timer 0 in the following code, using both of the methods of
Figure 5. Do not include the overhead due to instructions.
CLR P2.3 ; c l e a r P2.3
MOV TMOD, #01 ; Timer 0 , mode 1 (16− b i t mode )
HERE: MOV TL0 , #3EH ; TL0 = 3EH, Low b y t e
MOV TH0, #0B8H ; TH0 = B8H, High b y t e
SETB P2.3 ; SET h i g h P2.3
SETB TR0 ; s t a r t Timer 0
AGAIN: JNB TF0 , AGAIN ; monitor Timer 0 f l a g
CLR TR0 ; s t o p Timer 0
CLR TF0 ; c l e a r Timer 0 f l a g f o r n e x t round
CLR P2.3
Solution:
(a) (FFFF − B83E + 1) = 47C2H = 18370 in decimal and 18370 × 1.085 µs = 19.93145 ms.
(b) Since TH–TL = B83EH = 47166 (in decimal) we have 65536 − 47166 = 18370. This means that the
timer counts from B83EH to FFFFH. This plus rolling over to 0 goes through a total of 18370 clock cycles,
where each clock is 1.085 µs in duration. Therefore, we have 18370 × 1.085 µs = 19.93145 ms as the width
of the pulse.
[Example 9-8] Modify TL and TH in Example 9-7 to get the largest time delay possible. Find the delay
in ms. In your calculation, exclude the overhead due to the instructions in the loop.
Solution:
To get the largest delay we make TL and TH both 0. This will count up from 0000 to FFFFH and then
roll over to zero.
CLR P2.3 ; c l e a r P2.3
MOV TMOD, #01 ; Timer 0 , mode 1 (16− b i t mode )
HERE: MOV TL0 , #0 ; TL0 = 0 , Low b y t e
MOV TH0, #0 ; TH0 = 0 , High b y t e
SETB P2.3 ; SET P2.3 h i g h
SETB TR0 ; s t a r t Timer 0
AGAIN: JNB TF0 , AGAIN ; monitor Timer 0 f l a g
CLR TR0 ; s t o p Timer 0
CLR TF0 ; c l e a r Timer 0 f l a g
CLR P2.3
Making TH and TL both zero means that the timer will count from 0000 to FFFFH, and then roll
over to raise the TF flag. As a result, it goes through a total of 65536 states. Therefore, we have delay
= (65536 − 0) × 1.085 µs = 71.1065 ms.
[Example 9-9] The following program generates a square wave on pin P1.5 continuously using Timer 1
for a time delay. Find the frequency of the square wave if XTAL = 11.0592 MHz. In your calculation do not
6
include the overhead due to instructions in the loop.
MOV TMOD, #10H ; Timer 1 , mode 1 (16− b i t )
AGAIN: MOV TL1 , #34H ; TL1 = 34H, Low b y t e
MOV TH1, #76H ; TH1 = 76H, High b y t e
; (7634H = t i m e r v a l u e )
SETB TR1 ; s t a r t Timer 1
BACK: JNB TF1 , BACK ; stay u n t i l timer r o l l s over
CLR TR1 ; s t o p Timer 1
CPL P1.5 ; comp. P1.5 t o g e t hi , l o
CLR TF1 ; c l e a r Timer 1 f l a g
SJMP AGAIN ; r e l o a d t i m e r s i n c e Mode 1
; i s not auto−r e l o a d
Solution:
In the above program notice the target of SJMP. In mode 1, the program must reload the TH, TL register
every time if we want to have a continuous wave. Now the calculation. Since FFFFH − 7634H = 89CBH +
1 = 89CCH and 89CCH = 35276 clock count.
35276 × 1.085 µs = 38.274 ms for half of the square wave. The entire square wave length is 38.274 × 2 =
76.548 ms and has a frequency = 13.064 Hz.
Also notice that the high and low portions of the square wave pulse are equal. In the above calculation,
the overhead due to all the instructions in the loop is not included.
In Examples 9-7 and 9-8, we did not reload TH and TL since it was a single pulse. Look at Example 9-9
to see how the reloading works in mode 1.
[Example 9-10] Assume that XTAL = 11.0592 MHz. What value do we need to load into the timer’s
registers if we want to have a time delay of 5 ms (milliseconds)? Show the program for Timer 0 to create a
pulse width of 5 ms on P2.3.
Solution:
Since XTAL = 11.0592 MHz, the counter counts up every 1.085 µs. This means that out of many 1.085
µs intervals we must make a 5 ms pulse. To get that, we divide one by the other. We need 5 ms / 1.085 µs
= 4608 clocks. To achieve that we need to load into TL and TH the value 65536 − 4608 = 60928 = EE00H.
Therefore, we have TH = EE and TL = 00.
CLR P2.3 ; c l e a r P2.3
MOV TMOD, #01 ; Timer 0 , mode 1 (16− b i t mode )
HERE: MOV TL0 , #0 ; TL0 = 0 , Low b y t e
MOV TH0, #0EEH ; TH0 = EE ( hex ) , High b y t e
SETB P2.3 ; SET P2.3 h i g h
SETB TR0 ; s t a r t Timer 0
7
AGAIN: JNB TF0 , AGAIN ; monitor Timer 0 f l a g
; u n t i l i t r o l l s over
CLR P2.3 ; c l e a r P2.3
CLR TR0 ; s t o p Timer 0
CLR TF0 ; c l e a r Timer 0 f l a g
[Example 9-11] Assuming that XTAL = 11.0592 MHz, write a program to generate a square wave of 2
kHz frequency on pin P1.5.
Solution:
This is similar to Example 9-10, except that we must toggle the bit to generate the square wave. Look
at the following steps.
(a) T = 1/f = 1/2 kHz = 500 µs the period of the square wave.
(b) 1/2 of it for the high and low portions of the pulse is 250 µs.
(c) 250 µs / 1.085 µs = 230 and 65536 − 230 = 65306, which in hex is FF1AH.
(d) TL = 1AH and TH = FFH, all in hex. The program is as follows.
AGAIN:
MOV TMOD, #10H ; Timer 1 , mode 1 (16− b i t )
MOV TL1 , #1AH ; TL1 = 1AH, Low b y t e
MOV TH1, #0FFH ; TH1 = FFH, High b y t e
SETB TR1 ; start Timer 1
BACK:
JNB TF1 , BACK ; stay u n t i l timer r o l l s over
CLR TR1 ; s t o p Timer 1
CPL P1.5 ; complement P1.5 t o g e t hi , l o
CLR TF1 ; c l e a r Timer 1 f l a g
SJMP AGAIN ; r e l o a d t i m e r s i n c e mode 1
; i s not auto−r e l o a d
[Example 9-12] Assuming XTAL = 11.0592 MHz, write a program to generate a square wave of 50 Hz
frequency on pin P2.3.
Solution:
Look at the following steps.
(a) T = 1/50 Hz = 20 ms, the period of the square wave.
(b) 1/2 of it for the high and low portions of the pulse = 10 ms
(c) 10 ms / 1.085 µs = 9216 and 65536 − 9216 = 56320 in decimal, and in hex it is DC00H.
(d) TL = 00 and TH = DC (hex)
The program follows.
MOV TMOD, #10H ; Timer 1 , mode 1 (16− b i t )
AGAIN: MOV TL1 , #00 ; TL1 = 00 , Low b y t e
MOV TH1, #0DCH ; TH1 = DCH, High b y t e
SETB TR1 ; s t a r t Timer 1
BACK: JNB TF1 , BACK ; stay u n t i l timer r o l l s over
CLR TR1 ; s t o p Timer 1
CPL P2.3 ; comp. P2.3 t o g e t hi , l o
CLR TF1 ; c l e a r Timer 1 f l a g
SJMP AGAIN ; r e l o a d t i m e r s i n c e mode 1
; i s not auto−r e l o a d
8
1.4.1 Using Windows Calculator to Find TH, TL
The scientific calculator in Microsoft Windows is a handy and easy-to-use tool to find the TH, TL values.
Assume that we would like to find the TH, TL values for a time delay that uses 35,000 clocks of 1.085 µs.
The following steps show the calculation.
[Example 9-13] Examine the following program and find the time delay in seconds. Exclude the overhead
due to the instructions in the loop.
MOV TMOD, #10H ; Timer 1 , mode 1 (16− b i t )
MOV R3 , #200 ; counter for multiple delay
AGAIN: MOV TL1 , #08H ; TL1 = 08 , Low b y t e
MOV TH1, #01H ; TH1 = 01 , High b y t e
SETB TR1 ; s t a r t Timer 1
BACK: JNB TF1 , BACK ; stay u n t i l timer r o l l s over
CLR TR1 ; s t o p Timer 1
CLR TF1 ; c l e a r Timer 1 f l a g
DJNZ R3 , AGAIN ; i f R3 not z e r o t h e n
; reload timer
Solution:
TH–TL = 0108H = 264 in decimal and 65536 − 264 = 65272. Now 65272 × 1.085 µs = 70.820 ms, and
for 200 of them we have 200 × 70.820 ms = 14.164024 seconds.
1.5 Mode 0
Mode 0 is exactly like mode 1 except that it is a 13-bit timer instead of 16-bit. The 13-bit counter can hold
values between 0000 to 1FFFH in TH–TL. Therefore, when the timer reaches its maximum of 1FFH, it rolls
over to 0000, and TF is raised.
1. It is an 8-bit timer; therefore, it allows only values of 00 to FFH to be loaded into the timer’s register
TH.
2. After TH is loaded with the 8-bit value, the 8051 gives a copy of it to TL. Then the timer must be
started. This is done by the instruction “SETB TR0” for Timer 0 and “SETB TR1” for Timer 1. This
is just like mode 1.
3. After the timer is started, it starts to count up by incrementing the TL register. It counts up until it
reaches its limit of FFH. When it rolls over from FFH to 00, it sets high the TF (timer flag). If we are
using Timer 0, TF0 goes high; if we are using Timer 1, TF1 is raised.
9
Figure 6: Timer Mode 2 Block Diagram (Auto-Reload)
4. When the TL register rolls from FFH to 0 and TF is set to 1, TL is reloaded automatically with the
original value kept by the TH register. To repeat the process, we must simply clear TF and let it go
without any need by the programmer to reload the original value. This makes mode 2 an auto-reload,
in contrast with mode 1 in which the programmer has to reload TH and TL.
It must be emphasized that mode 2 is an 8-bit timer. However, it has an auto-reloading capability. In
auto-reload, TH is loaded with the initial count and a copy of it is given to TL. This reloading leaves TH
unchanged, still holding a copy of the original value. This mode has many applications, including setting
the baud rate in serial communication, as we will see in Chapter 10.
1. Load the TMOD value register indicating which timer (Timer 0 or Timer 1) is to be used, and select
the timer mode (mode 2).
2. Load the TH registers with the initial count value.
3. Start the timer.
4. Keep monitoring the timer flag (TF) with the “JNB TFx, target” instruction to see whether it is
raised. Get out of the loop when TF goes high.
5. Clear the TF flag.
6. Go back to Step 4, since mode 2 is auto-reload.
Example 9-14 illustrates these points. To achieve a larger delay, we can use multiple registers as shown
in Example 9-15.
[Example 9-14] Assuming that XTAL = 11.0592 MHz, find (a) the frequency of the square wave generated
on pin P1.0 in the following program, and (b) the smallest frequency achievable in this program, and the
TH value to do that.
MOV TMOD, #20H ; T1/mode 2/8− b i t / auto−r e l o a d
MOV TH1, #5 ; TH1 = 5
SETB TR1 ; s t a r t Timer 1
BACK: JNB TF1 , BACK ; stay u n t i l timer r o l l s over
CPL P1.0 ; comp. P1.0 t o g e t hi , l o
CLR TF1 ; c l e a r Timer 1 f l a g
SJMP BACK ; mode 2 i s auto−r e l o a d
Solution:
(a) First notice the target address of SJMP. In mode 2 we do not need to reload TH since it is auto-reload.
Now (256 − 05) × 1.085 µs = 251 × 1.085 µs = 272.33 µs is the high portion of the pulse. Since it is a 50%
duty cycle square wave, the period T is twice that; as a result T = 2 × 272.33 µs = 544.67 µs and the
frequency = 1.83597 kHz.
(b) To get the smallest frequency, we need the largest T and that is achieved when TH = 00. In that
case, we have T = 2 × 256 × 1.085 µs = 555.52 µs and the frequency = 1.8 kHz.
[Example 9-15] Find the frequency of a square wave generated on pin P1.0.
10
MOV TMOD, #2H ; Timer 0 , mode 2
; (8− b i t , auto−r e l o a d )
MOV TH0, #0 ; TH0 = 0
AGAIN: MOV R5 , #250 ; c o un t for multiple delay
ACALL DELAY
CPL P1.0 ; t o g g l e P1.0
SJMP AGAIN ; repeat
DELAY: SETB TR0 ; s t a r t Timer 0
BACK: JNB TF0 , BACK ; stay u n t i l timer r o l l s over
CLR TR0 ; s t o p Timer 0
CLR TF0 ; c l e a r TF f o r n e x t round
DJNZ R5 , DELAY
RET
T = 2 × (250 × 256 × 1.085 µs) = 138.88 ms, and frequency = 72 Hz.
11
duty cycle). Therefore, we have: T = high portion + low portion = 325.5 µs +162.25 µs = 488.25 µs and
frequency = 2.048 kHz.
Notice that in many of the time delay calculations we have ignored the clocks caused by the overhead
instructions in the loop. To get a more accurate time delay, and hence frequency, you need to include them.
If you use a digital scope and you don’t get exactly the same frequency as the one we have calculated, it is
because of the overhead associated with those instructions.
In this section, we used the 8051 timer for time delay generation. However, a more powerful and creative
use of these timers is to use them as event counters. We discuss this use of the counter next.
8. In the instruction “MOV TH1, #-200”, find the hex value for the TH register.
9. To get a 2-ms delay, what number should be loaded into TH, TL using mode 1? Assume that XTAL
= 11.0592 MHz.
10. To get a 100-µs delay, what number should be loaded into the TH register using mode 2? Assume
XTAL = 11.0592 MHz.
2 Counter Programming
In the last section we used the timer/counter of the 8051 to generate time delays. These timers can also
be used as counters counting events happening outside the 8051. The use of the timer/counter as an event
counter is covered in this section. As far as the use of a timer as an event counter is concerned, everything
that we have talked about in programming the timer in the last section also applies to programming it as a
counter, except the source of the frequency. When the timer/counter is used as a timer, the 8051’s crystal
is used as the source of the frequency. When it is used as a counter, however, it is a pulse outside the 8051
that increments the TH, TL registers. In counter mode, notice that the TMOD and TH, TL registers are
the same as for the timer discussed in the last section; they even have the same names. The timer’s modes
are the same as well.
12
Table 2: Port 3 Pins Used for Timers 0 and 1
Objectives
Upon completion of this chapter, you will be able to:
Computers transfer data in two ways: parallel and serial. In parallel data transfers, often 8 or more lines
(wire conductors) are used to transfer data to a device that is only a few feet away. Examples of parallel
transfers are printers and hard disks; each uses cables with many wire strips. Although in such cases a lot
of data can be transferred in a short amount of time by using many wires in parallel, the distance cannot be
great. To transfer to a device located many meters away, the serial method is used. In serial communication,
the data is sent one bit at a time, in contrast to parallel communication, in which the data is sent a byte
or more at a time. Serial communication of the 8051 is the topic of this chapter. The 8051 has serial
communication capability built into it, thereby making possible fast data transfer using only a few wires.
In this chapter we first discuss the basics of serial communication. In Section 10.2, 8051 interfacing to
RS232 connectors via MAX232 line drivers is discussed. Serial port programming of the 8051 is discussed in
Section 10.3. The second serial port of DS89C4x0 is programmed in Section 10.4. Section 10.5 covers 8051
C programming for serial ports #0 and #1.
13
Figure 7: Serial versus Parallel Data Transfer
is used for transferring data between two systems located at distances of hundreds of feet to millions of miles
apart. Figure 7 diagrams serial versus parallel data transfers.
The fact that serial communication uses a single data line instead of the 8-bit data line of parallel
communication not only makes it much cheaper but also enables two computers located in two different
cities to communicate over the telephone.
For serial data communication to work, the byte of data must be converted to serial bits using a parallel-
in-serial-out shift register; then it can be transmitted over a single data line. This also means that at the
receiving end there must be a serial-in-parallel-out shift register to receive the serial data and pack them
into a byte. Of course, if data is to be transferred on the telephone line, it must be converted from 0s and
1s to audio tones, which are sinusoidal-shaped signals. This conversion is performed by a peripheral device
called a modem, which stands for “modulator/demodulator.”
When the distance is short, the digital signal can be transferred as it is on a simple wire and requires no
modulation. This is how IBM PC keyboards transfer data to the motherboard. However, for long-distance
data transfers using communication lines such as a telephone, serial data communication requires a modem
to modulate (convert from 0s and 1s to audio tones) and demodulate (converting from audio tones to 0s and
1s).
Serial data communication uses two methods, asynchronous and synchronous. The synchronous method
transfers a block of data (characters) at a time, while the asynchronous method transfers a single byte at a
time. It is possible to write software to use either of these methods, but the programs can be tedious and
long. For this reason, there are special IC chips made by many manufacturers for serial data communications.
These chips are commonly referred to as UART (universal asynchronous receiver-transmitter) and USART
(universal synchronous asynchronous receiver-transmitter). The 8051 chip has a built-in UART, which is
discussed in detail in Section 10.3.
14
3.1 Half- and Full-Duplex Transmission
In data transmission if the data can be transmitted and received, it is a duplex transmission. This is in
contrast to simplex transmissions such as with printers, in which the computer only sends data. Duplex
transmissions can be half or full duplex, depending on whether or not the data transfer can be simultaneous.
If data is transmitted one way at a time, it is referred to as half duplex. If the data can go both ways at
the same time, it is full duplex. Of course, full duplex requires two wire conductors for the data lines (in
addition to the signal ground), one for transmission and one for reception, in order to transfer and receive
data simultaneously. See Figure 8.
Notice in Figure 9 that when there is no transfer, the signal is 1 (high), which is referred to as mark. The
0 (low) is referred to as space. Notice that the transmission begins with a start bit followed by D0, which is
the LSB, then the rest of the bits until the MSB (D7), and finally, the one stop bit indicating the end of the
character “A”.
In asynchronous serial communications, peripheral chips and modems can be programmed for data that
is 7 or 8 bits wide. This is in addition to the number of stop bits, 1 or 2. While in older systems ASCII
characters were 7-bit, in recent years, due to the extended ASCII characters, 8-bit data has become common.
In some older systems, due to the slowness of the receiving mechanical device, two stop bits were used to give
the device sufficient time to organize itself before transmission of the next byte. In modern PCs however,
the use of one stop bit is standard. Assuming that we are transferring a text file of ASCII characters using
1 stop bit, we have a total of 10 bits for each character: 8 bits for the ASCII code, and 1 bit each for the
start and stop bits. Therefore, for each 8-bit character there are an extra 2 bits, which gives 20% overhead.
In some systems, the parity bit of the character byte is included in the data frame in order to maintain
data integrity. This means that for each character (7- or 8-bit, depending on the system) we have a single
parity bit in addition to start and stop bits. The parity bit is odd or even. In the case of an odd-parity bit
the number of data bits, including the parity bit, has an odd number of 1s. Similarly, in an even-parity bit
system the total number of bits, including the parity bit, is even. For example, the ASCII character “A”,
binary 0100 0001, has 0 for the even-parity bit. UART chips allow programming of the parity bit for odd-,
even-, and no-parity options.
15
3.3 Data Transfer Rate
The rate of data transfer in serial data communication is stated in bps (bits per second). Another widely
used terminology for bps is baud rate. However, the baud and bps rates are not necessarily equal. This is
due to the fact that baud rate is the modem terminology and is defined as the number of signal changes
per second. In modems a single change of signal, sometimes transfers several bits of data. As far as the
conductor wire is concerned, the baud rate and bps are the same, and for this reason in this book we use
the terms bps and baud interchangeably.
The data transfer rate of a given computer system depends on communication ports incorporated into
that system. For example, the early IBM PC/XT could transfer data at the rate of 100 to 9600 bps. In
recent years, however, Pentium-based PCs transfer data at rates as high as 56K bps. It must be noted that
in asynchronous serial data communication, the baud rate is generally limited to 100,000 bps.
Since not all the pins are used in PC cables, IBM introduced the DB-9 version of the serial I/O standard,
which uses 9 pins only, as shown in Table 4. The DB-9 pins are shown in Figure 11.
16
Table 3: RS232 Pins (DB-25)
Pin Description
1 Protective ground
2 Transmitted data (TxD)
3 Received data (RxD)
4 Request to send (RTS)
5 Clear to send (CTS)
6 Data set ready (DSR)
7 Signal ground (GND)
8 Data carrier detect (DCD)
9/10 Reserved for data testing
11 Unassigned
12 Secondary data carrier detect
13 Secondary clear to send
14 Secondary transmitted data
15 Transmit signal element timing
16 Secondary received data
17 Receive signal element timing
18 Unassigned
19 Secondary request to send
20 Data terminal ready (DTR)
21 Signal quality detector
22 Ring indicator
23 Data signal rate select
24 Transmit signal element timing
25 Unassigned
Pin Description
1 Data carrier detect (DCD)
2 Received data (RxD)
3 Transmitted data (TxD)
4 Data terminal ready (DTR)
5 Signal ground (GND)
6 Data set ready (DSR)
7 Request to send (RTS)
8 Clear to send (CTS)
9 Ring indicator (RI)
17
3.6 Data Communication Classification
Current terminology classifies data communication equipment as DTE (data terminal equipment) or DCE
(data communication equipment). DTE refers to terminals and computers that send and receive data, while
DCE refers to communication equipment such as modems, that are responsible for transferring the data.
Notice that all the RS232 pin function definitions of Tables 3 and 4 are from the DTE point of view.
The simplest connection between a PC and microcontroller requires a minimum of three pins, TxD, RxD,
and ground, as shown in Figure 12. Notice in that figure that the RxD and TxD pins are interchanged.
1. DTR (data terminal ready). When a terminal (or a PC COM port) is turned on, after going
through a self-test, it sends out signal DTR to indicate that it is ready for communication. If there
is something wrong with the COM port, this signal will not be activated. This is an active-low signal
and can be used to inform the modem that the computer is alive and kicking. This is an output pin
from DTE (PC COM port) and an input to the modem.
2. DSR (data set ready). When DCE (modem) is turned on and has gone through the self-test, it
asserts DSR to indicate that it is ready to communicate. Thus, it is an output from the modem (DCE)
and input to the PC (DTE). This is an active-low signal. If for any reason the modem cannot make
a connection to the telephone, this signal remains inactive, indicating to the PC (or terminal) that it
cannot accept or send data.
3. RTS (request to send). When the DTE device (such as a PC) has a byte to transmit, it asserts
RTS to signal the modem that it has a byte of data to transmit. RTS is an active-low output from the
DTE and an input to the modem.
4. CTS (clear to send). In response to RTS, when the modem has room for storing the data it is to
receive, it sends out signal CTS to the DTE (PC) to indicate that it can receive the data now. This
input signal to the DTE is used by the DTE to start transmission.
18
5. DCD (carrier detect, or DCD, data carrier detect). The modem asserts signal DCD to inform
the DTE (PC) that a valid carrier has been detected and that contact between it and the other modem
is established. Therefore, DCD is an output from the modem and an input to the PC (DTE).
6. RI (ring indicator). An output from the modem (DCE) and an input to a PC (DTE) indicates
that the telephone is ringing. It goes on and off in synchronization with the ringing sound. Of the six
handshake signals, this is the least often used, due to the fact that modems take care of answering the
phone.
From the above description, PC and modem communication can be summarized as follows: While signals
DTR and DSR are used by the PC and modem, respectively, to indicate that they are alive and well, it is
RTS and CTS that actually control the flow of data. When the PC wants to send data it asserts RTS, and
in response, if the modem is ready (has room) to accept the data, it sends back CTS. If, for lack of room,
the modem does not activate CTS, the PC will deassert DTR and try again. RTS and CTS are also referred
to as hardware control flow signals.
This concludes the description of the most important pins of the RS232 handshake signals plus TxD,
RxD, and ground. Ground is also referred to as SG (signal ground).
4. The start and stop bits are used in the (synchronous, asynchronous) method.
5. Assuming that we are transmitting the ASCII letter “E” (0100 0101 in binary) with no parity bit and
one stop bit, show the sequence of bits transferred serially.
6. In Question 5, find the overhead due to framing.
7. Calculate the time it takes to transfer 10,000 characters as in Question 5 if we use 9600 bps. What
percentage of time is wasted due to overhead?
8. True or false. RS232 is not TTL-compatible.
9. What voltage levels are used for binary 0 in RS232?
19
4 8051 Connection to RS232
In this section, the details of the physical connections of the 8051 to RS232 connectors are given. As stated
in Section 10.1, the RS232 standard is not TTL compatible; therefore, it requires a line driver such as the
MAX232 chip to convert RS232 voltage levels to TTL levels, and vice versa. The interfacing of 8051 with
RS232 connectors via the MAX232 chip is the main topic of this section.
4.2 MAX232
Since the RS232 is not compatible with today’s microprocessors and microcontrollers, we need a line driver
(voltage converter) to convert the RS232’s signals to TTL voltage levels that will be acceptable to the 8051’s
TxD and RxD pins. One example of such a converter is MAX232 from Maxim Corp. The MAX232 converts
from RS232 voltage levels to TTL voltage levels, and vice versa. One advantage of the MAX232 chip is that
it uses a +5 V power source which, is the same as the source voltage for the 8051. In other words, with
a single +5 V power supply we can power both the 8051 and MAX232, with no need for the dual power
supplies that are common in many older systems.
The MAX232 has two sets of line drivers for transferring and receiving data, as shown in Figure 13. The
line drivers used for TxD are called T1 and T2, while the line drivers for RxD are designated as R1 and
R2. In many applications only one of each is used. For example, T1 and R1 are used together for TxD
and RxD of the 8051, and the second set is left unused. Notice in MAX232 that the T1 line driver has a
designation of T1in and T1out on pin numbers 11 and 14, respectively. The T1in pin is the TTL side and is
connected to TxD of the microcontroller, while T1out is the RS232 side that is connected to the RxD pin of
the RS232 DB connector. The R1 line driver has a designation of R1in and R1out on pin numbers 13 and
12, respectively. The R1in (pin 13) is the RS232 side that is connected to the TxD pin of the RS232 DB
connector, and R1out (pin 12) is the TTL side that is connected to the RxD pin of the microcontroller. See
Figure 13. Notice the null modem connection where RxD for one is TxD for the other.
Figure 13: (a) Inside MAX232 and (b) its Connection to the 8051 (Null Modem)
MAX232 requires four capacitors ranging from 1 to 22 µF. The most widely used value for these capacitors
is 22 µF.
20
4.3 MAX233
To save board space, some designers use the MAX233 chip from Maxim. The MAX233 performs the same job
as the MAX232 but eliminates the need for capacitors. However, the MAX233 chip is much more expensive
than the MAX232. Notice that MAX233 and MAX232 are not pin compatible. You cannot take a MAX232
out of a board and replace it with a MAX233. See Figure 14 for MAX233 with no capacitor used.
Figure 14: (a) Inside MAX233 and (b) Its Connection to the 8051 (Null Modem)
Baud Rate
110
150
300
600
1200
2400
4800
9600
19200
21
In this section we discuss the serial communication registers of the 8051 and show how to program them to
transfer and receive data serially. Since IBM PC/compatible computers are so widely used to communicate
with 8051-based systems, we will emphasize serial communications of the 8051 with the COM port of the
PC. To allow data transfer between the PC and an 8051 system without any error, we must make sure that
the baud rate of the 8051 system matches the baud rate of the PC’s COM port. Some of the baud rates
supported by PC BIOS are listed in Table 5.
22
The moment a byte is written into SBUF, it is framed with the start and stop bits and transferred serially
via the TxD pin. Similarly, when the bits are received serially via RxD, the 8051 deframes it by eliminating
the stop and start bits, making a byte out of the data received, and then placing it in the SBUF.
23
SM0 SM1 Mode
0 0 Serial Mode 0
0 1 Serial Mode 1, 8-bit data, 1 stop bit, 1 start bit
1 0 Serial Mode 2
1 1 Serial Mode 3
Timer 1 of the 8051. In serial mode 1, for each character a total of 10 bits are transferred, where the first
bit is the start bit, followed by 8 bits of data, and finally 1 stop bit.
5.3.2 SM2
SM2 is the D5 bit of the SCON register. This bit enables the multiprocessing capability of the 8051 and is
beyond the discussion of this chapter. For our applications, we will make SM2 = 0 since we are not using
the 8051 in a multiprocessor environment.
5.3.3 REN
The REN (receive enable) bit is D4 of the SCON register. The REN bit is also referred to as SCON.4 since
SCON is a bit-addressable register. When the REN bit is high, it allows the 8051 to receive data on the
RxD pin of the 8051. As a result if we want the 8051 to both transfer and receive data, REN must be set
to 1. By making REN = 0, the receiver is disabled. Making REN = 1 or REN = 0 can be achieved by the
instructions “SETB SCON.4” and “CLR SCON.4”, respectively.
5.3.4 TB8
TB8 (transfer bit 8) is bit D3 of SCON. It is used for serial modes 2 and 3. We make TB8 = 0 since it is
not used in our applications.
5.3.5 RB8
RB8 (receive bit 8) is bit D2 of the SCON register. In serial mode 1, this bit gets a copy of the stop bit when
an 8-bit data is received. This bit (as is the case for TB8) is rarely used anymore. In all our applications we
will make RB8 = 0.
5.3.6 TI
TI (transmit interrupt) is bit D1 of the SCON register. This is an extremely important flag bit in the SCON
register. When the 8051 finishes the transfer of the 8-bit character, it raises the TI flag to indicate that it is
ready to transfer another byte. The TI bit is raised at the beginning of the stop bit.
5.3.7 RI
RI (receive interrupt) is the D0 bit of the SCON register. This is another extremely important flag bit in
the SCON register. When the 8051 receives data serially via RxD, it gets rid of the start and stop bits and
places the byte in the SBUF register. Then it raises the RI flag bit to indicate that a byte has been received
and should be picked up before it is lost. RI is raised halfway through the stop bit.
1. The TMOD register is loaded with the value 20H, indicating the use of Timer 1 in mode 2 (8-bit
auto-reload) to set the baud rate.
24
2. The TH1 is loaded with one of the values in Table 6 to set the baud rate for serial data transfer
(assuming XTAL = 11.0592 MHz).
3. The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8-bit data is
framed with start and stop bits.
Example 10-2 shows a program to transfer data serially at 4800 baud. Example 10-3 shows how to
transfer “YES” continuously.
[Example 10-2] Write a program for the 8051 to transfer letter “A” serially at 4800 baud, continuously.
25
1. The byte character to be transmitted is written into the SBUF register.
2. The start bit is transferred.
3. The 8-bit character is transferred one bit at a time.
4. The stop bit is transferred. It is during the transfer of the stop bit that the 8051 raises the TI flag (TI
= 1), indicating that the last character was transmitted and it is ready to transfer the next character.
5. By monitoring the TI flag, we make sure that we are not overloading the SBUF register. If we write
another byte into the SBUF register before TI is raised, the untransmitted portion of the previous byte
will be lost. In other words, when the 8051 finishes transferring a byte, it raises the TI flag to indicate
it is ready for the next character.
6. After SBUF is loaded with a new byte, the TI flag bit must be forced to 0 by the “CLR TI” instruction
in order for this new byte to be transferred.
From the above discussion we conclude that by checking the TI flag bit, we know whether or not the
8051 is ready to transfer another byte. More importantly, it must be noted that the TI flag bit is raised by
the 8051 itself when it finishes the transfer of data, whereas it must be cleared by the programmer with an
instruction such as “CLR TI”. It also must be noted that if we write a byte into SBUF before the TI flag
bit is raised, we risk the loss of a portion of the byte being transferred. The TI flag bit can be checked by
the instruction “JNB TI,. . . ” or we can use an interrupt, as we will see in Chapter 11.
1. The TMOD register is loaded with the value 20H, indicating the use of Timer 1 in mode 2 (8-bit
auto-reload) to set the baud rate.
2. TH1 is loaded with one of the values in Table 6 to set the baud rate (assuming XTAL = 11.0592 MHz).
3. The SCON register is loaded with the value 50H, indicating serial mode 1, where 8-bit data is framed
with start and stop bits and receive enable is turned on.
4. TR1 is set to 1 to start Timer 1.
5. RI is cleared with the “CLR RI” instruction.
6. The RI flag bit is monitored with the use of the instruction “JNB RI, xx” to see if an entire character
has been received yet.
7. When RI is raised, SBUF has the byte. Its contents are moved into a safe place.
8. To receive the next character, go to Step 5.
[Example 10-4] Program the 8051 to receive bytes of data serially, and put them in P1. Set the baud
rate at 4800, 8-bit data, and 1 stop bit.
26
[Example 10-5] Assume that the 8051 serial port is connected to the COM port of the IBM PC, and on
the PC we are using the HyperTerminal program to send and receive data serially. P1 and P2 of the 8051
are connected to LEDs and switches, respectively. Write an 8051 program to (a) send to the PC the message
“We Are Ready”, (b) receive any data sent by the PC and put it on LEDs connected to P1, and (c) get data
on switches connected to P2 and send it to the PC serially. The program should perform part (a) once, but
parts (b) and (c) continuously. Use the 4800 baud rate.
1. It receives the start bit indicating that the next bit is the first bit of the character byte it is about to
receive.
2. The 8-bit character is received one bit at time. When the last bit is received, a byte is formed and
placed in SBUF.
3. The stop bit is received. When receiving the stop bit the 8051 makes RI = 1, indicating that an entire
character byte has been received and must be picked up before it gets overwritten by an incoming
character.
27
4. By checking the RI flag bit when it is raised, we know that a character has been received and is sitting
in the SBUF register. We copy the SBUF contents to a safe place in some other register or memory
before it is lost.
5. After the SBUF contents are copied into a safe place, the RI flag bit must be forced to 0 by the “CLR
RI” instruction in order to allow the next received character byte to be placed in SBUF. Failure to do
this causes loss of the received character.
From the above discussion we conclude that by checking the RI flag bit we know whether or not the 8051
has received a character byte. If we fail to copy SBUF into a safe place, we risk the loss of the received
byte. More importantly, it must be noted that the RI flag bit is raised by the 8051, but it must be cleared
by the programmer with an instruction such as “CLR RI”. It also must be noted that if we copy SBUF into
a safe place before the RI flag bit is raised, we risk copying garbage. The RI flag bit can be checked by the
instruction “JNB RI, xx” or by using an interrupt, as we will see in Chapter 11.
Option 1 is not feasible in many situations since the system crystal is fixed. More importantly, it is not
feasible because the new crystal may not be compatible with the IBM PC serial COM port’s baud rate.
Therefore, we will explore option 2. There is a software way to double the baud rate of the 8051 while the
crystal frequency is fixed. This is done with the register called PCON (power control). The PCON register
is an 8-bit register. Of the 8 bits, some are unused, and some are used for the power control capability of
the 8051. The bit that is used for the serial communication is D7, the SMOD (serial mode) bit. When the
8051 is powered up, D7 (SMOD bit) of the PCON register is zero. We can set it to high by software and
thereby double the baud rate. The following sequence of instructions must be used to set high D7 of PCON,
since it is not a bit-addressable register:
MOV A, PCON ; p l a c e a copy o f PCON i n ACC
SETB ACC.7 ; make D7 = 1
MOV PCON, A ; now SMOD = 1 w i t h o u t
; c h a n g i n g any o t h e r b i t s
28
Table 8: Baud Rate Comparison for SMOD = 0 and SMOD = 1
[Example 10-6] Assuming that XTAL = 11.0592 MHz for the following program, state (a) what this
program does, (b) compute the frequency used by Timer 1 to set the baud rate, and (c) find the baud rate
of the data transfer.
MOV A, PCON ;A = PCON
SETB ACC.7 ; make D7 = 1
MOV PCON, A ;SMOD = 1 , d o u b l e baud r a t e
; w i t h same XTAL f r e q .
MOV TMOD, #20H ; Timer 1 , mode 2 ( auto−r e l o a d )
MOV TH1, #−3 ; 19200 ( 5 7 , 6 0 0 / 3 = 19200)
; s i n c e SMOD = 1)
MOV SCON, #50H ; 8− b i t data , 1 s t o p b i t , RI e n a b l e d
SETB TR1 ; s t a r t Timer 1
MOV A, #”B” ; transfer letter B
A 1: CLR TI ; make s u r e TI = 0
MOV SBUF, A ; transfer it
H 1: JNB TI , H 1 ; s t a y h e r e u n t i l t h e l a s t b i t i s gone
SJMP A 1 ; k e e p s e n d i n g ”B” a g a i n and a g a i n
Solution:
(a) This program transfers ASCII letter B (01000010 binary) continuously.
(b) With XTAL = 11.0592 MHz and SMOD = 1 in the above program, we have:
11.0592 MHz / 12 = 921.6 kHz machine cycle frequency
921.6 kHz / 16 = 57,600 Hz frequency used by Timer 1 to set the baud rate
57,600 Hz / 3 = 19,200 baud rate
[Example 10-7] Find the TH1 value (in both decimal and hex) to set the baud rate to each of the following.
(a) 9600 (b) 4800 if SMOD = 1. Assume that XTAL = 11.0592 MHz.
Solution:
With XTAL = 11.0592 MHz and SMOD = 1, we have Timer 1 frequency = 57,600 Hz.
(a) 57,600 / 9600 = 6; therefore, TH1 = −6 or TH1 = FAH.
(b) 57,600 / 4800 = 12; therefore, TH1 = −12 or TH1 = F4H.
[Example 10-8] Find the baud rate if TH1 = −2, SMOD = 1, and XTAL = 11.0592 MHz. Is this baud
rate supported by IBM/compatible PCs?
Solution:
With XTAL = 11.0592 MHz and SMOD = 1, we have Timer 1 frequency = 57,600 Hz. The baud rate
is 57,600 / 2 = 28,800. This baud rate is not supported by the BIOS of the PCs; however, the PC can be
programmed to do data transfer at such a speed. Also, HyperTerminal in Windows supports this and other
baud rates.
[Example 10-9] Assume a switch is connected to pin P1.7. Write a program to monitor its status and
send two messages to serial port continuously as follows:
SW = 0 send “NO”
SW = 1 send “YES”
Assume XTAL = 11.0592 MHz, 9600 baud, 8-bit data, and 1 stop bit.
29
ORG 0H
MAIN: MOV TMOD, #20H
MOV TH1, #−3 ; 9600 baud r a t e
MOV SCON, #50H
SETB TR1
SETB SW1 ; make SW an i n p u t
S1 : JB P2.1 , NEXT ; c h e c k SW s t a t u s
MOV DPTR, #MESS1 ; i f SW=0 d i s p l a y ”NO”
FN: CLR A
MOVC A, @A+DPTR ; re ad t h e v a l u e
JZ S1 ; c h e c k f o r end o f l i n e
ACALL SENDCOM ; send v a l u e t o s e r i a l p o r t
INC DPTR ; move t o n e x t v a l u e
SJMP FN ; repeat
NEXT: MOV DPTR, #MESS2 ; i f SW=1 d i s p l a y ”YES”
LN : CLR A
MOVC A, @A+DPTR ; re ad t h e v a l u e
JZ S1 ; c h e c k f o r end o f l i n e
ACALL SENDCOM ; send v a l u e t o s e r i a l p o r t
INC DPTR ; move t o n e x t v a l u e
SJMP LN ; repeat
SENDCOM: MOV SBUF, A ; place value in b u f f e r
HERE: JNB TI , HERE ; wait u n t i l transmitted
CLR TI
RET
MESS1 : DB ”NO” , 0
MESS2 : DB ”YES” , 0
END
[Example 10-10] Write a program to send the message “The Earth is but One Country” to serial port.
Assume a SW is connected to pin P1.2. Monitor its status and set the baud rate as follows:
SW = 0, 4800 baud rate
SW = 1, 9600 baud rate
Assume XTAL = 11.0592 MHz, 8-bit data, and 1 stop bit.
30
JZ S1 ; c h e c k f o r end o f l i n e
ACALL SENDCOM ; send v a l u e t o t h e s e r i a l p o r t
INC DPTR ; move t o n e x t v a l u e
SJMP FN ; repeat
SENDCOM:
MOV SBUF, A ; place value in b u f f e r
HERE: JNB TI , HERE ; wait u n t i l transmitted
CLR TI ; clear
RET ; return
MESS1 : DB ”The Earth i s but One Country ” , 0
END
4. With XTAL = 11.0592 MHz, what value should be loaded into TH1 to have a 9600 baud rate? Give
the answer in both decimal and hex.
5. To transfer a byte of data serially, it must be placed in register .
6. SCON stands for and it is a(n) -bit register.
7. Which register is used to set the data size and other framing information such as the stop bit?
8. True or false. SCON is a bit-addressable register.
9. When is TI raised?
10. Which register has the SMOD bit, and what is its status when the 8051 is powered up?
31
6.2 Addresses for All SCON and SBUF Registers
All the programs we have seen so far in this chapter assume the use of the first serial port as the default
serial port since every version of the 8051 comes with at least one serial port. The SCON, SBUF, and PCON
registers of the 8051 are part of the special function registers. The address for each of the SFRs is shown
in Table 9. Notice that SCON has address 98H, SBUF has address 99H, and finally PCON is assigned the
87H address. The first serial port is supported by all assemblers and C compilers in the market for the
8051. If you examine the list file for 8051 Assembly language programs, you will see that these labels are
replaced with their SFR addresses. The second serial port is not implemented by all versions of the 8051/52
microcontroller. Only a few versions of the 8051/52, such as the DS89C4x0, come with the second serial
port. As a result, the second serial port uses some reserved SFR addresses for the SCON and SBUF registers
and there is no universal agreement among the makers as to which addresses should be used. In the case of
the DS89C4x0, the SFR addresses of C0H and C1H are set aside for SBUF and SCON, as shown in Table 9.
The DS89C4x0 technical documentation refers to these registers as SCON1 and SBUF1 since the first ones
are designated as SCON0 and SBUF0.
32