In this tutorial we’ll show you have to send temperature and humidity data from a DHT11 sensor up to Azure with a Raspberry Pi, let’s get started:

Get your Raspberry Pi up and Running for projects

First set up to purchase the items you need an perform the a basic installation:

  • Remove the monitor, keyboard, mouse and RDP into the machine.

Wire up the Temperature Humidity Sensor for data collection

  • Connect GND of DHT11 to Ground (pin 6) of the Pi
  • Connect VCC of DHT11 to 5V (pin 2) of Pi
  • Connect DATA of DHT11 to GPIO4 (pin 7) of the Pi

Raspberry GPIO

Raspberry DHT11

  • Get Python library to read DHT humidity and temperature sensors
sudo apt-get update
sudo apt-get install build-essential python-dev
  • Create a file named ‘util.py’ and add the following code. This will get the Raspberry Pi 3 model B serial number
def getId():
    iD = "0000000000000000"
    try:
        f = open('/proc/cpuinfo','r')
        for line in f:
            if line[0:6]=='Serial':
                iD = line[10:26]
        f.close()
    except:
        iD = "ERROR00000000000"
        f.close()
    return iD
  • Create a file named ‘dht11.py’ and ad the following code that will capture DHT11 sensor reading data, convert to json, and print a data.
import ays, datetime, json
import Adafruit_DHT
from util import *
iD = getId()
while True:
    # get timestamp
    dt = str(datetime.datetime.now())
    # get sensor 11 data on GPIO 4
    h, t = Adafruit_DHT.read_retry(11, 4)
    # convert C to F
    f = t * 9. / 5. + 32 # from C to F
    # create json message
    d = {
    'DeviceID': iD,
    'Temperature': f,
    'Humidity': h,
    'Time': dt
    }
    msg = json.dumps(d)
    print(msg)

Saving Events to Azure

  • Now that we have our our data collection working. lets get it to persist this data to the cloud.
  • Install the Azure Python SDK to store data into blob storage via Azure event hub
sudo pip install azure-servicebus
  • Install Azure CLI on Windows 10
  • Use CLI to create an Azure Namespace and Event Hub
  • Add the following function code ‘util.py’ to open the ServiceBusService.
from azure.servicebus import ServiceBusService
from azure.servicebus import Message
def createSBS():
    service_namespace = 'service bus name here'
    key_name = 'event hub here' key_value = 'mKG+x1xmMHso/ZdL/nZ45retMqVXz+HQQjHp98='
    sbs = ServiceBusService(service_namespace, shared_access_key_name=key_name, shared_access_key_value=key_value)
   return sbs
  • Add the following lines of code to ‘dht11.py’ to create the service bus and send a message
sbs = createSBS()
sbs.send_event('event queue name here', msg)

The entire Python code is out on GitHub project here.

Categories: Speaking