Skip to content

Commit 4b3c011

Browse files
committed
Pico W WiFi examples
Adding WiFi examples for the Pico W: basic connection test, requests, JSON feed, Twitter feed, Adafruit IO and Azure IoT Central
1 parent fe196e9 commit 4b3c011

File tree

6 files changed

+346
-0
lines changed

6 files changed

+346
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries
2+
# SPDX-License-Identifier: MIT
3+
4+
import os
5+
import time
6+
import ssl
7+
import wifi
8+
import socketpool
9+
import microcontroller
10+
import board
11+
import busio
12+
import adafruit_requests
13+
import adafruit_ahtx0
14+
from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError
15+
16+
wifi.radio.connect(os.getenv('WIFI_SSID'), os.getenv('WIFI_PASSWORD'))
17+
18+
aio_username = os.getenv('aio_username')
19+
aio_key = os.getenv('aio_key')
20+
21+
pool = socketpool.SocketPool(wifi.radio)
22+
requests = adafruit_requests.Session(pool, ssl.create_default_context())
23+
# Initialize an Adafruit IO HTTP API object
24+
io = IO_HTTP(aio_username, aio_key, requests)
25+
print("connected to io")
26+
27+
# use Pico W's GP0 for SDA and GP1 for SCL
28+
i2c = busio.I2C(board.GP1, board.GP0)
29+
aht20 = adafruit_ahtx0.AHTx0(i2c)
30+
31+
try:
32+
# get feed
33+
picowTemp_feed = io.get_feed("pitemp")
34+
picowHumid_feed = io.get_feed("pihumid")
35+
except AdafruitIO_RequestError:
36+
# if no feed exists, create one
37+
picowTemp_feed = io.create_new_feed("pitemp")
38+
picowHumid_feed = io.create_new_feed("pihumid")
39+
40+
# pack feed names into an array for the loop
41+
feed_names = [picowTemp_feed, picowHumid_feed]
42+
print("feeds created")
43+
44+
clock = 300
45+
46+
while True:
47+
try:
48+
# when the clock runs out..
49+
if clock > 300:
50+
# read sensor
51+
data = [aht20.temperature, aht20.relative_humidity]
52+
# send sensor data to respective feeds
53+
for z in range(2):
54+
io.send_data(feed_names[z]["key"], data[z])
55+
print("sent %0.1f" % data[z])
56+
time.sleep(1)
57+
# print sensor data to the REPL
58+
print("\nTemperature: %0.1f C" % aht20.temperature)
59+
print("Humidity: %0.1f %%" % aht20.relative_humidity)
60+
print()
61+
time.sleep(1)
62+
# reset clock
63+
clock = 0
64+
else:
65+
clock += 1
66+
# pylint: disable=broad-except
67+
# any errors, reset Pico W
68+
except Exception as e:
69+
print("Error:\n", str(e))
70+
print("Resetting microcontroller in 10 seconds")
71+
time.sleep(10)
72+
microcontroller.reset()
73+
# delay
74+
time.sleep(1)
75+
print(clock)
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries
2+
# SPDX-License-Identifier: MIT
3+
4+
import time
5+
import os
6+
import json
7+
import busio
8+
import microcontroller
9+
import board
10+
import rtc
11+
import socketpool
12+
import wifi
13+
import adafruit_ntp
14+
import adafruit_ahtx0
15+
from adafruit_azureiot import IoTCentralDevice
16+
17+
# use Pico W's GP0 for SDA and GP1 for SCL
18+
i2c = busio.I2C(board.GP1, board.GP0)
19+
aht20 = adafruit_ahtx0.AHTx0(i2c)
20+
21+
print("Connecting to WiFi...")
22+
wifi.radio.connect(os.getenv('WIFI_SSID'), os.getenv('WIFI_PASSWORD'))
23+
24+
print("Connected to WiFi!")
25+
26+
# ntp clock
27+
pool = socketpool.SocketPool(wifi.radio)
28+
ntp = adafruit_ntp.NTP(pool)
29+
rtc.RTC().datetime = ntp.datetime
30+
31+
if time.localtime().tm_year < 2022:
32+
print("Setting System Time in UTC")
33+
rtc.RTC().datetime = ntp.datetime
34+
35+
else:
36+
print("Year seems good, skipping set time.")
37+
38+
# Create an IoT Hub device client and connect
39+
esp = None
40+
pool = socketpool.SocketPool(wifi.radio)
41+
device = IoTCentralDevice(
42+
pool, esp, os.getenv('id_scope'), os.getenv('device_id'), os.getenv('device_primary_key')
43+
)
44+
45+
print("Connecting to Azure IoT Central...")
46+
47+
device.connect()
48+
49+
print("Connected to Azure IoT Central!")
50+
51+
# clock to count down to sending data to Azure
52+
azure_clock = 500
53+
54+
while True:
55+
try:
56+
# when the azure clock runs out
57+
if azure_clock > 500:
58+
# pack message
59+
message = {"Temperature": aht20.temperature,
60+
"Humidity": aht20.relative_humidity}
61+
print("sending json")
62+
device.send_telemetry(json.dumps(message))
63+
print("data sent")
64+
# reset azure clock
65+
azure_clock = 0
66+
else:
67+
azure_clock += 1
68+
# ping azure
69+
device.loop()
70+
# if something disrupts the loop, reconnect
71+
# pylint: disable=broad-except
72+
# any errors, reset Pico W
73+
except Exception as e:
74+
print("Error:\n", str(e))
75+
print("Resetting microcontroller in 10 seconds")
76+
time.sleep(10)
77+
microcontroller.reset()
78+
# delay
79+
time.sleep(1)
80+
print(azure_clock)
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
import os
6+
import ipaddress
7+
import wifi
8+
import socketpool
9+
10+
print()
11+
print("Connecting to WiFi")
12+
13+
# connect to your SSID
14+
wifi.radio.connect(os.getenv('WIFI_SSID'), os.getenv('WIFI_PASSWORD'))
15+
16+
print("Connected to WiFi")
17+
18+
pool = socketpool.SocketPool(wifi.radio)
19+
20+
# prints MAC address to REPL
21+
print("My MAC addr:", [hex(i) for i in wifi.radio.mac_address])
22+
23+
# prints IP address to REPL
24+
print("My IP address is", wifi.radio.ipv4_address)
25+
26+
# pings Google
27+
ipv4 = ipaddress.ip_address("8.8.4.4")
28+
print("Ping google.com: %f ms" % (wifi.radio.ping(ipv4)*1000))
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
import time
6+
import os
7+
import ssl
8+
import wifi
9+
import socketpool
10+
import microcontroller
11+
import adafruit_requests
12+
13+
wifi.radio.connect(os.getenv('WIFI_SSID'), os.getenv('WIFI_PASSWORD'))
14+
15+
# Use cityname, country code where countrycode is ISO3166 format.
16+
# E.g. "New York, US" or "London, GB"
17+
location = "Manhattan, US"
18+
19+
# openweathermap URL, brings in your location & your token
20+
url = "http://api.openweathermap.org/data/2.5/weather?q="+location
21+
url += "&appid="+os.getenv('openweather_token')
22+
23+
pool = socketpool.SocketPool(wifi.radio)
24+
requests = adafruit_requests.Session(pool, ssl.create_default_context())
25+
26+
while True:
27+
try:
28+
# pings openweather
29+
response = requests.get(url)
30+
# packs the response into a JSON
31+
response_as_json = response.json()
32+
print()
33+
# prints the entire JSON
34+
print(response_as_json)
35+
# gets location name
36+
place = response_as_json['name']
37+
# gets weather type (clouds, sun, etc)
38+
weather = response_as_json['weather'][0]['main']
39+
# gets humidity %
40+
humidity = response_as_json['main']['humidity']
41+
# gets air pressure in hPa
42+
pressure = response_as_json['main']['pressure']
43+
# gets temp in kelvin
44+
temperature = response_as_json['main']['temp']
45+
# converts temp from kelvin to F
46+
converted_temp = (temperature - 273.15) * 9/5 + 32
47+
# converts temp from kelvin to C
48+
# converted_temp = temperature - 273.15
49+
50+
# prints out weather data formatted nicely as pulled from JSON
51+
print()
52+
print("The current weather in %s is:" % place)
53+
print(weather)
54+
print("%s°F" % converted_temp)
55+
print("%s%% Humidity" % humidity)
56+
print("%s hPa" % pressure)
57+
# delay for 5 minutes
58+
time.sleep(300)
59+
# pylint: disable=broad-except
60+
except Exception as e:
61+
print("Error:\n", str(e))
62+
print("Resetting microcontroller in 10 seconds")
63+
time.sleep(10)
64+
microcontroller.reset()
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
import os
6+
import time
7+
import ssl
8+
import wifi
9+
import socketpool
10+
import microcontroller
11+
import adafruit_requests
12+
13+
# adafruit quotes URL
14+
quotes_url = "https://www.adafruit.com/api/quotes.php"
15+
16+
# connect to SSID
17+
wifi.radio.connect(os.getenv('WIFI_SSID'), os.getenv('WIFI_PASSWORD'))
18+
19+
pool = socketpool.SocketPool(wifi.radio)
20+
requests = adafruit_requests.Session(pool, ssl.create_default_context())
21+
22+
while True:
23+
try:
24+
# pings adafruit quotes
25+
print("Fetching text from %s" % quotes_url)
26+
# gets the quote from adafruit quotes
27+
response = requests.get(quotes_url)
28+
print("-" * 40)
29+
# prints the response to the REPL
30+
print("Text Response: ", response.text)
31+
print("-" * 40)
32+
response.close()
33+
# delays for 1 minute
34+
time.sleep(60)
35+
# pylint: disable=broad-except
36+
except Exception as e:
37+
print("Error:\n", str(e))
38+
print("Resetting microcontroller in 10 seconds")
39+
time.sleep(10)
40+
microcontroller.reset()
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
import time
6+
import os
7+
import ssl
8+
import wifi
9+
import socketpool
10+
import microcontroller
11+
import adafruit_requests
12+
13+
# query URL for tweets. looking for hashtag partyparrot sent to a specific username
14+
# disabling line-too-long because queries for tweet_query & TIME_URL cannot have line breaks
15+
# pylint: disable=line-too-long
16+
tweet_query = 'https://api.twitter.com/2/tweets/search/recent?query=NEW GUIDE from:adafruit&tweet.fields=created_at'
17+
18+
headers = {'Authorization': 'Bearer ' + os.getenv('bearer_token')}
19+
20+
wifi.radio.connect(os.getenv('WIFI_SSID'), os.getenv('WIFI_PASSWORD'))
21+
22+
pool = socketpool.SocketPool(wifi.radio)
23+
requests = adafruit_requests.Session(pool, ssl.create_default_context())
24+
25+
last_id = 0 # checks last tweet's ID
26+
check = 0 # time.monotonic() holder
27+
28+
print(time.monotonic())
29+
30+
while True:
31+
try:
32+
if (check + 30) < time.monotonic():
33+
# updates current time
34+
# get tweets from rpilocator containing in stock at adafruit
35+
twitter_response = requests.get(url=tweet_query, headers=headers)
36+
# gets data portion of json
37+
twitter_json = twitter_response.json()
38+
twitter_json = twitter_json['data']
39+
# to see the entire json feed, uncomment 'print(twitter_json)'
40+
# print(twitter_json)
41+
# tweet ID number
42+
tweet_id = twitter_json[0]['id']
43+
# tweet text
44+
tweet = twitter_json[0]['text']
45+
# timestamp
46+
timestamp = twitter_json[0]['created_at']
47+
if last_id != tweet_id:
48+
print("New Learn Guide!")
49+
print(tweet)
50+
print(timestamp)
51+
last_id = tweet_id
52+
check = time.monotonic()
53+
# pylint: disable=broad-except
54+
# any errors, reset Pico W
55+
except Exception as e:
56+
print("Error:\n", str(e))
57+
print("Resetting microcontroller in 10 seconds")
58+
time.sleep(10)
59+
microcontroller.reset()

0 commit comments

Comments
 (0)