From 75b5488b8d217c1d602bc4646e99e9af053107a8 Mon Sep 17 00:00:00 2001 From: Paul Mathieu Date: Sat, 13 Mar 2021 15:49:28 -0800 Subject: [PATCH] uart: upgrade C api --- uart/echo.c | 6 ++++-- uart/ledctrl.c | 4 +++- uart/uart.c | 20 ++++++++++---------- uart/uart.h | 17 ++++++++++------- 4 files changed, 27 insertions(+), 20 deletions(-) diff --git a/uart/echo.c b/uart/echo.c index 4d78baf..9cfb9b3 100644 --- a/uart/echo.c +++ b/uart/echo.c @@ -1,9 +1,11 @@ #include "uart.h" +#define uart0 ((struct uart*)0xc010) + int main() { while (1) { - char c = uart_read(); - uart_write(c); + char c = uart_read(uart0); + uart_write(uart0, c); } // never returns diff --git a/uart/ledctrl.c b/uart/ledctrl.c index 38fdddd..c5c49fb 100644 --- a/uart/ledctrl.c +++ b/uart/ledctrl.c @@ -1,13 +1,15 @@ #include "led.h" #include "uart.h" +#define uart0 ((struct uart*)0xc010) + int main() { int c; int led = 0; while (1) { led_write(1 << led); - c = uart_read(); + c = uart_read(uart0); if (c == 'a') { led++; diff --git a/uart/uart.c b/uart/uart.c index debb0b7..098d8de 100644 --- a/uart/uart.c +++ b/uart/uart.c @@ -1,23 +1,23 @@ #include "uart.h" -int uart_rx_available() { - return (*UART_STATUS & UART_STATUS_RXNE_msk) != 0; +int uart_rx_available(struct uart* uart) { + return uart->flags & UART_STATUS_RXNE_msk != 0; } -int uart_tx_available() { - return (*UART_STATUS & UART_STATUS_TXE_msk) != 0; +int uart_tx_available(struct uart* uart) { + return uart->flags & UART_STATUS_TXE_msk != 0; } -void uart_write(const char c) { - while (!uart_tx_available()) { +void uart_write(struct uart* uart, const char c) { + while (!uart_tx_available(uart)) { } - *UART_DATA = c; + uart->data = c; } -char uart_read() { - while (!uart_rx_available()) { +char uart_read(struct uart* uart) { + while (!uart_rx_available(uart)) { } - return *UART_DATA; + return uart->data; } diff --git a/uart/uart.h b/uart/uart.h index 726691d..e5266af 100644 --- a/uart/uart.h +++ b/uart/uart.h @@ -1,13 +1,16 @@ -#define UART_BASE 0xc010 -#define UART_DATA ((volatile char*) (UART_BASE + 0x00)) -#define UART_STATUS ((volatile char*) (UART_BASE + 0x02)) +#pragma once #define UART_STATUS_RXNE_pos 1 #define UART_STATUS_RXNE_msk (1 << UART_STATUS_RXNE_pos) #define UART_STATUS_TXE_pos 0 #define UART_STATUS_TXE_msk (1 << UART_STATUS_TXE_pos) -int uart_rx_available(); -int uart_tx_available(); -void uart_write(const char c); -char uart_read(); +struct uart { + volatile uint8_t data; + volatile uint16_t flags; +}; + +int uart_rx_available(struct uart* uart); +int uart_tx_available(struct uart* uart); +void uart_write(struct uart* uart, const char c); +char uart_read(struct uart* uart);