I tried changing the IP address of the WiFi connected to the router, when I applied it the IP address wouldn't change. What is wrong?
#include <WiFi.h>
#include <ModbusIP_ESP8266.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <FS.h>
#include <SPIFFS.h>
// WiFi credentials
String routerSSID = "";
String routerPassword = "";
// AP Mode credentials
const char* apSSID = "ESP_AP";
const char* apPassword = "password123";
// Static IP configuration
IPAddress staticIP;
IPAddress gateway;
IPAddress subnet(255, 255, 255, 0);
IPAddress dns1(8, 8, 8, 8); // Google DNS
IPAddress dns2(8, 8, 4, 4); // Google DNS alternate
bool useStaticIP = false;
// Modbus TCP server
ModbusIP mb;
const int modbusPort = 502; // Default Modbus port
// GPIO pin definitions
const int touchPin1 = T0;
const int touchPin2 = T3;
const int touchPin3 = T6;
const int touchPin4 = T7;
const int outputPin = 4; // Using GPIO4 as output
const int buttonPin = 5; // Using GPIO5 as button pin
// Modbus registers
const int REG_TOUCH1 = 0;
const int REG_TOUCH2 = 1;
const int REG_TOUCH3 = 2;
const int REG_TOUCH4 = 3;
const int REG_OUTPUT = 4;
AsyncWebServer server(80);
bool isServerRunning = false;
unsigned long lastWiFiCheckMillis = 0;
const long wifiCheckInterval = 30000; // Check WiFi connection every 30 seconds
int failedWiFiConnections = 0;
bool isAPMode = false;
void resetSettings() {
routerSSID = "";
routerPassword = "";
useStaticIP = false;
saveWiFiCredentials();
saveStaticIPConfig();
Serial.println("Semua pengaturan direset ke nilai default");
}
void loadWiFiCredentials() {
if (SPIFFS.exists("/wifi_creds.txt")) {
File file = SPIFFS.open("/wifi_creds.txt", "r");
if (file) {
routerSSID = file.readStringUntil('\n');
routerPassword = file.readStringUntil('\n');
routerSSID.trim();
routerPassword.trim();
Serial.println("Kredensial WiFi dimuat: " + routerSSID);
file.close();
}
}
}
void saveWiFiCredentials() {
File file = SPIFFS.open("/wifi_creds.txt", "w");
if (file) {
file.println(routerSSID);
file.println(routerPassword);
file.close();
Serial.println("Kredensial WiFi disimpan");
}
}
void saveStaticIPConfig() {
File file = SPIFFS.open("/static_ip.txt", "w");
if (file) {
file.println(useStaticIP);
file.println(staticIP.toString());
file.println(gateway.toString());
file.println(subnet.toString());
file.println(dns1.toString());
file.println(dns2.toString());
file.close();
Serial.println("Konfigurasi IP statis disimpan");
}
}
void loadStaticIPConfig() {
if (SPIFFS.exists("/static_ip.txt")) {
File file = SPIFFS.open("/static_ip.txt", "r");
if (file) {
useStaticIP = file.readStringUntil('\n').toInt();
staticIP.fromString(file.readStringUntil('\n'));
gateway.fromString(file.readStringUntil('\n'));
subnet.fromString(file.readStringUntil('\n'));
dns1.fromString(file.readStringUntil('\n'));
dns2.fromString(file.readStringUntil('\n'));
file.close();
Serial.println("Konfigurasi IP statis dimuat");
}
}
}
void saveWiFiMode(WiFiMode_t mode) {
File file = SPIFFS.open("/wifi_mode.txt", "w");
if (file) {
file.println(static_cast<int>(mode));
file.close();
Serial.println("Mode WiFi disimpan");
}
}
WiFiMode_t loadWiFiMode() {
WiFiMode_t mode = WIFI_AP_STA; // Default mode
if (SPIFFS.exists("/wifi_mode.txt")) {
File file = SPIFFS.open("/wifi_mode.txt", "r");
if (file) {
String modeStr = file.readStringUntil('\n');
modeStr.trim();
mode = (WiFiMode_t)modeStr.toInt();
file.close();
}
}
return mode;
}
bool checkInternetConnection() {
WiFiClient client;
if (!client.connect("www.google.com", 80)) {
Serial.println("Gagal terhubung ke www.google.com");
return false;
}
Serial.println("Berhasil terhubung ke www.google.com");
client.stop();
return true;
}
void startAPMode() {
WiFi.mode(WIFI_AP);
WiFi.softAP(apSSID, apPassword);
isAPMode = true;
Serial.println("Mode AP dimulai");
Serial.print("IP Address AP: ");
Serial.println(WiFi.softAPIP());
}
void connectToWiFi() {
int attempts = 0;
const int maxAttempts = 20;
Serial.println("Menghubungkan ke WiFi...");
if (useStaticIP) {
if (!WiFi.config(staticIP, gateway, subnet, dns1, dns2)) {
Serial.println("Gagal mengonfigurasi Static IP");
}
}
WiFi.begin(routerSSID.c_str(), routerPassword.c_str());
while (WiFi.status() != WL_CONNECTED && attempts < maxAttempts) {
delay(500);
Serial.print(".");
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
isAPMode = false;
Serial.println("\nTerhubung ke WiFi");
Serial.print("Alamat IP: ");
Serial.println(WiFi.localIP());
Serial.print("Modbus port: ");
Serial.println(modbusPort);
unsigned int signalStrength = WiFi.RSSI();
int signalQuality = getSignalQuality(signalStrength);
Serial.print("Kekuatan sinyal WiFi: ");
Serial.println(signalQuality);
} else {
Serial.println("\nGagal terhubung ke WiFi");
startAPMode();
}
}
void resetWiFiConnection() {
WiFi.disconnect(true);
delay(1000);
connectToWiFi();
}
void setupServerRoutes() {
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(SPIFFS, "/index.html", "text/html");
});
server.on("/assets/css/foundation.css", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(SPIFFS, "/assets/css/foundation.css", "text/css");
});
server.on("/reset", HTTP_POST, [](AsyncWebServerRequest *request) {
resetSettings();
request->send(200, "text/plain", "Semua pengaturan direset. Memulai ulang...");
ESP.restart();
});
server.on("/setwifi", HTTP_POST, [](AsyncWebServerRequest *request) {
if (request->hasParam("ssid", true) && request->hasParam("password", true)) {
routerSSID = request->getParam("ssid", true)->value();
routerPassword = request->getParam("password", true)->value();
saveWiFiCredentials();
request->send(200, "text/plain", "Kredensial WiFi diperbarui. Memulai ulang...");
ESP.restart();
} else {
request->send(400, "text/plain", "Permintaan tidak valid");
}
});
server.on("/setstaticip", HTTP_POST, [](AsyncWebServerRequest *request) {
if (request->hasParam("ip", true) && request->hasParam("gateway", true)) {
String ip = request->getParam("ip", true)->value();
String gw = request->getParam("gateway", true)->value();
if (staticIP.fromString(ip) && gateway.fromString(gw)) {
useStaticIP = true;
saveStaticIPConfig();
request->send(200, "text/plain", "Konfigurasi IP statis diperbarui. Memulai ulang...");
ESP.restart();
} else {
request->send(400, "text/plain", "Format IP tidak valid");
}
} else {
request->send(400, "text/plain", "Permintaan tidak valid");
}
});
server.on("/disablestaticip", HTTP_POST, [](AsyncWebServerRequest *request) {
useStaticIP = false;
saveStaticIPConfig();
request->send(200, "text/plain", "IP statis dinonaktifkan. Memulai ulang...");
ESP.restart();
});
server.on("/devicestatus", HTTP_GET, [](AsyncWebServerRequest *request) {
String response = "{";
response += "\"ssid\":\"" + String(isAPMode ? apSSID : WiFi.SSID()) + "\",";
response += "\"ip\":\"" + (isAPMode ? WiFi.softAPIP().toString() : WiFi.localIP().toString()) + "\",";
response += "\"freeHeap\":\"" + String(ESP.getFreeHeap()) + "\",";
response += "\"signalStrength\":\"" + String(isAPMode ? 5 : getSignalQuality(WiFi.RSSI())) + "\",";
response += "\"mode\":\"" + String(isAPMode ? "AP" : "STA") + "\",";
response += "\"staticIP\":\"" + String(useStaticIP ? "true" : "false") + "\"";
response += "}";
request->send(200, "application/json", response);
});
}
void toggleServer() {
if (isServerRunning) {
server.end();
isServerRunning = false;
Serial.println("Server dimatikan");
} else {
server.begin();
isServerRunning = true;
Serial.println("Server dihidupkan");
}
}
void setup() {
Serial.begin(115200);
Serial.println("Memulai Setup...");
if (!SPIFFS.begin(true)) {
Serial.println("Terjadi kesalahan saat memasang SPIFFS");
return;
}
Serial.println("SPIFFS berhasil dipasang");
loadWiFiCredentials();
loadStaticIPConfig();
WiFiMode_t savedMode = loadWiFiMode();
WiFi.mode(savedMode);
delay(1000);
connectToWiFi();
setupServerRoutes();
Serial.println("Server siap untuk dihidupkan");
Serial.printf("Free heap: %d bytes\n", ESP.getFreeHeap());
// Initialize Modbus TCP server
mb.server();
// Add Modbus registers
mb.addCoil(REG_OUTPUT);
mb.addCoil(REG_TOUCH1);
mb.addCoil(REG_TOUCH2);
mb.addCoil(REG_TOUCH3);
mb.addCoil(REG_TOUCH4);
// Initialize GPIO pins
pinMode(outputPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
static bool lastButtonState = HIGH;
bool currentButtonState = digitalRead(buttonPin);
if (lastButtonState == HIGH && currentButtonState == LOW) {
delay(50); // debounce
if (digitalRead(buttonPin) == LOW) {
toggleServer();
}
}
lastButtonState = currentButtonState;
unsigned long currentMillis = millis();
if (!isAPMode && currentMillis - lastWiFiCheckMillis >= wifiCheckInterval) {
lastWiFiCheckMillis = currentMillis;
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi terputus. Mencoba menghubungkan kembali...");
connectToWiFi();
if (WiFi.status() != WL_CONNECTED) {
failedWiFiConnections++;
if (failedWiFiConnections >= 3) {
Serial.println("Mengatur ulang koneksi WiFi...");
resetWiFiConnection();
failedWiFiConnections = 0;
}
} else {
failedWiFiConnections = 0;
}
}
}
// Handle Modbus requests
mb.task();
delay(10);
// Read touch sensor values
bool touch1 = touchRead(touchPin1) < 20;
bool touch2 = touchRead(touchPin2) < 20;
bool touch3 = touchRead(touchPin3) < 20;
bool touch4 = touchRead(touchPin4) < 20;
// Update Modbus registers
mb.Coil(REG_TOUCH1, touch1);
mb.Coil(REG_TOUCH2, touch2);
mb.Coil(REG_TOUCH3, touch3);
mb.Coil(REG_TOUCH4, touch4);
// Control GPIO output based on Modbus register
bool outputState = mb.Coil(REG_OUTPUT);
digitalWrite(outputPin, outputState ? HIGH : LOW);
// Debugging: Print touch sensor values
Serial.print("Touch1: ");
Serial.print(touch1);
Serial.print(" Touch2: ");
Serial.print(touch2);
Serial.print(" Touch3: ");
Serial.print(touch3);
Serial.print(" Touch4: ");
Serial.println(touch4);
}
// Function to convert RSSI to signal quality (1 to 5)
int getSignalQuality(int rssi) {
if (rssi >= -50) {
return 5; // Sangat Bagus
} else if (rssi >= -60) {
return 4; // Bagus
} else if (rssi >= -70) {
return 3; // Sedang
} else if (rssi >= -80) {
return 2; // Buruk
} else {
return 1; // Sangat Buruk
}
}