i am receiving bytes from the serial port on my c# , and i am storing them in a byte array and then making them as string so now i need to convert the bytes to ASCII how i can do that? This is my code
void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
string bytestr = "";
int numbytes = serialPort1.BytesToRead;
byte[] rxbytearray = new byte[numbytes];
for (int i = 0; i < numbytes; i++)
{
rxbytearray[i] = (byte)serialPort1.ReadByte();
}
string hexvalues = "";
foreach (byte b in rxbytearray)
{
if (b != '\r')
hexvalues = hexvalues + (b.ToString()) + " ";
} // hexvalues = richTextBox1.Text;
Thread.Sleep(500);
MessageBox.Show(hexvalues);
}
Encoding.ASCII.GetString(byteArray);
I'd do it this way:
class SomeClass
{
private StringBuilder _sb = new StringBuilder();
private SerialPort serialPort1
[...]
void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
if (e.EventType == SerialData.Chars)
{
_sb.Append(serialPort1.ReadExisting());
}
else
{
MessageBox.Show(_sb.ToString());
_sb.Clear();
}
}
}
Related
I have a Barcode Weighing machine Sartorious BSA 4235 and it is connected to a serial port(COM). I am trying to display it in a text box in my winforms asp.net application. The data received is coming in the format N + 5.249 g . I need to get only the weight value. But when I am trying to extract only the weight, as the fluctuation of the weight is happening, and as I am replacing the string with decimal the value, the textbox is overwriting instead of only the last digit fluctuation similar to weighing scale. So the user is unable to finalize the weight. The fluctuation is happening at a faster rate. Here are the settings for the serial port:
Baud Rate:1200
Parity:None
Data Bits:7
Stop Bits:1
and Here is the code:
_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]);
}
}
}
}
}
This is untested and may need some syntactical correction, but try it:
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);
}
}
I have a program where i need to count how many females and Males are in the file that has been read into the richtextbox, but I'm not sure how to do that , in the file has the name, gender,specific job . I have to count between 15 different people
for example : " Donna,Female,Human Resources.",
This is what I have so far:
private void Form1_Load(object sender, EventArgs e)
{
StreamReader sr;
richTextBox1.Clear();
sr = new StreamReader("MOCK_DATA.txt");
string data;
while (!sr.EndOfStream)
{
data = sr.ReadLine();
richTextBox1.AppendText(data + "\n");
}
}
private void button1_Click(object sender, EventArgs e)
{
string[] data = richTextBox1.Text.Split(',');
for (int n = 0; n < data.Length; n++)
{
if (data[n] == richTextBox1.Text)
n++;
To get the plain text from a RichTextBox (stolen from this article):
string StringFromRichTextBox(RichTextBox rtb)
{
TextRange textRange = new TextRange(
// TextPointer to the start of content in the RichTextBox.
rtb.Document.ContentStart,
// TextPointer to the end of content in the RichTextBox.
rtb.Document.ContentEnd
);
// The Text property on a TextRange object returns a string
// representing the plain text content of the TextRange.
return textRange.Text;
}
Basic word counting routine:
int CountWord(string textToSearch, string word)
{
int count = 0;
int i = textToSearch.IndexOf(word);
while (i != -1)
{
count++;
i = textToSearch.IndexOf(word, i+1);
}
return count;
}
Putting it together:
var plainText = StringFromRichTextBox(richTextBox1);
var countOfMale = CountWord(plainText, "Male");
var countOfFemale = CountWord(plainText, "Female");
private void toolStripButton81_Click(object sender, EventArgs e)
{
string findterm = string.Empty;
findterm = toolStripTextBox2.Text;
// the search term - specific word
int loopCount = 0;
// count the number of instance
int findPos = 0;
// depending on checkbox settings
// whole word search or match case etc
try
{
while (findPos < GetRichTextBox().Text.Length)
{
if (wholeWordToolStripMenuItem.CheckState == CheckState.Checked & matchCaseToolStripMenuItem.CheckState == CheckState.Checked)
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.WholeWord | RichTextBoxFinds.MatchCase);
}
else if (wholeWordToolStripMenuItem.CheckState == CheckState.Checked)
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.WholeWord);
}
else if (matchCaseToolStripMenuItem.CheckState == CheckState.Checked)
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.MatchCase);
}
else
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.None);
}
GetRichTextBox().Select(findPos, toolStripTextBox2.Text.Length);
findPos += toolStripTextBox2.Text.Length + 1;
loopCount = loopCount + 1;
}
}
catch
{
findPos = 0;
}
// at the end bring the cursor at the beginning of the document
GetRichTextBox().SelectionStart = 0;
GetRichTextBox().SelectionLength = 0;
GetRichTextBox().ScrollToCaret();
// Show the output in statusbar
toolStripStatusLabel2.Text = "Instances: " + loopCount.ToString();
}
I'm designing an interface using C# windows Forms and I want to send and receive 1024 bits using serial port, the number I'm sending is in the hex-form, so what I did was the next:
private void button2_Click(object sender, EventArgs e)
{
int i;
int a = 0;
byte[] mychar;
mychar = new byte[128];
string M = textBox1.Text;
for (i = 0; i < 127; i++ )
{
mychar[i] = Convert.ToByte((M.Substring(a,2)),16);
a += 2;
}
serialPort1.Write(mychar,0,127);
}
and to check if the data is correct or not, I shorted out both the transmitter and receiver so I can see what I send from textbox1 to be shown in textbox5, the problem is the textbox is shown the output as ASCII, and I couldn't tell how to convert it to Hex form ,(see my attempt as commented bellow):
private void displaytext(object s, EventArgs e)
{
textBox5.Clear();
textBox5.AppendText(RXstring);
//int value = Convert.ToInt32(RXstring, 16);
//string stringValue = Char.ConvertFromUtf32(value);
//textBox4.AppendText(stringValue);
}
so to summarize my problems:
1- Is the code to send data is correct?
2- How can I force the textbox to show the output as Hex?
thank you very much.
UPDATE this is my full code, maybe then you understand my problem :
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;
namespace WindowsFormsApplication1
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
string RXstring = "";
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
RXstring = serialPort1.ReadExisting();
this.Invoke(new EventHandler(displaytext));
}
catch (System.TimeoutException)
{
}
}
private void displaytext(object s, EventArgs e)
{
textBox5.Clear();
textBox5.AppendText(RXstring);
//int value = Convert.ToInt32(RXstring, 16);
//string stringValue = Char.ConvertFromUtf32(value);
//textBox4.AppendText(stringValue);
}
private void pictureBox2_Click(object sender, EventArgs e)
{
serialPort1.Close();
Form1 myForm = new Form1();
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (!serialPort1.IsOpen)
{
serialPort1.Open();
button1.Enabled = false;
}
else
{
MessageBox.Show("Port is Open by other party!");
}
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form3_FormClosed(object sender, FormClosedEventArgs e)
{
serialPort1.Close();
}
private void button3_Click(object sender, EventArgs e)
{
textBox1.Text = "0";
textBox2.Text = "0";
textBox3.Text = "0";
textBox4.Text = "0";
textBox5.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
int i;
int a=0;
byte[] mychar;
mychar = new byte[128];
string M = textBox1.Text;
for (i = 0; i < 127; i++ ) {
mychar[i] = Convert.ToByte((M.Substring(a,2)),16);
a += 2;
}
serialPort1.Write(mychar,0,127);
}
}
}
when I send data from textbox1 I want to be shown exactly as I send it in textbox5, can you help me in that ?
https://drive.google.com/file/d/0B5PXKMhwKWQRREtuMXBaZDA1LUU/view?usp=sharing
This MCVE shows how to convert between bytes and hexadecimal strings:
class Program {
static void Main(string[] args) {
byte[] bytes = FromHexString("0123456789ABCEF");
string text = ToHexString(bytes);
Console.Write(text);
Console.ReadKey(true);
}
static byte[] FromHexString(string hexString) {
byte[] result;
//determine length and handle case of uneven digit count
int length = hexString.Length / 2;
bool even = length * 2 == hexString.Length;
if(!even) {
length++;
}
//allocate memory
result = new byte[length];
int offset;
if(even) {
offset = 0;
} else {
//convert first digit, if digit count is uneven
result[0] = Convert.ToByte(hexString[0].ToString(), 16);
offset = 1;
}
for(int i = offset; i < result.Length; i++) {
//convert digit to byte
result[i] = Convert.ToByte((hexString.Substring(i * 2 - offset, 2)), 16);
}
return result;
}
static string ToHexString(byte[] bytes, bool upperCase = true) {
string format = upperCase ? "X" : "x";
//initialize result with double capacity as a byte in hex notation occupies 2 chars
StringBuilder result = new StringBuilder(bytes.Length * 2);
foreach(var #byte in bytes) {
result.Append(#byte.ToString(format));
}
return result.ToString();
}
}
I just added the following to the code :
string hex = "";
foreach (char c in RXstring)
{
int tmp = c;
hex += String.Format("{0:X2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
}
textBox5.AppendText(hex);
thank you any way :)
I use this code to read from a weighting scale, I successfully read weight value from it but when trying to set the variable hex = "" for the next weight value I can't get it in the textbox, it appears very quickly and then disappears again, if I trace the program with the hex = "" enabled the results are as expected, but if run the program without trace it, then the blinking with the values and the textbox gets empty :( any ideas
string hex = "";
private delegate void Closure();
private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{
if (InvokeRequired)
{
BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); }));
}
else
{
if (_serialPort.BytesToRead > 0)
{
//hex = ""; <- Without this different weight values appears one after another. If applied then happens what explained above.
while (_serialPort.BytesToRead > 0) //<-- repeats until the In-Buffer is empty
{
hex += string.Format("{0:X2} ", _serialPort.ReadByte());
}
byte[] data = FromHex(hex.Trim());
textBox1.Text = Encoding.ASCII.GetString(data).Trim();
}
}
}
public byte[] FromHex(string aHex)
{
aHex = aHex.Replace(" ", "");
byte[] raw = new byte[aHex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(aHex.Substring(i * 2, 2), 16);
}
return raw;
}
This is the code to start listening:
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
/*--- OHAUS Ranger Count Config ---*/
//http://us.ohaus.com/us/en/home/support/faq.aspx
_serialPort = new SerialPort(comboBox1.Text);
_serialPort.BaudRate = 2400;
_serialPort.Parity = Parity.None;
_serialPort.DataBits = 7;
_serialPort.StopBits = StopBits.Two;
_serialPort.Handshake = Handshake.None;
/*--- End OHAUS Ranger Count Config ---*/
label1.Text = "Listening on " + _serialPort.PortName + "...";
_serialPort.DataReceived += SerialPortOnDataReceived; //<- Here I add the event
_serialPort.Open(); //<-- make the comport listen
}
Inside the method that is called when you press the print key, you can add the serial port event handler:
_serialPort.OnDataReceived+=SerialPortOnDataReceived;
Then, at the end of your SerialPortOnDataReceived method (after the successful read), remove the event handler from the serial port object. This will make it stop listening for new data on the serial port until you press print again.
private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{
if (InvokeRequired)
{
BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); }));
}
else
{
if (_serialPort.BytesToRead > 0)
{
//hex = ""; <- Without this different weight values appears one after another. If applied then happens what explained above.
while (_serialPort.BytesToRead > 0) //<-- repeats until the In-Buffer is empty
{
hex += string.Format("{0:X2} ", _serialPort.ReadByte());
}
byte[] data = FromHex(hex.Trim());
textBox1.Text = Encoding.ASCII.GetString(data).Trim();
_serialPort.OnDataReceived-=SerialPortOnDataReceived; // <---add this
}
}
}
This is how I update the UI thread.
delegate void SerialPortOnDataReceivedDelegate(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs);
private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{
if (InvokeRequired)
BeginInvoke(new SerialPortOnDataReceivedDelegate(SerialPortOnDataReceived), new object[] { sender, serialDataReceivedEventArgs });
else
{
if (_serialPort.BytesToRead > 0)
{
//hex = ""; <- Without this different weight values appears one after another. If applied then happens what explained above.
while (_serialPort.BytesToRead > 0) //<-- repeats until the In-Buffer is empty
{
hex += string.Format("{0:X2} ", _serialPort.ReadByte());
}
byte[] data = FromHex(hex.Trim());
textBox1.Text = Encoding.ASCII.GetString(data).Trim();
}
}
}
public byte[] FromHex(string aHex)
{
aHex = aHex.Replace(" ", "");
byte[] raw = new byte[aHex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(aHex.Substring(i * 2, 2), 16);
}
return raw;
}
This is what worked for me, I added some delay before hex = "", however I believe this is not a good practice though:
string hex = "";
private delegate void Closure();
private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{
if (InvokeRequired)
{
BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); }));
}
else
{
if (_serialPort.BytesToRead > 0)
{
Thread.Sleep(200); //<-- Add some delay
hex = "";
while (_serialPort.BytesToRead > 0) //<-- repeats until the In-Buffer is empty
{
hex += string.Format("{0:X2} ", _serialPort.ReadByte());
}
byte[] data = FromHex(hex.Trim());
textBox1.Text = Encoding.ASCII.GetString(data).Trim();
}
}
}
I have an application that reads XBee frames through the serial port and displays the frame in a richtextbox. It also displays the 2 analog channels (temperature Readings) in a chart and updates it in real time.
I was having issues that the application was reading the serial port faster than the bytes were coming in so I added this line:
while (comPort.BytesToRead < (inLength + 4)) Thread.Sleep(10);
That solved that problem but now I am unable to Close the serial port or quit the application without getting the message: "An unhandled exception of type 'System.InvalidOperationException' occurred in System.dll Additional information: The port is closed."
I am suspicious that it is a multithreading issue, but how do I solve it? I saw on a similar post that using BeginInvoke instead of Invoke should resolve the issue, but I am already using that.
Here is the code:
namespace SerialTest
{
public partial class frmMain : Form
{
delegate void SetTextCallback(string text);
delegate void SetChartCallback(double a, double b);
string inRawFrame = String.Empty;
double temp1 = 0;
double temp2 = 0;
public frmMain()
{
InitializeComponent();
}
private void btnGetSerialPorts_Click(object sender, EventArgs e)
{
if(btnGetSerialPorts.Text == "Open")
{
btnGetSerialPorts.Text = "Close";
comPort.PortName = Convert.ToString(cboPorts.Text);
comPort.BaudRate = Convert.ToInt32(cboBaudRate.Text);
comPort.ReadTimeout = 4000;
comPort.WriteTimeout = 6000;
if (!comPort.IsOpen)
{
try
{
comPort.Open();
cboPorts.Enabled = false;
cboBaudRate.Enabled = false;
}
catch(UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
}
}
else if (btnGetSerialPorts.Text == "Close")
{
btnGetSerialPorts.Text = "Open";
comPort.Close();
cboPorts.Enabled = true;
cboBaudRate.Enabled = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
string[] arrayComPortsNames = null;
int index = 0;
string comPortName = null;
arrayComPortsNames = SerialPort.GetPortNames();
Array.Sort(arrayComPortsNames);
while (!((arrayComPortsNames[index] == comPortName) || (index == arrayComPortsNames.GetUpperBound(0))))
{
cboPorts.Items.Add(arrayComPortsNames[index]);
index++;
}
comPortName = arrayComPortsNames[0];
cboPorts.Text = comPortName;
cboBaudRate.Items.Add(9600);
cboBaudRate.Items.Add(14400);
cboBaudRate.Items.Add(19200);
cboBaudRate.Items.Add(38400);
cboBaudRate.Items.Add(57600);
cboBaudRate.Items.Add(115200);
cboBaudRate.Items.ToString();
cboBaudRate.Text = cboBaudRate.Items[5].ToString();
}
private void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
byte[] incByte = new byte[3];
int length = 0;
if(comPort.BytesToRead > 3)
{
comPort.Read(incByte, 0, 3);
if (incByte[0] == 0x7E)
{
length = (incByte[1] << 8) + incByte[2];
byte[] buffer = new byte[length+4];
buffer[0] = incByte[0];
buffer[1] = incByte[1];
buffer[2] = incByte[2];
ReadFrame(buffer, length, DateTime.Now);
temp1 = ReadTemp(buffer, 1);
temp2 = ReadTemp(buffer, 2);
DisplayFrame();
UpdateChart();
}
}
}
private void ReadFrame(byte[] inBuffer, int inLength, DateTime time)
{
while (comPort.BytesToRead < (inLength + 4)) Thread.Sleep(10);
comPort.Read(inBuffer, 3, (inBuffer.Length - 3));
inRawFrame = time + " " + BitConverter.ToString(inBuffer).Replace("-", " ");
}
private void DisplayFrame()
{
if (rtbIncomingData.InvokeRequired)
{
rtbIncomingData.BeginInvoke(new SetTextCallback(SetText), new object[] { inRawFrame });
}
else
{
SetText(inRawFrame);
}
}
private void SetText(string text)
{
this.rtbIncomingData.AppendText(text + Environment.NewLine);
}
private double ReadTemp(byte[] data, int channel)
{
if(data[3] == 0x92)
{
if(channel == 1)
{
return ((((data[19] << 8) + data[20]) * 1.2 / 1023) - 0.5) * 100.0;
}
else
{
return ((((data[21] << 8) + data[22]) * 1.2 / 1023) - 0.5) * 100.0;
}
}
else
return 100;
}
private void UpdateChart()
{
if (chart1.InvokeRequired)
chart1.BeginInvoke(new SetChartCallback(SetChart), new object[] { temp1, temp2 });
else
SetChart(temp1, temp2);
}
private void SetChart(double val1, double val2)
{
chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Format = "HH:mm:ss";
chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineColor = Color.LightGray;
chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineColor = Color.LightGray;
chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Font = new Font("Consolas", 8);
chart1.ChartAreas["ChartArea1"].AxisY.LabelStyle.Font = new Font("Consolas", 8);
chart1.ChartAreas["ChartArea1"].AxisY.Maximum = 30;
chart1.ChartAreas["ChartArea1"].AxisY.Minimum = 10;
chart1.ChartAreas["ChartArea1"].AxisY.Interval = 1;
chart1.Series[0].Name = "Temp 1";
chart1.Series[1].Name = "Temp 2";
chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
chart1.Series[0].MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Diamond;
chart1.Series[0].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime;
chart1.Series[1].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
chart1.Series[1].MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Diamond;
chart1.Series[1].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime;
chart1.Series[0].Points.AddXY(DateTime.Now, val1);
chart1.Series[1].Points.AddXY(DateTime.Now, val2);
}
}
}
If you close the serial port while ReadFrame() is still waiting for bytes, you'll end up checking BytesToRead on a closed serial port. Maybe try this version instead:
private void ReadFrame(byte[] inBuffer, int inLength, DateTime time)
{
while (comPort.IsOpen)
{
if (comPort.BytestoRead >= inLength + 4)
{
comPort.Read(inBuffer, 3, (inBuffer.Length - 3));
inRawFrame = time + " " + BitConverter.ToString(inBuffer).Replace("-", " ");
return;
}
Thread.Sleep(10);
}
}
It will exit if the serial port closes while waiting for a frame, and only checks BytesToRead if the port is still open.