Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
167 views

Arduino Document

This document provides an introduction to the Arduino starter kit. It includes a list of the components included in the kit and descriptions of their functions. It explains that the book will guide the reader through building electronic projects using the Arduino hardware and software. It emphasizes that the projects are designed for beginners to learn core concepts in a step-by-step manner without requiring prior knowledge of electronics, programming, or the Arduino platform.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
167 views

Arduino Document

This document provides an introduction to the Arduino starter kit. It includes a list of the components included in the kit and descriptions of their functions. It explains that the book will guide the reader through building electronic projects using the Arduino hardware and software. It emphasizes that the projects are designed for beginners to learn core concepts in a step-by-step manner without requiring prior knowledge of electronics, programming, or the Arduino platform.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

Department of Electronics and Telecommunication Engg.

Contents
Introduction 1 Project 12 - Piezo Sounder Melody Player 37

The Starter Kit Contents 2 Code Overview 38

What exactly is an Arduino? 3 Hardware Overview 39

Getting Started 11 Project 13 - Serial Temperature Sensor 40

Upload your first sketch 13

The Arduino IDE 15

The Projects 19

Project 1 - LED Flasher 21

Hardware Overview 21

Project 2 - SOS Morse Code Signaller 22

Code Overview 22

Project 3 - Traffic Lights 23

Project 4 - Interactive Traffic Lights 23

Code Overview 24

Project 5 - LED Chase Effect 23

Code Overview 25

Project 6 - Interactive LED Chase Effect 25

Code Overview 26

Hardware Overview 26

Project 7 - Pulsating Lamp 27

Code Overview 27

Project 8 - Mood Lamp 28

Code Overview 29

Project 9 - LED Fire Effect 30

Code Overview 31

Project 10 - Serial Controlled Mood Lamp 32

Code Overview 33

Project 11 - Drive a DC Motor 34

Code Overview 35

Hardware Overview 36

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

Introduction
Everything will be explained in clear and easy to follow
steps. The book contains a lot of diagrams and
photographs to make it as easy as possible to check
that you are following along with the project correctly.
What you will need

You are now well on your way in your journey into the Firstly, you will need access to the internet to be able
wonderful world of the Arduino and microcontroller to download the Arduino IDE (Integrated Development
electronics. Environmentand also any code libraries that may be
necessary to get your project working.
This book will guide you, step by step, through using
the Starter Kit to learn about the Arduino hardware, You will need a well lit table or other flat surface to lay
software and general electronics theory. Through the out your components and this will need to be next to
use of electronic projects we will take you from the your desktop or laptop PC to enable you to upload the
level of complete beginner through to having an code to the Arduino. Remember that you are working
intermediate set of skills in using the Arduino. with electricity (although low voltage DC) and
therefore a metal table or surface will first need to be
The booklet has been written presuming that you have covered in a non-conductive material (e.g. tablecloth,
no prior knowledge of electronics, the Arduino paper, etc.) before laying out your materials.
hardware, software environment or of computer Also of some benefit, although not essential, may be a
programming. At no time will we get too deep into
pair of wire cutters, a pair of long nosed pliers and a
electronics or programming in C. There are many
other resources available for free that will enable you wire stripper.
to learn a lot more about this subject if you wish to go A notepad and pen will also come in handy for
further. The best possible way to learn the Arduino, drawing out rough schematics, working out concepts
after using this kit of course, is to join the Arduino
and designs, etc.
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.

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

The Starter Kit Contents


Please note that your kit contents may look slightly different to those listed here

Freeduino or
Piezo Sounder
Roboduino Board 9v DC Power Supply Breadboard USB Cable

10 x Clear RED 5mm 10 x Clear Blue 5mm 10 x Clear Green 5mm


LEDʼs LEDʼs LEDʼs 5 x 1N4001 Diodes 3-Way Terminal Block

10 x Yellow Diffused 10 x Green Diffused 10 x RED Diffused


5mm LEDʼs
5mm LEDʼs 5mm LEDʼs 5 x Tactile Switches 4K7 Potentiometer

Light Dependent 8x8 Mini LED 2 x BC547 NPN TIP-120 NPN Transistor
Resistor Dot Matrix Display Transistors DC Motor

10 x 100R Resistors
10 x 150R Resistors 10 x 240R Resistors 10 x 470R Resistors 10 x 1KR Resistors

3 x 74HC595
10 x 1K5R Resistors 10 x 1MR Resistors LM35DT Shift Register ICʼs
Temperature Sensor 3 x 16-Pin IC Socket

Jumper Wire Kit eBook


Component Case

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

What exactly is an Arduino?


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
Now that you are a proud owner of an Arduino, or an that the Arduino understands. In the case of the
Arduino clone, it might help if you knew what it was Arduino the language is C. The IDE enables you to
and what you can do with it. write a computer program, which is a set of step-by-
step instructions that you then upload to the Arduino.
In its simplest form, an Arduino is a tiny computer that
Then your Arduino will carry out those instructions and
you can program to process inputs and outputs going interact with the world outside. In the Arduino world,
to and from the chip. programs are known as ʻSketchesʼ.
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 hardware and software are both Open
The Arduino can be used to develop stand-alone
Source, which means the code, the schematics,
interactive objects or it can be connected to a
computer to retrieve or send data to the Arduino and design, etc. are all open for anyone to take freely and
then act on that data (e.g. Send sensor data out to the do what they like with it.
internet). This means there is nothing stopping anyone from
The Arduino can be connected to LEDʼs. Dot Matrix taking the schematics and PCB designs of the Arduino
displays, LED displays, buttons, switches, motors, and making their own and selling them. This is
temperature sensors, pressure sensors, distance perfectly legal, and indeed the whole purpose of Open
sensors, webcams, printers, GPS receivers, ethernet Source, and indeed the Freeduino that comes with the
modules,
Earthshine Design Arduino Starter Kit is a perfect
The Arduino board is made of an an Atmel AVR
example of where someone has taken the Arduino
Microprocessor, a crystal or oscillator (basically a
PCB design, made their own and are selling it under
crude clock that sends time pulses to the
the Freeduino name. You could even make your own
microcontroller to enable it to operate at the correct
Arduino, with just a few cheap components, on a
breadboard.

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

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 Then, for a couple of quid or bucks you can replace
own products and hence the clone boards have the AVR chip in your Arduino with a new one. The chip
names such as Freeduino, Boarduino, Roboduino, etc. must be pre-programmed with the Arduino Bootloader
to enable it to work with the Arduino IDE, but you can
As the designs are open source, any clone board, either burn the Bootloader yourself if you purchase an
such as the Freeduino, is 100% compatible with the AVR Programmer, or you can buy these pre-
Arduino and therefore any software, hardware, programmed from many suppliers around the world.
shields, etc. will all be 100% compatible with a Of course, Earthshine Design provide pre-
genuine Arduino. programmed 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.
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
The Arduino can also be extended with the use of program the Arduino and make it interact with other
ʻShieldsʼ which are circuit boards containing other components a well as a bit of imagination, you can
devices (e.g. GPS receivers, LCD Displays, Ethernet build anything you want.
connections, etc.) that you can simply slot into the top This book and the kit will give you the necessary skills
of your Arduino to get extra functionality. You donʼt
needed to get started in this exciting and creative
have to use a shield if you donʼt want to as you can
make the exact same circuitry using a breadboard, hobby.
some veroboard or even by making your own PCBʼs. So, now you know what an Arduino is and what you
There are many different variants of the Arduino can do with it, letʼs open up the starter kit and dive
available. The most common one is the Diecimila or right in.
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 under-
stairs 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.

10

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

Getting Started
This section will presume you have a PC running
Windows or a Mac running OSX (10.3.9 or later). If
If you have a Mac these are in the drivers directory.
you use Linux as your Operating System, then refer to
If you have an older Mac like a PowerBook, iBook, G4
the Getting Started instructions on the Arduino website
or G5, you should use the PPC drivers:
at http://www.arduino.cc/playground/Learning/Linux
FTDIUSBSerialDriver_v2_1_9.dmg. If you havea
newer Mac with an Intel chip, you need the Intel d r i v
ers:
FTDIUSBSerialDriver _v2
_2_9_Intel.dmg.Double-click to mount the disk
image and run the included
FTDIUSBSerialDriver.pkg.
The latest version of the drivers can be found on the
FTDI website.
Connect the Freeduino

First, make sure that the little power jumper, between


the power and USB sockets, is set to USB and not
EXTernal power (not applicable if you have a
Get the Freeduino and the USB Cable Roboduino board, which has an Auto Power Select
function).
Firstly, get your Freeduino board and lay it on the
table in front of you. Take the USB cable Using this
and plug the B plug (the fatter jumper you can
squarer end) into the USB socket either power the
board from the
on the Freeduino.
USB port (good
At this stage do NOT connect the for low current
Freeduino to your PC or Mac yet. deviceslike
LEDʼs, etc.) or
Download the Arduino IDE from an external
power supply (6-12V DC).
Download the Arduino IDE from the Arduino
downloadpage. As of the time of writing this book, the Now, connect the other end of the USB cable into the
latestIDE version is 0015. The file is a ZIP file so you USB socket on your PC or Mac. You will now see the
will need to uncompress it. Once the download has small power LED (marked PWR above the RESET
finished, unzip the file, making sure that you preserve switch) light up to show you have power to the board.
the folder structure as it is and do not make any If you have a Mac, this stage of the process is
changes.
complete and you can move on to the next Chapter. If
If you double-click the folder, you will see a few files
you are using Windows, there are a few more steps to
and sub-folders inside. complete (Damn you Bill Gates!).
Install the USB Drivers

If you are using Windows you will find the drivers in


the drivers/FTDI USB
Drivers directory of the
Arduino distribution. In the
next stage (“Connect the
Freeduino”), you will point
W i n d o w ʼ s A d d N e
wHardware wizard to
thesedrivers.

11

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

On Windows the Found New Hardware Wizard will Uncheck “Search removable media”. Check
now open up as Windows will have detected that you “Includethis location in the search” and then click
have connected a new piece of hardware (your the
Freeduino board) to your PC. Tell it NOT to connect to Browse button. Browse to the location of the
Windows update (Select No, not at this time) and USBdrivers and then click Next.
then click Next.

The wizard will now search for a suitable driver and


then tell you that a “USB Serial Convertor” has been
On the next page select “Install from a list orspecific found and that the hardware wizard is now complete.
location (Advanced)” and click Next. Click Finish.

Make sure that “Search for the best driver in these You are now ready to upload your first Sketch.
locations” is checked.

12

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

Upload your first Sketch


you will see the Sketch inside the white code window.

Now, before we upload the Sketch, we need to tell the


IDE what kind of Arduino we are using and the details
of our USB port. Go to the file menu and click Tools,
then clock on Board. You will be presented with a list
of all of the different kinds of Arduino board that can
be connected to the IDE. Our Freeduino board will
either be fitted with an Atmega328 or an Atmega168
chip so choose “Arduino Duemilanove w/ATmega328”
if you have a 328 chip or “Arduino Diecimila or
Duemilanove w/ ATmega168” if you have a 168 chip.

Now that your Freeduino has been connected and the Now you need to tell the IDE the details of your USB
drivers for the USB chip have been installed, we are port, so now click on Tools again, scroll down to Serial
now ready to try out the Arduino for the first time and Port and a list of the available serial ports on your
upload your first Sketch. system will be displayed. You need to choose the one
that refers to your USB cable, which is usually listed
Navigate to your newly unzipped Arduino folder and as something like /dev/tty.usbserial-xxxx on a
look for the Arduino IDE icon, which looks something Mac or something like Com 4 on Windows so click on
like this.... that. If not sure, try each one till you find one that
works.
Double click the ICON to open up the
IDE. You will then be presented with a
blue and white screen with a default
sketch loaded inside.
This is the Arduino IDE (Integrated Development
Environment) and is where you will write your
Sketches (programs) to upload to your Arduino board.
Now that you have selected the correct board and
We will take a look at the IDE in a little more detail in
USB port you are ready to upload the Blink Sketch to
the next chapter. For now, simply click File in the file
the board.
menu and scroll down to
Sketchbook. Then scroll
You can either click the Upload button, which is the 6th
down to Examples and
button from the left at the top with an arrow pointing to
c l i c k i t . Yo u w i l l b e
the right (hover your mouse pointer over the buttons to
presented with a list of
see what they are) or by clicking on File in the file
Example sketches that you
menu and scrolling down to Upload to I/O Board and
can use to try out your
clicking on that.
Arduino. Now click on
Digital and inside there you Presuming everything has been set up correctly you
will find an example Sketch called Blink. Click on this. will now see the RX and TX LEDʼs (and also LED 13)
on the Freeduino flash on and off very quickly as data
The Blink
is uploaded to the board. You will see Uploading to
Sketch will
I/OBoard.... Just below the code window too.
now be
loaded into
the IDE and

13

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

Once the data has been uploaded to the board If so, congratulations, you have just successfully
successfully you will get a Done Uploading message installed your Arduino, uploaded and ran your first
in the IDE and the RX/TX LEDʼs will stop flashing. sketch.
The Arduino will now reset itself and immediately start We will now explain a bit more about the Arduino IDE
to run the Sketch that you have just uploaded. and how to use it before moving onto the projects that
you can carry out using the hardware supplied with the
The Blink sketch is a kit. For our first project we will carry out this Blink LED
very simple sketch sketch again, but this time using an LED that we will
that blinks LED 13, physically connect to one of the digital output pins on
which is a tiny green the Arduino. We will also explain the hardware and
LED soldered to the software involved in this simple project. But first, letʼs
boardandalso take a closer look at the Arduino IDE.
connected to Digital
Pin 13 from the
Microcontroller, and
will make it flash on
and off every 1000 milliseconds, or 1 second.
If your sketch has uploaded successfully, you will now
see this LED happily flashing on and off slowly on your
board.

14

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

The Arduino IDE

When you open up the Arduino IDE it will look very The Toolbar consists of 7 buttons, underneath the
similar to the image above. If you are using Windows Toolbar is a tab, or set of tabs, with the filename of the
or Linux there will be some slight differences but the code within the tab. There is also one further button on
IDE is pretty much the same no matter what OS you the far right hand side.
are using.
Along the top is the file menu with drop down menus
The IDE is split up into the Toolbar across the top, the headed under File, Edit, Sketch, Tools and Help. The
code or Sketch Window in the centre and the Serial buttons in the Toolbar provide convenient access to
Output window at the bottom. the most commonly used functions within this file
menu.

15

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

Verify/ Serial
Stop New Open Save Upload
Compile Monitor
The Toolbar buttons are listed above. The functions of each button are as follows :-

Verify/C ompile Checks the code for errors

Stop Stops the serial monitor, or un-highlights other buttons

Ne w Creates a n ew blank Sketch

Ope n Show s a list of Sket ches in your sketchbook

Save Saves the current Sketch

Upload Uplo ads the current Sketch to the Arduino

Serial Monitor Displays serial data b eing sent from the Arduino

The Verify/Compile button is used to check that your The Upload to I/O Board button will upload the code
code is correct, before you upload it to your Arduino. within the current sketch window to your Arduino. You
need to make sure that you have the correct board
The Stop button will stop the Serial Monitor from and port selected (in the Tools menu) before
operating. It will also un-highlight other selected uploading. It is essential that you Save your sketch
buttons. Whilst the Serial Monitor is operating you may before you upload it to your board in case a strange
wish to press the Stop button to obtain a ʻsnapshotʼ of error causes your system to hang or the IDE to crash.
the serial data so far to examine it. This is particularly It is also advisable to Verify/Compile the code before
useful if you are sending data out to the Serial Monitor you upload to ensure there are no errors that need to
quicker than you can read it. be debugged first.
The New button will create a completely new and The Serial Monitor is a very useful tool, especially for
blank Sketch read for you to enter code into. The IDE debugging your code. The monitor displays serial data
will ask you to enter a name and a location for your being sent out from your Arduino (USB or Serial
Sketch (try to use the default location if possible) and board). You can also send serial data back to the
will then give you a blank Sketch ready to be coded. Arduino using the Serial Monitor. If you click the Serial
The tab at the top of the Sketch will now contain the Monitor button you will be presented with an image
name you have given to your new sketch. like the one above.
The Open button will present you with a list of On the left hand side you can select the Baud Rate
Sketches stored within your sketchbook as well as a that the serial data is to be sent to/from the Arduino.
list of Example sketches you can try out with various The Baud Rate is the rate, per second, that characters
peripherals once connected. (data) is sent to/from the board. The default setting is
9600 baud, which means that if you were to send a
The Save button will save the code within the sketch text novel over the serial communications line (in this
window to your sketch file. Once complete you will get case your USB cable) then 9600 letters, or symbols, of
a ʻDone Saving message at the bottom of the code the novel, would be sent per second.
window.

16

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

To the right of this is a blank text box for you to enter Across the top of the IDE window (or across the top of
text to send back to the Arduino and a Send button to your screen if you are using a Mac) you will see the
send the text within that field. Note that no serial data various menus that you can click on to access more
can be received by the Serial Monitor unless you have menu items.
set up the code inside your sketch to do so. Similarly,
the Arduino will not receive any data sent unless you
have coded it to do so.
The menu bar across the top of the IDE looks like the
Finally, the black area is where your serial data will be
image above (and slightly different in Windows and
displayed. In the image above, the Arduino is running
Linux). I will explain the menus as they are on a Mac,
the ASCIITable sketch, that can be found in the
the details will also apply to the Windows and Linux
Communications examples. This program outputs
ASCII characters, from the Arduino via serial (the USB versions of the IDE.
cable) to the PC where the Serial monitor then The first menu is the
displays them. Arduinomenu. Within this is
To start the Serial Monitor press the Serial Monitor the
button and to stop it press the Stop button. On a Mac About Arduino option,
or in Linux, Arduino board will reset itself (rerun the whichwhen pressed will show
code from the beginning) when you click the Serial you the current version
Monitor button. number, a list of the people
involved in making this
Once you are proficient at communicating via serial to amazing device and some
and from the Arduino you can use other programs further information.
such as Processing, Flash, MaxMSP, etc. To
Underneath that is the
communicate between the Arduino and your PC. Preferences option. This
We will make use of the Serial Monitor later on in our willbring up the Preferences
projects when we read data from sensors and get the window where you can change various IDe options,
Arduino to send that data to the Serial Monitor, in such as were you default Sketchbook is stored, etc.
human readable form, for us to see. Also, is the Quit option, which will Quit the program.
The Serial Monitor window is also were you will see
The next menu is the
error messages (in red text) that the IDE will display to
File menu. In here
you when trying to connect to your board, upload code
youget access to
or verify code. options to create a New
Below the Serial Monitor at the bottom left you will see sketch, take a look at
a number. This is the current line that the cursor, Sketches s t o r e d i n y
within the code window, is at. If you have code in your o u r Sketchbook (as
window and you move down the lines of code (using well as the Example
the ↓ key on your keyboard) you will see the number Sketches), options to
Save your Sketch (or
increase as you move down the lines of code. This is
Save As if
useful for finding bugs highlighted by error messages.
you want to give it a different name). You also have
the option to upload your sketch to the I/O Board
(Arduino) as well as the Print options for printing out

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
your code.

17

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

Next is the Edit menu. In here you The next menu in the
get options to enable you to Cut, IDE is the Tools menu.
Copy and Paste sections of code. Within this are the
Select All of your code as well as options to select the
Find certain words or phrases Board and Serial Port we
within the code. Also included are are using, as we did
the useful Undo and Redo options when setting up the
which come in handy when you Arduino for the first time.
make a mistake. Also we have the Auto
Format function that
Our next menu is the Sketch menu which gives us formats your code to make it look nicer.
access to the Verify/Compile functions and some other
useful functions you The Copy for Forum option will copy the code within
will use later on. the Sketch window, but in a format that when pasted
These include the into the Arduino forum (or most other Forums for that
Import Library option, matter) will show up the same as it is in the IDE, along
which when clicked with syntax colouring, etc.
will bring up a list of
the available The Archive Sketch option will enable you to
libraries, stored compress your sketch into a ZIP file and asks you
within your were you want to store it.
libraries folder.
Finally, the Burn Bootloader option can be used to
A Library, is a collection of code, that you can include burn the Arduino Bootloader (piece of code on the
in your sketch, to enhance the functionality of your chip to make it compatible with the Arduino IDE) to the
project. It is a way of preventing you from ʻre - chip. This option can only be used if you have an AVR
inventing the wheelʼ by reusing code already made by programmer and have replaced the chip in your
someone else for various pieces of common hardware Arduino or have bought blank chips to use in your own
you may encounter whilst using the Arduino. embedded project. Unless you plan on burning lots of
chips it is usually cheaper and easier to just buy an
For example, one of the libraries you will find is ATmega chip with the Arduino Bootloader already pre-
Stepper, which is a set of functions you can programmed. Many online stores stock pre-
usewithin your code to control a Stepper Motor. programmed chips and obviously these can be found
Somebody else has kindly already created all of the in the Earthshine Design store.
necessary functions necessary to control a stepper
motor and by including the Stepper library into our The final menu is the Help menu were you can find
sketch we can use those functions to control the motor help menus for finding out more information about the
as we wish. By storing commonly used code in a IDE or links to the reference pages of the Arduino
library, you can re-use that code over and over in website and other useful pages.
different projects and also hide the complicated parts
of the code from the user. Donʼt worry too much about using the IDE for now as
you will pick up the important concepts and how to use
We will go into greater detail concerning the use of it properly as we work our way through the projects.
libraries later on. Finally within the Sketch menu is the So, on that note, letʼs get on with it.
Show Sketch Menu option, which will open up the
folder were your Sketch is stored. Also, there is the
Add File option which will enable you to add another
source file to your Sketch. This functionality allows you
to split larger sketches into smaller files and then Add
them to the main Sketch.

Arduino classified in basic three parts:

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
Structure VariablesConstants FunctionsDigital I/O

 setup() HIGH | LOW  pinMode()


 loop() INPUT | OUTPUT| INPUT_PUL  digitalWrite()
LUP  digitalRead()
Control Structures  true | false
 integer constants Analog I/O
 if  floating point constants
 if...else  analogReference()
 for Data Types  analogRead()
 switch case  analogWrite() - PWM
 while  void
 do... while  boolean Due only
 break  char
 continue  unsigned char  analogReadResolution
 return  byte ()
 goto  int  analogWriteResolutio
 unsigned int n()
Further Syntax  word
 long Advanced I/O
 ; (semicolon)  unsigned long
 {} (curly braces)  short  tone()
 // (single line  float  noTone()
comment)  double  shiftOut()
 /* */ (multi-line  string - char array  shiftIn()
comment)  String - object  pulseIn()
 #define  array
 #include Time
Conversion
Arithmetic  millis()
Operators  char()  micros()
 byte()  delay()
 = (assignment  int()  delayMicroseconds()
operator)  word()
 + (addition)  long() Math
 - (subtraction)  float()
 * (multiplication)  min()
 / (division) Variable Scope & Qualifiers  max()
 % (modulo)  abs()
 variable scope  constrain()
Comparison  static  map()
Operators  volatile  pow()
 const  sqrt()
 == (equal to)
 != (not equal to) Utilities Trigonometry
 < (less than)
 > (greater than)  sizeof()  sin()
 <= (less than or  cos()
equal to)   tan()
 >= (greater than or
equal to) Random Numbers

Boolean Operators  randomSeed()

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
 random()
 && (and)
 || (or)
 ! (not) Bits and Bytes

Pointer Access  lowByte()


Operators  highByte()
 bitRead()
 * dereference  bitWrite()
operator  bitSet()
 & reference operator  bitClear()
 bit()
Bitwise Operators
External Interrupts
 & (bitwise and)
 | (bitwise or)
 attachInterrupt()
 ^ (bitwise xor)
 detachInterrupt()
 ~ (bitwise not)
 << (bitshift left)
 >> (bitshift right) Interrupts

Compound  interrupts()
Operators  noInterrupts()

 ++ (increment) Communication
 -- (decrement)
 += (compound  Serial
addition)  Stream
 -= (compound
subtraction)
 *= (compound
multiplication)
 /= (compound
division)
 &= (compound
bitwise and)
 |= (compoun
d bitwise or)

Structure

Sno Structure Description

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
The setup() function is called when a sketch starts. Use
it to initialize variables, pin modes, start using libraries,
1 setup() etc. The setup function will only run once, after each
powerup or reset of the Arduino board.
After creating a setup() function, which initializes and
sets the initial values, the loop() function does precisely
2 loop() what its name suggests, and loops consecutively,
allowing your program to change and respond. Use it to
actively control the Arduino board.

Control Structures
Sno Conditional description
1 if, which is used in conjunction with a comparison
if
operator, tests whether a certain condition has been
reached, such as an input being above a certain number.
2 if/else allows greater control over the flow of code than
if / else
the basic if statement, by allowing multiple tests to be
grouped together.
3 for The for statement is used to repeat a block of
statements enclosed in curly braces. An increment
counter is usually used to increment and terminate the
loop.
4 a switch statement compares the value of a variable to
switch /
the values specified in case statements.
case
statements
5 while loops will loop continuously, and infinitely, until
While loop
the expression inside the parenthesis, () becomes false.
6 The do loop works in the same manner as
do - while
the while loop, with the exception that the condition is
tested at the end of the loop, so the do loop
will always run at least once.
7 break is used to exit from a do, for, or while loop,
break
bypassing the normal loop condition. It is also used to
exit from aswitch statement.
8 The continue statement skips the rest of the current
continue
iteration of a loop (do, for, or while). It continues by
checking the conditional expression of the loop, and
proceeding with any subsequent iterations.
9 Terminate a function and return a value from a function
return
to the calling function, if desired.
10 Transfers program flow to a labeled point in
goto
the program

Arithmetic Operators
Sno operators Description
1 = Stores the value to the right of the equal sign in the variable
to the left of the equal sign.
2 + These operators return the sum of the two operands.
3 - These operators return the difference of the two operands.
4 * These operators return the product of the two operands.
Govt. Girls Polytechnic Jagdalpur
Department of Electronics and Telecommunication Engg.
5 / These operators return the quotient of the two operands.
6 % Calculates the remainder when one integer is divided by
another. It is useful for keeping a variable within a
particular range

Comparison Operators
Sno Operators Description
1 == These operators return the equal between operands.
2 != These operators return the not equal between operands.
3 < These operators return the less than between operands.
4 > These operators return the greater than between
operands.
5 <= These operators return the less than or equal to between
operands.
6 >= These operators return the greater than or equal to
between operands.

Boolean Operators
Sno Operators Description
1 && These operators return the AND the two operands.
2 || These operators return the OR of the two operands.
3 ! These operators return the NOT of the two operands.

Pointer Access Operators


The pointer operators
& (reference) and * (dereference)
Pointers are one of the more complicated subjects for beginners in learning
C, and it is possible to write the vast majority of Arduino sketches without
ever encountering pointers. However for manipulating certain data
structures, the use of pointers can simplify the code, and and knowledge of
manipulating pointers is handy to have in one's toolkit.

Bitwise Operators
Sno Operators Description
1 & The bitwise operators perform their calculations at the bit
level of variables.
2 | The bitwise OR of two bits is 1 if either or both of the input
bits is 1, otherwise it is 0.
3 ^ This operator is similar to the bitwise OR operator |, only it
evaluates to 0 for a given bit position when both of the
input bits for that position are 1
4 ~ Bitwise NOT changes each bit to its opposite: 0 becomes 1,
and 1 becomes 0.
5 << These operators cause the bits in the left operand to be
shifted left
6 >> These operators cause the bits in the right operand to be
shifted right

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
Compound Operators
Sno Operators Description
1 ++ Increment a variable
2 -- Decrement a variable
3 += compound addition
4 -= compound subtraction
5 *= compound multiplication
6 /= compound division
7 &= compound bitwise and
8 |= compound bitwise or

Variables

Constants
Sno constants Description
1 HIGH|LOW The meaning of HIGH whena pin is set to an INPUT or
OUTPUT. When a pin is configured as an INPUT with
pinMode, and read with digitalRead, the
microcontroller will report HIGH if a voltage of 3 volts
or more is present at the pin.
The meaning of LOW when a pin is configured as an
INPUT with pinMode, and read with digitalRead, the
microcontroller will report LOW if a voltage of 2 volts or
less is present at the pin.
2 INPUT A pin may also be configured as an INPUT with
PULLUP pinMode, and subsequently made HIGH with
digitalWrite, this will set the internal 20K pullup
resistors, which will steer the input pin to a HIGH
reading unless it is pulled LOW by external circuitry.
3 TRUE|FALSE true is defined as 1, which is correct which is non-zero is
true
false is the easier of the two to define. false is defined
as 0 (zero).
4 INTEGER Integer constants are treated as base 10 (decimal)
CONSTANT integers, but special notation (formatters) may be used
to enter numbers in other bases.
5 FLOATING Floating point constants can also be expressed in a
POINT variety of scientific notation. 'E' and 'e' are both
CONSTANT accepted as valid exponent indicators.

Data Types
Sno Data Types Description
1 Void The void keyword is used only in function declarations. It
indicates that the function is expected to return no
information to the function from which it was called.
2 A boolean holds one of two values, true or false. (Each
boolean
boolean variable occupies one byte of memory.)

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
3 A data type that takes up 1 byte of memory that stores a
char
character value.

4 A byte stores an 8-bit unsigned number, from 0 to 255.


byte

5 unsigned ints (unsigned integers) are the same as ints in


unsigned
that they store a 2 byte value. Instead of storing negative
int
numbers

6 A word stores a 16-bit unsigned number, from 0 to 65535.


word

7 Long variables are extended size variables for number


Long
storage, and store 32 bits (4 bytes), from -2,147,483,648
to 2,147,483,647.

8 Unsigned long variables are extended size variables for


unsigned
number storage, and store 32 bits (4 bytes). Unlike
long
standard longs unsigned longs won't store negative
numbers
9 Datatype for floating-point numbers, a number that has a
float
decimal point. Floating-point numbers are often used to
approximate analog and continuous values because they
have greater resolution than integers.
10 Double precision floating point number this occupies 4
double
bytes

11 Text strings can be represented char array and abject.


String
12 An array is a collection of variables that are accessed with
Array
an index number.

Conversion
Sno Conversion Description
1 Char() Converts a value to the char data type.
2 Byte() Converts a value to the byte data type.
3 Int() Converts a value to the int data type.
4 Word() Convert a value to the word data type or create a word
from two bytes.
5 Long() Converts a value to the long data type.
6 Float() Converts a value to the float data type.

Variable Scope & Qualifiers


Sno Conversion Description
1 Variables in the C programming language, which
Variable Scope
Arduino uses, have a property called scope. This is in
contrast to early versions of languages such as BASIC
where every variable is a global variable.

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
A global variable is one that can be seen by every
function in a program. Local variables are only visible
to the function in which they are declared.
2 The static keyword is used to create variables that
Static
are visible to only one function. Variables declared as
static will only be created and initialized the first time
a function is called.
3 volatile is a keyword known as a variable qualifier, it
Volatile
is usually used before the datatype of a variable, to
modify the way in which the compiler and
subsequent program treats the variable.

4 The const keyword stands for constant. It is a


Constant
variable qualifier that modifies the behavior of the
variable, making a variable "read-only".

Functions

Sno Function Discription


1 Configures the specified pin to behave either as an
pinMode()
input or an output. See the description of digital
pins for details on the functionality of the pins.
2
digitalWrite() Write a HIGH or a LOW value to a digital pin.
If the pin has been configured as an OUTPUT
with pinMode(), its voltage will be set to the
corresponding value: 5V (or 3.3V on 3.3V boards)
for HIGH, 0V (ground) for LOW.
3 Reads the value from a specified digital pin,
digitalRead()
either HIGH or LOW.

Analog I/O
Sno Function Discription
1 Configures the reference voltage used for
analogReference(type)
analog input (i.e. the value used as the top
of the input range).
2 Reads the value from the specified analog
analogRead()
pin. The Arduino board contains a 6 channel
(8 channels on the Mini and Nano, 16 on the
Mega), 10-bit analog to digital converter.
This means that it will map input voltages
between 0 and 5 volts into integer values
between 0 and 1023.
3 Writes an analog value (PWM wave) to a pin.
analogWrite()
Can be used to light a LED at varying
brightnesses or drive a motor at various
speeds. After a call to analogWrite(), the pin
will generate a steady square wave of the
Govt. Girls Polytechnic Jagdalpur
Department of Electronics and Telecommunication Engg.
specified duty cycle until the next call
to analogWrite() (or a call
to digitalRead() or digitalWrite() on the same
pin). The frequency of the PWM signal on
most pins is approximately 490 Hz. On the
Uno and similar boards, pins 5 and 6 have a
frequency of approximately 980 Hz. Pins 3
and 11 on the Leonardo also run at 980 Hz

Due only
Sno Function Function
1 analogReadResolution() is an extension of
analogReadResolution()
the Analog API for the Arduino Due.
Sets the size (in bits) of the value returned
by analogRead(). It defaults to 10 bits
(returns values between 0-1023) for
backward compatibility with AVR based
boards.
The Due has 12-bit ADC capabilities that
can be accessed by changing the
resolution to 12. This will return values
from analogRead() between 0 and 4095.
2 analogWriteResolution() is an extension of
analogWriteResolution()
the Analog API for the Arduino Due.
analogWriteResolution() sets the
resolution of the analogWrite() function. It
defaults to 8 bits (values between 0-255)
for backward compatibility with AVR
based boards.
The Due has the following hardare
capabilities:

 12 pins which default to 8-bit


PWM, like the AVR-based boards.
These can be changed to 12-bit
resolution.
 2 pins with 12-bit DAC (Digital-to-
Analog Converter)

Advanced I/O
Sno Function Discription
1 Tone() Generates a square wave of the specified

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
frequency (and 50% duty cycle) on a pin. A
duration can be specified, otherwise the wave
continues until a call to noTone().
2 Stops the generation of a square wave triggered
noTone()
by tone(). Has no effect if no tone is being
generated.
3 Shifts out a byte of data one bit at a time. Starts
shiftOut()
from either the most (i.e. the leftmost) or least
(rightmost) significant bit. Each bit is written in
turn to a data pin, after which a clock pin is
pulsed (taken high, then low) to indicate that
the bit is available.
4 None The dataPin and clockPin must already be
configured as outputs by a call to pinMode().
shiftOut is currently written to output 1 byte (8
bits) so it requires a two step operation to
output values larger than 255.

5 Shifts in a byte of data one bit at a time. Starts


shiftIn()
from either the most (i.e. the leftmost) or least
(rightmost) significant bit. For each bit, the clock
pin is pulled high, the next bit is read from the
data line, and then the clock pin is taken low.
6 Reads a pulse (either HIGH or LOW) on a pin. For
pulseIn()
example, if value is HIGH, pulseIn() waits for the
pin to go HIGH, starts timing, then waits for the
pin to go LOW and stops timing. Returns the
length of the pulse in microseconds. Gives up
and returns 0 if no pulse starts within a specified
time out.

Advanced I/O

Time

Sno Function Discription


1 Returns the number of milliseconds since
millis()
the Arduino board began running the
current program.
2 Returns the number of microseconds since
micros()
the Arduino board began running the
current program. This number will overflow
(go back to zero), after approximately 70
minutes. On 16 MHz Arduino boards (e.g.
Duemilanove and Nano), this function has a
resolution of four microseconds (i.e. the
value returned is always a multiple of four).
On 8 MHzArduino boards (e.g. the LilyPad),
this function has a resolution of eight
microseconds.
3 Pauses the program for the amount of time
delay()
(in miliseconds) specified as parameter.
Govt. Girls Polytechnic Jagdalpur
Department of Electronics and Telecommunication Engg.
(There are 1000 milliseconds in a second.)
4 Pauses the program for the amount of time
delayMicroseconds()
(in microseconds) specified as parameter.
There are a thousand microseconds in a
millisecond, and a million microseconds in a
second.

Math
Sno Function Discription
1 Calculates the minimum of two numbers.
min(x, y)
2 Calculates the maximum of two numbers.
max(x, y)
3 abs(x,y) Computes the absolute value of a number.
4 Constrains a number to be within a range.
constrain(x, a, b)
5 Re-maps a number from one range to another.
map(value,
That is, a value of fromLow would get mapped
fromLow, fromHigh,
to toLow, a value offromHigh to toHigh, values
toLow, toHigh)
in-between to values in-between, etc.
Does not constrain values to within the range,
because out-of-range values are sometimes
intended and useful. The constrain() function
may be used either before or after this
function, if limits to the ranges are desired.
Note that the "lower bounds" of either range
may be larger or smaller than the "upper
bounds" so the map() function may be used to
reverse a range of numbers
6 Calculates the value of a number raised to a
pow(base,
power. Pow() can be used to raise a number to
exponent)
a fractional power. This is useful for generating
exponential mapping of values or curves.
7 Calculates the square root of a number.
sqrt(x)

Trigonometry
Sno Function Discription
1 Calculates the sine of an angle (in radians).
sin(rad)
The result will be between -1 and 1.

2 Calculates the cos of an angle (in radians). The


cos(rad)
result will be between -1 and 1.
3 Calculates the tangent of an angle (in radians).
tan(rad)
The result will be between negative infinity
and infinity.

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
Random Numbers
Sno Function Discription
1 randomSeed() initializes the pseudo-random
randomSeed(seed)
number generator, causing it to start at an
arbitrary point in its random sequence. This
sequence, while very long, and random, is
always the same.
2 The random function generates pseudo-
random()
random numbers.

Bits and Bytes


Sno Function Discription
1 Extracts the low-order (rightmost) byte of a
lowByte()
variable (e.g. a word).
2 Extracts the high-order (leftmost) byte of a
highByte()
word (or the second lowest byte of a larger
data type).
3 Reads a bit of a number.
bitRead()
4 Writes a bit of a numeric variable.
bitWrite()
5 Sets (writes a 1 to) a bit of a numeric variable.
bitSet()
6 Clears (writes a 0 to) a bit of a numeric
bitClear()
variable.
7 Computes the value of the specified bit (bit 0
bit()
is 1, bit 1 is 2, bit 2 is 4, etc.).

External Interrupts
Sno Function Discription
1 Specifies a named Interrupt Service Routine
attachInterrupt()
(ISR) to call when an interrupt occurs.
Replaces any previous function that was
attached to the interrupt.
2 Turns off the given interrupt.
detachInterrupt()

Interrupts
Sno Function Discription
1 Interrupts Re-enables interrupts (after they've been
disabled by noInterrupts()). Interrupts allow
certain important tasks to happen in the
background and are enabled by default. Some
functions will not work while interrupts are
disabled, and incoming communication may
be ignored.
2 Disables interrupts (you can re-enable them
noInterrupts()
with interrupts()). Interrupts allow certain
important tasks to happen in the background
Govt. Girls Polytechnic Jagdalpur
Department of Electronics and Telecommunication Engg.
and are enabled by default. Some functions
will not work while interrupts are disabled,
and incoming communication may be
ignored.

Communication
Sno Function Discription
1 Serial Used for communication between the Arduino
board and a computer or other devices. All
Arduino boards have at least one serial port
(also known as a UART or USART): Serial. It
communicates on digital pins 0 (RX) and 1 (TX)
as well as with the computer via USB.
2 Stream is the base class for character and
Stream
binary based streams. It is not called directly,
but invoked whenever you use a function that
relies on it.
Stream defines the reading functions in
Arduino.

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

Arduino
Project

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

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 on 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

150Ω 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 :-

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
It doesnʼt matter if you use different coloured wires or use different holes on the
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 :-

// Project 1 - LED Flasher

int ledPin = 10;

void setup() {
pinMode(ledPin, OUTPUT);
}

void loop() { digitalWrite(ledPin, HIGH); delay(1000);


digitalWrite(ledPin, LOW); delay(1000);
}

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.

Project 2 - SOS Morse Code


Signale
For this project we are going to leave the exact same circuit set up as in
Project 1, but will use some different code to make the LED display a
message in Morse Code. In this case, we are going to get the LED to signal
the letters S.O. S., which is the international morse code distress signal.
Morse Codeis a type of characterencoding that transmits letters and
numbers using patterns of On and Off. It is therefore nicely suited to our
digital system as we can turn an LED on and off in the necessary pattern to
spell out a word or a series of characters. In this case we will be signaling
S.O.S. which in the Morse Code alphabet is three dits (short flash), followed
by three dahs (long flash), followed by three dits again.
Govt. Girls Polytechnic Jagdalpur
Department of Electronics and Telecommunication Engg.
We can therefore now code our sketch to flash the LED on and off in this
pattern, signaling SOS.

Enter the code

Create a new sketch and then type in the code listed above. Verify your code
is error free and then upload it to your Arduino.
If all goes well you will now see the LED flash the Morse Code SOS signal,
wait 5 seconds, then repeat.
If you were to rig up a battery operated Arduino to a very bright light and
then place the whole assembly into a waterproof and handheld box, this
code could be used to control an SOS emergency strobe light to be used on
boats, whilst mountain climbing, etc.
So, letʼs take a look at this code and work out how it works.

// Project 2 - SOS Morse Code Signaler

// LED connected to digital pin 10


int ledPin = 10;

// run once, when the sketch starts void setup()


{
// sets the digital pin as output pinMode(ledPin,
OUTPUT);
}
// run over and over again
void loop()
{
// 3 dits

for (int x=0; x<3; x++) {


digitalWrite(ledPin, HIGH); // sets the LED on
delay(150); // waits for 150ms
digitalWrite(ledPin, LOW); // sets the LED off
delay(100); // waits for 100ms
}

// 100ms delay to cause slight gap between letters delay(100);


// 3 dahs
for (int x=0; x<3; x++) {

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
digitalWrite(ledPin, HIGH); // sets the LED on
delay(400); // waits for 400ms
digitalWrite(ledPin, LOW); // sets the LED off
delay(100); // waits for 100ms
}

// 100ms delay to cause slight gap between letters delay(100);

// 3 dits again

for (int x=0; x<3; x++) {


digitalWrite(ledPin, HIGH); // sets the LED on
delay(150); // waits for 150ms
digitalWrite(ledPin, LOW); // sets the LED off
delay(100); // waits for 100ms
}
// wait 5 seconds before repeating the SOS signal delay(5000);
}

