stm32duino / STM32Examples

Arduino library to provide several examples for the Arduino core for STM32 MCUs.
140 stars 54 forks source link

Timebase_callback example does not work with STMduino core #19

Closed Bodmer closed 4 years ago

Bodmer commented 4 years ago

Could not get the example to work or find a way using the HardwareTimer support library so resorted to HAL. This works:

/*
  Timer interrupt callback
  This example shows how to configure HardwareTimer to execute a callback at a regular interval.
  Callback toggles pin.
*/

#include "HardwareTimer.h"

#if defined(TIM1)
  #define TIMER TIM1
#else
  #define TIMER TIM2
#endif

#define TICK_HZ 1 // Set interrupt frequency

// Create an instance of the timer class
HardwareTimer tick = HardwareTimer(TIMER);

void timerCallback(HardwareTimer*) {
  // Toggle the LED pin state
  digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}

void setup() {
  // Set LED pin to output
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);

  // Attach interrupt to the sketch callback
  tick.attachInterrupt(timerCallback);

  // Configure the timer using low level HAL calls
  TIM_HandleTypeDef timerHal;
  timerHal.Instance = TIMER;
  timerHal.Init.Prescaler = tick.getTimerClkFreq() / 4000;
  timerHal.Init.Period = (4000 / TICK_HZ) - 1; // Tick frequency
  timerHal.Init.CounterMode = TIM_COUNTERMODE_UP;
  timerHal.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  timerHal.Init.RepetitionCounter = 0;
  HAL_TIM_Base_Init(&timerHal);
  HAL_TIM_Base_Start(&timerHal);
}

void loop() {
  // Timer interrupt toggles LED as a background interrupt task
}
fpistm commented 4 years ago

I guess you used the master example example instead of the latest release one. See https://github.com/stm32duino/STM32Examples/commit/60f8b8cbbea7bd4ef0beee7c275ce60a3352f716#diff-496a1315886bd1b0c808440193033adeL34

So add the setMode to the example

Bodmer commented 4 years ago

You guessed right. All working now, thanks.