Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
In this project, we will learn how to make an automatic hand sanitizer using an ultrasonic sensor and a servo motor.
The ultrasonic sensor is a device that uses high-frequency sound waves (ultrasound) to detect objects, measure distances, or detect changes in the environment. It emits sound waves and measures the time it takes to bounce off an object and return to the sensor. Visit Exploring the Power of Ultrasonic Sensors: A Brief Introduction for more information.
The servo motor is a device that can rotate to a specific angle or position, making it ideal for applications such as moving robotic arms, steering mechanisms, and camera gimbals. Visit SG90 Servo Motor Basics: What You Need to Know for more information.
For more information, visit Getting to Know Your Arduino Uno: A Beginner’s Guide to Its Components.
The ultrasonic sensor detects the presence of a hand approximately 5 cm away. Once a hand is detected, the sensor sends a signal to the Arduino. The Arduino then activates the servo motor by sending an output signal. In response, the servo motor rotates and triggers the dispenser pump.
| Ultrasonic Sensor | Arduino |
| VCC | 3.3V |
| GND | GND |
| Trig | D6 |
| Echo | D5 |
| Servo Motor | Arduino |
| VCC | 5V |
| GND | GND |
| SIG | D3 |
Connect the Arduino to your computer using a USB cable. Upload the program to the Arduino through the Arduino IDE software. Visit Getting Started with Arduino IDE: A Beginner’s Guide to Coding and Creating for more information.
Warning: Disconnect the USB cable or adapter before connecting the battery.
#include <Servo.h>
// defines pins numbers
const int trigPin = 6;
const int echoPin = 5;
long duration;
int distance;
Servo myServo; // create servo object
void setup() {
myServo.attach(3); // attach to digital pin 3
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
void loop() {
distance = calculateDistance();
myServo.write(0); // move to 0 degrees
if ( distance < 5){
myServo.attach(3);
myServo.write(160); // move to 160 degrees
delay(500);
myServo.write(0); // move to 0 degrees
delay(1000);
}
else{
myServo.detach();
}
}
int calculateDistance(){
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
return distance;
}