Test USART reading

This commit is contained in:
2024-08-27 00:38:12 +02:00
parent 42792bfdf8
commit 0f5a383f14
7 changed files with 94 additions and 81 deletions

76
src/serial.c Normal file
View File

@@ -0,0 +1,76 @@
#include "common.h"
#include "serial.h"
#include <avr/io.h>
#include <stdio.h>
#define USART_BAUDRATE 9600
// Ensure closest fit for target baudrate
//#define BAUD_PRESCALE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
#define BAUD_PRESCALE ((((F_CPU / 16) + (USART_BAUDRATE / 2)) \
/ (USART_BAUDRATE)) - 1)
static char USART_Rx(void);
static void USART_Tx(char ch);
void USART_Init(void)
{
UCSRB |= BIT(RXEN) | BIT(TXEN); // Enable rx and tx circuitry
UCSRC |= BIT(URSEL) | BIT(UCSZ0) | BIT(UCSZ1); // 8-bit chars
UBRRH = (BAUD_PRESCALE >> 8); // Baud Rate upper byte
UBRRL = BAUD_PRESCALE; // Baud rate lower byte
}
void USART_Read(char **buf, int size)
{
int n = 0;
char *p = *buf;
char ch;
if ((UCSRA & BIT(RXC)) == 0) {
p = '\0';
return;
}
do {
// Discard messages exceeding
// given size limit quietly
if (n == size) {
p = '\0';
while (USART_Rx());
return;
}
ch = USART_Rx();
p[n] = ch;
n++;
} while (ch != '\0');
}
void USART_Write(const char *buf)
{
int n = 0;
while (buf[n] != '\0') {
USART_Tx(buf[n++]);
}
}
static char USART_Rx(void)
{
// Anything to read from UDR?
if ((UCSRA & BIT(RXC)) == 0)
return '\0';
return UDR;
}
static void USART_Tx(char ch)
{
// Wait until UDR can receive data
while ((UCSRA & BIT(UDRE)) == 0);
UDR = ch;
}