Finding timestamps of CAN messages received by a microcontroller

canusb

The microcontroller kit (STM32F4 discovery kit) which I am using has CAN and USB support. I want to program my microcontroller so that each time when a CAN message is received, it is transmitted via USB to the host PC. I also need to see the time at which each CAN message was received. In the host PC I can see this information.

How do I find the time information about the CAN message received, that is, at what time was each CAN message received?

I already have a method which I will explain here. I need your suggestion regarding my idea or you may suggest a new method.

My method: Run a timer inside the microcontroller. Each time a CAN message is received, the value present in timer is stored and the timer is reset. The stored timer value along with the CAN message information is transfered via USB to the host machine.

Here each timer increment might be equivalent to 1 millisecond or 1 microsecond depending on the timer configuration. The microcontroller will be always sending the time difference between two CAN messages.

I am also planning to use another counter which would increment for each timer overflow. Sometimes a CAN message might only arrive after two seconds (or even some other time). In that case the timer can overflow. Each time when a timer has finished, the counter will be incremented. This happens until next CAN message arrives. This counter value will be also transmitted to the host PC.

How is my above method? Is there any better idea?

Best Answer

I never worked with STM32F4 but like most of other controllers with CAN, it has timestamp register. I checked in this reference manual, this one has a register

Check out CAN_RDTxR. It has timestamp field. Description says,

This field contains the 16-bit timer value captured at the SOF detection.

You might want to use this in-built feature instead of using your own timers etc.

(P.S. I would strongly recomment you to use FIFO, if you are not using them!)