Timing and Events

Managing timings, threads, and events.

  1. Basic threads
    1. Blink
  2. Event Queues
    1. Periodic and delayed tasks.
    2. Worker Thread for the event Queue
  3. Event Queues for Interrupts
  4. Modular programming

Basic threads

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.

  1. Add other threads that flashe other LEDs
  2. How easy is it to determine timings?

Event Queues

Periodic and delayed tasks.

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);
  1. Nothing happens until the queue is told to dispatch events queue.dispatch_forever()
  2. The function called for the event exits like any other function. It does not need a while(1) loop

There is also a call_after() function to delay the action for a given time.

  1. Add other periodic functions (led flashes) to the program.
  2. Does the call to dispatch_forever return?

Worker Thread for the event Queue

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.)

Event Queues for Interrupts

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.

Modular programming

Threads and events allow a more modular approach to programming.

  1. Create a thread that simply updates the display (LCD) periodically.
  2. Create a couple of functions that increment and decrement a counter (shown on the display)
  3. Create a Thread for an Event queue.
    1. Generate an event from Sw2 to call the increment function
    2. Generate an event from Sw3 to call the decrement function
  4. Poll one of the sensors (Accelerometer, Potentiometer, Temperature) regularly (using call_every) and update a variable shown on the display.

© 2017   Dr Alun Moon
alun.moon@northumbria.ac.uk