Project 3 - Traffic Lights


We are now going to create a set of UK traffic lights that will change from green to red,
via amber, and back again, after a set
length of time using the 4-state system. This project could be used on a model railway to
make a set of working traffic lights or for a childʼs toy town.

Enter the code

Enter the following code, check it and upload.If youʼve read up on Projects 1 & 2 then
this code will be self explanatory as will the hardware.

// Project 3 - Traffic Lights


Govt. Girls Polytechnic Jagdalpur
Department of Electronics and Telecommunication Engg.
int ledDelay = 10000; // delay in between changes int redPin = 10;
int yellowPin = 9; int greenPin = 8;

void setup() { pinMode(redPin, OUTPUT); pinMode(yellowPin,


OUTPUT); pinMode(greenPin, OUTPUT);
}
void loop() {
// turn the red light on digitalWrite(redPin, HIGH); delay(ledDelay); //
wait 5 seconds

digitalWrite(yellowPin, HIGH); // turn on yellow delay(2000); // wait 2 seconds

digitalWrite(greenPin, HIGH); // turn green on digitalWrite(redPin, LOW); // turn red


off digitalWrite(yellowPin, LOW); // turn yellow off delay(ledDelay); // wait ledDelay
milliseconds

digitalWrite(yellowPin, HIGH); // turn yellow on digitalWrite(greenPin, LOW); // turn


green off delay(2000); // wait 2 seconds

digitalWrite(yellowPin, LOW); // turn yellow off // now our loop repeats

Project 4 - Interactive Traffic Lights

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

This time we are going to extend the previous project to include a set of
pedestrian lights and a pedestrian push button to request to cross the
road. The Arduino will react when the button is pressed by changing the
state of the lights to make the cars stop and allow the pedestrian to cross
safely.
For the first time we are able to interact with the Arduino and cause it to
do something when we change the state of a button that the Arduino is
watching (i.e. Press it to change the state from open to closed). In this
project we will also learn how to create our own functions.

Project 4 - Interactive Traffic Lights

int carRed = 12; // assign the car lights


int carYellow = 11;
int carGreen = 10;
int pedRed = 9; // assign the pedestrian lights
int pedGreen = 8;
int button = 2; // button pin
int crossTime = 5000; // time allowed to cross
unsigned long changeTime; // time since button
pressed

void setup() {
pinMode(carRed,
OUTPUT);
pinMode(carYellow,
OUTPUT);
pinMode(carGreen,
OUTPUT);
pinMode(pedRed,
OUTPUT);
pinMode(pedGreen,
OUTPUT);
pinMode(button, INPUT); // button on
pin 2 // turn on the green light
digitalWrite(carGreen, HIGH);
digitalWrite(pedRed, HIGH);
}
Govt. Girls Polytechnic Jagdalpur
Department of Electronics and Telecommunication Engg.
void loop() {
int state = digitalRead(button);
/* check if button is pressed and it is
over 5 seconds since last button press
*/

if (state == HIGH && (millis() - changeTime) > 5000) {


// Call the function to change the lights
changeLights();
}
}

void changeLights() {
digitalWrite(carGreen, LOW); // green
off
digitalWrite(carYellow, HIGH); // yellow
on delay(2000); // wait 2 seconds

digitalWrite(carYellow, LOW); // yellow


off digitalWrite(carRed, HIGH); // red on
delay(1000); // wait 1 second till its safe

digitalWrite(pedRed, LOW); // ped red off


digitalWrite(pedGreen, HIGH); // ped green on
delay(crossTime); // wait for preset time
period

// flash the ped green


for (int x=0; x<10; x++) {
digitalWrite(pedGreen,
HIGH); delay(250);
digitalWrite(pedGreen,
LOW); delay(250);
}
// turn ped red on
digitalWrite(pedRed,
HIGH); delay(500);
digitalWrite(carYellow, HIGH); // yellow
on digitalWrite(carRed, LOW); // red off
delay(1000);
digitalWrite(carGreen, HIGH);
digitalWrite(carYellow, LOW); // yellow

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
off

// record the time since last change of lights


changeTime = millis();
// then return to the main program loop
}

Project 4 - LED Chase Effect


We are now going to use a string of LEDʼs (10 in total)
Connect it up to make an LED chase effect, similar to
that used onthe car KITT in the Knightrider TV Series
and on the way introduce the concept of arrays.

Enter the code


// Project 5 - LED Chase Effect
// Create array for LED pins
byte ledPin[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; int ledDelay(65); // delay
between changes
int direction = 1; int currentLED = 0;
unsigned long changeTime;
void setup() {
// set all pins to output for (int x=0; x<10; x++) {
pinMode(ledPin[x], OUTPUT); } changeTime =
millis();
}

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
void loop() {
// if it has been ledDelay ms since last change if ((millis() -
changeTime) > ledDelay) {
changeLED(); changeTime = millis();
}
}
void changeLED() {
// turn off all LED's
for (int x=0; x<10; x++) { digitalWrite(ledPin[x],
LOW);
}
// turn on the current LED digitalWrite(ledPin[currentLED],
HIGH);
// increment by the direction value currentLED +=
direction;
// change direction if we reach the end if (currentLED == 9)
{direction = -1;} if (currentLED == 0) {direction = 1;}
}

