Writing analog signals

Just as you can read analog signals, you can also send analog values. Arduino uses Pulse Width Modulation (or PWM) pins to send out analog values. Check out the digital pins with a tilde symbol (~) next to them.

When using a normal digital pin to write HIGH or LOW, it outputs 5V or 0V. These PWM pins have a different ability – you can use them to send a voltage level anywhere between 5V and 0. With this, you can dim a LED smoothly between fully on and fully off.

To use this special ability of PWM pins, you’ll need to use the function of analogWrite(). It takes two parameters – the number of the PWM pin and the level of output. Level of output is a number between 0 and 255. 0 is equivalent to digital LOW and 255 is equivalent to digitalHIGH. You can set the level of output to any number in between.

Note: Be aware of the difference between analogRead() andanalogWrite()analogRead() receives a value between 0 and 1023, while analogWrite() sends a value between 0 and 255. analogRead()uses analog in pins, whereas analogWrite() uses PWM digital pins.

Now let’s try a simple example. Get an LED and a 220 ohm resistor (with the color strips of red, red, brown). Connect one leg of the resistor to digital pin 10. Connect the long leg of LED to the other leg of the resistor. Finally, connect the short leg of LED to GND.

There’s no need to call pinMode() when using analogWrite() so just leave the setup() empty here.

After you upload the code below, you’ll see the LED gradually lighting up to full brightness, turn off, and then repeat again.

int ledPin = 10;
int fade = 0;

void setup() {
// nothing here

void loop() {
analogWrite(ledPin, fade);
fade = fade + 10;
if (fade > 255) fade = 0;

A new command used here:

  • analogWrite(pinNumber, fadeLevel): It writes an analog signal to a PWM pin. pinNumber is the number of PWM pin you’re using, fadeLevelis a number between 0 and 255. 0 equals to digital LOW, 255 equals to digital HIGH.

Experiment Further

  • Try to make the LED fade back out after it reaches full brightness, instead of turning dark suddenly. We call this a breath light.
  • Can you change the speed of “breathing” so that it fades faster/slower?
  • Can you use a potentiometer to control the LED? Remember the difference between analogRead() and analogWrite().