Example #1
0
        private void Form1_Load(object sender, EventArgs e)
        {
            card_read = false;

            serial = new SerialPort();
            //speech Sythesizer
            speechSynthesizerObj = new SpeechSynthesizer();

            LBL_Allergen.Text = start;
            //Auto Select Serial Port
            //Tries every availbe serial port on pc
            foreach (string p in SerialPort.GetPortNames())
            {
                //Set read timeout low to speed up auto conenct
                serial.ReadTimeout = 50;
                try
                {
                    //Mbed Returns 0 on ?
                    serial.PortName = p;
                    serial.Open();
                    Thread.Sleep(20);

                    Console.WriteLine("Trying Port " + p);
                    serial.WriteLine("?");

                    string test_return = serial.ReadLine();
                    int    t_return    = int.Parse(test_return);
                    if (t_return == 0)
                    {
                        Console.WriteLine("MBed Connected To " + p);
                        Messagebox.showdialog("MBed Connected To " + p);
                        break;
                    }
                    else
                    {
                        Console.WriteLine("Mbed Not Connected to " + p);
                        //if not connected close port before trying to connect
                        serial.Close();
                    }
                }
                catch (TimeoutException)
                {
                    //no return from ?
                    Console.WriteLine("Mbed Not Connected to " + p);
                }
                catch (InvalidOperationException)
                {
                    //port unavailbe
                    Console.WriteLine("Unable to open " + p);
                }
                catch (UnauthorizedAccessException)
                {
                    //Port already open
                    Console.WriteLine("Port " + p + " is Already Open");
                }
                catch (FormatException)
                {
                    //wrong value returned
                    Console.WriteLine("Parse Error");
                }
            }
            serial.ReadTimeout = 5000;
        }