$npx -y skills add mohitmishra786/low-level-dev-skills --skill timers-pwm-baremetalBare-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.
| 1 | # Timers and PWM (Bare-Metal) |
| 2 | |
| 3 | ## Purpose |
| 4 | |
| 5 | Configure MCU timers for PWM output, input capture, and periodic scheduling: prescaler/ARR setup, compare channels, and SysTick as a simple tick source. |
| 6 | |
| 7 | ## When to Use |
| 8 | |
| 9 | - Motor/LED dimming via PWM |
| 10 | - Measuring pulse width (input capture) |
| 11 | - Bare-metal `millis()` without FreeRTOS |
| 12 | - Hardware periodic sampling trigger |
| 13 | |
| 14 | ## Workflow |
| 15 | |
| 16 | ### 1. PWM on TIM2 CH1 (STM32) |
| 17 | |
| 18 | ``` |
| 19 | f_pwm = f_timer_clk / ((PSC+1) * (ARR+1)) |
| 20 | duty = (CCR / (ARR+1)) * 100% |
| 21 | ``` |
| 22 | |
| 23 | ```c |
| 24 | RCC->APB1ENR |= RCC_APB1ENR_TIM2EN; |
| 25 | |
| 26 | TIM2->PSC = 83; /* 84MHz / 84 = 1 MHz tick */ |
| 27 | TIM2->ARR = 999; /* 1 kHz PWM */ |
| 28 | TIM2->CCR1 = 500; /* 50% duty */ |
| 29 | TIM2->CCMR1 |= (6U << TIM_CCMR1_OC1M_Pos); /* PWM mode 1 */ |
| 30 | TIM2->CCER |= TIM_CCER_CC1E; |
| 31 | TIM2->CR1 |= TIM_CR1_CEN; |
| 32 | ``` |
| 33 | |
| 34 | GPIO: PA0 AF1 TIM2_CH1. |
| 35 | |
| 36 | ### 2. SysTick tick |
| 37 | |
| 38 | ```c |
| 39 | volatile uint32_t tick_ms; |
| 40 | |
| 41 | void SysTick_Handler(void) { |
| 42 | tick_ms++; |
| 43 | } |
| 44 | |
| 45 | void systick_init(uint32_t hz) { |
| 46 | SysTick_Config(SystemCoreClock / hz); |
| 47 | } |
| 48 | ``` |
| 49 | |
| 50 | ### 3. Input capture |
| 51 | |
| 52 | Configure channel in `CCMR` as input, set `CCER` polarity, read `CCR` on interrupt when edge captured. |
| 53 | |
| 54 | ### 4. Agent usage |
| 55 | |
| 56 | ``` |
| 57 | /timers-pwm-baremetal 1 kHz 25% duty PWM on TIM2 channel 1 |
| 58 | ``` |
| 59 | |
| 60 | ## Common Problems |
| 61 | |
| 62 | | Symptom | Cause | Fix | |
| 63 | |---------|-------|-----| |
| 64 | | Wrong frequency | APB timer clock doubling | Check RM timer clock x2 rule | |
| 65 | | No PWM output | CCER/CCMR not enabled | Enable channel output | |
| 66 | | Jittery tick | SysTick overridden | One owner for SysTick | |
| 67 | |
| 68 | ## Related Skills |
| 69 | |
| 70 | - `skills/baremetal/gpio-baremetal` — timer pin AF |
| 71 | - `skills/embedded/freertos` — replace SysTick with RTOS tick |
| 72 | - `skills/baremetal/adc-dac-baremetal` — timer TRGO for ADC trigger |