MODULE 4: 8051 Serial Port Programming in Assembly and C: Microcontroller Notes:18EE52
MODULE 4: 8051 Serial Port Programming in Assembly and C: Microcontroller Notes:18EE52
Structure
Objectives
To explain in detail the execution of 8051 Assembly language instructions and data
types
To explain develop 8051 programs for time delay and Interrupts
1. When a microprocessor communicates with the outside world, it provides the data in
byte-sized chunks. In some cases, such as printers, the information is simply grabbed
from the 8-bit data bus and presented to the 8-bit data bus of the printer.
2. This can work only if the cable is not too long, since long cables diminish and even
distort signals. Furthermore, an 8-bit data path is expensive. For these reasons, serial
communication is used for transferring data between two systems located at distances
of hundreds of feet to millions of miles apart. Figure 4-1 diagrams serial versus
parallel data transfers.
3. 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.
4. 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 Os and Is to audio
tones, which are sinusoidal-shaped signals. This conversion is performed by a
peripheral device called a modem, which stands for “modulator/demodulator.”
5. t , 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 Os and 1 s to audio tones) and demodulate (converting
from audio tones to Os and 1 s).
6. 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 1C 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).
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.
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.
7. 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.
8. 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 Is. Similarly, in an even-parity bit
system the total number of bits, including the parity bit, is even.
9. 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.
RS232 pins
Table 4.1 provides the pins and their labels for the RS232 cable, commonly referred to as the
DB-25 connector. In labelling, DB-25P refers to the plug connector (male) and DB-25S is for
the socket connector (female).
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.
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 modern 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. However, if the PC is in
charge of answering the phone, this signal can be used.
3. These pins are TTL compatible; therefore, they require a line driver to make them
RS232 compatible. One such line driver is the MAX232 chip.
b)MAX232
1. 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.
2. One example of such a converter is MAX232 from Maxim Corp. (www.maxim-
ic.com). 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.
3. 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.
4. The MAX232 has two sets of line drivers for transferring and receiving data, as
shown in
Figure 4.7. The line drivers used for TxD are called Tl and T2, while the line drivers
for RxD are designated as Rl and R2. In many applications only one of each is used.
For example, Tl and Rl are used together for TxD and RxD of the 8051, and the
second set is left unused. Notice in MAX232 that the Tl line driver has a designation
of Tlin and Tlout on pin numbers 11 and 14, respectively.
5. The Tlin pin is the TTL side and is connected to TxD of the microcontroller, while
Tlout is the RS232 side that is connected to the RxD pin of the RS232 DB connector.
The Rl line driver has a designation of Rlin and Rlout on pin numbers 13 and 12,
respectively. The Rlin (pin 13) is the RS232 side that is connected to the TxD pin of
the RS232 DB connector, and Rlout (pin 12) is the TTL side that is connected to the
RxD pin of the microcontroller.
6. MAX232 requires four capacitors ranging from 1 to 22 nF. The most widely used
value for these capacitors is 22 nF.
Figure 4.7. (a) Inside MAX232 and (b) its Connection to the 8051 (Null Modem)
Example 4-1
With XTAL = 11.0592 MHz, find the TH1 value needed to have the following baud
rates. (a) 9600 (b) 2400 (c) 1200
Solution:
With XTAL = 11.0592 MHz, we have:
The machine cycle frequency of the 8051 = 11.0592 MHz / 12 = 921.6 kHz, and 921.6 kHz /
32 = 28,800 Hz is the frequency provided by UART to Timer 1 to set baud rate.
Notice that 1/12th of the crystal frequency divided by 32 is the default value upon activation
of the 8051 RESET pin. We can change this default setting.
11.0592MHz
SBUF is an 8-bit register used solely for serial communication in the 8051. For a byte of data
to be transferred via the TxD line, it must be placed in the SBUF register. Similarly, SBUF
holds the byte of data when it is received by the 8051 ‘s RxD line. SBUF can be accessed like
any other register in the 8051. Look at the following examples of how this register is
accessed:
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.
The SCON register is an 8-bit register used to program the start bit, stop bit, and data bits of
data framing, among other things.
The following describes various bits of the SCON register.
In the SCON register, when serial mode 1 is chosen, the data framing is 8 bits, 1 stop bit, and
1 start bit, which makes it compatible with the COM port of IBM/compatible PCs. More
importantly, serial mode 1 allows the baud rate to be variable and is set by 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.
b) 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.
c) 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. Notice
that these instructions use the bit-addressable features of register SCON. This bit can be used
to block any serial data reception and is an extremely important bit in the SCON register.
d) TBS
TBS (transfer bit 8) is bit D3 of SCON. It is used for serial modes 2 and 3. We make TBS = 0
since it is not used in our applications.
e) 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 TBS) is rarely used
anymore. In all our applications we will make RB8 = 0. Like TB8, the RB8 bit is also used in
serial modes 2 and 3.
f) Tl
TI (transmit interrupt) is bit Dl 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. We will discuss its role further when programming examples of data
transmission are given.
g) Rl
RI (receive interrupt) is the DO 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, and we will soon see how this bit is used in programs for
receiving data serially.
Example 4-3
Write a program to transfer the message “YES” serially at 9600 baud, 8-bit data, 1 stop bit.
Do this continuously.
Example 4-4
Program the 8051 to receive bytes of data serially, and put them in PI. Set the baud rate at
4800, 8-bit data, and 1 stop bit.
Example 4-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. PI 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 PI, 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.
In receiving bits via its RxD pin, the 8051 goes through the following steps.
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.
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.
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:
To see how the baud rate is doubled with this method, we show the role of the SMOD bit (D7
bit of the PCON register), which can be 0 or 1.
We discuss each case.
Baud rates for SMOD = 0
1. When SMOD = 0, the 8051 divides 1/12 of the crystal frequency by 32 and uses that
frequency for Timer 1 to set the baud rate. In the case of XTAL = 11.0592 MHz we
have:
Machine cycle freq. = 11.0592 MHz / 12 = 921.6 kHz
And 921.6 kHz / 32 = 28,800 Hz since SMOD = 0
This is the frequency used by Timer 1 to set the baud rate. This has been the basis of all the
examples so far since it is the default when the 8051 is powered up.
Example 4-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.
Example 4-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 4-9
Assume a switch is connected to pin PL7. 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.
Solution:
Example 4.11
Example 4.12
Example 4.13
Write an 8051 C program to send two different strings to the serial port. Assuming that
SW is connected to pin P2.0, monitor its status and make a decision as follows:
SW = 0: send your first name
SW = 1: send your last name
Assume XTAL = 11.0592 MHz, baud rate of 9600, 8-bit data, 1 stop bit.
Example 4.14
Write an 8051 C program to send the two messages “Normal Speed” and “High Speed” to the
serial port. Assuming that SW is connected to pin P2.0, monitor its status and set the baud
rate as follows:
SW = 0 28,800 baud rate
SW = 1 56K baud rate
Assume that XTAL = 11.0592 MHz for both cases.
Solution:
Since many C compilers do not support the second serial port of the DS89C4xO chip, we
have to declare the byte addresses of the new SFR registers using the sfr keyword. Table 10-6
and Figure 10-12 provide the SFR byte and bit addresses for the DS89C4xO chip.
Example 4-15
Write a C program for the DS89C4xO to transfer letter “A” serially at 4800 baud
continuously. Use the second serial port with 8-bit data and 1 stop bit. We can only use Timer
1 to set the baud rate.
Solution:
Example 4-16
Program the DS89C4xO in C to receive bytes of data serially via the second serial port and
put them in PI. Set the baud rate at 9600, 8-bit data, and 1 stop bit. Use Timer 1 for baud rate
generation.
e)The most important reason that the interrupt method is preferable is that the polling method
wastes much of the microcontroller’s time by polling devices that do not need service. So in
order to avoid tying down the microcontroller, interrupts are used. For example, in discussing
timers in Chapter 9 we used the instruction “JNB TF, target”, and waited until the timer
rolled over, and while we were waiting we could not do anything else.
f)That is a waste of the microcontroller’s time that could have been used to perform some
useful tasks. In the case of the timer, if we use the interrupt method, the microcontroller can
go about doing other tasks, and when the TF flag is raised the timer will interrupt the
microcontroller in whatever it is doing.
Interrupt service routine
When an interrupt is invoked, the microcontroller runs the interrupt service routine. For every
interrupt, there is a fixed location in memory that holds the address of its ISR. The group of
memory locations set aside to hold the addresses of ISRs is called the interrupt vector table.
Figure 4.9. Redirecting the 8051 from the Interrupt Vector Table at Power-up
Example 4-16
4. In this way, the microcontroller can do other things until it is notified that the timer
has rolled over
Example 4-17
Write a program that continuously gets 8-bit data from PO and sends it to PI while
simultaneously creating a square wave of 200 (as period on pin P2.1. Use Timer 0 to create
the square wave. Assume that XTAL =11.0592 MHz.
Solution:
Example 4-18
Write a program o create a square wave that has a high portion of 1085 us and a low portion
of 15 us. Assume XTAL = 11.0592 MHz. Use Timer 1.
Notice that the low portion of the pulse is created by the 14 MC (machine cycles) where
each MC = 1.085 us and 14 x 1.085 us = 15.19 us.
Example 4-19
Write a program to generate a square wave of 50 Hz frequency on pin PI .2. UseTimer 0.
Assume that XTAL = 11.0592MHz.
The 8051 has two external hardware interrupts. Piri 12 (P3.2) and pin 13 (P3.3) of the 8051,
designated as INTO and INT1, are used as external hardware interrupts. Upon activation of
these pins, the 8051 gets interrupted in whatever it is doing and jumps to the vector table to
perform the interrupt service routine.
Example 4.20
Assume that the INT1 pin is connected to a switch that is normally high. Whenever it goes
low, it should turn on an LED. The LED is connected to PI .3 and is normally off. When it is
turned on it should stay on for a fraction of a second. As long as the switch is pressed low, the
LED should stay on.
Solution:
but no more. This is due to the fact that the level-triggered interrupt is not latched.
Thus the pin must be held in a low state until the start of the ISR execution.
TF0 TCON.5 Timer 0 overflow flag. Set by hardware when timer/counter 0 overflows.
Cleared by hardware as the processor vectors to the service routine.
TR0 TCON.4 Timer 0 run control bit. Set/cleared by software to turn
timer/counter 0 on/off.
IE1 TCON.3 External interrupt 1 edge flag. Set by CPU when the external interrupt edge (H-
to-L transition) is detected. Cleared by CPU when the interrupt is processed. Note: This flag
does not latch low-level triggered interrupts.
IT1 TCON.2 Interrupt 1 type control bit. Set/cleared by software to specify falling edge/low-
level triggered external interrupt.
IE0 TCON.1 External interrupt 0 edge flag. Set by CPU when external interrupt (H-to-L
transition) edge is detected. Cleared by CPU when interrupt is processed. Note: This flag
does not latch low-level triggered interrupts.
IT0 TCON.0 Interrupt 0 type control bit. Set/cleared by software to specify falling edge/low-
level triggered external interrupt.
Example 4-21
Assuming that pin 3.3 (INT1) is connected to a pulse generator, write a program in which the
falling edge of the pulse will send a high to PI.3, which is connected to an LED (or buzzer).
In other words, the LED is turned on and off at the same rate as the pulses are applied to the
INT1 pin. This is an edge-triggered version of Example 11-5.
In edge-triggered interrupts, the external source must be held high for at least one machine
cycle, and then held low for at least one machine cycle to ensure that the transition is seen by
the microcontroller.
1. The falling edge is latched by the 8051 and is held by the TCON register. The TCON.
1 and TCON.3 bits hold the latched falling edge of pins INTO and INT1, respectively.
TCON.l and TCON.3 are also called IEO and IE1, respectively, as shown in Figure
11-6. They function as interrupt-in-service flags.
2. When an interrupt-in-service flag is raised, it indicates to the external world that the
interrupt is being serviced and no new interrupt on this INTw pin will be responded to
until this service is finished. This is just like the busy signal you get if calling a
telephone number that is in use. Regarding the ITO and IT1 bits in the TCON register,
the following two points must be emphasized.
Example 4-22
What is the difference between the RET and RETI instructions? Explain why we cannot use
RET instead of RETI as the last instruction of an ISR.
Solution:
Both perform the same actions of popping off the top two bytes of the stack into the program
counter, and making the 8051 return to where it left off. However, RETI also performs an
additional task of clearing the interrupt-in-service flag, indicating that the servicing of the
interrupt is over and the 8051 now can accept a new interrupt on that pin. If you use RET
instead of RETI as the last instruction of the interrupt service routine, you simply block any
new interrupt on that pin after the first interrupt, since the pin status would indicate that the
interrupt is still being serviced. In the cases of TFO, TF1, TCON.l, and TCON.3, they are
cleared by the execution of RETI.
Example 4-24
Write a program in which the 8051 gets data from PI and sends it to P2 continuously while
incoming data from the serial port is sent to PO. Assume that XTAL = 11.0592 MHz. Set the
baud rate at 9600.
Solution:
Example 4-26
Discuss what happens if interrupts INTO, TFO, and INT1 are activated at the same time.
Assume priority levels were set by the power-up reset and that the external hardware
interrupts are edge-triggered.
Solution:
If these three interrupts are activated at the same time, they are latched and kept internally.
Then the 8051 checks all five interrupts according to the sequence listed in Table 4.6.If any is
activated, it services it in sequence. Therefore, when the above three interrupts are activated,
IEO (external interrupt 0) is serviced first, then Timer 0 (TFO), and finally IE1 (external
interrupt 1).
Example 4-28
Assume that after reset, the interrupt priority is set by the instruction “MOV IP,
400001100B”. Discuss the sequence in which the interrupts are serviced.
Solution:
The instruction “MOV IP, #0 0 0 0110 OB” (B is for binary) sets the external interrupt 1
(INT1) and Timer 1 (TF1) to a higher priority level compared with the rest of the interrupts.
However, since they are polled according to Table 11-3, they will have the following priority.
The 8051 C compilers have extensive support for the 8051 interrupts with two major features
as follows:
1. They assign a unique number to each of the 8051 interrupts, as shown in Table
11-4.
2. It can also assign a register bank to an ISR. This avoids code overhead due to
the pushes and pops of the RO – R7 registers.
Table 4.7: 8051/52 Interrupt Numbers in C
Example 4-29
Write a C program that continuously gets a single bit of data from PI. 7 and sends it to Pl.0,
while simultaneously creating a square wave of 200 (as period on pin P2.5. Use timer 0 to
create the square wave. Assume that XTAL = 11.0592 MHz.
Solution:
Example 4-30
Write a C program that continuously gets a single bit of data from PI. 7 and sends it to Pl.0 in
the main, while simultaneously (a) creating a square wave of 200 us period on pin P2.5, and
(b) sending letter ‘A’ to the serial port. Use Timer 0 to create the square wave. Assume that
XTAL = 11.0592 MHz. Use the 9600 baud rate.
Solution:
Example 4-31
Write a C program using interrupts to do the following:
1. Receive data serially and send it to P0,
2. Read port PI, transmit data serially, and give a copy to P2,
3. Make timer 0 generate a square wave of 5 kHz frequency on P0.l.
Assume that XTAL = 11.0592 MHz. Set the baud rate at 4800.
Solution:
Example 4-32
Write a C program using interrupts to do the following:
1. Generate a 10000 Hz frequency on P2.1 using TO 8-bit auto-reload,
2. Use timer 1 as an event counter to count up a 1-Hz pulse and display it on PO. The
pulse is connected to EX1.
Assume that XTAL = 11.0592 MHz. Set the baud rate at 9600.
Outcomes