I am trying to get my esp32 to connect to my wifi, but it attempts forever without connecting. I don't think there is anything wrong with the code. I'm thinking the issue is something with my router.
#include<WiFi.h>
const char *ssid = "mySSID";
const char *password = "myPW";
void initWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
}
void setup() {
Serial.begin(115200);
initWiFi();
Serial.print("RRSI: ");
Serial.println(WiFi.RSSI());
}
void loop() {
// put your main code here, to run repeatedly:
}
I have a netgear router that puts out a 2.4G and 5G network. I ran a WiFi scan sketch on my esp32 and it successfully saw my 2.4Ghz wifi and identified it was using WPA2. I checked my router log and saw it thought my esp32 connection attempts were DoS attacks so i disabled DoS protection, and added my esp32's mac address to the allow list. None of that worked. any ideas here?
I checked my code vs your code. I can only see one difference.
// Debug information
#define DEBUG 1
#if DEBUG ==1
#define debug(x) Serial.print(x)
#define debugln(x) Serial.println(x)
#else
#define debug(x)
#define debugln(x)
#endif
#define vtDelay(x) vTaskDelay(x / portTICK_PERIOD_MS)
void initWiFi() {
debug("Start initWiFi");
// Set WiFi to station mode and disconnect from an AP if it was previously connected
WiFi.mode(WIFI_STA);
//WiFi.disconnect();
vtDelay(1000);
WiFi.begin(ssid, password);
debugln("Connecting to WiFi ..");
WiFiAttempts = 1;
while (WiFiRet != WL_CONNECTED ) {
WiFiRet = WiFi.status();
debug("WiFi.status = ");
debug(WiFiRet);
debug(" WiFiAttempts = ");
debugln(WiFiAttempts++);
vtDelay(1000);
if (WiFiAttempts > 20) {
debugln("Restarting the ESP32");
ESP.restart();
}
}
debugln(WiFi.localIP());
}
This works for me the only difference was the vtDelay for 1000 milliseconds. I am also using my 2.4G and have security set to 'WPA2-PSK'.
I hope this helps.
Related
I have application that I need to run multiple ESP32s in same network which publishes webserver, in my case multi device is broadcasting in same port as 80. This causing port issue I guess because only one device at a time is working on browser. When I change port number to 8080, I cannot make it work. Is there any configuration that I need to do before working with multi webserver?
I shared the code below which working, my purpose is make it work with multi device in same network.
#include <ESPmDNS.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
const char* ssid = "XXXX";
const char* password = "XXXX";
AsyncWebServer server(80);
void setup(){
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
if(!MDNS.begin("esp32")) {
Serial.println("Error starting mDNS");
return;
}
Serial.println(WiFi.localIP());
server.on("/hello", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(200, "text/plain", "Hello World");
});
server.begin();
}
void loop(){}
I'm developing a simple mobile robot controlled by a custom web application hosted on ESP32. The communication protocol that is used is WebSocket. I had a code that was working but after some break, I can't make it run properly again... most likely I changed something accidentally or I don't understand some code parts. The logs in SerialPort suggest that the program connects to the WiFi, it gets data (HTML files) from Flash memory and the server is started under some particular IP. However, when I try to access the server IP nothing is given in response. I pasted my .ino code down below, I can also add HTML and .js files if needed. The data folder is ofc uploaded to the flash memory. For now I just want to host that page on a server and access it, the code is not supposed to do anything else for now. I'm going crazy because of that issue. Does anyone see some mistake or misconception?
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "SPIFFS.h"
#include <Arduino_JSON.h>
// Network credentials
const char *ssid = "mySSID";
const char *password = "myCredentials";
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
// Create a WebSocket object
AsyncWebSocket ws("/ws");
// Placeholder for messages from the clients
String message = "";
void initFS()
{
if (!SPIFFS.begin())
{
Serial.println("An error has occurred while mounting SPIFFS");
}
else
{
Serial.println("SPIFFS mounted successfully");
}
}
// Initialise WiFi
void initWiFi()
{
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
}
void handleWebSocketMessage(void *arg, uint8_t *data, size_t len)
{
AwsFrameInfo *info = (AwsFrameInfo *)arg;
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT)
{
data[len] = 0;
message = (char *)data;
}
}
void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len)
{
switch (type)
{
case WS_EVT_CONNECT:
Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
break;
case WS_EVT_DISCONNECT:
Serial.printf("WebSocket client #%u disconnected\n", client->id());
break;
case WS_EVT_DATA:
handleWebSocketMessage(arg, data, len);
break;
case WS_EVT_PONG:
case WS_EVT_ERROR:
break;
}
}
void initWebSocket()
{
Serial.println("I'm Inside!");
ws.onEvent(onEvent);
server.addHandler(&ws);
}
void setup()
{
Serial.begin(115200);
Serial.println("Initialising SPIFFS");
initFS();
Serial.println("Initialising WiFi");
initWiFi();
Serial.println("Initialising WebSocket");
initWebSocket();
// Web Server Root URL
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send(SPIFFS, "/index.html", "text/html"); });
server.serveStatic("/", SPIFFS, "/");
// Start server
server.begin();
Serial.println("Starting Server");
}
void loop()
{
ws.cleanupClients();
}
Update:
I created a different, very simple sketch just to have a look if it might work and it doesn't. It connects to the WiFi according to the logs but I'm getting timed out when I try to access the server IP address Down below is the code that I used for the second sketch:
#include <WiFi.h>
#include <WebServer.h>
//SSID and Password to the local WiFi
const char* ssid = "ssid";
const char* password = "password";
WebServer server(80);
String webpage = "<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>Document</title></head><body> <h1> Test! </h1></body></html>";
//Function to initialise the connection with local WiFi
void InitWiFi()
{
WiFi.begin(ssid, password);
Serial.println("Trying to connect to the WiFi with SSID: " + String(ssid) + "..");
while(WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("Connected to the WiFi with the IP address: ");
Serial.println(WiFi.localIP());
}
void setup() {
Serial.begin(115200);
InitWiFi();
//Initialising WebServer
server.on("/", []() {
server.send(200, "text\html", webpage);
});
delay(1000);
server.begin();
Serial.println("Server started");
}
void loop() {
server.handleClient();
}
I am working on a project that uses the ESP32 C3 dev board and runs a webserver with dns, and comunicates with the client via websocket. here is the arduino code (the part of it relevent to the webserver):
#include <math.h>
#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>
#include <WiFiClient.h>
#include <time.h>
#include "SPIFFS.h"
#include <FS.h>
#include <EEPROM.h>
#include <ArduinoOTA.h>
#include <WiFiUdp.h>
#include <ESPmDNS.h>
#include <WebSocketsServer.h>
#include <DNSServer.h>
#include <NTPClient.h>
#include <Adafruit_NeoPixel.h>
#include <driver/adc.h>
WebServer server(8000);
DNSServer dnsServer;
WebSocketsServer webSocket = WebSocketsServer(81);
WiFiServer server2(80);
IPAddress apIPDNS(8,8,4,4);
IPAddress testIP1(192,168,1,4);
IPAddress testIP2(192,168,1,5);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
IPAddress apIP(192, 168, 4, 3);
IPAddress netMsk(255, 255, 255, 0);
uint8_t* data;
void onWebSocketEvent(uint8_t num,
WStype_t type,
uint8_t * data1,
size_t length) {
// Figure out the type of WebSocket event
switch(type) {
// Client has disconnected
case WStype_DISCONNECTED:
Serial.printf("[%u] Disconnected!\n", num);
break;
// New client has connected
case WStype_CONNECTED:
{
IPAddress ip = webSocket.remoteIP(num);
// Serial.printf("[%u] Connection from ", num);
// Serial.println(ip.toString());
}
break;
// Echo text message back to client
case WStype_TEXT:
data = data1;
parsedata();
break;
case WStype_BIN:
case WStype_ERROR:
case WStype_FRAGMENT_TEXT_START:
case WStype_FRAGMENT_BIN_START:
case WStype_FRAGMENT:
case WStype_FRAGMENT_FIN:
default:
break;
}
}
void setup() {
Serial.begin(115200);
EEPROM.begin(512);
time_now = millis();
WiFi.mode(WIFI_AP_STA);
WiFi.softAPConfig(testIP1, testIP1, netMsk);
WiFi.softAP(ssid, password);
WiFi.hostname("esp32server");
WiFi.begin(sta_ssid, sta_password);
dnsServer.start(53, "*", WiFi.softAPIP());
Serial.println("connecting to wifi1...");
delay(6000);
if(WiFi.status() == WL_CONNECTED) { current_connected_wifi = String(sta_ssid); current_connected_password = String(sta_password);Serial.println("connected to:" + current_connected_wifi);}
else {WiFi.begin(sta_ssid2, sta_password2);delay(6000);Serial.println("connecting to wifi2...");
if(WiFi.status() == WL_CONNECTED) { current_connected_wifi = String(sta_ssid2); current_connected_password = String(sta_password2);Serial.println("connected to:" + current_connected_wifi);}
else {WiFi.begin(sta_ssid3, sta_password3);delay(6000);
Serial.println("connecting to wifi3...");
if(WiFi.status() == WL_CONNECTED) { current_connected_wifi = String(sta_ssid3); current_connected_password = String(sta_password3);Serial.println("connected to:" + current_connected_wifi);}
else { Serial.println("NO INTERNET"); WiFi.disconnect();dnsServer.start(53, "*", WiFi.softAPIP());}
}
}
SPIFFS.begin();
MDNS.begin("espserver");
server.on("/", handle_root);
server.on("/Chart",HTTP_GET, handle_chart);
server.on("/Style",HTTP_GET, handle_chartcss);
server.on("/mark",HTTP_GET, handle_img);
server.on("/nonet",HTTP_GET, handle_img2);
server.on("/wifilogo",HTTP_GET, handle_img3);
server.on("/adressip", handle_adressip);
server.on("/maxcoff", handle_maxcoff);
server.on("/request", handle_request);
server.on("/mintime", handle_mintime);
server.on("/maxtime", handle_maxtime);
server.on("/dailychart", handle_dailychart);
server.on("/hourlychart", handle_hourlychart);
server.on("/monthlychart", handle_monthlychart);
server.on("/cumulative", handle_cumulative);
server.on("/monthly", handle_monthly);
server.on("/SSIDnames", handle_SSIDnames);
server.on("/getmaxenergy", handle_maxenergy);
server.begin();
webSocket.begin();
webSocket.onEvent(onWebSocketEvent);
server2.begin();
MDNS.addService("http", "tcp", 80);
}
void loop() {
WiFiClient client = server2.available();
dnsServer.processNextRequest();
server.handleClient();
webSocket.loop();
delay(20);
}
quick explenation:
when the ESP32 starts, it checks if it can connect to the internet with any of the 3 saved credentials from eeprom (sta_ssid, sta_password). If it manages to connect with any of them, the webserver can be accesed either when connecting to the wifi of the ESP or on the network that the ESP32 is connected to. When it is unable to find a a network it can only be accesed when connected to the wifi AP of the ESP32. The webserver is accesed from either 192.168.1.4:8000 or espserver.local:8000.
This works great regardless of internet access. When i connect to the webserver i send my html and javascript code to the client and then establish a websocket connection. When the esp doesnt have internet acces the websocket connection works fine, and packets get recieved within milieconds, worst case scenario a couple of them take 2 seconds to arrive.
HOWEVER, when the ESP is not connected to the internet, the packets get stuck on pending and take forever to arive (even 10 seconds), or dont arive at all. Its almost like the webserver is too busy, even tho it has far less to do compered to when it is connected to the internet.
My question is, do i have to use a special function to disconect the webserver from the internet (where WiFi.disconect() is not enough?) or how can I make the WebServer library work better to not lose any packets?
(i have tried using the asynch websocket library, however it does not work on my specific chipset (esp32 c3) so i have to make it work with this library)
I figured it out. the problem was as some people hinted, that the wifi status was 1, which meant it was constantly trying to reconnect (and using cpu time). I used WiFi.disconnect(true); to disconnect the wifi if it didnt connect to any network during setup. that solved the problem.
My project is about using nodeMCU measure value from sensor DHT11 and sent value to database Mysql. I use xampp for server. I cannot sent value to database.
nodeMCU can read value and sent value.But HTTP GET is fail.And return connect refused. I think maybe have problems with port for listening.
this is my code
#include <Arduino.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include "DHT.h"
#define DHTPIN 2 // what digital pin the DHT22 is conected to
#define DHTTYPE DHT11 // there are multiple kinds of DHT sensors
DHT dht(DHTPIN, DHTTYPE);
ESP8266WiFiMulti WiFiMulti;
const char* ssid = "something";
const char* password = "something";
int EP =5;
void setup() {
Serial.begin(115200);
pinMode(EP, INPUT);
for (uint8_t t = 4; t > 0; t--) {
Serial.printf("[SETUP] WAIT %d...\n", t);
Serial.flush();
delay(1000);
}
WiFiMulti.addAP(ssid, password); // ssid , password
randomSeed(50);
}
int timeSinceLastRead = 0;
void loop() {
if ((WiFiMulti.run() == WL_CONNECTED)) {
HTTPClient http;
float temp = dht.readTemperature();
float humi = dht.readHumidity();
long meas =TP_init();
Serial.println(WiFi.localIP());
//int temp = random(25,35);
String url = "localhost:8012/add2.php?temp="+String(temp)+"&humi="+String(humi)+"&meas=0";
Serial.println(url);
http.begin(url); //HTTP
int httpCode = http.GET();
if (httpCode > 0) {
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
delay(3000);
}
long TP_init(){
delay(10);
long meas=pulseIn (EP, HIGH); //wait for the pin to get HIGH and returns measurement
return meas;
}
I changed Apache port from 80 to 8012
I use PHPMyadmin for store database . File php's name add2.php for insert value from sensor DHT11
enter image description here
This is result from serial port.
String url = "localhost should be replaced with String url = "<IP-address-of-your-webserver> as the webserver clearly isn't running on the ESP8266.
I was recently working on a home automation project which has finally come to end and I am thinking to install it in my home. First of all, I would like to brief you with the basic architecture.
I am using a Raspberry Pi 3 as the central controller node which is running Node-Red and its Mosca palette. Currently, there are 5 ESP-01 in the project. Four of them are wired up with a relay and the remaining ESP is wired up with a DHT11 temperature sensor. Almost everything is running good but I am facing some stability issues, like, when I recycle the power the ESP-01 doesn't run the program. Serial monitor stays blank. However, when I disconnect the GPIO2 from the relay and then power up the ESP. The program begins. So, I have to pull out the GPIO2 then power up the ESP then connect the GPIO2 with the relay on every power recycle. Another problem which I am facing is sometimes the ESP crashes automatically. It sometimes prints out fatal exception(0) or soft wdt reset even though I have added a watchdog timer.
Here is the code for one of the client ESP:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "........";
const char* password = ".........";
const int led = 13;
const char* mqtt_server = "192.168.1.8";
WiFiClient espClient;
PubSubClient client(espClient);
const int ledGPIO2 = 2;
void setup_wifi() {
int i;
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("WIFI BEGUN");
while (WiFi.status() != WL_CONNECTED) {
ESP.wdtFeed();
delay(500);
i++;
if ((i&0x01)==0){
digitalWrite(led, 0);
} else {
digitalWrite(led, 1); // led should start blinking at .5 seconds
}
Serial.print(".");
if (i>1000) break; // get out after 50 seconds
if (i==1000){
}
Serial.print(".");
Serial.println("");
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
}
void callback(String topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
if(topic=="Lamp1"){
Serial.print("Changing GPIO 2 to ");
if(messageTemp == "on"){
digitalWrite(ledGPIO2, HIGH);
Serial.print("On");
}
else if(messageTemp == "off"){
digitalWrite(ledGPIO2, LOW);
Serial.print("Off");
}
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP8266Client")) {
Serial.println("connected");
client.subscribe("Lamp1");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(ledGPIO2, OUTPUT);
digitalWrite(ledGPIO2, true);
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
if(!client.loop())
client.connect("ESP8266Client");
}
Also, I have been thinking for an efficient power supply for ESP. Batteries cannot be reliable for long-term and powering up via an adapter would be unfeasible as the module is going to be mounted on the wall. Moreover, ac to dc converter was something which seems to be a decent way for power supply.
Vcc - 3.3V
CH_PD - 3.3V
Tx - Tx (Arduino)
Rx - Rx (Arduino)
GPIO0 - GND (while uploading the sketch)/ 3.3V
GND - GND
I am not using capacitors or resistors. I am getting a 5V supply from Arduino which is regulated to 3.3V using LD33V voltage regulator.
Any suggestions would be appreciated. Thank You!!