I'm writing an IoT thing and the issue I'm having is that the technique I'm using to timeout and then reset that timeout is not working. It's a technique I've used many times in the past, and I'm posting here just to rule out that I've got something wrong in this code. The behavior I'm getting is unexpected.
What I am doing is using
millis()
which returns the number of milliseconds elapsed since the machine was booted. I'm storing that in a timestamp, and then in my
loop()
function which gets called for each iteration of a tight loop the cpu spins for me basically I'm seeing if the number of the difference between now and when the timestamp was taken is more than 1000 milliseconds (1 second)
I have a
callback()
method that is called any time the end of a wire is physically touched. This works, as in the routine fires, but it's behaving as if I didn't reset the timestamp inside the function.
Can anyone tell me where I went wrong?
(See the "what have you tried?" section for more)
What I have tried:
uint32_t _timestamp;
void callback() {
_timestamp = 0;
Serial.println("Callback");
}
void setup() {
Serial.begin(115200);
touchAttachInterrupt(T3, callback, 40);
_timestamp = millis();
}
void loop() {
if (!_timestamp)
_timestamp = millis();
if (millis() - _timestamp > 1000) {
_timestamp = millis();
Serial.println("Time elapsed");
}
}
Above I've bolded a critical line that appears not to be running. I've also tried making
_timestamp
volatile
to no avail.
The serial output (with timestamps) are as follows
This yields
15:29:56.544 -> Time elapsed
15:29:57.537 -> Time elapsed
...
(i'm pressing the touch sensor wire now)
15:29:59.755 -> Callback
15:29:59.755 -> Time elapsed
15:29:59.788 -> Callback
15:29:59.788 -> Time elapsed
15:29:59.821 -> Callback
....
(i've released the touch sensor wire)
15:30:00.186 -> Time elapsed
15:30:01.179 -> Time elapsed
...
I've bolded some bits to highlight how fast it's happening.
but anyway I expect something like this
Time elapsed
Time elapsed
Time elapsed
(I've held the wire)
Callback
Callback
Callback
Callback
(I've released the wire)
Time elapsed
Time elapsed