A car that drives until something is in the way, looks left and right with a servo-mounted HC-SR04, and turns towards the open side.
Guide
An HC-SR04 sends out a burst of ultrasound and times the echo. Mounted on a servo "neck", it can look straight ahead while driving and glance left and right when something gets close.
9 parts · about ₹1,861
What you need
Step 1 of 4
Assemble the chassis and motors, then wire the L298N exactly like the line follower: ENA → D5, IN1 → D7, IN2 → D8, ENB → D6, IN3 → D9, IN4 → D10, with the ENA/ENB jumpers removed and the grounds shared.
Why pins 5 and 6 for speed? The Servo library takes over the timer behind pins 9 and 10, so analogWrite stops working there. Pins 9 and 10 are still fine for plain on/off direction signals.
Milestone
Drive wired
Step 2 of 4
neck.write(90), then fit the horn pointing straight ahead.Milestone
Sensor looks around
The servo sweeps smoothly and the sensor faces forward at 90°.
Step 3 of 4
| 1 | #include <Servo.h> |
| 2 | |
| 3 | const int TRIG = 12, ECHO = 11, SERVO_PIN = 3; |
| 4 | const int ENA = 5, IN1 = 7, IN2 = 8; // left motor |
| 5 | const int ENB = 6, IN3 = 9, IN4 = 10; // right motor |
| 6 | const int SPEED = 160, SAFE_CM = 25; |
| 7 | |
| 8 | Servo neck; |
| 9 | |
| 10 | long distanceCm() { |
| 11 | digitalWrite(TRIG, LOW); delayMicroseconds(2); |
| 12 | digitalWrite(TRIG, HIGH); delayMicroseconds(10); |
| 13 | digitalWrite(TRIG, LOW); |
| 14 | long us = pulseIn(ECHO, HIGH, 30000); // give up after 30 ms (about 5 m) |
| 15 | return us == 0 ? 500 : us / 58; // no echo = nothing in range |
| 16 | } |
| 17 | |
| 18 | long look(int angle) { |
Milestone
It avoids obstacles
Drives across a room and turns away from a wall without touching it.
Step 4 of 4
drive calls in the last if.SPEED.Labs
All labs