I'm developing an object avoiding robot with Arduino UNO board, two motors DC 3-6V, an ultrasonic sensor HC-SRO4, and the driver l298n, all these supplied with 3 lithium batteries of 3.7V each (11,1V in total). I've programmed the code and it works perfectly. The problem is that when I turn on the battery and the robot turns on, before starting with the code that I uploaded it, the motor on the left starts working forward crazy for about 5 seconds. Do you know how to solve it? I would be really grateful if you could help me, every contribution is perfect. Thanks.
Here's the code I'm using, just in case the error is there:
const int pinTrigger=6;
const int pinEcho=5;
long distance=0;
long time =0;
const int IN1 = 13;
const int IN2 = 12;
const int IN3 = 11;
const int IN4 = 10;
const int ENA = 3;
const int ENB = 9;
void setup() {
pinMode(pinTrigger,OUTPUT);
pinMode(pinEcho,INPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(ENA, OUTPUT);
pinMode(ENB, OUTPUT);
}
void loop() {
mesure();
if(distance < 19) {
obstacle();
}
if(distance > 18) {
forward();
}
}
void mesure() {
digitalWrite(pinTrigger,LOW);
delayMicroseconds(2);
digitalWrite(pinTrigger,HIGH);
delayMicroseconds(10);
digitalWrite(pinTrigger, LOW);
time = pulseIn(pinEcho, HIGH);
distance = time/29/2 ;
}
void forward(){
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
analogWrite(ENA, 90);
analogWrite(ENB, 90);
}
void right (){
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
analogWrite(ENA, 150);
analogWrite(ENB, 200);
}
void stop(){
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
analogWrite(ENA, 0);
analogWrite(ENB, 0);
}
void obstacle (){
stop();
delay(300);
right();
delay(500);
stop();
delay(100);
}