Project5 - Interactive LED Chase Effect


We are now going to use a string of LEDʼs (10 in total) to make an LED chase
effect, similar to that used on the car KITT in the Knightrider TV Series and on
the way introduce the concept of arrays.

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

// Create array for LED pins


byte ledPin[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
int ledDelay; // delay between changes int direction = 1;
int currentLED = 0; unsigned long changeTime;
int potPin = 2; // select the input
pin for the potentiometer
void setup() {
// set all pins to output for (int x=0; x<10; x++) {
pinMode(ledPin[x], OUTPUT); } changeTime = millis();
}

void loop() {
// read the value from the pot ledDelay =
analogRead(potPin);
// if it has been ledDelay ms since last change
if ((millis() - changeTime) > ledDelay) {
changeLED(); changeTime = millis();

}
}

void changeLED() {
// turn off all LED's
for (int x=0; x<10; x++) { digitalWrite(ledPin[x], LOW);
}
// turn on the current LED digitalWrite(ledPin[currentLED],
HIGH);
// increment by the direction value currentLED += direction;
// change direction if we reach the
end
if (currentLED == 9) {direction = -1;}
if (currentLED == 0) {direction = 1;}
}

Project 6 - Pulsating Lamp


We are now going to delve further into a more advanced method of
controlling LEDʼs.
So far we have simply turned the LED on or off. How about being able to
adjust itʼs
Govt. Girls Polytechnic Jagdalpur
Department of Electronics and Telecommunication Engg.
brightness too? Can we do that with an Arduino? Yes we can.
Time to go back to basics.

