Arduino MQTT disconnect - arduino

I have a ESP32 board with 2 relays and a DHT22 sensor and the bellow code in Arduino running on the ESP32
MQTT Broker is running on Pi4 with mosquitto and node-red dashboard.
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
#define DHTTYPE DHT22
const char* ssid = "MY SSID";
const char* password = "1234";
const char* mqtt_server = "192.168.1.118";
WiFiClient espClient;
PubSubClient client(espClient);
const int DHTPin = 14;
const int lamp = 25;
const int lamp1 = 26;
DHT dht(DHTPin, DHTTYPE);
long now = millis();
long lastMeasure = 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);
delay(1000);
WiFi.disconnect();
delay(1000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
String message;
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
char c = (char)payload[i];
message += c;
}
Serial.println();
if ((char)payload[0] == '0' || message == "false") {
digitalWrite(lamp, HIGH);
delay(100);
digitalWrite(lamp1, LOW);
Serial.println("lamp, HIGH si lamp1, LOW");
} else if ((char)payload[0] == '1' || message == "true") {
digitalWrite(lamp1, HIGH);
delay(100);
digitalWrite(lamp, LOW);
Serial.println("lamp, LOW si lamp1, HIGH");
} else if ((char)payload[0] == '2') {
digitalWrite(lamp, HIGH);
digitalWrite(lamp1, HIGH);
Serial.println("lamp, LOW si lamp1, LOW > STOP");
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Subscribe or resubscribe to a topic
// You can subscribe to more topics (to control more LEDs in this example)
client.subscribe("room/lamp");
client.subscribe("room/lamp1");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(lamp, OUTPUT);
pinMode(lamp1, OUTPUT);
pinMode(LED,OUTPUT);
dht.begin();
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
// For this project, you don't need to change anything in the loop function. Basically it ensures that you ESP is connected to your broker
void loop() {
if (!client.connected()) {
reconnect();
}
if(!client.loop())
client.connect("ESP8266Client");
now = millis();
// Publishes new temperature and humidity every 30 seconds
if (now - lastMeasure > 5000) {
lastMeasure = now;
// 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))
if (isnan(h) || isnan(t)){
Serial.println("Failed to read from DHT sensor!");
return;
}
// Computes temperature values in Celsius
float hic = dht.computeHeatIndex(t, h, false);
static char temperatureTemp[7];
dtostrf(t, 6, 2, temperatureTemp);
static char test[7];
dtostrf(hic, 6, 2, test);
static char humidityTemp[7];
dtostrf(h, 6, 2, humidityTemp);
client.publish("room/temperature", temperatureTemp);
client.publish("room/humidity", humidityTemp);
client.publish("room/test", test);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t Temperature: ");
Serial.print(t);
Serial.print(" *C ");
//Serial.print(f);
Serial.print(" *F\t Heat index: ");
Serial.print(hic);
Serial.println(" *C ");
delay(500);
digitalWrite(LED,HIGH);
delay(500);
digitalWrite(LED,LOW);
}
}
The 2 relays are controlling a window in my bathroom. If I plug the ESP32 to power all is working, and I can open/close the window and sensor readings are ok.
But after ~24hours I can still see realtime sensor readings but when I try to open/close the window nothing is happening. On the MQTT broker I can see the mqtt messages but nothing is happening.
room/lamp1 1
room/lamp1 1
room/lamp 0
room/lamp 0
room/lamp 0
room/lamp 0
room/lamp 0
room/lamp 0
room/temperature 24.00
room/humidity 29.10
room/test 23.22
room/lamp 0
room/lamp 0
room/lamp 2
room/lamp1 2
room/lamp 2
room/lamp1 2
room/lamp 2
room/lamp1 2
room/lamp 2
Any suggestions.

Related

Node mcu esp8266 disconnects from MQTT broker

I have two node mcu modules connected to the same network, running the same code and powered the same way. Both of them are subscribed to the topic Terma but one of them randomly disconnects and then reconnects to the MQTT broker meanwhile it stayed connected to the wifi uninterruptedly, the other module stays connected with no problem. I don't know if it is a network issue or if the node mcu is damaged.
here is the code:
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "Milagros";
const char* password = "18095381";
const char* mqtt_server = "192.168.1.133";
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("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') {
digitalWrite(14, LOW);
client.publish("estado","1");
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(14, HIGH);
client.publish("estado","0");
}
}
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("terma", "hello world 1");
// ... and resubscribe
client.subscribe("terma");
} 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(14, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1884);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}

ESP8266 is not able to connect to mosquitto broker. "Attempting MQTT connection...failed, rc=-2 try again in 5 seconds"

