License: MIT, chosen by its author.
A stalled motor draws many times its running current. Size the supply, wires and driver for the stall current, fit a fuse, and keep fingers clear of moving parts.
Provided as is by its author and not checked by breadboardhub. Check ratings, tolerances and heat before you build. Do not use for mains voltage or anything safety critical. Building safely
// Robot car: two DC motors on an L298N-style driver and an HC-SR04.
// It drives forward. When something is closer than 25 cm it stops,
// backs up, turns right, then drives on.
// Power the motors from their own battery, not from the Uno's 5V pin,
// and join the two grounds.
const int LEFT_EN = 5; // PWM: left motor speed
const int LEFT_IN1 = 7;
const int LEFT_IN2 = 8;
const int RIGHT_EN = 6; // PWM: right motor speed
const int RIGHT_IN1 = 9;
const int RIGHT_IN2 = 10;
const int TRIG = 2;
const int ECHO = 4;
const int SPEED = 200; // 0 to 255
const int TOO_CLOSE_CM = 25;
// One motor: dir 1 forward, -1 backward, 0 stop.
void motor(int en, int in1, int in2, int dir, int speed) {
digitalWrite(in1, dir > 0 ? HIGH : LOW);
digitalWrite(in2, dir < 0 ? HIGH : LOW);
analogWrite(en, dir == 0 ? 0 : speed);
}
void drive(int left, int right) {
motor(LEFT_EN, LEFT_IN1, LEFT_IN2, left, SPEED);
motor(RIGHT_EN, RIGHT_IN1, RIGHT_IN2, right, SPEED);
}
// Distance in cm, or 0 when nothing echoes back within 30 ms.
int distanceCm() {
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long echo = pulseIn(ECHO, HIGH, 30000);
return (echo + 29) / 58;
}
void setup() {
Serial.begin(9600);
pinMode(LEFT_EN, OUTPUT);
pinMode(LEFT_IN1, OUTPUT);
pinMode(LEFT_IN2, OUTPUT);
pinMode(RIGHT_EN, OUTPUT);
pinMode(RIGHT_IN1, OUTPUT);
pinMode(RIGHT_IN2, OUTPUT);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
}
void loop() {
int cm = distanceCm();
if (cm > 0 && cm < TOO_CLOSE_CM) {
Serial.print("Obstacle at ");
Serial.print(cm);
Serial.println(" cm: stop, back up, turn");
drive(0, 0);
delay(200);
drive(-1, -1);
delay(400);
drive(1, -1); // left forward, right backward: turn right
delay(400);
} else {
drive(1, 1);
delay(60);
}
}
@design{breadboardhub/arduino-robot-car,
title = {Arduino Uno: robot car},
author = {breadboardhub},
url = {https://www.breadboardhub.com/breadboardhub/arduino-robot-car},
version = {1.0.0}
}