Analog values are written to the Arduino with the Pulse-Width Modulation (PWM) pins. In Chapter 1, The Arduino, we looked at what PWM is and how they work. On most Arduino boards the PWM pins are configured for pins 3, 5, 6, 9, 10, and 11; however, the Arduino Mega has significantly more pins available for PWM functionality.
To perform an analog write, we use the analogWrite() function, which takes the following syntax:
analogWrite(pin, value);
The analogWrite() function accepts two parameters, where the first one is the pin number and the second is the value to set. The value for the analogWrite() function can range from 0 to 255.
Let's look at a sample sketch to see how we can use the analogWrite() function to fade a led in and out:
#define LED_ONE 11 int val = 0; int change = 5; void setup() { pinMode(LED_ONE, OUTPUT); } void loop() { val += change...