当前位置: 首页 > news >正文

两个USB-CAN-A收发测试

硬件连接

请添加图片描述

#接受

import serial
import sysdef calculate_checksum(data):"""Calculate checksum for configuration commands"""checksum = sum(data[2:])return checksum & 0xffdef print_can_message(frame_type, frame_format, can_id, data, can_rate, raw_frame):"""Print received CAN message in categorized format with raw frame"""print("\n" + "="*50)print("CAN Message Received".center(50))print("="*50)print(f"{'ID (HEX)':<20}: {can_id}")print(f"{'Frame Type':<20}: {frame_type}")print(f"{'Frame Format':<20}: {frame_format}")print(f"{'Data Frame (HEX)':<20}: {data}")print(f"{'CAN Rate (bps)':<20}: {can_rate}")print(f"{'Raw Frame':<20}: {raw_frame}")print("="*50 + "\n")def main():# ConfigurationCAN_RATE = 500000  # 500kbps (matches our configuration)print("CAN Message Receiver Program")print("="*50)print("The converter supports two protocols:")print("- Fixed 20-byte protocol")print("- Variable length protocol (selected)")print("Ensure variable length protocol is selected in the converter software")print("="*50 + "\n")try:# Initialize serial portser = serial.Serial("/dev/ttyUSB0", 2000000, timeout=1)print(f"Serial port {ser.portstr} opened at 2,000,000 baud")# Configure CAN interface (500kbps, Extended Frame)set_can_baudrate = [0xaa, 0x55, 0x12, 0x03, 0x02, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]# Add checksum and send configurationchecksum = calculate_checksum(set_can_baudrate)set_can_baudrate.append(checksum)ser.write(bytes(set_can_baudrate))print("CAN interface configured: 500kbps, Extended Frame, Normal Mode")# Main reception loopprint("\nWaiting for CAN messages...\n")while True:# Read packet header (2 bytes)header = ser.read(2)if len(header) != 2:continue# Check for valid header (0xAA followed by byte with 0xC0 mask)if header[0] == 0xaa and (header[1] & 0xc0) == 0xc0:# Parse header informationdata_len = header[1] & 0x0fframe_format = "Data Frame" if (header[1] & 0x10) == 0x00 else "Remote Frame"frame_type = "Standard Frame" if (header[1] & 0x20) == 0x00 else "Extended Frame"# Determine remaining bytes to readremaining_bytes = (data_len + 3) if frame_type == "Standard Frame" else (data_len + 5)# Read remaining messagemessage = ser.read(remaining_bytes)if len(message) != remaining_bytes:print("Error: Incomplete message received")continue# Check for valid end code (0x55)if message[-1] != 0x55:print("Error: Invalid message end code")continue# Combine header and message for raw frameraw_frame = list(header) + list(message)hex_raw_frame = [f"0x{byte:02X}" for byte in raw_frame]# Extract CAN ID and dataif frame_type == "Standard Frame":can_id = (message[1] << 8) + message[0]can_data = message[2:2+data_len] if data_len > 0 else []else:  # Extended Framecan_id = (message[3] << 24) + (message[2] << 16) + (message[1] << 8) + message[0]can_data = message[4:4+data_len] if data_len > 0 else []# Format outputhex_id = f"0x{can_id:0{'4' if frame_type == 'Standard Frame' else '8'}X}"hex_data = [f"0x{byte:02X}" for byte in can_data] if can_data else ["No Data"]# Print categorized message with raw frameprint_can_message(frame_type, frame_format, hex_id, hex_data, CAN_RATE, hex_raw_frame)except serial.SerialException as e:print(f"Serial port error: {e}")except KeyboardInterrupt:print("\nProgram terminated by user")finally:if 'ser' in locals() and ser.is_open:ser.close()print("Serial port closed")if __name__ == "__main__":main()

#发送

