I have done a setup where if I press 4-pin switch,the LED connected to digital pin 7 with Arduino,will glow.
This is working fine when I connect it without MQTT publish.
Its working fine for the below code,
void loop(){ // read the state of the pushbutton value: buttonState = digitalRead(buttonPin); Serial.println(buttonState); // check if the pushbutton is pressed. // if it is, the buttonState is HIGH: if (buttonState == HIGH) { // turn LED on: digitalWrite(ledPin, LOW); } else { // turn LED off: digitalWrite(ledPin, HIGH); }
But When I use MQTT publish,its sending more than 300 publish messages to MQTT clients!!!! .I want it as,when I press the switch,the led has to glow and an MQTT message has to be published.But here it is like,eventhough I press once or twice,or evenif I dont press also,the message starts getting published the moment I upload the sketch into Arduino!
Code which is not working,
#include <SPI.h> #include <PubSubClient.h> #include <Ethernet.h> #include <util.h> #include <ctype.h> #define CLIENTID "ArduinoSensor" #define TOPICNAME "switch/signal" #define POLLINTERVAL 120000 #define PORT 80 //Connect to MQTT server byte server1 [] = {X,X,X,X}; byte mac[] = {X,X,X,X}; IPAddress arduinoIP(X,X,X,X); IPAddress dnsIP(X,X,X,X); IPAddress gatewayIP(X,X,X,X); IPAddress subnetIP(X,X,X,X); EthernetServer server(PORT); EthernetClient ethClient; PubSubClient arduinoClient(server1, 8081, callback, ethClient); const int buttonPin = 2; // the number of the pushbutton pin const int ledPin = 7; // the number of the LED pin // variables will change: int buttonState=0; void callback(char* topic, byte* payload, unsigned int length) { // handle message arrived } void setup() { Serial.begin(9600); Ethernet.begin(mac, arduinoIP, dnsIP, gatewayIP, subnetIP); pinMode(ledPin, OUTPUT); pinMode(buttonPin, INPUT); digitalWrite(ledPin, LOW); //Connect to the MQTT server beginConnection() ; } //Initialise MQTT connection void beginConnection() { Serial.begin(9600); //Ethernet.begin(mac) ; int connRC = arduinoClient.connect(CLIENTID) ; if (!connRC) { Serial.println(connRC) ; Serial.println("Could not connect to MQTT Server"); Serial.println("Please reset the arduino to try again"); delay(100); exit(-1); } else { Serial.println("Connected to MQTT Server..."); }} void loop(){ // read the state of the pushbutton value: buttonState = digitalRead(buttonPin); Serial.println(buttonState); if (buttonState == HIGH) { digitalWrite(ledPin, LOW); } else { digitalWrite(ledPin, HIGH); arduinoClient.publish(TOPICNAME, "Button A is pressed") ; } }
In Serial Monitor,I can see the output as below,
1
1
1
0
0
0
0
1
1
1
0
0
0
0
0
0
When switch is not pressed,the output is with 1s and 0s.But when there is switch pressed,0s are coming continuously until switch is pressed...
Not sure how to make this work...I need this little urgently..Please help me on this...