PlayHardGoPro PlayHardGoPro - 3 months ago 18
C# Question

How to get the BaudRate of the device?

I'd like to know if there is a way to get the

Baud Rate
when it's connected on the
RS232 port


BEFORE
you initialize the
SerialPort
class and set it's values. Let me try to explain the reason for that...

Today, I'm working with two different
RFID Reader
devices, each one works on a different
BaudRate
, so if I set a wrong
baudrate
when I create the
SerialPort
class, it will read the card id all wrong, instead get the real card's id, it will get something like
????|W2???
.

Also, there's a possibilite that the device have a
USB
port.

That's why I'd like to know the device's
baud rate
before I instantiate the
SerialPort
class.

Answer

I tried for my serial usb devices. Keep changing the baud rate and check. ComboBox contains series of possible baudrates.

    public void initConfig(SerialPort serialPort)
    {
        // you can assign these values in a combo box
        string[] ports= "{COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8"};

        //you can assign these values in a combo box in a string format
        int[] baudRate = { 4800, 9600, 19200, 38400, 57600, 115200, 230400 };

        serialPort.PortName = ports[0]; //else get from combobox  : portCombobox.SelectedItem
        serialPort.BaudRate = baudRate[0];
        //serialPort.BaudRate = Int32.Parse(speedComboBox.SelectedItem.ToString());

        //you can have controls to store and change these values if required
        serialPort.Handshake = System.IO.Ports.Handshake.None;
        serialPort.Parity = System.IO.Ports.Parity.None;
        serialPort.DataBits = 8;
        serialPort.StopBits = System.IO.Ports.StopBits.One;
        serialPort.ReadTimeout = 200;
        serialPort.WriteTimeout = 50;
    }

change the strings into respective types and call open.

finally:

    public void callingMethod() //or your connect event attached control
    {
        SerialPort serialPort = new SerialPort();

        initConfig(serialPort);

        try
        {
            serialPort.Open();
        }
        catch
        {
            MessageBox.Show("Error: Unable to Open the serial interface !");
            return;
        }
    }