Built-in project · Arduino Leonardo

Leonardo fade

Two LEDs off two different kinds of timer: the ten-bit one on pin 13 and an ordinary 16-bit one on pin 9. The whole build, an Arduino Leonardo and 4 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.

Runs in your browser. Free, and no account needed.

Leonardo fade · Arduino Leonardolive0.000 s 0.00x
Click to open it in the editor
The circuit itself, running here on the simulator. Press what can be pressed; click anything else to open it in the editor.

The code

The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.

sketch.ino · Arduino Leonardo
// Fade: hardware PWM on pin 13, which on this board is timer 4.
//
// Timer 4 is the 32U4's ten-bit high-speed timer and it is unlike anything on
// an Uno: its TOP is a register (OCR4C) rather than a mode, its channels are
// A, B and D with no C, and each channel needs a PWM4x enable of its own on
// top of the COM bits. analogWrite hides all of that (the sketch is the
// ordinary one), but the waveform on pin 13 is coming out of a different kind
// of timer from the one that drives pin 9.
//
// Pin 9 gets the same ramp a quarter of a period behind, off timer 1, so the
// two PWM frequencies this board has are both on screen: 976.5625 Hz on 13 and
// 490.196 Hz on 9.

int level = 0;
int step = 5;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(9, OUTPUT);
}

void loop() {
  analogWrite(LED_BUILTIN, level);
  analogWrite(9, 255 - level);

  level += step;
  if (level <= 0 || level >= 255) {
    step = -step;
    level += step;
  }
  delay(12);
}

Parts list

6 parts, plus the jumper wires. Every one is in the editor's parts bin.

How it is wired

5 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.

  • Ground: Arduino Leonardo pin GND; LED, red pin C; LED, blue pin C
  • Arduino Leonardo pin 13; Resistor, 220 Ω (1) pin 1
  • Arduino Leonardo pin 9; Resistor, 220 Ω (2) pin 1
  • Resistor, 220 Ω (1) pin 2; LED, red pin A
  • Resistor, 220 Ω (2) pin 2; LED, blue pin A

Change it and keep it

Open it in the editor, change the circuit or the code, and keep your version in a free account.