问题描述
我使用 SerialDataReceivedEventHandler
类的 SerialPort
与串行端口设备进行通信。我通过 SerialPortObject.Write(command)
向设备发送 SCPI 代码,其中 command 是字符串类型。然后设备将回复一个字符串,该字符串由事件处理程序收集并由 SerialPortObject.ReadLine()
读入变量。
我向串行端口发送不同的命令,例如获取步进电机的速度或位置,并希望将它们分别存储在 string speed
或 string position
中。但是,事件处理程序只能读取设备发送的行而不知道它应该将数据存储在哪个变量中。 解决方案是在每个 SerialPortObject.ReadLine()
命令之后键入 SerialPortObject.Write()
命令,但是,这会暂停线程和 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
。
解决方法
我认为您应该保持上次发送哪个命令的状态,例如使用枚举。 或者发送方应该添加(如果可能)请求的参数。