Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
# References:
# -
# -
# Hardware
# - Raspberry Pi 4 Model B
# [2GB]
# [4GB]
# [8GB]
# - Grove Base Kit for Raspberry Pi
# Install
# - sudo pip3 install adafruit-blinka
# - sudo pip3 install adafruit-io
# Update:
# 28 Feb 2021
# Import standard python modules.
import sys
# Import blinka python modules.
import board
import digitalio
# This example uses the MQTTClient instead of the REST client
from Adafruit_IO import MQTTClient
# Set to your Adafruit IO key.
# Remember, your key is a secret,
# so make sure not to publish it when you publish this code!
# Set to your Adafruit IO username.
# (go to to find your username)
# Set to the ID of the feed to subscribe to for updates.
FEED_ID = 'digital'
relay = digitalio.DigitalInOut(board.D5)
relay.direction = digitalio.Direction.OUTPUT
# Define callback functions which will be called when certain events happen.
def connected(client):
"""Connected function will be called when the client is connected to
Adafruit IO.This is a good place to subscribe to feed changes. The client
parameter passed to this function is the Adafruit IO MQTT client so you
can make calls against it easily.
# Subscribe to changes on a feed named Counter.
print('Subscribing to Feed {0}'.format(FEED_ID))
print('Waiting for feed data...')
def disconnected(client):
"""Disconnected function will be called when the client disconnects."""
def message(client, feed_id, payload):
"""Message function will be called when a subscribed feed has a new value.
The feed_id parameter identifies the feed, and the payload parameter has
the new value.
print('Feed {0} received new value: {1}'.format(feed_id, payload))
if payload == "OFF":
print("Turn off relay!")
relay.value = False
elif payload == "ON":
print("Turn on relay!")
relay.value = True
# Create an MQTT client instance.
# Setup the callback functions defined above.
client.on_connect = connected
client.on_disconnect = disconnected
client.on_message = message
# Connect to the Adafruit IO server.
# The first option is to run a thread in the background so you can continue
# doing things in your program.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment