Hi,
I'm attempting to build an obstacle avoiding car using both IR and ultrasonic sensing. My first step is to correctly program the vehicle using only IR sensing and have built a basic, two-motor vehicle. Below I have attached my first crack at the code. My issue is that the code is only calling the STOP, RIGHT, BACK, and FORWARD functions and never runs the LEFT. I have tested the sensors and they all work as designed. Additionally, I know that since BACK runs, the sensors are properly wired and being read. My issue must be with the code, but I don't know what it is. Any help is greatly appreciated. JD
int RIR = 3;
int LIR = 2;
#define ENA 5
#define ENB 6
#define IN1 17
#define IN2 16
#define IN3 15
#define IN4 14
#define carSpeed 100
void forward(){
analogWrite(ENA, carSpeed);
analogWrite(ENB, carSpeed);
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
Serial.println("Forward");
}
void back() {
analogWrite(ENA, carSpeed);
analogWrite(ENB, carSpeed);
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
Serial.println("Back");
}
void left() {
analogWrite(ENA, carSpeed);
analogWrite(ENB, carSpeed);
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
Serial.println("Left");
}
void right() {
analogWrite(ENA, carSpeed);
analogWrite(ENB, carSpeed);
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
Serial.println("Right");
}
void stop() {
digitalWrite(ENA, LOW);
digitalWrite(ENB, LOW);
Serial.println("Stop!");
}
void setup() {
Serial.begin(9600);
pinMode(RIR, INPUT);
pinMode(LIR, INPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(ENA, OUTPUT);
pinMode(ENB, OUTPUT);
stop();
}
void loop() {
int LIR = digitalRead(2);
int RIR = digitalRead(3);
if((RIR == LOW) && (LIR == LOW)) {
stop();
delay(200);
back();
delay(400);
right();
delay(800);
}
else if((LIR == LOW)&& (RIR==HIGH)) {
stop();
delay(500);
right();
delay(200);
}
else if((RIR = LOW) && (LIR == HIGH)) {
stop();
delay(500);
left();
delay(200);
}
else {
forward();
}
}