A rosemary plant connected to a PyPortal tracking temperature and soil moisture
A rosemary plant connected to a PyPortal tracking temperature and soil moisture

Keep forgetting to water your plants? Want to monitor the ambient temperature of 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 Azure IoT Central from Microsoft 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 Azure IoT Central, you can visualize your data on a dashboard. From there you can connect other Azure services such as:

  • Azure Blob Storage: Blob storage for all your sensor data to analyze later
  • Event Hubs: Real-time data pipelines capable of streaming millions of events per second between Azure services
  • Azure Stream Analytics: Real-time analytics pipeline allowing you to query data in real time
  • Azure Machine Learning: Build machine learning models that can be used from Stream Analytics to provide real-time predictions over your data

You can get hands on with and learn more about the Azure IoT services on Microsoft Learn.

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 provide an API to interact with Azure IoT Central.

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...
OUT OF 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',
    'id_scope' : '0101018D',
    'device_id' : 'pyportal',
    'key' : 'MyK3y=='
    }

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 ones needed to access Azure IoT Central. Other non-secret data can also go here, just cause its called secrets doesn't mean you can't have general customization data in there!

Of course, don't share your secrets.py - keep that out of GitHub, Discord or other project-sharing sites. For example, if you are using git, you should add it to your .gitignore file.

Connect to WiFi

OK now you have your secrets file set up, then you can look to connecting 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 Visual Studio Code, Mu or your favorite editor:

Download: file
import board
import busio
from digitalio import DigitalInOut
import neopixel
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
from secrets import secrets

print("ESP32 SPI webclient test")

# Get the pins for the PyPortal
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

# Initialize the ESP over SPI
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

# Configure the status light
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)

# Connect the WiFi manager
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
wifi.connect()

# Log the connection details
print("Connected to", str(esp.ssid, "utf-8"))
print("My IP address is", esp.pretty_ip(esp.ip_address))

# Look up some sites to validate the connection
print("IP lookup adafruit.com: %s" % 
      esp.pretty_ip(esp.get_host_by_name("adafruit.com")))
print("Ping Bing.com: %d ms" % esp.ping("bing.com"))

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

You should see something like the following on the screen on your PyPortal:

Download: file
ESP32 SPI webclient test
Connected to MySSID
My IP address is 192.168.0.1
IP lookup adafruit.com: 104.20.39.240
Ping Bing.com: 10 ms

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-*.x-mpy-*.zip bundle zip file where *.x MATCHES THE VERSION OF CIRCUITPYTHON YOU INSTALLED, 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

Azure IoT Central Setup

Please note: In this guide you can use a free tier of Azure IoT Central with up to 2 PyPortals, but if you want to use more devices or other services, there may be a charge. Keep track of any services you create, and ensure you delete any services you are no longer using.

Azure IoT Central

Azure IoT Central is an IoT platform allowing you to quickly create an IoT application that gathers data from devices and displays it on a dashboard. It also has many more capabilities including being able to synchronize data to a device, command the device to perform an action, export data to a range of other Azure services, and set up rules that can be triggered when data breaches certain ranges.

Azure Subscription

To use Azure IoT Central it is recommended to have an Azure subscription. If you don't already have an Azure Subscription, you can sign up for free.

  • Azure for Students - If you are a student aged 18 or over you can sign up for a free Azure for Students account at azure.microsoft.com/free/students. This will give you US$100 of Azure credit and 12 months of free tiers of various Azure services, along with some services offering free tiers for life. This can be renewed every 12 months that you remain a student.
  • Azure free account - Sign up for an Azure free subscription at azure.microsoft.com/free. This will give you US$200 of credit for the first 30 days along with 12 months of free tiers of various Azure services, along with some services offering free tiers for life. You will need a credit card for verification purposes, but your card will NOT be charged until you explicitly convert to a pay-as-you-go account, if you run out of credit your services will be disabled instead of you receiving a bill.
You can still use Azure IoT Central without an Azure subscription, but any apps you create will only live for 7 days.

