当前位置: 首页 > 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.xdnf.cn/news/1190431.html

相关文章:

  • pytorch学习笔记-自定义卷积
  • 在C#中判断两个列表数据是否相同
  • Day04–链表–24. 两两交换链表中的节点,19. 删除链表的倒数第 N 个结点,面试题 02.07. 链表相交,142. 环形链表 II
  • # JsSIP 从入门到实战:构建你的第一个 Web 电话
  • VTK交互——ImageRegion
  • kali [DNS劫持] 实验(详细步骤)
  • python I 本地 html 文件读取方法及编码报错问题详解
  • Android 蓝牙学习
  • 在python3.8和pytorch1.8.1的基础上安装tensorflow
  • 对比JS“上下文”与“作用域”
  • kafka中生产者的数据分发策略
  • RabbitMQ面试精讲 Day 5:Virtual Host与权限控制
  • GMP模型
  • Qt 多线程编程最佳实践
  • 公域流量向私域流量转化策略研究——基于开源AI智能客服、AI智能名片与S2B2C商城小程序的融合应用
  • 数据结构 二叉树(2)---二叉树的实现
  • Spring AI Alibaba Video 示例
  • “三十二应身”架构设计:论高扩展性度化系统的实现原理
  • MyBatis_3
  • 想入门网络编程?——网络通信的基本概念
  • Maven之依赖管理
  • ts-node 深入全面讲解
  • OCR工具集下载与保姆级安装教程!!
  • Spring Boot 实战:用 Apache Commons CSV 优雅解析 CSV 文件
  • MySQL 基本查询
  • Linux随记(二十一)
  • JVM 基础架构全解析:运行时数据区与核心组件
  • 商汤InternLM发布最先进的开源多模态推理模型——Intern-S1
  • 开源智能体框架(Agent Zero)
  • 从稀疏数据(CSV)创建非常大的 GeoTIFF(和 WMS)