Read the code

Here is the whole sketch. It reads the knob, then sets the light.

l3-fade-arduino.ino
// Lesson 3, Arduino version: the knob on A0 sets how
// bright the LED on pin 9 is.
void setup() {
  pinMode(9, OUTPUT);
}

void loop() {
  int reading = analogRead(A0);  // 0 to 1023
  analogWrite(9, reading / 4);   // 0 to 255
}

What each line does

  1. void setup()Its lines run once, when the board starts11.
  2. pinMode(9, OUTPUT);Makes pin 9 an output7.
  3. void loop()Its lines run again and again12.
  4. int reading = analogRead(A0);Reads the knob on A0 as a number from 0 to 10236. The int variable reading keeps it8.
  5. analogWrite(9, reading / 4);Sets pin 9 from 0, always off, to 255, always on1. The reading goes up to 1023, so dividing by 4 makes it fit1, 13.

How a pin can be half on

PWM gets an in-⁠between result from a pin that is only on or off9. The pin switches on and off, over and over9. On an UNO R3, pin 9 does this about 490 times a second1.

The number you give analogWrite sets how much of the time the pin is on. That share is the duty cycle1, 9. At this speed, the LED looks dimmer instead of blinking9.

Sources for this page

  1. Arduino reference: analogWrite
  2. Arduino reference: analogRead: values 0 to 1023 on the UNO R3
  3. Arduino reference: pinMode
  4. Arduino reference: int
  5. Arduino: Basics of PWM (Pulse Width Modulation)
  6. Arduino reference: setup()
  7. Arduino reference: loop()
  8. Arduino reference: / (division)