我目前正在使用稱爲Fluke 5500A多產品校準設備的設備。我用C#編寫了一個小程序來與它進行交互,並學習更多關於它是如何工作的,但不幸的是,SerialPort.DataReceived給了我一些非常奇怪的結果。該計劃的時間不長,所以我打算將它張貼在其全部在這裏:SerialPort.DataReceived返回奇怪的結果
class Program
{
static public bool isExecuting = true;
static private string serialCommand;
static private string dataReceived;
static void Main(string[] args)
{
SerialPortConnection serialPort = new SerialPortConnection();
serialPort.OpenSerialConnection();
while (isExecuting == true)
{
Console.WriteLine("Enter a command or type q to quit.");
serialCommand = Console.ReadLine().ToUpper();
if (serialCommand == "Q")
isExecuting = false;
else if (serialCommand == "CLEAR")
Console.Clear();
else
{
dataReceived = serialPort.WriteSerialConnection(serialCommand);
Console.WriteLine(dataReceived);
}
}
serialPort.CloseSerialConnection();
}
}
}
而且我SerialPortConnection類:
public class SerialPortConnection
{
private SerialPort serialPort;
private string dataReceived = "none";
public SerialPortConnection(string comPort = "Com3", int baud = 9600, System.IO.Ports.Parity parity = System.IO.Ports.Parity.None, int dataBits = 8, System.IO.Ports.StopBits stopBits = System.IO.Ports.StopBits.One)
{
serialPort = new SerialPort(comPort, baud, parity, dataBits, stopBits);
}
public void OpenSerialConnection()
{
try
{
serialPort.Open();
}
catch (Exception e)
{
Console.Write("\nError");
Console.Write(e);
}
}
public string WriteSerialConnection(string SerialCommand)
{
try
{
serialPort.Write(String.Format(SerialCommand + "\r"));
dataReceived = serialPort.ReadExisting();
return dataReceived;
}
catch (Exception e)
{
Console.Write("\nError");
Console.Write(e);
return "Execution Unsuccessful";
}
}
public void CloseSerialConnection()
{
try
{
serialPort.Close();
}
catch (Exception e)
{
Console.Write("\nError");
Console.Write(e);
}
}
}
我的問題是目前輸出到控制檯看起來像這樣:
Enter a command or type q to quit.
*IDN?
Enter a command or type q to quit.
OUT 50V <-- Command input
*IDN? <-- Previous command echoed back
FLUKE,5500A,8030005,2.61+1.3+2.0+* <-- Data received from previous command
161>
Enter a command or type q to quit.
OPER
OUT 50V
162>
Enter a command or type q to quit.
STBY
OPER
163>
Enter a command or type q to quit.
*RST
STBY
164>
Enter a command or type q to quit.
該命令執行得很好,但輸出到公司nsole似乎是被執行的最後一個命令以及該命令返回的任何數據。我不知道爲什麼會這樣。
編輯:
感謝羅伯特·普的回答我實現下面的代碼:你的問題的
var received = "";
bool isReading = true;
while (isReading == true)
{
try
{
received += serialPort.ReadExisting();
if (received.Contains('>'))
isReading = false;
}
catch (Exception e)
{
}
}
Console.WriteLine(received);
該設備只是回顯命令。但是你沒有檢查,也沒有等待足夠長的時間來接收它。您的ReadExisting()調用無法正常工作。使用ReadLine()取而代之。 –
@HansPassant感謝您的信息,但只是讓線程休眠幾秒鐘然後嘗試ReadExisting()會不會更容易?我沒有考慮到需要時間的事實。 – DanteTheEgregore
@HansPassant假設我等了很長時間才能收到,我應該等多少時間?半秒鐘?兩秒鐘?也許是十分之一秒? – DanteTheEgregore