Mbed forum

Unable to use CAN.read() when using CAN interrupt


(Jack Jhonsen) #1

I’ve been struggling to get the CAN interrupt to work for some time now without succes. I’m using a Nucleo F446RE board on which I’d like to use an interrupt to receive CAN messages. My code is as follows:

#include "mbed.h"

// CAN-bus
CAN can(D15, D14);
int canFrequency = 100000;

// LED
DigitalOut led1(LED1);

CANMessage msg;
bool newMsg = false;

 * Called when a CAN message is received
void interruptCanMessage() {
    newMsg = true;

int main() {
    can.attach(&interruptCanMessage, CAN::RxIrq);

    while (true) {
        if (newMsg) {
            led1 = !led1;
            newMsg = false;

I use another Nucleo F446RE to send a CAN message every second. The first Nucleo is able to receive the messages when using no interrupt attached and this in my main:

while (true) {
    if (can.read(msg)) {
        led1 = !led1;

-I’ve found on various sites that you can’t call the can.read() function within the interrupt so that’s why I used the boolean, but maybe that is the correct way, I don’t know.

-Another problem might lie in the boolean that is used in multiple threads maybe?

-Also if I toggle the led in the ISR function (interruptCanMessage()) the LED is rapidly toggled because the can message is never read so the ISR function is continiously called.

Can someone explain what I’m doing wrong and point me in the right direction.
Thanks in advance.

(Jack Jhonsen) #2

Solved using this: https://os.mbed.com/blog/entry/Simplify-your-code-with-mbed-events/
And the last reply in this discussion: https://github.com/ARMmbed/mbed-os/issues/6714

Basically disabling the mutex lock in the CAN.cpp file in the mbed drivers, then you are able to call can.read within the ISR. This might lead to problems in the future, but it works for now.