pwm-respiration.ino

Arduino Mega 2560 (Rev3) · File : pwm-respiration.ino · Language : Arduino · Use case : Faire respirer une LED avec la modulation de largeur d'impulsion

The LED ramps up then down thanks to analogWrite, which generates an 8-bit PWM on a ~-marked pin. The step reverses at the 0 and 255 bounds.

Hardware required

An Arduino Mega 2560 (ATmega2560, 16 MHz, 5 V): 54 digital I/O, 15 PWM, 16 analog inputs, 4 hardware UARTs. 1 LED + 330 Ω resistor.

Wiring

LED anode (through the resistor) on pin 9, cathode to GND.

How it works

analogWrite applies a rising then falling duty cycle; the eye perceives smooth brightness change. In the Arduino IDE, select « Arduino Mega 2560 » and the port, then Upload. PWM on 2-13 and 44-46; UART1=18/19, UART2=16/17, UART3=14/15; SPI on 50-53.

Going further

Drive several LEDs in opposite phases, or a MOSFET for a full LED strip.

pwm-respiration.ino

// Respiration LED sur broche PWM (analogWrite 0..255).
const int LED = 9;
int niveau = 0;
int pas = 4;

void setup() {
  pinMode(LED, OUTPUT);
}

void loop() {
  analogWrite(LED, niveau);
  niveau += pas;
  if (niveau <= 0 || niveau >= 255) pas = -pas; // inversion au bord
  delay(15);
}

← Back to the board