Obstacle avoidance fire fighting car

#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <WebSocketsServer.h>
#include "index.h"
#include <ESP32Servo.h>
Servo servo;  // create servo object to control a servo

//setting  sr04 pins
#define trigger_pin 23
#define echo_pin 35

//setting servo pin 
#define SERVO_PIN 13 

// Setting Motor A
int enable1Pin = 14;
int motor1Pin1 = 27;
int motor1Pin2 = 26;

//Settin Motor B
int enable2Pin = 32;
int motor2Pin3 = 25;
int motor2Pin4 = 33;

//keys for car movement
#define CMD_STOP 0
#define CMD_FORWARD 1
#define CMD_BACKWARD 2
#define CMD_LEFT 4
#define CMD_RIGHT 8

// define pins for flame sensor
#define FlamePinForawrdAnlog 4 
#define FlamePinRight 15
#define FlamePinLeft  18

// define pins for gas sensor
#define GasSensorDi 17

// pin 12 that connects to the relay to control the pump
#define RELAY_PIN   12

//pins for siren led and buzzer
//siren
#define LedBlue 2
#define LedRed 21 
#define Buzzer 19

//vars for falme sensor read front analog rest is digital
int FlameCheckForawrdAnalog;
int FlameCheckRight;
int FlameCheckLeft;


//vars for gas sensor read
int GasSensorD;
int three60forward = 0;//var for 360 turn 

//time vars for front sensor 
const unsigned long eventFrontSensorInterval = 200;
unsigned long previouseventFrontSensor = 0;
//time vars for front sensor trigger and movement forward
const unsigned long eventCarMovementInterval = 200;
unsigned long previouseventCarMovement = 0;
//time vars for front sensor trigger and movment left and right 
const unsigned long eventCarSideMovementInterval = 200;
unsigned long previouseventCarSideMovement = 0;
//time vars for siren
const unsigned long eventSirenInterval = 500;
unsigned long previousEventSiren = 0;
//var for movement forward on the gas condition
const unsigned long eventCarMovementGasInterval = 2500;
unsigned long previouseventGasCarMovement = 0;

const char* ssid = "Galaxy A52s 5GA0A0";     // wifi name
const char* password = "zmuz6970";  // wifi password

AsyncWebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);  // WebSocket server on port 81

void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) {
  switch (type) {
    case WStype_DISCONNECTED:
      Serial.printf("[%u] Disconnected!\n", num);
      break;
    case WStype_CONNECTED:
      {
        IPAddress ip = webSocket.remoteIP(num);
        Serial.printf("[%u] Connected from %d.%d.%d.%d\n", num, ip[0], ip[1], ip[2], ip[3]);
      }
      break;
    case WStype_TEXT:
      //Serial.printf("[%u] Received text: %s\n", num, payload);
      String angle = String((char*)payload);
      int command = angle.toInt();
      Serial.print("command: ");
      Serial.println(command);
      
      delay(200);
      int CurrentDistance = DistanceMeasure();
      delay(200);

      switch (command) {
        case CMD_STOP:
          Serial.println("Stop");
          StopCar();
          break;
        case CMD_FORWARD:
        {
          CurrentDistance = DistanceMeasure();
          if(CurrentDistance >= 20){//movement forward if no obstacle ahead
          Serial.println("Move Forward");
          CAR_moveForwardWifi();
          }
          else
          { Serial.println("obstacle ahead");
            obstacleAvoid();}

          } 
        break;
        case CMD_BACKWARD:
        {
          CurrentDistance = DistanceMeasure();
          Serial.println("Move Backward");
          CAR_moveBackwardWifi();
          if(CurrentDistance < 20)
            {obstacleAvoid();}
        }
        break;
        case CMD_LEFT:
        {
          CurrentDistance = DistanceMeasure();
          Serial.println("Turn Left");
          CAR_turnLeftWifi();
          if(CurrentDistance < 20)
            {obstacleAvoid();}
        }
        break;
        case CMD_RIGHT:
        {
          CurrentDistance = DistanceMeasure();
          Serial.println("Turn Right");
          CAR_turnRightWifi();
        }
        break;
        default:
        {
          Serial.println("Unknown command");
        }
      }

      break;
  }
}


void setup() {
  //modding motor A
  pinMode(enable1Pin, OUTPUT);
  pinMode(motor1Pin1, OUTPUT);
  pinMode(motor1Pin2, OUTPUT); 

  //modding Motor B
  pinMode(enable2Pin, OUTPUT);
  pinMode(motor2Pin3, OUTPUT);
  pinMode(motor2Pin4, OUTPUT);

  //setting flame sensor as input
  //pinMode(FlamePinForawrd, INPUT);
  pinMode(FlamePinForawrdAnlog, INPUT);
  pinMode(FlamePinRight, INPUT);
  pinMode(FlamePinLeft, INPUT);

  //setting gas sensor as input
  pinMode(GasSensorDi,INPUT);
  // configure relay pin 12 as an oytput
  pinMode(RELAY_PIN,   OUTPUT);

  //setting siren for right
  pinMode(LedBlue, OUTPUT);  //defined port for right leds
  pinMode(LedRed, OUTPUT);
  pinMode(Buzzer, OUTPUT); // port front buzzer

  servo.attach(SERVO_PIN);  // attaches the servo on pin 12 to the servo objectư
  pinMode(trigger_pin,OUTPUT); // attaches the trigger pin to 5 pin
  pinMode(echo_pin,INPUT); // attaches echo pin to 18 pin

  // initaite serial monitor 
  Serial.begin(9600);

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  // Initialize WebSocket server
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);

  // Serve a basic HTML page with JavaScript to create the WebSocket connection
  server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
    Serial.println("Web Server: received a web page request");
    String html = HTML_CONTENT;  // Use the HTML content from the servo_html.h file
    request->send(200, "text/html", html);
  });

  server.begin();
  Serial.print("ESP32 Web Server's IP address: ");
  Serial.println(WiFi.localIP());

}

void loop() {
  webSocket.loop();

  unsigned long currentTime = millis();
  //vars for storing flame sensor vlaues
  FlameCheckForawrdAnalog = analogRead(FlamePinForawrdAnlog);
  Serial.println(FlameCheckForawrdAnalog);
  FlameCheckRight = digitalRead(FlamePinRight);
  FlameCheckLeft = digitalRead(FlamePinLeft);
  //vars for storing gas sensor vlaues
  GasSensorD=digitalRead(GasSensorDi);
  // taking intial distance value
  int CurrentDistance = DistanceMeasure();

  // firefighting routine
  if (FlameCheckForawrdAnalog <= 4090 && FlameCheckForawrdAnalog >= 500)
    {
      if(currentTime -  previouseventCarMovement >= eventCarMovementInterval) {
        Serial.println("flame dected a head");
        FlameCheckForawrdAnalog = analogRead(FlamePinForawrdAnlog);
        Serial.println(FlameCheckForawrdAnalog);
        CAR_moveForwardWifi();
        

        previouseventCarMovement = currentTime;
      }
      if(currentTime -  previousEventSiren >= eventSirenInterval){
        //  siren on
        Serial.println("sirens on");
        //sirenOn(LedBlue, LedRed, Buzzer);

        previousEventSiren = currentTime;
      }
    }

  else if(FlameCheckRight == LOW && !FlameCheckForawrdAnalog < 4000 )
    {
      if(currentTime -  previouseventCarSideMovement >= eventCarSideMovementInterval){
        Serial.println("flame dected on the right");
        Serial.println("turning right");
        CAR_turnRightWifi();
        Serial.println("siren on");
        //sirenOn(LedBlue,LedRed, Buzzer);

        previouseventCarSideMovement = currentTime;
      }
    } 

  else if(FlameCheckLeft == LOW && !FlameCheckForawrdAnalog < 4000 )
    {
      if(currentTime -  previouseventCarSideMovement >= eventCarSideMovementInterval){
        Serial.println("flame dected on the left");
        Serial.println("turning left");
        CAR_turnLeftWifi();
        Serial.println("siren on");
        //sirenOn(LedBlue,LedRed, Buzzer);

        previouseventCarSideMovement = currentTime;
      }
    }   


  else if(GasSensorD == LOW && !FlameCheckForawrdAnalog < 4000){
        if(currentTime -  previousEventSiren >= eventSirenInterval){
          //  siren on
          Serial.println("sirens on");
          //sirenOn(LedBlue, LedRed, Buzzer);

          previousEventSiren = currentTime;}
        if(three60forward < 20){
            Serial.println("gas dected ,looking around for fire");
            Serial.println("turning right");
            Serial.println(three60forward);
            CAR_turnRightWifi();
            three60forward++;}
        else{
            CurrentDistance = DistanceMeasure();
            if(CurrentDistance < 20){//check if no obstacle ahead
             Serial.println("obstacle ahead");
             obstacleAvoid();}

            {Serial.println("move forawrd");
            CAR_moveForwardWifi();
            delay(1000);}
            three60forward = 0;}
   }
  else if(FlameCheckForawrdAnalog < 500 ){//turn pump while in front sensor triggred
        StopCar();
         
        Serial.println("pump on");
        digitalWrite(RELAY_PIN, HIGH);
        CurrentDistance = DistanceMeasure();
        if(CurrentDistance < 20){//check if no obstacle ahead
          Serial.println("obstacle ahead");
          obstacleAvoid();
         }
         
        }
     
       
  else
     {Serial.println("pump off");
      digitalWrite(RELAY_PIN, LOW);
      Serial.println("sirens off");
      sirenoff(LedBlue, LedRed, Buzzer);
      StopCar();} 
  

}

//functions for car movement
void CAR_moveForwardWifi() {
  Serial.println("MoveForward");
  //Set speed motor A and B
  analogWrite(enable1Pin,195);
  analogWrite(enable2Pin,200);
  //move forawrd
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, HIGH);
  digitalWrite(motor2Pin3, HIGH);
  digitalWrite(motor2Pin4, LOW);
}

void CAR_moveBackwardWifi() {
  Serial.println("MoveBackward");
  //setting speed motor A and B
  analogWrite(enable1Pin,186);
  analogWrite(enable2Pin,200);
  //back movement
  digitalWrite(motor1Pin1, HIGH);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin3, LOW);
  digitalWrite(motor2Pin4, HIGH);
}

void CAR_turnLeftWifi() {
  Serial.println("turn left");
  //Set speed motor A and B
  analogWrite(enable1Pin,178);
  analogWrite(enable2Pin,195);
  //turn left
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, HIGH);
  digitalWrite(motor2Pin3, LOW);
  digitalWrite(motor2Pin4, LOW);
  
}

void CAR_turnRightWifi() {
  Serial.println("turn right");
  //Set speed motor A and B
  analogWrite(enable1Pin,255);
  analogWrite(enable2Pin,255);
  //turn right
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin3, HIGH);
  digitalWrite(motor2Pin4, LOW);
}
// stop car
void StopCar(){
  Serial.println("StopCar");
  analogWrite(enable1Pin,0);
  analogWrite(enable2Pin,0);

  digitalWrite(motor1Pin1,LOW);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin3,LOW);
  digitalWrite(motor2Pin4, LOW);
  delay(700);
}

//servo seek clear path funcs


//getting distance from hc-sr04


//sro4 calc distance
int DistanceMeasure(){
  long t;    //var time to calculate distance
  float distance; //var to store diatnce

  //setting hc-sro4
  digitalWrite(trigger_pin,LOW);
  delayMicroseconds(5);
  digitalWrite(trigger_pin,HIGH);
  delayMicroseconds(100);
  digitalWrite(trigger_pin,LOW);

  //time to singanl get back
  t = pulseIn(echo_pin, HIGH);

  //calculation of distance
  distance = (t*0.034)/2;

  Serial.print("Distance (cm): ");
  Serial.print(distance);
  Serial.print(" Duration (us): ");
  Serial.println(t);
  return distance;
}
//servo turn left
int ServoLookLeft(){
  Serial.println("ServoLookLeft");
  int distanceLeft = 0;
  delay(500);

  servo.write(180); //lefting servo and taking value
  delay(2000);
  distanceLeft = DistanceMeasure();
  return distanceLeft;
}
//servo turn right
int ServoLookRight(){
  Serial.println("ServoLookRight");
  int ditanceRight = 0;
  delay(500);

  servo.write(0); //lefting servo and taking value
  delay(2000);
  ditanceRight = DistanceMeasure();  
  servo.write(90);
  return ditanceRight;
}
//avoid obastacle protocol
void obstacleAvoid(){
//setting var for left and right distances
 int CalculatedDistanceLeft = 0; 
 int CalculatedDistanceRight = 0; 

 //car will stop
  StopCar();
  delay(200);

  //car backwards
  CAR_moveBackwardWifi();
  delay(200);

  //car will stop
  StopCar();
    

  //left distance calc
  CalculatedDistanceLeft = ServoLookLeft();
  delay(200);
    
  //right  distance calc
  CalculatedDistanceRight = ServoLookRight(); //right distance calc
  delay(200);
     
  //calcauting shortest distance
  if(CalculatedDistanceRight <= CalculatedDistanceLeft)
    {CAR_turnLeftWifi();
     delay(500);}
  else
    {CAR_turnRightWifi();
     delay(500);}

}

//functions for siren 
void sirenOn(int Led1Pin, int Led2Pin,int BuzzerPin)
{
  int i;

  for (int i = 700; i < 800; i++) // duration of the first sound 350 2 millisecond cycles.
    
  {
    tone(BuzzerPin,i);
    delay(15);
    digitalWrite(Led1Pin, HIGH); // turn on the leds
    digitalWrite(Led2Pin, LOW);
    delay(30);
    digitalWrite(Led1Pin, LOW); // blinking leds
    digitalWrite(Led2Pin, HIGH);
    delay(30); 
    delay(15); // wait 1 millisecond and restart from the for statement (100 repetitions)
  }

  for(i=800;i>700;i--){
  tone(BuzzerPin,i);
  delay(15);
  digitalWrite(Led1Pin, HIGH); // turn on the leds
  digitalWrite(Led2Pin, LOW);
  delay(30);
  digitalWrite(Led1Pin, LOW); // blinking leds
  digitalWrite(Led2Pin, HIGH);
  delay(30); 
  delay(15); // wait 1 millisecond and restart from the for statement (100 repetitions)
  }

}
void sirenoff(int Led1Pin, int Led2Pin,int BuzzerPin)
{
    digitalWrite(Led1Pin, LOW); // turn off blinking leds
    digitalWrite(Led2Pin, LOW);

    tone(BuzzerPin,0); // turn off buzzer

}

the web loop is wifi controlled car. with obstacle avoidance.
next in the loop is is the fire fighting part.
when the front sensor triggers ,the car will move forward up to a safe distance from the
fire the water pump will turn on.

what happens

Connecting to WiFi...
Connecting to WiFi...
Connecting to WiFi...
Connecting to WiFi...
Connecting to WiFi...
Connected to WiFi
ESP32 Web Server's IP address: 192.168.83.7
0
Distance (cm): 51.54 Duration (us): 3032
StopCar
pump on

the code jump right into the condition

else if(FlameCheckForawrdAnalog < 500 ){//turn pump while in front sensor triggred
        StopCar();
         
        Serial.println("pump on");
        digitalWrite(RELAY_PIN, HIGH);
        CurrentDistance = DistanceMeasure();
        if(CurrentDistance < 20){//check if no obstacle ahead
          Serial.println("obstacle ahead");
          obstacleAvoid();
         }
         
        }

instead of moving into goes right into turn on the pump.
when i try the code without the wifi element

// Setting Motor A
int enable1Pin = 14;
int motor1Pin1 = 27;
int motor1Pin2 = 26;

//Settin Motor B
int enable2Pin = 32;
int motor2Pin3 = 25;
int motor2Pin4 = 33;

// define pins for flame sensor
//#define FlamePinForawrd 17
#define FlamePinForawrdAnlog 4 
#define FlamePinRight 15
//#define FlamePinLeft 

// define pins for gas sensor
#define GasSensorDi 17

// pin 12 that connects to the relay to control the pump
#define RELAY_PIN   12

//pins for siren led and buzzer
//siren
#define LedBlue 2
#define LedRed 21 
#define Buzzer 19

//vars for falme sensor read
int FlameCheckForawrdAnalog;
int FlameCheckRight;

//vars for gas sensor read
int GasSensorD;
int three60forward = 0;//var for 360 turn 


//time vars for front sensor 
const unsigned long eventFrontSensorInterval = 200;
unsigned long previouseventFrontSensor = 0;
//time vars for front sensor trigger and movement forward
const unsigned long eventCarMovementInterval = 200;
unsigned long previouseventCarMovement = 0;
//time vars for front sensor trigger and movment left and right 
const unsigned long eventCarSideMovementInterval = 200;
unsigned long previouseventCarSideMovement = 0;
//time vars for siren
const unsigned long eventSirenInterval = 500;
unsigned long previousEventSiren = 0;
//time vars for water pump
const unsigned long eventPumpInterval = 500;
unsigned long previousEventPump = 0;
//var for movement forward on the gas condition
const unsigned long eventCarMovementGasInterval = 2500;
unsigned long previouseventGasCarMovement = 0;

void setup() {
  //modding motor A
  pinMode(enable1Pin, OUTPUT);
  pinMode(motor1Pin1, OUTPUT);
  pinMode(motor1Pin2, OUTPUT); 

  //modding Motor B
  pinMode(enable2Pin, OUTPUT);
  pinMode(motor2Pin3, OUTPUT);
  pinMode(motor2Pin4, OUTPUT);

  //setting flame sensor as input
  //pinMode(FlamePinForawrd, INPUT);
  pinMode(FlamePinForawrdAnlog, INPUT);
  pinMode(FlamePinRight, INPUT);
  //pinMode(FlamePinLeft, INPUT);

  //setting gas sensor as input
  pinMode(GasSensorDi,INPUT);
  // configure relay pin 12 as an oytput
  pinMode(RELAY_PIN,   OUTPUT);

  //setting siren for right
  pinMode(LedBlue, OUTPUT);  //defined port for right leds
  pinMode(LedRed, OUTPUT);
  pinMode(Buzzer, OUTPUT); // port front buzzer

  // initaite serial monitor 
  Serial.begin(9600);


}

void loop() {
   unsigned long currentTime = millis();
   //vars for storing flame sensor vlaues
  //  if(currentTime -  previouseventFrontSensor >= eventFrontSensorInterval) {
  //       FlameCheckForawrdAnalog = analogRead(FlamePinForawrdAnlog);
  //       Serial.println(FlameCheckForawrdAnalog);

  //       previouseventFrontSensor = currentTime;
  //     }
   FlameCheckForawrdAnalog = analogRead(FlamePinForawrdAnlog);
   Serial.println(FlameCheckForawrdAnalog);

   FlameCheckRight = digitalRead(FlamePinRight);
   //vars for storing gas sensor vlaues
   GasSensorD=digitalRead(GasSensorDi);


    ///sensorTest();
   
   if (FlameCheckForawrdAnalog <= 4090 && FlameCheckForawrdAnalog >= 500)
    {
      if(currentTime -  previouseventCarMovement >= eventCarMovementInterval) {
        Serial.println("flame dected a head");
        //FlameCheckForawrdAnalog = analogRead(FlamePinForawrdAnlog);
        Serial.println(FlameCheckForawrdAnalog);
        CAR_moveForwardWifi();
        

        previouseventCarMovement = currentTime;
      }
      if(currentTime -  previousEventSiren >= eventSirenInterval){
        //  siren on
        Serial.println("sirens on");
        //sirenOn(LedBlue, LedRed, Buzzer);

        previousEventSiren = currentTime;
      }
    }

   else if(FlameCheckRight == LOW && !FlameCheckForawrdAnalog < 4000 )
    {
      if(currentTime -  previouseventCarSideMovement >= eventCarSideMovementInterval){
        Serial.println("flame dected on the right");
        Serial.println("turning right");
        CAR_turnRightWifi();
        Serial.println("siren on");
        //sirenOn(LedBlue,LedRed, Buzzer);

        previouseventCarSideMovement = currentTime;
      }
    }    
        
    //else if (FlameCheckLeft == LOW)
     //{
      //Serial.println("flame dected on the left");
      //while(FlameCheckForawrd != LOW)
        //{
         //FlameCheckForawrd = digitalRead(FlamePinForawrd);
         //Serial.println("turning left");
         //CAR_turnLeftWifi();
         //delay(200);
        //} 
     //} 

   else if(GasSensorD == LOW && !FlameCheckForawrdAnalog < 4000){
        if(currentTime -  previousEventSiren >= eventSirenInterval){
          //  siren on
          Serial.println("sirens on");
          //sirenOn(LedBlue, LedRed, Buzzer);

          previousEventSiren = currentTime;}
        if(three60forward < 20){
            Serial.println("gas dected ,looking around for fire");
            Serial.println("turning right");
            Serial.println(three60forward);
            CAR_turnRightWifi();
            three60forward++;}
        else{
           {Serial.println("move forawrd");
            CAR_moveForwardWifi();
            delay(1000);}
            three60forward = 0;}
   }
   else if(FlameCheckForawrdAnalog < 500 ){//turn pump while in front sensor triggred
        StopCar();
         
        Serial.println("pump on");
        digitalWrite(RELAY_PIN, HIGH);
        
          
   }
     
       
   else
     {Serial.println("pump off");
      digitalWrite(RELAY_PIN, LOW);
      Serial.println("sirens off");
      sirenoff(LedBlue, LedRed, Buzzer);
      StopCar();} 
     
   }

     
     
// stop car
void StopCar(){
  Serial.println("StopCar");
  analogWrite(enable1Pin,0);
  analogWrite(enable2Pin,0);

  digitalWrite(motor1Pin1,LOW);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin3,LOW);
  digitalWrite(motor2Pin4, LOW);
}

void CAR_moveForwardWifi() {
  //Set speed motor A and B
  analogWrite(enable1Pin,200);
  analogWrite(enable2Pin,185);
  //move forawrd
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, HIGH);
  digitalWrite(motor2Pin3, HIGH);
  digitalWrite(motor2Pin4, LOW);
}

void CAR_moveBackwardWifi() {
  //setting speed motor A and B
  analogWrite(enable1Pin,190);
  analogWrite(enable2Pin,200);
  //back movement
  digitalWrite(motor1Pin1, HIGH);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin3, LOW);
  digitalWrite(motor2Pin4, HIGH);
}

void CAR_turnLeftWifi() {
    //Set speed motor A and B

  analogWrite(enable1Pin,255);
  analogWrite(enable2Pin,0);
  //turn left
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, HIGH);
  digitalWrite(motor2Pin3, LOW);
  digitalWrite(motor2Pin4, LOW);
}

void CAR_turnRightWifi() {
  //Set speed motor A and B
  analogWrite(enable1Pin,255);
  analogWrite(enable2Pin,255);
  //turn right
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin3, HIGH);
  digitalWrite(motor2Pin4, LOW);
}

void sensorTest() {
  while (1) {
    for (int i = 0; i < 3; i++) {
      Serial.print(digitalRead(i + 15)); // read "flame" sensors
    }
    Serial.println(); // print the sensor state
    delay(250);
  }
}

//functions for siren 
void sirenOn(int Led1Pin, int Led2Pin,int BuzzerPin)
{
  int i;

  for (int i = 700; i < 800; i++) // duration of the first sound 350 2 millisecond cycles.
    
  {
    tone(BuzzerPin,i);
    delay(15);
    digitalWrite(Led1Pin, HIGH); // turn on the leds
    digitalWrite(Led2Pin, LOW);
    delay(30);
    digitalWrite(Led1Pin, LOW); // blinking leds
    digitalWrite(Led2Pin, HIGH);
    delay(30); 
    delay(15); // wait 1 millisecond and restart from the for statement (100 repetitions)
  }

  for(i=800;i>700;i--){
  tone(BuzzerPin,i);
  delay(15);
  digitalWrite(Led1Pin, HIGH); // turn on the leds
  digitalWrite(Led2Pin, LOW);
  delay(30);
  digitalWrite(Led1Pin, LOW); // blinking leds
  digitalWrite(Led2Pin, HIGH);
  delay(30); 
  delay(15); // wait 1 millisecond and restart from the for statement (100 repetitions)
  }

}

void sirenoff(int Led1Pin, int Led2Pin,int BuzzerPin)
{
    digitalWrite(Led1Pin, LOW); // turn off blinking leds
    digitalWrite(Led2Pin, LOW);

    tone(BuzzerPin,0); // turn off buzzer

}


  

the car move forward just fine.

1 Like

Well done!

This seems to be a popular project. I assume it's a college assignment that is used every year

I'm sure others will be appreciative of your code and solution next year!

1 Like

@zuczac12 - You downloaded another bad sketch. You need to focus on (1) controlling your robot steering first, then (2) obstacles then (3) "firefighting" with flame-following and waterpump then (4) wifi, and do not use gas sensing, as that needs a lot more power and time (hours of warming up). You keep stopping and starting the same thing.

i am feeling you abit to quick to comment.
on my last thread you insisted the wiring is wrong. but it wasn't.
i padded the code and got it to work.
published and stated it in 1# , it works experimentally.

the obstacle avoidance code works on its own.
folks and i think you too helped on a separate thread.

#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <WebSocketsServer.h>
#include "index.h"
#include <ESP32Servo.h>
Servo servo;  // create servo object to control a servo

//seeting for sr04 pins
#define trigger_pin 23
#define echo_pin 35

#define SERVO_PIN 13 //setting servo pin 

//keys for car movement
#define CMD_STOP 0
#define CMD_FORWARD 1
#define CMD_BACKWARD 2
#define CMD_LEFT 4
#define CMD_RIGHT 8

// Setting Motor A
int enable1Pin = 14;
int motor1Pin1 = 27;
int motor1Pin2 = 26;

//Settin Motor B
int enable2Pin = 32;
int motor2Pin3 = 25;
int motor2Pin4 = 33;

const char* ssid = "Galaxy A52s 5GA0A0";     // wifi name
const char* password = "zmuz6970";  // wifi password

AsyncWebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);  // WebSocket server on port 81

void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) {
  switch (type) {
    case WStype_DISCONNECTED:
      Serial.printf("[%u] Disconnected!\n", num);
      break;
    case WStype_CONNECTED:
      {
        IPAddress ip = webSocket.remoteIP(num);
        Serial.printf("[%u] Connected from %d.%d.%d.%d\n", num, ip[0], ip[1], ip[2], ip[3]);
      }
      break;
    case WStype_TEXT:
      //Serial.printf("[%u] Received text: %s\n", num, payload);
      String angle = String((char*)payload);
      int command = angle.toInt();
      Serial.print("command: ");
      Serial.println(command);
      
      delay(200);
      int CurrentDistance = DistanceMeasure();
      delay(200);

      switch (command) {
        case CMD_STOP:
          Serial.println("Stop");
          CAR_stopWifi();
          break;
        case CMD_FORWARD:
        {
          CurrentDistance = DistanceMeasure();
          if(CurrentDistance >= 20){//movement forward if no obstacle ahead
          Serial.println("Move Forward");
          CAR_moveForwardWifi();
          }
          else
          { Serial.println("obstacle ahead");
            obstacleAvoid();}

          } 

          
            

        
          
        
        break;
        case CMD_BACKWARD:
        {
          CurrentDistance = DistanceMeasure();
          Serial.println("Move Backward");
          CAR_moveBackwardWifi();
          if(CurrentDistance < 20)
            {obstacleAvoid();}
        }
          break;
          
        
        case CMD_LEFT:
        {
          CurrentDistance = DistanceMeasure();
          Serial.println("Turn Left");
          CAR_turnLeftWifi();
          if(CurrentDistance < 20)
            {obstacleAvoid();}
        }
        break;
        case CMD_RIGHT:
        {
          CurrentDistance = DistanceMeasure();
          Serial.println("Turn Right");
          CAR_turnRightWifi();
        }
        break;
        default:
        {
          Serial.println("Unknown command");
        }
      }

      break;
  }
}

void setup() {
  servo.attach(SERVO_PIN);  // attaches the servo on pin 12 to the servo objectư
  pinMode(trigger_pin,OUTPUT); // attaches the trigger pin to 5 pin
  pinMode(echo_pin,INPUT); // attaches echo pin to 18 pin

  //modding motor A
  pinMode(enable1Pin, OUTPUT);
  pinMode(motor1Pin1, OUTPUT);
  pinMode(motor1Pin2, OUTPUT); 

  //modding Motor B
  pinMode(enable2Pin, OUTPUT);
  pinMode(motor2Pin3, OUTPUT);
  pinMode(motor2Pin4, OUTPUT);

  // initaite serial monitor 
  Serial.begin(9600);

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  // Initialize WebSocket server
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);

  // Serve a basic HTML page with JavaScript to create the WebSocket connection
  server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
    Serial.println("Web Server: received a web page request");
    String html = HTML_CONTENT;  // Use the HTML content from the servo_html.h file
    request->send(200, "text/html", html);
  });

  server.begin();
  Serial.print("ESP32 Web Server's IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  webSocket.loop();
  // TO DO: Your code here
}

