Skip to content

Commit 23c4da0

Browse files
authored
Merge pull request #66 from brentru/rp2040-example
Add rp2040 publish/sub example for guide
2 parents 5b74431 + 2fb8eae commit 23c4da0

File tree

1 file changed

+121
-0
lines changed

1 file changed

+121
-0
lines changed
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
# SPDX-FileCopyrightText: Brent Rubell for Adafruit Industries
2+
# SPDX-License-Identifier: MIT
3+
4+
import time
5+
from microcontroller import cpu
6+
import board
7+
import busio
8+
from digitalio import DigitalInOut
9+
from adafruit_esp32spi import adafruit_esp32spi
10+
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
11+
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
12+
import adafruit_minimqtt.adafruit_minimqtt as MQTT
13+
from adafruit_io.adafruit_io import IO_MQTT
14+
15+
### WiFi ###
16+
17+
# Get wifi details and more from a secrets.py file
18+
try:
19+
from secrets import secrets
20+
except ImportError:
21+
print("WiFi secrets are kept in secrets.py, please add them there!")
22+
raise
23+
24+
# Raspberry Pi RP2040
25+
esp32_cs = DigitalInOut(board.GP13)
26+
esp32_ready = DigitalInOut(board.GP14)
27+
esp32_reset = DigitalInOut(board.GP15)
28+
29+
spi = busio.SPI(board.GP10, board.GP11, board.GP12)
30+
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
31+
32+
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets)
33+
34+
# Configure the RP2040 Pico LED Pin as an output
35+
led_pin = DigitalInOut(board.LED)
36+
led_pin.switch_to_output()
37+
38+
# Define callback functions which will be called when certain events happen.
39+
# pylint: disable=unused-argument
40+
def connected(client):
41+
# Connected function will be called when the client is connected to Adafruit IO.
42+
print("Connected to Adafruit IO! ")
43+
44+
45+
def subscribe(client, userdata, topic, granted_qos):
46+
# This method is called when the client subscribes to a new feed.
47+
print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))
48+
49+
50+
# pylint: disable=unused-argument
51+
def disconnected(client):
52+
# Disconnected function will be called when the client disconnects.
53+
print("Disconnected from Adafruit IO!")
54+
55+
56+
def on_led_msg(client, topic, message):
57+
# Method called whenever user/feeds/led has a new value
58+
print("New message on topic {0}: {1} ".format(topic, message))
59+
if message == "ON":
60+
led_pin.value = True
61+
elif message == "OFF":
62+
led_pin.value = False
63+
else:
64+
print("Unexpected message on LED feed.")
65+
66+
67+
# Connect to WiFi
68+
print("Connecting to WiFi...")
69+
wifi.connect()
70+
print("Connected!")
71+
72+
# Initialize MQTT interface with the esp interface
73+
MQTT.set_socket(socket, esp)
74+
75+
# Initialize a new MQTT Client object
76+
mqtt_client = MQTT.MQTT(
77+
broker="io.adafruit.com",
78+
username=secrets["aio_username"],
79+
password=secrets["aio_key"],
80+
)
81+
82+
# Initialize an Adafruit IO MQTT Client
83+
io = IO_MQTT(mqtt_client)
84+
85+
# Connect the callback methods defined above to Adafruit IO
86+
io.on_connect = connected
87+
io.on_disconnect = disconnected
88+
io.on_subscribe = subscribe
89+
90+
# Set up a callback for the led feed
91+
io.add_feed_callback("led", on_led_msg)
92+
93+
# Connect to Adafruit IO
94+
print("Connecting to Adafruit IO...")
95+
io.connect()
96+
97+
# Subscribe to all messages on the led feed
98+
io.subscribe("led")
99+
100+
prv_refresh_time = 0.0
101+
while True:
102+
# Poll for incoming messages
103+
try:
104+
io.loop()
105+
except (ValueError, RuntimeError) as e:
106+
print("Failed to get data, retrying\n", e)
107+
wifi.reset()
108+
io.reconnect()
109+
continue
110+
# Send a new temperature reading to IO every 30 seconds
111+
if (time.monotonic() - prv_refresh_time) > 30:
112+
# take the cpu's temperature
113+
cpu_temp = cpu.temperature
114+
# truncate to two decimal points
115+
cpu_temp = str(cpu_temp)[:5]
116+
print("CPU temperature is %s degrees C" % cpu_temp)
117+
# publish it to io
118+
print("Publishing %s to temperature feed..." % cpu_temp)
119+
io.publish("temperature", cpu_temp)
120+
print("Published!")
121+
prv_refresh_time = time.monotonic()

0 commit comments

Comments
 (0)