IntermediateRobotics about 240 min
Obstacle Avoiding Car
An ultrasonic sensor on a servo scans for obstacles; the car backs up, looks left and right and picks the clearer way.
Steps
Build the base
Mount the TT motors and wheels on the chassis.
Fit the scanning head
Glue or screw the HC-SR04 onto the SG90 servo horn and mount the servo at the front centre.
Wire everything
Servo signal to D11, HC-SR04 Trig to A0 and Echo to A1, L298N as in the sketch (ENA 5, IN1 7, IN2 8, ENB 6, IN3 9, IN4 10).
Upload and test
Test with the wheels off the ground first, then let it loose on the floor.
Code
#include <Servo.h>
Servo head;
const int TRIG = A0, ECHO = A1;
const int ENA = 5, IN1 = 7, IN2 = 8, ENB = 6, IN3 = 9, IN4 = 10;
long distanceCm() {
digitalWrite(TRIG, LOW); delayMicroseconds(2);
digitalWrite(TRIG, HIGH); delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long t = pulseIn(ECHO, HIGH, 30000);
return t == 0 ? 400 : t * 0.0343 / 2;
}
void drive(int l, int r) {
digitalWrite(IN1, l > 0); digitalWrite(IN2, l < 0); analogWrite(ENA, abs(l));
digitalWrite(IN3, r > 0); digitalWrite(IN4, r < 0); analogWrite(ENB, abs(r));
}
void setup() {
pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT);
pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
pinMode(ENB, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT);
head.attach(11); head.write(90);
}
void loop() {
if (distanceCm() > 25) { drive(180, 180); delay(30); return; }
drive(0, 0); delay(100);
drive(-150, -150); delay(300); drive(0, 0);
head.write(30); delay(450); long right = distanceCm();
head.write(150); delay(450); long left = distanceCm(); // swap if your servo is mounted the other way
head.write(90); delay(300);
if (left > right) drive(-160, 160); else drive(160, -160); // spin toward the clearer side
delay(350); drive(0, 0);
}Notes. Power the motors from a separate battery pack through the L298N and share GND with the Arduino.