You are on page 1of 71

Department of Mechanical Engineering

Higher Colleges of Technology

MCE 2903
Sophomore Design Project

LAB MANUAL

April, 2021
1
TABLE OF CONTENTS
Laboratory SafetyExperiments………………...
……………………………………………………………………………5
Experiment 1: LED Blinking ………………………………………………………………………….……………..5
Experiment 2: LED by Button ……………………………………………………………….………………………7
Experiment 3: Reading Potentiometer ……………………………………………………………….……………....9
Experiment 4: Reading Infrared Distance …………………………………………………………………………..11
Experiment 5: Temperature Sensor and LED indicator …………………………………………………………….13
Experiment 6: Calibration …………………………………………………………………………………………..15
Experiment 7: Fading using PMW ………………………………………………………………………………….17
Experiment 8: Controlling Servo Motor with Potentiometer ……………………………………………………….19
Experiment 9: Sweeps the shaft of a RC Servo motor back and forth across 180 degrees ……………………...….21
Experiment 10: Ultrasonic Sensors and Servo Motors ………………………………………..…………………….23

References to further resources ..............................................................................................................................…...25

2
Laboratory Safety
Introduction
Laboratory Conduct Code should be followed, to minimize the risk of hazards to human health.

People who work in laboratories are required to be suitably trained, informed, instructed, and
supervised, and to ensure that equipment used is fit for purpose, maintained, inspected, and used in
accordance with recommended requirements.

Rules and Regulations


Besides the General Rules of Labs and the Computer Utilization Policy, other specific rules apply to
this lab:

 Unauthorized personnel are not allowed in the laboratory without special permission.
 Open-toed shoes or sandals are not permitted. Shoes should be worn at all times.
 Smoking, eating, and drinking are not allowed.
 Horseplay or other acts of carelessness are prohibited.
 Students are not allowed to work alone in the laboratory.
 Understand the operation of apparatus before using them. Prior permission from the Lab
Supervisor must be obtained if any change is to be made.
 If in doubt about the operation of apparatus, electrical safety, etc, consult the laboratory
instructor.
 Handle all apparatus with care. Turn OFF the apparatus when not in use.
 All equipment, apparatus, and stools must be RETURNED to their original place after use.
 Do not take any things out of the laboratory without special permission.
 The experiment must be completed within the given time.
 Clean up laboratory work areas before leaving the workplace.
 Report immediately to the laboratory engineer or instructor any injury incurred.
 Report to the laboratory engineers any damage to equipment, hazards, and potential hazards.

 Know the location of all safety equipment (e.g. eyewash, fire extinguisher, fire blanket, safety
showers, and spill kit) and how to use them.
 Consumption of food or beverages in the laboratory is forbidden. Food may not be stored in
refrigerators located in a laboratory.
3
 Wash hands before leaving the lab and before eating.
 Read labels carefully.
 Keep the work area clear of all materials except those needed for your work. Coats should be
hung in the hall or placed in a locker. Extra books, purses, etc. should be kept away from
equipment that requires air flow or ventilation to prevent overheating.
 Disposal - Students are responsible for the proper disposal of used material if any in the
appropriate containers.

Safety Precautions in general


 Do not touch any exposed wires.
 Do not unplug the cable while the power is switched on.
 Do not wear long, loose ties, scarves, or other loose clothing.
 Make sure that long hairs are tied.
 Handle all chemicals with care.
 Glove and apron, if required, must be worn at all times.
 Keep fluids and chemicals away from electrical equipment.
 Always keep the door close.

4
Department of Mechanical Engineering
Laboratory Exercise
Higher Colleges of Technology

Laboratory Exercise
Number
Experiment 1 Laboratory Title LED Blinking

Course Code MCE 2903 Course Title Sophomore Design Project

Student ID Student Name

Term Date

Instructor

Section
Group
Members

Report Written by:

Note: Students are expected to refrain from all forms of academic dishonesty as defined in the college
policies and as explained and defined by college policies and procedures and directions from teachers
or other college personnel. By signing this cover page you are stating that the work presented is yours
and yours alone. The work includes all figures, tables, calculations, data and text. Please note only
reports that include a signed cover sheet will be graded.

I hereby state that all work submitted in this report is mine and solely mine.

5
Objective:
 To show the simplest thing that can do with an Arduino.
 To see physical output: it blinks the on-board LED.
 To familiarize with the use of:
Digital Pins digital Write(), digital Read()
Analog Pins – analog Write(), analog Read()
if…else statement
For loop
Serial Communication

Equipment Required:
 Arduino board with data cable
 Arduino Software on PC or Laptop
 Resistor 220 ohm
 LED
 Breadboard

Note: Make account in thinkercad program to simulate your circuit diagram, and program.
Blinking LED: (What is Blinking Lead)

Procedure:
LED is connected to a digital pin and its number may vary from board type to board type. To make your life
easier, we have a constant that is specified in every board descriptor file. This constant is LED_BUILTIN and
allows you to control the built-in LED easily. Here is the correspondence between the constant and the
digital pin.

Introduction:

Program Code: (Copy and attach the program code)

Pictures: (Attach a picture of the actual experiment)

Circuit diagram: (Attach circuit diagram)

Observations/Conclusion:
Reference:
https://learn.sparkfun.com/tutorials/sik-experiment-guide-for-arduino---v32/experiment-1-blinking-an-led
https://www.arduino.cc/en/Tutorial/Blink

6
Department of Mechanical Engineering
Laboratory Exercise
Higher Colleges of Technology

Laboratory Exercise
Number
Experiment 2 Laboratory Title LED by Button

Course Code MCE 2903 Course Title Sophomore Design Project

Student ID Student Name

Term Date

Instructor

Section
Group
Members

Report Written by:

Note: Students are expected to refrain from all forms of academic dishonesty as defined in the college
policies and as explained and defined by college policies and procedures and directions from teachers
or other college personnel. By signing this cover page you are stating that the work presented is yours
and yours alone. The work includes all figures, tables, calculations, data and text. Please note only
reports that include a signed cover sheet will be graded.

I hereby state that all work submitted in this report is mine and solely mine.

7
Objective:
 To Set LED ON when Button is pressed.
 To Set LED OFF when Button is pressed (the opposite effect).

Equipment Required:
 Arduino Board
 Momentary button or Switch
 10K ohm resistor
 hook-up wires
 breadboard

Switch LED by button:

Procedure: (Write the procedure of the experiment)

Introduction:

Program Code: (Attach the program code)

Pictures: (Attach a picture of the actual experiment)

Circuit diagram: (Attach circuit diagram)

Observations/Conclusion:

Reference:
8
https://www.arduino.cc/en/Tutorial/Button

Department of Mechanical Engineering


Laboratory Exercise
Higher Colleges of Technology

Laboratory Exercise
Experiment 3 Laboratory Title
Number LED By Analog In Out Serial
Course Code MCE 2903 Course Title Sophomore Design Project

