Write a UART transmit routine (polled and interrupt-driven).
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
typedef struct { volatile uint32_t SR, DR, BRR, CR1; } uart_t; /* simplified register map */
#define UART_SR_TXE (1u << 7) /* transmit data register empty */
#define UART_SR_TC (1u << 6) /* transmission complete */
#define UART_CR1_TXEIE (1u << 7) /* TXE interrupt enable */
/* polled, with a timeout so a broken UART cannot hang the system */
int uart_write_polled(uart_t *u, const uint8_t *buf, size_t len, uint32_t timeout)
{
for (size_t i = 0; i < len; i++) {
uint32_t t = timeout;
while (!(u->SR & UART_SR_TXE)) if (--t == 0) return -1;
u->DR = buf[i];
}
return 0;
}
/* interrupt-driven: application fills a ring buffer, the ISR drains it */
#define TXQ 256u
static volatile uint8_t txq[TXQ];
static volatile uint16_t tx_head, tx_tail; /* head written by app, tail by ISR */
static uart_t *g_uart;
bool uart_putc(uint8_t c)
{
uint16_t next = (uint16_t)((tx_head + 1u) % TXQ);
if (next == tx_tail) return false; /* full: caller decides to wait or drop */
txq[tx_head] = c;
tx_head = next;
g_uart->CR1 |= UART_CR1_TXEIE; /* (re)enable TXE interrupt; in real code use an
atomic set or a critical section for this RMW */
return true;
}
void UART_IRQHandler(void)
{
if ((g_uart->SR & UART_SR_TXE) && (g_uart->CR1 & UART_CR1_TXEIE)) {
if (tx_tail != tx_head) {
g_uart->DR = txq[tx_tail];
tx_tail = (uint16_t)((tx_tail + 1u) % TXQ);
} else {
g_uart->CR1 &= ~UART_CR1_TXEIE; /* nothing left: stop TXE interrupts */
}
}
}
Points: wait for TXE before writing DR; wait for TC before disabling the UART or turning an RS-485 driver around (the last byte is still shifting out when TXE is set); always use timeouts in polled code; in the interrupt version, disable the TXE interrupt when the buffer empties, otherwise it fires continuously. For large transfers, use DMA.