Linux C++读取串口信息学习笔记

参考链接: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
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值