void CAR_moveForwardWifi() {
  Serial.println("MoveForward");
  //Set speed motor A and B
  analogWrite(enable1Pin,186);
  analogWrite(enable2Pin,200);
  //move forawrd
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, HIGH);
  digitalWrite(motor2Pin3, HIGH);
  digitalWrite(motor2Pin4, LOW);
}

void CAR_moveBackwardWifi() {
  Serial.println("MoveBackward");
  //setting speed motor A and B
  analogWrite(enable1Pin,186);
  analogWrite(enable2Pin,200);
  //back movement
  digitalWrite(motor1Pin1, HIGH);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin3, LOW);
  digitalWrite(motor2Pin4, HIGH);
}

void CAR_turnLeftWifi() {
  Serial.println("turn left");
  //Set speed motor A and B
  analogWrite(enable1Pin,178);
  analogWrite(enable2Pin,195);
  //turn left
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, HIGH);
  digitalWrite(motor2Pin3, LOW);
  digitalWrite(motor2Pin4, LOW);
  
}

void CAR_turnRightWifi() {
  Serial.println("turn right");
  //Set speed motor A and B
  analogWrite(enable1Pin,255);
  analogWrite(enable2Pin,255);
  //turn right
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin3, HIGH);
  digitalWrite(motor2Pin4, LOW);
}

void CAR_stopWifi() {
  Serial.println("StopCar");
  //Set speed motor A and B to 0
  analogWrite(enable1Pin,0);
  analogWrite(enable2Pin,0);
  //stop movement
  digitalWrite(motor1Pin1,LOW);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin3,LOW);
  digitalWrite(motor2Pin4, LOW);
  
}

//servo seek clear path funcs


//getting distance from hc-sr04
//sro4 calc distance
int DistanceMeasure(){
  long t;    //var time to calculate distance
  float distance; //var to store diatnce

  //setting hc-sro4
  digitalWrite(trigger_pin,LOW);
  delayMicroseconds(5);
  digitalWrite(trigger_pin,HIGH);
  delayMicroseconds(100);
  digitalWrite(trigger_pin,LOW);

  //time to singanl get back
  t = pulseIn(echo_pin, HIGH);

  //calculation of distance
  distance = (t*0.034)/2;

  Serial.print("Distance (cm): ");
  Serial.print(distance);
  Serial.print(" Duration (us): ");
  Serial.println(t);
  return distance;
}


//servo turn left
int ServoLookLeft(){
  Serial.println("ServoLookLeft");
  int distanceLeft = 0;
  delay(500);

  servo.write(180); //lefting servo and taking value
  delay(2000);
  distanceLeft = DistanceMeasure();
  return distanceLeft;
}


//servo turn right
int ServoLookRight(){
  Serial.println("ServoLookRight");
  int ditanceRight = 0;
  delay(500);

  servo.write(0); //lefting servo and taking value
  delay(2000);
  ditanceRight = DistanceMeasure();  
  servo.write(90);
  return ditanceRight;
}

//avoid obastacle protocol
void obstacleAvoid(){
//setting var for left and right distances
 int CalculatedDistanceLeft = 0; 
 int CalculatedDistanceRight = 0; 

 //car will stop
  StopCar();
  delay(200);

  //car backwards
  MoveBackward();
  delay(200);

  //car will stop
  StopCar();
    

  //left distance calc
  CalculatedDistanceLeft = ServoLookLeft();
  delay(200);
    
  //right  distance calc
  CalculatedDistanceRight = ServoLookRight(); //right distance calc
  delay(200);
     
  //calcauting shortest distance
  if(CalculatedDistanceRight <= CalculatedDistanceLeft)
    {CAR_turnLeftWifi();
     delay(500);}
  else
    {CAR_turnRightWifi();
     delay(500);}

}

//car movement functions for obstacle avoidance

//move forward
void MoveForward(){
  Serial.println("MoveForward");
  //Set speed motor A and B
  analogWrite(enable1Pin,178);
  analogWrite(enable2Pin,195);
  
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, HIGH);
  digitalWrite(motor2Pin3, HIGH);
  digitalWrite(motor2Pin4, LOW);
  //lcd.clear(); 
}

//move backward
void MoveBackward(){
  Serial.println("MoveBackward");
  analogWrite(enable1Pin,178);
  analogWrite(enable2Pin,195);
  
  digitalWrite(motor1Pin1, HIGH);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin3, LOW);
  digitalWrite(motor2Pin4, HIGH);
  //lcd.clear();
  delay(400);
}

//turn car left
void TurnLeft(){
  Serial.println("TurnLeft");
   //Set speed motor A and B
  analogWrite(enable1Pin,255);
  analogWrite(enable2Pin,255);
  
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, HIGH);
  digitalWrite(motor2Pin3, LOW);
  digitalWrite(motor2Pin4, LOW);
  //lcd.clear();
  delay(625);

  //Stop motor for half second
  StopCar();
}


//turn car  right 
void TurnRight(){
  Serial.println("TurnRight");
   //turn right
  analogWrite(enable1Pin,255);
  analogWrite(enable2Pin,255);
  
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin3, HIGH);
  digitalWrite(motor2Pin4, LOW);
  //lcd.clear();
  delay(625);

  //Stop motor for half second
  StopCar();
}

// stop car
void StopCar(){
  Serial.println("StopCar");
  analogWrite(enable1Pin,0);
  analogWrite(enable2Pin,0);

  digitalWrite(motor1Pin1,LOW);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin3,LOW);
  digitalWrite(motor2Pin4, LOW);
  delay(700);
}

No. I compared the new to the second sketch. You wrapped it in wifi.

It was.

You were using a pin reserved for ESP32, you tried to wire your motors in series, then your motors and servo did not move because of wiring. Did you forget? I did not.

I recommend you prove your robot can do all the steps in post #3, and in order.

If parts of your sketch work, then show the working parts. As I was "simulating" your sketch, most of your sketch did not work. I got it working for you with two of four sensors and stopped the robot from driving into the fire.

Introducing wifi and web service is a bad idea until you get the robot working.

i am not sure about the motor in series part, but the wiring were faulty way back on the obstacle avoid sketch.

you mentioned the wiring in the fire fighting part, by then it was no problem.
as i mentioned the working part is the one on post #4 and the last sketch on post 1#.

"I got it working for you with two of four sensors and stopped the robot from driving into the fire." you indeed help. and i am thinking you for that.
but in the part of "stopped the robot from driving into the fire." you didnt. the thread ended before it was solved.
so i continued on my own. thats the last sketch of post 1#.
and on it own, it works. the car moves left, right and forward, and stops a distance from the the fire.

when i combined the two sketches , i get the problem mentioned on post 1#.

You must... must... start from a good base of controlling the robot and follow the steps in adding to the good base. Dumping bad code is not the answer. Little by little is the answer. Try it. You will find the issue in the structure of your code.

That is also where your wiring was incorrect. It stopped in the simulation. You just argued about it. ( && versus || )

both of the sketches were done little by little.
including two threads on the fourms .

the --&& versus ||-- didnt solve the running into the fire problem.
i added a code

else if(FlameCheckForawrdAnalog < 500 ){//turn pump while in front sensor triggred
        StopCar();
         
        Serial.println("pump on");
        digitalWrite(RELAY_PIN, HIGH);
        CurrentDistance = DistanceMeasure();
        if(CurrentDistance < 20){//check if no obstacle ahead
          Serial.println("obstacle ahead");
          obstacleAvoid();
         }
         
        }

to fix it.
the wiring stayed the same.
anyways thanks for you help so far.
i will just wait for another input.

Yes, the code change did stop the motors... you even complained it "broke" your code by not letting the motors run. The code change stopped the motors near the fire with analog reading 3500 to 4095. Your wiring was not correct.

Your blob of a program also has many "race" conditions that are fighting for control, but control is not shared (non-blocking, time-sharing), rather sequential (one after the other, blocking). I have been working on a non-blocking solution to let multiple actions appear to happen at the same time.

"Yes, the code change did stop the motors... you even complained it "broke" your code by not letting the motors run. The code change stopped the motors near the fire with analog reading 3500 to 4095. Your wiring was not correct."

dont think i fully got you there, the conversation ended with you standing on the wrong wiring.
there were couple but that way before that.
and i am not sure to which one you mean.
there were one with not common ground , thats was in the obstacle avoid thread.
and there was one that the analog front sensor wasn't wired to analog pin.
but again that was before that.
not sure to which one you mean.

the || vs && solved the motor wont stop running problem.

what stop the motor was solved by separating the interval of the front sensor if statement and the pump statement.
what i did was over laying the condition over each other
say front sensor condition 3500 <=x < 4095.
and pump condition 2500 <=x
so i missed that , and then caught it and fix it. that what made the motor running

what solved the not running into the fire was the changes i made in post #8

a both of the last changes were made after the conversation ended with the wiring problem statement.
didnt change the wiring . because i knew the motor run fine in simple forward and backward, left and right code.

as for the last paragraph, we were not taught those techniques.
and i have about a week . not sure i can master those in time.

You can make this work with the techniques you understand (I will continue finishing the other method). The code you have is overly complicated. Your car should do this:

  1. read sensors (L flame, R flame, F flame, gas) - call this search mode
  2. if one sensor shows activity, (a) turn that direction (b) read analog value
  3. if analog flame value is increasing, continue straight
  4. if analog flame value is above "fire" value, reverse, stop.
  5. if analog flame value is at "fire" value, stop, start pump, stop pump, repeat this step until flame drops below "fire"
  6. If analog flame value drops below "fire" value but above "no flame" drive forward toward the fire... return to #3
  7. if analog flame value drops below "flame" value, return to search mode.
  8. if gas, then make 360 180 because you have L and R sensor (in small steps, probably four steps of 45 degrees = 180) and if flame is detected, go to #3.

You can use the methods you know. You will not be able to do more than one task at a time (you can not drive and search, or pump and drive, or anything together).

All that other stuff you add in your post is just defending your choice to not follow advice. For this project; get the basics down (sense flame, measure fire, turn, drive, stop, reverse, pump) before using wifi. I will continue with the "non-blocking" code... it has a "dashboard" showing all the data to quickly identify problems in software or hardware... I will post it here when done.

2 -
instead of starting with front sensor check, you mean to do

else if(FlameCheckRight == LOW && !FlameCheckForawrdAnalog < 4000 )
    {
      if(currentTime -  previouseventCarSideMovement >= eventCarSideMovementInterval){
        Serial.println("flame dected on the right");
        Serial.println("turning right");
        CAR_turnRightWifi();
        Serial.println("siren on");
        //sirenOn(LedBlue,LedRed, Buzzer);

        previouseventCarSideMovement = currentTime;
      }
      if (FlameCheckForawrdAnalog <= 4090 && FlameCheckForawrdAnalog >= 500)
      {
        if(currentTime -  previouseventCarMovement >= eventCarMovementInterval) {
        Serial.println("flame dected a head");
        FlameCheckForawrdAnalog = analogRead(FlamePinForawrdAnlog);
        Serial.println(FlameCheckForawrdAnalog);
        CAR_moveForwardWifi();
        

        previouseventCarMovement = currentTime;
      }
      if(currentTime -  previousEventSiren >= eventSirenInterval){
        //  siren on
        Serial.println("sirens on");
        //sirenOn(LedBlue, LedRed, Buzzer);

        previousEventSiren = currentTime;
      }
      }

    } 

  else if(FlameCheckLeft == LOW && !FlameCheckForawrdAnalog < 4000 )
    {
      if(currentTime -  previouseventCarSideMovement >= eventCarSideMovementInterval){
        Serial.println("flame dected on the left");
        Serial.println("turning left");
        CAR_turnLeftWifi();
        Serial.println("siren on");
        //sirenOn(LedBlue,LedRed, Buzzer);

        previouseventCarSideMovement = currentTime;
      }
      if (FlameCheckForawrdAnalog <= 4090 && FlameCheckForawrdAnalog >= 500)
      {
        if(currentTime -  previouseventCarMovement >= eventCarMovementInterval) {
        Serial.println("flame dected a head");
        FlameCheckForawrdAnalog = analogRead(FlamePinForawrdAnlog);
        Serial.println(FlameCheckForawrdAnalog);
        CAR_moveForwardWifi();
        

        previouseventCarMovement = currentTime;
      }
      if(currentTime -  previousEventSiren >= eventSirenInterval){
        //  siren on
        Serial.println("sirens on");
        //sirenOn(LedBlue, LedRed, Buzzer);

        previousEventSiren = currentTime;
      }
      }
    }   

in 3 i am assuming you mean decreasing.
how if statement like that should look like?
wont it be the same as as long as checking is fire value is inside the interval

if (FlameCheckForawrdAnalog <= 4090 && FlameCheckForawrdAnalog >= 500)

move forward?

5 - how i make until in code? while loop?
i was suggested to relay on the main loop.

in 6&7 how i do return to in code?
dont think i got you at all but you mean somthing like that

void loop() {
  
  unsigned long currentTime = millis();
  //read sensor mode
  //vars for storing flame sensor vlaues
  FlameCheckForawrdAnalog = analogRead(FlamePinForawrdAnlog);
  Serial.println(FlameCheckForawrdAnalog);
  FlameCheckRight = digitalRead(FlamePinRight);
  FlameCheckLeft = digitalRead(FlamePinLeft);
  //vars for storing gas sensor vlaues
  GasSensorD=digitalRead(GasSensorDi);
  // taking intial distance value
  int CurrentDistance = DistanceMeasure();



  if(FlameCheckRight == LOW && !FlameCheckForawrdAnalog < 4000 )
    {
      if(currentTime -  previouseventCarSideMovement >= eventCarSideMovementInterval){
        Serial.println("flame dected on the right");
        Serial.println("turning right");
        CAR_turnRightWifi();
        Serial.println("siren on");
        //sirenOn(LedBlue,LedRed, Buzzer);

        previouseventCarSideMovement = currentTime;
      }
      if (FlameCheckForawrdAnalog <= 4090 && FlameCheckForawrdAnalog >= 500)
      {
        if(currentTime -  previouseventCarMovement >= eventCarMovementInterval) {
        Serial.println("flame dected a head");
        FlameCheckForawrdAnalog = analogRead(FlamePinForawrdAnlog);
        Serial.println(FlameCheckForawrdAnalog);
        CAR_moveForwardWifi();
        

        previouseventCarMovement = currentTime;
      }
      if(currentTime -  previousEventSiren >= eventSirenInterval){
        //  siren on
        Serial.println("sirens on");
        //sirenOn(LedBlue, LedRed, Buzzer);

        previousEventSiren = currentTime;
      }
      if(FlameCheckForawrdAnalog < 500 ){//turn pump while in front sensor triggred
        StopCar();
        CAR_moveBackwardWifi();
        Serial.println("pump on");
        digitalWrite(RELAY_PIN, HIGH);
        CurrentDistance = DistanceMeasure();
        if(CurrentDistance < 20){//check if no obstacle ahead
          Serial.println("obstacle ahead");
          obstacleAvoid();
         }
         
        }
      }

    } 

  else if(FlameCheckLeft == LOW && !FlameCheckForawrdAnalog < 4000 )
    {
      if(currentTime -  previouseventCarSideMovement >= eventCarSideMovementInterval){
        Serial.println("flame dected on the left");
        Serial.println("turning left");
        CAR_turnLeftWifi();
        Serial.println("siren on");
        //sirenOn(LedBlue,LedRed, Buzzer);

        previouseventCarSideMovement = currentTime;
      }
      if (FlameCheckForawrdAnalog <= 4090 && FlameCheckForawrdAnalog >= 500)
      {
        if(currentTime -  previouseventCarMovement >= eventCarMovementInterval) {
        Serial.println("flame dected a head");
        FlameCheckForawrdAnalog = analogRead(FlamePinForawrdAnlog);
        Serial.println(FlameCheckForawrdAnalog);
        CAR_moveForwardWifi();
        

        previouseventCarMovement = currentTime;
      }
      if(currentTime -  previousEventSiren >= eventSirenInterval){
        //  siren on
        Serial.println("sirens on");
        //sirenOn(LedBlue, LedRed, Buzzer);

        previousEventSiren = currentTime;
      }
      }
      if(FlameCheckForawrdAnalog < 500 ){//turn pump while in front sensor triggred
        StopCar();
        CAR_moveBackwardWifi();
        Serial.println("pump on");
        digitalWrite(RELAY_PIN, HIGH);
        CurrentDistance = DistanceMeasure();
        if(CurrentDistance < 20){//check if no obstacle ahead
          Serial.println("obstacle ahead");
          obstacleAvoid();
         }
         
        }
    }   

    else if(GasSensorD == LOW && !FlameCheckForawrdAnalog < 4000){
        if(currentTime -  previousEventSiren >= eventSirenInterval){
          //  siren on
          Serial.println("sirens on");
          //sirenOn(LedBlue, LedRed, Buzzer);

          previousEventSiren = currentTime;}
        if(one80forward < 10){
            Serial.println("gas dected ,looking around for fire");
            Serial.println("turning right");
            Serial.println(three60forward);
            CAR_turnRightWifi();
            one80forward++;}
        else{
            CurrentDistance = DistanceMeasure();
            if(CurrentDistance < 20){//check if no obstacle ahead
             Serial.println("obstacle ahead");
             obstacleAvoid();}

            {Serial.println("move forawrd");
            CAR_moveForwardWifi();
            delay(1000);}
            one80forward = 0;}
   }

}

also are you dropping the wifi part?
if so i got the fire fighting part working already. messy code or not.
my problem is combining the two.
what happens is the front sensor goes straight to 0 vlaue.

not trying to be difficult but we had to hand in small report with simple code on each components on its own.
only trying to reassure i got the basics down.

Check all sensors, as in:

for (int i = 15; i < 19; i++) { // 15 = right, 16 = forward, 17 = left, 18 = gas
  if (digitalRead(sensorPin[i]) {
    // either "do things" or indicate flame/gas is detected for later action
  }
}

Your analog values tell you what to do:

  • 0 - 500 = no flame "search mode" - drive forward, scan, drive forward, scan...
  • > 500, < 3500 = flame detected... turn toward flame, drive toward flame (to later pump water)
  • > 3500 = you are inside the flame, back up until < 3500

As you pump water (turn relay ON), stop the pump, measure the analog value, if analog value = "fire" turn pump on, if analog value is < "fire" turn pump off... go back to search mode

Your main loop() should be the "director" of your sketch, calling the various functions... something like this...

void loop() {
  readSensors();
  if (fireLeft)
    turnLeft();
  if (fireRight)
    turnRight();
  if (fireForward)
    driveForward();
  }
.
.
void turnLeft() {
  motor1pin1 = LOW;
  motor1pin2 = LOW;
  motor2pin1 = HIGH;
  motor2pin2 = LOW;
}
void turnRight() {
  // do things
}
void driveForward() {
  // do things
}

When several "state" levels (no flame, flame, fire) exist, call other functions, for example, if you are inside a fire, reverse until out of the fire (< 3500) before pumping water, and if you are pumping water and then detect no fire (reverse) or flame (follow), scan and drive.

"Return" is my bad choice of words. Use decisions ( if (x && y || z) ) to call functions or exit a function back to the main loop()

You should make your robot work first before adding features.

Check your Fire sensors alone. Verify they are "1" when not active and "0" when active.

This is good... clean code is useful code and will be easier to "wrap" inside your wifi control.

*** Your analog value ranges 0 to 4096. Your program uses values 4000 and 4090... clean those up.

how i pull that

for (int i = 15; i < 19; i++) { // 15 = right, 16 = forward, 17 = left, 18 = gas
  if (digitalRead(sensorPin[i]) {
    // either "do things" or indicate flame/gas is detected for later action
  }

i skip the global variable such

//vars for falme sensor read front analog rest is digital
int FlameCheckForawrdAnalog;
int FlameCheckRight;
int FlameCheckLeft;

all of the pin definitions

// define pins for flame sensor
#define FlamePinForawrdAnlog 15 
#define FlamePinRight 16
#define FlamePinLeft  17

// define pins for gas sensor
#define GasSensorDi 18

should be dropped?
and instead use just sensorPin[i] variable inside the loop.

also say i a function for sensor input in a loop

(int i = 15; i < 19; i++) { // 15 = right, 16 = forward, 17 = left, 18 = gas
    if (digitalRead(sensorPin[i]) == HIGH || )
    return i;
  }

how i return the 15th pin, which is analog while the rest are digital

The example I showed is another way to read the four sensors.

Pin 15 is DIO "Right Flame Sensor". Analog Flame pin is Pin 4 (see my comments and your code).

you right about the pins
i thought you meant to you use the read method

digitalRead(sensorPin[i]

to read all the pins.
so i reorder them as

// define pins for flame sensor
#define FlamePinForawrdAnlog 15 
#define FlamePinRight 16
#define FlamePinLeft  17

// define pins for gas sensor
#define GasSensorDi 18

to be in a series from 15 to >19

so i think i got it now
i use the--sensorpin[i] --method to read only digital, and then separately read analog each time.

1 Like

You only need to read the analog pin when "front flame" sensor detects flame... when "front flame" is not detected, analog pin is probably zero.

The maximum value of the analog pin is 4095... correct the "4000" and "4090" to "4095" or better; use a variable substitution, like "int maxValue = 4095" and replace "4000" (and 4090) with "maxValue"

just to make sure because i think it been miscommunicated.
in 4095 value there is no flame and in 0 value fire is the closest.

also how i connect the sensor pins in the array.
when i try to declare

//vars for falme sensor read front analog rest is digitl
int sensorPin[4;16;17;18];

i get

C:\Users\PC\Documents\Arduino\final2\final2.ino:40:16: error: expected ']' before ';' token
 int sensorPin[4;16;17;18];
                ^
                ]
C:\Users\PC\Documents\Arduino\final2\final2.ino:40:17: error: expected unqualified-id before numeric constant
 int sensorPin[4;16;17;18];
                 ^~
C:\Users\PC\Documents\Arduino\final2\final2.ino:40:20: error: expected unqualified-id before numeric constant
 int sensorPin[4;16;17;18];
                    ^~
C:\Users\PC\Documents\Arduino\final2\final2.ino:40:23: error: expected unqualified-id before numeric constant
 int sensorPin[4;16;17;18];
                       ^~
C:\Users\PC\Documents\Arduino\final2\final2.ino: In function 'void loop()':
C:\Users\PC\Documents\Arduino\final2\final2.ino:95:20: error: 'sensorPin' was not declared in this scope
     if(digitalRead(sensorPin[4])<MaxFlameVlaue && digitalRead(sensorPin[4])>=500){
                    ^~~~~~~~~
C:\Users\PC\Documents\Arduino\final2\final2.ino:95:20: note: suggested alternative: 'constrain'
     if(digitalRead(sensorPin[4])<MaxFlameVlaue && digitalRead(sensorPin[4])>=500){
                    ^~~~~~~~~
                    constrain
C:\Users\PC\Documents\Arduino\final2\final2.ino:106:20: error: 'sensorPin' was not declared in this scope
     if(digitalRead(sensorPin[4])<MaxFlameVlaue && digitalRead(sensorPin[4])>MinFlameVlaue){
                    ^~~~~~~~~
C:\Users\PC\Documents\Arduino\final2\final2.ino:106:20: note: suggested alternative: 'constrain'
     if(digitalRead(sensorPin[4])<MaxFlameVlaue && digitalRead(sensorPin[4])>MinFlameVlaue){
                    ^~~~~~~~~
                    constrain
C:\Users\PC\Documents\Arduino\final2\final2.ino:112:49: error: 'sensorPin' was not declared in this scope
   else if(readSensorDio() == 18 && !digitalRead(sensorPin[4]) < MaxFlameVlaue){
                                                 ^~~~~~~~~
C:\Users\PC\Documents\Arduino\final2\final2.ino:112:49: note: suggested alternative: 'constrain'
   else if(readSensorDio() == 18 && !digitalRead(sensorPin[4]) < MaxFlameVlaue){
                                                 ^~~~~~~~~
                                                 constrain
C:\Users\PC\Documents\Arduino\final2\final2.ino: In function 'int readSensorDio()':
C:\Users\PC\Documents\Arduino\final2\final2.ino:137:21: error: 'sensorPin' was not declared in this scope
     if (digitalRead(sensorPin[i]) == HIGH)
                     ^~~~~~~~~
C:\Users\PC\Documents\Arduino\final2\final2.ino:137:21: note: suggested alternative: 'constrain'
     if (digitalRead(sensorPin[i]) == HIGH)
                     ^~~~~~~~~
                     constrain
C:\Users\PC\Documents\Arduino\final2\final2.ino: In function 'void frontSensorTrig()':
C:\Users\PC\Documents\Arduino\final2\final2.ino:143:18: error: 'sensorPin' was not declared in this scope
   Serial.println(sensorPin[4]);
                  ^~~~~~~~~
C:\Users\PC\Documents\Arduino\final2\final2.ino:143:18: note: suggested alternative: 'constrain'
   Serial.println(sensorPin[4]);
                  ^~~~~~~~~
                  constrain```
i tried to followed the post 11# instruction as literal as possible.
the main body loop

// put your main code here, to run repeatedly:
  if(readSensorDio() == 16){
    Serial.println("turning right");
    CAR_turnRightWifi();
    Serial.println("siren on");
    //sirenOn(LedBlue,LedRed, Buzzer);
    if(digitalRead(sensorPin[4])<MaxFlameVlaue && digitalRead(sensorPin[4])>=500){
      frontSensorTrig();} 
    else if(digitalRead(sensorPin[4])<MinFlameVlaue){
      pumpOn();
      delay(1000);} 
  }
  else if(readSensorDio() == 17){
    Serial.println("turning left");
    CAR_turnLeftWifi();
    Serial.println("siren on");
    //sirenOn(LedBlue,LedRed, Buzzer);
    if(digitalRead(sensorPin[4])<MaxFlameVlaue && digitalRead(sensorPin[4])>MinFlameVlaue){
      frontSensorTrig();}
    else if(digitalRead(sensorPin[4])<MinFlameVlaue){
      pumpOn();
      delay(1000);}  
  }
  else if(readSensorDio() == 18 && !digitalRead(sensorPin[4]) < MaxFlameVlaue){
    {Serial.println("sirens on");
     //sirenOn(LedBlue, LedRed, Buzzer);
     delay(1000);}
    if(one80forward < 10)
    {
      Serial.println("gas dected ,looking around for fire");
      CAR_turnRightWifi();
      one80forward++;}
    else{
        CurrentDistance = DistanceMeasure();
        if(CurrentDistance < 20){//check if no obstacle ahead
        Serial.println("obstacle ahead");
        obstacleAvoid();}
        }
    {Serial.println("move forawrd");//taking step forward
     CAR_moveForwardWifi();
      delay(1000);}
    one80forward = 0;
    }

but what if the start is with flame in the front?
or i missing something?

Sorry. I was backwards all this time.

If you are creating an array of pins, use a comma (,) separator and end braces.

int sensorPin = {4, 16, 17, 18}; // enclosed by braces "{}" separated by comma ","

The front flame sensor (digital) should indicate the robot goes forward... and then uses the analog fire sensor to measure "0" inside flame/too close/reverse to "4095" keep moving forward, the other ranges will tell the robot to stop and use the pump.

yeah i gotcha now.
didnt register using both digital and analog to front sensor.

how do i read sensor pins sequentially?
like in your example post #13

for (int i = 15; i < 19; i++) { // 15 = right, 16 = forward, 17 = left, 18 = gas
  if (digitalRead(sensorPin[i]) 

what i am struggling with is
is defined the pins by names


// define pins for flame sensor
#define FlamePinForawrdAnlog 4
#define FlamePinRight 15
#define FlamePinRight 16
#define FlamePinLeft  17

but how i make work with an array?

int sensorPin[FlamePinRight,FlamePinRight,FlamePinLeft,GasSensorDi];

and then the for loop i++ move correctly through the entries?
also, after the first loop i basically save boolean values into the array.
in the next for loop it will have trouble to go through the array in 15 to 18 .