参考这篇教程中的方法,实现了NANO的CAN通信
参考官方的send()和receive()的.py文件后,实际使用的过程中,发现上位机只能收到一条消息,代码如下:
import os
import can
import time
os.system('sudo ip link set can0 type can bitrate 500000') # can0500K
os.system('sudo ifconfig can0 up') # can0 up
# can0 = can.interface.Bus(channel = 'can0', bustype = 'socketcan_ctypes')# socketcan_native
def send_message(bus, msg):
try:
bus.send(msg)
print(f"Sent: {msg}")
except can.CanError as e:
print(f"Error sending message: {e}")
def receive_messages(bus):
try:
while True:
msg = bus.recv(1.0)
if msg is not None:
print(f"Received: {msg}")
except KeyboardInterrupt:
pass
if __name__ == '__main__':
try:
can0 = can.interface.Bus(channel = 'can0', bustype = 'socketcan_ctypes')
msg = can.Message(arbitration_id=0x123, data=[0x11, 0x22, 0x33, 0x44])
msg1 = can.Message(arbitration_id=0x123, data=[0x55, 0x66, 0x77, 0x88])
send_message(can0, msg)
time.sleep(0.2)
send_message(can0, msg1)
receive_messages(can0)
except can.CanError as e:
print(f"Error accessing CAN bus: {e}")
finally:
os.system('sudo ifconfig can0 down')
上位机发送一条消息给NANO后,收到了第二条消息
但不可以让我的nano一直发送消息?一定要有应答了才能发送出第二条消息嘛?