树莓派4B 读取 SensorHub 上传数据到 IoT

树莓派上安装了个小的sensor hub,准备收集环境数据然后当成 IoT device上传到IoT Hub。

树莓派Sensor Hub 初配置

前边树莓派端Sensor Hun相关的配置参考的是另一个腿哥的这个文档:
链接: 当 DockerPi SensorHub 遇到 matplotlib.
当然他这个是从头开始配的树莓派,跳过一段一段有一段之后

开始我们配置一下I2C功能,

sudo raspi-config

Interfacing options -> I2C -> Yes

然后保存设置
输入

i2cdetect -y 1

在这里插入图片描述能看到这个17就说明安装好了。

matplotlib 的配置

然后安装matplotlib

pip install matplotlib

需要等一会儿
安装好之后测试一下

python
//等弹出来python命令行之后输入
import matplotlib.pyplot as plt

确定安好之后,我们来试试腿哥给的测试小样例。嗯,树莓派上还没装截图软件就不照了,反正成功了就是了。

树莓派配置成IoT Device

嗯,跟windows下面基本上没啥差别,按windows下面的命令一样样儿的搞过来就好
链接: 树莓派4B实践Azure IoT 上传.
哦对了,你用pip还是pip3装完了记得用对应的python执行就好
在这里插入图片描述测试接收成功,美滋滋,来给____(天空题)来一杯卡布奇诺

通过smbus在进行传感器数据的接收

听腿哥的话,我们试试smbus来做数据收集者

pip install smbus

继续用腿哥的代码测一下smbus是不是装好了
Ok没问题,那我们把两边代码揉一揉测试一下从树莓派读取数据送到IoT Hub,记得改CONNECTION_STRING

import time
import smbus
from azure.iot.device import IoTHubDeviceClient, Message

CONNECTION_STRING = "HostName=nijiezhecaiya;DeviceId=woshishebeiidya;SharedAccessKey=nawonenggaosunima"
MSG_TXT = '{{"temperature": {temperature},"humidity": {humidity}}}'

DEVICE_BUS = 1
DEVICE_ADDR = 0x17
TEMP_REG = 0X01
ON_BOARD_HUMIDITY_REG = 0x06

bus = smbus.SMBus(DEVICE_BUS)

def iothub_client_init():
  # Create an IoT Hub client
  client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
  return client
def iothub_client_telemetry_sample_run():
  try:
    client = iothub_client_init()
    print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" )

    while True:
      temperature = bus.read_byte_data(DEVICE_ADDR, TEMP_REG)/10
      humidity = bus.read_byte_data(DEVICE_ADDR, ON_BOARD_HUMIDITY_REG)
      msg_txt_formatted = MSG_TXT.format(temperature=temperature, humidity=humidity)
      message = Message(msg_txt_formatted)
      
      if temperature > 30:
        message.custom_properties["temperatureAlert"] = "true"
      else:
        message.custom_properties["temperatureAlert"] = "false"
        
      print( "Sending message: {}".format(message) )
      client.send_message(message)
      print ( "Message successfully sent" )
      time.sleep(5)
      
  except KeyboardInterrupt:
    print ( "IoTHubClient sample stopped" )
if __name__ == '__main__':
  print ( "IoT Hub Quickstart 1 - My Raspberry Pi" )
  print ( "Press Ctrl-C to exit" )
  iothub_client_telemetry_sample_run()

在这里插入图片描述
Cheers

发布了6 篇原创文章 · 获赞 6 · 访问量 151

猜你喜欢

转载自blog.csdn.net/Elleryer/article/details/105407351