HOME  → Other material for programmers → Arduino Tutorial Table of Contents
Delicious.Com Bookmark this on Delicious StumbleUpon.Com Recommend to StumbleUpon

Arduino Programming: Second program


Welcome. Here we go...

Fire up your Arduino. Enter the following program....
/*
PLTut1bFirstExample
ver 8Feb08
*/

#define ledPin 13                // LED connected to digital pin 13

void setup()
{
  pinMode(ledPin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
  digitalWrite(ledPin, HIGH);
  delay(6000);
  digitalWrite(ledPin, LOW);
  delay(2000);
 do
 {  //bracket 1
     digitalWrite(ledPin, HIGH);
     delay(500);
     digitalWrite(ledPin, LOW);
     delay(500);
 }  //bracket 2
while (true);
}

... and press ctrl-U to compile the program, send it to the Arduino, and start it running.

After a bit of flickering which is part of the program upload process, you should see the LED come on for six seconds, go off for 2, and then start going on/ off/ on/ off with a half a second for each on and each off.

I hope that you can see WHY that is happening? We've really only added a tiny thing to the program, a statement that boils down to....

do
 {
 SOMETHING;}
while (CONDITION);

The "condition" we've used is a little unusual. Normally, where we have "true" we would have something that might start true, but would eventually become false. But there's nothing wrong with what we've done... if we want the "SOMETHING" we've got between the curly brackets to go on forever. Which, for the sake of this introductory example, is fine.

(Don't worry... your Arduino isn't "broken". As soon as you send it another program to run, it will break out of the "forever" loop.)

Think back to the end of the previous tutorial. The stuff about program structure. See the way we get "{ ...}" delimited "stuff" inside "{ ...}" delimited "stuff"?

Notice that brackets... curly and normal, are ALWAYS paired, and nested. The Arduino editor does a nice job of showing you the other half of any pair when you highlight a bracket. The one I've marked with the comment "Bracket 1" is the partner of "Bracket 2", as I hope you can see. Note also the way lines have been indented to help the reader see the logical elements of the program. The compiler doesn't care about the indents. Make them be whatever helps the human.

What we've created is called an infinite loop. Loops are powerful and useful, though you rarely make infinite loops... on purpose! Some bugs are the result inadvertent infinite loops.



By moving just the "do" line, and the "{" after it, modify the program so that it says....

/*
PLTut1bFirstExample
ver 8Feb08
*/

#define ledPin 13                // LED connected to digital pin 13

void setup()
{
  pinMode(ledPin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
 do
 {  //bracket 1
  digitalWrite(ledPin, HIGH);
  delay(6000);
  digitalWrite(ledPin, LOW);
  delay(2000);
     digitalWrite(ledPin, HIGH);
     delay(500);
     digitalWrite(ledPin, LOW);
     delay(500);
 }  //bracket 2
while (true);
}

(The word "do" has been moved up. You can do this by obvious means, but you can also do it by selecting the text, and then dragging it to where you want it!)

When you've made the change, and re-run the program. Now we get six seconds on, 2 off, a brief on/ off, and then we go back to six seconds on. Notice the big effect on the results that arises from the simple, short, move of the "do" line. You should be able to see why the program behaves differently....

We'll come back to loops. Our brief encounter should have helped you see how a general form...

do
 {
 SOMETHING;}
while (CONDITION);

... guides us as we write actual programs. It was also a nice example of one of the "somethings" that can be plugged into the body of a function.


Next we have to consider inputs and outputs. First time users of micro-controllers for the first time will need to adjust their expectations in regard to what is "normal" by way of input and output.

I imagine most of my readers will be quite used to using ordinary PCs. They will be used to keyboards and display screens capable of lots of text, and even pretty pictures.

Certainly micro-controllers can read from/ write to such devices.... but it will be a while before your skills and bank balances allow you to use an Arduino like a $500 Windows laptop.

(Having said that, I should add that a little LCD screen to display limited amounts of text, and even crude graphics, isn't terribly expensive... under $45. But for now, I will show you what you can do with just an Arduino and a few dollars worth of components.)

We've already seen some "output"... for that's what the LED is. You can add more LEDs, as we shall see.

The most basic form of input is a switch connected to one of the Arduino's digital inputs, and that's what we'll look at next.

I half remember reading somewhere that the Arduino has pull up resistors on the inputs. If that is so, you only need to connect a switch between a pin you want to use for input, and "ground", i.e. the "0 volts" side of the power on your board.

Any of the digital pins can be inputs or outputs... we'll come to that in a moment.

Until I'm sure about the presence of those "pull up resistors", I'm going to add one on each line I'm using for input, just to be sure. I'll be using about 10k resistors. Anything from 5k to 50k would probably work okay. It won't do any harm. They are added so that the digital input is connected, through the resistor, to the +5volts present on your Arduino. The switch discussed earlier is connected as before.

The result is as follows: When the switch is closed, be it a toggle, or a "door bell"- like momentary switch, there is no resistance between the digital input and 0v. The input "sees" zero.

When the switch is closed, you will also be connecting the board's 5v to it's 0 volts... but through the 10k resistor, so don't worry, the current will be so tiny that no problem will arise.

When the switch is open, because the digital input is of virtually infinite resistance, it will "see" the 5v, even though it "sees" it through the resistor. Because very, very little current is flowing, it is as if the resistor were not there, and the input "sees" what we call "1".

For the sake of this tutorial, I am assuming input via switches on digital pins P8 and P9, and output via LEDs on pins P11, P12 and P13.

Because it is a good practice in general, and in case you already have switches and LEDs attached to your Arduino, I will be using #defines at the start of the program to assign the pins to the names "Sw0" and "Sw1" and "LEDpin0", "LEDpin1", "LEDpin2". (That's Switch and LEDpin "zero", not "oh". Oh. Computer people count from zero... for a reason. For now, instead of experiencing an explanation, just deal with it.) If you have the switches and LEDs, but they are on different pins, JUST change then number given in each #define. E.g. if your first switch was on pin 8, then in what follows, you would say....

#define Sw0 8

For the first of the following programs, the Diecimila's onboard LED plus Sw0 will be sufficient.

Completely replace the program in your Arduino with the following. If you can't just copy and paste, you can leave the comments out.

/*
PLTut1bSecondExample */

#define LEDpin0 13                // LED "0" connected to digital pin 13
#define LEDpin1 12                // LED "1" connected to digital pin 12
#define LEDpin2 11                // LED "2" connected to digital pin 11

#define Sw0 8   //Switch 0 on digital pin 8
#define Sw1 9   //Switch 1 on digital pin 9


void setup()
{
  pinMode(LEDpin0, OUTPUT);      // sets the digital pin to provide output
  pinMode(LEDpin1, OUTPUT);
  pinMode(LEDpin2, OUTPUT);
  // unless set up for output, a pin will be assumed to be employed for input

 // And to establish initial states...
  digitalWrite(LEDpin0,HIGH); //Turn the LED on at the outset.
  digitalWrite(LEDpin1,HIGH); //Turn the LED on at the outset.
  digitalWrite(LEDpin2,HIGH); //Turn the LED on at the outset.
}

void loop()
{
//The next line is the "interesting" one!
  if (digitalRead(Sw0)==0) {digitalWrite(LEDpin0,LOW);}; //See text
}

That's two equals signs in a row... to say "does it equal?" Elsewhere we use single equals signs to say "change what's in the variable".

Once the program is properly entered, what will happen is that all the LEDs will come on, and stay on, until you press Sw0. At that point LED0 will go off, and stay off until you restart the program with ctrl-U.

Why? It is down to two things; one you know, and one you don't.

Did you remember that the "if(digitalRead...." line is going to happen over and over again? It does that because it is in the Loop function. You knew that.

What you didn't know, but can probably figure out, is how the "if" statement works.

It's basic form is.....

if (CONDITION) {SOMETHING;}

The "condition" is something that is true or false. In this case...

digitalRead(Sw0)==0

.... we have asked the computer to go off and look at the state of the Sw0 pin. It will either be 0 or 1. The double equals sign is not a typo. It is how we compare two things. In this case the state of the Sw0 pin and zero. If the switch is up, then digitalRead(Sw0) will return a 1, and 1 is not equal to 0, so the condition will "boil down to" false.

On the other hand, if the switch on Sw0 is closed, then digitalRead(Sw0) will return a 0, and that 0 would be equal to the 0 that is after the double equals sign, so the condition will "boil down to" true.

Nota Bene - - - - if, in a condition, you are asking if something equals something else, you must have a double equals sign between them. If you enter....

if (c1 = 5) {do something}

... when you meant to enter....

if (c1 == 5) {do something}

... then it will compile, and it may seem to work... but it won't work the way you will be thinking it will work.

You have been warned!.... do try to remember!

So much for the "condition" part of the statement. what about the rest of it?

The "something" between the "{" and the ";}" can be a simple statement, as in our example, or a number of simple statements "glued" together with semicolons. That concept should be familiar.... we encountered the same sort of thing in the body of a function, and "inside" the "do"...." "while" statement that we started this tutorial with.

The "something" stuff happens IF the condition is true.

Now look at the program again, and think about how the Arduino behaves when the program is running. The program checks Sw0 over and over again. If the program finds Sw0 pressed, it switches LED0 off. And, so far, there is no provision to turn it back on. Pretty limited program! But it does introduce the "if" statement.

Happily, there's an optional extra we can use.

Change the "if" line so that it reads....

if (digitalRead(Sw0)==0)
    {digitalWrite(LEDpin0,LOW);}
    else  {digitalWrite(LEDpin0,HIGH);};

The if... then... else structure proves for one thing to do when the condition is true, and an alternative for when the condition is false.

When you run the modified program, you will find that the switch turns the LED off when pressed, as before, but also: releasing the switch turns the LED back on again.

Try adding another line so that the other switch turns one of the other LEDs on and off.

Conditions can be more complex that the one we've used so far. You could have....

((digitalRead(Sw0)==0) and (digitalRead(Sw1)==0))

... in which case switch 0 AND switch 1 would have to be closed to make what is in the first clause happen. If either, or both were open, then what was in the "else" clause would happen.

Let me speak about "then" for a moment: it has at least two meanings in English. It can be a matter of sequence: I put on my socks, THEN I put on my shoes. Or it can be a matter of consequence: If you eat three pizzas, THEN you will be sick. While time comes into that, too, I hope you'll see the more significant "consequence" element. In programming, "then" is used in the consequence sense.

Cast your mind back to....

if (digitalRead(Sw0)==0)
    {digitalWrite(LEDpin0,LOW);} else
    {digitalWrite(LEDpin0,HIGH);};

I don't know how the line above appears on your screen.... and, I'm glad to say, it doesn't matter! If you have a high resolution screen, and your browser window isn't narrow, the whole thing may fit on a single line. However, it is also acceptable to write it as two lines or even more lines. Make your browser window wide enough to show the following as three lines)...

if (digitalRead(Sw0)==0)
      {digitalWrite(LEDpin0,LOW);}
       else  {digitalWrite(LEDpin0,HIGH);};

The use of new lines and indents can help a lot towards making code readable. The indentation emphasizes the fact that the second and third ("else...") lines are just a continuation of what started on the previous line.

Just before I end this tutorial, let's lift our eyes from the mud in front of our feet on this trek towards programming proficiency, and gaze at more interesting projects in the middle distance. Suppose you had your Arduino wired to your six disc CD player, and you wanted to be able to use switches (like Sw0) to select which CD will play. Of course, you could simply use six switches... but with a little cleverness a mere three will do. I the following, a 0 stands for "switch in off position", and a 1 stands for "switch in on position" Each group of 3 digits shows the settings of the three switches.


000 could stand for "play CD1"
001 could stand for "play CD2"
010 could stand for "play CD3"
011 could stand for "play CD4"
100 could stand for "play CD5"
101 could stand for "play CD6"

... and you's still have 2 codes spare! If you want to switch between 256 options, a mere 8 switches is enough. Cool?




The work so far may have seemed "boring", but you have to walk before you run. If you're not determined (stubborn?) enough to slog through this dull stuff, you're probably not temperamentally suited to programming, anyway. But that's okay: Higher wages for those of us who are! Even if you aren't looking for wages, hang in there? It does get fun! And I hope you've had some fun already?




Please also note that I have two other sites, and that the following search will not include them. They have their own search buttons.

My Sheepdog Guides site.
My Arunet site.

Go to the sites above, and use their search buttons if you want to search them.
To search this site....

Search this site or the web powered by FreeFind

Site search Web search
The search engine merely looks for the words you type, so....
*    Spell them properly.
*    Don't bother with "How do I get rich?" That will merely return pages with "how", "do", "I"....

You can also search this site without using forms.
Ad from page's editor: Yes.. I do enjoy compiling these things for you... hope they are helpful. However.. this doesn't pay my bills!!! If you find this stuff useful, (and you run an MS-DOS or Windows PC) please visit my freeware and shareware page, download something, and circulate it for me? Links on your page to this page would also be appreciated!
Click here to visit editor's freeware, shareware page.


Want a site hosted, or email? You can also help me if you sign up via this link to 1&1's services. (I wouldn't recommend them unless I was happy after several years as one of their customers, but yes, they do pay me if you use this link! As do the Google advertisers, about whom I know nothing, of course.)



Valid HTML 4.01 Transitional Page tested for compliance with INDUSTRY (not MS-only) standards, using the free, publicly accessible validator at validator.w3.org


Why does this page cause a script to run? Because of the Google panels, and the code for the search button. Also, I have some of my pages' traffic monitored for me by eXTReMe tracker. They offer a free tracker. If you want to try one, check out their site. Why do I mention the script? Be sure you know all you need to about spyware.
Editor's Main Homepage
How to email or write this page's editor, Tom Boyd

....... P a g e . . . E n d s .....