【发布时间】:2011-09-10 18:44:25
【问题描述】:
我正在尝试在 Windows XP 机器上使用 C#.net 2.0 中的以下代码从 Sartorius 称重秤型号 BS2202S 读取重量:
public string readWeight()
{
string lastError = "";
string weightData = "";
SerialPort port = new SerialPort();
port.PortName = "COM1";
port.BaudRate = 9600;
port.Parity = Parity.Even;
port.DataBits = 7;
port.StopBits = StopBits.One;
port.Handshake = Handshake.RequestToSend;
try {
port.Open();
weightData = port.ReadExisting();
if(weightData == null || weightData.Length == 0) {
lastError = "Unable to read weight. The data returned form weighing machine is empty or null.";
return lastError;
}
}
catch(TimeoutException) {
lastError = "Operation timed out while reading weight";
return lastError;
}
catch(Exception ex) {
lastError = "The following exception occurred while reading data." + Environment.NewLine + ex.Message;
return lastError;
}
finally {
if(port.IsOpen == true) {
port.Close();
port.Dispose();
}
}
return weightData;
}
我可以使用 Hyperterminal 应用程序(随 Windows XP 提供)读取重量,该应用程序与上面给出的用于打开端口的串行端口参数相同。但是从上面的代码sn-p,我可以打开端口,每次都返回空数据。
我尝试使用this Stack Overflow thread 给出的代码打开端口,但它仍然返回空数据。
请帮助我。
【问题讨论】:
标签: windows-xp .net-2.0 serial-port c#-2.0