5 #warning "compiled for 1mhz internal rc osc. serial comms won't work"
12 #include <avr/interrupt.h>
13 #include <util/delay.h>
14 #include <avr/power.h>
16 static int uart_send_char(char c, FILE *fp);
17 static int uart_get_char(FILE *fp);
20 #define BUF_IDX_MASK (BUF_SZ - 1)
21 #define NEXT_IDX(x) (((x) + 1) & BUF_IDX_MASK)
22 static char outbuf[BUF_SZ];
23 static volatile unsigned char out_rd, out_wr;
24 static char inbuf[BUF_SZ];
25 static volatile unsigned char in_rd, in_wr;
27 static FILE std_stream = FDEV_SETUP_STREAM(uart_send_char, uart_get_char, _FDEV_SETUP_RW);
31 void init_serial(long baud)
33 unsigned int ubrr_val = F_CPU / 16 / baud - 1;
35 power_usart0_enable();
37 /* set baud generator timer reset value */
38 UBRR0H = (unsigned char)(ubrr_val >> 8);
39 UBRR0L = (unsigned char)ubrr_val;
41 /* enable rx/tx and recv interrupt */
42 UCSR0B = (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0);
43 /* set frame format: 8n1 */
46 stdin = stdout = stderr = &std_stream;
51 return in_wr != in_rd;
54 static int uart_send_char(char c, FILE *fp)
58 while((UCSR0A & (1 << UDRE0)) == 0);
59 UDR0 = (unsigned char)c;
61 next = NEXT_IDX(out_wr);
62 while(next == out_rd);
67 /* enable the Tx data register empty interrupt */
68 UCSR0B |= 1 << UDRIE0;
73 static int uart_get_char(FILE *fp)
77 while(in_rd == in_wr);
80 in_rd = NEXT_IDX(in_rd);
89 in_wr = NEXT_IDX(in_wr);
92 /* USART Tx data register empty (can send more data) */
95 if(out_rd != out_wr) {
96 UDR0 = outbuf[out_rd];
97 out_rd = NEXT_IDX(out_rd);
99 /* no more data to send for now, disable the interrupt */
100 UCSR0B &= ~(1 << UDRIE0);