Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

03 Arduino Manual v2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 102
At a glance
Powered by AI
The manual covers different experiments that can be conducted using Arduino to interface with devices like LEDs, motors, sensors etc. It explains concepts like digital input/output, analog read, PWM etc.

The components used include Arduino UNO board, breadboard, resistors, LEDs, sensors, motors etc. Devices like LCD, GSM module are also interfaced.

Experiments on digital input/output, interfacing Arduino with DC loads, AC loads, analog read, PWM, DC motors, servo motors, stepper motors etc are covered.

EXPERIMENT MANUAL

2016
TABLE OF CONTENTS

Introduction to Arduino …….………………..……………………………….. 3


Using Arduino UNO …………………………………………………………….15

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.

Figure 1: Arduino Board

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.

Figure 4: Arduino Uno

4
And then you have fancier Arduino with more powerful processors, which have
Wi-Fi, Ethernet and more.

Figure 5: Arduino TIAN and Ethernet

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.

Figure 6: Arduino Clones

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.

Figure 8: Arduino Shields sparkfun

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

Figure 9: Arduino Shields sparkfun

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

Figure 10: Microcontroller Programming Language

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.

Figure 12: Arduino connected to USB cable

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

Figure 14: Arduino UNO

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.

Arduino uses the microcontroller Atmel AT mega 328, connected to the


microcontroller is a crystal resonator, this controls how fast the microcontroller is
running.

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

Figure 16: Microcontroller

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.

Figure 17: Arduino connected to USB cable

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

Figure 19: Arduino IDE parts

Arduino consists of both a physical programmable circuit board (often referred to


as a microcontroller) and a piece of software, or IDE (Integrated Development
Environment) that runs on your computer, used to write and upload computer code to
the physical board.

14
Using Arduino UNO

1. Write your sketch


2. Press compile button (to check for errors)
3. Press upload button to program Arduino
board with your sketch

Try it out with the Blink sketch.

Click File, Examples, 01.Basics, Blink

Figure 20: Steps in using Arduino IDE

15
ARDUINO - DIGITAL OUT

Programming Digital I/0 PINs


pinMode(pin, mode)
Sets pin to either INPUT or OUTPUT

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: __________________

Experiment No: 1 ARDUINO - DIGITAL OUT

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.

II - MATERIALS AND EQUIPMENT

1pc Power Supply or 5V adaptor 1pair Alligator Clip


1pc Arduino UNO 1pc Resistor 220Ω 1/4W
8pcs LED Green or Any Color 2m AWG #22 Solid wire
1pc Bread board

III - PROBLEM

Instruction:

Write your answer on the space provided after each problem

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:

1. How many Digital pins Arduino UNO have?


2. What is the voltage out equivalent to logic high in digital pins of Arduino UNO?
3. What is the voltage out equivalent to logic low in digital pins of Arduino UNO?

V - CONCLUSION:

______________________________________________________________________
______________________________________________________________________
______________________________________________________________________

20
ARDUINO - DIGITAL OUT

Programming Digital I/0 PINs


pinMode(pin, mode)
Sets pin to either INPUT or OUTPUT

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:

int ledPins[] = {0,1, 2, 3, 4, 5,6,7,8,9,10,11,12,13};

void setup() {
for (int thisPin = 0; thisPin < 14; thisPin++)
{
pinMode(ledPins[thisPin], OUTPUT);
}
}

21
22
ARDUINO - DIGITAL IN / OUT

Programming Digital I/0 PINs


pinMode(pin, mode)
Sets pin to either INPUT or OUTPUT

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.

Figure 2.1: Schematic of Problem 1

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: __________________

Experiment No: 2 ARDUINO - DIGITAL IN / OUT

I - OBJECTIVES

a. To interface N.O. Push button as input device to Arduino UNO board


b. To sketch a program for digital input output circuit.
c. Apply knowledge gained to control each digital pin of Adruino UNO board.

II - MATERIALS AND EQUIPMENT

1pc Power Supply or 5V adaptor 1pair Alligator Clip


