knolleary / pubsubclient

A client library for the Arduino Ethernet Shield that provides support for MQTT.
http://pubsubclient.knolleary.net/
MIT License
3.83k stars 1.47k forks source link

message should be publish single time when condition satisfied #587

Open akashshankar1 opened 5 years ago

akashshankar1 commented 5 years ago

Hello i am working with current sensor which is giving RMSamp according to below code. Problem is when i tried to publish payload at my topic. It continuously publishing topic because sensor sense current continuously. I want to publish payload to topic only single time when condition satisfied, it should not publish continuously..I hope you understand my point my code is below.

include

include "Adafruit_MQTT.h"

include "Adafruit_MQTT_Client.h"

define WLAN_SSID "**"

define WLAN_PASS "**"

define SERVER "..."

define SERVERPORT ****

define USERNAME "****"

define KEY "***"

const int sensorIn = A0; int mVperAmp = 66; WiFiClient client;

float Voltage = 0; float VRMS = 0; float AmpsRMS = 0; Adafruit_MQTT_Client mqtt(&client, SERVER, SERVERPORT, USERNAME, KEY); Adafruit_MQTT_Publish S4 = Adafruit_MQTT_Publish(&mqtt, "topicname"); Adafruit_MQTT_Subscribe R1 = Adafruit_MQTT_Subscribe(&mqtt, "topicname");

void setup(){ Serial.begin(9600);

WiFi.begin(WLAN_SSID, WLAN_PASS); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println();

Serial.println("WiFi connected");

}

void loop(){ MQTT_connect(); Voltage = getVPP(); VRMS = (Voltage/2.0) 0.707; AmpsRMS = (VRMS 1000)/mVperAmp; Serial.print(AmpsRMS); Serial.println("= Amps RMS"); if(AmpsRMS > 0.22){ S4.publish(2); } if(AmpsRMS < 0.22){ S4.publish(3); }

}

float getVPP() { float result;

float readValue;
int maxValue = 0;
int minValue = 1024;

uint32_t start_time = millis(); while((millis()-start_time) < 1000) { readValue = analogRead(sensorIn);

   if (readValue > maxValue) 
   {

       maxValue = readValue;
   }
   if (readValue < minValue) 
   {

       minValue = readValue;
   }

}

result = ((maxValue - minValue) * 5.0)/1024.0;

return result; }

void MQTT_connect() { int8_t ret;

if (mqtt.connected()) { return; }

Serial.print("Connecting to MQTT... ");

uint8_t retries = 3; while ((ret = mqtt.connect()) != 0) { Serial.println(mqtt.connectErrorString(ret)); Serial.println("Retrying MQTT connection in 5 seconds..."); mqtt.disconnect(); delay(10000); retries--; if (retries == 0) { while (1); } } Serial.println("MQTT Connected!"); }

knolleary commented 5 years ago

I assume you don't want issue #586 to still be open? Please close it.

You are using the Adafruit MQTT client. That is not the client library this repository maintains.