Programming an Interrupt Driven UART
If UART is still new to you, please read 8051 Tutorial 5: 8051 UART Programming in C.
1. Set Timer 1 to operate in 8-bit auto reload mode.
2. Load the TH1 register with a value that will set the desired baud rate.
3. Load the SCON register that will set the UART to operate according to the desired mode.
5. Start Timer 1 by setting TR1.
6. Clear RI or TI Flag.
7. Enable serial port interrupt by setting ES (ES=1).
8. Enable the global interrupt by setting EA (EA=1).
Example:
Write a program that will enable AT89C2051 to receive data via UART and move the data received to Port 1 pins. Use Mode 1, 8-bits, 1 start bit, 1 stop bit, no parity bit, 9600bps at 11.0592MHz crystal.
Solution:
#include<reg51.h>void my_uart_isr(void) interrupt 4 { if(TI) //check if interrupt is caused by Transmit Flag TI=0; //clear TI else //go here if interrupt is caused by Receive Flag { P1=SBUF; RI=0; //clear RI } }void main(void) { TMOD = 0x20; //Timer 1, mode 2 (auto-reload) TH1 = 0xFD; //load TH with -3 or FDh SCON = 0x50; //UART mode 1, receive enabled TR1 = 1; //start Timer1 RI = 0; //clear RI ES=1; //enable UART interrupt EA=1; //enable global interrupt while(1) //loop forever {;} }
The interrupt of the UART points to the interrupt priority number 4. For UART, the format of the ISR must be:
void your_uart_isr(void) interrupt 4
{
if(TI) //check if interrupt is caused by Transmit Flag
{
//your routine here
TI=0; //clear TI
}
else //go here if interrupt is caused by Receive Flag
{
//your routine here
RI=0; //clear RI
}
}
The interrupts caused by TI or RI are of the same priority. Therefore, their ISRs points to the same interrupt vector.
Unlike the timer interrupts, the TI or RI must be cleared inside the ISR.













nice post..well explained….thanx
how can we improve number of interrupt in 8051
I’m not very familiar with the 8051, but in most systems you can use a programmable interrupt controller (PIC) to handle, prioritize, or nest interrupts, and have it alert the processor using just one interrupt pin. In the processor’s interrupt handler code there can be more elaborate communication with the PIC to gather type/level/vector related data and respond accordingly.
I use the Intel 8259a regularly, but this is in a very outdated lab using mostly intel 8086 chips.