如何从串口只读取重量而不是整个文本

时间:2017-08-17 09:19:45

标签: c# asp.net serial-port

我有条形码称重机Sartorious BSA 4235,它连接到串口(COM)。我试图在我的winforms asp.net应用程序的文本框中显示它。收到的数据格式为N + 5.249 g。我只需要获得重量值。但是当我试图仅提取重量时,由于重量的波动正在发生,并且当我用小数值替换字符串时,文本框被覆盖而不是仅仅与称量标度相似的最后一个数字波动。因此用户无法确定重量。波动发生得更快。以下是串口的设置: 波特率:1200 奇偶校验:无 数据位:7 停止位:1 这是代码:

 _serialPort = new SerialPort(PortName, BaudRate, (Parity)Enum.ToObject(typeof(Parity), paritybits), databits, (StopBits)Enum.ToObject(typeof(StopBits), stopbits));  


private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
    {
        if (IsFire)
        {
            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
            {
                int dataLength = _serialPort.BytesToRead;
                byte[] data = new byte[dataLength];
                int nbrDataRead = _serialPort.Read(data, 0, dataLength);
                if (nbrDataRead == 0)
                    return;
                string str = System.Text.Encoding.UTF8.GetString(data);

                double number;

                if (Double.TryParse(str, out number))
                {
                    txtBCGGrassWeight.Text = string.Format("{0:0.000}", str);
                }
                else
                {
                    var doubleArray = Regex.Split(str, @"[^0-9\.]+")
                    .Where(c => c != "." && c.Trim() != "");

                    string[] str1 = ((System.Collections.IEnumerable)doubleArray)
                  .Cast<object>()
                  .Select(x => x.ToString())
                  .ToArray();
                    if (str1 != null && str1.Length > 0)
                    {
                        txtBCGGrassWeight.Text = string.Format("{0:0.000}", str1[0]);
                    }
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

这是未经测试的,可能需要一些语法修正,但请尝试:

private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{
    if (IsFire)
    {
        int dataLength = _serialPort.BytesToRead;
        byte[] data = new byte[dataLength];
        int nbrDataRead = _serialPort.Read(data, 0, dataLength);
        if (nbrDataRead == 0) return;
        string str = System.Text.Encoding.UTF8.GetString(data);

        double number;
        bool success = false;
        if (Double.TryParse(str, out number))
        {
            success = true;
        }
        else
        {
            var match = Regex.Match( str, @"\d+\.\d+");
            if( match.Success )
            {
                success = Double.TryParse(match.Value, out number);
            }
        }

        if( success )
        {
            SetText(number.ToString());
        }
    }
}

delegate void SetTextCallback(string text);

private void SetText(string text)
{
    // InvokeRequired required compares the thread ID of the
    // calling thread to the thread ID of the creating thread.
    // If these threads are different, it returns true.
    if (this.txtBCGGrassWeight.InvokeRequired)
    {
        SetTextCallback d = new SetTextCallback(SetText);
        this.Invoke(d, new object[] { text });
    }
    else
    {
        this.txtBCGGrassWeight.Text = string.Format("{0:0.000}",text);

    }
}