basic memory management and uart wait fix
[cortex-from-scratch] / uart.c
diff --git a/uart.c b/uart.c
index bfef4b4..a3905c4 100644 (file)
--- a/uart.c
+++ b/uart.c
@@ -6,10 +6,32 @@
 
 void uart_init() {
 
-/* To use the UARTs, the peripheral clock must be enabled by setting the UART0, UART1, or UART2
-bits in the RCGC1 register. (section 12.4: Initialization and Configuration */
+       
+       *RCC_APB2ENR = 0x4005; // enable clock to UART1, AFIO and GPIOA
+       *GPIOA_CRH = 0x444444D4; // (after enable GPIOA), on PA9&PA10 and set mode to alternative output
+       *AFIO_EVCR = 0x89; // (after enable) set event control register, output on PA, Pin 9
+
+       *USART1_CR1 = (0 << 13); // disable temporarily to set values
+
+       /* baud rate 115200,  8MHz / (16 * USARTDIV)
+        * USARTDIV = 4.34
+        * FRACTION: 16 x 0.34 = 0d5.44 0d5 -> 0x5
+        * MANTISSA: 0d4.34 0d4 -> 0x4 
+        * USART_BRR = 0x45*/
+
+       /* baud rate 2400 
+        * 
+        * 16 * 0.33 -> 0x5
+        * 208 -> 0x34 */
 
-*SYSCTRL_RCGC1 = *SYSCTRL_RCGC1 | 0x0003;
+       *USART1_BRR = (volatile uint32_t) 0x00000045;
+       
+       *USART1_CR2 = (volatile uint32_t) 0x0000; // set stop bit, default is 1 stop bit 0x00
+       // enable DMA 
+       // *USART1_CR3 = 0x0C0; 
+       /* parity = 8 bit, UART1 enabled,
+        * TX and RX enabled, interrupts enabled */
+       *USART1_CR1 = (volatile uint32_t) 0x000030AC; 
 
 /* 
  * Configure UART0:
@@ -19,33 +41,26 @@ bits in the RCGC1 register. (section 12.4: Initialization and Configuration */
        4. Write the desired serial parameters to the UARTLCRH register
        5. Enable the UART by setting the UARTEN bit in the UARTCTL register.
 */
+}
 
-/* TODO: bitrate: How fast is CPU running?*/
-
-*UART0_CTRL = 0;
-*UART0_IBRD = 27; 
-*UART0_FBRD = 9;
-*UART0_LCRH = 0x60; 
-*UART0_CTRL = 0x301;
-
-*UART1_CTRL = 0;
-*UART1_IBRD = 27; 
-*UART1_FBRD = 9;
-*UART1_LCRH = 0x60; 
-*UART1_CTRL = 0x301;
-
-
+void wait() {
+       for (int i = 0; i < 100; i++);
 }
 
 extern void uart_putc(unsigned char ch) {
        
-       if (ch == '\n') {
-               while ((*UART0_FLAG & 0x8)); // busy bit
-               *UART0_DATA = 0x0D; // return line
+       if (ch == '\n') {
+               while (*USART1_SR & 0x0C) { } // transmit data register empty and complete
+               *USART1_DR = 0x0D; // return line
        }
+
+
+       while (*USART1_SR & 0x0C) {} 
+               *USART1_DR = ch;
+
+
        
-       while ((*UART0_FLAG & 0x8)); // busy bit
-       *UART0_DATA = ch;
+       wait();
 }
 
 extern void uart_puts(unsigned char *str)
@@ -60,6 +75,7 @@ extern void uart_puts(unsigned char *str)
 }
 
 
+
 char * uart_read() {
 
        return NULL;