360 Secure SkillHub
360 安全技能中心

timers-pwm-baremetal

该 Skill 面向裸机嵌入式开发,说明如何配置 MCU 通用定时器实现 PWM 输出、输入捕获和 SysTick 周期 tick,给出预分频、自动重装载、比较通道等寄存器级 C 代码示例,并列出频率错误、无 PWM 输出和 tick 抖动等问题的排查建议。仅含说明文档,未提供工程、脚本或构建配置。

分类:开发
mohitmishra786
热度 0.00
最近更新 2026-11-21 00:19:41

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add mohitmishra786/low-level-dev-skills/timers-pwm-baremetal
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
timers-pwm-baremetal
description
Bare-metal timer and PWM skill. Use when configuring general-purpose timers for PWM, input capture, or periodic ticks without RTOS. Activates on queries about timer prescaler, PWM duty cycle, input capture, or SysTick bare-metal.

Timers and PWM (Bare-Metal)

Purpose

Configure MCU timers for PWM output, input capture, and periodic scheduling: prescaler/ARR setup, compare channels, and SysTick as a simple tick source.

Triggers

  • Motor/LED dimming via PWM
  • Measuring pulse width (input capture)
  • Bare-metal millis() without FreeRTOS
  • Hardware periodic sampling trigger

Workflow

1. PWM on TIM2 CH1 (STM32)

f_pwm = f_timer_clk / ((PSC+1) * (ARR+1))
duty = (CCR / (ARR+1)) * 100%
RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;

TIM2->PSC  = 83;      /* 84MHz / 84 = 1 MHz tick */
TIM2->ARR  = 999;     /* 1 kHz PWM */
TIM2->CCR1 = 500;     /* 50% duty */
TIM2->CCMR1 |= (6U << TIM_CCMR1_OC1M_Pos);  /* PWM mode 1 */
TIM2->CCER  |= TIM_CCER_CC1E;
TIM2->CR1   |= TIM_CR1_CEN;

GPIO: PA0 AF1 TIM2_CH1.

2. SysTick tick

volatile uint32_t tick_ms;

void SysTick_Handler(void) {
    tick_ms++;
}

void systick_init(uint32_t hz) {
    SysTick_Config(SystemCoreClock / hz);
}

3. Input capture

Configure channel in CCMR as input, set CCER polarity, read CCR on interrupt when edge captured.

4. Agent usage

/timers-pwm-baremetal 1 kHz 25% duty PWM on TIM2 channel 1

Common Problems

Symptom Cause Fix
Wrong frequency APB timer clock doubling Check RM timer clock x2 rule
No PWM output CCER/CCMR not enabled Enable channel output
Jittery tick SysTick overridden One owner for SysTick

Related skills

  • skills/baremetal/gpio-baremetal — timer pin AF
  • skills/embedded/freertos — replace SysTick with RTOS tick
  • skills/baremetal/adc-dac-baremetal — timer TRGO for ADC trigger