Student ID Student Name

Term Date

Instructor

Section
Group
Members

Report Written by:

Note: Students are expected to refrain from all forms of academic dishonesty as defined in the college
policies and as explained and defined by college policies and procedures and directions from teachers
or other college personnel. By signing this cover page you are stating that the work presented is yours
and yours alone. The work includes all figures, tables, calculations, data and text. Please note only
reports that include a signed cover sheet will be graded.

I hereby state that all work submitted in this report is mine and solely mine.

9
Objective: (Write the objective of this experiment)

Equipment Required:
 Arduino Board
 Potentiometer
 Red LED
 220 ohm resistor

Switch LED by button:

Procedure: (Write the procedure of the experiment)

Introduction:

Program Code: (Attach the program code)

Pictures: (Attach a picture of the actual experiment)

Circuit diagram: (Attach circuit diagram)

Observations/Conclusion:

Reference:
https://www.arduino.cc/en/Tutorial/BuiltInExamples/AnalogInOutSerial
10
Department of Mechanical Engineering
Laboratory Exercise
Higher Colleges of Technology

Laboratory Exercise Ultrasonic Distance Sensor in


Experiment 4 Laboratory Title
Number Arduino With Tinkercad
Course Code MCE 2903 Course Title Sophomore Design Project

Student ID Student Name

Term Date

Instructor

Section
Group
Members

Report Written by:

Note: Students are expected to refrain from all forms of academic dishonesty as defined in the college
policies and as explained and defined by college policies and procedures and directions from teachers
or other college personnel. By signing this cover page you are stating that the work presented is yours
and yours alone. The work includes all figures, tables, calculations, data and text. Please note only
reports that include a signed cover sheet will be graded.

I hereby state that all work submitted in this report is mine and solely mine.

11
Objective: (Write the objective of this experiment)

Equipment Required:

Switch LED by button:

Procedure: (Write the procedure of the experiment)

Introduction:

Program Code:
1. Open your Thinkercad software.
2. Using your Thinkercad follow Step 1 to Step 4.
3. Follow Step 3: Code With Blocks, for the program (Make the program in your Thinkercad).
4. Go to the Code and select Block and Txt to see your program.
5. Simulate the program in your thinkercad.
6. Attach the program code

Pictures: (Attach a picture of the experiment)

Circuit diagram: (Attach circuit diagram)

Observations/Conclusion:

Reference:
https://www.instructables.com/Ultrasonic-Distance-Sensor-Arduino-Tinkercad/

12
Department of Mechanical Engineering
Laboratory Exercise
Higher Colleges of Technology

Laboratory Exercise Arduino Temperature Sensor


Experiment 5 Laboratory Title
Number with LED Indicator
Course Code MCE 2903 Course Title Sophomore Design Project

Student ID Student Name

Term Date

Instructor

Section
Group
Members

Report Written by:

Note: Students are expected to refrain from all forms of academic dishonesty as defined in the college
policies and as explained and defined by college policies and procedures and directions from teachers
or other college personnel. By signing this cover page you are stating that the work presented is yours
and yours alone. The work includes all figures, tables, calculations, data and text. Please note only
reports that include a signed cover sheet will be graded.

I hereby state that all work submitted in this report is mine and solely mine.

13
Objective: (Write the objective of this experiment)

Equipment Required:

Arduino Temperature Sensor with LED Indicator:

Procedure: (Write the procedure of the experiment)

Introduction:

Program Code: (Attach the program code)

Pictures: (Attach a picture of the experiment)

Circuit diagram: (Attach circuit diagram)

Observations/Conclusion:

Reference:
http://www.instructables.com/id/Arduino-LEDTemperature-Indicator/

14
Department of Mechanical Engineering
Laboratory Exercise
Higher Colleges of Technology

Laboratory Exercise
Number
Experiment 6 Laboratory Title Calibration

Course Code MCE 2903 Course Title Sophomore Design Project

Student ID Student Name

Term Date

Instructor

Section
Group
Members

Report Written by:

Note: Students are expected to refrain from all forms of academic dishonesty as defined in the college
policies and as explained and defined by college policies and procedures and directions from teachers
or other college personnel. By signing this cover page you are stating that the work presented is yours
and yours alone. The work includes all figures, tables, calculations, data and text. Please note only
reports that include a signed cover sheet will be graded.

I hereby state that all work submitted in this report is mine and solely mine.

15
Objective: (Write the objective of this experiment)

Equipment Required:

Procedure: (Write the procedure of the experiment)

Introduction:

Program Code: (attach the proram code)

Pictures: (Attach a picture you make from Thinker cad when the light is off and when the light is
on)

Circuit diagram: (Attach circuit diagram you draw in Thinker cad)

Observations/Conclusion:

Reference:
https://www.arduino.cc/en/Tutorial/Calibration

16
Department of Mechanical Engineering
Laboratory Exercise
Higher Colleges of Technology
Fading using PWM (to be
Laboratory Exercise
Number Experiment 7 Laboratory Title changed based on the project
nature for each semester)
Course Code MCE 2903 Course Title Sophomore Design Project

Student ID Student Name

Term Date

Instructor

Section
Group
Members

Report Written by:

Note: Students are expected to refrain from all forms of academic dishonesty as defined in the college
policies and as explained and defined by college policies and procedures and directions from teachers
or other college personnel. By signing this cover page you are stating that the work presented is yours
and yours alone. The work includes all figures, tables, calculations, data and text. Please note only
reports that include a signed cover sheet will be graded.

I hereby state that all work submitted in this report is mine and solely mine.

Click here to enter text.


17
Objective: (Write the objective of this experiment)

Equipment Required:

Procedure: (Write the procedure of the experiment)

Introduction:

Program Code: (attach the program in thinker cad, remove unnecessary comment in the
program and simulate, attach in your report).

Pictures: (Attach a picture you make from Thinker cad when the light is off and when the light is
on)

Circuit diagram: (Attach circuit diagram you draw in Thinker cad)

Observations/Conclusion:

Reference:
https://www.arduino.cc/en/Tutorial/Fading

18
Department of Mechanical Engineering
Laboratory Exercise
Higher Colleges of Technology
How to control servo motor with
Laboratory Exercise Potentiometer (to be changed
Experiment 8 Laboratory Title
Number based on the project nature for
each semester)
Course Code MCE 2903 Course Title Sophomore Design Project

Student ID Student Name

Term Date

Instructor

Section
Group
Members

Report Written by:

Note: Students are expected to refrain from all forms of academic dishonesty as defined in the college
policies and as explained and defined by college policies and procedures and directions from teachers
or other college personnel. By signing this cover page you are stating that the work presented is yours
and yours alone. The work includes all figures, tables, calculations, data and text. Please note only
reports that include a signed cover sheet will be graded.

I hereby state that all work submitted in this report is mine and solely mine.

