I am beginner. I am using ESP8266 WIFI single relay ESP-12F Dev board to send some data over MQTT with PubSub client, it used to work well but after sometime(1-2 days) it does not receive message through MQTT. When I reset the board, it get starts working. I do not where the issue is and where is it freezing.
I am storing MQTT credentials in EEPROM also.
Here's my code
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <PubSubClient.h>
#include <WiFiManager.h>
#include <EEPROM.h>
WiFiClient espClient;
PubSubClient client(espClient);
const char MAIN_page[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
<body>
<h3> HTML Form ESP8266</h3>
<form action="/action_page">
Topic name:<br>
<input type="text" name="PublishTopic" value="">
<br>
Broker name:<br>
<input type="text" name="Mqtt_Broker" value="">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
)=====";
//SSID and Password of your WiFi router
const char* ssid = "Cherry"; //Daalchini#2.4Ghz
const char* password = "ravan#123"; //G_2425G_A
ESP8266WebServer server(80); //Server on port 80
//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void handleRoot() {
String s = MAIN_page; //Read HTML contents
server.send(200, "text/html", s); //Send web page
}
//===============================================================
// This routine is executed when you press submit
//===============================================================
void handleForm() {
String PublishTopic = server.arg("PublishTopic");
String Mqtt_Broker = server.arg("Mqtt_Broker");
const char* topic = PublishTopic.c_str(); //strstr( PublishTopic.c_str(), "]" );
const char* mqtt_server = Mqtt_Broker.c_str();
Serial.print("topic:");
Serial.println(topic);
Serial.print("PublishTopic:");
Serial.println(PublishTopic);
Serial.print("mqtt_server:");
Serial.println(mqtt_server);
Serial.print("MQTT Broker:");
Serial.println(Mqtt_Broker);
if(mqtt_server)
{
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
reconnect(topic);
if(!client.connected())
{
reconnect(topic);
Serial.print("disconnected");
}
}
String s = "<a href='/'> Go Back </a>";
server.send(200, "text/html", s); //Send web page
// Writing
int str1AddrOffset = writeStringToEEPROM(0,topic);
int str2AddrOffset = writeStringToEEPROM(str1AddrOffset,mqtt_server);
}
//==============================================================
// SETUP
//==============================================================
//===========================================
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Message arrived : ");
Serial.print(topic);
Serial.print(" : ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
}
//===========================================
void reconnect(const char* topic)
{
while(!client.connected()){
Serial.println("Attempting MQTT connection");
if(client.connect(""))
{
Serial.println("Connected");
//client.publish("justinmqtt/house/TMP","Connected!");
client.subscribe(topic);
Serial.print("subscribed!");
}
else
{
Serial.print("Failed, rc = ");
Serial.print(client.state());
Serial.println("Waiting for 5 seconds to try again");
delay(5000);
}
}
}
void setup(void){
Serial.begin(9600);
EEPROM.begin(512);
WiFi.begin(ssid, password); //Connect to your WiFi router
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.print("Connected to ");
Serial.println("WiFi");
String newStr1;
String newStr2;
int readstr = readingData(0, &newStr1);
int readstr1 = readingData(readstr, &newStr2);
const char* top = newStr1.c_str(); //strstr( PublishTopic.c_str(), "]" );
const char* servermqtt = newStr2.c_str();
Serial.println("top");
Serial.println(top);
Serial.println("servermqtt");
Serial.println(servermqtt);
if(servermqtt)
{
Serial.print("entering in a loop: ");
client.setServer(servermqtt, 1883);
client.setCallback(callback);
reconnect(top);
if(!client.connected())
{
reconnect(top);
Serial.print("disconnected");
}
}
else{
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
server.on("/", handleRoot); //Which routine to handle at root location
server.on("/action_page", handleForm); //form action is handled here
server.begin(); //Start server
Serial.println("HTTP server started");
}
// Serial.print("IP address: ");
// Serial.println(WiFi.localIP()); //IP address assigned to your ESP
//
// server.on("/", handleRoot); //Which routine to handle at root location
// server.on("/action_page", handleForm); //form action is handled here
//
// server.begin(); //Start server
// Serial.println("HTTP server started");
}
//==============================================================
// WRITE EEPROM
//==============================================================
int writeStringToEEPROM(int addrOffset, const String &strToWrite)
{
Serial.println("Writing Data ");
byte len = strToWrite.length();
Serial.println(len);
EEPROM.write(addrOffset, len);
for (int i = 0; i < len; i++)
{
EEPROM.write(addrOffset + 1 + i, strToWrite[i]);
}
EEPROM.commit();
return addrOffset + 1 + len;
}
//==============================================================
// READ EEPROM
//==============================================================
int readingData(int addrOffset, String *strToRead)
{
Serial.println("Reading Data");
int newStrLen = EEPROM.read(addrOffset);
char data[newStrLen + 1];
for (int i = 0; i< newStrLen; i++) {
data[i] = EEPROM.read(addrOffset + 1 + i);
}
data[newStrLen] = '\0';
Serial.println(data);
*strToRead = String(data);
return addrOffset + 1 + newStrLen;
}
//==============================================================
// LOOP
//==============================================================
void loop(void){
server.handleClient(); //Handle client requests
yield();
delay(50);
client.loop();
}
Related
I have some code I have been putting on an ESP8266-12e board. Until recently it always worked fine. Now though when I finish uploading the code the blue light on the ESP8266-12e is staying on. I have tried it on two different board and the blue light stay on on both. I can't figure out what I changed in the code.
I have decided to put it up and have everyone look at it and let me know what I may be missing.
I hope someone can find something.
My code:
//NodeMCU 1.0 (ESP-12E Module constant connect)
#include <ESP8266WiFi.h>
#include <FS.h> //https://github.com/esp8266/Arduino
#include <EEPROM.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
//MQTT stuff
#define AIO_SERVER "go,here"
#define AIO_SERVERPORT SSSS // 8883 for MQTTS
#define AIO_USERNAME "FFFFFF"
#define AIO_KEY "XXXXXXXXXXXXXXXXXXXXXXX"
int tripper = 1;
#define MQTT_CONN_KEEPALIVE 18000000
#define LED3 16
//NEW AUTOCONNECT
const byte numChars = 32;
char receivedChars[numChars];
char Password[36]="";
char apiKey[16]="";
char apiKey2[32]="";
char channelKey[16];
char channelKey2[16];
String channelKey21= "&";
byte pinState = LOW;
char ssid[] = "";
char pass[] = "";
String Label = "";
String TOTAL = "";
uint32_t m=0;
WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
// Setup a feed called 'onoff' for subscribing to changes.
Adafruit_MQTT_Subscribe trip2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/trip");
Adafruit_MQTT_Publish move1 = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/motion");
/*************************** Error Reporting *********************************/
Adafruit_MQTT_Subscribe errors = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/errors");
Adafruit_MQTT_Subscribe throttle = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/throttle");
//NEW AUTOCONNECT
int LED2 = 13;
int MOVEMENT = 5;
//send ssid/pass
String f;
//mqtt
char temperature[]="000";
String level;
String battery;
String trip;
String date;
int addr = 0;
//END NEW AUTOCONNECT
void MQTT_connect();
void setup() {
Serial.begin(115200);
pinMode(MOVEMENT,OUTPUT);
digitalWrite(MOVEMENT,LOW);
pinMode(D5,OUTPUT);
digitalWrite(D5,LOW);
pinMode(LED3,OUTPUT);
digitalWrite(LED3,LOW);
pinMode(LED2,INPUT);
Serial.println(F("Adafruit MQTT demo"));
//NEW AUTOCONNECT
WiFiManager wifiManager;
// put your setup code here, to run once:
WiFiManagerParameter customAPIKey("apiKey", "Time Zone #", apiKey, 16);
wifiManager.addParameter(&customAPIKey);
wifiManager.autoConnect("FloWT2");
Serial.println("Connected");
strcpy(apiKey,customAPIKey.getValue());
EEPROM.begin(512); //Initialize EEPROM
EEPROM.write(addr, 'A'); //Write character A
addr++; //Increment address
EEPROM.write(addr, 'B'); //Write character A
String www = apiKey;
Serial.print("www");
Serial.print (www);
for(int i=0;i<www.length();i++) //loop upto string lenght www.length() returns length of string
{
EEPROM.write(0x0F+i,www[i]); //Write one by one with starting address of 0x0F
}
EEPROM.commit();
delay (2000);
if (WiFi.status() == WL_DISCONNECTED) {
wifiManager.autoConnect("FloWT2");
delay(60000);}
if (WiFi.status() == WL_CONNECTED) { Serial.println("Connected");
delay(1000);
//get time zone
EEPROM.begin(512);
Serial.println(""); //Goto next line, as ESP sends some garbage when you reset it
Serial.print(char(EEPROM.read(addr))); //Read from address 0x00
addr++; //Increment address
Serial.print(char(EEPROM.read(addr))); //Read from address 0x01
addr++; //Increment address
Serial.println(char(EEPROM.read(addr))); //Read from address 0x02
//Read string from eeprom
String www;
//Here we dont know how many bytes to read it is better practice to use some terminating character
//Lets do it manually www.circuits4you.com total length is 20 characters
for(int i=0;i<16;i++)
{
www = www + char(EEPROM.read(0x0F+i)); //Read one by one with starting address of 0x0F
}
Serial.println("this");
Serial.print(www);
Serial.println("IP address: "); Serial.println(WiFi.localIP());
// Setup MQTT subscription for onoff feed
mqtt.subscribe(&trip2);
// Setup MQTT subscriptions for throttle & error messages
mqtt.subscribe(&throttle);
mqtt.subscribe(&errors);
WiFiClient client;
delay(2000);
Serial.printf("SSID: %s\n", WiFi.SSID().c_str());
Serial.printf("SSID: %s\n", WiFi.psk().c_str());
String ssidString = WiFi.SSID().c_str();
String pskString = WiFi.psk().c_str();
f = String('<')+String("Hi")+String(',')+String(ssidString)+String(',')+String(pskString)+String(',')+String(www)+String('>');
delay (1000);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
Serial.print(f);
delay(500);
}
client.stop();
}
void loop() {
MQTT_connect();
uint32_t m=0;
Serial.print(F("\nSending motion val "));
Serial.print(m);
Serial.print("...");
if (! move1.publish(m)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
long state = digitalRead(LED2);
if(state == HIGH) {
m = 1;
Serial.print(F("\nSending motion val "));
Serial.print(m);
Serial.print("...");
digitalWrite(MOVEMENT,HIGH);
delay(1000);
digitalWrite(MOVEMENT,LOW);
if (! move1.publish(m)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
}
else{
}
// this is our 'wait for incoming subscription packets' busy subloop
// try to spend your time here
//12e
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(5000))) {
if (subscription == &trip2) {
Serial.print(F("Got onoff: "));
Serial.println((char *)trip2.lastread);
uint16_t sliderval = atoi((char *)trip2.lastread);
//THIS IS FOR LATCHING RELAY TURN ON D5 HIGH THEN OFF AFTER 1 SECOND
//NEXt TURN D6 HIGH THEN OFF AFTER A SECONDS
if((sliderval ==0)&&(tripper == 1)){
digitalWrite(D5,HIGH);
delay(1000);
digitalWrite(D5,LOW);
tripper = 2;
Serial.print(tripper);
Serial.print("tripped");
}
else if(sliderval == 50){
}
else if((sliderval == 100)&&(tripper == 2)){
digitalWrite(LED3,HIGH);
delay(1000);
digitalWrite(LED3,LOW);
tripper = 1;
Serial.print(tripper);
Serial.print("tripped2");
}
} else if(subscription == &errors) {
Serial.print(F("ERROR: "));
Serial.println((char *)errors.lastread);
} else if(subscription == &throttle) {
Serial.println((char *)throttle.lastread);
}
}
}
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
}
I hope it is not toooo long.
Anyway I hope someone can find my problem. Everything works ok with the blue light on it is just know supposed to be that I can tell.
When I upload another code it doesn't stay on so it has to be in the code.
I will keep looking.
THANKS
So I got the blue light to go off. Instead of pinMode(D4,INPUT); and digitalWrite(D4,LOW); D4 is pin 16 which is the wake pin. So I had to define it thus #define LED3 16 and then pinMode(LED3,INPUT); and digitalWrite(LED3,LOW); I will change my original code to reflect these changes.
I have an NodeMCU chip that needs to connect to my home wifi and post an http request. I use the chip in WIFI_STA_AP mode as I need the chip to both accept requests via http and issue requests by http.
I do not want to hard-code my home's SSID/Password into the chip, so I have written some code that places the ESP (NodeMCU) into AP mode, receives the SSID/Pass via an http request and saves it on EEPROM.
This works great.
In the code below, onTestWifi() is called when I call http://192.168.4.1/test_wifi?wifi_ssid=mySsid&wifi_password=myPassword. The ssid and password are provided to the WiFi.begin() function. However, if I accidentally type in the wrong password and use it in WiFi.begin(), the connection will always fail until reset the chip and then insert the correct password.
What am I missing? Is it possible to change the ESP's wifi credentials programmatically, without having to reset the chip? Resetting the chip causes the client (in the case, an iPhone app) to disconnect from the chip and this breaks the entire program flow.
Here's the experimentation code I am using:
#include <ESP8266WiFiMulti.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
ESP8266WebServer server(80);
ESP8266WiFiMulti WiFiMulti;
void setup() {
Serial.begin(115200);
Serial.println("");
delay(100);
Serial.println("Starting...");
WiFi.persistent(false);
WiFi.mode(WIFI_AP_STA);
WiFi.softAP("APSSID");
IPAddress ip = WiFi.softAPIP();
server.on("/test_wifi", onTestWifi);
server.begin();
yield();
}
void onTestWifi()
{
char ssid[30] = "";
char password[30] = "";
for (int i = 0; i < server.args(); i++)
{
String n = server.argName(i);
String v = server.arg(i);
if (n == "wifi_ssid")
v.toCharArray(ssid, 30);
else if (n == "wifi_password")
v.toCharArray(password, 30);
yield();
}
Serial.print("Connecting to: ");
Serial.print(ssid);
Serial.print(" ");
Serial.println(password);
delay(100);
WiFi.begin(ssid, password);
yield();
int counter = 0;
while (WiFi.status() != WL_CONNECTED && counter < 10)
{ // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++counter);
Serial.print(' ');
}
if (WiFi.status() != WL_CONNECTED)
{ // Failed to connect.
Serial.println("Connection failed!");
}
else {
Serial.println("Connection succeeded!");
}
yield();
}
void loop() {
server.handleClient();
}```
OK, so I figured it out. Had to add the line WiFi.disconnect(true) in the onTestWifi() function. Apparently it disconnects from the network and erases the credentials. This stuff is very poorly documented and I wasted days on it.
I hope someone finds it useful.
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
ESP8266WebServer server(80);
ESP8266WiFiMulti WiFiMulti;
void setup() {
Serial.begin(115200);
Serial.println("");
delay(100);
Serial.println("Starting...");
WiFi.persistent(false);
WiFi.mode(WIFI_AP_STA);
WiFi.softAP("APSSID");
IPAddress ip = WiFi.softAPIP();
server.on("/test_wifi", onTestWifi);
server.begin();
yield();
}
void onTestWifi()
{
char ssid[30] = "";
char password[30] = "";
for (int i = 0; i < server.args(); i++)
{
String n = server.argName(i);
String v = server.arg(i);
if (n == "wifi_ssid")
v.toCharArray(ssid, 30);
else if (n == "wifi_password")
v.toCharArray(password, 30);
yield();
}
Serial.print("Connecting to: ");
Serial.print(ssid);
Serial.print(" ");
Serial.println(password);
delay(100);
WiFi.begin(ssid, password);
yield();
int counter = 0;
while (WiFi.status() != WL_CONNECTED && counter < 10)
{ // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++counter);
Serial.print(' ');
}
if (WiFi.status() != WL_CONNECTED)
{ // Failed to connect.
Serial.println("Connection failed!");
}
else {
Serial.println("Connection succeeded!");
}
WiFi.disconnect(true); // <--- Added this line
yield();
}
void loop() {
server.handleClient();
}
Can someone help me with this code?
The goal is to trigger a Led when the value of the payload is > 1000.
It is a MQTT subscribtion code based on the esp8266mqtt PubSub client example. I will use it for a subscribyion of a topic from a CO2sensor
I've tried to modify a part of it but I think it has yo do something with the kind of datatype or a wrong condition?
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char *ssid = "xxx";
const char *password = "xxx";
const char *mqtt_server = "xxxx";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
int led = D4;
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("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 value of C02 is above 1000
i = atoi (payload); //convert string to integer
if ( i > 1000) // comparison
{
digitalWrite(led, HIGH); // Turn the LED on
}
else
{
digitalWrite(led, LOW); // Turn the LED off
}
}
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("outTopic", "Test");
// ... and resubscribe
client.subscribe("my/sensors/co2");
}
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(led, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop()
{
if (!client.connected())
{
reconnect();
}
client.loop();
}
Kind regards
Hi, This is what I publish:
void pubMessage() {
char message[16];
snprintf(message, sizeof(message), "%d", co2);
client.publish("my/sensors/co2", message);
delay(30000);
First you are casting the first byte of payload to a char.
Since it's just the first byte, it has a max value of 256.
Second you are comparing that 1 bytes value to the string '1000'
Without knowing exactly what you are publishing it is very hard to tell you how to fix it.
If you are publishing a string representing the number then you will need to parse it first with atoi() then do the comparison to the integer 1000 not the string.
If it is a byte value then you will need to read the correct value from the incoming byte array before doing the comparison.
In my code I am receiving a "Wifi is not declared in this scope" error when compiling to a NodeMCU board. The code has some customization, but regarding the WiFi and lines where it calls Wifi functions, it has the same structure to the source code.
The source code compiles flawless, what let me think that there is no issue with libraries or any kind of updates. I already reviewed my code many times and don't get the error.
Here follows the complete compiling error:
C:\Users\Administrator\Documents\Arduino\teste_watsoniot\teste_watsoniot.ino:
In function 'void setup()':
teste_watsoniot:65:14: error: 'Wifi' was not declared in this scope
if (strcmp(Wifi.SSID().c_str(), ssid) != 0) {
^
teste_watsoniot:73:59: error: 'Wifi' was not declared in this scope
Serial.print("Connected, IP address: ");
Serial.println(Wifi.localIP());
^
exit status 1 'Wifi' was not declared in this scope
Here is the code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <SimpleTimer.h>
#include "DHT.h"
/* Wi-Fi Information */
const char* ssid = "xxx";
const char* password = "xxx";
/* Watson Configurations */
#define DEVICE_TYPE "xxx"
#define DEVICE_ID "xxx"
#define ORG "xxx"
#define TOKEN "xxx" // this authentication token given with API key
char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char topic[] = "iot-2/evt/status/fmt/json"; //"iot-2/type/xxx/id/xxx/evt/1-anl/fmt/json"; // customize type and ID
char authMethod[] = "use-token-auth";
//char authMeth[] = "xxx"; // here a API key
char token[] = TOKEN;
char clientID[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
/* String to send data */
String Str1 = "hum";
String Str2 = "temp";
String Str3 = "ldrValue1";
String Str4 = "soilValue2";
/* Start Wi-Fi */
WiFiClientSecure wifiClient;
PubSubClient client(server, 1833, wifiClient);
/* TIMER */
SimpleTimer timer;
/* DHT22*/
#define DHTPIN D3
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
float hum = 0;
float temp = 0;
/* Soil Moister and LDR */
int sensorPin = A0; // analog input for both sensors
int enable1 = D1; // enable reading Sensor 1
int enable2 = D2; // enable reading Sensor 2
int ldrValue1 = 0;
int soilValue2 = 0;
void setup()
{
Serial.begin(115200); Serial.println();
Serial.print("Conectando na rede "); Serial.print(ssid);
if (strcmp(Wifi.SSID().c_str(), ssid) != 0) {
WiFi.begin(ssid, password);
}
while (WiFi.status() != WL_CONNECTED) {
delay (500);
Serial.print (".");
}
Serial.println("");
Serial.print("Connected, IP address: "); Serial.println(Wifi.localIP());
timer.setInterval(1000L, getDhtData);
pinMode(enable1, OUTPUT);
pinMode(enable2, OUTPUT);
dht.begin();
}
/* Send to cloud */
void enviaDado(float dado1,float dado2, float dado3, float dado4){
String payload = "{\"d\":{\"" + Str1 + "\":";
payload += dado1;
payload += ", \"" + Str2 + "\":";
payload += dado2;
payload += ", \"" + Str3 + "\":";
payload += dado3;
payload += ", \"" + Str4 + "\":";
payload += dado4;
payload += "}}";
Serial.print("Sending payload: ");
Serial.println(payload);
//__ Envia o dado
if (client.publish(topic, (char*) payload.c_str())) {
Serial.println("Publish ok");
} else {
Serial.println("Publish failed");
}
}
void loop()
{
// Sensor DHT22
getDhtData();
// Sensor 1 LDR
digitalWrite(enable1, HIGH);
ldrValue1 = analogRead(sensorPin);
ldrValue1 = constrain(ldrValue1, 300, 850);
ldrValue1 = map(ldrValue1, 300, 850, 0, 1023);
Serial.print("Light intensity: ");
Serial.println(ldrValue1);
digitalWrite(enable1, LOW);
delay(500);
// Sensor 2 SOIL MOISTURE
digitalWrite(enable2, HIGH);
delay(500);
soilValue2 = analogRead(sensorPin);
soilValue2 = constrain(soilValue2, 300, 0);
soilValue2 = map(soilValue2, 300, 0, 0, 100);
Serial.print("Soil moisture: ");
Serial.println(soilValue2);
Serial.println();
delay(500);
digitalWrite(enable2, LOW);
displayData();
delay(2000); // delay for getting DHT22 data
timer.run(); // Initiates SimpleTimer
}
/* Get DHT data */
void getDhtData(void)
{
float tempIni = temp;
float humIni = hum;
temp = dht.readTemperature();
hum = dht.readHumidity();
if (isnan(hum) || isnan(temp)) // Check if any reads failed and exit early (to try again).
{
Serial.println("Failed to read from DHT sensor!");
temp = tempIni;
hum = humIni;
return;
}
}
/* display DHT data */
void displayData(void)
{
Serial.print(" Temperature: ");
Serial.print(temp);
Serial.print("oC Humidity: ");
Serial.print(hum);
Serial.println("%");
}
Here is the source code:
https://github.com/ibm-watson-iot/device-arduino/blob/master/samples/ESP8266MqttSecure/ESP8266MqttSecure.ino
I have a simple code in which I am trying to connect to HiveMQ open broker and subscribe to a topic to listen to incoming messages.
here is the code
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char *ssid = "P9Inct"; // cannot be longer than 32 characters!
const char *pass = "P9inct123*"; //
const char *mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
const char *mqtt_user = "testUser";
const char *mqtt_pass = "abc123";
const char *mqtt_client_name = "12312312332212";
#define BUFFER_SIZE 100
String incoming="";
String did="";
String state="";
// Update these with values suitable for your network.
//IPAddress server(172, 16, 0, 2);
String DEVID="8581870006";//"6931108641";//old
WiFiClient wclient;
PubSubClient client(wclient, mqtt_server,mqtt_port);
void callback(const MQTT::Publish& pub) {
// handle message arrived
Serial.print(pub.topic());
Serial.print(" => ");
if (pub.has_stream()) {
uint8_t buf[BUFFER_SIZE];
int read;
while (read = pub.payload_stream()->read(buf, BUFFER_SIZE)) {
Serial.write(buf, read);
}
pub.payload_stream()->stop();
Serial.println("");
} else
Serial.println(pub.payload_string());
////////////////////////////////////////////
incoming=String(pub.payload_string());
Serial.println(pub.payload_string());
Serial.println(incoming);
}
void setup() {
// Setup console
Serial.begin(115200);
delay(10);
Serial.println();
Serial.println();
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Connecting to ");
Serial.print(ssid);
Serial.println("...");
WiFi.begin(ssid, pass);
if (WiFi.waitForConnectResult() != WL_CONNECTED)
return;
Serial.println("WiFi connected");
}
if (WiFi.status() == WL_CONNECTED) {
if (!client.connected()) {
Serial.println("Connecting to MQTT server");
if (client.connect(MQTT::Connect(mqtt_client_name)
.set_auth(mqtt_user, mqtt_pass))) {
Serial.println("Connected to MQTT server");
client.set_callback(callback);
client.subscribe("diy/1"+DEVID);
} else {
Serial.println("Could not connect to MQTT server");
}
}
if (client.connected())
client.loop();
}
}
WiFi connection is working fine but, communication via broker is not working and it always gives the message "Could not connect to MQTT server". How to make esp8266 work with HiveMQ broker. The dashboard of borker is
http://www.mqtt-dashboard.com/
So, you are connected. You have unnecessary print line in your loop. Try to adapt on this :
/* Incoming data callback. */
void callback(char* topic, byte* payload, unsigned int length)
{
char payloadStr[length + 1];
memset(payloadStr, 0, length + 1);
strncpy(payloadStr, (char*)payload, length);
Serial.printf("Topic : [%s]\n", topic);
Serial.printf("Payload : %s\n", payloadStr);
}
void performConnect()
{
uint16_t connectionDelay = 5000;
while (!client.connected())
{
if (client.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_KEY))
{
Serial.printf("Connected to Broker.\n");
client.subscribe("diy/1"+DEVID);
}
else
{
Serial.printf("MQTT Connect failed, rc = %d\n", client.state());
Serial.printf("Trying again in %d msec.\n", connectionDelay);
delay(connectionDelay);
}
}
}
void loop()
{
if (!client.connected())
{
performConnect();
}
client.loop();
}