本教程是的一部分: Elegoo智能汽车套件教程
本文下方有其他视频的链接。
Elegoo Robot Car Video #4: Avoid Obstacles and Stop. Follow Obstacles in a Straight Path
🤖 Lesson 4: Obstacle Detection & Avoidance – ELEGOO Smart Robot Car V3
In this lesson, we explore an essential robotics concept: obstacle detection and avoidance using an ultrasonic sensor with the ELEGOO Smart Robot Car V3. By integrating the HC-SR04 ultrasonic module, we program the car to detect obstacles, stop, reverse, and reroute—mimicking intelligent navigation behavior commonly found in autonomous systems.
This tutorial is ideal for learners and developers seeking to understand sensor-based motion logic in embedded robotics. All necessary code is available for download below.
🧠How It Works – Ultrasonic Sensor
The HC-SR04 ultrasonic sensor emits a sound wave and calculates the distance based on the echo time it receives. It can detect obstacles from a few centimeters up to 4 meters away. In this project, we use the sensor to trigger motor actions when an object comes too close to the front of the robot.
🧪 Demonstration Flow
The video walks through the real-time application of this logic:
Distance is displayed via serial monitor.
The robot stops when an obstacle is detected at close range.
Advanced versions follow the contour of an obstacle or backtrack and redirect intelligently.
🎬 Video Chapters
00:00 – Start
01:06 – Introduction
03:33 – Code: Ultrasonic Distance Sensor Explained
07:18 – Demonstration: Measuring Distance
07:47 – Obstacle Avoidance and Stop
11:39 – Demonstration: Stop at Obstacle
13:00 – Code: Follow Obstacle
15:40 – Demonstration: Avoid and Reverse
📠Download Section
The full Arduino code and required wiring diagrams are available below. This lesson is part of the ELEGOO Smart Robot Car series and introduces real-world robotics logic essential for autonomous driving and environmental awareness.
/**************
* Elegoo Smart Robot Car
*
* This is the sketch to stop the car when it reaches an obstacle in front of the car.
*
* Code updated by Ahmad Shamshiri on November 30, 2019, in Ajax, Ontario, Canada
*
* Watch video instructions for this code: https://youtu.be/wtyw-Q_AlB0
*
* Original code can be obtained from: www.elegoo.com
*
*
* Get this code and other Arduino codes from Robojax.com.
Learn Arduino step by step in a structured course with all material, wiring diagrams, and libraries
all in one place. Purchase my course on Udemy.com: http://robojax.com/L/?id=62
****************************
Get early access to my videos via Patreon and have your name mentioned at the end of every
video I publish on YouTube here: http://robojax.com/L/?id=63 (watch until the end of this video for a list of my Patrons)
****************************
or make a donation using PayPal: http://robojax.com/L/?id=64
* * This code is "AS IS" without warranty or liability. Free to be used as long as you keep this note intact.*
* This code has been downloaded from Robojax.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
//*** start of ultrasonic sensor settings
#include <NewPing.h>
int Echo = A4;
int Trig = A5;
#define MAX_DISTANCE 200
const int distanceToAvoid = 20;//in cm
int rightDistance = 0, leftDistance = 0, middleDistance = 0;
NewPing sonar(Trig, Echo, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
//***** end of ultrasonic sensor settings
#include <Servo.h> //servo library
Servo myservo; // create servo object to control servo
#define ENA 5
#define ENB 6
#define IN1 7
#define IN2 8
#define IN3 9
#define IN4 11
#define carSpeed 100
void forward(){
analogWrite(ENA, carSpeed);
analogWrite(ENB, carSpeed);
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
Serial.println("Forward");
}
void back() {
analogWrite(ENA, carSpeed);
analogWrite(ENB, carSpeed);
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
Serial.println("Back");
}
void stop() {
digitalWrite(ENA, LOW);
digitalWrite(ENB, LOW);
Serial.println("Stop!");
}
void setup() {
myservo.attach(3); // attach servo on pin 3 to servo object
myservo.write(80); //setservo position according to scaled value
Serial.begin(9600);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(ENA, OUTPUT);
pinMode(ENB, OUTPUT);
stop();
}
void loop() {
middleDistance = getDistance();
Serial.print("Distance:");
Serial.print(middleDistance);
Serial.println("cm");
if(middleDistance <= distanceToAvoid) {
stop();
delay(2000);
}
else {
forward();
}
}//loop end
/*
* Gets the corrected distance using the NewPing library.
* The library returns 0 when the distance is higher than MAX_DISTANCE.
* This is fixed so that it never returns zero because even if the obstacle is
* in contact with the sensor, it doesn't return zero.
* Written by Ahmad Shamshiri on November 16, 2019 at 16:33 in Ajax, Ontario, Canada
* www.Robojax.com
*/
int getDistance()
{
int d = sonar.ping_cm();
if(d ==0)
{
return MAX_DISTANCE;
}else{
return d;
}
}//getDistance() end
/**************
* Elegoo Smart Robot Car
*
* This is the sketch to stop the car when it reaches an obstacle in front of the car and
* if an obstacle comes closer to the robot, the robot should go backwards
*
* Written by Ahmad Shamshiri on November 30, 2019, in Ajax, Ontario, Canada
*
* Watch video instructions for this code: https://youtu.be/wtyw-Q_AlB0
*
* Original code can be obtained from: www.elegoo.com
*
*
* Get this code and other Arduino codes from Robojax.com.
Learn Arduino step by step in a structured course with all materials, wiring diagrams, and libraries
all in one place. Purchase my course on Udemy.com: http://robojax.com/L/?id=62
****************************
Get early access to my videos via Patreon and have your name mentioned at the end of every
video I publish on YouTube here: http://robojax.com/L/?id=63 (watch until the end of this video for a list of my Patrons)
****************************
or make a donation using PayPal: http://robojax.com/L/?id=64
* * This code is "AS IS" without warranty or liability. Free to be used as long as you keep this note intact.*
* This code has been downloaded from Robojax.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
//*** start of ultrasonic sensor settings
#include <NewPing.h>
int Echo = A4;
int Trig = A5;
#define MAX_DISTANCE 200
const int distanceToAvoid = 20;//cm
const int distanceGoBack = 10;//cm
int rightDistance = 0, leftDistance = 0, middleDistance = 0;
NewPing sonar(Trig, Echo, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
//***** end of ultrasonic sensor settings
#include <Servo.h> //servo library
Servo myservo; // create servo object to control servo
#define ENA 5
#define ENB 6
#define IN1 7
#define IN2 8
#define IN3 9
#define IN4 11
#define carSpeed 100
int getDistance();
void forward(){
analogWrite(ENA, carSpeed);
analogWrite(ENB, carSpeed);
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
Serial.println("Forward");
}
void back() {
analogWrite(ENA, carSpeed);
analogWrite(ENB, carSpeed);
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
Serial.println("Back");
}
void stop() {
digitalWrite(ENA, LOW);
digitalWrite(ENB, LOW);
Serial.println("Stop!");
}
void setup() {
myservo.attach(3); // attach servo on pin 3 to servo object
myservo.write(80); //setservo position according to scaled value
Serial.begin(9600);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(ENA, OUTPUT);
pinMode(ENB, OUTPUT);
stop();
}
void loop() {
delay(100);
middleDistance = getDistance();
Serial.print("Distance:");
Serial.print(middleDistance);
Serial.println("cm");
if(middleDistance < distanceToAvoid && middleDistance > distanceGoBack )
{
stop();
delay(1000);
}else if(middleDistance < distanceGoBack)
{
back();
}
else{
forward();
}
}
/*
* gets the corrected distance using the NewPing library.
* The library returns 0 when the distance is higher than MAX_DISTANCE.
* This is fixed so that it never returns zero because even if the obstacle is
* in contact with the sensor, it doesn't return zero.
* Written by Ahmad Shamshiri on November 16, 2019 at 16:33 in Ajax, Ontario, Canada
* www.Robojax.com
*/
int getDistance()
{
int d = sonar.ping_cm();
if(d ==0)
{
return MAX_DISTANCE;
}else{
return d;
}
}//getDistance() end
资源与参考
-
外部Elegoo智能机器人车网页(获取所有代码)elegoo.com
文件📁
没有可用的文件。