In 8051, we make use of Timer 1 to generate the required baud rate. Following are the registers that are need to be configured to communicate over UART.

  • TMOD
  • SCON
  • TH1
  • TL1
  • TCON

TMOD: This register is used to set the mode of Timer0 and Timer1. It is also used to select whether the timers are used as Timer or Counter.

SCON: Serial Control register has various functions like.. it has flags for Framing error, Transmit interrupt and receive interrupt. Its used to select the serial port mode, to enable or disable the reception etc.

TCON: This register has various flag and control bits e.g. Timer overflow flags, interrupt edge flags, timer control bits to start/stop the timer.

TH1 & TL1: Timer registers for Timer 1 determines the baudrate of UART.

More information on the above registers can be found in the 8051 Hardware manual.

Initializing UART in 8051

In Assembly:

Serial_Init:
	;Set timer 1 mode to 8-bit Auto-Reload
	mov TMOD,#20H
	;Enable reception
	;Set Serial port mode to 8-bit UART
	mov SCON,#50H
	;Set baudrate to 9600 at 11.0592MHz
	mov TH1,#0FDH
	mov TL1,#0FDH
	;Start Timer
	setb TR1
	ret

in C we can do this as...

#include <reg51.h>.
void serial_init(){
	TMOD = 0x20;
	SCON = 0x50;
	TH1  = 0xFD;
	TL1  = 0xFD;
	TR1  = 1;
}

To Send data to the serial port we just have to move the data in SBUF (serial buffer register) and wait for the Transmit Interrupt flag to be set. While receiving we wait for the Receive interrupt flag to be set and read the data from SBUF register. This can be done as shown below...

Serial_Send:
	;wait for last data to be
	;sent completely
	jnb TI,Serial_Send
	;clear the transmit interrupt flag
	clr TI
	;Then move the data to send in SBUF
	mov SBUF,A
	ret
	
Serial_Read:
	;Wait for Receive interrupt flag
	jnb RI,Serial_Read
	;If flag is set then clear it
	clr RI
	;Then read data from SBUF
	mov A,SBUF
	ret

Similarly in C we can write functions for read and write on serial port.

void serial_send(unsigned char dat){
	while(!TI);
	TI = 0;
	SBUF = dat;
}
unsigned char serial_read(){
	while(!RI);
	RI = 0;
	return SBUF;
}

See Also

Help & Queries

If you have any queries, doubts or feedback on this tutorial please share in our discussion forum.


Powered by MediaWiki
This page was last modified on 3 March 2015, at 14:38.
ArrayContent is available under Creative Commons Attribution Non-Commercial Share Alike unless otherwise noted.