// Project 6 - Pulsating lamp

int ledPin = 11; float sinVal; int ledVal;

void setup() { pinMode(ledPin, OUTPUT);


}

void loop() {
for (int x=0; x<180; x++) {
// convert degrees to radians
// then obtain sin value sinVal = (sin(x*(3.1412/180))); ledVal
= int(sinVal*255); analogWrite(ledPin, ledVal); delay(25);
}
}

Project 7 - Mood Lamp


In the last project we saw that we could adjust the brightness of an LED using
the PWM capabilities of the Atmega chip. We will now take advantage of this
capability by using a red, green and blue LED and by mixing their colours to
create any colour we wish. From that, we will create a mood lamp similar to
the kind you see for sale all over the place nowadays.

// Project 7 - Mood Lamp float RGB1[3];


float RGB2[3]; float INC[3];

int red, green, blue;

int RedPin = 11; int GreenPin = 10; int BluePin =


9;

void setup()
{
Serial.begin(9600); randomSeed(analogRead(0));

RGB1[0] = 0;
Govt. Girls Polytechnic Jagdalpur
Department of Electronics and Telecommunication Engg.
RGB1[1] = 0;
RGB1[2] = 0;

RGB2[0] = random(256); RGB2[1] = random(256);


RGB2[2] = random(256);
}

