a3905c4e0cd4f0e1eb1533a16baf02ee9d1cc41b
[cortex-from-scratch] / uart.c
1 #include <stdbool.h>
2 #include <stddef.h>
3 #include <stdint.h>
4 #include <stm32.h>
5 #include <mmap.h>
6
7 void uart_init() {
8
9         
10         *RCC_APB2ENR = 0x4005; // enable clock to UART1, AFIO and GPIOA
11         *GPIOA_CRH = 0x444444D4; // (after enable GPIOA), on PA9&PA10 and set mode to alternative output
12         *AFIO_EVCR = 0x89; // (after enable) set event control register, output on PA, Pin 9
13
14         *USART1_CR1 = (0 << 13); // disable temporarily to set values
15
16         /* baud rate 115200,  8MHz / (16 * USARTDIV)
17          * USARTDIV = 4.34
18          * FRACTION: 16 x 0.34 = 0d5.44 0d5 -> 0x5
19          * MANTISSA: 0d4.34 0d4 -> 0x4 
20          * USART_BRR = 0x45*/
21
22         /* baud rate 2400 
23          * 
24          * 16 * 0.33 -> 0x5
25          * 208 -> 0x34 */
26
27         *USART1_BRR = (volatile uint32_t) 0x00000045;
28         
29         *USART1_CR2 = (volatile uint32_t) 0x0000; // set stop bit, default is 1 stop bit 0x00
30         // enable DMA 
31         // *USART1_CR3 = 0x0C0; 
32         /* parity = 8 bit, UART1 enabled,
33          * TX and RX enabled, interrupts enabled */
34         *USART1_CR1 = (volatile uint32_t) 0x000030AC; 
35
36 /* 
37  * Configure UART0:
38         1. Disable the UART by clearing the UARTEN bit in the UARTCTL register.
39         2. Write the integer portion of the BRD to the UARTIBRD register.
40         3. Write the fractional portion of the BRD to the UARTFBRD register.
41         4. Write the desired serial parameters to the UARTLCRH register
42         5. Enable the UART by setting the UARTEN bit in the UARTCTL register.
43 */
44 }
45
46 void wait() {
47         for (int i = 0; i < 100; i++);
48 }
49
50 extern void uart_putc(unsigned char ch) {
51         
52         if (ch == '\n') {
53                 while (*USART1_SR & 0x0C) { } // transmit data register empty and complete
54                 *USART1_DR = 0x0D; // return line
55         }
56
57
58         while (*USART1_SR & 0x0C) {} 
59                 *USART1_DR = ch;
60
61
62         
63         wait();
64 }
65
66 extern void uart_puts(unsigned char *str)
67 {
68
69     int i;
70
71     for (i = 0; i < strlen(str); i++)
72     {
73         uart_putc(str[i]);
74     }
75 }
76
77
78
79 char * uart_read() {
80
81         return NULL;
82 }
83
84