Write to console from callback

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

Write to console from callback

Postby enmas » Sun Oct 17, 2021 1:50 pm


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
Site Admin
Posts: 13876
Joined: Wed May 27, 2009 8:48 am
Location: Salerno, Italy
Has thanked: 951 times
Been thanked: 808 times

Re: Write to console from callback

Postby Giovanni » Sun Oct 17, 2021 2:01 pm


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.


Return to “ChibiOS/HAL”

Who is online

Users browsing this forum: No registered users and 3 guests