专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 浅谈Linux下的串口

浅谈Linux下的串口

更新时间:2021-01-07 17:29:04 来源:赢咖4 浏览1058次

串行接口简称串口(通常指COM接口),是采用串行通信方式的扩展接口。串口是计算机一种常用的接口,具有连接线少,通讯简单,得到广泛的使用。串口的特点是通信线路简单,只要一对传输线就可以实现双向通信从而大大降低了成本,特别适用于远距离通信,但传送速度较慢。在Linux中,同样存在着大量的串口,本文我们就来聊聊Linux下的串口

 

一、串口需要的头文件
1: #include /*标准输入输出定义*/
2: #include /*标准函数库定义*/
3: #include /*Unix 标准函数定义*/
4: #include
5: #include  
6: #include /*文件控制定义*/
7: #include /*POSIX 终端控制定义*/
8: #include /*错误号定义*/

 

二、打开关闭串口
对于串口设备文件的操作与其他文件操作基本相同。可以使用系统调用open(), close()打开或关闭串口。
在Linux下串口文件是在/dev下的,例如串口一为/dev/ttyS0,串口二为/dev/ttyS1。
open(),close()系统调用的原型
1: #include
2: #include
3: #include
4: int open(const char *path, int oflags);
5: int open(const char *path, int oflags, mode_t mode);
6: #include
7: int close(int fildes);
8: 实例:打开串口ttyS0。
9: int fd;
10: /*以读写方式打开串口*/
11: fd = open( "/dev/ttyS0", O_RDWR);
12: if (-1 == fd){ 
13: /* 不能打开串口一*/ 
14: perror("open serial port error");
15: }

 

三、设置串口
设置串口包括波特率设置、校验位、停止位设置。在串口设置中主要是设置struct termios结构体成员的值。
struct termios结构如下
1: #include
2: struct termio
3: {
4: unsigned short c_iflag; /* input options输入模式标志 */
5: unsigned short c_oflag; /* output options输出模式标志 */
6: unsigned short c_cflag; /* control options控制模式标志*/
7: unsigned short c_lflag; /* local mode flags */
8: unsigned char c_line; /* line discipline */
9: unsigned char c_cc[NCC]; /* control characters */
10: };

 

实例:设置波特率
1: struct termios options;
2: /*
3: * 得到当前串口设置,保存在options中
4: */
5: tcgetattr(fd, &options);
6: /*
7: * 设置波特率为19200
8: */
9: cfsetispeed(&options, B19200);
10: cfsetospeed(&options, B19200);
11: /*
12: * 本地连接和接收使能
13: */
14: options.c_cflag |= (CLOCAL | CREAD);
15: /*
16: * 应用设置(立即应用)
17: */
18: tcsetattr(fd, TCSANOW, &options);

 

四、读写串口
读写串口和普通的文件操作相同,分别使用read()和write()。
原型:
1: #include
2: size_t read(int fields, void *buf, size_t nbytes);
3: size_t write(int fildes, const void *buf, size_t nbytes);
实例:写串口
1: char buffer[] = “hello world”;
2: int length = 11;
3: int nByte;
4: nByte = write(fd, buffer, length);

 

以上就是Linux下的串口的一些基本的知识,串口有着许多的类型,串行接口按电气标准及协议来分包括RS-232-C、RS-422、RS485等。RS-232-C、RS-422与RS-485标准只对接口的电气特性做出规定,不涉及接插件、电缆或协议。想了解这些串口的特性可以观看本站的Linux教程,带你走进串口的世界。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>