🛠 Graduer une LED avec le PWM d'un timer
Objectives
Use the PWM output (MDP in French) of one of the GD32F103's 16-bit timers to gradually vary the brightness of an LED. The GD32F103C8 features up to 10 general-purpose 16-bit timers, 2 advanced timers, and 2 basic timers; the community Arduino core maps analogWrite to the timer channels. You will understand the principle of duty cycle and the clock constraint of APB1 (54 MHz max) / APB2 (108 MHz max).
Hardware
- GD32F103C8T6 / CBT6 Blue Pill compatible board
- External LED + 330 ohm resistor between the output pin and ground (do not rely on the onboard PC13 LED, which is not suitable for visible PWM)
- Timer output pin: PA6 (TIM3_CH1 timer channel on this package) >
- 3.3 V power supply
Complete Code
// pwm_led.ino — GD32F103C8, core CommunityGD32Cores
const uint8_t PWM_PIN = PA6; // sortie timer (cf. tableau AF du core) >
void setup {
pinMode(PWM_PIN, OUTPUT);
Serial.begin(115200);
}
void loop {
for (int p = 0; p <= 255; p += 4) { // rampe montante
analogWrite(PWM_PIN, p);
Serial.println(p);
delay(15);
}
for (int p = 255; p >= 0; p -= 4) { // rampe descendante
analogWrite(PWM_PIN, p);
delay(15);
}
}
Expected Verification
The external LED smoothly ramps up and down in brightness (breathing effect), without abrupt steps. With a logic analyzer or oscilloscope, you see a square wave of constant frequency whose duty cycle follows the 0-255 ramp. The onboard PC13 LED does not blink: it is not on this channel.
Common Errors
analogWritehas no effect: the chosen pin is not mapped to a timer channel in the core; cross-referencepins_arduino.hfrom the CommunityGD32Cores with the AF table in the datasheet. >- LED barely visible or burnt out: missing resistor (pin overvoltage) or too high resistance (LED off); 330 Ω to 1 kΩ to ground is a good range at 3.3 V.
- Confusion between 0-255 / 0-4095:
analogWriteexpects 0-255 even if the GD32 core's ADC is 12-bit; this is not the same scale asanalogRead. - PWM frequency too low/high: the core's default frequency may be audible or cause flickering; if your core exposes it, adjust the channel frequency, keeping in mind the clock chain (APB1 ≤ 54 MHz, APB2 ≤ 108 MHz).
- 108 MHz misconfigured: the GD32 resets to IRC8M just as the STM32 resets to HSI; switching to 108 MHz requires a correct PLL from the 8 MHz HXTAL crystal, and crystals on some clones are marginal at this frequency. >
- Forgetting
HSE_STARTUP_TIMEOUT: for a project ported from ST code, AN001 requires 0xFFFF to avoid startup blocking (the PWM will never start).
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinorespiration.inoArduinopotentiometre.inoArduinopont-uart.inoArduinooled-i2c.inoArduino