DockerPi SensorHub相信已经有很多小伙伴入手了,还没入手的小伙伴可以看看就是下图的样子奥。是不是感觉有超多的功能呢?实际也确实如此。它有检测环境温度,大气湿度,板载温度等功能。通过编写小程序,可以实现很多功能呢。今天我就来教大家通过IOT平台使用它来监控家庭环境的参数。
IOT环境
上篇中已经讲述了如何搭建IOT环境,在这里我就不再赘述了,还不明白的小伙伴可以去看看我们的文章奥。
硬件组装
请断开电源状态下把继电器板子安装到树莓派上,DockerPi板子不支持热插拔
硬件需求
1.RaspberryPi 3B/3B+/4B
2.16GB TF 卡
3. 5V/2.5A电源或者4B的5V/3A电源
4.DockerPi SensorHub
软件环境
1.打开RaspberryPi 的I2C
如何打开树莓派的I2C功能,我相信大家都会操作,我在这里就不再赘述了
2.检查Python3的版本,必须是3.7或以上,是python3的版本奥
python3 –version
3.先安装Azure IOT的环境
pip3 install azure-iot-device
然后git clone Python3的SDK
git clone https://github.com/Azure/azure-iot-sdk-python --depth=1
编写程序
1.首先进入到 azure-iot-sdk-python/tree/master/azure-iot-device/samples/advanced-hub-scenarios目录,打开文件update_twin_reported_properties.py
把con_str的值换成我们在上文提到你自己获取的HostName的值,这个是怎么获取的呢?请看我们的前面的文章是怎么讲述的
同样打开get_twin.py文件然后做相同的操作。
2.然后再次打开 update_twin_reported_properties.py 文件开始加入下图红框里面的代码:
复制出来的格式可能是错的呦,请参考图片的格式添加!
bus = smbus.SMBus(1)
await device_client.connect()
aReceiveBuf = []
aReceiveBuf.append(0x00) # 占位符
for i in range(0x01,0x0D + 1):
aReceiveBuf.append(bus.read_byte_data(0X17, i))
if aReceiveBuf[0X01] & 0x01 :
state0 = "Off-chip temperature sensor overrange!"
elif aReceiveBuf[0X01] & 0x02 :
state0 = "No external temperature sensor!"
else :
state0 = "Current off-chip sensor temperature = %d Celsius" % aReceiveBuf[0x01]
light = (bus.read_byte_data(0x17,0x03) << 8) | (bus.read_byte_data(0x17,0x02))
temp = bus.read_byte_data(0x17,0x05)
humidity = bus.read_byte_data(0x17,0x06)
temp1 = bus.read_byte_data(0x17,0x08)
pressure = (bus.read_byte_data(0x17,0x0B) << 16) | ((bus.read_byte_data(0x17,0x0A) << 8)) | ((bus.read_byte_data(0x17,0x09)))
state = bus.read_byte_data(0x17,0x0C)
if (state == 0):
state = "the sensor of BMP280 is ok"
else:
state = "the sensor of BMP280 is bad"
human = bus.read_byte_data(0x17,0x0D)
if (human == 1):
human = "live body has been detected"
else:
human = "no live body"
然后保存运行,如果没有错误的话,你会看到显示图片上的信息:
然后再打开get_twin.py文件,添加如图所示代码:
print("{}".format(twin["reported"]["state0"]))
print("Reported light is: {}".format(twin["reported"]["light"]),"Lux")
print("Reported temperature of board is: {}".format(twin["reported"]["temperature"]),"degC")
print("Reported humidity is: {}".format(twin["reported"]["humidity"]),"%")
print("Reported temperature of sensor is: {}".format(twin["reported"]["temperature1"]),"degC")
print("Reported pressure of air is: {}".format(twin["reported"]["pressure"]),"Pa")
print("Reported {}".format(twin["reported"]["state"]))
print("Reported whether detect live body is: {}".format(twin["reported"]["human"]))
保存以后运行get_twin.py文件,没问题的话,你会看到下面的效果: