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?

Arduino 5: Analog Input

Image made with Fritzing (http://fritzing.org/)

Analog input is anything that produces a varying voltage. The most common analog input is a variable resistor, or potentiometer. This example uses a potentiometer to output a varying sound wave to a speaker. Connect the middle pin on the potentiometer to analog pin 1, and the two end pins to +5V and ground. Connect one end of the speaker to pin 11 and the other end to ground.

int res=0;
void setup(){
pinMode(11,OUTPUT);
}
void loop(){
res=analogRead(1);
digitalWrite(11, HIGH);
delayMicroseconds(1000+10*res);
digitalWrite(11, LOW);
delayMicroseconds(1000+10*res);
}

Analog pins don’t need the pinMode command because they are always in input mode. An analog pin can accept a voltage between 0 and 5V, and is read using the function

x = analogRead(pin_number);

This function divides up the interval between 0 and 5V into 1024 levels, reading the voltage on pin_number and returning a value from 0 (0V) to 1023 (5V) and storing it in variable  x.  Sound is generated by turning the speaker on and off on pin 11 very rapidly, between 100 and 1000 times a second, with the timing changing with the variable x. This is accomplished by turning the speaker output pin HIGH or LOW and then pausing in that state using the function

delayMicroseconds(t);

where t is an integer representing a time in microseconds.

Arduino 4: Counting Events

Image made with Fritzing (http://fritzing.org/)

A common requirement is to count digital input signals, like how many times a button is pressed. This program uses a button, one button pin connected to +5V, the other button pin connected to both Arduino pin 8 and a 10K resistor to ground. You need the resistor to ground so that when the button is not pressed, the Arduino pin reads LOW (0V, which is ground) and not some random voltage. The code follows:

int state=LOW;
int lastState=LOW;
int count=0;
void setup(){
Serial.begin(9600);
pinMode(8, INPUT);
state=digitalRead(8);
}
void loop(){
if (state==HIGH && lastState==LOW){
count++;
Serial.println(count);
}
lastState=state;
state=digitalRead(8);
}

Notice you can test two statements at once in an IF statement. The && symbol means “and”, so only if both “state is HIGH” and “lastState is LOW” will the variable count increase. Note also the notation

count++;

A double-plus sign after an integer variable adds one to the number. Similarly a double-negative (count–) would subtract one from the number.

Modulo division

A variation on this idea is to repeatedly count through a sequence of numbers, like 1-2-3-1-2-3-1-2-3, perhaps to cycle through different input or output ports. You can do this easily using the idea of modulo division, which divides one integer by another, and returns the remainder of the division. The symbol for modulo division is %, so

x=9%4;

takes 9/4 and returns 1, the remainder. The following program cycles between turning on three LED’s every time you push a button.  The button is now on pin 3, again with a 10K resistor to ground, and the other pin to +5V. LED’s are on pins 5,6 and 7, each to a 220-ohm resistor (red-red-brown) to ground. The code follows the diagram.

int state=LOW;
int lastState=LOW;
int count=0;
int remainder=0;
int lastPin=5;
void setup(){
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7,OUTPUT);
pinMode(3, INPUT);
state=digitalRead(3);
digitalWrite(lastPin,HIGH);
}
void loop(){
if (state==HIGH & lastState==LOW){
count++;
remainder=count%3;
digitalWrite(lastPin, LOW);
digitalWrite(5+remainder, HIGH);
lastPin=5+remainder;
}
lastState=state;
state=digitalRead(3);
}

Arduino 3: Digital Input

Image made with Fritzing (http://fritzing.org/)

To make the Arduino react to the outside world, it must be able to read input data. The simplest way to do this is to use digital input – reading whether a switch is on or off, and using that input to switch between doing two actions. Pins 1-12 along the top edge of the Arduino can all read digital input, but note that pin 13 can’t , because it’s got a resistor and LED on the board attached to it – only use 13 for output.

For a simple example, let’s use a button and two LED’s. When the button isn’t pressed, a red LED lights while a green LED remains off. When the button is pressed, the red turns off and the green one lights. The parts include two LED’s, the long leads going to Arduino pins 6 (green) and 7 (red), the short leads of each connected to 220-ohm resistors (red-red-brown) and then to the ground pin. There’s also a push button, one end connected to +5V, the other end connected both to the Arduino pin 8, and also to a 10K resistor (brown-black-orange) connected to ground. See the  diagram above.

Enter the program:

int button;
void setup(){
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, INPUT);
}
void loop(){
button  = digitalRead(8);
if (button==HIGH) {
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
}
else {
digitalWrite(6, HIGH);
digitalWrite(7, LOW);
}
}

The first line

int button;

declares a variable button to hold integer numbers.  The function

digitalRead(pin_number);

read the wire connected to Arduino pin pin_number, and returns either a 0 if the pin is LOW (voltage between 0 and 2.5V ), or a 1 if the pin is HIGH (voltage between 2.5 and 5V). In this case the value is stored in the variable button. Then the conditional statement

if (logical test) {
what to do if true
} else {
what to do if false
}

decides which of two actions to perform. In Arduino, LOW and HIGH are the same as the integers 0 and 1. So the statement button == HIGH tests the value of button to see if it equals 1. Note two equal signs == perform a test. If we just typed button=HIGH, it would store the value 1 into the variable button. You could also use symbols <, >, <=, >=, != (not equal) in the test as well.

Arduino 2: Digital Output

Blink – Arduino controlling digital output

Let’s use the Arduino to blink an LED once every second (on for a half-second, off for a half- second). We will use pin 13 as an output pin – that means that it will be a + voltage pin that Arduino can turn on (+5V) or off (0V). Choose an LED, and put the positive lead  (the long one) into pin 13 of the Arduino, and the short lead into the ground pin GND next to it. Type in the following program:

void setup() {
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
}

Upload the program to the Arduino. The LED should blink on and off. Note that pin 13 has a built in resistor (and actually a built-in tiny LED on the board that blinks in time with the one you plugged in). Normally LED’s should not be connected directly to an output pin or power supply on the Arduino, or it will burn out. Always put a 220-ohm resistor (red-red-brown) in series with an LED on any other pin or with a 5V power supply.

Computers can do four basic things: they read input data, they process data, they store data in memory, and they output data.  This simple program does two of them: process and output data. All data in the computer (and any data that is “digital”) is coded as a series of a high (+5) or low (0) voltages – a code with two states, or “binary” code. So the simplest output a computer can perform is to turn something on or off, by making an output wire (or “pin”) HIGH or LOW. In setup(), the command

pinMode(pin_number,mode);

sets a particular pin pin_numer on the Arduino to one of two modes, INPUT or OUTPUT (you must use capitals). An output pin allows it to turn a voltage on or off, to control an outside device, while an input pin would read incoming data. A given pin generally shouldn’t change modes in a program, so this is only done once in setup(). To actually turn the pin on or off in the loop() function, use

digitalWrite(pin_number, state);

which will turn the Arduino pin pin_number to one of two states, HIGH or LOW. A pin that is HIGH is basically “on” or at +5V, while a LOW pin is off.

As a challenge, grab your breadboard, another LED, two 220-ohm resistors and some jumper wire, and make the Arduino control two LED’s on different pins. Hint:  along the long edges of your breadboard are probably two lines of pins that are all connected right along the length of the board. It’s helpful to wire one of these lines to the ground pin on the Arduino, and then plug all the parts that need ground into this long channel. See the diagram below. Now you figure out the programming.

Image made with Fritzing (http://fritzing.org/)

Arduino 1: Writing Sketches and Printing to Screen

Connect the USB cable between the Arduino and the computer, then start the Arduino software. Once the software opens, the first thing to do is to tell the software on which port the Arduino is connected. In the top menu click on Tools>Serial Port, and generally you choose the last COM port on the list (the latest version of the software, Arduino 17, will do this automatically.) Also set up which Arduino board you have by going to Tools>Board, and clicking on the proper one (as of 12/2009, probably the Duemilanova – the name is stamped on your Arduino board.)

Hello world – getting Arduino to print to the laptop screen

Unlike traditional programming, programs written in Arduino (called “sketches”) are usually intended to loop infinitely. While that’s generally a bug in a typical program, you want a microcontroller running a project to keep going until you turn it off, so infinite loops are OK. Let’s start by printing a message to the laptop to make sure everything is connected. Since the program will keep looping, let’s have it alternate printing two words, with a one-second delay between them. Type in the following program, watching the capitalization and punctuation:

void setup(){
Serial.begin(9600);
}
void loop(){
Serial.println(“hello”);
delay(1000);
Serial.println(“world.”);
delay(1000);
}

Once it’s typed in, you upload it to the Arduino board by clicking the sixth icon in the icon row at the top of the screen, the right-pointing arrow. You will get the message “Uploading to I/O board”, and lights should flash on the Arduino. If you typed something incorrectly, you will get a message to that effect at the bottom of the screen in red– make your corrections and upload again.  If instead you get the message “Done uploading”, it worked. But in order to see output from the Arduino you have to click the last icon in the row at the top of the screen, the Serial Monitor.  Then a new window will display information sent back from the Arduino. If you see gibberish, check the little drop-down box in the bottom right of the window, which is the communication speed – it should read 9600. If not, change it to 9600. You ought to see a continuing sequence of  “hello” and “world.” go by indefinitely. To stop it running, click the second icon in the row, the square. This just stops the printout – the program is still running on the Arduino board.

Arduino programs usually are made up of two functions, called setup() and loop(). You start a function with the command “void”, and names of functions end in a pair of parentheses (). The setup function runs just once, and takes care of initializing values in variables or defining whether pins on the Arduino are input or output. The loop function holds all the code that is meant to loop indefinitely, which is the body of your program. Notice that all the commands in a function are contained in curly braces, {}, and that all command lines end in a semicolon.

In this program, the command

Serial.begin(9600);

opens up a line of communication between the Arduino and the computer at 9600 baud, or bits per second (specifically use 9600, not any old number). You must do this in setup if you want to have Arduino print to the computer screen. The command

Serial.println(“text”);

prints whatever text you put in quotes to the screen, then moves the cursor to the next line. If you put a variable in the parentheses with no quotes, it would print the value stored in the variable. The command

delay(n);

makes the program pause n milliseconds before continuing (n should be a positive integer).

At this point, it would be a good idea to check out the language reference page at the Arduino website. You can also get there from within the Arduino software via the top menu, at Help>Reference.