[英]Understanding pseudocode for device serial communication and implementation using PySerial
我正在尝试使用PySerial自动执行一些数据收集,但是我不了解设备如何要求我传递/编写命令。
伪代码如下:
Structure{
WORD Handle //Reserves address space of a 2 byte word to store Handle
DWORD ParameterA[] // Reserves address space of one 4 byte word to store ParameterA (4 byte word is a double word)
DWORD ParameterB[6] //Resereves address space of 6 double words to store an array of 6 parameters called ParameterB
} PackedData
... // Later in program
Handle = 1200
ParamaterA = 1
SendStringToSerialPort(PackedData, 6)//This routine transfers the data found at theaddress of structure PackedData to the serial port. 6bytes used, 2 for the Handle, 4 for the DWORD ParameterA
如果有用的话,以下是原始文档的链接:第40页上的http://www.gentec-eo.com/Content/downloads/user-manual/User_Manual_SOLO_2_V7.pdf
到目前为止,这是我的解释方式,但我知道它是不正确的,因为它仅写入5个字节。
import serial
ser = serial.Serial()
ser.baudrate = 9600
ser.port = 3
ser.open()
class PackedData:
Handle = 1200
ParameterA = bytearray(0)
ParameterB = bytearray(6)
powerMeter = PackedData()
powerMeter.ParameterA = long(1)
print(ser.write(str(PackedData.Handle)+ str(powerMeter.ParameterA)))
有谁能告诉我我要去哪里错了?
您正在发送8位字符(字符串),而问题中描述的协议正在发送打包字节。 使用struct
模块将要发送的内容转换为打包字节:
import struct
print ser.write(struct.pack("<HL", PackedData.Handle, powerMeter.ParameterA))
您可能需要修复字节顺序(在结构格式字符串前面使用“>”或“ <”)。 当然,请根据远程设备的要求调整格式(在上面的示例中,我假设使用无符号整数)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.