This project involves using ultrasonic sensors to detect walls so that a robot can navigate a course. The basic function of this code is to have my robot race around a track for three laps and then stop at the end of the third lap. The way I decided to count how may laps would be to count how many walls it sees in front of it. If it sees a wall with it's front sensor, it will turn 90 degrees left and keep going. Eventually, assuming everything goes well, it should be finished with the three laps after seeing a wall in front 12 times.
Anyway, my question involves counting how many walls that it sees. See my code below to see what I thought would work.
#include <Ultrasonic.h>
#include <Servo.h>
#include <ESP8266WiFi.h>
#include <math.h>
#define motorRpin D0
#define motorLpin D2
Servo motorR;
Servo motorL;
Ultrasonic usFront (D8, D5);
Ultrasonic usRight (D9, D6);
Ultrasonic usLeft (D10, D7);
int distFront = 0;
int distRight = 0;
int distLeft = 0;
int wall = 0;
void setup() {
Serial.begin(115200);
motorR.attach(motorRpin);
motorL.attach(motorLpin);
motorR.write(90); //Right Forward = 0
motorL.write(90); //Left Forward = 180
}
void loop() {
distFront = usFront.read(CM) * 10;
distRight = usRight.read(CM) * 10;
distLeft = usLeft.read(CM) * 10;
// Serial.println(distFront);
// Serial.println(distRight);
// Serial.println(distLeft);
Serial.println(wall);
//delay(100);
if (wall < 12 && distFront > 150 && distRight > 40 && distLeft > 40) {
motorR.write(52); //move forward if no obstacles
motorL.write(180);
}
if (wall < 12 && distFront <= 150) {
motorR.write(90); //stop if wall in front
motorL.write(90);
delay(500);
motorR.write(0); //turn left 90 degrees
motorL.write(0);
delay(150);
motorR.write(52);
motorL.write(180); //go forwards again
wall++;
distFront = 1000;
delay(500);
}
if (wall < 12 && distFront > 150 && distRight <= 40) {
motorR.write(50); //turn left slightly if wall detected on right
motorL.write(90);
delay(20);
motorR.write(52); //forwards again
motorL.write(180);
}
if (wall < 12 && distFront > 150 && distLeft <= 40) {
motorR.write(90); //turn right slightly if wall detected on left
motorL.write(130);
delay(25);
motorR.write(52); //forwards again
motorL.write(180);
}
if (wall = 12 && distFront <= 150) {
motorR.write(90); //stop when race is finished
motorL.write(90);
wall = 13;
}
}
The robot functions perfectly besides being able to count walls. I thought that putting "wall++" in the "if (wall < 12 && distFront <= 150)" statement would increment the wall variable every time those conditions were met, but it seems that it stays at zero forever. Any idea on how to fix this/better approach this? I considered using a for or while loop but couldn't quite get those to function either. My programming skills aren't excellent, so any help is greatly appreciated. Thank you!