Professional Documents
Culture Documents
Textbook Ebook Programming Arduino Getting Started With Sketches Tab Monk All Chapter PDF
Textbook Ebook Programming Arduino Getting Started With Sketches Tab Monk All Chapter PDF
SECOND EDITION
Simon Monk
Copyright © 2016, 2012 by McGraw-Hill Education. All rights reserved. Printed in the United
States of America. Except as permitted under the United States Copyright Act of 1976, no
part of this publication may be reproduced or distributed in any form or by any means, or
stored in a database or retrieval system, without the prior written permission of the
publisher, with the exception that the program listings may be entered, stored, and executed
in a computer system, but they may not be reproduced for publication.
McGraw-Hill Education, the McGraw-Hill Education logo, TAB, and related trade dress are
trademarks or registered trademarks of McGraw-Hill Education and/or its affiliates in the
United States and other countries and may not be used without written permission. All other
trademarks are the property of their respective owners. McGraw-Hill Education is not
associated with any product or vendor mentioned in this book.
Arduino is a trademark of Arduino LLC.
1 2 3 4 5 6 7 8 9 DOC 21 20 19 18 17 16
ISBN 978-1-25-964163-3
MHID 1-25-964163-5
Sponsoring Editor
Michael McCabe
Editorial Supervisor
Stephen M. Smith
Production Supervisor
Pamela A. Pelton
Acquisitions Coordinator
Lauren Rogers
Project Manager
Srishti Malasi,
Cenveo® Publisher Services
Copy Editor
Claire Splan
Proofreader
Cenveo Publisher Services
Indexer
Jack Lewis
Art Director, Cover
Jeff Weeks
Illustration
Cenveo Publisher Services
Composition
Cenveo Publisher Services
1 This Is Arduino
Microcontrollers
Development Boards
A Tour of an Arduino Board
Power Supply
Power Connections
Analog Inputs
Digital Connections
Microcontroller
Other Components
The Origins of Arduino
The Arduino Family
Uno and Leonardo
Mega and Due
The Micro and Small Arduino Boards
Yun
Lilypad
Other “Official” Boards
Arduino Clones and Variants
Conclusion
2 Getting Started
Powering Up
Installing the Software
Uploading Your First Sketch
The Arduino Application
Conclusion
3 C Language Basics
Programming
What Is a Programming Language?
Blink—Again!
Variables
Experiments in C
Numeric Variables and Arithmetic
Commands
if
for
while
Constants
Conclusion
4 Functions
What Is a Function?
Parameters
Global, Local, and Static Variables
Return Values
Other Variable Types
floats
boolean
Other Data Types
Coding Style
Indentation
Opening Braces
Whitespace
Comments
Conclusion
8 Data Storage
Constants
Storing Data in Flash Memory
EEPROM
Storing an int in EEPROM
Using the AVR EEPROM Library
Storing a float in EEPROM
Storing a String in EEPROM
Clearing the Contents of EEPROM
Compression
Range Compression
Conclusion
9 Displays
Alphanumeric LCD Displays
A USB Message Board
Using the Display
Other LCD Library Functions
OLED Graphic Displays
Connecting an OLED Display
Software
Conclusion
Index
PREFACE
The first edition of this book was published in November 2011 and
has been Amazon’s highest ranking book on Arduino.
At the time the book was originally written, the current Arduino
model was the Arduino 2009 and the software version was Beta018.
Almost at the time the book arrived in stores, the Arduino Uno and
version 1.0 of the Arduino software were released. Soon after, the
second printing of the book had a minor update to cover the new
board and software without formally being a second edition. This
edition brings the book fully up to date and is based on Arduino 1.6.
The Arduino Uno R3 is still considered to be the standard
Arduino board. However, many other boards, including both official
Arduino boards (like the Leonardo, Zero, 101, Due, and Yun) and
other Arduino programming language–based devices like the Photon
and Intel Edison, have also appeared.
This edition also addresses the use of Arduino in IoT (Internet of
Things) projects and the use of various types of display including
OLED and LCD.
Simon Monk
ACKNOWLEDGMENTS
I thank Linda for giving me the time, space, and support to write
this book and for putting up with the various messes my projects
create around the house.
Many thanks to Robert “BobKat” Logan and the many other
eagle-eyed and helpful folk who reported errata for the first edition. I
have done my best to fix what you found.
Finally, I would like to thank Michael McCabe, Srishti Malasi, and
everyone involved in the production of this book. It’s a pleasure to
work with such a great team.
INTRODUCTION
Resources
This book is supported by an accompanying website:
www.arduinobook.com
There you will find all the source code used in this book as well as
other resources, such as errata.
1
This Is Arduino
Microcontrollers
The heart of your Arduino is a microcontroller. Pretty much
everything else on the board is concerned with providing the board
with power and allowing it to communicate with your desktop
computer.
A microcontroller really is a little computer on a chip. It has
everything and more than the first home computers had. It has a
processor, a kilobyte or two of random access memory (RAM) for
holding data, a few kilobytes of erasable programmable read-only
memory (EPROM) or flash memory for holding your programs and it
has input and output pins. These input/output (I/O) pins link the
microcontroller to the rest of your electronics.
Inputs can read both digital (is the switch on or off?) and analog
(what is the voltage at a pin?). This opens up the opportunity of
connecting many different types of sensor for light, temperature,
sound, and more.
Outputs can also be analog or digital. So, you can set a pin to be
on or off (0 volts or 5 volts) and this can turn light-emitting diodes
(LEDs) on and off directly, or you can use the output to control higher
power devices such as motors. They can also provide an analog
output. That is, you can control the power output of a pin, allowing
you to control the speed of a motor or the brightness of a light, rather
than simply turning it on or off.
The microcontroller on an Arduino Uno board is the 28-pin chip
fitted into a socket at the center of the board. This single chip
contains the memory, processor, and all the electronics for the
input/output pins. It is manufactured by the company Atmel, which is
one of the major microcontroller manufacturers. Each of the
microcontroller manufacturers actually produces dozens of different
microcontrollers grouped into different families. The microcontrollers
are not all created for the benefit of electronics hobbyists like us. We
are a small part of this vast market. These devices are really
intended for embedding into consumer products, including cars,
washing machines, DVD players, children’s toys, and even air
fresheners.
The great thing about the Arduino is that it reduces this
bewildering array of choices by standardizing on one microcontroller
and sticking with it. (Well, as we see later, this statement is not quite
true, but it’s close enough.)
This means that when you are embarking on a new project, you
do not first need to weigh all the pros and cons of the various flavors
of microcontroller.
Development Boards
We have established that the microcontroller is really just a chip. A
chip microcontroller will not just work on its own without some
supporting electronics to provide it with a regulated and accurate
supply of electricity (microcontrollers are fussy about this) as well as
a means of communicating with the computer that is going to
program the microcontroller.
This is where development boards come in. An Arduino Uno
board is really a microcontroller development board that happens to
be an independent open source hardware design. This means that
the design files for the printed circuit board (PCB) and the schematic
diagrams are all publicly available, and everyone is free to use the
designs to make and sell his or her own Arduino boards.
All the microcontroller manufacturers—including Atmel, which
makes the ATmega328 microcontroller used in an Arduino board—
also provide their own development boards and programming
software. Although they are usually fairly inexpensive, these tend to
be aimed at professional electronics engineers rather than hobbyists.
This means that such boards and software are arguably harder to
use and require a greater learning investment before you can get
anything useful out of them.
One day after we had been married less than a year my husband
came home looking so studiously unconcerned that I knew at once he
had something to tell me.
“Nellie, what would you think,” he began casually, “if I should be
appointed a Judge of the Superior Court?”
“Oh, don’t try to be funny,” I exclaimed. “That’s perfectly
impossible.”
But it was not impossible, as he soon convinced me. My father had
just refused the same appointment and it was difficult to believe that
it could now be offered to my husband who was only twenty-nine
years old. It was a position made vacant by the retirement from the
Bench of Judge Judson Harmon who was my husband’s senior by
more than a decade.
One of the most prominent and prosperous law firms in Cincinnati
was that of Hoadley, Johnston and Colston, and both Mr. Hoadley
and Mr. Johnston had been invited to go to New York and become
partners of Mr. Edward Lauterbach who was then doing an
enormous business.
They went, and the old firm in Cincinnati being broken up, Mr.
Colston asked Judge Harmon, who was then on the Superior Court,
to take Mr. Hoadley’s place. Mr. Harmon decided to do so, but he
was anxious to resign his judgeship in such a way as to leave a long
enough vacancy to attract a good man. It was an elective office and
the law provided that a vacancy occurring within thirty days before
election could not be filled by an election until the following year.
Judge Harmon resigned so as to make the appointment for a period
of fourteen months. After my father declined it, the choice lay
between Mr. Taft and Mr. Bellamy Storer. Mr. Taft always thought
that but for his opportunity in the Campbell case Judge Hannon
would not have recommended him and Governor Foraker would not
have appointed him. That is why he says he traces all his success
back to that occasion. Mr. Foraker was opposing counsel in the
Campbell case, but he had a lawyer’s appreciation for a lawyer’s
effort.
After the first pleased surprise at the honour which came to us so
unexpectedly I began to think; and my thinking led me to decide that
my husband’s appointment on the Bench was not a matter for such
warm congratulation after all. I saw him in close association with
men not one of whom was less than fifteen years older than he, and
most of whom were much more than that. He seemed to me
suddenly to take on a maturity and sedateness quite out of keeping
with his actual years and I dreaded to see him settled for good in the
judiciary and missing all the youthful enthusiasms and exhilarating
difficulties which a more general contact with the world would have
given him. In other words, I began even then to fear the narrowing
effects of the Bench and to prefer for him a diverse experience which
would give him an all-round professional development.
He did not share this feeling in any way. His appointment on the
Superior Court was to him the welcome beginning of just the career
he wanted. After serving the interim of fourteen months he became a
candidate for the office and was elected for a term of five years. This
was the only elective office Mr. Taft ever held until he became
President.
My own time and interest during that winter was largely spent on
my house. We had been very particular about the plans for it and had
fully intended that it should combine outward impressiveness with
inward roominess and comfort. It was a frame structure, shingled all
over, and with certain bay window effects which pleased me
exceedingly. In fact, with our assistance, the architect had made a
special effort to produce something original and, while I don’t claim
that the result was a conspicuous architectural success, to my mind it
was anything but a failure. And our view of the Ohio River and the
surrounding country was really superb.
But I was not destined to enjoy my satisfaction with my
surroundings very long. The section had been at one time a stone
quarry, and the man who had levelled off the land and filled in the
gulches made by the quarry operations, took as a part of his
compensation two building lots which happened to be just across the
street from ours. He forthwith proceeded to put up a sort of double
house which looked more like a gigantic dry-goods box than anything
else, and I felt that it quite robbed the neighbourhood of the “tone”
which I had confidently hoped our house would give it. The double
house had just one quality and that was size.
I think the owner, whose name was Jerry something, lived in one
side of it, and he had a tenant in the other who hung clothes out of
the front windows. But tastes in architecture differ, as we soon found
out.
We were paying taxes on our house at an assessed value of $4000
and the undervaluation had been troubling my husband’s conscience
for a long time, in spite of my assuring him that tax collectors ought
to know their own business. Some men from the board of
equalization were to call one day to make a new appraisement and I
had very much hoped that my husband would not be at home. But he
was; he was there to welcome them and give them every possible
assistance. Without waiting for an examination of the premises, he
addressed one of them, an Irishman named Ryan.
“See here, Mr. Ryan,” he said, “I understand that Jerry, my
neighbour across the street, has his property assessed at $5000. Now
I don’t think that’s fair. I’m assessed at only $4000 and I’m sure my
house cost a good deal more than his. As a matter of fact it cost over
$6000. Now I’m a Judge of the Superior Court; I get my income out
of taxes and I certainly have no disposition to pay any less than my
share.”
“Well, Judge, your Honour,” said Mr. Ryan, “that is a sentiment
very befitting your Honour. Now I’ll just be after goin’ over and
lookin’ at those houses of Jerry’s, and then I’ll come back and look at
yours.”
I watched them as they went over to the other houses; then I saw
them go up the street a way and down the street a way, looking us
carefully over from every possible view-point. When they came in
they wore a very judicial aspect and I expected to see taxes go up
with one wild leap.
“Well, Judge, your Honour,” began Mr. Ryan, “I think you’re givin’
yourself unnecessary concern. We assess houses for what they’re
worth and not for what they cost. While your house no doubt suits
your taste, it has a peculiar architectural style that wouldn’t please
very many people, and certainly it ain’t to compare with those houses
of Jerry’s. There’s a modern polish about those houses that will rent,
Judge, your Honour.”
My son Robert was born in this house on McMillan Street in
September, 1889. In the following February an interruption occurred
in our peaceful existence which was welcome at least to me.
President Harrison offered the appointment of Solicitor General of
the United States to Mr. Taft and he, with a few regretful glances at
his beloved Bench, accepted it. I think that once again it was Major
Butterworth who suggested my husband’s name to the appointing
power. I was very glad because it gave Mr. Taft an opportunity for
exactly the kind of work I wished him to do; work in which his own
initiative and originality would be exercised and developed. I looked
forward with interest, moreover, to a few years in Washington.
Mr. Taft made his first official arrival in Washington alone. My
baby, Robert, was only six months old and I concluded to remain in
Cincinnati until my husband could make arrangements for our
comfortable reception. His description of his first day in Washington
is, in the light of later events, rather amusing.
He arrived at six o’clock on a cold, gloomy February morning at
the old dirty Pennsylvania station. He wandered out on the street
with a heavy bag in his hand looking for a porter, but there were no
porters. Then he stood for a few moments looking up at the Capitol
and feeling dismally unimportant in the midst of what seemed to him
to be very formidable surroundings. He wondered to himself why on
earth he had come. He was sure he had made a fatal mistake in
exchanging a good position and a pleasant circle at home, where
everybody knew him, for a place in a strange and forbidding city
where he knew practically nobody and where, he felt sure, nobody
wanted to know him. He lugged his bag up to the old Ebbitt House
and, after eating a lonesome breakfast, he went to the Department of
Justice to be sworn in. After that ceremony was over and he had
shaken hands with the Attorney General, he went up to inspect the
Solicitor General’s Office, and there he met the most dismal sight of
the whole dismal day. His “quarters” consisted of a single room,
three flights up, and bearing not the slightest resemblance to his
mental picture of what the Solicitor General’s offices would be like.
The Solicitor General’s stenographer, it seemed, was a telegrapher in
the chief clerk’s office and had to be sent for when his services were
required. Altogether it must have been a very disheartening outlook.
As Mr. Taft sat looking over briefs and other papers, and trying to
get some definite idea about his new work, a messenger brought in a
card.
“Mr. Evarts, New York,” it read.
Evarts was a well-known name, of course, but it was hard for Mr.
Taft to believe that the William M. Evarts, leader of the American Bar
and then Senator from New York, could be calling on the Solicitor
General of less than a day. He knew that Wm. M. Evarts had known
his father.
Mr. Evarts entered.
“Mr. Taft,” he said, as he gave my husband’s hand a cordial grasp,
“I knew your father. I was in the class of ’37 at Yale and he had
graduated before I entered; but he was there as a tutor in my time
and I valued his friendship very highly.”
Then the visitor came straight to the point.
“Mrs. Evarts and I are giving a dinner to-night for my former
partner and his wife, Mr. and Mrs. Joseph Choate. Mr. Choate is in
Washington for a short time to argue a case before the Supreme
Court. Now, unfortunately, one of our guests has sent word that he
can’t come and I thought, perhaps, considering my long-standing
friendship with your father, you might consent to waive ceremony
and fill the place at our table at this short notice.”
My husband accepted the invitation with almost undue alacrity,
and when his guest left started in on his new duties feeling that, after
all, Washington might afford just as friendly an atmosphere as
Cincinnati, once he became accustomed to it.
There is just one incident in connection with the dinner party
which Mr. Taft adds to his account of that day. As he sat down to
dinner the ladies on either side of him leaned hastily forward to see
what was written on his place card. “The Solicitor General”—that was
all. Of course neither of them knew who the new Solicitor General
was and it didn’t occur to him to enlighten them until it was too late
to do it gracefully. So he allowed them to go on addressing him as
“Mr. Solicitor General” while he, having them at an advantage,
addressed them by the names which he had surreptitiously read on
their place-cards. They were Mrs. Henry Cabot Lodge and Mrs. John
Hay.