Problems when close port

106 Views Asked by At

I'm reading Arduino information into C# but when I want to stop reading the info by pressing the btnStop I always get " IOException was unhandled " why?

Error shown is commented below. The C# codes are as follows:

 public Form1()
    {
        InitializeComponent();
    }

    private void btnStart_Click(object sender, EventArgs e)
    {
        serialPort1.PortName = txtPortName.Text;
        serialPort1.BaudRate = 9600;
        serialPort1.Open();

        serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
        serialPort1.DataReceived += serialPort1_DataReceived;
    }

    void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            Data = serialPort1.ReadLine(); //----->>>ERROR SHOWN HERE
            this.Invoke(new EventHandler(displaydata_event));
        }
        catch (IOException ex5)
        {
            MessageBox.Show("ERROR:" + ex5);
        }
    }

    void displaydata_event(object sender, EventArgs e)
    {
        txtData.AppendText(Data + "\n");
    }

    private void btnStop_Click(object sender, EventArgs e)
    {
        try
        {
            serialPort1.Close();
        }
        catch (IOException ex2)
        {
            txtData.AppendText("Close error: " + ex2 + "\n");
        }
    }
}
0

There are 0 best solutions below