blob: 2cd95b4f70a77e79e2d8e20592e1df1ea1607e93 [file] [log] [blame]
Brian Silvermandf49fe32013-12-11 14:21:37 -08001#include "cape/uart_byte.h"
2#include "cape/uart_common_private.h"
3
4#include <STM32F2XX.h>
5
6#define TIMEOUT_TIM TIM7
Brian Silverman1b6fbd02013-12-12 18:08:47 -08007#define RCC_APB1ENR_TIMEOUT_TIMEN RCC_APB1ENR_TIM7EN
Brian Silvermandf49fe32013-12-11 14:21:37 -08008
9void uart_byte_configure(void) {
Brian Silverman1b6fbd02013-12-12 18:08:47 -080010 RCC->APB1ENR |= RCC_APB1ENR_TIMEOUT_TIMEN;
11
Brian Silvermanffeef3f2013-12-22 14:06:23 -080012 TIMEOUT_TIM->CR1 = 0;
Brian Silvermandf49fe32013-12-11 14:21:37 -080013}
14
15int uart_byte_receive(uint16_t timeout_count, uint16_t timeout_divider) {
16 TIMEOUT_TIM->PSC = timeout_divider;
17 TIMEOUT_TIM->EGR = TIM_EGR_UG;
18 TIMEOUT_TIM->CR1 |= TIM_CR1_CEN;
19
20 while ((UART->SR & USART_SR_RXNE) == 0) {
21 if (TIMEOUT_TIM->CNT >= timeout_count) {
22 TIMEOUT_TIM->CR1 &= ~TIM_CR1_CEN;
23 return -1;
24 }
25 }
26
Brian Silverman3aa0d542014-01-25 17:16:43 -080027 int r = UART->DR; // do it now to clear interrupts etc
28
29 if (UART->SR & USART_SR_PE) r = -2;
30 if (UART->SR & USART_SR_FE) r = -3;
31 if (UART->SR & USART_SR_NE) r = -4;
32 if (UART->SR & USART_SR_ORE) r = -5;
33
Brian Silvermandf49fe32013-12-11 14:21:37 -080034 TIMEOUT_TIM->CR1 &= ~TIM_CR1_CEN;
Brian Silverman3aa0d542014-01-25 17:16:43 -080035 return r;
Brian Silvermandf49fe32013-12-11 14:21:37 -080036}
37
38void uart_byte_send(uint8_t value) {
39 while ((UART->SR & USART_SR_TXE) == 0) {}
40 UART->DR = value;
41}