1pc Arduino UNO 1pc Resistor 220Ω 1/4W
8pcs LED Green or Any Color 8pcs Resistor 10KΩ 1/4W
1pc Bread board 1pc LED Green
8pcs N.O. Push Button 2m AWG #22 Solid wire

III- PROBLEM

Instruction:

Write your answer on the space provided after each problem

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:

One of the most fundamental applications of a transistor is using it to control the


flow of power to another part of the circuit – using it as an electric switch. Driving it in
cutoff or saturation mode, the transistor can create the binary on/off effect of a switch.

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:

Figure 3.1: Transistor Switching NPN

Our control input flows into the base, the output is tied to the collector, and the
emitter is kept at a fixed voltage.

While a normal switch would require an actuator to be physically flipped, this


switch is controlled by the voltage at the base pin. A microcontroller I/O pin can be
programmed to go high or low to turn the LED on or off.

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:

Figure 3.2: Transistor Switching PNP

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.

Recall that, in a way, a transistor is just a pair of interconnected diodes. We’re


forward-biasing the base-emitter diode to turn the load on. The diode only needs 0.6V to
turn on, more voltage than that means more current. Some transistors may only be rated
for a maximum of 10-100mA of current to flow through them. If you supply a current over
the maximum rating, the transistor might blow up.

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

Figure 3.3: Schematic Diagram for Example 3-1

29
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________

Experiment No.3: Interfacing Microcontroller to High Power DC Loads

I - OBJECTIVES

a. To use the Arduino UNO board in switching a high power DC load


b. To construct a program that will control the state of transistor
c. To apply knowledge gained in use of switch and transistor interfaced to the
pins of Arduino UNO board.

II - MATERIALS AND EQUIPMENT

1pc Power Supply or 5V adaptor 1pair Alligator Clip


1pc Arduino UNO 1pc Resistor 220Ω 1/4W
8pcs LED Green or Any Color 8pcs Resistor 10KΩ 1/4W
1pc Bread board 1pc LED Green
8pcs N.O. Push Button 2m AWG #22 Solid wire
1pc Power Supply or 12V adaptor 1pc 12V DC Lamp or any 12V Load
1pc 2n2222A Transistor

III- PROBLEM

Instruction:

Write your answer on the space provided after each problem

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:

A relay is an electrically operated switch. Many relays use an electromagnet to


operate a switching mechanism mechanically, but other operating principles are also
used. Relays are used where it is necessary to control a circuit by a low-power signal
(with complete electrical isolation between control and controlled circuits), or where
several circuits must be controlled by one signal.

Figure 4.1: SPDT 12V Dc Relay

We can’t drive AC loads directly with a Microcontroller, as AC loads requires high


current and high voltage than a Microcontroller can handle. Microcontrollers usually
operates at +5 or +3.3V DC supply and it I/O pin can provide only up to 25mA DC
current. Commonly used AC loads requires 220V AC supply and 5,000mA AC current.
Thus it is clear that, interfacing AC load directly with Microcontrollers will damage and
destroy the microcontroller.

To interface Microcontroller to AC loads we need a device that will isolate the


microcontroller to AC load but still can be able to control the ON and OFF state of the
load. The solution in by using Relay, since relay is an electromechanical switch its coil
can be energized by 5Vdc to 24Vdc and its secondary connection is completely isolated
to its primary connection, which we need to control AC loads.

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

Figure 4.2: Schematic Diagram for Example 4-1

34
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________

Experiment No.4: Interfacing PIC Microcontroller to AC Loads

I - OBJECTIVES

a. To use the Arduino UNO board in switching a relay


b. To construct a program that will control the state of relay
c. To apply knowledge gained in use of switch and relay interfaced to the pins of
Arduino UNO board.

II - MATERIALS AND EQUIPMENT

1pc Power Supply or 5V adaptor 1pair Alligator Clip


1pc Arduino UNO 1pc Resistor 220Ω 1/4W
8pcs LED Green or Any Color 8pcs Resistor 10KΩ 1/4W
1pc Bread board 1pc LED Green
8pcs N.O. Push Button 2m AWG #22 Solid wire
1pc Power Supply or 12V adaptor 1pc Extension socket, wire, plug
1pc 2n2222A Transistor 1pc 5V to 12V SPDT Relay

