Guest User

AVR USART maxEmbedded.com

a guest
Oct 19th, 2013
3,248
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2.  
  3. #include <avr/io.h>
  4. #include <util/delay.h>
  5. #include <stdlib.h>
  6. #include "lcd.h"                            // include LCD library
  7.  
  8. #define BAUD 9600                           // define baud
  9. #define BAUDRATE ((F_CPU)/(BAUD*16UL)-1)    // set baudrate value for UBRR
  10.  
  11. #ifndef F_CPU
  12. #define F_CPU 16000000UL                    // set the CPU clock
  13. #endif
  14.  
  15. // function to initialize UART
  16. void uart_init (void)
  17. {
  18.     UBRRH=(BAUDRATE>>8);
  19.     UBRRL=BAUDRATE;                         //set baud rate
  20.     UCSRB|=(1<<TXEN)|(1<<RXEN);             //enable receiver and transmitter
  21.     UCSRC|=(1<<URSEL)|(1<<UCSZ0)|(1<<UCSZ1);// 8bit data format
  22. }
  23.  
  24. // function to send data - NOT REQUIRED FOR THIS PROGRAM IMPLEMENTATION
  25. void uart_transmit (unsigned char data)
  26. {
  27.     while (!( UCSRA & (1<<UDRE)));          // wait while register is free
  28.     UDR = data;                             // load data in the register
  29. }
  30.  
  31. // function to receive data
  32. unsigned char uart_recieve (void)
  33. {
  34.     while(!(UCSRA) & (1<<RXC));             // wait while data is being received
  35.     return UDR;                             // return 8-bit data
  36. }
  37.  
  38. // main function: entry point of program
  39. int main (void)
  40. {
  41.     unsigned char a;
  42.     char buffer[10];
  43.  
  44.     uart_init();                            // initialize UART
  45.     lcd_init(LCD_DISP_ON_CURSOR);           // initialize LCD
  46.     lcd_home();                             // goto LCD Home
  47.  
  48.     while(1)
  49.     {
  50.         a=uart_recieve();                   // save the received data in a variable
  51.         itoa(a,buffer,10);                  // convert numerals into string
  52.         lcd_clrscr();                       // LCD clear screen
  53.         lcd_home();                         // goto LCD home
  54.         lcd_puts(buffer);                   // display the received value on LCD
  55.         _delay_ms(100);                     // wait before next attempt
  56.     }
  57.    
  58.     return 0;
  59. }
RAW Paste Data