Configuration 2: Obstacle Avoiding Robot
Use ultrasonic distance sensing and a servo scan to make safe turns.
The obstacle avoiding robot uses the ultrasonic sensor to measure distance. The servo turns the sensor left and right, so Arduino Nano can choose the safer path.
Mode-specific circuit schematic
Pin and power rules
Use the Li-ion pack for motor power through L293D VCC2, and regulated 5V for Arduino Nano logic and modules.
All grounds must be common, otherwise the Arduino signal has no reliable reference.
The Arduino programs on this page match this pin plan: D5/D6 PWM, D8-D11 motor direction, D2-D3 Bluetooth, D4/D7 ultrasonic, D12 servo, A0-A5 sensors/RF.
Step-by-step build
- Build the base motor wiring first.
- Mount the ultrasonic sensor on the micro servo.
- Connect TRIG to D4, ECHO to D7, and servo signal to D12.
- Start with a 25 cm stop distance.
- Place books or boxes as obstacles and observe decisions.
Arduino Nano program
// Arduino Nano Obstacle Avoiding Robot
#include <Servo.h>
Servo scanner;
const int trigPin = 4, echoPin = 7, servoPin = 12;
const int ENA = 5, IN1 = 8, IN2 = 9, ENB = 6, IN3 = 10, IN4 = 11;
void setup() {
pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT);
pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
pinMode(ENB, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT);
scanner.attach(servoPin);
scanner.write(90);
}
void loop() {
scanner.write(90);
delay(180);
int front = distanceCm();
if (front > 25) {
forward(150);
} else {
stopMotors();
backward(140); delay(250); stopMotors();
int leftSpace = look(150);
int rightSpace = look(30);
scanner.write(90);
if (leftSpace > rightSpace) { left(150); delay(450); }
else { right(150); delay(450); }
}
}
int look(int angle){ scanner.write(angle); delay(350); return distanceCm(); }
int distanceCm(){
digitalWrite(trigPin, LOW); delayMicroseconds(2);
digitalWrite(trigPin, HIGH); delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long us = pulseIn(echoPin, HIGH, 30000);
if (us == 0) return 999;
return us / 58;
}
void forward(int s){ drive(HIGH,LOW,HIGH,LOW,s); }
void backward(int s){ drive(LOW,HIGH,LOW,HIGH,s); }
void left(int s){ drive(LOW,HIGH,HIGH,LOW,s); }
void right(int s){ drive(HIGH,LOW,LOW,HIGH,s); }
void stopMotors(){ analogWrite(ENA,0); analogWrite(ENB,0); }
void drive(int a1,int a2,int b1,int b2,int s){
digitalWrite(IN1,a1); digitalWrite(IN2,a2);
digitalWrite(IN3,b1); digitalWrite(IN4,b2);
analogWrite(ENA,s); analogWrite(ENB,s);
}Do and don't
- Use Arduino Nano as the controller.
- Keep battery negative and all module GND pins connected.
- Test motors with wheels lifted first.
- Use a voltage divider for HC-05 RX if Arduino TX is 5 V.
- Power servo from a stable 5 V source.
- Do not short Li-ion cells.
- Do not connect motors directly to Arduino Nano pins.
- Do not mix loose wires without labels.
- Do not run high motor speed during first tests.
- Do not assume every RF module has the same pinout.