I'm trying to use mqtt and I presume there are restrictions on where objects can be used?
After the pin13Int is called, the led lights ok.
The lightOut void is called and the serial message is displayed but the led does not go off and no mqtt message is published.
I then get another call straight away to pin13Int even though there's no more activity on pin 13..
Any ideas anyone? Thanks BTW - I don't know c, not used arduino dev env before and just trying to get basic things to work hence dodgy code ...
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <Ticker.h>
const char* ssid = "wifi";
const char* password = "passy";
char* topic = "kitchen/mainlight";
char* server = "192.168.2.103";
String clientName = "Arduino-esp";
Ticker lightOut;
WiFiClient wifiClient;
PubSubClient client(server, 1883, callback, wifiClient);
void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
}
void setup() {
Serial.begin(115200);
delay(10);
Serial.println();
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.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("Connecting to ");
Serial.print(server);
Serial.print(" as ");
Serial.println(clientName);
pinMode(13, INPUT);
pinMode(12, OUTPUT);
attachInterrupt(13, pin13Int, RISING);
if (client.connect((char*) clientName.c_str())) {
Serial.println("Connected to MQTT broker");
Serial.print("Topic is: ");
Serial.println(topic);
}
else {
Serial.println("MQTT connect failed");
Serial.println("Will reset and try again...");
abort();
}
}
void turnLightOff() {
Serial.println("Light Off");
digitalWrite(12,0);
String payload;
payload="Light Off";
client.publish(topic, (char*) payload.c_str());
lightOut.detach();
}
void pin13Int() {
Serial.print("Movement!");
digitalWrite(12,1);
String payload;
payload="Movement!";
client.publish(topic, (char*) payload.c_str());
lightOut.attach(5, turnLightOff);
}
void loop() {
}
serial monitor:
WiFi connected
IP address:
192.168.2.26
Connecting to 192.168.2.103 as Arduino-esp
Connected to MQTT broker
Topic is: kitchen/mainlight
Movement!Light Off
Movement!Movement!Light Off
Movement!Movement!Light Off
Movement!