III- PROBLEM

Instruction:

Write your answer on the space provided after each problem

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:

1. Relay is categorized as what type of switch?


2. Explain the principle of relay switching?

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.

EXAMPLE 5-1: ANALOG READ

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.

Figure 5.1: Wiring Diagram of Example 5-1

38
Solution:

// the setup routine runs once when you press reset:


void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

// the loop routine runs over and over again forever:


void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
delay(1); // delay in between reads for stability
}

EXAMPLE 5-2: PWM OUT

Create a program that uses the analog output pin 9 (Pulse Width Modulation
(PWM)) to fade an LED.

Note:

PWM is a technique for getting an analog-like behavior from a digital output by


switching it off and on very fast and with different ratio between on and off time.

Figure 5.2: Wiring Diagram of Example 5-2

39
Figure 5.3: Schematic of Example 5-2

Solution:

int ledPin = 9; // LED connected to digital pin 9

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

// fade out from max to min in increments of 5 points:


for (int fadeValue = 255 ; fadeValue >= 0; 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: __________________

Experiment No.5: Arduino – Analog Read and PWM

I - OBJECTIVES

a. To use the Arduino UNO board in switching a relay


b. To construct a program that will control the state of relay
c. To apply knowledge gained in use of switch and relay interfaced to the pins of
Arduino UNO board.

II - MATERIALS AND EQUIPMENT

1pc Power Supply or 5V adaptor 1pair Alligator Clip


1pc Arduino UNO 1pc Resistor 220Ω 1/4W
8pcs LED Green or Any Color 1pc 10K Ω Potentiometer
1pc Bread board 2m AWG #22 Solid wire

III- PROBLEM

Instruction:

Write your answer on the space provided after each problem

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:

1. What is PWM signal?


2. Explain the principle of PWM signal?

V - CONCLUSION:

______________________________________________________________________
______________________________________________________________________
______________________________________________________________________

42
INTERFACING ARDUINO TO DC MOTOR USING L293D

INTRODUCTION

I - Introductory Information:

Figure 6.1: DC motor

DC Motor and L293D

We can’t drive a DC Motor (depends) directly with a Microcontroller, as DC


Motors requires high current and high voltage than a Microcontroller can handle.
Microcontrollers usually operates at +5 or +3.3V supply and it I/O pin can provide only
up to 25mA current. Commonly used DC Motors requires 12V supply and 300mA
current, moreover interfacing DC Motors directly with Microcontrollers may affect the
working of Microcontroller due to the Back EMF of the DC Motor. Thus it is clear that, it
not a good idea to interface DC Motor directly with Microcontrollers.

The solution to above problems is to use H-bridge circuit.

Basic H-Bridge DC Motor Driving

It is a special circuit, by using the 4 switches we can control the direction of DC


Motor. Depending upon our power requirements we can make our own H-bridge using
Transistors/MOSFETs as switches. It is better to use ready made ICs, instead of making
our own H-bridge.

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.

Figure 6.3: PIN Diagram of L293D

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.

Table 6.1: FUNCTION TABLE

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

Table 6.2: Control Signals and Motor Status

RB0/IN1 RB2/IN2 Motor Status

LOW LOW Stops

LOW HIGH CounterClockwise

HIGH LOW Clockwise

HIGH HIGH Stops

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: __________________

Experiment No.6: Interfacing Arduino to DC Motor Using L293D

I - OBJECTIVES

a. To use the Arduino UNO interfaced to L293D to drive DC motor


b. To construct a program that will send signal to L293D to drive DC motor
c. To apply knowledge gained in programming Arduino UNO interfaced to
L293D in a circuit.

II - MATERIALS AND EQUIPMENTS

1pc Power Supply or 5V adaptor 1pair Alligator Clip


1pc Arduino UNO 4pc Resistor 220Ω 1/4W
8pcs LED Green or Any Color 4pcs Resistor 10KΩ 1/4W
1pc Bread board 2m AWG #22 Solid wire
8pcs N.O. Push Button 4pc 1N4001 Diode
1pc Power Supply or 12V adaptor 4pc 5V to 12V SPDT Relay
4pc 2n2222A Transistor 2pc 6 V DC motor
1pc L293D

III - PROBLEM

Instruction:

Write your answer on the space provided after each problem

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:

1. Give at least one example of application of DC motor in our technology


today?
2. Why does DC motor is used for that application aside from othertype of
motors?
3. What are the advantages of DC motor?
4. What are the disadvantages of DC motor?

V - CONCLUSION:

______________________________________________________________________
______________________________________________________________________
______________________________________________________________________

51
INTERFACING ARDUINO TO SERVO MOTOR

INTRODUCTION

Figure 7.1: Servo motor

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.

Figure 7.3: Wiring Diagram for Example 7-1

53
Solution:

#include <Servo.h>

Servo myservo; // create servo object to control a servo


// twelve servo objects can be created on most boards

int pos = 0; // variable to store the servo position

void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}

