Electronic – Atmega8 USART transmitting wrong data

atmegaavrmicrocontrollerserialuart

I'm trying to get USART working on my atmega8-16PU microcontroller. I've studied the documentation and took the examples of code from there. I've managed to transmit the data from microcontroller to PL-2303HX chip which is connected to my computer via USB enter image description here

The problem is that i receive different data from what i send from mcu. Here is the code:

#define F_CPU 8000000UL // Clock Speed
#define BAUD 9600
#define MYUBRR (((F_CPU / (BAUD * 16UL))) - 1)

void USART_Init( unsigned int ubrr)
{
    /* Set baud rate */
    UBRRH = (unsigned char)(ubrr>>8);
    UBRRL = (unsigned char)ubrr;
    /* Enable receiver and transmitter */
    UCSRB = (1 << RXEN) | (1 << TXEN);
    /* Set frame format: 8 data bits, 1 stop bit */
    UCSRC = (1 << URSEL) | (1 << USBS) | (1 << UCSZ0);
}

void USART_Transmit( unsigned char data )
{
    /* Wait for empty transmit buffer */
    while ( !( UCSRA & (1<<UDRE)) );
    /* Put data into buffer, sends the data */
    UDR = data;
}

int main()
{
    USART_Init(MYUBRR);
    while(1)                      /* run continuously */
    {
        USART_Transmit('a');
        _delay_ms(100);
    }
}

I get 0x80 0x00 at the receiver's side and that is not the 'a' symbol. If it's important a 12 MHz quartz is connected to the PL-2303HX chip. What am I doing wrong?

Best Answer

Most common error: You forgot the (default) Clock Div8 Fuse and your MCU runs on 1 MHz instead of 8 MHz. Try setting your COM Baudrate to 1200 Baud on the PC.

Another nitpick:

#define FOSC 8000000UL // Clock Speed
...
#define MYUBRR (((F_CPU / (BAUD * 16UL))) - 1)

Notice that you defined FOSC but then used F_CPU in your macro.