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.
analogWrite()function and how it differs from
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:
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
analogWrite(): This command takes two parameters for input – the pin and the value to write.
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.