TX/RX Communication with NodeMCU - wifi

I am trying to set up a transmitter-receiver-style relationship between two NodeMCUs (ESP-12e) using WiFi. I have one NodeMCU (the "transmitter") configured as a server and the other ("receiver") as a client. The transmitter reads in an analog value and sends it to the receiver, which outputs it in digital format via 8 LEDs. The transmitter says that the network is active, but the client cannot connect, and when I look in my laptop WiFi manager the network isn't there either. Can someone tell me what I'm doing wrong? Is it something in my code or is it how the board is configured?
Transmitter/Server Code:
#include <ESP8266WiFi.h>
#define PORT 8555
#define LED0 13
#define LED1 14
#define ADC 0
const char* NETWORK = "NodeMCU";
const char* PASSKEY = "asdf1234";
WiFiServer host(PORT);
WiFiClient node;
IPAddress IP(192,168,4,1);
IPAddress gateway(192,168,4,1);
IPAddress subnet(255,255,255,0);
void setup() {
pinMode(LED0, OUTPUT);
pinMode(LED1, OUTPUT);
pinMode(ADC, INPUT);
digitalWrite(LED0, LOW);
digitalWrite(LED1, LOW);
WiFi.disconnect();
WiFi.mode(WIFI_AP);
WiFi.softAP(NETWORK, PASSKEY);
WiFi.softAPConfig(IP, gateway, subnet);
delay(100);
WiFi.begin(NETWORK, PASSKEY);
delay(100);
host.begin();
delay(100);
digitalWrite(LED1, HIGH);
}
void loop() {
if (node.connected()) digitalWrite(LED0, HIGH);
else digitalWrite(LED0, LOW);
host.write(analogRead(ADC) / 4);
}
Receiver/Client Code:
#include <ESP8266WiFi.h>
#define PORT 8555
#define DAC0 16
#define DAC1 5
#define DAC2 4
#define DAC3 2
#define DAC4 14
#define DAC5 12
#define DAC6 13
#define DAC7 15
const char* NETWORK = "NodeMCU";
const char* PASSKEY = "asdf1234";
IPAddress hostIP(192,168,4,1);
WiFiClient node;
void setup() {
pinMode(DAC0, OUTPUT);
pinMode(DAC1, OUTPUT);
pinMode(DAC2, OUTPUT);
pinMode(DAC3, OUTPUT);
pinMode(DAC4, OUTPUT);
pinMode(DAC5, OUTPUT);
pinMode(DAC6, OUTPUT);
pinMode(DAC7, OUTPUT);
digitalWrite(DAC7, HIGH);
WiFi.disconnect();
WiFi.mode(WIFI_STA);
WiFi.begin(NETWORK, PASSKEY);
while (WiFi.status() != WL_CONNECTED) { // <-- gets stuck here
digitalWrite(DAC7, LOW);
delay(200);
digitalWrite(DAC7, HIGH);
delay(200);
}
if(node.connect(hostIP, PORT)) digitalWrite(DAC7, LOW);
}
void loop() {
if (node.available()) adcWrite(node.read());
}
void adcWrite(byte level) {
bool vals[8];
for (int i = 0; i < 8; i++) {
vals[i] = level % 2;
level /= 2;
}
digitalWrite(DAC0, vals[0]);
digitalWrite(DAC1, vals[1]);
digitalWrite(DAC2, vals[2]);
digitalWrite(DAC3, vals[3]);
digitalWrite(DAC4, vals[4]);
digitalWrite(DAC5, vals[5]);
digitalWrite(DAC6, vals[6]);
digitalWrite(DAC7, vals[7]);
}
Ports LED0 and LED1 on the TX and DAC0-7 on the RX are connected to LEDs, the ADC on the TX is connected to a 10k potentiometer. When I run the code, LED0 is off, LED1 is on, and DAC7 blinks indefinitely.

Related

Lose MQTT Connection after 15-30 minutes

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.

ESP8266 unable to read data from Google Firebase

