Implement basic UART reading

This commit is contained in:
2024-08-26 19:01:40 +02:00
parent 4ce77c09b1
commit 42792bfdf8
4 changed files with 44 additions and 9 deletions

View File

@@ -3,6 +3,8 @@
#define UNUSED(s) (void)(s)
#include <stdlib.h>
#include <stdbool.h>
#include <util/delay.h>
#define Sleep(ms) _delay_ms(ms)

View File

@@ -3,10 +3,19 @@
#include <stdio.h>
#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);
}

View File

@@ -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;
}

View File

@@ -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