Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Serial Communication

How do I go about sending and receiving data from a USB comm port using C#?

The requirements for communication are:

  • 115.2 kBaud
  • 8-bit character size
  • 1 stop bit
  • No parity
like image 792
Mohammad Adib Avatar asked Feb 04 '26 22:02

Mohammad Adib


1 Answers

A USB comm port appears to the system the same as an onboard port. Use the SerialPort class.

    using (var sp = new System.IO.Ports.SerialPort("COM11", 115200, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One))
    {
        sp.Open();

        sp.WriteLine("Hello!");

        var readData = sp.ReadLine();
        Console.WriteLine(readData);
    }

You can find the available ports by calling SerialPort.GetPortNames. If that doesn't appeal to you, you can also access the port as a file, but that is much more complex and there are few reasons to do so. See the documentation for CreateFile for more.

like image 179
Mitch Avatar answered Feb 06 '26 12:02

Mitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!