Connectivity handling is a major part of firmware development in ESP32 and I've found event based reconnect to work well. Here is the code that you find very commonly everywhere, but it doesn't directly work -
#include <WiFi.h>
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
void WiFiStationConnected(WiFiEvent_t event, WiFiEventInfo_t info){
Serial.println("Connected to AP successfully!");
}
void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info){
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void WiFiStationDisconnected(WiFiEvent_t event, WiFiEventInfo_t info){
Serial.println("Disconnected from WiFi access point");
Serial.print("WiFi lost connection. Reason: ");
Serial.println("Trying to Reconnect");
WiFi.begin(ssid, password);
}
void setup(){
Serial.begin(115200);
// delete old config
WiFi.disconnect(true);
delay(1000);
WiFi.onEvent(WiFiStationConnected, SYSTEM_EVENT_STA_CONNECTED);
WiFi.onEvent(WiFiGotIP, SYSTEM_EVENT_STA_GOT_IP);
WiFi.onEvent(WiFiStationDisconnected, SYSTEM_EVENT_STA_DISCONNECTED);
WiFi.begin(ssid, password);
Serial.println();
Serial.println();
Serial.println("Wait for WiFi... ");
}
void loop(){
delay(1000);
}
It doesn't directly work because you are using the Arduino framework. The event constants are for ESP-IDF if I am not wrong.
We need to use the following constants which are specific for Arduino:
ARDUINO_EVENT_WIFI_STA_CONNECTED: ESP32 station connected to AP
ARDUINO_EVENT_WIFI_STA_GOT_IP: ESP32 station got IP from connected AP
ARDUINO_EVENT_WIFI_STA_DISCONNECTED: ESP32 station disconnected from AP
So the correct working code would be:
#include <WiFi.h>
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
void WiFiStationConnected(WiFiEvent_t event, WiFiEventInfo_t info){
Serial.println("Connected to AP successfully!");
}
void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info){
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void WiFiStationDisconnected(WiFiEvent_t event, WiFiEventInfo_t info){
Serial.println("Disconnected from WiFi access point");
Serial.print("WiFi lost connection. Reason: ");
Serial.println("Trying to Reconnect");
WiFi.begin(ssid, password);
}
void setup(){
Serial.begin(115200);
// delete old config
WiFi.disconnect(true);
delay(1000);
WiFi.onEvent(WiFiStationConnected,ARDUINO_EVENT_WIFI_STA_CONNECTED);
WiFi.onEvent(WiFiGotIP, ARDUINO_EVENT_WIFI_STA_GOT_IP);
WiFi.onEvent(WiFiStationDisconnected, ARDUINO_EVENT_WIFI_STA_DISCONNECTED);
WiFi.begin(ssid, password);
Serial.println();
Serial.println();
Serial.println("Wait for WiFi... ");
}
void loop(){
delay(1000);
}
Related
hello i am trying to send data to lcd screen
,but they arrive as GET/ DATO /HTTP 1.1
I ONLY NEED TO ARRIVE DATA AND DELETE (GET/ /HTTP 1.1)
I am used to the esp8266 by wifi in access point mode the program works well
request is the data that arrives at the arduino terminal
}
if (request.indexOf("") != -1) { //////SHIPPING PART
// enviar
lcd.init();
lcd.backlight();
lcd.setCursor(0,0);
lcd.print(request);
delay(1000);
}
Send Text
I just want to send text so this is what I hope to ahieve
SEND DATO
DELETE GET/ /HTTP 1.1
#include <ESP8266WiFi.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const char *ssid_AP = "LCDAP";
const char *Password_AP = "12345678";
WiFiServer server(80);
LiquidCrystal_I2C lcd(0x27,2,16);
void setup(){
lcd.init(); // initialize the lcd
lcd.backlight();
lcd.setCursor(2,0);
lcd.print("LCD Ready");
Serial.begin(115200);
delay(10);
delay(1000);
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid_AP,Password_AP);
Serial.println("WiFi conected");
Serial.println();
WiFi.printDiag(Serial);
Serial.print("AP direccion IP: ");
Serial.println(WiFi.softAPIP());
// Start the server
server.begin();
Serial.println("Server started");
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
// Read the first line of the\r %d\n
String request = client.readStringUntil('\n');
Serial.println(request);
client.flush();
if (request.indexOf("/LCDBORRAR") != -1) {
lcd.clear();
delay(1000);
}
if (request.indexOf("") != -1) { ////// send text
// enviar
lcd.init();
lcd.backlight();
lcd.setCursor(0,0);
lcd.print(request);
delay(1000);
}
delay(1);
Serial.println("Client disonnected");
Serial.println("");
}
req.replace(" HTTP/1.1", ""); // Para quitar HTTP/1.1
req.replace("GET /", ""); // Para quitar GET /
I am currently having a problem with my ESP8266 establishing a stable connection to my mosquitto MQTT broker.
I have moved house and am therefore using a different network.
In the previous network, my ESP ran stably and I had no problems at all. The MQTTserver run on a Raspberry PI 4.
In the new network, as already mentioned, it breaks off every 15-30 minutes (no fixed length of time).
The code is of course adapted to the new network and the IP of the broker.
The code I use is probably the generally known code for connecting to the MQTT server.
I only added some I/O Ports.
Since the code worked without problems in the old network, I first thought that the WLAN connection was failing.
So in the loop I inserted the reestablishment with the WLAN.
But this is running stably:
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Connecting to Vodafone-947E
.....
WiFi connected
IP address:
192.168.0.52
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
..............
Can it be that my new router simply interrupts the connection after some time? Otherwise, I don't understand what the problem could be.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
//----------------------------------------------------------------------------------------------------------------------
#define wifi_ssid "xxxxxxx"
#define wifi_password "xxxxxxxxx"
#define mqtt_server "192.168.0.xxx"
//----------------------------------------------------------------------------------------------------------------------
WiFiClient espClient;
PubSubClient client(espClient);
bool status;
const int OutputPin2 = 12;
const int ResetPin = 4;
int ResetCounter =0;
//----------------------------------------------------------------------------------------------------------------------
void setup() {
Serial.begin(9600);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
pinMode(OutputPin2, OUTPUT);
pinMode(ResetPin, OUTPUT);
digitalWrite(OutputPin2, HIGH);
digitalWrite(ResetPin, HIGH);
}
//----------------------------------------------------------------------------------------------------------------------
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
WiFi.begin(wifi_ssid, wifi_password);
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId= "ESP8266-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
delay(100);
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
// ... and resubscribe
client.subscribe("esp3/LED");
} else {
ResetCounter++;
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
Serial.println(ResetCounter);
if (ResetCounter >=5)
{
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
//digitalWrite(ResetPin, LOW);
ResetCounter =0;
}
// Wait 5 seconds before retrying
delay(5000);
}
}
}
//----------------------------------------------------------------------------------------------------------------------
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
//----------------------------------------------------------------------------------------------------------------------
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(wifi_ssid);
WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
//----------------------------------------------------------------------------------------------------------------------
void callback(char* 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();
client.subscribe ("esp3/LED");
if (strcmp(topic,"esp3/LED")) {
Serial.print("Changing output to ");
if(messageTemp == "on LED"){
Serial.println("on LED");
digitalWrite(OutputPin2, LOW); //Invertiertes Signal
delay(200);
}
else if(messageTemp == "off LED"){
Serial.println("off LED");
digitalWrite(OutputPin2, HIGH);
delay(200);
}
}
}
```
Fortunately, I was able to solve the problem. The reason was that the WLAN signal on the ESP8266 was simply too low. As a result, the ESP was not able to stay on the network permanently. I actually ruled this out because the router is only one room away. The problem is that many routers in the surrounding flats also transmit on the same frequency band and thus influence the signal. I bought a WLAN amplifier (of course this does not improve the situation with the signal overlapping). Now I have no more problems with disconnects from the ESP and this has been the case for 2 days.
#include "WiFiEsp.h"
char ssid[] = "***"; // your network SSID (name)
char pass[] = "#"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's statusb
char server[] = "apiv2.corona-live.com";
// Initialize the Ethernet client object
WiFiEspClient client;
void setup()
{
// initialize serial for debugging
Serial.begin(115200);
// initialize serial for ESP module
Serial1.begin(115200);
// initialize ESP module
WiFi.init(&Serial1);
// check for the presence of the shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue
while (true);
}
// attempt to connect to WiFi network
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network
status = WiFi.begin(ssid, pass);
}
// you're connected now, so print out the data
Serial.println("You're connected to the network");
printWifiStatus();
Serial.println();
Serial.println("Starting connection to server...");
// if you get a connection, report back via serial
if (client.connect(server, 80)) {
Serial.println("Connected to server");
// Make a HTTP request
client.println("GET /stats.json?timestamp=1634891368873 HTTP/1.1");
client.println("Host: apiv2.corona-live.com");
client.println("Connection: close");
client.println();
}
}
void loop()
{
delay(500);
// if there are incoming bytes available
// from the server, read them and print them
while(client.connected())
{
// There is a client connected. Is there anything to read?
while(client.available() > 0)
{
char c = client.read();
Serial.print(c);
}
Serial.println();
Serial.println("Waiting for more data...");
delay(100); // Have a bit of patience...
}
// if the server's disconnected, stop the client
if (!client.connected()) {
Serial.println();
Serial.println("Disconnecting from server...");
client.stop();
// do nothing forevermore
while (true);
}
}
void printWifiStatus()
{
// print the SSID of the network you're attached to
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength
long rssi = WiFi.RSSI();
Serial.print("Signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
Result :
[WiFiEsp] Connecting to apiv2.corona-live.com
Connected to server
HTTP/1.1 301 Moved Permanently
D[WiFiEsp] TIMEOUT: 720
https://apiv2.corona-live.com/stats.json?timestamp=1634891368873 Can I get JSON data from these sites? If possible, I would like to know why this error occurred.
(I use arduino mega 2560 + esp8266/esp01 module
I want to use ESP 8266 01 and arduino uno as client in MQTT. The code For ESP8266 01 is successfully compiled and I'M getting errors in Arduino uno
The error is 'messageTemp' was not declared in this scope
Amd also I have a thought of using stm32xx in client.
If I compile for that
exit status 1
ISO C++ forbids comparison between pointer and integer [-fpermissive]
above is the error I'm getting
1)ESP code
// Loading the ESP8266WiFi library and the PubSubClient library
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Change the credentials below, so your ESP8266 connects to your router
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
const char* mqtt_server = "YOUR_RPi_IP_Address";
// Initializes the espClient
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
if(topic=="home/office/esp1/gpio2"){
Serial.print("Changing GPIO 2 to ");
if(messageTemp == "1"){
// digitalWrite(ledGPIO2, HIGH);
Serial.print("On");
}
else if(messageTemp == "0"){
// digitalWrite(ledGPIO2, LOW);
Serial.print("Off");
}
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
client.subscribe("home/office/esp1/gpio2");
}
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() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
Code for Arduino UNO
void setup(){
Serial.begin(9600);
pinMode(12, OUTPUT);
digitalWrite(12, HIGH);
String messageTemp;
}
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();
}
void loop ()
{
if (Serial.available()){
char topic = Serial.read();
{
if (topic=="home/office/esp1/gpio2")
{
Serial.print("Changing GPIO 2 to ");
if(messageTemp == "1"){
digitalWrite(12, HIGH);
Serial.print("On");
}
else if(messageTemp == "0")
{
digitalWrite(12, LOW);
Serial.print("Off");
}
}}}}
ESP code doesn't look the whole source code you provided. In case of Arduino UNO, if you're intending to use messageTemp as a global variable, then you need to declare it only one time outside of functions. In the above code, you declared it twice in setup() and callback(), then those are considered as local variables. Even in loop(), there's no declaration, this should create the compile error.
I am trying to access a simple web page running in my Rpi-server using ESP8266 and Arduino.
I have refereed this similar SO question , but it's not the solution for my problem.
Here is my current Arduino Code :
#include "WiFiEsp.h"
// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2,3); // RX, TX
#endif
char ssid[] = "RPi"; // your network SSID (name)
char pass[] = "raspberry"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
char server[] = "192.168.50.1";
// Initialize the Ethernet client object
WiFiEspClient client;
void setup()
{
// initialize serial for debugging
Serial.begin(9600);
// initialize serial for ESP module
Serial1.begin(9600);
// initialize ESP module
WiFi.init(&Serial1);
// check for the presence of the shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue
while (true);
}
// attempt to connect to WiFi network
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network
status = WiFi.begin(ssid, pass);
}
// you're connected now, so print out the data
Serial.println("You're connected to the network");
printWifiStatus();
Serial.println();
Serial.println("Starting connection to server...");
// if you get a connection, report back via serial
if (client.connect(server, 80)) {
Serial.println("Connected to server");
// Make a HTTP request
client.println("GET /simple.html HTTP/1.1");
client.println("Host: 192.168.50.1");
client.println("Connection: close");
client.println();
}
}
void loop()
{
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// if the server's disconnected, stop the client
if (!client.connected()) {
Serial.println();
Serial.println("Disconnecting from server...");
client.stop();
// do nothing forevermore
while (true);
}
void printWifiStatus()
{
// print the SSID of the network you're attached to
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength
long rssi = WiFi.RSSI();
Serial.print("Signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
Output:
Starting connection to server...
[WiFiEsp] Connecting to 192.168.50.1
Connected to server
[WiFiEsp] Data packet send error (2)
[WiFiEsp] Failed to write to socket 3
[WiFiEsp] Disconnecting 3
My simple.html looks like this.
<html>
<body>
<p>1</p>
</body>
</html>
}
I accessed to this page from web browser and it shows the content properly.
What is missing here?
Thanks in advance.
Try this line in your code
client.print("GET /simple.html HTTP/1.0\r\n\r\n");