-
Notifications
You must be signed in to change notification settings - Fork 5
Delaying
Teensyduino provides the standard delay functions delay(uint32_t ms)
, '
delayMicrosecons(uint32_t mus)
and delayNanoseconds(uint32_t ns)
.
Those functions are blocking execution of the sketch for the specified period. The usual heartbeat code
void loop(){
digitalToggleFast(LED_BUILTIN);
delay(250); // 250ms
}
shows how to use the delay function. After toggling the led it pauses execution of the loop function for 250ms before loop returns.
Of course you get the same effect by using
void loop()
{
digitalToggleFast(LED_BUILTIN);
delayMicroseconds(250'000); // 250'000µs = 250ms
}
DelayNanoseconds comes in handy if you need to wait for very short times. This is often the case if you access external hardware.
//...
digitalWriteFast(LD, LOW); // load pin requires a low pulse (>100 ns) to
delayNanoseconds(100); // store the values at the data pins A-E
digitalWriteFast(LD, HIGH); // in the shift register
int value = digitalReadFast(QH); // read the first data bit
// do something with the bit...
for (unsigned i = 1; i < 8; i++) // shift in the the rest of the data
{
digitalWriteFast(CLK, HIGH); // set the clock pin
delayNanoseconds(50); // the 74165 needs some time for the shifting
int value = digitalReadFast(QH); // read the next data bit
digitalWriteFast(CLK, LOW); // reset the clock pin and make sure
delay50ns(); // that it stays low for at least 50ns
// do something with the bit...
}
//...
Teensyduino implements a yield()
function which handles stuff like
SerialEvents and much more in the background. In principle yield
is called
automatically after each iteration of loop. If you place a say
delay(10'000)
in loop, yield wouldn't be called for 10s which might mess up
those backup tasks. To avoid this delay(unsigned ms)
also calls yield while it
spins.
In contrary, delayMicroseconds
and delayNanoseconds
do not call yield. So,
try to avoid using delayMicroseconds for long delays if you rely on background
tasks being run from yield().
//...
// delayMicroseconds(500'000); // not good, doesn't call yield()
delay(500); // better, calls yield() while it spins
//...
Also, if your own code takes significant time it might be a good idea to manually call yield() between iterations to keep the background tasks alive:
void someFunction()
{
for (int i = 0; i < 10000; i++)
{
// do something important
Teensy is a PJRC trademark. Notes here are for reference and will typically refer to the ARM variants unless noted.