In this exercise, you will use an ultrasonic sensor to detect objects in front of a two-wheel-drive electric car. The electric motors are driven by a L298N board and the Arduino is actually powered by the 5V logic supply included on the board. We supply the board with 9V but significantly reduce the power delivered to the motors by using PWM and lowering the percentage of time the motors actually receive power. This project is ripe for a lot of side projects being added on to it. After you do the basics, try to take it a step further!
Parts:
1 – Arduino Uno
1 – L298N Motor Driver Board
1 – 9V Battery
1 – Robot Chassis
1 – Ultrasonic Sensor
Assorted Wires
Wiring:
When downloading your code, remove the wire going from 5V on the L298N to the Vin on Arduino. Once code is uploaded, remove USB and replace wire.
Ultrasonic
Arduino
Vcc
5V
Trig
13
Echo
12
GND
Gnd
Code:
//here we declare what each pin will be on arduino board
//you may need to change the pins for left and right once you see what your car does
int rf = 4; // to in1 on L298N
int rb = 5; // to in2 on L298N
int rpwm = 6; // to ENA on L298N
int lf = 8; // to in4 on L298N
int lb = 7; // to in3 on L298N
int lpwm = 9; //to ENB on L298N
int trigPin = 13;
int echoPin = 12;
void setup() {
Serial.begin(9600);
// establishes each pin as an input/output
pinMode(rf, OUTPUT);
pinMode(rb, OUTPUT);
pinMode(rpwm, OUTPUT);
pinMode(lf, OUTPUT);
pinMode(lb, OUTPUT);
pinMode(lpwm, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
//gives the user half a second to put down the car after turning the switch delay(500);
}
void loop() {
// get the distance away from the sensor for an object
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
//print distance for troubleshooting
if (distance >= 200 || distance <= 0) {
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(20);
// decide how to drive based on ultrasonic sensor
if (distance < 15) {
//back up
digitalWrite(rf, LOW);
digitalWrite(rb, HIGH);
analogWrite(rpwm, 80);
digitalWrite(lf, LOW);
digitalWrite(lb, HIGH);
analogWrite(lpwm, 80);
delay(500);
// turn left
digitalWrite(rf, HIGH);
digitalWrite(rb, LOW);
analogWrite(rpwm, 80);
digitalWrite(lf, LOW);
digitalWrite(lb, LOW);
analogWrite(lpwm, 80);
delay(300);
}
else {
//drive forward
digitalWrite(rf, HIGH);
digitalWrite(rb, LOW);
analogWrite(rpwm, 100);
digitalWrite(lf, HIGH);
digitalWrite(lb, LOW);
analogWrite(lpwm, 80);
delay(20);
}
}