Obstacle avoider with an ultrasonic sensor
A two-wheel robot roams a room of boxes: it pings ahead with its ultrasonic sensor every 60 ms, turns on the spot when something is closer than 35 cm, and…
Control · Intermediate
In a real product: Robot vacuum (Consumer electronics): A robot vacuum slows and turns before it touches a chair leg: its first line of defence is a distance sensor at the front.
An obstacle avoider is the simplest robot that reacts to the world: it measures the distance ahead, and when something is near, it turns away. The robot here roams a 1.6 m × 1.0 m room with three boxes. Open the World tool's Arena view to watch it, the ultrasonic sensor's beam and the distance it measures.
What you'll learn
- Timing an ultrasonic echo with
pulseIn, and why it has a timeout - Pinging no faster than the echoes die away
- A two-state machine (drive, turn) with hysteresis: turn at 35 cm, drive again only past 70 cm
- Where a single fixed sensor is blind: a corner just outside its beam
How it works
The ultrasonic sensor at the robot's front sends a burst when TRIG has a 10 µs pulse; ECHO then goes high for the round trip to the nearest wall in its beam, which spreads about 15° each way: 58.3 µs for each centimetre. The sketch pings every 60 ms with a 12 ms timeout (2 m); nothing within reach reads as 400 cm.
While driving, anything closer than 35 cm switches it to turning on the spot to the right. It turns for at least 250 ms and until the way ahead is clear for 70 cm: the gap between the two thresholds is hysteresis, so it does not flick between the two states at one distance. The robot's chassis is 136 mm across, wider than the beam close up, so the margin also keeps a box's corner that the beam only just misses from clipping a wheel.
Try this
- Run it with the Arena view open and follow the robot with the camera's Follow button. Does it ever touch a box?
- Lower
NEAR_CMto 15: it gets closer before turning, and sooner or later clips a corner (the HUD counts collisions). - Drop the 250 ms minimum turn: watch it hesitate at the edge of a box.
- Try another seed on the arena: the boxes move a few centimetres. Does the avoider still never touch one?
- The Warehouse run challenge asks for more than avoiding: reach the charging pad in the far corner, with the wheel encoders to measure the way.
sketch.ino
// Obstacle avoider: drive ahead; when the ultrasonic sensor sees something closer than 35 cm, turn on the spot to
// the right until the way is clear for 70 cm, then drive on.
// Left motor: AIN1 7, AIN2 8, PWMA 5. Right motor: BIN1 10, BIN2 11, PWMB 6. STBY 9. Ultrasonic TRIG 4, ECHO 12.
const int AIN1 = 7, AIN2 = 8, PWMA = 5, BIN1 = 10, BIN2 = 11, PWMB = 6, STBY = 9, TRIG = 4, ECHO = 12;
const int CRUISE = 115, TURN = 100; // duty out of 255
const float NEAR_CM = 35, CLEAR_CM = 70;
enum Mode { DRIVE, TURNING };
Mode mode = DRIVE;
float distanceCm = 400;
unsigned long lastPing = 0, turnStart = 0, lastPrint = 0;
void motor(int in1, int in2, int pwm, int duty) {
digitalWrite(in1, duty >= 0 ? HIGH : LOW);
digitalWrite(in2, duty >= 0 ? LOW : HIGH);
analogWrite(pwm, abs(duty));
}
// One ping: the echo's length is the round trip, 58.3 us a centimetre. Nothing within 2 m reads as 400 cm.
float ping() {
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
unsigned long us = pulseIn(ECHO, HIGH, 12000);
return us ? us / 58.3 : 400;
}
void setup() {
Serial.begin(115200);
pinMode(AIN1, OUTPUT); pinMode(AIN2, OUTPUT); pinMode(PWMA, OUTPUT);
pinMode(BIN1, OUTPUT); pinMode(BIN2, OUTPUT); pinMode(PWMB, OUTPUT);
pinMode(STBY, OUTPUT); pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT);
digitalWrite(STBY, HIGH);
}
void loop() {
unsigned long now = millis();
// A ping every 60 ms, so one echo has died away before the next.
if (now - lastPing < 60) return;
lastPing = now;
distanceCm = ping();
if (mode == DRIVE && distanceCm < NEAR_CM) { mode = TURNING; turnStart = now; }
// Turn for at least 250 ms, so a corner the beam only just misses is left well behind.
if (mode == TURNING && distanceCm > CLEAR_CM && now - turnStart > 250) mode = DRIVE;
if (mode == DRIVE) { motor(AIN1, AIN2, PWMA, CRUISE); motor(BIN1, BIN2, PWMB, CRUISE); }
else { motor(AIN1, AIN2, PWMA, TURN); motor(BIN1, BIN2, PWMB, -TURN); }
if (now - lastPrint >= 250) {
lastPrint = now;
Serial.print("cm:"); Serial.print(distanceCm, 0);
Serial.println(mode == DRIVE ? " drive" : " turn");
}
}