I hope some of you can shed some light on what is going wrong here?
My current problem is when I power down the esp8266 and power it on again it will not connect to my access point (router). When I flash my code on to the esp it works fine. If reset the module via the reset pin(with button wired to ground). It will connect to my router just fine. If I unplug the power and connect it back up it wont connect to my router anymore. It did occur to me to try and reset the router as well but it still didnt work.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
ESP8266WebServer server(80);
const char* ssid="------"; //router ssid
const char* password="--------"; //router password
char WiFiAPPSK[] = "1234567890"; //ap mode password
String webSite,javaScript,XML;
int WiFiAP;
void initWiFi()
{
int i = 0;
WiFi.mode(WIFI_STA);
while(WiFi.status()!=WL_CONNECTED && i < 5) //If cant connect to router retry 5 times
{
WiFi.begin(ssid,password);
i++;
delay(500);
Serial.print(".");
if(WiFi.status() == WL_CONNECTED)
{
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("Station IP address: ");
Serial.println(WiFi.localIP());
WiFiAP = 0;
}
}
Serial.println(ssid);
Serial.println(password);
if (WiFi.status()!= WL_CONNECTED) //if still cant connect after 5 retries turn on ap mode
{
WiFi.mode(WIFI_AP);
uint8_t mac[WL_MAC_ADDR_LENGTH]; //Create a ap name from mac address.
WiFi.softAPmacAddress(mac);
String macID = String(mac[WL_MAC_ADDR_LENGTH - 2], HEX) +
String(mac[WL_MAC_ADDR_LENGTH - 1], HEX);
macID.toUpperCase();
String AP_NameString = "Testap " + macID;
char AP_NameChar[AP_NameString.length() + 1];
memset(AP_NameChar, 0, AP_NameString.length() + 1);
for (int i=0; i<AP_NameString.length(); i++)
{
AP_NameChar[i] = AP_NameString.charAt(i);
}
WiFi.softAP(AP_NameChar, WiFiAPPSK);
Serial.print("AP mode enabled: ");
Serial.println(AP_NameChar);
Serial.println(WiFi.softAPIP());
WiFiAP = 1;
}
}
void setup()
{
Serial.begin(115200);
Serial.println();
initWiFi();
server.on("/",handleIndex); //web page
server.on("/xml",handleXML); //web page
server.on("/PC",handlePC); //web page
server.begin();
}
void loop()
{
server.handleClient();
}
From the above code I left out the web page portion. The web page works fine in both sta and ap modes. When the esp cant connect to my router I can connect to the esp directly (in ap mode) without a problem. After the esp fails to connect to my router I tried using println to see if the ssid and password has changed some how. It printed the correct ssid and password. I also tried wifi.disconnect() before wifi.mode(wifi_sta) but that didnt solve my problem.
What am I doing wrong here??
My setup:
Windows xp running arduino IDE 1.6.9
USB to ttl cp2102
ESP8266 ESP01 powered from usb to ttl 3.3V