Lesson 11
22 min
Vary an LED's brightness with analogWrite() and play notes with a buzzer.
A digital pin can only produce 0 V or 5 V. So how do you vary an LED's brightness? The trick is called PWM("Pulse Width Modulation"): the board switches the pin on and off very quickly, about 490 times per second (about 980 on pins 5 and 6). The longer the pin stays on during each cycle, the brighter the LED appears.

On the Arduino Uno, only certain pins can do PWM. They can be recognized by the ~ symbol printed in front of their number:3, 5, 6, 9, 10 and 11.
The analogWrite(pin, value) function accepts a value from 0 (always off) to255 (always on). The name is misleading: it is not a true analog voltage, but PWM.
const int ledPin = 9; // PWM pin (~)
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
analogWrite(ledPin, 0); // off
delay(1000);
analogWrite(ledPin, 64); // about 25%
delay(1000);
analogWrite(ledPin, 128); // about 50%
delay(1000);
analogWrite(ledPin, 255); // 100%
delay(1000);
}By gradually varying the value with a loop, you get a smooth fade, like the LED on a device in standby mode.
const int ledPin = 9;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
// Gradual fade in
for (int v = 0; v <= 255; v++) {
analogWrite(ledPin, v);
delay(5);
}
// Gradual fade out
for (int v = 255; v >= 0; v--) {
analogWrite(ledPin, v);
delay(5);
}
}
By combining the potentiometer's analog reading (0 to 1023) with the PWM output (0 to 255), you can build a dimmer. The map() function does the scale conversion.
const int potPin = A0;
const int ledPin = 9;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
int reading = analogRead(potPin); // 0 to 1023
int brightness = map(reading, 0, 1023, 0, 255);
analogWrite(ledPin, brightness);
}A buzzer turns an electrical signal into sound. Apassive buzzer (the kind found in kits, often without a sticker) produces notes of varying pitch; the frequency is controlled by the program with tone(pin, frequency) (in hertz). noTone(pin) stops the sound. Connect one leg of the buzzer to pin 8 and the other to GND.

const int buzzerPin = 8;
// Frequencies in Hz: C, D, E, F, G, A, B, C
int notes[] = {262, 294, 330, 349, 392, 440, 494, 523};
void setup() {
}
void loop() {
for (int i = 0; i < 8; i++) {
tone(buzzerPin, notes[i]);
delay(400);
}
noTone(buzzerPin);
delay(2000);
}This example uses an array (notes[]) to store several values under a single name. The first element has index 0, the last one index 7.
Good to know
The tone() function uses one of the microcontroller's timers, which can disrupt PWM on pins 3 and 11. If you also use the buzzer, avoid those two pins for PWM LEDs and prefer pins 5, 6, 9 and 10.
Exercise
map() to between 200 and 1000 Hz) determines the pitch of the buzzer's sound.