Learn to Program in Arduino C. 18 Lessons, From setup() to...

Learn to Program in Arduino C. 18 Lessons, From setup() to Robots

William P. Osborne
5.0 / 0
你有多喜欢这本书?
下载文件的质量如何?
下载该书,以评价其质量
下载文件的质量如何?
The lessons in this book offer an accessible STEM curriculum. Classes based on it are currently taught in a growing number of high school classrooms. Students and teachers alike are supported on the companion website, www.LearnCSE.com.
Aided by more than 250 color photos, illustrations, and diagrams, the lessons and exercises in the book teach how to program and use the Arduino singleboard computer. In the process, the reader learns: How to program in C, the language underlying the most commonly used programming languages How to identify and use common electronic components and sensors How to perform electronics-specific tasks, such as creating a circuit board How to construct, program, communicate with, and control robotic devices, including servos, LEDs, DC motors, infrared communicators, push buttons, potentiometers, NeoPixels, and H-bridges. Sample code provides starting points in each of the lessons.
Through all of this, the reader is connected to career paths where these skills are in high demand. Best of all, the reader gets excited about learning how to program. LearnCSE’s methods are designed for hands-on learners they stimulate creativity as well as problem solving and critical thinking.
内容类型:
书籍
年:
2017
出版社:
CreateSpace
语言:
english
页:
289
ISBN 10:
0998128716
ISBN 13:
9780998128719
文件:
PDF, 5.73 MB
IPFS:
CID , CID Blake2b
english, 2017
pdf, 5.73 MB
正在转换
转换为 失败

关键词

 

Learn to Program
in Arduino™ C:
18 Lessons, from setup() to robots

William P. Osborne holds a BSEE and an MIT (master's degree in teaching) from
Seattle University and an MBA and an MS from Stanford University. His career has
included consulting to technology manufacturers, running a small software company,
and ten years at the Microsoft Corporation, primarily in the Windows operating system division. He teaches computer science and engineering at a public high school.
© Copyright 2017, William P. Osborne
Earlier versions of this book were shared on the author's website, LearnCSE.com.
Printed in the United States of America
Published by Armadillo Books
Printed by CreateSpace
ISBN: 978-0-9981287-1-9
Edited by Margo Paddock
Book design by Margo Paddock
Cover design by Abby Osborne
Photographs by Abby Osborne and Caroline Osborne
Although the electronic design of the Arduino™ boards is open source (Creative Commons CC-SA-BY License) the Arduino™ name, logo, and the graphic design of its
boards are protected trademarks of Arduino LLC (USA).

Introduction
he Arduino™ is an extremely popular single-board computer that can be used to make a vast variety of intelligent devices. With this book you will learn how to work with the Arduino™ itself, to
identify and control common electronic components used with an Arduino,™ and, most important
of all, to write programs for the Arduino.™
his book is for you if you want to understand, program, and use the Arduino™ to make things
that work. It is also for you if you want to teach Arduino™ programming. We believe this mastery
is valuable for three reasons:
1. Industry demands and career opportunity: he key component of the Arduino™ is a microcontroller from the Atmel Corporation. Learning to program and apply an Arduino™
is also learning to program and apply a microcontroller, a skill that is in heavy demand in
industry.
2. As a basis for learning other programming languages: he Arduino™ is programmed in a
version of the C programming language. Consequently, knowledge of the;  syntax of Arduino™ C transfers to learning higher-level languages, including C++, C#, Java, and Python,
which are all currently used in industry.
3. Satisfaction and fun: he Arduino™ can be used as the computing component for many
diferent kinds of devices. Students who have completed the lessons in this book have gone
on to design, build, and program robots that walk, sensors that record and report data,
musical instruments, and quadcopters that ly, among other things.
You will guide and pace your own learning. Each lesson builds upon and extends the content of
the preceding lessons. And each lesson is constructed as it would be presented in a classroom, beginning irst with key concepts and ending with exercises in applying that knowledge:
Big Idea: he major concept or skill the lesson conveys. Everything else in the lesson supports
this idea.
Background: he underlying theory, and, when appropriate, the science behind the content
of the lesson. Understanding the background of new material enhances your ability to apply
that knowledge.
Vocabulary: New terms are highlighted in yellow when they introduced in text. hose terms
and their deinitions are also conveniently arranged in a table (with a yellow banner heading)
for reference.

Description: Further detail of the concepts covered in the lesson and other information that
will put the lesson's procedure and exercises into the context of the Big Idea.
Goals: he speciic set of concepts you will learn and skills you will develop while completing
the lesson.
Materials: A list of the electronic materials and tools used in the lesson. Each item on the list
has a number linking it to a Parts Catalog (available at LearnCSE.com), which provides information about where the part can be purchased.
Procedure: A set of ordered steps for conducting the experiment or building the project that
illustrates the content of the lesson.
Exercise(s): A set of one or more additional experiments or projects you can do in order to
apply and reinforce what you have learned in the lesson.
Support in the form of sample programs (referred to as "sketches") for the Arduino,™ FAQs, the
Parts Catalog, new topics and projects, and a blog can be found at  .
he lessons in this book have been classroom tested. Students have created projects of their own
designs based on what they've learned with earlier versions of these lessons. hey have made model
helicopters and airplanes, elaborate rolling robots, musical instruments, light panels, keyboards to
drive synthesizers, "laser" tag games, hover boards, Segway-like vehicles, and more.
Whether you are exploring this book for yourself or to teach others, I hope you ind the content
engaging and useful. I invite you to share your thoughts, suggestions, and cool projects of your
own. Visit us anytime at  .

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

Lesson 1
LESSONS

Lesson 1: Microcontrollers and SBCs

Microcontrollers and SBCs

The Big Idea:
This book is about computer science.
It is not about the Arduino,™ the C programming language, electronic components, or the mathematics of electricity—even though we refer to them extensively in the lessons in this book.
The Arduino,™ the C programming language, electronic components, and
the mathematics of electricity are the tools this book uses to teach computer
science.
hese tools allow readers to learn by doing, to learn with their hands. Every lesson is either an experiment or a project. Some projects, lighting LEDs, for example, are simple. Others are complex.
Laser tag is an excellent example. But simple or complex, none of the projects does anything unless
some computer science has been applied to bring them to life.

Background: What, precisely, is computer science?
For the purposes of this text, computer science is the application of numbers and logic to make
devices, algorithms, and languages that, together, can model just about anything. his book uses
the tools listed in Table 1-1.
Table 1-1. Tools this book uses
Tool Description
devices The Arduino™ family of Single-Board Computers (SBCs).
algorithms The collection of programming techniques, tools, and libraries we use to
build our models.
language The C programming language.

Lesson 1

Microcontrollers and SBCs

1

he key word is model. Consider Table 1-2, examples of the uses of models in computing.
Table 1-2. Examples of models in computing
Example

What is modeled

How model connects to world

League of
Legends

A fantasy world where Players (humans) participate by controlling
characters possess mag- the actions of some of the characters. High
ical and physical powers. quality graphics and game play allow the
user to suspend disbelief and pretend the
world is real and that the player is actually
the character being controlled.

Digital medical The detailed densities of By collecting data about minute movement
imaging via Mag- the portions of the body of molecules in response to a changing
netic Resonance being scanned.
magnetic ield, a model of the scanned object is created. This model is presented to
the user as startlingly detailed 2D and 3D
images of what would be found if the subject were opened surgically.
Microsoft Word

The appearance of formatted text as if it were
typed directly onto a
piece of paper.

The user can add to and modify both the
content and appearance of this text and can
cause a copy of the model to be printed on
paper.

Aircraft Autopilot The stable light of an air- The computer collects data (speed, direction, physical orientation of the aircraft, alcraft.
titude) and uses the model to control wing
surfaces and engine speed.

Notice that in each case the computer creates and maintains a model. hat model might be something that exists in reality or something entirely ictional. And the output from the model may
be information that appears on a screen, instructions that control physical devices, or a physical
product, such as text or graphics printed on paper or plastic.
he important takeaway is this: all computer programs are models.
he lessons in this book contain experiments and projects that explore concepts and build models that control lights, make sounds, run robots, turn motors, detect and compose messages, and
more. Some of these models will collect and respond to data from their environments. Some will
provide text as their output, and others will control physical devices. But every experiment and
project is controlled by an Arduino™ running a model of what is being built. And, that model will
be written with the C programming language.

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

Table 1-3. Vocabulary

1

Term Deinition
algorithm A means of or steps to performing a speciic
task. For a computer, an algorithm is usually expressed in a set of computer program instructions.
Arduino™ A single-board computer and an open-source
electronics platform based on easy-to-use
hardware and software. It's intended for anyone
making interactive projects.
C programming language The programming language used to write sketches for the Arduino™ SBC. The syntax is similar
to several other commonly used programming
languages, including C++, C#, and Java.
Integrated Development Environment A collection of computer programs used to cre(IDE) ate other computer programs.
microcontroller A complete self-contained computer in a chip,
including the memory for a program and its
data. This small microprocessor also contains
the necessary electronics to communicate with
external devices.
microprocessor A complex electronic integrated circuit that performs the processing tasks of a computer, including input, output, and computation.
output Information of any sort that comes out of a computer.
single-board computer (SBC) An entire microcomputer on a single printed circuit board. Abbreviated SBC. Examples include
the Arduino™ and the Raspberry Pi.
sketch A computer program written for the Arduino™.

Description:
Arduino™ is a name given to a family of single-board computers (SBCs). he particular family
member used in lessons in this book is the Arduino™ Uno. All Arduinos™ contain an integrated
circuit called a microcontroller. A microcontroller is a small but complete microprocessor capable
of input, output, and computation. In addition, a microcontroller includes storage memory for a
computer program and its data.

Lesson 1

Microcontrollers and SBCs

Figure 1-1. The Arduino™ Uno

Surrounding this microcontroller are the electronic components, connectors, and rows of sockets
necessary to bring power to the microcontroller, allow it to receive information from the outside
world, and to transmit information.
he term single-board means that the entire computer its on a single circuit board. Diferent members of the Arduino™ family have diferent features. Some are small and light enough to be sewn
into clothing, while others are suiciently powerful to perform complex tasks very quickly. But
they are a family in that they are all programmed with the same language. he syntax of this language is so very close to C that it is referred to as the C language. Mastery of this language serves as
an excellent base for other commonly used programming languages, including C++, C#, and Java.
he upcoming lessons explore most of the features of the Arduino™ Uno. his irst lesson begins
with installation and testing of the set of computer programs used to write and install Arduino™
sketches. his collection of computer programs is called the Arduino™ Integrated Development
Environment (IDE). A program written for the Arduino™ is called a sketch.

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

Goals:

1

By the end of this lesson you will:
1. Know the purpose of an Integrated Development Environment (IDE).
2. Know how to locate, download, and install the Arduino™ IDE.
3. Be able to modify, save, upload, and run simple sketches for the Arduino.™
4. Know that sketch refers to a computer program written for the Arduino.™

Materials:
Quantity

Notes

Catalog
Number

Arduino™ Uno

Single-board computer. This
board is delicate and should
be handled with care. When
you are not using it, keep it in
a box or plastic bag.

3102

1

USB Cable

This is the standard USB
adapter cable with the lat
connector on one end and
the square connector on the
other.

2301

1

Computer with at least
one USB port and access to the Arduino™
website,
 

The operating system of this
computer must be Windows,
Macintosh OS/X, or Linux.

---

1

Part

Image

---

Procedure:
These instructions are for Windows and will work in most situations. For Macintosh
and Linux, refer to the instructions on the Arduino™ website:
Important  

Lesson 1

Microcontrollers and SBCs

Part I: Download, install, and test the Integrated Development Environment
1. Open Internet Explorer or another Internet browser and navigate to
the Arduino™ website  .
Arduino.cc.

2. Locate the "Download" section of
the page and select [Windows].
his will begin the download of the
package that will install the IDE.

3. Double-click the Arduino™ icon.
A warning message may appear.
If it does, click the [Run] button.

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

4. he IDE work space should then
appear.

1

Part II: Connect and test the Arduino™ Uno
1. Connect the Arduino™ Uno to the computer using the USB cable. A small green light should
appear on the Arduino,™ indicating it has power.
A small message may appear in the lower-right tray of Windows indicating to which COM
port the Arduino™ is assigned. If it does, remember it because it may be needed later.
2. Click the [Tools] menu at the top of the IDE. From the dropdown menu select [Board], and
from that menu select [Arduino™ Uno].

Lesson 1

Microcontrollers and SBCs

3. Select [File]. From the dropdown menu,
select [Examples], then [Basics], then
[Blink]. An Arduino™ program, called
a sketch, will appear in the IDE. Notice
that the name of the sketch, Blink, is
in the tab.

4. Verify the IDE is communicating with
the Arduino™ by clicking the [Upload]
button on the IDE toolbar.
If communication is successfully established, the message "Uploading to I/O
board" will appear at the bottom of the
IDE. It will be followed by the message
"Done uploading." A small light should
now be blinking: on for one second, then
of for one second.

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

Exercises:

1

Exercise 1-1. Verify success of Blink sketch

1. Under the File menu is a submenu
called Preferences. Open [Preferences]
to verify that the Sketchbook location
is the Arduino™ folder in Documents.
hen click [OK] at the bottom of the
screen.

2. Save the Blink sketch as MyBlink
by selecting the [File] menu, then [Save
as], then naming the ile [MyBlink].
Click the [Save] button.
Notice that the tab in the IDE should
now say [MyBlink].

Lesson 1

Microcontrollers and SBCs

3. Modify the MyBlink sketch to make
the light blink on and of at half-second intervals by changing the number
1000 to 500 in the two delay statements. Don't be concerned about understanding the sketch at this time. he
intent of this step is simply to verify the
proper operation of the Arduino™ Uno
and the IDE.

4. Save the modiied sketch by selecting [File] then [Save].
5. Upload the sketch to the Arduino™. If you're successful, the light should blink twice as fast
as before.
Exercise 1-2. Verify sketch runs on Arduino™ and experiment with
time delays

1. Verify that the modiied sketch is, in fact, running on the Arduino™ and not on the computer to which the Arduino™ is connected. his can be done by unplugging the Arduino™ from its USB cable and providing power to
the Arduino™ by means of a wall-plug power supply (3101 in Parts Catalog) or a battery pack.
Note: he light should blink even though the Arduino™ is now independent of the computer.
2. he number used in the delay statement, delay(500);, is a measure of time in milliseconds. he number "500" is 500 milliseconds, or one half second. his is a common technique
used to save power. For example, roadside lashers turn their lights on for short periods of time
while leaving them of for a longer period. Experiment with the values of MyBlink to ind
the shortest blink time that still appears to be long enough to be noticed by a casual observer.

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

3. Experiment with at least six values of delay for time on.

1

Set the delay for the light of to be one second. hat is 1000 milliseconds. Complete Exercise Table 1-1.
Exercise Table 1-1. Time delay experiment table
Condition Time On, in Milliseconds
Light on longer than necessary:
___________
Light not on long enough to be noticed reliably:
___________
Optimal time on: ___________

Lesson 1

Microcontrollers and SBCs

Lesson 2

Lesson 2: Communicating with the ArduiCommunicating with the Arduino™
no™

The Big Idea:
An Arduino™ can be programmed to send messages to and receive messages from the computer
being used to write and upload sketches. A feature called the serial port makes this communication
possible. his lesson shows how to use the serial port to send messages from an Arduino™ sketch
and to use a feature of the Arduino™ IDE called the Serial Monitor to view those messages.

Background:
Any computer must have, at a minimum, the features listed in Table 2-1.
Table 2-1. Computer features, purposes, and examples
Feature

Purpose

Examples

input

To receive information from the Keyboard, mouse, network connection,
outside world.
touch screen, voltage sensor

output

To display information or to con- Monitor, lights, printer, motor, network control devices.
nection

processor

To manipulate information.

storage

To contain programs to be run Memory, hard disk, cloud storage
and data to be accessed.

Intel Core i5, Atmel ATmega 328

Serial Port
he Arduino™ is a complete computer possessing each of the features listed in Table 2-1. In this
lesson, you will have the opportunity to write your irst Arduino™ sketches. he sketches take
advantage of the output ability of the Arduino™ to send text messages to the Arduino™ Integrated
Development Environment (IDE) via a built-in serial port. his port is composed of some electronic components speciically designed to send data to and receive data from another device, in
this case a computer via USB, some special hardware designed to communicate text. he port can
also send data out pin 1 of the Arduino™ and receive it via pin 0. hese pins are marked TX for
transmit and RX for receive.

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

2

Figure 2-1. USB connector and pins controlled by the serial port
he ability of the port to transmit and receive data is very handy. It is especially useful for discovering why sketches don't always operate as expected. he process of ixing things that are wrong
with a sketch is called debugging. A common technique for debugging is building into a sketch the
sending of text messages to the IDE.

The Arduino™ Sketch
To make use of the serial port, or any other feature of the Arduino,™ a sketch is required. A sketch
is a collection of instructions for your Arduino.™ A speciic instruction within a sketch is called a
programming statement. An example of a statement is shown in Example 2-1.
Example 2-1. Programming statement
Serial.print("Hello");

Programming statements end with a semicolon.
Note

he programming statement in Example 2-1 instructs the Arduino™ to send the word "Hello"
out the serial port.
Statements that, taken together, perform a speciic task may be grouped and named. Such a group
is called a method. A method is a collection of programming statements that, when executed in
order, perform some subtask essential to the overall purpose of the sketch. If the sketch operates
a robot, for example, one subtask is to detect surrounding obstacles. Another subtask controls
motors. Yet another detects and decodes messages from a remote control. Each of these subtasks
appears in the sketch as a method. Each method has a name, parameters, a return type, and some
programming statements.
Lesson 2

Communicating with the ArduinoTM

Figure 2-2. Hierarchical diagram of Arduino™ sketch,
methods, and programming statements
Example 2-2 is an Arduino™ method that might be found within a sketch. his particular method
has parameters: the length and width of a rectangle. It has a return type of int, meaning integer,
because the method "returns" the calculated area. (he use of return values is included in a later
lesson.)
Example 2-2. Arduino™ method

The programming statements necessary to calculate area and then return that
Important value are contained within a pair of curly braces.
Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

All methods comply with this format. If a method does not have parameters, then empty parentheses are used in the name. (A parameter is a special kind of variable used by a method to refer
to data provided as input.) If no values are to be returned, then the return type is void. Example
2-3 is an Arduino™ method that has no parameters and no values returned. his method merely
plays some sounds.
Example 2-3. Example of Arduino™ method with no parameters
void playSounds(){
tone( 5, NOTE_A4, 50);
delay( 600);
tone( 5, NOTE_E4, 50);
delay( 300);
tone( 5, NOTE_C4, 80);
delay( 400);
}

Every Arduino™ sketch must use, at a minimum, the two methods listed in Table 2-2.
Table 2-2. Methods required in every Arduino™ sketch
Method

What the statement does

Return Type

setup()

Initializes the Arduino™ and its components

void

loop()

Performs a task

void

Both setup() and loop() have void as the return type (or type of data that the method
yields) because neither ever has any values to return. Neither method has any parameters, which is
why their names are followed by empty parentheses. To help other people understand what you,
the programmer, have done and when and to aid you when you revisit a sketch, you can embed
notes within a sketch. hese notes have nothing to do with how the sketch works; they are for
information only.
One way of entering a note is to begin with a pair of slashes. When the Arduino™ is executing programming statements, it ignores anything following a pair of slashes. he following programming
statement has a note:
Serial.println("Greetings.");

// First line the user sees

Another method of entering a note is to use slash-asterisk bookends: /* and */. he content between them becomes a comment, and the Arduino™ ignores the comment when it is carrying out
programming statements.
Example 2-4.
/* MyFirstArduino™Sketch


*/
Lesson 2

Communicating with the ArduinoTM

2

Finally, some words have special meaning to the C language as it is used with the Arduino.™ hese
are called keywords. A keyword cannot be used for any other purpose. he programming statement
delay() uses the keyword delay.
Other commonly used keywords are: double int switch void while long return
short signed if goto for else do const char case break false true

In this lesson you will create the sketch shown in Sketch 2-1. Note the comments, methods, and
programming statements.
Sketch 2-1. First Arduino™ sketch
/* MyFirstArduino™Sketch.ino
W. P. Osborne
6/30/15
*/
void setup(){
Serial.begin(9600);
}
void loop(){
// print message at one second intervals
Serial.println("Hello, world!");
delay(1000);
}

Note

Throughout this book, sketches and snippets that the reader will type on her or
his keyboard appear in a gray box, as seen in Sketch 2-1.

In the sketch shown in Sketch 2-1, the irst three lines are comments. he irst line is the name of
the sketch; the second line names the author; the third notes the date the sketch was created.
he sketch also has two methods: setup() and loop(). he setup() method contains only
one programming statement while the loop() method contains two. he loop() method also
includes a comment.

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

Table 2-3. Vocabulary
Term Deinition
baud A unit of measure of the speed of data going into and out of a serial port.
comment Text inside a sketch that is present to provide the human reader of the
sketch insight into some aspect of the sketch's operation but that is ignored by the Arduino™ as it obeys programming statements.
debugging Finding and ixing improper behaviors in an Arduino™ sketch (and in other
computer programs).
escape An escape sequence is a pair of characters embedded in text where the
sequence irst character is a backslash (\). The second character is a command to do
something special when that text is printed on a computer screen via the
Serial.print() and Serial.println() programming statements.
The second characters are: the double quote ("), used to print the quotation mark as text, the lower-case letter t, which advances printing to the
next tab, the lower-case letter n, which moves printing to a new line, and
the backslash character itself (\), which prints the backslash as text.
keyword A word that has a speciic and predeined meaning in the C programming
language.
loop() One of the two essential methods in each Arduino™ sketch. The C-lanmethod guage statements in this method run over and over.
method A collection of C-language statements that perform a speciic task. A
method always has a name. Some methods can receive and return data.
programming A computer language instruction. A set of pre-written C-language instrucstatement tions that are used to send and receive data via a serial port.
serial library A set of pre-written C-language instructions that are used to send and
receive data via a serial port.
serial port A service built into each Arduino™ speciically to send to and receive data
from outside devices, including another computer.
Serial A feature of the Arduino™ IDE that allows sending text to and getting text
Monitor from the sketch running on the Arduino.™
setup() One of the two essential methods in each Arduino™ sketch. The C-lanmethod guage statements in this method run only once, when the sketch irst
starts. These statements initialize the Arduino,™ any attached devices,
and the sketch itself prior to running.
sketch A collection of instructions for your Arduino.™

Lesson 2

Communicating with the ArduinoTM

2

Goals:
1. Know that the Arduino™ pins 0 and 1 are used to receive and transmit data.
2. Know that the serial port is conigured in the setup method and that the rate of data exchange is set at this time. Understand that the Arduino™ IDE includes a tool called the
Serial Monitor for exchanging text with the Arduino.™
3. Know how to ind and open the Serial Monitor.
4. Know how to invoke the text transmission from the Arduino™ to the Serial Monitor using
the C-language statements Serial.print() and Serial.println().
5. Be able to write, save, upload, and run simple programs for the Arduino.™
6. Understand and know how to use escape sequences to format text.

Materials:
Quantity

Notes

Catalog
Number

Arduino™ Uno

Single-board computer. This
board is delicate and should
be handled with care. When
you are not using it, keep it in
a box or plastic bag.

3102

1

USB Cable

This is the standard USB
adapter cable with the lat
connector on one end and
the square connector on the
other.

2301

1

Computer with at least
one USB port and access to the Arduino™
website,
 .

The operating system of this
computer must be Windows,
Macintosh OS/X, or Linux.

---

1

Part

Image

---

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

Procedure:
Set up, upload, and run the irst Arduino™ sketch

2

1.

Connect the Arduino™ Uno to the serial cable and that cable to the computer.

2.

Start the Arduino™ IDE (Integrated Development Environment) by clicking the Arduino™
icon.
he Arduino™ IDE will appear.
he white space is where you will
type the program code.

3.

Lesson 2

Communicating with the ArduinoTM

4.

Enter the header comments. hese
comments identify the sketch, the
author, and the date the sketch was
created.

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

5.

Enter the programming statements
for the setup() method as shown
in Sketch 2-1 (shown again below
for reference).

2

his method runs when the
Arduino™ is irst started.

Complete listing 2-1. First Arduino™ sketch
/* MyFirstArduino™Sketch.ino


*/
void setup(){
Serial.begin(9600);
}
void loop(){
// send text to the Serial Monitor
Serial.println("Hello, world!");
// pause for one-half second
delay(500);
}

Lesson 2

Communicating with the ArduinoTM

6.

Next add the loop() method.
his method runs over and over
and over and over — continuously
repeating the programming statements.
In this case the loop() method is
sending the message
Hello, world!

repeatedly to the Serial Monitor.
he programming statement
delay(500) pauses the Arduino™

for 500 milliseconds (one-half a
second).

7.

Under the File, click [Save
As], change the ile name to
MyFirstArduino™Sketch and
make sure that the folder ile name
appearing in the [Save in:] box
is the Arduino™ folder in Documents.

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

8.

9.

Connect the Arduino™ to your
computer, then click the [Upload]
button. Wait for the program to be
uploaded to the Arduino.™

2

Open the Serial Monitor by clicking Serial Monitor under the Tools
menu.

Lesson 2

Communicating with the ArduinoTM

10. he words "Hello, world!" should
be scrolling through the text window in the Serial Monitor. If they
are not, make certain the box
marked Autoscroll is checked.
Check the baud rate that appears
in the Combo Box at the lower
right. It should be set to 9600, the
rate used in the
Serial.begin(9600)

statement in the setup method.
Baud is a measure of data transfer
speed.

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

Exercises:
Exercise 2-1. Experiment with formatting text
Perform the tasks listed in Table 2-4 and record your observations in its right-hand column.
Table 2-4. Observation table
Task

Observations

1. Replace the Serial.println command
with:Serial.println("test");
2. Replace the word println with print.

3. Add a second double quote.
Serial.print("test \"");

Note

The \ (backslash) character followed by
the quotation mark is called an escape
sequence. It allows for the quotation
mark to be printed rather than interpreted as the end of the text.

4. Replace the second quote with a second
backslash.
Serial.print("test \\");
5. Replace the second backslash with the
letter n followed by another word.
Serial.print("test \n hello");
6. Use what you have learned to cause the
words "Snoopy is a dog." to be printed, including the quotation marks.
Write the new statement in the box to the
right.

Lesson 2

Communicating with the ArduinoTM

2

Important

In Exercise 2-1, the use of the backslash before the double quote, a second
backslash, and the letter n are called escape sequences. There are others, but
these are the primary ones. More information about programming the serial
port can be found at  .

Exercise 2-2. Create a rocket
Save and close MyFirstArduino™Sketch. hen, using "new" under the File menu, create a
new Arduino™ sketch. Name this sketch Rocket.
Add the setup()method to this sketch. Have it initialize the serial port to 9600 baud, just as
you did in MyFirstArduino™Sketch.
Add the loop()method. Place it in the programming statements necessary to draw the rocket,
as shown in Example 2-3, in the Serial Monitor. Don't forget that some of the characters require
escape sequences.
Insert a half-second delay between the drawing of each line. he statement delay(500)will accomplish this.
Example 2-4. Rocket, as it appears in Serial Monitor
/\
/

\

/
\
+----+
+
+
+
+
+----+
+
+
+----+
+
+
+
+
+----+
/\
/ \
/
\

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

Lesson 3

Lesson 3:
Variables and
Strings
Variables
and
Strings

3

The Big Idea:
his lesson extends what we know about working with text in an Arduino™ sketch by adding the
ability to change it as the sketch is running.

Background:
In Lesson 2, an Arduino™ sketch used the serial port to send text to a computer screen, where it
appeared in the Serial Monitor. he programming statement that sent the text was:
Serial.println("Hello, world!");

he text was contained inside double quotation marks. Such information is pre-set. It cannot be
changed as the sketch runs. It is used literally. Such information that is programmed exactly as it
is to be used is called a literal.
Further, a collection of characters, such as the Hello, world! message, is called a String.
A String (note that this word always begins with a capital letter) is a kind of data. Kinds of data
are referred to as types. Putting these together, then, the String in the programming statement is a
String literal. Another way of saying this is that the message Hello, world! is a literal of type
String.
Most Arduino™ sketches, including nearly all the lessons in this book, need a way to store values so
the values can change over time and so that multiple parts of the sketch can access the values. his
is accomplished by employing a variable. You may be familiar with variables from algebra. Here
the variable X is set equal to the number 42.
X = 42

he variable name is X. he value is the integer 42.
Computer programming languages, including C, provide ways to create and name variables. Along
with each variable name C also sets aside spaces in computer memory to store the values being represented. Once created, a variable may be assigned a value. hat value may be retrieved or replaced
with another whenever the sketch requires.
What use would a sketch have for a variable? Making cool sketches possible. Table 3-1 provides
some examples.

Lesson 3

Variables and Strings

Table 3-1. Uses of variables in sketches
Kind of sketch

Possibly use for a variable

Laser Tag

A variable to store energy level is set when the game is started. The
sketch refers to the variable when tagging or receiving a tag.

Quad Copter

A variable to store the desired throttle setting to detemine if the copter is climbing, hovering or descending. Its value is set by the user's
manipulation of a control and is compared to the copter's actual
throttle setting.

Digital Musical
Keyboard

Lots of variables are used to hold the frequencies of diferent notes
and to provide the correct note output when the corresponding key
is pressed.

Just as in algebra, variables have names. Unlike with algebra, however, programmers can give
variables meaningful names, which aid in making the programming instructions in an Arduino™
sketch understandable. Suppose, for example, a sketch that programs the Arduino™ to play a game.
A variable to keep track of a player's name might be playerName.
Notice this name is really two words: player and name. How they are combined into one is by
means of a naming convention called camel notation. Under this convention the irst letter of the
irst word of the variable is always lowercase, and there are no spaces between words. he irst letters of all subsequent words in the variable are capitalized.
he process of setting aside memory space for a variable and assigning that variable's name to that
space is called declaration. Before it can be used, a variable must be declared. he programmer has
the option of assigning an initial value to the variable at that time.

Table 3-2. Vocabulary
Term Deinition
assignment The symbol used in a programming statement to store a value to a varioperator able. The symbol is the equals sign, =.
camel A convention for naming variables where words are joined together to
notation form a meaningful phrase to describe what is being assigned. Example of
a possible variable in camel notation: playerHighScore
concatenation The process of appending the value of one String variable to the value
of another String variable.
declaration A programming statement that sets aside memory for a particular type of
data and assigns the variable name that will refer to that type.
delimiter The character used to identify the beginning and end of the values for
some types of data. For data of the type String the delimiter is the quotation mark: "
Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

Term Deinition
initialization The initial value assigned to a newly declared variable.
literal A notation for representing a ixed value in source code. Its value cannot
be changed as a sketch runs. Literals are often used to initialize variables.
scope The portions of an Arduino™ sketch where a variable can be accessed.
Scope comes in two kinds:
• global: the variable is declared at the beginning of the sketch and may
be accessed anywhere.
• local: the variable is declared within a set of curly braces and may be
accessed only within those curly braces. This will be discussed in a
later lesson.
String A sequence of characters treated as one object. Example: “Hello, World!”.
type The kind of data to be assigned to a variable. The type used in this lesson
is String. Other types, which will be introduced in future lessons, are:
boolean, int, double, and char.
variable A name given to a location in memory where a value can be stored. A
variable is for a speciic type. The name must follow some naming rules.
Putting a value into memory is referred to as assigning that value to the
variable.

Description:
he rules for using variables in C are:
1. Declare a variable before assigning a value to it.
2. Assign a value to a variable before using it for some other purpose, such as printing or
having its value assigned to another variable.
3. Give variables valid names, meaning the names follow some simple rules.
4. Give variables meaningful names in accordance with good practices. Do not access a variable outside of its scope. Local variables may be accessed only from within their set of curly
braces, while global variables may be accessed from anywhere within a sketch. he limitation on access is referred to as scope.

Declaring variables
In order for an Arduino™ sketch to use a variable, the sketch must irst know two things about the
variable: its name and its type.
Naming variables
A variable can be given any name, subject to the following rules:
1. A variable name may not begin with a number but can begin with an underbar (_) or a
dollar sign ($).
Lesson 3

Variables and Strings

3

2. A variable name may not contain spaces.
3. A variable name may not contain mathematical operators: + - / * % =
4. A variable name may not contain the symbols for logical operators: > < !
5. A variable name may not contain a comma.
Table 3-3. Examples of names of variables
Example

Comment

volumeOfCube

valid and descriptive.

correct_answer

valid.

3ForAChange

invalid; cannot begin with a number.

answerForQuestion5 valid; number is allowed, just not the irst character.
location of Wumpus invalid; contains a space.
tax%rate

invalid; contains mathematical operator.

age1,age2

invalid as one name. C will interpret this as two variables, one
named age1 and the other named age2.

FrodoLives

valid but not good practice since the name is not likely to be
meaningful in the context of the sketch.

Declaration
A declaration is the C-language programming statement that makes a variable available to a sketch.
For these irst few lessons, all variables will be given global scope, meaning they are declared near
the top of the sketch, before the setup() method.
he declaration statement consists of two required parts and one optional part. he type and the
name are required. As part of declaring a variable, the programmer has the option of giving the
variable an initial value. he format of the variable declaration is simple, consisting of three parts:
the type, followed by the name and, optionally, an initial value for the variable.
Example 3-1. String variable declarations in the C language
String nameOfAccountHolder;
String playerName = "Deputy Dog";
String capital;
Notice the following about each of the declarations in Table 3-4:

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

1. Each declaration begins with the type of variable. In this case each variable is of type
String.
2. he type of variable is followed by the variable name.
3. hese names follow the naming rules, convey meaning, and comply with the camel notation naming convention.
4. he variable playerName is assigned an initial value.
Assigning and using values
Once declared, a variable can be assigned a value by using the equals sign. In C, the equals sign is
referred to as the assignment operator. hat value may be replaced by the assignment of a new value.
For example, the statement:
nameOfAccountHolder = "Flintstone";

stores the String literal Flintstone to the variable nameOfAccountHolder.
his statement:
Serial.println(nameOfAccountHolder);

will cause the String Flintstone to appear on the Arduino™ IDE's Serial Monitor.
his statement changes the value stored to the variable nameOfAccountHolder:
nameOfAccountHolder = "Rubble";

Now the statement:
Serial.println(nameOfAccountHolder);

will cause the String Rubble to appear on the Serial Monitor.

Concatenation
Finally, the plus sign (+) may be used to append one String to another. his is called concatenation.
For example, consider the following two declarations:
String actorFirstName = "Yogi";
String actorFamilyName = "Bear";

Suppose the programmer needs to have the full name stored to another variable, called
actorFullName. Further, a space is required between the two names. One way to do this is with
concatenation, where the irst name, a space String literal, and the last name are combined.
See Example 3-2.
Lesson 3

Variables and Strings

3

Example 3-2.
String fullName;
fullName = actorFirstName + " " + actorLastName;

he statement
Serial.println(fullName);

results in the following to appear on the Serial Monitor:
Yogi Bear

Goals:
By the end of this lesson readers will:
1. Know that a variable is a name that can be assigned a value.
2. Be able to follow naming rules and conventions.
3. Know that before a variable can be used it must be declared.
4. Be able to declare variables.
5. Be able to declare variables and assign initial values as part of the declaration.
6. Know how to work with the String data type, including use of the concatenation operator +.

Materials:
Quantity

1

1

Notes

Catalog
Number

Arduino™ Uno

Single-board computer. This
board is delicate and should
be handled with care. When
you are not using it, keep it in
a box or plastic bag.

3102

USB Cable

This is the standard USB
adapter cable with the lat
connector on one end and
the square connector on the
other.

2301

Part

Image

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

Quantity

Part

1

Computer with at least
one USB port and access to the Arduino™
website,
 .

Catalog
Number

Image

Notes

---

The operating system of this
computer must be Windows,
Macintosh OS/X, or Linux.

---

Procedure:
Part I: Set up, upload, and run the irst sketch.

1. Connect the Arduino™ to the computer then start the Arduino™ Integrated Development
Environment (IDE).

Arduino™ IDE as it appears when irst opened.
Notice the type of Arduino™ and the COM port
being used appear in the lower-right corner.
COM refers to the communications port.
his is assigned by the computer's operating
system and may change from time to time.

2. Enter the header comments as shown in Snippet 3-1.
Snippet 3-1.
/* Lesson3LearnStringVariables


*/
3. Declare three String variables just below the header comments as shown in Snippet
3-2. By declaring them here, outside of any methods, the variables are global and can be
accessed anywhere in the sketch.
Lesson 3

Variables and Strings

3

Snippet 3-2.
...
String str1 = "Hello,";
String str2 = "world!";
String str3;

4. Add the setup() method to your sketch as shown in Snippet 3-3. Use it to send the initial values to the Serial Monitor:
Snippet 3-3.
...
void setup(){
Serial.begin(9600);
Serial.print("str1 is: ");
Serial.println(str1);
Serial.print("str2 is: ");
Serial.println(str2);
}

5. Add the loop() method, as shown in Snippet 3-4, but place no programming statements
within it.
Snippet 3-4.
...
void loop(){
}
6. Save the sketch as Lesson3LearnStringVariables.

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

7. Upload the sketch, then open the Serial Monitor. he following should appear:

3

Notice the text does not repeat. his is because the print statements are inside the setup()
method. Since the setup() method is run only once, these statements are run only once.

Part II: Experiment with concatenation.
As in Part I, these steps will place programming statements in the setup() method. Keep in
mind that they could easily be put in the loop() method instead. But statements in the loop()
method are executed over and over. his means the text will be sent to the Serial Monitor over and
over.
8. Add the programming statements to the bottom of the setup() method (existing statements are in gray, new statements in black), as shown in Snippet 3-5.

Lesson 3

Variables and Strings

Snippet 3-5.
...
void setup(){
Serial.begin(9600);
Serial.print("str1 is: ");
Serial.println(str1);
Serial.print("str2 is: ");
Serial.println(str2);
// Concatenate str1 with a space
// and str2 to produce the message
// hello world!
// Assign result to str3 then
// print it.
str3 = str1 + " " + str2;
Serial.println(str3);
}
...
9. str3 now contains the concatenation of str1 with a space, followed by str2. he next
line sends the contents of str3 to the Serial Monitor.

10. Save the sketch, then upload to the Arduino.™ Open the Serial Monitor. he Serial Monitor should look like this:

Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

Exercise:
Exercise 3-1. "There was an old lady"
Create a new sketch called SpiderLady.ino. Pattern this sketch after
Lesson3LearnStringVariables.ino Initialize variables str1 and str2 as follows:
String str1 = "There was an old lady who swallowed a ";
String str2 = "I don't know why she swallowed a ";
String sentence;

hen, after initializing the Serial port in setup() add the programming statements necessary to
print a truncated version of the children's poem. he irst few statements will look like this:
sentence = str1 + "ly";
Serial.println(sentence);
sentence = str2 + "ly";
Serial.println(sentence);
sentence = str1 + "spider";
Serial.println(sentence);
… and so on through the critter of bird.

The ArduinoTM does not have suicient data storage for this sketch to print the
entire poem.
Note

Lesson 3

Variables and Strings

3

Lesson 4

Lesson 4: Digital Pins and Constants

Digital Pins and Constants

The Big Idea:
his lesson is the irst step toward learning to connect the Arduino™ to its surrounding world.
You will connect lights to your Arduino™ and then write sketches to turn them on and of in any
desired pattern. In the process you will learn how to conigure the digital pins of the Arduino™
in order to control devices and to turn those devices on and of. You will also learn how to use a
solderless bread-board to connect electronic devices together and to the Arduino.™ Later lessons
expand this connection ability to control motors, make sounds, detect light, and receive and transmit messages.

Background:
In Lesson 3, sketches used the serial port to send text from the Arduino™ Uno to the computer
running the Arduino™ IDE. In Lesson 4, you will learn to make things happen by taking advantage
of Arduino™ pins.
A pin is a connection with which the Arduino™ can be wired to external devices — everything from
motors and switches to display panels.

Figure 4-1. Arduino™ Uno with digital and analog pins
called out

he Arduino™ Uno has two
kinds of pins for receiving
and sending information:
analog and digital. he six
analog pins, pictured on
the upper right side of the
Arduino™ in Figure 4-1,
are the subject of a future
lesson. his lesson is about
digital pins, of which the
Arduino™ has 14. hese are
numbered from 0 through
13 and are found along one
side of the board.

A digital pin has only two states; on or of. he names for these states are HIGH and LOW. A HIGH
state means that a volt meter connected to that pin would measure +5 volts. LOW, by contrast,
means a measurement of zero volts.
Learn to Program in ArduinoTM C: 18 Lessons, from setup() to robots

Suppose a pin is HIGH. Where do the +5 volts come from? his depends on the mode of that
pin. A digital pin can be set to detect the presence or absence of +5 volts coming from outside the
Arduino.™ his voltage can come from a battery or some sort of sensing device. A digital pin that is
set to detect the presence or absence of +5 volts from an outside source is said to be in the INPUT
mode. Such a pin can detect signals from the outside world.
But an Arduino™ sketch itself can set a pin to HIGH or LOW. A pin that can have its voltage set
from within a sketch is said to be in the OUTPUT mode. Pins in OUTPUT mode are used to turn
devices on and of, to send signals, to control motors, and to generate sounds.
Table 4-1. Summary of modes and states of pins
Pin Mode Pin Status Meaning*
The Arduino™ raises the voltage of the pin to +5 volts, meaning

HIGH (on) that devices connected to this pin have access to electricity. A
light, for example, could come on, or a motor could start to turn.

OUTPUT
LOW (of)

The Arduino™ sets the voltage of the pin to zero volts. A light
connected to this pin would go dark; a motor would stop.

HIGH (on)

The presence of +5 volts is detected on this pin. This voltage is
coming from outside the Arduino™ and can be from a switch or
a sensor. Some sensors are +5 volts when nothing is detected.

LOW (of)

The voltage of the pin is determined to be zero. This may relect a
button being pushed or a sensor detecting a signal.

INPUT

*he meanings in this table are merely possibilities that relect what commonly happens. What
actually happens depends on the device and how it is wired to the Arduino.™ For example, in these
lessons push buttons are usually connected in such a way as to produce +5 volts on a pin in INPUT
mode when the button is not being pushed. he voltage drops to zero when the button is pushed.
his lesson will conine itself to digital pins in the OUTPUT mode. It also introduces some new
electronic components and the schematic diagram.

Lesson 4

Digital Pins and Constants

4

Table 4-2. Vocabulary
Term Deinition
breadboard As