I am hoping someone will be willing to point my error. This is only my second program and I am missing something.
Here is the setup:
I am using an Arduino uno, an Ethernet shield, 4 relays and 4 magnetic switches. Mqtt on an raspberry pi.
The plan:
Use Mqtt to send command to cycle the relay, I have this working.
the switch will tell Mqtt if the door is open or closed, partially working.
This is the portion of code in question
state_1 = digitalRead (2);
if (state_1 == HIGH){
client.publish("outTopic","Garage door 1 open");
}
else{
client.publish("outTopic", "Garage door 1 Closed");
}
When I boot up the arduino, I get an open or closed based on the pin state. The problem I run into is that I don’t know where to place this portion of code. If I place it in void loop, it runs and runs, I know it should, but it seems to overload my broker. Also I only need it to report the when it changes not constantly.
I created what I think is called a function, void open() and placed the code there, but I did not get any result. What I would like to know is where to place this so it reports open or close when the pin high/low changes.
Here is the full code I am working with:
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Update these with values for your network
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
IPAddress ip(192, 168, 1, 18); //arduino IP, static
IPAddress server(192, 168, 1 ,7); //MQTT IP
// Callback function header
void callback(char* topic, byte* payload, unsigned int length);
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
// Callback function
void callback(char* topic, byte* payload, unsigned int length) {
//Cycle relay and publish to the MQTT server a confirmation message
if(payload[0] == '1'){
digitalWrite(6, LOW);
client.publish("outTopic", "Garage Door 1 Button Pressed");
delay (1000);
digitalWrite(6, HIGH);
}
if(payload[0] == '2'){
digitalWrite(7, LOW);
client.publish("outTopic", "Garage Door 2 Button Pressed");
delay (1000);
digitalWrite(7, HIGH);
}
if(payload[0] == '3'){
digitalWrite(8, LOW);
client.publish("outTopic", "Garage Door 3 Button Pressed");
delay (1000);
digitalWrite(8, HIGH);
}
if(payload[0] == '4'){
digitalWrite(9, LOW);
client.publish("outTopic", "Garage Door 4 Button Pressed");
delay (1000);
digitalWrite(9, HIGH);
}
}
int state_1;
void setup()
{
pinMode(6, OUTPUT);
digitalWrite(6, HIGH);
pinMode(7, OUTPUT);
digitalWrite(7, HIGH);
pinMode(8, OUTPUT);
digitalWrite(8, HIGH);
pinMode(9, OUTPUT);
digitalWrite(9, HIGH);
pinMode(2, INPUT_PULLUP);
Ethernet.begin(mac, ip);
if (client.connect("arduinoClient")) {
client.publish("outTopic","Garage door opener conected");
client.subscribe("inTopic");
}
state_1 = digitalRead (2);
if (state_1 == HIGH){
client.publish("outTopic","Garage door 1 open");
}
else{
client.publish("outTopic", "Garage door 1 Closed");
}
}
void loop()
{
client.loop();
}
Thanks in advance