一段能够读取USB串口信息并打印的C++代码
时间: 2024-04-29 18:22:37 浏览: 110
C/C++语言实现串口(USB)的数据收发
5星 · 资源好评率100%
Sure, I can help you with that! Here is a sample C code snippet that reads USB serial port information and prints it:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
int fd;
struct termios options;
char buf[256];
if ((fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY)) == -1) {
perror("open_port: Unable to open /dev/ttyUSB0 - ");
return 1;
}
tcgetattr(fd, &options);
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
tcsetattr(fd, TCSANOW, &options);
while (1) {
memset(buf, 0, sizeof(buf));
if (read(fd, buf, sizeof(buf)) > 0) {
printf("%s", buf);
}
}
close(fd);
return 0;
}
```
Note that this code assumes that the USB serial port you want to read from is located at "/dev/ttyUSB0". You may need to modify this depending on your system configuration. Also, make sure to include the necessary headers and libraries.
阅读全文