首页 > 编程知识 正文

树莓派体验12 树莓派I2C接口获取温湿度

时间:2023-05-05 12:26:07 阅读:185238 作者:4762

i2c-tools工具安装

apt-get install i2c-tools

i2c-tools包含如下命令:

i2cdetect  i2cdump    i2cget     i2cset

通过raspi-config打开树莓派I2C,执行i2cdetect -l查看:

root@raspberrypi:/opt# i2cdetect -l
i2c-1   i2c             3f804000.i2c                            I2C adapter

查看I2C-1上所挂的设备信息:

root@raspberrypi:/opt# i2cdetect -y -r 1
     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: -- -- -- -- -- -- -- --

地址40为温湿度传感器SHT20。

查看传感器信息:

root@raspberrypi:/opt# i2cdump -f -y 1 0x40
No size specified (using byte-data access)
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f    0123456789abcdef
00: XX XX XX 69 XX 67 3a 3a XX 06 XX XX XX XX XX 02    XXXiXg::X?XXXXX?
10: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX    XXXXXXXXXXXXXXXX

其中寄存器0x03为温度值,寄存器0x05为湿度,可以使用i2cget命令单独获取:

root@raspberrypi:/opt# i2cget -f -y 1 0x40 0x03
0x69
root@raspberrypi:/opt# i2cget -f -y 1 0x40 0x05
0x67

写个python脚本调用i2c-tools获取温湿度:

#!/usr/开放的曲奇/pythonimport commandsstatus_temp,temp_reg=commands.getstatusoutput('i2cget -f -y 1 0x40 0x03')status_humd,humd_reg=commands.getstatusoutput('i2cget -f -y 1 0x40 0x05')print "Register temp:",temp_regprint "Register humd:",humd_regtemp_int = int(temp_reg,16)humd_int = int(humd_reg,16)temp = (temp_int<<8)|temp_inthumd = (humd_int<<8)|humd_intT=-46.85 + 175.72/65536*tempRH=-6.0+125.0/65536*humdprint "Current Temperature=",Tprint "Relative Humidity=",RH

保存为SHT20.py,执行:

root@raspberrypi:/opt/i2c# ./SHT20.py
Register temp: 0x69
Register humd: 0x68
Current Temperature= 25.5041900635
Relative Humidity= 44.9796142578

树莓派通过Python操作I2C接口的库很多,常用的有smbus、quick2wire、wiringpi等。

使用wiringpi Python 获取SHT20温湿度脚本如下:

#!/usr/开放的曲奇/pythonimport wiringpifd=wiringpi.wiringPiI2CSetup(0x40)temp_org=wiringpi.wiringPiI2CReadReg8(fd,0x03)humd_org=wiringpi.wiringPiI2CReadReg8(fd,0x05)temp = (temp_org<<8)|temp_orghumd = (humd_org<<8)|humd_orgT=-46.85 + 175.72/65536*tempRH=-6.0+125.0/65536*humdprint "Current Temperature=",Tprint "Relative Humidity=",RH

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。