aboutsummaryrefslogtreecommitdiff
path: root/03-refactor/src/main.c
blob: 97449b25f1c4d4d2bb36203c2058ce0708b1de4e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103

#include "clock.h"
#include "delay.h"
#include "gpio.h"
#include "spin.h"
#include "usart.h"
#include "sio.h"

void unhandled_isr_2();
void init();

int in_the_data;
volatile uint32_t delay_amt = 20000000 / 4;

int enable_usart1(uint32_t baud_rate)
{
  /* Enable the GPIO bus. */
  __IO gpio_port_t* port_b = enable_gpio(GPIO_PORT_B);

  /* Enable the USART clock. */
  RCC.apb2en_r |= BIT(14);

  /* == Configure the IO Pins. == */

  /* GPIO D5 (Port B pin 6) is USART1 Tx,
   * GPIO D6 (Port B pin 7) is USART1 Rx. */
  set_gpio_pin_mode(port_b, PIN_6, MODE_ALTERNATE);
  set_gpio_pin_mode(port_b, PIN_7, MODE_ALTERNATE);

  /* Set the GPIO pins to use the USART alternate function. */
  set_gpio_alternate_function(port_b, PIN_6, AFN_7);
  set_gpio_alternate_function(port_b, PIN_7, AFN_7);

  RCC.apb2rst_r &= ~BIT(14); /* De-assert reset of USART1 */

  uint32_t baud_rate_div = 80000000 / baud_rate;
  USART1.c1.r = 0;
  USART1.c2.r = 0;
  USART1.c3.r = 0;
  USART1.br.v = baud_rate_div;

  USART1.c1.r |= BIT(3) | BIT(2);
  USART1.c1.r |= BIT(0);

  /* Enable the transmitter and the receiver. */
  usart_set_enabled(&USART1, USART_ENABLE_TX);
  asm volatile(" cpsie i ");
}

void dwn() {
  int val = 19;

  while (val > 1) {
    usart_printf(&USART2, "Value: %2d\r\n", val);
    if ((val & 1) == 0) {
      val /= 2;
    } else {
      val = val * 3 + 1;
    }
  }
  usart_printf(&USART2, "Value: %2d\r\n", val);
}

/* Main function. This gets executed from the interrupt vector defined above. */
int main()
{
  /* Enable the GPIO port B. */
  // __IO gpio_port_t* port_b = enable_gpio(GPIO_PORT_B);
  // gpio_output_pin_t pin3 = set_gpio_pin_output(port_b, PIN_3);
  // gpio_output_pin_t pin1 = set_gpio_pin_output(port_b, PIN_1);

  /* Enable a higher clock frequency. */
  set_system_clock_MHz(80);

  enable_usart2(115200);
  int on_the_stack;

  USART2.c1.tcie = 1;
  USART2.c1.txeie = 1;

  // pin_on(pin3);
  if (is_usart2_enabled()) {
    dwn();
    usart_printf(&USART2, "Hello, %d!\r\n", -15);
    usart_printf(&USART2, "Hello, %022x\r\n", 0xeadbeef);
    usart_printf(&USART2, "on_the_stack: %08X\r\n", (unsigned) &on_the_stack);

    int i;

    printf("isr-2: %08x\r\n", (unsigned int)(void *) unhandled_isr_2);
    printf("init: %08x\r\n", (unsigned int)(void *) init);
    for (i = 0; i < 20; ++ i) {
      printf("isr %d: %08x\r\n", i, *(unsigned int*)(0x08000000 + i * 4));
    }
  }

  // usart_printf(&USART2, "that_thing: %d\n", *(unsigned*)(0x0));
  // for(;;);
}

void do_thing(void(*fn)()) {
  fn();
}