Arduino in a Nutshell 1.8
-
Upload
hemu07121990 -
Category
Documents
-
view
221 -
download
1
Transcript of Arduino in a Nutshell 1.8
-
8/13/2019 Arduino in a Nutshell 1.8
1/20
Arduino
in a Nutshell
Jan Borchers
Version 1.8 (Aug 5, 2013)
for Arduino Uno R3 & Arduino IDE 1.0.5
Latest version at: hci.rwth-aachen.de/arduino
http://hci.rwth-aachen.de/borchershttp://hci.rwth-aachen.de/borchers -
8/13/2019 Arduino in a Nutshell 1.8
2/20
-
8/13/2019 Arduino in a Nutshell 1.8
3/20
I. INTRODUCTION
The Arduino is a family of
microcontroller boardsto simplify
electronic design, prototyping
and experimenting for artists,
hackers, hobbyists, but also many
professionals. Use it as brains for your robot, to build a
new digital music instrument, or to make your house plant
tweet you when its dry. Know a little programming, but
no electronics? This book will get you started quickly.
Arduinos (we use the standard Arduino Uno R3) contain
an ATmega microcontroller thats a complete computer
with CPU, RAM, Flash memory, and input/output pins,
all on a single chip. Unlike, say, a Raspberry Pi, its
designed to attach all kinds of sensors, LEDs, small
motors and speakers, servos, etc. directly to these pins,
which can read in or output digital or analog voltages
between 0 and 5 volts. The Arduino connects to your
computer via USB, where you program it in a simple
language (C/C++, similar to Java) inside the free
Arduino IDE by uploading your compiled code to the board.
Once programmed, the Arduino can run with the USB
link back to your computer, or stand-alone without it
no keyboard or screen needed, just power.
Arduino in a Nutshell 3
-
8/13/2019 Arduino in a Nutshell 1.8
4/20
II. GETTING STARTED: BLINK AN LED!1.Get the MAKE Ultimate Micro-
controller Packwith an Arduino Uno
R3from makershed.comor your local RadioShack
($149). Also get a standard USBA-B cable and a 9V
battery. Or, for just the parts well use here, get the
Wish Listat sparkfun.com/wish_lists/46366($63).
SparkFuns Inventors Kit or Adafruits Experimenta-tion Kitalso have most parts we need, and more.
2. Download and install the Arduino IDEfor Mac, Linux
or Windows from arduino.cc. Windows users also
need to install a driver .INF file, see the website.
3. Connect your board via USB. Launch the Arduino
app. From the Tools:Board menu, select Arduino Uno.
From the Tools: Serial Portmenu, select the new serial
port(/dev/tty.usbmodem... on Macs).Open the
sketch (program) File:Examples:01.Basics:Blink . Click
thetoolbar button toupload it to your board.
After some flickering, its tiny yellow LED should blink
regularly (1 second on, 1 second off). Youve
programmed your first microcontroller!Change the
durations in delay()and upload to see the effect.
4 Arduino in a Nutshell
http://arduino.cc/https://www.sparkfun.com/wish_lists/46366https://www.sparkfun.com/wish_lists/46366http://www.makershed.com/Ultimate_Microcontroller_Pack_p/msump.htmhttp://arduino.cc/http://arduino.cc/https://www.sparkfun.com/wish_lists/46366https://www.sparkfun.com/wish_lists/46366http://www.makershed.com/Ultimate_Microcontroller_Pack_p/msump.htmhttp://www.makershed.com/Ultimate_Microcontroller_Pack_p/msump.htm -
8/13/2019 Arduino in a Nutshell 1.8
5/20
III. RUN WITHOUT A COMPUTER
1. Disconnectthe USB cable from your board.
2. Put the 9V batteryinto the battery case(takes some
fiddling).
3. Plug the barrel plugfrom the battery case into the
round socketon the Arduino, and turn on the switch
on the battery case if it has one.
4. Your sketch starts running as soon as the board is
powered up, and the LED blinks, until you turn off
power no computer needed!Thats a great way to
build small, autonomoussystems around an Arduino.
The Arduino convertsthe 9V from the battery down to 5Vusing a regulator on the board. You can also connect
anything from 712volts DC to the barrel plug socket
(2.1 mm / 5.5 mm diameter, center positive), or stick
cables directly into the Vinand GND (Ground) pins to
power the board from 712 volts great if you dont
have a barrel plug on your power source.
Dont attach a 5V power source directly to the +5V pin
though its a voltage outputpin only, and you may fry
your onboard regulator. Use the USB connector instead.
Arduino in a Nutshell 5
-
8/13/2019 Arduino in a Nutshell 1.8
6/20
IV. CONNECT A BIG LED
1.Always disconnect or turn
off your power source before
you change your circuit to
avoid shorts. They may shut
down your USB port, or
worse.
2. Bend and stick the longerlead (+) of any red, yellow
or green LEDinto Digital Pin 13 on the Arduino. Stick
its shorterlead () into the GND pin next to pin 13,
as shown.
3. Connect USB now your big LED blinkstoo.
The Blink sketch outputs ahigh signal (5V)on pin 13
using digitalWrite(led,HIGH); waits for 1000 ms (1 s)
using delay(1000);then outputs a low signal (0V) and
waits another second. This makes your LED blink. The
yellow onboard LED is also connected to pin 13, so it
blinks along.
Every Arduino sketch has one setup() method that runs
once whenever the Arduino powers up or resets, and a
loop() function that is repeatedafter that until the board
is powered off or reset again. No OS, no multiple apps!
6 Arduino in a Nutshell
Made with Fritzing.org
-
8/13/2019 Arduino in a Nutshell 1.8
7/20
V. ADD A RESISTOR
Connecting an LED directly to 5V and GND will usually
fryit because of too much current flowing through it. It
survived only because the Arduino cant provide more
than 40 mA(milliamps) of current on each pin.
Thats still more than the 20 mAstandard LEDs like and
need, however. LEDs also drop(consume) around 2Vof
forward voltage (Vf). For precise values, google, e.g.,
SparkFun red 5mm LED (SparkFunsells great basic
components and documents them well). To limit the
current, add a resistorbefore or after the LED.
Whats the right resistor value? The Arduino pins provide
5V. 2V are dropped by the LED. That leaves 3V to dropover the resistor, at a current of 20 mA. Ohms law (I use
the picture on the right to remember it) says
U (voltage) = R (resistance) x I (current), or
R = U / I = 3 V / 20 mA = 3 V / 0.02 A = 150 !.
Choose the next bigger resistoryou have; in our case its330 !(OrangeOrangeBrownGold). Use the color
code tablein the Make Pack booklet, google resistor
color codes, or get Adafruits simple Circuit Playground
app or the comprehensive Electronic Toolbox Proapp for
your iPhone/iPad.
Arduino in a Nutshell 7
UR I
http://adafruit.com/circuitplaygroundhttp://www.sparkfun.com/http://itunes.apple.com/us/app/electronic-toolbox-pro/id339158729?mt=8http://itunes.apple.com/us/app/electronic-toolbox-pro/id339158729?mt=8http://adafruit.com/circuitplaygroundhttp://adafruit.com/circuitplaygroundhttp://www.sparkfun.com/http://www.sparkfun.com/ -
8/13/2019 Arduino in a Nutshell 1.8
8/20
Disconnect USB. In themini
solderless breadboard, each
vertical columnof 5 holes is
connectedinside the board.Stick the LED, 330 "resistor
and jumper wires in as shown.
Current will now flow from
Arduino pin 13 through the
resistorand the LEDto GND
when pin 13 is HIGH.
Connect USB. Your LED will glow slightly less brightthan
before, but will last forever. The current is now around 3
V / 330 "= 9 mA. Current is the same everywhere in a
simple closed circuit without branches. So it doesnt
matter if you put the resistor before or after the LED.
8 Arduino in a Nutshell
Made with Fritzing.org
Tip: Alwaysuse red wiresfor connections to 5V, black
wiresfor connections to GND, and other colors using a
schema you like. I use yellow wiresfor outputs to LEDs,
green wiresfor outputs to motors and servos, and bluewiresfor sensor inputs. Itll help avoid confusion, short-
circuits, and fried components. Trust me; Ive been there.
-
8/13/2019 Arduino in a Nutshell 1.8
9/20
VI. DIGITAL INPUT: READ A BUTTONDisconnect USB. Add a
pushbutton, 10 k!resistor
(BrownBlackOrange
Gold) and wiresas shown.
Orient the button so the pins
that are closerare nextto
each other. These connectwhen you push it; the pins
below each other are
always connected.
Change the Blinkcode so it only blinks the LED while pin
2 is LOW: Define a global integer (int) variablepushbutton. Set it to 2 in your setup(). In your loop()
code, use if (digitalRead(button)==LOW) {...}. Dont
forget the curly braces and the double equal sign. Now,
the LED will only blink while you press the pushbutton!
We are using pin 2as a digitalinputto detect if itsvoltage is closer to GND or 5V. Every digital pin 0..13
can be an input or output pin. While input is the default,
its good style to add pinMode(pushbutton,INPUT);to
your setup()function to make it more readable.
Remember to end each statement with a semicolon.
Arduino in a Nutshell 9
Made with Fritzing.org
-
8/13/2019 Arduino in a Nutshell 1.8
10/20
The 10 k"resistor is a pullup resistor. It provides a
defined voltage (5V) to pin 2 when the button switch is
open (it pulls it up to 5V). Otherwise pin 2 would be
connected to nothing, or floating, and pick up random
electromagnetic noise like an antenna, leading to
unpredictable HIGH/LOW values when you read it.
When you push the button, it pulls pin 2 low (connects it
to GND = 0V), and a small current flows through the
resistor and switch to GND. All 5V then drop across
the resistor. Arduino inputs themselves just measure the
voltage on their pins while consuming hardly any current.
VII. INTERNAL PULLUP RESISTORS
Remove the 10 k"pullup resistor from the board. Now
your LED may be blinking or not, since pin 2 is floating.
Change setup()to say pinMode(button, INPUT_PULLUP);
and upload.This connects an internal pullup resistor to
that pin inside the ATmega chip. It works like your
external pullup resistor, but you can simplify your circuit.
10 Arduino in a Nutshell
Tip: Forhelpwith any function, click on it, then select the
Help:Find In Reference menu. I also use the language
reference at arduino.cc/en/Referencea lot; more
tutorials are at arduino.cc/en/Tutorial/Foundations.
http://arduino.cc/en/Tutorial/Foundationshttp://arduino.cc/en/Referencehttp://arduino.cc/en/Tutorial/Foundationshttp://arduino.cc/en/Tutorial/Foundationshttp://arduino.cc/en/Referencehttp://arduino.cc/en/Referencehttp://arduino.cc/en/Tutorial/Foundationshttp://arduino.cc/en/Tutorial/Foundationshttp://arduino.cc/en/Referencehttp://arduino.cc/en/Reference -
8/13/2019 Arduino in a Nutshell 1.8
11/20
VIII. READING ANALOG VALUESDisconnect USB.Remove the
pushbutton and connect a
force-sensitive resistor,the
10k"resistor and wires to
analog input A0as shown.
Youve created a voltage
divider. Normally the force
sensor has a resistance much
higher than 10 k", so A0 gets
pulled to near 0V by the
10k"resistor. Press on the
force sensor, and you lower itsresistance. It can go way
below 10 k", and the voltage on A0 then goes up to
almost 5V. So: more pressure higher voltage. Thats
how you can read continuous (analog) values.
Load File:Examples:03. Analog:AnalogInput. It usesanalogRead(...)to read the voltage on A0, and turns the
LED on and off with a delay determined by that voltage
the harder you press, the slower the LED will blink.
analogRead() returns values from 0 (0V) to 1023(5V).
Arduino in a Nutshell 11
Made with Fritzing.or
-
8/13/2019 Arduino in a Nutshell 1.8
12/20
IX. DEBUGGING USING SERIAL OUTPUT
Its hard to really see what values youre getting from the
force sensor through the analog pin just by looking at the
blink frequency of that LED. To see the actual numbers,
open File:Examples:01.Basics:AnalogReadSerial. Upload
it, then click on the magnifiertoolbar button in the top
right to open the Serial Monitor
window. Youll see values
changing as you press the sensor.
The code uses Serial.begin(9600) to open a serial
connection back to your computer in setup(), and
Serial.println(...)to output (print) numbers to that serial
connection, which end up in the Serial Monitor window
on your screen. Its also possible to send data back to
the Arduino that way, using Serial.read(...).
12 Arduino in a Nutshell
-
8/13/2019 Arduino in a Nutshell 1.8
13/20
X. ANALOG OUTPUT AND PWMDisconnect USB.Move the
yellow wire from pin 13 to pin
11. Pin 11 has a tilde (~)on
the board, which means it can
output analog values.
Change your loop() to control
the LED with analogWrite(...).
Analog values for output go
from 0 to 255, not 1023, so
divide the value from
analogRead(...) by 4 before
writing it to the LED pin.
Connect USB and upload your code. Now
you can control the brightness of your LED
by pressing on the force sensor.
Arduino uses Pulse-Width Modulation (PWM)to create
analog values itll turn the output on (5V) and off (0V)
at 500 Hz, and increase the duty cycle (relative on-time)
of that square wave signal to represent higher analog
values. 500 Hz is too fast for the human eye, so the LED
looks like its always on, just more or less bright.
Arduino in a Nutshell 13
Made with Fritzing.or
-
8/13/2019 Arduino in a Nutshell 1.8
14/20
-
8/13/2019 Arduino in a Nutshell 1.8
15/20
However, the Servo libraryfor Arduino takes care of all
this. Note the #importstatement, the Servoobject
declaration, and how the sample code then sends data to
the servo using angular values. You can easily declare,create, and control two or more Servo objects this way
essential for your robot!
Servos can take around 0.51s to reach their target
position. For a simple walking movement, you can just
send the maximum angle, wait, then send the minimumangle, wait, and so on.
Arduino in a Nutshell 15
Tip:If you run out of 5V pins on the Arduino, bring 5V
over to a columnon the breadboard, and connect things
from there (similar for GND). Use red and black wires to
keep your sanity! On larger breadboards like the large
one in the MAKE Pack, use the horizontal connector rows
(rails) along the top and bottom put 5V only to the
top red rail, and GND only to the bottom blue rail, to
avoid plugging things into the wrong one.
-
8/13/2019 Arduino in a Nutshell 1.8
16/20
XII. SHIELDS
Shields are PCBs that stack on top of the Arduinoand
connect to all Arduino pins to add all kinds of hardware
features. There are shields to play MP3 files, for WiFi,
Bluetooth, Ethernet, Zigbee, MIDI, GPS, to log data,
drive big motors, etc. shieldlist.orglists over 200!
Good shields are stackablethey have the same female
header pins as the Arduino on top.
The MAKE Pack contains a kit for a
MakerShieldprototyping shield
(see photo). Solderit together (URL
for instructions on the pack), stick
the mini breadboard onto it, and
you have a very useful board with
some built-in LEDs, buttons, even a
potentiometer for quick experiments. Its not a perfect fit
for the Arduino, but it works well enough. SparkFunhas a
similar ProtoShield.
RadioShack also carries a simpler, but more modern
prototyping shielddesigned by the Arduino team, to
solder your own parts onto. In the future, look for shields
like that one, with 18 pins at the top, which is the new
Arduino standard.
16 Arduino in a Nutshell
http://www.sparkfun.com/products/7914http://www.makershed.com/MakerShield_p/msms01.htmhttp://www.sparkfun.com/products/7914http://www.sparkfun.com/products/7914http://www.makershed.com/MakerShield_p/msms01.htmhttp://www.makershed.com/MakerShield_p/msms01.htmhttp://shieldlist.org/http://shieldlist.org/ -
8/13/2019 Arduino in a Nutshell 1.8
17/20
-
8/13/2019 Arduino in a Nutshell 1.8
18/20
Digikey.com, Mouser.com,and Farnell.comare
professional electronic component vendors. They carry
and have datasheets for everything, at the best prices if
you know what youre looking for, but they areoverwhelmingto beginners try SparkFun, MakerShed,
Adafruit or RadioShack at first.
Fritzing.orghas a nice free tool to document your
Arduino breadboard designs, and to design shields that
can then be made by submitting your files to an onlinePCB maker. I used it for all the Arduino diagrams here.
In general, if you want to hook up X to an Arduino,
google Arduino Xand youre likely to find a solution. :)
Look for the above sites among the search results.
There are countless Arduino booksout there; the gentlest
is probably Massimo Banzis Getting Started With
Arduino (he designed the Arduino board). The PDF is ten
bucks at theMakershed. Tom Igoes Making Things Talk
is excellent and beautifully designed, focusing on making
Arduinos and other electronic devices connect and shareinformation. Arduino Bots and Gadgetsis interesting if
you want to build robots. However, all Arduino books
become outdated quicklybecause the Arduino boards
and IDE have changed slightly almost every year so far.
Look for a book edition thats no older than a year.
18 Arduino in a Nutshell
http://fritzing.org/http://fritzing.org/http://digikey.com/http://mouser.com/http://farnell.com/http://fritzing.org/http://fritzing.org/http://farnell.com/http://farnell.com/http://mouser.com/http://mouser.com/http://digikey.com/http://digikey.com/ -
8/13/2019 Arduino in a Nutshell 1.8
19/20
For a current book on basic electronics(not
Arduino), there is no better choice than Make:
Electronicsby Charles Platt. Beautifully illustrated,
starts with the basics, very accessible and fun.And experiment #1 is licking a 9V battery. I read
it cover to cover to refresh my electronics knowledge.
In general, OReilly.comhas excellent books on Arduino
and other techie topics, with DRM-free versions for iPads
and in PDF, lifetime access and dropbox syncing,frequent updatesof their PDF editions, 3-for-2 deals, and
special pricing if you own the printed book.
There are dozens of different Arduino boards out there.
Stick with those documented on arduino.cc at first. Their
new Leonardo board, e.g., can act as a USB keyboard ormouse, the new Due is faster, and SparkFuns Arduino
Pro Micro (right) is a great tiny option, but for a
beginner theyre not quite as smooth to use yet.
Without a doubt this version of
this guide will become outdatedjust as quickly as all those
books. Check back at the URL on
the front cover for updates, and
meanwhile, have fun hacking
and making with Arduino!
Arduino in a Nutshell 19
http://oreilly.com/http://oreilly.com/http://oreilly.com/ -
8/13/2019 Arduino in a Nutshell 1.8
20/20
About the author
Jan Borchersis a professor of computer science and head of the
Media Computing Group at RWTH Aachen University. He works in
human-computer interaction, usability, and digital fabrication, and has
taught Arduino to students and kids since 2008.
Feel free to use this booklet for yourself, with your
friends, or in noncommercial classes. Instead of
hosting a local copy, please link back to the URLon
the cover so we can keep old versions from floating around. Ill keep
older versions of the booklet there for reference. Thanks!
This work is licensed under the Creative Commons Attribution-
NonCommercial-NoDerivs3.0 Unported License. To view a copy of this
license, visit creativecommons.org/licenses/by-nc-nd/3.0/. For otheruses, including commercial or derivative works, contact the author.
Version history
2013-08-05 (1.8): Added QR code, adjusted cover page graphics.
2013-07-31 (1.7): Clarified p.4, updated SparkFun prices, corrected pinModetypo, updated for IDE 1.0.5.
2013-01-24 (1.6): Added target audience, author info, premium headers on
wishlist. Updated pushbutton declaration. Updated for IDE 1.0.2 & 1.0.3.Cosmetic corrections throughout.
2012-08-17 (1.5): Corrected button use in Ch.VI. Changed title page, tipslayout, last page layout.
2012-08-15 (1.4): Added shieldlist.org.
2012-08-15 (1.3): Updated acknowledgements, Java reference, +5V pin,
enabling pullups, page footers, layout. Added Creative Commons license
terms.
2012-08-15 (1.2): Added: cropmarks, boldface in first chapters, Raspberry Pi,SparkFun wish list, other starter kits, Electronic Toolbox, Arduino Pro
Micro, Make: Electronics cover, double-sided layout for binding. Edited:
shields, OReilly, title, headings.
2012-08-12 (1.1): Added: missing sensor wire in ch. X+XI diagrams, Circuit
Playground, different boards, version history. Fixed typos.
2012-08-09 (1.0): Initial release, see Acknowledgements.
http://creativecommons.org/licenses/by-nc-nd/3.0/http://creativecommons.org/licenses/by-nc-nd/3.0/http://creativecommons.org/licenses/by-nc-nd/3.0/http://creativecommons.org/licenses/by-nc-nd/3.0/