Last active
March 10, 2020 15:30
-
-
Save tokolist/6675583 to your computer and use it in GitHub Desktop.
Simple AVR UART library
This file contains hidden or 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 "uart.h" | |
#include <avr/io.h> | |
unsigned int uart_calc_ubrr(unsigned long fosc, unsigned long baud) | |
{ | |
unsigned int ubrr; | |
unsigned long div, rem; | |
div = 16 * baud; | |
rem = fosc / div; | |
ubrr = (fosc / div) - 1; | |
if(rem >= div / 2) | |
{ | |
ubrr++; | |
} | |
return ubrr; | |
} | |
void uart_init(unsigned int ubrr) | |
{ | |
UBRRH = (unsigned char)(ubrr>>8); | |
UBRRL = (unsigned char)ubrr; | |
UCSRA = 0; | |
UCSRB = (1<<RXEN) | (1<<TXEN); | |
UCSRC = (1<<URSEL) | (1<<UCSZ0) | (1<<UCSZ1); | |
} | |
void uart_send_char(unsigned char c) | |
{ | |
while(!(UCSRA & (1<<UDRE))); | |
UDR = c; | |
} | |
bool uart_available() | |
{ | |
return UCSRA & (1<<RXC); | |
} | |
unsigned char uart_get_char() | |
{ | |
while(!uart_available()); | |
return UDR; | |
} | |
void uart_send_string(unsigned char s[]) | |
{ | |
for(int i=0; s[i]!=0; i++) | |
{ | |
uart_send_char(s[i]); | |
} | |
} | |
bool uart_get_string(unsigned char s[], unsigned char endc) | |
{ | |
uint8_t len; | |
for(len=0; s[len]!=endc; len++); | |
unsigned char c = uart_get_char(); | |
if(c != endc) | |
{ | |
s[len] = c; | |
s[len+1] = endc; | |
return false; | |
} | |
return true; | |
} |
This file contains hidden or 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
#ifndef UART_H_ | |
#define UART_H_ | |
unsigned int uart_calc_ubrr(unsigned long fosc, unsigned long baud = 9600); | |
void uart_init(unsigned int ubrr); | |
void uart_send_char(unsigned char c); | |
bool uart_available(); | |
unsigned char uart_get_char(); | |
void uart_send_string(unsigned char s[]); | |
bool uart_get_string(unsigned char s[], unsigned char endc = '\0'); | |
#endif /* UART_H_ */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment