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.
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, 2022Comments
-
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 over 11 yearsWhat have you tried? mattgemmell.com/2008/12/08/what-have-you-tried
-
zmbq over 11 yearsWell, you open the COM port, configure it and send and receive.
-
user1703401 over 11 yearsThese 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 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 over 10 yearsGetPortNames doesn't enumerate normal USB ports.
-
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 à lawinusb.sys
, that would not be very helpful.