EVENT BASED LIBRARY for Arduino

The old way

Using a delay is not going to work (I need to be doing something else), and interrupts are limited. To help separate code, and not use any delays, I often add functions like this...

void setup() {
  pinMode(statusPin, OUTPUT);
}

void loop(){
  processStat();
}

unsigned long statusNext = 0;
boolean statusState = LOW;
#define statusUpdate 500;
void processStatus() {
  if (statusNext == 0 || (millis() > statusNext)) {
    statusState = !statusState;
    digitalWrite(statusPin, statusState);
    statusNext = millis() + statusUpdate;
  }
}

The new way

There are lots of event libraries to help, but most of them require you to create a new instance of a class for each thing, and check (in the loop) each of those. I was working on a library to make that easier... but here is another.

http://code.google.com/p/ebl-arduino/

Although there are some issues, this seems to do what I wanted, and adds quite a few features I would not have thought of.

It is worth noting there is an LED specific version of the EBL code for blinking, flashing etc, but here is the timed based version.

#include <TimedEvent.h>
void setup() {
  TimedEvent.addTimer(500, processStatus);
}

void loop(){
  TimedEvent.loop();
}

boolean statusState = LOW;
void processStatus() {
  statusState = !statusState;
  digitalWrite(statusPin, statusState);
}

Once you start adding lots of timed events, this code gets cleaner and easier to read.

EBL evaluation

This seems to be an excellent library. And my assessment has so far been fairly short. Here is some comments, some TODO, etc. But this is a work in progress, and here for my own notes, and possibly feedback.

Performance

Memory

Timed

Serial

The advanced serial uses event message IDs and events. But there is only one message handler. It would be better if you could use event id. The example shows BACKLIGHT on/off on an LCD

  • AdvancedSerial.setReciever( BACKLIGHT_ON_MESSAGE, backlightOn);
  • AdvacnedSerial.setReceiver (BACKLIGHT_OFF_MESSAGE, backlightOff);
  • etc

Fortunately that is a fairly easy change to make.

Errors are a little hidden. If you send a message that is too long for the buffers it is silently dropped. Some form of error counter, or serial print (see next point).

Choosing serial - there is no way to choose serial, it is only the built in serial. On some devices, e.g. Lightuino you need to be able to use USB.write instead of Serial.write. But also you may want to use a software serial port, or just another UART (depending on AVR used).

The serial protocol is binary - it is much harder to debug a binary protocol. You can't even interact directly with it on the serial monitor. There is plenty of binary protocols, especially serial, but they are harder. One thing I have been thinking about is a variation using NMEA extensions. This would allow messages to be passed (like the example here for LCD control) and mix those with NMEA from a GPS, or other IMU.

See Also