RS232问题 - 如何读取PC的重量

Gol*_*old 1 c# serial-port

我有一个通过RS232连接到PC的秤,我发送"W"来接收重量.秤在读取时始终发送重量.我如何抓住正在阅读的重量?

我可以获得任何C#示例代码吗?

Nic*_*cki 12

发送W?听起来像FedEx给企业带来的Mettler Toledo规模.我碰巧有一些代码从这样的规模读取:


// where this.port is an instance of SerialPort, ie
// this.port = new SerialPort(
//  portName,
//  1200,
//  Parity.None,
//  8,
//  StopBits.One);
//  this.port.Open();

protected override bool GetWeight(out decimal weightLB, out bool stable)
{
    stable = false;
    weightLB = 0;

    try
    {
        string data;

        this.port.Write("W\r\n");
        Thread.Sleep(500);
        data = this.port.ReadExisting();

        if (data == null || data.Length < 12 || data.Substring(8, 2) != "LB")
        {
            return false;
        }

        if (decimal.TryParse(data.Substring(1, 7), out weightLB))
        {
            stable = (data[11] == '0');

            return true;
        }
    }
    catch (TimeoutException)
    {
        return false;
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)

  • +1用于通过字母"W"识别随机设备. (8认同)
  • 很好地推断缺失的上下文. (5认同)