🛠 Piloter 15 LED en PWM simultané

Arduino Mega 2560 (Rev3) · intermediaire · Schéma : IMG-mega-2560-intermediaire-1-pwm-multi-led.svg — barre de 15 LED avec résistances sur les broches PWM 2 à 13 et 44 à 46 de l’Arduino Mega 2560, effet balayage lumineux

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials