ESP32 IoT Project
Overview
This project demonstrates how to manage Wi-Fi connections and interact with a server using an ESP32. The goal is to provide an efficient solution for handling dynamic Wi-Fi connections and device control through HTTP requests. We also include methods for resetting Wi-Fi credentials and troubleshooting common issues.
Wi-Fi Manager with AutoConnect and Reset Option
The ESP32 uses the WiFiManager library to simplify the Wi-Fi setup process. The following code demonstrates how to enable AutoConnect with an option to reset the Wi-Fi settings by holding a button for more than two seconds.
Example Code
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <WiFi.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
// Replace with the server URL
const char* serverURL = "http://your-server.local/ESP32_MySql_Database/Final/get_device_status.php";
int ledPin = 2; // GPIO for the LED
int devicePins[] = {2, 4, 5}; // Array to control multiple devices (one GPIO per device)
int resetButtonPin = 0; // GPIO pin for reset button
unsigned long buttonPressTime = 0;
bool resetWiFi = false;
void setup() {
Serial.begin(115200);
// Initialize reset button pin
pinMode(resetButtonPin, INPUT_PULLUP);
// Check if reset button is held down
if (digitalRead(resetButtonPin) == LOW) {
buttonPressTime = millis();
while (digitalRead(resetButtonPin) == LOW) {
if (millis() - buttonPressTime > 2000) {
resetWiFi = true;
break;
}
}
}
// Initialize WiFiManager
WiFiManager wm;
if (resetWiFi) {
wm.resetSettings(); // Reset Wi-Fi settings
Serial.println("Wi-Fi settings reset. Restarting...");
ESP.restart();
}
// Attempt to auto-connect to WiFi with WiFiManager
bool res = wm.autoConnect("AutoConnectAP", "password"); // AP name and password
if (!res) {
Serial.println("Failed to connect to Wi-Fi");
ESP.restart();
} else {
Serial.println("Connected to Wi-Fi!");
}
// Initialize device pins
for (int pin : devicePins) {
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
}
}
void loop() {
// Ensure Wi-Fi is still connected
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(serverURL);
int httpResponseCode = http.GET();
if (httpResponseCode == 200) {
String response = http.getString();
Serial.println("Received response:");
Serial.println(response);
// Parse JSON
DynamicJsonDocument doc(1024);
deserializeJson(doc, response);
// Control each device based on the JSON response
for (JsonObject device : doc.as<JsonArray>()) {
int id = device["id"];
int status = device["status"];
// Control devices within devicePins array bounds
if (id <= sizeof(devicePins) / sizeof(devicePins[0])) {
digitalWrite(devicePins[id - 1], status == 1 ? HIGH : LOW);
Serial.print("Device ");
Serial.print(id);
Serial.print(" Status: ");
Serial.println(status == 1 ? "ON" : "OFF");
}
}
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("Wi-Fi not connected");
}
delay(5000); // Check every 5 seconds
}
PHP Script for Server-Side Handling
The server-side PHP script handles incoming HTTP requests and returns the status of connected devices as JSON. Below is an example of a PHP script to interact with the database and return device status:
Example PHP Code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "esp32_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, status FROM devices";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$devices = array();
while ($row = $result->fetch_assoc()) {
$devices[] = $row;
}
header('Content-Type: application/json');
echo json_encode($devices);
} else {
echo "[]"; // Empty JSON array if no data is found
}
$conn->close();
?>
Working Video:
Troubleshooting Tips
Ensure the ESP32 and server are on the same network.
Use the actual IP address of the server if
http://mycomputer.local
does not resolve.Verify that the PHP script is hosted correctly on the server (e.g., using XAMPP or a similar tool).
Check for any firewall or network restrictions.
No comments:
Post a Comment