简体   繁体   中英

How to read USB serial input in a cross-platform way in C?

I'm trying to read serial input from a USB device with 9600 baud into a C program, but I'm not sure how to go about this. The program input will be really simple. I have a circuit set up with a potentiometer and its sending the voltage value every second over the USB.

How do I read this into a C program being developed on Windows? I'd prefer something cross-platform if possible.

You can either do something like this in your code to write seperate functions for Linux and windows...

#ifdef __unix__         
...
#elif defined(_WIN32) || defined(WIN32) 

#define OS_Windows

#endif

Or search for C libraries for cross-platform serial communication, here is one I found for C++ in one google search https://github.com/wjwwood/serial .

I assume you are using arduino-like device, which can be easily configured to output serial data over USB. See a tutorial on the subject.

USB is not as simple as legacy serial ports and USB devices will need drivers. Class compliant devices are usually supported directly by operating system, see USB device classes , at least to some extent.

For example, if you are using Arduino, the simple way is to install FTDI drivers ( see their website ) and use the virtual COM port provided by the driver.

Communication over a COM port is a well-covered subject and you should be able to find a vast number of documentation over that. There are also cross-platform serial communication libraries that could make your development easier.

Then you could also write your own library for the device, but that would probably be an overkill if all you want is to read in a voltage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM