From b41240dc6326464403b73351cb8ff24abedee59a Mon Sep 17 00:00:00 2001 From: xengineering Date: Mon, 27 Sep 2021 11:49:00 +0200 Subject: Switch from Delays to Timer / Counter --- src/main.c | 54 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 35 insertions(+), 19 deletions(-) diff --git a/src/main.c b/src/main.c index 50d7fdc..1027d18 100644 --- a/src/main.c +++ b/src/main.c @@ -2,31 +2,27 @@ #include +#include #include - - -/* -SYSCLK should be at 72.000.000 Hz ---> 18.000.000 __asm__("nop") per second (one instruction --> 4 clock cycles) ---> 18.000 __asm__("nop") per millisecond -*/ -#define DELAY_MS 18000 // FIXME seems to be too slow by factor of 4 +#include +#include static void clock_init(void); static void gpio_init(void); -static void delay(uint32_t delay); +void tim2_isr(void); +static void nvic_init(void); +static void timer_init(void); void main(void) { clock_init(); gpio_init(); + nvic_init(); + timer_init(); - while(1){ - gpio_toggle(GPIOC, GPIO13); - delay(250 * DELAY_MS); - } + while(1); // wait forever } @@ -34,19 +30,39 @@ static void clock_init(void) { rcc_clock_setup_pll(&rcc_hse_configs[RCC_CLOCK_HSE8_72MHZ]); rcc_periph_clock_enable(RCC_GPIOC); // for PC13 blinking + rcc_periph_clock_enable(RCC_TIM2); // for timer / counter 2 } static void gpio_init(void) { - gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO13); - gpio_set(GPIOC, GPIO13); + gpio_set_mode(GPIOC, + GPIO_MODE_OUTPUT_50_MHZ, + GPIO_CNF_OUTPUT_PUSHPULL, + GPIO13); +} + + +void tim2_isr(void) +{ + gpio_toggle(GPIOC, GPIO13); + TIM_SR(TIM2) &= ~TIM_SR_UIF; // clear interrrupt flag +} + + +static void nvic_init(void) +{ + nvic_enable_irq(NVIC_TIM2_IRQ); + nvic_set_priority(NVIC_TIM2_IRQ, 1); } -static void delay(uint32_t delay) +static void timer_init(void) { - for (uint32_t i = 0; i < delay; i++) { - __asm__("nop"); - } + gpio_set(GPIOC, GPIO13); + TIM_CNT(TIM2) = 1; // set start value + TIM_PSC(TIM2) = 1440; // set prescaler + TIM_ARR(TIM2) = 50000; // interrupt value + TIM_DIER(TIM2) |= TIM_DIER_UIE; // update interrupt enable + TIM_CR1(TIM2) |= TIM_CR1_CEN; // enable timer } -- cgit v1.2.3-70-g09d2