Termes les plus recherchés
[PDF](+72👁️) Télécharger Programming Arduino pdf
Programming ArduinoTélécharger gratuit Programming Arduino pdf
lashSequence(let
(ch >=
Programming
Arduino"
shSequence(nuri
(ch == ' '
(dotDelay *
Getting Started
with Sketches >
f lash‘3equence(
quence[i]
tOrDash($
lay * 3)
Simon Monk
>
(dotDelay);
{
(dotDelay f 3^
Programming Arduino
TM
Getting Started with Sketches
Simon Monk
New York Chicago San Francisco Lisbon
London Madrid Mexico City Milan New Delhi
San Juan Seoul Singapore Sydney Toronto
The McGrawHIII Comport *s
HM
Copyright © 2012 by The McGraw-Hill Companies. All rights reserved. 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.
ISBN: 978-0-07-178423-8
MHID: 0-07-178423-3
The material in this eBook also appears in the print version of this title: ISBN: 978-0-07-
178422-1, MHID: 0-07-178422-5.
All trademarks are trademarks of their respective owners. Rather than put a trademark
symbol after every occurrence of a trademarked name, we use names in an editorial
fashion only, and to the benefit of the trademark owner, with no intention of infringement
of the trademark. Where such designations appear in this book, they have been printed
with initial caps.
McGraw-Hill eBooks are available at special quantity discounts to use as premiums and
sales promotions, or for use in corporate training programs. To contact a representative
please e-mail us at bulksales@mcgraw-hill.com.
All trademarks or copyrights mentioned herein are the possession of their respec-tive
owners and McGraw-Hill makes no claim of ownership by the mention of products that
contain these marks.
“Arduino” is a trademark of the Arduino team.
Information has been obtained by McGraw-Hill from sources believed to be reliable.
However, because of the possibility of human or mechanical error by our sources,
McGraw-Hill, or others, McGraw-Hill does not guarantee the accuracy, adequacy, or
completeness of any information and is not responsible for any errors or omissions or the
results obtained from the use of such information.
TERMS OF USE
This is a copyrighted work and The McGraw-Hill Companies, Inc. (“McGraw-Hill”) and
its licensors reserve all rights in and to the work. Use of this work is subject to these
terms. Except as permitted under the Copyright Act of 1976 and the right to store and
retrieve one copy of the work, you may not decompile, disassemble, reverse engineer,
reproduce, modify, create derivative works based upon, transmit, distribute, disseminate,
sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent.
You may use the work for your own noncommercial and personal use; any other use of the
work is strictly prohibited. Your right to use the work may be terminated if you fail to
comply with these terms.
THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE
NO GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR
COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK,
INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE
WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY
WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
PARTICULAR PURPOSE. McGraw-Hill and its licensors do not warrant or guarantee
that the functions contained in the work will meet your requirements or that its operation
will be uninterrupted or error free. Neither McGraw-Hill nor its licensors shall be liable to
you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work
or for any damages resulting therefrom. McGraw-Hill has no responsibility for the content
of any information accessed through the work. Under no circumstances shall McGraw-
Hill and/or its licensors be liable for any indirect, incidental, special, punitive,
consequential or similar damages that result from the use of or inability to use the work,
even if any of them has been advised of the possibility of such damages. This limitation of
liability shall apply to any claim or cause whatsoever whether such claim or cause arises
in contract, tort or otherwise.
To my boys, Stephen and Matthew,
from a very proud Dad.
About the Author
Simon Monk has a bachelor’s degree in cybernetics and computer science and a doctorate
in software engineering. He has been an active electronics hobbyist since his school days
and is an occasional author in hobby electronics magazines. He is also author of 30
Arduino Projects for the Evil Genius and 15 Dangerously Mad Projects for the Evil
Genius.
CONTENTS
Acknowledgments
Introduction
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. Duemilanove. and Diecimila
Mega
Nano
Bluetooth
Lilvpad
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
The #define Directive
Conclusion
4 Functions
What Is a Function?
Parameters
Global. Focal, and Static Variables
Return Values
Other Variable Types
floats
boolean
Other Data Types
Coding Style
Indentation
Opening Braces
Whitespace
Comments
Conclusion
5 Arrays and Strings
Arrays
Morse Code SOS Using Arrays
String Arrays
String Fiterals
String Variables
A Morse Code Translator
Data
Globals and Setup
The loop function
The flashSequence Function
The flashDotOrDash Function
Putting It All Together
Conclusion
6 Input and Output
Digital Outputs
Digital Inputs
Pull-up Resistors
Internal Pull-up Resistors
Debouncing
Analog Outputs
Analog Input
Conclusion
7 The Standard Arduino Library
Random Numbers
Math Functions
Bit Manipulation
Advanced I/O
Generating Tones
Feeding Shift Registers
Interrupts
Conclusion
8 Data Storage
Constants
The PROGMEM Directive
EEPROM
Storing an int in EEPROM
Storing a float in EEPROM (Unions)
Storing a String in EEPRQM
Clearing the Contents of EEPROM
Compression
Range Compression
Conclusion
9 LCD Displays
A USB Message Board
Using the Display
Other LCD Library Functions
Conclusion
10 Arduino Ethernet Programming
Ethernet Shields
Communicating with Web Servers
HTTP
HTML
Arduino as a Web Server
Setting Arduino Pins over the Network
Conclusion
11 C++ and Libraries
Object Orientation
Classes and Methods
Built-in Library Example
Writing Libraries
The Header Lile
The Implementation Lile
Completing Your Library
Conclusion
Index
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.
I also thank Stephen and Matthew Monk for taking an interest in what their Dad is up to
and their general assistance with project work.
Finally, I would like to thank Roger Stewart, Sapna Rastogi, and everyone involved in
the production of this book. It’s a pleasure to work with such a great team.
INTRODUCTION
Arduino interface boards provide a low-cost, easy-to-use technology to create
microcontroller-based projects. With a little electronics, you can make your Arduino do all
sorts of things, from controlling lights in an art installation to managing the power on a
solar energy system.
There are many project-based books that show you how to connect things to your
Arduino, including 30 Arduino Projects for the Evil Genius by this author. However, the
focus of this book is on programming the Arduino.
This book will explain how to make programming the Arduino simple and enjoyable,
avoiding the difficulties of uncooperative code that so often afflict a project. You will be
taken through the process of programming the Arduino step by step, starting with the
basics of the C programming language that Arduinos use.
So, What Is Arduino?
Arduino is a small microcontroller board with a universal serial bus (USB) plug to connect
to your computer and a number of connection sockets that can be wired to external
electronics such as motors, relays, light sensors, laser diodes, loudspeakers, microphones,
and more. They can either be powered through the USB connection from the computer,
from a 9V battery, or from a power supply. They can be controlled from the computer or
programmed by the computer and then disconnected and allowed to work independently.
The board design is open source. This means that anyone is allowed to make Arduino-
compatible boards. This competition has lead to low costs for the boards.
The basic boards are supplemented by accessory shield boards that can be plugged on
top of the Arduino board. In this book, we will use two shields—an LCD display shield
and an Ethernet shield—that will allow us to turn our Arduino into a tiny web server.
The software for programming your Arduino is easy to use and also freely available for
Windows, Mac, and LINUX computers.
What Will I Need?
This is a book intended for beginners, but it is also intended to be useful to those who have
used Arduino for a while and want to learn more about programming the Arduino or gain
a better understanding of the fundamentals.
You do not need to have any programming experience or a technical background, and
the book’s exercises do not require any soldering. All you need is the desire to make
something.
If you want to make the most of the book and try out some of the experiments, then it is
useful to have the following on hand:
• A few lengths of solid core wire
• A cheap digital multimeter
Both are readily available for a few dollars from a hobby electronics shop such as Radio
Shack. You will of course also need an Arduino Uno board.
If you want to go a step further and experiment with Ethernet and the liquid crystal display
(LCD) shield, then you will need to buy shields that are available from online stores. See
Chapters 9 and 10 for details.
Using this Book
This book is structured to get you started in a really simple way and gradually build on
what you have learned. You may, however, find yourself skipping or skimming some of
the early chapters as you find the right level to enter the book.
The book is organized into the following chapters:
• Chapter 1 : This Is Arduino An introduction to the Arduino hardware, this chapter
describes what it is capable of, and the various types of, Arduino boards that are
available.
• Chapter 2 : Getting Started Here you conduct your first experiments with your Arduino
board: installing the software, powering it up, and uploading your first sketch.
• Chapter 3 : C Language Basics This chapter covers the basics of the C language; for
complete programming beginners, the chapters also serves as an introduction to
programming in general.
• Chapter 4 : Functions This chapter explains the key concept of using and writing
functions in Arduino sketches. These sketches are demonstrated throughout with
runnable code examples.
• Chapter 5 : Arrays and Strings Here you learn how to make and use data structures that
are more advanced than simple integer variables. A Morse code example project is
slowly developed to illustrate the concepts being explained.
• Chapter 6 : Input and Output You learn how to use the digital and analog inputs and
outputs on the Arduino in your programs. A multimeter will be useful to show you what
is happening on the Arduino’s input/output connections.
• Chapter 7 : The Standard Arduino Library This chapter explains how to make use of
the standard Arduino functions that come in the Arduino’s standard library.
• Chapter 8 : Data Storage Here you learn how to write sketches that can save data in
electrically erasable read-only memory (EEPROM) and make use of the Arduino’s
built-in flash memory.
• Chapter 9 : LCD Displays In this chapter, you program with the LCD Shield library to
make a simple USB message board example.
• Chapter 10 : Arduino Ethernet Programming You learn how to make the Arduino
behave like a web server as you get a little background on HyperText Markup Language
(HTML) and the HyperText Transfer Protocol (HTTP).
• Chapter 11 : C++ and Libraries You go beyond C, looking at adding object-orientation
and writing your own Arduino libraries.
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
Arduino is a microcontroller platform that has captured the imagination of electronics
enthusiasts. Its ease of use and open source nature make it a great choice for anyone
wanting to build electronic projects.
Ultimately, it allows you to connect electronics through its pins so that it can control
things—for instance, turn lights or motors on and off or sense things such as light and
temperature. This is why Arduino is sometimes given the description physical computing.
Because Arduinos can be connected to your computer by a universal serial bus (USB)
lead, this also means that you can use the Arduino as an interface board to control those
same electronics from your computer.
This chapter is an introduction to the Arduino, including the history and background of
the Arduino, as well as an overview of the hardware.
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 voltage. That is, you can set the output of a pin to some particular voltage,
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 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 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 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.
A Tour of an Arduino Board
Figure 1-1 shows an Arduino board. Let’s take a quick tour of the various components on
the board.
Crystal
USB Interface Chip Digital Connections
Reset Switch
Power
Connectors
Microcontroller Analog
Inputs
Serial
Programming
Connector
5V Voltage Regulator
Figure 1-1 An Arduino Uno board
Power Supply
Referring to Figure 1-1 . directly below the USB connector is the 5-volt (5V) voltage
regulator. This regulates whatever voltage (between 7V and 12V) is supplied from the
power socket into a constant 5V.
The 5V voltage regulator chip is actually quite big for a surface mount component. This
is so that it can dissipate the heat required to regulate the voltage at a reasonably high
current. This is useful when driving external electronics.
Power Connections
Next let us look at the connectors at the bottom of Figure 1-1 . You can read the connection
names next to the connectors. The first is Reset. This does the same thing as the Reset
button on the Arduino. Rather like rebooting a PC, using the Reset connector resets the
microcontroller so that it begins its program from the start. To reset the microcontroller
with the Reset connector, you momentarily set this pin low (connecting it to OV).
The rest of the pins in this section just provide different voltages (3.5V, 5V, GND, and
9V), as they are labeled. GND, or ground, just means zero volts. It is the reference voltage
to which all other voltages on the board are relative.
Analog Inputs
The six pins labeled as Analog In AO to A5 can be used to measure the voltage connected
to them so that the value can be used in a sketch. Note that they measure a voltage and not
a current. Only a tiny current will ever flow into them and down to ground because they
have a very large internal resistance. That is, the pin having a large internal resistance only
allows a tiny current to flow into the pin.
Although these inputs are labeled as analog, and are analog inputs by default, these
connections can also be used as digital inputs or outputs.
Digital Connections
We now switch to the top connector and start on the right-hand side in Figure 1-1 . Here we
find pins labeled Digital 0 to 13. These can be used as either inputs or outputs. When used
as outputs, they behave rather like the power supply voltages discussed earlier in this
section, except that these are all 5V and can be turned on or off from your sketch. So, if
you turn them on from your sketch they will be at 5V, and if you turn them off they will be
at OV. As with the power supply connectors, you must be careful not to exceed their
maximum current capabilities. The first two of these connections (0 and 1) are also labeled
RX and TX, for receive and transmit. These connections are reserved for use in
communication and are indirectly the receive and transmit connections for your USB link
to your computer.
These digital connections can supply 40 mA (milliamps) at 5V. That is more than
enough to light a standard LED, but not enough to drive an electric motor directly.
Microcontroller
Continuing our tour of the Arduino board, the microcontroller chip itself is the black
rectangular device with 28 pins. This is fitted into a dual inline (DIL) socket so that it can
be easily replaced. The 28-pin microcontroller chip used on the Arduino Uno board is the
ATmega328. Figure 1-2 is a block diagram showing the main features of this device.
The heart—or, perhaps more appropriately, the brain—of the device is the central
processing unit (CPU). It controls everything that goes on within the device. It fetches
program instructions stored in the flash memory and executes them. This might involve
fetching data from working memory (RAM), changing it, and then putting it back. Or, it
may mean changing one of the digital outputs from 0V to 5V.
The EEPROM memory is a little like the flash memory in that it is nonvolatile. That is,
you can turn the device off and on and it will not have forgotten what is in the EEPROM.
Whereas the flash memory is intended for storing program instructions (from sketches),
the EEPROM is used to store data that you do not want to lose in the event of a reset or
the power being turned off.
UART (serial data interface)
2 KB RAM
(working
memory)
32 KB Flash
Memory
(sketches)
1 KB
A A
EEPROM
(non-volatile)
CPU J
Input/Output ports
Figure 1-2 ATmega328 block diagram
Other Components
Above the microcontroller is a small, silver, rectangular component. This is a quartz
crystal oscillator. It ticks 16 million times a second, and on each of those ticks, the
microcontroller can perform one operation—addition, subtraction, or another
mathematical operation.
To the right of the crystal is the Reset switch. Clicking on this switch sends a logic
pulse to the Reset pin of the microcontroller, causing the microcontroller to start its
program afresh and clear its memory. Note that any program stored on the device will be
retained, because this is kept in non-volatile flash memory—that is, memory that
remembers even when the device is not powered.
To the right of the Reset button is the Serial Programming Connector. It offers another
means of programming the Arduino without using the USB port. Because we do have a
USB connection and software that makes it convenient to use, we will not avail ourselves
of this feature.
In the top-left corner of the board next to the USB socket is the USB interface chip.
This chip converts the signal levels used by the USB standard to levels that can be used
directly by the Arduino board.
The Origins of Arduino
Arduino was originally developed as an aid for teaching students. It was subsequently (in
2005) developed commercially by Massimo Banzi and David Cuartielles. It has since gone
on to become enormously successful with makers, students, and artists for its ease of use
and durability.
Another key factor in its success is that all the designs for Arduino are freely available
under a Creative Commons license. This has allowed many lower-cost alternatives to the
boards to appear. Only the name Arduino is protected, so such clones often have
“*dunino” names, such as Boarduino, Seeeduino, and Freeduino. However, the official
boards manufactured in Italy still sell extremely well. Many big retailers sell only the
official boards, which are nicely packaged and of high quality.
Yet another reason for the success of Arduino is that it is not limited to microcontroller
boards. There are a huge number of Arduino-compatible shield boards that plug directly
into the top of an Arduino board. Because shields are available for almost every
conceivable application, you often can avoid using a soldering iron and instead plug
together shields that can be stacked one upon another. The following are just a few of the
most popular shields:
• Ethernet, which gives an Arduino web-serving capabilities
• Motor, which drives electric motors
• USB Host, which allows control of USB devices
• Relays, which switches relays from your Arduino
Figure 1-3 shows an Arduino Uno with an Ethernet shield attached.
Figure 1-3 Arduino Uno with an Ethernet shield
The Arduino Family
It is useful to have a little background on the various Arduino boards. We will be using the
Arduino Uno as our standard device. Indeed, this is by far the most used of the Arduino
boards, but the boards are all programmed using the same language and largely have the
same connections to the outside world, so you can easily use a different board.
Uno, Duemilanove, and Diecimila
The Arduino Uno is the latest incarnation of the most popular series of Arduino boards.
The series includes the Diecimila (Italian for 10,000) and the Duemilanove (Italian for
2011). Figure 1-4 shows an Arduino clone. By now you may have guessed that Arduino is
an Italian invention.
These older boards look very similar to the Arduino Uno. They both have the same
connectors and a USB socket and are generally compatible with each other.
The most significant difference between the Uno and the earlier boards is that the Uno
uses a different USB chip. This does not affect how you use the board, but it does make
installation of the Arduino software easier and allows higher speeds of communication
with the computer.
The Uno can also supply more current on its 3.3V supply and always comes equipped
with the ATmega328. The earlier boards will have either an ATmega328 or ATmegal68.
The ATmega328 has more memory, but unless you are creating a large sketch, this will
make no difference.
Figure 1-4 The Arduino Duemilanove
Mega
The Arduino Mega ( Figure 1-5 ) is the muscle car of Arduino boards. It boasts a huge
collection of input output ports, but cleverly adds these as extra connectors at one end of
the board, allowing it to remain pin-compatible with the Arduino Uno and all the shields
available for Arduino.
It uses a processor with more input output pins, the ATmegal280, which is a surface
mount chip that is fixed permanently to the board. So, unlike with the Uno and similar
boards, you cannot replace the processor if you accidentally damage it.
The extra connectors are arranged at the end of the board. Extra features provided by
the Mega include the following:
• 54 input/output pins
• 128KB of flash memory for storing sketches and fixed data (compared to the Uno’s
32KB)
• 8KB of RAM and 4KB of EEPROM
Nano
The Arduino Nano ( Figure 1-6 ) is a very useful device for use with a solderless
breadboard. If you fit pins to it, it can just plug into the breadboard as if it were a chip.
Figure 1-5 An Arduino Mega board
Figure 1-6 Arduino Nano
The downside of the Nano is that because it is so much smaller than an Uno, it cannot
accept Uno-sized shields.
Bluetooth
The Arduino Bluetooth ( Figure 1-7 ) is an interesting device as it includes Bluetooth
hardware in place of the USB connector. This allows the device to even be programmed
wirelessly.
The Arduino Bluetooth is not a cheap board, and it is often cheaper to attach a third-
party Bluetooth module to a regular Arduino Uno.
Lilypad
The Lilypad ( Figure l-8 f is a tiny, thin Arduino board that can be stitched into clothing for
applications that have become known as wearable computing.
The Lilypad does not have a USB connection, and you must use a separate adaptor to
program it. It has an exceptionally beautiful design.
Figure 1-7 Arduino Bluetooth
Figure 1-8 Arduino Lilypad
Other “Official” Boards
The previously described Arduino boards are the most useful and popular ones. However,
the range of Arduino boards constantly changes, so for a complete and up-to-date picture
of the Arduino family, see the official Arduino website list at
www. arduino. cc/en/Main/Hardwar e .
Arduino Clones and Variants
Unofficial boards fall into two categories. Some just take the standard open source
hardware designs of Arduino and build a cheaper one. Some names you can search for
boards of this nature include the following:
• Roboduino
• Freeduino
• Seeeduino (yes, with three e’s)
More interestingly, some Arduino-compatible designs are intended to extend or improve
the Arduino in some way. New variants are appearing all the time, and far too many exist
to mention them all. However, the following are some of the more interesting and popular
variants:
• Chipkit, a high-speed variant based on a PIC processor, but which is fairly compatible
with Arduino
• Femtoduino, a very small Arduino
• Ruggeduino, with is an Arduino board with built-in I/O protection
• Teensy, a low-cost nano-type device
Conclusion
Now that you have explored the Arduino hardware a little, it’s time to set up your Arduino
software.
2
Getting Started
Having introduced the Arduino, and learnt a little about what it is that we are
programming, it is time to learn how install the software that we will need on our
computer and to start working on some code.
Powering Up
When you buy an Arduino board, it is usually preinstalled with a sample Blink program
that will make the little built-in light-emitting diode (LED) flash.
The LED marked L is wired up to one of the digital input output sockets on the board. It
is connected to digital pin 13. This limits pin 13 to being the one used as an output.
However, the LED uses only a small amount of current, so you can still connect other
things to that connector.
All you need to do to get your Arduino up and running is supply it with some power.
The easiest way to do this is to plug in it into the USB port on your computer. You will
need a type-A-to-type-B USB lead. This is the same type of lead that is normally used to
connect a computer to a printer.
If everything is working OK, the LED should blink. New Arduino boards come with
this Blink sketch already installed so that you can verify that the board works.
Installing the Software
To be able to install new sketches onto your Arduino board, you need to do more than
supply power to it over the USB. You need to install the Arduino software ( Figure 2-1 1.
Full and comprehensive instructions for installing this software on Windows, Linux,
and Mac computers can be found at the Arduino website ( www.arduino.cc L
Once you have successfully installed the Arduino software and, depending on your
platform, USB drivers, you should now be able to upload a program to the Arduino board.
Figure 2-1 The Arduino application
Uploading Your First Sketch
The blinking LED is the Arduino equivalent to the “Hello World” program used in other
languages as the traditional first program to run when learning a new language. Let’s test
out the environment by installing this program on your Arduino board and then modifying
it.
When you start the Arduino application on your computer, it opens with an empty
sketch. Fortunately, the application ships with a wide range of useful examples. So from
the File menu, open the Blink example as shown in Figure 2-2 .
Figure 2-2 The Blink sketch
You now need to transfer or upload that sketch to your Arduino board. So plug your
Arduino board into your computer using the USB lead. You should see the green “On”
LED on the Arduino light up. The Arduino board will probably already be flashing, as the
boards are generally shipped with the Blink sketch already installed. But let’s install it
again and then modify it.
When you plug the board in, if you are using a Mac, you may get the message, “A new
network interface has been detected.” Just click Cancel; your Mac is confused and thinks
that the Uno is a USB modem.
Before you can upload a sketch, you must tell the Arduino application what type of
board you are using and which serial port you are connected to. Figures 2-3 and 2z4 show
how you do this from the Tools menu.
ee Blink ArduinoOO??
F*e Edt Sketch
Nek)
@© [q]G
Auto Format Ctrt+T
ArcFrve Sketch
Fix Encoding ft Reload
/•
+M
Blink
Board
»
Tlitns on an
Serial Port
»
This example
Burn Bootloader
»
■Old loot* 0 (
digitAlVtite<13, HIGH);
delay(1000);
dl0UllVEltl(llf LOW);
delaY(LOOO);
H set the LED
// wait Coc a 9
// jet the LED
// wait Cor a 3
VOld <M*tU|l() (
// initialize the digital pin as an output
// )tn 13 has an LED connected on most Art
pinHcde(13, OUTPUT);
)
» a Arduno Uno
ArAmo Cuerrrlenove or Mano w/ Afmcga328
Arduno OeorrAa, CuerrAanove, or Nano w/ ATmegal68
Arduno Mega 2S60
Arduno Mega (ATmegal280)
Arduno Mm
Arduno fio
Arduno BT w/ ATmege328
Arduno 6T w/ATmegel68
liyPad Arduno *v/ AT meg*328
llyPed Arduno w/ ATmegal68
Arduno Pro or Pro Mri (5V, 16 MHz) w/ ATmega328
Arduno Pro or Pro Mrt (5V, 16 MHz) w/ A Tmega168
Arduno Pro or Pro Mrt (3.3V, 8 MHz) w/ ATmega328
Arduno Pro Or Pro Mn (3.3V, 8 MHz) w/ ATrr*gal68
Arduno MG or older *»/ AT mega 1 68
Arduno MG or older w/ ATmega8
SB
Figure 2-3 Selecting the board type
Figure 2-4 Selecting the serial port (in Windows)
On a Windows machine, the serial port is always COM3. On Macs and Linux machines,
you will see a much longer list of serial devices (see Figure 2-5 L The device will normally
be the top selection in the list, with a name similar to /dev/tty.usbmodem621.
Now click on the Upload icon in the toolbar. This is shown highlighted in Figure 2-6 .
After you click the button, there is a short pause while the sketch is compiled and then
the transfer begins. If it is working, then there will be some furious blinking of LEDs as
the sketch is transferred, after which you should see the message “Done Uploading” at the
bottom of the Arduino application window and a further message similar to “Binary
sketch size: 1018 bytes (of a 14336 byte maximum).”
# Arduino File Edit Sketch ^£2£J Help_
Auto Format XT
Archive Sketch
Fix Encoding & Refold
Serial Monitor OXM
« ^V> Blink | AnJjin
veld Mt*<> ^
.1 ••• -<i3. ajr#«jT)i
}
y>.d i**<> {
i 1 . '' - (13.
- <iwe>*
it ; •*<*! *.-(», LOU);
tv
}
Board
Serial Port
Burn Bootloader
► ✓ /dev/tty.usbmodem621
/dev/cu.usbmod«m621
/dev/tty. Si monMonksiPhone-Wirele
/dev/cu.S*fnonMonkslPhor»e-Wrele
/dev/tty.OmniTek. Bluet ooth-DevB
/dev/cu,OmniTek_Biuetooth-OevS
/dev/tty.Bluetooth-Modem
/dev/cu. Bluetooth-Modem
/dev/tty.linvor-DevB
/dev/cu.Unvor- DevB
/dev/tty.Bluetooth-POA-Sync
/dev/cu. Bluetooth-POA-Sync
Figure 2-5 Selecting the serial port (on a Mac)
Once uploaded, the board automatically starts running the sketch and you will see the
LED start to blink.
If this did not work, then check your serial and board type settings.
Now let’s modify the sketch to make the LED blink faster. To do this, let’s alter the two
places in the sketch where there is a delay for 1,000 milliseconds so that the delay is 500
milliseconds. Figure 2-7 shows the modified sketch with the changes highlighted.
Figure 2-6 Uploading the sketch
Click on the Upload button again. Then, once the sketch has uploaded, you should see
your LED start to blink twice as fast as it did before.
Congratulations, you are now ready to start programming your Arduino. First, though,
let’s take a mini-tour of the Arduino application.
0® Blink | Arduino 0022
| N» Edt Stech Took Hdp
©@ HEH2E] 0
113
A
Blink
Turns on an LCD on Cor one second, then off Cor one second, repea
This example code is in the public domain.
void stftmpO (
// initialise the digital pm as an output.
// Fin 13 has an LED connected on most Arduino boards:
pinHode(13, OUTPUT);
)
void loop() (
digvtatmcettt, HIGH); // set the LCD on
deity(500); // wait Cor halC a second
* <13, LOU); // set the LCD oCf
delay(500); // wait Cor halC (a second
>
Binary sketch size: 1018 bytes <o t a 14336 byta aaxiauaO
Figure 2-7 Modifying the Blink sketch
The Arduino Application
Sketches in Arduino are like documents in a word processor. You can open them and copy
parts from one to another. So you see options to Open, Save, and Save As in the File
menu. You will not normally use Open because the Arduino application has the concept of
a Sketchbook where all your sketches are kept carefully organized into folders. You gain
access to the Sketchbook from the File menu. As you have just installed the Arduino
application for the first time, your Sketchbook will be empty until you create some
sketches.
As you have seen, the Arduino application comes with a selection of example sketches
that can be very useful. Having modified the Blink example sketch, if you try and save it,
you get a message that says, “Some files are marked read-only so you will need to save
this sketch in a different location.”
Try this now. Accept the default location, but change the filename to MyBlink, as
shown in Figure 2-8 .
Now if you go to the File menu and then click on Sketches, you will see MyBlink as
one of the sketches listed. If you look at your computer’s file system, on a PC, you will
find that the sketch has been written into My DocumentsYArduino, and on Mac or Linux,
they are in Documents/Arduino.
All of the sketches used in this book can be downloaded as a zip file
(Programming_Arduino.zip) from www.arduinobook.com . I suggest that now is the time
to download this file and unzip it into the Arduino folder that contains the sketches. In
other words, when you have unzipped the folder, there should be two folders in your
Arduino folder: one for the newly saved MyBlink and one called Programming Arduino
(see Figure 2-9 L The Programming Arduino folder will contain all the sketches, numbered
according to chapter, so that sketch 03-01, for example, is sketch 1 of Chapter 3 .
Figure 2-8 Saving a copy of Blink
These sketches will not appear in your Sketchbook menu until you quit the Arduino
application and restart it. Do so now. Then your Sketchbook menu should look similar to
that shown in Figure 2-10 .
Figure 2-9 Installing the sketches from the book
> MyBtlnk | Arduino 002?
Edt Sketch Tools He*>
1 New
| Open...
QrkN
QrtfO
SletchbccA
bi^hd
Ex amoves
►l
Oose
Qrla-W
Save
Ctrl-fS
Save As...
Ctrf+SMt+S
Upload to I/O Board
CtriaU
Page Setup
Qrl+Shft+P
Pnrt
QrW»
second, then off
; public detain.
sketch .03 JJ2
sketch _03_03
sketch _03_04
sketch _G3_06
sketch _03_06
sketch_03_07
sketch_03_C*3
El
Figure 2-10 Sketchbook with the book’s sketches installed
Conclusion
Your environment is all set up and ready to go.
In the next chapter, we will look at some of the basic principles of the C language that
the Arduino uses and start writing some code.
3
C Language Basics
The programming language used to program Arduinos is a language called C. In this
chapter, you get to understand the basics of the C language. You will use what you learn
here in every sketch you develop as an Arduino programmer. To get the most out of
Arduino, you need to understand these fundamentals.
Programming
It is not uncommon for people to speak more than one language. In fact, the more you
learn, the easier it seems to learn spoken languages as you start to find common patterns of
grammar and vocabulary. The same is true of programming languages. So, if you have
used any other programming language, you will quickly pick up C.
The good news is that the vocabulary of a programming language is far smaller than
that of a spoken language, and because you write it rather than say it, the dictionary can
always be at hand whenever you need to look things up. Also, the grammar and syntax of
a programming language are extremely regular, and once you come to grips with a few
simple concepts, learning more quickly becomes second nature.
It is best to think of a program—or a sketch, as programs are called in Arduino—as a
list of instructions to be carried out in the order that they are written down. For example,
suppose you were to write the following:
digitalWrite(13, HIGH);
delay(500) ;
digitalWrite (13, LOW);
These three lines would each do something. The first line would set the output of pin 13 to
HIGH. This is the pin with an LED built in to the Arduino board, so at this point the LED
would light. The second line would simply wait for 500 milliseconds (half a second) and
then the third line would turn the LED back off again. So these three lines would achieve
the goal of making the LED blink once.
You have already seen a bewildering array of punctuation used in strange ways and
w
Lire la suite
- 5.39 MB
- 15
Vous recherchez le terme ""

72

36

58