typestar

PWM fade in Arduino

analogWrite dims with duty cycle: 0 is off, 255 is full.

// analogWrite is PWM: 0 is off, 255 is full grow-light.
const int LIGHT_PIN = 9;

int brightness = 0;
int fadeStep = 5;

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

void loop() {
  analogWrite(LIGHT_PIN, brightness);
  brightness += fadeStep;
  // Reverse at either end of the range.
  if (brightness <= 0 || brightness >= 255) {
    fadeStep = -fadeStep;
  }
  delay(20);
}

How it works

  1. analogWrite(LIGHT_PIN, brightness) sets the PWM duty.
  2. The step adds each pass; hitting either end negates it.
  3. A short delay(20) sets the fade's tempo.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
361
Tokens
74
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 63 seconds.

Type this snippet

Step 3 of 3 in Digital I/O, step 6 of 27 in Language basics.

← Previous Next →