/* ************************************************************************* */
/* */
/* Description : UART communication routines */
/* Based on AppNote AVR109 - Self-programming */
/* */
/* FileName : serial.c */
/* */
/* ************************************************************************* */
#include <avr\io.h>
// Following calculation assumes that F_CPU is assigned in 'Project/Options'
#define BAUDRATE 4800
#define BAUD_PRESCALE (((F_CPU / (BAUDRATE * 16UL))) - 1)
/* definitions for UART control */
// Valid for ATmega328
#define BAUD_RATE_REG UBRR0 //
#define UART_STATUS_REG UCSR0A // OK, checked (but also control reg.)
#define UART_CONTROL_REG_B UCSR0B // OK, checked
#define UART_CONTROL_REG_C UCSR0C // Added for mode setting
#define ENABLE_TRANSMITTER_BIT TXEN0 // OK, checked
#define ENABLE_RECEIVER_BIT RXEN0 // OK, checked
#define DATA_REGISTER_EMPTY_BIT UDRE0 // Added, for possible speed-up
#define TRANSMIT_COMPLETE_BIT TXC0 // OK, checked
#define RECEIVE_COMPLETE_BIT RXC0 // OK, checked
#define UART_DATA_REG UDR0 // OK, checked
void inituart(void)
{
BAUD_RATE_REG = (unsigned char)BAUD_PRESCALE; // Set baud rate: Load the UBRR register
UART_CONTROL_REG_B = (1 << ENABLE_RECEIVER_BIT)|
(1 << ENABLE_TRANSMITTER_BIT); // Enable receive + transmit
UART_CONTROL_REG_C = (3<<UCSZ00); // Added: Async. UART, None
// Parity, 8-data, 1 stopbit
}
void sendchar(unsigned char c)
{
UART_DATA_REG = c; // prepare transmission
while (!(UART_STATUS_REG & (1 << TRANSMIT_COMPLETE_BIT)));// wait until byte sendt
UART_STATUS_REG |= (1 << TRANSMIT_COMPLETE_BIT); // delete TXCflag
}
unsigned char recchar(void)
{
while( !(UART_STATUS_REG & (1 << RECEIVE_COMPLETE_BIT)) ); // wait for data
return UART_DATA_REG;
}