[Linux] 串口读写

直接通过终端控制串口

cd 进入 /dev

ls 查看当前文件夹文件

在这里操作,ttyS*为串口的格式

可以直接操作串口1/3,在这里使用串口3

设置波特率(stty命令)

stty -F /dev/ttyS3 115200 

在这里使用 stty 设置串口的属性为115200,校验位等都是通过这个命令设置

串口数据读写操作

使用echo向串口发送数据,如echo “hello linux” > /dev/ttyS3

输出为


可以使用cat来读取串口中的数据,如cat /dev/ttyS3,注意 在这里使用cat的时候串口会回显输入的数据,例如我在这里串口输入 123 ,注意点发送新行

得到的结果是:


也可以读取数据并保存到txt文本文件中,如cat /dev/ttyS3 > test.txt,这里不演示

C语言控制串口

持续串口交互

使用C语言在vim上开发

用到的头文件主要为 "termios.h"

读取函数为 read(fd,&readbuf,sizeof(readbuf));

输出函数为write(fd,&writebuf,sizeof(writebuf));

在这里贴一个串口回传实验:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#include <termios.h>
#include <string.h>

/* 115200, 8, N, 1 */
int uart_setup(int fd)
{
    struct termios options;

    // 获取原有串口配置
    if  (tcgetattr(fd, &options) < 0) {
        return -1;
    }

    // 修改控制模式,保证程序不会占用串口
    options.c_cflag  |=  CLOCAL;

    // 修改控制模式,能够从串口读取数据
    options.c_cflag  |=  CREAD;

    // 不使用流控制
    options.c_cflag &= ~CRTSCTS;

    // 设置数据位
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;

    // 设置奇偶校验位
    options.c_cflag &= ~PARENB;
    options.c_iflag &= ~INPCK; 

    // 设置停止位
    options.c_cflag &= ~CSTOPB;

    // 设置最少字符和等待时间
    options.c_cc[VMIN] = 1;     // 读数据的最小字节数
    options.c_cc[VTIME]  = 0;   //等待第1个数据,单位是10s
    
    // 修改输出模式,原始数据输出
    options.c_oflag &= ~OPOST;
    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);

    // 设置波特率
    cfsetispeed(&options, B115200); 
    cfsetospeed(&options, B115200);

    // 清空终端未完成的数据
    tcflush(fd, TCIFLUSH);

    // 设置新属性
    if(tcsetattr(fd, TCSANOW, &options) < 0) {
        return -1;
    }

    return 0;
}

int main(int argc, char *argv[])
{
    int fd;
    int ret;
    char readbuf[20]={0};
	char writebuf[20]={0};
    /* 打开串口 */
    fd = open("/dev/ttyS3", O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd < 0) {
        printf("open dev fail!\n");
        return -1;
    } else {
		printf("Open uart OK \n");
        fcntl(fd, F_SETFL, 0);
	}
    /* 设置串口 */
    ret = uart_setup(fd);
    if (ret < 0) {
        printf("uart setup fail!\n");
        close(fd);
        return -1;
    }
	printf("setup uart OK \n");

    /* 串口回传实验 */
    while (1) {
        ret = read(fd, &readbuf, sizeof(readbuf));
        if (ret != -1) {
			ret=write(fd,&readbuf,sizeof(readbuf));  
			ret=write(fd,"\r\n",2);
		}
    }

    close(fd);
}

运行后的结果为:

通过串口输入内容会通过串口返回

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值