In this example, you'll use the adafruit_requests library to fetch a text response from the Adafruit Quotes PHP script. Each time the URL is requested, it returns a new quote from a large database of quotes.
Code the Requests Test
Once you've finished setting up your Pico W with CircuitPython, you can access the code and necessary libraries by downloading the Project Bundle.
To do this, click on the Download Project Bundle button in the window below. It will download as a zipped folder.
# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries # # SPDX-License-Identifier: MIT import os import time import ssl import wifi import socketpool import microcontroller import adafruit_requests # adafruit quotes URL quotes_url = "https://www.adafruit.com/api/quotes.php" # connect to SSID wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD')) pool = socketpool.SocketPool(wifi.radio) requests = adafruit_requests.Session(pool, ssl.create_default_context()) while True: try: # pings adafruit quotes print("Fetching text from %s" % quotes_url) # gets the quote from adafruit quotes response = requests.get(quotes_url) print("-" * 40) # prints the response to the REPL print("Text Response: ", response.text) print("-" * 40) response.close() # delays for 1 minute time.sleep(60) # pylint: disable=broad-except except Exception as e: print("Error:\n", str(e)) print("Resetting microcontroller in 10 seconds") time.sleep(10) microcontroller.reset()
Upload the Code and Libraries to the Pico W
After downloading the Project Bundle, plug your Pico W into the computer's USB port with a known good USB data+power cable. You should see a new flash drive appear in the computer's File Explorer or Finder (depending on your operating system) called CIRCUITPY. Unzip the folder and copy the following items to the Pico W's CIRCUITPY drive.
- lib folder
- code.py
Your Pico W CIRCUITPY drive should look like this after copying the lib folder and the code.py file.
Add Your settings.toml File
Remember to add your settings.toml file as described in the Create Your settings.toml File page earlier in the guide. You'll need to include your WIFI_SSID
and WIFI_PASSWORD
in the file.
CIRCUITPY_WIFI_SSID = "your-ssid-here" CIRCUITPY_WIFI_PASSWORD = "your-ssid-password-here"
Once everything is saved to the CIRCUITPY drive, connect to the serial console to see the data printed out!
Every 60 seconds, a request
will be made to the Adafruit quotes URL. Then, the response will be printed to the REPL. The response includes the quote text and the author of the quote.
Text editor powered by tinymce.