I have an application in Visual studio, reading value from serial port and drawing it on a chart. Everything goes perfecly fine, but when I click a close button on the application (or serial port disconnect button), an error occurs:"IOException() was unhandled", and the program highlights the serial1.Readline() command. How can I handle the exception?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Windows.Forms.DataVisualization.Charting;
namespace usart3
{
public partial class OknoGlowne : Form
{
public OknoGlowne()
{
string[] mojePorty = SerialPort.GetPortNames();
InitializeComponent();
foreach (string port in mojePorty)
{
cmbPorty.Items.Add(port);
}
cmbBaud.Items.Add(2400);
cmbBaud.Items.Add(9600);
cmbBaud.Items.Add(19200);
btnRozlacz.Enabled = false;
}
private volatile string rxString;
//private byte[] rxByte;
private Object thisLock = new Object();
Boolean i = false;
private void btnPolacz_Click(object sender, EventArgs e)
{
i = true;
serialPort1.PortName = cmbPorty.Text;
serialPort1.BaudRate = Convert.ToInt32(cmbBaud.Text);
serialPort1.Parity = Parity.None;
serialPort1.StopBits = StopBits.One;
serialPort1.DataBits = 8;
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
serialPort1.Open();
btnPolacz.Enabled = false;
btnRozlacz.Enabled = true;
}
int rt = 0;
private void btnRozlacz_Click(object sender, EventArgs e)
{
serialPort1.Close();
btnPolacz.Enabled = true;
btnRozlacz.Enabled = false;
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
rt++;
rxString = serialPort1.ReadLine();
this.Invoke(new EventHandler(displayText));
}
private void displayText(object o, EventArgs e)
{
richTextBox1.AppendText(rxString);
this.chart1.Series["Temperatura"].Points.AddXY(rt, rxString);
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Form2 nowy = new Form2();
nowy.Show();
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
}
private void Start2_Click(object sender, EventArgs e)
{
Form2 nowy = new Form2();
nowy.Show();
}
private void button1_Click_1(object sender, EventArgs e)
{
Form2 nowy = new Form2();
nowy.Show();
}
}
}
I had similar issue.
The IOExcpection is kind of confusing because accordingly to the documentation ReadLine() is not supposed to throw this type of exception. The problem is that ReadLine is in a state of waiting for an EOL character when we close the port. Closing the port stops the thread holding ReadLine in an unsupported state.
For me the solution was to follow this port closure sequence:
Unsubscribe data_reciver method from the port.
Send a port.WriteLine("get serial number") command. The goal is to trig an EOL character in the input_buffer. This will release ReadLine.
Wait until EOL is recieved.
Close the port.
Surround your call with a try/catch block. In the catch you should code in way that you can handle the error by doing something else.
try {
rxString = serialPort1.ReadLine();
} catch (IOException e) {
// or do something else
}
EDIT:
try {
rt++;
rxString = serialPort1.ReadLine();
this.Invoke(new EventHandler(displayText));
} catch (IOException e) {
MessageBox.Show("Connection is lost");
}
I'm trying to create a simple GUI implementation of the ping program. I have a form which is just a text box textBox1 where users enter the IP as a string, press a button Ping, and the result of the ping is displayed in a label label1. For some reason the text wont show up when I run the program.
Code partially taken from Ping.SEndAsync:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Net.NetworkInformation;
using System.Net;
namespace pinger
{
public partial class Form1 : Form
{
private string address;
private string response;
private PingReply reply;
//public string response;
private void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
if (e.Cancelled)
((AutoResetEvent)e.UserState).Set();
if (e.Error != null)
((AutoResetEvent)e.UserState).Set();
reply = e.Reply;
((AutoResetEvent)e.UserState).Set();
if (reply == null)
return;
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
address = IPtextbox.Text;
}
private void Ping_click(object sender, EventArgs e)
{
AutoResetEvent waiter = new AutoResetEvent(false);
Ping pingSender = new Ping(); //creates a new 'pingSender' Ping object
pingSender.PingCompleted +=
new PingCompletedEventHandler(PingCompletedCallback);
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 1000;
pingSender.SendAsync(address, timeout, buffer, waiter);
}
private void label1_Click(object sender, EventArgs e)
{
label1.Text = "the ping was: " + reply.Status.ToString();
Show();
Refresh();
}
}
}
According to your code you label only changes it's text when you click on it. label1_Click event is raised.
PingCompleted event to get information about the completion status and data collected by a call to the SendAsync methods. In it you can change your label text with the result of the ping.
Add all the code inside label1_Click to PingCompletedCallback method as follows;
private void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
if (e.Cancelled || e.Error != null)
((AutoResetEvent)e.UserState).Set();
reply = e.Reply;
if (reply == null)
return;
//Change the label here
label1.Text = "the ping was: " + reply.Status.ToString();
Show();
Refresh();
}
I am developing weight scale program by serial port communication
but I have do like this.... example:
use put item on scale when my
app get weight then stop comunicate with scale first get weight set on
gridviewrowcolumn then row change automatically and when user put
second item on scale comunication start and same procedure do..
here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
namespace serial
{
public partial class Form1 : Form
{
private SerialPort _serialPort; //<-- declares a SerialPort Variable to be used throughout the form
private const int BaudRate = 9600;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
#region Form Load
try
{
//getRawWeight();
string[] portNames = SerialPort.GetPortNames(); //<-- Reads all available comPorts
foreach (var portName in portNames)
{
comboBox1.Items.Add(portName); //<-- Adds Ports to combobox
}
comboBox1.SelectedIndex = 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
#endregion
}
private void button1_Click(object sender, EventArgs e)
{
if (_serialPort != null && _serialPort.IsOpen)
_serialPort.Close();
if (_serialPort != null)
_serialPort.Dispose();
//<-- End of Block
_serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 8, StopBits.One); //<-- Creates new SerialPort using the name selected in the combobox
_serialPort.DataReceived += SerialPortOnDataReceived; //<-- this event happens everytime when new data is received by the ComPort
_serialPort.Open(); //<-- make the comport listen
textBox1.Text = "Listening on " + _serialPort.PortName + "...\r\n";
}
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 reading = "";
reading += string.Format("{0:X2} ", _serialPort.ReadByte());
//<-- bytewise adds inbuffer to textbox
//string reading = System.Text.Encoding.UTF8.GetString(_serialPort);
textBox1.Text = reading.Substring(13);
}
}
}
}
}
I would open the serial port once and then leave it open until you close your program. Have you successfully communicated with the scale yet? Also some devices like scales have their own button that will send data across the serial port each time you push it. What is wrong with your code? What does it do as it is written?
i am develop application for getting weight from weigh Bridge machine using C#.Net.i am trying lot of ways but,doesn't read correct data format weight from weigh bridge machine.i am getting ouput like ?x???????x?x?x??x???x??x???x???x? continuously get from serial port.i want to get weight from weigh bridge machine my code is listed below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
namespace SerialPortTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String a = "";
private void button1_Click(object sender, EventArgs e)
{
serialPort1 = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
if (serialPort1.IsOpen == false)
{
serialPort1.Open();
}
timer1.Start();
button1.Enabled = false;
button2.Enabled = true;
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
a = a + serialPort1.ReadExisting();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (a.Length != 0)
{
textBox1.AppendText(a);
a = "";
}
}
private void button2_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen == true)
{
serialPort1.Close();
button2.Enabled = false;
button1.Enabled = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
if (serialPort1.IsOpen == true)
{
button1.Enabled = false;
button2.Enabled = true;
}
else
{
button1.Enabled = true;
button2.Enabled = false;
}
}
}
}
my code is append text from serial port data to textbox but,it's shows only like ?xxx?xxxx?xxxx?
can any one help me how to get weight from serial port using c#
Thanks For Reading My Post!
You are using ReadExisting(), that method tries to convert the bytes received by the port into a string. You'll get a question mark if that conversion fails. The default Encoding is ASCII, a byte value between 128 and 255 is not an ASCII character and thus produces a ?
Several possible reasons, roughly in order of likelihood:
Using the wrong baud rate, in particular guessing too high.
The device might be sending binary data, not strings. Which requires using Read() instead of ReadExisting and decoding the binary data.
Electrical noise picked up by a long cable that isn't shielded well enough. Easy to eliminate as a possible reason by disconnecting the cable at the bridge end. If that stops the data then it isn't likely to be noise.
Be sure to thoroughly read the manual. Contact the vendor of the device if you don't have one or can't make sense of it.
This code will be reading weightbridge continuously in background. Be sure to connect the pc with serial port. Also in design page Form1.cs[Design] you need to add Serial port from the toolbox. This code works for me, I hope it works for you too...
public partial class Form1 : Form
{
//Initialize the port and background Worker
private SerialPort port;
private BackgroundWorker backgroundWorker_Indicator;
public Form1()
{
backgroundWorker_Indicator = new BackgroundWorker();
backgroundWorker_Indicator.WorkerSupportsCancellation = true;
backgroundWorker_Indicator.DoWork += new DoWorkEventHandler(Indicator_DoWork);
//set the port according to your requirement.
port = new SerialPort("COMM2", 2400, Parity.None, 8, StopBits.One);
port.DataReceived += new SerialDataReceivedEventHandler(this.Indicator_DataReceived);
}
//button which starts the method. You can also put the method in Form1_Load()
private void SerialPortButton(object sender, EventArgs e)
{
StartStopIndicator();
}
private void StartStopIndicator()
{
try
{
port.Open();
backgroundWorker_Indicator.RunWorkerAsync();
}catch (Exception ea)
{
MessageBox.Show("13 "+ea.Message);
}
}
// Not a button. Just a methood.
private void Indicator_DoWork(object sender, DoWorkEventArgs e)
{
}
private void Indicator_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
string str = StripNonNumeric(port.ReadLine());
UpdateWeightOnUI(str);
}
catch (Exception eb)
{
MessageBox.Show("12"+eb.Message);
}
}
private void UpdateWeightOnUI(string Weight)
{
try
{
// A label named weightLabel from the toolbox. This will keep updating on weight change automatically
if (weightLabel.InvokeRequired)
{
this.Invoke((Delegate)new Form1.SetTextCallBack(this.UpdateWeightOnUI), (object)Weight);
}
else
{
weightLabel.Text = Weight;
}
}
catch (Exception ec)
{
MessageBox.Show("11"+ec.Message);
}
}
// This method will remove all other things except the integers
private string StripNonNumeric(string original)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (char c in original)
{
if (char.IsDigit(c))
stringBuilder.Append(c);
}
return stringBuilder.ToString();
}
private delegate void SetTextCallBack(string text);
I've been assigned to display weight from weighing scale (CAS CI-201A) into a textbox using C#. The weight will be sent via serial port RS-232 or USB converter. The scale is with me but I don't know where to start. How can I achieve my goal?
Have you tried anything yet?
If you want to use the serial port it makes sense to first give the user a way to select which port to use. This can be done easily, by filling a combobox with all available ports.
private void Form1_Load(object sender, EventArgs e)
{
string[] portNames = SerialPort.GetPortNames();
foreach (var portName in portNames)
{
comboBox1.Items.Add(portName);
}
comboBox1.SelectedIndex = 0;
}
This code uses a form with a comboBox on it, called "comboBox1" (Default).
You will need to add:
using System.IO.Ports;
to the using directives.
Then add a button (button1) and a multiline textbox (textbox1) to the form and add this code:
private void button1_Click(object sender, EventArgs e)
{
_serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 8, StopBits.One);
_serialPort.DataReceived += SerialPortOnDataReceived;
_serialPort.Open();
textBox1.Text = "Listening on " + comboBox1.Text + "...";
}
private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{
while(_serialPort.BytesToRead >0)
{
textBox1.Text += string.Format("{0:X2} ", _serialPort.ReadByte());
}
}
This also requires you to add:
private SerialPort _serialPort;
private const int BaudRate = 9600;
right below the opening brackets of
public partial class Form1 : Form
After clicking the button, all received data from the selected comPort will be displayed as hex values in the TextBox.
DISCLAIMER: The above code contains NO error-handling and will produce errors if button1 is clicked multiple times, due to the fact that the previous instance of "SerialPort" is not closed properly. Please remember this when using this example.
Regards Nico
Complete Code:
using System;
using System.IO.Ports; //<-- necessary to use "SerialPort"
using System.Windows.Forms;
namespace ComPortTests
{
public partial class Form1 : Form
{
private SerialPort _serialPort; //<-- declares a SerialPort Variable to be used throughout the form
private const int BaudRate = 9600; //<-- BaudRate Constant. 9600 seems to be the scale-units default value
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] portNames = SerialPort.GetPortNames(); //<-- Reads all available comPorts
foreach (var portName in portNames)
{
comboBox1.Items.Add(portName); //<-- Adds Ports to combobox
}
comboBox1.SelectedIndex = 0; //<-- Selects first entry (convenience purposes)
}
private void button1_Click(object sender, EventArgs e)
{
//<-- This block ensures that no exceptions happen
if(_serialPort != null && _serialPort.IsOpen)
_serialPort.Close();
if (_serialPort != null)
_serialPort.Dispose();
//<-- End of Block
_serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 8, StopBits.One); //<-- Creates new SerialPort using the name selected in the combobox
_serialPort.DataReceived += SerialPortOnDataReceived; //<-- this event happens everytime when new data is received by the ComPort
_serialPort.Open(); //<-- make the comport listen
textBox1.Text = "Listening on " + _serialPort.PortName + "...\r\n";
}
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
{
textBox1.Text += string.Format("{0:X2} ", _serialPort.ReadByte());
//<-- bytewise adds inbuffer to textbox
}
}
}
}
}
Based on this:
Listening on COM1... 30 30 33 33 20 49 44 5F 30 30 3A 20 20 20 31 30
2E 36 20 6B 67 20 0D 0A 0D 0A
Being the ASCII for this:
0033 ID_00: 10.6 kg
You can get the result by trimming the received string. Assuming your listener puts the bytes into an array byte[] serialReceived :
string reading = System.Text.Encoding.UTF8.GetString(serialReceived);
textBox1.Text = reading.Substring(13);
Firstly, before you start to code anything, I would check whether you're using the right cable. Try open a serial terminal of your choice (HyperTerm, putty) and check whether there is any data at all.
Be sure to configure the same baudrate, stopbits and parity on both the weight scale and your terminal program.
If you receive data (the terminal program should at least display some garbage), then you can move on to coding. If not, check if you're using the right cable (nullmodem aka crossed-over).
When you're this far, then you may use the SerialPort class of C#
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx
based on adam suggestion i converted the output to human readable format ( from ASCII to UTF8 )
i puts the bytes into an array byte[]
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
{
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);
textBox1.Text = str.ToString();
}
}
here is the full working code
using System;
using System.IO.Ports; //<-- necessary to use "SerialPort"
using System.Windows.Forms;
namespace ComPortTests
{
public partial class Form1 : Form
{
private SerialPort _serialPort; //<-- declares a SerialPort Variable to be used throughout the form
private const int BaudRate = 9600; //<-- BaudRate Constant. 9600 seems to be the scale-units default value
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] portNames = SerialPort.GetPortNames(); //<-- Reads all available comPorts
foreach (var portName in portNames)
{
comboBox1.Items.Add(portName); //<-- Adds Ports to combobox
}
comboBox1.SelectedIndex = 0; //<-- Selects first entry (convenience purposes)
}
private void button1_Click(object sender, EventArgs e)
{
//<-- This block ensures that no exceptions happen
if(_serialPort != null && _serialPort.IsOpen)
_serialPort.Close();
if (_serialPort != null)
_serialPort.Dispose();
//<-- End of Block
_serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 8, StopBits.One); //<-- Creates new SerialPort using the name selected in the combobox
_serialPort.DataReceived += SerialPortOnDataReceived; //<-- this event happens everytime when new data is received by the ComPort
_serialPort.Open(); //<-- make the comport listen
textBox1.Text = "Listening on " + _serialPort.PortName + "...\r\n";
}
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
{
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);
textBox1.Text = str.ToString();
}
}
}
if your are using A&D EK V Calibration Model : AND EK-610V. you have use BaudRate = 2400; and DataBits = 7
Note : if you get output like this
you have to check the BaudRate,DataBits (refer your weighing machine manual ) or check your cable
I was using Anto sujesh's Code, but I had the problem that some of the values I got from the scale were corrupted. I solved it by buffering the values in a cache file.
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
{
int dataLength = _serialPort.BytesToRead;
byte[] data = new byte[dataLength];
int nbrDataRead = _serialPort.Read(data, 0, dataLength);
if (nbrDataRead == 0)
return;
string str = Encoding.UTF8.GetString(data);
//Buffers values in a file
File.AppendAllText("buffer1", str);
//Read from buffer and write into "strnew" String
string strnew = File.ReadLines("buffer1").Last();
//Shows actual true value coming from scale
textBox5.Text = strnew;
using System;
using System.IO.Ports;
using System.Windows.Forms;
namespace ComPortTests
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SerialPort _serialPort = null;
private void Form1_Load(object sender, EventArgs e)
{
_serialPort = new SerialPort("COM1", 9600, Parity.None, 8);
_serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);
_serialPort.Open();
}
void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string data = _serialPort.ReadExisting();
textBox2.Text = data;
}
}
}
using System;
using System.IO;
using System.IO.Ports;
namespace comport
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SerialPort _serialPort = null;
private void Form1_Load(object sender, EventArgs e)
{
AppConfiguration.sConfigType = "default";
_serialPort = new SerialPort("COM1", 9600, Parity.None, 8);
_serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);
_serialPort.Open();
}
void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string data = _serialPort.ReadExisting();
textBox2.Text = data;
}
}
}
I am using
yaohua xk3190-a9
Weighing Scale indicator connected to my serial port. And after trying lots of codes, follwing code finally worked for me. I am pasting the code here so that if anybody is using the same device can get help.
private SerialPort _serialPort;
private const int BaudRate = 2400;
private void Form1_Load(object sender, EventArgs e)
{
string[] portNames = SerialPort.GetPortNames();
foreach (var portName in portNames)
{
comboBox1.Items.Add(portName);
}
comboBox1.SelectedIndex = 0;
//<-- This block ensures that no exceptions happen
if (_serialPort != null && _serialPort.IsOpen)
_serialPort.Close();
if (_serialPort != null)
_serialPort.Dispose();
//<-- End of Block
_serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 7, StopBits.One); //<-- Creates new SerialPort using the name selected in the combobox
_serialPort.DataReceived += SerialPortOnDataReceived; //<-- this event happens everytime when new data is received by the ComPort
_serialPort.Open(); //<-- make the comport listen
}
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
{
string data = _serialPort.ReadExisting();
if (data != null)
{
if (data.ToString() != "")
{
if (data.Length > 6)
{
var result = data.Substring(data.Length - 5);
textBox1.Text = result.ToString().TrimStart(new Char[] { '0' });
}
}
}
}
}