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
    
    一般这个函数初始化最后使用
    无欲速,无见小利。欲速,则不达;见小利,则大事不成。
  • 相关阅读:
    cocos2d-x把json数据解析到数组或字典中(libjson库)
    (bug更正)利用KVC和associative特性在NSObject中存储键值
    第二次博客作业
    我的感想
    期末总结
    陈老师作业
    第三次作业---四则运算的进一步完善
    好难
    对git的认识
    计应143 卞玉新
  • 原文地址:https://www.cnblogs.com/ch122633/p/9358272.html
Copyright © 2011-2022 走看看