Last active
March 20, 2018 14:24
-
-
Save 3XX0/5524477 to your computer and use it in GitHub Desktop.
simple AVR USART
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <avr/io.h> | |
#include <avr/interrupt.h> | |
#include <avr/sfr_defs.h> | |
static void init(uint16_t rate) | |
{ | |
UBRR0H = (uint8_t) (rate >> 8); // freq/(16*speed)-1 | |
UBRR0L = (uint8_t) rate; | |
UCSR0A &= ~_BV(U2X0); // unset double speed (optiboot) | |
UCSR0B = _BV(RXEN0) | _BV(TXEN0); // enable transmision/reception | |
UCSR0C = _BV(UCSZ00) | _BV(UCSZ01); // set 8N1 | |
UCSR0B |= _BV(RXCIE0); // enable interrupt on char | |
} | |
static void putchr(char c) | |
{ | |
loop_until_bit_is_set(UCSR0A, UDRE0); // check if read op is pending | |
UDR0 = c; // write char | |
} | |
ISR(USART_RX_vect) | |
{ | |
char c; | |
c = UDR0; // read char | |
if (bit_is_clear(UCSR0A, FE0)) // check for transmission error | |
{ | |
if (c != '\n') | |
putchr(c + 1); | |
else | |
putchr('\n'); | |
} | |
} | |
int main(void) | |
{ | |
init(103); | |
sei(); | |
for (;;); | |
return (0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for publishing your code snippet. Line 12 helped me a lot!