The goal is to make the robot aware of obstacles in front of him, so he can change direction and avoid them. In the previous article we made the robot move – now we will give him some autonomy.
Watch video directly on YouTube
Ultrasonic sensor

Circuit
Code
The code below contains only an “ultrasonic” extension to DC motor control using an H-Bridge from the previous article. When the robot detects an obstacle in front of it, he turns around (random degree) and continues moving forward. This functionality could be easily extended to keep turning and detecting obstacles at the same time – so the robot would not turn randomly, but start moving forward only when no object is detected.
int EchoPin = 2; // connect Pin 2 to Echo at HC-SR04 int TrigPin = 3; // connect Pin 3 to Trig at HC-SR04 unsigned long Time_Echo_us = 0; unsigned long Len_cm = 0; void setup() {
// Set EchoPin as input, to receive measure result pinMode(EchoPin, INPUT);
// Set TrigPin as output, to send a pulse to start pinMode(TrigPin, OUTPUT); delay(5000); } void loop() { if (motorsInStandby) return; // robot is in standby mode // Drive both motors forward motorDrive(leftMotor, 1, 128); motorDrive(rightMotor, 1, 128);
// begin to send a high pulse to begin measuring digitalWrite(TrigPin, HIGH);
// set this high pulse width as 50us delayMicroseconds(50);
// end this high pulse digitalWrite(TrigPin, LOW);
// calculate the pulse width at EchoPin Time_Echo_us = pulseIn(EchoPin, HIGH);
// a valid pulse width should be between (1, 60000) if ((Time_Echo_us < 60000) && (Time_Echo_us > 1)) {
// calculate the distance in cm Len_cm = (Time_Echo_us / 2) / 29; if (Len_cm < 10) { // very close object (<10 cm), stop the robot (standby) motorStop(leftMotor); motorStop(rightMotor); motorsInStandby = true; } else if (Len_cm < 40) { // turn around motorDrive(leftMotor, 1, 128); motorDrive(rightMotor, 0, 128); delay(random(220, 800)); } } }
Leave a Reply