HOME

Programming the Arduino: Quick start guide.

This guide is for those who've programmed before. Prior familiarity with microcontrollers will also help you. I have also produced tutorials for beginners. No doubt you've already found out something about an Arduino before coming here. Skim through this page, and to fill in the gaps you have, and to discover treats you didn't know were in the device.

This webpage is easier to read if you put it on your screen in a window that doesn't use the full width of your screen. Make it at least wide enough that you can see the X's on the ends of the following line of ='s, and you should be okay. Your browser will claim that you will need to scroll horizontally for some text, and you will... but only for the Google bar at the bottom of the page.

X===============================================X

The following is a minimal program to wink an LED connected to the Arduino's pin 13. The Diecimila model of the Arduino comes with an LED (with resistor) on that line on the board.

I know that this is not "good" code. However, it is simple code, so that you can see the heart of what you need.

First two facts for you: The Arduino language is similar to C. It is case sensitive. (You can't put "PinMode" where "pinMode" is needed. The first letter of that must be in lower case, i.e. "p", not "P".)

N.B.: The programs here have not yet tested for PERFECTION on a Diecimila... mine's tied up doing other things just now. They all "should" work; do let me know, please, if you spot any typos?

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

What do we learn from the above?>

The basic structure for any Arduino program is...

void setup()
{
statement
}
void loop()
{
statement
}

So far we have seen three "statements".

(The semicolon is not, strictly speaking, part of the statement... but you can pretend it is, and if you do, everything is so much easier!)

"PinID" will be a number. 0 - 13 for "ordinary" operations.

In these "Quickstart with Arduino programming" pages, when I refer to, say, "pin 5", I am using the reference scheme used by the software. You will sometimes need to "translate" that to the "pin number" as it would be referenced in respect of the Diecimila's J1, J2 or J3, where the pins are supplied for connection to external devices.("Pin 0" (software) is "pin 1" of J1). Or, you may be looking at a circuit diagram showing the number of a "pin" in terms of the leg of the IC at the heart of the Diecimila. ("Pin 0" (software) is pin 2 of the IC.) And you will probably be working with a prototyping board, and which row of holes on that connects to "Pin 0" (software), of course depends on you. I find a little diagram very helpful!

Be sure to read the page about the pins, at the official Arduino. In particular, note that you can damage the chip at the heart of your Arduino by using pinMode(PinID,OUTPUT) and then issuing, say digitalWrite(PinID,HIGH) when the pin is connected to 0v, aka "ground". Note also the clever built in, connectible- (or dis- connectible- ) by- software pull up resistors, for use when you are using a pin as an input.

"PinMode" will be INPUT or OUTPUT.

"PinState" will be HIGH or LOW.

"HowLong" will be a number, 1 - 32000 will work nicely for you. If you say "delay(1000)", the Arduino will go into a loop and "sit there" for 1 second. Bigger numbers can be dealt with, but data-type assumptions by the compiler begin to be a pain. If you want long delays, make a function that makes the Arduino wait for 1 second or 1 minute, and then call that function as many times as you need to call it.

If you copy things from this by hand, be careful with the brackets. Ordinary brackets, "(" and ")", won't do where curly brackets "{" and "}" are wanted, nor will vice versa work.


I always prefer to understand things in general terms, so I'm going to explain Arduino programming in general terms. Grit your teeth, get through "keyword" and "identifier". Things get better rapidly, once they are out of the way.

In the following "keyword" means a word "built into" to the Arduino compiler. We've already met pinMode, digitalWrite, and delay. Also HIGH, LOW, INPUT, and OUTPUT.

The words setup and loop are keywords, but slightly atypical. Usually words used in the context they appear in are user-created words, not keywords.

Don't worry overmuch that you might use a keyword where you shouldn't simply because you don't know that the word is a keyword. You will usually be saved by the Arduino development environment' syntax highlighting. And a little common sense and experience will go a long way. If you're in need, there's a list of the Arduino keywords on the official site.

In a moment we're going to use the term "identifier". An identifier is something that....

Okay as identifiers: myIdentifier, c5, an_identifier_with_a_stupidly_long_name

Not okay as identifiers: an-identifier-made-with-hypens, made with space, 1startingWithADigit

Would "work" as identifiers, I think, but Bad Choices:

Bad Choice 1: "Delay" (too easily confused with the keyword "delay". Be careful that you don't accidentally type, say, Delay, meaning to put the keyword in your program, but actually putting in an identifier.)

Bad Choice 2: "a" would certainly work, but single letter identifiers are not sufficiently meaningful.

Whew! That's got us past "keyword" and "identifier". Things get better, more useful, now.

An Arduino program will consist of two or more functions.

Many functions begin with the keyword void. Following that, you either have "startup", or "loop", or an identifier. Following that, always a pair of normal brackets, i.e. "( )", which sometimes do, sometimes don't have something between them. And following the normal brackets, always a pair of curly brackets, i.e. "{ }". You can compile a program with nothing between the curly brackets, but the program won't do anything. They always have a statement between them. As I said before, the statement always has a semicolon after it.

Look again at the little program given as an example above. You should be able to see all of the features we've just discussed in general terms.


In one sense, you now know "most" of what goes into every Arduino program!

You'll have to learn about all the possible statements, but that's not as bad as it sounds. Understanding the structure of things, which you mostly do now, is the hard part.

One little "trick". Before I get to it, I need to show you something similar in a more familiar environment- the English language.

Bear with me? What is a simple, whole number? (Which I'll call a "number" for now, implying that for this discussion we're forgetting numbers with fractional parts, etc.)

To say what a number is, we can start by defining "digit"...

A digit is....

0 or 1 or 2 or 3..... or 8 or 9

By defining "|" to mean "or", we can make that easier to read...

0 | 1 | 2 | 3..... | 8 | 9

Now we can define "number". A number is....

(a digit) | (a digit and a number)

This is a recursive definition In the course of defining "number", we are using the word "number"... but that's still okay. According to our definition, let's list some "numbers": "8" is a number. "4" is a number. To know that either of those is a number, we only need the simple part of the definition, which says that any digit is a number. However, using the second part of the rule, if "8" is a number, then "98" (the digit 9, and the number 8) is also a number. As is "498". And "7498", etc, etc, etc! Shezam!

Don't dismiss that bit of "simple, obvious" stuff too lightly. Although the example is simple, when you get the hang of it, that system, Backus-Naur form, can be used to pin down extremely complex definitions extremely clearly.

Why have I gone off on this tangent? Because I want to define "a statement" as follows:

(statement) | (statement plus statement)

We already know that "delay(800);" and "digitalWrite(13,HIGH);" are a statements. From the rule we've just made, we can also say that....

delay(800);digitalWrite(13,HIGH);

... is a statement. You can call it a compound statement, if that makes you more comfortable. The beauty of calling delay(800);digitalWrite(13,HIGH); "a" (singular) statement is that you can now say that the loop function will always look like....

void loop()
{
statement
}

You don't have to clutter what's between the { }'s with "one or more..." And, if you stick to the slightly bent rule and agree that every statement ends with a semi colon, lots of other things don't need to be said in complex ways. Note that one consequence of that is that there should always be a semicolon before a close- curly- bracket (}).


Now with out new tools, we are going to revisit our earlier definition of what an Arduino program consists of.

If you only want to do very simple things, you don't need what follows. Master it, and you'll be able to do much more.

An Arduino program consists of...

a "setup" function declaration
a "loop" function declaration
... and sometimes, one or more other
                          function declarations.

To make sense of that, we need a definition of "function declaration". Easy, now that we have the tools. A function declaration is....

void an identifier (optional arguments)
{
a statement
}

(Don't worry about those optional arguments for now.)

If the "identifier" is setup, we have the setup function declaration; if the "identifier" is loop we have the loop function declaration. We haven't seen a program yet with more than the two function declarations, but we're about to.

The following, (I hope you agree... if you don't go figure out where you're confused...) meets out rules for an Arduino program:

void setup()
{
pinMode(13,OUTPUT);
}

void loop()
{
winkLED;
}

void WinkLED()
{
digitalWrite(13,HIGH);
delay(800);
digitalWrite(13,LOW);
delay(800);
}

It is very similar to the program we had before, but we've made up a new word for the language! In the loop function, we've used "WinkLED" as if it were a keyword, even though it is not. But it can be used like one in this program because of the function declaration we've put into the program.


Hummm. I've left this a bit late. Maybe I'll move it when I edit this page. But before we go further, let me make explicit something you probably figured out for yourself.

When you run an Arduino program, the Arduino will first do whatever the setup function calls for. It will then do what is in the loop function... again and again and again.


Programs should have comments, also known as remarks.

If you put "//" into a line, everything following the "//" on that line will be ignored by the compiler.

If you put a "/*" into an Arduino program, everything from that to the first instance of a "*/" will be ignored. For example....

/*SamplePrgm2
ver 18 Feb 08
It is wise to start every program
with the filename on the first line,
and a version ID on the second */

void setup()
{
pinMode(13,OUTPUT);
}

void loop()
{
winkLED; //Turn LED on, then off
}

void WinkLED()
{
//This is the function we made up
digitalWrite(13,HIGH);
delay(800);
digitalWrite(13,LOW);
delay(800);
}

Warning! Do not put a comment between the ( )s and the { in a function declaration. Causes hard- to- understand errors.

Another thing I should have mentioned previously: In Arduino code you can put spaces and new lines pretty well where you like, within reason.

So! Commenting out of the way... but do remember to put comments in your code, even though they "do nothing".


#define

Next I'm going to tell you about #define. Here it is in action....

/*SamplePrgm2
ver 18 Feb 08 b
Version to show #define */

#define LEDpin 13 //do not put a ; here

void setup()
{
pinMode(LEDpin,OUTPUT);
}

void loop()
{
winkLED; //Turn LED on, then off
}

void WinkLED()
{
//This is the function we made up
digitalWrite(LEDpin,HIGH);
delay(800);
digitalWrite(LEDpin,LOW);
delay(800);
}

LEDpin is not a variable. We'll come to those. When we said "#define LEDpin 13", we were saying "anywhere you see LEDpin, use 13". Suppose we wanted to wink an LED on pin 12? In the version of the program we've just seen, only one change is needed: The 13 on the #define line becomes a 12. In the earlier versions of the program, all the references to pin 13 have to be found. Not too hard in our little program, especially as a strange number like 13 stands out... but in a serious program, and when changing something less strange, you stand a very good chance of changing something that should not have been changed and failing to change every instance of the number that should be changed.

Note that you do not put a semicolon after a #define. Because this is so unusual in Arduino programming, I recommend always adding the "//no ; here" comment to #define lines.


Variables

I never knew a programming language without variables; Arduino has them too. (Local and global, but that's for later in this tale.

While there is no point in the program, as shown, you could use a variable as follows....

/*SamplePrgm3
ver 18 Feb 08*/

#define LEDpin 13 //do not put a ; here
int iHowLong;

void setup()
{
pinMode(LEDpin,OUTPUT);
iHowLong=800;
}

void loop()
{
winkLED; //Turn LED on, then off
}

void WinkLED()
{
//This is the function we made up
digitalWrite(LEDpin,HIGH);
delay(iHowLong);
digitalWrite(LEDpin,LOW);
delay(iHowLong);
}

That's the "no frills" version. I created an integer-type variable called iHowLong" with the variable declaration

int iHowLong;

During the setup function, I put 800 in the variable with

iHowLong=800;

Because I had done that, when the program, in "WinkLED" came to....

delay(iHowLong);

... it was as good as "delay(800);"

A little frill:

If, during the declaration, I'd said....

int iHowLong=800;

It would have been just as good as putting the "iHowLong=800;" into the setup function. Better, actually, in terms of program readability and error avoidance. I can't think of a good reason to declare a variable without initializing it, even a different first value will be established within the program before the variable is used. Assuming that a variable holds something is a common source of bugs.

The Arduino has a selection of data types. Besides "int" (16 bit signed integers.... -32768 to 32767 inclusive.... there is "unsigned int", "byte", "boolean", etc. There is a floating point data-type, pretty cool for a little guy like the Arduino. Arrays are also possible. More on them later. If you need something special right away, you can consult the official Arduino website's reference page.


Arithmetic

The example... at first... is going to be a little artificial, but if you'd be willing to suspend disbelief, we can progress faster.

Modify the "WinkLED" portion of our previous example to create the following. You only need to add one line, and it is marked. (Yes, there is a problem in the logic. We'll resolve it in a moment.)

/*SamplePrgm3 b
ver 18 Feb 08*/

#define LEDpin 13 //do not put a ; here
int iHowLong;

void setup()
{
pinMode(LEDpin,OUTPUT);
iHowLong=800;
}

void loop()
{
winkLED; //Turn LED on, then off
}

void WinkLED()
{
//This is the function we made up
digitalWrite(LEDpin,HIGH);
delay(iHowLong);
digitalWrite(LEDpin,LOW);
delay(iHowLong);
iHowLong=iHowLong-20; //This line is new
}

When you run that, the first wink will be as before. Then the program executes....

iHowLong=iHowLong-20;

... which changes the contents of iHowLong, so that the next "on" time and "off" time are shorter. This happens over and over, until the contents of iHowLong fall to 0, and if that doesn't cause a problem, there will certainly be a problem when, on the next pass you try what boils down to "delay(-10);".... but until then, the program is behaving sensibly, winking faster and faster.

We can fix the problem easily enough by adding a line just after the "iHowLong=iHowLong-20;" that says.....

if (iHowLong<80) {iHowLong=800};

... we'll look at the "if" statement in detail in a moment. For now, I hope what that does is obvious?

Besides adding (+), the Arduino can....

The first are the same things you did when you were 9 years old. Modulo works as follows..... it can be very useful!

Get it? No reason you should... just thought I'd give you the chance. Modulo works like this. Remember when you were learning to divide, and you said, say, that 9 divided by 4 is two remainder 1? The answer to x modulo y is the remainder part of the answer. As I said... the operator is useful. You'll see. But you don't need to worry about it now.

Much of the time in an Arduino, you will be working with data that is of a type that does not allow fractions. Unless I am very much mistaken (although I must admit, I haven't checked), the "division" operator does a "div" when applied to such data. The remainder part is "thrown away", i.e....

Comparison Operators and Conditions

A moment ago, we "just used" an if statement without looking too closely at its general form.

Before we can talk sensibly about control structures, we need to define another term: Comparison Operator

"Less than" (symbol <) is a comparison operator. We can use it to ask about the relationship between two things. We can say....

iHowLong < 80

... in places where we want to as, "Is the number stored in the variable iHowLong less than 80?" This would boil down to "true" if iHowLong was holding, say, 50, but "false" if iHowlong were holding 100.

Comparison operators can be used when building conditions.

A condition looks like....

value ComparisonOperator value

In our previous example, "iHowLong < 80", iHowLong was a value, because it boils down to a number, < was the comparison operator, and 80 was the second value.

Conditions always "boil down" to "true" or "false".

There are some other comparison operators:

In our program, where iHowLong started at 800, and we were subtracting 20 from it each time, the "if" statement which put iHowLong back to 800 when it got too low could have been....

if (iHowLong = = 80) {iHowLong=800};

There will come a moment when iHowLong equals 80. But it wouldn't be a very good idea. Safer to use the "less than" test. If we decide to make iHowLong smaller by, say, 75, on each pass through the loop, then eventually iHowLong will be 125, and after 75 is subtracted again, iHowLong will be 50... less than 80, but never equal to 80, so the "iHowLong=800" will never happen.

BE CAREFUL when entering an "is it equal?" condition operator. It is TWO equals signs. If you write....

if (iHowLong = 80) {iHowLong=800};

... the compiler may process it as if nothing's wrong. But if it does, the statement won't do what you wanted done.

There's another group of conditional operators to get out of the way before we talk about using conditional operators: The boolean operators

If the values in the condition are Boolean, i.e. things that boiled down to "true" or "false", then you can use....

A condition always boils down to "true" or "false".

So! Now that we know what a "condition" is, we can look at....

Control Structures

You've already met one! The "if" statement we saw earlier is a control structure. It controls the program's execution, sometimes allowing execution of, sometimes not allowing execution of, a bit of code... the "iHowLong=800" part in our example. (N.B. in "iHowLong =800" we are making iHowLong hold 800. We aren't asking if it does hold 800. This is because we used a single equals sign. If we wanted to ask "Does it hold 800?" we would use two equals signs.)

The simple form of the "if" statement looks like this:,/p>

if (condition) {statement};

Here we have a statement (the "if" statement) that has another statement as a constituent part. (And remember: That constituent statement may itself consist of numerous statements "joined together".)

Even the simplest "if" statement will have two semicolons: One at the end of the "if" statement, shown above, and one at the end of the embedded statement, not shown above, because you "know" there's always a semicolon at the end of a statement. If I'd written the general definition with an extra semicolon, i.e. like....

if (condition) {statement;};

... then my more logical readers justifiably would infer that the following would be a correct "if" statement:

if (iHowLonjg<80) {iHowLong=800;;};

(That has an extra semicolon in it, just after the 800).

Notice the way the brackets are used in the "if" statement. The condition is delimited by plain brackets, i.e. "(" and ")". What is to happen when the condition boils down to "true" is delimited with the curly brackets, "{" and "}".

Let's look at another control structure. We can accomplish exactly the same thing we did before, a winking LED that winks faster and faster up to a point, and then starts at the 800ms on/ 800ms off state again, merely by changing the "loop" function to...

void loop ()
{
      do
      {
      winkLED;
      iHowLong=iHowLong-20;
      }
      while (iHowLong>80);
iHowLong=800;
}

Here we are using the "do... while" statement, which, in general, consists of....

do {statement;}  while (condition);

The first thing to notice in the example is that there's a pair of {}s inside a second pair. The outer pair define the extent of "loop". The inner pair define the statement(s) to be executed while the condition remains true. Just "English", really, but you need to approach it with cold logic.

What you're seeing is called bracket nesting. It can get a bit tedious, but it is necessary and useful. And the Arduino development environment has a nice feature: When your cursor is at a bracket, the other bracket of that pair will be highlighted. This can be very helpful when you're fixing a left out a bracket or an extra one.

Note also the way that the indenting of lines help you see what lines are part of the code that happens until the condition is true.

Here's an example of bracket nesting used in defining a condition:

if ((it is raining) and (it is cold))...

That is only true when both it is raining and it is cold. The brackets help you see that, I hope. While the example is "non computer", you will meet the computer equivalent frequently.

There's another form of the while statement. In our case, we can use either with reasonable... but not exactly identical... results. There are times when the difference in the results is more profound. Here's the alternative in action:

void loop ()
{
      while (iHowLong>80)
      {
      winkLED;
      iHowLong=iHowLong-20;
      }
      ;
iHowLong=800;
}

... and here's the general form of the alternate "while":

while (condition) {statement;};

We're still creating a way for something to happen over and over, though not necessarily forever, but this time we've done it without the "do".

Moving on.

Suppose you want to do something 5 times. Easy. The following will, over and over again, as that's the nature of the loop function, wink the LED 5 times, and then "die" for 6 seconds, before winking the LED 5 times again, etc, etc.

void loop ()
{
for (byte i=1; i<6; i=i+1)
      {
      winkLED;
      }
      ;
delay(6000);
}

The general form of the "for" statement is as follows:

for (init;condition;change) {statement;};

The "init" should remind you of a variable declaration, because that is what is going on. The variable is local to the "for" statement, that is it is created as the statement begins to execute, and forgotten about again after the "for" statement finishes. "i" is the traditional name for the variable you create to control the loop, but it can be whatever you like.

The "condition" is just like the ones we were discussing before. When it is false, the "for" loop stops looping.

The "change" should change what's in the variable that controls the looping, and the program should be written so that eventually the "condition" is false because of the value the variable has reached.

Note the "extra" semicolons "inside" the statement. What you see is a single, simple statement. You can, as always, "stick" it to another statement by using a semicolon, but what we see above defines one statement. The semicolons are used a little eccentrically here. Do not imagine that "for (init;" could stand alone as a statement just because you see the semicolon.

A neat little shortcut for you: If you want to say "i=i+1", you can do it with "i++". The result of executing either is identical.

Moving on....

The Arduino language also has a "switch... case" control structure. We can't illustrate it with our LED winking program, but it can be very useful. The basic structure is....

switch (variable) {
   case 1:statement to do when variable holds 1;
       break;
   case 2:statement to do when variable holds 2;
       break;
   case 3:statement to do when variable holds 3;
       break;
...
... etc
...
   default:statement to do when
        variable didn't hold one of the
        values provided for explicitly.
      };

Note the unusual "extra" semicolons "inside" the statement.

Note also the word "break". Let's say that we were using bTmp as the variable. If the program came to this "switch case" statement with bTmp equal to 2, the line you'd expect to be executed to would be. But without the "break"'; the line that looks like it should happen only if bTmp holds a three would ALSO be executed.... I think. It shouldn't be like that, but I think things behaved like that in one of my programs. The "break" will ensure that it doesn't! (Of course, if the statement that is executed when bTmp is 2 happens to be "bTmp=3", then it is not unreasonable that the "case 3" line executes as well if there is no "break".

Moving on...

There is an extended version of the "if" statement that looks like this....

if (condition)
    {statement1}
  else
    {statement2};

Have a look at that. Don't let my explanation get in the way. It merely does the obvious: If the condition is true, then statement1 gets executed; if not, statement2 gets executed.


Inputs, and more on function declarations

We have already declared one function: winkLED. We've crafted our own versions of "setup" and "loop" by changing the "guts" of their declarations to suit our purposes.

But so far, our function declarations have always begun with void, and we've always had an empty pair of brackets, i.e. "(" and ")", after the function's name.

For the sake of further discussion, imagine that pushbuttons have been fitted to pins 2 and 3 of the Arduino. They have been wired up so that when pushed, they switches connect the pins to 0 volts ("ground") and when not pushed, the pins are, individually, connected to 5v through a 10k resistor. (This is called a "pull up" resistor, and there are ways to get around having to include one, but for now we'll do things the easy- to- explain way.) (Yes... when the button is presses, the 10k resistor is also connected to ground, and some current will flow through it from the end connected to 5v. It will be okay.)

With switches wired thus, you can say iTmp=digitalRead(2);, or iTmp=digitalRead(3);.... providing you have declared a variable called iTmp. If the button is pressed, iTmp will be left with "1" in it, otherwise iTmp will be holding zero.

If you do pinMode(2,INPUT); during the "setup" function, no harm will come of it, but you don't need to. All of the Arduino's pins are set for input when the power comes on or the computer is reset, even before "setup" is done. This is a "fail safe" design: You can connect 0 volts or 5 volts, or anything in between to an input without hassle or damage. However, once a pin is set up for output, you have to be more careful. Don't create circuits which would cause currents higher than 40mA if the pin were to go to 0v or to 5v. For instance, you really don't what such a pin directly connected to 0v or 5v.... if connected to 5v, and the pin went to 0v, you would theoretically get infinite current. Something would fry first, but that is not a desired outcome!

So! We have our Arduino provided with two push buttons. Now add another LED and resistor, using pin 12, bringing the total up to two LEDs.

Now we can go back to doing fancier function declarations. The following is an example:

int buttons ()
int iState2=0;
int iState3=0;
int iTmpAns=0;
{
if (digitalRead(2) = = 1) {iState2=1};
if (digitalRead(3) = = 1) {iState3=1};

if ((iState2 = = 0) && (iState3 = = 0))
        {iTmpAns=0};
if ((iState2 = = 0) && (iState3 = = 1))
        {iTmpAns=1};
if ((iState2 = = 1) && (iState3 = = 0))
        {iTmpAns=2};
if ((iState2 = = 1) && (iState3 = = 1))
        {iTmpAns=3};
return iTmpAns;
}

That code declares a function called "buttons". If you use the "buttons" word, i.e. if you put it into your program somewhere the way we put the "winkLED" word into our earlier program, then it will "boil down" to a 0, a 1, a 2 or a 3. Here's the "buttons" word used in a program....

void loop ()
int iStateOfButtons=0;
{
iStateOfButtons=buttons;

switch(iStateOfButtons) {
   case 0:
       digitalWrite(12,LOW);
       digitalWrite(13,LOW);
       break;

   case 1:
       digitalWrite(12,HIGH);
       digitalWrite(13,LOW);
       break;

   case 2:
       digitalWrite(12,LOW);
       digitalWrite(13,HIGH);
       break;

   case 3:
       digitalWrite(12,HIGH);
       digitalWrite(13,HIGH);
       break;
    };
}

The above program would "watch" the two buttons, and show the binary numbers 0, 1, 2 or 3 depending on whether neither, only the first, only the second, or both buttons were pushed, respectively.

In particular, the above illustrates that a function declaration does not have to start with void. It can start with any variable type. And when it doesn't start with void, you will expect to find a line in the function saying return, and followed by something of the same data type as the function.

("return" can also be used to trigger a premature return from a function during debugging work.)

What about the until- now- always- empty brackets after the identifier on the first line of the function declaration? Study the following. It is a re-write of the program we just had.

void loop ()
int iStateOfButtons=0;
{
iStateOfButtons=buttons;

switch(iStateOfButtons) {
   case 0:
       showByLEDs(0,0);
       break;

   case 1:
       showByLEDs(0,1);
       break;

   case 2:
       showByLEDs(1,0);
       break;

   case 3:
       showByLEDs(1,1);
       break;
    };
}

void showByLEDs(b0 byte; b1 byte;)
{
    if (b0==0)
         {digitalWrite(12,HIGH);}
      else
         {digitalWrite(12,LOW);};

    if (b1==0)
         {digitalWrite(13,HIGH);}
      else
         {digitalWrite(13,LOW);};
}

In the above, we created another function, showByLEDs, to "package" the part of the code responsible for switching the LEDs on or off. When we called showByLEDs, we "passed parameters" to the function. Whatever numbers are in the brackets after showByLEDs at the point where the function is called get passed into b0 and b1 prior to the function's execution.

Notice the way that the indenting has been used to try to help the reader see which statement is executed in each circumstance. Notice how the two sections which more or less copy one another in function also copy one another in appearance


Hurrah!

The above pretty well covers the hard concepts involved in everyday Arduino programming. Now we can turn to mopping up odds and ends, and some advanced topics.

Further output options.

For the sake of the remaining discussions, we're going to assume that you Arduino has an LCD panel on which it can write messages. These output devices aren't expensive either in terms of case (about $30, if you assemble a kit... easy) or in terms of tying up pins of your Arduino. (Uses one.)

To use such a panel you should put....

Serial.begin(9600);

... in the setup function. Having done that, you have the Arduino do....

Serial.print("Hello world");

... to put text on the LCD panel.

If you want to display a number which is stored in a variable called iMyNum, you simply have the Arduino do....

Serial.print(iMyNum);

If you want to print Hello world on one line, and then whatever's in iMyNum on the next, you would use....

Serial.println("Hello world");
Serial.print(iMyNum);

(Without the "ln" (that's "ell" "en", as in "LIne") to start a new line, the number in iMyNum would be on the same line as the "Hello World".)

So! On to further work, now that we have a way to display answers.

The following topics remain. You can look at them in any order. This scheme of categories is drawn from the official Arduino site's scheme.

Well! Done?

I think that pretty well covers "all there is to know" about programming an Arduino. Over to you. Have fun!

If you notice any gaps in my coverage of programming the Arduino, I'll be pleased to hear from you. Note that this page doesn't attempt to teach you to program, only to tell you about the Arduino environment. I do have a series of tutorials if you want help with how to program. If you want help with the hardware side of things, you might want to visit my Sensing and Control, or my Electronics pages.





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 Software... my main 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 .....