100% found this document useful (2 votes)
373 views

Arduino Inventors Kit Manual

This document is the manual for the Arduino Inventors Kit. It contains instructions for 14 projects of increasing complexity to teach users about the Arduino hardware and software. The kit contents include an Arduino Uno board, sensors, actuators, and other electronic components. The manual explains how to set up the Arduino integrated development environment and guides users step-by-step through each project, providing code examples and explanations of how the hardware and software work together. The goal is to take users from beginner to intermediate skill levels in using Arduinos for electronic projects.

Uploaded by

William Cruz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
373 views

Arduino Inventors Kit Manual

This document is the manual for the Arduino Inventors Kit. It contains instructions for 14 projects of increasing complexity to teach users about the Arduino hardware and software. The kit contents include an Arduino Uno board, sensors, actuators, and other electronic components. The manual explains how to set up the Arduino integrated development environment and guides users step-by-step through each project, providing code examples and explanations of how the hardware and software work together. The goal is to take users from beginner to intermediate skill levels in using Arduinos for electronic projects.

Uploaded by

William Cruz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

www.b2cqshop.

com Ebay store: b2cqshop , E-qstore

Arduino Inventors Kit Manual

B2CQSHOP

2012 - 3 - 04

www.b2cshop.com Ebay store: b2cqshop , E-qstore 1


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Contents
The Kit Contents ...............................................................................................................................4
Introduction.......................................................................................................................................5
What exactly is an Arduino? .............................................................................................................7
Getting Started ................................................................................................................................11
COMPONENT DETAILS...............................................................................................................18

Project 1 - LED Flasher ..................................................................................................................24


Project 1 - Code verview.................................................................................................................26
Project 1 - Hardware Overview.......................................................................................................31

Project 2 - 8 LEDS Multiple LEDs .................................................................................................36


Project 2 – Hardware Overview......................................................................................................43

Project 3 - Make music ...................................................................................................................45


Project 3 - Code Overview..............................................................................................................48

Project 4 – Respond to buttons..................................................................................................52


Project 4 – Code Overview .......................................................................................................54

Project 5 – Detect ambient light................................................................................................56

Project 6 – Read a volume knob ..................................................................................................59


Project 6 – Code Overview .......................................................................................................61

Project 7 – Control DC motor ......................................................................................................63


Project 7 – Code Overview .......................................................................................................67

Project 8 – Control a servo...........................................................................................................68


Project 8 – Code Overview .......................................................................................................70

Project 9 – Mix LED colors .........................................................................................................71


Project 9 – Code Overview .......................................................................................................75

Project 10 – Colorful Light ..........................................................................................................76


Project 10 – Code Overview .....................................................................................................79

Project 11 – 7seg-4digit LED Display ......................................................................................80

Project 12 – Show in 1602 LCD ..................................................................................................88


Project 12 - Hardware Overview.....................................................................................................91
www.b2cshop.com Ebay store: b2cqshop , E-qstore 2
www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Lesson 13 : Measure temperature (LM35)...................................................................................93

Project 14 - Infrared Remote Control..............................................................................................97


Project 14 - Hardware Overview...................................................................................................102

Mix Project 2 - Automatic Home Application Control .................................................................105

www.b2cshop.com Ebay store: b2cqshop , E-qstore 3


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

The Kit Contents

1 X Uno board (Arduino-Compatible)


1 X Color LED ( Tri-color LED )
1 X small servo
1 X 1602 LCD blue
1 X Photocell sensor
1 X Piezo Buzzer
1 X LM35 Temperature sensor
1 X Diode 1N4001
1 X Transistor 2N2222
1 X 5V Relay module
1 X DC motor
1 X 74HC595 shift register Chip
1 X IR Sender
1 X IR Remote Controller
1 X IR Receiver
1 X 7seg-4digit LED Display
1 X 40-pin 2.54mm Male Header
1 X 10K potentiometer
5 X Red 3mm LEDs
5 X Green 3mm LEDs
5 X Mini Push Button Switches
10 X 220 Ω Resistors
10 X 10k Ω Resistors
1 X High quality mini Breadboard
1 X bundle Breadboard Jump Wires

www.b2cshop.com Ebay store: b2cqshop , E-qstore 4


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Introduction

Thank you for purchasing this Arduino Kit. You are now well on your way in
your journey into the wonderful world of the Arduino and microcontroller electronics.
This book will guide you, step by step, through using the Starter Kit to learn about the
Arduino hardware, software and general electronics theory. Through the use of electronic
projects we will take you from the level of complete beginner through to having an
intermediate set of skills in using the Arduino.
The purpose of this book and the kit is to give you a gentle introduction to the Arduino,
electronics and programming in C and to set you up with the necessary skills needed to
progress beyond the book and the kit into the world of the Arduino and microcontroller
electronics.
The booklet has been written presuming that you have no prior knowledge of
electronics, the Arduino hardware, software environment or of computer programming. At
no time will we get too deep into electronics or programming in C. There are many other
resources available for free that will enable you to learn a lot more about this subject if you
wish to go further. The best possible way to learn the Arduino, after using this kit of course,
is to join the Arduino Forum on the Arduino website and to check out the code and
hardware examples in the ‘Playground’ section of the Arduino website too.
We hope you enjoy using the kit and get satisfaction from creating the projects and seeing
your creations come to life.

How to use it
The book starts off with an introduction to the Arduino, how to set up the hardware,
install the software, etc.
We then explain the Arduino IDE and how to use it before we dive right into some
projects progressing from very basic stuff through to advanced topics. Each project will
start off with a description of how to set up the hardware and what code is needed to get it
working. We will then describe separately the code and the hardware and explain in some
detail how it works.
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.

What you will need


Firstly, you will need access to the internet to be able to download the Arduino IDE
(Integrated Development Environment) and to also download the Code Samples within
this book (if you don’t want to type them out yourself) and also any code libraries that may
be necessary to get your project working.
You will need a well lit table or other flat surface to lay out your components and this
will need to be next to your desktop or laptop PC to enable you to upload the code to the

www.b2cshop.com Ebay store: b2cqshop , E-qstore 5


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
Arduino. Remember that you are working with electricity (although low voltage DC) and
therefore a metal table or surface will first need to be covered in a non-conductive material
(e.g. tablecloth, paper, etc.) before laying out your materials.
Also of some benefit, although not essential, may be a pair of wire cutters, a pair of
long nosed pliers and a wire stripper. A notepad and pen will also come in handy for
drawing out rough schematics, working out concepts and designs, etc.
Finally, the most important thing you will need is enthusiasm and a willingness to
learn. The Arduino is designed as a simple and cheap way to get involved in
microcontroller electronics and nothing is too hard to learn if you are willing to at least
‘give it a go’. This Arduino Kit will help you on that journey and introduce you to this
exciting and creative hobby.

( Thank you very much for the book of “Sparkfun” , book title is “ Sparkfun inventors
kit for arduino guide ”
Thank you very much for the book of “ Mike McRoberts “ , book title is “ Arduino Starter
Kit Manual Mar2010 “
Thank you very much for the book of “Michael.Margolis “,book title is “Arduino
Cookbook 2011”.
And Thank you very much the team of B2CQSHOP , too )

B2CQSHOP
Webstite : www.b2cqshop.com
Email : [email protected]
MSN : [email protected]
Skype : evanjoo

www.b2cshop.com Ebay store: b2cqshop , E-qstore 6


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

What exactly is an Arduino?

an Arduino is a tiny computer that you can program to process inputs and outputs
going to and from the chip.
The Arduino is what is known as a Physical or Embedded Computing platform, which
means that it is an interactive system, that through the use of hardware and software can
interact with it’s environment.
For example, a simple use of the Arduino would be to turn a light on for a set period of
time, let’s say 30 seconds, after a button has been pressed (we will build this very same
project later in the book). In this example, the Arduino would have a lamp connected to it
as well as a button. The Arduino would sit patiently waiting for the button to be pressed.
When you press the button it would then turn the lamp on and start counting. Once it had
counted 30 seconds it would then turn the lamp off and then carry on sitting there waiting
for another button press. You could use this set-up to control a lamp in an under-stairs
cupboard for example. You could extend this example to sense when the cupboard door
was opened and automatically turn the light on, turning it off after a set period of time.
The Arduino can be used to develop stand-alone interactive objects or it can be
connected to a computer to retrieve or send data to the Arduino and then act on that data
(e.g. Send sensor data out to the internet).
The Arduino can be connected to LED displays, LED’s. Dot Matrix displays, buttons,
switches, motors, temperature sensors, pressure sensors, distance sensors, SD card,
webcams, printers, GPS receivers, ethernet modules, and so on .
The Arduino board is made of an an Atmel AVR Microprocessor, a crystal or oscillator
(basically a crude clock that sends time pulses to the microcontroller to enable it to
operate at the correct speed) and a 5-volt linear regulator. Depending on what type of
Arduino you have, you may also have a USB connector to enable it to be connected to a
PC or Mac to upload or retrieve data. The board exposes the microcontroller’s I/O
(Input/Output) pins to enable you to connect those pins to other circuits or to sensors, etc.
To program the Arduino (make it do what you want it to) you also use the Arduino
IDE (Integrated Development Environment), which is a piece of free software, that
enables you to program in the language that the Arduino understands. In the case of the
Arduino the language is C. The IDE enables you to write a computer program, which is a
set of step-bystep instructions that you then upload to the Arduino. Then your Arduino will
carry out those instructions and interact with the world outside. In the Arduino world,
programs are known as ‘ Sketches

www.b2cshop.com Ebay store: b2cqshop , E-qstore 7


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

‘.
The Arduino hardware and software are both Open Source, which means the code,
the schematics, design, etc. are all open for anyone to take freely and do what they like
with it.
This means there is nothing stopping anyone from taking the schematics and PCB
designs of the Arduino and making their own and selling them. This is perfectly legal, and
indeed the whole purpose of Open Source, and indeed the Freeduino that comes with the
Earthshine Design Arduino Starter Kit is a perfect example of where someone has taken
the Arduino PCB design, made their own and are selling it under the Freeduino name.
You could even make your own Arduino, with just a few cheap components, on a
breadboard.
The only stipulation that the Arduino development team put on outside developers is
that the Arduino name can only be used exclusively by them on their own products and
hence the clone boards have names such as Dfrobot, Freeduino, Boarduino, Roboduino,
etc.
As the designs are open source, any clone board, such as the Freeduino is 100%
compatible with the Arduino and therefore any software, hardware, shields, etc. will all be
100% compatible with a genuine Arduino.

www.b2cshop.com Ebay store: b2cqshop , E-qstore 8


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

The Arduino can also be extended with the use of ‘Shields’ which are circuit boards
containing other devices (e.g. GPS receivers, LCD Displays, Ethernet connections, etc.)
that you can simply slot into the top of your Arduino to get extra functionality. You don’t
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.
There are many different variants of the Arduino available. The most common one is
the Diecimila or the Duemilanove. You can also get Mini, Nano and Bluetooth Arduino’s.
New to the product line is the new Arduino Mega with increased memory and number
of I/O pins.
Probably the most versatile Arduino, and hence the reason it is the most popular, is
the Duemilanove. This is because it uses a standard 28 pin chip, attached to an IC Socket.
The beauty of this systems is that if you make something neat with the Arduino and then
want to turn it into something permanent (e.g. Or understairs cupboard light), then instead
of using the relatively expensive Arduino board, you can simply use the Arduino to
develop your device, then pop the chip out of the board and place it into your own circuit
board in your custom device. You would then have made a custom embedded device,
which is really cool. Then, for a couple of quid or bucks you can replace the AVR chip in
your Arduino with a new one. The chip must be pre-programmed with the Arduino
Bootloader to enable it to work with the Arduino IDE, but you can either burn the
bootloader yourself if you purchase an AVR Programmer, or you can buy these
preprogrammed from many suppliers around the world. Of course, Earthshine Design
provide preprogrammed Arduino chips in it’ store for a very reasonable price.
If you do a search on the Internet by simply typing ‘Arduino’ into the search box of
your favourite search 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.
www.b2cshop.com Ebay store: b2cqshop , E-qstore 9
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
The Arduino is an amazing device and will enable you to make anything from
interactive works of art to robots. With a little enthusiasm to learn how to program the
Arduino and make it interact with other components a well as a bit of imagination, you can
build anything you want.
This book and the kit will give you the necessary skills needed to get started in this
exciting and creative hobby.
So, now you know what an Arduino is and what you can do with it, let’s open up the
starter kit and dive right in.

www.b2cshop.com Ebay store: b2cqshop , E-qstore 10


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Getting Started
This section will presume you have a PC running Windows or a Mac running OSX ,
Linux (on the playground wiki).

Get an Arduino board and USB cable


Firstly, get your Freeduino board and lay it on the table in front of you. Take the USB
cableand plug the B plug (the fatter squarer end) into the USB socket on the Arduino
UNO.
At this stage do NOT connect the Arduino Uno to your PC or Mac yet.

Download the Arduino IDE


Get the latest version from the download page .
When the download finishes, unzip the downloaded file. Make sure to preserve the folder
structure. Double-click the folder to open it. There should be a few files and sub-folders
inside.
If you double-click the folder, you will see a few files and sub-folders inside.

Connect the board


The Arduino Uno, Mega, Duemilanove and Arduino Nano automatically draw power
from either the USB connection to the computer or an external power supply. If you're
using an Arduino Diecimila, you'll need to make sure that the board is configured to draw
power from the USB connection. The power source is selected with a jumper, a small
piece of plastic that fits onto two of the three pins between the USB and power jacks.
Check that it's on the two pins closest to the USB port.

Connect the Arduino board to your computer using the USB cable. The green power
LED (labelled PWR) should go on.

Install the USB Drivers

www.b2cshop.com Ebay store: b2cqshop , E-qstore 11


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
(1) Installing drivers for the Arduino Uno with Windows7, Vista, or
XP:

• Plug in your board and wait for Windows to begin it's driver installation
process. After a few moments, the process will fail, despite its best efforts
• Click on the Start Menu, and open up the Control Panel.
• While in the Control Panel, navigate to System and Security. Next, click on
System. Once the System window is up, open the Device Manager.
• Look under Ports (COM & LPT). You should see an open port named "Arduino
UNO (COMxx)"
• Right click on the "Arduino UNO (COmxx)" port and choose the "Update Driver
Software" option.
• Next, choose the "Browse my computer for Driver software" option.
• Finally, navigate to and select the Uno's driver file, named "ArduinoUNO.inf",
located in the "Drivers" folder of the Arduino Software download (not the "FTDI
USB Drivers" sub-directory).
• Windows will finish up the driver installation from there.

(2) Installing drivers for the Arduino Duemilanove, Nano, or Diecimila


with Windows7, Vista, or XP:

When you connect the board, Windows should initiate the driver installation
process (if you haven't used the computer with an Arduino board before).

On Windows Vista, the driver should be automatically downloaded and


installed. (Really, it works!)

On Windows XP, the Add New Hardware wizard will open:

• When asked Can Windows connect to Windows Update to search for


software? select No, not this time. Click next.
• Select Install from a list or specified location (Advanced) and click next.
• Make sure that Search for the best driver in these locations is checked;
uncheck Search removable media; check Include this location in the search
and browse to the drivers/FTDI USB Drivers directory of the Arduino distribution.
(The latest version of the drivers can be found on the FTDI website.) Click next.
• The wizard will search for the driver and then tell you that a "USB Serial
Converter" was found. Click finish.
• The new hardware wizard will appear again. Go through the same steps and
select the same options and location to search. This time, a "USB Serial Port" will
be found.

www.b2cshop.com Ebay store: b2cqshop , E-qstore 12


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
You can check that the drivers have been installed by opening the
Windows Device Mananger (in the Hardware tab of System control panel).
Look for a "USB Serial Port" in the Ports section; that's the Arduino board.

Upload your first Sketch


Now that your Arduino Mage 2560 board has been connected and the drivers for the
USB chip have been installed, we are now ready to try out the Arduino for the first time
and upload your first Sketch.
Navigate to your newly unzipped Arduino folder and look for the Arduino IDE icon,
which looks something like this....

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.

This is the Arduino IDE (Integrated Development Environment) and is where you will write
your Sketches (programs) to upload to your Arduino board .

1) Open the LED blink example sketch: File > Examples > 1.Basics > Blink.

2) And then you should select your board .


www.b2cshop.com Ebay store: b2cqshop , E-qstore 13
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
You'll need to select the entry in the Tools > Board menu that corresponds to your
Arduino.

Selecting an Arduino Uno


For Duemilanove Arduino boards with an ATmega328 (check the text on the chip on
the board), select Arduino Duemilanove or Nano w/ ATmega328. Previously, Arduino
boards came with an ATmega168; for those, select Arduino Diecimila, Duemilanove, or
Nano w/ ATmega168. (Details of the board menu entries are available on the
environment page.)

3) Select your serial port


Select the serial device of the Arduino board from the Tools | Serial Port menu. This is likely
to be COM3 or higher (COM1 and COM2 are usually reserved for hardware serial ports). To find
out, you can disconnect your Arduino board and re-open the menu; the entry that disappears
should be the Arduino board. Reconnect the board and select that serial port.

www.b2cshop.com Ebay store: b2cqshop , E-qstore 14


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

4) Upload the program

Now, simply click the "Upload" button in the environment. Wait a few
seconds - you should see the RX and TX leds on the board flashing. If the
upload is successful, the message "Done uploading." will appear in the
status bar. (Note: If you have an Arduino Mini, NG, or other board, you'll
need to physically present the reset button on the board immediately
before pressing the upload button.)

A few seconds after the upload finishes, you should see the pin 13
(L) LED on the board start to blink (in orange). If it does,
congratulations! You've gotten Arduino up-and-running.

Tips :

Verify/ Stop New Open Save Upload Serial


Compile Monitor
www.b2cshop.com Ebay store: b2cqshop , E-qstore 15
www.b2cqshop.com Ebay store: b2cqshop , E-qstore

The Toolbar buttons are listed above. The functions of each button are as follows :
z Verify/Compile Checks the code for errors

z Stop Stops the serial monitor, or un-highlights


other buttons
z New Creates a new blank Sketch

z Open Shows a list of Sketches in your sketchbook

z Save Saves the current Sketch

z Upload Uploads the current Sketch to the Arduino

z Serial Monitor Displays serial data being sent from the


Arduino

The Verify/Compile button is used to check that yourcode is correct, before you
upload it to your Arduino.
The Stop button will stop the Serial Monitor from operating. It will also un-highlight
other selected buttons. Whilst the Serial Monitor is operating you may wish to press the
Stop button to obtain a ‘snapshot’ of the serial data so far to examine it. This is particularly
useful if you are sending data out to the Serial Monitor quicker than you can read it.
The New button will create a completely new and blank Sketch read for you to enter
code into. The IDE will ask you to enter a name and a location for your Sketch (try to use
the default location if possible) and will then give you a blank Sketch ready to be coded.
The tab at the top of the Sketch will now contain the name you have given to your new
sketch.
The Open button will present you with a list of Sketches stored within your
sketchbook as well as a list of Example sketches you can try out with various peripherals
once connected.
The Save button will save the code within the sketch window to your sketch file. Once
complete you will get a ‘Done Saving message at the bottom of the code window.
The Upload to I/O Board button will upload the code within the current sketch
window to your Arduino. You need to make sure that you have the correct board and port
selected (in the Tools menu) before uploading. It is essential that you Save your sketch
before you upload it to your board in case a strange error causes your system to hang or
the IDE to crash.
It is also advisable to Verify/Compile the code before you upload to ensure there are
no errors that need to be debugged first.
The Serial Monitor is a very useful tool, especially for debugging your code. The

www.b2cshop.com Ebay store: b2cqshop , E-qstore 16


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
monitor displays serial data being sent out from your Arduino (USB or Serial board). You
can also send serial data back to the Arduino using the Serial Monitor. If you click the
Serial Monitor button you will be presented with an image like the one above.
On the left hand side you can select the Baud Rate that the serial data is to be sent
to/from the Arduino. The Baud Rate is the rate, per second, that state changes or bits
(data) are sent to/from the board. The default setting is 9600 baud, which means that if
you were to send a text novel over the serial communications line (in this case your USB
cable) then 9600 letters, or symbols, of the novel, would be sent per second.

To the right of this is a blank text box for you to enter text to send back to the Arduino
and a Send button to send the text within that field. Note that no serial data can be
received by the Serial Monitor unless you have 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.
Finally, the black area is where your serial data will be displayed. In the image above,
the Arduino is running the ASCIITable sketch, that can be found in the Communications
examples. This program outputs ASCII characters, from the Arduino via serial (the USB
cable) to the PC where the Serial monitor then displays them.
To start the Serial Monitor press the Serial Monitor button and to stop it press the
Stop button. On a Mac or in Linux, Arduino board will reset itself (rerun the code from the
beginning) when you click the Serial Monitor button.
Once you are proficient at communicating via serial to and from the Arduino you can
use other programs such as Processing, Flash, MaxMSP, etc. To communicate between
the Arduino and your PC.

www.b2cshop.com Ebay store: b2cqshop , E-qstore 17


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

COMPONENT DETAILS

1) Solderless Breadboard
The breadboard has 400 Tie points. 1) Terminal Strip, Tie-point 300 ;2)
Distribution strip, Tie-point 100 .
Accepts a variety of wire sizes (29-20 AWG) .
It is Compatible with all kind of ProtoShield. Completely reusable,Reusable for fast build
a prototype of an electronic circuit. With Twin adhesive back, it could be fix and remove to
any position easily. Its Dimension: 83.5mm x 54.5mm x 8.5mm.

2) LED

What it Does: No. of Leads:


Emits light when a small current is 2 (one longer, this one connects to positive)
passed through it. (only in one direction) Things to watch out for:
Identifying: - Will only work in one direction
Looks like a mini light bulb. - Requires a current limiting resistor

More Details:
http://ardx.org/LED

3) Diode

www.b2cshop.com Ebay store: b2cqshop , E-qstore 18


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
What it Does: No. of Leads:
The electronic equivalent of a one way 2
valve. Allowing current to flow in one Things to watch out for:
direction but not the other. - Will only work in one direction (current will
Identifying: flow if end with the line is connected to ground)
Usually a cylinder with wires extending from
either end. (and an off center line indicating polarity)

More Details:
http://ardx.org/DIOD

4) Resistors

What it Does: No. of Leads:


Restricts the amount of current that can 2
flow through a circuit. Things to watch out for:
Identifying: - Easy to grab the wrong value (double
Cylinder with wires extending from either check the colors before using)
end. The value is displayed using a color
coding system
More Details:
http://ardx.org/RESI

5) Transistor

What it Does: No. of Leads:


Uses a small current to switch or amplify a 3 (Base, Collector, Emitter)
much larger current. Things to watch out for:
Identifying: - Plugging in the right way round (also a
Comes in many different packages but you current limiting resistor is often needed on the base pin)
can read the part number off the package.
www.b2cshop.com Ebay store: b2cqshop , E-qstore 19
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
(P2N2222AG in this kit and find a datasheet online)

More Details:
http://ardx.org/TRAN

6)Small Servo

What it Does: No. of Leads:


Takes a timed pulse and converts it into 3
an angular position of the output shaft. Things to watch out for:
Identifying: - The plug is not polarized so make sure
A plastic box with 3 wires coming out one it is plugged in the right way.
side and a shaft with a plastic horn out
the top.

More Details:
http://ardx.org/SERV

7) DC Motor

What it Does: No. of Leads:


Spins when a current is passed through it. 2
Identifying: Things to watch out for:
This one is easy, it looks like a motor. - Using a transistor or relay that is rated
Usually a cylinder with a shaft coming out for the size of motor you're using.
of one end.

More Details:
http://ardx.org/MOTO

7) Piezo Element
www.b2cshop.com Ebay store: b2cqshop , E-qstore 20
www.b2cqshop.com Ebay store: b2cqshop , E-qstore

What it Does: No. of Leads:


A pulse of current will cause it to click. A 2
stream of pulses will cause it to emit a
tone. Things to watch out for:
Identifying: - Difficult to misuse.
In this kit it comes in a little black barrel,
but sometimes they are just a gold disc.

More Details:
http://ardx.org/PIEZ

8) IC 74HC595 (Integrated Circuit)

What it Does: No. of Leads:


Packages any range of complicated 2 - 100s (in this kit there is one with 3 (TMP36) and
electronics inside an easy to use package. one with 16 (74HC595)
Identifying: Things to watch out for:
The part ID is written on the outside of the - Proper orientation. (look for marks showing pin 1)
package. (this sometimes requires a lot of
light or a magnifying glass to read).

More Details:
http://ardx.org/ICIC

9) Pushbutton

