HOME - - - - - - - - - Other material for programmers - - - - - - - - - Arduino Tutorial Table of Contents

Arduino Programming: Introducing Variables


Forgive a nostalgic digression? As I start this tutorial, I must just pay homage to Per Ranhoff. I can remember extraordinary detail of a day in the late sixties when I was sitting in my first computer lesson. Per started us with the concept of variables. The specific machine he was showing us how to use was the same machine that he who would become technical director of "Toy Story" started his programming on not many years later.

So.. down to work.

Inside the computer, at one level, everything is numbers. You don't always have to work at such a low level... can type "Hi" into a program without having to worry about the fact that the code for H is 72 and the code for i is 105, for instance... but it pays to be aware that there are numbers inside the machine.

Given that there are numbers involved, it follows that they must exist somewhere. Where they are is the essence of variables.... again, "at one level".

Suppose you were writing a program to calculate the tax payable on some transaction. You would need to have the tax rate available to your program. It could be stored in a variable.

In the following example, we're going to look at the state of a switch on one of the Arduino's ports. It will be easiest to use the program if you use a toggle switch, e.g. the sort used for light switches, i.e. one that will stay on or off after you touch it. But a momentary (door bell like) switch will also do. (If you are in any doubt about the basics of reading a switch, see my "Going Loopy" tutorial, as that introduces reading switches) We'll call it Sw0 from now on. WHICH pin of your Arduino it is attached to matters only once in the whole program. (That matter will be dealt later by in a comment embedded in the program.) If Sw0 is on, and you've wired it up so that "on" connects the Arduino input pin to zero volts, then when the Arduino "looks" at it, the answer comes back as a number... zero. When the switch is off, and you may have to provide a pull up to 5v so that the input doesn't "float" (again, see Going Loopy), then the answer "one" comes back. Zero and one: numbers. With a variable, we can store that number so that at a later stage in our program we can see what the state of the switch was at the time it was read. Fear not... eventually we'll explore more challenging uses of variables!


Before we get to the program that will illustrate variables, you need to set up your Arduino so that there's at least one switch for input, and one LED for output. Type it in, get rid of any error inducing typos, play with it. In a moment I'll take you through it. Yes: What this program does can be accomplished by simpler means. Remember that it is only done this way to help introduce variables.

Here's a little program to test your LED and your switch. DO type it in! Bits of it are recycled in the next program, and until this little test program is working, the main one won't. All that happens while the test program is running is that if Sw0 is on, the LED is on, and if Sw0 if off, the LED is off. (Don't tell your non-geek friends that you spent the time and money it took to get here. They wouldn't understand.)

Make sure you understand WHY everything works in the little test program, what it does, etc.
/*Test switch and LED*/
#define ledPin 13 /* (No ; after #define) Configures program to
  run on hardware with an LED on digital line 13, which
  makes sense as there's already one on that line, on the
  Diecimila itself. You can also have a "bigger, better"
  LED attached. Just be sure to connect it through a suitable
  resistor to the ground line */

#define Sw0 8 /* Configure the program to look at digital
  line 8 when asked to read "Sw0"... "SWitch zero"*/
void setup()
{
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  digitalWrite(ledPin,digitalRead(Sw0));
}


Don't be tempted to skip over the above because it is "too basic". ALWAYS build up projects bit by bit. Developing the skills of breaking a project down so that it CAN be built up in bits is one of the essential tasks of any would be engineer... software, hardware, or other!

The program above gets two "little bits" working: Can we turn the LED on and off? Can we read the switch? I actually spent about 15 minutes getting them both working... and I've been a this game a while. I even had to take out the "Can we read the switch?" part to get past problem in turning the LED on.

