MODULE - 6
Timer and serial port programming
Contents
• Programs on accessing timers registers
• Programs on producing time delay using mode 1 and mode 2
• Programs on generating various clock frequencies
• Programming of timers 0 and 1 as counters
• Serial port programming:
• transmitting and receiving data with different baud rates
• Programs on timer and Serial communication interrupts.
Introduction
• 8051 has two Timers/Counters
• Timer0/Counter0 and Timer1/Counter1
• Both timer/counter is sixteen-bit
Registers used
• TMOD (Timer Mode Register)
• TCON (Timer Control Register)
• THx (Timer High Register)
• TLx (Timer Low Register)
• x = 0, Timer 0
• x = 1, Timer 1
TMOD Register
TIMER 1 TIMER 0
GATE C/T M1 M0 GATE C/T M1 M0
• Gate: This bit indicates how to control the timer whether by software, or
hardware. If we set this by 0 we can start and stop the timer by software
(coding). If we set 1 timer is controlled by hardware.
• C/T: This bit used to select timer or counter. 0 for Timer and 1 for the
counter.
• M0, M1: These bits are used to select the timer modes like below.
M1 M0 MODE
0 0 Mode 0: 13 bit mode (seldom used).
0 1 Mode 1: 16-bit mode
1 0 Mode 2: 8-bit mode (with auto-reload feature)
1 1 Mode 3: 8-bit split timer
• 16-bit Time Mode (Mode 1)
• Timer mode “1” is a 16-bit timer.
• Commonly used mode.
• 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.
• 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.
TCON Register
Initializing a Timer
• First initialize the TMOD SFR
• For example, if we are using 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.
0 0 0 0 0 0 0 1
• TMOD=0x01;
• 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.
• TR0=1;
• Detecting Timer Overflow
• while (TF0==0); for timer 0 overflow
Timer’s clock frequency
XTAL frequency = 11.0592MHz, when C/T bit of TMOD is ‘0’
f = (1/12) * 11.0592e6
= 921.6 kHz
T = 1/f
= 1/921.6e3
= 1.085ms
In order to generate a delay of 1ms, the calculations
using above steps are as follows.
N = 1ms/1.085μs ≈ 922.
M = 65536-922 = 64614 (decimal).
64614 in Hexadecimal = FC66h.
Load TH with 0xFC and TL with 0x66.
• Write an 8051 C program to toggle all bits of P2 continuously every
500ms. Use Timer 1, mode 1 to create the delay.
• Making TH and TL both zero means that the timer will count from 0000
to FFFF, 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 ms = 71.1065ms.
71.1065ms * x =500ms
x = 500/71.1065 = 7
#include<reg51.h>
void T1M1Delay(void)
void T1M1Delay(void);
{
void main(void)
TMOD=0x10;
{
TH1=0x00;
unsigned char x;
TL1=0x00;
P2=0x55; TR1=1;
while(1) while(TF1==0);
{ TF1=0;
P2=~P2; TR1=0;
for(x=0;x<7;x++) }
T1M1Delay();
}
}
Example
Assuming XTAL = 11.0592 MHz, write a program to generate a square wave
of 50 Hz frequency on pin P2.3.
T = 1/50 Hz = 20 ms
1/2 of it for the high and low portions of the pulse = 10 ms
10 ms / 1.085 us = 9216
65536 - 9216 = 56320 = DC00H
TL = 00H and TH = DCH
The calculation for 12MHz crystal uses the same steps
Write an 8051 C program to create a frequency of 2500Hz
on pin P2.7. Use Timer 1, mode 2 to create the delay.
Given frequency: 2500Hz
T = 1/2500 Hz = 400ms
1/2 of it for the high and low portions of the pulse = 200ms
200ms / 1.085 us = 184.33≈184
256 - 184 = 72 in decimal = 48H
TH = 48H
Design a digital event counter system using an 8051 microcontroller. The system should
count the number of external pulses received on pin T1 (P3.5) from a 1-Hz clock source.
Implement Counter 1 in Mode 2 to automatically reload the counter value and
continuously count from 0H. Display the current count value on Port 1 (P1) in real-time.
#include <reg51.h> {
void main(void) TR1=1;
{ P1=TL1;
T1=1; }
TMOD = 0X60; // mode 2 while(TF1==0);
TH1 = 0; TR1=0;
while(1) TF1=0;
{ }
do }
Used for applications such as counting objects on a conveyor belt, monitoring machine cycles, or tracking
periodic events in an industrial environment
Assume that a 1-Hz external clock is being fed into pin T0(P3.4). Write a C program
for counter 0 in mode 1 to count up and display the state of the TL0 and TH0 registers
on P2 and P1 respectively.
#include <reg51.h> {
void main(void) TR0=1; //start timer
{ P1=TL0; //place value on pins
T0=1; //make T0 an input P2=TH0;
TMOD=0x05; }
TL0=0; //set count to 0 while (TF0==0); //wait here
TH0=0; //set count to 0 TR0=0; // stop timer
while(1) //repeat forever TF0=0;
{ }
do
Exercise Programs
1. Create a stopwatch using Timer 1 in counter mode. The system
should count external pulses from a 1-Hz clock source, allowing
users to start, stop, and reset the count using push buttons.
2. Implement a fault detection system where an 8051 counter
counts objects passing on a conveyor belt. If the expected count
does not match the actual count within a given time, trigger an
alarm/emergency LED.
3. Write an 8051 Embedded C program to generate a 10kHz square
wave on P1.0 using Timer 0.
Serial Communication
Introduction
• The microcontroller MCS51 has an inbuilt UART for carrying out
serial communication. The serial communication is done in the
asynchronous mode.
• A serial port, like other PC ports, is a physical interface to establish
data transfer between a computer and external hardware or device.
This transfer, through a serial port, takes place bit by bit.
• Bit Addressable: We can assign the values bit by bit. For example, for
a single bit, we can set whether 1 or 0.
• Byte Addressable: We can’t assign the values bit by bit. We can set
only byte by byte.
Serial Communication Basics
• Baud Rate: Speed of data transmission (e.g., 9600, 115200 bps).
• Frame Format:
• Start Bit (1 bit)
• Data (8 bits)
• Parity Bit (Optional)
• Stop Bit (1 bit)
• Modes of Serial Communication:
• Mode 0: Shift Register (Synchronous)
• Mode 1: 8-bit UART (Asynchronous)
• Mode 2: 9-bit UART (Fixed Baud)
• Mode 3: 9-bit UART (Variable Baud)
8051 Registers for Serial Communication
•SCON (Serial Control Register)
•Controls the mode of operation.
•Enables transmit/receive operations.
•TMOD (Timer Mode Register)
•Configures Timer 1 for baud rate generation.
•TH1 (Timer 1 High Byte)
•Defines baud rate.
•TI (Transmit Interrupt)
•Set when a byte is transmitted.
•RI (Receive Interrupt)
•Set when a byte is received.
SCON (Serial Control Register)
SM0 SM1 SM2 REN TB8 RB8 TI RI
SM0: Serial Port Mode Specifier 1 bit.
SM1: Serial port Mode Specifier 2-bit.
SM0 SM1 Mode Baudrate
0 0 Shift Register (Mode 0) Fosc/12
0 1 8-bit UART (Mode 1) Variable (Set by Timer 1)
1 0 9-bit UART (Mode 2) Fosc/32 or Fosc/64
1 1 9-bit UART (Mode 3) Variable (Set by Timer 1)
• SM2: Multiprocessor communications bit.
• Set/cleared by the program to enable multiprocessor communications in modes 2 and 3.
• When set to 1 an interrupt is generated if bit 9 of the received data is a 1; no interrupt is
generated if bit 9 is a 0.
• If set to 1 for mode 1, no interrupt will be generated unless a valid stop bit is received.
• Clear to 0 if mode 0 is in use.
• REN: Receive enable bit.
• Set to 1 to enable reception; cleared to 0 to disable reception.
• TB8: Transmitted bit 8.
• Set/cleared by the program in modes 2 and 3.
• RB8: Received bit 8.
• Bit 8 of received data in modes 2 and 3; stop bit in mode 1.
• Not used in mode 0.
• TI: Transmit Interrupt flag.
• Set to one at the end of bit 7 time in mode 0, and at the beginning of the stop bit for other
modes. Must be cleared by the program.
• RI: Receive Interrupt flag.
• Set to one at the end of bit 7 time in mode 0, and halfway through the stop bit for other moves.
Must be cleared by the program.
SBUF (Serial Buffer Register)
• SBUF Register: For a byte of data to be transferred via the TxD line, it
must be placed in the SBUF.
• SBUF holds the byte of data when it is received by the MCS51’s RxD
line.
PCON (Power Control Register)
SMOD – – – GF1 GF0 PD IDL
• SMOD: Double baud rate bit.
• If Timer 1 is used to generate the baud rate and SMOD = 1, the baud rate is
doubled when the serial port is used in modes 1, 2, or 3.
• GF1: General-purpose flag bit.
• GF0: General-purpose flag bit.
• PD: Power Down bit.
• Setting this bit activates the power-down operation in the 8051BH.
• IDL: Idle Mode bit. Setting this bit activates the Idle Mode operation in the
8051BH.
Initialize the UART (Configuration)
1. Configure Serial Port mode 1 or 3.
2. Configure Timer 1 to Timer mode 2 (8-bit auto-reload).
3. Set TH1 to xxH to reflect the correct frequency for desired baud.
4. Set PCON.7 (SMOD) to double the baud rate.
Steps to send data serially in serial port communication
1. Set baud rate by loading TMOD register with the value 20H; this indicates
timer 1 in mode 2 (8-bit auto-reload) to set baud rate.
2. The TH1 is loaded with proper values to set baud rate for serial data transfer.
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.
4. TR1 is set to 1 to start timer 1.
5. Transmit Interrupt(TI) is cleared by CLR TI instruction.
6. The character byte to be transferred serially is written into SBUF register.
7. The TI flag bit is monitored to see if the character has been transferred
completely.
8. To transfer the next byte, go to step 5.
Steps to receive data serially in serial port
communication
1. Set baud rate by loading TMOD register with the value 20H; this indicates
setting of timer 1 in mode 2 (8-bit auto-reload) to set baud rate.
2. The TH1 is loaded with proper values to set baud rate for serial data transfer.
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.
4. TR1 is set to 1 to start timer 1.
5. Receive Interrupt(RI) is cleared by CLR RI instruction.
6. The RI flag bit is monitored 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 transfer the next byte, go to step 5.
1. 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 and SMOD = 1,
we have timer frequency = 57,600 Hz.
(a) 57600 / 9600 = 6; so TH1 = -6 or TH1 = FAH
(b) 57600 / 4800 = 12; so TH1 = -12 or TH1 = F4H
2. 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=0. Assume that
XTAL 11.0592 MHz
(a) 28800 / 9600 = ?; so TH1 = ?
(b) 28800 / 4800 = ?; so TH1 = ?
Write a C program for 8051 to transfer the letter “A”
serially at 4800 baud continuously.
#include <reg51.h>
void main(void){
TMOD=0x20; //use Timer 1, mode 2
TH1=0xFA; //4800 baud rate
SCON=0x50;
TR1=1; // start timer
while (1) {
SBUF=‘A’; //place value in buffer
while (TI==0);
TI=0;}
}
Write an 8051 C program to transfer the message “YES”
serially at 9600 baud, 8-bit data, 1 stop bit. Do this
continuously.
#include <reg51.h> void SerTx(unsigned char x){
void SerTx(unsigned char); SBUF=x;
void main(void){ //place value in buffer
TMOD=0x20; //use Timer 1, mode 2 while (TI==0);
TH1=0xFD; //9600 baud rate //wait until transmitted
SCON=0x50; TI=0;
TR1=1; //start timer }
while (1) {
SerTx(‘Y’);
SerTx(‘E’);
SerTx(‘S’);
}
}
Program the 8051 in C to receive bytes of data serially
and put them in P1. Set the baud rate at 4800; use 8-bit
data, and 1 stop bit.
#include <reg51.h> while (RI==0); //wait to receive
void main(void){ mybyte=SBUF; //save value
unsigned char mybyte; P1=mybyte; //write value to port
TMOD=0x20; //use Timer 1, mode 2 RI=0;
TH1=0xFA; //4800 baud rate }
SCON=0x50; }
TR1=1; //start timer
while (1) { //repeat forever
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.
#include <reg51.h> if(MYSW==0) {
for (z=0;z<12;z++) {
sbit MYSW=P2^0; //input switch SBUF=Mess1[z]; //place value in buffer
void main(void){ while(TI==0); //wait for transmit
unsigned char z; TI=0;
unsigned char Mess1[]=“Normal Speed”; }
unsigned char Mess2[]=“High Speed”; }
//initialising serial port else {
TMOD=0x20; //use Timer 1, mode 2 PCON=PCON|0x80; //for high speed of 56K
TH1=0xFF; //28800 for normal for (z=0;z<10;z++) {
SCON=0x50; SBUF=Mess2[z]; //place value in buffer
TR1=1; //start timer
while(TI==0); //wait for transmit
TI=0;
}
}
}
LAB TASK-8
1. Write a C program for 8051 to transfer the letter “A” serially at 4800
baud continuously.
2. Write an 8051 C program to transfer the message “VIT” serially at
9600 baud, 8-bit data, 1 stop bit. Do this continuously.
3. Write a program the 8051 in C to receive bytes of data serially and
put them in P1. Set the baud rate at 4800; use 8-bit data, and 1 stop bit.
4. Write an 8051 C program to transfer the message “EMBEDDED C
PROGRAMMING” serially at 9600 baud, 8-bit data, 1 stop bit. Do this
continuously. Use function calls for initializing UART, transmit data,
get the string serially.
Interrupts in 8051 Microcontroller
• Interrupt is an event that temporarily suspends the main program, passes the
control to a special code section, executes the event-related function and
resumes the main program flow where it had left off.
• Interrupts in the 8051 microcontroller are more desirable because they
reduce the regular status checking of the interfaced devices or inbuilt
devices.
• Interrupts come in different types, such as software and hardware, maskable
and non-maskable, fixed and vector interrupts, and so on.
• Interrupt Service Routine (ISR) comes into the picture when interrupt
occurs, and then tells the processor to take appropriate action for the
interrupt, and after ISR execution, the controller jumps into the main
program.
Types of Interrupts in 8051
• The 8051 microcontroller can recognize five different events that cause the main
program to interrupt the normal execution. These five sources of interrupts in
8051are:
• Timer 0 overflow interrupt- TF0
• Timer 1 overflow interrupt- TF1
• External hardware interrupt- INT0
• External hardware interrupt- INT1
• Serial communication interrupt- RI/TI
• The microcontroller internally generates a timer and Serial interrupts.
• External interrupts are generated by additional interfacing devices or switches that
are externally connected to the microcontroller.
Types of Interrupts in 8051
• When an interrupt occurs, the microcontroller executes the interrupt
service routine so that the memory location corresponds to the
interrupt that enables it.
• The Interrupt corresponding to the memory location is given in the
interrupt vector table below for Embedded C.
Interrupt Enable (IE) Register
• This register is responsible for
enabling and disabling the
interrupt.
• It is a bit addressable register in
which EA must be set to one
for enabling interrupts.
• The corresponding bit in this
register enables particular
interrupts like timer-, external
and serial inputs.
• In the below IE register, the bit
corresponding to 1 activates the
interrupt, and 0 disables the
interrupt.
Interrupt Priority Register (IP)
• It is also possible to change the priority levels of the interrupts by setting or
clearing the corresponding bit in the Interrupt priority (IP) register as shown in
the figure.
Timer Interrupt Programming
• T0 and T1 interrupts are generated by the timer register bits
TF0 and TF1.
• These interrupts programming by C code involves:
• Selecting the timer by configuring the TMOD register and its
mode of operation.
• Choosing and loading the initial values of TLx and THx for
appropriate modes.
• Enabling the IE registers and corresponding timer bit in it.
• Set the timer - run bit to start the timer.
• Writing the subroutine for the timer for time required and clear
timer value TRx at the end of a subroutine.
Timer Interrupt Programming
• Assume that XTAL = 11.0592 MHz; write a C program that
continuously gets a single bit of data from PI. 7 and sends it to P1.0;
simultaneously generate a square wave of 2 kHz frequency on pin
P1.5. The crystal frequency is 11.0592MHz.
(a) T = 1 / f = 1 / 2 kHz = 500 us the period of square wave.
(b) 1 / 2 of it for the high and low portion of the pulse is 250ms.
(c) 250ms / 1.085ms = 230 and 65536 – 230 = 65306 = FF1AH.
(d) TL = 1A and TH = FF, all in hex.
#include <reg51.h> void main()
{
sbit SW =P1^7;
SW=1; //make switch input
sbit IND =P1^0; TMOD=0x01;
sbit WAVE =P1^5; TL0=0x1A;
TH0=0xFF; //for delay
void timer0(void) interrupt 1 IE=0x82; //enable interrupt for timer 0
{ TR0=1;
while (1)
WAVE=~WAVE; //toggle pin {
} IND=SW; //send switch to LED
}
}
Serial Communication Interrupt
Programming
• Serial communication interrupts come into the picture when sending or receiving
data is needed.
• Since one interrupt bit is set for the TI (Transfer Interrupt) and RI (Receiver
Interrupt) flags, the Interrupt Service routine must examine these flags to
determine the actual interrupt.
• The logical OR operation of these two flags (RI and TI) causes this interrupt,
which is cleared by the software alone.
• Here, a special register, SCON, controls communication operations by enabling its
corresponding bits.
• Configure the IE register to enable a serial interrupt
• Configure the SCON register for receiving or transferring operation
• Write a subroutine for this interrupt with the appropriate function and clear TI or
RI flags within this routine.
Serial Communication Interrupt
Programming
Write a C program that continuously gets a single bit of data from P1.7
and sends it to P1.0. Simultaneously, generate a square wave of 2 kHz
frequency on pin P2.5. Send the character 'a' at a baud rate of 9600bps.
Write a C program that continuously gets a single bit of data from P1.7
and sends it to P1.0. Simultaneously, generate a square wave of 2 kHz
frequency on pin P2.5. Send the character 'a' at a baud rate of 9600bps.
#include <reg51.h> //Subroutine for Interrupt void main(void)
sbit SW=P1^7; void serial0() interrupt 4 {
sbit IND=P1^0; { SW=1;
sbit WAVE=P2^5; if(TI==1) TH1= -3;
{ TMOD = 0x22;
void timer0(void) interrupt 1 SBUF='a'; TH0=0xA4;
{ TI=0; SCON=0x50;
WAVE=~WAVE; } TR0=1;
} else TR1=1;
{ IE=0x92;
RI=0; while(1)
} {
} IND=SW;
}
}
Write a C program using interrupt to do the following
1)Receive data serially and send it to P0
2)Read port P1 transmit data serially and give a copy to P2
3)Make timer 0 generate a square wave of 5 KHz frequency on P0.1
Assume that XTAL = 11.0592 MHz. Use the 9600 baud rate.
#include <reg51.h> void main()
sbit WAVE =P0^1; {
void timer0(void) interrupt 1 unsigned char x;
{ P1=0xFF;
WAVE=~WAVE; //toggle pin TH1=0xF6;
} TH0=0xA4;
void ser_intr(void)interrupt 4 //Subroutine for Interrupt TMOD=0x22;
{ SCON=0x50;
if(TI==1) TR0=1;
{ TR1=1;
TI=0; IE=0x92; //enable interrupt for timer 0
} while (1)
else {
{ x=P1;
char c; SBUF = x;
c=SBUF; P2=x;
IE=0x00; //Turning off interrupt to prevent recursion }
P0=SBUF; }
while(RI==0);
RI=0;
}
IE=0x90; //Reactivating the interrupt
}
External Interrupts
• A switch is connected to pin P3.2. The corresponding line goes low
when the switch is pressed, and "0A" is displayed at Port 0. Write a C
program to blink alternate LEDS connected to Port 1 Simultaneously.
• Note:
• Pins P3.2 and P3.3 are used for normal I/O unless the INT0 and INT1 bits in
the IE register are enable
External Interrupts
#include <reg51.h> void main()
sbit SW =P3^2; {
unsigned int i; SW=1;
void extint0() interrupt 0 IE=0x81;
{ while(1)
P0=0x0A; {
} P1=0x00;
for(i=250;i>0;i--)
{}
P1=0xAA;
for(i=250;i>0;i--)
{}
} }
Lab Tasks - 9
Write a C program
1. that continuously gets a single bit of data from P1. 7 and sends it to P1.0;
simultaneously generate a square wave of 2 kHz frequency on pin P1.5. The crystal
frequency is 11.0592MHz. (Timer 0, Mode 1)
2. that continuously gets a single bit of data from P1. 7 and sends it to P1.0;
simultaneously generate a square wave of 2 kHz frequency on pin P1.5. The crystal
frequency is 11.0592MHz. (Timer 1, Mode 2)
3. A switch is connected to pin P3.2. The corresponding line goes low when the switch is
pressed, and "0A" is displayed at Port 0. Write a C program to blink alternate LEDS
connected to Port 1 Simultaneously.
4. Write a C program using interrupts to do the following:
(a) Generate a 10 KHz frequency on P2.1 using T0 8-bit auto-reload
(b) Assume the clock pulse is connected to external interrupt1 EX1. Count the pulses and
display it on P0. Assume that XTAL = 11.0592 MHz. Set the baud rate at 9600.
TIMER/COUNTER MODE TMOD
T0 M1 0x01H
0x02H
T0 M2
T1 M1 0x10H
T1 M2 0x20H
C0 M1 0x05H
C0 M2 0x06H
C1 M1 0x50H
C1 M2 0x60H