www.b2cshop.com Ebay store: b2cqshop , E-qstore 21


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
What it Does: No. of Leads:
Completes a circuit when it is pressed. 4
Identifying: Things to watch out for:
A little square with leads out the bottom - these are almost square so can be
and a button on the top. inserted 90 degrees off angle.
More Details:
http://ardx.org/BUTT

10) Potentiometer

What it Does: No. of Leads:


Produces a variable resistance dependant 3
on the angular position of the shaft. Things to watch out for:
Identifying: - Accidentally buying logarithmic scale.
They can be packaged in many different
form factors, look for a dial to identify.

More Details:
http://ardx.org/POTE

Photo Resistor
What it Does: No. of Leads:
Produces a variable resistance dependant 2
on the amount of incident light. Things to watch out for:
Identifying: - Remember it needs to be in a voltage
Usually a little disk with a clear top and a divider before it provides a useful input.
curvy line underneath.

More Details:
http://ardx.org/PHOT

www.b2cshop.com Ebay store: b2cqshop , E-qstore 22


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

LEAD CLIPPING
Some components in this kit come with very long wire leads. To make them more compatible
with a breadboard a couple of changes are required.
LEDs:
Clip the leads so the long lead is ~10mm (3/8”) long and the short one is ~7mm (9/32”).
Resistors:
Bend the leads down so they are 90 degrees to the cylinder. Then snip them so they are
~6mm (1/4”) long.
Other Components:
Other components may need clipping.
Use your discretion when doing so.

www.b2cshop.com Ebay store: b2cqshop , E-qstore 23


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 1 - LED Flasher


In this project we are going to repeat what we did in setting up and testing the Arduino,
that is to blink an LED. However, this time we are going to use one of the LED’s in the kit and
you will also learn about some electronics and coding in C along the way.

What you will need


Breadboard
Red LED
220 Ω Resistor
Jumper Wires

Connect it up
Now, first make sure that your Arduino is powered off. You can do this either by
unplugging the USB cable or by taking out the Power Selector Jumper on the Arduino
board. Then connect everything up like this :

It doesn’t matter if you use different coloured wires or use different holes on the

www.b2cshop.com Ebay store: b2cqshop , E-qstore 24


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
breadboard as long as the components and wires are connected in the same order as the
picture. Be careful when insterting components into the Breadboard. The Breadboard is
brand new and the grips in the holes will be stiff to begin with. Failure to insert
components carefully could result in damage. Make sure that your LED is connected the
right way with the longer leg connected to Digital Pin 10. The long led is the Anode of the
LED and always must go to the +5v supply (in this case coming out of Digital Pin 10) and
the short leg is the Cathode and must go to Gnd (Ground).
When you are happy that everything is connected up correctly, power up your
Arduino and connect the USB cable.

Enter the code


Now, open up the Arduino IDE and type in the following code :-

Now press the Verify/Compile button at the top of the IDE to make sure there are no
errors in your code. If this is successful you can now click the Upload button to upload the
code to your Arduino.
If you have done everything right you should now see the Red LED on the
breadboard flashing on and off every second. Now let’s take a look at the code and the
hardware and find out how they both work.
Now let’s take a look at the code and the hardware and find out how they both work.

www.b2cshop.com Ebay store: b2cqshop , E-qstore 25


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 1 - Code verview


// Project 1 - LED Flasher
int ledPin = 10;
void setup() {
! pinMode(ledPin, OUTPUT);
}
void loop() {
! digitalWrite(ledPin, HIGH);
! delay(1000);
! digitalWrite(ledPin, LOW);
! delay(1000);
}
So let’s take a look at the code for this project. Our first line is
// Project 1 - LED Flasher
This is simply a comment in your code and is ignored by the compiler (the part of the
IDE that turns your code into instructions the Arduino can understand before uploading it).
Any text entered behind a // command will be ignored by the compiler and is simply there
for you, or anyone else that reads your code. Comments are essential in your code to help
you understand what is going on and how your code works. Comments can also be put
after commands as in the next line of the program.
Later on as your projects get more complex and your code expands into hundreds or
maybe thousands of lines, comments will be vital in making it easy for you to see how it
works. You may come up with an amazing piece of code, but if you go back and look at
that code days, weeks or months alter, you may forget how it all works. Comments will
help you understand it easily. Also, if your code is meant to be seen by other people (and
as the whole ethos of the Arduino, and indeed the whole Open Source community is to
share code and schematics. We hope when you start making your own cool stuff with the
Arduino you will be willing to share it with the world) then comments will enable that
person to understand what is going on in your code.
You can also put comments into a block statement by using the /* and */ commands.
E.g.
/* All of the text within the slash and the asterisks is a comment and will be ignored by
the compiler */
The IDE will automatically turn the colour of any commented text to grey.
The next line of the program is:
int ledPin = 10;
This is what is know as a variable. A variable is a place to store data. In this case you
are setting up a variable of type int or integer. An integer is a number within the range of
-32,768 to 32,767. Next you have assigned that integer the name of ledPin and have
given it a value of 10. We didn’t have to call it ledPin, we could have called it anything we
www.b2cshop.com Ebay store: b2cqshop , E-qstore 26
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
wanted to. But, as we want our variable name to be descriptive we call it ledPin to show
that the use of this variable is to set which pin on the Arduino we are going to use to
connect our LED. In this case we are using Digital Pin 10. At the end of this statement is a
semi-colon. This is a symbol to tell the compiler that this statement is now complete.
Although we can call our variables anything we want, every variable name in C must
start with a letter, the rest of the name can consist of letters, numbers and underscore
characters. C recognises upper and lower case characters as being different. Finally, you
cannot use any of C's keywords like main, while, switch etc as variable names. Keywords
are constants, variables and function names that are defined as part of the Arduino
language. Don’t use a variable name that is the same as a keyword. All keywords within
the sketch will appear in red.
So, you have set up an area in memory to store a number of type integer and have
stored in that area the number 10. Imagine a variable as a small box where you can keep
things. A variable is called a variable because you can change it. Later on we will carryout
mathematical calculations on variables to make our program do more advanced stuff.
Next we have our setup() function :
void setup() {
! pinMode(ledPin, OUTPUT);
}
An Arduino sketch must have a setup() and loop() function otherwise it will not work.
The setup() function is run once and once only at the start of the program and is where
you will issue general instructions to prepare the program before the main loop runs, such
as setting up pin modes, setting serial baud rates, etc.
Basically a function is a block of code assembled into one convenient block. For
example, if we created our own function to carry out a whole series of 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

www.b2cshop.com Ebay store: b2cqshop , E-qstore 27


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
out the code again each time. Later on we will go into functions in more detail when
we start to create our own.
In the case of our program the setup() function only has one statement to carry out.
The function starts with
void setup()
and here we are telling the compiler that our function is called setup, that it returns no
data (void) and that we pass no parameters to it (empty parenthesis). If our function
returned an integer value and we also had integer values to pass to it (e.g. for the function
to process) then it would look something like this :
int myFunc(int x, int y)
In this case we have created a function (or a block of code) called myFunc. This
function has been passed two integers called X and Y. Once the function has finished it
will then return an integer value to the point after where our function was called in the
program (hence int before the function name).
All of the code within the function is contained within the curly braces. A { symbol
starts the block of code and a } symbol ends the block. Anything in between those two
symbols is code that belongs to the function.
We will go into greater detail about functions later on so don’t worry about them for
now. All you need to know is that in this program, we have two functions, the first function
is called setup and it’s purpose is to setup anything necessary for our program to work
before the main program loop runs.
void setup() {
pinMode(ledPin, OUTPUT);
}

Our setup function only has one statement and that is pinMode. Here we are telling the
Arduino that we want to set the mode of one of our digital pins to be Output mode, rather
than Input. Within the parenthesis we put the pin number and the mode (OUTPUT or
INPUT). Our pin number is ledPin, which has been previously set to the value 10 in our
program. Therefore, this statement is simply telling the Arduino that the Digital Pin 10 is to
be set to OUTPUT mode. As the setup() function runs only once, we now move
onto the main function loop.
void loop() {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
}
The loop() function is the main program function and runs continuously as long as our
Arduino is turned on.Every statement within the loop() function (within the curly braces) is
carried out, one by one, step by step, until the bottom of the function is reached, then the
loop starts again at the top of the function, and so on forever or until you turn the Arduino
off or press the Reset switch.
www.b2cshop.com Ebay store: b2cqshop , E-qstore 28
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
In this project we want the LED to turn on, stay on for one second, turn off and remain
off for one second, and then repeat. Therefore, the commands to tell the Arduino to do
that are contained within the loop() function as we wish them to repeat over and over.
The first statement is
digitalWrite(ledPin, HIGH);
and this writes a HIGH or a LOW value to the digital pin within the statement (in this
case ledPin, which is Digital Pin 10). When you set a digital pin to HIGH you are sending
out 5 volts to that pin. When you set it to LOW the pin becomes 0 volts, or Ground. This
statement therefore sends out 5v to digital pin 10 and turns the LED on.
After that is
delay(1000);
and this statement simply tells the Arduino to wait for 1000 milliseconds (to 1 second as
there are 1000 milliseconds in a second) before carrying out the next statement which is
digitalWrite(ledPin, LOW);
which will turn off the power going to digital pin 10 and therefore turn the LED off.
There is then another delay statement for another 1000 milliseconds and then the function
ends. However, as this is our main loop() function, the function will now start again at the
beginning. By following the program structure step by step again we can see that it is very
simple.
// Project 1 - LED Flasher
int ledPin = 10;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
}
We start off by assigning a variable called ledPin, giving that variable a value of 10.
Then we move onto the setup() function where we simply set the mode for digital pin 10
as an output.
In the main program loop we set Digital Pin 10 to high, sending out 5v. Then we wait for
a second and then turn off the 5v to Pin 10, before waiting another second. The loop then
starts again at the beginning and the LED will therefore turn on and off continuously for as
long as the Arduino has power.
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.
seconds, then go off for half a second we could do
this:-
void loop() {
digitalWrite(ledPin, HIGH);
www.b2cshop.com Ebay store: b2cqshop , E-qstore 29
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
delay(2000);
digitalWrite(ledPin, LOW);
delay(500);
}
or maybe you would like the LED to stay off for 5 seconds and then flash briefly (250ms),
like the LED indicator on a car alarm then you could do this :
void loop() {
digitalWrite(ledPin, HIGH);
delay(250);
digitalWrite(ledPin, LOW);
delay(5000);
}
or make the LED flash on and off very fast
void loop() {
digitalWrite(ledPin, HIGH);
delay(50);
digitalWrite(ledPin, LOW);
delay(50);
}
By varying the on and off times of the LED you create any effect you want. Well, within
the bounds of a single LED going on and off that is.
Before we move onto something a little more exciting let’s take a look at the hardware
and see how it works.

www.b2cshop.com Ebay store: b2cqshop , E-qstore 30


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 1 - Hardware Overview

The hardware used for this project was :-


Breadboard
Red LED
220Ω Resistor
Jumper Wires

LED

The internal structure Of LED.

www.b2cshop.com Ebay store: b2cqshop , E-qstore 31


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

The longer one lead is Anode ( “+”), the another one is Cathode (“ --”) .

The wiring of LED

The next component we have is a Resistor. A resistor is a device designed to cause


‘resistance’ to an electric current and therefore cause a drop in voltage across it’s
terminals. If you imagine a resistor to be like a water pipe that is a lot thinner than the pipe
connected to it. As the water (the electric current) comes into the resistor, the pipe gets
thinner and the current coming out of the other end is therefore reduced. We use
resistors to decrease voltage or current to other devices. The value of resistance is
known as an Ohm and it’s symbol is a greek Omega symbol Ω.
In this case Digital Pin 10 is outputting 5 volts DC at (according to the Atmega
datasheet) 40mA (milliamps) and our LED’s require (according to their datasheet) a
www.b2cshop.com Ebay store: b2cqshop , E-qstore 32
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
voltage of 2v and a current of 20mA. We therefore need to put in a resistor that will reduce
the 5v to 2v and the current from 40mA to 20mA if we want to display the LED at it’s
maximum brightness. If we want the LED to be dimmer we could use a higher value of
resistance.
To work out what resistor we need to do this we use what is called Ohm’s law which
is I = V/R where I is current, V is voltage and R is resistance. So to work out the resistance
we arrange the formula to be R = V/I which is R = 3/0.014 which is 220 Ohms. V is 3
because we need the Voltage Drop, which is the supply voltage (5v) minus the Forward
Voltage (2v) of the LED (found in the LED datasheet) which is 3v. We therefore need to
find a 220Ω resistor. So how do we do that?
A resistor is too small to put writing onto that could be readable by most people so
instead resistors use a colour code. Around the resistor you will typically find 4 coloured
bands and by using the colour code in the chart on the next page you can find out the
value of a resistor or what colour codes a particular resistance will be.

