Arduino Document
Arduino Document
Contents
Introduction 1 Project 12 - Piezo Sounder Melody Player 37
The Projects 19
Hardware Overview 21
Code Overview 22
Code Overview 24
Code Overview 25
Code Overview 26
Hardware Overview 26
Code Overview 27
Code Overview 29
Code Overview 31
Code Overview 33
Code Overview 35
Hardware Overview 36
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.
Freeduino or
Piezo Sounder
Roboduino Board 9v DC Power Supply Breadboard USB Cable
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
10
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
11
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.
Make sure that “Search for the best driver in these You are now ready to upload your first Sketch.
locations” is checked.
12
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
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
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
Verify/ Serial
Stop New Open Save Upload
Compile Monitor
The Toolbar buttons are listed above. The functions of each button are as follows :-
Serial Monitor Displays serial data 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
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
17
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.
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
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.
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
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.)
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.
Functions
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:
Advanced I/O
Sno Function Discription
1 Tone() Generates a square wave of the specified
Advanced I/O
Time
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.
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.
Arduino
Project
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 :-
Now, open up the Arduino IDE and type in the following code :-
void setup() {
pinMode(ledPin, OUTPUT);
}
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.
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.
// 3 dits again
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.
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.
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
*/
void changeLights() {
digitalWrite(carGreen, LOW); // green
off
digitalWrite(carYellow, HIGH); // yellow
on delay(2000); // wait 2 seconds
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;}
}
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);
}
}
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;
void loop()
{
randomSeed(analogRead(0));
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);
}
}
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));
}
char buffer[18];
int red, green, blue;
int RedPin
= 11; int
GreenPin
= 10; int
BluePin =
9;
void setup()
{
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);
}
}
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);
}
}
int potPin = 0;
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);
}
int potPin = 0;
float temperature = 0;
void setup()
{
Serial.begin(9600); Serial.println("LM35 Thermometer "); analogReference(INTERNAL);
}
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.
Setup
The breadboard configuration is simple:
This is the recommended connection and matches the default HC05 library configuration:
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
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.
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
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.
// This program shown how to control arduino from Andriod Via Bluetooth
// Connect ...
// arduino>>bluetooth
// D0 >>> Rx
// D1 >>> Tx
byte serialA;
void setup()
pinMode(LED, OUTPUT);
void loop() {
if (Serial.available() > 0)
{serialA = Serial.read();
Serial.println(serialA);
switch (serialA) {
case 1:
break;
case 2:
default:
break;
} }