void loop() {
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 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
}
}

Figure 7.4: Schematic Diagram for Example 7-1

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.

Figure 7.5: Schematic Diagram for Example 7-2

55
Figure 7.6: Wiring Diagram for Example 7-2

Solution:

#include <Servo.h>

Servo myservo; // create servo object to control a servo

int potpin = 0; // analog pin used to connect the potentiometer


int val; // variable to read the value from the analog pin

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: __________________

Experiment No.7: Interfacing Arduino to Servo Motor

I - OBJECTIVES

a. To use the Arduino UNO board to drive a Servo motor


b. To construct a program that will send PWM to Servo motor
c. To apply knowledge gained in programming Arduno UNO board interfaced to
Servo motor in a circuit.

II - MATERIALS AND EQUIPMENTS

1pc Power Supply or 5V adaptor 1pair Alligator Clip


1pc Arduino UNO 4pc Resistor 220Ω 1/4W
8pcs LED Green or Any Color 4pcs Resistor 10KΩ 1/4W
1pc Bread board 2m AWG #22 Solid wire
1pc 5V Servo Motor 1pc 10k Ω Potentiometer

III - PROBLEM

Instruction:

Write your answer on the space provided after each problem

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

Figure 8.1: Stepper motor

A Stepper Motor is a brushless, synchronous DC electric motor, which divides


the full rotation into a number of equal steps. It finds great application in field of
microcontrollers such as robotics. Please refer the article Stepper Motor or Step Motor
for detailed information about working of stepper motor, types and modes of operation.
Unipolar Motor is the most popular stepper motor among electronics hobbyist because
of its ease of operation and availability.

Figure 8.2: Unipolar Stepper Motor Windings

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.

Note: 1 – Represents Supply Voltage and 0 – Represents Ground

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.

Table 8.1: Unipolar Stepper Motor Wave Drive Stepping Sequence

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.

Table 8.3: Unipolar Stepper MotorHalf Drive Stepping Sequence

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

Driving Bipolar Motor

Figure 8.3: Bipolar Stepper Motor Windings

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.

Table 8.3: Bipolar Motor Stepping Sequence

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

// initialize the stepper library on pins 8 through 11:


Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0; // number of steps the motor has taken

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

// initialize the stepper library on pins 8 through 11:


Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0; // number of steps the motor has taken

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: __________________

Experiment No.8: Interfacing Arduino to Stepper Motor

I - OBJECTIVES

a. To use the Arduino UNO board to drive a Stepper motor


b. To construct a program that will send signal to Stepper motor
c. To apply knowledge gained in programming Arduino UNO interfaced to
Stepper motor in a circuit.

II - MATERIALS AND EQUIPMENTS

1pc Power Supply or 5V adaptor 1pair Alligator Clip


1pc Arduino UNO 4pc Resistor 220Ω 1/4W
8pcs LED Green or Any Color 4pcs Resistor 10KΩ 1/4W
1pc Bread board 2m AWG #22 Solid wire
1pc Power Supply or 5V adaptor 1pair Alligator Clip
4pcs N.O. Push Button 10pc Female to female header connector
1pc Power Supply or 6V adaptor 1pc 5or 6V Unipolar Stepper Motor
1pc L293D 1pc 5or 6V Bipolar Stepper Motor

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:

1. What is the difference of unipolar stepper motor to bipolar stepper motor?


2. Give at least one example of application of stepper motor in our technology
today?
3. Why does stepper motor is used for that application aside from DC motorand
servo motor?
4. What are the advantages of stepper motor to DC motor and servo motor?
5. What are the disadvantages of stepper motor to DC motor and servo motor?

V - CONCLUSION:

______________________________________________________________________
______________________________________________________________________
______________________________________________________________________

67
INTERRUPT SUBROUTINE
INTRODUCTION

Interrupts are useful for making things happen automatically in microcontroller


programs, and can help solve timing problems. Good tasks for using an interrupt may
include reading a rotary encoder, or monitoring user input.

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.

The first parameter to attachInterrupt is an interrupt number. Normally you should


use digitalPinToInterrupt(pin) to translate the actual digital pin to the specific interrupt
number. For example, if you connect to pin 3, use digitalPinToInterrupt(3) as the first
parameter to attachInterrupt.

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:

const byte ledPin = 13;


const byte interruptPin = 2;
volatile byte state = LOW;

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: __________________

Experiment No.9: Interrupts

I - OBJECTIVES

a. To know the concept of Interrupts.


b. To demonstrate the program Interrupts using Arduino IDE
c. To construct a program that will utilized Interrupts.

II - MATERIALS AND EQUIPMENTS

1pc Power Supply or 5V adaptor 1pair Alligator Clip


1pc Arduino UNO 4pc Resistor 220Ω 1/4W
8pcs LED Green or Any Color 4pcs Resistor 10KΩ 1/4W
1pc Bread board 2m AWG #22 Solid wire
1pc Power Supply or 6V adaptor 2pcs 6V DC motor
1pc L293D 10pc Female to female header connector
1pc 3bit Line Tracker Sensor 1pc Distance Proximity Sensor

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:

1. Why it is interrupt is important in Arduino programming?


2. What are the different types of interrupt used by Arduino UNO Board?

V - CONCLUSION:

______________________________________________________________________
______________________________________________________________________
______________________________________________________________________

71
Arduino - GSM Shield Interface

What is GSM

GSM is an international standard for mobile telephones. It is an acronym


that stands for Global System for Mobile Communications. It is also sometimes
referred to as 2G, as it is a second-generation cellular network.

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

GPRS is a packet switching technology that stands for General Packet


Radio Service. It can provide idealized data rates between 56-114 kbit per
second.

A number of technologies such as SMS rely on GPRS to function. With


the GSM shield, it is also possible to leverage the data communication to access
the internet. Similar to the Ethernet and WiFi libraries, the GSM library allows the
Arduino to act as a client or server, using http calls to send and receive web
pages.

72
Network operator requirements

To access a network, you must have a subscription with a mobile phone


operator (either prepaid or contract), a GSM compliant device like the GSM
shield or mobile phone, and a Subscriber Identity Module (SIM) card. The
network operator provides the SIM card, which contains information like the
mobile number, and can store limited amounts of contacts and SMS messages.

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.

Figure 10.1: Arduino GSM Shield

73
Hardware Required

 Arduino UNO Board


 GSM/GPRS Shield
 SIM card

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 :

#define PINNUMBER ""

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 :

boolean notConnected = true;

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

Finish setup with some information to the serial monitor.

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.

int readSerial(char result[])


{

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.

while (Serial.available() > 0)


{
char inChar = Serial.read();

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.

Serial.print("Enter a mobile number: ");


char remoteNumber[20];
readSerial(remoteNumber);
Serial.println(remoteNumber);

Create a new char array named txtMsg. This will hold the content of your SMS. Pass
txtMsg to readSerial to populate the array.

Serial.print("Now, enter SMS content: ");


char txtMsg[200];
readSerial(txtMsg);

Call sms.beginSMS() and pass it remoteNumber to start sending the message,


sms.print() to send the message, and sms.endSMS() to complete the process. Print out
some diagnostic information and close the loop. Your message is on its way!

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.

EXAMPLE 10-1: Send SMS

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:

// Include the GSM library


#include <GSM.h>

#define PINNUMBER ""

// initialize the library instance


GSM gsmAccess;
GSM_SMS sms;

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
}

Serial.println("SMS Messages Sender");

// connection state
boolean notConnected = true;

// Start GSM shield


// If your SIM has PIN, pass it as a parameter of begin() in quotes
while (notConnected) {
if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
notConnected = false;
} else {
Serial.println("Not connected");
delay(1000);
}
}

Serial.println("GSM initialized");
}

void loop() {

Serial.print("Enter a mobile number: ");


char remoteNum[20]; // telephone number to send sms
readSerial(remoteNum);
Serial.println(remoteNum);

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

// send the message


sms.beginSMS(remoteNum);
sms.print(txtMsg);
sms.endSMS();
Serial.println("\nCOMPLETE!\n");
}

/*
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

 Arduino UNO Board


 GSM/GPRS Shield

78
 SIM card

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 :

#define PINNUMBER ""

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 :

boolean notConnected = true;

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
}

Finish setup with some information to the serial monitor.

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())
{

If a SMS is available, retrieve the remote sender's number by calling


sms.remoteNumber(remoteNumber, 20). the remoteNumber argument is the char array
you declared in the beginning of the sketch, it can be no longer than 20 characters. Send
this number to the serial monitor.

Serial.println("Message received from:");


sms.remoteNumber(remoteNumber, 20);
Serial.println(remoteNumber);

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

Add a brief delay and close the loop.

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.

EXAMPLE10-2: Receives SMS

Create a program for the Arduino GSM shield that waits for a SMS message

and displays it through the Serial port.

Solution:

// include the GSM library


#include <GSM.h>

// PIN Number for the SIM


#define PINNUMBER ""

// initialize the library instances


GSM gsmAccess;
GSM_SMS sms;

// Array to hold the number a SMS is retreived from


char senderNumber[20];

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
}

Serial.println("SMS Messages Receiver");

// connection state
boolean notConnected = true;

// Start GSM connection


while (notConnected) {
if (gsmAccess.begin(PINNUMBER) == GSM_READY) {

81
notConnected = false;
} else {
Serial.println("Not connected");
delay(1000);
}
}

Serial.println("GSM initialized");
Serial.println("Waiting for messages");
}

void loop() {
char c;

// If there are any SMSs available()


if (sms.available()) {
Serial.println("Message received from:");

// Get remote number


sms.remoteNumber(senderNumber, 20);
Serial.println(senderNumber);

// An example of message disposal


// Any messages starting with # should be discarded
if (sms.peek() == '#') {
Serial.println("Discarded SMS");
sms.flush();
}

// Read message bytes and print them


while (c = sms.read()) {
Serial.print(c);
}

Serial.println("\nEND OF MESSAGE");

// Delete message from modem memory


sms.flush();
Serial.println("MESSAGE DELETED");
}

delay(1000);

82
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________

Experiment No.10: Arduino - GSM Shield Interface

I - OBJECTIVES

a. To know the concept of GSM.


b. To develop a program for Arduino UNO to interface with GSM Shield
c. To construct a program that will utilized serial transmission.

II - MATERIALS AND EQUIPMENTS

1pc Power Supply or 5V adaptor 1pair Alligator Clip


1pc Arduino UNO 2m AWG #22 Solid wire
1pc GSM/GPRS Shield 10pc Female to female header connector
1pc Sim Card w load 1pc Bread board

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:

1. How many channels does JZ863tranceiver have?


2. What is the carrier frequency of channel 1 of JZ863?
3. What is the working frequency or range of carrier frequency of JZ863?
4. What are the different Channel speed rates of JZ863?

V - CONCLUSION:

______________________________________________________________________
______________________________________________________________________
______________________________________________________________________

84
LCD INTERFACING

INTRODUCTION

Electronic device comprising of the molecules of a semi-liquid material


sandwiched between sheets of a transparent material. The molecules are oriented by an
electric current applied to them,

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

Figure 11.1: 2x16 Liquid-Crystal Display

Figure 11.2: LCD display component, and pin configuration

Table 11.1: Pin configuration of 2x16 Liquid-Crystal Display

85
Pin No. Name Description

Pin no. 1 VSS Power supply (GND)

Pin no. 2 VCC Power supply (+5V)

Pin no. 3 VEE Contrast adjust

0 = Instruction input
Pin no. 4 RS
1 = Data input

0 = Write to LCD Module


Pin no. 5 R/W
1 = Read from LCD module

Pin no. 6 EN Enable signal

Pin no. 7 D0 Data bus line 0 (LSB)

Pin no. 8 D1 Data bus line 1

Pin no. 9 D2 Data bus line 2

Pin no. 10 D3 Data bus line 3

Pin no. 11 D4 Data bus line 4

Pin no. 12 D5 Data bus line 5

Pin no. 13 D6 Data bus line 6

Pin no. 14 D7 Data bus line 7 (MSB)

/*
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.

This sketch prints "Hello World!" to the LCD


and shows the time.

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)

Library originally added 18 Apr 2008


by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe
modified 22 Nov 2010
by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/LiquidCrystal
*/

