# CubeMX settings: Timers and PWM

ARGYNIX Skills (worldskills.blog), lesson "Timers and PWM on the STM32".
Our own settings sheet for the worked example: 1 kHz PWM on PA0 whose duty follows a knob
on PA1, and LD2 blinking at 2 Hz. Board: NUCLEO-F103RB. The code to add is in
`timers_pwm_user_code.c`.

Labels are as STM32CubeMX 6 shows them. If one reads a little differently in your version,
look for the same word nearby. Part 6 tells you whether every setting really reached the
code.

## 1. New project

- STM32CubeMX: start a new project from the **MCU Selector** with the part
  **STM32F103RBTx**. Starting from the chip, not the board, means nothing is set that you
  did not set yourself. That is how a competition board with its own pinout will feel.

## 2. Pinout & Configuration

| Where | Setting | Value | Why |
|---|---|---|---|
| System Core > SYS | Debug | Serial Wire | On an F1, "No Debug" can make the generated code switch the debug pins off. The ST-LINK then cannot connect to the running program. |
| System Core > SYS | Timebase Source | SysTick | `HAL_GetTick()` counts milliseconds from it. |
| System Core > RCC | High Speed Clock (HSE) | BYPASS Clock Source | The Nucleo's ST-LINK feeds a ready 8 MHz clock into OSC_IN. On a Blue Pill, with its own 8 MHz crystal: Crystal/Ceramic Resonator. |
| Pin PA0 | click it | TIM2_CH1 | |
| Timers > TIM2 | Clock Source | Internal Clock | |
| Timers > TIM2 | Channel1 | PWM Generation CH1 | |
| TIM2 > Parameter Settings | Prescaler (PSC) | 71 | 72 MHz / (71 + 1) = 1 MHz: one count is 1 us |
| | Counter Mode | Up | Edge-aligned PWM |
| | Counter Period (ARR) | 999 | 1 MHz / (999 + 1) = 1 kHz |
| | auto-reload preload | Enable | A new ARR waits for the end of the period |
| | PWM Generation Channel 1: Mode | PWM mode 1 | HIGH while the count is below CCR1 |
| | Pulse | 0 | The start duty; the program sets it |
| | Output compare preload | Enable | A new CCR1 waits for the end of the period: no glitch |
| | CH Polarity | High | |
| Pin PA1 | click it | ADC1_IN1 | The knob |
| Analog > ADC1 | IN1 | ticked | |
| ADC1 > Parameter Settings | Continuous Conversion Mode | Disabled | The program starts each conversion |
| | Rank 1: Sampling Time | 239.5 Cycles | The longest: a 10 kOhm knob needs time to charge the sampling capacitor |
| Pin PA5 | click it | GPIO_Output | LD2, the green LED |

The ST-LINK clock reaches the chip on boards marked MB1136 C-02 or later (the sticker
under the board). On an early C-01 board it does not: set HSE to Disable, use PLL Source
Mux HSI / 2 and PLLMul x 16 for 64 MHz, and redo the timer maths for a 64 MHz timer clock
(PSC = 63 for 1 MHz).

## 3. Clock Configuration

Follow the path from left to right:

| Box | Value |
|---|---|
| Input frequency (HSE) | 8 MHz |
| PLL Source Mux | HSE |
| PLLMul | x 9, so 72 MHz |
| System Clock Mux | PLLCLK: SYSCLK = 72 MHz |
| AHB Prescaler | /1: HCLK = 72 MHz |
| APB1 Prescaler | /2: 36 MHz, the most APB1 allows |
| APB1 timer clocks | 72 MHz. This is the clock TIM2 counts. The APB1 prescaler is not 1, so the timers get twice the bus clock. |
| APB2 Prescaler | /1: 72 MHz |
| ADC Prescaler | /6: 12 MHz. The ADC allows at most 14 MHz. |

A box in red is a clock above its limit. Fix it before you generate.

## 4. Project Manager, then generate

- Project Name and Location: no spaces in the path.
- Toolchain / IDE: **STM32CubeIDE**.
- Code Generator: leave "Generate peripheral initialization as a pair of .c/.h files"
  unticked, so every `MX_..._Init()` stays in `main.c` and the blocks in the download
  match your file.
- Click **GENERATE CODE**.

## 5. Open it in STM32CubeIDE

Since STM32CubeIDE 2.0, CubeMX is a separate program.

- STM32CubeIDE: **File > STM32 Project Create/Import > Import STM32 Project**, choose
  the STM32CubeMX project, and give the folder CubeMX generated.
- Each time you generate again in CubeMX: in CubeIDE, select the project and press **F5**
  (Refresh), or it may still show the old files.
- Copy the blocks of `timers_pwm_user_code.c` into `Core/Src/main.c`, each between its
  own `USER CODE BEGIN` and `USER CODE END` comments.
