参考链接:Linux 串口读取,作者 wabil大佬
后期补充说明:这里提供的代码后面自己用的时候出现了问题,具体问题请参考我的另一篇帖子:linux打开串口自动写入信息导致读取阻塞。当然了,建议大家直接参考参考链接的帖子,下面的内容仅供大家参考,了解大致使用逻辑即可,切忌不要用我的代码(惭愧惭愧)
代码逻辑
打开串口设备文件间
通过open函数打开串口设备文件,返回文件描述符fd。
int fd = open("/dev/ttyUSB0", O_RDWR|O_NOCTTY);
// O_RDWR代表可读可写模式;O_NOCTTY代表“不会使打开的文件成为该进程的控制终端“,即输入不会影响
用户的进程
open成功打开的标识为fd大于0。
配置串口
linux的“termios.h”提供了配置串口的结构体,叫做termios。
struct termios opt;
tcgetattr(fd, & opt); // 获取终端控制属性
cfsetispeed(& opt, B115200); // 设置输入波特率
cfsetospeed(& opt, B115200); // 设置输出波特率
opt.c_cflag &= CS8; // 数据宽度是8bit
tcflush(fd, TCIOFLUSH); // 清空串口缓存
接收数据(字符串)
int RxLen = 0;
uint8_t RxBuff[1024] = {0};
char
while (1) {
while ( ((RxLen = read(fd, RxBuff, sizeof(RxBuff))) >0) ) {
RxBuff[RxLen] = 0;
printf("%s", RxBuff);
}
}
完整代码如下:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <termios.h>
int main() {
int fd = 0;
printf("ready to open\n");
fd = open("/dev/ttyUSB0", O_RDWR|O_NOCTTY);
printf("opened! %d\n", fd);
struct termios opt;
tcgetattr(fd, & opt);
cfsetispeed(& opt, B921600);
cfsetospeed(& opt, B921600);
opt.c_cflag &= CS8;
tcflush(fd, TCIOFLUSH);
u_int8_t buf[10] = {0};
int n;
printf("blocking...\n");
n = read(fd, buf, 10);
printf("read!!\n");
if (n<0) {
exit(1);
}
// write(STDIN_FILENO, buf, n);
printf("nread=%d, %s\n", n, buf);
return 0;
}
输入如下:
yuankai@yuankai:~/Desktop/formation/UWB/protocal/nlink_unpack$ ./read_serial
ready to open
opened! 3
blocking...
read!!
nread=10, 254