An embedded system is usually an event driven system, in which the system does a course of action based on occurrence of events. The system would check for events in a loop and would perform actions corresponding to it.
Thus many applications have an infinite loop called the event loop, in which events are checked and processed. Examples of events could be key pressed, timer expired, data received on serial port, etc. An algorithmic representation of the event loop is shown below.
while(1) {
if (key_pressed())
handle_key_press();
if (timer_expired())
handle_timer_expired();
if (serial_data())
handle_serial_data();
if (spi_slave_data())
handle_spi_data();
...
...
}
Since this is a very common design pattern, the ZDev API has an Event module that makes implementation of the pattern simple and flexible. The user registers handler function for various events and the Event module invokes the handler function when the event occurs.
The Event module functions are declared in event.h
. The following
example shows handling of serial data receive events and timer events,
simultaneously.
#include <board.h>
#include <event.h>
#include <timer.h>
#include <serial.h>
void rx_handler()
{
char ch = serial_getc();
serial_putc(ch);
}
void led_handler(timer_t *timer)
{
static bool state;
gpio_set_pin(LED1_GPIO, state);
state != state;
timer_setup(timer, 1000);
}
timer_t blink_timer;
int main()
{
board_init();
timer_init();
gpio_init();
gpio_enable_pin(LED1_GPIO);
gpio_direction_output(LED1_GPIO, OFF);
serial_init();
serial_puts("Echo World: ");
/* Set up serial receive handler. */
serial_rx_setcb(rx_handler);
/* Setup timer event source and handler. */
timer_setup(&blink_timer, 1000);
timer_setcb(&blink_timer, led_handler);
/*
* Enter infinite mainloop, which checks for events and
* dispatches the handler.
*/
event_poll();
return 0;
}