用C语言编写Linux环境下读写串口的代码
时间: 2024-05-14 09:14:12 浏览: 52
```c
#include <stdio.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
int main()
{
int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY);
if (fd < 0) {
printf("Open serial port failed!\n");
return -1;
}
struct termios options;
tcgetattr(fd, &options);
options.c_cflag |= CLOCAL;
options.c_cflag |= CREAD;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CRTSCTS;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_iflag &= ~(IXON | IXOFF | IXANY);
options.c_oflag &= ~OPOST;
options.c_cc[VTIME] = 0;
options.c_cc[VMIN] = 1;
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
tcsetattr(fd, TCSANOW, &options);
char buf[1024];
// 读取串口数据
int n = read(fd, buf, sizeof(buf));
if (n > 0) {
printf("Read data: %s\n", buf);
}
// 写入串口数据
char data[] = "Hello, serial port!";
write(fd, data, sizeof(data));
close(fd);
return 0;
}
```
阅读全文