Good Day Everyone
I am having difficulty connecting to WIFI
I am using an esp2866 with USB adapter
I am using the code to light an LED
I can connect to WIFI when i use WiFi.begin("UserName", "XXXXXX")
this shows the name and pass directly to the IDE
This is not secure
my expectation:
I want to use the serial monitor to type the ssid and password
my problem:
when i change WiFi.begin("UserName", "XXXXXX")
to WiFi.begin(ssid.c_str(), pass.c_str()), it just run the do while function endlessly indicating that it is not connected
I use c_str because WiFi begin cannot recognize string
I also tried casting the the ssid and pass to const char. It did not work also
Can you help me to make this work. Thank you
Here is the code:
#include<ESP8266WiFi.h>
#include<ESP8266WebServer.h>
//#include<Wifi.h>
#define LED 2
String ssid = "";
String pass = "";
ESP8266WebServer server(80);
void setup() {
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
Serial.begin(115200);
Serial.println("Begin");
}
void SetServerHandler() {
if (WiFi.status() == WL_CONNECTED) {
server.on("/LED=ON", []() {
digitalWrite(LED, HIGH);
String res = digitalRead(LED) == HIGH ? "ON" : "OFF";
server.send(200, "text/html", "LED is " + res);
});
server.on("/LED=OFF", []() {
digitalWrite(LED, LOW);
String res = digitalRead(LED) == HIGH ? "ON" : "OFF";
server.send(200, "text/html", "LED is " + res);
});
server.begin();
}
}
void loop() {
if (Serial.available()) {
String params = Serial.readStringUntil('\n');
if (params.startsWith("ssid")) {
ssid = params.substring(5);
Serial.println("ssid = [" + ssid + "]");
} else if (params.startsWith("pass")) {
pass = params.substring(5);
Serial.println("pass = [" + pass + "]");
} else if (params.startsWith("connect")) {
//WiFi.begin("UserName", "XXXXXX"); //this is not secure but works
//WiFi.begin(ssid, pass);
//WiFi.begin((const char*)ssid.c_str(), (const char*)pass.c_str());//casting to const char
WiFi.begin(ssid.c_str(), pass.c_str());
Serial.println("Connect to " + ssid);
int retry = 0;
while (WiFi.status() != WL_CONNECTED) {
retry++;
if ((retry % 20) == 0)
Serial.println(".");
else
Serial.print(".");
delay(500);
}
Serial.println();
Serial.println("Wifi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
SetServerHandler();
}
}
server.handleClient();
}