Page 1 of 1

Write to console from callback

Posted: Sun Oct 17, 2021 1:50 pm
by enmas

For development purposes I want to write to console via UART from a callback function. As I came to understand and experienced the following is not allowed:

Code: Select all

static void icuwidthcb(ICUDriver *icup) {

  last_width = icuGetWidthX(icup);
  chprintf((BaseSequentialStream*)&SD2, "Callback icuwidth: %d\r\n", last_width);

What is the simpest way of doing this? And what is the best practice when doing "work" using callbacks?
A simple example code would be much appreciated as I'm relative new to chibios and using threads.

BR enmas

Re: Write to console from callback

Posted: Sun Oct 17, 2021 2:01 pm
by Giovanni

Callbacks are called from ISRs so you can't call any blocking function in there, chprintf() calls blocking primitives. From callbacks you can only call those functions postfixed with "I" using this pattern:

- chSysLockFromISR()
- Call one or more I-functions.
- chSysUnlockFromISR()

One possible solution is to wakeup a thread from the callback and call chprintf() from the thread. If you need to print ICU values I would use a mailbox object.

From the ISR you post ICU values to the mailbox as messages.
From thread you read messages and do the printing.

Mailboxes offer I-functions for use from ISR context.