void loop()
{
randomSeed(analogRead(0));

for (int x=0; x<3; x++) {


INC[x] = (RGB1[x] - RGB2[x]) / 256; }

for (int x=0; x<256; x++) {

red = int(RGB1[0]); green = int(RGB1[1]); blue =


int(RGB1[2]);

analogWrite (RedPin, red); analogWrite (GreenPin, green);


analogWrite (BluePin, blue); delay(100);

RGB1[0] -= INC[0];
RGB1[1] -= INC[1];
RGB1[2] -= INC[2];
}
for (int x=0; x<3; x++) { RGB2[x] = random(556)-300;
RGB2[x] = constrain(RGB2[x], 0, 255); delay(1000);
}
}

Project 8 - LED Fire Effect


Project 9 will use LEDʼs and a flickering random light effect, using PWM again, to recreate
the effect of a flickering flame. If you were to place these LEDʼs inside a model house on a
model railway layout, for example, you could create a special effect of the house being on
fire, or you could place it into a fake fireplace in your house to give a fire effect. This is a
simple example of how LEDʼs can be used to create SFX for movies, stage plays, model

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
dioramaʼs, model railways, etc.

// Project 8 - LED Fire Effect

int ledPin1 = 9; int ledPin2 = 10; int ledPin3 = 11;

void setup()
{
pinMode(ledPin1, OUTPUT); pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
}

void loop()
{
analogWrite(ledPin1, random(120)+135); analogWrite(ledPin2, random(120)+135);
analogWrite(ledPin3, random(120)+135); delay(random(100));
}

Project 9 - Serial Controlled Mood


Lamp
We will now use the same circuit as in Project 9, but will now 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.

// Project 9 - Serial controlled RGB Lamp

char buffer[18];
int red, green, blue;

int RedPin
= 11; int
GreenPin
= 10; int
BluePin =
9;

void setup()
{

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
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
(numC
har>15
){
numCh
ar=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++)
Govt. Girls Polytechnic Jagdalpur
Department of Electronics and Telecommunication Engg.
{

buffer[x]='\0';
}
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);
}
}

Project 10 - Drive a DC Motor


We are now going to step away from LEDʼs for a little Connect it up
while and take a look at a different piece of hardware,the DC Motor. In
your kit you have been supplied with a standard 1.5 to 4.5 volt DC
Motor. In this project you must power the Arduino using the 9v DC
Power Supply and NOT the USB cable. Also make sure your diode is the
right way around with the white stripe going to +5V.

Enter the code

int potPin = 0;

// connected to the base of the transistor

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
int potValue = 0; // value returned from the potentiometer

