2014-12-02 17:10:06 -07:00
|
|
|
#include "Serial.h"
|
|
|
|
#include <util/setbaud.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <string.h>
|
|
|
|
|
|
|
|
void serial_init(Serial *serial) {
|
|
|
|
memset(serial, 0, sizeof(*serial));
|
2019-01-08 12:56:58 -07:00
|
|
|
memset(serialBuf, 0, sizeof(serialBuf));
|
|
|
|
|
2014-12-02 17:10:06 -07:00
|
|
|
UBRR0H = UBRRH_VALUE;
|
|
|
|
UBRR0L = UBRRL_VALUE;
|
|
|
|
|
|
|
|
#if USE_2X
|
|
|
|
UCSR0A |= _BV(U2X0);
|
|
|
|
#else
|
|
|
|
UCSR0A &= ~(_BV(U2X0));
|
|
|
|
#endif
|
|
|
|
|
2019-01-08 12:56:58 -07:00
|
|
|
// Set to 8-bit data, enable RX and TX, enable receive interrupt
|
2014-12-02 17:10:06 -07:00
|
|
|
UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);
|
2019-01-08 12:56:58 -07:00
|
|
|
UCSR0B = _BV(RXEN0) | _BV(TXEN0) | _BV(RXCIE0);
|
2014-12-02 17:10:06 -07:00
|
|
|
|
|
|
|
FILE uart0_fd = FDEV_SETUP_STREAM(uart0_putchar, uart0_getchar, _FDEV_SETUP_RW);
|
2019-01-08 05:19:58 -07:00
|
|
|
|
2014-12-02 17:10:06 -07:00
|
|
|
serial->uart0 = uart0_fd;
|
2019-01-08 12:56:58 -07:00
|
|
|
|
|
|
|
fifo_init(&serialFIFO, serialBuf, sizeof(serialBuf));
|
2014-12-02 17:10:06 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
bool serial_available(uint8_t index) {
|
|
|
|
if (index == 0) {
|
|
|
|
if (UCSR0A & _BV(RXC0)) return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2018-04-24 06:38:48 -06:00
|
|
|
int uart0_putchar(char c, FILE *stream) {
|
2019-01-12 07:12:51 -07:00
|
|
|
LED_COM_ON();
|
2014-12-02 17:10:06 -07:00
|
|
|
loop_until_bit_is_set(UCSR0A, UDRE0);
|
|
|
|
UDR0 = c;
|
2018-04-24 06:38:48 -06:00
|
|
|
return 1;
|
2014-12-02 17:10:06 -07:00
|
|
|
}
|
|
|
|
|
2018-04-24 06:38:48 -06:00
|
|
|
int uart0_getchar(FILE *stream) {
|
2014-12-02 17:10:06 -07:00
|
|
|
loop_until_bit_is_set(UCSR0A, RXC0);
|
|
|
|
return UDR0;
|
|
|
|
}
|
|
|
|
|
|
|
|
char uart0_getchar_nowait(void) {
|
|
|
|
if (!(UCSR0A & _BV(RXC0))) return EOF;
|
|
|
|
return UDR0;
|
2019-01-08 12:56:58 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
ISR(USART0_RX_vect) {
|
|
|
|
if (serial_available(0)) {
|
2019-01-12 07:12:51 -07:00
|
|
|
LED_COM_ON();
|
2019-01-08 12:56:58 -07:00
|
|
|
char c = uart0_getchar_nowait();
|
|
|
|
fifo_push(&serialFIFO, c);
|
|
|
|
}
|
2014-12-02 17:10:06 -07:00
|
|
|
}
|