Hello, i am trying to make a line follower 4x4 robot using Arduino Uno, L298N motor driver and two IR modules, and it works fine. then i wanted to add an ultrasonic sensor for obstacle avoidance. And here comes my problem, the ultrasonic sensor works well when tested alone, however when i add the ultrasonic code to the line follower code, the robot does not follow the line anymore and does not avoid obstacles either.
Would you please help me. Thank you.
Here's the code.
#include <NewPing.h>
int motorA_E1 = 9;
int motorA_E2 = 10;
int motorA_speed = 5;
int motorB_E3 = 11;
int motorB_E4 = 12;
int motorB_speed= 6;
int left_sensor_pin = 2;
int right_sensor_pin = 3;
int trigPin = A0;
int echoPin = A1;
int max_distance =100;
NewPing sonar(trigPin, echoPin, max_distance);
void setup() {
pinMode(motorA_E1, OUTPUT);
pinMode(motorA_E2, OUTPUT);
pinMode(motorB_E3, OUTPUT);
pinMode(motorB_E4, OUTPUT);
pinMode(motorA_speed, OUTPUT);
pinMode(motorB_speed, OUTPUT);
pinMode(left_sensor_pin, INPUT);
pinMode(right_sensor_pin, INPUT);
Serial.begin(9600);
}
void loop() {
boolean left_sensor_state=digitalRead(left_sensor_pin);
boolean right_sensor_state=digitalRead(right_sensor_pin);
delay(70);
int distance =sonar.ping_cm();
Serial.print("distance= ");
Serial.println(distance);
if (distance == 0)
{
distance = 30;
Serial.print("distance= ");
Serial.println(distance);
}
if(distance<10)
{
off();
Serial.println("stop,, obstacle");
}
if (left_sensor_state==0 and right_sensor_state==0)
{
analogWrite (motorA_speed,100);
analogWrite (motorB_speed,100);
forward();
Serial.println("forward");
}
else if (left_sensor_state==1 and right_sensor_state==0)
{
analogWrite (motorA_speed,150);
analogWrite (motorB_speed,150);
turnLeft();
Serial.println("turn left");
}
else if (left_sensor_state==0 and right_sensor_state==1)
{
analogWrite (motorA_speed,150);
analogWrite (motorB_speed,150);
turnRight();
Serial.println("turn right");
}
else if (left_sensor_state==1 and right_sensor_state==1 )
{
analogWrite (motorA_speed,0);
analogWrite (motorB_speed,0);
off();
Serial.println("stop bc of double straps");
}
}
void forward(){
digitalWrite(motorA_E1,HIGH);
digitalWrite (motorA_E2,LOW);
digitalWrite(motorB_E3,LOW);
digitalWrite (motorB_E4,HIGH);
}
void off() {
digitalWrite(motorA_E1,LOW);
digitalWrite (motorA_E2,LOW);
digitalWrite(motorB_E3,LOW);
digitalWrite (motorB_E4,LOW);
}
void turnRight(){
digitalWrite(motorA_E1,HIGH);
digitalWrite (motorA_E2,LOW);
digitalWrite(motorB_E3,HIGH);
digitalWrite (motorB_E4,LOW);
}
void turnLeft() {
digitalWrite(motorA_E1,LOW);
digitalWrite (motorA_E2,HIGH);
digitalWrite(motorB_E3,LOW);
digitalWrite (motorB_E4,HIGH);
}