STM32F446RE CAN bus example not working: Not allowed in ISR context

Hi, I’m learning CAN usage in Mbed OS 6.7. When I try to run the example provided in the guide here I get the following error:

My code, right now, looks like this:

#include "mbed.h"

Ticker ticker;
DigitalOut led1(LED1);
DigitalOut led2(LED2);
char counter = 0;

CAN can1(PB_12, PB_13);
CAN can2(PA_11, PA_12);

void send()
{
printf("send()\n");
if (can1.write(CANMessage(1337, &counter, 1))) {
    printf("wloop()\n");
    counter++;
    printf("Message sent: %d\n", counter);
}
led1 = !led1;
}

int main()
{
printf("main()\n");
ticker.attach(&send, 1);
CANMessage msg;
while (1) {
    printf("loop()\n");
    if (can2.read(msg)) {
        printf("Message received: %d\n", msg.data[0]);
        led2 = !led2;
    }
    ThisThread::sleep_for(200);
}
}

I can’t get this example working, and that’s odd.
Could anyone using STM32 give me a simplistic piece of code that works with CAN RX and TX?

Thank you in advance.

Hello Fabrizio,

Try the following:

#include "mbed.h"

Ticker      ticker;
DigitalOut  led1(LED1);
DigitalOut  led2(LED2);
char        counter = 0;
CAN         can1(PB_12, PB_13);
CAN         can2(PA_11, PA_12);

void send()
{
    printf("send()\n");
    if (can1.write(CANMessage(1337, &counter, 1))) {
        printf("wloop()\n");
        counter++;
        printf("Message sent: %d\n", counter);
    }
    led1 = !led1;
}

int main()
{
    printf("main()\n");

    CANMessage      msg;
    EventQueue*     queue = mbed_event_queue();  // pointer to mbed's shared event queue

    //ticker.attach(&send, 1);
    ticker.attach(queue->event(send), 1);        // attaching an event handler function
    while (1) {
        printf("loop()\n");
        if (can2.read(msg)) {
            printf("Message received: %d\n", msg.data[0]);
            led2 = !led2;
        }
        ThisThread::sleep_for(200ms);
    }
}

The code above defers the execution of the send function from the Ticker's interrupt handler to a shared queue event handler.

Best regards, Zoltan

Thank you, you saved my day. The code is now compiling but I also had to add:

    "target_overrides": {
    "*": {
        "platform.callback-nontrivial"      : true,

to my mbed_app.json

Why is the official example not working though? Should we update it?

Why is the official example not working though?

The reason for that could be as described here.

Should we update it?

I’m afraid the official example can be updated only by the Mbed Team.

Hi Fabrizio

we would certainly welcome a pull request raised here GitHub - ARMmbed/mbed-os-examples-docs_only: Examples currently in use by Mbed OS docs that are in need of a home for the solution !

Many thanks
Anna