3 #include <avr/interrupt.h>
5 #define UART_UBRR_CALC(BAUD_,FREQ_) ((FREQ_)/((BAUD_)*16L)-1)
7 static volatile char read[RINGBUFFER_LEN];
8 static volatile char *in_read_ptr;
9 static volatile char *out_read_ptr;
12 // update read from uart
13 if (UCSRA & (1<<RXC)) {
16 if (in_read_ptr < read + RINGBUFFER_LEN - 1) in_read_ptr++;
17 else in_read_ptr = (char *)read;
22 void setup_uart(unsigned int rate) {
23 UCSRB |= (1<<TXEN) | (1<<RXEN); // UART TX & RX
24 UCSRB |= (1<<RXCIE); // RX Interrupt
25 UCSRC |= (3<<UCSZ0); // Asynchron 8N1
27 UBRRH = (uint8_t)(UART_UBRR_CALC(rate, F_CPU) >> 8);
28 UBRRL = (uint8_t)UART_UBRR_CALC(rate, F_CPU);
30 in_read_ptr = out_read_ptr = read;
34 void uart_putc(char *c) {
35 while (!(UCSRA & (1<<UDRE)));
40 int uart_putchar(char c, FILE *stream)
47 void uart_puts(char *s) {
50 for (c = s; *c != '\0'; c++)
55 int uart_getchar(FILE *stream)
62 while (!(UCSRA & (1<<RXC)));
67 void uart_setup_stdout() {
68 fdevopen(uart_putchar, uart_getchar);
72 void uart_stream_update(ringbuffer_t *buffer) {
73 // update write to uart
74 if (buffer->out_write_ptr != buffer->in_write_ptr) {
75 if (UCSRA & (1<<UDRE)) {
76 UDR = *buffer->out_write_ptr;
77 if (buffer->out_write_ptr < buffer->write + RINGBUFFER_LEN - 1) buffer->out_write_ptr++;
78 else buffer->out_write_ptr = buffer->write;
82 // update read from uart
83 if (in_read_ptr != out_read_ptr) {
84 *buffer->in_read_ptr = *out_read_ptr;
86 // update newline chars
87 if (buffer->block_read == *buffer->in_read_ptr) buffer->newlines++;
89 if (buffer->in_read_ptr < buffer->read + RINGBUFFER_LEN - 1) buffer->in_read_ptr++;
90 else buffer->in_read_ptr = buffer->read;
93 if (out_read_ptr < read + RINGBUFFER_LEN - 1) out_read_ptr++;
94 else out_read_ptr = read;