Linux C 串口编程

 Linu x C 串口编程。

串口操作需要的头文件:

1
2
3
4
5
6
7
8
#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>      /*错误号定义*/
 

首先需要打开串口

在 Linux 下串口文件是位于 /dev 下的

串口一 为 /dev/ttyS0

串口二 为 /dev/ttyS1

打开串口是通过使用标准的文件打开函数操作:

1
2
3
4
5
6
7
int fd;
/*以读写方式打开串口*/
fd = open( "/dev/ttyS0" , O_RDWR);
if (-1 == fd){ 
/* 不能打开串口一*/ 
perror ( " 打开错误!" );
}

然后对串口设置

串口设置设计的结构体如下:

1
2
3
4
5
6
7
8
struct termio
{   unsigned short  c_iflag;    /* 输入模式标志 */    
     unsigned short  c_oflag;    /* 输出模式标志 */    
     unsigned short  c_cflag;    /* 控制模式标志*/ 
     unsigned short  c_lflag;    /* local mode flags */  
     unsigned char   c_line;     /* line discipline */   
     unsigned char   c_cc[NCC];      /* control characters */
};

这里仅对常用的设置进行介绍:

1.波特率设置:

1
2
3
4
5
struct  termios Opt;
tcgetattr(fd, &Opt);
tcflush(fd,TCIFLUSH);
cfsetispeed(&Opt,B19200);     /*设置为19200Bps*/
cfsetospeed(&Opt,B19200);

2.校验位和停止位设置

常用的一般是8N0

1
2
3
4
5
6
Opt.c_cflag |= CS8;                          //设置数据位
Opt.c_cflag &= ~PARENB;   
Opt.c_oflag &= ~(OPOST);
Opt.c_cflag &= ~CSTOPB;
Opt.c_lflag &= ~(ICANON|ISIG|ECHO|IEXTEN);
Opt.c_iflag &= ~(INPCK|BRKINT|ICRNL|ISTRIP|IXON);
1
2
Opt.c_cc[VMIN] = 0;
Opt.c_cc[VTIME] = 0;

3.写入配置

1
2
3
4
5
6
if (tcsetattr(fd,TCSANOW,&Opt) != 0)       //装载初始化参数
    perror ( "SetupSerial!\n" ); 
    close(fd);
    return -1;
}

4.测试串口

1
2
3
4
5
6
7
8
9
10
11
12
char buf[20];
  
for (;;)
{
len = write(fd, buf, 1);        //写串口
if (len > 0)
{
read(fd, buf, sizeof (buf));      //读串口数据
printf ( "buf %s\n" , buf);    //输出读到的数据
}
usleep(100000);
}
 
对其中的细节可以参考一下两篇,仔细阅读,基本解决串口的所有疑问。
 
 
 
 

猜你喜欢

转载自blog.csdn.net/huangquanming/article/details/8194537
今日推荐