Struggling to understand why the IOT "void on change" isn't working the way I would anticipate.
I've created a simple project to demonstrate and isolate my issue:
- My IOT Thing is a single int variable (Selector).
- This Thing is linked to Value Selector widget on my dashboard, with three selection options: 0, 1, and 2.
- My sketch uses a Switch/Case based off the Selector from the widget. I can easily switch the cases in my code from my dashboard--so that part is fine.
My issue with with a StateChangeMillis that I've created. This purpose is so I can trigger various events based off how long each Case has been active.
My simple code works fine when I change the Selector from the dashboard. However, when I attempt to change the Selector from inside my sketch, the StateChangeMillis is not updating. I would expect it would update each time the Selector changed.
The Selector state is updating as expected per the void OnSelectorChange() function, but the StateChangeMillis is not.
/*
Sketch generated by the Arduino IoT Cloud Thing "Untitled"
https://create.arduino.cc/cloud/things/9f5311cf-5ba7-475b-8b79-26aa36c8e381
Arduino IoT Cloud Variables description
The following variables are automatically generated and updated when changes are made to the Thing
int selector;
Variables which are marked as READ/WRITE in the Cloud Thing will also have functions
which are called when their values are changed from the Dashboard.
These functions are generated with the Thing and added at the end of this sketch.
*/
#include "thingProperties.h"
unsigned long StateChangeMillis;
void setup() {
// Initialize serial and wait for port to open:
Serial.begin(9600);
// This delay gives the chance to wait for a Serial Monitor without blocking if none is found
delay(1500);
initProperties();
ArduinoCloud.begin(ArduinoIoTPreferredConnection);
setDebugMessageLevel(2);
ArduinoCloud.printDebugInfo();
}
void loop() {
ArduinoCloud.update();
Serial.print ("StateChangeMillis=");
Serial.println(StateChangeMillis);
switch(selector){
case 0:
//do activity for 3 seconds when entering Case 0
if(millis()-StateChangeMillis >=3000)
//after 3 seconds, stop activity and stay in Case 0
{Serial.println("Selector 0, Post-Delay");}
else
{Serial.println("Selector 0, Pre-Delay");}
break;
case 1:
//do activity for 5 seconds when entering Case 1
Serial.println("Selector 1");
if(millis()-StateChangeMillis >5000)
//after 5 seconds, stop activity and switch back to Case 0
{selector=0;}
break;
case 2:
Serial.println("Selector 2");
break;
}
}
void onSelectorChange() {StateChangeMillis = millis();}