How to set up UART of ATmega328pb in Atmel Studio 7.0

Posted

in

by

To set up uart in Atmel studio 7.0.

Firstly you will need a common baud rate.

Then you go to section 24.11 of the datasheet. You will find common calculated values for the UBRRn register.

UBRRn register is comprised of high and low registers.

First, you have to initialise the Data direction registers for the RX and Tx Pins. Then you initialise the UART peripheral.

DDRD &= ~(1 << DDD0);				// PD0 - Rx Input
DDRD |= (1 << DDD1);				// PD1 - Tx Ouput
USART_Init();					// UART intialise

Here is the basic UART library code.

/*
* Name: UART library Code
*/
void USART_Init( )
{
	/*Set baud rate */
	
	UBRR0L = 103;
	/* Enable receiver and transmitter */
	UCSR0B = (1 << RXCIE0)|(1<<RXEN0)|(1<<TXEN0);
	/* Set frame format: 8data, 1stop bit */
	UCSR0C = (3<<UCSZ00);
}

void USART_Transmit(uint8_t data )
{
	
	/* Wait for empty transmit buffer */
	while ( !( UCSR0A & (1<< UDRE0 )) )
	;
	/* Put data into buffer, sends the data */
	UDR0 = data;
	
}

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_SendString(char *str)
{
	unsigned char j=0;
	
	while (str[j]!=0)		/* Send string till null */
	{
		USART_Transmit(str[j]);
		j++;
	}
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *