How to catch a disconnected serial port in c#?

  • Thread starter Thread starter colinodowd
  • Start date Start date
C

colinodowd

Guest
So I have a C# windows form application with a GUI that allows me to connect to an Arduino via a Bluetooth Serial connection and I want to turn the GUI background RED when the connection is broken.

I have created an ErrorHandler in my connectToArduino function but it does not seem to be working properly. When I pull the power on the Arduino, the GUI does not turn red!

private void connectToArduino()
{
string selectedPort = comboBox1.GetItemText(comboBox1.SelectedItem);
portArduino =
new SerialPort(selectedPort, 9600, Parity.None, 8, StopBits.One);
portArduino.
RtsEnable = true;
portArduino.
DtrEnable = true;

try
{
portArduino.
Open();
isConnectedArduino =
true;
}
catch (Exception e)
{
label8.
Text = "Connection to Micro Failed. Try Again";
}

portArduino.
DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
portArduino.
ErrorReceived += new SerialErrorReceivedEventHandler(ErrorReceivedHandler);

button1.
Text = "Disconnect";
enableControlsArduino();
}


Error Handler:

private void ErrorReceivedHandler(object sender, SerialErrorReceivedEventArgs e)
{
Invoke(new Action(() =>
{
this.BackColor = Color.Red;
}));
}


Continue reading...
 
Back
Top