I'm running a mosquitto broker and a node-red server in my PC , node-red is able to connect to mosquitto. The ESP8266 is able to connect to the WiFi but not to the broker a "Attempting MQTT connection...failed, rc=-2 try again in 5 seconds" message is displayed in the serial monitor. I'm also using MQTT explorer I don't know if it has something to do with it.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "Milagros";
const char* password = "18095381";
const char* mqtt_server = "192.168.1.133";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
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.mode(WIFI_STA);
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 an 1 was received as first character
if ((char)payload[0] == '1') {
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 active low on the ESP-01)
} else {
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("data", "hello world");
// ... and resubscribe
} 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);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("data", msg);
}
}```

Unable to establish connection to mosquitto broker from Arduino+ESP8266

I am using Arduino Uno and ESP8266 for WIFI connectivity. My Laptop on which mosquitto broker is running and Arduino(through ESP8266) is are both connected to wifi network. But I am unable to establish a connection to mqtt server.
I am using the follwing code.
#define FASTLED_INTERNAL
#include <SoftwareSerial.h>
#include <DHT.h>
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>
#include <PubSubClient.h>
#include <FastLED.h>
#define DHTPIN 2
#define DHTTYPE DHT11
#define ESP_RX 9
#define ESP_TX 8
#define WIFI_AP "Anurag"
#define WIFI_PASSWORD "qwerty12345"
#define NUM_LED 64
#define DATA_PIN 5
#define CLOCK_PIN 13
static const int RXPin = 4, TXPin = 3;
static const uint32_t baudRate = 9600;
static const int rainSensorMin = 0;
static const int rainSensorMax = 1024;
WiFiEspClient espClient;
PubSubClient mqttClient(espClient);
IPAddress broker(192,168,43,235);
SoftwareSerial ESP8266(ESP_RX, ESP_TX);
DHT dht(DHTPIN, DHTTYPE);
int status = WL_IDLE_STATUS;
char *ID = "uno";
char *TOPIC = "weatherStats";
int AT_cmd_time;
boolean AT_cmd_result = false;
CRGB leds[NUM_LED];
void setup() {
//pinMode(13, OUTPUT);
//FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LED);
Serial.begin(9600);
//ss.begin(baudRate);
initWiFi();
dht.begin();
mqttClient.setServer(broker,1883);
Serial.println("GPS, DHT11, and, Raindrop detector started.");
}
void loop() {
status = WiFi.status();
if ( status != WL_CONNECTED) {
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(WIFI_AP);
// Connect to WPA/WPA2 network
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
delay(500);
}
Serial.println("Connected to AP");
}
delay(3000);
float h = dht.readHumidity();
float t = dht.readTemperature();
int rainReading = analogRead(A0);
int range = map(rainReading, rainSensorMin, rainSensorMax, 0, 2);
if(!mqttClient.connected()){
reconnect_mqtt();
}
mqttClient.loop();
mqttClient.publish(TOPIC,"one step forward");
//Serial.println("Satellites: " + String(gps.satellites.value()));
if (!isnan(h) || !isnan(t))
Serial.print("Temparture: " + String(t) + "°C | " + " Humidity: " + String(h) + " | ");
else {
Serial.println("Failed to obtain temparature and humidity data");
}
switch (range) {
case 0:
Serial.print("Rain Warning : 1");
break;
case 1:
Serial.print("Rain Warning : 0");
break;
}
Serial.println(" | Lat: 22.716191217468406 Lon: 72.44229199663788");
}
void initWiFi(){
ESP8266.begin(9600);
WiFi.init(&ESP8266);
// 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(WIFI_AP);
//Connect to WPA/WPA2 network
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
}
}
void reconnect_mqtt(){
while(!mqttClient.connected()){
Serial.println("Attempting MQTT Connection");
if(mqttClient.connect(ID)){
Serial.println("MQTT connection established.");
Serial.print("Publishing to: ");
Serial.println(TOPIC);
}
else{
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
Runnig this code I keep getting output "try again in 5 seconds". Please help.

Code error in smart irrigation system, using dht11 sensor

I have wrtitten a code for automatically watering plant using esp8266, dht11, moisture sensor but my code has some error, i dont know how to fix it
#include <DHT.h>
#include <ESP8266WiFi.h>
String apiKey = "X5AQ3EGIKMBYW31H"; // Enter your Write API key here
const char* server = "api.thingspeak.com";
const char *ssid = "CircuitLoop"; // Enter your WiFi Name
const char *pass = "circuitdigest101"; // Enter your WiFi Password
#define DHTPIN D3 // GPIO Pin where the dht11 is connected
DHT dht(DHTPIN, DHT11);
WiFiClient client;
const int moisturePin = A0; // moisteure sensor pin
const int motorPin = D0;
unsigned long interval = 10000;
unsigned long previousMillis = 0;
unsigned long interval1 = 1000;
unsigned long previousMillis1 = 0;
float moisturePercentage; //moisture reading
float h; // humidity reading
float t; //temperature reading
void setup()
{
Serial.begin(115200);
delay(10);
pinMode(motorPin, OUTPUT);
digitalWrite(motorPin, LOW); // keep motor off initally
dht.begin();
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print("."); // print ... till not connected
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop()
{
unsigned long currentMillis = millis(); // grab current time
h = dht.readHumidity(); // read humiduty
t = dht.readTemperature(); // read temperature
if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
moisturePercentage = ( 100.00 - ( (analogRead(moisturePin) / 1023.00) * 100.00 ) );
if ((unsigned long)(currentMillis - previousMillis1) >= interval1) {
Serial.print("Soil Moisture is = ");
Serial.print(moisturePercentage);
Serial.println("%");
previousMillis1 = millis();
}
if (moisturePercentage < 50) {
digitalWrite(motorPin, HIGH); // tun on motor
}
if (moisturePercentage > 50 && moisturePercentage < 55) {
digitalWrite(motorPin, HIGH); //turn on motor pump
}
if (moisturePercentage > 56) {
digitalWrite(motorPin, LOW); // turn off mottor
}
if ((unsigned long)(currentMillis - previousMillis) >= interval) {
sendThingspeak(); //send data to thing speak
previousMillis = millis();
client.stop();
}
}
void sendThingspeak() {
if (client.connect(server, 80))
{
String postStr = apiKey; // add api key in the postStr string
postStr += "&field1=";
postStr += String(moisturePercentage); // add mositure readin
postStr += "&field2=";
postStr += String(t); // add tempr readin
postStr += "&field3=";
postStr += String(h); // add humidity readin
postStr += "\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length()); //send lenght of the string
client.print("\n\n");
client.print(postStr); // send complete string
Serial.print("Moisture Percentage: ");
Serial.print(moisturePercentage);
Serial.print("%. Temperature: ");
Serial.print(t);
Serial.print(" C, Humidity: ");
Serial.print(h);
Serial.println("%. Sent to Thingspeak.");
}
}
This is the error which i get
Arduino: 1.8.9 (Windows 8.1), Board: "Generic ESP8266 Module, 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), ck, 26 MHz, 40MHz, DOUT (compatible), 512K (no SPIFFS), 2, nonos-sdk 2.2.1 (legacy), v2 Lower Memory, Disabled, None, Only Sketch, 115200"
sketch_oct03a:7:16: error: 'D3' was not declared in this scope
#define DHTPIN D3 // GPIO Pin where the dht11 is connected
^
C:\Users\Shweta\Desktop\Libraries\sketch_oct03a\sketch_oct03a.ino:8:9: note: in expansion of macro 'DHTPIN'
DHT dht(DHTPIN, DHT11);
^
sketch_oct03a:12:22: error: 'D0' was not declared in this scope
const int motorPin = D0;
^
exit status 1
'D3' was not declared in this scope
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
Digital pins are not prefixed with D, unlike their analog counterparts.
#define DHTPIN 3
const int motorPin = 0;

Openhab doesn't change the status of switch from manual overide

I have just made an account because of this particular problem I'm having with OpenHAB. I was following a tutorial from this https://openhardwarecoza.wordpress.com/2015/03/29/openhab-mqtt-arduino-and-esp8266-part-3-hardware-arduino-with-ethernet-shield/ site but since the reply there didn't help me. I decided to go to this site.
I have successfully installed OpenHAB and use it. When I turn the switch off and on from both the HTTP page and android device, It works just fine. But when I tried to manual override using a push button on an Arduino. It didn't update the state of the switch in both of them. I'm using windows with OpenHAB version 1.71
The Openhab server notices that there is an update of the state from the push button, but the button in the HTTP page and android device didn't change at all.
I have tested the connection using MQTTlens and it works just fine.
Below is my code
items configuration
Group All
Switch mqttsw1 "Switch 1" (all) {mqtt=">[mymosquitto:/arduino/l1/com:command:off:0],>[mymosquitto:/arduino/l1/com:command:on:1],<[mymosquitto:/arduino/l1/state:state:default]"}
Switch mqttsw2 "Switch 2" (all) {mqtt=">[mymosquitto:/arduino/l2/com:command:off:0],>[mymosquitto:/arduino/l2/com:command:on:1],<[mymosquitto:/arduino/l2/state:state:default]"}
Number temp "Temperature [%.1f °C]" <temperature> {mqtt="<[mymosquitto:/arduino/temp/state:state:default]"}
Number hum "Humidity [%.1f &#37]" <temperature> {mqtt="<[mymosquitto:/arduino/hum/state:state:default]"}
Sitemap configuration
sitemap dolphin label="Main Menu"
{
Frame label="Switch" {
Switch item=mqttsw1 label="Switch 1"
Switch item=mqttsw2 label="Switch 2"
}
Frame label="Weather" {
Text item=temp
Text item=hum
}
The Arduino Code
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <DHT.h>
const int butt1 = 3;// the pin that the pushbutton is attached to
const int butt2 = 2;
const int ledPin1 = 5;
const int ledPin2 = 4;
int ledState1 = HIGH;
int buttonState1;
int lastButtonState1 = LOW;
int ledState2 = HIGH;
int buttonState2;
int lastButtonState2 = LOW;
long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 60000; // READING INTERVAL
int t = 0; // TEMPERATURE VAR
int h = 0; // HUMIDITY VAR
#define DHTPIN 24 // SENSOR PIN
#define DHTTYPE DHT11 // SENSOR TYPE - THE ADAFRUIT LIBRARY OFFERS SUPPORT FOR MORE MODELS
DHT dht(DHTPIN, DHTTYPE);
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xEF };
IPAddress ip(192, 168, 1, 103);
IPAddress server(192, 168, 1, 100);
void callback(char* topic, byte* payload, unsigned int length);
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println();
Serial.println("Callback");
Serial.print("Topic = ");
Serial.println(topic);
Serial.print("Payload = ");
for (int i=0;i<length;i++){
Serial.print((char)payload[i]);
}
Serial.println();
if (strcmp(topic,"/esp1/l1/com")==0) {
if (payload[0] == '0')
{
digitalWrite(ledPin1, LOW);
delay(100);
client.publish("/esp1/l1/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(ledPin1, HIGH);
delay(100);
client.publish("/esp1/l1/state","1");
}
}
if (strcmp(topic,"/esp1/l2/com")==0) {
if (payload[0] == '0')
{
digitalWrite(ledPin2, LOW);
delay(100);
client.publish("/esp1/l2/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(ledPin2, HIGH);
delay(100);
client.publish("/esp1/l2/state","1");
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient")) {
Serial.println("connected");
client.subscribe("/esp1/#");
client.publish("conn","Connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void push1() {
int reading1 = digitalRead(butt1);
buttonState1 = reading1;
if (buttonState1 == HIGH) {
ledState1 = !ledState1;
if (ledState1 < 1)
{
digitalWrite(ledPin1, LOW);
delay(100);
client.publish("/esp1/l1/com","0");
client.publish("/esp1/l1/state","0");
}
else
{
digitalWrite(ledPin1, HIGH);
delay(100);
client.publish("/esp1/l1/com","1");
client.publish("/esp1/l1/state","1");
}
}
}
void push2() {
int reading2 = digitalRead(butt2);
buttonState2 = reading2;
if (buttonState2 == HIGH) {
ledState2 = !ledState2;
if (ledState2 < 1)
{
digitalWrite(ledPin2, LOW);
delay(100);
client.publish("/esp1/l2/com","0");
client.publish("/esp1/l2/state","0");
}
else
{
digitalWrite(ledPin2, HIGH);
delay(100);
client.publish("/esp1/l2/com","1");
client.publish("/esp1/l2/state","1");
}
}
}
void temp() {
h = (int)dht.readHumidity();
t = (int)dht.readTemperature();
char temp[2];
char hum[3];
sprintf(hum, "%d", h);
sprintf(temp, "%d", t);
client.publish("/esp1/temp/state", temp);
client.publish("/esp1/hum/state", hum);
}
void setup() {
// put your setup code here, to run once:
pinMode(butt1, INPUT);
pinMode(butt2, INPUT);
// initialize the LED as an output:
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
Serial.begin(9600);
Ethernet.begin(mac, ip);
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
pinMode(26, OUTPUT); // sets the digital pin as output
pinMode(22, OUTPUT); // sets the digital pin as output
digitalWrite(26, HIGH); // sets +5v for the sensor
digitalWrite(22, LOW); // sets gnd for the sensor
h = (int)dht.readHumidity();
t = (int) dht.readTemperature();
if (client.connect("arduinoClient")) {
client.publish("conn","Connected");
client.subscribe("/esp1/#");
}
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()) {
reconnect();
}
currentMillis = millis();
if (currentMillis - previousMillis > interval) { // READ ONLY ONCE PER INTERVAL
previousMillis = currentMillis;
temp();
}
int reading1 = digitalRead(butt1);
int reading2 = digitalRead(butt2);
if (reading1 != buttonState1) {
push1();
}
if (reading2 != buttonState2){
push2();
}
client.loop();
}
If there are anybody who can help me I would be very grateful. Thank you for your attention !
Best Regards,
Aldi
If I remember correctly you should post back a status of ON or OFF instead of 1 or 0.
Could you change your arduino code to publish back ON and OFF and test that?
e.g.
client.publish("/esp1/l1/state","ON");

Resources