🛠 Piloter 15 LED en PWM simultané
Objectives
Leverage the Mega 2560's capabilities: 15 8-bit PWM channels accessible via analogWrite on pins 2 to 13 and 44 to 46 (whereas the Uno only has 6). You will implement a non-blocking "knight-rider" light sweep across all 15 LEDs simultaneously, controlling the refresh interval with millis to keep the serial connection responsive.
Hardware
- 1 × Arduino Mega 2560 + USB cable
- 15 × LEDs + 15 × 330 Ω resistors
- Breadboard (or two breadboards placed side by side) and wires
Important reminder: 20 mA recommended per pin, 40 mA absolute maximum. Fifteen LEDs at full intensity draw approximately 120 mA in total, which is acceptable, but never exceed 40 mA on a single pin.
Complete Code
// Balayage PWM sur les 15 broches PWM (2-13, 44-46)
const uint8_t PWM_PINS[] = {2,3,4,5,6,7,8,9,10,11,12,13,44,45,46};
const uint8_t N = sizeof(PWM_PINS);
uint32_t t0 = 0;
float phase = 0;
void setup {
for (uint8_t i = 0; i < N; i++) pinMode(PWM_PINS[i], OUTPUT);
Serial.begin(115200);
}
void loop {
uint32_t now = millis;
if (now - t0 >= 20) { // rafraîchissement 50 Hz
t0 = now;
phase += 0.08f;
if (phase >= N) phase -= N;
for (uint8_t i = 0; i < N; i++) {
float d = fabsf(phase - (float)i);
if (d > (float)N / 2) d = (float)N - d;
uint8_t v = (d < 3) ? (uint8_t)(255 - d * 85) : 0;
analogWrite(PWM_PINS[i], v); // PWM 8 bits (0-255)
}
}
}
Expected Result
A brightness wave moves in a loop along the 15 LEDs, with a triangular intensity drop around the moving peak. The serial monitor remains responsive (no blocking delay): you can add commands without stuttering.
Common Mistakes
- Trying
analogWriteon a pin outside 2–13 / 44–46: the function does not generate any PWM on other Mega pins. - Wiring pins 44–46 incorrectly: they are on the middle connector of the board, not next to pin 13.
- Forgetting resistors on some LEDs: at PWM value 255, the affected LED and pin will heat up.
- Using
delayin the loop: the entire system freezes and the serial port stops responding; break it down usingmillis.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinodouble-servo.inoArduinopont-uart.inoArduinopwm-respiration.inoArduinopotentiometre-plotter.inoArduino