linux 创建串口节点,浅谈Linux下的串口

串行接口简称串口(通常指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教程,带你走进串口的世界。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值