IOexception was unhandled through Arduino

94 views Asked by At

so I'm doing a project where one system transmits data via Arduino and Xbee and the receiving system receives data via Arduino and Xbee. At the receiving end, i'm sending the information to Visual Studios. So, when I press the stop button to stop receiving data i get IOException was unhandled. How do i solve this?

The error will point to line that I added comment below

My C# codes at the receiving end:

public Form1()
    {
        InitializeComponent();
    }

    private void start_btn_Click(object sender, EventArgs e)
    {
        myport = new SerialPort();
        myport.BaudRate = 9600;
        myport.PortName = port_name_tb.Text;
        myport.Parity = Parity.None;
        myport.DataBits = 8;
        myport.StopBits = StopBits.One;
        myport.DataReceived+=SerialDataReceivedEventHandler
        (myport_DataReceived);


        try
      {
        myport.Open();
        data_tb.Text = "";
      }
        catch (Exception ex)
      {
          MessageBox.Show(ex.Message, "Error");
      }
    }

    void myport_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        this.Invoke(new EventHandler(displaydata_event));
        in_data = myport.ReadLine();  //------> ERROR POINTED TO THIS LINE
    }

    private void displaydata_event(object sender, EventArgs e)
    {
        datetime = DateTime.Now;
        string date = datetime.Day + "/" + datetime.Month;
        string time = datetime.Hour + ":" + datetime.Minute + ":" 
         +      datetime.Second;
        data_tb.AppendText(date +" " +  time + "\t\t" + in_data + "\n");
    }

    private void stop_btn_Click(object sender, EventArgs e)
    {
        try
        {
            myport.Close();
        }

        catch (Exception ex2)
        {
            MessageBox.Show(ex2.Message, "Error");
        }

    }

    private void save_btn_Click(object sender, EventArgs e)
    {
        datetime = DateTime.Now;
        string date = datetime.Day + "/" + datetime.Month;
        string time = datetime.Hour + ":" + datetime.Minute + ":" 
         + datetime.Second;

        try
        {
            string pathfile = @"C:\Users\User\Desktop\Cdata\";
            string filename = "prototype.txt";
            System.IO.File.WriteAllText(pathfile + filename, data_tb.Text);
            MessageBox.Show("Data has been saved to " + pathfile);
        }
        catch (Exception ex3)
        {
            MessageBox.Show(ex3.Message, "Error");
        }
        }
      }
1

There are 1 answers

2
Mike Armstrong On

You're not catching an exception in your switch correctly, hence the unhandled IOException.

You can solve this by changing your catch from Exception to IOException exX& then doing something with that.