Arduino 6: Analog Output & For-loops

Analog output means outputting a variable voltage, as opposed to the fixed +5V/off of a digital output pin. The Arduino fakes analog output by pulsing the output pin on and off very quickly (about 490Hz) so it averages a voltage less than 5V. You can change the rate of pulsing to simulate 256 voltage steps between 0 and 5V. However only certain pins on the Arduino can do this, the digital pins labeled PWM (pulse-width modulation). On more recent Arduinos, that’s pins 3,5,6 and 9,10,11. The function

analogWrite(pinNumber, level);

writes to one of the PWM pins a level between 0 and 255, where 0 is off and 255 is full on (5V). The following program fades an LED on pin 9 (with a 220 ohm resistor to ground) on and off between 0 and 2.5V.

int ledPin = 9; // must be a PWM digital pin
int maxBright = 128; // between 0 and 255
int ms = 10;    // delay in milliseconds
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
for (int n = 0; n < maxBright; n++) {
analogWrite(ledPin,n);
delay(ms);
}
for (int n = maxBright; n > -1; n--) {
analogWrite(ledPin, n);
delay(ms);
}
}

Note the new control structure,

for (initial state; condition; increment) {…}

This is a looping structure, which will repeat the steps in the brackets for a fixed number of times using a counting variable.  For the initial state, you define an integer counting variable and set it to an initial value. Then the code in the curly braces is run once. After that the counting variable is incremented in the way you specified (you can add, subtract or do anything mathematical to the counting variable in increment). Then the condition is checked, and if it’s still true, the process repeats, running code and incrementing the counting variable until the condition fails. Then the code continues with whatever comes after the curly braces. Typically this is used to simply repeat code a fixed number of times; if you want to repeat something ten times, use:

for (int n = 0;  n < 10;  n++) {…}

By convention, the counting variable starts at 0, so your condition is to check for less than the number of times you want to repeat. Recall that n++ means add 1 to n. You could also count down using n–, subtracting 1 from n.

You could do the same thing with shorter code using a single for-loop; how?

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s