2
\$\begingroup\$

I am trying to get UART working via the ATmega328A. I want to enter a character, and get that character to be printed out. However, when my code is run this is what happens:

  1. I enter one character, that character is printed out.
  2. I enter a second character, and the character is printed out,But then the first character is printed out continuously, forever.

For example, the output from the console.

<user input a 5><5 is printed><system waits for input><user enter a 3><three is printed><system prints 5 repeatedly(for ever)>

enter image description here

The code:

 #include <avr/io.h>
 #include <util/delay.h>
 #include <stdlib.h>
                                                      // include LCD library
  #define F_CPU 8000000UL       
 #define BAUD 9600                                                       // define baud
 #define BAUDRATE ((F_CPU)/(BAUD*16UL)-1)        // set baudrate value for UBRR


                                 // set the CPU clock


 // function to initialize UART
 void uart_init (void)
 {
     UBRR0H=(BAUDRATE>>8);
     UBRR0L=BAUDRATE;                                                 //set baud rate
     UCSR0B|=(1<<TXEN0)|(1<<RXEN0);                     //enable receiver and transmitter
     UCSR0C|=(1<<UCSZ00)|(1<<UCSZ01);// 8bit data format
 }

 // function to send data - NOT REQUIRED FOR THIS PROGRAM IMPLEMENTATION
 void uart_transmit (unsigned char data)
 {
     while (!( UCSR0A & (1<<UDRE0)));                  // wait while register is free
     UDR0 = data;                                                     // load data in the register
 }

 // function to receive data
 unsigned char uart_recieve (void)
 {
     while(!(UCSR0A) & (1<<RXC0));                     // wait while data is being received
     return UDR0;                                                     // return 8-bit data
 }

 // main function: entry point of program
 int main (void)
 {
     unsigned char a;
     char buffer[10];

     uart_init();                                                    // initialize UART

     while(1)
     {

         uart_transmit( uart_recieve());                               

         _delay_ms(100);                                         
     }

     return 0;
 }
\$\endgroup\$
5
\$\begingroup\$

You have missing parentheses in while(!(UCSR0A) & (1<<RXC0)); condition. Correct it as

while(!(UCSR0A & (1<<RXC0)));

or

while(!(UCSR0A & _BV(RXC0)));

to reuse macros or

while(!bitRead(UCSR0A, RXC0));

if using Arduino.h library.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.