Azure IoT Central application

To get started with Azure IoT Central, you need to create an IoT Central application. Applications manage the IoT devices they are connected to, as well as defining what the capabilities of the devices are - for example what telemetry values they might send. Applications can also define dashboards for devices to visualize the data they send.

The simplest way to create an application is to copy one from an existing application template. Click the button below to launch Azure IoT Central and create a pre-defined application for this project.

You will need to log in with a Microsoft account. If you have an Azure subscription, use the account that was used to create the Azure subscription. If you don't have a Microsoft account, there is an option to create one. You can create one with any email address.

Once you have logged in, you will be presented with a template for a new application with some fields to fill in.

App information

The IoT Central app name and URL fields
Set the application name and URL
  • Application name: Set this to a name that makes sense for your application, for example PyPortal Plant Monitor.
  • URL: Set this to a unique URL for your app. The final app URL will end with .azureiotcentral.com. This value needs to be globally unique, so you can leave it as the default value that is created, or try to find a unique value of your own, for example by including your name.

Pricing plan

Pricing details for Azure IoT Central with a free tier for up to 7 days, an S1 tier for 5000 messages a month and a S2 tier for 30000 messages a month
Set the pricing plan

Select the pricing plan you want to use.

For the Free plan you don't need an Azure subscription, but you will need to provide a phone number for verification. Free plans expire after 7 days,

For the S plans, you can have up to 2 devices for free, and will need an Azure subscription. If you exceed the message limits then you won't be charged more, instead the messages will be lost.

To get more details on pricing, including the cost to use more than 2 devices, read the Azure IoT Central Pricing docs.

Contact info (Free plan)

Contact info form with fields for name, email, phone number and region
Set your contact info

If you select the free plan, you will need to provide some contact information. Enter your name, phone number and the region closest to you.

The phone number will be verified to ensure you are not a bot. The region will be used to work out where in the world to deploy your application so that it is as close to you as possible.

Billing info (Standard plans)

Billing info form with fields for the Azure directory, subscription and location
Select your Azure subscription details

If you select a standard plan, you will need to select your Azure directory and subscription. If you only have one subscription then the directory and subscription will be pre-filled for you. If you have access to more then select the one you want to use.

Then select the location closest to you. The location will be used to work out where in the world to deploy your application so that it is as close to you as possible.

Create

The create button
Select Create to create the app

Once the form is filled out, select the Create button.

Azure IoT Central will provision your application, then load it.

Configure the PyPortal as a device

The IoT Central application that was created defines a device template for the PyPortal - a description of the telemetry data that a device can send as well as a dashboard to visualize that data. This device template lists two possible telemetry values - temperature and soil moisture. The dashboard shows these values by listing the last received value, as well as a graph of values over time.

To connect a PyPortal, you need to create a device in IoT Central that uses the device template.

Selecting the devices tab, then the PyPortal Plant Monitor template, then the New button
Create a new device

From the side menu, select Devices. This will show a list of device templates, so select PyPortal Plant Monitor. Then select + New.

The create new device dialog where you can select the template type and give the device a name and id
The create device dialog

In the Create a new device dialog, enter the details for the device.

  • Template type: This is already set to the PyPortal template
  • Device name: Give the device a name that makes sense to you
  • Device ID: Give the device a unique ID
  • Simulate this device: Set this to No. IoT Central can create simulated devices to test out your application, and these send dummy data.

Then select Create.

The device will be created and show up in the Devices list.

The IoT Central dashboard for the PyPortal without any data
The device dashboard

Select the device from the Devices list, and it will show up with a dashboard, with fields for the temperature and soil moisture data showing Waiting for data.

The device connect button
The device connect button

The final step is to get connection information for the device. This is a set of fields that are needed by the the device to connect to IoT Central and authenticate itself as the device in question.

Select the Connect button in the top corner.

The connect dialog showing the ID scope, device id and keys
The Device Connection dialog

From this dialog, take a copy of the ID scope, the Device ID and the Primary key.

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_binascii
  • adafruit_bitmap_font
  • adafruit_bus_device
  • adafruit_display_text
  • adafruit_esp32spi
  • adafruit_logging
  • adafruit_minimqtt
  • adafruit_ntp
  • adafruit_requests
  • 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 Central with
your PyPortal

Authors: Brent Rubell for Adafruit Industries, 2019
       : Jim Bennett for Microsoft, 2020
"""
import time
import json
import board
import busio
from digitalio import DigitalInOut
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
import neopixel
from adafruit_ntp import NTP
from adafruit_azureiot import IoTCentralDevice
from adafruit_seesaw.seesaw import Seesaw

# gfx helper
import azure_gfx_helper

# init. graphics helper
gfx = azure_gfx_helper.Azure_GFX(is_celsius=True)

# 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)

# Set up the WiFi manager with a status light to show the WiFi connection status
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
print("WiFi connecting...")
wifi.connect()
print("WiFi connected!")

# Time setup, needed to authenticate with Azure IoT Central
ntp = NTP(esp)
while not ntp.valid_time:
    print("Failed to obtain time, retrying in 5 seconds...")
    time.sleep(5)
    ntp.set_time()

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

# Create an instance of the Azure IoT Central device
device = IoTCentralDevice(
    socket,
    esp,
    secrets["id_scope"],
    secrets["device_id"],
    secrets["key"]
)

# Connect to Azure IoT Central
device.connect()

# Hide the splash screen and show the telemetry values
gfx.show_text()

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)
        gfx.display_temp(temperature)

        print('Sending data to Azure')
        gfx.display_azure_status('Sending data...')

        # send the temperature and moisture level to Azure
        message = {
            "Temperature": temperature,
            "MoistureLevel": moisture_level
        }
        device.send_telemetry(json.dumps(message))
        device.loop()

        gfx.display_azure_status('Data sent!')
        print('Data sent!')
    except (ValueError, RuntimeError) as e:
        print("Failed to get data, retrying\n", e)
        wifi.reset()
        wifi.connect()
        device.reconnect()
        continue

    # Sleep for 10 minutes before getting the next value
    time.sleep(600)

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

The content of the CIRCUITPY drive showing the code, azure_gfx_helper and secrets python files, a fonts folder, an images folder, as well as a list of libraries in a lib folder.ntents.png
The contents of the CIRCUITPYTHON device

Install an editor

This guide requires you to edit and interact with CircuitPython code. While you can use any text editor of your choosing, two recommended editors are Visual Studio Code and Mu.

Visual Studio Code is a free, open source code editor with a huge range of extensions to support multiple languages and technologies. It runs on Windows, MacOS, and Linux.

After installing Visual Studio Code, you will need to install the Python extension if you want intellisense and code completion. You can read about this in the the Python in Visual Studio Code documentation.

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!

Secrets File Setup

First, use Visual Studio Code or 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 IoT Central Device.

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

  • ReplaceMY_WIFI_SSID with the name of your WiFi SSID
  • ReplaceMY_WIFI_PASSWORD with your WiFi's password
  • ReplaceMY_AZURE_IOT_CENTRAL_ID_SCOPE with the ID Scope of your Azure IoT Central device from the connection dialog.
  • ReplaceMY_AZURE_IOT_CENTRAL_DECVICE_IDwith the Device ID of your Azure IoT Central device from the connection dialog.
  • Replace MY_AZURE_IOT_CENTRAL_PRIMAEY_KEY with the Primary Key of your Azure IoT Central device from the connection dialog.
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',
    'id_scope' : 'MY_AZURE_IOT_CENTRAL_ID_SCOPE',
    'device_id' : 'MY_AZURE_IOT_CENTRAL_DEVICE_ID',
    'key' : 'MY_AZURE_IOT_CENTRAL_PRIMARY_KEY'
}

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

Done

Setting up the PyPortal with the Azure IoT Central is finished! You do not need to repeat this process again unless you change your IoT Central device.

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 Central and also display when the data is sent. 

Monitoring the data with Azure IoT Central

Once your device is connected and sending data, you will see the temperature and soil moisture values start to appear in your IoT Central app.

sensors_DashboardWithData.pngThe IoT Central dashboard showing the temperature and moisture with the current level and a graph showing the last hour of data
The IoT Central app dashboard

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 Central operations such as properties and commands.

Azure IoT Central has a number of additional capabilities you can add to your IoT App:

  • Set up a rule to send you an email if your soil moisture levels are too low and the plant needs watering.
  • Export all your data into storage to keep a history of all the recorded values.

You can also take advantage of other Azure services to work with the data:

Code Walkthrough

Importing CircuitPython Libraries

Download: file
import time
import json
import board
import busio
from digitalio import DigitalInOut
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
import neopixel
from adafruit_ntp import NTP
from adafruit_azureiot import IoTCentralDevice
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 Central, 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 Graphical Helper 

The graphics helper, which manages' the PyPortal's display is created. Once created it shows a splash screen whilst the device connects to WiFi and Azure IoT Central. If you want to show the temperature in Fahrenheit instead of Celsius, change is_celsius=True to is_celsius=False.

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

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 to manage the WiFi connection.

Finally a Network Time Protocol, or NTP object is set up to synchronize the current time from a server.

Download: file
# 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)

# Set up the WiFi manager with a status light to show the WiFi connection status
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
print("WiFi connecting...")
wifi.connect()
print("WiFi connected!")

# Time setup, needed to authenticate with Azure IoT Central
ntp = NTP(esp)
while not ntp.valid_time:
    print("Failed to obtain time, retrying in 5 seconds...")
    time.sleep(5)
    ntp.set_time()

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 Central Module

Next, we'll create an instance of the Azure IoT Central device client called device. It takes in the ESP network socket, socket, the ESP object, esp, and the IoT Central connection details from the secrets file. Once created, the device connects to IoT Central.

Download: file
# Create an instance of the Azure IoT Central device
device = IoTCentralDevice(
    socket,
    esp,
    secrets["id_scope"],
    secrets["device_id"],
    secrets["key"]
)

# Connect to Azure IoT Central
device.connect()

Hide the splash screen and show the telemetry

Once the device is connected, the graphical helper can hide the splash screen and start displaying the telemetry values on screen.

Download: file
# Hide the splash screen and show the telemetry values
gfx.show_text()

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
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)
        gfx.display_temp(temperature)

The next block of code changes the displays status to indicate that data is about to be sent. It then builds a JSON object, message, containing the temperature and soil moisture.

This message is then sent to Azure IoT Central as telemetry data using the device.send_telemetry() call. The device.loop() method is then called to process any communication back and further between the Azure IoT Central module and the Azure IoT Central application.

Finally the display status is changed to show data has been sent.

Download: file
# send the temperature and moisture level to Azure
message = {
    "Temperature": temperature,
    "MoistureLevel": moisture_level
}
device.send_telemetry(json.dumps(message))
device.loop()

gfx.display_azure_status('Data sent!')
print('Data sent!')

All of this code is wrapped in a try/except control flow block. If connection is lost at any point, then the except code will be run before going back to the try.

This except code block will reset and reconnect the wifi object, then reconnect to Azure IoT Central.

Download: file
except (ValueError, RuntimeError) as e:
    print("Failed to get data, retrying\n", e)
    wifi.reset()
    wifi.connect()
    device.reconnect()
    continue

Finally the loop sleeps for 10 minutes, represented as 600 seconds. This is to ensure IoT Central doesn't receive too much data - the S1 tier is limited to 5,000 messages a month, and one message every 10 minutes is a maximum of 4,464 messages a month.

Download: file
# Sleep for 10 minutes before getting the next value
time.sleep(600)
This guide was first published on May 24, 2019. It was last updated on May 24, 2019.