Loading...  ## 使用场景 这里操作的是太阳能mppt控制板 型号是:太阳宣言 支持Rs485对设备数据进行读取以及设置 ## 实现功能 通过读取rs485转ttl,再通过type-c连接电脑读取出设备里面的数据,当然了也支持写入数据的 ## windows端 用 USB 转 RS485 模块接好控制器 A/B,Windows 上 COM 口号可能是 `COM3/COM4`这个去端口上面查询一下就知道了 ```python import serial import struct # ----------------- # CRC16-Modbus 校验 # ----------------- def crc16(data: bytes): crc = 0xFFFF for pos in data: crc ^= pos for _ in range(8): if (crc & 0x0001) != 0: crc >>= 1 crc ^= 0xA001 else: crc >>= 1 return crc # ----------------- # 发送指令 # ----------------- def build_frame(dev_addr, func, reg_addr, reg_count): frame = struct.pack('>B B H H', dev_addr, func, reg_addr, reg_count) crc = crc16(frame) frame += struct.pack('<H', crc) # CRC 低字节在前 return frame # ----------------- # 主程序 # ----------------- if __name__ == '__main__': ser = serial.Serial("COM3", baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=1) # 读 0x0101 (电池电压),数量=1 cmd = build_frame(1, 3, 0x0101, 1) print("发送帧:", cmd.hex()) ser.write(cmd) resp = ser.read(7) # 响应长度:设备号(1)+功能码(1)+字节数(1)+寄存器值(2)+CRC(2) print("接收帧:", resp.hex()) if len(resp) >= 7: value = int.from_bytes(resp[3:5], byteorder='big') / 10.0 print("电池电压:", value, "V") else: print("无响应或响应错误") ``` ## Mac端 用命令查看串口设备 ```sh ls /dev/tty.* ``` 如果有类似/dev/tty.usbserial-1420带有usbserial,那就是了 比如: ```shell /dev/tty.usbserial-1420 /dev/tty.wchusbserial1420 ``` 在代码里,把 `COM3` 改成对应的: ```sh ser = serial.Serial("/dev/tty.usbserial-1420", baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=1) ``` 最后修改:2025 年 09 月 09 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