0

I have been trying to write a code that would allow me to read all the data on the CAN bus every 0.1 seconds. There are 10 messages on the bus that are being sent every 0.1 seconds from another RPI3. Are there any examples available?

I can read the messages using can.notifier or can. recv()

import can

while True:
    measurements = get_readings_from_canbus(can)
    time.sleep(0.1)

Should I use can.notifier or can. recv() inside get_readings_from_canbus? I tried to use can.recv(), but it gets only one message. Using can.notifier is not very clear to me, since it keeps reading the CAN bus.

This return all the bus messages

import can 
bus = can.interface.Bus(channel='can0', bustype='socketcan_native') 
notifier = can.Notifier(bus, [can.Printer()])

Or using can.recv(), it returns only on message

import can 
bus = can.interface.Bus(channel='can0', bustype='socketcan_native') 
notifier = bus.recv()
2
  • can.recv should work fine for your purpose. To be able to find your problem, would you mind posting the rest of the can-related code?
    – oh.dae.su
    Apr 24, 2019 at 5:31
  • @oh.dae.su Thanks for your reply, I updated the question to include the code.
    – Moe
    Apr 24, 2019 at 11:48

1 Answer 1

2

I assume you have the trouble with bus.recv(), because of your time.sleep(0.1) line.

bus.recv() is a blocking call that receives a single can-frame. It will only move on, when a message is received on the bus. So in your case due to the time.sleep(0.1), you only receive a single message every 0.1 seconds, even though you expect more messages. I suggest to get rid of the time.sleep(0.1) in the while-loop. Then you can receive all can-frames on the bus in-time.

Here is a very basic example, how this could look like:

import can 
bus = can.interface.Bus(channel='can0', bustype='socketcan_native') 
while True:
    message = bus.recv()
    print(message.arbitration_id)

As bus.recv() is blocking your program will stop at this line, when there are no can-frames on the bus. If you want your program to do some work while waiting for the next frame, you can call the bus.recv(timeout) with a timeout argument, after which it will move on, even though it has not received a new can-frame.

I hope my interpretation of your question was right and the answer was helpful to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.