03 Arduino Manual v2
03 Arduino Manual v2
03 Arduino Manual v2
2016
TABLE OF CONTENTS
1
Arduino - Digital Out …………..……………………………………………… 16
Experiment No: 1 ………………………………. …….………… 17
Arduino - Digital In / Out ……………………...…..………………………….. 21
Experiment No: 2 ………………………………. …….………… 23
Interfacing Arduino to High Power DC Loads ……………...…………….. 25
Experiment No: 3 ………………………………. …….………… 28
Interfacing Arduino to AC Loads ……………………………..…………….. 31
Experiment No: 4 ………………………………. …….….……...33
Arduino – Analog Read and PWM ………………………………….………. 36
Experiment No: 5 ………………………………. …….………....39
Interfacing Arduino to DC Motor Using L293D …………………………… 41
Experiment No: 6 ………………………………. …….….……...46
Interfacing Arduino to Servo Motor ………….…………………………….. 50
Experiment No: 7 ………………………………. …….……...….55
Interfacing Arduino to Stepper Motor ……….…………………………….. 57
Experiment No: 8 ………………………………. …….……...….63
Interrupt Subroutine ………………………………..……………………….. 66
Experiment No: 9 ………………………………. …….….…..….67
Arduino - GSM Shield Interface …………………………………………….. 70
Experiment No: 10 ……………………………. …….….…..…. 81
LCD Interfacing………………………………..……………………………….. 83
Experiment No: 11 ………………………………. …….….…….87
TONE() FUNCTION ……………………………………………………...…….. 90
Experiment No: 12 ………………………………. …….….…….97
2
INTRODUCTION TO ARDUINO
This experiment manual is focus on what Arduino are, what they can do and the
basic on how to set one up to do simple things like making an LED Dimming circuit,
control the speed of motor.
What is an Arduino? I’m sure you have heard this things million times by now,
and if you are confuse you have you have every right to be, because the word Arduino
refers to so many different things which will be explained in this manual.
Figure 2: Microcontroller
Microcontrollers are integrated circuits that are basically tiny computers; they can
run small simple software programs. They are low power enough that they can be
powered by battery for days but they are fast enough to process data much faster than
any human being can think.
3
Figure 3: Arduino Company
Arduino is a company in Italy that design and sells circuit boards that make
microcontrollers easy to use. They call this circuit boards Arduinos, and they are a lot of
different types of Arduinos. For example you have simple Arduino board like the Arduino
Uno which is cheap and good enough for most projects. You can use Arduino Uno to
control motors, lighting, cameras, or even build a simple robot.
4
And then you have fancier Arduino with more powerful processors, which have
Wi-Fi, Ethernet and more.
The company Arduino open sources all of their hardware designs, which means
you just don’t have to buy from them. There are countless third party companies that
make their own variance of Arduino hardware designs. They cant call them Arduino but
functionally they are the same thing.
5
Figure 7: Arduino Shields Ada fruit
They are also this things called Arduino Shields, which are basically circuit
boards that plug-in into your main Arduino circuit board and let you do more stuff. For
example Adafruit makes shields that let you control motor and servos without having to
design motor control circuitry.
6
And sparkfun have shields that let you turn your Arduino into a simple cellphone
or an MP3 player.
That is a quick overview of the Arduino the company and Arduino hardware. But
there is more there is also the Arduino software development environment
And this is what makes Arduino good for beginners. Historically if you wanted to
program microcontroller you’d have to type out lot of binary and memorize a lot of hard
to remember registers and instructions
7
Figure 11: Microcontroller programmer
Then you have to use special programming hardware and custom made cables
to upload you program to your microcontroller.
Arduino the company got rid of all of that, they created software that works on
windows, MAC and Linux which makes uploading your code as simple as connecting
your USB cable and clicking a button.
They created a programming language that’s let you configure all of the Arduino
Hardware products in the same way and although it is not as simple as learning Phyton
the Arduino software is one of the easiest programming experiences you’ll ever have.
8
Figure 13: Arduino kits
So hopefully that clarifies what Arduino means in different context. Now when
people say they use an Arduino for their project, they probably talking about the Arduino
Uno. It is highly unlikely that you will outgrow sometime soon. It is the perfect Arduino
hardware for beginners you can buy it in electronic store cheaply and if you have the
money I recommend buying the one of the many Arduino kits out there where you can
get a lot of different pieces of hardware to play with.
9
ARDUINO UNO HARDWARE
You are often hear Arduinos being called microcontrollers and that’s technically
incorrect. Arduino are circuit boards that have microcontroller chips on them but they
also have a lot of other stuff on their too. Lets take a quick tour.
Now in order to upload the software that you create to the microcontroller there is
actually another microcontroller the USB to serial chip. This chip is what lets you connect
your USB cable to your Arduino board and communicate via USB, It lest you upload your
programs onto the main microcontroller. And once you have your program running this
chip is what allows you to send messages back in forth between your computer and your
Arduino and this is extremely important for debugging.
One great thing about Arduinos is that you can power them purely from you USB
cable. But if you don’t want your project always attached to a computer you can just use
an external 9V DC power source with a barrel jack that you can connect to the DC power
jack of the Arduino. The Arduino has a built in voltage regulator that will reduce the
voltage to 5V and another voltage regulator that reduce voltage to 3.3V.
And if ever you want to reboot your Arduino program you got a reset button
10
Figure 15: Arduino UNO Hardware parts
Let’s now go to the pin connectors below is the power pins, the Vin, GND, GND,
5V, 3.3V and the reset pin. If you want you can connect wires at the power pin to other
circuitries with 5V or 3.3V such as the different shields, sensors and modules.
RX and TX or Digital Pin 0 and 1 are for sending and receiving data you can use
this pin to receive and send data to a GPS module, Bluetooth module, Wi-Fi modules
and more.
Digital pins 2 to 13 are for digital inputs and outputs and pins 3, 5, 6, 9, 10, and
11 are dual function pin that can be configured for Pulse Width Modulated (PWM) signal.
Arduino Uno has six Analog input pin, Analog in pin 0 to 5, and this are used to
measure continuous voltages anywhere from 0V to 5V.
11
ARDUINO UNO SOFTWARE
Most of the work you do with your Arduino will actually be in the software, so start
out by downloading the Arduino software from https://www.arduino.cc. During the
installation you can expect a lot of prompts or menus to shows up, where you are ask if
you want to install various divers, just say yes to everything.
Once you are done connect your Arduino to your computer using the USB cable,
next start up the Arduino development environment. The first thing that you want to do is
to make sure that the software tries to connect to the right type of Arduino. Go to tools
Boards and we are going to using an Arduino Uno.
12
Figure 18: Arduino IDE
Next we have to make sure that the Arduino environment can actually connect
and communicate with your Arduino, go to tools, ports and select the com or serial port
where your Arduno is connected. If there is no Arduino listed here you may have a
problem with your drivers or you can try plugging your Arduino with different USB port.
GETTING STARTED
1. Download & install the Arduino environment (IDE)
2. Connect the board to your computer via the USB cable
3. If needed, install the drivers
4. Launch the Arduino IDE
5. Select your board
6. Select your serial port
7. Open the blink example
8. Upload the program
13
ARDUINO IDE
14
Using Arduino UNO
15
ARDUINO - DIGITAL OUT
digitalRead(pin)
Reads HIGH or LOW from a pin
delay(ms);
Electronic stuff
Output pins can provide 25 mA of current
Writing HIGH to an input pin installs a 20KΩ pullup
EXAMPLE 1-1:
Create a program that will produce logic high on pin 13 and logic low to all of the
remaining digital output pins of Arduino UNO board.
Solution:
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
}
EXAMPLE 1-2:
Create a program that will turn “ON” and turn “OFF” the LED connected at pin 13
of Arduino UNO board every sec.
Solution:
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
16
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________
I - OBJECTIVES
a. To know the different codes for digital pin of Arduino UNO board
b. To create a program that will turn ON or turn OFF a load that is connected to
the pin of the Arduino UNO board.
c. Apply knowledge gained to control other pins of the Arduino UNO board.
III - PROBLEM
Instruction:
DIGITAL OUT
1. Create a program that will produce logic high on digital pin 0 and logic low from
digital pin 1 to pin 13 of Arduino UNO board. See Figure 1.7for details.
17
Figure 1.1: Schematic of Problem 1
Solution:
2. Create a program that will set pin 0, 2, 4 and 6 and clear all the remaining digital pin
of Arduino UNO. See Figure 1.7 for details
Solution:
18
3. Create a program that will alternately turn “ON” and turn “OFF” the LED
connected at digital pin 0 and pin 1 of Arduino UNO board every sec.
Solution:
4. Create a program that will alternately turn “ON” and turn “OFF” all the odd and
even digital pins of Arduino UNO every sec.
Solution:
19
5. Create a program of a single bit running light that repeatedly moves from digital
pin 0 to pin 13 of Arduino UNO board. The interval for each bit movement is 1
sec.
Solution:
IV - QUESTIONS/ APPLICATIONS:
V - CONCLUSION:
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
20
ARDUINO - DIGITAL OUT
digitalRead(pin)
Reads HIGH or LOW from a pin
digitalWrite(pin, value)
Writes HIGH or LOW to a pin
Electronic stuff
Output pins can provide 25 mA of current
Writing HIGH to an input pin installs a 20KΩ pullup
EXAMPLE 1-1:
Create a program that will produce logic high on pin 13 and logic low to all of the
remaining digital output pins of Arduino UNO board.
Solution:
void setup() {
for (int thisPin = 0; thisPin < 14; thisPin++)
{
pinMode(ledPins[thisPin], OUTPUT);
}
}
21
22
ARDUINO - DIGITAL IN / OUT
digitalRead(pin)
Reads HIGH or LOW from a pin
digitalWrite(pin, value)
Writes HIGH or LOW to a pin
Electronic stuff
Output pins can provide 40 mA of current
Writing HIGH to an input pin installs a 20KΩ pullup
EXAMPLE 2-1:
Create a program that will check the logic status of signal fed to the digital pin 2
of Arduino UNO board, and will turn “ON” the LED connected at pin 13 if the logic status
of pin 2 is 1 and turn “OFF” the LED connected at pin 13 if the logic status of pin 2 is 0.
23
Solution:
int buttonstate = 0;
void setup() {
pinMode(13, OUTPUT);
pinMode(2, INPUT);
}
void loop() {
buttonstate = digitalRead(2);
if (buttonstate == HIGH)
{
digitalWrite(13, HIGH);
}
else
{
digitalWrite(13, LOW);
}
}
24
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________
I - OBJECTIVES
III- PROBLEM
Instruction:
1. Create a program that will check the logic status of signal fed to the digital pin 0
of Arduino UNO board, and will turn “ON” the LED connected at pin 13 if the logic
status of pin 0 is 1 and turn “OFF” the LED connected at pin 13 if the logic status
of pin 0 is 0.
25
Solution:
2. Create a program that will set pin 10 and 13 if pin 0 is logic 1, set pin 11 and 12 if
pin 1 is logic 1, set pin 10 and 12 if pin 2 is logic 1, set pin 11 and 13 if pin 3 is
logic 1, otherwise it will clear pin 10, 11, 12, and 13 if pin 0, 1, 2, and 3 are logic
0.
Solution:
IV - QUESTIONS/ APPLICATIONS:
1. What electronic components are needed to input logic high on digital input pin of
Arduino UNO?
2. How many digital input pin has Arduino UNO have?
V - CONCLUSION:
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
26
INTERFACING ARDUINO TO HIGH POWER DC LOADS
INTRODUCTION
I - Introductory Information:
Transistor switches are critical circuit-building blocks; they’re used to make logic
gates, which go on to create microcontrollers, microprocessors, and other integrated
circuits. Below are a few example circuits.
Transistor Switch
Let’s look at the most fundamental transistor-switch circuit: an NPN switch. Here
we use an NPN to control a high-power LED:
Our control input flows into the base, the output is tied to the collector, and the
emitter is kept at a fixed voltage.
27
When the voltage at the base is greater than 0.6V (or whatever your transistor’s
Vth might be), the transistor starts saturating and looks like a short circuit between
collector and emitter. When the voltage at the base is less than 0.6V the transistor is in
cutoff mode – no current flows because it looks like an open circuit between C and E.
The circuit below is called a low-side switch, because the switch – our transistor
– is on the low (ground) side of the circuit. Alternatively, we can use a PNP transistor to
create a high-side switch:
Similar to the NPN circuit, the base is our input, and the emitter is tied to a
constant voltage. This time however, the emitter is tied high, and the load is connected
to the transistor on the ground side.
This circuit works just as well as the NPN-based switch, but there’s one huge
difference: to turn the load “on” the base must be low. This can cause complications;
especially if the load’s high voltage (VCC in this picture) is higher than our control input’s
high voltage. For example, this circuit wouldn’t work if you were trying to use a 5V-
operating Microcontroller to switch on a 12V motor. In that case it’d be impossible to turn
the switch off because VB would always be less than VE.
You’ll notice that each of those circuits uses a series resistor between the control
input and the base of the transistor. Don’t forget to add this resistor! A transistor without
a resistor on the base is like an LED with no current-limiting resistor.
28
The series resistor between our control source and the base limits current into
the base. The base-emitter node can get its happy voltage drop of 0.6V, and the resistor
can drop the remaining voltage. The value of the resistor, and voltage across it, will set
the current.
EXAMPLE 3-1:
Create a program that will turn “ON” a 12V DC lamp for 2sec and turn it “OFF” for
1sec using pin 13 of Arduino UNO board. (Note: to interface a 12Vdc load to an Arduino
UNO board you must use a transistor.)
Solution:
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
delay(2000);
digitalWrite(13, LOW);
delay(1000);
}
29
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________
I - OBJECTIVES
III- PROBLEM
Instruction:
1. Create a program that will turn “ON” a 12V DC lamp for 1min and turn it “OFF” for
30sec using pin 0 of Arduino UNO board. (Note: to interface a 12Vdc load to an
Arduino UNO board you must use a transistor.)
Solution:
30
2. Create a program that will check the logic status of signal fed to the pin 0 of
Arduino UNO board, and will turn “ON” the 12Vdc load connected at pin 13 if the
logic status of pin 0 is 1 and turn “OFF” the 12Vdc load connected at pin 13 if the
logic status of pin 0 is 0. (Note: to interface a 12Vdc load to an Arduino UNO
board you must use a transistor.)
Solution:
31
3. Create a program for Arduino UNO board that will turn “ON” the 12Vdc load
connected at pin 13 if both pin 0 and pin 1 is logic 1. (Note: to interface a 12Vdc
load to an Arduino UNO board you must use a transistor.)
Solution:
IV - QUESTIONS/ APPLICATIONS:
1. What are the regions of operation of a transistor that is used for electronic
switching?
2. Differentiate Transistor saturation region and cut-off region?
3. What is the control terminal of a Bipolar Junction Transistor in transistor
switching?
V - CONCLUSION:
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
32
INTERFACING MICROCONTROLLER TO AC LOADS
INTRODUCTION
I - Introductory Information:
33
If the coil voltage needed by the relay is 5V dc it can be interfaced directly to the
terminals of the microcontroller. But if the coil voltage is greater than 5V dc we need to
connect a transistor switch to drive the Relay coil.
EXAMPLE 4-1:
Create a program that will turn “ON” a 220Vac load for 1min and turn it “OFF” for
30sec using pin 13 of Arduino UNO board. (Note: to interface a 220Vac load to an
Arduino UNO board you must use a transistor and a relay.)
Solution:
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
delay(60000);
digitalWrite(13, LOW);
delay(30000);
}
34
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________
I - OBJECTIVES
III- PROBLEM
Instruction:
1. Create a program that will turn “ON” a 220Vac load for 2sec and turn it “OFF” for
1sec using pin 0 of Arduino UNO board. (Note: to interface a 220Vac load to an
Arduino UNO board you must use a transistor and a relay.)
35
Solution:
2. Create a program that will check the logic status of signal fed to the pin 0 of
Arduino UNO board, and will turn “ON” the 220Vac load connected at pin 13 if
the logic status of pin 0 is 1 and turn “OFF” the 220Vac load connected at pin 13
if the logic status of pin 0 is 0. (Note: to interface a 220Vac load to an Arduino
UNO board you must use a transistor and a relay.)
Solution:
36
3. Create a program for Arduino UNO board that will turn “ON” the 220Vac load
connected at pin 13 if both pin 0 and pin 1 is logic 1. (Note: to interface a 220Vac
load to an Arduino UNO board you must use a transistor and a relay.)
Solution:
IV - QUESTIONS/ APPLICATIONS:
V - CONCLUSION:
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
37
ARDUINO – ANALOG READ AND PWM
On the previous experiments we talk about digital input and outputs, 0V and 5V.
But a lot all the times we need more than just 0V and 5V, for example we need to know
how bright is a light, or what is the level of intensity of sound? This type of question is
often answered by analog signals. The Arduino has dedicated pins to analyze this type
of signals the Analog pin 0 to pin 5.
Create a program that will read an analog signal input on Analog pin 0, and prints
the result to the serial monitor.
Note:
Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and
ground.
38
Solution:
Create a program that uses the analog output pin 9 (Pulse Width Modulation
(PWM)) to fade an LED.
Note:
39
Figure 5.3: Schematic of Example 5-2
Solution:
void setup() {
// nothing happens in setup
}
void loop() {
// fade in from min to max in increments of 5 points:
for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
40
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________
I - OBJECTIVES
III- PROBLEM
Instruction:
1. Create a program that will read an analog signal input on Analog pin 0, and uses
the digital output pin 9 (Pulse Width Modulation (PWM)) to fade an LED
Solution:
41
2. Create a program that will read an analog signal input on Analog pin 0, and will
turn on a 12V lamp at digital pin 2 if analog read is >=100, and will turn on a
220V buzzer at digital pin 4 if analog read is >=300, and will turn OFF the 12V
Lamp and 220V Buzzer if analog read <=99.
Solution:
IV - QUESTIONS/ APPLICATIONS:
V - CONCLUSION:
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
42
INTERFACING ARDUINO TO DC MOTOR USING L293D
INTRODUCTION
I - Introductory Information:
43
Figure 6.2: Basic H-Bridge DC Motor Driving
L293D and L293 are two such ICs. These are dual H-bridge motor drivers, ie by
using one IC we can control two DC Motors in both clock wise and counter clockwise
directions. The L293D can provide bidirectional drive currents of up to 600-mA at
voltages from 4.5 V to 36 V while L293 can provide up to 1A at same voltages. Both ICs
are designed to drive inductive loads such as dc motors, bipolar stepping motors, relays
and solenoids as well as other high-current or high-voltage loads in positive-supply
applications. All inputs of these ICs are TTL compatible and output clamp diodes for
inductive transient suppression are also provided internally. These diodes protect our
circuit from the Back EMF of DC Motor.
44
In both ICs, drivers are enabled in pairs, with drivers 1 and 2 are enabled by a
high input to 1,2EN and drivers 3 and 4 are enabled by a high input to 3,4EN. When
drivers are enabled, their outputs will be active and in phase with their inputs. When
drivers are disabled, their outputs will be off and will be in the high-impedance state.
EXAMPLE 6-1:
Create a program that will repeatedly rotate a DC motor clockwise for 2 sec, stop
for 2 sec, counterclockwise for 2 sec and stop for 2 sec. (use Digital pin 10 and pin 11 as
the positive (+) and negative (-) terminal of the DC motor.
Note: DC motor cannot be connected directly to Arduino UNO board, use L293D to
interface DC motor to Arduino UNO board
45
Solution:
void setup() {
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
}
void loop() {
digitalWrite(10, HIGH);
digitalWrite(11, LOW);
delay(2000);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
delay(2000);
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
delay(2000);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
delay(2000);
46
Figure 6.4: EXAMPLE CIRCUIT
We can drive two DC Motors with one L293D, in this example we are using only
the first pair of drivers to drive one DC Motor. First pair of drivers are enabled by
connecting EN1 to Logic HIGH. IN1 and IN2 are connected to RB0 and RB1 of PIC
Microcontroller respectively which are used to provide control signal to the DC Motor.
DC Motor is connected to OUT1 and OUT2 of the L293D.
47
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________
I - OBJECTIVES
III - PROBLEM
Instruction:
1. Create a program that will repeatedly produce, FORWARD 3sec, STOP 1sec,
REVERSE 3sec, STOP 1sec, TURN RIGHT 3sec, STOP 1sec and TURN LEFT
3sec, STOP 1sec, movement for 2 DC motor with transistor and relay driver
interfaced with Digital Pint 10, 11, 12 and 13 of Arduino UNO board.
48
Figure 6.5: Schematic Diagram of 2 DC motor with Transistor and Relay Driver
Solution:
2. Create a program that will repeatedly produce, FORWARD 3sec, STOP 1sec,
REVERSE 3sec, STOP 1sec, TURN RIGHT 3sec, STOP 1sec and TURN LEFT
3sec, STOP 1sec, movement for 2 DC motor with L293D driver interfaced with
Digital pin 10, 11, 12 and 13 of Arduino UNO board.
49
Figure 6.6: Schematic Diagram of 2 DC motor with L293D driver
Solution:
3. Create a program that if digital pin 0 is logic 1, will call subroutine for FORWARD
movement, and if pin 0 is logic 0, will call subroutine for STOP. Use 2 DC motor
with L293D driver interfaced with digital pin 10, 11, 12 and 13 of Arduino UNO
board.
50
Solution:
IV - QUESTIONS/ APPLICATIONS:
V - CONCLUSION:
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
51
INTERFACING ARDUINO TO SERVO MOTOR
INTRODUCTION
Servo Motor uses error sensing negative feedback to control the precise angular
position. Servos are used for precise positioning in robotic arms, legs, RC Aero-planes,
Helicopters etc. Please read the article Servo Motor for more information about its
working and construction. Hobby Servo Motors have three wires, two of them (RED and
BLACK) are used to given power and the third one is used to give control signals. Servo
can be easily be controlled using microcontrollers using Pulse Width Modulated (PWM)
signals on the control wire. Here we are using a servo whose angular rotation is limited
to 0 – 180°. We can control the exact angular position by using a pulse, whose width
varying from 1 millisecond to 2 millisecond on the control wire. The actual behavior of a
particular motor depends upon its manufacture; please refer the datasheet of the
particular motor for that.
52
Figure 7.2: Servo Angular Rotation Pulse Width Modulation
EXAMPLE 7-1:
Create a program that will sweep the shaft of a RC servo motor connected at
PWM Digital pin 9 back and forth across 180 degrees. (use the Arduino servo library.)
Note:
Servo motors have three wires: power, ground, and signal. The power wire is
typically red, and should be connected to the 5V pin on the Arduino or Genuino board.
The ground wire is typically black or brown and should be connected to a ground pin on
the board. The signal pin is typically yellow, orange or white and should be connected to
pin 9 on the board.
53
Solution:
#include <Servo.h>
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
54
EXAMPLE 7-2:
Create a program that will Control the position of a RC servo motor connected at
PWM Digital pin 9 with your Arduino and a potentiometer at Analog pin 0. (use the
Arduino servo library.)
Note:
Servo motors have three wires: power, ground, and signal. The power wire is
typically red, and should be connected to the 5V pin on the Arduino or Genuino board.
The ground wire is typically black or brown and should be connected to a ground pin on
the board. The signal pin is typically yellow or orange and should be connected to pin 9
on the board.
The potentiometer should be wired so that its two outer pins are connected to
power (+5V) and ground, and its middle pin is connected to analog input 0 on the board.
55
Figure 7.6: Wiring Diagram for Example 7-2
Solution:
#include <Servo.h>
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
val = analogRead(potpin); // reads the value of the potentiometer (value
between 0 and 1023)
val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0
and 180)
myservo.write(val); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
}
56
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________
I - OBJECTIVES
III - PROBLEM
Instruction:
1. Create a program that will sweep the shaft of a RC servo motor connected at
PWM Digital pin 9 back and forth across 180 degrees. And also sweep the shaft
of a RC servo motor connected at PWM Digital pin 10 back and forth across 180
degrees. (use the Arduino servo library.).
57
Solution:
2. Create a program that will control the position of a RC servo motor connected at
PWM Digital pin 9 with your Arduino and a potentiometer at Analog pin 0. And
also another potentiometer connected at Analog pin 1 that will control the
position of a RC servo motor connected at PWM Digital pin 10. (Use the Arduino
servo library.).
Solution:
IV - QUESTIONS/ APPLICATIONS:
1. Give at least one example of application of servo motor in our technology today?
2. Why does servo motor is used for that application aside from DC motor?
3. What are the advantages of servo motor to DC motor?
4. What are the disadvantages of servo motor to DC motor?
V - CONCLUSION:
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
58
INTERFACING ARDUINO TO STEPPER MOTOR
INTRODUCTION
59
Stepper Motor can be easily interfaced with PIC Microcontroller by using
readymade ICs such as L293D or ULN2003. There are three different types of stepping
modes for unipolar stepper motor.
Wave Drive
In this mode only one stator electromagnet is energized at a time. It has the
same number of steps as the full step drive but the torque is significantly less. It is rarely
used. It can be used where power consumption is more important than torque.
Step A B C D
1 1 0 0 0
2 0 1 0 0
3 0 0 1 0
4 0 0 0 1
Full Drive
In this mode two stator electromagnets are energized at a time. It is the usual
method used for driving and the motor will run at its full torque in this mode of driving.
60
Table 8.2: Unipolar Stepper MotorFull Drive Stepping Sequence
Step A B C D
1 1 1 0 0
2 0 1 1 0
3 0 0 1 1
4 1 0 0 1
Half Drive
In this stepping mode, alternatively one and two phases are energized. This
mode is commonly used to increase the angular resolution of the motor but the torque is
less approximately 75% at its half step position (when only a single phase is on). We can
see that the angular resolution doubles in Half Drive Mode.
Step A B C D
1 1 0 0 0
2 1 1 0 0
3 0 1 0 0
4 0 1 1 0
5 0 0 1 0
6 0 0 1 1
7 0 0 0 1
61
8 1 0 0 1
Bipolar motors are simpler in construction as it contains two coils and no center
tap. Being simple, driving is little complex compared to unipolar motors. To reverse the
magnetic polarity of stator windings, current through it must be reversed. For this we
should use H-Bridge. We can distinguish bipolar motors from unipolar motors by
measuring the coil resistance. In bipolar motors we can find two wires with equal
resistance.
Step A B C D
1 1 0 0 0
2 0 0 1 0
3 0 1 0 0
4 0 0 0 1
62
EXAMPLE 8-1:
Create a program drives a unipolar or bipolar stepper motor. Use digital pins 8 -
11 of the Arduino to interface the A, B, C, and D terminals of the stepper motor.
Note:
The motor will step one step at a time, very slowly. You can use this to test that
you've got the four wires of your stepper wired to the correct pins. If wired correctly, all
steps should be in the same direction.
Use this also to count the number of steps per revolution of your motor, if you
don't know it. Then plug that number into the one Revolution example to see if you got it
right.
Solution:
#include <Stepper.h>
const int stepsPerRevolution = 200; // change this to fit the number of steps per
revolution
// for your motor
void setup() {
// initialize the serial port:
Serial.begin(9600);
}
void loop() {
// step one step:
myStepper.step(1);
Serial.print("steps:");
Serial.println(stepCount);
stepCount++;
delay(500);
}
63
EXAMPLE 8-2:
Create a program that drives a unipolar or bipolar stepper motor. Use digital pins
8 - 11 of the Arduino to interface the A, B, C, and D terminals of the stepper motor.
Connect the potentiometer to analog input pin 0.
Note:
The motor will rotate in a clockwise direction. The higher the potentiometer value,
the faster the motor speed. Because setSpeed() sets the delay between steps, you may
notice the motor is less responsive to changes in the sensor value at low speeds.
Solution:
#include <Stepper.h>
const int stepsPerRevolution = 200; // change this to fit the number of steps per
revolution
// for your motor
void setup() {
// nothing to do inside the setup
}
void loop() {
// read the sensor value:
int sensorReading = analogRead(A0);
// map it to a range from 0 to 100:
int motorSpeed = map(sensorReading, 0, 1023, 0, 100);
// set the motor speed:
if (motorSpeed > 0) {
myStepper.setSpeed(motorSpeed);
// step 1/100 of a revolution:
myStepper.step(stepsPerRevolution / 100);
}
}
64
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________
I - OBJECTIVES
III - PROBLEM
1. Create a program for a unipolar stepper motor that when N.O. push button
connected at digital pin 0 is pressed, the stepper motor will rotate clock wise. But
when N.O. push button connected at digital pin 1 is pressed, the stepper motor
65
will rotate counter-clock wise and if no push button is pressed the stepper motor
will stop. Use digital pin 8, 9, 10 and 11 of Arduino UNO board to interface the A,
B, C, and D terminal of the stepper motor. And the delay per step of the stepper
motor is 100mS.
Solution:
2. Create a program for a bipolar stepper motor that when N.O. push button
connected at digital pin 0 is pressed, the stepper motor will rotate clock wise. But
when N.O. push button connected at digital pin 1 is pressed, the stepper motor
will rotate counter-clock wise and if no push button is pressed the stepper motor
will stop. Use digital pin 8, 9, 10 and 11 of Arduino UNO board to interface the A,
B, C, and D terminal of the stepper motor. And the delay per step of the stepper
motor is 100mS.
Solution:
66
IV - QUESTIONS/ APPLICATIONS:
V - CONCLUSION:
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
67
INTERRUPT SUBROUTINE
INTRODUCTION
If you wanted to insure that a program always caught the pulses from a rotary
encoder, so that it never misses a pulse, it would make it very tricky to write a program
to do anything else, because the program would need to constantly poll the sensor lines
for the encoder, in order to catch pulses when they occurred. Other sensors have a
similar interface dynamic too, such as trying to read a sound sensor that is trying to
catch a click, or an infrared slot sensor (photo-interrupter) trying to catch a coin drop. In
all of these situations, using an interrupt can free the microcontroller to get some other
work done while not missing the input.
EXAMPLE 9-1:
Create a program that will CHANGE the state of the LED connected at digital pin
13 if external interrupt logic high is read at digital interrupt pin.
Solution:
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}
void loop() {
digitalWrite(ledPin, state);
}
void blink() {
state = !state;
}
68
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________
I - OBJECTIVES
III - PROBLEM
1. Create a program for Arduino UNO that will display an alternating LED that is
connected at digital pin 12 and pin 13 with a delay of 500ms and having an
interrupt that will set both pin 12 and pin 13, for 1sec. if interrupt pin 2 detects an
edge triggered logic 1.
Solution:
69
2. Create a program for a mobile robot that continuously move forward use digital pin
10, 11, 12, and 13 of Arduino UNO for the connection to DC motor and digital pin 2
for the interrupt connected in distance sensor. If the distance sensor detects an
object in front of the mobile robot while it is moving forward the interrupt will execute
a turn right movement for 1 sec.
Solution:
70
3. Create a program using Arduino UNO for a line tracker obstacle avoider mobile
robot set digital pin 7 for Line Tracker sensor bit 1, digital pin 8 for Line Tracker
sensor bit 2, and set digital pin 9 for Line Tracker sensor bit 3, if the data of Line
Tracker bit 1, 2, and 3 are 111 the mobile robot will execute STOP subroutine, if
the data of Line Tracker bit 1, 2, and 3 are 101 the mobile robot will execute
FORWARD subroutine, if the data of Line Tracker bit 1, 2, and 3 are 110 the
mobile robot will execute RIGHT subroutine, and if the data of Line Tracker bit 1,
2, and 3 are 011 the mobile robot will execute LEFT subroutine. Set digital pin 2
for interrupt connected in distance sensor if distance sensor is logic 1, no
interrupt will execute wile if distance sensor is logic 0 the mobile robot will rotate
to the right for 6 sec.
Solution:
IV - QUESTIONS/ APPLICATIONS:
V - CONCLUSION:
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
71
Arduino - GSM Shield Interface
What is GSM
To use GPRS for internet access, and for the Arduino to request or serve
webpages, you need to obtain the Access Point Name (APN) and a
username/password from the network operator. See the information in
Connecting to the Internet for more information about using the data capabilities
of the shield.
Among other things, GSM supports outgoing and incoming voice calls,
Simple Message System (SMS or text messaging), and data communication (via
GPRS).
The Arduino GSM shield is a a GSM modem. From the mobile operator
perspective, the Arduino GSM shield looks just like a mobile phone. From the
Arduino perspective, the Arduino GSM shield looks just like a modem.
What is GPRS
72
Network operator requirements
To use GPRS for internet access, and for the Arduino to request or serve
webpages, you need to obtain the Access Point Name (APN) and a
username/password from the network operator. See the information in
Connecting to the Internet for more information about using the data capabilities
of the shield.
Send SMS
This sketch, for the Arduino GSM shield, sends an SMS message you enter in
the serial monitor.
Connect your Arduino with the GSM shield and SIM card, open the serial
monitor, and wait for the "READY" message to appear in the monitor.
Next, type a message to send and press "return". Make sure the serial monitor is
set to send a newline when you press return.
73
Hardware Required
Code Explanation
First, import the GSM library
#include <GSM.h>
SIM cards may have a PIN number that enables their functionality. Define the PIN for
your SIM. If your SIM has no PIN, you can leave it blank :
Initialize instances of the classes you're going to use. You're going to need both the
GSM and GSM_SMS class.
GSM gsmAccess;
GSM_SMS sms;
In setup, open a serial connection to the computer. After opening the connection, send a
message indicating the sketch has started.
void setup(){
Serial.begin(9600);
Serial.println("SMS Messages Sender");
Create a local variable to track the connection status. You'll use this to keep the sketch
from starting until the SIM is connected to the network :
Connect to the network by calling gsmAccess.begin(). It takes the SIM card's PIN as an
argument. By placing this inside a while() loop, you can continually check the status of
the connection. When the modem does connect, gsmAccess() will return GSM_READY.
Use this as a flag to set the notConnected variable to true or false. Once connected, the
remainder of setup will run.
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_READY)
notConnected = false;
74
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized.");
}
Create a function named readSerial of type int. You'll use this to iterate through input
from the serial monitor, storing the number you wish to send an SMS to, and the
message you'll be sending. It should accept a char array as an argument.
Create a variable to count through the items in the serial buffer, and start a while loop
that will continually execute.
int i = 0;
while(1)
{
As long as there is serial information available, read the data into a variable named
inChar.
If the character being read is a newline, terminate the array, clear the serial buffer and
exit the function.
if (inChar == '\n')
{
result[i] = '\0';
Serial.flush();
return 0;
}
If the incoming character is an ASCII character other than a newline or carriage return,
add it to the array and increment the index. Close up the while loops and the function.
if(inChar!='\r')
{
result[i] = inChar;
i++;
}
75
}
}
}
In loop, create a char array named remoteNumber to hold the number you wish to send
an SMS to. Invoke the readSerial function you just created, and pass remoteNumber as
the argument. When readSerial executes, it will populate remoteNumber with the
number you wish to send the message to.
Create a new char array named txtMsg. This will hold the content of your SMS. Pass
txtMsg to readSerial to populate the array.
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);
sms.beginSMS(remoteNumber);
sms.print(txtMsg);
sms.endSMS();
Serial.println("\nCOMPLETE!\n");
}
Once your code is uploaded, open the serial monitor. Make sure the serial monitor is set
to only send a newline character on return. When prompted to enter the number you
wish to call, enter the digits and press return. You'll then be asked to enter your
message. Once you've typed that, press return again to send it.
Create a program that send a SMS message from an Arduino UNO board
equipped with a GSM shield.
Note:
76
Using the serial monitor of the Arduino Software (IDE), you'll enter the number to
connect with, and the text message to send.
Solution:
void setup() {
// initialize serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// connection state
boolean notConnected = true;
Serial.println("GSM initialized");
}
void loop() {
// sms text
Serial.print("Now, enter SMS content: ");
char txtMsg[200];
readSerial(txtMsg);
77
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);
/*
Read input serial
*/
int readSerial(char result[]) {
int i = 0;
while (1) {
while (Serial.available() > 0) {
char inChar = Serial.read();
if (inChar == '\n') {
result[i] = '\0';
Serial.flush();
return 0;
}
if (inChar != '\r') {
result[i] = inChar;
i++;
}
}
}
}
Receive SMS
This sketch waits for an SMS message and prints it to the serial monitor. It uses
the GSM library of the Arduino GSM Shield and an active SIM card. To operate, the SIM
card doesn't need a data plan.
Hardware Required
78
SIM card
Code Explanation
#include <GSM.h>
SIM cards may have a PIN number that enables their functionality. Define the PIN for
your SIM. If your SIM has no PIN, you can leave it blank :
Initialize instances of the classes you're going to use. You're going to need both the
GSM and GSM_SMS class.
GSM gsmAccess;
GSM_SMS sms;
Create a char array to hold the number that is sending the message :
char remoteNumber[20];
In setup, open a serial connection to the computer. After opening the connection, send a
message indicating the sketch has started.
void setup(){
Serial.begin(9600);
Serial.println("SMS Messages Receiver");
Create a local variable to track the connection status. You'll use this to keep the sketch
from starting until the SIM is connected to the network :
Connect to the network by calling gsmAccess.begin(). It takes the SIM card's PIN as an
argument. By placing this inside a while() loop, you can continually check the status of
the connection. When the modem does connect, gsmAccess() will return GSM_READY.
Use this as a flag to set the notConnected variable to true or false. Once connected, the
remainder of setup will run.
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_READY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
79
}
Serial.println("GSM initialized.");
Serial.println("Waiting for messages");
}
SMS messages are received by the modem. SIM cards have some memory space to
store incoming SMS. The number of SMS the card can hold can be as few as 10, or as
many as 200, depending on the SIM. You should check with your provider to determine
how many your SIM can keep in memory.
In loop(), create a variable of type char to temporarily hold characters from any SMS
received. Use sms.available() to check for the presence of any messages on the SIM :
void loop()
{
char c;
if (sms.available())
{
It's possible to delete SMS messages by calling sms.flush(). Using sms.peek() it's
possible to identify the message index number, which could be helpful for removal
The code below won't remove any from the SIM, but you could iterate through a for loop,
or identify a specific index number to remove, instead of the dummy # used below
if(sms.peek()=='#')
{
Serial.println("Discarded SMS");
sms.flush();
}
To read a message, use sms.read(). Here, you'll store each character from the message
into the variable c and print it out as it gets read.
while(c=sms.read())
Serial.print(c);
Indicate the message is complete and remove it from memory with sms.flush().
80
Serial.println("\nEND OF MESSAGE");
sms.flush();
Serial.println("MESSAGE DELETED");
}
delay(1000);
}
Once your code is uploaded, open the serial monitor. With a phone, or other SMS
enabled service, send a SMS to the number of your SIM. You should see the message
print out on screen when it is received.
Create a program for the Arduino GSM shield that waits for a SMS message
Solution:
void setup() {
// initialize serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// connection state
boolean notConnected = true;
81
notConnected = false;
} else {
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
Serial.println("Waiting for messages");
}
void loop() {
char c;
Serial.println("\nEND OF MESSAGE");
delay(1000);
82
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________
I - OBJECTIVES
III - PROBLEM
1. This sketch, for the Arduino GSM shield, puts a voice call to a remote phone
number that you enter through the serial monitor.
Note:
To make it work, open the serial monitor, and when you see the READY message,
type a phone number. Make sure the serial monitor is set to send a just newline when
you press return.
Solution:
83
2. Create a program for the Arduino GSM shield that receives voice calls, then
displays the calling number, and waits a few seconds then hangs up.
Solution:
IV - QUESTIONS/ APPLICATIONS:
V - CONCLUSION:
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
84
LCD INTERFACING
INTRODUCTION
Used mainly in newer computer monitors and handheld devices such as cell
phones and digital cameras, LCDs use very little current and have long service life.
LCD display
85
Pin No. Name Description
0 = Instruction input
Pin no. 4 RS
1 = Data input
/*
LiquidCrystal Library - Hello World
86
Demonstrates the use a 16x2 LCD display. The LiquidCrystal
library works with all LCD displays that are compatible with the
Hitachi HD44780 driver. There are many of them out there, and you
can usually tell them by the 16-pin interface.
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* LCD VSS pin to ground
* LCD VCC pin to 5V
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
http://www.arduino.cc/en/Tutorial/LiquidCrystal
*/
EXAMPLE 11-1:
87
// include the library code:
#include <LiquidCrystal.h>
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
}
void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis() / 1000);
}
88
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________
I - OBJECTIVES
III - PROBLEM
1. Create a program that will display “LCD Interfacing” at LCD line 1 and
“Experiment No 11” at LCD line 2 of a 16x2 LCD display. Use Arduino UNO
board.
89
Solution:
2. Create a program that will display “I LOVE” at LCD line 1 and after 3 sec will
display “ELECTRONICS” at LCD line 2 of a 16x2 LCD display. Use Arduino UNO
board.
Solution:
90
3. Create a program that will repeatedly count from “000” to “999” and display the
output at LCD display, having a delay of 1 second. Use Arduino UNO board.
Solution:
IV - QUESTIONS/ APPLICATIONS:
V - CONCLUSION:
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
91
PLAY A MELODY USING THE TONE() FUNCTION
INTRODUCTION
This example shows how to use the tone() command to generate notes. It plays
a little melody you may have heard before.
Hardware Required
92
Figure 12.2: Schematic Diagram of piezo buzzer interface to Arduino
Code
The code below uses an extra file, pitches.h. This file contains all the pitch values
for typical notes. For example, NOTE_C4 is middle C. NOTE_FS4 is F sharp, and so
forth. This note table was originally written by Brett Hagman, on whose work the tone()
command was based. You may find it useful for whenever you want to make musical
notes.
93
EXAMPLE 12-1:
#include "pitches.h"
void setup() {
// iterate over the notes of the melody:
for (int thisNote = 0; thisNote < 8; thisNote++) {
void loop() {
// no need to repeat the melody.
}
Note:
To make the pitches.h file, either click on the button just below the serial monitor
icon and choose "New Tab", or use Ctrl+Shift+N.
94
/*********************************** #define NOTE_F4 349
#define NOTE_FS4 370
* Public Constants #define NOTE_G4 392
***********************************/ #define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_B0 31 #define NOTE_AS4 466
#define NOTE_C1 33 #define NOTE_B4 494
#define NOTE_CS1 35 #define NOTE_C5 523
#define NOTE_D1 37 #define NOTE_CS5 554
#define NOTE_DS1 39 #define NOTE_D5 587
#define NOTE_E1 41 #define NOTE_DS5 622
#define NOTE_F1 44 #define NOTE_E5 659
#define NOTE_FS1 46 #define NOTE_F5 698
#define NOTE_G1 49 #define NOTE_FS5 740
#define NOTE_GS1 52 #define NOTE_G5 784
#define NOTE_A1 55 #define NOTE_GS5 831
#define NOTE_AS1 58 #define NOTE_A5 880
#define NOTE_B1 62 #define NOTE_AS5 932
#define NOTE_C2 65 #define NOTE_B5 988
#define NOTE_CS2 69 #define NOTE_C6 1047
#define NOTE_D2 73 #define NOTE_CS6 1109
#define NOTE_DS2 78 #define NOTE_D6 1175
#define NOTE_E2 82 #define NOTE_DS6 1245
#define NOTE_F2 87 #define NOTE_E6 1319
#define NOTE_FS2 93 #define NOTE_F6 1397
#define NOTE_G2 98 #define NOTE_FS6 1480
#define NOTE_GS2 104 #define NOTE_G6 1568
#define NOTE_A2 110 #define NOTE_GS6 1661
#define NOTE_AS2 117 #define NOTE_A6 1760
#define NOTE_B2 123 #define NOTE_AS6 1865
#define NOTE_C3 131 #define NOTE_B6 1976
#define NOTE_CS3 139 #define NOTE_C7 2093
#define NOTE_D3 147 #define NOTE_CS7 2217
#define NOTE_DS3 156 #define NOTE_D7 2349
#define NOTE_E3 165 #define NOTE_DS7 2489
#define NOTE_F3 175 #define NOTE_E7 2637
#define NOTE_FS3 185 #define NOTE_F7 2794
#define NOTE_G3 196 #define NOTE_FS7 2960
#define NOTE_GS3 208 #define NOTE_G7 3136
#define NOTE_A3 220 #define NOTE_GS7 3322
#define NOTE_AS3 233 #define NOTE_A7 3520
#define NOTE_B3 247 #define NOTE_AS7 3729
#define NOTE_C4 262 #define NOTE_B7 3951
#define NOTE_CS4 277 #define NOTE_C8 4186
#define NOTE_D4 294 #define NOTE_CS8 4435
#define NOTE_DS4 311 #define NOTE_D8 4699
#define NOTE_E4 330 #define NOTE_DS8 4978
95
Pitch follower using the tone() function
This example shows how to use the tone() command to generate a pitch that
follows the values of an analog input. Using a photoresistor your Arduino or Genuino
board becomes a simplified light theremin.
Hardware Required
96
Note:
Connect one terminal of your speaker to digital pin 9 through a 100 ohm resistor,
and its other terminal to ground. Power your photoresistor with 5V, and connect it to
analog 0 with the addition of a 4.7K resistor to ground.
Code
The code for this example is very simple. Just take an analog input and map its
values to a range of audible pitches. Humans can hear from 20 - 20,000Hz, but 120 -
1,500 usually works pretty well for this sketch.
You'll need to get the actual range of your analog input for the mapping. In the
circuit shown, the analog input value ranged from about 400 to about 1,000. Change the
values in the map() command to match the range for your sensor.
97
EXAMPLE 12-2:
void setup() {
// initialize serial communications (for debugging only):
Serial.begin(9600);
}
void loop() {
// read the sensor:
int sensorReading = analogRead(A0);
// print the sensor reading so you know its range
Serial.println(sensorReading);
// map the analog input range (in this case, 400 - 1000 from the photoresistor)
// to the output pitch range (120 - 1500Hz)
// change the minimum and maximum input numbers below
// depending on the range your sensor's giving:
int thisPitch = map(sensorReading, 400, 1000, 120, 1500);
98
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________
I - OBJECTIVES
III - PROBLEM
1. Create a program that uses the tone() command to play different notes on
multiple outputs. Interface 3 speaker to D6, D7, and D8
99
Hardware Required
100
Figure 12.7: Wiring Diagram for Problem 1
Solution:
101
IV - QUESTIONS/ APPLICATIONS:
V - CONCLUSION:
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
102