打印
[应用相关]

硬件定时器配置PWM

[复制链接]
443|2
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
/*
  All-in-one setPWM
  This example shows how to configure a PWM with HardwareTimer in one single function call.
  PWM is generated on `LED_BUILTIN` if available.
  No interruption callback used: PWM is generated by hardware.
  Once configured, there is no CPU load.
*/

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

#if defined(LED_BUILTIN)
#define pin  LED_BUILTIN
#else
#define pin  D2
#endif

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

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


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

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


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


使用特权

评论回复
沙发
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


使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

174

主题

3372

帖子

13

粉丝