Hi,
I am trying to make an obstacle avoiding bot using arduino. I have used Li ion 7.4 V battery to power the L298Ndriver and the driver in turn is powering the arduino.
However the motors are not spinning the wheels together or are working haphazardly. I am unable to get them to work according to the code.
I am attaching my code and picture of my connections below:
'
#include <Servo.h>
int p = 0;
int r = 13;
Servo motor;
float dist_front;
float dist_left;
float dist_right;
const int trig = 9;
const int echo = 10;
//motor driver
int speedl = 5;
int pin1 = 4;
int pin2 = 7;
int pin3 = 1;
int pin4 = 2;
int speedr = 3;
void setup() {
Serial.begin(9600);
motor.attach(6);
motor.write(180);
pinMode(6, OUTPUT);
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
//motor driver
pinMode(speedl, OUTPUT);
pinMode(speedr, OUTPUT);
pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
pinMode(pin3, OUTPUT);
pinMode(pin4, OUTPUT);
}
void loop() {
motor.write(90);
dist_front = measuring_distance(trig, echo);
while (dist_front > 15) {
go_forward();
dist_front = measuring_distance(trig, echo);
}
stop();
dist_front = measuring_distance(trig, echo);
delay(2000);
motor.write(180);
dist_left = measuring_distance(trig, echo);
delay(2000);
motor.write(0);
dist_right = measuring_distance(trig, echo);
delay(2000);
motor.write(90);
go_backward();
delay(1000);
if (dist_right > dist_left) {
//turn right
turn_right();
} else {
//turn left
turn_left();
}
}
float measuring_distance(int trigpin, int echopin) {
float distance;
float duration;
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin, HIGH);
delayMicroseconds(10);
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin, HIGH);
distance = (0.034 * duration) / 2;
return (distance);
}
void turn_left() {
digitalWrite(pin1, HIGH);
digitalWrite(pin2, LOW);
analogWrite(speedl, 100);
digitalWrite(pin3, HIGH);
digitalWrite(pin4, LOW);
analogWrite(speedr, 100);
delay(662);
analogWrite(speedl, 0);
analogWrite(speedr, 0);
}
void turn_right() {
digitalWrite(pin4, HIGH);
digitalWrite(pin3, LOW);
analogWrite(speedr, 100);
digitalWrite(pin1, LOW);
digitalWrite(pin2, HIGH);
analogWrite(speedl, 100);
delay(662);
analogWrite(speedl, 0);
analogWrite(speedr, 0);
delay(1000);
}
void go_forward() {
digitalWrite(pin1, LOW);
digitalWrite(pin2, HIGH);
analogWrite(speedl, 100);
digitalWrite(pin3, HIGH);
digitalWrite(pin4, LOW);
analogWrite(speedr, 100);
}
void stop() {
analogWrite(speedl, 0);
analogWrite(speedr, 0);
}
void go_backward() {
digitalWrite(pin1, HIGH);
digitalWrite(pin2, LOW);
analogWrite(speedl, 100);
digitalWrite(pin4, HIGH);
digitalWrite(pin3, LOW);
analogWrite(speedr, 100);
}
'
Please help with this