For example , If We need a 150Ω resistor, so if we look at the colour table we see that
we need 1 in the first band, which is Brown, followed by a 5 in the next band which is
Green and we then need to multiply this by 101 (in other words add 1 zero) which is
www.b2cshop.com Ebay store: b2cqshop , E-qstore 33
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
Brown in the 3rd
band. The final band is irrelevant for our purposes as this is the tolerance. Our resistor has
a gold band and therefore has a tolerance of ±5% which means the actual value of the
resistor can vary between 142.5Ω and 157.5Ω. We therefore need a resistor with a Brown,
Green, Brown, Gold colour band combination

which looks like this:-

If we needed a 1K (or 1 kilo-ohm)


resistor we would need a Brown, Black,
Red combination (1, 0, +2 zeros). If we
needed a 570K resistor the colours would be Green, Violet and Yellow.

In the same way, if you found a resistor and wanted to know


what value it is you would do the same in reverse. So if you found
this resistor and wanted to find out what value it was so you could
store it away in your nicely labelled resistor storage box, we could
look at the table to see it has a value of 220Ω.

Our final component is an LED (I’m sure you can figure out what the jumper wires do
for yourself), which stands for Light Emitting Diode. A Diode is a device that permits
current to flow in only one direction. So, it is just like a valve in a water system, but in this
case it is letting electrical current to go in one direction, but if the current tried to reverse
and go back in the opposite direction the diode would stop it from doing so. Diodes can be
useful to prevent someone from accidently connecting the Power and Ground to the
wrong terminals in a circuit and damaging the components.
An LED is the same thing, but it also emits light. LED’s come in all kinds of different
colours and brightnesses and can also emit light in the ultraviolet and infrared
part of the spectrum (like in the LED’s in your TV remote control).
If you look carefully at the LED you will notice two things. One is that the legs are of
different lengths and also that on one side of the LED, instead of it being cylindrical, it is
flattened. These are indicators to show you which leg is the Anode (Positive) and which is
the Cathode (Negative). The longer leg gets connected to the Positive Supply (3.3v) and
the leg with the flattened side goes to Ground.
If you connect the LED the wrong way, it will not damage it (unless you put very high
currents through it) and indeed you can make use of that ‘feature’ as we will see later on.
It is essential that you always put a resistor in series with the LED to ensure that the
correct current gets to the LED. You can permanently damage the LED if you fail to do
this.
As well as single colour resistors you can also obtain bi-colour and tricolour LED’s.
These will have several legs coming out of them with one of them being common (i.e.
Common anode or common cathode).
Supplied with your kit is an RGB LED, which is 3 LED’s in a single package. An RGB
www.b2cshop.com Ebay store: b2cqshop , E-qstore 34
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
LED has a Red, Green and a Blue (hence RGB) LED in one package.
The LED has 4 legs, one will be a common anode or cathode, common to all 3 LED’s
and the other 3 will then go to the anode or cathode of the individual Red, Green and Blue
LED’s. By adjusting the brightness values of the R, G and B channels of the RGB LED you
can get any colour you want. The same effect can be obtained if you used 3 separate red,
green and blue LED’s.
Now that you know how the components work and how the code in this project works,
let’s try something a bit more interesting.

www.b2cshop.com Ebay store: b2cqshop , E-qstore 35


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 2 - 8 LEDS Multiple LEDs

WHAT WE’RE DOING:


We have caused one LED to blink, now it's time to up the stakes. Lets connect eight.
We'll also have an opportunity to stretch the Arduino a bit by creating various lighting
sequences. This circuit is also a nice setup to experiment with writing your own programs
and getting a feel for how the Arduino works.
Along with controlling the LEDs we start looking into a few simple programming
methods to keep your programs small.
for() loops - used when you want to run a piece of code several times.
arrays[] - used to make managing variables easier (it's a group of variables).

www.b2cshop.com Ebay store: b2cqshop , E-qstore 36


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Enter the code


/* ---------------------------------------------------------
* | Arduino Experimentation Kit Example Code |
* | : 8 LED Fun :. (Multiple LEDs) |
* ---------------------------------------------------------
*
* A few Simple LED animations
*
* For more information on this circuit http://tinyurl.com/d2hrud
*
*/

//LED Pin Variables


int ledPins[] = {2,3,4,5,6,7,8,9}; //An array to hold the pin each LED is connected to
//i.e. LED #0 is connected to pin 2, LED #1, 3 and so on
//to address an array use ledPins[0] this would equal 2
//and ledPins[7] would equal 9

/*
* setup() - this function runs once when you turn your Arduino on
* We the three control pins to outputs
*/
void setup()
{

//Set each pin connected to an LED to output mode (pulling high (on) or low (off)
www.b2cshop.com Ebay store: b2cqshop , E-qstore 37
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
for(int i = 0; i < 8; i++){ //this is a loop and will repeat eight times
pinMode(ledPins[i],OUTPUT); //we use this to set each LED pin to output
} //the code this replaces is below

/* (commented code will not run)


* these are the lines replaced by the for loop above they do exactly the
* same thing the one above just uses less typing
pinMode(ledPins[0],OUTPUT);
pinMode(ledPins[1],OUTPUT);
pinMode(ledPins[2],OUTPUT);
pinMode(ledPins[3],OUTPUT);
pinMode(ledPins[4],OUTPUT);
pinMode(ledPins[5],OUTPUT);
pinMode(ledPins[6],OUTPUT);
pinMode(ledPins[7],OUTPUT);
(end of commented code)*/
}

/*
* loop() - this function will start after setup finishes and then repeat
* we call a function called oneAfterAnother(). if you would like a different behaviour
* uncomment (delete the two slashes) one of the other lines
*/
void loop() // run over and over again
{
oneAfterAnotherNoLoop(); //this will turn on each LED one by one then turn each off
//oneAfterAnotherLoop(); //does the same as oneAfterAnotherNoLoop but with
//much less typing
//oneOnAtATime(); //this will turn one LED on then turn the next one
//on turning the
//former off (one LED will look like it is scrolling
//along the line
//inAndOut(); //lights the two middle LEDs then moves them out then back
//in again
}

/*
* oneAfterAnotherNoLoop() - Will light one LED then delay for delayTime then light
* the next LED until all LEDs are on it will then turn them off one after another
*
* this does it without using a loop which makes for a lot of typing.
* oneOnAtATimeLoop() does exactly the same thing with less typing
www.b2cshop.com Ebay store: b2cqshop , E-qstore 38
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
*/
void oneAfterAnotherNoLoop(){
int delayTime = 100; //the time (in milliseconds) to pause between LEDs
//make smaller for quicker switching and larger for slower
digitalWrite(ledPins[0], HIGH); //Turns on LED #0 (connected to pin 2 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[1], HIGH); //Turns on LED #1 (connected to pin 3 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[2], HIGH); //Turns on LED #2 (connected to pin 4 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[3], HIGH); //Turns on LED #3 (connected to pin 5 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[4], HIGH); //Turns on LED #4 (connected to pin 6 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[5], HIGH); //Turns on LED #5 (connected to pin 7 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[6], HIGH); //Turns on LED #6 (connected to pin 8 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[7], HIGH); //Turns on LED #7 (connected to pin 9 )
delay(delayTime); //waits delayTime milliseconds

//Turns Each LED Off


digitalWrite(ledPins[7], LOW); //Turns on LED #0 (connected to pin 2 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[6], LOW); //Turns on LED #1 (connected to pin 3 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[5], LOW); //Turns on LED #2 (connected to pin 4 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[4], LOW); //Turns on LED #3 (connected to pin 5 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[3], LOW); //Turns on LED #4 (connected to pin 6 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[2], LOW); //Turns on LED #5 (connected to pin 7 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[1], LOW); //Turns on LED #6 (connected to pin 8 )
delay(delayTime); //waits delayTime milliseconds
digitalWrite(ledPins[0], LOW); //Turns on LED #7 (connected to pin 9 )
delay(delayTime); //waits delayTime milliseconds
}

/*
* oneAfterAnotherLoop() - Will light one LED then delay for delayTime then light
* the next LED until all LEDs are on it will then turn them off one after another
www.b2cshop.com Ebay store: b2cqshop , E-qstore 39
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
*
* this does it using a loop which makes for a lot less typing.
* than oneOnAtATimeNoLoop() does exactly the same thing with less typing
*/
void oneAfterAnotherLoop(){
int delayTime = 100; //the time (in milliseconds) to pause between LEDs
//make smaller for quicker switching and larger for slower

//Turn Each LED on one after another


for(int i = 0; i <= 7; i++){
digitalWrite(ledPins[i], HIGH); //Turns on LED #i each time this runs i
delay(delayTime); //gets one added to it so this will repeat
} //8 times the first time i will = 0 the final
//time i will equal 7;

//Turn Each LED off one after another


for(int i = 7; i >= 0; i--){ //same as above but rather than starting at 0 and counting up
//we start at seven and count down
digitalWrite(ledPins[i], LOW); //Turns off LED #i each time this runs i
delay(delayTime); //gets one subtracted from it so this will repeat
} //8 times the first time i will = 7 the final
//time it will equal 0

/*
* oneOnAtATime() - Will light one LED then the next turning off all the others
*/
void oneOnAtATime(){
int delayTime = 100; //the time (in milliseconds) to pause between LEDs
//make smaller for quicker switching and larger for slower

for(int i = 0; i <= 7; i++){


int offLED = i - 1; //Calculate which LED was turned on last time through
if(i == 0) { //for i = 1 to 7 this is i minus 1 (i.e. if i = 2 we will
offLED = 7; //turn on LED 2 and off LED 1)
} //however if i = 0 we don't want to turn of led -1 (doesn't exist)
//instead we turn off LED 7, (looping around)
digitalWrite(ledPins[i], HIGH); //turn on LED #i
digitalWrite(ledPins[offLED], LOW); //turn off the LED we turned on last time
delay(delayTime);
}
www.b2cshop.com Ebay store: b2cqshop , E-qstore 40
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
}

/*
* inAndOut() - This will turn on the two middle LEDs then the next two out
* making an in and out look
*/
void inAndOut(){
int delayTime = 100; //the time (in milliseconds) to pause between LEDs
//make smaller for quicker switching and larger for slower

//runs the LEDs out from the middle


for(int i = 0; i <= 3; i++){
int offLED = i - 1; //Calculate which LED was turned on last time through
if(i == 0) { //for i = 1 to 7 this is i minus 1 (i.e. if i = 2 we will
offLED = 3; //turn on LED 2 and off LED 1)
} //however if i = 0 we don't want to turn of led -1 (doesn't exist)
//instead we turn off LED 7, (looping around)
int onLED1 = 3 - i; //this is the first LED to go on ie. LED #3 when i = 0 and LED
//#0 when i = 3
int onLED2 = 4 + i; //this is the first LED to go on ie. LED #4 when i = 0 and LED
//#7 when i = 3
int offLED1 = 3 - offLED; //turns off the LED we turned on last time
int offLED2 = 4 + offLED; //turns off the LED we turned on last time

digitalWrite(ledPins[onLED1], HIGH);
digitalWrite(ledPins[onLED2], HIGH);
digitalWrite(ledPins[offLED1], LOW);
digitalWrite(ledPins[offLED2], LOW);
delay(delayTime);
}

//runs the LEDs into the middle


for(int i = 3; i >= 0; i--){
int offLED = i + 1; //Calculate which LED was turned on last time through
if(i == 3) { //for i = 1 to 7 this is i minus 1 (i.e. if i = 2 we will
offLED = 0; //turn on LED 2 and off LED 1)
} //however if i = 0 we don't want to turn of led -1 (doesn't exist)
//instead we turn off LED 7, (looping around)
int onLED1 = 3 - i; //this is the first LED to go on ie. LED #3 when i = 0 and LED
//#0 when i = 3
int onLED2 = 4 + i; //this is the first LED to go on ie. LED #4 when i = 0 and LED
//#7 when i = 3
int offLED1 = 3 - offLED; //turns off the LED we turned on last time
www.b2cshop.com Ebay store: b2cqshop , E-qstore 41
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
int offLED2 = 4 + offLED; //turns off the LED we turned on last time

digitalWrite(ledPins[onLED1], HIGH);
digitalWrite(ledPins[onLED2], HIGH);
digitalWrite(ledPins[offLED1], LOW);
digitalWrite(ledPins[offLED2], LOW);
delay(delayTime);
}
}

www.b2cshop.com Ebay store: b2cqshop , E-qstore 42


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 2 – Hardware Overview

1) NOT WORKING? (3 things to try)

2) MAKING IT BETTER
www.b2cshop.com Ebay store: b2cqshop , E-qstore 43
www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Switching to loops: Extra animations:


In the loop() function there are 4 lines.The last Tired of this animation? Then try the other two
three all start with a '//'. This means the line is sample animations. Uncomment their lines and upload
treated as a comment (not run). To switch the the program to your board and enjoy the new light
program to use loops change the void loop() animations. (delete the slashes in front of row 3 and then 4)

code to:
//oneAfterAnotherNoLoop(); Testing out your own animations:
oneAfterAnotherLoop(); Jump into the included code and start changing
//oneOnAtATime(); things. The main point is to turn an LED on use
//inAndOut(); digitalWrite(pinNumber, HIGH); then to turn
Upload the program, and notice that nothing has it off use digitalWrite(pinNumber, LOW); .
changed. You can take a look at the two Type away, regardless of what you change you won't
functions, each does the same thing, but use break anything.
different approaches (hint: the second one uses
a for loop).

www.b2cshop.com Ebay store: b2cqshop , E-qstore 44


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 3 - Make music

WHAT WE’RE DOING:


To this point we have controlled light, motion, and electrons. Let's tackle sound next.
But sound is an analog phenomena, how will our digital Arduino cope?
We will once again rely on its incredible speed which will let it mimic analog behavior.
To do this, we will attach a piezo element to one of the Arduino's digital pins. A piezo
element makes a clicking sound each time it is pulsed
with current. If we pulse it at the right frequency (for example 440 times a second to make
the note middle A) these clicks will run together to produce notes. Let's get to
experimenting with it and get your Arduino playing "Twinkle Twinkle Little Star".

Connect it up

Enter the code

www.b2cshop.com Ebay store: b2cqshop , E-qstore 45


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
//(courtesy of }

http://www.arduino.cc/en/Tutorial/Melody ) // pause between notes


int speakerPin = 9; delay(tempo / 2);
int length = 15; // the number of notes }
char notes[] = "ccggaagffeeddc "; // a space }
represents a rest
int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1,
1, 1, 1, 1, 2, 4 };
int tempo = 300;
void playTone(int tone, int duration) {
for (long i = 0; i < duration * 1000L; i +=
tone * 2) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
}
}
void playNote(char note, int duration) {
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a',
'b', 'C' };
int tones[] = { 1915, 1700, 1519, 1432, 1275,
1136, 1014, 956 };

// play the tone corresponding to the note


name
for (int i = 0; i < 8; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}
}
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);

www.b2cshop.com Ebay store: b2cqshop , E-qstore 46


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
When you run this code the Arduino will play a very nice (yeah ok it’s terrible)
rendition of ‘Twinkle Twinkle Little Star’. Sounding very similar to those annoying birthday
cards you can buy that play a tune when you open it up.
Let’s take a look at this code and see how it works and find out what a piezo disc is.

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 3 - Code Overview


In this project we are making sounds using a piezo disc. A piezo disc can do nothing
more than make a click when we apply a voltage to it. So to get the tones we can hear out
of it we need to make it click many times a second fast enough that it becomes a
recognisable note.
The program starts off by setting up the variables we need. The piezo sounders
positive (red) cable is attached to Pin 9.
int speakerPin = 9;

The tune we are going to play is made up of 15 notes.


int length = 15; // the number of notes

The notes of the tune are stored in a character array as a text string.
char notes[] = "ccggaagffeeddc ";

Another array, this time of integers, is set up to store the length of each note.
int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };

And finally we set a tempo for the tune to be played at,


int tempo = 300;

Next you will notice that we declare two functions before our setup() and loop() functions.
It doesn’t matter if we put our own functions before or after setup() and loop(). When the
program runs, the code within these two functions will not run before setup() runs as we have
not called those functions yet.
Let’s look at the setup and loop functions before we look at the playTone and playNote
functions. All that happens in setup() is we assign the speaker pin (9) as an output.
void setup() {
pinMode(speakerPin, OUTPUT);
}

In the main program loop we have an if/else statement inside a for loop.
for (int i = 0; i < length; i++) {
if (notes[i] == ' ') {
delay(beats[i] * tempo); // rest
} else {
playNote(notes[i], beats[i] * tempo);
}

As you can see, the first if statement has as it’s condition, that the array element [i] that
the element contains a space character.
if (notes[i] == ' ')

If this is TRUE then the code within it’s block is executed.


delay(beats[i] * tempo); // rest

and this simply works out the value of eats[i] * empo nd causes a delay of that length to
cause a rest in the notes. We then have an else statement.
else {

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
playNote(notes[i], beats[i] * tempo);
}

After an if statement we can extend it with an else statement. An else statements is


carried out if the condition within the if statement is false. So, for example. Let’s say we had an
integer called test and it’s value was 10 and this if/else statement:
if (test == 10) {
digitalWrite(ledPin, HIGH)
} else {
digitalWrite(ledPin, LOW)
}

Then if ‘test' had a value of 10 (which it does) the ledPin would be set to HIGH. If the
value of test was anything other than 10, the code within the else statement would be
carried out instead and the ledPin would be set to LOW.
The else statement calls a function called playNote and passes two parameters. The
first parameter is the value of notes[i] and the second is the value calculated from beats[i]
* tempo.
playNote(notes[i], beats[i] * tempo);
After if/else statement has been carried out, there is a delay whose value is
calculated by dividing tempo by 2.
delay(tempo / 2);
Let us now take a look at the two functions we have created for this project.
The first function that is called from the main program loop is playNote.
void playNote(char note, int duration) {
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a',
'b', 'C' };
int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
// play the tone corresponding to the note name
for (int i = 0; i < 8; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}

Two parameters have been passed to the function and within the function these have
been given the names note (character) and duration (integer).
The function sets up a local variable array of data type char called names . This
variable has local scope so is only visible to this function and not outside of it.
This array stores the names of the notes from middle C to high C.
We then create another array of data type integer and this array stores numbers that
correspond to the frequency of the tones, in Kilohertz, of each of the notes in the names[]
array.
int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };

After setting up the two arrays there is a for loop that looks through the 8 notes in the
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
names[] array and compares it to the note sent to the function.
for (int i = 0; i < 8; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}

The tune that is sent to this function is ‘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 play Tone, to play thecorresponding tone using in the
tones[] array using a note length of ‘duration’.
The second function is called playTone.
void playTone(int tone, int duration) {
for (long i = 0; i < duration * 1000L; i +=tone * 2) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
}
}

Two parameters are passed to this function. The first is the tone (in kilohertz) that we want
the piezo speaker to reproduce and the second is the duration (made up by calculating beats[i]
* tempo.

The function starts a for loop


for (long i = 0; i < duration * 1000L; i += tone
* 2)

As each for loop must be of a different length to make each note the same length (as
the delay differs between clicks to produce the desired frequency) the for loop will run to
duration multiplied by 1000 and the increment of the loop is the value of ‘tone’
multiplied by 2.
Inside the for loop we simply make the pin connected to the piezo speaker go high, wait a
short period of time, then go low, then wait another short period of time, then repeat.
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);

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 varying
frequencies.

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 4 – Respond to buttons

WHAT WE’RE DOING:


Up to this point we have focused entirely on
outputs, time to get our Arduino to listen, watch and
feel. We'll start with a simple pushbutton. Wiring up
the pushbutton is simple. There is one component,
the pull up resistor, that might seem out of place.
This is included because an Arduino doesn't
sense the same way we do (ie button pressed,
button unpressed). Instead it looks at the voltage on
the pin and decides whether it is HIGH or LOW. The
button is set up to pull the Arduino's pin LOW when
it is pressed, however, when the button is unpressed the voltage of the pin will float
(causing occasional errors). To get the Arduino to reliably read the pin as HIGH when the
button is unpressed, we add the pull up resistor.
(note: the first example program uses only one of the two buttons)

THE CIRCUIT:

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Code :

/*
* Button
*
* Turns on and off a light emitting diode(LED) connected to digital
* pin 13, when pressing a pushbutton attached to pin 7.
* http://www.arduino.cc/en/Tutorial/Button
*/
int ledPin = 13; // choose the pin for the LED
int inputPin = 2; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare pushbutton as input
}
void loop(){
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, LOW); // turn LED OFF
} else {
digitalWrite(ledPin, HIGH); // turn LED ON
}
}

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 4 – Code Overview


On button off button:
The initial example may be a little underwhelming (ie. I don't really need an Arduino to
do this), let’s make it a little more complicated. One button will turn the LED on the other
will turn the LED off. Change the code to:

int ledPin = 13; // choose the pin for the LED


int inputPin = 2; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare pushbutton as input
}
void loop(){
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, LOW); // turn LED OFF
} else {
digitalWrite(ledPin, HIGH); // turn LED ON
}
}

Upload the program to your board, and start toggling the LED on and off.

Fading up and down:


Lets use the buttons to control an analog signal. To do this you will need to change
the wire connecting the LED from pin 13 to pin 9, also change this in code.

int ledPin = 13; ----> int ledPin = 9;

Next change the loop() code to read.

