Hello,
i managed to make a 4x4w robot to follow a line using L298N driver and IR modules. i want the robot to follow a line and then comes back following the same line, so i used four IR modules; two on the robot front, two on the back.
but my problem is that i could not write a proper code to do this, after trying so many times, i came here needing some guidance.
this sketch is for following a line but the robot does not come back, i would like to know what to add to this sketch to do what i want/
thank you.
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;
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);
}
void loop() {
boolean left_sensor_state=digitalRead(left_sensor_pin);
boolean right_sensor_state=digitalRead(right_sensor_pin);
if (left_sensor_state==0 and right_sensor_state==0)
{
analogWrite (motorA_speed,120);
analogWrite (motorB_speed,120);
forward();
}
else if (left_sensor_state==1 and right_sensor_state==0)
{
analogWrite (motorA_speed,180);
analogWrite (motorB_speed,180);
turnLeft();
}
else if (left_sensor_state==0 and right_sensor_state==1)
{
analogWrite (motorA_speed,180);
analogWrite (motorB_speed,180);
turnRight();
}
else if (left_sensor_state==1 and right_sensor_state==1)
{
analogWrite (motorA_speed,0);
analogWrite (motorB_speed,0);
off();
}
}
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);
}