19
Objective:
To control servo motor position and direction using Arduino PWM output and potentiometer connected to
Arduino Analog input.

Equipment Required:
 Arduino or Genuino Board
 Servo Motor
 10k ohm potentiometer
 hook-up wires
 mini breadboard

Procedure: (Write the connection procedure)

Introduction:

Servos are ideal for embedded electronics applications because they do one thing very well that motors cannot
– they can move to a position accurately. By varying the pulse width of the output voltage to a servo, you can
move a servo to a specific position. For example, a pulse of 1.5 milliseconds will move the servo 90 degrees. In
this circuit, you’ll learn how to use PWM (pulse width modulation) to control and rotate a servo.

Program Code: (attach the program in thinker cad, remove unnecessary comment in the
program and simulate, attach in your report).

Pictures: (Attach a picture you make from Thinker cad when the light is off and when the light is
on)

Circuit diagram: (Attach circuit diagram you draw in Thinker cad)

Observations/Conclusion:

Refference:
https://www.instructables.com/Arduino-How-to-Control-Servo-Motor-With-Potentiome/

https://create.arduino.cc/projecthub/Raushancpr/servo-motor-control-with-potentiometer-5d866f
20
Department of Mechanical Engineering
Laboratory Exercise
Higher Colleges of Technology

Sweep (to be changed based on


Laboratory Exercise
Number Experiment 9 Laboratory Title the project nature for each
semester)
Course Code MCE 2903 Course Title Sophomore Design Project

Student ID Student Name

Term Date

Instructor

Section
Group
Members

Report Written by:

Note: Students are expected to refrain from all forms of academic dishonesty as defined in the college
policies and as explained and defined by college policies and procedures and directions from teachers
or other college personnel. By signing this cover page you are stating that the work presented is yours
and yours alone. The work includes all figures, tables, calculations, data and text. Please note only
reports that include a signed cover sheet will be graded.

I hereby state that all work submitted in this report is mine and solely mine.

21
Objective:
Abstract in this lab to learn how to connect servo motor to the Arduino, by applying sweep programming to
control the motor

Equipment Required:
 Arduino Board
 Servo Motor
 hook-up wires

Procedure:
Start to build a circuit by connect the servo motor in the breadboard to the Arduino. Programming Procedure
1- First connect the Arduino to the computer using USP and start Arduino software.
2- Make sure that you are dealing with Arduino board from tools/boards.
3-Enter the codes.

Introduction:
Servos are ideal for embedded electronics applications because they do one thing very well that motors cannot
– they can move to a position accurately. By varying the pulse width of the output voltage to a servo, you can
move a servo to a specific position. For example, a pulse of 1.5 milliseconds will move the servo 90 degrees. In
this circuit, you’ll learn how to use PWM (pulse width modulation) to control and rotate a servo.
Load up the following sketch onto your Arduino. You should find that the servo immediately begins to
turn first in one direction and then back in the other.

Program Code: (attach the program in thinker cad, remove unnecessary comment in the program and
simulate, attach in your report).

Pictures: (Attach a picture you make from Thinker)

Circuit diagram: (Attach circuit diagram you draw in Thinker cad)

Discussion:

Conclusion:

Refference:
https://www.arduino.cc/en/Tutorial/Sweep

22
Department of Mechanical Engineering
Laboratory Exercise
Higher Colleges of Technology

Laboratory Exercise 2 ultrasonic sensor & servo


Experiment 10 Laboratory Title
Number motor
Course Code MCE 2903 Course Title Sophomore Design Project

Student ID Student Name

Term Date

Instructor

Section
Group
Members

Report Written by:

Note: Students are expected to refrain from all forms of academic dishonesty as defined in the college
policies and as explained and defined by college policies and procedures and directions from teachers
or other college personnel. By signing this cover page you are stating that the work presented is yours
and yours alone. The work includes all figures, tables, calculations, data and text. Please note only
reports that include a signed cover sheet will be graded.

I hereby state that all work submitted in this report is mine and solely mine.

Objective:
23
1. Learn the working principle of the ultrasonic sensor.
2. How to program the arduino board by using the Arduino software.
3. How to use 2 ultrasonic sensors and a servo motor to create your very own motion follower
circuit.

Equipment Required:
 Arduino Board
 Ultrasonic sensors(2 pcs.)
 Servo Motor
 hook-up wires
 Breadboard

Procedure:
(Write the Step by step the procedure of your project)

Introduction:
The project uses the Arduino Uno board as the main controller for the whole circuitry. There will be 2
ultrasonic sensors that will serve as the input and triggering device for the servo motor. Once
something is in front of the sensors, (assuming that there is a person or a moving object in front) the
sensors will send the data to the arduino board stating that there is something near it, thus activating
the servo motor to start moving and face the source of the movement.

Program Code: (attach the program in thinker cad, remove unnecessary comment in the program and
simulate, attach in your report).

Circuit diagram: (Attach circuit diagram you draw in Thinker cad)

Discussion:

Conclusion:

Refference:
https://steemit.com/utopian-io/@ted7/arduino-
101-using-2-ultrasonic-sensors-and-servo-motor

24
References for all experiments
Experiment 1: Blinking an LED

Introduction
LEDs are small, powerful lights that are used in many different applications. To start
off, we will work on blinking an LED, the Hello World of microcontrollers. That's right -
it's as simple as turning a light on and off. It might not seem like much, but
establishing this important baseline will give you a solid foundation as we work
toward more complex experiments.

Parts Needed
You will need the following parts:

 1x Breadboard
 1x RedBoard or Arduino Uno R3
 1x LED
 1x 330Ω Resistor
 2x Jumper Wires

Didn't get the SIK?


If you are following through this experiment and didn't get the SIK, we suggest using
these parts:

Suggested Reading
Before continuing on with this experiment, we recommend you be familiar with the
concepts in the following tutorial:

 Light-emitting Diodes - Learn more about LEDs!

Hardware Hookup
Ready to start hooking everything up? Check out the Fritzing diagram and hookup
table below, to see how everything is connected.

Polarized Pay special attention to the component’s markings indicating how to place it on
Componen the breadboard. Polarized components can only be connected to a circuit in one
ts direction. Polarized components are highlighted with a yellow warning triangle, in
the table below.

**Please note: Pay close attention to the LED. The negative side of the LED is the
short leg, marked with a flat edge. **

25
Components like resistors need to have their legs bent into 90° angles in order to
correctly fit the breadboard sockets. You can also cut the legs shorter to make them
easier to work with on the breadboard.

Fritzing Diagram for RedBoard

Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger
image.

Fritzing Diagram for Arduino

26
Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger
image.
Compone RedBoard or Arduino Uno R3 Breadboard Breadboard
nt

LED c2 LED ( + ) c3 LED ( - )

330 a3 (-)
Resistor

Jumper GND (-)


Wire

Jumper PIN 13 e2
Wire