I'm trying to make an IOT app. My android side is working good so far, however my ESP8266 is unable to read data from Firebase Database. There is no error while connecting to the internet using onboard ESP8266 though. Can anyone point to a possible error? Thank You
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#define WIFI_SSID "WiFi"
#define WIFI_PASSWORD "xxxxxxxx"
#define FIREBASE_HOST "https://iot.firebaseio.com"
#define FIREBASE_AUTH "xxxxxxxx"
int LED1 = D5;
void setup()
{
Serial.begin(115200);
pinMode(LED1, OUTPUT);
Serial.println('\n');
wifiConnect();
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
delay(10);
}
void loop()
{
if(WiFi.status() != WL_CONNECTED)
{
wifiConnect();
}
delay(10);
Serial.print("Data from firebase:" + Firebase.getString("LED1") + "\n");
digitalWrite(LED1, Firebase.getString("LED1").toInt());
//digitalWrite(LED1, HIGH);
delay(10);
}
void wifiConnect()
{
WiFi.begin(WIFI_SSID, WIFI_PASSWORD); // Connect to the network
Serial.print("Connecting to ");
Serial.print(WIFI_SSID); Serial.println(" ...");
int teller = 0;
while (WiFi.status() != WL_CONNECTED)
{ // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++teller); Serial.print(' ');
}
Serial.println('\n');
Serial.println("Connection established!");
Serial.print("IP address:\t");
Serial.println(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer
}
For anyone encountering this issue. I got it working by removing the forward slash '/' at the end and the https:// from the start of Host Address.
At the line:
#define FIREBASE_HOST "https://iot.firebaseio.com"
you should fix to:
#define FIREBASE_HOST "iot.firebaseio.com"

Send data from NodeMcu(ESP266) to ESP32 using esp now?

I am trying to send some data from a Nodemcu(esp8266) to ESP32. I am trying to use espnow for that purpose, but I am really stuck, I cant merge the Master and Slave for both the boards, I find the codes to be far different I tried some modifications and I can send data from the Nodemcu but can't receive it on the ESP32. I am trying to send two analog values for a Gesture control car.
The master code or the controller code running on the Nodemcu is given below
#include <ESP8266WiFi.h>
#include <espnow.h>
#define MUX_A D4
#define MUX_B D3
#define MUX_C D2
#define ANALOG_INPUT A0
#define CHANNEL 4
extern "C" {
}
uint8_t remoteMac[] = {0x24, 0x6F, 0x28, 0xB6, 0x24, 0x49};
struct __attribute__((packed)) DataStruct {
//char text[32];
int x;
int y;
unsigned long time;
};
DataStruct myData;
unsigned long lastSentMillis;
unsigned long sendIntervalMillis = 1000;
unsigned long sentMicros;
unsigned long ackMicros;
int xAxis;
int yAxis;
int zAxis;
void InitESPNow() {
WiFi.disconnect();
if (esp_now_init()==0) {
Serial.println("ESPNow Init Success");
}
else {
Serial.println("ESPNow Init Failed");
// Retry InitESPNow, add a counte and then restart?
// InitESPNow();
// or Simply Restart
ESP.restart();
}
}
void sendData() {
if (millis() - lastSentMillis >= sendIntervalMillis) {
lastSentMillis += sendIntervalMillis;
myData.time = millis();
uint8_t bs[sizeof(myData)];
memcpy(bs, &myData, sizeof(myData));
sentMicros = micros();
esp_now_send(NULL, bs, sizeof(myData)); // NULL means send to all peers
Serial.println("sent data");
Serial.println(myData.x);
Serial.println(myData.y);
}
}
void sendCallBackFunction(uint8_t* mac, uint8_t sendStatus) {
ackMicros = micros();
Serial.print("Trip micros "); Serial.println(ackMicros - sentMicros);
Serial.printf("Send status = %i", sendStatus);
Serial.println();
Serial.println();
}
void setup() {
Serial.begin(115200); Serial.println();
Serial.println("Starting EspnowController.ino");
WiFi.mode(WIFI_STA); // Station mode for esp-now controller
WiFi.disconnect();
Serial.printf("This mac: %s, ", WiFi.macAddress().c_str());
Serial.printf("slave mac: %02x%02x%02x%02x%02x%02x", remoteMac[0], remoteMac[1], remoteMac[2], remoteMac[3], remoteMac[4], remoteMac[5]);
Serial.printf(", channel: %i\n",CHANNEL);
InitESPNow();
esp_now_set_self_role(ESP_NOW_ROLE_CONTROLLER);
esp_now_add_peer(remoteMac, ESP_NOW_ROLE_SLAVE, CHANNEL, NULL, 0);
esp_now_register_send_cb(sendCallBackFunction);
Serial.print("Message ");
pinMode(MUX_A, OUTPUT);
pinMode(MUX_B, OUTPUT);
pinMode(MUX_C, OUTPUT);
Serial.println("Setup finished");
}
void changeMux(int c, int b, int a) {
digitalWrite(MUX_A, a);
digitalWrite(MUX_B, b);
digitalWrite(MUX_C, c);
}
void loop() {
changeMux(LOW, LOW, LOW);
xAxis = analogRead(ANALOG_INPUT); //Value of the sensor connected to pin 0 of IC
changeMux(LOW, LOW, HIGH);
yAxis = analogRead(ANALOG_INPUT); //Value of the sensor connected to pin 1 of IC
changeMux(LOW, HIGH, LOW);
zAxis = analogRead(ANALOG_INPUT); //Value of the sensor connected to pin 2 of IC
changeMux(LOW, HIGH, LOW);
myData.x= xAxis;
myData.y= yAxis;
sendData();
delay(500);
}
The slave code running on the ESP32 is given below
#include <esp_now.h>
#include <WiFi.h>
#include <esp_wifi.h>
#define CHANNEL 4
uint8_t mac[] = {0x36, 0x33, 0x33, 0x33, 0x33, 0x33};
struct __attribute__((packed)) DataStruct {
//char text[32];
int x;
int y;
unsigned long time;
};
DataStruct myData;
// Init ESP Now with fallback
void setup() {
Serial.begin(115200);
Serial.println("ESPNow/Basic/Slave Example");
//Set device in AP mode to begin with
WiFi.mode(WIFI_AP);
// configure device AP mode
// This is the mac address of the Slave in AP Mode
esp_wifi_set_mac(ESP_IF_WIFI_STA, &mac[0]);
Serial.print("AP MAC: "); Serial.println(WiFi.softAPmacAddress());
// Init ESPNow with a fallback logic
if (esp_now_init()!=0) {
Serial.println("*** ESP_Now init failed");
while(true) {};
}
// Once ESPNow is successfully Init, we will register for recv CB to
// get recv packer info.
esp_now_register_recv_cb(OnDataRecv);
Serial.print("Aheloiioi");
}
// callback when data is recv from Master
void OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int data_len) {
memcpy(&myData, data, sizeof(myData));
char macStr[18];
snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
Serial.print("Last Packet Recv from: "); Serial.println(macStr);
Serial.print("Last Packet Recv Data: "); Serial.println(myData.x); Serial.println(myData.y);
Serial.println("");
}
void loop() {
// Chill
}
This is the only output I get on the ESP32
ESPNow/Basic/Slave Example
AP MAC: 24:6F:28:B6:24:49
Aheloiioi
While this is the output on Nodemcu
Starting EspnowController.ino
This mac: BC:DD:C2:B5:E3:2B, slave mac: 246f28b62449, channel: 4
ESPNow Init Success
Message Setup finished
sent data
10
8
Trip micros 7320
Send status = 1
sent data
9
8
Trip micros 6817
Send status = 1
sent data
10
9
Trip micros 6731
Send status = 1
and it continues
If there are any other methods to send data, please do mention
I never use esp_now before so I didn't test it myself, but I think this has nothing to do with the library or esp32, it is just a minor mistake of c++ usage.
On your sendData() function of your esp8266, you did this:
uint8_t bs[sizeof(myData)];
memcpy(bs, &myData, sizeof(myData));
sentMicros = micros();
esp_now_send(NULL, bs, sizeof(myData));
The bs has a type of uint8_t and is an array, and you try to copy the data that has a type of struct myData into the array. And you then try to pass the array into the esp_now_send(). I quickly took a look at the esp_now_send() function prototype definition, the esp_now_send() need to pass in the address (which has a type of uint8_t) of your data structure myData.
I don't know know why you need to do the memcpy, but I think it will easier and simply to just directly pass in the pointer of myData into the function call.
void sendData() {
if (millis() - lastSentMillis >= sendIntervalMillis) {
lastSentMillis += sendIntervalMillis;
myData.time = millis();
esp_now_send(NULL, (uint8_t *)&myData, sizeof(myData)); // NULL means send to all peers
Serial.println("sent data");
Serial.println(myData.x);
Serial.println(myData.y);
}
}
Please let me know if this work?

Publish/Subscribe simultaneously using MQTT

I'm trying to make a code that can subscribe and publish operations simultaneously. I have this code below that I think should perform the functions simultaneously but it doesn't seem to be working:
#include <Adafruit_MQTT.h>
#include <Adafruit_MQTT_Client.h>
#include <Adafruit_MQTT_FONA.h>
//#include <stackThunk.h>
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include "DHT.h"
#define DHTPIN 13
#define DHTTYPE DHT11
#define Relay1 4
#define Relay2 0
#define Relay3 2
#define Relay4 14
//#define WLAN_SSID "((DREAMNET03132490047))" // Your SSID
//#define WLAN_PASS "multan69"
DHT dht(DHTPIN, DHTTYPE);
char str_hum[16];
char str_temp[16];
#define WLAN_SSID "Connect(ow)03002618017" // Your SSID
#define WLAN_PASS "XXXXXXX" // Your password
/************************* Adafruit.io Setup *********************************/
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883 // use 8883 for SSL
#define AIO_USERNAME "XXXXXXXXXXXXXX" // Replace it with your username
#define AIO_KEY "XXXXXXXXXXXXXXXXXXXXXXXXXXX" // Replace with your Project Auth Key
/************ Global State (you don't need to change this!) ******************/
// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
/****************************** Feeds ***************************************/
// Setup a feed called 'onoff' for subscribing to changes.
Adafruit_MQTT_Subscribe Light1 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Relay1"); // FeedName
Adafruit_MQTT_Subscribe Light2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay2");
Adafruit_MQTT_Subscribe Light3 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay3");
Adafruit_MQTT_Subscribe Light4 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Relay4");
Adafruit_MQTT_Publish temp = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Temperature");
Adafruit_MQTT_Publish hum = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Humidity");
void MQTT_connect();
void setup() {
Serial.begin(115200);
delay(10);
dht.begin();
pinMode(Relay1, OUTPUT);
pinMode(Relay2, OUTPUT);
pinMode(Relay3, OUTPUT);
pinMode(Relay4, OUTPUT);
// Connect to WiFi access point.
Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// Setup MQTT subscription for onoff feed.
mqtt.subscribe(&Light1);
mqtt.subscribe(&Light3);
mqtt.subscribe(&Light2);
mqtt.subscribe(&Light4);
}
void loop() {
MQTT_connect();
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.println(" *F");
Serial.print("Temperature in Celsius:");
Serial.println(String(t).c_str());
Serial.print("Temperature in Fahrenheit:");
Serial.println(String(f).c_str());
Serial.print("Humidity:");
Serial.println(String(h).c_str());
//dtostrf(gps_latitude, 4, 2, str_temp);
//dtostrf(gps_longitude, 4, 2, str_hum);
// Now we can publish stuff!
Serial.print(F("\nSending Humidity value: "));
Serial.print(String(h).c_str());
Serial.print("...");
if (! hum.publish(String(h).c_str())) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
delay(1000);
Serial.print(F("\nSending Temperature value: "));
Serial.print(String(t).c_str());
Serial.print("...");
if (! temp.publish(String(t).c_str())) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
//temperature_work();
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(20000))) {
if (subscription == &Light1) {
Serial.print(F("Got: "));
Serial.println((char *)Light1.lastread);
int Light1_State = atoi((char *)Light1.lastread);
digitalWrite(Relay1, Light1_State);
}
if (subscription == &Light2) {
Serial.print(F("Got: "));
Serial.println((char *)Light2.lastread);
int Light2_State = atoi((char *)Light2.lastread);
digitalWrite(Relay2, Light2_State);
}
if (subscription == &Light3) {
Serial.print(F("Got: "));
Serial.println((char *)Light3.lastread);
int Light3_State = atoi((char *)Light3.lastread);
digitalWrite(Relay3, Light3_State);
}
if (subscription == &Light4) {
Serial.print(F("Got: "));
Serial.println((char *)Light4.lastread);
int Light4_State = atoi((char *)Light4.lastread);
digitalWrite(Relay4, Light4_State);
}
}
}
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!");
}
void temperature_work(){
delay(2000);
}
However, when I upload the code of publish and subscription separately, it works fine. Can anyone please take a look at my code attempt and tell me what I'm doing wrong?

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