Linux:串口通信编程

串口通过直接连接在两台设备间的线发送和接收数据,两台设备通信最少需要三根线(发送数据、接收数据和接地)才可以通信。以最常见的 RS232 串口为例,通信距离较近时(<12m) ,可以用电缆线直接连接标准 RS232 端口。如果传输距离远,可以通过调制解调器(MODEM)传输。因为串口设备工作频率低且容易受到干扰,远距离传输会造成数据丢失。

DB9 接口的 RS232 串口数据线定义

Linux 系统后在/dev 目录下有若干个 ttySx(x代表从 0 开始的正整数)设备文件。ttyS0 对应第一个串口,也就是 Windows 系统下的串口设备 COM1,以此类推。

操作串口需要用到的头文件:

#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 系统通常使用 termios 结构存储串口参数,该结构在 termios.h头文件定义如下:

struct termios
{ unsigned short c_iflag; /* 输入模式标志 */
unsigned short c_oflag; /* 输出模式标志 */
unsigned short c_cflag; /* 控制模式标志 */
unsigned short c_lflag; /* 本地模式标志 */
unsigned char c_line; /* 线路规则 */
unsigned char c_cc[NCC]; /* 控制字 */
};

termios 结构的各成员常用取值

termios 结构 c_cc 成员数组下标取值及其含义

termios.h 头文件为 termios 结构提供了一组设置的函数,函数定义如下:

#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);

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值