Hoijoo Kim
Hoijoo Kim

Reputation: 1

Python - socket CAN connection

I am using python to receive data from Linux socket CAN. ID is 0x1f7d8401, whereas the ID of the data I received was 401, showing only the last three digits.

What should I modify to get the whole ID value except 0x? Attached is the source code.

import can
import time
import os


print('\n\rCAN Rx test')
print('Bring up CAN0....')
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")
    print('\n\rKeyboard interrtupt')

Upvotes: 0

Views: 2815

Answers (1)

Shanti
Shanti

Reputation: 11

I just copied your code for testing, but with vcan0, instead of can0. It works fine. Able to receive full address. I don't know how you are sending data. I used cansend vcan0 1f7d8401#data. (No '0x' prefix for canid, here).

Upvotes: 1

Related Questions