C# Read serial port value only if changed (weight machine) -


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 weight machine connected serial port , displays in textbox. code works fine want change value of textbox if there change in weight ie. if value returned readexisting() differs previous value.(i don't want textbox fluctuated no reason)

when debug 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 big string

and textbox displays "+ 0.000" (continuously blinking)

you that:

void _serialport_datareceived(object sender, serialdatareceivedeventargs e) {    var newval = _serialport.readexisting();     if(string.compare(txtweight.text, newval) != 0)       txtweight.text = newval; } 

you change value of textbox if value differs previous one.

update
since "+ 0.000 s\r+ 0.000 s\r+ 0.000 s\r+ 0.000 s\r+ 0.000 s\r+ 0.000 s\r" need "+ 0.000" can use regex process 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 fetches "+ 0.000" values , put them in collection mc

matchcollection mc = regex.matches(newval, expr); 

now first element of collection gets accessed mc[0].value (first "+ 0.000" value of received data)


Comments