用c实现linux下串口通信,带中文注释
时间: 2024-05-06 19:20:35 浏览: 9
以下是一个简单的例子,用于在Linux下使用C语言实现串口通信。本例中实现了从串口接收数据并将其打印到终端上,同时也可以向串口发送数据。代码中包含了中文注释,以便于理解。
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <string.h>
int main(int argc, char *argv[])
{
int fd;
struct termios options;
char buffer[256];
// 打开串口设备
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
// 获取串口属性
tcgetattr(fd, &options);
// 设置串口输入和输出波特率为115200
cfsetspeed(&options, B115200);
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
// 设置字符大小和流控制方式
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~CRTSCTS;
// 设置为无奇偶校验和1位停止位
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
// 禁用软件控制流控制
options.c_iflag &= ~(IXON | IXOFF | IXANY);
// 设置为非规范模式,禁用回显和系统信号
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
// 禁用输出处理
options.c_oflag &= ~OPOST;
// 设置串口属性
tcsetattr(fd, TCSANOW, &options);
// 设置非阻塞模式
fcntl(fd, F_SETFL, FNDELAY);
while (1) {
// 从串口读取数据
int n = read(fd, buffer, sizeof(buffer));
if (n > 0) {
// 打印接收到的数据
buffer[n] = '\0';
printf("Received data: %s\n", buffer);
}
// 从终端读取数据并发送到串口
fgets(buffer, sizeof(buffer), stdin);
if (strlen(buffer) > 0) {
write(fd, buffer, strlen(buffer));
}
}
// 关闭串口设备
close(fd);
return 0;
}
```
在此代码中,我们首先打开了串口设备`/dev/ttyS0`,并获取了其属性。然后,我们设置了输入和输出波特率为115200,字符大小为8位,停止位为1位,无奇偶校验,禁用了软件流控制和回显,并使用非阻塞模式。在主循环中,我们从串口读取数据并打印,同时也从终端读取数据并发送到串口。最后,我们关闭了串口设备。
请注意,此代码中的串口设备为`/dev/ttyS0`,这是Linux系统中的一个串口设备文件,对应于计算机上的物理串口。如果您的计算机没有物理串口,则需要使用USB转串口适配器等外部设备。另外,请根据您的实际需求更改串口属性。