Skip to content

Instantly share code, notes, and snippets.

@lonesometraveler
Created March 31, 2020 11:20
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lonesometraveler/e3711f0f80046019e519cd84606d2618 to your computer and use it in GitHub Desktop.
Save lonesometraveler/e3711f0f80046019e519cd84606d2618 to your computer and use it in GitHub Desktop.
Mbed EventQueue example 2: Serial Interrupt Callback and deferred printf()
// Execution of certain function in an ISR context is not safe.
// For example, printf() in an interrupt context causes a Mutex error.
// Using Mbed's EventQueue, you can defer execution of code from an interrupt context to a user context.
// More about EventQueue: https://os.mbed.com/docs/mbed-os/v5.15/tutorials/the-eventqueue-api.html
#include "mbed.h"
EventQueue *queue = mbed_event_queue(); // event queue
RawSerial pc(USBTX, USBRX);
void onDataReceived();
void myCallback() {
char c = pc.getc();
printf("received: %c\r\n", c);
pc.attach(&onDataReceived, Serial::RxIrq); // reattach interrupt
}
void onDataReceived() {
pc.attach(NULL, Serial::RxIrq); // detach interrupt
queue->call(myCallback); // process in a different context
}
int main() {
pc.attach(&onDataReceived, Serial::RxIrq);
queue->dispatch_forever();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment