linux uart例程
时间: 2023-06-21 19:15:04 浏览: 51
以下是一个简单的 Linux UART 例程,使用 C 语言实现,可以配置串口参数并发送和接收数据:
```c
#include <stdio.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
int main()
{
int fd;
struct termios options;
// 打开串口设备文件
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY);
if (fd == -1) {
perror("open");
return -1;
}
// 获取串口参数
tcgetattr(fd, &options);
// 配置波特率为115200,8个数据位,1个停止位,无奇偶校验
options.c_cflag |= B115200 | CS8 | CLOCAL | CREAD;
options.c_iflag |= IGNPAR;
options.c_oflag = 0;
// 设置串口参数
tcsetattr(fd, TCSANOW, &options);
// 发送数据
char str[] = "Hello, world!\n";
write(fd, str, sizeof(str));
// 接收数据
char buf[100];
int len = read(fd, buf, sizeof(buf));
buf[len] = '\0';
printf("Received: %s\n", buf);
// 关闭串口设备文件
close(fd);
return 0;
}
```
在该例程中,我们首先使用 `open()` 函数打开串口设备文件,然后使用 `tcgetattr()` 函数获取串口参数。接下来,我们使用 `tcsetattr()` 函数设置波特率、数据位数、停止位数和奇偶校验等参数。然后,我们可以使用 `write()` 函数发送数据,使用 `read()` 函数接收数据。最后,我们使用 `close()` 函数关闭串口设备文件。
需要注意的是,在 Linux 中,串口设备文件通常以 `/dev/tty*` 的形式命名,其中 `*` 表示串口号,例如 `/dev/ttyUSB0` 表示 USB 转串口模块连接的串口0。此外,需要以超级用户身份运行程序才能访问串口设备文件。