串口通信协议

Serial Port Communication Protocol

在与数字万用表(例如BK Precision 2831E)等设备进行串行通信时,为什么我需要发送一次查询命令但读取两次输出?例如,我发送了一个测量电压的查询命令,并收到了一个回声,但没有电压值。 然后我发送了两次查询命令,返回了回声和测量的电压。本质上,要读出测得的电压,我必须连续两次发送相同的查询命令。 我不明白这个概念。谁能帮我推理一下。

我在下面附上了示例代码:

def readoutmm(portnumber_multimeter):
    import serial
    import time
    ser2 = serial.Serial(
    port="com"+str(portnumber_multimeter),
    baudrate=9600,
    bytesize=serial.EIGHTBITS,  
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE
    )
    ser2.write(b'fetc?\n') # Query command
    voltage= ser2.readline() # Returns echo
    voltage=ser2.readline() # Returns measured voltage
    voltage=float(voltage)
    ser2.close()
    packet=[voltage]
    return packet 

这对于基于 RS232/RS485 协议的设备来说实际上很常见。

来自manual of the machine you mentioned,本人引用:

The character received by the multimeter will be sent back to the controller again. The controller will not send the next character until the last returned character is received correctly from the meter. If the controller fails to receive the character sent back from the meter, the possible reasons are listed as follows:

  • The serial interface is not connected correctly.
  • Check if the same baud rate is selected for both the meter and the controller.
  • When the meter is busy with executing a bus command, it will not accept any character from the serial interface at the same time. So the character sent by controller will be ignored.

In order to make sure the whole command is sent and received correctly, the character without a return character should be sent again by the controller.

在很多设备上,这实际上是一个您可以打开和关闭的设置。

现在,关于你的问题:

why do I need to send a query command once but read the output twice?

您应该在发送一个新字符之前读回每个字符以验证该字符是否被正确接收。但是在您的代码中实际上是在读取其中一个字符之前发送所有字符。

在你有可靠连接的情况下,你的方法也可以工作,但因此你需要阅读两遍;一次验证是否收到命令,第二次检索实际数据。

请记住,读取缓冲区可能会受到一定数量的限制。如果您在查询大量数据和发送大量命令时遇到意外行为,可能是因为这些缓冲区已满。