9 years, 9 months ago.

Weird CAN bus / Timer interaction bug?

I have a simple program that uses the CAN Rx interrupt to read the ID of the received packets and then in the main loop outputs the most recently seen CAN ID to the USB serial.

It runs perfectly if I also define a Timer object in the code and initialize it in some way (the code below uses .start() but .reset() seems to also work)

If I comment out the line starting/resetting the timer the system locks.

Am I missing something or is this a bug in the libraries?

Obviously there is a simple enough workaround but this has had me scratching my head for a while as to why one application worked and another very similar one didn't until I tracked the cause down.

The hardware is an LPC1768 mbed. The CAN bus is getting hit fairly hard, around 800 packets per second.

#include "mbed.h"

Serial pc(USBTX,USBRX);

CAN canBus(p30,p29);
CANMessage canIn;

Timer aPointlessTimer;

int canID;

void canInIrq()
{

    while (canBus.read(canIn)) {
        canID = canIn.id;
    }
}


int main()
{

    pc.baud(115200);
    
    // without this it doesn't work.
    aPointlessTimer.start();

    canID = 0;
    canBus.frequency(500000);
    while (canBus.read(canIn)) {}; // clear any pending packets.
    canBus.attach(canInIrq,CAN::RxIrq);

    while (true) {
        if (canID != 0)
            pc.printf("%04X\n",canID);
        canID = 0;
    }
}
Be the first to answer this question.