#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <BluetoothSerial.h> // Bluetooth library
BluetoothSerial SerialBT; // Bluetooth object
String receivedSSID = ""; // SSID received via Bluetooth
String receivedPassword = ""; // Password received via Bluetooth
WebServer server(80); // Create a web server on port 80
const int led = 2; // LED pin number
bool wifiConnected = false; // Wi-Fi connection status
bool bluetoothConnected = false; // Bluetooth connection status
bool credentialsReceived = false; // Status to check if SSID and password are received
// Enumeration for input states
enum InputState {
WAITING_FOR_SSID,
WAITING_FOR_PASSWORD,
WAITING_FOR_WIFI_CONNECT
};
InputState currentInputState = WAITING_FOR_SSID; // Current input state starts with waiting for SSID
// Function to handle root webpage ("/")
void handleRoot() {
String html = "<html><body>";
html += "<h1>ESP32 LED Control</h1>";
html += "<button onclick=\"location.href='/led/on'\">Turn LED ON</button><br>";
html += "<button onclick=\"location.href='/led/off'\">Turn LED OFF</button><br>";
html += "</body></html>";
server.send(200, "text/html", html); // Send HTML response to the client
}
// Function to turn the LED on
void handleLedOn() {
digitalWrite(led, HIGH); // Turn the LED on
server.send(200, "text/plain", "LED is ON"); // Send plain text response
}
// Function to turn the LED off
void handleLedOff() {
digitalWrite(led, LOW); // Turn the LED off
server.send(200, "text/plain", "LED is OFF"); // Send plain text response
}
// Function to handle 404 errors (not found)
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message); // Send 404 error as plain text
}
// Function to connect to Wi-Fi using received SSID and password
void connectWiFi() {
if (!wifiConnected && credentialsReceived) {
WiFi.begin(receivedSSID.c_str(), receivedPassword.c_str()); // Start Wi-Fi connection with the received SSID and password
Serial.print("Connecting to Wi-Fi with SSID: ");
Serial.println(receivedSSID);
int timeout = 0; // Timeout counter
while (WiFi.status() != WL_CONNECTED && timeout < 20) { // 20 seconds timeout
delay(500);
Serial.print(".");
timeout++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\nWi-Fi connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); // Print IP address when connected
wifiConnected = true;
if (MDNS.begin("esp32")) {
Serial.println("MDNS responder started");
}
server.begin(); // Start web server
Serial.println("HTTP server started");
} else {
Serial.println("\nWi-Fi connection failed. Please check credentials.");
wifiConnected = false;
}
} else {
Serial.println("Wi-Fi is already connected or credentials not received.");
}
}
// Function to disconnect Wi-Fi
void disconnectWiFi() {
if (wifiConnected) {
WiFi.disconnect(); // Disconnect Wi-Fi
Serial.println("Wi-Fi disconnected.");
wifiConnected = false;
}
}
// Function to start Bluetooth connection
void connectBluetooth() {
if (!bluetoothConnected) {
SerialBT.begin("ESP32"); // Set Bluetooth device name
Serial.println("Bluetooth started. Device name: ESP32");
bluetoothConnected = true;
// Prompt for SSID input
SerialBT.println("Please enter SSID:");
currentInputState = WAITING_FOR_SSID; // Set state to wait for SSID
} else {
Serial.println("Bluetooth is already connected.");
}
}
// Function to disconnect Bluetooth
void disconnectBluetooth() {
if (bluetoothConnected) {
SerialBT.end(); // End Bluetooth connection
Serial.println("Bluetooth disconnected.");
bluetoothConnected = false;
}
}
// Function to disconnect all connections (Wi-Fi and Bluetooth)
void disconnectAll() {
disconnectWiFi();
disconnectBluetooth();
Serial.println("All connections are off.");
}
// Function to handle incoming Bluetooth data
void handleBluetoothInput() {
String incomingData = "";
while (SerialBT.available()) {
char receivedChar = SerialBT.read();
if (receivedChar == '\n') { // Stop reading when newline character is received
break;
}
incomingData += receivedChar; // Append received characters to the incoming data string
}
// Process SSID or password input based on current state
if (currentInputState == WAITING_FOR_SSID) {
receivedSSID = incomingData; // Store received SSID
Serial.println("SSID received: " + receivedSSID);
SerialBT.println("SSID received. Please enter Password:"); // Prompt for password
currentInputState = WAITING_FOR_PASSWORD; // Set state to wait for password
} else if (currentInputState == WAITING_FOR_PASSWORD) {
receivedPassword = incomingData; // Store received password
Serial.println("Password received: " + receivedPassword);
credentialsReceived = true;
// SSID and password are both received, wait for Wi-Fi connect command
SerialBT.println("Credentials received. Press 'w' to connect to Wi-Fi.");
currentInputState = WAITING_FOR_WIFI_CONNECT; // Set state to wait for Wi-Fi connect
}
}
// Function to initialize the system
void setup() {
pinMode(led, OUTPUT);
digitalWrite(led, LOW); // Set LED to off by default
Serial.begin(115200);
Serial.println("ESP32 is ready. Waiting for Bluetooth input...");
// Start with all connections disabled
disconnectAll();
// Set up web server routes
server.on("/", handleRoot);
server.on("/led/on", handleLedOn); // Route for turning LED on
server.on("/led/off", handleLedOff); // Route for turning LED off
server.onNotFound(handleNotFound); // Handle 404 errors
// Start Bluetooth connection
connectBluetooth();
}
// Main loop function
void loop() {
// Handle web server client requests (only if Wi-Fi is connected)
if (wifiConnected) {
server.handleClient();
}
// Handle Bluetooth input
if (SerialBT.available()) {
handleBluetoothInput();
}
// Handle keyboard commands from the serial monitor
if (Serial.available()) {
char command = Serial.read();
switch (command) {
case 'b': // Connect Bluetooth
disconnectWiFi();
connectBluetooth();
break;
case 'w': // Connect to Wi-Fi (after receiving credentials)
if (credentialsReceived) {
connectWiFi();
} else {
Serial.println("No Wi-Fi credentials received. Cannot connect.");
}
break;
case 'f': // Disconnect all connections
disconnectAll();
break;
default:
Serial.println("Invalid command. Use 'b' for Bluetooth, 'w' for Wi-Fi, 'f' to turn off all.");
break;
}
}
}
Since I have an esp wroom 32 module, wifi and bluetooth do not work at the same time, so I created this code. However, when I try to connect with wifi ssid and pass, it still doesn't work. Please fix it!