views:

264

answers:

2

Hi,

When opening a serial port, the device I am trying to access may not have a baudrate of 9600 set so I will have to go thru each baudrate until the device opens correctly.

What error, ArgumentOutOfRangeException or an IOException or some other, should I look for after performing the Port.Open ? Or do I perform this check using the PortOpen statement ?

Sorry to have to ask all of these simple questions, but I am unsure how else to get the information ?

Is there any way that I can tell how to use the PortOpen procedures correctly, including the error handling too, so that I dont have to keep asking everyone ?

Thanks, George.

+1  A: 

IOException InvalidOperationException

is what You should receive in case of errors.

Here You have great example in C#: http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.open.aspx

You could find all exceptions explanation down there.

bua
A: 

For more general advice, have a look at the System.IO.Ports namespace which has a more complete example. Personally I'd adapt what they have there to set your general port settings and then try a few different baud rates in debug mode (some bad, one known good). You'll very quickly see what a bad configuration gives vs a good one. I'm assuming you have access to test the device here?

It's worth noting that you won't see any problems with the call to open the port (just opening it will only test that you've set some parameters which the port supports). You'll start to see issues when you try and read/write to the device and it's there that you'll want to do the error checking for a valid baud rate.

[EDIT] Try something along these lines (NOTE: I've not tested this with any hardware but it at least compiles):

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO.Ports;

namespace SerialPortExperiments
{
    class Program
    {
        public static void Main()
        {
            // Create a new SerialPort object with default settings.
            SerialPort _serialPort = new SerialPort();
            // Set some generic settings
            SetBasicSettings(ref _serialPort);
            // Try and find something valid
            int baudRate = FindValidBaud(ref _serialPort);
            if (baudRate > 0)
            {
                Console.WriteLine(String.Format("Found baudrate: {0}", baudRate));
            }
            else
            {
                Console.WriteLine("ERROR: Failed to identify baudrate");
            }
        }


        public static void SetBasicSettings(ref SerialPort port)
        {
            port.PortName = "COM1";
            port.Parity = Parity.None;
            port.DataBits = 8;
            port.StopBits = 0;
            port.Handshake = Handshake.None;
            port.ReadTimeout = 500;
            port.WriteTimeout = 500;
        }

        public static int FindValidBaud(ref SerialPort port)
        {
            bool buadrateIdentified = false;

            // Pick some baudrates to try
            List<int> baudrates = new List<int>();
            baudrates.Add(9600);
            baudrates.Add(19200);

            // Try and open the port at each baud rate in turn, trying one write/read to verify success
            for (int i = 0; i < baudrates.Count; i++)
            {
                // Pick a baud rate
                port.BaudRate = baudrates[i];

                // Try opening a connection and exchanging some data
                port.Open();
                buadrateIdentified = AttemptValidExchange(ref port);
                port.Close();

                if (buadrateIdentified)
                {
                    return port.BaudRate;
                }
            }

            return -1;
        }

        public static bool AttemptValidExchange(ref SerialPort port)
        {
            try
            {
                // Send a test command
                port.Write("SOME_TEST_COMMAND");

                // Check to see what the device responded with
                const int expectedReturnLength = 1024;
                byte[] buffer = new byte[expectedReturnLength];
                port.Read(buffer, 0, expectedReturnLength);
                if (buffer.ToString().Equals("EXPECTED_RETURN_VALUE"))
                {
                    return true;
                }
            }
            catch (TimeoutException) // NOTE: You'll probably need to catch other exceptions like parity errors here
            {
            }

            return false;
        }
    }
}
Jon Cage
Hi Jon,Thanks for that.Yes I have access to the unit to test.I will let you know the outcome.Thanks, George.
George