Skip to content

Instantly share code, notes, and snippets.

@TorsteinOvstedal
Last active March 24, 2023 09:55
Show Gist options
  • Save TorsteinOvstedal/4a89bd5e96f3f385998be1a435325cec to your computer and use it in GitHub Desktop.
Save TorsteinOvstedal/4a89bd5e96f3f385998be1a435325cec to your computer and use it in GitHub Desktop.
USART on the MCU ATmega328p.
#ifndef USART_H
#define USART_H
#include <avr/io.h>
/**
* Initialize the USART registers for async operation with 8N1 data frames.
*
* Ref: 7810D–AVR–01/15, p. 159 - 165
*/
void usart_init(uint16_t baud_rate)
{
uint16_t bdrr = (F_CPU / 16 / baud_rate - 1);
UBRR0 = bdrr & 0xfff;
UCSR0A = 0b00100000;
UCSR0B = 0b00011000;
UCSR0C = 0b00000110;
}
/**
* Send one byte of data.
*
* Ref: 7810D–AVR–01/15, p. 150
*/
void usart_transmit(uint8_t data)
{
// Wait for empty transmit buffer.
while (!(UCSR0A & (1 << UDRE0)));
UDR0 = data;
}
/**
* Send a string of data.
*/
void usart_transmit_string(char *data)
{
for (; *data; data++)
usart_transmit((uint8_t) *data);
}
/**
* Receive a byte of data.
*
* Ref: 7810D–AVR–01/15, p. 152.
*/
uint8_t usart_receive(void)
{
// Wait for data.
while (!(UCSR0A & (1 << RXC0)));
return UDR0;
}
/**
* Flush the data buffer.
*
* Ref: 7810D–AVR–01/15, p. 155
*/
void usart_flush(void)
{
uint8_t _;
while (UCSR0A & (1 << RXC0))
_ = UDR0;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment