ESP32 wroom not connects platformio but is not online on website

I cant get this to connect to blynk online. It’s strange, I did at one point when I first created the project, I had my water drop sensor updating on the website. Went back a few days later and it doesn’t connect anymore. I tried new auth token, disconnecting power sources like sensors, and switching code like the port 80 to 8080 and different positions of Blynk.begin(). Am I missing something or is it my esp32 Wroom device? I also put some of the blynk.virtualwrite in the void loop would that have blocked my device?

I put my device information here:

CONFIGURATION: https://docs.platformio.org/page/boards/espressif32/esp32dev.html
PLATFORM: Espressif 32 (6.6.0) > Espressif ESP32 Dev Module
HARDWARE: ESP32 240MHz, 320KB RAM, 4MB Flash
DEBUG: Current (cmsis-dap) External (cmsis-dap, esp-bridge, esp-prog, iot-bus-jtag, jlink, minimodule, olimex-arm-usb-ocd, olimex-arm-usb-ocd-h, olimex-arm-usb-tiny-h, olimex-jtag-tiny, tumpa)
PACKAGES: 
 - framework-arduinoespressif32 @ 3.20014.231204 (2.0.14) 
 - tool-esptoolpy @ 1.40501.0 (4.5.1) 
 - tool-mkfatfs @ 2.0.1 
 - tool-mklittlefs @ 1.203.210628 (2.3) 
 - tool-mkspiffs @ 2.230.0 (2.30) 
 - toolchain-xtensa-esp32 @ 8.4.0+2021r2-patch5
LDF: Library Dependency Finder -> https://bit.ly/configure-pio-ldf
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 37 compatible libraries
Scanning dependencies...
Dependency Graph
|-- OneWire @ 2.3.8
|-- DallasTemperature @ 3.11.0
|-- Blynk @ 1.3.2
|-- ESP32 Async UDP @ 2.0.0
|-- Preferences @ 2.0.0
|-- WebServer @ 2.0.0
|-- WiFi @ 2.0.0

; Please visit documentation for the other options and examples

; https://docs.platformio.org/page/projectconf.html

[env:upesy_wroom]

platform = espressif32

board = esp32dev

framework = arduino

monitor_speed = 115200

lib_deps =

OneWire

DallasTemperature

Blynk

Console output

Access Point Started
AP IP Address: 
192.168.4.1
Attempting to connect to SSID: The LAN before Time
.
Connected to Wi-Fi!

Connected to Blynk!
IP Address: 192.168.0.238
SoftAP disconnected.
Flow rate: 0.00 L/min
Number of devices found on bus: 0
No devices found
Digital Output: 0, Analog Output: 117
[7306] Connecting to 0.0.0.0
[ 25577][E][WiFiClient.cpp:275] connect(): socket error on fd 49, errno: 113, "Software caused connection abort"
Flow rate: 0.00 L/min
Number of devices found on bus: 0
No devices found
Digital Output: 0, Analog Output: 0
[30593] Connecting to 0.0.0.0
[ 49113][E][WiFiClient.cpp:275] connect(): socket error on fd 49, errno: 113, "Software caused connection abort"
Flow rate: 0.00 L/min
Number of devices found on bus: 0
No devices found
Digital Output: 0, Analog Output: 2
[54128] Connecting to 0.0.0.0
[ 72648][E][WiFiClient.cpp:275] connect(): socket error on fd 49, errno: 113, "Software caused connection abort"
Flow rate: 0.00 L/min
Number of devices found on bus: 0
No devices found
Digital Output: 0, Analog Output: 0
[77663] Connecting to 0.0.0.0
[ 96183][E][WiFiClient.cpp:275] connect(): socket error on fd 49, errno: 113, "Software caused connection abort"
F
// Created by Jacob Lamkey

#include <Arduino.h>
#include "LidarHelper.h" // Include the LiDAR helper file
#include "WifiHelper.h"
#include "SensorHelper.h"

void setup() {

    // Start the serial communication:
    Serial.begin(115200);
    Serial2.begin(230400, SERIAL_8N1, 16, 17); // Baud rate and UART2 pins lidar
    sensors.begin(); 

    pinMode(flowPin, INPUT_PULLUP); // water flow pin Set flow sensor pin as input
    pinMode(relayPin, OUTPUT); // Set the relay pin as an output for lidar
    pinMode(hunterPin, OUTPUT); // Set relay pin as output
    pinMode(digitalPin, INPUT); // water drop sensor
    pinMode(analogPin, INPUT);  // Set analog pin as input

   // checkDeviceIP();
    attachInterrupt(digitalPinToInterrupt(flowPin), pulseCounter, RISING); // Interrupt on rising edge
    flowMillis = millis();
    // Connect to Wi-Fi
    setupAccessPointAndServer();

    digitalWrite(relayPin, LOW); // Start with the relay off
}

void loop() {

    server.handleClient();
    handleLidarData();    
    waterFlowSensor();

    static unsigned long lastReadingTime = 0;
   // if (millis() - lastReadingTime >= 5000) {
    tempSensor();  // Get temperature reading
     //   lastReadingTime = millis();
    //}

    //if (millis() - lastReadingTime >= 5000) {
    
    waterDropSensor(); // Add this line to call the water drop sensor function
     //   lastReadingTime = millis();
    //}

    if (delayRunning && (millis() - delayStart >= 100000)) {
        delayRunning = false;
        // Delay has finished, perform any actions that should happen after the delay
        if (WiFi.status() == WL_CONNECTED) {
            WiFi.softAPdisconnect(true);
            Serial.println("Access Point Stopped");
        };
    }
    
    Blynk.run();

    // delay(1000);
}

// WifiHelper.h
#ifndef WIFI_HELPER_H
#define WIFI_HELPER_H

#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPL2MJ_30SAi"
#define BLYNK_TEMPLATE_NAME "ESP32Sensor"
#define BLYNK_AUTH_TOKEN "ZPd901JgdiSGUOP7HMna9V9tRRMKcboD"

// #define BLYNK_FIRMWARE_VERSION "0.1.0"
#define APP_DEBUG
#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>
#include "LidarHelper.h"
#include <Preferences.h>
#include <WiFiUdp.h>
#include <AsyncUDP.h>
#include "SensorHelper.h"
#include <BlynkSimpleEsp32.h>

Preferences preferences;

//const char* globalSSID = "The LAN before Time";     // Replace with your network SSID
//const char* globalPassword = "Jbl?8042"; // Replace with your network password
const char* SSID = "lidar";     // Replace with your network SSID
const char* Password = "123456789"; // Replace with your network password

bool relayState = false; // Variable to hold the relay state
const int relayPin = 13;  // Relay connected to GPIO 13
// String state = "";
// WiFiUDP udp;
//AsyncUDP udp;

LidarPacket latestPacket;
//
//WebServer server(80);
bool isConnected = false; // Flag to check connection status

uint8_t globalByte;
String lidarDataBuffer = "";
String ipAddressStr = "";
//IPAddress ipAddress; // For storing the converted IP address
String ssidBlynk = "";
String passwordBlynk = "";

unsigned long delayStart = 0;
bool delayRunning = false;

const int SOME_MAX_SIZE = 46 * 2; // 7200 bytes * 2 characters per byte
//const int PACKET_SIZE = sizeof(LidarPacket);
//unsigned int udpPort = 8042; // Example port number
const char* data = "Hello, UDP!";
char incomingPacket[255];  // Buffer for incoming packets
const int rele = 23;
int stateNum = 0;   // 0 = undefined, 1 = on, 2 = off

void handleRelayToggle() {
    if (server.hasArg("state")) {
        state = server.arg("state");

        if (state == "on") {
            digitalWrite(relayPin, HIGH); // Turn on the relay
            stateNum = 1;
        } else if (state == "off") {
            digitalWrite(relayPin, LOW); // Turn off the relay
            stateNum = 2;
        }
        server.send(200, "text/plain", "Relay state set to " + state);
        Serial.println("State is set to " + state);
        
        Blynk.virtualWrite(V3, stateNum); // Send flowRate to virtual pin V1

    } else {
        server.send(400, "text/plain", "Missing 'state' parameter");
    } 
}

// Blynk handler to receive commands from the Blynk app
BLYNK_WRITE(V3) {
    stateNum = param.asInt(); // Get the state number (1 for on, 2 for off)

    if (stateNum == 1) {
        digitalWrite(relayPin, HIGH); // Turn on the relay
        Serial.println("Relay turned ON via Blynk");
    } else if (stateNum == 2) {
        digitalWrite(relayPin, LOW); // Turn off the relay
        Serial.println("Relay turned OFF via Blynk");
    }
}

void handleReceiveIP() {
    if (server.hasArg("ip")) {
        ipAddressStr = server.arg("ip");
        if (ipAddress.fromString(ipAddressStr)) { // Convert String to IPAddress
            Serial.println("Received and converted IP: " + ipAddressStr);
            // Now, you can use ipAddress with udp.begin
            delay(1000);
            //Serial.println("UDP server started");
            server.send(200, "text/plain", "IP Address received and UDP started: " + ipAddressStr);
        } else {
            Serial.println("Invalid IP address received");
            server.send(400, "text/plain", "Invalid IP address");
        }
    } else {
        server.send(400, "text/plain", "Missing IP address");
    }
}

void handleRoot() {
  server.send(200, "text/plain", "\n ESP32 is connected to Wi-Fi.");
}

// Function to handle removal of Wi-Fi configuration

bool removeWiFiConfiguration() {
    Preferences preferences;
    preferences.begin("wifi", false);

    preferences.remove("homeSSID");
    preferences.remove("homePassword");
    preferences.remove("cellularSSID");
    preferences.remove("cellularPassword");

    preferences.end();

    return true; // Return true if successful, otherwise handle failure as needed
}

void handleRemoveWiFi() {
    if (server.hasArg("action")) {
        String action = server.arg("action");
        if (action == "remove_wifi") {
            if (removeWiFiConfiguration()) {

                Serial.println("Wifi Configuration moved");
                server.send(200, "text/plain", "Wi-Fi configuration removed");
            } else {
                server.send(500, "text/plain", "Failed to remove Wi-Fi configuration");
            }
        } else {
            server.send(400, "text/plain", "Invalid action");
        }
    } else {
        server.send(400, "text/plain", "Missing action parameter");
    }
}
bool connectToWiFi(String ssid, String password) {
    if (ssid.isEmpty() || password.isEmpty()) {
        Serial.println("Missing SSID or Password in the request");
        server.send(400, "text/plain", "Missing SSID or Password");
        return false;
    }

    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);

    // Optional: Static IP configuration
    IPAddress staticIP(WiFi.localIP());  // Use the current local IP (if any)
    IPAddress gateway(WiFi.gatewayIP());  // Gateway (your router IP)
    IPAddress subnet(WiFi.subnetMask());   // Subnet mask
IPAddress primaryDNS(1, 1, 1, 1);      // Cloudflare Primary DNS
IPAddress secondaryDNS(1, 0, 0, 1);    // Cloudflare Secondary DNS

    // Only configure static IP if the current IP is valid
    if (staticIP != IPAddress(0, 0, 0, 0) && !WiFi.config(staticIP, gateway, subnet,primaryDNS,secondaryDNS)) {
        Serial.println("STA Failed to configure static IP");
    }

    // Attempt to connect to the new Wi-Fi network
    WiFi.begin(ssid.c_str(), password.c_str());

    unsigned long startTime = millis();
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
        if (millis() - startTime > 30000) { // 30-second timeout
            Serial.println("\nFailed to connect to Wi-Fi.");
            server.send(500, "text/plain", "Failed to connect to Wi-Fi");
            return false;
        }
    }


    Serial.println("\nConnected to Wi-Fi!");
    Serial.println("\nConnected to Blynk!");
    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());

    // Disconnect from the SoftAP
    WiFi.softAPdisconnect(true);
    Serial.println("SoftAP disconnected.");

    passwordBlynk = password;
    ssidBlynk = ssid;
    // Send a successful response
    server.send(200, "text/plain", "Connected to new Wi-Fi successfully");
    return true;
}

void setupAccessPointAndServer() {
    Preferences preferences; // Create a Preferences object
    preferences.begin("wifi", false); // Open the NVS namespace "wifi"

    // Retrieve Wi-Fi configurations from NVS
    String homeSSID = preferences.getString("homeSSID", "");
    String homePassword = preferences.getString("homePassword", "");
    String cellularSSID = preferences.getString("cellularSSID", "");
    String cellularPassword = preferences.getString("cellularPassword", "");

    // Start ESP32 as an Access Point
    WiFi.softAP(SSID, Password);
    Serial.println("Access Point Started");
    Serial.println("AP IP Address: ");
    Serial.println(WiFi.softAPIP());

    // Try connecting to home Wi-Fi first, then cellular network
    if (!connectToWiFi(homeSSID, homePassword)) {
        Serial.println("Failed to connect to home Wi-Fi, trying cellular...");

        if (!connectToWiFi(cellularSSID, cellularPassword)) {
            Serial.println("Failed to connect to both home and cellular Wi-Fi");

        }
    }

    // Setup server routes
    server.on("/setup", HTTP_POST, [&]() {
        Serial.println("Received a request on /setup");

        // Get SSIDs and passwords from the request
        String newHomeSSID = server.arg("homeSSID");
        String newHomePassword = server.arg("homePassword");
        String newCellularSSID = server.arg("cellularSSID");
        String newCellularPassword = server.arg("cellularPassword");

        // Save SSIDs and passwords to NVS
        if (!newHomeSSID.isEmpty() && !newHomePassword.isEmpty()) {
            preferences.putString("homeSSID", newHomeSSID);
            preferences.putString("homePassword", newHomePassword);
            Serial.println("New Home SSID and Password saved");
        }

        if (!newCellularSSID.isEmpty() && !newCellularPassword.isEmpty()) {
            preferences.putString("cellularSSID", newCellularSSID);
            preferences.putString("cellularPassword", newCellularPassword);
            Serial.println("New Cellular SSID and Password saved");
        }

        server.send(200, "text/plain", "Wi-Fi configuration saved");

        // Attempt to reconnect with the new credentials
        if (!connectToWiFi(newHomeSSID, newHomePassword)) {
            if (!connectToWiFi(newCellularSSID, newCellularPassword)) {
                server.send(500, "text/plain", "Failed to connect to new Wi-Fi");
            }
        }
    });

    server.on("/getIP", HTTP_GET, []() {
        if (WiFi.status() == WL_CONNECTED) {
            server.send(200, "text/plain", WiFi.localIP().toString());
            Blynk.begin(BLYNK_AUTH_TOKEN, ssidBlynk.c_str(), passwordBlynk.c_str(), "blynk-cloud.com", 8080);

            Serial.println("Send localIP to swift");
        } else {
            server.send(404, "text/plain", "Not connected to WiFi");
        }
    });     

    server.on("/receiveIP", HTTP_GET, handleReceiveIP);

    server.on("/wifiConnected", handleRoot);

    preferences.end(); // Close the NVS namespace

    server.on("/toggleRelay", HTTP_GET,  handleRelayToggle);

    server.on("/toggleValve", HTTP_GET, handleToggleValve);

    server.on("/flowrate", HTTP_GET, handleFlowRate); // Endpoint to get the flow rate

    server.on("/waterdrops", HTTP_GET, handleWaterDropSensor);

    server.on("/temp", HTTP_GET, tempSensor);

    server.on("/remove_wifi", HTTP_POST, handleRemoveWiFi);

    delay(1000);
    server.begin();

    // Blynk.config(BLYNK_AUTH_TOKEN, "blynk-cloud.com", 80);  // Explicitly set the server
    // Blynk.connect();
    server.send(200, "text/plain", "ESP32 setup Successfull");

    //delay(100000);
    //isConnected = true;
   // WiFi.softAPdisconnect(true);
    //Serial.println("Access Point Stopped");
    //delayStart = millis();
    //delayRunning = true;
}


#endif

Why are you doing all of this stuff with the captive portal/SoftAP in your sketch?

Your current code will never connect to Blynk IoT, because you’re using a url of blynk-cloud.com which is the legacy url which was decommissioned two years ago. The correct url is blynk.cloud but use of the url and port are optional in the blynk.begin() command anyway.

Your use of a serial print statement which says “Blynk connected!” Is extremely confusing when you’re debugging, because there is no code which checks that Blynk is actually connected before this is printed, so it’s misleading.

You should all #define BLYNK_PRINT Serial to your sketch so that you can see info from the Blynk library regarding connection attempts and connection status instead of trying to include your own misleading debug info.

Your void loop isn’t compatible with Blynk, as it’s too cluttered. It calls quite a few functions which aren’t 8ncluded 8n the code you’ve shared, so it’s possible that, if these contain Blynk.virtualWrite() commands you would be spamming the Blynk server if you were able to establish a connection.

I’d recommend starting again, with a non-Edgent example sketch, and a more conventional code structure.

Pete.

1 Like

I added the timers to my setupAccessPointAndServer() function and moved the blynk.begin() function to my connectToWiFi() function and it works now.

    // Schedule the sensor readings using BlynkTimer
    timer.setInterval(300000L, waterFlowSensor);    // Call waterFlowSensor() every 2 seconds 300000 is 5 minutes
    timer.setInterval(300000L, tempSensor);         // Call tempSensor() every 3 seconds
    timer.setInterval(900000L, waterDropSensor);    // Call waterDropSensor() every 4 seconds 900000 is 15 minutes