覆盆子罐头

2024-06-23 19:07:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我对覆盆子和Python是绝对的初学者。现在我需要解决一个问题。我有树莓3,皮坎2双和CAN消息的来源。我做了Raspberry接收CAN信息所需的所有设置。然后我使用了这个代码,它运行得非常好:

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")

但问题是,我必须发送这个-ID 36/数据链路连接器:8/数据00 00 00 09 00 00 00-每100毫秒,然后读取我收到的信息。如果我不这样做,CAN源就不能工作,它只发送随机数。你知道吗

你能告诉我,如何重新编写代码,所以我每100毫秒发送一条信息,并一直阅读即将到来的内容吗?你知道吗

非常感谢


Tags: 代码importip信息formatmessagetimeos
1条回答
网友
1楼 · 发布于 2024-06-23 19:07:12

只需设置循环消息发送任务:

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

不需要多处理或多线程。你知道吗

接收可以像当前一样进行,也可以使用回调。 这些都在python can的文档中。 如文档中所述,您可能需要添加

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

之后

import can

相关问题 更多 >

    热门问题