Electronic – UART Baudrate on ATmega328p

avrc

I've wrote a program to run the UART on a custom board, using the the atmega328p only with the internal oscillator, here is my code :

#define F_CPU 1000000UL
#include <avr/io.h>
#include <util/delay.h>
#define BAUD 9600 
#define MYUBRR    F_CPU/16/BAUD-1

void init_uart(unsigned short uValue  ){
    // setting the baud rate 
    UBRR0H =(unsigned char)  ( uValue>> 8);  // 0x00 
    UBRR0L =(unsigned char) uValue;  // 0x0C
    // enabling TX & RX 
    UCSR0B = (1<<RXEN0)|(1<<TXEN0);
    UCSR0A = (1<<UDRE0);
    UCSR0C =  (1 << UCSZ01) | (1 << UCSZ00);    // Set frame: 8data, 1 stop
    
}
int main (){
    init_uart(MYUBRR);
    DDRD |= (1<< PD7);
    for(;;){
        PORTD ^= (1<< PD7);
        UDR0 = 'k';
        //_delay_ms(500);
    }
    return 0;
}

I've set the register values based on the examplein the datasheet page 241.
the problem that I have is, that I'm not receiving the word correctly, here's what I get :

enter image description here

So any idea what I'm missing here ?

thanks in advance !

Best Answer

I solved it. I had to wait on the transmitter and receive flags here the working code :

#define F_CPU 1000000
#include <avr/io.h>
#include <util/delay.h>
#define BAUD 9600 
#define MYUBRR    F_CPU/8/BAUD-1

void init_uart(unsigned short uValue  ){
    // setting the baud rate  based on the datasheet 
    UBRR0H =0x00;//(unsigned char)  ( uValue>> 8);  // 0x00 
    UBRR0L =0x0C;//(unsigned char) uValue;  // 0x0C  
    // enabling TX & RX 
    UCSR0B = (1<<RXEN0)|(1<<TXEN0);
    UCSR0A = (1<<UDRE0)|(1<<U2X0);
    UCSR0C =  (1 << UCSZ01) | (1 << UCSZ00);    // Set frame: 8data, 1 stop

}

unsigned char USART_Receive( void )
{
    /* Wait for data to be received */
    while ( !(UCSR0A & (1<<RXC0)) )
    ;
    /* Get and return received data from buffer */
    return UDR0;
}
void USART_Transmit( unsigned char data )
{
    /* Wait for empty transmit buffer */
    while ( !( UCSR0A & (1<<UDRE0)) )
    ;
    /* Put data into buffer, sends the data */
    UDR0 = data;
}

int main (){
    init_uart(MYUBRR);
    DDRD |= (1<< PD7);
    for(;;){
        PORTD ^= (1<< PD7);
        USART_Transmit('x');
        USART_Transmit('l');
        //_delay_ms(1000);
    }
    return 0;
}
Related Topic