- Build: **Project > Build Project**. Aim for 0 errors and 0 warnings.

## 6. Check the generated code

In `main.c` you should find:

- `SystemClock_Config()`: `RCC_HSE_BYPASS`, `RCC_PLL_MUL9`, `RCC_HCLK_DIV2` for APB1,
  `RCC_ADCPCLK2_DIV6`.
- `MX_TIM2_Init()`: `htim2.Init.Prescaler = 71;`, `htim2.Init.Period = 999;`,
  `htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;`,
  `sConfigOC.OCMode = TIM_OCMODE_PWM1;`.
- `MX_ADC1_Init()`: `sConfig.Channel = ADC_CHANNEL_1;`,
  `sConfig.SamplingTime = ADC_SAMPLETIME_239CYCLES_5;`.

If a value is not there, the setting did not take. Go back to CubeMX, not to the code:
a change outside the USER CODE blocks is lost at the next generate.

## 7. Flash and debug

- **Run > Debug As > STM32 C/C++ Application**. The first time, a launch configuration
  opens. The probe is the ST-LINK. The program stops at `main()`: press Resume (F8).
- **Live Expressions** view: add `knob_raw` and `duty_permille`, and turn the knob.
  They update while the program runs. Live expressions are on by default in the debug
  configuration.
- **SFRs** view (Window > Show View > SFRs): pause, open TIM2, and read the registers the
  HAL wrote: PSC = 71, ARR = 999, OC1M = 110 (PWM mode 1) and OC1PE = 1 in CCMR1, ARPE = 1
  in CR1, CC1E = 1 in CCER. CCR1 is the duty in tenths of a percent.
- A breakpoint on the line `last_led += 250u;`: each stop is one LED toggle. Remove it
  before you measure, or the timing is yours, not the program's.
- SWV, if you want to watch the duty as a graph: in the debug configuration, Debugger
  tab, enable Serial Wire Viewer (SWV) and set Core Clock to 72 MHz. Then Window > Show
  View > SWV > SWV Data Trace Timeline Graph, Configure Trace, and enter `duty_permille`
  in a Data Trace comparator. SWV uses the SWO pin, PB3: keep it free.

## 8. Prove it on the pin

Scope or logic analyser on PA0, knob set until Live Expressions shows `duty_permille`
= 250: period 1.000 ms, HIGH for 250 us. LD2: 250 ms on, 250 ms off.

## Sources

Checked on 2026-11-25. st.com did not answer from our network that day, so we read ST's
documents in the copies named here and the HAL in ST's own source code.

- STM32CubeIDE user guide, UM2609 Rev 18, June 2026 (the copy installed with STM32CubeIDE
  2.2): Debug As, Live Expressions, SFRs, SWV.
  https://www.st.com/resource/en/user_manual/um2609-stm32cubeide-user-guide-stmicroelectronics.pdf
- STM32CubeIDE quick start guide, UM2553 Rev 6, June 2026 (installed with STM32CubeIDE):
  Import STM32 Project.
- STM32CubeIDE 2.0.0, interoperability instead of integration, ST community, 2025-11-19,
  with ST's reply on refreshing with F5:
  https://community.st.com/t5/developer-news/stm32cubeide-2-0-0-interoperability-instead-of-integration/ba-p/856658
- STM32CubeMX user manual, UM1718 Rev 50, February 2026 (the copy installed with
  STM32CubeMX): SYS Debug Serial Wire, the user sections, Toolchain / IDE.
  https://www.st.com/resource/en/user_manual/um1718-stm32cubemx-for-stm32-configuration-and-initialization-c-code-generation-stmicroelectronics.pdf
- How to use STM32CubeMX to configure HSE and LSE, ST community article, 2022-06-09:
  https://community.st.com/s/article/how-to-use-stm32cubemX-to-configure-high-speed-external-oscillator-and-low-speed-external-oscillator
- STM32 Nucleo-64 boards user manual, UM1724 (we read Rev 14): the 8 MHz from the ST-LINK
  on boards marked MB1136 C-02 or later, LD2 on PA5.
  https://www.st.com/resource/en/user_manual/dm00105823-stm32-nucleo64-boards-mb1136-stmicroelectronics.pdf
- STM32F1 HAL driver V1.1.10 (22 July 2024), ST's source on GitHub: every HAL call and
  macro above. https://github.com/STMicroelectronics/stm32f1xx-hal-driver
- RM0008, STM32F10x reference manual: the timer clock doubling, PWM mode 1, preload.
  https://www.st.com/resource/en/reference_manual/rm0008-stm32f101xx-stm32f102xx-stm32f103xx-stm32f105xx-and-stm32f107xx-advanced-armbased-32bit-mcus-stmicroelectronics.pdf
