Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 树莓-发送CAN信息_Python_Raspberry Pi_Can Bus - Fatal编程技术网

Python 树莓-发送CAN信息

Python 树莓-发送CAN信息,python,raspberry-pi,can-bus,Python,Raspberry Pi,Can Bus,我对覆盆子和蟒蛇是绝对的初学者。现在我需要解决一个问题。我有树莓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(

我对覆盆子和蟒蛇是绝对的初学者。现在我需要解决一个问题。我有树莓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")
但问题是,我必须每隔100毫秒发送一次-ID36/DLC:8/Data 00 00 09 00 00,然后读取我收到的内容。如果我不这样做,CAN源就不能工作,它只发送随机数

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


非常感谢

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

task = can.send_periodic('can0', msg, 0.1)
task.start()
不需要多处理或多线程

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

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

import can

“每100mS发送一次…一直在阅读”:如果你想在一个脚本中并行执行任务,你必须使用
线程
多处理
。我很抱歉,我的愚蠢。我的意思是发送一条消息并阅读将要发送的内容,直到下一条消息将要发送为止,发送一条消息,然后重新发送;总线发送('ID36…');睡眠时间(0.1);bus.recv()?您好,谢谢您的帮助。当我尝试它时,它显示了两个错误。因此,我将其重写为“task=bus.send…”,仍然存在错误。我做了所有的更新,如果问题可能是这样的话,重新启动,但它仍然显示“AttributeError:'SocketscanNative_Bus'对象没有属性'send_periodic'”。我试图寻找那个,但我什么也找不到。@v.hartman必须是can,而不是bus。我已经详细回答了。除此之外,只需查看文档并搜索send_periodic.com,以感谢您的努力。我照你说的做了,但仍然有错误:
Traceback(最近一次调用):File“/home/pi/Desktop/zkouska.py”,第26行,在task=can.send_periodic('can0',msg,0.1)File“/usr/local/lib/python3.7/dist packages/python-can-1.4.1-py3.7.egg/can/broadcastmanager.py”,第75行,在send_中,定期返回can.interfaces.interface.CyclicSendTask(频道、消息、时段)属性错误:模块“can.interfaces.interface”没有属性“CyclicSendTask”
,但正如您所说,我将尝试在文档中找到答案