summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorxengineering <me@xengineering.eu>2021-09-27 11:49:00 +0200
committerxengineering <me@xengineering.eu>2021-09-27 11:49:00 +0200
commitb41240dc6326464403b73351cb8ff24abedee59a (patch)
treebee4ba3a3731df88fef0a98bf1d90ca2ed6c6a4a
parentcd9eaac6dacc0179815f16c9494b18633f1c6586 (diff)
downloadledcontrol-b41240dc6326464403b73351cb8ff24abedee59a.tar
ledcontrol-b41240dc6326464403b73351cb8ff24abedee59a.tar.zst
ledcontrol-b41240dc6326464403b73351cb8ff24abedee59a.zip
Switch from Delays to Timer / Counter
-rw-r--r--src/main.c54
1 files 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 <libopencm3/stm32/rcc.h>
+#include <libopencm3/stm32/flash.h>
#include <libopencm3/stm32/gpio.h>
-
-
-/*
-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 <libopencm3/stm32/timer.h>
+#include <libopencm3/cm3/nvic.h>
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
}