diff --git a/src/common.h b/src/common.h index 3d70c03..fa33a1c 100644 --- a/src/common.h +++ b/src/common.h @@ -3,6 +3,8 @@ #define UNUSED(s) (void)(s) +#include +#include #include #define Sleep(ms) _delay_ms(ms) diff --git a/src/main.c b/src/main.c index 8a139f6..040659c 100644 --- a/src/main.c +++ b/src/main.c @@ -3,10 +3,19 @@ #include +#define MAX_CMDBUF 256 + int main(void) { unsigned long i; char buf[128]; + char *cmd; + + // UART command buffer + cmd = malloc(MAX_CMDBUF); + if (cmd == NULL) { + return 1; + } UART_Init(); @@ -16,6 +25,10 @@ int main(void) sprintf(buf, "[CORE] Fetching sensors #%05lu...\r\n", i); UART_Write(buf); + UART_Read(&cmd, MAX_CMDBUF); + sprintf(buf, "[CORE] Checking cmdbuf=\"%s\"\r\n", cmd); + UART_Write(buf); + Sleep(3000); } diff --git a/src/uart.c b/src/uart.c index e2f4f38..cdde2cc 100644 --- a/src/uart.c +++ b/src/uart.c @@ -15,14 +15,27 @@ void UART_Init(void) UBRRL = BAUD_PRESCALE; } -void UART_Read(char **buf) -{ - // do { - // p[n++] = UART_Rx(); - // } while (p[n] != '\n'); - UNUSED(UART_Rx); - UNUSED(buf); +void UART_Read(char **buf, int size) +{ + int n = 0; + char *p = *buf; + char ch; + + do { + // Discard messages exceeding + // given size limit quietly + if (n == size) { + p = '\0'; + while (UART_Rx()); + return; + } + + ch = UART_Rx(); + p[n] = ch; + n++; + + } while (ch != '\0'); } void UART_Write(const char *buf) @@ -34,9 +47,16 @@ void UART_Write(const char *buf) } } +static bool UART_IsReceiving(void) +{ + return ((UCSRA & (1 << RXC)) ? true : false); +} + static char UART_Rx(void) { - while ((UCSRA & (1 << RXC)) == 0); + if (!UART_IsReceiving() || UDR == '\n') + return '\0'; + return UDR; } diff --git a/src/uart.h b/src/uart.h index ae85b9f..26edfe4 100644 --- a/src/uart.h +++ b/src/uart.h @@ -2,7 +2,7 @@ #define MAD_UART_H void UART_Init(void); -void UART_Read(char **buf); +void UART_Read(char **buf, int size); void UART_Write(const char *buf); #endif // MAD_UART_H