(My problems arose not from the Arduino, but from the rat's nest of wires in and around my Arduino and the BasicStamp connected to it and the two computers connected to the micro-controllers. I don't want to tear down something else I'm working on in the same hardware.... but the price is complexity, and the first cousin of complexity is faults. A wire had come loose, among other things.)

And now, here's the program to illustrate variables in action. The program does not merely light or not light the LED depending on the state of the switch, i.e "Switch on= LED on; Switch off= LED off".

Note that you have to restart the program again and again to see it in action. It does something when it starts, and does something else when the setting of the switch is first changed. After that, it just sits there.

To restart the program, you can either do the simple but time consuming thing: Press ctrl-U on the machine you are using to program the Arduino. OR: You can press the button marked "S1" on the top of a Diecimila. OR: (If your Diecimila's button isn't accessible because of the way your Diecimila is plugged into your proto-board, you can cause a reset by bringing the Reset input of the board (it's nicely marked "Reset") low for a moment. The line can float at other times.

Be sure to try starting the program with the switch in the "on" position, and try starting it with the switch in the "off" position. Play with it a bit. We'll go through it in a moment.
/*plt1ca_1
First program (after "test switch and LED") in plt1ca.htm's tutorial*/

#define ledPin 13 /* (No ; after #define) Configures program to
  run on hardware with an LED on digital line 13, which
  makes sense as there's already one on that line, on the
  Diecimila itself. You can also have a "bigger, better"
  LED attached. Just be sure to connect it through a suitable
  resistor to the ground line */

#define Sw0 8 /* Configure the program to look at digital
  line 8 when asked to read "Sw0"... "SWitch zero"*/

byte itWas;
byte itIs;

void setup()
{
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin,HIGH);
  itWas=digitalRead(Sw0);
}

void loop()
{
  itIs=digitalRead(Sw0);
  if (itIs!=itWas) {digitalWrite(ledPin,LOW);};
}


See what it does? Either playing with the "black box" of Arduino, switch and LED, or by going through the code?

Do try to figure it out yourself. Answer and analysis in a moment....







... answer further down...





Okay! Here we go.

First, at the "black box" level:

The LED comes on when the program is started. Regardless of how the switch is set. It stays on until the switch's position is changed. The the LED goes off, and stays off. It goes off whether the switch changes from open to closed, or from closed to open.

Now we'll go through the code. The lines....

byte itWas;
byte itIs;
...create two variables, one called itWas and the other called itIs. In them, I'm going to store what the state of the switch was at the beginning of the program's execution, and what it is at the moment (at least what it "is" at the most recent read).

These are variable declarations. They appear even before....

void setup()
.... because they aren't "doing" things... They are preparing the "pigeonholes" where we are going to "keep" numbers we want to be able to look at.

A variable declaration starts with a keyword specifying a data type, in this case we used the "byte" type, which is fine if we only need to store 0,1,2,3... 253, 254 or 255. You'll learn about data types as you progress through this course.

Next in a variable declaration line comes the name of the variable we are declaring. This, for simple variables... we'll look at fancier ones in a later tutorial... can be any "identifier", using the term exactly as we used it before when we said what could come after "#define". In a nutshell, a word that isn't an Arduino keyword, that starts with a letter, and has only letters, digits and underscores in it. One body of knowledge you need to grow is the knowledge of what the language's keywords are. Happily, the editor's syntax highlighting will help you. If you forget that "delay" is a keyword, the fact that it changes color when you enter it is a hint that warns you. (And conversely, if you enter "Delay", when you meant "delay" the fact that it doesn't get highlighted is a warning that something (the capital "D") is wrong.)

Just as I made up the names "ledPin" and "Sw0", I simply made up the variable names, "itWas" and "itIs". Try to come up with names that are concise, unambiguous, informative.

We might, if we had wished, have said....
byte itWas=5;
If we had, then "itWas" would start its life holding a 5. This is called initialization. It is often useful; it just didn't happen to be in this program. Never assume you know what is in a variable that you have not first put something in.

And there will be a semicolon at the end of the variable declaration. It isn't really part of the declaration; it is "glue" to hold the whole program together. It also acts a bit like a period in a page of English text.... it helps define the boundaries between statements. (The language doesn't usually pay any attention to where a new line starts. In fact I can't think of a place you can't start a new line, apart from inside the middle of a word. But sensible use of new lines helps humans read the code, even if the compiler "doesn't care".)

Moving on: Within the "setup" function, we said the digital line identified by "ledPin" would be used as an output, and we set that output high in the early moments of the program's execution....

void setup()
{
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin,HIGH);
.... and we looked to see what the state of Sw0 was, AND STORED THE ANSWER in itWas. That is what....
itWas=digitalRead(Sw0);
... did. THIS IS AT THE HEART OF THIS TUTORIAL'S primary mission: To help you understand the use of variables.

When neophytes see itWas=digitalRead(Sw0), they usually, quite reasonably, think of things like 20=16+4.

The computer doesn't mean the same thing at all by "=".

You should read....
itWas=digitalRead(Sw0);
as "The contents of the variable itWas BECOME whatever digitalRead(Sw0) gives."

Sw0 will give either 0 or 1, depending on whether the switch is closed, so itWas will BECOME either 0 or 1.

Hold that thought.

A moment later, and repeatedly, as it is in the Loop function, we get...
  itIs=digitalRead(Sw0);
That makes itWas BECOME whatever digitalRead(Sw0) returns at the moment the line is executed. In the first instants of the program's execution, of course, itIs will hold the same thing that itWas is holding. However, as time goes on, the state of Sw0 may change. Every time it changes, shortly thereafter what is in itIs changes... but there's nothing in the program to change what's in itWas. That will continue to "be" (shorthand for "hold") what it was set to right at the beginning of the program's execution.

"Putting something into a variable" is called "assigning a value". itWas=0 assigns itWas the value zero.

Hold on to your hat. We're moving on, and about to encounter something that may seem nasty at first brush. Let's start picking through....
if (itIs!=itWas) {digitalWrite(ledPin,LOW);};
It is a nice, well behaved "if..."statement... really!

It consists of....

if (CONDITION) {statement}

The condition is....

itIs != itWas

The "!=" says "does not equal". When we see itIs and itWas in a condition, we (eventually) know that we must look and see what's in those variables.

itIs != itWas may, at some times, boil down to "0 != 1", which would be TRUE. (All "conditions" boil down to true or false.) Zero does not equal one- true.

If itIs had a 1 in it, and itWas had a 1 in it, then itIs != itWas would be false: it is NOT TRUE that "1 does not equal 1".

You'll get it when you've used it a bit.

=====

A little break for you. The following is the program to do something similar in a different microcontroller. Have a little look, see if you can figure it out. Doesn't matter if you can't. b1 is roughly the equivalent of Sw0, except that it returns a boolean value, i.e. something that is "true" or "false", hence its use as the condition in an "if...." clause.

program third;
var ItWas,ItIs: byte;
begin
if b1 then ItWas:=1 else ItWas:=0;
if ItWas=1 then write(led,1)
         else write(led,0);
repeat
    if ItWas=1 then write(led,1)
         else write(led,0);
    if b1 then ItIs:=1 else ItIs:=0;
until not(ItIs=ItWas);
end.
Aren't you glad you work with the Arduino? Interesting that a program that is simple in one language can be more complex in another. The machine the above was written for doesn't have the equivalent of a "Loop" function.


Back to work! But we're moving on from discussing variables. Forgive a slight bit of repetition? This tutorial was developed out of an earlier one. I can either give this one final editing, or move on and get others roughly "translated to Arduino" for you. I'm choosing the latter for now.

You need to maintain descriptions of what is going in programs as you build them up. Such descriptions are called documentation, and you'll need to do it to get very far in programming.

The first level is user documentation. For the program we wrote for the Arduino, the user documentation would be....

This program will turn an LED on.
The first time the user changes the state of the switch, the LED be turned off.

The deeper level is programmer's documentation. For our little program, it could be....

When the program begins, the state of a switch is checked, and a zero or a one is stored in the variable ItWas. An LED is turned on. The program then enters a loop. On each pass through the loop, the switch is checked again, and a zero or one is stored in the variable ItIs. On each pass through the loop, the values stored in ItWas and ItIs are compared. If they are not equal, the LED is turned off.



Well! That at last brings us to a good place to finish for now. Come back to the index of Arduino tutorials for another one soon?


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 .....