问题
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();
}
This code continuously gets values from weight machine connected to serial port and displays it in a textbox. Code works fine but I want to change the value of textbox if there is change in weight ie. if value returned by ReadExisting() differs from previous value.(I don't want the textbox to be fluctuated for no reason)
When I debug I get this value:
"+ 0.000 S\r+ 0.000 S\r+ 0.000 S\r+ 0.000 S\r+ 0.000 S\r+ 0.000 S\r"
sometimes even big string
And my textbox displays "+ 0.000" (continuously blinking)
回答1:
You could do something like that:
void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
var newVal = _serialPort.ReadExisting();
if(String.Compare(txtWeight.Text, newVal) != 0)
txtWeight.Text = newVal;
}
You now only change the value of the TextBox if the value differs from the previous one.
Update
Since you get "+ 0.000 S\r+ 0.000 S\r+ 0.000 S\r+ 0.000 S\r+ 0.000 S\r+ 0.000 S\r" back but only need "+ 0.000" you can use regex to process your data:
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;
}
}
This line only fetches the "+ 0.000" Values and put them in a collection mc
MatchCollection mc = Regex.Matches(newVal, expr);
Now only the first element of this collection gets accessed with mc[0].Value (first "+ 0.000" value of the received data)
来源:https://stackoverflow.com/questions/35080188/c-sharp-read-serial-port-value-only-if-changed-weight-machine