Obstacle Detection Ultrasonic Sensor Program
Obstacle Detection Ultrasonic Sensor Program
Components Needed:
1. Arduino Board
2. Motor Driver Shield (with appropriate motor connections)
3. Servo Motor
4. Ultrasonic Sensor
5. Switch
6. Jumper Wires
Connection Steps:
Step 1: Motor Driver Shield
1. Connect the motor driver shield to the Arduino board.
Step 5: Switch
5. Connect the switch to the Arduino:
- Connect one end of the switch to the `switchPin` (Pin 12 on the Arduino).
- Connect the other end of the switch to the Arduino's GND.
Step 6: Power
6. Power the Arduino through USB or an external power source.
Step 8: Test
8. Power on the circuit and press the switch to see if the robot moves forward.
- The ultrasonic sensor will detect obstacles, and if the distance is less than 20 cm,
the robot will stop and turn.
Additional Notes:
- Ensure that the motors, servo, and ultrasonic sensor are properly connected, and their
power requirements are met.
- Double-check the pin assignments in the program to match your hardware
connections.
- Open the Serial Monitor in the Arduino IDE to view distance readings for debugging.
Note: Ensure that you have the Arduino IDE installed on your computer, and you
should be able to compile and upload the code to your Arduino board without needing
any additional libraries
Code is given below, You can copy paste. Be Careful about connections.
// Include libraries
#include <Servo.h>
// Define variables
int distance; // variable to store distance measured by ultrasonic sensor
int speed = 150; // variable to control speed of motors
Servo servo; // create servo object to control servo motor
void setup() {
// Initialize motor pins as output
pinMode(motor1Pin1, OUTPUT);
pinMode(motor1Pin2, OUTPUT);
pinMode(motor2Pin1, OUTPUT);
pinMode(motor2Pin2, OUTPUT);
pinMode(motor3Pin1, OUTPUT);
pinMode(motor3Pin2, OUTPUT);
pinMode(motor4Pin1, OUTPUT);
pinMode(motor4Pin2, OUTPUT);
void loop() {
// Check if switch is pressed
if(digitalRead(switchPin) == HIGH) {
// Move forward
moveForward();
// Function to turn
void turn() {
// Turn servo motor to 90 degrees
servo.write(90);
// Calculate distance in cm
int distance = duration * 0.034 / 2;
// Code sourced from Arduino website for ultrasonic sensor and servo motor control.
If you’re Still Confused, Look below what we’ve done in the
code.
6. Speed Variable:
You have a `speed` variable that controls the speed of your motors. You might want to
experiment with different speed values to find the optimal speed for your robot.