Controlling speed of loop

I need to run functions randomly every 5 seconds or so …

I also have a loop within each function.
That ‘q’ loop needs to be slowed down with delay.

It’s this internal loop that I’m having trouble figuring out …
How do I pause or wait for example .2 seconds?
I can’t find a good example of a pause or wait function, and can there be a function inside a function?

This is a simplified layout of what I’m doing …

`
function program1()
{
for (local q=0; q<4; ++q)
{
local valuex=2;
writeSerial(valuex);
// here is where the q loop is delayed (in seconds or fractional seconds) after writing to serial.
//delay();
server.log(valuex);
}
}

function program2()
{
for (local q=0; q<4; ++q)
{
local valuex=4;
writeSerial(valuex);
//delay();
server.log(valuex);
}
}

function program3()
{
for (local q=0; q<4; ++q)
{
local valuex=16;
writeSerial(valuex);
//delay();
server.log(valuex);
}
}

function clockTick()
{
// randomly pick a program every 5 seconds …
// this part would determine program1,2,3,etc.
imp.wakeup(5.0, program1);
server.log(“clocktick”);
}

clockTick();

`

Thanks for any tips on this.

.

I think this will work

imp.sleep(float);

If you’re fine with the imp not doing anything else (network traffic or code) in the delay time, then imp.sleep() is fine for these short, sub-second delays.

Above that and you’d be better off using eg generators to suspend/resume the functions whilst allowing other code to run.

Sorry for my ignorance, but what is an “eg generator”. I couldn’t find anything on Google.

EDIT: Is this what you are referring to:
http://electricimp.com/docs/resources/generators/

Generators are a little complicated - but luckily @smittytone has put together this great guide about them:

http://electricimp.com/docs/resources/generators/

imp.sleep() is working OK for me.

If I happen to sleep too long, in a loop, at what point will there be a loss of communication or error? Is there a specific amount of time required?

I guess I should just test things out and see what happens … that’s the best way to learn.

The guides, tutorials, and documentation that is starting to show up is fantastic. I’m amazed at how much the imp documentation has grown over the past 18 months.

Kudos to @smittytone !

Yep, @smittytone is truly prolific (and if you’re near London, you should go and meet him tomorrow night!)

Sleeping - or running busy - shouldn’t actually cause a disconnect until it’s into the tens of seconds without yielding.