上一篇介绍了i2c协议,SHT20是使用标准的i2c接口的温湿度传感器,我们首先要完成树莓派与SHT20传感器的连接:
使能内核I2C驱动模块:
liruiyan@cloud-ubuntu18:~$ sudo raspi-config
重启树莓派,系统启动之后会自动安装i2c的相关驱动:
liruiyan@cloud-ubuntu18:~$ sudo reboot
liruiyan@cloud-ubuntu18:~$ sudo apt-get install i2c-tools
liruiyan@cloud-ubuntu18:~$ lsmod | grep i2c
i2c_bcm2835 16384 0
i2c_dev 16384 0
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: 40 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --
使用i2cdetect命令可以查看到SHT21温湿度传感器设备地址0x40。
i2c设备驱动有两种模式:一种是用户模式设备驱动,这种驱动依赖于i2c子系统中i2c-dev驱动,这种驱动对应用程序员的要求很高,要
求应用程序员了解硬件的一些东西,了解时序、地址等;另一种是普通的设备驱动,应用程序员在使用的时候就像读写文件
一样,不过这里的read()和write()函数只能对应一条消息。
liruiyan@cloud-ubuntu18:~$ vim sht20.c
1 #include <stdio.h>
2 #include <fcntl.h>
3 #include <unistd.h>
4 #include <sys/ioctl.h>
5 #include <linux/types.h>
6 #include <sys/stat.h>
7 #include <linux/i2c.h>
8 #include <linux/i2c-dev.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <sys/types.h>
12 #include <string.h>
13 #include <stdint.h>
14 #include <time.h>
15 #include <errno.h>
16 #include <string.h>
17 #define SOFTRESET 0xFE