int value = 0;
void loop(){
if (digitalRead(inputPin1) == LOW) { value--; }
else if (digitalRead(inputPin2) == LOW) { value++; }
value = constrain(value, 0, 255);
analogWrite(ledPin, value);

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
delay(10);
}
Changing fade speed:
If you would like the LED to fade faster or slower, there is only one line of code that
needs changing;
delay(10); ----> delay(new #);
To fade faster make the number smaller, slower requires a larger number.

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 5 – Detect ambient light

WHAT WE’RE DOING:


Whilst getting input from a potentiometer can be useful
for human controlled experiments, what do we use when
we want an environmentally controlled experiment?
We use exactly the same principles but instead of a
potentiometer (twist based resistance) we use a photo
resistor (light based resistance). Our purposes (just
sensing relative light) we can experiment with the values
and see what works for us. A low value will occur when the
sensor is well lit while a high value will occur when it is in
darkness.

In the light intensity is strong , it’s resistance decreases; however , when the light is
weak, this sensor’s resistance increases.

First Experiment:
Prepare: 1 X Ambient Light sensor , 1 X buzzer , some Jumper cable.

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

To build the circuit, attach buzzer’s long, positive leg (called the anode) to pin 6 . Connect
the cathode (the shorter, negative leg) directly to ground.
Attach the Ambient Light sensor pin to the 5 volt supply, the other side to Analog Pin 5 .

Code : open the folder Project_6 , and open the Project_6.pde


In the program, when the Light is stronger, the resistance of sensor will be smaller, and
then the buzzer speak louder.

/*
Created By: Samleong
Created On: 2011-9-17
Website / More Infomation: http://www.b2cqshop.com
Email: [email protected]
*/
void setup()
{
pinMode(6,OUTPUT);
}
void loop()
{
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
int val = analogRead(5);
char i,j;
if(val>1000)
{
for(i=0;i<80;i++) //Output a frequency of sound
{
digitalWrite(6,HIGH);
delay(1);
digitalWrite(6,LOW);
delay(1);
}
}
else if(val>800)
{
for(i=0;i<100;i++) //Output another frequency of sound
{
digitalWrite(6,HIGH);
delay(4);
digitalWrite(6,LOW);
delay(4);
}
}
}

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 6 – Read a volume knob

WHAT WE’RE DOING:


Along with the digital pins, the Arduino also has 6 pins which
can be used for analog input. These inputs take a voltage (from
0 to 5 volts) and convert it to a digital number between 0 (0 volts)
and 1024 (5 volts) (10 bits of resolution). A very useful device
that exploits these inputs is a potentiometer (also called a
variable resistor). When it is connected with 5 volts across its
outer pins the middle pin will read some value between 0 and 5
volts dependent on the angle to which it is turned (ie. 2.5 volts in
the middle). We can then use the returned values as a variable in our program.

THE CIRCUIT:

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Code :

/* Analog Input
* Demonstrates analog input by reading an analog sensor on analog
* pin 0 and turning on and off a light emitting diode(LED) connected to
digital pin 13.
* The amount of time the LED will be on and off depends on the value obtained by
* analogRead().
* Created by David Cuartielles
* Modified 16 Jun 2009
* By Tom Igoe
* http://arduino.cc/en/Tutorial/AnalogInput
*/
int sensorPin = 0; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor
void setup() {
pinMode(ledPin, OUTPUT); //declare the ledPin as an OUTPUT:
}
void loop() {
sensorValue = analogRead(sensorPin);// read the value from the sensor:
digitalWrite(ledPin, HIGH); // turn the ledPin on
delay(sensorValue); // stop the program for <sensorValue> milliseconds:
digitalWrite(ledPin, LOW); // turn the ledPin off:
delay(sensorValue); // stop the program for for <sensorValue> milliseconds:
}

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 6 – Code Overview


Threshold switching:
Sometimes you will want to switch an output when a value exceeds a certain
threshold. To do this with a potentiometer change the loop() code to.

void loop() {
sensorValue = analogRead(sensorPin);// read the value from the sensor:
digitalWrite(ledPin, HIGH); // turn the ledPin on
delay(sensorValue); // stop the program for <sensorValue> milliseconds:
digitalWrite(ledPin, LOW); // turn the ledPin off:
delay(sensorValue); // stop the program for for <sensorValue> milliseconds:
}

This will cause the LED to turn on when the value is above 512 (about halfway), you can
adjust the sensitivity by changing the threshold value.

Fading:
Let’s control the brightness of an LED directly from the potentiometer. To do this we need
to first change the pin the LED is connected to. Move the wire from pin 13 to pin 9 and
change one line in the code.

int ledPin = 13; ----> int ledPin = 9;

Then change the loop code to.

void loop() {
int value = analogRead(potPin) / 4;
analogWrite(ledPin, value);
}

Upload the code and watch as your LED fades in relation to your potentiometer spinning.
(Note: the reason we divide the value by 4 is the analogRead() function returns a value
from 0 to 1024 (10 bits), and analogWrite() takes a value from 0 to 255 (8 bits) )

Controlling a servo:
This is a really neat example and brings a couple of circuits together. Wire up the
servo , then open the example program Knob , then change one line of code.

int potpin = 0; ----> int potpin = 2;

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
Upload to your Arduino and then watch as the servo shaft turns as you turn the
potentiometer.

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 7 – Control DC motor

WHAT WE’RE DOING:


The Arduino's pins are great for directly controlling small electric items like LEDs.
However, when dealing with larger items (like a toy motor or washing machine), an
external transistor is required. A transistor is incredibly useful. It switches a lot of current
using a much smaller current. A transistor has 3 pins. For a negative type (NPN) transistor,
you connect your load to collector and the emitter to ground. Then when a small current
flows from base to the emitter, a current will flow through the transistor and your motor will
spin (this happens when we set our Arduino pin HIGH). There are literally thousands of
different types of transistors, allowing every situation to be perfectly matched. We have
chosen a 2N2222 a rather common general purpose transistor. The important factors in
our case are that its maximum voltage (40v) and its maximum current (200 milliamp) are
both high enough for our toy motor (full details can be found on its datasheet
http://ardx.org/2222).
(The 1N4001 diode is acting as a flyback diode for details on why its there visit: http://ardx.org/4001)

THE CIRCUIT:

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Code :

int motorPin = 9; // define the pin the motor is connected to


// (if you use pin 9,10,11 or 3you can also control speed)

/*
* setup() - this function runs once when you turn your Arduino on
* We set the motors pin to be an output (turning the pin high (+5v) or low (ground) (-))
* rather than an input (checking whether a pin is high or low)
*/
void setup()
{
pinMode(motorPin, OUTPUT);
}

/*
* loop() - this function will start after setup finishes and then repeat
* we call a function called motorOnThenOff()
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
*/

void loop() // run over and over again


{
motorOnThenOff();
//motorOnThenOffWithSpeed();
//motorAcceleration();
}

/*
* motorOnThenOff() - turns motor on then off
* (notice this code is identical to the code we used for
* the blinking LED)
*/
void motorOnThenOff(){
int onTime = 2500; //the number of milliseconds for the motor to turn on for
int offTime = 1000; //the number of milliseconds for the motor to turn off for

digitalWrite(motorPin, HIGH); // turns the motor On


delay(onTime); // waits for onTime milliseconds
digitalWrite(motorPin, LOW); // turns the motor Off
delay(offTime); // waits for offTime milliseconds
}

/*
* motorOnThenOffWithSpeed() - turns motor on then off but uses speed values as well
* (notice this code is identical to the code we used for
* the blinking LED)
*/
void motorOnThenOffWithSpeed(){

int onSpeed = 200; // a number between 0 (stopped) and 255 (full speed)
int onTime = 2500; //the number of milliseconds for the motor to turn on for

int offSpeed = 50; // a number between 0 (stopped) and 255 (full speed)
int offTime = 1000; //the number of milliseconds for the motor to turn off for

analogWrite(motorPin, onSpeed); // turns the motor On


delay(onTime); // waits for onTime milliseconds
analogWrite(motorPin, offSpeed); // turns the motor Off
delay(offTime); // waits for offTime milliseconds
}

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
/*
* motorAcceleration() - accelerates the motor to full speed then
* back down to zero
*/
void motorAcceleration(){
int delayTime = 50; //milliseconds between each speed step

//Accelerates the motor


for(int i = 0; i < 256; i++){ //goes through each speed from 0 to 255
analogWrite(motorPin, i); //sets the new speed
delay(delayTime); // waits for delayTime milliseconds
}

//Decelerates the motor


for(int i = 255; i >= 0; i--){ //goes through each speed from 255 to 0
analogWrite(motorPin, i); //sets the new speed
delay(delayTime); // waits for delayTime milliseconds
}
}

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 7 – Code Overview


Controlling speed:
We played with the Arduino's ability to control the brightness of an LED earlier now
we will use the same feature to control the speed of our motor. The Arduino does this
using something called Pulse Width Modulation (PWM). This relies on the Arduino's ability
to operate really, really fast. Rather than directly controlling the voltage coming from the
pin the Arduino will switch the pin on and off very quickly. In the computer world this is
going from 0 to 5 volts many times a second, but in the human world we see it as a voltage.
For example if the Arduino is PWM'ing at 50% we see the light dimmed 50% because our
eyes are not quick enough to see it flashing on and off. The same feature works with
transistors. Don't believe me? Try it out.
In the loop() section change it to this

// motorOnThenOff();
motorOnThenOffWithSpeed();
// motorAcceleration();

Then upload the program. You can change the speeds by changing the variables
onSpeed and offSpeed.

Accelerating and decelerating:

Why stop at two speeds, why not accelerate and decelerate the motor. To do this
simply change the loop() code to read
// motorOnThenOff();
// motorOnThenOffWithSpeed();
motorAcceleration();

Then upload the program and watch as your motor slowly accelerates up to full speed
then slows down again. If you would like to change the speed of acceleration change the
variable delayTime (larger means a longer acceleration time).

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 8 – Control a servo

WHAT WE’RE DOING:


Spinning a motor is good fun but when it comes to
projects where motion control is required they tend to leave us
wanting more. The answer? Hobby servos. They are mass
produced, widely available and cost anything from a couple of
dollars to hundreds. Inside is a small gearbox (to make the
movement more powerful) and some electronics (to make it
easier to control). A standard servo is positionable from 0 to
180 degrees. Positioning is controlled through a timed pulse, between 1.25 milliseconds
(0 degrees) and 1.75 milliseconds (180 degrees) (1.5 milliseconds for 90 degrees). Timing
varies between manufacturer. If the pulse is sent every 25-50 milliseconds the servo will
run smoothly. One of the great features of the Arduino is it has a software library that
allows
you to control two servos (connected to pin 9 or 10) using a single line of code.

THE CIRCUIT:

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Code :

// Sweep
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 8 – Code Overview

Potentiometer control:

We have yet to experiment with inputs but if you would like to read ahead, there is an
example program File > Servo > Knob. This uses a potentiometer (CIRC08) to control
the servo. You can find instructions online here: http://ardx.org/KNOB

Self timing:

While it is easy to control a servo using the Arduino's included library sometimes it is
fun to figure out how to program something yourself. Try it. We're controlling the pulse
directly so you could use this method to control servos on any of the Arduino's 20
available pins (you need to highly optimize this code before doing that).

int servoPin = 9;
void setup(){
pinMode(servoPin,OUTPUT);
}
void loop() {
int pulseTime = 2100; //(the number of microseconds
//to pause for (1500 90 degrees // 900 0 degrees 2100 180 degrees)
digitalWrite(servoPin, HIGH);
delayMicroseconds(pulseTime);
digitalWrite(servoPin, LOW);
delay(25);
}

Great ideas:

Servos can be used to do all sorts of great things, here are a few of our favorites.

Xmas Hit Counter


http://ardx.org/XMAS

Open Source Robotic Arm (uses a servo controller as well as the Arduino)
http://ardx.org/RARM

Servo Walker
http://ardx.org/SEWA
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 9 – Mix LED colors

WHAT WE’RE DOING:


Time to start playing with chips, or
integrated circuits (ICs) as they like to be called.
The external packaging of a chip can be very
deceptive. For example, the chip on the Arduino
board (a microcontroller) and the one we will use
in this circuit (a shift register) look very similar but
are in fact rather different. The price of the
ATMega chip on the Arduino board is a few
dollars while the 74HC595 is a couple dozen
cents. It's a good introductory chip, and once
you're comfortable playing around with it and its datasheet (available online
http://ardx.org/74HC595 ) the world of chips will be your oyster.
The shift register (also called a serial to parallel converter), will give you an additional 8
outputs (to control LEDs and the like) using only three Arduino pins. They can also be
linked together to give you a nearly unlimited number of outputs using the same four pins.
To use it you “clock in” the data and then lock it in (latch it). To do this you set the data pin
to either HIGH or LOW, pulse the clock, then set the data pin again and pulse the clock
repeating until you have shifted out 8 bits of data. Then you pulse the latch and the 8 bits
are transferred to the shift registers pins. It sounsds complicated but is really simple once
you get the hang of it.
(for a more in depth look at how a shift register works visit: http://ardx.org/SHIF)

THE CIRCUIT:

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Code :
/* ---------------------------------------------------------
* | Arduino Experimentation Kit Example Code |
* | 8 More LEDs :. (74HC595 Shift Register) |
* ---------------------------------------------------------
*
* We have already controlled 8 LEDs however this does it in a slightly
* different manner. Rather than using 8 pins we will use just three
* and an additional chip.
*
*
*/

//Pin Definitions
//Pin Definitions
//The 74HC595 uses a serial communication
//link which has three pins
int data = 2;
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
int clock = 3;
int latch = 4;

//Used for single LED manipulation


int ledState = 0;
const int ON = HIGH;
const int OFF = LOW;

/*
* setup() - this function runs once when you turn your Arduino on
* We set the three control pins to outputs
*/
void setup()
{
pinMode(data, OUTPUT);
pinMode(clock, OUTPUT);
pinMode(latch, OUTPUT);
}

/*
* loop() - this function will start after setup finishes and then repeat
* we set which LEDs we want on then call a routine which sends the states to the
74HC595
*/
void loop() // run over and over again
{
int delayTime = 100; //the number of milliseconds to delay between LED updates
for(int i = 0; i < 256; i++){
updateLEDs(i);
delay(delayTime);
}
}

/*
* updateLEDs() - sends the LED states set in ledStates to the 74HC595
* sequence
*/
void updateLEDs(int value){
digitalWrite(latch, LOW); //Pulls the chips latch low
shiftOut(data, clock, MSBFIRST, value); //Shifts out the 8 bits to the shift register
digitalWrite(latch, HIGH); //Pulls the latch high displaying the data
}

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
/*
* updateLEDsLong() - sends the LED states set in ledStates to the 74HC595
* sequence. Same as updateLEDs except the shifting out is done in software
* so you can see what is happening.
*/
void updateLEDsLong(int value){
digitalWrite(latch, LOW); //Pulls the chips latch low
for(int i = 0; i < 8; i++){ //Will repeat 8 times (once for each bit)
int bit = value & B10000000; //We use a "bitmask" to select only the eighth
//bit in our number (the one we are addressing this time through
value = value << 1; //we move our number up one bit value so next time bit 7 will be
//bit 8 and we will do our math on it
if(bit == 128){digitalWrite(data, HIGH);} //if bit 8 is set then set our data pin high
else{digitalWrite(data, LOW);} //if bit 8 is unset then set the data pin low
digitalWrite(clock, HIGH); //the next three lines pulse the clock pin
delay(1);
digitalWrite(clock, LOW);
}
digitalWrite(latch, HIGH); //pulls the latch high shifting our data into being displayed
}

//These are used in the bitwise math that we use to change individual LEDs
//For more details http://en.wikipedia.org/wiki/Bitwise_operation
int bits[] = {B00000001, B00000010, B00000100, B00001000, B00010000, B00100000,
B01000000, B10000000};
int masks[] = {B11111110, B11111101, B11111011, B11110111, B11101111, B11011111,
B10111111, B01111111};
/*
* changeLED(int led, int state) - changes an individual LED
* LEDs are 0 to 7 and state is either 0 - OFF or 1 - ON
*/
void changeLED(int led, int state){
ledState = ledState & masks[led]; //clears ledState of the bit we are addressing
if(state == ON){ledState = ledState | bits[led];} //if the bit is on we will add it to ledState
updateLEDs(ledState); //send the new LED state to the shift register
}

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 9 – Code Overview

Doing it the hard way:


An Arduino makes rather complex actions very easy, shifting out data is one of these
cases. However one of the nice features of an Arduino is you can make things as easy or
difficult as you like. Let's try an example of this. In your loop switch the line:
Upload the program and notice nothing has changed. If you look at the code you can
see how we are communicating with the chip one bit at a time. (for more details
http://ardx.org/SPI ).

Controlling individual LEDs:


Time to start controlling the LEDs in a similar method as we did in led before. As the
eight LED states are stored in one byte (an 8 bit value) for details on how this works try
http://ardx.org/BINA. An Arduino is very good at manipulating bits and there are an
entire set of operators that help us out. Details on bitwise maths ( http://ardx.org/BITW ).

Our implementation.
Replace the loop() code with
int delayTime = 100; //the number of milliseconds
//to delay
//between LED updates
for(int i = 0; i < 8; i++){
changeLED(i,ON);
delay(delayTime);
}
for(int i = 0; i < 8; i++){
changeLED(i,OFF);
delay(delayTime);
}
Uploading this will cause the lights to light up one after another and then off in a
similar manner. Check the code and wikipedia to see how it works, or shoot us an e-mail if
you have questions.

More animations:
Now things get more interesting. If you look back to the code from (8 LED Fun) you
see we change the LEDs using digitalWrite(led, state), this is the same format as the
routine we wrote changeLED(led, state). You can use the animations you wrote for Blink
LEDs by copying the code into this sketch and changing all the digitalWrite()'s to
changeLED()'s. Powerful? Very. (you'll also need to change a few other things but follow
the compile errors and it works itself out).
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 10 – Colorful Light

WHAT WE’RE DOING:


When you first started with lesson one you were
happy just to get a red LED blinking away. But you're past
that now, right? You want orange, you want teal, you want
aubergine!
Fortunately there's a way to shine multiple colors from a
single LED without having to stock up on every shade of the
rainbow. To do this we use a RGB LED. An RGB LED isn't a
single LED it's actually three LEDs in one small package:
one Red, one Green and one Blue. When you turn them on
their light mixes together and you get other colors. The color you get is a result of the
intensity of the individual red, green and blue LEDs.
This project we will delve into the world of serial communications and control our
lamp by sending commands from the PC to the Arduino using the Serial Monitor in the
Arduino IDE. This project also introduces how we manipulate text strings. So leave the
hardware set up the same as before and enter the new code.

THE CIRCUIT:

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Code :
// Serial controlled RGB Lamp
char buffer[18];
int red, green, yellow;
int RedPin = 9;
int GreenPin = 10;
int BluePin = 11;
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);
}
}
void splitString(char* data) {
Serial.print("Data entered: ");
Serial.println(data);
char* parameter;
parameter = strtok (data, " ,");
while (parameter != NULL) {
setLED(parameter);
parameter = strtok (NULL, " ,");
}
// Clear the text and serial buffers
for (int x=0; x<16; x++) {
buffer[x]='\0';
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
}
Serial.flush();
}
void setLED(char* data) {
if ((data[0] == 'r') || (data[0] == 'R')) {
int Ans = strtol(data+1, NULL, 10);
Ans = constrain(Ans,0,255);
analogWrite(RedPin, Ans);
Serial.print("Red is set to: ");
Serial.println(Ans);
}
if ((data[0] == 'g') || (data[0] == 'G')) {
int Ans = strtol(data+1, NULL, 10);
Ans = constrain(Ans,0,255);
analogWrite(GreenPin, Ans);
Serial.print("Green is set to: ");
Serial.println(Ans);
}
if ((data[0] == 'b') || (data[0] == 'B')) {
int Ans = strtol(data+1, NULL, 10);
Ans = constrain(Ans,0,255);
analogWrite(BluePin, Ans);
Serial.print("Blue is set to: ");
Serial.println(Ans);
}
}

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 10 – Code Overview

Once you’ve verified the code, upload it to your Arduino.


Now when you upload the program nothing seems to happen. This is because the
program is waiting for your input. Start the Serial Monitor by clicking it’s icon in the Arduino
IDE taskbar.
In the Serial Monitor text window you can now enter the R, G and B values for each of
the 3 LED’s manually and the LED’s will change to the colour you have input.

E.g. If you enter R255 the Red LED will display at full brightness.

If you enter R255, G255, then both the red and green LED’s will display at full
brightness.

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.

The input text is designed to accept both a lowercase or upper-case R, G and B and
then a value from 0 to 255. Any values over 255 will be dropped down to 255 maximum.
You can enter a comma or a space in between parameters and you can enter 1, 2 or 3
LED values at any one time.
E.g.
r255 b100
r127 b127 g127
G255, B0
B127, R0, G255
Etc.

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 11 – 7seg-4digit LED Display


1. What is an 7seg-4digit LED Display?

In the following picture, there are other LED displays.

The internal structure Of LED display. This is the Common cathode 7seg-4digit LED
Display that we will use in this Experiment.
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore

First Experiment:
Prepare: 1 X 7seg-4digit LED Display , 8 X 220-ohm resistor , some Jumper
cable.

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
To build the circuit, attach the LED display’s (through a 220-ohm resistor) Pin 11, 7, 4, 2, 1,
10, 5, 3 to your Arduino board’s digital Pin 12, 11, 10, 9, 8, 7, 6, 5 .
Attach the LED display’s 12, 9, 8, 6 to the Ardiuno board’s digital Pin 4, 3, 2, 1 .

Code : open the folder Project_5 , and open the Project_5.pde


In the program, It will loop to show the number from 0 to 9

//设置控制各段的数字 IO 脚
int a = 12;
int b = 11;
int c = 10;
int d = 9;
int e = 8;
int f = 7;
int g = 6;
int dp = 5;
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
int ls1 = 1; //最右边第一位数码管
int ls2 = 2; //第二位数码管
int ls3 = 3; //第三位数码管
int ls4 = 4; //第四位数码管

//显示数字 0 , 11111100
void digital_0(void)
{
unsigned char j;
digitalWrite(dp,LOW);//给数字 5 引脚低电平,熄灭小数点 DP 段
digitalWrite(g,LOW);//熄灭 g 段
for(j=7;j<=12;j++)//点亮其余段
digitalWrite(j,HIGH);
}
//显示数字 1 , 01100000
void digital_1(void)
{
unsigned char j;
digitalWrite(a,LOW);
for(j=5;j<=9;j++)
digitalWrite(j,LOW);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
}
//显示数字 2
void digital_2(void)
{
unsigned char j;
digitalWrite(c,LOW);
digitalWrite(f,LOW);
digitalWrite(dp,LOW);
for(j=11;j<=12;j++)
digitalWrite(j,HIGH);
for(j=8;j<=9;j++)
digitalWrite(j,HIGH);
digitalWrite(g,HIGH);
}
//显示数字 3 22
void digital_3(void)
{
unsigned char j;
digitalWrite(e,LOW);
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
digitalWrite(f,LOW);
digitalWrite(dp,LOW);
for(j=9;j<=13;j++)
digitalWrite(j,HIGH);
digitalWrite(g,HIGH);
}
//显示数字 4
void digital_4(void)
{
digitalWrite(a,LOW);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(dp,LOW);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
}
//显示数字 5
void digital_5(void)
{
unsigned char j;
digitalWrite(b,LOW);
digitalWrite(e,LOW);
digitalWrite(dp,LOW);

digitalWrite(a,HIGH);
for(j=6;j<=7;j++)
digitalWrite(j,HIGH);
for(j=9;j<=10;j++)
digitalWrite(j,HIGH);
}
//显示数字 6
void digital_6(void)
{
unsigned char j;
digitalWrite(b,LOW);
digitalWrite(dp,LOW);

digitalWrite(a,HIGH);
for(j=6;j<=10;j++)
digitalWrite(j,HIGH);
}
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
//显示数字 7
void digital_7(void)
{
unsigned char j;
for(j=5;j<=9;j++)
digitalWrite(j,LOW);
for(j=10;j<=12;j++)
digitalWrite(j,HIGH);
}
//显示数字 8
void digital_8(void)
{
unsigned char j;
digitalWrite(dp,LOW);
for(j=6;j<=12;j++)
digitalWrite(j,HIGH);
}
//显示数字 9
void digital_9(void)
{
unsigned char j;
digitalWrite(e,LOW);
digitalWrite(dp,LOW);

for(j=9;j<=12;j++)
digitalWrite(j,HIGH);
for(j=6;j<=7;j++)
digitalWrite(j,HIGH);
}

//显示----------------------------
void Display(unsigned char mun)
{
switch (mun) {
case 0:
digital_0();//显示数字 0
break;
case 1:
digital_1();
break;
case 2:
digital_2();
break;
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
case 3:
digital_3();
break;
case 4:
digital_4();
break;
case 5:
digital_5();
break;
case 6:
digital_6();
break;
case 7:
digital_7();
break;
case 8:
digital_8();
break;
case 9:
digital_9();
break;
default: return;
// if nothing else matches, do the default
// default is optional
}
}

void setup()
{
int i;//定义变量
for(i=1;i<=12;i++)
pinMode(i,OUTPUT);//设置 1~12 引脚为输出模式
}
void loop()
{
unsigned char i, j, t;
while(1)
{
t = 1;
for(j=0; j<4 ; j++)
{
digitalWrite(j,LOW); //熄灭数码管使能端
}
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore

for(i=0; i<=9 ; i++)


{
if(t==1) //第一位数码管显示数字
{
digitalWrite(ls4,HIGH);
digitalWrite(ls3,HIGH);
digitalWrite(ls2,HIGH);
digitalWrite(ls1,LOW);
}
if(t==2) //第二位数码管显示数字
{
digitalWrite(ls4,HIGH);
digitalWrite(ls3,HIGH);
digitalWrite(ls1,HIGH);
digitalWrite(ls2,LOW);
}
if(t==3) //第三位数码管显示数字
{
digitalWrite(ls4,HIGH);
digitalWrite(ls2,HIGH);
digitalWrite(ls1,HIGH);
digitalWrite(ls3,LOW);
}
if(t==4) //第四位数码管显示数字
{
t = 0;
digitalWrite(ls3,HIGH);
digitalWrite(ls2,HIGH);
digitalWrite(ls1,HIGH);
digitalWrite(ls4,LOW);
}
Display(i);
delay(2000);//延时 2s
t++;

for(j=0; j<4 ; j++)


{
digitalWrite(ls1,LOW); //熄灭数码管使能端
}
}
}
}
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 12 – Show in 1602 LCD


In this project, we will learn how to control the 1602 LCD . It will use the
“ LiquidCrystal library “. This library allows you to control LCD displays that are
compatible with the Hitachi HD44780 driver. There are many of them out there, and you
can usually tell them by the 16-pin interface.
This example sketch prints funny words to the LCD and shows the time in seconds
since the Arduino was reset.

What you will need


1602 LCD Screen
10k Potentiometer

Connect it up
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
Additionally, wire a 10K pot to +5V and GND, with it's wiper (output) to LCD screen's
VO pin (pin3).

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Enter the code

// include the library code:


#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
}
void loop() {
// Print a message to the LCD.
lcd.print("hello, world!");
// Turn off the blinking cursor:
lcd.noBlink();
delay(3000);
// Turn on the blinking cursor:
lcd.blink();
delay(3000);
// set the cursor position:
lcd.setCursor(0,0); // begin from the first row of the first character
lcd.print("OK: ");
lcd.setCursor(5,0); // begin from the first row of the sixth character
lcd.print("Arduino!");
lcd.setCursor(0,1); // begin from the second row of the sixth character
lcd.print("Yes,B2CQSHOP");
delay(5000);
}

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 12 - Hardware Overview

The LCDs have a parallel interface, meaning that the microcontroller has to
manipulate several interface pins at once to control the display. The interface consists of
the following pins:

A register select (RS) pin that controls where in the LCD's memory you're writing
data to. You can select either the data register, which holds what goes on the screen, or
an instruction register, which is where the LCD's controller looks for instructions on what to
do next.

A Read/Write (R/W) pin that selects reading mode or writing mode

An Enable pin that enables writing to the registers

8 data pins (D0 -D7). The states of these pins (high or low) are the bits that you're
writing to a register when you write, or the values you're reading when you read.

There's also a display constrast pin (Vo), power supply pins (+5V and Gnd) and
LED Backlight (Bklt+ and BKlt-) pins that you can use to power the LCD, control the
display contrast, and turn on and off the LED backlight, respectively.

The process of controlling the display involves putting the data that form the image of
what you want to display into the data registers, then putting instructions in the instruction
register. The LiquidCrystal Library simplifies this for you so you don't need to know the
low-level instructions.

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore
The Hitachi-compatible LCDs can be controlled in two modes: 4-bit or 8-bit. The 4-bit
mode requires seven I/O pins from the Arduino, while the 8-bit mode requires 11 pins. For
displaying text on the screen, you can do most everything in 4-bit mode, so example
shows how to control a 2x16 LCD in 4-bit mode.

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Lesson 13 : Measure temperature (LM35)


1. What is LM35 Temperature Sensor ?

The LM35 series are precision integrated-circuit temperature sensors, whose output voltage
is linearly proportional to the Celsius (Centigrade) temperature.

Connection Diagrams

Calibrated directly in ° Celsius (Centigrade) , Linear + 10.0 mV/°C scale factor

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

First Experiment:
Prepare: 1 X LM35 Temperature Sensor , 1 X 1602 LCD display , some Jumper cable.

Please check the Lesson 7 : 1602 LCD , to wire your LED screen to your Arduino .
Attach the LM35’s Pin Vout ( the middle pin) to your arduino’s Analog Pin 0 . Vcc to
+5v , Gnd to your arduino board’s gnd
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
Code :
open the folder Project_8 , and open the Project_8.pde
In the program, when the Light is stronger, the resistance of sensor will be smaller, and
then the buzzer speak louder.

/*

The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)

*/

// include the library code:


#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins


LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
//tempeter
int val;
int dat;

void setup() {
Serial.begin(9600);
// set up the LCD's number of rows and columns:
lcd.begin(16, 2);
}

void loop() {
val=analogRead(0);
dat=(125*val)>>8; //计算温度值

lcd.setCursor(0,0);
lcd.print("Tep: ");
lcd.setCursor(6,0);
lcd.print(dat);
www.bestqshop.com Ebay store: b2cqshop , E-qstore
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
lcd.setCursor(10,0);
lcd.print("'C");
delay(10);
lcd.setCursor(0,1);
if(dat>18)
{
lcd.print("Warm! B2CQSHOP");
}
else
{
lcd.print("Cold! B2CQSHOP");
}

delay(500);
}

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 14 - Infrared Remote Control


In this project we will learn how to control the Infrared Remote .
To know more about how to control IR Remote Control. You should have a knowledge
of the NEC Protocol . Just do this project first, Go aheard .

(Please note that, connect the Infrared Receiver correctly .)

What you will need


Infrared Receiver (IRM_3638)
IR Remote Control
10 kΩ Resistors

Connect it up

www.bestqshop.com Ebay store: b2cqshop , E-qstore


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Enter the code

/*
Created By: Samleong
Created On: 2011-9-17
Website / More Infomation: http://www.b2cqshop.com
Email: [email protected]
*/
#define IR_IN 8 //Infrared receiver Pin

int Pulse_Width=0;//Storage width


int adr_code=0x00;// User-coded values
char comL_code=0x00;//Command code
char comH_code=0x00;//Anti-code command

void timer1_init(void)//Timer initialization function


{
TCCR1A = 0X00;
TCCR1B = 0X05;//To the timer clock source
TCCR1C = 0X00;
TCNT1 = 0X00;
www.bestqshop.com Ebay store: b2cqshop , E-qstore 98
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
TIMSK1 = 0X00; //Disable timer overflow interrupt
}
void remote_deal(void)//The results of the implementation of decoding function
{
//Show Data
if(adr_code!=0XFF)
{
Serial.print("the Address Code is : ");
Serial.println(adr_code, HEX);//Hexadecimal display
Serial.print("the Command code is : ");
Serial.println(comL_code, HEX);//Hexadecimal display
}
}
char logic_value()//Determine the logic value "0" and "1" Functions
{
TCNT1 = 0X00;
while(!(digitalRead(IR_IN))); //Low wait
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=7&&Pulse_Width<=10)//Low 560us
{
while(digitalRead(IR_IN));//Is waiting for another job
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=7&&Pulse_Width<=10)//Then high 560us
return 0;
else if(Pulse_Width>=25&&Pulse_Width<=27) //Then high 1.7ms
return 1;
}
return -1;
}
void pulse_deal()//Receiver address code and command code pulse function
{
int i;
int j;
adr_code=0x00;// Clear
comL_code=0x00;// Clear
comH_code=0x00;// Clear

//Parsing remote code value in the user code


for(i = 0 ; i < 16; i++)
{
if(logic_value() == 1) //if 1
www.bestqshop.com Ebay store: b2cqshop , E-qstore 99
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
adr_code |= (1<<i);//Save value
}
//Parsing code in the remote control command codes
for(i = 0 ; i < 8; i++)
{
if(logic_value() == 1) //if 1
comL_code |= (1<<i);//Save value
}
//Parsing code in the remote control command codes counter code
for(j = 0 ; j < 8; j++)
{
if(logic_value() == 1) //if 1
comH_code |= (1<<j);//Save value
}
}
void remote_decode(void)//Decoding function
{
TCNT1=0X00;
while(digitalRead(IR_IN))//if high then waiting
{
if(TCNT1>=1563) //When the high lasts longer than 100ms, that no button is pressed at this time
{
adr_code=0x00ff;// User-coded values
comL_code=0x00;//Key code value of the previous byte
comH_code=0x00;//After a byte key code value
return;
}
}

//If the high does not last more than 100ms


TCNT1=0X00;

while(!(digitalRead(IR_IN))); //Low wait


Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=140&&Pulse_Width<=142)//9ms
{

while(digitalRead(IR_IN));//high wait
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=68&&Pulse_Width<=72)//4.5ms
{
www.bestqshop.com Ebay store: b2cqshop , E-qstore 100
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
pulse_deal();
return;
}
else if(Pulse_Width>=34&&Pulse_Width<=36)//2.25ms
{
while(!(digitalRead(IR_IN)));//low wait
Pulse_Width=TCNT1;
TCNT1=0;
if(Pulse_Width>=7&&Pulse_Width<=10)//560us
{
return;
}
}
}
}
void setup()
{
unsigned char i;
pinMode(IR_IN,INPUT);//Set the infrared receiver input pin
// start serial port at 9600 bps:
Serial.begin(9600);
}
void loop()
{
timer1_init();//Timer initialization
while(1)
{
remote_decode(); //Decoding
remote_deal(); //Perform decoding
results
}
}

