8051 Tutorial 5: 8051 UART Programming in C

Programming 8051 to Receive Data

1. Set the Timer 1 of AT89C2051 to operate in Mode 2 (8-bit auto reload). To do this, load the TMOD register with 20h. The Timer 1 of AT89C2051 is the one responsible to UART baud rates. More about AT89C2051 timers here.

2. Load the TH1 register with a value that will set the desired baud rate using the previously given formula.

3. Load the SCON register with a value that will set the UART to operate in Mode 1 with 8bits, 1 start bit, 1 stop bit, no parity bit, and receive enabled. To do this, load SCON with 50h.

4. Start Timer 1 by setting TR1.

5. Clear RI flag.

6. Monitor the RI flag. If RI is set, the SBUF received a byte. Read the content of SBUF once RI is set.

7. To receive another byte go to step 5.

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 main(void)
{
TMOD = 0×20;  //Timer 1, mode 2 (auto-reload)
TH1 = 0xFD;   //load TH with -3 or FDh
SCON = 0×50;  //UART mode 1, receive enabled
TR1 = 1;      //start Timer1
RI = 0;       //clear RI
while(1)      //loop forever
{
while(!RI){;} //monitor if RI is set
P1 = SBUF;    //move the contents of SBUF to Port 1
RI = 0;       //clear RI once RI is set
}
}

Pages: 1 2 3 4

Speak Your Mind

*