Arduino UNO Ultrasonic Distance Sensor with DC Motor Control
View and Edit Project In Cirkit Designer
Circuit Documentation
Summary
This circuit consists of an Arduino UNO microcontroller, an HC-SR04 Ultrasonic Sensor, a DC Motor, and a 9V Battery. The Arduino UNO is used to control the DC Motor based on the distance measured by the Ultrasonic Sensor. The 9V Battery powers the Arduino UNO.
Component List
Arduino UNO
- Description: A microcontroller board based on the ATmega328P.
- Pins: UNUSED, IOREF, Reset, 3.3V, 5V, GND, Vin, A0, A1, A2, A3, A4, A5, SCL, SDA, AREF, D13, D12, D11, D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0
HC-SR04 Ultrasonic Sensor
- Description: A sensor used to measure distance by using ultrasonic waves.
- Pins: VCC, TRIG, ECHO, GND
DC Motor
- Description: A motor that converts electrical energy into mechanical energy.
- Pins: pin 1, pin 2
9V Battery
- Description: A battery used to power the Arduino UNO.
- Pins: -, +
Wiring Details
Arduino UNO
- Vin: Not connected
- 5V: Connected to VCC of HC-SR04 Ultrasonic Sensor
- GND: Connected to GND of HC-SR04 Ultrasonic Sensor
- D11: Connected to pin 1 of DC Motor
- D10: Connected to ECHO of HC-SR04 Ultrasonic Sensor
- D9: Connected to TRIG of HC-SR04 Ultrasonic Sensor
HC-SR04 Ultrasonic Sensor
- VCC: Connected to 5V of Arduino UNO
- TRIG: Connected to D9 of Arduino UNO
- ECHO: Connected to D10 of Arduino UNO
- GND: Connected to GND of Arduino UNO
DC Motor
- pin 1: Connected to D11 of Arduino UNO
- pin 2: Not connected
9V Battery
- +: Not connected
- -: Not connected
Code Documentation
// defines pin numbers for the ultrasonic sensor.
const int trigPin = 9;
const int echoPin = 10;
// defines pin numbers for motors.
const int motor = 11;
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(motor, OUTPUT); // Sets the Motor as an Output
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 microseconds
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;
// Prints the distance on the Serial Monitor
Serial.print("Distance = ");
Serial.println(distance);
if (distance < 5) {
digitalWrite(motor, HIGH);
} else {
digitalWrite(motor, LOW);
}
}
This code sets up the pins for the ultrasonic sensor and the motor. It continuously measures the distance using the ultrasonic sensor and turns the motor on if the distance is less than 5 cm, otherwise, it turns the motor off.