给我一份串口配置的代码
时间: 2023-12-09 11:04:43 浏览: 17
好的,以下是一个串口配置的示例代码:
```c++
#include <iostream>
#include <string>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
int main()
{
int fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
{
std::cerr << "Failed to open serial port" << std::endl;
return 1;
}
struct termios options;
tcgetattr(fd, &options);
options.c_cflag = B9600 | CS8 | CLOCAL | CREAD;
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &options);
std::string message = "Hello, world!";
write(fd, message.c_str(), message.length());
char buffer[256] = {0};
int len = read(fd, buffer, sizeof(buffer));
std::cout << "Received " << len << " bytes: " << buffer << std::endl;
close(fd);
return 0;
}
```
请注意,该示例代码是在 Linux 操作系统下编写的,需要包含头文件 `unistd.h`、`fcntl.h` 和 `termios.h`。其中,“/dev/ttyUSB0” 是指代串口设备的路径,实际应用中需要根据自己的设备路径进行修改。另外,串口波特率为 9600,数据位为 8 位,无奇偶校验位,无流控。