0

I am having trouble communicating with a serial device. I am having trouble determining with the baud rate should be. The documentation says signaling rate is 38400 bit/sec.

Here is the documentation for the serial port.

Documentation

How does this translate to the .NET SerialPort class?

using (var port = new SerialPort("COM16"))
{
    port.BaudRate = 9800;       // ??
    port.Parity = Parity.Even;  // ??

    // anything else? anything wrong?

    port.Open(); //go!
}
Paul Knopf
  • 9,568
  • 23
  • 77
  • 142
  • Improperly they are considered to be equivalent. 1 baud/s == 1 bit/s, 38400 bauds/s == 38400 bits/s. **improperly**! – xanatos Mar 23 '15 at 13:23
  • @xanatos, even with the even parity? – Paul Knopf Mar 23 '15 at 13:40
  • Why would you set Baudrate = 9800 when the docs say 38400??? Set the StopBits, DataBits and Handshake properties as well. – Hans Passant Mar 23 '15 at 13:46
  • @HansPassant, I thought the baud rate was different than the bits per-second, because it may take more than one bit (start/stop/parity) to describe a single 8-bit byte. No? http://electronics.stackexchange.com/questions/117241/baud-rate-calculation – Paul Knopf Mar 23 '15 at 14:58
  • @HansPassant, also, I'm not typically a serial/com developer. I can write/read bytes all day, but I don't understand modem communication enough to translate the documents correctly to the .NET SerialPort type. – Paul Knopf Mar 23 '15 at 15:00

1 Answers1

0

If you don't want to put all of your code in the using block, you can close the port explicitly at the end.

SerialPort port = new SerialPort();
port.PortName = "COM16";
port.BaudRate = 38400; // Baud rate = bits per second
port.DataBits = 8; // unnecessary as 8 is the default
port.Parity = Parity.Even; // unnecessary as Even is the default
port.StopBits = StopBits.One; // unnecessary as One is the default

If you still can't connect, try connecting with Termite, which is a serial port terminal program. If you have to choose settings like "DTR/DTS" to get it to work, then you might need settings like this:

port.DtrEnable = true;
port.RtsEnable = true;

Then open your port.

port.Open();

port.DataReceived += OnRx; // Add the event handler for receiving data

The easiest way to read asynchronously is to create an event handler and pass the data back to a variable that the method has access to.

List<string> rx = new List<string>(); // the event handler stores the received data here

// Add this method to your class to read asynchronously.
protected void OnRx(object sender, SerialDataReceivedEventArgs e) {
    while (port.BytesToRead > 0) {
        try {
            rx.Add(port.ReadLine());
        } catch (Exception) { }    
    }
}

Close your port

port.Close();

Also check out the SerialPort documentation.