Managing timings, threads, and events.
The Mbed libraries provide a simple thread that can be used to manage timings. s6.1
worker.start( flash_red );
The thread is started by passing it the function to call.
Note: the thread function has it’s own while(1)
block, so that it keeps running.
What happens if we want a task to run at a specific period? Or to act after a given delay? The Mbed libraries provide an EventQueue
which has mechanisms for triggering events.
s6.2
The EventQueue
has a call_every
function that allows a function to be called at a given periodic rate.
queue.call_every(300, blink);
queue.dispatch_forever()
while(1)
loopThere is also a call_after()
function to delay the action for a given time.
dispatch_forever
return?What happens after dispatch_forever
is called? it may be useful to create a thread specifically to handle the EventQueue
Thread worker;
worker.start(callback(&queue, &EventQueue::dispatch_forever ));
Note: the use of a function to create the callback
. This is a means of robustly preserving state in real time systems (see Callbacks section of the Platform Overview first for deeper insight into their use.)
Remember that for Interrupt Service Routines, we can’t use lengthy or costly operations? We can use an event queue. The ISR generates an event, which is then handled separately outside of the ISR.
Example s6.3 shows how we can register an event trigger with an Interrupt:
sw.fall(queue.event(blink));
Causes the event that calls blink
to be generated on the falling edge interrupt of switch 2.
Note: we still have to have a thread running for the event queue.
Threads and events allow a more modular approach to programming.
call_every
) and update a variable shown on the display.