Hello,
I'm setting up Arduino based IoT device which is waking up every 1 minute (externally triggered by RTC), sending/receiving MQTT messages (managed by Node Red), acting if needed, and going to sleep until next cycle to preserve solar charged battery.
It works perfectly well both for publishing and subscribing as well as acting upon (turning on built in led) as long as I disable sleep cycle (Clock.checkIfAlarm(1);). Once I enable that device starts to cycle through and only publish MQTT messages to broker. Subscribing / acting based on that (via callback) seems to be never executed.
Your support is highly appreciated.
Narrowed down bare minimum code:
#include <Wire.h>
#include <DS3231.h>
#include <SPI.h>
#include <WiFiNINA.h>
#include <PubSubClient.h>
#define MSG_BUFFER_SIZE (50)
WiFiClient wifiClient;
PubSubClient client(wifiClient);
char ssid[] = "****";
char pass[] = "****";
char mqtt_server[] = "****";
int status = WL_IDLE_STATUS;
unsigned long lastMsg = 0;
char msg[MSG_BUFFER_SIZE];
int value = 0;
DS3231 Clock;
void setup() {
delay(1000);
while ( status != WL_CONNECTED) {
status = WiFi.begin(ssid, pass);
}
printWifiStatus();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
pinMode(LED_BUILTIN, OUTPUT);
Wire.begin();
Clock.turnOffAlarm(2);
Clock.enableOscillator(false, false, 0);
Clock.enable32kHz(false);
Clock.setClockMode(false);
Clock.setA1Time(1, 2, 3, 4, 0b1110, false, false, false);
Clock.turnOnAlarm(1);
while (Wire.available()) {
Wire.read();
}
}
void printWifiStatus() {
IPAddress ip = WiFi.localIP();
long rssi = WiFi.RSSI();
}
void reconnect() {
while (!client.connected()) {
if (client.connect("ArduinoClient-3")) {
client.publish("waterpump/status", "waterpump connected");
client.subscribe("waterpump/servo");
}
else {
delay(5000);
}
}
}
void callback(char* topic, byte* payload, unsigned int length) {
if ((char)payload[0] == '1') {
digitalWrite(LED_BUILTIN, HIGH);
}
else {
digitalWrite(LED_BUILTIN, LOW);
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
Clock.checkIfAlarm(1);
while (1);
}