3 #include <libopencm3/cm3/cortex.h>
4 #include <libopencm3/cm3/nvic.h>
5 #include <libopencm3/cm3/scb.h>
6 #include <libopencm3/cm3/systick.h>
7 #include <libopencm3/stm32/rcc.h>
8 #include <libopencm3/stm32/gpio.h>
9 #include <libopencm3/stm32/usart.h>
11 static void clock_setup(void)
13 rcc_clock_setup_in_hse_8mhz_out_72mhz();
15 rcc_periph_clock_enable(RCC_GPIOA);
16 rcc_periph_clock_enable(RCC_GPIOB);
17 rcc_periph_clock_enable(RCC_GPIOC);
18 rcc_periph_clock_enable(RCC_USART1);
19 rcc_periph_clock_enable(RCC_USART3);
21 rcc_periph_reset_pulse(RST_GPIOA);
22 rcc_periph_reset_pulse(RST_GPIOB);
23 rcc_periph_reset_pulse(RST_GPIOC);
24 rcc_periph_reset_pulse(RST_USART1);
25 rcc_periph_reset_pulse(RST_USART3);
28 static void gpio_setup(void)
30 // PC13 = BluePill LED
31 gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
32 gpio_clear(GPIOC, GPIO13);
35 static volatile u32 ms_ticks;
37 void sys_tick_handler(void)
42 static void tick_setup(void)
44 systick_set_frequency(1000, 72000000);
45 systick_counter_enable();
46 systick_interrupt_enable();
50 static void delay_ms(uint ms)
52 u32 start_ticks = ms_ticks;
53 while (ms_ticks - start_ticks < ms)
58 static void usart_setup(void)
61 gpio_set_mode(GPIOA, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO_USART1_RX);
62 gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO_USART1_TX);
64 usart_set_baudrate(USART1, 115200);
65 usart_set_databits(USART1, 8);
66 usart_set_stopbits(USART1, USART_STOPBITS_1);
67 // usart_set_mode(USART1, USART_MODE_TX);
68 usart_set_mode(USART1, USART_MODE_TX_RX);
69 usart_set_parity(USART1, USART_PARITY_NONE);
70 usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE);
75 gpio_set_mode(GPIOB, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO_USART3_RX);
76 gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_OPENDRAIN, GPIO_USART3_TX);
78 usart_set_baudrate(USART3, 4800);
79 usart_set_databits(USART3, 9);
80 usart_set_stopbits(USART3, USART_STOPBITS_1);
81 usart_set_mode(USART3, USART_MODE_TX_RX);
82 usart_set_parity(USART3, USART_PARITY_ODD);
83 usart_set_flow_control(USART3, USART_FLOWCONTROL_NONE);
88 static const byte send_pkt[] = {
89 0xdc, 0xc2, 0x00, 0x0b, 0x06, 0x3d, 0x2e, 0x11, 0x25, 0x40, 0x78,
98 // This is needed when programming via serial boot loader, harmless otherwise.
99 SCB_VTOR = 0x08000000;
100 cm_enable_interrupts();
102 debug_printf("Hello, kitty!\n");
105 u32 led_ticks = ms_ticks;
108 if (USART_SR(USART1) & USART_SR_RXNE) {
109 uint c = usart_recv(USART1) & 0xff;
113 if (USART_SR(USART3) & USART_SR_RXNE) {
114 uint x = (usart_recv(USART3) & 0xff) ^ 0xff;
115 debug_printf("%02x ", x);
116 last_ticks = ms_ticks;
118 if (tx_pos && (USART_SR(USART3) & USART_SR_TXE)) {
119 if (tx_pos > sizeof(send_pkt)) {
123 uint x = send_pkt[tx_pos++ - 1];
124 usart_send(USART3, x ^ 0xff);
128 if (last_ticks && ms_ticks - last_ticks >= 100) {
132 if (ms_ticks - led_ticks >= 100) {
133 led_ticks = ms_ticks;