Looping pattern

Hi, I’m trying to create a pattern of switching pins on and off (in an infinite loop) that I would like to be able to toggle in and out of. I’ve managed to create a flag that is useful in getting into the loop, but once the imp has entered it it doesn’t seem to recognize agent messages attempting to change the flag. Any ideas?

Infinite loops are bad in imp code. The imp only has a single thread of execution, and if you code an infinite loop, your code will never yield (which means it will always be running, and nothing else on the imp will run).

The imp has numerous background tasks that it likes to do, one of which is maintaining/managing your network connection. Luckily, this can easily be done with an imp.wakeup() “loop.” Here’s what the code looks like:

`// you can call your function whatever you want
function loop() {
// schedule loop function to run again in 1 second (this can essentially be as small or large as you want)
imp.wakeup(1.0, loop);

// do stuff:
// your code goes here
}

// call loop once to get it started:
loop();`

So, supposing I have a series of LEDs on a breadboard, is there no way I can adapt this wakeup method to create a visual pattern than I can drop in or out of with a particular request query?

Thanks for your help!

That is to say, within that particular thread of execution, to perhaps add a handler of some kind … ?

You can set up multiple loops, each triggered by calling imp.wakeup() with a different callback function. Usefully, imp.wakeup() returns a reference to the timer it has set up:

timer = imp.wakeup(1.0, loop);

and this can be used to cancel the timer, perhaps in response to an incoming message from the agent:

imp.cancelwakeup(timer);

It’s not too hard to set up the loops you need for the pattern, record their timer references in an array, say, and cancel them in a handler (let’s say cancel_loops()) registered this way:

agent.on("cancel-all-loops", cancel_loops);

BTW, I have a Dev Center article in preparation that explores imp.wakeup() and its uses in a lot more depth. Watch out for it.

Thanks! I’ll give it a try and post back here.