嵌入式Linux如何用C读写uart
时间: 2024-05-16 11:11:58 浏览: 12
嵌入式Linux可以使用C语言编写程序来读写UART串口。具体步骤如下:
1. 打开串口设备文件
在Linux下,串口设备文件一般位于/dev目录下,例如/dev/ttyS0。程序需要打开这个设备文件以便读写串口。可以使用open()函数打开设备文件,例如:
```
int fd = open("/dev/ttyS0", O_RDWR);
if (fd < 0) {
perror("open");
return -1;
}
```
2. 配置串口参数
在打开串口设备文件后,需要对串口进行参数配置,例如波特率、数据位、停止位、奇偶校验等。可以使用tcsetattr()函数进行参数配置,例如:
```
struct termios options;
tcgetattr(fd, &options); // 获取当前串口参数
cfsetispeed(&options, B9600); // 设置波特率为9600
cfsetospeed(&options, B9600);
options.c_cflag &= ~PARENB; // 不使用奇偶校验
options.c_cflag &= ~CSTOPB; // 停止位为1
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8; // 数据位为8
options.c_cflag |= CLOCAL; // 忽略控制线
options.c_cflag |= CREAD; // 允许读取数据
tcsetattr(fd, TCSANOW, &options); // 设置参数
```
3. 读写数据
配置好串口参数后,就可以使用read()和write()函数进行串口数据的读写了。例如:
```
char buf[1024];
int ret = read(fd, buf, sizeof(buf)); // 从串口读取数据
if (ret < 0) {
perror("read");
return -1;
}
write(fd, buf, ret); // 将读取到的数据写回串口
```
完整的串口读写程序示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
int main(int argc, char *argv[])
{
int fd = open("/dev/ttyS0", O_RDWR);
if (fd < 0) {
perror("open");
return -1;
}
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag |= CLOCAL;
options.c_cflag |= CREAD;
tcsetattr(fd, TCSANOW, &options);
while (1) {
char buf[1024];
int ret = read(fd, buf, sizeof(buf));
if (ret < 0) {
perror("read");
return -1;
}
if (ret > 0) {
write(fd, buf, ret);
}
}
close(fd);
return 0;
}
```