Running Code at Intervals Using Adafruit IO
We introduced time utilities to Adafruit IO about a month ago, but we
haven’t provided any examples of how to use the feature. To correct this oversight, we added an example to v0.14.2
of the Adafruit MQTT Arduino Library. This example was a response to a feature request from @phlemoine in the io-issues GitHub repo:
I am looking for a way to trigger at a specific time in the day… how can I set up the time the trigger starts ? Same for a 12 hours or even 4 hours …
Here is the relevant code that allows code to be run at 4 hour intervals (midnight, 4am, 8am, etc):
Adafruit_MQTT_Subscribe timefeed = Adafruit_MQTT_Subscribe(&mqtt, "time/seconds");
// set timezone offset from UTC
int timeZone = -4; // UTC - 4 eastern daylight time (nyc)
int interval = 4; // trigger every X hours
int hour = 0; // current hour
void timecallback(uint32_t current) {
// stash previous hour
int previous = hour;
// adjust to local time zone
current += (timeZone * 60 * 60);
// calculate current hour
hour = (current / 60 / 60) % 24;
// only trigger on interval
if((hour != previous) && (hour % interval) == 0) {
Serial.println("Run your code here");
}
}
The full example
can be found in the Adafruit_MQTT Arduino Library on GitHub. You will need to install or update the Adafruit MQTT Library to version 0.14.2
in the Arduino Library Manager, and open the
adafruitio_time_esp8266
example to get started.
Are these examples helpful? Please visit our IO forum and share your thoughts.