Brian Silverman | aa9183a | 2013-12-08 10:33:47 -0800 | [diff] [blame] | 1 | #include "cape/uart_common.h" |
| 2 | #include "cape/uart_common_private.h" |
| 3 | |
Brian Silverman | 1b6fbd0 | 2013-12-12 18:08:47 -0800 | [diff] [blame] | 4 | #include "cape/util.h" |
| 5 | |
Brian Silverman | ed03006 | 2013-12-20 21:03:47 -0800 | [diff] [blame] | 6 | #define RCC_APB2ENR_UARTEN RCC_APB2ENR_USART1EN |
| 7 | |
Brian Silverman | aa9183a | 2013-12-08 10:33:47 -0800 | [diff] [blame] | 8 | #define FPCLK 60000000 |
| 9 | |
Brian Silverman | 1b6fbd0 | 2013-12-12 18:08:47 -0800 | [diff] [blame] | 10 | // The UART is on PA9 and PA10. |
Brian Silverman | aa9183a | 2013-12-08 10:33:47 -0800 | [diff] [blame] | 11 | void uart_common_configure(int baud) { |
Brian Silverman | 1b6fbd0 | 2013-12-12 18:08:47 -0800 | [diff] [blame] | 12 | gpio_setup_alt(GPIOA, 9, 7); |
| 13 | gpio_setup_alt(GPIOA, 10, 7); |
Brian Silverman | ed03006 | 2013-12-20 21:03:47 -0800 | [diff] [blame] | 14 | RCC->APB2ENR |= RCC_APB2ENR_UARTEN; |
Brian Silverman | 1b6fbd0 | 2013-12-12 18:08:47 -0800 | [diff] [blame] | 15 | |
Brian Silverman | 3aa0d54 | 2014-01-25 17:16:43 -0800 | [diff] [blame] | 16 | UART->CR1 = |
| 17 | //USART_CR1_M /* 9th bit for the parity */ | |
| 18 | //USART_CR1_PCE /* enable parity (even by default) */ | |
| 19 | //USART_CR1_OVER8 /* support going faster */ | |
| 20 | 0; |
| 21 | |
Brian Silverman | ed03006 | 2013-12-20 21:03:47 -0800 | [diff] [blame] | 22 | // baud = 60MHz / kMultiplier * (whole_part + fraction / kMultiplier)) |
| 23 | static const int kMultiplier = 16 /* 8 * (2 - OVER8) */; |
| 24 | // The divisor of FPCLK that we want (*2). |
| 25 | int divisor = FPCLK * 2 / baud; |
| 26 | // The whole-number part of the divisor. |
| 27 | int mantissa = divisor / kMultiplier / 2; |
| 28 | // The fractional part of the divisor (*2). |
| 29 | int fraction = divisor % (kMultiplier * 2); |
| 30 | UART->BRR = (mantissa << 4) | ((fraction + 1) / 2); |
Brian Silverman | 3aa0d54 | 2014-01-25 17:16:43 -0800 | [diff] [blame] | 31 | |
Brian Silverman | ed03006 | 2013-12-20 21:03:47 -0800 | [diff] [blame] | 32 | UART->CR1 |= USART_CR1_UE; // enable it |
Brian Silverman | aa9183a | 2013-12-08 10:33:47 -0800 | [diff] [blame] | 33 | } |