How to catch a disconnected serial port?

colinodowd

Member
Joined
Jan 23, 2020
Messages
12
Programming Experience
1-3
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!

C#:
  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:

C#:
    private void ErrorReceivedHandler(object sender, SerialErrorReceivedEventArgs e)
    {
        Invoke(new Action(() =>
        {
            this.BackColor = Color.Red;
        }));
    }
 
It's not going to be instantaneous. That event only gets fired when an error is detected. Usually errors are detected when a read or write operation is done and it fails.
 
@Skydiver Are you suggesting that my form will eventually turn red? Am I using the ErrorReceivedHandler in the correct way for what I am trying to detect or is there a better solution?

Ideally, i would use something as simple as but I don't know if anything like that exists:

C#:
if (portArduino.IsConnected()) {
     do this;
} else {
     do that;
}
 
I'd run that in a loop on a new thread and if it ever fails, I would invoke the UI to reflect the error or port being disconnected.

Where do you think an event handler should be created and raised should an error happen?
 
@Sheepings I am not sure what you mean by run the loop in a new thread.

I assumed it would just be made after the port is opened similar to what I did with the DataReceived handler. I then complete more actions in the Handler function like this:
The same thing is not working for the ErrorReceived handler though.

C#:
   private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {

            if (isConnectedArduino)
            {
                try
                {
                    incoming_data = portArduino.ReadLine();
                    portArduino.Write(travel_command);
                }
                catch (Exception e1)
                {

                }
            }
            else
            {
                incoming_data = portMotor.ReadLine();
            }

            // this is executing on a separate thread - so throw it on the UI thread
            Invoke(new Action(() =>
            {
                textBox3.Text += incoming_data;
                textBox3.AppendText(Environment.NewLine);
                deactivate_event(incoming_data);
                RFID_reader(incoming_data);
                chart_setup(incoming_data);
                xlxs_builder(incoming_data);

            }));

        }
 
Back
Top Bottom