Ask Manual Rev 5
Ask Manual Rev 5
Ask Manual Rev 5
www.EarthshineElectronics.com
Earthshine Design
www.EarthshineElectronics.com
2
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
©2009 M.R.McRoberts
Published 2009 by Earthshine Electronics
www.earthshineelectronics.com
Design: Mike McRoberts
License
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL"
OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK
OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF
THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE
RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
1. Definitions
a. "Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation,
adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or
performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or
adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be
considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work,
performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be
considered an Adaptation for the purpose of this License.
b. "Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances,
phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of
the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in
unmodified form along with one or more other contributions, each constituting separate and independent works in themselves,
which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation
(as defined above) for the purposes of this License.
c. "Distribute" means to make available to the public the original and copies of the Work through sale or other transfer of
ownership.
d. "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License.
e. "Original Author" means, in the case of a literary or artistic work, the individual, individuals, entity or entities who created the
Work or if no individual or entity can be identified, the publisher; and in addition (i) in the case of a performance the actors,
singers, musicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or otherwise perform literary or
artistic works or expressions of folklore; (ii) in the case of a phonogram the producer being the person or legal entity who first
fixes the sounds of a performance or other sounds; and, (iii) in the case of broadcasts, the organization that transmits the
broadcast.
f. "Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production
in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as
a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-
musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a
cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing,
painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a
process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to
geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it
is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise
considered a literary or artistic work.
g. "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this
License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this
License despite a previous violation.
h. "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations,
by any means or process, including by wire or wireless means or public digital performances; to make available to the public
Works in such a way that members of the public may access these Works from a place and at a place individually chosen by
them; to perform the Work to the public by any means or process and the communication to the public of the performances of
the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds
or images.
i. "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and
the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital
form or other electronic medium.
3
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from
limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws.
3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-
exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:
a. to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in
the Collections; and,
The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right
to make such modifications as are technically necessary to exercise the rights in other media and formats, but otherwise you have no
rights to make Adaptations. Subject to 8(f), all rights not expressly granted by Licensor are hereby reserved, including but not limited to
the rights set forth in Section 4(d).
4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:
a. You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the
Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not
offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise
the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all
notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly
Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the
Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of
the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart
from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor
You must, to the extent practicable, remove from the Collection any credit as required by Section 4(c), as requested.
b. You may not exercise any of the rights granted to You in Section 3 above in any manner that is primarily intended for or directed
toward commercial advantage or private monetary compensation. The exchange of the Work for other copyrighted works by
means of digital file-sharing or otherwise shall not be considered to be intended for or directed toward commercial advantage or
private monetary compensation, provided there is no payment of any monetary compensation in connection with the exchange
of copyrighted works.
c. If You Distribute, or Publicly Perform the Work or Collections, You must, unless a request has been made pursuant to Section 4
(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the
name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate
another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's
copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if
supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless
such URI does not refer to the copyright notice or licensing information for the Work. The credit required by this Section 4(c)
may be implemented in any reasonable manner; provided, however, that in the case of a Collection, at a minimum such credit
will appear, if a credit for all contributing authors of Collection appears, then as part of these credits and in a manner at least as
prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by
this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You
may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor
and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission
of the Original Author, Licensor and/or Attribution Parties.
i. Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through
any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect
such royalties for any exercise by You of the rights granted under this License;
ii. Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any
statutory or compulsory licensing scheme can be waived, the Licensor reserves the exclusive right to collect such
royalties for any exercise by You of the rights granted under this License if Your exercise of such rights is for a
purpose or use which is otherwise than noncommercial as permitted under Section 4(b) and otherwise waives the
right to collect royalties through any statutory or compulsory licensing scheme; and,
iii. Voluntary License Schemes. The Licensor reserves the right to collect royalties, whether individually or, in the event
that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society,
from any exercise by You of the rights granted under this License that is for a purpose or use which is otherwise than
noncommercial as permitted under Section 4(b).
e. Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce,
Distribute or Publicly Perform the Work either by itself or as part of any Collections, You must not distort, mutilate, modify or
take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation.
UNLESS OTHERWISE MUTUALLY AGREED BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO
REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR
OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR
4
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF
ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF
IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES
ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
7. Termination
a. This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License.
Individuals or entities who have received Collections from You under this License, however, will not have their licenses
terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will
survive any termination of this License.
b. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in
the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop
distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other
license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force
and effect unless terminated as stated above.
8. Miscellaneous
a. Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work
on the same terms and conditions as the license granted to You under this License.
b. If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of
the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be
reformed to the minimum extent necessary to make such provision valid and enforceable.
c. No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall
be in writing and signed by the party to be charged with such waiver or consent.
d. This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no
understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any
additional provisions that may appear in any communication from You. This License may not be modified without the mutual
written agreement of the Licensor and You.
e. The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne
Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of
1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal
Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in
which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those
treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes
additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is
not intended to restrict the license of any rights under applicable law.
Disclaimer
The information contained in this eBook is for general information purposes only. The information is provided by Mike McRoberts of
Earthshine Design and whilst we endeavour to keep the information up-to-date and correct, we make no representations or warranties of
any kind, express or implied, about the completeness, accuracy, reliability, suitability or availability with respect to the eBook or the
information, products, services, or related graphics contained on the website for any purpose. Any reliance you place on such information
is therefore strictly at your own risk.
5
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
Contents
Introduction 7 Project 11 - Piezo Sounder Melody Player 66
Project 6 - Interactive LED Chase Effect 44 Project 16 - LED Dot Matrix - Basic Animation 93
! Code Overview 49
! Code Overview 52
! Code Overview 56
! Code Overview 60
6
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
Introduction
Everything will be explained in clear and easy to follow
steps. The book contains a lot of diagrams and
photographs to make it as easy as possible to check
that you are following along with the project correctly.
7
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
8
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
9
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
Arduino, with just a few cheap components, on a Then, for a couple of quid or bucks you can replace
breadboard. the AVR chip in your Arduino with a new one. The chip
must be pre-programmed with the Arduino Bootloader
The only stipulation that the Arduino development to enable it to work with the Arduino IDE, but you can
team put on outside developers is that the Arduino either burn the Bootloader yourself if you purchase an
name can only be used exclusively by them on their AVR Programmer, or you can buy these pre-
own products and hence the clone boards have programmed from many suppliers around the world.
names such as Freeduino, Boarduino, Roboduino, etc. Of course, Earthshine Design provide pre-
programmed Arduino chips in itʼ store for a very
As the designs are open source, any clone board, reasonable price.
such as the Freeduino, is 100% compatible with the
Arduino and therefore any software, hardware, If you do a search on the Internet by simply typing
shields, etc. will all be 100% compatible with a ʻArduinoʼ into the search box of your favourite search
genuine Arduino. engine, you will be amazed at the huge amount of
websites dedicated to the Arduino. You can find a
mind boggling amount of information on projects made
with the Arduino and if you have a project in mind, will
easily find information that will help you to get your
project up and running easily.
This book and the kit will give you the necessary skills
needed to get started in this exciting and creative
The Arduino can also be extended with the use of hobby.
ʻShieldsʼ which are circuit boards containing other
devices (e.g. GPS receivers, LCD Displays, Ethernet So, now you know what an Arduino is and what you
connections, etc.) that you can simply slot into the top can do with it, letʼs open up the starter kit and dive
of your Arduino to get extra functionality. You donʼt right in.
have to use a shield if you donʼt want to as you can
make the exact same circuitry using a breadboard,
some veroboard or even by making your own PCBʼs.
10
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
Getting Started
This section will presume you have a PC running If you have a Mac these are in the drivers directory.
Windows or a Mac running OSX (10.3.9 or later). If If you have an older Mac like a PowerBook, iBook, G4
you use Linux as your Operating System, then refer to or G5, you should use the PPC drivers:
the Getting Started instructions on the Arduino website FTDIUSBSerialDriver_v2_1_9.dmg. If you have
at http://www.arduino.cc/playground/Learning/Linux a newer Mac with an Intel chip, you need the Intel
d r i v e r s :
FTDIUSBSerialDriver_v2_2_9_Intel.dmg.
Double-click to mount the disk image and run the
included FTDIUSBSerialDriver.pkg.
The latest version of the drivers can be found on the
FTDI website.
Download the Arduino IDE Now, connect the other end of the USB cable into the
USB socket on your PC or Mac. You will now see the
Download the Arduino IDE from the Arduino download small power LED (marked PWR above the RESET
page. As of the time of writing this book, the latest switch) light up to show you have power to the board.
IDE version is 0015. The file is a ZIP file so you will
need to uncompress it. Once the download has If you have a Mac, this stage of the process is
finished, unzip the file, making sure that you preserve complete and you can move on to the next Chapter. If
the folder structure as it is and do not make any you are using Windows, there are a few more steps to
changes. complete (Damn you Bill Gates!).
11
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
On Windows the Found New Hardware Wizard will Uncheck “Search removable media”. Check “Include
now open up as Windows will have detected that you this location in the search” and then click the
have connected a new piece of hardware (your Browse button. Browse to the location of the USB
Freeduino board) to your PC. Tell it NOT to connect to drivers and then click Next.
Windows update (Select No, not at this time) and
then click Next.
Make sure that “Search for the best driver in these You are now ready to upload your first Sketch.
locations” is checked.
12
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
Now that your Freeduino has been connected and the Now you need to tell the IDE the details of your USB
drivers for the USB chip have been installed, we are port, so now click on Tools again, scroll down to Serial
now ready to try out the Arduino for the first time and Port and a list of the available serial ports on your
upload your first Sketch. system will be displayed. You need to choose the one
that refers to your USB cable, which is usually listed
Navigate to your newly unzipped Arduino folder and as something like /dev/tty.usbserial-xxxx on a
look for the Arduino IDE icon, which looks something Mac or something like Com 4 on Windows so click on
like this.... that. If not sure, try each one till you find one that
works.
Double click the ICON to open up the
IDE. You will then be presented with a
blue and white screen with a default
sketch loaded inside.
13
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
14
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
When you open up the Arduino IDE it will look very The Toolbar consists of 7 buttons, underneath the
similar to the image above. If you are using Windows Toolbar is a tab, or set of tabs, with the filename of the
or Linux there will be some slight differences but the code within the tab. There is also one further button on
IDE is pretty much the same no matter what OS you the far right hand side.
are using.
Along the top is the file menu with drop down menus
The IDE is split up into the Toolbar across the top, the headed under File, Edit, Sketch, Tools and Help. The
code or Sketch Window in the centre and the Serial buttons in the Toolbar provide convenient access to
Output window at the bottom. the most commonly used functions within this file
menu.
15
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
Verify/ Serial
Stop New Open Save Upload
Compile Monitor
The Toolbar buttons are listed above. The functions of each button are as follows :-
Serial Monitor Displays serial data being sent from the Arduino
The Verify/Compile button is used to check that your The Upload to I/O Board button will upload the code
code is correct, before you upload it to your Arduino. within the current sketch window to your Arduino. You
need to make sure that you have the correct board
The Stop button will stop the Serial Monitor from and port selected (in the Tools menu) before
operating. It will also un-highlight other selected uploading. It is essential that you Save your sketch
buttons. Whilst the Serial Monitor is operating you may before you upload it to your board in case a strange
wish to press the Stop button to obtain a ʻsnapshotʼ of error causes your system to hang or the IDE to crash.
the serial data so far to examine it. This is particularly It is also advisable to Verify/Compile the code before
useful if you are sending data out to the Serial Monitor you upload to ensure there are no errors that need to
quicker than you can read it. be debugged first.
The New button will create a completely new and The Serial Monitor is a very useful tool, especially for
blank Sketch read for you to enter code into. The IDE debugging your code. The monitor displays serial data
will ask you to enter a name and a location for your being sent out from your Arduino (USB or Serial
Sketch (try to use the default location if possible) and board). You can also send serial data back to the
will then give you a blank Sketch ready to be coded. Arduino using the Serial Monitor. If you click the Serial
The tab at the top of the Sketch will now contain the Monitor button you will be presented with an image
name you have given to your new sketch. like the one above.
The Open button will present you with a list of On the left hand side you can select the Baud Rate
Sketches stored within your sketchbook as well as a that the serial data is to be sent to/from the Arduino.
list of Example sketches you can try out with various The Baud Rate is the rate, per second, that state
peripherals once connected. changes or bits (data) are sent to/from the board. The
default setting is 9600 baud, which means that if you
The Save button will save the code within the sketch were to send a text novel over the serial
window to your sketch file. Once complete you will get communications line (in this case your USB cable)
a ʻDone Saving message at the bottom of the code then 9600 letters, or symbols, of the novel, would be
window. sent per second.
16
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
To the right of this is a blank text box for you to enter Across the top of the IDE window (or across the top of
text to send back to the Arduino and a Send button to your screen if you are using a Mac) you will see the
send the text within that field. Note that no serial data various menus that you can click on to access more
can be received by the Serial Monitor unless you have menu items.
set up the code inside your sketch to do so. Similarly,
the Arduino will not receive any data sent unless you
have coded it to do so.
The menu bar across the top of the IDE looks like the
Finally, the black area is where your serial data will be
image above (and slightly different in Windows and
displayed. In the image above, the Arduino is running
Linux). I will explain the menus as they are on a Mac,
the ASCIITable sketch, that can be found in the
the details will also apply to the Windows and Linux
Communications examples. This program outputs
versions of the IDE.
ASCII characters, from the Arduino via serial (the USB
cable) to the PC where the Serial monitor then
The first menu is the Arduino
displays them.
menu. Within this is the
About Arduino option, which
To start the Serial Monitor press the Serial Monitor
when pressed will show you
button and to stop it press the Stop button. On a Mac
the current version number, a
or in Linux, Arduino board will reset itself (rerun the
list of the people involved in
code from the beginning) when you click the Serial
making this amazing device
Monitor button.
and some further information.
Once you are proficient at communicating via serial to
Underneath that is the
and from the Arduino you can use other programs
Preferences option. This will
such as Processing, Flash, MaxMSP, etc. To
bring up the Preferences
communicate between the Arduino and your PC.
window where you can change various IDe options,
such as were you default Sketchbook is stored, etc.
We will make use of the Serial Monitor later on in our
projects when we read data from sensors and get the
Also, is the Quit option, which will Quit the program.
Arduino to send that data to the Serial Monitor, in
human readable form, for us to see.
The next menu is the
File menu. In here you
The Serial Monitor window is also were you will see
get access to options to
error messages (in red text) that the IDE will display to
create a New sketch,
you when trying to connect to your board, upload code
take a look at Sketches
or verify code.
stored in your
Sketchbook (as well as
Below the Serial Monitor at the bottom left you will see
the Example Sketches),
a number. This is the current line that the cursor,
options to Save your
within the code window, is at. If you have code in your
Sketch (or Save As if
window and you move down the lines of code (using
you want to give it a different name). You also have
the ↓ key on your keyboard) you will see the number the option to upload your sketch to the I/O Board
increase as you move down the lines of code. This is (Arduino) as well as the Print options for printing out
useful for finding bugs highlighted by error messages. your code.
17
Earthshine Electronics Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
www.EarthshineElectronics.com
Next is the Edit menu. In here you The next menu in the
get options to enable you to Cut, IDE is the Tools menu.
Copy and Paste sections of code. Within this are the
Select All of your code as well as options to select the
Find certain words or phrases Board and Serial Port
within the code. Also included are we are using, as we did
the useful Undo and Redo options when setting up the
which come in handy when you Arduino for the first time.
make a mistake. Also we have the Auto
Format function that
Our next menu is the Sketch menu which gives us formats your code to make it look nicer.
access to the Verify/Compile functions and some other
useful functions you The Copy for Forum option will copy the code within
will use later on. the Sketch window, but in a format that when pasted
These include the into the Arduino forum (or most other Forums for that
Import Library option, matter) will show up the same as it is in the IDE, along
which when clicked with syntax colouring, etc.
will bring up a list of
the available The Archive Sketch option will enable you to compress
libraries, stored your sketch into a ZIP file and asks you were you want
within your to store it.
libraries folder.
Finally, the Burn Bootloader option can be used to
A Library, is a collection of code, that you can include burn the Arduino Bootloader (piece of code on the chip
in your sketch, to enhance the functionality of your to make it compatible with the Arduino IDE) to the
project. It is a way of preventing you from ʻre-inventing chip. This option can only be used if you have an AVR
the wheelʼ by reusing code already made by someone programmer and have replaced the chip in your
else for various pieces of common hardware you may Arduino or have bought blank chips to use in your own
encounter whilst using the Arduino. embedded project. Unless you plan on burning lots of
chips it is usually cheaper and easier to just buy an
For example, one of the libraries you will find is ATmega chip with the Arduino Bootloader already pre-
Stepper, which is a set of functions you can use programmed. Many online stores stock pre-
within your code to control a Stepper Motor. programmed chips and obviously these can be found
Somebody else has kindly already created all of the in the Earthshine Design store.
necessary functions necessary to control a stepper
motor and by including the Stepper library into our The final menu is the Help menu were you can find
sketch we can use those functions to control the motor help menus for finding out more information about the
as we wish. By storing commonly used code in a IDE or links to the reference pages of the Arduino
library, you can re-use that code over and over in website and other useful pages.
different projects and also hide the complicated parts
of the code from the user. Donʼt worry too much about using the IDE for now as
you will pick up the important concepts and how to use
We will go into greater detail concerning the use of it properly as we work our way through the projects.
libraries later on. Finally within the Sketch menu is the So, on that note, letʼs get on with it.
Show Sketch Menu option, which will open up the
folder were your Sketch is stored. Also, there is the
Add File option which will enable you to add another
source file to your Sketch. This functionality allows you
to split larger sketches into smaller files and then Add
them to the main Sketch.
18
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Earthshine Design
Arduino Starters Kit Manual
A Complete Beginners guide to the Arduino
The Projects 19
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 1
LED Flasher
20
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
21
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
This is simply a comment in your code and is ignored Although we can call our variables anything we want,
by the compiler (the part of the IDE that turns your every variable name in C must start with a letter, the
code into instructions the Arduino can understand rest of the name can consist of letters, numbers and
before uploading it). Any text entered behind a // underscore characters. C recognises upper and lower
command will be ignored by the compiler and is simply case characters as being different. Finally, you cannot
there for you, or anyone else that reads your code. use any of C's keywords like main, while, switch etc as
Comments are essential in your code to help you variable names. Keywords are constants, variables
understand what is going on and how your code and function names that are defined as part of the
works. Comments can also be put after commands as Arduino language. Donʼt use a variable name that is
in the next line of the program. the same as a keyword. All keywords within the sketch
will appear in red.
Later on as your projects get more complex and your
code expands into hundreds or maybe thousands of So, you have set up an area in memory to store a
lines, comments will be vital in making it easy for you number of type integer and have stored in that area
to see how it works. You may come up with an the number 10. Imagine a variable as a small box
amazing piece of code, but if you go back and look at where you can keep things. A variable is called a
that code days, weeks or months alter, you may forget variable because you can change it. Later on we will
how it all works. Comments will help you understand it carryout mathematical calculations on variables to
easily. Also, if your code is meant to be seen by other make our program do more advanced stuff.
people (and as the whole ethos of the Arduino, and
indeed the whole Open Source community is to share Next we have our setup() function
code and schematics. We hope when you start
making your own cool stuff with the Arduino you will be void setup() {
willing to share it with the world) then comments will ! pinMode(ledPin, OUTPUT);
enable that person to understand what is going on in }
your code.
An Arduino sketch must have a setup() and loop()
You can also put comments into a block statement by function otherwise it will not work. The setup() function
using the /* and */ commands. E.g. is run once and once only at the start of the program
and is where you will issue general instructions to
/* All of the text within prepare the program before the main loop runs, such
the slash and the asterisks as setting up pin modes, setting serial baud rates, etc.
is a comment and will be
ignored by the compiler */ Basically a function is a block of code assembled into
one convenient block. For example, if we created our
The IDE will automatically turn the colour of any own function to carry out a whole series of
commented text to grey. complicated mathematics that had many lines of code,
we could run that code as many times as we liked
simply by calling the function name instead of writing
22
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
void loop() {
! digitalWrite(ledPin, HIGH);
out the code again each time. Later on we will go into ! delay(1000);
functions in more detail when we start to create our ! digitalWrite(ledPin, LOW);
own. ! delay(1000);
In the case of our program the setup() function only }
has one statement to carry out. The function starts
with The loop() function is the main program function and
runs continuously as long as our Arduino is turned on.
void setup() Every statement within the loop() function (within the
curly braces) is carried out, one by one, step by step,
and here we are telling the compiler that our function until the bottom of the function is reached, then the
is called setup, that it returns no data (void) and that loop starts again at the top of the function, and so on
we pass no parameters to it (empty parenthesis). If forever or until you turn the Arduino off or press the
our function returned an integer value and we also had Reset switch.
integer values to pass to it (e.g. for the function to
process) then it would look something like this In this project we want the LED to turn on, stay on for
one second, turn off and remain off for one second,
int myFunc(int x, int y) and then repeat. Therefore, the commands to tell the
Arduino to do that are contained within the loop()
In this case we have created a function (or a block of function as we wish them to repeat over and over.
code) called myFunc. This function has been passed
two integers called X and Y. Once the function has The first statement is
finished it will then return an integer value to the point
after where our function was called in the program digitalWrite(ledPin, HIGH);
(hence int before the function name).
and this writes a HIGH or a LOW value to the digital
All of the code within the function is contained within pin within the statement (in this case ledPin, which is
the curly braces. A { symbol starts the block of code Digital Pin 10). When you set a digital pin to HIGH you
and a } symbol ends the block. Anything in between are sending out 5 volts to that pin. When you set it to
those two symbols is code that belongs to the LOW the pin becomes 0 volts, or Ground.
function.
This statement therefore sends out 5v to digital pin 10
We will go into greater detail about functions later on and turns the LED on.
so donʼt worry about them for now. All you need to
know is that in this program, we have two functions, After that is
the first function is called setup and itʼs purpose is to
setup anything necessary for our program to work delay(1000);
before the main program loop runs.
and this statement simply tells the Arduino to wait for
void setup() { 1000 milliseconds (to 1 second as there are 1000
! pinMode(ledPin, OUTPUT); milliseconds in a second) before carrying out the next
} statement which is
digitalWrite(ledPin, LOW);
23
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
which will turn off the power going to digital pin 10 and For example, if we wanted the LED to stay on for 2
therefore turn the LED off. There is then another delay seconds, then go off for half a second we could do
statement for another 1000 milliseconds and then the this:-
function ends. However, as this is our main loop()
function, the function will now start again at the void loop() {
beginning. By following the program structure step by ! digitalWrite(ledPin, HIGH);
step again we can see that it is very simple. ! delay(2000);
! digitalWrite(ledPin, LOW);
// Project 1 - LED Flasher ! delay(500);
}
int ledPin = 10;
or maybe you would like the LED to stay off for 5
void setup() { seconds and then flash briefly (250ms), like the LED
! pinMode(ledPin, OUTPUT); indicator on a car alarm then you could do this:-
}
void loop() {
void loop() { ! digitalWrite(ledPin, HIGH);
! digitalWrite(ledPin, HIGH); ! delay(250);
! delay(1000); ! digitalWrite(ledPin, LOW);
! digitalWrite(ledPin, LOW); ! delay(5000);
! delay(1000); }
}
or make the LED flash on and off very fast
We start off by assigning a variable called ledPin,
giving that variable a value of 10. void loop() {
! digitalWrite(ledPin, HIGH);
Then we move onto the setup() function where we ! delay(50);
simply set the mode for digital pin 10 as an output. ! digitalWrite(ledPin, LOW);
! delay(50);
}
In the main program loop we set Digital Pin 10 to high,
sending out 5v. Then we wait for a second and then
By varying the on and off times of the LED you create
turn off the 5v to Pin 10, before waiting another
any effect you want. Well, within the bounds of a
second. The loop then starts again at the beginning
single LED going on and off that is.
and the LED will therefore turn on and off continuously
for as long as the Arduino has power.
Before we move onto something a little more exciting
letʼs take a look at the hardware and see how it works.
Now that you know this you can modify the code to
turn the LED on for a different period of time and also
turn it off for a different time period.
24
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
25
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Black 0 0 x100
Orange 3 3 x103
Yellow 4 4 x104
White 9 9 x109
None ±20%
We need a 150Ω resistor, so if we look at the colour Our final component is an LED (Iʼm sure you can
table we see that we need 1 in the first band, which is figure out what the jumper wires do for yourself),
Brown, followed by a 5 in the next band which is which stands for Light Emitting Diode. A Diode is a
Green and we then need to multiply this by 101 (in device that permits current to flow in only one
other words add 1 zero) which is Brown in the 3rd direction. So, it is just like a valve in a water system,
band. The final band is irrelevant for our purposes as but in this case it is letting electrical current to go in
this is the tolerance. Our resistor has a gold band and one direction, but if the current tried to reverse and go
therefore has a tolerance of ±5% which means the back in the opposite direction the diode would stop it
actual value of the resistor can vary between 142.5Ω from doing so. Diodes can be useful to prevent
and 157.5Ω. We therefore need a resistor with a someone from accidently connecting the Power and
Brown, Green, Brown, Gold colour band combination Ground to the wrong terminals in a circuit and
which looks like this:- damaging the components.
If we needed a 1K (or 1 kilo-ohm) An LED is the same thing, but it also emits light. LEDʼs
resistor we would need a Brown, Black, come in all kinds of different colours and brightnesses
Red combination (1, 0, +2 zeros). If we and can also emit light in the ultraviolet and infrared
needed a 570K resistor the colours part of the spectrum (like in the LEDʼs in your TV
would be Green, Violet and Yellow. remote control).
In the same way, if you found a resistor and wanted to If you look carefully at the LED you will notice two
know what value it is you would do the same in things. One is that the legs are of different lengths and
reverse. So if you found this resistor also that on one side of the LED, instead of it being
and wanted to find out what value it cylindrical, it is flattened. These are indicators to show
was so you could store it away in you which leg is the Anode (Positive) and which is the
your nicely labelled resistor storage Cathode (Negative). The longer leg gets connected to
box, we could look at the table to the Positive Supply (3.3v) and the leg with the
see it has a value of 220Ω. flattened side goes to Ground.
26
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
If you connect the LED the wrong way, it will not Supplied with your kit is an RGB LED, which is 3
damage it (unless you put very high currents through LEDʼs in a single package. An RGB LED has a Red,
it) and indeed you can make use of that ʻfeatureʼ as Green and a Blue (hence RGB) LED in one package.
we will see later on. The LED has 4 legs, one will be a common anode or
cathode, common to all 3 LEDʼs and the other 3 will
It is essential that you then go to the anode or cathode of the individual Red,
always put a resistor in Green and Blue LEDʼs. By adjusting the brightness
series with the LED to values of the R, G and B channels of the RGB LED
ensure that the correct you can get any colour you want. The same effect can
current gets to the LED. be obtained if you used 3 separate red, green and
You can permanently blue LEDʼs.
damage the LED if you
fail to do this. Now that you know how the components work and
how the code in this project works, letʼs try something
As well as single colour a bit more interesting.
resistors you can also
obtain bi-colour and tri-
colour LEDʼs. These will have several legs coming out
of them with one of them being common (i.e. Common
anode or common cathode).
27
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 2
S.O.S. Morse Code Signaler
28
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
For this project we are going to leave // Project 2 - SOS Morse Code Signaler
the exact same circuit set up as in
Project 1, but will use some different // LED connected to digital pin 10
code to make the LED display a int ledPin = 10;
message in Morse Code. In this case,
we are going to get the LED to signal // run once, when the sketch starts
the letters S.O.S., which is the void setup()
international morse code distress signal. {
Morse Code is a type of character // sets the digital pin as output
encoding that transmits letters and pinMode(ledPin, OUTPUT);
}
numbers using patterns of On and Off. It
is therefore nicely suited to our digital // run over and over again
system as we can turn an LED on and void loop()
off in the necessary pattern to spell out {
a word or a series of characters. In this // 3 dits
case we will be signaling S.O.S. which for (int x=0; x<3; x++) {
in the Morse Code alphabet is three dits digitalWrite(ledPin, HIGH); // sets the LED on
(short flash), followed by three dahs delay(150); // waits for 150ms
(long flash), followed by three dits again. digitalWrite(ledPin, LOW); // sets the LED off
delay(100); // waits for 100ms
We can therefore now code our sketch }
to flash the LED on and off in this
// 100ms delay to cause slight gap between letters
pattern, signaling SOS. delay(100);
// 3 dahs
Enter the code for (int x=0; x<3; x++) {
digitalWrite(ledPin, HIGH); // sets the LED on
Create a new sketch and then type in delay(400); // waits for 400ms
the code listed above. Verify your code digitalWrite(ledPin, LOW); // sets the LED off
is error free and then upload it to your delay(100); // waits for 100ms
Arduino. }
29
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
The first block is what outputs the 3 dits In our code we are comparing x with the value of 3 to
see if it is smaller than 3. If x is smaller than 3, then
for (int x=0; x<3; x++) { the code in the block will repeat again.
digitalWrite(ledPin, HIGH);
delay(150); The final statement is
digitalWrite(ledPin, LOW);
delay(100);
x++
}
this is a statement to increase the value of x by 1. We
We can see that the LED is turned on for 150ms and could also have typed in x = x + 1; which would
then off for 100ms and we can see that those assign to x the value of x + 1. Note there is no need to
statements are within a set of curly braces and are put a semi-colon after this final statement in the for
therefore in a separate code block. But, when we run loop.
the sketch we can see the light flashes 3 times not just
once. You can do simple mathematics using the symbols +,
-, * and / (addition, subtraction, multiplication and
This is done using the for loop. division). E.g.
for (int x=0; x<3; x++) {
1 + 1 = 2
3 - 2 = 1
This statement is what makes the code within itʼs code
2 * 4 = 8
block execute 3 times. There are 3 parameters we
8 / 2 = 4
need to give to the for loop. These are initialisation,
condition, increment. The initialisation happens first
So, our for loop initialises the value of x to 0, then runs
and exactly once. Each time through the loop, the
the code within the block (curly braces). It then
condition is tested; if it's true, the statement block,
increases the increment, in this case adds 1 to x.
and the increment is executed, then the condition is
Finally it then checks that the condition is met, which
tested again. When the condition becomes false, the
is that x is smaller than 3 and if so repeats.
loop ends.
So, now we know how the for loop works, we can see
So, first we need to initialise a variable to be the start
in our code that there are 3 for loops, one that loops 3
number of the loop. In this case we set up variable X
times and displays the ʻditsʼ, the next one repeats 3
and set it to zero.
times and displays the ʻdahsʼ, then there is a repeat of
int x=0; the ditʼs again.
We then set a condition to decide how many times the It must be noted that the variable x has a local ʻscopeʼ,
code in the loop will execute. which means it can only be seen by the code within
itʼs own code block. Unless you initialise it before the
x<3; setup() function in which case it has ʻglobal scopeʼ and
can be seen by the entire program. If you try to access
In this case the code will loop if X is smaller than (<) 3. x outside the for loop you will get an error.
The code within a for loop will always execute once no
matter what the condition is set to. In between each for loop there is a small delay to
make a tiny visible pause between letters of SOS.
The < symbol is what is known as a ʻcomparison Finally, the code waits for 5 seconds before the main
operatorʼ. They are used to make decisions within program loop starts again from the beginning.
your code and to compare two values. The symbols
used are:- OK now letʼs move onto using multiple LEDʼs.
30
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 3
Traffic Lights
31
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
void setup() {
3 x 220Ω Resistors pinMode(redPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(greenPin, OUTPUT);
}
Jumper Wires
void loop() {
32
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 4
Interactive Traffic Lights
33
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
This time we are going to extend the previous project What you will need
to include a set of pedestrian lights and a pedestrian
push button to request to cross the road. The Arduino
will react when the button is pressed by changing the 2 x Red Diffused
state of the lights to make the cars stop and allow the LEDʼs
pedestrian to cross safely.
Yellow Diffused LED
For the first time we are able to interact with the
Arduino and cause it to do something when we 2 x Green Diffused
change the state of a button that the Arduino is
watching (i.e. Press it to change the state from open to LEDʼs
closed). In this project we will also learn how to create
our own functions. 6 x 150Ω Resistors
From now on when connecting the components we
will no longer list the breadboard and jumper wires.
Just take it as read that you will always need both of Tactile Switch
those.
34
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
35
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
void setup() {
pinMode(carRed, OUTPUT);
pinMode(carYellow, OUTPUT);
pinMode(carGreen, OUTPUT);
pinMode(pedRed, OUTPUT);
pinMode(pedGreen, OUTPUT);
pinMode(button, INPUT); // button on pin 2
// turn on the green light
digitalWrite(carGreen, HIGH);
digitalWrite(pedRed, HIGH);
}
void loop() {
int state = digitalRead(button);
/* check if button is pressed and it is
over 5 seconds since last button press */
if (state == HIGH && (millis() - changeTime) > 5000) {
// Call the function to change the lights
changeLights();
}
}
void changeLights() {
digitalWrite(carGreen, LOW); // green off
digitalWrite(carYellow, HIGH); // yellow on
delay(2000); // wait 2 seconds
36
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
37
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Next we have
By subtracting the value in the changeTime variable
pinMode(button, INPUT); from the current millis() value we can check if 5
seconds have passed since changeTime was last set.
This tells the Arduino that we want to use Digital Pin 2 The calculation of millis()-changeTime is put
(button = 2) as in INPUT. We are going to use pin 2 to inside itʼs own set of parenthesis to ensure that we
listen for button presses so itʼs mode needs to be set compare the value of state and the result of this
to input. calculation and not the value of millis() on its own.
In the main program loop we check the state of digital The symbol ʻ&&’ in between
pin 2 with this statement:-
state == HIGH
int state = digitalRead(button);
and the calculation is an example of a Boolean
This initialises an integer( yes itʼs wasteful and we Operator. In this case it means AND. To see what we
should use a boolean) called ʻstateʼ and then sets the mean by that, letʼs take a look at all of the Boolean
value of state to be the value of the digital pin 2. The Operators.
digitalRead statement reads the state of the digital
pin within the parenthesis and returns it to the integer &&! Logical AND
we have assigned it to. We can then check the value ||! Logical OR
in state to see if the button has been pressed or not. !! NOT
if (state == HIGH && (millis() - changeTime) >
5000) { These are logic statements and can be used to test
// Call the function to change the lights various conditions in if statements.
changeLights();
} && means true if both operands are true, e.g. :
When we read a digital pin using the digitalRead This will run if x is 5 or if y is 10.
command, the state of the pin will either be HIGH or
LOW. So the if command in our sketch looks like this The ! or NOT statement means true if the operand is
false, e.g. :
if (state == HIGH && (millis() - changeTime) >
5000)
if (!x) {.......
What we are doing here is checking that two
conditions have been met. The first is that the variable Will run if x is false, i.e. equals zero.
called state is high. If the button has been pressed
state will be high as we have already set it to be the You can also ʻnestʼ conditions with parenthesis, for
value read in from digital pin 2. We are also checking example
that the value of millis()-changeTime is greater
if (x==5 && (y==10 || z==25)) {.......
than 5000 (using the logical AND command &&). The
millis() function is one built into the Arduino language
In this case, the conditions within the parenthesis are
and it returns the number of milliseconds since the
processed separately and treated as a single condition
Arduino started to run the current program. Our
and then compared with the second condition. So, if
changeTime variable will initially hold no value, but
we draw a simple truth table for this statement we can
after the changeLights) function has ran we set it at
see how it works.
the end of that function to the current millis()
value.
38
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
39
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 5
LED Chase Effect
40
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
10 x Red Diffused
LEDʼs
10 x 220Ω Resistors
void setup() {
// set all pins to output
for (int x=0; x<10; x++) {
pinMode(ledPin[x], OUTPUT); }
changeTime = millis();
}
void loop() {
// if it has been ledDelay ms since last change
if ((millis() - changeTime) > ledDelay) {
changeLED();
changeTime = millis();
}
}
void changeLED() {
// turn off all LED's
for (int x=0; x<10; x++) {
digitalWrite(ledPin[x], LOW);
}
// turn on the current LED
digitalWrite(ledPin[currentLED], HIGH);
// increment by the direction value
currentLED += direction;
// change direction if we reach the end
if (currentLED == 9) {direction = -1;}
if (currentLED == 0) {direction = 1;}
}
41
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
42
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 6
Interactive LED Chase Effect
43
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
void loop() {
// read the value from the pot
ledDelay = analogRead(potPin);
// if it has been ledDelay ms since
last change
if ((millis() - changeTime) >
ledDelay) {
changeLED();
changeTime = millis();
}
}
void changeLED() {
// turn off all LED's
for (int x=0; x<10; x++) {
digitalWrite(ledPin[x], LOW);
}
// turn on the current LED
digitalWrite(ledPin[currentLED],
HIGH);
// increment by the direction value
currentLED += direction;
// change direction if we reach the
end
if (currentLED == 9) {direction =
-1;}
This is the same circuit as in Project 5, but we have
if (currentLED == 0) {direction = 1;}
simply added the potentiometer and connected it to
}
5v, Ground and Analog Pin 5.
Letʼs take a look at how this works and find our what a
potentiometer is.
44
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
45
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Exercises
46
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 7
Pulsating Lamp
47
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
void loop() {
Connect it up for (int x=0; x<180; x++) {
// convert degrees to radians
// then obtain sin value
sinVal = (sin(x*(3.1412/180)));
ledVal = int(sinVal*255);
analogWrite(ledPin, ledVal);
delay(25);
}
}
Verify and upload. You will now see your LED pulsate
on and off steadily. Instead of a simple on/off state we
are now adjusting itʼs brightness. Letʼs find out how
this works.
48
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
int ledPin = 11; But, how can we send an analog value to a digital pin?
float sinVal; Well, if we take a look at our Arduino and look at the
int ledVal; Digital Pins you can see that 6 of those pins (3, 5, 6, 9,
10 & 11) have PWM written next to them. Those pins
void setup() {
differ from the remaining digital pins in that they are
pinMode(ledPin, OUTPUT);
able to send out a PWM signal.
}
ledVal = int(sinVal*255);
49
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 8
Mood Lamp
50
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
void loop()
{
randomSeed(analogRead(0));
red = int(RGB1[0]);
green = int(RGB1[1]);
blue = int(RGB1[2]);
RGB1[0] -= INC[0];
RGB1[1] -= INC[1];
RGB1[2] -= INC[2];
}
for (int x=0; x<3; x++) {
RGB2[x] = random(556)-300;
RGB2[x] = constrain(RGB2[x], 0, 255);
delay(1000);
}
Get a piece of paper about A5 size, roll it into a }
cylinder then tape it so it remains that way. Then place
the cylinder over the top of the 3 LEDʼs.
When you run this you will see the colours slowly
change. Youʼve just made youʼre own mood lamp.
51
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
255 0 0 Red Once we have set a ʻseedʼ for our random number we
can create one using the random() function. We then
0 255 0 Green have two sets of RGB values stored in a 3 element
array. RGB1 is the RGB values we want the lamp to
0 0 255 Blue start with (in this case all zeros or off).
255 255 0 Yellow RGB1[0] = 0;
RGB1[1] = 0;
0 255 255 Cyan
RGB1[2] = 0;
255 0 255 Magenta
Then the RGB2 array is a set of random RGB values
255 255 255 White that we want the lamp to transition to,
RGB2[0] = random(256);
By adjusting the brightnesses using PWM we can get RGB2[1] = random(256);
every other colour in between too. By placing the RGB2[2] = random(256);
LEDʼs close together and by mixing their values, the
light spectra of the 3 colours added together make a In this case we have set them to a random number set
single colour. By diffusing the light with our paper by random(256) which will give is a number between 0
cylinder we ensure the colours are mixed nicely. The and 255 inclusive (as the number will always range
LEDʼs can be placed into any object that will diffuse from zero upwards).
the light or you can bounce the light off a reflective
diffuser. Try putting the lights inside a ping pong ball or If you pass a single number to the random() function
a small white plastic bottle (the thinner the plastic the then it will return a value between 0 and 1 less than
better). the number, e.g. random(1000) will return a number
between 0 and 999. If you supply two numbers as itʼs
The total range of colours we can get using PWM with parameters then it will return a random number
a range of 0 to 255 is 16,777, 216 colours between the lower number inclusive and the maximum
(256x256x256) which is way more than we would ever number (-1). E.g. random(10,100) will return a random
need. number between 10 and 99.
In the code, we start off by declaring some floating In the main program loop we first take a look at the
point arrays and also some integer variables that will start and end RGB values and work out what value is
store our RGB values as well as an increment value. needed as an increment to progress from one value to
the other in 256 steps (as the PWM value can only be
float RGB1[3]; between 0 and 255). We do this with
float RGB2[3];
float INC[3]; for (int x=0; x<3; x++) {
INC[x] = (RGB1[x] - RGB2[x]) / 256; }
int red, green, blue;
52
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
This for loop sets the INCrement values for the R, G The random number is chosen by picking a random
and B channels by working out the difference between number between 0 and 556 (256+300) and then
the two brightness values and dividing that by 256. deducting 300. The reason we do that is to try and
force primary colours from time to time to ensure we
We then have another for loop donʼt always just get pastel shades. We have 300
chances out of 556 in getting a negative number and
for (int x=0; x<256; x++) { therefore forcing a bias towards one or more of the
other two colour channels. The next command makes
red = int(RGB1[0]); sure that the numbers sent to the PWM pins are not
green = int(RGB1[1]); negative by using the constrain() function.
blue = int(RGB1[2]);
The constrain function requires 3 parameters - x, a
analogWrite (RedPin, red);
analogWrite (GreenPin, green); and b as in constrain(x, a, b) where x is the number
analogWrite (BluePin, blue); we want to constrain, a is the lower end of the range
delay(100); and b is the higher end. So, the constrain functions
looks at the value of x and makes sure it is within the
RGB1[0] -= INC[0]; range of a to b. If it is lower than a then it sets it to a, if
RGB1[1] -= INC[1]; it is higher than b it sets it to b. In our case we make
RGB1[2] -= INC[2]; sure that the number is between 0 and 255 which is
} the range or our PWM output.
and this sets the red, green and blue values to the As we use random(556)-300 for our RGB values,
values in the RGB1 array, writes those values to pins some of those values will be lower than zero and the
9, 10 and 11, then deducts the increment value then constrain function makes sure that the value sent to
repeats this process 256 times to slowly fade from one the PWM is not lower than zero.
random colour to the next. The delay of 100ms in
between each step ensures a slow and steady Forcing a bias towards one or more of the other two
progression. You can of course adjust this value if you channels ensures more vibrant and less pastel shades
want it slower or faster or you can add a potentiometer of colour and also ensures that from time to time one
to allow the user to set the speed. or more channels are turned off completely giving a
more interesting change of lights (or moods).
After we have taken 256 slow steps from one random
colour to the next, the RGB1 array will have the same
values (nearly) as the RGB2 array. We now need to
decide upon another set of 3 random values ready for
the next time. We do this with another for loop
Exercise
53
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 9
LED Fire Effect
54
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Connect it up
Now press the Verify/Compile button at the top of the
Now, first make sure that your Arduino is powered off. IDE to make sure there are no errors in your code. If
You can do this either by unplugging the USB cable or this is successful you can now click the Upload button
by taking out the Power Selector Jumper on the to upload the code to your Arduino.
Arduino board. Then connect everything up like this :-
If you have done everything right you should now see
the LEDʼs flickering in a random manner to simulate a
flame or fire effect.
So letʼs take a look at the code for this project. First The main loop then starts again causing the flicker
we declare and initialise some integer variables that light effect you can see.
will hold the values for the Digital Pins we are going to
connect our LEDʼs to. Bounce the light off a white card or a mirror onto your
wall and you will see a very realistic flame effect.
int ledPin1 = 9;
int ledPin2 = 10; As the hardware is simple and we should understand
int ledPin3 = 11; it by now we will jump right into Project 10.
Exercises
56
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 10
Serial Controlled Mood Lamp
57
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
char buffer[18];
int red, green, blue;
void setup()
{
Serial.begin(9600);
Serial.flush();
pinMode(RedPin, OUTPUT);
pinMode(GreenPin, OUTPUT);
pinMode(BluePin, OUTPUT);
}
void loop()
{
if (Serial.available() > 0) {
int index=0;
delay(100); // let the buffer fill up
int numChar = Serial.available();
if (numChar>15) {
numChar=15;
}
while (numChar--) {
buffer[index++] = Serial.read();
}
splitString(buffer);
}
}
58
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Once youʼve verified the code, upload it to your The input text is designed to accept both a lower-
Arduino. case or upper-case R, G and B and then a value
from 0 to 255. Any values over 255 will be dropped
Now when you upload the program nothing seems to down to 255 maximum. You can enter a comma or a
happen. This is because the program is waiting for space in between parameters and you can enter 1, 2
your input. Start the Serial Monitor by clicking itʼs icon or 3 LED values at any one time.
in the Arduino IDE taskbar.
E.g.
In the Serial Monitor text window you can now enter
the R, G and B values for each of the 3 LEDʼs r255 b100
manually and the LEDʼs will change to the colour you
have input. r127 b127 g127
E.g. If you enter R255 the Red LED will display at full G255, B0
brightness.
B127, R0, G255
If you enter R255, G255, then both the red and green
LEDʼs will display at full brightness. Etc.
Now enter R127, G100, B255 and you will get a nice
purplish colour.
If you type, r0, g0, b0 all the LEDʼs will turn off.
59
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
int red, green, blue; An integer called index is declared and initialised as
zero. This integer will hold the position of a pointer to
int RedPin = 11; the characters within the char array.
int GreenPin = 10;
int BluePin = 9; We then set a delay of 100. The purpose of this is to
ensure that the serial buffer (the place in memory
In our setup function we set the 3 digital pins to be where the serial data that is received is stored prior
outputs. But, before that we have the Serial.begin to processing) is full before we carry on and process
command. the data. If we donʼt do that, it is possible that the
function will execute and start to process the text
void setup()
string, before we have received all of the data. The
{
serial communications line is very slow compared to
Serial.begin(9600);
Serial.flush(); the speed the rest of the code is executing at. When
pinMode(RedPin, OUTPUT); you send a string of characters the Serial.available
pinMode(GreenPin, OUTPUT); function will immediately have a value higher than
pinMode(BluePin, OUTPUT); zero and the if function will start to execute. If we
} didnʼt have the delay(100) statement in there it could
start to execute the code within the if statement
Serial.begin tells the Arduino to start serial before all of the text string had been received and the
communications and the number within the serial data may only be the first few characters of the
parenthesis, in this case 9600, sets the baud rate line of text entered.
(characters per second) that the serial line will
communicate at. After we have waited for 100ms for the serial buffer
to fill up with the data sent, we then declare and
The Serial.flush command will flush out any initialise the numChar integer to be the number of
characters that happen to be in the serial line so that characters within the text string.
it is empty and ready for input/output.
E.g. If we sent this text in the Serial Monitor:
The serial communications line is simply a way for
the Arduino to communicate with the outside world, in R255, G255, B255
this case to and from the PC and the Arduino IDEʼs
Serial Monitor. Then the value of numChar would be 17. It is 17 and
not 16 as at the end of each line of text there is an
In the main loop we have an if statement. The invisible character called a NULL character. This is a
condition it is checking for is ʻnothingʼ symbol and simply tells the Arduino that the
end of the line of text has been reached.
if (Serial.available() > 0) {
The next if statement checks if the value of numChar
The Serial.available command checks to see if any is greater than 15 or not and if so it sets it to be 15.
characters have been sent down the serial line. If any This ensures that we donʼt overflow the array char
characters have been received then the condition is buffer[18];
60
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
61
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
and this is our way of sending data back from the Char* parameter;
Arduino to the PC. In this case the print command
sends whatever is within the parenthesis to the PC, and as we are going to use this variable to access
via the USB cable, where we can read it in the Serial elements of the ʻdataʼ array it must be the same type,
Monitor window. In this case we have sent the words hence the * symbol. You cannot pass data from one
“Data entered: “. Text must be enclosed within quotes data type type variable to another as the data must
“”. The next line is similar be converted first. This variable is another example
of one that has ʻlocal scopeʼ. It can be ʻseenʼ only by
Serial.println(data); the code within this function. If you try to access the
parameter variable outside of the splitString function
and again we have sent data back to the PC, this you will get an error.
time we send the char variable called data. The Char
type variable we have called ʻdataʼ is a copy of the We then use a strtok command, which is a very
contents of the ʻbufferʼ character array that we useful command to enable us to manipulate text
passed to the function. So, if our text string entered strings. Strtok gets itʼs name from String and Token
was as itʼs purpose is to split a string using tokens. In our
case the token it is looking for is a space or a
R255 G127 B56 comma. It is used to split text strings into smaller
strings.
Then the
We pass the ʻdataʼ array to the strtok command as
Serial.println(data); the first argument and the tokens (enclosed within
quotes) as the second argument. Hence
Command will send that text string back to the PC
and print it out in the Serial Monitor window (make parameter = strtok (data, " ,");
sure you have enabled the Serial Monitor window
first). And it splits the string at that point. So we are using it
to set ʻparameterʼ to be the part of the string up to a
This time the print command has ln on the end to space or a comma.
make it println. This simply means ʻprintʼ with a
ʻlinefeedʼ. So, if our text string was
When we print using the print command, the cursor R127 G56 B98
(the point at where the next symbol will appear)
remains at the end of whatever we have printed. Then after this statement the value of ʻparameterʼ will
When we use the println command a linefeed be
command is issued or in other words the text prints
and then the cursor drops down to the next line. R127
Serial.print("Data entered: "); as the strtok command would have split the string up
Serial.println(data); to the first occurrence of a space of a comma.
If we look at our two print commands, the first one After we have set the variable ʻparameterʼ to the part
prints out “Data entered: “ and then the cursor of the text string we want to strip out (i.e. The bit up
remains at the end of that text. The next print to the first space or comma) we then enter a while
command will print ʻdataʼ, or in other words the loop whose condition is that parameter is not empty
contents of the array called ʻbufferʼ and then issue a (i.e. We havenʼt reached the end of the string) using
linefeed, or drop the cursor down to the next line.
This means that if we issue another print or println while (parameter != NULL) {
statement after this whatever is printed in the Serial
Monitor window will appear on the next line Within the loop we call our second function
underneath the last.
setLED(parameter);
62
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Which we will look at later on. Then it sets the if ((data[0] == 'r') || (data[0] == 'R'))
variable ʻparameterʼ to the next part of the string up {
to the next space or comma. We do this by passing int Ans = strtol(data+1, NULL, 10);
to strtok a NULL parameter Ans = constrain(Ans,0,255);
analogWrite(RedPin, Ans);
Serial.print("Red is set to: ");
parameter = strtok (NULL, " ,");
Serial.println(Ans);
}
This tells the strtok command to carry on where it last if ((data[0] == 'g') || (data[0] == 'G'))
left off. {
int Ans = strtol(data+1, NULL, 10);
So this whole part of the function Ans = constrain(Ans,0,255);
analogWrite(GreenPin, Ans);
char* parameter; Serial.print("Green is set to: ");
parameter = strtok (data, " ,"); Serial.println(Ans);
while (parameter != NULL) { }
setLED(parameter); if ((data[0] == 'b') || (data[0] == 'B'))
parameter = strtok (NULL, " ,"); {
} int Ans = strtol(data+1, NULL, 10);
Ans = constrain(Ans,0,255);
is simply stripping out each part of the text string that analogWrite(BluePin, Ans);
is separated by spaces or commas and sending that Serial.print("Blue is set to: ");
part of the string to the next function called setLED(). Serial.println(Ans);
}
}
The final part of this function simply fills the buffer
array with NULL character, which is done with the /0
symbol and then flushes the Serial data out of the
We can see that this function contains 3 very similar
Serial buffer ready for the next set of data to be
if statements. We will therefore take a look at just one
entered.
of them as the other 2 are almost identical.
// Clear the text and serial buffers
for (int x=0; x<16; x++) { if ((data[0] == 'r') || (data[0] == 'R')) {
buffer[x]='\0'; int Ans = strtol(data+1, NULL, 10);
} Ans = constrain(Ans,0,255);
Serial.flush(); analogWrite(RedPin, Ans);
Serial.print("Red is set to: ");
Serial.println(Ans);
The setLED function is going to take each part of the
}
text string and set the corresponding LED to the
colour we have chosen. So, if the text string we enter
The if statement checks that the first character in the
is
string data[0] is either the letter r or R (upper case
and lower case characters are totally different as far
! G125 B55
as C is concerned. We use the logical OR command
whose symbol is || to check if the letter is an r OR an
Then the splitString() function splits that into the two
R as either will do.
separate components
If it is an r or an R then the if statement knows we
! G125
wish to change the brightness of the Red LED and so
! B55
the code within executes. First we declare an integer
called Ans (which has scope local to the setLED
and send that shortened text string onto the setLED()
function only) and use the strtol (String to long
function, which will read it, decide what LED we have
integer) command to convert the characters after the
chosen and set it to the corresponding brightness
letter R to an integer. The strtol command takes 3
value.
parameters and these are the string we are passing
it, a pointer to the character after the integer (which
So letʼs take a look at the second function called
we donʼt use as we have already stripped the string
setLED().
using the strtok command and hence pass a NULL
character) and then the ʻbaseʼ, which in our case is
void setLED(char* data) {
base 10 as we are using normal decimal numbers
63
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
(as opposed to binary, octal or hexadecimal which exactly the same but for the Green and the Blue
would be base 2, 8 and 16 respectively). So in other LEDʼs.
words we declare an integer and set it to the value of
the text string after the letter R (or the number bit). We have covered a lot of ground and a lot of new
concepts in this project. To make sure you
Next we use the constrain command to make sure understand exactly what is going on in this code I am
that Ans goes from 0 to 255 and no more. We then going to set the project code side by side with
carry out an analogWrite command to the red pin and pseudo-code (an fake computer language that is
send it the value of Ans. The code then sends out essentially the computer language translated into a
“Red is set to: “ followed by the value of Ans back to language humans can understand).
the Serial Monitor. The other two if statements do
// Project 10 - Serial controlled RGB Lamp A comment with the project number and name
64
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Hopefully you can use this ʻpseudo-codeʼ to make We are now going to leave LEDʼs behind for a little
sure you understand exactly what is going on in this while and look at how to makes sounds with your
projects code. Arduino.
65
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 11
Piezo Sounder Melody PLayer
66
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Piezo Disc
Terminal Block
(courtesy of http://www.arduino.cc/en/Tutorial/Melody)
void setup() {
pinMode(speakerPin, OUTPUT);
}
void loop() {
for (int i = 0; i < length; i++) {
if (notes[i] == ' ') {
delay(beats[i] * tempo); // rest
} else {
playNote(notes[i], beats[i] * tempo);
}
67
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
The tune we are going to play is made up of 15 rest in the notes. We then have an else statement.
notes.
else {
playNote(notes[i], beats[i] * tempo);
int length = 15; // the number of notes
}
All that happens in setup() is we assign the speaker After if/else statement has been carried out, there is
pin (9) as an output. a delay whose value is calculated by dividing tempo
by 2.
void setup() {
pinMode(speakerPin, OUTPUT); delay(tempo / 2);
}
68
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
The first function that is called from the main program corresponding tone using in the tones[] array using a
loop is playNote. note length of ʻdurationʼ.
void playNote(char note, int duration) { The second function is called playTone.
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a',
'b', 'C' };
void playTone(int tone, int duration) {
int tones[] = { 1915, 1700, 1519, 1432, 1275,
for (long i = 0; i < duration * 1000L; i +=
1136, 1014, 956 };
tone * 2) {
// play the tone corresponding to the note name
digitalWrite(speakerPin, HIGH);
for (int i = 0; i < 8; i++) {
delayMicroseconds(tone);
if (names[i] == note) {
digitalWrite(speakerPin, LOW);
playTone(tones[i], duration);
delayMicroseconds(tone);
}
}
}
}
}
Two parameters have been passed to the function Two parameters are passed to this function. The first
and within the function these have been given the is the tone (in kilohertz) that we want the piezo
names note (character) and duration (integer). speaker to reproduce and the second is the duration
(made up by calculating beats[i] * tempo.
The function sets up a local variable array of data
type char called ʻnamesʼ. This variable has local The function starts a for loop
scope so is only visible to this function and not
for (long i = 0; i < duration * 1000L; i += tone
outside of it. * 2)
This array stores the names of the notes from middle As each for loop must be of a different length to
C to high C. make each note the same length (as the delay differs
between clicks to produce the desired frequency) the
We then create another array of data type integer for loop will run to ʻdurationʼ multiplied by 1000 and
and this array stores numbers that correspond to the the increment of the loop is the value of ʻtoneʼ
frequency of the tones, in Kilohertz, of each of the multiplied by 2.
notes in the names[] array.
Inside the for loop we simply make the pin connected
int tones[] = { 1915, 1700, 1519, 1432, 1275,
1136, 1014, 956 }; to the piezo speaker go high, wait a short period of
time, then go low, then wait another short period of
After setting up the two arrays there is a for loop that time, then repeat.
looks through the 8 notes in the names[] array and
digitalWrite(speakerPin, HIGH);
compares it to the note sent to the function. delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
for (int i = 0; i < 8; i++) { delayMicroseconds(tone);
if (names[i] == note) {
playTone(tones[i], duration);
} These repetitive clicks, of different lengths and with
} different pauses (of only microseconds in length) in
between clicks, makes the piezo produce a tone of
The tune that is sent to this function is varying frequencies.
ʻccggaagffeeddc’ so the first note will be a middle C.
The for loop compares that note with the notes in the
names[] array and if there is a match, calls up the
second function, called playTone, to play the
69
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Exercise
2. Write a program to
make a rising and fal
similar to a car alarm ling tone from the pie
or police siren. zo,
70
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 12
Serial Temperature Sensor
71
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
int potPin = 0;
float temperature = 0;
void setup()
{
Serial.begin(9600);
Serial.println("LM35 Thermometer ");
analogReference(INTERNAL);
}
void loop() {
int span = 20;
int aRead = 0;
for (int i = 0; i < span; i++) {
aRead = aRead+analogRead(potPin);
}
aRead = aRead / 20;
temperature = ((100*1.1*aRead)/1024)*10;
// convert voltage to temperature
Serial.print("Analog in reading: ");
Serial.print(long(aRead));
// print temperature value on serial monitor
Serial.print(" - Calculated Temp: ");
printTenths(long(temperature));
delay(500);
}
72
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
73
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
The, after the for loop, the total value of aRead is After we have calculated the temperature, the program
divided by 20 (or whatever value is stored in ʻspanʼ). then prints out “Analog in reading: : to the Serial
This gives us an average value read in from the Monitor, then displays the value of aRead followed by
temperature sensor, averaged out over 20 consecutive “Calculated Temp: “ and the value stored in
readings. The reason we do that is because analog ʻtemperatureʼ. (passed to the printTenths function).
devices, such as our temperature sensor, are prone to
fluctuations caused by electrical noise in the circuit, The value of ʻtemperatureʼ has the word long before it
interference, etc. and therefore each reading, out of a when we pass it to printTenths. This is an example of
set of 20, will differ slightly. To give a more accurate ʻcastingʼ or forcing one variable type to become
reading, we take 20 values from the sensor and then another. The printTenths function is expecting an
average them out to give us a more accurate reading. integer, we pass it a long type instead. Any values
The readings are taken one after the other, without after the decimal point are truncated (ignored).
any delay and therefore it will take only a tiny fraction
of a second for the Arduino to perform this task. E.g.
This calculation multiplies the value from the digital pin Finally the program delays half a second and then
by 1.1 (our reference voltage) and again by 100. What repeats.
this does is stretch out or values from 0 to 930 to be a
74
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
75
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 13
Light Sensor
76
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
void loop()
{
! // Read in value from LDR
! lightVal = analogRead(ldrPin);
! // Turn LED on
! digitalWrite(ledPin, HIGH);
! // Delay of length lightVal
! delay(lightVal);
! // Turn LED off
! digitalWrite(ledPin, LOW);
! // Delay again
! delay(lightVal);
}
77
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
int ledPin = 6;
As more light falls on the LDR the value read in from
// Pin connected to LDR
Analog Pin 0 decreases and the LED flashes faster.
int ldrPin = 0;
// Value read from LDR
int lightVal = 0; Letʼs find out how this circuit works.
! pinMode(ledPin, OUTPUT);
78
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Our LDR is connected in series with 3 x Held under a bright light 150Ω
1.5KΩ Resistors and the input into Analog
Pin 0 is between these 2. This is what is
known as a voltage divider. We will explain So using these values of resistance, the input voltage
this in a second. and the calculation we listed above, the approx. output
voltage can be calculated thus:
The 3 x 1.5K give a total resistance of 4500Ω (4.5KΩ).
Resistors in series have a resistance equal to the sum
Vin R1 R2 Vout
of their individual resistances. In this case the value is
3 x 1500 = 4500.
5v 4500Ω 8000Ω 3.2v
A voltage divider is a circuit consisting of two
resistances across a voltage supply. An output 5v 4500Ω 1000Ω 0.9v
between the two resistances will give a lower voltage
depending on the values of the two resistors. 5v 4500Ω 150Ω 0.16v
The diagram on the left As you can see, as the resistance of the LDR (R2)
shows a voltage divider decreases, the voltage out of the voltage divider
made up of two resistors. decreases also, making the value read in from the
The value of Vout will be Analog Pin lower and therefore decreasing the delay
lower than the value of Vin. making the LED flash faster.
To work out the value of Vout A voltage divider circuit could also be used for
we use the following decreasing a voltage to a lower one if you used 2
calculation: standard resistors, rather than a resistor and an LDR
(which is a variable resistor). Alternatively, you could
use a potentiometer so you can adjust the voltage out
R2 by turning the knob.
Vout = Vin
R1 + R2
79
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 14
Shift Register 8-Bit Binary Counter
80
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
81
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
// Project 14
void setup() {
//set pins to output
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}
void loop() {
//count from 0 to 255
for (int i = 0; i < 256; i++) {
//set latchPin low to allow data flow
digitalWrite(latchPin, LOW);
shiftOut(i);
//set latchPin to high to lock and send data
digitalWrite(latchPin, HIGH);
delay(500);
}
}
82
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
000,001,002,003,004,005,006,007,008,009 255 1 1 1 1 1 1 1 1
010,011,012,013,014,015,016,017,018,019
020,021,023 ………
...and so on.
In Binary the exact same thing happens, except the
highest digit is 1 so adding 1 to 1 results in the digit So now that you understand binary (or at least I hope
resetting to zero and 1 being added to the column to you do) we will first take a look at the hardware, before
the left. looking at the code.
000, 001
010, 011
100, 101... TOP TIP
An 8 bit number (or a byte) is represented like this You can use Google to convert between a Decimal
and a Binary number and vice versa.
27 26 25 24 23 22 21 20 E.g to convert 171 Decimal to Binary type
128 64 32 16 8 4 2 1
171 in Binary
Into the Google search box returns
0 1 0 0 1 0 1 1 171 = 0b10101011
The 0b prefix shows the number is a Binary number
The number above in Binary is 1001011 and in
and not a Decimal number.
Decimal this is 75. So the answer is 10101011.
This is worked out like this : To convert a Binary number to decimal do the
reverse. E.g. Enter
1x1=1 0b11001100 in Decimal
1x2=2 Into the search box returns
1x8=8 0b11001100 = 204
1 x 64 = 64
83
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
We are using a Shift Register. Specifically the To use the Shift Register the Latch Pin and Clock Pin
74HC595 type of Shift Register. This type of Shift must be set to LOW. The Latch Pin will remain at LOW
Register is an 8-bit serial-in, serial or parallel-out shift until all 8 bits have been set. This allows data to be
register with output latches. This means that you can entered into the Storage Register (the storage register
send data in to the Shift Register in series and send it is simply a place inside the IC for storing a 1 or a 0).
out in parallel. In series means 1 bit at a time. Parallel We then present either a HIGH or LOW signal at the
means lots of bits (in this case 8) at a time. So you Data Pin and then set the Clock Pin to HIGH. By
give the Shift Register data (in the form of 1ʼs and 0ʼs) setting the Clock Pin to HIGH this stores the data
one bit at a time, then send out 8 bits all at the exact presented at the Data Pin into the Storage Register.
same time. Each bit is shunted along as the next bit is Once this is done we set the Clock to LOW again,
entered. If a 9th bit is entered before the Latch is set then present the next bit of data at the Data Pin. Once
to HIGH then the first bit entered will be shunted off we have done this 8 times, we have sent a full 8 bit
the end of the row and be lost forever. number into the 595. The Latch Pin is now raised
which transfers the data from the Storage Register
Shift Registers are usually used for serial to parallel into the Shift Register and outputs it from QA to QH
data conversion. In our case, as (Pin 15, 1 to 7).
the data that is output is 1ʼs and
0ʼs (or 0v and 3.3v) we can use it I have connected a Logic Analyser (a device that lets
to turn on and off a bank of 8 you see the 1ʼs and 0ʼs coming out of a digital device)t
LEDʼs. o my 595 whilst this program is running and the image
at the bottom of the page shows the output.
The Shift Register, for this
project, requires only 3 inputs The sequence of events here is:
from the Arduino. The outputs of
the Arduino and the inputs of the 595 are as follows: Pin State Description
Latch LOW Latch lowered to allow data to be entered
Arduino 595 Description
Pin Pin Data HIGH First bit of data (1)
Clock HIGH Clock goes HIGH. Data stored.
8 12 Storage Register Clock Input
Clock LOW Ready for next Bit. Prevent any new data.
11 14 Serial Data Input Data HIGH 2nd bit of data (1)
Clock HIGH 2nd bit stored
12 11 Shift Register Clock Input
... ... …
Data LOW 8th bit of data (0)
We are going to refer to Pin 12 as the Clock Pin, Pin
14 as the Data Pin and Pin 11 as the Latch Pin. Clock HIGH Store the data
Clock LOW Prevent any new data being stored
Imagine the Latch as a gate that will allow data to Latch HIGH Send 8 bits out in parallel
escape from the 595. When the gate is lowered (LOW)
the data in the 595 cannot get out, but data can be
entered. When the gate is raised (HIGH) data can no In the image below, you can see that the binary
longer be entered, but the data in the SHift Register is number 00110111 (reading from right to left) or
Decimal 55 has been sent to the chip.
84
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
So to summarise the use of a single Shift Register in this project, we have 8 LEDʼs attached to the 8 outputs of
the Register. The Latch is set to LOW to enable data entry. Data is sent to the Data Pin, one bit at a time, the
CLock Pin is set to HIGH to store that data, then back down to low ready for the next bit. After all 8 bits have
been entered, the latch is set to HIGH which prevents further data entry and sets the 8 output pins to either High
(3.3v or LOW (0 volts) depending on the state of the Register.
If you want to read up more about the shift register you have in your kit, then take a look at the serial number on
the IC (e.g. 74HC595N or SN74HC595N, etc.) and enter that into Google. You can then find the specific
datasheet for the IC and read more about it.
As the outputs are simply ONʼs and OFFʼs of an output voltage, they can also be used to switch other low
powered (or even high powered devices with the use of transistors or relays) devices on and off or to send data
to devices (e.g. An old dot matrix printer or other serial device).
All of the 595 Shift Registers from any manufacturer are just about identical to each other. There are also larger
Shift Registers with 16 outputs or higher. Some ICʼs advertised as LED Driver Chips are, when you examine the
datasheet, simply larger Shift Registers (e.g. The M5450 and M5451 from STMicroelectronics).
85
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Then, in setup, the pins are all set to Outputs. digitalWrite(dataPin, LOW);
digitalWrite(clockPin, LOW);
pinMode(latchPin, OUTPUT); After this, we are ready to send the 8 bits in series to
pinMode(clockPin, OUTPUT); the 595 one bit at a time.
pinMode(dataPin, OUTPUT);
A for loop that iterates 8 times is set up.
The main loop simply runs a for loop counting from 0
to 255. On each iteration of the loop the latchPin is set for (int i=0; i<=7; i++) {
to LOW to enable data entry, then the function called
shiftOut is called, passing the value of i in the for loop The clock pin is set low prior to sending a Data bit.
to the function. Then the latchpin is set to HIGH,
preventing further data entry and setting the outputs digitalWrite(clockPin, LOW);
from the 8 pins. Finally there is a delay of half a
second before the next iteration of the loop Now an if/else statement determines if the pinState
commences. variable should be set to a 1 or a 0.
86
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Bitwise Operators
The Bitwise Operators perform calculations at the bit ! 0 0 1 1! Operand1
level on variables. There are 6 common Bitwise ! 0 1 0 1! Operand2
Operators and these are: ! -------
! 0 1 1 0! (Operand1 ^ Operand2)
! &! Bitwise and
! |! Bitwise or Bitwise NOT (~)
! ^! Bitwise xor
! ~! Bitwise not The Bitwise NOT Operator is applied to a single
! <<! Bitshift left
operand to its right.
! >>! Bitshift right
Bitwise OR (|)
! 0 0 1 1! Operand1
! 0 1 0 1! Operand2
! -------
! 0 1 1 1! (Operand1 | Operand2)
87
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 15
Dual 8-Bit Binary Counters
89
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
90
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Enter the Code When you run this code you will see the Red set of
LEDʼs count up (in Binary) from 0 to 255 and the
Enter the following code and upload it to your Arduino. Green LEDʼs count down from 255 to 0 at the same
time.
// Project 15
void setup() {
//set pins to output
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}
void loop() {
//count from 0 to 255
for (int i = 0; i < 255; i++) {
//set latchPin low to allow data flow
digitalWrite(latchPin, LOW);
shiftOut(i);
shiftOut(255-i);
//set latchPin to high to lock and send data
digitalWrite(latchPin, HIGH);
delay(250 );
}
}
boolean pinState;
digitalWrite(clockPin, LOW);
}
91
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
The 2nd 595 is wired up exactly the same as the 1st An almost unlimited number of 595 chips can be daisy
one. The clock and latch pins are tied to the pins of chained in this manner.
the first 595. However, we have a wire going from Pin
9 on IC 1 to Pin 14 on IC 2. Pin 9 is the data output pin
and pin 14 is the data input pin.
Exercise
92
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Project 16
LED Dot Matrix -
Basic Animation
93
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
94
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
// Project 16
#include <TimerOne.h>
uint8_t led[8];
long counter1 = 0;
long counter2 = 0;
void setup() {
//set pins to output
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
led[0] = B11111111;
led[1] = B10000001;
led[2] = B10111101;
led[3] = B10100101;
led[4] = B10100101;
led[5] = B10111101;
led[6] = B10000001;
led[7] = B11111111;
Timer1.initialize(10000);
Timer1.attachInterrupt(screenUpdate);
}
void loop() {
counter1++;
if (counter1 >=100000) {counter2++;}
if (counter2 >= 10000) {
counter1 = 0;
counter2 = 0;
for (int i=0; i<8; i++) {
led[i]= ~led[i];
}
}
}
void screenUpdate() {
uint8_t row = B00000001;
for (byte k = 0; k < 9; k++) {
// Open up the latch ready to receive data
! digitalWrite(latchPin, LOW);
shiftIt(~row );
shiftIt(led[k] ); // LED array
// Close the latch, sending the data in the registers out to the
matrix
digitalWrite(latchPin, HIGH); row = row << 1;
}
}
95
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
boolean pinState;
//stop shifting
digitalWrite(clockPin, LOW);
}
When this code is run, you will see a very basic animation of a heart that flicks back and forth between a positive
and a negative image.
Before this code will work you will need to download the TimerOne library from the Arduino website. It can be
downloaded from http://www.arduino.cc/playground/uploads/Code/TimerOne.zip
Once downloaded, unzip the package and place the folder, called TimerOne, into the hardware/libraries
directory.
96
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
A typical single colour 8x8 Dot Matrix unit will have 16 This is because we are applying power to row 3 and 6
pins, 8 for each row and 8 for each column. You can and grounding columns 3 and 5. We canʼt turn off the
also obtain bi-colour units (e.g. Red and Green) as unwanted LEDʼs without turning off the ones we want
well as Full Colour RGB (Red, Green and Blue) Units, on also. It would appear that there is no way we can
such as is used in large video walls. Bi or Tri (RGB) light just the two required LEDʼs with the rows and
colour units have 2 or 3 LEDʼs in each pixel of the columns wired together as they are. The only way this
array. These are very small and next to each other. would work would be to have a separate pinout for
each LED meaning the number of pins would jump
By turning on different combinations of Red, Green or from 16 to 65. A 65 pin Dot Matrix unit would be very
Blue in each pixel and by varying their brightnesses, hard to wire up and also to control as youʼd need a
any colour can be obtained. microcontroller with at least 64 digital outputs.
The reason the rows and columns are all wired Is there a way to get around this problem? Yes there
together is to minimise the number of pins required. If is, and it is called ʻmultiplexingʼ (or muxing).
this was not the case, a single colour 8x8 Dot Matrix
unit would have to have 65 pins. One for each LED Multiplexing
and a common Anode or Cathode connector. By wiring
the rows and columns together only 16 pin outs are Multiplexing is the technique of switching one row of
required. the display on at a time. By selecting the appropriate
columns that we want an LED to be lit in that row and
However, this now poses a problem. If we want a then turning the power to that row (or the other way
particular LED to light in a certain position. If for round for common cathode displays) on, the chosen
example we had a Common Anode unit and wanted to LEDʼs in that row will illuminate. That row is then
light the LED at X, Y position 5, 3 (5th column, 3rd turned off and the next row is turned on, again with the
row), then we would apply a current to the 3rd Row appropriate columns chosen and the LEDʼs in the 2nd
and Ground the 5th column pin. The LED in the 5th row will now illuminate. Repeat with each row till we
column and 3rd row would now light. get to the bottom and then start again at the top.
97
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
98
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
After this the pins used to interface with the shift Timer1.initialize(10000);
registers are declared. Timer1.attachInterrupt(screenUpdate);
//Pin connected to Pin 12 of 74HC595 (Latch) In the main loop we set a counter that counts to
int latchPin = 8; 1,000,000,000 to create a delay. This is done by two
//Pin connected to Pin 11 of 74HC595 (Clock) loops, one that loops 100,000 times and the other one
int clockPin = 12; that loops 10,000 times. I have done it this way,
//Pin connected to Pin 14 of 74HC595 (Data)
instead of using delay() as the current version of the
int dataPin = 11;
Timer1 library seems to interfere with the delay
function. You may try delay() instead and see if it
We now create an array of type uint8_t that has 8
works (updates to the libraries are occurring from time
elements and two counters of type long. An uint8_t is
to time). counter1 and counter2 are reset to zero once
simply the same as a byte. It is an unsigned integer of
they reach their targets.
8 bits.
void loop() {
uint8_t led[8]; counter1++;
long counter1 = 0; if (counter1 >=100000) {counter2++;}
long counter2 = 0; if (counter2 >= 10000) {
counter1 = 0;
The led[8] array will be used to store the image we are counter2 = 0;
going to display on the Dot Matrix display. The
counters will be used to create a delay. Once the end of the delay is reached, a for loop cycles
through each of the 8 elements of the led array and
In the setup routine we set the latch, clock and data inverts the contents using the ~ or NOT bitwise
pins as outputs. operator.
Once the pins have been set to outputs, the led array This simply turns the binary image into a negative of
is loaded with the 8-bit binary images that will be itself by turning all 1ʼs to 0ʼs and all 0ʼs to 1ʼs.
displayed in each row of the 8x8 Dot Matrix Display.
99
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
We now have the screenUpdate function. This is the Once we have shifted out that current rows 8 bits the
function that the interrupt is activating every 100th of a value in row is bitshifted left 1 place so that the next
second. This whole routine is very important as it is row is displayed.
responsible for ensuring our LEDʼs in the DOt Matrix
array are lit correctly and displays the image we wish row = row << 1;
to convey. It is a very simple but very effective
function. Remember from the hardware overview that the
multiplexing routine is only displaying one row at a
void screenUpdate() { time, turning it off and then displaying the next row.
uint8_t row = B00000001; This is done at 100Hz which is too fast for the human
for (byte k = 0; k < 9; k++) { eye to see the flicker.
// Open up the latch ready to receive
data Finally, we have a ShiftOut function, the same as in
! digitalWrite(latchPin, LOW);
the previous Shift Register based projects, that sends
shiftIt(~row );
the data out to the 74HC595 chips.
shiftIt(led[k] ); // LED array
void shiftIt(byte dataOut)
// Close the latch, sending the data in
the registers out to the matrix
digitalWrite(latchPin, HIGH); row = row So, the basic concept here is that we have an interruot
<< 1; routine that executes every 100th of a second. In that
} routine we simply take a look at the contents of a
} screen buffer array (in this case led[] ) and display it
on the dot matrix unit one row at a time, but do this so
An 8 bit integer called ʻrowʼ is declared and initialised fast that to the human eye it all seems to be lit at once.
with the value B00000001.
The main loop of the program is simply changing the
uint8_t row = B00000001; contents of the screen buffer array and letting the ISR
do the rest.
We now simply cycle through the led array and send
that data out to the Shift Registers preceded by the The animation in this project is very simple, but by
row (which is processed with the bitwise NOT ~ to manipulating the 1ʼs and 0ʼs in the buffer we can make
make sure the row we want to display is turned off, or anything we like appear on the Dot Matrix unit from
grounded). shapes to scrolling text.
for (byte k = 0; k < 9; k++) {
// Open up the latch ready to receive
data
! digitalWrite(latchPin, LOW);
shiftIt(~row );
shiftIt(led[k] ); // LED array
100
Earthshine Design Arduino Starters Kit Manual - A Complete Beginners Guide to the Arduino
Brought to you by
www.EarthshineElectronics.com
mike@earthshineelectronics.com
© 2009
101