配置CH340串口和创建slcan设备
串口波特率:2000000
CAN波特率:500000
标准帧类型
ID帧:0x00000000
数据:00 00 00 00 00 00 00 00
-
安装 can-utils 依赖包:
sudo apt-get install can-utils
-
加载必要的内核模块:
sudo modprobe can
sudo modprobe can-raw
sudo modprobe slcan
-
查看串口设备信息:
使用以下命令结合dmesg
命令和grep
命令来查找特定串口设备的相关信息:
sudo dmesg | grep ttyUSB
这条命令将会列出所有包含 ttyUSB
的设备
-
配置串口波特率为2000000:
使用 stty
命令配置串口波特率:
sudo stty -F /dev/ttyUSB1 2000000
-
创建并配置slcan设备:
使用 slcand
创建一个新的 slcan
设备并配置其波特率:
sudo slcand -o -c -s6 /dev/ttyUSB1 slcan0 sudo ip link set up slcan0
其中,-s6
表示 CAN 波特率为 500000,-o
表示打开设备,-c
表示校验。
-
检查设备状态:
确认设备状态:
ip link show slcan0
发送和接收CAN消息的Python脚本
确保使用标准数据帧和十六进制帧ID (0x00):
import can
import time# 配置CAN总线
can_interface = 'slcan0'# 创建CAN总线接口
bus = can.interface.Bus(channel=can_interface, bustype='socketcan')# 定义要发送的CAN消息,帧ID为十六进制0x00,数据为0x00 00 00 00 00 00 00 00
msg = can.Message(arbitration_id=0x00,data=[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],is_extended_id=False, # 标准帧is_remote_frame=False) # 数据帧try:# 发送CAN消息bus.send(msg)print("Message sent on {}: {}".format(bus.channel_info, msg))
except can.CanError:print("Message NOT sent")# 等待接收消息并打印
print("Listening for incoming messages...")
start_time = time.time()
while time.time() - start_time < 10: # 监听10秒message = bus.recv(timeout=1.0)if message:print("Received message: {}".format(message))# 关闭CAN总线接口
bus.shutdown()
运行Python脚本
保存上述脚本为 poc.py
,并运行它:
python poc.py
使用 candump
和 cangen
工具确认总线消息
如果脚本没有打印接收到的消息,可以使用 candump
和 cangen
工具进行进一步测试:
生成CAN消息:
cangen slcan0 -g 10 -I 000 -D 0000000000000000 -L 8
捕获CAN消息:
candump slcan0
检查日志
如果仍然没有接收到消息,请检查系统日志以获取更多信息:
dmesg | grep -i can journalctl -k | grep -i can