Ultrasonic Smart Car
Last updated
Last updated
//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);
}
}