首先科普IIC,即I2C
IIC(Inter-Integrated Circuit)其实是IICBus简称,所以中文应该叫集成电路总线。
包括两个SDA和SCL,SDA是串行数据线,SCL是串行时钟线,IIC工作方式为半双工。
可以看到MLX90614有四个引脚,vcc接3.3v,GND接地,SDA和SCL分别对应树莓派相应接口(见下图)。
接好线之后
首先安装IIC库(这个一般树莓派操作系统自带)
1 | sudo apt install i2c-tools |
再装专门为python的smbus
1 | sudo apt install python-smbus |
安完上面两个,就可以打开IIC
1 | sudo raspi-config |
选择5 interface options,然后选择P5 I2C,打开这一项
之后就可以查看模块的地址了(下面代码如果运行不了,自己加管理员权限sudo)1
i2cdetect -y -a 1
如果树莓派SDA和SCL接的是SDA.1和SCL.1,那么模块地址就是0x5a,如图
这样就说明检测到了模块,地址为0x5a
接下来上代码,打开万能的GitHub,源码链接在此!
照顾一下打不开的朋友
mlx90614.py1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63import smbus
from time import sleep
class MLX90614():
MLX90614_RAWIR1=0x04
MLX90614_RAWIR2=0x05
MLX90614_TA=0x06
MLX90614_TOBJ1=0x07
MLX90614_TOBJ2=0x08
MLX90614_TOMAX=0x20
MLX90614_TOMIN=0x21
MLX90614_PWMCTRL=0x22
MLX90614_TARANGE=0x23
MLX90614_EMISS=0x24
MLX90614_CONFIG=0x25
MLX90614_ADDR=0x0E
MLX90614_ID1=0x3C
MLX90614_ID2=0x3D
MLX90614_ID3=0x3E
MLX90614_ID4=0x3F
comm_retries = 5
comm_sleep_amount = 0.1
def __init__(self, address=0x5a, bus_num=1):
self.bus_num = bus_num
self.address = address
self.bus = smbus.SMBus(bus=bus_num)
def read_reg(self, reg_addr):
err = None
for i in range(self.comm_retries):
try:
return self.bus.read_word_data(self.address, reg_addr)
except IOError as e:
err = e
#"Rate limiting" - sleeping to prevent problems with sensor
#when requesting data too quickly
sleep(self.comm_sleep_amount)
#By this time, we made a couple requests and the sensor didn't respond
#(judging by the fact we haven't returned from this function yet)
#So let's just re-raise the last IOError we got
raise err
def data_to_temp(self, data):
temp = (data*0.02) - 273.15
return temp
def get_amb_temp(self):
data = self.read_reg(self.MLX90614_TA)
return self.data_to_temp(data)
def get_obj_temp(self):
data = self.read_reg(self.MLX90614_TOBJ1)
return self.data_to_temp(data)
if __name__ == "__main__":
sensor = MLX90614()
print(sensor.get_amb_temp())
print(sensor.get_obj_temp())
example.py1
2
3
4
5
6
7
8from mlx90614 import MLX90614
thermometer_address = 0x5a
thermometer = MLX90614(thermometer_address)
print thermometer.get_amb_temp()
print thermometer.get_obj_temp()
直接运行mlx90614.py就行了。
版权声明:本文为CSDN博主「帅帅气气的黑猫警长」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Hao_ge_666/article/details/117170782