Code Just loops in serial Monitor

The code i have uploaded just loops this in the serial monitor without connectin to the wiFi or establashing a webserver.

ESP-ROM:esp32s2-rc4-20191025

Build:Oct 25 2019

rst:0x8 (TG1WDT_SYS_RST),boot:0x8 (SPI_FAST_FLASH_BOOT)

Saved PC:0x4002c8ec

SPIWP:0xee
Connected to WiFi

ESP-ROM:esp32s2-rc4-20191025

Build:Oct 25 2019

rst:0x8 (TG1WDT_SYS_RST),boot:0x8 (SPI_FAST_FLASH_BOOT)
Connected to WiFi

#include <WiFi.h>
#include <AsyncTCP.h>
#include <AsyncElegantOTA.h>
#include <ESPAsyncWebServer.h>

// Configure WiFi connection
const char* ssid = "SSID";
const char* password = "Pass";

// Configure the HC-SR04 sensors
const int echo_top = 17;
const int trigger_top = 16;
const int echo_bottom = 18;
const int trigger_bottom = 19;

// Configure the relay
const int relay_pin = 27;
int relay_state = LOW;

// Initialize objects
AsyncWebServer server(80);

// Function to measure distance using HC-SR04
float measure_distance(int echo_pin, int trigger_pin) {
  // Send trigger signal
  digitalWrite(trigger_pin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigger_pin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigger_pin, LOW);
  // Measure echo signal
  float pulse_time = pulseIn(echo_pin, HIGH);
  float distance = pulse_time / 58.0;
  return distance;
}

// Function to toggle the relay
void toggleRelay() {
  relay_state = !relay_state;
  digitalWrite(relay_pin, relay_state);
}

// Handle HTTP requests
void handle_request(AsyncWebServerRequest* request) {
  String request_string = request->url();
  if (request_string == "/") {
    // Read sensor data
    float distance_top = measure_distance(echo_top, trigger_top);
    float distance_bottom = measure_distance(echo_bottom, trigger_bottom);
    // Determine door state
    int door_state_top, door_state_bottom, garage_door;
    if (distance_top >= 5.0 && distance_top < 10.0) {
      door_state_top = 3;
    } else if (distance_top >= 10.0 && distance_top < 300.0) {
      door_state_top = 2;
    } else {
      door_state_top = 1;
    }
    if (distance_bottom >= 5.0 && distance_bottom < 10.0) {
      door_state_bottom = 3;
    } else if (distance_bottom >= 10.0 && distance_bottom < 300.0) {
      door_state_bottom = 2;
    } else {
      door_state_bottom = 1;
    }
    if (door_state_top == 3 && door_state_bottom == 3) {
      garage_door = 3;
    } else if (door_state_top == 1 && door_state_bottom == 1) {
      garage_door = 1;
    } else {
      garage_door = 2;
    }
    // Set JSON response
    String response = "{";
    response += "\"distance_top\":" + String(distance_top) + ",";
    response += "\"distance_bottom\":" + String(distance_bottom) + ",";
    response += "\"door_status\":" + String(garage_door) + "}";
    request->send(200, "application/json", response);
  } else if (request_string == "/toggle") {
    // Toggle the relay and send response
    toggleRelay();
    request->send(200, "text/plain", "OK");
  }
}

void setup() {
  // Set up serial communication
  Serial.begin(115200);
  // Connect to Wi-Fi network
  WiFi.begin(ssid, password);  // Replace SSID and password with your own network details
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  // Set up pins
  pinMode(echo_top, INPUT);
  pinMode(trigger_top, OUTPUT);
  pinMode(echo_bottom, INPUT);
  pinMode(trigger_bottom, OUTPUT);
  pinMode(relay_pin, OUTPUT);

  // Start the asynchronous web server
  server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
    handle_request(request);
  });

  // Start the ElegantOTA service
  AsyncElegantOTA.begin(&server);

  // Print the IP address of the server over the serial console
  Serial.print("Local IP address: ");
  Serial.println(WiFi.localIP());

  // Initialize the relay to the off position
  digitalWrite(relay_pin, LOW);
}
void loop() {
  delay(10000);
}

This is just a statement.
What is your question?
If you are too lazy to even write down a specific question
The users here are too lazy to speculate what your question might be

what do you think is the meaning of the comment above these two lines of code?

best regards Stefan

1 Like

Well the obvious thing is check the SSID and password are correct.

Is your mystery board plugged into breadboard? If so is the aerial close to the breadboard contacts?

What exactly does 'loop in the serial monitor ' mean? Paste the output here in code tags.

It might be that your code is causing a reset which makes your code start again over and over

Add Serial.prints in your setup-function to narrow down where in the code the reset occurs

Here is a demo-code for ESP32-boards which prints more information to the serial monitor.

// Demo-Code connect an ESP32 to a WiFi-network using stationmode STA

// stationmode is simply join the WiFi-network as your computer or smartphone does it
// the code has three useful functions one for easy identifiying the code in the flash
// one for non-blocking timing
// a heartbeat-blinker function for indicating the state the code is in

// the code is written with two programming rules:
// 1. put EACH functionality into its OWN function
// 2. give EACH function a SELF-explaining name what the function does
// you should follow these programming rules
#include <WiFi.h>

// fill in YOUR SSID and YOUR password
const char *ssid     = "YOUR SSID??";
const char *password = "YOUR password?";


void PrintFileNameDateTime() {
  Serial.println( F("Code running comes from file ") );
  Serial.println( F(__FILE__));
  Serial.print( F("  compiled ") );
  Serial.print(F(__DATE__));
  Serial.print( F(" ") );
  Serial.println(F(__TIME__));
}


boolean TimePeriodIsOver (unsigned long &periodStartTime, unsigned long TimePeriod) {
  unsigned long currentMillis  = millis();
  if ( currentMillis - periodStartTime >= TimePeriod )
  {
    periodStartTime = currentMillis; // set new expireTime
    return true;                // more time than TimePeriod) has elapsed since last time if-condition was true
  }
  else return false;            // not expired
}

unsigned long MyTestTimer = 0; // variables MUST be of type unsigned long
const byte    OnBoard_LED = 2;


void BlinkHeartBeatLED(int IO_Pin, int BlinkPeriod) {
  static unsigned long MyBlinkTimer;
  pinMode(IO_Pin, OUTPUT);

  if ( TimePeriodIsOver(MyBlinkTimer, BlinkPeriod) ) {
    digitalWrite(IO_Pin, !digitalRead(IO_Pin) );
  }
}

void ScanForWiFis() {
  Serial.println("start scanning for WiFi...");
  int numberOfNetworks = WiFi.scanNetworks();
  Serial.println("scanning finished");
  Serial.print("number of networks: ");
  Serial.println(numberOfNetworks);

  for (int i = 0; i < numberOfNetworks; i++) {

    Serial.print("Network name: ");
    Serial.println(WiFi.SSID(i));
    Serial.print("Signal strength: ");
    Serial.println(WiFi.RSSI(i));
    Serial.println("---------------------- -");
  }
}


void ConnectToWiFi() {
  const byte maxCount = 60;
  
  WiFi.mode(WIFI_STA);
  Serial.println("WiFi.mode(WIFI_STA)");

  int myCount = 0;

  Serial.print("trying to connect to #");
  Serial.print(ssid);
  Serial.println("#");
  WiFi.begin(ssid, password);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED && myCount < maxCount) {
    BlinkHeartBeatLED(OnBoard_LED, 50); // blink LED fast during attempt to connect
    yield();
    if ( TimePeriodIsOver(MyTestTimer, 500) ) { // once every 500 miliseconds
      Serial.print(".");                        // print a dot
      myCount++;

      if (myCount > maxCount) { // after 60 dots = 30 seconds restart
        Serial.println();
        Serial.print("trying to connect to WiFi with SSID ");
        Serial.print(ssid);
        Serial.println(" failed start scanning WiFis");
        ScanForWiFis();
        Serial.print("are you sure that the SSID ");
        Serial.println(ssid);
        Serial.print(" and password are correct ? ");

      }
    }
  }

  if (WiFi.status() == WL_CONNECTED ) {
    Serial.println("");
    Serial.print("Connected to #");
    Serial.print(ssid);
    Serial.print("# IP address: ");
    Serial.println(WiFi.localIP());
  }

}

void setup() {
  Serial.begin(115200);
  Serial.println( F("Setup - Start") );
  PrintFileNameDateTime();
  ConnectToWiFi();
}

void PrintHelloMsg() {
  Serial.print( F("Hi there I'm the demo-code my IP address is: ") );
  Serial.println(WiFi.localIP());
}


void loop() {
  BlinkHeartBeatLED(OnBoard_LED, 500); // change blinking to a lower frequency indicating beeing connected

  if ( TimePeriodIsOver(MyTestTimer, 1000) ) {
    PrintHelloMsg();
  }
}



/*
  most ESP32 boards have a blue LED connected to GPIO-pin 2
  This blue LED is used to indicate state connecting to WiFi by blinking fast
  state beeing connected to Wifi by blinking with 1 Hz

  If the WiFi-connection is successfully established the serial monitor shows

  08:44:02.915 -> Setup-Start
  08:44:02.915 -> Code running comes from file
  08:44:02.915 -> your-path\ESP32-connect-to-Wifi-Demo-001\ESP32-connect-to-Wifi-Demo-001.ino
  08:44:02.915 ->   compiled date/time of compiling
  08:44:02.971 -> WiFi.mode(WIFI_STA)
  08:44:02.971 -> trying to connect to #Your SSID#
  08:44:03.362 -> ....
  08:44:04.215 -> Connected to #Your SSID# IP address: given IP-adress NNN.NNN.NNN.NNN
  08:44:04.865 -> Hi there I'm the demo - code my IP address is : NNN.NNN.NNN.NNN

if trying to connect to the wifi fails the code scans for WiFis 
and lists up all found SSIDs
So you can compare the SSIDs with the one used in the code

*/

If your board is not an ESP32 post the exact type of board you are using

best regards Stefan

Hi yes the board is an esp32.

Im not sure what had happened. It didnt seem to be a brownout. But yes something in the code was causing a loop.

I did remove my wifi credentials and added the generic SSID and Pass.

I rewrote the code using a differnet libraries.

I suspect it was something in the way i was calling the AsyncElegantOTA.begin(&server).

But if that was it im not sure. But thank you to everyone who commented.

And apologies for not formulating my problem better.

But all that was happening was the serial monitor was stuck in a loop. Not establishing an actual connection to the router.

Typically the esp32 displays an ip address and i can view that device from the router or via the ip address but niether of those methods worked. Once the ip address is obtained the serial monitor would either show the outputs being requested or not print anything else.
This was just looping the same pieces of information and completing the full connection.

Have you now got it working?

Yes i have got it working..but not using that code. I just rewrote the whole thing.

1 Like

How about posting the working code as a thank you to the community?

2 Likes

Totally agree @StefanL38.

I would if i had a working code thats complete.

I have solved the issue of the boot. But i have about 10 more im currently working through.
So once i have those done. I will be sure to add the working version of the code.

Coding is still new to me. So i have a lot to learn

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.