Electgpl

8051 - Tx/Rx UART Atmel

Sep 28th, 2017
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.18 KB | None | 0 0
  1. #include<reg51.h>
  2. void UART_Init(int baudrate){
  3.    SCON=0x50;                                   // Asynchronous mode, 8-bit data and 1-stop bit
  4.    TMOD=0x20;                                   //Timer1 in Mode2.
  5.    TH1=256-(11059200UL)/(long)(32*12*baudrate); // Load timer value for baudrate generation
  6.    TR1=1;                                       //Turn ON the timer for Baud rate generation
  7. }
  8. void UART_TxChar(char ch){
  9.    SBUF=ch;                                     // Load the data to be transmitted
  10.    while(TI==0);                                // Wait till the data is trasmitted
  11.    TI=0;                                        //Clear the Tx flag for next cycle.
  12. }
  13. char UART_RxChar(void){
  14.    while(RI==0);                                // Wait till the data is received
  15.    RI=0;                                        // Clear Receive Interrupt Flag for next cycle
  16.    return(SBUF);                                // return the received char
  17. }
  18. int main(){
  19.    char i,a[]={"Welcome to 8051 Serial Comm, Type the char to be echoed: "};
  20.    char ch;
  21.    UART_Init(9600);                             //Initialize the UART module with 9600 baud rate
  22.    for(i=0;a[i]!=0;i++){
  23.       UART_TxChar(a[i]);                        // Transmit predefined string
  24.    }
  25.    while(1){
  26.       ch=UART_RxChar();                         // Receive a char from serial port
  27.       UART_TxChar(ch);                          // Transmit the received char
  28.    }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment