Overview

Keep forgetting to water your plants? Want to monitor the ambient temperature of your the room your plant is located in from across the world? 

In this guide, you will build an Internet-enabled plant monitoring display by combining Microsoft's Azure IoT Hub and CircuitPython! 

Using Azure with your CircuitPython IoT projects allows you to rapidly prototype (and even mass-prototype) advanced internet-of-things devices and connect them to Microsoft Azure services. 

Once your CircuitPython device's data is sent to an Azure IoT Hub, you can link your IoT Hub with all of the Azure Cloud Tools, such as:

You can find all the services compatible with the Azure IoT Hub here.

CircuitPython Code

CircuitPython is perfect for building Internet-of-Things projects. This project uses the ESP32SPI CircuitPython library, which can use the ESP32 as a WiFi-coprocessor to send web requests.

We've created a CircuitPython Azure IoT helper module to make interacting with an Azure IoT Hub incredibly simple.

You can rapidly update your code without having to compile and store WiFi and API secret keys on the device. This means that there's no editing code and re-uploading whenever you move the PyPortal to another network - just update a file and you're set. 

Stemma Soil Sensor

This soil sensor uses capacitive measurement. Capacitive measurements use only one probe, don't have any exposed metal, and don't introduce any DC currents into your plants. We use the built in capacitive touch measurement system built into the ATSAMD10 chip, which will give you a reading ranging from about 200 (very dry) to 2000 (very wet).

As a bonus, we also give you the ambient temperature from the internal temperature sensor on the microcontroller, it's not high precision, maybe good to + or - 2 degrees Celsius.

Prerequisite Guides

If you're new to CircuitPython, take a moment to walk through the following guides to get you started and up-to-speed:

Parts

Adafruit PyPortal - CircuitPython Powered Internet Display

PRODUCT ID: 4116
PyPortal, our easy-to-use IoT device that allows you to create all the things for the “Internet of Things” in minutes. Make custom touch screen interface...
$54.95
IN STOCK

Adafruit STEMMA Soil Sensor - I2C Capacitive Moisture Sensor

PRODUCT ID: 4026
Most low cost soil sensors are resistive style, where there's two prongs and the sensor measures the conductivity between the two. These work OK at first, but eventually...
$7.50
IN STOCK

STEMMA Cable - 150mm/6" Long 4 Pin JST-PH Cable–Female/Female

PRODUCT ID: 3568
This 4-wire cable is a little over 150mm / 6" long and fitted with JST-PH female 4-pin connectors on each end. These types of JST cables are commonly found on small rechargeable...
$0.75
IN STOCK

Materials

You'll need some extra supplies to finish this project. If you do not have them already, pick some up from Adafruit.

1 x PyPortal Stand
Adafruit PyPortal Desktop Stand Enclosure Kit
1 x USB Cable
Pink and Purple Braided USB A to Micro B Cable - 2 meter long

PyPortal Wiring

We recommend using a Female-to-Female Stemma Connector and plugging it in between the PyPortal and the STEMMA Soil Sensor. No soldering is involved - just connect the cable between the Stemma Soil Sensor and the PyPortal's I2C port.

STEMMA Cable - 150mm/6" Long 4 Pin JST-PH Cable–Female/Female

PRODUCT ID: 3568
This 4-wire cable is a little over 150mm / 6" long and fitted with JST-PH female 4-pin connectors on each end. These types of JST cables are commonly found on small rechargeable...
$0.75
IN STOCK

The cable makes the following connections between the PyPortal's I2C port and the STEMMA Soil Sensor:

  • PyPortal 5V to Sensor VIN
  • PyPortal GND to Sensor GND
  • PyPortal SCL to Sensor SCL
  • PyPortal SDA to Sensor SDA

That's it - your PyPortal is wired up!

When you're ready, just stick the STEMMA Soil sensor into your plant's soil. Be sure to leave the white portion of the sensor not covered by soil. You may also want to position the sensor at the edge of your plant's pot.

Internet Connect!

Once you have CircuitPython setup and libraries installed we can get your board connected to the Internet. Note that access to enterprise level secured WiFi networks is not currently supported, only WiFi networks that require SSID and password.

To get connected, you will need to start by creating a secrets file.

What's a secrets file?

We expect people to share tons of projects as they build CircuitPython WiFi widgets. What we want to avoid is people accidentally sharing their passwords or secret tokens and API keys. So, we designed all our examples to use a secrets.py file, that is in your CIRCUITPY drive, to hold secret/private/custom data. That way you can share your main project without worrying about accidentally sharing private stuff.

Your secrets.py file should look like this:

Download: file
# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it

secrets = {
    'ssid' : 'home ssid',
    'password' : 'my password',
    'timezone' : "America/New_York", # http://worldtimeapi.org/timezones
    'github_token' : 'fawfj23rakjnfawiefa',
    'hackaday_token' : 'h4xx0rs3kret',
    }

Inside is a python dictionary named secrets with a line for each entry. Each entry has an entry name (say 'ssid') and then a colon to separate it from the entry key 'home ssid' and finally a comma ,

At a minimum you'll need the ssid and password for your local WiFi setup. As you make projects you may need more tokens and keys, just add them one line at a time. See for example other tokens such as one for accessing github or the hackaday API. Other non-secret data like your timezone can also go here, just cause its called secrets doesn't mean you can't have general customization data in there!

For the correct time zone string, look at http://worldtimeapi.org/timezones and remember that if your city is not listed, look for a city in the same time zone, for example Boston, New York, Philadelphia, Washington DC, and Miami are all on the same time as New York.

Of course, don't share your secrets.py - keep that out of GitHub, Discord or other project-sharing sites.

Connect to WiFi

OK now you have your secrets setup - you can connect to the Internet. Lets use the ESP32SPI and the Requests libraries - you'll need to visit the CircuitPython bundle and install:

  • adafruit_bus_device
  • adafruit_esp32spi
  • adafruit_requests
  • neopixel

Into your lib folder. Once that's done, load up the following example using Mu or your favorite editor:

import board
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests

print("ESP32 SPI webclient test")

TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
JSON_URL = "http://api.coindesk.com/v1/bpi/currentprice/USD.json"


# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

requests.set_socket(socket, esp)

if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
    print("ESP32 found and in idle mode")
print("Firmware vers.", esp.firmware_version)
print("MAC addr:", [hex(i) for i in esp.MAC_address])

for ap in esp.scan_networks():
    print("\t%s\t\tRSSI: %d" % (str(ap['ssid'], 'utf-8'), ap['rssi']))

print("Connecting to AP...")
while not esp.is_connected:
    try:
        esp.connect_AP(b'MY_SSID_NAME', b'MY_SSID_PASSWORD')
    except RuntimeError as e:
        print("could not connect to AP, retrying: ",e)
        continue
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)
print("My IP address is", esp.pretty_ip(esp.ip_address))
print("IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com")))
print("Ping google.com: %d ms" % esp.ping("google.com"))

#esp._debug = True
print("Fetching text from", TEXT_URL)
r = requests.get(TEXT_URL)
print('-'*40)
print(r.text)
print('-'*40)
r.close()

print()
print("Fetching json from", JSON_URL)
r = requests.get(JSON_URL)
print('-'*40)
print(r.json())
print('-'*40)
r.close()

print("Done!")

And save it to your board, with the name code.py

This first connection example doesn't use a secrets file - you'll hand-enter your SSID/password to verify connectivity first!

Then go down to this line

esp.connect_AP(b'MY_SSID_NAME', b'MY_SSID_PASSWORD')

and change MY_SSID_NAME and MY_SSID_PASSWORD to your access point name and password, keeping them within the '' quotes. (This example doesn't use the secrets' file, but its also very stand-alone so if other things seem to not work you can always re-load this. You should get something like the following:

In order, the example code...

Initializes the ESP32 over SPI using the SPI port and 3 control pins:

Download: file
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

Tells our requests library the type of socket we're using (socket type varies by connectivity type - we'll be using the adafruit_esp32spi_socket for this example). We'll also set the interface to an esp object. This is a little bit of a hack, but it lets us use requests like CPython does.

Download: file
requests.set_socket(socket, esp)

Verifies an ESP32 is found, checks the firmware and MAC address

Download: file
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
    print("ESP32 found and in idle mode")
print("Firmware vers.", esp.firmware_version)
print("MAC addr:", [hex(i) for i in esp.MAC_address])

Performs a scan of all access points it can see and prints out the name and signal strength:

Download: file
for ap in esp.scan_networks():
    print("\t%s\t\tRSSI: %d" % (str(ap['ssid'], 'utf-8'), ap['rssi']))

Connects to the AP we've defined here, then prints out the local IP address, attempts to do a domain name lookup and ping google.com to check network connectivity (note sometimes the ping fails or takes a while, this isn't a big deal)

Download: file
    print("Connecting to AP...")
esp.connect_AP(b'MY_SSID_NAME', b'MY_SSID_PASSWORD')
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)
print("My IP address is", esp.pretty_ip(esp.ip_address))
print("IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com")))
print("Ping google.com: %d ms" % esp.ping("google.com"))
  

OK now we're getting to the really interesting part. With a SAMD51 or other large-RAM (well, over 32 KB) device, we can do a lot of neat tricks. Like for example we can implement an interface a lot like requests - which makes getting data really really easy

To read in all the text from a web URL call requests.get - you can pass in https URLs for SSL connectivity

Download: file
TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
print("Fetching text from", TEXT_URL)
r = requests.get(TEXT_URL)
print('-'*40)
print(r.text)
print('-'*40)
r.close()

Or, if the data is in structured JSON, you can get the json pre-parsed into a Python dictionary that can be easily queried or traversed. (Again, only for nRF52840, M4 and other high-RAM boards)

Download: file
JSON_URL = "http://api.coindesk.com/v1/bpi/currentprice/USD.json"
print("Fetching json from", JSON_URL)
r = requests.get(JSON_URL)
print('-'*40)
print(r.json())
print('-'*40)
r.close()

Requests

We've written a requests-like library for web interfacing named Adafruit_CircuitPython_Requests. This library allows you to send HTTP/1.1 requests without "crafting" them and provides helpful methods for parsing the response from the server.

# adafruit_requests usage with an esp32spi_socket
import board
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests

# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

print("Connecting to AP...")
while not esp.is_connected:
    try:
        esp.connect_AP(b'MY_SSID_NAME', b'MY_SSID_PASSWORD')
    except RuntimeError as e:
        print("could not connect to AP, retrying: ",e)
        continue
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)

# Initialize a requests object with a socket and esp32spi interface
requests.set_socket(socket, esp)

TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
JSON_GET_URL = "http://httpbin.org/get"
JSON_POST_URL = "http://httpbin.org/post"

print("Fetching text from %s"%TEXT_URL)
response = requests.get(TEXT_URL)
print('-'*40)

print("Text Response: ", response.text)
print('-'*40)
response.close()

print("Fetching JSON data from %s"%JSON_GET_URL)
response = requests.get(JSON_GET_URL)
print('-'*40)

print("JSON Response: ", response.json())
print('-'*40)
response.close()

data = '31F'
print("POSTing data to {0}: {1}".format(JSON_POST_URL, data))
response = requests.post(JSON_POST_URL, data=data)
print('-'*40)

json_resp = response.json()
# Parse out the 'data' key from json_resp dict.
print("Data received from server:", json_resp['data'])
print('-'*40)
response.close()

json_data = {"Date" : "July 25, 2019"}
print("POSTing data to {0}: {1}".format(JSON_POST_URL, json_data))
response = requests.post(JSON_POST_URL, json=json_data)
print('-'*40)

json_resp = response.json()
# Parse out the 'json' key from json_resp dict.
print("JSON Data received from server:", json_resp['json'])
print('-'*40)
response.close()

The code first sets up the ESP32SPI interface. Then, it initializes a request object using an ESP32 socket and the esp object.

Download: file
import board
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests

# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

print("Connecting to AP...")
while not esp.is_connected:
    try:
        esp.connect_AP(b'MY_SSID_NAME', b'MY_SSID_PASSWORD')
    except RuntimeError as e:
        print("could not connect to AP, retrying: ",e)
        continue
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)

# Initialize a requests object with a socket and esp32spi interface
requests.set_socket(socket, esp)

HTTP GET with Requests

The code makes a HTTP GET request to Adafruit's WiFi testing website - http://wifitest.adafruit.com/testwifi/index.html.

To do this, we'll pass the URL into requests.get(). We're also going to save the response from the server into a variable named response.

While we requested data from the server, we'd what the server responded with. Since we already saved the server's response, we can read it back. Luckily for us, requests automatically decodes the server's response into human-readable text, you can read it back by calling response.text.

Lastly, we'll perform a bit of cleanup by calling response.close(). This closes, deletes, and collect's the response's data. 

Download: file
print("Fetching text from %s"%TEXT_URL)
response = requests.get(TEXT_URL)
print('-'*40)

print("Text Response: ", response.text)
print('-'*40)
response.close()

While some servers respond with text, some respond with json-formatted data consisting of attribute–value pairs.

CircuitPython_Requests can convert a JSON-formatted response from a server into a CPython dict. object.

We can also fetch and parse json data. We'll send a HTTP get to a url we know returns a json-formatted response (instead of text data). 

Then, the code calls response.json() to convert the response to a CPython dict

Download: file
print("Fetching JSON data from %s"%JSON_GET_URL)
response = requests.get(JSON_GET_URL)
print('-'*40)

print("JSON Response: ", response.json())
print('-'*40)
response.close()

HTTP POST with Requests

Requests can also POST data to a server by calling the requests.post method, passing it a data value.

Download: file
data = '31F'
print("POSTing data to {0}: {1}".format(JSON_POST_URL, data))
response = requests.post(JSON_POST_URL, data=data)
print('-'*40)

json_resp = response.json()
# Parse out the 'data' key from json_resp dict.
print("Data received from server:", json_resp['data'])
print('-'*40)
response.close()

You can also post json-formatted data to a server by passing json_data into the requests.post method.

Download: file
    json_data = {"Date" : "July 25, 2019"}
print("POSTing data to {0}: {1}".format(JSON_POST_URL, json_data))
response = requests.post(JSON_POST_URL, json=json_data)
print('-'*40)

json_resp = response.json()
# Parse out the 'json' key from json_resp dict.
print("JSON Data received from server:", json_resp['json'])
print('-'*40)
response.close()
  

Advanced Requests Usage

Want to send custom HTTP headers, parse the response as raw bytes, or handle a response's http status code in your CircuitPython code?

We've written an example to show advanced usage of the requests module below.

import board
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests

# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

print("Connecting to AP...")
while not esp.is_connected:
    try:
        esp.connect_AP(b'MY_SSID_NAME', b'MY_SSID_PASSWORD')
    except RuntimeError as e:
        print("could not connect to AP, retrying: ",e)
        continue
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)

# Initialize a requests object with a socket and esp32spi interface
requests.set_socket(socket, esp)

JSON_GET_URL = "http://httpbin.org/get"

# Define a custom header as a dict.
headers = {"user-agent" : "blinka/1.0.0"}

print("Fetching JSON data from %s..."%JSON_GET_URL)
response = requests.get(JSON_GET_URL, headers=headers)
print('-'*60)

json_data = response.json()
headers = json_data['headers']
print("Response's Custom User-Agent Header: {0}".format(headers['User-Agent']))
print('-'*60)

# Read Response's HTTP status code
print("Response HTTP Status Code: ", response.status_code)
print('-'*60)

# Read Response, as raw bytes instead of pretty text
print("Raw Response: ", response.content)

# Close, delete and collect the response data
response.close()

WiFi Manager

That simpletest example works but its a little finicky - you need to constantly check WiFi status and have many loops to manage connections and disconnections. For more advanced uses, we recommend using the WiFiManager object. It will wrap the connection/status/requests loop for you - reconnecting if WiFi drops, resetting the ESP32 if it gets into a bad state, etc.

Here's a more advanced example that shows the WiFi manager and also how to POST data with some extra headers:

import time
import board
import busio
from digitalio import DigitalInOut
import neopixel
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager

print("ESP32 SPI webclient test")

# Get wifi details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
"""Use below for Most Boards"""
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
"""Uncomment below for ItsyBitsy M4"""
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
# Uncomment below for an externally defined RGB LED
# import adafruit_rgbled
# from adafruit_esp32spi import PWMOut
# RED_LED = PWMOut.PWMOut(esp, 26)
# GREEN_LED = PWMOut.PWMOut(esp, 27)
# BLUE_LED = PWMOut.PWMOut(esp, 25)
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)

counter = 0

while True:
    try:
        print("Posting data...", end='')
        data = counter
        feed = 'test'
        payload = {'value':data}
        response = wifi.post(
            "https://io.adafruit.com/api/v2/"+secrets['aio_username']+"/feeds/"+feed+"/data",
            json=payload,
            headers={"X-AIO-KEY":secrets['aio_key']})
        print(response.json())
        response.close()
        counter = counter + 1
        print("OK")
    except (ValueError, RuntimeError) as e:
        print("Failed to get data, retrying\n", e)
        wifi.reset()
        continue
    response = None
    time.sleep(15)

You'll note here we use a secrets.py file to manage our SSID info. The wifimanager is given the ESP32 object, secrets and a neopixel for status indication.

Note, you'll need to add a some additional information to your secrets file so that the code can query the Adafruit IO API:

  • aio_username
  • aio_key

You can go to your adafruit.io View AIO Key link to get those two values and add them to the secrets file, which will now look something like this:

Download: file
# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it

secrets = {
    'ssid' : '_your_ssid_',
    'password' : '_your_wifi_password_',
    'timezone' : "America/Los_Angeles", # http://worldtimeapi.org/timezones
    'aio_username' : '_your_aio_username_',
    'aio_key' : '_your_aio_key_',
    }

Next, set up an Adafruit IO feed named test

We can then have a simple loop for posting data to Adafruit IO without having to deal with connecting or initializing the hardware!

Take a look at your test feed on Adafruit.io and you'll see the value increase each time the CircuitPython board posts data to it!

PyPortal CircuitPython Setup

To use all the amazing features of your PyPortal with CircuitPython, you must first install a number of libraries. This page covers that process.

Adafruit CircuitPython Bundle

Download the Adafruit CircuitPython Library Bundle. You can find the latest release here:

Download the adafruit-circuitpython-bundle-4.x-mpy-*.zip bundle zip file, and unzip a folder of the same name. Inside you'll find a lib folder. You have two options:

  • You can add the lib folder to your CIRCUITPY drive. This will ensure you have all the drivers. But it will take a bunch of space on the 8 MB disk
  • Add each library as you need it, this will reduce the space usage but you'll need to put in a little more effort.

At a minimum we recommend the following libraries, in fact we more than recommend. They're basically required. So grab them and install them into CIRCUITPY/lib now!

  • adafruit_esp32spi - This is the library that gives you internet access via the ESP32 using (you guessed it!) SPI transport. You need this for anything Internet
  • adafruit_requests - This library allows us to perform HTTP requests and get responses back from servers. GET/POST/PUT/PATCH - they're all in here!
  • adafruit_pyportal - This is our friendly wrapper library that does a lot of our projects, displays graphics and text, fetches data from the internet. Nearly all of our projects depend on it!
  • adafruit_touchscreen - a library for reading touches from the resistive touchscreen. Handles all the analog noodling, rotation and calibration for you.
  • adafruit_cursorcontrol - a library for reading PyGamer and PyBadge joystick and buttons. Handles all the graphics, button press reading and joystick movement for you.
  • adafruit_io - this library helps connect the PyPortal to our free datalogging and viewing service
  • adafruit_imageload - an image display helper, required for any graphics!
  • adafruit_display_text - not surprisingly, it displays text on the screen
  • adafruit_bitmap_font - we have fancy font support, and its easy to make new fonts. This library reads and parses font files.
  • adafruit_slideshow - for making image slideshows - handy for quick display of graphics and sound
  • neopixel - for controlling the onboard neopixel
  • adafruit_adt7410 - library to read the temperature from the on-board Analog Devices ADT7410 precision temperature sensor
  • adafruit_sdcard - support for reading/writing data from the onboard SD card slot.
  • adafruit_bus_device - low level support for I2C/SPI

Microsoft Azure Setup

Please note: Azure is a PAID IoT service - you will be charged for usage. For non-production usage, keep track of the billing & make sure that you shut off any running services if you're not using them.

Create an IoT Hub

Microsoft's Azure IoT Hub requires an active Microsoft Azure account. Azure is a PAID internet-of-things service, and will require you to enter a valid credit-card (even for their free tier).

Now that you have a Microsoft Azure account, you'll want to set up an Azure IoT Hub. This will be your "endpoint" for sending messages to, and receiving messages from.

To authenticate with the Azure IoT Hub, you'll need to obtain a Shared-Access-Signature token for your Azure IoT Hub.

From your Microsoft Azure Portal, open a new console instance by clicking the >_ icon on the top menu bar. 

Once the Azure console has been loaded and a connection is established, enter the following command into the console. Make sure to replace azure-hub-name with the name your IoT Hub.

Download: file
az iot hub generate-sas-token --hub-name azure-hub-name

After you hit enter, the Azure Console will take a moment and then display a freshly generated SAS token:

Download: file
[email protected]:~$ az iot hub generate-sas-token --hub-name airlift-test-hub
{
  "sas": "SharedAccessSignature sr=azure-test-hub.azure-devices.net&sig=jzaRYmbAK6eShkB1mU0fByZREuX4UV8mzfv0vnv7HyU%3D&se=1558473904&skn=iothubowner"
}

In the response, copy and paste the SAS token into a notepad or text file and save it somewhere safe. We'll need it in our the following step.

Note: The SAS token is not the full response returned by the Azure CLI in the code snippet above - it looks like the following:

Download: file
SharedAccessSignature sr=azure-test-hub.azure-devices.net&sig=jzaRYmbAK6eShkB1mU0fByZREuX4UV8mzfv0vnv7HyU%3D&se=1558473904&skn=iothubowner

Once you have a SAS token, you can continue to adding an IoT Device to the IoT Hub.

Add IoT Devices to your IoT Hub

Now that you have an IoT Hub set up, you'll need to create IoT Devices to connect to the Azure IoT Hub. Azure allows addressing of each device by a device identifier. This is incredibly handy if you have more than one device, such as a temperature logger, in your home. You can send data from, and to, each device using its device identifier.

From your Azure IoT Hub Portal, navigate to Explorers -> IoT devices

This page will display the devices currently on your IoT Hub along with metrics such as their Last Activity and Status

On the top left, click Add to add a new device.

In the Create a Device menu, make the following changes:

  • Set a unique Device ID 
    • You can set this to any alphanumeric value, make it as descriptive as you want!
  • Select Symmetric Key for Authentication Type
  • Tick the checkbox to Auto-generate keys
  • Enable Connect this device to an IoT Hub

Then, Click Save

You'll be re-directed back to the Device Explorer.

If everything worked correctly, you should now see your new device in the Device Explorer.

Congrats - you've successfully set up an Azure IoT Hub and connected a device to it! Next, we'll set up your CircuitPython device to connect to the IoT Hub.

Code Setup

CircuitPython Library Installation

First make sure you are running the latest version of Adafruit CircuitPython for your board.

Next you'll need to install the necessary libraries to use the hardware--carefully follow the steps to find and install these libraries from Adafruit's CircuitPython library bundle matching your version of CircuitPython. PyPortal requires at least CircuitPython version 4.0.0.

Before continuing make sure your board's lib folder has the following files and folders copied over.

  • adafruit_azureiot
  • adafruit_bitmap_font
  • adafruit_bus_device
  • adafruit_display_text
  • adafruit_esp32spi
  • adafruit_register
  • adafruit_seesaw
  • neopixel

Add CircuitPython Code and Project Assets

In the embedded code element below, click on the Download: Project Zip link, and save the .zip archive file to your computer.

Then, uncompress the .zip file, it will unpack to a folder named PyPortal_Azure_Plant_Monitor.

Copy the contents of the PyPortal_Azure_Plant_Monitor directory to your PyPortal's CIRCUITPY drive.

"""
PyPortal Azure IoT Plant Monitor
====================================================
Log plant vitals to Microsoft Azure IoT with
your PyPortal

Author: Brent Rubell for Adafruit Industries, 2019
"""
import time
import board
import busio
from digitalio import DigitalInOut
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
import neopixel
from adafruit_azureiot import IOT_Hub
from adafruit_seesaw.seesaw import Seesaw

# gfx helper
import azure_gfx_helper

# Get wifi details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

# PyPortal ESP32 Setup
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)

# Soil Sensor Setup
i2c_bus = busio.I2C(board.SCL, board.SDA)
ss = Seesaw(i2c_bus, addr=0x36)

# Create an instance of the Azure IoT Hub
hub = IOT_Hub(wifi, secrets['azure_iot_hub'], secrets['azure_iot_sas'], secrets['azure_device_id'])

# init. graphics helper
gfx = azure_gfx_helper.Azure_GFX(False)

while True:
    try:
        # read moisture level
        moisture_level = ss.moisture_read()
        # read temperature
        temperature = ss.get_temp()
        # display soil sensor values on pyportal
        gfx.display_moisture(moisture_level)
        temperature = gfx.display_temp(temperature)
        print('Sending data to Azure')
        gfx.display_azure_status('Sending data...')
        hub.send_device_message(temperature)
        hub.send_device_message(moisture_level)
        gfx.display_azure_status('Data sent!')
        print('Data sent!')
    except (ValueError, RuntimeError) as e:
        print("Failed to get data, retrying\n", e)
        wifi.reset()
        continue
    time.sleep(60)

This is what the final contents of the CIRCUITPY drive will look like:

Install the Mu Editor

This guide requires you to edit and interact with CircuitPython code. While you can use any text editor of your choosing,  Mu is a simple code editor that works with the Adafruit CircuitPython boards. It's written in Python and works on Windows, MacOS, Linux and Raspberry Pi. The serial console is built right in, so you get immediate feedback from your board's serial output!

Before proceeding, click the button below to install the Mu Editor. There are versions for PC, mac, and Linux.

Secrets File Setup

First, use Mu to open up a secrets.py file on your CIRCUITPY drive. Next, you're going to edit the file to enter your local WiFi credentials along with data about your Azure Device and Hub.

Make the following changes to the code below in the secrets.py file:

  • Replace MY_WIFI_SSID with the name of your WiFi SSID
  • Replace MY_WIFI_PASSWORD with your WiFi's password
  • Replace MY_AZURE_HUB_NAME with the name of your Azure IoT Hub.
  • Replace MY_AZURE_HUB_SAS_TOKEN with the Shared Access Signature token you copied down earlier.
  • Replace MY_AZURE_DEVICE_ID with the name of your Azure IoT Device.
Download: file
# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it

secrets = {
    'ssid' : 'MY_WIFI_SSID',
    'password' : 'MY_WIFI_PASSWORD',
    'azure_iot_hub' : 'MY_AZURE_HUB_NAME',
    'azure_iot_sas' : 'MY_AZURE_HUB_SAS_TOKEN',
    'azure_device_id' : 'MY_AZURE_DEVICE_ID'
}

You can then close secrets.py, saving the updated file onto the device.

Done

Setting up the PyPortal with the Azure IoT Hub is finished! You do not need to repeat this process again unless you change your IoT Hub name, or your SAS token expires.

Code Usage

Viewing Data on the PyPortal

When the PyPortal starts up, it will first load the azure_splash.bmp image in the images folder on your CIRCUITPY drive. This is a "loading screen" while the code waits for the fonts and display objects load on the screen.

You should see the PyPortal display update to display the temperature value and moisture level.

The status indicator at the bottom of the PyPortal will display when it's sending data to Azure IoT Hub and also display when the data is sent. 

Monitoring Azure IoT Hub Events

While your PyPortal shows that its sending data to the IoT Hub, you'll need to check that the hub is receiving your PyPortal's messages.

From your Azure Portal, open a new console instance by clicking the >_ icon on the top menubar. 

After the console connects, enter the following command, replacing your-test-hub with the name of your IoT Hub resource

Download: file
az iot hub monitor-events --hub-name your-azure-hub

If you're sending data to the Azure Hub from your CircuitPython device, data will be displayed in the Azure Console as it comes in:

Download: file
[email protected]:~$ az iot hub monitor-events --hub-name azure-airlift-test-hub
Starting event monitor, use ctrl-c to stop...
{
    "event": {
        "origin": "PyPortal",
        "payload": 67
    }
}
{
    "event": {
        "origin": "PyPortal",
        "payload": 627
    }
}

Here, we can see that two new pieces of data (called events) were received by the hub. The origin is the device identifier's name and the payload is the data sent by the PyPortal.

If you have a large amount of IoT devices sending the same type of data (lots of PyPortal Planters!), you would be able to identify them by sorting by the origin.

Not sure if the hub is receiving the correct data? Add a print() statement to your CircuitPython code to print the data to the REPL. Then, cross-verify the value displayed in the REPL against the value received by the Azure IoT Hub. 

Going Further

Ready to go further with your CircuitPython-Powered Azure-connected IoT Device? The CircuitPython_AzureIoT module provides usage examples for advanced Azure IoT operations such as device management, device-to-cloud communication, device twin operations, and cloud-to-device communication.

Since you have your device's data on an Azure IoT resource - you may also be interested in bridging Azure IoT and the rest of Microsoft's Azure tools:

Code Walkthrough

Importing CircuitPython Libraries

Download: file
import board
import busio
import time
from digitalio import DigitalInOut
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
import neopixel
from adafruit_azureiot import IOT_Hub
from adafruit_seesaw.seesaw import Seesaw

# gfx helper
import azure_gfx_helper

The code first imports all of the modules required to run the code. Some of these libraries are  CircuitPython core modules (they're "burned into" the firmware) and some of them you dragged into the library folder.

The code for this project imports a special adafruit_azureiot library. To help simplify communication between your device and Azure IoT's REST API, we wrote a CircuitPython helper module called Adafruit_CircuitPython_AzureIoT

We've also included an azure_gfx_helper.py file which handles displaying the status of the code on the PyPortal's display.

Configuring the PyPortal's WiFi

The next chunk of code grabs information from a secrets.py file including wifi configuration. Then, it sets up the ESP32's SPI connections for use with the PyPortal. The wifi object is set up here too - it's used later in the code to communicate with the IoT Hub.

Download: file
# Get wifi details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

# PyPortal ESP32 Setup
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
"""Uncomment below for ItsyBitsy M4"""
#status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)

Configuring the Soil Sensor

An I2C busio device is set up and linked to the soil sensor's address (0x36)

Download: file
# Soil Sensor Setup
i2c_bus = busio.I2C(board.SCL, board.SDA)
ss = Seesaw(i2c_bus, addr=0x36)

Configuring the Azure IoT Module

Next, we'll create an instance of the Azure IoT Hub called hub. It takes in the WiFiManager object, wifi, the name of the IoT hub, the hub's SAS token, and the name of the device sending data to the hub.

Download: file
# Create an instance of the Azure IoT Hub
hub = IOT_Hub(wifi, secrets['azure_iot_hub'], secrets['azure_iot_sas'], secrets['azure_device_id'])

Configuring the Graphical Helper 

The graphics helper, which manages' the PyPortal's display is created. If you want to show the temperature in Fahrenheit instead of Celsius, change is_celsius=False to is_celsius=True.

Download: file
# init. graphics helper
gfx = azure_gfx_helper.Azure_GFX(is_celsius=False)

Main Loop

The first part of the main loop reads the soil sensor's (ss) moisture level and temperature. It then calls gfx.display_moisture and gfx.display_temp to display the moisture and temperature values on the PyPortal's display

Download: file
# read moisture level
moisture_level = ss.moisture_read()
# read temperature
temperature = ss.get_temp()
# display soil sensor values on pyportal
gfx.display_moisture(moisture_level)
temperature = gfx.display_temp(temperature)

The next chunk of code changes the display's status text to indicate that the data is being sent to the Azure hub. Next we have two hub.send_device_message() calls - one to send the stemma soil sensor's temperature and one to send the moisture_level.

After the two send_device_message calls are completed, the Azure status text area is changed to indicate that data has been sent.

Download: file
print('Sending data to Azure')
gfx.display_azure_status('Sending data...')
hub.send_device_message(temperature)
hub.send_device_message(moisture_level)
gfx.display_azure_status('Data sent!')
print('Data sent!')

All of this code is wrapped inside a try/except control flow. If the WiFi module fails at any point, the program will execute the except and reset the module before going back to the top of the try.

Finally, the code will "sleep" for sixty seconds. If you'd like to make a longer delay, simply increase the value inside the call to time.sleep().

Download: file
except (ValueError, RuntimeError) as e:
  time.sleep(60)
This guide was first published on May 24, 2019. It was last updated on May 24, 2019.