iksd
iksd

Reputation: 19

Raspberry - Sending CAN message

i'am absolute beginner in Raspberry and python. Right now i need to solve a problem. I have Raspberry3, PiCAN 2 DUO and source of CAN messages. I did all the setting Raspberry needs to receive CAN messages. Then i used this code, which works perfectly fine:

import can
import time
import os

os.system("sudo /sbin/ip link set can0 up type can bitrate 500000")
time.sleep(0.1) 

try:
    bus = can.interface.Bus(channel='can0', bustype='socketcan_native')
except OSError:
    print('Cannot find PiCAN board.')
    exit()

print('Ready')
try:
    while True:
        message = bus.recv()    # Wait until a message is received.

        c = '{0:f} {1:x} {2:x} '.format(message.timestamp, message.arbitration_id, message.dlc)
        s=''
        for i in range(message.dlc ):
            s +=  '{0:x} '.format(message.data[i])

        print(' {}'.format(c+s))


except KeyboardInterrupt:
    #Catch keyboard interrupt
    os.system("sudo /sbin/ip link set can0 down")

But the problem is, i have to send this - ID 36 / DLC:8 / Data 00 00 00 00 09 00 00 00 - every 100mS and then read what i am receiving. The CAN source can't work without that, if i am not doing it, it just sends random numbers.

Could you advise me, how to remake the code, so i am sendin every 100mS that message and all the time reading what is coming?

Thank you very much

Upvotes: 1

Views: 1673

Answers (1)

mspiller
mspiller

Reputation: 3839

Just set up a task for cyclic message sending:

task = can.send_periodic('can0', msg, 0.1)
task.start()

No need for multiprocessing or multithreading.

Receiving can be done like you are doing currently or by using callbacks. It’s all in the documentation of python-can. As written in the documentation, you might have to add

can.rc['interface'] = 'socketcan_ctypes'

after

import can

Upvotes: 1

Related Questions