Professional Documents
Culture Documents
MCE-2903 Lab Manual
MCE-2903 Lab Manual
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
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.
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.
4
Department of Mechanical Engineering
Laboratory Exercise
Higher Colleges of Technology
Laboratory Exercise
Number
Experiment 1 Laboratory Title LED Blinking
Term Date
Instructor
Section
Group
Members
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:
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
Term Date
Instructor
Section
Group
Members
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
Introduction:
Observations/Conclusion:
Reference:
8
https://www.arduino.cc/en/Tutorial/Button
Laboratory Exercise
Experiment 3 Laboratory Title
Number LED By Analog In Out Serial
Course Code MCE 2903 Course Title Sophomore Design Project
Term Date
Instructor
Section
Group
Members
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
Introduction:
Observations/Conclusion:
Reference:
https://www.arduino.cc/en/Tutorial/BuiltInExamples/AnalogInOutSerial
10
Department of Mechanical Engineering
Laboratory Exercise
Higher Colleges of Technology
Term Date
Instructor
Section
Group
Members
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:
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
Observations/Conclusion:
Reference:
https://www.instructables.com/Ultrasonic-Distance-Sensor-Arduino-Tinkercad/
12
Department of Mechanical Engineering
Laboratory Exercise
Higher Colleges of Technology
Term Date
Instructor
Section
Group
Members
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:
Introduction:
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
Term Date
Instructor
Section
Group
Members
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:
Introduction:
Pictures: (Attach a picture you make from Thinker cad when the light is off and when the light is
on)
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
Term Date
Instructor
Section
Group
Members
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.
Equipment Required:
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)
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
Term Date
Instructor
Section
Group
Members
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
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)
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
Term Date
Instructor
Section
Group
Members
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).
Discussion:
Conclusion:
Refference:
https://www.arduino.cc/en/Tutorial/Sweep
22
Department of Mechanical Engineering
Laboratory Exercise
Higher Colleges of Technology
Term Date
Instructor
Section
Group
Members
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).
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
Suggested Reading
Before continuing on with this experiment, we recommend you be familiar with the
concepts in the following tutorial:
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.
Having a hard time seeing the circuit? Click on the Fritzing diagram to see a bigger
image.
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
330 a3 (-)
Resistor
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.
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
Hardware connections:
28
(We always use resistors between the Arduino and and LEDs
to keep the LEDs from burning out due to too much current.)
// Welcome to Arduino!
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().
pinMode(13, OUTPUT);
// 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").
// All together, the above code turns the LED on, waits one
// second, turns it off, and waits another second.
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).
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
created 2005
by DojoDave <http://www.0j0.org>
modified 30 Aug 2011
by Tom Igoe
http://www.arduino.cc/en/Tutorial/Button
*/
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);
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.
The circuit:
by Tom Igoe
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
void setup() {
Serial.begin(9600);
}
void loop() {
sensorValue = analogRead(analogInPin);
analogWrite(analogOutPin, outputValue);
Serial.print("sensor = ");
Serial.print(sensorValue);
Serial.println(outputValue);
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.
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.
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
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
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()
44
distanceThreshold = 350;
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.
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(2, HIGH);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
45
digitalWrite(4, HIGH);
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
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.
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
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
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
void setup() {
49
pinMode(4, OUTPUT); //red
Serial.begin(9600);
void loop() {
Serial.print("temp: ");
Serial.print(tempF);
digitalWrite(2, HIGH);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, HIGH);
else { //fine
digitalWrite(2, LOW);
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
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:
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:
This way, any further readings you take can be mapped to the range between this minimum
and maximum like so:
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:
by David A. Mellis
56
modified 30 Aug 2011
by Tom Igoe
http://www.arduino.cc/en/Tutorial/Fading
*/
void setup() {
void loop() {
analogWrite(ledPin, fadeValue);
57
delay(30);
analogWrite(ledPin, fadeValue);
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.
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.
#include <Servo.h>
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
62
}
}
Experiment 10: Arduino 101: Using 2 ultrasonic sensors and servo motor
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
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.
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