ESP8266 geeting back to loop - esp8266

The most of the following code ist from #Juraj https://github.com/jandrassy/lab/blob/master/ConfigurationAP/ConfigurationAP.ino
I change it a littel bit. My Probelm now ist, I do not know, how I get back to loop() from configAP()
It works well, if the ssid and the password are already saved
#include <ESP8266WiFi.h>
const char* ssidh = "ESP-Accesspoint";
const char* password = "12345678";
// Wir setzen den Webserver auf Port 80
WiFiServer configWebServer(80);
// Eine Variable um den HTTP Request zu speichern
String header;
void setup() {
Serial.begin(115200);
delay(500);
WiFi.begin(); // use SSID and password stored by SDK. please comment out to test the Configuration AP
// waiting for connection to remembered Wifi network
Serial.println("Waiting for connection to WiFi");
WiFi.waitForConnectResult();
if (WiFi.status() != WL_CONNECTED) {
Serial.println();
Serial.println("Could not connect to WiFi. Starting configuration AP...");
configAP();
} else if(WiFi.status() == WL_CONNECTED) {
//seite();
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP Adresse: ");
Serial.println(WiFi.localIP());
configWebServer.begin();
}else{
Serial.println("whaaat");
}
}
void configAP() {
WiFiServer configWebServer(80);
WiFi.mode(WIFI_AP_STA); // starts the default AP (factory default or setup as persistent)
WiFi.softAP(ssidh, password);
Serial.print("Connect your computer to the WiFi network ");
Serial.print(WiFi.softAPSSID());
Serial.println();
IPAddress ip = WiFi.softAPIP();
Serial.print("and enter http://");
Serial.print(ip);
Serial.println(" in a Web browser");
configWebServer.begin();
while (true) {
WiFiClient client = configWebServer.available();
if (client) {
char line[64];
int l = client.readBytesUntil('\n', line, sizeof(line));
line[l] = 0;
client.find((char*) "\r\n\r\n");
if (strncmp_P(line, PSTR("POST"), strlen("POST")) == 0) {
l = client.readBytes(line, sizeof(line));
line[l] = 0;
// parse the parameters sent by the html form
const char* delims = "=&";
strtok(line, delims);
const char* ssid = strtok(NULL, delims);
strtok(NULL, delims);
const char* pass = strtok(NULL, delims);
// send a response before attemting to connect to the WiFi network
// because it will reset the SoftAP and disconnect the client station
client.println(F("HTTP/1.1 200 OK"));
client.println(F("Connection: close"));
client.println(F("Refresh: 10")); // send a request after 10 seconds
client.println();
client.println(F("<html><body><h3>Configuration AP</h3><br>connecting...</body></html>"));
client.stop();
Serial.println();
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
WiFi.persistent(true);
WiFi.setAutoConnect(true);
WiFi.begin(ssid, pass);
WiFi.waitForConnectResult();
// configuration continues with the next request
} else {
client.println(F("HTTP/1.1 200 OK"));
client.println(F("Connection: close"));
client.println();
client.println(F("<html><body><h3>Configuration AP</h3><br>"));
client.println(F("<html><body><h3>IP Adresse:</h3><br>"));
client.println(F("<html><body><h3>WiFi.localIP()</h3><br>"));
int status = WiFi.status();
if (status == WL_CONNECTED) {
client.println(F("Connection successful. Ending AP."));
delay(1000); // to let the SDK finish the communication
Serial.println("Connection successful. Ending AP.");
configWebServer.stop();
WiFi.mode(WIFI_STA);
} else {
client.println(F("<form action='/' method='POST'>WiFi connection failed. Enter valid parameters, please.<br><br>"));
client.println(F("SSID:<br><input type='text' name='i'><br>"));
client.println(F("Password:<br><input type='password' name='p'><br><br>"));
client.println(F("<input type='submit' value='Submit'></form>"));
client.println(F("<Funktion 2 <a href=\"?pin=FUNCTION2ON\"><button>einschalten</button>"));
}
client.println(F("</body></html>"));
client.stop();
}
}
}
}
void loop() {
WiFiClient client = configWebServer.available(); // Hört auf Anfragen von Clients
if (client) { // Falls sich ein neuer Client verbindet,
Serial.println("Neuer Client."); // Ausgabe auf den seriellen Monitor
String currentLine = ""; // erstelle einen String mit den eingehenden Daten vom Client
while (client.connected()) { // wiederholen so lange der Client verbunden ist
if (client.available()) { // Fall ein Byte zum lesen da ist,
char c = client.read(); // lese das Byte, und dann
Serial.write(c); // gebe es auf dem seriellen Monitor aus
header += c;
if (c == '\n') { // wenn das Byte eine Neue-Zeile Char ist
// wenn die aktuelle Zeile leer ist, kamen 2 in folge.
// dies ist das Ende der HTTP-Anfrage vom Client, also senden wir eine Antwort:
if (currentLine.length() == 0) {
// HTTP-Header fangen immer mit einem Response-Code an (z.B. HTTP/1.1 200 OK)
// gefolgt vom Content-Type damit der Client weiss was folgt, gefolgt von einer Leerzeile:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// Hier wird nun die HTML Seite angezeigt:
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// Es folgen der CSS-Code um die Ein/Aus Buttons zu gestalten
// Hier können Sie die Hintergrundfarge (background-color) und Schriftgröße (font-size) anpassen
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #333344; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #888899;}</style></head>");
// Webseiten-Überschrift
client.println("<body><h1>ESP8266 Web Server</h1>");
client.println("</body></html>");
// Die HTTP-Antwort wird mit einer Leerzeile beendet
client.println();
// und wir verlassen mit einem break die Schleife
break;
} else { // falls eine neue Zeile kommt, lösche die aktuelle Zeile
currentLine = "";
}
} else if (c != '\r') { // wenn etwas kommt was kein Zeilenumbruch ist,
currentLine += c; // füge es am Ende von currentLine an
}
}
}
// Die Header-Variable für den nächsten Durchlauf löschen
header = "";
// Die Verbindung schließen
client.stop();
Serial.println("Client getrennt.");
Serial.println("");
}
}
The Programm should ends to loop() in both cases, I mean, if you have to configAP() or not.
please comment out WiFi.begin(); at the beginning to test the Configuration AP

Related

LCD ESP8266WiFi access point Send Text

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 /

How to solve espwifi.h library

#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

Arduino sketch for NodeMCU v1.0 (ESP8266-12E) have no error of compiling but not working on NodeMCU v1.0 (ESP8266-12E) Board

I compiled an Arduino Sketch for NodeMCU v1.0 (ESP8266-12E) which have no error while i test with verifiy button in Arduino IDE 1.8.6 but i don't know what is the problem when i upload and test it . it [ NodeMCU v1.0 (ESP8266-12E) ] is not showing an static IP address while there is turned ON WiFi hotspot from my android phone.
I'm sharing two codes (code 1, code 2) here. Code 1 is modified form of code 2.
Code 2 connect to the WiFi Hotspot but i make changes in code 2 to make code 1 for desired output which is not working. Need help for making proper code.
For better understanding, what i want you can check this video on Youtube or by typing in search bar in youtube.com
Home automation circuit using NodeMCU v1.0 (ESP8266-12E).
**code 1**
#include
int pin1 = 2; // GPIO 14 (D5)
int pin2 = 3; // GPIO 5 (D1)
int pin3 = 6; // GPIO 5 (D2)
const char* ssid = "wifi";
const char* password = "12345678";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(6, OUTPUT);
// Connect to WiFi network
Serial.println();
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.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
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 request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
// Match the request
int value = LOW;
if (request.indexOf("/pin1=ON") != -1) {
digitalWrite(2, HIGH);
value = HIGH;
}
if (request.indexOf("/pin1=OFF") != -1) {
digitalWrite(2, LOW);
value = LOW;
}
if (request.indexOf("/pin2=ON") != -1) {
digitalWrite(3, HIGH);
value = HIGH;
}
if (request.indexOf("/pin2=OFF") != -1) {
digitalWrite(3, LOW);
value = LOW;
}
if (request.indexOf("/pin3=ON") != -1) {
digitalWrite(6, HIGH);
value = HIGH;
}
if (request.indexOf("/pin3=OFF") != -1) {
digitalWrite(6, LOW);
value = LOW;
}
// Set ledPin according to the request
//digitalWrite(ledPin, value);
// Return the response
// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head>");
client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
client.println("</head>");
client.println("<body bgcolor = \"#f7e6ec\">");
client.println("<hr/><hr>");
client.println("<h4><center>Wifi Based Project</center></h4>");
client.println("</center>");
client.println("<hr/><hr>");
client.println("<center>");
client.println("<button>Data </button><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("Load 1");
client.println("<button>Turn On </button>");
client.println("<button>Turn Off </button><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("Load 2");
client.println("<button>Turn On </button>");
client.println("<button>Turn Off </button><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("Load 3");
client.println("<button>Turn On </button>");
client.println("<button>Turn Off </button><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("<br><br>");
client.println("<center>");
client.println("<table border=\"5\">");
client.println("<br><br>");
client.println("<tr>");
if(digitalRead(pin1)){client.print("<td>Load 1 is ON</td>");}
else{client.print("<td>Load 1 is OFF</td>");}
if(digitalRead(pin2)){client.print("<td>Load 2 is ON</td>");}
else{client.print("<td>Load 2 is OFF</td>");}
if(digitalRead(pin3)){client.print("<td>Load 3 is ON</td>");}
else{client.print("<td>Load 3 is OFF</td>");}
client.println("</tr>");
client.println("</table>");
client.println("</center>");
client.println("</html>");
delay(1);
Serial.println("Client disonnected");
Serial.println("");
}
if you will upload this code in your NodeMCU v1.0 (ESP8266-12E) , this will
connect with your Android phone. You can consider it, code 2 and above code 1.
code 2
#include <ESP8266WiFi.h>
int pin1 = 14; // GPIO 14 (D5)
int pin2 = 5; // GPIO 5 (D1)
int pin3 = 4; // GPIO 5 (D2)
const char* ssid = "wifi";
const char* password = "12345678";
WiFiServer server(80);
void setup()
{
Serial.begin(115200);
delay(10);
pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
pinMode(pin3, OUTPUT);
// Connect to WiFi network
Serial.println();
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.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
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 request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
if (request.indexOf("/l1on") > 0) {
digitalWrite(pin1, HIGH);
}
if (request.indexOf("/l1off") >0) {
digitalWrite(pin1, LOW);
}
if (request.indexOf("/l2on") > 0) {
digitalWrite(pin2, HIGH);
}
if (request.indexOf("/l2off") >0) {
digitalWrite(pin2, LOW);
}
if (request.indexOf("/l3on") >0) {
digitalWrite(pin3, HIGH);
}
if (request.indexOf("/l3off") > 0) {
digitalWrite(pin3, LOW);
}
// Set ledPin according to the request
//digitalWrite(ledPin, value);
// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head>");
client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
client.println("</head>");
client.println("<body bgcolor = \"#f7e6ec\">");
client.println("<hr/><hr>");
client.println("<h4><center>Wifi Based Project</center></h4>");
client.println("</center>");
client.println("<hr/><hr>");
client.println("<center>");
client.println("<button>Data </button><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("Load 1");
client.println("<button>Turn On </button>");
client.println("<button>Turn Off </button><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("Load 2");
client.println("<button>Turn On </button>");
client.println("<button>Turn Off </button><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("Load 3");
client.println("<button>Turn On </button>");
client.println("<button>Turn Off </button><br />");
client.println("</center>");
client.println("<br><br>");
client.println("<center>");
client.println("<br><br>");
client.println("<center>");
client.println("<table border=\"5\">");
client.println("<br><br>");
client.println("<tr>");
if(digitalRead(pin1)){client.print("<td>Load 1 is ON</td>");}
else{client.print("<td>Load 1 is OFF</td>");}
if(digitalRead(pin2)){client.print("<td>Load 2 is ON</td>");}
else{client.print("<td>Load 2 is OFF</td>");}
if(digitalRead(pin3)){client.print("<td>Load 3 is ON</td>");}
else{client.print("<td>Load 3 is OFF</td>");}
client.println("</tr>");
client.println("</table>");
client.println("</center>");
client.println("</html>");
delay(1);
Serial.println("Client disonnected");
Serial.println("");
}
You can't use io 6. IO 6 is for internal use to connect the flash memory to esp8266. IO 6 has no Dx pin on the board. And io 3 is Serial RX connected to USB.
Use Dx constants and the corresponding 'D' labeled pins of the NodeMcu. (and remove conflicting comments)
const int pin1 = D2;
const int pin2 = D3;
const int pin3 = D6;
pin D3 is io 0 used to put the board into flashing mode. do not connect there something that pulls the pin LOW at reset or power-up

NodeMCU esp8266 using PubSubClient.h callback function gets ignored

EDIT: The topics to publish and subscribe are correct even if they look different. with my publish, I writing on the field 4. Moreover I run also MQTT.fx in sub/pub mode with the same topics and it works perfectly.
I want to use mqtt with my NodeMCU with esp8266. I adapted simple MQTT example to my minimal project. In my code (attached below) I'm trying to publish and subscribe to a ThingSpeak channel. The publish function does not have any problem, it publishes every time it is called. But the callback function is simply ignored, my code never enters in it.
To give more infor here you have My settings:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "*****";
const char* password = "*****";
const char* mqtt_server = "mqtt.thingspeak.com";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
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(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Ciao sono la callback1\n");
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
Serial.print("Ciao sono la callback2\n");
digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is acive low on the ESP-01)
} else {
Serial.print("Ciao sono la callback3\n");
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("channels/517055/publish/V4ZW4Y01ZLFD5XYR", "field5=7&status=MQTTPUBLISH");
// ... and resubscribe
client.subscribe("channels/517055/subscribe/fields/field4");
Serial.print("Ciao sono subscribe 01\n");
} 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(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
Serial.print("Ciao sono la callback 10\n");
client.subscribe("channels/517055/subscribe/fields/field4");
Serial.print("Ciao subscribe 10\n");
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, 75, "field4= %ld&status=MQTTPUBLISH", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("channels/517055/publish/V4ZW4Y01ZLFD5XYR", msg);
}
}
Moreover here you have my serial monitor output:
Connecting to ZICHICHI
scandone
scandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 1
cnt
connected with ZICHICHI, channel 1
dhcp client start...
............ip:192.168.1.68,mask:255.255.255.0,gw:192.168.1.254
.
WiFi connected
IP address:
192.168.1.68
Ciao sono la callback 10
Ciao subscribe 10
Attempting MQTT connection...connected
Ciao sono subscribe 01
Publish message: field4= 1&status=MQTTPUBLISH
Publish message: field4= 2&status=MQTTPUBLISH
pm open,type:2 0
Publish message: field4= 3&status=MQTTPUBLISH
Publish message: field4= 4&status=MQTTPUBLISH
Publish message: field4= 5&status=MQTTPUBLISH
Publish message: field4= 6&status=MQTTPUBLISH
Publish message: field4= 7&status=MQTTPUBLISH
Publish message: field4= 8&status=MQTTPUBLISH
Publish message: field4= 9&status=MQTTPUBLISH
Publish message: field4= 10&status=MQTTPUBLISH
Publish message: field4= 11&status=MQTTPUBLISH
Publish message: field4= 12&status=MQTTPUBLISH
Publish message: field4= 13&status=MQTTPUBLISH
Publish message: field4= 14&status=MQTTPUBLISH
Publish message: field4= 15&status=MQTTPUBLISH
Publish message: field4= 16&status=MQTTPUBLISH
Publish message: field4= 17&status=MQTTPUBLISH
I hope someone know what I made wrong.
Actually, your Code is Almost correct but the loop() function is executing to Infinity.
basically, the code got stuck in the loop function, so that's why its not able to subscribe. Even if it is subscribed also, loop function will dominate on callback function and callback function will not be called, it will act as a NULL
Here is the Code, I have made some changes. Just try out
**This code will not keep on Publish the payload every time, If you want you can add the client.plublish in the loop() before client.loop()
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "*****";
const char* password = "*****";
const char* mqtt_server = "mqtt.thingspeak.com";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
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(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Ciao sono la callback1\n");
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
Serial.print("Ciao sono la callback2\n");
digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is acive low on the ESP-01)
} else {
Serial.print("Ciao sono la callback3\n");
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("channels/517055/publish/V4ZW4Y01ZLFD5XYR", "field5=7&status=MQTTPUBLISH");
// ... and resubscribe
client.subscribe("channels/517055/subscribe/fields/field4");
Serial.print("Ciao sono subscribe 01\n");
} 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(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
Serial.print("Ciao sono la callback 10\n");
connectmqtt();
}
void loop() {
if (!client.connected()) {
reconnect();
}
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, 75, "field4= %ld&status=MQTTPUBLISH", value);
Serial.print("Publish message: ");
Serial.println(msg);
}
client.loop();
}
void connectmqtt()
{
client.connect("ESP8266Client-");
{
Serial.println("connected");
// Once connected, publish an announcement...
// ... and resubscribe
client.subscribe("channels/517055/subscribe/fields/field4");
client.publish("channels/517055/publish/V4ZW4Y01ZLFD5XYR", msg);
if (!client.connected())
{
reconnect();
}
}
}
You are subscribing to a different topic than a topic you are publishing to. Your publishing topic is "channels/517055/publish/V4ZW4Y01ZLFD5XYR" while you are subscribing to "channels/517055/subscribe/fields/field4".
SOLVED
The code posted by me and the code posted by #karan was correct. The problem I had was realeted with thingspeak Broker connection and the Thingspeak documentation, that wasn't updated at the time. In particular is necessary to pass MQTT_APIKEY and USERNAME to establish connection with mqtt broker, even with PUBLIC channel.
The problem is solved passing these 2 parameters in connection step, like this:
client.connect("ESP8266Client-", "Your_username", "MQTT_APIKEY");
Many thanks to #karan that help me, and improved my code.

Arduino ESP8266 01 MQTT Raspberry pi

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.

Resources