How I can fix this code to allow my AVR to talk over serial port?

Posted by samoz on Stack Overflow See other posts from Stack Overflow or by samoz
Published on 2009-05-10T22:03:04Z Indexed on 2010/04/09 8:43 UTC
Read the original article Hit count: 405

Filed under:
|
|
|
|

Hi guys, I've been pulling my hair out lately trying to get an ATmega162 on my STK200 to talk to my computer over RS232. I checked and made sure that the STK200 contains a MAX202CPE chip.

I've configured the chip to use its internal 8MHz clock and divided it by 8.

I've tried to copy the code out of the data sheet (and made changes where the compiler complained), but to no avail.

My code is below, could someone please help me fix the problems that I'm having?

I've confirmed that my serial port works on other devices and is not faulty.

Thanks!

#include <avr/io.h>
#include <avr/iom162.h>

#define BAUDRATE 4800

void USART_Init(unsigned int baud)
{
    UBRR0H = (unsigned char)(baud >> 8);
    UBRR0L = (unsigned char)baud;

    UCSR0B = (1 << RXEN0) | (1 << TXEN0);

    UCSR0C = (1 << URSEL0) | (1 << USBS0) | (3 << UCSZ00);
}

void USART_Transmit(unsigned char data)
{
    while(!(UCSR0A & (1 << UDRE0)));

    UDR0 = data;
}

unsigned char USART_Receive()
{
    while(!(UCSR0A & (1 << RXC0)));

    return UDR0;
}

int main()
{

    USART_Init(BAUDRATE);

    unsigned char data;

    // all are 1, all as output
    DDRB = 0xFF;

    while(1)
    {
    	data = USART_Receive();

    	PORTB = data;

    	USART_Transmit(data);


    }
}

© Stack Overflow or respective owner

Related posts about embedded

Related posts about avr