uart small ping pong receive, update of register functions
[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 #define RXNE ((*USART1_SR >> 5) & 0x1)
8
9 #define O_WRITE 0x01
10 #define SET 0x02
11 #define CLEAR 0x03
12
13 void * uart_handler() {
14
15         uart_puts("\n echo: ");
16         while (RXNE) {
17                 char echochar = *USART1_DR;
18         //      regw_u8(USART1_DR, echochar, 0, O_WRITE);
19         uart_putc(echochar);
20         }  
21 //for(;;);
22
23 }
24 void uart_init() {
25
26         // global interrupt setup
27 //      regw_u32(EXTI_IMR, 0x000FFFFF, 0, O_WRITE);
28 //      regw_u32(EXTI_RTSR, 0x000FFFFF, 0, O_WRITE);
29
30                 
31         regw_u32(RCC_APB2ENR, 0x4005, 0, SET);// enable clock to UART1, AFIO and GPIOA
32         
33         /* (after enable GPIOA), on PA9&PA10 and set mode
34          *  to alternative output */
35         regw_u32(GPIOA_CRH, 0x444444D4, 0, O_WRITE);
36         regw_u8(AFIO_EVCR, 0x89, 0, O_WRITE);// set event control register, output on PA, Pin 9
37
38         //disable temporarily to set values
39         regw_u8(USART1_CR1, 0x0, 13, SET);
40
41         /* baud rate 115200,  8MHz / (16 * USARTDIV)
42          * USARTDIV = 4.34
43          * FRACTION: 16 x 0.34 = 0d5.44 0d5 -> 0x5
44          * MANTISSA: 0d4.34 0d4 -> 0x4 
45          * USART_BRR = 0x45*/
46
47         regw_u32(USART1_BRR, 0x00000045, 0, O_WRITE);
48         regw_u32(USART1_CR2, 0x0000, 0, O_WRITE); //set stop bit, default is 1 stop bit 0x00
49         
50         /* parity = 8 bit, UART1 enabled,
51          * TX and RX enabled, interrupts enabled */
52         //regw_u32(USART1_CR1, 0x000030AC, 0, O_WRITE);
53         regw_u32(USART1_CR1, 0x0000302C, 0, O_WRITE);
54
55         ivt_set_gate(53, uart_handler, 0);
56         
57         *NVIC_ISER1 = (1 << 5); // Enable UART interrupt at NVIC
58 }
59
60 void wait() {
61         for (int i = 0; i < 100; i++);
62 }
63
64 extern void uart_putc(unsigned char ch) {
65         
66         if (ch == '\n') {
67                 while (*USART1_SR & 0x0C) { } // transmit data register empty and complete
68                 regw_u8(USART1_DR, 0x0D, 0, O_WRITE); // return line
69         }
70
71         while (*USART1_SR & 0x0C) {} 
72                 regw_u8(USART1_DR, ch, 0, O_WRITE);
73
74         wait();
75 }
76
77 extern void uart_puts(unsigned char *str) {
78     int i;
79     for (i = 0; i < strlen(str); i++)     {
80         uart_putc(str[i]);
81     }
82 }
83
84
85
86 char uart_read() { 
87
88         /* while (buffer not empty)
89          *      read()
90          *      uart_putc(ch) // echo
91          *              if ch = enter
92          *              process inquiry.
93          */
94         
95 }
96
97