I’m using SimpleTimer in my Blynk code on a Wemos D1 Mini, all works great and learning how to use Simpletimer. Question If I need a short time delay to read sensor inside my void myTimerEvent() can I use Delay()? What would be best function to use? Thanks!
Because delay()
is blocking (i.e. absolutely nothing else gets done on the MCU until the delay is finished sitting around on it’s backside), It is to be avoided wherever possible for wireless connected projects… else it tends to cause disconnections.
Timers are the answer… yes, it is a bit of extra coding and logic, but it is non-blocking and much more elegant in operation.
BAD
BLYNK_WRITE(Vx) // Virtual button on Vx to activate action
{
int BTN = param.asInt();
if (BTN == 1) {
digitalWrite(pin, HIGH); // Set pin high
delay(5000); // NOOOOOooooooooo
digitalWrite(pin, LOW); // Set pin Low
}
}
GOOD
BLYNK_WRITE(Vx) // Virtual button on Vx to activate action
{
int BTN = param.asInt();
if (BTN == 1) {
ActionON; // Run ActionON function
}
}
void ActionON()
{
digitalWrite(pin, HIGH); // Set pin high
timer.setTimeout(5000L, ActionOFF); // Run ActionOFF function in 5 seconds
}
void ActionOFF()
{
digitalWrite(pin, LOW); // Set pin Low
}
And this is just a dirt simple code solution that is within my coding experience level… there are probably even more elegant ways of coding a non-blocking delay.
EDITED - switched code to setTimeout from setTimer
One little thing @Gunner, use timer.setTimeout() otherwise it will keep running and consume. The ActionOn() can also just be put in Blynk write. Each declaration of a void costs memory
Maybe that’s where mine is going… to many voids in my life
I am still learning all the timer functions myself, and keep forgetting how to use some of them.
And I should have thought about the ActionON/BLYNK_WRITE() merger… doh
Thanks!
Ah, Google my friend
I think this will work?.. too hot out to think, let alone sit at the computer compiling code…
GOODer
BLYNK_WRITE(Vx) // Virtual button on Vx to activate action
{
int BTN = param.asInt();
if (BTN == 1) {
digitalWrite(pin, HIGH); // Set pin high
timer.setTimeout(5000L, ActionOFF); // Run ActionOFF function in 5 seconds
}
}
void ActionOFF()
{
digitalWrite(pin, LOW); // Set pin Low
}
Nothing makes me happier
Great coding guys! I’ve learned something new too now
Sadly this does not work, it would have been sweeter
BLYNK_WRITE(Vx)
{
param.asInt() ? timer.setTimeout(5000L, [](){ digitalWrite(pin, LOW) } ) : ;
}
The “eval ? true : false;” shorthand only takes void functions it seems at least from my short testing. And needs both the true and false statements.
I guess this is cool enough
BLYNK_WRITE(Vx)
{
if ( param.asInt()) { digitalWrite(pin, HIGH); timer.setTimeout(5000L, [](){ digitalWrite(pin, LOW) } ) } ;
}
Careful, the “digitalWrite(pin, HIGH)” is missing now
My bad, not easy from the phone fixed
Just found this post and tried searching to find what this “[ ] ( )” meant…
Does anyone have a link that could help?
Thanks.