Press the key of the remote


controller, user the Serial Monitor
tool , the receiver will receive the
command code .

www.bestqshop.com Ebay store: b2cqshop , E-qstore 101


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Project 14 - Hardware Overview

The picture is the IRM_3638 Infrared Receiver . The Pin of it is showing in the picture,
when you wire this project, please check it carefully .

About the NEC protocol

NEC Protocol Features : ( http://www.sbprojects.com/knowledge/ir/nec.htm )

• 8 bit address and 8 bit command length


• Address and command are transmitted twice for reliability
• Pulse distance modulation
• Carrier frequency of 38kHz
• Bit time of 1.125ms or 2.25ms

Modulation:

The NEC protocol uses pulse distance encoding of the bits. Each pulse is a 560µs
long 38kHz carrier burst (about 21 cycles). A logical "1" takes 2.25ms to transmit, while a
logical "0" is only half of that, being 1.125ms. The recommended carrier duty-cycle is 1/4
or 1/3.
www.bestqshop.com Ebay store: b2cqshop , E-qstore 102
www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Protocol :

The picture above shows a pulse train of the NEC protocol. With this protocol the
LSB is transmitted first. In this case Address $59 and Command $16 is transmitted. A
message is started by a 9ms AGC burst, which was used to set the gain of the earlier IR
receivers. This AGC burst is then followed by a 4.5ms space, which is then followed by the
Address and Command. Address and Command are transmitted twice. The second time
all bits are inverted and can be used for verification of the received message. The total
transmission time is constant because every bit is repeated with its inverted length. If
you're not interested in this reliability you can ignore the inverted values, or you can
expand the Address and Command to 16 bits each!

A command is transmitted only once, even when the key on the remote control
remains pressed. Every 110ms a repeat code is transmitted for as long as the key
remains down. This repeat code is simply a 9ms AGC pulse followed by a 2.25ms space
and a 560µs burst.

In this Experiment, we will use a little different IR Remote Control , which use
WD6122 chip . ( Extended NEC protocol )

www.bestqshop.com Ebay store: b2cqshop , E-qstore 103


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Pay attention: When there is no infrared signals, the receiver’s output is High ;
while, it receives an signal, its output is LOW . We can check the received pulse
through the Oscilloscope, analyse the program according to the waveform.

About the IR Remote controller.

The Command Values of the IR Remote Control’s key like the following picture.

www.bestqshop.com Ebay store: b2cqshop , E-qstore 104


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

Mix Project 2 - Automatic Home


Application Control
About the relay, please view the relay from the bottom

WHAT WE’RE DOING:

This next circuit is a bit of a test. We combine what we learned about using transistors
to control a relay. A relay is an electrically controlled mechanical switch. Inside the little
plastic box is an electromagnet that, when energized, causes a switch to trip (often with a
very satisfying clicking sound). You can buy relays that vary in size from a quarter of the
size of the one in this kit up to as big as a fridge, each capable of switching a certain
amount of current. They are immensely fun because there is an element of the physical to
them. While all the silicon we've played with to this point is fun sometimes, you may just
want to wire up a hundred switches to control something magnificent. Relays give you the
ability to dream it up then control it with your Arduino. Now to using today's technology to
control the past. (The 1N4001 diode is acting as a flyback diode, for details on why it's
there visit: http://ardx.org/4001)

In this Project, we combine the Project of Measure temperature and show in the 1602
LCD .

www.bestqshop.com Ebay store: b2cqshop , E-qstore 105


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

CODE

/*
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
* LM35 Temperation sensor pin is Analog 0 ;
* The pin to control relay is Digital Pin 9
*/

// include the library code:


#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins


LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
//tempeter
www.bestqshop.com Ebay store: b2cqshop , E-qstore 106
www.b2cqshop.com Ebay store: b2cqshop , E-qstore
int val;
int dat;
//the relay to control the ledpin
int relayPin = 9 ;

void setup() {
Serial.begin(9600);
// set up the LCD's number of rows and columns:
lcd.begin(16, 2);
pinMode(relayPin,OUTPUT);
}

void loop() {
// clear the screen
val=analogRead(0);
dat=((125*val)>>8)+12; //Calculate the temperation

lcd.setCursor(0,0);
lcd.print("Tep: ");
lcd.setCursor(6,0);
lcd.print(dat);
lcd.setCursor(10,0);
lcd.print("'C");
delay(10);
lcd.setCursor(0,1);
if(dat>29)
{
lcd.print("open conditioner");
digitalWrite(relayPin,HIGH);
delay(1000);
}
else
{
lcd.print("Cold! B2CQSHOP");
digitalWrite(relayPin,LOW);
delay(1000);
}

delay(1000);
lcd.clear();
}

www.bestqshop.com Ebay store: b2cqshop , E-qstore 107


www.b2cqshop.com Ebay store: b2cqshop , E-qstore

www.bestqshop.com Ebay store: b2cqshop , E-qstore 108

You might also like