print to uart0 [note: always printed on screen through DMA]
[cortex-from-scratch] / uart.c
1 #include <stdbool.h>
2 #include <stddef.h>
3 #include <stdint.h>
4 #include <stm32.h>
5
6 #define SYSCTRL_RCC ((volatile unsigned long *)(0x400FE060))
7 #define SYSCTRL_RIS ((volatile unsigned long *)(0x400FE050))
8 #define SYSCTRL_RCGC1 ((volatile unsigned long *)(0x400FE104))
9 #define SYSCTRL_RCGC2 ((volatile unsigned long *)(0x400FE108))
10 #define GPIOPA_AFSEL ((volatile unsigned long *)(0x40004420))
11
12 #define UART0_DATA ((volatile unsigned long *)(0x4000C000))
13 #define UART0_FLAG ((volatile unsigned long *)(0x4000C018))
14 #define UART0_IBRD ((volatile unsigned long *)(0x4000C024))
15 #define UART0_FBRD ((volatile unsigned long *)(0x4000C028))
16 #define UART0_LCRH ((volatile unsigned long *)(0x4000C02C))
17 #define UART0_CTRL ((volatile unsigned long *)(0x4000C030))
18 #define UART0_RIS ((volatile unsigned long *)(0x4000C03C))
19
20 #define UART1_DATA ((volatile unsigned long *)(0x4000D000))
21 #define UART1_FLAG ((volatile unsigned long *)(0x4000D018))
22 #define UART1_IBRD ((volatile unsigned long *)(0x4000D024))
23 #define UART1_FBRD ((volatile unsigned long *)(0x4000D028))
24 #define UART1_LCRH ((volatile unsigned long *)(0x4000D02C))
25 #define UART1_CTRL ((volatile unsigned long *)(0x4000D030))
26 #define UART1_RIS ((volatile unsigned long *)(0x4000D03C))
27
28
29 void uart_init() {
30
31 /* To use the UARTs, the peripheral clock must be enabled by setting the UART0, UART1, or UART2
32 bits in the RCGC1 register. (section 12.4: Initialization and Configuration */
33
34 *SYSCTRL_RCGC1 = *SYSCTRL_RCGC1 | 0x0003;
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 /* TODO: bitrate: How fast is CPU running?*/
46
47 *UART0_CTRL = 0;
48 *UART0_IBRD = 27; 
49 *UART0_FBRD = 9;
50 *UART0_LCRH = 0x60; 
51 *UART0_CTRL = 0x301;
52
53 *UART1_CTRL = 0;
54 *UART1_IBRD = 27; 
55 *UART1_FBRD = 9;
56 *UART1_LCRH = 0x60; 
57 *UART1_CTRL = 0x301;
58
59
60 }
61
62 extern void uart_putc(unsigned char ch) {
63         
64         if (ch == '\n') {
65                 while ((*UART0_FLAG & 0x8)); // busy bit
66                 *UART0_DATA = 0x0D; // return line
67         }
68         
69         while ((*UART0_FLAG & 0x8)); // busy bit
70         *UART0_DATA = ch;
71 }
72
73 extern void uart_puts(unsigned char *str)
74 {
75
76     int i;
77
78     for (i = 0; i < strlen(str); i++)
79     {
80         uart_putc(str[i]);
81     }
82 }
83
84
85 char * uart_read() {
86
87         return NULL;
88 }
89
90