Before we run the script at the bottom of this page, we'll need to change ADAFRUIT_IO_USERNAME and ADAFRUIT_IO_KEY to the username and key for your Adafruit IO account.
- If you need the AIO Key, navigate to your Adafruit IO Profile
# Set to your Adafruit IO key. # Remember, your key is a secret, # so make sure not to publish it when you publish this code! ADAFRUIT_IO_KEY = 'YOUR_AIO_KEY' # Set to your Adafruit IO username. # (go to https://accounts.adafruit.com to find your username) ADAFRUIT_IO_USERNAME = 'YOUR_AIO_USERNAME'
We're going to set up an instance of the feed we created earlier:
digital = aio.create_feed(Feed(name="digital"))
In the while True loop, we're going to check the value of the button and send it to Adafruit IO. A delay (time.sleep()) has been added to avoid timing out by sending too many requests to Adafruit IO.
while True:
if not button.value:
button_current = 1
else:
button_current = 0
print('Button -> ', button_current)
aio.send(digital.key, button_current)
# avoid timeout from adafruit io
time.sleep(1)
Make sure you're within the /io-client-python/examples/basics directory.
If you're not sure which directory you're in, you can check this by running pwd and you should see the following output from your terminal:
~/io-client-python/examples/basics
Let's run the script. In your terminal, run:
python3 digital-in.py
You can now press the button, and you should see button presses being sent to Adafruit IO:
Button -> 1 Button -> 0 Button -> 1 Button -> 0
Check your dashboard on Adafruit IO, and you should see the gauge respond to button presses:
"""
'digital_in.py'
==================================
Example of sending button values
to an Adafruit IO feed.
Author(s): Brent Rubell, Todd Treece
"""
# Import standard python modules
import os
import time
# import Adafruit Blinka
import board
import digitalio
# import Adafruit IO REST client.
from Adafruit_IO import Client, Feed, RequestError
# Set to your Adafruit IO username.
# (go to https://accounts.adafruit.com to find your username)
ADAFRUIT_IO_USERNAME = os.getenv('ADAFRUIT_IO_USERNAME', 'YOUR_AIO_USERNAME')
# Set to your Adafruit IO key.
# Remember, your key is a secret,
# so make sure **not** to publish it when you publish this code!
ADAFRUIT_IO_KEY = os.getenv('ADAFRUIT_IO_KEY', 'YOUR_AIO_KEY')
# Create an instance of the REST client.
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
try: # if we have a 'digital' feed
digital = aio.feeds('digital')
except RequestError: # create a digital feed
feed = Feed(name="digital")
digital = aio.create_feed(feed)
# button set up
button = digitalio.DigitalInOut(board.D12)
button.direction = digitalio.Direction.INPUT
button.pull = digitalio.Pull.UP
button_current = 0
while True:
if not button.value:
button_current = 1
else:
button_current = 0
print('Button -> ', button_current)
aio.send(digital.key, button_current)
# avoid timeout from adafruit io
time.sleep(1)
Page last edited January 18, 2025
Text editor powered by tinymce.