zoukankan      html  css  js  c++  java
  • 4412 串口编程

    一、打开串口

    串口在linux里都是设备,可以用open之类的函数操作

    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <unistd.h>
    #include <string.h>
    
    
    void main()
    {
            int fd;
            char *uart3 = "/dev/ttySAC3";
    
            fd = open(uart3, O_RDWR|O_CREAT, 0777);
            if(fd < 0) {
                    printf("open %s failed!
    ", uart3);
            } else {
                    printf("open %s success!
    ", uart3);
            }
    
            close(fd);
    }

    二、串口使用的相关函数

    int tcgetattr(int fd, struct termios *termios_p);
    参数1:fd是open返回的文件描述符
    参数2:*termios_p是termios的结构体指针
    在初始化开始调用这个函数
    获取当前波特率函数
    speed_t cfgetispeed(const struct termios *termios_p);
    speed_t cfgetospeed(const struct termios *termios_p);
    *termios_p:前面介绍的结构体
    失败返回-1:成功返回波特率
    波特率设置函数
    int cfsetispeed(struct termios *termios_p, speed_t speed);
    int cfsetospeed(struct termios *termios_p, speed_t speed);
    参数*termios_p:前面介绍的结构体
    参数speed:speed波特率,常用的B2400,B4800,B9600,B115200,B460800等等
    执行成功返回0,失败返回-1
    清空串口BUFFER中的数据函数
    int tcflush(int fd, int queue_selector);
    参数1:fd是open返回的文件描述符
    参数2:控制tcflush的操作
    TCIFLUSH清除正受到的数据,且不读出来
    TCOFLUSH清除正写入的数据,且不会发送至终端
    TCIOFLUSH清除所有正在发生的I/O数据
    设置串口参数函数
    int tcsetattr(int fd, int optional_actions, const struct termios *termios_p);
    参数fd:open返回的文件句柄
    参数optional_actions:参数生效时间。TCSANOW:不但数据传输完毕就立即改变属性
    TCSADRAIN:等待所有数据传输结束才改变属性;TCSAFLUSH:清空输入输出缓冲区才改变属性。
    参数*termios_p:在旧的参数基础上修改的后的参数
    返回值:成功0, 失败-1
    
    一般这个函数初始化最后使用
    无欲速,无见小利。欲速,则不达;见小利,则大事不成。
  • 相关阅读:
    Windows 科研软件推荐
    有关Python 包 (package) 的基本知识
    《Using Python to Access Web Data》Week4 Programs that Surf the Web 课堂笔记
    Coursera助学金申请模板
    《Using Databases with Python》 Week2 Basic Structured Query Language 课堂笔记
    Jupyter 解决单个变量输出问题
    解决 pandas 中打印 DataFrame 行列显示不全的问题
    《Using Python to Access Web Data》 Week3 Networks and Sockets 课堂笔记
    缓存击穿及解决方案
    jvm垃圾收集器
  • 原文地址:https://www.cnblogs.com/ch122633/p/9358272.html
Copyright © 2011-2022 走看看