Sending data over WiFi#
Requirements
A Pico
A Wifi adapator (we are using a Pico W which has built in Wifi)
Set-up#
Since the Wifi module is built in - we don’t need to worry about wiring anything to the Pico W.
The only step we need to first take is to create a settings.toml
file in the CIRCUITPY drive. This is a type of text file which will hold all our sensitive network information separate to the main code.py
file.
The information that we will hold here is your WiFi’s SSID (its name) and password, as well as your Raspberry Pi’s IP address.
WIFI_SSID = "___" # Fill in with your WiFi network's name
WIFI_PASSWORD = "___" # Fill in with your WiFi network's password
IP_ADDRESS = "___" # Fill in with your Raspberry Pi's password
PORT = "___" # Fill in the port you are connecting over
URL = "___" # Fill in the URL you wish to connect to
Warning
Remember this information is stored in plain text and so can be read by anyone with access to the Pico
There may be other information you want to include here like the port or other URL extensions.
Note
Make sure to keep the speech marks when putting your own network details into the settings.toml
. This ensures that CircuitPython recognises the variables as strings.
Code set-up#
Now we can program our Pico to send data over WiFi to the Raspberry Pi that is hosting our Node-RED server.
Below is an example for sending temperature and time data to a Node-RED server.
Importing libraries#
Here we require two libraries that are not included in the core CircuitPython package that we downloaded - adafruit_connection_manager and adafruit_requests.
To access these libraries, we need to upload them to the Pico from a separate bundle. Follow the instructions below:
Go to this website where you can download a bundle of official CircuitPython libraries. Make sure to download the bundle that matches your version of CP (most likely 9.x).
Open the .zip file and in the lib folder, find the files called adafruit_connection_manager.mpy and adafruit_requests.mpy.
Copy these files into the lib folder on your CIRCUITPY drive.
You have now uploaded these libraries onto your Pico and can use them as seen below.
import os
import microcontroller
import adafruit_connection_manager
import wifi
import adafruit_requests
import time
#Retrieve variables from settings.toml
ssid = os.getenv("WIFI_SSID")
password = os.getenv("WIFI_PASSWORD")
ip = os.getenv('IP_ADDRESS')
#Set URL
NODE_RED_URL = "http://"+ip+os.getenv('PORT')+os.getenv('URL')
# Initalize Wifi, Socket Pool, Request Session
pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
requests = adafruit_requests.Session(pool, ssl_context)
# This code will scan for available Wifi networks
# Can comment out if you know what you wish to connect to
for network in wifi.radio.start_scanning_networks():
print("\t%s\t\tRSSI: %d\tChannel: %d" % (str(network.ssid, "utf-8"),
network.rssi, network.channel))
wifi.radio.stop_scanning_networks()
# Connect to the Wi-Fi network
print(f"\nConnecting to {ssid}...")
try:
wifi.radio.connect(ssid, password)
except OSError as e:
print(f"❌ OSError: {e}")
print("✅ Wifi!\n")
while True:
temp = microcontroller.cpu.temperature
timetrial = time.monotonic()
json_data = {"cpu_temp":temp,"time":timetrial} # Send data with JSON syntax
print(f" | ✅ Sending JSON ('key':'value'): {json_data}")
with requests.post(NODE_RED_URL, json = json_data) as response:
json_resp = response.json()
print(f" | ✅ Received CPU Temperature: {json_resp['cpu_temp']} & Time: {json_resp['time']}")
print("-" * 80 + "\n")
time.sleep(10)
This code works with the following simple Node-RED HTTP flow:
HTTP In Node - Method: Post, URL = /test
–> json Node - Action: Convert between JSON string & Object
–> HTTP Response Node