123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- #include <avr/io.h>
- #include <avr/interrupt.h>
- #include "uart.h"
- #define RX_BUFFER_SIZE 64
- #define TX_BUFFER_SIZE 40
- static volatile uint8_t tx_buffer[TX_BUFFER_SIZE];
- static volatile uint8_t tx_buffer_head;
- static volatile uint8_t tx_buffer_tail;
- static volatile uint8_t rx_buffer[RX_BUFFER_SIZE];
- static volatile uint8_t rx_buffer_head;
- static volatile uint8_t rx_buffer_tail;
- void uart_init(uint32_t baud)
- {
- cli();
- UBRR0 = (F_CPU / 4 / baud - 1) / 2;
- UCSR0A = (1<<U2X0);
- UCSR0B = (1<<RXEN0) | (1<<TXEN0) | (1<<RXCIE0);
- UCSR0C = (1<<UCSZ01) | (1<<UCSZ00);
- tx_buffer_head = tx_buffer_tail = 0;
- rx_buffer_head = rx_buffer_tail = 0;
- sei();
- }
- void uart_putchar(uint8_t c)
- {
- uint8_t i;
- i = tx_buffer_head + 1;
- if (i >= TX_BUFFER_SIZE) i = 0;
- while (tx_buffer_tail == i) ;
-
- tx_buffer[i] = c;
- tx_buffer_head = i;
- UCSR0B = (1<<RXEN0) | (1<<TXEN0) | (1<<RXCIE0) | (1<<UDRIE0);
-
- }
- uint8_t uart_getchar(void)
- {
- uint8_t c, i;
- while (rx_buffer_head == rx_buffer_tail) ;
- i = rx_buffer_tail + 1;
- if (i >= RX_BUFFER_SIZE) i = 0;
- c = rx_buffer[i];
- rx_buffer_tail = i;
- return c;
- }
- uint8_t uart_available(void)
- {
- uint8_t head, tail;
- head = rx_buffer_head;
- tail = rx_buffer_tail;
- if (head >= tail) return head - tail;
- return RX_BUFFER_SIZE + head - tail;
- }
- ISR(USART_UDRE_vect)
- {
- uint8_t i;
- if (tx_buffer_head == tx_buffer_tail) {
-
- UCSR0B = (1<<RXEN0) | (1<<TXEN0) | (1<<RXCIE0);
- } else {
- i = tx_buffer_tail + 1;
- if (i >= TX_BUFFER_SIZE) i = 0;
- UDR0 = tx_buffer[i];
- tx_buffer_tail = i;
- }
- }
- ISR(USART_RX_vect)
- {
- uint8_t c, i;
- c = UDR0;
- i = rx_buffer_head + 1;
- if (i >= RX_BUFFER_SIZE) i = 0;
- if (i != rx_buffer_tail) {
- rx_buffer[i] = c;
- rx_buffer_head = i;
- }
- }
|