import serial
import timeprint("The converter is equipped with two built - in conversion protocols, \none is a fixed 20 byte protocol and the other is a variable length protocol. \nPlease ensure that the variable length protocol is selected in the supporting software \nand click the Set and Start button to issue a configuration command to the converter")t = serial.Serial("/dev/ttyUSB1", 2000000)print(t.portstr)def calculate_checksum(data):checksum = sum(data[2:])return checksum & 0xffset_can_baudrate = [0xaa,     #  0  Packet header0x55,     #  1  Packet header0x12,     #  3 Type: use variable protocol to send and receive data##  0x02- Setting (using fixed 20 byte protocol to send and receive data),   0x12- Setting (using variable protocol to send and receive data)##0x03,     #  3 CAN Baud Rate:  500kbps  ##  0x01(1Mbps),  0x02(800kbps),  0x03(500kbps),  0x04(400kbps),  0x05(250kbps),  0x06(200kbps),  0x07(125kbps),  0x08(100kbps),  0x09(50kbps),  0x0a(20kbps),  0x0b(10kbps),   0x0c(5kbps)##0x02,     #  4  Frame Type: Extended Frame  ##   0x01 standard frame,   0x02 extended frame ##0x00,     #  5  Filter ID10x00,     #  6  Filter ID20x00,     #  7  Filter ID30x00,     #  8  Filter ID40x00,     #  9  Mask ID10x00,     #  10 Mask ID20x00,     #  11 Mask ID30x00,     #  12 Mask ID40x00,     #  13 CAN mode:  normal mode  ##   0x00 normal mode,   0x01 silent mode,   0x02 loopback mode,   0x03 loopback silent mode ##0x00,     #  14 automatic resend:  automatic retransmission0x00,     #  15 Spare0x00,     #  16 Spare0x00,     #  17 Spare0x00,     #  18 Spare
]# Calculate checksum
checksum = calculate_checksum(set_can_baudrate)
set_can_baudrate.append(checksum)
print(set_can_baudrate)
set_can_baudrate = bytes(set_can_baudrate)# Send command to set CAN baud ratenum_set_baud = t.write(set_can_baudrate)
print(f"Set CAN baud rate command sent, bytes written: {num_set_baud}")time.sleep(1)
print("send CAN ID:0x01234567,extended frame, data:0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88")
send_can_id_data = bytes([0xaa,     # 0  Packet header0xe8,     # 1  0xc0 Tyep# bit5(frame type 0- standard frame (frame ID 2 bytes), 1-extended frame (frame ID 4 bytes))# bit4(frame format 0- data frame, 1 remote frame)# Bit0~3 Frame data length (0~8)0x67,     # 2  Frame ID data 1    1~8 bit, high bytes at the front, low bytes at the back0x45,     # 3  Frame ID data 2    1~8 bit, high bytes at the front, low bytes at the back0x23,     # 4  Frame ID data 3    1~8 bit, high bytes at the front, low bytes at the back0x01,     # 5  Frame ID data 4    9~16 bit, high bytes at the front, low bytes at the back0x11,     # 6  Frame data 1       CAN sends  data 10x22,     # 7  Frame data 2       CAN sends  data 20x33,     # 8  Frame data 3       CAN sends  data 30x44,     # 9  Frame data 4       CAN sends  data 40x55,     # 10 Frame data 5       CAN sends  data 50x66,     # 11 Frame data 6       CAN sends  data 60x77,     # 12 Frame data 7       CAN sends  data 70x88,     # 13 Frame data 8       CAN sends  data 80x55,     # 14 Frame data 4       CAN sends  data 4
])
print(send_can_id_data)
num = t.write(send_can_id_data)
print(num)
t.close()
http://www.dtcms.com/a/300376.html

相关文章:

  • Item14:在资源管理类中小心拷贝行为
  • 小白成长之路-部署Zabbix7(二)
  • 每日一题【删除有序数组中的重复项 II】
  • linux shell从入门到精通(二)——变量操作
  • 深度学习损失函数的设计哲学:从交叉熵到Huber损失的深入探索
  • java--JDBC
  • OSPF路由协议之多区域划分
  • nuphy新键盘快捷键
  • 智慧工业缺陷检测准确率↑32%:陌讯多模态融合算法实战解析
  • 英语听力口语词汇-8.美食类
  • docker安装问题汇总
  • ETE_Voice:端到端C++智能语音对话系统
  • 用unity开发教学辅助软件---幼儿绘本英语拼读
  • 相机标定相关原理
  • 【高等数学】第五章 定积分——第五节 反常积分的审敛法 Γ函数
  • C++编程学习(第16天)
  • 【RK3568 PWM 子系统(SG90)驱动开发详解】
  • JavaScript手录06-函数
  • Linux——线程同步
  • KubeKey安装KubeSphere、部署应用实践问题总结
  • 立式加工中心X-Y轴传动机械结构设“cad【6张】三维图+设计说明书
  • 计算机中的单位(详细易懂)
  • 计算机结构-逻辑门、存储器、内存、加法器、锁存器、程序计数器
  • 斐波那契数列加强版 快速矩阵幂
  • 53. 最大子数组和
  • 组合问题(回溯算法)
  • Windows Server容器化应用的资源限制设置
  • 图书管理系统:一个功能完善的图书馆管理解决方案
  • 【C++篇】STL的关联容器:map和set(下篇):用一颗红黑树同时封装出map和set
  • CCFRec-人大高瓴-KDD2025-序列推荐中充分融合协同信息与语义信息