UART(Universal Asynchronous Receiver/Transmitter)是一种异步串行通信协议,广泛应用于嵌入式系统和计算机硬件之间的数据传输。在Linux系统中,UART通常通过设备文件(如 /dev/ttyS0
或 /dev/ttyUSB0
)进行访问。
常见的UART类型包括:
在Linux中,可以通过直接访问硬件寄存器来操作UART。以下是一些常用的UART寄存器及其功能:
以下是一个简单的C语言示例,展示如何在Linux中通过 /dev/ttyS0
设备文件进行UART通信:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
int main() {
int fd;
struct termios options;
// 打开设备文件
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("open_port: Unable to open /dev/ttyS0");
return -1;
}
// 获取当前选项并修改
tcgetattr(fd, &options);
cfsetispeed(&options, B9600); // 设置输入波特率为9600
cfsetospeed(&options, B9600); // 设置输出波特率为9600
options.c_cflag |= (CLOCAL | CREAD); // 启用接收器
options.c_cflag &= ~PARENB; // 禁用奇偶校验
options.c_cflag &= ~CSTOPB; // 1个停止位
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8; // 8个数据位
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // 非规范模式
options.c_oflag &= ~OPOST; // 直接输出
tcsetattr(fd, TCSANOW, &options); // 应用设置
// 发送数据
char *message = "Hello, UART!\n";
write(fd, message, strlen(message));
// 接收数据
char buffer[256];
int n = read(fd, buffer, sizeof(buffer));
if (n > 0) {
buffer[n] = '\0';
printf("Received: %s", buffer);
}
close(fd);
return 0;
}
ls -l /dev/ttyS0
检查权限。cfsetispeed
和 cfsetospeed
函数。options.c_cc[VTIME]
和 options.c_cc[VMIN]
参数以控制读取超时。通过以上步骤和示例代码,可以有效地进行Linux下的UART寄存器读写操作。
领取专属 10元无门槛券
手把手带您无忧上云