The Arduino Inventor's Guide (9 page)

When writing sketches in Arduino, you need to be very specific with the words, punctuation, and capitalization you use. These elements are part of a programming language’s
syntax
. For the IDE to
compile your sketch properly, you must use words that it recognizes. These are called
keywords
, and you’ll notice them when they change to a different color, such as orange, teal, or green. Now, let’s look at some of the features used in this first sketch in detail.

Key Sketch Elements

At the top of the sketch, you declare a new
global namespace

. This is a space that describes what the sketch does and often includes other information such as variable initializations and library statements. Nearly every sketch will include a namespace. This sketch’s namespace has comments written to help human readers understand what the sketch does. In the Arduino IDE, comments are gray. Every comment either starts with the characters
//
or is bounded by the symbols
/*
and
*/
if the comment is longer than a few lines. Notice that not all comments come between lines of code; some appear on the same line as the code they clarify. This doesn’t affect the sketch, because comments are ignored by the IDE. Unlike with code, you can write anything you want in the comments using regular words, spelling, or punctuation.

The skeleton of any sketch consists of two main function definitions,
setup()

and
loop()

. A
function
is simply a way of grouping multiple instructions or lines of code together. Each function has a data type, a name, and a group of instructions. The word before the function indicates the type of data the function will return. Both
setup()
and
loop()
have the type
void
because they do not return any values.

The name of every function includes a set of parentheses. These parentheses are where you pass
parameters
to the function. Parameters are values that a function needs to do its job. Neither
setup()
nor
loop()
needs parameters, but you’ll use some functions in later projects that do need them. Finally, the lines of code that make up the function are grouped by an opening curly bracket,
{
, and closing curly bracket,
}
.

The
setup()
and
loop()
functions are required for every Arduino sketch; when the Arduino is turned on for the first time or is reset, the
setup()
code runs once and only once, and
loop()
code repeats continuously over and over. It’s like baking cookies: instructions in
setup()
get out all of your tools and ingredients, and
loop()
bakes batches over and over until you turn off the oven (that is, the Arduino).

Now, let’s figure out what each line of code in
setup()
and
loop()
is actually doing.

The setup() Function

First, let’s take a closer look at the Blink sketch’s
setup()
function; see
Listing 1-2
.

LISTING 1-2:
The
setup()
code for our Blink example

void
setup
() {
  
//initialize digital pin LED_BUILTIN as an output
  
pinMode
(
LED_BUILTIN
,
OUTPUT
);
}

The only line of code inside the
setup()
function is a call to the
pinMode()
function. Pins 0–13 on the Arduino are considered
general-purpose input/output (GPIO) pins
. They can be used as either inputs or outputs, and
pinMode()
allows you to tell the Arduino how you plan to use a digital pin. You do this by passing two parameters. The first is the pin number, and it can range from 0 to 13. The second parameter is the pin configuration.

For the pin reference, the Blink sketch uses a system constant called
LED_BUILTIN
to specify that you’re using the default LED on the device. On most Arduino devices, this is the same as pin 13. Notice that the value is in all caps and colored dark teal. This color indicates that
LED_BUILTIN
is a special keyword with a predefined value used in the IDE.

The second parameter defines the pin configuration as an
OUTPUT
. Notice that the keyword
OUTPUT
is also dark teal because it is another constant used in Arduino. There are a few other choices here, which we’ll cover in detail in
Projects 4
and
9
, but for now just note that Blink sets the pin as an
OUTPUT
for the LED.

If you were to describe this line of code as a sentence, it would say, “Tell pin 13 to output from the Arduino.”

NOTE

The
pinMode()
function follows a capitalization convention called
camel case.
In camel case, the first letter is lowercase, and any later letters that start words are capitalized.

The very last character in the
pinMode()
call is a semicolon (
;
), which marks the end of a line of code. When you start writing your own sketches, always end a finished line of code with a semicolon. If you forget one, don’t worry; nearly everyone who’s ever programmed forgets a semicolon eventually, so the Arduino IDE will show a handy warning to help you figure out where to put the missing punctuation.

WHERE’S THE MAIN() FUNCTION?

If you know a bit of programming or are familiar with C or C++, you might wonder where the
main()
function is in Arduino sketches. When you click Verify/Compile or Upload, Arduino actually pulls together a lot of other files behind the scenes—including a file called
main.cpp
. Dig around the Arduino program folder, and you can find all the nitty-gritty details of what’s going on. Remember, it’s open source!

Here’s a snippet of code from the
main.cpp
file:

  int main(void)
  {
    init();
    initVariant();
  #if defined(USBCON)
    USBDevice.attach();
  #endif

   setup();
    for (;;)
    {

   loop();
    if (serialEventRun) serialEventRun();
    }
    return 0;
  }

See where the
setup()
function is called at

? And notice that the
loop()
function

is inside a forever loop; Arduino implements a forever loop using an empty
for(;;)
. That’s how it runs continuously.

The loop() Function

Now let’s look again at the
loop()
function, which executes each instruction from top to bottom and repeats itself forever. See
Listing 1-3
.

LISTING 1-3:
The
loop()
code for the Blink sketch

void
loop
() {
  
digitalWrite
(
LED_BUILTIN
,
HIGH
);  
//turn the LED on
                                    
//(voltage level is HIGH)
  
delay
(1000);                      
//wait for a second
  
digitalWrite
(
LED_BUILTIN
,
LOW
);   
//turn the LED off
                                    
//(voltage level is LOW)
  
delay
(1000);                      
//wait for a second
}

The
digitalWrite()
function allows you to turn the Arduino pins on or off; this is called controlling a pin’s
state
. This function also uses two parameters. The first indicates the pin you want to control; in this case, we’re using the system constant
LED_BUILTIN
again. The second parameter is the state you want the pin to be in. To turn the light on, the Blink sketch passes in
HIGH
. To turn the light off, it passes in
LOW
.

The second instruction is
delay()
, which delays your sketch by the number of milliseconds you pass as its parameter. The Arduino Uno and derivative boards like the SparkFun RedBoard execute 16 million instructions per second; that’s really fast! It’s so fast, in fact, that without a delay, you’d never notice a change in the LED. The delay lets us control how long the LED stays on. In the example,
delay(1000)
instructs the Arduino to delay for 1,000 ms before executing the next command.

The next two lines of code are similar to the first two; they simply instruct the Arduino to turn the LED off and delay another 1,000 ms. After the last line, the
loop()
function repeats from the top and turns the LED back on.

HACK THE (HELLO) WORLD

One of the best ways to learn from example code is by changing what it does. Try decreasing the delays to
500
. Click
Upload
. How did the blink change? What if you pass
delay()
the number
5
instead? This is a 5 ms blink! Can you see it? What is the fastest blink rate that you
can
see?

Your First Piece of Hardware

With the LED on your board working and blinking away, the next step is to add your first piece of hardware: an external LED. As we mentioned, the pins on the Arduino are used for hooking up inputs and outputs to the microcontroller, and we can demonstrate that simply with an LED. Grab an LED and take a close look at it. It will look something like
Figure 1-20
.

You’ll notice that the LED has a short leg and a long leg. If you look really closely, you’ll also see that the edge of the LED bulb has a flat surface on the same side as the short leg. These help you
identify the
polarity
of the legs; the LED’s long leg is the positive leg, and the short leg on the side of the flat bulb surface is the negative, or ground, leg.

FIGURE 1-20:
An LED showing the long and short legs

Remember that
LED_BUILTIN
refers to pin 13 on the Arduino. So, adding your LED to the Arduino is as simple as plugging the long leg of the LED into pin 13 and the short leg of the LED into the GND (ground) pin right next to pin 13. Insert the LED now, with your board powered. If you plug it in correctly, as shown in
Figure 1-21
, the LED will start blinking. If the LED doesn’t blink, you probably have it plugged in backward. Not to worry: pull it out and flip it around.

FIGURE 1-21:
An LED added to pin 13 the quick and dirty way

GOING FURTHER

Each project in this book will have a “
Going Further
” section, which describes ways to take the concepts you learned in that project to the next level. These sections will include advice on using the existing project, hacking the code, and modifying the project physically.

Hack

For this project, we suggest you try to create some nifty blink patterns. First, copy and paste the four lines in the
loop()
function so that it repeats and you end up with eight lines of code. This gives you two blink sequences and more code to work with. You can create patterns by modifying the delay times to control when the
LED lights. For example, we made a pattern that looks like a heartbeat; our modified Blink sketch is shown in
Listing 1-4
.

LISTING 1-4:
Example code of a heartbeat pattern

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

Other books

Loving the Tigers by Tianna Xander
Rip It Up and Start Again by Simon Reynolds
Bone Mountain by Eliot Pattison
Cutlass by Nixon, Ashley
Fire and Forget by Matt Gallagher
The White Dominican by Gustav Meyrink
Erased From Memory by Diana O'Hehir