]> wirehaze git hosting - stm32f411ceu6.git/blob - sys/dev/uart.c

wirehaze git hosting

restructure
[stm32f411ceu6.git] / sys / dev / uart.c
1 #include <uart.h>
2 #include <stm32f411.h>
3
4 /* Wait for data to be transferred into the shift register. */
5 static void
6 busywait_txe (void)
7 {
8 /* TXE: Transmit data register empty */
9 while (!(*USART1_SR & (1u << 7))); /* 0: Data is not transferred to the shift
10 register */
11 }
12
13 /* Wait for transmission of the last frame. */
14 static void
15 busywait_tc (void)
16 {
17 /* TC: Transmission complete */
18 while (!(*USART1_SR & (1u << 6))); /* 0: Transmission is not complete */
19 }
20
21 static void
22 tx (char c)
23 {
24 /* DR[8:0]: Data value */
25 *USART1_DR = c;
26 }
27
28 void
29 uart_init (void)
30 {
31 /* GPIOAEN: IO port A clock enable */
32 *RCC_AHB1ENR |= (1u); /* 1: IO port A clock enabled */
33
34 /* MODERy[1:0]: Port x configuration bits (y = 0..15) */
35 *GPIOA_MODER &= ~(0b1111u << 18); /* Clear PA9 and PA10 bits */
36 *GPIOA_MODER |= (0b1010u << 18); /* 10: Alternate function mode */
37
38 /* AFRHy: Alternate function selection for port x bit y (y = 8..15) */
39 *GPIOA_AFRH &= ~(0b11111111u << 4); /* Clear PA9 and PA10 bits */
40 *GPIOA_AFRH |= (0b01110111u << 4); /* 0111: AF7 */
41
42 /* PA9: USART1_TX
43 * PA10: USART1_RX */
44
45 /* USART1EN: USART1 clock enable */
46 *RCC_APB2ENR |= (1u << 4); /* 1: USART1 clock enabled */
47
48 /* UE: USART enable */
49 *USART1_CR1 |= (1u << 13); /* 1: USART enable */
50
51 /* M: Word length */
52 *USART1_CR1 &= ~(1u << 12); /* 0: 1 Start bit, 8 Data bits, n Stop bit */
53
54 /* PCE: Parity control enable */
55 *USART1_CR1 &= ~(1u << 10); /* 0: Parity control disabled */
56
57 /* STOP: STOP bits */
58 *USART1_CR2 &= ~(0b11u << 12); /* 00: 1 Stop bit */
59
60 /* Clock frequency: 25MHz
61 * Desired baud rate: 1.2 KBps */
62
63 /* Mantissa and fraction (/16) */
64 *USART1_BRR = (1302u << 4) | 1u; /* USARTDIV = 1302.0625 */
65
66 /* TE: Transmitter enable */
67 *USART1_CR1 |= (1u << 3); /* 1: Transmitter is enabled */
68 }
69
70 void
71 kputs_busytc (const char *str)
72 {
73 while (*str)
74 {
75 busywait_txe ();
76 tx (*(str++));
77 }
78
79 busywait_tc ();
80 }