AVR USART sending garbage

arduinoavrserialuart

I'm trying to make an ATMega328P to send serial data to my computer and print onto Putty using an arduino board to do the USB to serial conversions. The data that's printed, however is garbage data. I've tried changing the number of stop bits, checked the serial communications in putty, checked the Baud error rates, and have also added a delay so that the computer can read the serial data easier. Here's the code:

#include <avr/io.h>
#include <stdio.h>
#include <util/delay.h>

#define USART_BAUDRATE 9600
#define F_CPU 7372800
#define BAUD_PRESCALE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)

void printString(const char myString[]){
    uint8_t i = 8;
    while(myString[i]){
       while ((UCSR0A &(1<<UDRE0)) == 0){}//do nothing until transmission flag is set
          UDR0 = myString[i];
          i++;
    }    
}

int main(void)
{
    //--------------init usart----------------//
    UCSR0B = (1<<RXEN0)|(1<<TXEN0); //Enables the USART transmitter and receiver
    _delay_ms(10);
    UCSR0C = (1<<UCSZ01)|(1<<UCSZ00)|(USBS0<<1); //tells it to send 8bit characters (setting both USCZ01 and UCSZ00 to one)
    //now it has 2 stop bits.

    UBRR0H = (BAUD_PRESCALE >> 8); //loads the upper 8 bits into the high byte of the UBRR register
    UBRR0L = BAUD_PRESCALE; //loads the lower 8 bits
    //----------------------------------------//
    _delay_ms(10);


    for(;;){
    printString("Hello World!\r\n");
    }
return (0);
}

And the data that's displayed in putty is as follows. First there's a bunch of this:
àà àà à à àà àà àà à. Then there's a bunch of this:
f,Mün$M´M,M´M$M´M,M´M,M´M,M´M
and other similar characters. I don't know why these are getting printed. Thanks.

edit: here's the datasheet

Best Answer

This line looks suspicious:

UCSR0C = (1<<UCSZ01)|(1<<UCSZ00)|(USBS0<<1);

You probably want that to be:

UCSR0C = (1<<UCSZ01)|(1<<UCSZ00)|(1<<USBS0);

Related Topic