【问题标题】:c# Read serial port weight cardinal scale 210c#读取串口体重秤210
【发布时间】:2017-05-27 02:28:00
【问题描述】:

我已经能够将指标的数据显示到我的计算机上,

输出看起来像这样

“[空间][空间] 978 0Kg”

[SPACE] 是空格文本(空)

我只想显示数字,

我使用以下脚本。

private delegate void Closure();
    private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
    {
        if (InvokeRequired)     //<-- Makes sure the function is invoked to work properly in the UI-Thread
            BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); }));     //<-- Function invokes itself
        else
        {
            while (_serialPort.BytesToRead > 0) //<-- repeats until the In-Buffer is empty
            {
                String tampung = _serialPort.ReadExisting();
                Regex regex = new Regex(@"[^\d|\.]");

                tampung = regex.Replace(tampung, "");


                textBox1.Text += string.Format("{0:X2} ", tampung);
            }
        }
    }

但显示的数字不完整,最后一个数字零没有输入

输出:

978

我正在使用指标http://www.cardinalscale.com/cs_product/210-storm/

有什么问题吗?

【问题讨论】:

    标签: c# parsing serial-port


    【解决方案1】:

    您可以使用正则表达式从字符串中提取数字,然后使用Trim 删除空格。

    string input = "  940 0Kg";
    string result = Regex.Replace(input, @"[^\d]", "").Trim();
    

    如果你需要它作为一个数字,当然

    int weight = int.Parse(result);
    

    【讨论】:

      【解决方案2】:

      替换

      String tampung = _serialPort.ReadExisting();
      Regex regex = new Regex(@"[^\d|\.]");
      

      string tampung = _serialPort.ReadExisting();
      string pattern = @"(\d+\.\,\d+)";
      MatchCollection matches = Regex.Matches(tampung, pattern);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-24
        • 2018-09-21
        • 2012-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多