Electronic – UART with PC : Reciving absurd characters in PC

atmegaavravr-gccserialuart

I am working on a project using Atmega16 micro-controller of AVR family. I am using UART for my project. I need to send data to my PC AT 9600 baud rate via an USB-TTL converter and view the data using 'putty'.

I am getting absurd data in putty. I am not an electronics guy but a computer science guy so need a little bit of help.

I guess I might be writing the wrong fuse bits or something else.
Please specify the fuse bits if possible

The program for the micro-controller is below

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

#define UBRR_VALUE 51

//function to initialize UART
void uart_init(void)
{
    UBRRH=(UBRR_VALUE>>8);//shift the register right by 8 bits
    UBRRL=UBRR_VALUE;//set baud rate
    UCSRB|=(1<<TXEN)|(1<<RXEN);//enable receiver and transmitter
    UCSRC|=(1<<URSEL)|(1<<UCSZ0)|(1<<UCSZ1);//8 bit data format
}

//function to transmit data
void uart_transmit(unsigned char data)
{
    while(!(UCSRA & (1<<UDRE)));
    UDR=data;
}

void transmit_string(char *str_data)
{
    while(*str_data)
    {
        uart_transmit(*str_data);
        str_data++;
    }
}

int main(void)
{
    uart_init();
    while(1)
    {
        //transmit_string("hello");
        uart_transmit('h');
    }
    return 0;
}

The fuse bits specifications are given below

enter image description here

enter image description here

Thanks in advance for any type of help

Best Answer

Your baud rate divisor seems to select a baud rate of 19200 instead of 9600:

baud = (clock speed) / ( 16 * (UBRR + 1) )

Try to set UBRR_VALUE to 103 and see if your communication gets better.

A proper way would be to define F_CPU and BAUD, and let the macros from setbaud.h do the calculation:

#include <avr/io.h>

#define F_CPU 16000000

static void
uart_9600(void)
{
#define BAUD 9600
#include <util/setbaud.h>
    UBRRH = UBRRH_VALUE;
    UBRRL = UBRRL_VALUE;
#if USE_2X
    UCSRA |= (1 << U2X);
#else
    UCSRA &= ~(1 << U2X);
#endif
}
Related Topic