Test USART reading
This commit is contained in:
76
src/serial.c
Normal file
76
src/serial.c
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user