EXAMPLE 11-1:

87
// include the library code:
#include <LiquidCrystal.h>

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


LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// 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: __________________

Experiment No.11: LCD Interfacing

I - OBJECTIVES

a. To know the different byte manipulation instruction


b. To simulate the program for LCD using mikroC programming.
c. To construct a program that will display strings of symbols in LCD.

II - MATERIALS AND EQUIPMENTS

1pc Power Supply or 5V adaptor 1pair Alligator Clip


1pc Arduino UNO 4pc Resistor 220Ω 1/4W
8pcs LED Green or Any Color 4pcs Resistor 10KΩ 1/4W
1pc Bread board 2m AWG #22 Solid wire
1pc LM016L - 2x16LCD Display

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:

1. Explain the process involve in LCD display

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

 Arduino or Genuino board


 piezo buzzer or a speaker
 hook-up wires

Figure 12.1: piezo buzzer or a speaker interface to Arduino

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"

// notes in the melody:


int melody[] = {
NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:


int noteDurations[] = {
4, 8, 8, 4, 4, 4, 4, 4
};

void setup() {
// iterate over the notes of the melody:
for (int thisNote = 0; thisNote < 8; thisNote++) {

// to calculate the note duration, take one second


// divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000 / noteDurations[thisNote];
tone(8, melody[thisNote], noteDuration);

// to distinguish the notes, set a minimum time between them.


// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(8);
}
}

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.

Figure 12.3. Add new pitches at pitches.h

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

 Arduino UNO board


 8 ohm speaker
 photoresistor
 4.7K ohm resistor
 100 ohm resistor
 hook-up wires
 breadboard

Figure 12.4: Wiring Diagram of Pitch follower circuit

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.

Figure 12.5: Schematic Diagram of Pitch follower circuit

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

// play the pitch:


tone(9, thisPitch, 10);
delay(1); // delay in between reads for stability
}

98
Name: ______________________________ Date Performed: _____________
Course yr. and Section: ________________ Date Submitted: _____________
Group No: ___________________________ Instructor: __________________

Experiment No.12: Play a Melody using the tone() function

I - OBJECTIVES

a. To know the concept of tone() function.


b. To create a program for pieozo and speaker using Arduino IDE
c. To construct a ccircuit that will utilized tone() function

II - MATERIALS AND EQUIPMENTS

1pc Power Supply or 5V adaptor 1pair Alligator Clip


1pc Arduino UNO 4pc Resistor 4.7K Ω 1/4W
3pcs 8 ohm speakers 3pcs Resistor 100Ω 1/4W
1pc Bread board 2m AWG #22 Solid wire
1pc Photoresistor 1pc 4x4 Keypad

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

 Arduino UNO Board


 3x 8 ohm speakers
 3x 100 ohm resistor
 hook-up wires
 breadboard

Figure 12.6. Wiring Diagram for Problem 1

100
Figure 12.7: Wiring Diagram for Problem 1

Solution:

101
IV - QUESTIONS/ APPLICATIONS:

1. Explain the process involve in tone() function


2. How to add new pitch in pitches.h file

V - CONCLUSION:

______________________________________________________________________
______________________________________________________________________
______________________________________________________________________

102

You might also like