29 if (interface == NULL)
30 return (
UART_t){.interface = NULL};
33 UART_t uart = {.interface = interface};
35 uart.setBaud = UART_setBaud;
41 uart.interface = interface;
67 USART_TypeDef *
interface = uart->interface;
71 interface->CR1 &= *(uint16_t *)config & ~UART_CR1_RESERVED;
72 interface->CR1 |= *(uint16_t *)config & ~UART_CR1_RESERVED;
75 UART_setBaud(uart, baud);
82void UART_setBaud(
UART_t *uart, uint32_t baud) {
83 USART_TypeDef *
interface = uart->interface;
86 while ((interface->SR & USART_SR_TXE) == 0 && !(interface->SR & USART_SR_TC));
87 interface->CR1 &= ~USART_CR1_UE;
88 while ((interface->SR & USART_SR_RXNE) == 1) {
89 (void)(interface->DR & 0xFF);
93 uint32_t sysclk = HSE_USED ? SYSCLK_HSE : SYSCLK_HSI;
94 uint8_t hpre = AHBPresc[((RCC->CFGR & RCC_CFGR_HPRE) >> RCC_CFGR_HPRE_Pos)];
98 if (interface == USART1 || interface == USART6) {
99 ppre = APBPresc[((RCC->CFGR & RCC_CFGR_PPRE2) >> RCC_CFGR_PPRE2_Pos)];
101 ppre = APBPresc[((RCC->CFGR & RCC_CFGR_PPRE1) >> RCC_CFGR_PPRE1_Pos)];
105 uint32_t pclk = sysclk / hpre / ppre;
107 uint16_t usartDiv = ((pclk / baud) * (1 + uart->config.OVER8));
108 if (uart->config.OVER8 && (usartDiv & 0x08)) {
112 interface->BRR &= 0xFFFF0000;
113 interface->BRR |= usartDiv;
115 interface->CR1 |= USART_CR1_UE;
128 USART_TypeDef *
interface = uart->interface;
129 while ((interface->SR & USART_SR_TXE) == 0);
130 interface->DR = data;
131 while ((interface->SR & USART_SR_TC) == 0);
145 for (
int i = 0; i < length; i++)
161 while (data[i] !=
'\0')
190 USART_TypeDef *
interface = uart->interface;
191 while ((interface->SR & USART_SR_RXNE) == 0);
192 return (uint8_t)(interface->DR & 0xFF);
209 if (config == NULL) {
210 config = &UART_CONFIG_DEFAULT;
214 uart->config = *config;
217 _UART_init(uart, uart->baud, config);
void UART_send(UART_t *, uint8_t data)
Sends a single byte of data over the UART interface.
void UART_updateConfig(UART_t *uart, UART_Config *config)
Update UART peripheral configuration.
void UART_sendBytes(UART_t *, uint8_t *data, int length)
Sends an array of bytes over the UART interface.
uint8_t UART_receive(UART_t *)
Receives a single byte of data from the UART interface.
UART_t UART_init(USART_TypeDef *interface, uint32_t baud, UART_Config *config)
Initialiser for a UART device interface.
void UART_print(UART_t *, char *data)
Sends a null terminated string over the UART interface.
void UART_println(UART_t *, char *data)
Sends a null terminated string over the UART interface. Terminates with a line feed control character...
Struct definition for UART interface.