浅谈linux下的串口通讯开发

2019-10-13 11:20:14王冬梅

用open函数打开设备文件,函数返回一个文件描述符(file descriptors,fd),通过文件描述符来访问文件。读串口操作是通过read函数来完成的。函数原型如下:

int read(int fd, *buffer,length);

参数说明:

(1).int fd:文件描述符

(2).*buffer:数据缓冲区

(3).length:要读取的字节数

函数返回值:

读操作成功读取返回读取的字节数,失败则返回-1。

6. 串口写操作(发送端)

写串口操作是通过write函数来完成的。函数原型如下:

write(int fd, *buffer,length);

参数说明:

(1).fd:文件描述符

(2).*buffer:存储写入数据的数据缓冲区

(3).length:写入缓冲去的数据字节数

函数返回值:

成功返回写入数据的字节数,该值通常等于length,如果写入失败返回-1。

例如:向终端设备发送初始化命令

#include //头文件包含

......

......

int n

sbuf[]={Hello,this is a Serial_Port test!/n };//待发送数据

int len_send="sizeof"(sbuf);//发送缓冲区字节数定义

n = write(fd,sbuf,len_send); //写缓冲区

if(n == -1)

{

printf("Wirte sbuf error./n");

}

......

......

7. 关闭串口

对设备文件的操作与对普通文件的操作一样,打开操作之后还需要关闭,关闭串口用函数close( )来操作,函数原型为:

int close(int fd);

参数说明:

fd:文件描述符

函数返回值:

成功返回0,失败返回-1。

NAME

termios, tcgetattr, tcsetattr, tcsendbreak, tcdrain, tcflush, tcflow, cfmakeraw, cfgetospeed, cfgetispeed, cfsetispeed, cfsetospeed - 获取和设置终端属性,行控制,获取和设置波特率

SYNOPSIS 总览

#include <termios.h>
#include <unistd.h>

int tcgetattr(int fd, struct termios *termios_p);

int tcsetattr(int fd, int optional_actions, struct termios *termios_p);

int tcsendbreak(int fd, int duration);

int tcdrain(int fd);

int tcflush(int fd, int queue_selector);

int tcflow(int fd, int action);

int cfmakeraw(struct termios *termios_p);

speed_t cfgetispeed(struct termios *termios_p);

speed_t cfgetospeed(struct termios *termios_p);

int cfsetispeed(struct termios *termios_p, speed_t speed);

int cfsetospeed(struct termios *termios_p, speed_t speed);

DESCRIPTION 描述

termios 函数族提供了一个常规的终端接口,用于控制非同步通信端口。

这里描述的大部分属性有一个 termios_p 类型的参数,它是指向一个 termios 结构的指针。这个结构包含了至少下列成员:

tcflag_t c_iflag;      /* 输入模式 */
tcflag_t c_oflag;      /* 输出模式 */
tcflag_t c_cflag;      /* 控制模式 */