C#仅在更改时读取串口值(称重机)

时间:2016-01-29 08:43:08

标签: c# serial-port

private SerialPort _serialPort = null;

public WeightDisplay()
{
    InitializeComponent();
    Control.CheckForIllegalCrossThreadCalls = false; 
    _serialPort = new SerialPort("COM1", 9600, Parity.None, 8);
    _serialPort.StopBits = StopBits.One;
    _serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);
    _serialPort.Open();
}
void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    txtWeight.Text = _serialPort.ReadExisting();
}

此代码不断从连接到串行端口的重量机器获取值,并将其显示在文本框中。代码工作正常但我想改变文本框的值,如果权重有变化,即。如果ReadExisting()返回的值与之前的值不同。(我不希望文本框无缘无故地波动)

当我调试时,我得到这个值:

  

“+ 0.000 S \ r + 0.000 S \ r + 0.000 S \ r + 0.000 S \ r + 0.000 S \ r + 0.000 S \ r”

有时甚至是大字符串

我的文本框显示"+ 0.000"(持续闪烁)

1 个答案:

答案 0 :(得分:1)

你可以这样做:

void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
   var newVal = _serialPort.ReadExisting();

   if(String.Compare(txtWeight.Text, newVal) != 0)
      txtWeight.Text = newVal;
}

如果值与前一个值不同,您现在只更改TextBox的值。

<强>更新
由于你得到“+ 0.000 S \ r + 0.000 S \ r + 0.000 S \ r + 0.000 S \ r + 0.000 S \ r + 0.000 S \ r”,但只需要“+ 0.000”即可使用正则表达式处理数据:

void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
   var expr = "\\+ [0-9]+\\.[0-9]+";
   var newVal = _serialPort.ReadExisting();

   MatchCollection mc = Regex.Matches(newVal, expr);

   if (mc.Count > 0)
   {
      if(String.Compare(txtWeight.Text, mc[0].Value) != 0)
         txtWeight.Text = mc[0].Value;
   }
}

此行仅提取“+ 0.000”值并将它们放入集合mc

MatchCollection mc = Regex.Matches(newVal, expr);

现在只有mc[0].Value访问此集合的第一个元素(接收数据的第一个“+ 0.000”值)