如何在 STM32 上的 PlatformIO / Arduino 中实现 1MHz 中断
在我们之前的文章最小 STM32 HardwareTimer PlatformIO / Arduino 定时器中断闪烁示例中,我们展示了如何使用 HardwareTimer 通过定时器中断闪烁 STM32F407 板的板载 LED。
在这篇文章中,我们将提供一个如何使用 HardwareTimer 并拥有一个以 1 MHz 运行的非常快的中断的示例 - 换句话说:每秒一百万次。
timer_interrupt.cpp
#include <Arduino.h>
HardwareTimer timer(TIM1);
bool ledOn = false;
void OnTimer1Interrupt() {
ledOn = !ledOn;
digitalWrite(PC13, ledOn ? HIGH : LOW);
}
void setup() {
pinMode(PC13, OUTPUT);
// 配置定时器
timer.setPrescaleFactor(21); // 设置预分频器为 21 => 定时器频率 = 168/21 = 8 MHz(来自 168 MHz 时钟源预分频为 1)
timer.setOverflow(8); // 设置 ARR 为 8 => 定时器频率 = 1 MHz
timer.attachInterrupt(OnTimer1Interrupt);
timer.refresh(); // 使寄存器更改生效
timer.resume(); // 启动定时器
}
void loop() {
}注意当运行如此快的中断时,在下一次中断运行之前你不能在中断内做太多事情。
Check out similar posts by category:
C/C++, PlatformIO, STM32
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow