1.串口介绍
linux操作系统对串行口提供了很好的支持,linux系统中串口设备被当做一个字符设备处理。
linux系统后在/dev目录下有若干个ttySx(x代表从0开始的正整数)设备文件。ttyS0对应第一个串口,也就是Windows系统下的串口设备COM1.

2.串口操作方法
操作串口的方法与文件类似,可以使用与文件操作相同的的方法打开和关闭串口、读写。以及使用select()函数监听串口。
不同的是,串口是一个字符设备,不能使用fseek()之类的文件定位函数。此外串口是个硬件设备,还可以设置串口设备的属性。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>  //UNIX标准函数定义
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> //文件控制定义
#include <termios.h>  //PPSIX终端控制定义
#include <errno.h>    //错误号定义

int main()
{
    int fd;

    fd = open("/dev/ttyS0", O_RDWR);
    if(fd == -1)
    {
        perror("open ttyS0");
        return 0;
    }
    printf("Open ttyS0 OK!\n");

    close(fd);
    return 0;
}

3.串口属性设置
串口的基本属性,包括波特率、数据位、停止位、奇偶检验等参数。linux系统通常使用termios结构存储串口参数,该结构在termios.h头文件定义如下:

struct termios
{
    tcflag_t c_iflag;      /* input modes 输入模式标志*/  //unsigned short == tcflag_t
    tcflag_t c_oflag;      /* output modes */
    tcflag_t c_cflag;      /* control modes */
    tcflag_t c_lflag;      /* local modes 本地模式标志*/
    unsigned char c_line;  /*线路规则*/
    unsigned cahr     c_cc[NCCS];   /* special characters 控制字*/

};

4.termios.h头文件为termios结构提供了一组设置的函数

int tcgetattr(int fd, struct termios *termios_p); //读取串口的参数设置
int tcsetattr(int fd, int optional_actions, const struct termios *termios_p); //设置指定串口的参数
参数说明:fd:指向已打开的串口设备句柄
termious_p:指向存放串口参数的termios结构首地址。
optional_actions:指定参数什么时候起作用:TCSANOW表示立即生效;TCSADRAIN表示在fd上所有的输出都被传输后生效;TCSAFLUSH表示所有引用fd对象的数据都在输出后生效
int tcsendbreak(int fd, int duration); //传送连续的0值比特流,持续一段时间。
int tcdrain(int fd); //函数会等待直到所有写入fd引用对象的输出都被传输。如果终端未使用异步串行数据传输,tcsendbreak()函数什么都不做
int tcflush(int fd, int queue_selector); //函数丢弃要写入引用的对象但是尚未传输的数据,或者收到但是尚未读取的数据,取决与参数queue_selector的值
int tcflow(int fd, int action);  //函数挂起fd引用对象上的数据传输或接受,取决于action的值
speed_t cfgetispeed(const struct termios *termios_p); //用来得到串口的输入速率
speed_t cfgetospeed(const struct termios *termios_p); //用来得到串口的输出速率, 返回值是speed_t类型的值,其取值及含义如下:
B0:波特率0bit/s B9600:波特率9600bit/s  波特率和通信距离是反比关系。
int cfsetispeed(struct termios *termios_p, speed_t speed);  //用来设置串口的输入速率
int cfsetospeed(struct termios *termios_p, speed_t speed);  //用来设置串口的输出速率  参数speed是要设置的波特率

termios结构相关的函数,除cfgetispeed和cfgetospeed函数外,其他函数返回0表示执行成功,返回-1表示失败,并且设置全局变量errno

提示:在linux串口编程实例中,都没有对termios结构的c_iflag成员做有效设置,在传输ASCII码时不会有问题,如果传输二进制数据就会遇到麻烦,比如0x0d0x110x13数据会被丢掉,因为他们是关键字符,
如果不特别设置一下,他们会被当做控制字符处理掉。设置关闭ICRNL和IXON参数可以解决。
c_iflag &= ~(ICRNL | IXON);
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