【问题标题】:RS232 question - how to read weight to PCRS232 问题 - 如何将重量读取到 PC
【发布时间】:2010-01-10 20:01:04
【问题描述】:

我有一个通过 RS232 连接到 PC 的秤,我发送“W”来接收重量。秤在读取时始终发送重量。如何捕捉正在读取的重量?

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

【问题讨论】:

    标签: c# serial-port


    【解决方案1】:

    发送一个 W?听起来像是联邦快递为企业提供的梅特勒托利多量表。我碰巧有一些从这样的规模读取的代码:

    
    // 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;
    }
    

    【讨论】:

    • 很好地推断了缺失的上下文。
    • 我会摆脱那个 Thread.Sleep(500).. 有更好的方法来完成这项任务
    【解决方案2】:

    您需要使用 .NET 的 SerialPort 组件。完整的描述和示例可在 MSDN 网站上找到:http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 2016-05-03
      相关资源
      最近更新 更多