Hookup Table
In the table, polarized components are highlighted in yellow for the whole
row and a warning triangle. Polarized components only be connected to a circuit in
one direction.

Open Your First Sketch


Open Up the Arduino IDE software on your computer. Coding in the Arduino language
will control your circuit. Open the code for Circuit 1 by accessing the “SIK Guide
Code” you downloaded and placed into your “examples” folder earlier.

To open the code go to: File > Examples > SIK Guide Code > Circuit_01

27
You can also copy and paste the following code into the Arduino IDE. Hit upload, and
see what happens!

COPY CODE/*
SparkFun Inventor's Kit
Example sketch 01

BLINKING A LED

Turn an LED on for one second, off for one second,


and repeat forever.

Hardware connections:

Most Arduinos already have an LED and resistor connected to


pin 13, so you may not need any additional circuitry.

But if you'd like to connect a second LED to pin 13, or use


a different pin, follow these steps:

Connect the positive side of your LED (longer leg) to Arduino


digital pin 13 (or another digital pin, don't forget to change
the code to match).

Connect the negative side of your LED (shorter leg) to a


330 Ohm resistor (orange-orange-brown). Connect the other side
of the resistor to ground.

pin 13 _____ + LED - _____ 330 Ohm _____ GND

28
(We always use resistors between the Arduino and and LEDs
to keep the LEDs from burning out due to too much current.)

This sketch was written by SparkFun Electronics,


with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG


*/

// Welcome to Arduino!

// If you're brand-new to this, there will be some new things to


// learn, but we'll jump right in and explain things as we go.

// The Arduino is a tiny computer that runs programs called


// "sketches". These are text files written using instructions
// the computer understances. You're reading a sketch right now.

// Sketches have computer code in them, but also (hopefully)


// "comments" that explain what the code does. Comments and code
// will have different colors in the editor so you can tell them
// apart.

// This is a comment - anything on a line after "//" is ignored


// by the computer.

/* This is also a comment - this one can be multi-line, but it


must start and end with these characters */

// A "function" is a named block of code, that performs a specific,


// well, function. Many useful functions are already built-in to
// the Arduino; others you'll name and write yourself for your
// own purposes.

// All Arduino sketches MUST have two specific functions, named


// "setup()" and "loop()". The Arduino runs these functions
// automatically when it starts up or if you press the reset
// button. You'll typically fill these function "shells" with your
// own code. Let's get started!

// The setup() function runs once when the sketch starts.


// You'll use it for things you need to do first, or only once:

29
void setup()
{
// The Arduino has 13 digital input/output pins. These pins
// can be configured as either inputs or outputs. We set this
// up with a built-in function called pinMode().

// The pinMode() function takes two values, which you type in


// the parenthesis after the function name. The first value is
// a pin number, the second value is the word INPUT or OUTPUT.

// Here we'll set up pin 13 (the one connected to a LED) to be


// an output. We're doing this because we need to send voltage
// "out" of the Arduino to the LED.

pinMode(13, OUTPUT);

// By the way, the Arduino offers many useful built-in functions


// like this one. You can find information on all of them at the
// Arduino website: http://arduino.cc/en/Reference
}

// After setup() finishes, the loop() function runs over and over
// again, forever (or until you turn off or reset the Arduino).
// This is usually where the bulk of your program lives:

void loop()
{
// The 13 digital pins on your Arduino are great at inputting
// and outputting on/off, or "digital" signals. These signals
// will always be either 5 Volts (which we call "HIGH"), or
// 0 Volts (which we call "LOW").

// Because we have an LED connected to pin 13, if we make that


// output HIGH, the LED will get voltage and light up. If we make
// that output LOW, the LED will have no voltage and turn off.

// digitalWrite() is the built-in function we use to make an


// output pin HIGH or LOW. It takes two values; a pin number,
// followed by the word HIGH or LOW:

digitalWrite(13, HIGH); // Turn on the LED

// delay() is a function that pauses for a given amount of time.


// It takes one value, the amount of time to wait, measured in
// milliseconds. There are 1000 milliseconds in a second, so if
30
// you delay(1000), it will pause for exactly one second:

delay(1000); // Wait for one second

digitalWrite(13, LOW); // Turn off the LED

delay(1000); // Wait for one second

// All together, the above code turns the LED on, waits one
// second, turns it off, and waits another second.

// When the computer gets to the end of the loop() function,


// it starts loop() over again. So this program will continue
// blinking the LED on and off!

// Try changing the 1000 in the above delay() functions to


// different numbers and see how it affects the timing. Smaller
// values will make the loop run faster. (Why?)
}

Code to Note
pinMode(13, OUTPUT);
Before you can use one of the Arduino's pins, you need to tell the RedBoard or
Arduino Uno R3 whether it is an INPUT or OUTPUT. We use a built-in "function"
called pinMode() to do this.
digitalWrite(13, HIGH);
When you're using a pin as an OUTPUT, you can command it to be HIGH (output 5
volts), or LOW (output 0 volts).

What You Should See


You should see your LED blink on and off. If it isn't, make sure you have assembled
the circuit correctly and verified and uploaded the code to your board, or see the
troubleshooting section.

31
Experiment 2: Button

Push buttons or switches connect two points in a circuit when you press them. This example
turns on the built-in LED on pin 13 when you press the button.
Hardware
 Arduino Board
 Momentary button or Switch
 10K ohm resistor
 hook-up wires
 breadboard

Circuit

image developed using Fritzing. For more circuit examples, see the Fritzing project page
Connect three wires to the board. The first two, red and black, connect to the two long vertical
rows on the side of the breadboard to provide access to the 5 volt supply and ground. The
third wire goes from digital pin 2 to one leg of the pushbutton. That same leg of the button
connects through a pull-down resistor (here 10K ohm) to ground. The other leg of the button
connects to the 5 volt supply.
When the pushbutton is open (unpressed) there is no connection between the two legs of the
pushbutton, so the pin is connected to ground (through the pull-down resistor) and we read a
LOW. When the button is closed (pressed), it makes a connection between its two legs,
connecting the pin to 5 volts, so that we read a HIGH.

You can also wire this circuit the opposite way, with a pullup resistor keeping the input HIGH,
and going LOW when the button is pressed. If so, the behavior of the sketch will be reversed,
with the LED normally on and turning off when you press the button.
If you disconnect the digital I/O pin from everything, the LED may blink erratically. This is
because the input is "floating" - that is, it will randomly return either HIGH or LOW. That's why
you need a pull-up or pull-down resistor in the circuit.

Schematic

32
Code

/*
Button
Turns on and off a light emitting diode(LED) connected to digital pin 13,
when pressing a pushbutton attached to pin 2.

The circuit:
- LED attached from pin 13 to ground
- pushbutton attached to pin 2 from +5V
- 10K resistor attached to pin 2 from ground

- Note: on most Arduinos there is already an LED on the board


attached to pin 13.

created 2005
by DojoDave <http://www.0j0.org>
modified 30 Aug 2011
by Tom Igoe

This example code is in the public domain.

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

// constants won't change. They're used here to set pin numbers:


const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin

// variables will change:


int buttonState = 0; // variable for reading the pushbutton status

void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}

void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed. If it is, the buttonState is HIGH:


if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
33
digitalWrite(ledPin, LOW);
}
}

Experiment 3: Analog In, Out Serial

This example shows you how to read an analog input pin, map the result to a range from 0 to
255, use that result to set the pulse width modulation (PWM) of an output pin to dim or
brighten an LED and print the values on the serial monitor of the Arduino Software (IDE).

Hardware Required
 Arduino Board
 Potentiometer
 Red LED
 220 ohm resistor

Circuit
image developed using Fritzing. For more circuit examples,
see the Fritzing project page
Connect one pin from your pot to 5V, the center pin to
analog pin 0 and the remaining pin to ground.
Next, connect a 220 ohm current limiting resistor to digital pin 9,
with an LED in series. The long, positive leg (the anode)
of the LED should be connected to the output from the resistor,
with the shorter, negative leg (the cathode) connected to ground.

Schematic

34
Code

In the sketch below, after declaring two pin assignments (analog 0 for our potentiometer and
digital 9 for your LED) and two variables, sensorValue and outputValue, the only things that
you do in the setup() function is to begin serial communication.
Next, in the main loop, sensorValue is assigned to store the raw analog value read from the
potentiometer. Arduino has an analogRead range from 0 to 1023, and an analogWrite range
only from 0 to 255, therefore the data from the potentiometer needs to be converted to fit into
the smaller range before using it to dim the LED.
In order to convert this value, use a function called map():
outputValue = map(sensorValue, 0, 1023, 0, 255);
outputValue is assigned to equal the scaled value from the potentiometer. map() accepts five
arguments: The value to be mapped, the low range and high values of the input data, and the
low and high values for that data to be remapped to. In this case, the sensor data is mapped
down from its original range of 0 to 1023 to 0 to 255.
The newly mapped sensor data is then output to the analogOutPin dimming or brightening the
LED as the potentiometer is turned. Finally, both the raw and scaled sensor values are sent to
the Arduino Software (IDE) serial monitor window, in a steady stream of data.

/*

35
Analog input, analog output, serial output

Reads an analog input pin, maps the result to a range from 0 to 255 and uses

the result to set the pulse width modulation (PWM) of an output pin.

Also prints the results to the Serial Monitor.

The circuit:

- potentiometer connected to analog pin 0.

Center pin of the potentiometer goes to the analog pin.

side pins of the potentiometer go to +5V and ground

- LED connected from digital pin 9 to ground

created 29 Dec. 2008

modified 9 Apr 2012

by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/AnalogInOutSerial

*/

// These constants won't change. They're used to give names to the pins used:

const int analogInPin = A0; // Analog input pin that the potentiometer is
attached to

const int analogOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue = 0; // value read from the pot


36
int outputValue = 0; // value output to the PWM (analog out)

void setup() {

// initialize serial communications at 9600 bps:

Serial.begin(9600);
}

void loop() {

// read the analog in value:

sensorValue = analogRead(analogInPin);

// map it to the range of the analog out:

outputValue = map(sensorValue, 0, 1023, 0, 255);

// change the analog out value:

analogWrite(analogOutPin, outputValue);

// print the results to the Serial Monitor:

Serial.print("sensor = ");

Serial.print(sensorValue);

Serial.print("\t output = ");

Serial.println(outputValue);

// wait 2 milliseconds before the next loop for the analog-to-digital

// converter to settle after the last reading:

delay(2);
}

37
Experiment 4: Ultrasonic Distance Sensor in Arduino With Tinkercad

Let's measure distances with an ultrasonic rangefinder (distance sensor) and Arduino's digital
input. We'll connect up a circuit using a breadboard and use some simple Arduino code to
control a single LED.
You may have already learned to read a pushbutton and PIR motion sensor with Arduino's digital
input, and we'll build on those skills in this lesson.
Ultrasonic rangefinders use sound waves to bounce off objects in front of them, much like bats
using echolocation to sense their environment. The proximity sensor sends out a signal and
measures how long it takes to return. The Arduino program receives this information and
calculates the distance between the sensor and object.
38
Find this circuit on Tinkercad
Explore the sample circuit embedded here by starting the simulation and clicking on the
proximity sensor. This will activate a highlighted area in front of the sensor with a circle "object"
inside. You may need to resize the view if the circle is off screen.
Click and drag the "object" circle closer and further away, noticing the changing distance values
on screen. More LEDs will light up the closer you get to the sensor.

39
In this lesson, you'll build this simulated circuit yourself along side the sample. To optionally
build the physical circuit, gather up your Arduino Uno board, USB cable, solderless breadboard,
three LEDs, resistors (any value from 100-1K), ultrasonic rangefinder, and breadboard wires.
You can follow along virtually using Tinkercad Circuits. You can even view this lesson from within
Tinkercad (free login required)! Explore the sample circuit and build your own right next to it.
Tinkercad Circuits is a free browser-based program that lets you build and simulate circuits. It's
perfect for learning, teaching, and prototyping.
Step 1: Build the LED Circuit

Just as you’ve learned from the introductory lessons, start by wiring up your Arduino and
breadboard with power and ground next to the example circuit, then add the the three red LEDs
to the breadboard, as shown. These will be the "bar graph" lights for visually indicating the
sensor's distance measurement.
Drag an Arduino Uno and breadboard from the components panel to the workplane, next to the
existing circuit.
Connect the 5 volt and ground pins on the Arduino to the power (+) and ground (-) rails on the
breadboard with wires. You can change the wire colors if you want to! Either use the inspector
dropdown or the number keys on your keyboard.
Drag three LEDs on the breadboard in row E, spaced 2 breadboard sockets apart. You can
change the LED color using the inspector that pops up when you click on each one.
Use a 220 Ohm resistor to connect each LED's cathode (left leg) to the ground rail (black) of the
breadboard. You can change a resistor's value by highlighting it and using the dropdown menu.
Connect the LED anodes (right legs) to digital pins 4, 3, and 2 on the Arduino. The LED anode (+)
is the terminal that current flows into. This will connect to the digital output pins on the Arduino.
The cathode (-) is the terminal that current flows from. This will connect to the ground rail.
Step 2: Add Proximity Sensor

40
Proximity sensors come in multiple flavors. Here in Tinkercad Circuits, you can choose between a
three-pin sensor or a four-pin sensor. In general, ultrasonic rangefinders have one pin that
connects to ground, another that connects to 5 volts, a third for sending a signal, and a fourth for
receiving a signal. The 'send' and 'receive' pins are combined into one pin on the three-pin flavor.
In the circuits editor, find the ultrasonic rangefinder in the components drawer. To find the four-
pin sensor, view "All" in the components panel (using the dropdown menu).
Place the sensor on the breadboard to the left of the LEDs in row E, as shown in the figure.
Wire up the sensor so the 5V pin connects to the 5V voltage rail, the GND pin connects to the
ground rail, the SIG or TRIG pin to Arduino pin 7, and, if using the four-pin flavor, the ECHO pin
connects to Arduino pin 6.

Step 3: Code With Blocks

41
Let's use the code blocks editor to listen to the state of the sensor, then make decisions about
which LEDs to light up based on the sensor's value.
Click the "Code" button to open the code editor. The grey Notation blocks are comments for
making note of what you intend for your code to do, but this text isn't required or executed as
part of the program.
Click on the Variables category in the code editor. Create a new variable called distanceThreshold
and use a "set" block to set it to 350 (centimeters).
To store the sensor value, create a variable named "cm".
42
Drag out a "set" block and adjust the dropdown to our new variable cm.
In the Input category, drag out a "read ultrasonic distance sensor on" block, and place it inside
the set block.
Adjust the dropdown menus inside the input block to set the trigger pin to 7, the echo pin to
"same as trigger" and units to cm.
Optionally create a new variable for converting centimeters to inches with a set block and an
arithmetic block to read "set inches to (cm / 2.54)".
Add some serial monitoring blocks to print out the sensor distance in centimeters and inches.
Click the Control category and drag out an if then block, then navigate to Math and drag a
comparator block onto the if block.
In the Variables category, grab the cm variable and the distanceThreshold variable and drag
them into the comparator block, adjusting the dropdown so it reads "if cm > distanceThreshold
then".
Add three digital output blocks inside the if statement to set pins 2, 3, and 4 LOW.
Duplicate this if statement four times and add arithmetic blocks and and/or blocks to create five
total state detection if statements. The first state is "the distance is farther than our threshold"
so no LEDs light up. When the distance is closer than or equal to the distanceThreshold and
greater than distanceThreshold-100, light up only pin 2's LED. When the temperature is between
distanceThreshold-100 and distanceThreshold-250, light up two LEDs. And so on to account for
all the desired states.
Step 4: Ultrasonic Rangefinder Arduino Code Explained

When the code editor is open, you can click the dropdown menu on the left and select "Blocks +
Text" to reveal the Arduino code generated by the code blocks. Follow along as we explore the
code in more detail.

int distanceThreshold = 0;

int cm = 0;

int inches = 0;

Before the setup() , we create variables to store the target distance threshold, as well as the
sensor value in centimeters (cm) and inches. They're called int because they are integers, or any
whole number.

long readUltrasonicDistance(int triggerPin, int echoPin)

pinMode(triggerPin, OUTPUT); // Clear the trigger

digitalWrite(triggerPin, LOW);

delayMicroseconds(2);

// Sets the trigger pin to HIGH state for 10 microseconds

digitalWrite(triggerPin, HIGH);

43
delayMicroseconds(10);

digitalWrite(triggerPin, LOW);

pinMode(echoPin, INPUT);

// Reads the echo pin, and returns the sound wave travel time in microseconds

return pulseIn(echoPin, HIGH);

The next section is a special bit of code for reading the ultrasonic distance sensor. It's called a
function. So far you are familiar with setup() and loop(), but in this sketch, the
function readUltrasonicDistance() is used to describe the sensor code and keep it separate from
the main body of the program. The function definition starts with what type of data the function
will return, or send back to the main program. In this case the function returns a long , which is
a decimal point number with many digits. Next is the name of the function, which is up to you.
Then in parentheses are the arguments the function takes. int triggerPin, int echoPin are the
variable declarations for your sensor's connection pins. The pin numbers will be specified when
you call the function in the main program loop() . Inside the function, these local variables are
used to reference the information you passed to it from the main loop (or from another
function). The function itself sends a signal through the triggerPin and reports back the time it
takes to get the signal back over echoPin.

void setup()

Serial.begin(9600);

pinMode(2, OUTPUT);

pinMode(3, OUTPUT);

pinMode(4, OUTPUT);

Inside the setup, pins are configured using the pinMode() function. The serial monitor
connection is established with Serial.begin . Pins 2, 3, and 4 are configured as outputs to control
the LEDs.

void loop()

// set threshold distance to activate LEDs

44
distanceThreshold = 350;

// measure the ping time in cm

cm = 0.01723 * readUltrasonicDistance(7, 6);

In the main loop, distanceThreshold is set to its target 350cm.

// convert to inches by dividing by 2.54

inches = (cm / 2.54);

Serial.print(cm);

Serial.print("cm, ");

Serial.print(inches);

Serial.println("in");

To convert centimeters to inches, divide by 2.54. Printing to the serial monitor helps you observe
the distance change more granularly than the LED states show alone.

