我使用SerialPort
类的SerialDataReceivedEventHandler
与串行端口设备通信。我通过SerialPortObject.Write(command)
向设备发送SCPI代码,其中命令是字符串类型。然后,设备将使用事件处理程序收集的字符串进行回复,并由SerialPortObject.ReadLine()
读取到变量中。
我向串行端口发送不同的命令,例如获取步进电机的速度或位置,并希望将它们分别存储在string speed
或string position
中。然而,事件处理程序只能读取设备发送的行,而不知道它应该将数据存储在哪个变量中。解决方案是在每个SerialPortObject.Write()
命令之后键入SerialPortObject.ReadLine()
命令,但是,这会暂停线程,Windows From会暂停,直到设备响应,有时可能会很长,而事件处理程序会异步执行此操作。
string position, speed;
SerialPortObject.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
var input = SerialPortObject.ReadLine();
}
public void CurrentPosition()
{
//This requests for the current position (command is specific to the device)
SerialPortObject.Write("?X");
}
public void Speed()
{
//This requests for the current position (command is specific to the device)
SerialPortObject.Write("?V");
}
我的问题如何让SerialDataReceivedEventHandler
识别CurrentPosition()
或Speed()
中的哪一个引发了事件,并将设备响应分别放入position
和speed
中。
我认为您应该保留上次发送命令的状态,例如使用枚举。或者,发送端应该添加(如果可能的话(请求的参数。