Write to console from callback

Discussions and support about ChibiOS/HAL, the MCU Hardware Abstraction Layer.
Post Reply
enmas
Posts: 1
Joined: Sun Oct 17, 2021 1:43 pm

Write to console from callback

Post by enmas »

Hi

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
User avatar
Giovanni
Site Admin
Posts: 14893
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: Write to console from callback

Post by Giovanni »

Hi,

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.

Giovanni
Post Reply