Analog Output

Objectives and Overview

This lesson covers the basics of working with analog output. The lesson introduces the Arduino analogWrite() function and some code examples to get you started.

Lesson Objectives

  • Understand and explain how the Arduino handles analog output.
  • Explain the Arduino analogWrite() function and how it differs from digitalWrite().

Analog Out and the Arduino

The Arduino platform is primarily a digital platform so the voltage coming out of the pins is always the same. Analog output is a range, so it’s more complicated than digital output.

However, the Arduino uses a trick where it rapidly cycles a pin’s power on and off in order to generate a voltage that varies in strength. This is called Pulse Width Modulation or PWM for short. Only certain pins on the Arduino support PWM so if you need analog output, you will want a pin with a squiggly line near it:

Arduino Yun board with annotations pointing to the PMW pins (3, 5, 6, 9, 10, 11)

Introducing analogWrite()

When you were working with digital output, you used digitalWrite(). Now that you’re working with analog output, you will use analogWrite(). Let’s take a look at some code:

int ledPin = 9; // the pin with the LED. this pin allows for PWM ~ int val = 255; // the initial value to write. analogWrite(ledPin, val); // writes the value 255 to pin 9
Code language: JavaScript (javascript)

analogWrite(): This command takes two parameters for input – the pin and the value to write.

  • The pins available for analog output are marked with the ~ symbol. On the Arduino Uno board, these are pins 3, 5, 6, 9, 10, and 11.
  • The value must be between 0 and 255.

This value controls how “on” the pin is. A value of 0 turns the pin off and a value of 255 means completely on. Any values in between 0 and 255 result in different levels of brightness. This is used to create a fading effect.