C# Serial Communication

26,905

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.

Share:
26,905
Mohammad Adib
Author by

Mohammad Adib

Email: [email protected] Facebook: http://fb.com/mohammad.a.adib Programming languages: Java, C# Occupation: Robotic Engineer at Wicresoft Workspace: Core i7-3770k @ 4.7ghz, 16gb RAM @ 1875mhz

Updated on July 10, 2022

Comments

  • Mohammad Adib
    Mohammad Adib almost 2 years

    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
    • xxbbcc
      xxbbcc over 11 years
    • zmbq
      zmbq over 11 years
      Well, you open the COM port, configure it and send and receive.
    • user1703401
      user1703401 over 11 years
      These settings only make sense if you actually connect to hardware through a physical serial port. The chip is called a UART, Universal Asynchronous Receiver and Transmitter. With a USB emulator it makes no difference whatsoever, the bus protocol doesn't require this kind of config.
    • kshitij Sabale
      kshitij Sabale over 11 years
      @HansPassant, these settings are still very critical for a USB device that contains a UART. There is no indication that he is using a USB device that does not contain a UART, and even then, the settings may still be enforced. Some Symbol/Motorola USB scanners, which present themselves as serial ports, still require 9600/8/N/1 even though they are virtual ports.
  • Karlth
    Karlth over 10 years
    GetPortNames doesn't enumerate normal USB ports.
  • kshitij Sabale
    kshitij Sabale over 10 years
    @user357320, GetPortNames will enumerate any device which presents itself as a COM port. If the USB device does not present itself as a COM port, then it will not show up. You'd need SetupDiEnumDeviceInterfaces to get all USB devices, but unless you are writing a custom driver à la winusb.sys, that would not be very helpful.