void setup() {
// set the transistor pin as output:
pinMode(transistorPin, OUTPUT);
}

void loop() {
// read the potentiometer, convert it to 0 - 255:
potValue = analogRead(potPin) / 4;
// use that to control the transistor:
analogWrite(transistorPin, potValue);
}

Project 11- Piezo Sounder Melody


Player
In this project we are going to use a super simplecircuit to produce sounds from our Arduino
using a Piezo Sounder.

// Project 11 - Melody Player int speakerPin = 9;


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);

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.
}
void loop() {
for (int i = 0; i < length; i++) { if (notes[i] == ' ') {
delay(beats[i] * tempo); // rest
} else {
playNote(notes[i], beats[i] * tempo);
}} }

Project 13 - Serial Temperature Sensor


Now we are going to make use of the Temperature Sensor in your kit, the LM35DT. You will need
just one component.
Enter the Code

Enter the code, then press the Serial Monitor button on


the Arduino IDE. You will now get a reading every half a
second(ish) that shows the analog reading from Pin 0 and
also the temperature (after conversion) from the LM35DT sensor.
Leave it a little while to stabilise and then hold the sensor. You will see the temperature rise as it
reads the temperature of your skin. Hold something cold against it and see it drop. The sensor can
read between 0 and 100 degrees C.

int potPin = 0;
float temperature = 0;
void setup()
{
Serial.begin(9600); Serial.println("LM35 Thermometer "); analogReference(INTERNAL);
}

void printTenths(int value) {


// prints a value of 123 as 12.3 Serial.print(value / 10); Serial.print(".");
Serial.println(value % 10);
}

void loop() { int span = 20; int aRead = 0;


for (int i = 0; i < span; i++) { aRead = aRead+analogRead(potPin);
}
aRead = aRead / 20;
temperature = ((100*1.1*aRead)/1024)*10;
// convert voltage to temperature Serial.print("Analog in reading: ");
Serial.print(long(aRead));
Govt. Girls Polytechnic Jagdalpur
Department of Electronics and Telecommunication Engg.
// print temperature value on serial monitor Serial.print(" - Calculated Temp: ");
printTenths(long(temperature));
delay(500);
}

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

Interface HC-05 Bluetooth


The HC-05 Bluetooth to Serial module is a low cost, widely available device for creating serial
data connections. When looking for an HC-05 to use with this exercise, and the HC05 library ,
watch carefully to make sure that the device offered is the HC-05, which is programmable as
master or a slave, and not the HC-06 which can only be one or the other.

The HC-05 is a surface mount module and runs at 3.3v. Many vendors offer the module
mounted on a carrier board with pins and, for some, 5v to 3.3v level translation. The HC05
library can be easily configured to work with hardware or software serial ports and includes a
debug mode.

Resources
 HC-05 Bluetooth to Serial Module
If you buy one mounted on a carrier (recommended), make sure it has a 6 pin connector
that includes the KEY and STATE signals. Keep in mind that the base HC-05 module
is a 3.3v device, so if you are using a 5V Arduino (such as the UNO), then you will
need to get a carrier with on-board regulator and 5v to 3v level shifters, or add those
components yourself.

 Arduino
I used an Arduino UNO v3 while developing this library. The library was designed to
work with other members of the Arduino family, it simply has not been tested with
other family members.

 A solderless breadboard with a selection of jumper wires. The colors I used were
chosen somewhat arbitrarily and don't really matter. Use what you have.

 A terminal program on a computer or smart phone that has a Bluetooth interface. I


used Blue Term on an Android phone for my testing.

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

Setup
The breadboard configuration is simple:

This is the recommended connection and matches the default HC05 library configuration:

 HC05:TX to UNO:0 pin


 HC05:RX to UNO:1 pin
 HC05:GND to UNO:Gnd
 HC05:5V to UNO:5V

Procedure
Install
To install the library on a Linux system, use git to clone the repository. The following
example steps assume that you have already installed and run the Arduino IDE at least once:
$ cd ~/sketchbook/libraries
$ git clone https://github.com/jdunmire/HC05.git

Open and upload


Now start up the Arduino IDE and open the echo example. It is found in the File-
>Sketchbook->libraries->HC05->Examples menu. Upload the sketch.

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

Observe Debug Output


When you have the echo example uploaded, open the Arduino Serial Monitor (Tools->Serial
Monitor). Set the serial speed to 57600 baud. You should see messages like these displayed:

findBaud
Trying 9600... x
Trying 19200... x
Trying 57600... x
Trying 115200... x
Trying 38400... Found.
No Connection. waiting...

The findBaud function tries different serial speeds until it gets a response from the HC05. It
prints an 'x' if HC05 does not respond and 'Found' when it does. It stops testing after it detects a
response.

The No Connection. waiting... message comes from the btSerial.println() function


called at line 27 of echo.ino.

At this point the echo example is waiting for a BT connection to be established.

BT Connection
Now use your BT terminal to connect to the HC05. There are so many different ways to do this
that I have to leave it to you to figure out.

Once the connection has been established you should see this message on the terminal:
Echo Server- type something

If you don't see it, try pressing the reset button on the Arduino UNO.

Back on the Arduino Serial Monitor you will find that 'OK' has been printed at the end of the
'No Connection' line. This indicates that a connection has been established and that
the echo sketch is ready to echo back any characters it receives over the BT interface.
No Connection. waiting... OK

At this point anything you type at the BT terminal should be echoed back a character at a time.

BT Disconnect
When you turn off or disconnect the BT connection from the BT terminal, the Arduino Serial

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

Monitor will show that the echo sketch has gone back to waiting for a connection:
No Connection. waiting... OK
No Connection. waiting...

Wrap-up
The echo sketch doesn't do much, but it is always a good starting point for confirming that the
library configuration matches your wiring.

You can't get debugging messages on the Arduino Serial Monitor with this configuration, and
the HC05 must be disconnected while you upload the sketch.

 Use the nameChange example sketch included with the library to change the name the
HC05 broadcasts. If you are going to use multiple HC05s in your project, this makes it
much easier to identify them.

The code below :

// This program shown how to control arduino from Andriod Via Bluetooth
// Connect ...
// arduino>>bluetooth
// D0 >>> Rx
// D1 >>> Tx

const int LED = 13;

byte serialA;

void setup()

Govt. Girls Polytechnic Jagdalpur


Department of Electronics and Telecommunication Engg.

// initialize the serial communication:

Serial.begin(9600); //baud rate - it matches that of the module you got:

// initialize the ledPin as an output:

pinMode(LED, OUTPUT);

void loop() {

if (Serial.available() > 0)

{serialA = Serial.read();

Serial.println(serialA);

switch (serialA) {

case 1:

digitalWrite(LED, HIGH);// if number 1 pressed LED ON

break;

case 2:

digitalWrite(motor1, LOW); //if number 1 pressed LED OFF

default:

break;

} }

Govt. Girls Polytechnic Jagdalpur

You might also like