if (cm > distanceThreshold) {

digitalWrite(2, LOW);

digitalWrite(3, LOW);

digitalWrite(4, LOW);

if (cm <= distanceThreshold && cm > distanceThreshold - 100) {

digitalWrite(2, HIGH);

digitalWrite(3, LOW);

digitalWrite(4, LOW);

if (cm <= distanceThreshold - 100 && cm > distanceThreshold - 250) {

digitalWrite(2, HIGH);

digitalWrite(3, HIGH);

digitalWrite(4, LOW);

if (cm <= distanceThreshold - 250 && cm > distanceThreshold - 350) {

digitalWrite(2, HIGH);

digitalWrite(3, HIGH);

45
digitalWrite(4, HIGH);

if (cm <= distanceThreshold - 350) {

digitalWrite(2, HIGH);

digitalWrite(3, HIGH);

digitalWrite(4, HIGH);

delay(100); // Wait for 100 millisecond(s)

The loop's six if statements evaluate for different ranges of distance between 0 and 350cm,
lighting up more LEDs the closer the object.
If you want to see a more obvious change in bar graph lights, you can change the
distanceThreshold variable and/or the range that you are looking at by changing the arguments
in the if() statements. This is called calibration.

Step 5: Build a Physical Circuit (Optional)

If you build a physical version of this circuit, you can try it out with the Arduino software's serial
monitor (magnifying glass button in the upper right of the sketch window), activating the sensor
with your hand, body, notebook, etc.
If using a physical board, put something in front of the sensor and observe the distance reading
using the serial monitor, and set distanceThreshold to that value.
Adjust your different distance threshold "buckets" to a range suitable to your initial value, for
instance if your hand was 60cm away, your ranges might be 60-40, 40-20, and 20-0.
Upload your code again, and try moving in front of the sensor. As the distance shortens, you
should see the LEDs turn on one by one

Step 6: Next, Try...

46
Congratulations! You have learned to detect distance using an ultrasonic sensor. You also
learned about standalone functions in this lesson, and used and the serial monitor to track
changes inside your Arduino. You could expand this project by making it a proximity alarm by
adding a piezo buzzer that turns on when all three LEDs are lit up (closest distance). Consider
swapping the distance sensor for a temperature sensor. Or add motors to create a robot with
obstacle detection!
You can also learn more electronics skills with the free Instructables classes on

Experiment 5: Arduino LED Temperature Indicator

More by the author:

This design is made to keep track of the temperature in a room.


You give it the parameters you want and it will light a blue LED if it is too cold, a red LED if it's too
hot, and a green one if it's just right.
Step 1: Get Parts

You will need:


 Arduino board:
 Breadboard
 Jumper wires
47
 3 220Ω resistors (red-red-brown
 3 LEDs (colors of your choice)
 A temperature sensor (mine is an LM35, but most should work)

Step 2: Make the Circuit

Wire it up:
 Red LED goes to digital pin 4 through one of the resistors and ground

48
 Green LED goes to digital pin 3 though a resistor and ground
 Blue LED goes to digital pin 2 through a resistor and ground
 Pin one (the pin on the left) of the temperature sensor goes to 5v
 Pin two (the pin in the middle) of the temperature sensor goes to analog pin A2
 Pin three (the pin on the right) of the temperature sensor goes to ground

Step 3: Coding

Connect your Arduino to your computer and upload this code:

const int hot = 87; //set hot parameter

const int cold = 75; //set cold parameter

void setup() {

pinMode(A2, INPUT); //sensor

pinMode(2, OUTPUT); //blue

pinMode(3, OUTPUT); //green

49
pinMode(4, OUTPUT); //red

Serial.begin(9600);

void loop() {

int sensor = analogRead(A2);

float voltage = (sensor / 1024.0) * 5.0;

float tempC = (voltage - .5) * 100;

float tempF = (tempC * 1.8) + 32;

Serial.print("temp: ");

Serial.print(tempF);

if (tempF < cold) { //cold

digitalWrite(2, HIGH);

digitalWrite(3, LOW);

digitalWrite(4, LOW);

Serial.println(" It's Cold.");

else if (tempF >= hot) { //hot

digitalWrite(2, LOW);

digitalWrite(3, LOW);

digitalWrite(4, HIGH);

Serial.println(" It's Hot.");

else { //fine

digitalWrite(2, LOW);

digitalWrite(3, HIGH);

digitalWrite(4, LOW);

Serial.println(" It's Fine.");

delay(10);

50
Experiment 6: Calibration
This example demonstrates one techinque for calibrating sensor input. The board takes sensor
readings for five seconds during the startup, and tracks the highest and lowest values it gets.
These sensor readings during the first five seconds of the sketch execution define the
minimum and maximum of expected values for the readings taken during the loop.
Hardware Required
 Arduino board
 LED
 analog sensor (a photoresistor will do)
 10k ohm resistor
 220 ohm resistor
 hook-up wires
 breadboard
Circuit
Analog sensor (e.g. potentiometer, light sensor) on Analog input 2. LED on Digital pin 9.
click the image to enlarge

51
image developed using Fritzing. For more circuit examples, see the Fritzing project page

Connect an LED to digital pin 9 with a 220 ohm current limiting resistor in series. Connect a
photoresistor to 5V and then to analog pin 0 with a 10K ohm resistor to ground .

Schematic

52
Code

Before the setup, you set initial values for the minimum and maximum like so:

int sensorMin = 1023; // minimum sensor value


int sensorMax = 0; // maximum sensor value

These may seem backwards. Initially, you set the minimum high and read for anything lower
than that, saving it as the new minimum. Likewise, you set the maximum low and read for
anything higher as the new maximum, like so:

// calibrate during the first five seconds


while (millis() < 5000) {
sensorValue = analogRead(sensorPin);
// record the maximum sensor value
if (sensorValue > sensorMax) {
sensorMax = sensorValue;
}
// record the minimum sensor value
if (sensorValue < sensorMin) {
sensorMin = sensorValue;
}
}

This way, any further readings you take can be mapped to the range between this minimum
and maximum like so:

// apply the calibration to the sensor reading


sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);

53
Experiment 7: Fading
This example demonstrates the use of analog output (Pulse Width Modulation (PWM) ) to fade
an LED. 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.

Hardware Required
 Arduino board
 LED
 220 ohm resistor
 hook-up wires
 breadboard
Circuit
An LED connected to digital output pin 9 through a 220 ohm resistor.
54
click the image to enlarge

Schematic

55
image developed using Fritzing. For more circuit examples, see the Fritzing project page
Code
In this example two loops are executed one after the other to increase and then decrease the
value of the output on pin 9.

/*

Fading

This example shows how to fade an LED using the analogWrite() function.

The circuit:

- LED attached from digital pin 9 to ground.

created 1 Nov 2008

by David A. Mellis
56
modified 30 Aug 2011

by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Fading

*/

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

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

}
}

58
Experiment 8: How To Control Servo Motor with Potentiometer

Step 1: Tutorial
Control the position of a RC (hobby) servo motor with your Arduino and a potentiometer.
You not connect directly the servo motor to arduino. Use external power to the servo.
SG90 Mini RC servo motors can be used. This can damage the Arduino MG996 instant high
torque.
MG996 Stall Torque: 9.4kg / cm (4.8V) - 11 kg / cm (6.0V) and Operating voltage: 4.8 ~ 6.6v.

Step 2: Hardware Required

Hardware Required
 Arduino or Genuino Board
 Servo Motor
 10k ohm potentiometer
 hook-up wires
 mini breadboard

Step 3: Circuit

5 More Images
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

59
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.

Step 4: Code

60
Experiment 9: Sweep
Sweeps the shaft of a RC servo motor back and forth across 180 degrees.
This example makes use of the Arduino servo library.
Hardware Required
 Arduino Board
 Servo Motor
 hook-up wires
Circuit
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 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.

images developed using Fritzing. For more circuit examples, see the Fritzing project page

Schematic

61
Code

/* Sweep
by BARRAGAN <http://barraganstudio.com>
This example code is in the public domain.

modified 8 Nov 2013


by Scott Fitzgerald
http://www.arduino.cc/en/Tutorial/Sweep
*/

#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
62
}
}

Experiment 10: Arduino 101: Using 2 ultrasonic sensors and servo motor

What Will I Learn?


 You will learn the working principle of the ultrasonic sensor.
 You will learn how to program the arduino board by using the Arduino software.
 You will learn how to use 2 ultrasonic sensors and a servo motor to create your very own motion
follower circuit.

Requirements

Hardware
 Arduino Uno
 Ultrasonic sensors(2 pcs.)
 Servo motor
 Jumper wire
 Breadboard
 Computer
 USB type A to B cable

Software
 Arduino software/ Arduino IDE
Knowledge
 Basic electronics and programming knowledge

Difficulty
63
 Intermediate
Project description
This project uses the Arduino Uno board as the main controller for the whole circuitry. There will
be 2 ultrasonic sensors that will serve as the input and triggering device for the servo motor.
Once something is in front of the sensors, (assuming that there is a person or a moving object in
front) the sensors will send the data to the arduino board stating that there is something near it,
thus activating the servo motor to start moving and face the source of the movement.

Component description
Arduino Uno - is a type of arduino board that is used regularly by specialist and hobbyist
because it is the most robust of the bunch. It is stuffed with a microcontroller board that is based
on ATMega328P with 14 advanced I/O pins (6 are PWM outputs), 6 analog inputs, 16 Mhz quartz
crystal, a power jack, a USB port, an ICSP header and a reset button.
Ultrasonic sensor - is a type of device that can measure the distance to an object by the use of
sound waves. It measures the distance by sending sound waves at a specific frequency and
listening for that sound wave to bounce back. By recording the elapsed time between the sound
wave being produced and the sound wave bouncing back, it is able to compute the distance
between the sonar sensor and the object.
Servo Motor - is a type of motor that is built for precise control of the angular or linear position,
velocity and acceleration. It consists of a suitable motor that is coupled to a sensor for position
feedback.

Tutorial Contents
Motion Follower circuit [2 ultrasonic sensors and servo motor]
Step 1: Gather the parts
 The following components electronics.

64
Step 2: Construct the circuit

Connect the Sources


 Connect the 5V pin of the arduino board to the top/bottom row of the breadboard(the
connections here are horizontally connected).
 Connect the GND pin of the arduino board to the top/bottom row of the breadboard but make
sure not to place the sources together as this will short the arduino board and may cause
damage.

Connect the sensors


1st sensor
 Connect the VCC pin of the ultrasonic sensor to the positive terminal in the breadboard.
 Connect the GND pin of the ultrasonic sensor to the negative terminal in the breadboard.
 Connect the TRIG pin of the ultrasonic sensor to pin number 11 of the arduino board.
 Connect the ECHO pin of the ultrasonic sensor to pin number 10 of the arduino board.

65
2nd sensor
 Connect the VCC pin of the ultrasonic sensor to the positive terminal in the breadboard.
 Connect the GND pin of the ultrasonic sensor to the negative terminal in the breadboard.
 Connect the TRIG pin of the ultrasonic sensor to pin number 13 of the arduino board.
 Connect the ECHO pin of the ultrasonic sensor to pin number 12 of the arduino board.

Connecting the Servo motor


 Connect the positive terminal of the servo motor(red wire) to the voltage source grid in the
breadboard.
 Connect the ground terminal of the servo motor (black wire) to the negative terminal in the
breadboard.
 Connect the data wire(yellow wire) of the servo motor to pin number 9 of the arduino board.

66
 Note: Use color coded wires so that you will not get confuse with the wirings.

Step 3: Programming
 Connect the arduino board to the computer by using the usb cable type a to b.

Once connection has been established, open the Arduino IDE and go to Tools > Board: >
then select the Arduino/Genuino Uno.

67
 Copy the codes below and paste it into your sketch in the Arduino IDE.
#include <Servo.h>
Servo myservo; //creates servo object
const int echopin1 = 10; //sets echopin1 @pin 10
const int trigpin1 = 11; //sets trigpin1 @pin 11
const int echopin2 = 12; //sets echopin2 @pin 12
const int trigpin2 = 13; //sets trigpin2 @pin 13
const int servo = 9; //sets servo @pin 9
long Rightduration, Leftduration, Rightinch, Leftinch; //establishes the variables of the
duration and sets distance in inches
int threshold = 10; //Sets the sensor threshold at 10 inches
int angle = 80; //Sets the Initial angle
void setup()
{
myservo.attach(9); //attaches the servo on pin 9
}
void loop()
{
pinMode(trigpin1, OUTPUT); //trigpin1 is set as output
digitalWrite(trigpin1, LOW); //sets the trigpin1 to give low pulse
delayMicroseconds(3); //duration is 3 microseconds
digitalWrite(trigpin1, HIGH); //sets the trigpin1 to give high pulse
delayMicroseconds(5); //duration is 5 microseconds
digitalWrite(trigpin1, LOW);
Rightduration = pulseIn(echopin1, HIGH); //reads high pulse
pinMode(trigpin2, OUTPUT); //trigpin2 is set as output
digitalWrite(trigpin2, LOW); //sets the trigpin2 to give low pulse
delayMicroseconds(3); //duration is 3 microseconds
digitalWrite(trigpin2, HIGH); //sets the trigpin2 to give high pulse
delayMicroseconds(5); //duration is 5 microseconds
digitalWrite(trigpin2, LOW);
Leftduration = pulseIn(echopin2, HIGH); //reads high pulse

68
//this will convert the elapsed time into the distance
Rightinch = microsecondsToInches(Rightduration);
Leftinch = microsecondsToInches(Leftduration);
follow(); //follows the movement
}
long microsecondsToInches(long microseconds)
{
// The speed of sound is 340 m/s or 73.746 microseconds per inch.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance traveled.
return microseconds / 74 / 2;
}
void follow() //conditions for the follow command
{
if (Leftinch <= threshold || Rightinch <= threshold)
{
if (Leftinch + 2 < Rightinch)
{
angle = angle - 2;
}
if (Rightinch + 2 < Leftinch)
{
angle = angle + 2;
}
}
if (angle > 160)
{
angle = 160;
}
if (angle < 0)
{
angle = 0;
}
myservo.write(angle);
}

What this code does is this, first it declares the pins of the ultrasonic sensors and servo as cons
int meaning it will be a read-only variable and cannot be changed. Then it declares the duration
and sets the distance as inches. The distance threshold is set to 10 inches with an initial angle of
80 degrees of the servo motor. Now, once the ultrasonic sensors detect something within the 10
inches threshold, it will send that data to the Arduino Uno which will then activate the servo
motor to face the source of the movement. This will follow that object if its within 10 inches with
2 degrees per step, the range of angle that it can follow is from 0 - 160 degrees. Once the source
of movement is gone, it will stop the servo from moving and will keep waiting until a new
movement has been detected.

69
 After typing the code into your Arduino IDE, click Verify to compile and save your sketch
and this will also check for any errors in the program.

70
 If there is no error found in the program, click the Upload button to install the program into
the Arduino board.

Step 4: Testing
 Once the installation is complete, remove the Arduino Uno from the computer and plug in your
battery pack to start the Arduino board. Once it has started, the circuit should already be
functioning. Hover you hand within the 10 inches range from the sensor, this should detect your
hand and will move to face in the direction of your hand. Slowly move your hand sideways and
this should follow it by 2 degrees per step until it reaches its 160 degrees or 0 degrees.
 Now, remove your hand away from the sensor, this should stop the servo motor from moving
from its place.
 If none is working, redo the previous steps and make sure that you have followed each step
carefully.
 Also check your connections as the wire from the breadboard will easily get loosen especially if
the wire is not properly fitted into the slot of the breadboard.

71

You might also like