[应用相关] 硬件定时器配置PWM

[复制链接]
624|2
 楼主| 天灵灵地灵灵 发表于 2024-4-19 18:39 | 显示全部楼层 |阅读模式
  1. /*
  2.   All-in-one setPWM
  3.   This example shows how to configure a PWM with HardwareTimer in one single function call.
  4.   PWM is generated on `LED_BUILTIN` if available.
  5.   No interruption callback used: PWM is generated by hardware.
  6.   Once configured, there is no CPU load.
  7. */

  8. /*
  9.   Note: Please verify that 'pin' used for PWM has HardwareTimer capability for your board
  10.   This is specially true for F1 serie (BluePill, ...)
  11. */

  12. #if defined(LED_BUILTIN)
  13. #define pin  LED_BUILTIN
  14. #else
  15. #define pin  D2
  16. #endif

  17. void setup()
  18. {
  19.   // no need to configure pin, it will be done by HardwareTimer configuration
  20.   // pinMode(pin, OUTPUT);

  21.   // Automatically retrieve TIM instance and channel associated to pin
  22.   // This is used to be compatible with all STM32 series automatically.
  23.   TIM_TypeDef *Instance = (TIM_TypeDef *)pinmap_peripheral(digitalPinToPinName(pin), PinMap_PWM);
  24.   uint32_t channel = STM_PIN_CHANNEL(pinmap_function(digitalPinToPinName(pin), PinMap_PWM));


  25.   // Instantiate HardwareTimer object. Thanks to 'new' instantiation, HardwareTimer is not destructed when setup() function is finished.
  26.   HardwareTimer *MyTim = new HardwareTimer(Instance);

  27.   // Configure and start PWM
  28.   // MyTim->setPWM(channel, pin, 5, 10, NULL, NULL); // No callback required, we can simplify the function call
  29.   MyTim->setPWM(channel, pin, 5, 10); // 5 Hertz, 10% dutycycle
  30. }


  31. void loop()
  32. {
  33.   /* Nothing to do all is done by hardware. Even no interrupt required. */
  34. }


yutingwei 发表于 2024-8-31 22:30 | 显示全部楼层
如果开发板上定义了 LED_BUILTIN,则 PWM 信号将输出到 LED_BUILTIN 引脚。否则,使用 D2 引脚。
yutingwei 发表于 2024-8-31 22:31 | 显示全部楼层
用于在 STM32 微控制器上配置和生成 PWM信号,利用 HardwareTimer 类来简化配置和启动 PWM 的过程。
#if defined(LED_BUILTIN)
#define pin  LED_BUILTIN
#else
#define pin  D2
#endif


您需要登录后才可以回帖 登录 | 注册

本版积分规则

183

主题

3475

帖子

13

粉丝
快速回复 在线客服 返回列表 返回顶部