Skip to content

14. Ryan and Ginny Networking Project

For this week’s group assignment, we decided to do wireless communicatino over the local network between each of our raspberry pi pico ws. On this website we were able to learn more about the new raspebrry pi pico Ws, in which it has a wirless capability connected to the internal RP2040, making it a powerful tool.

Each of us had used the Pico W in our individual work to get a basic understanding of servers, clients, etc. However, it was our job to send a message between the two Picos, rather than just to a simple web server.

Coding/Setup

This website provided a great basic understanding and example codes to get a message between two Pico Ws. The process included setting up a web server via one Pico to listen for clients, open the socket(or endpoint of the client to send data), and to send the message, we sent a random value from 0-255 on the RGB scale, in which the client would read and print in the Thonny monitor.

import network
import socket
import time
from machine import Pin, ADC
from secret import ssid,password
import random
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)

# Wait for connect or fail
max_wait = 10
while max_wait > 0:
    if wlan.status() < 0 or wlan.status() >= 3:
        break
    max_wait -= 1
    print('waiting for connection...')
    time.sleep(1)

# Handle connection error
if wlan.status() != 3:
    raise RuntimeError('network connection failed')
else:
    print('connected')
    status = wlan.ifconfig()
    print( 'ip = ' + status[0] )

# Open socket
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]

s = socket.socket()
s.bind(addr)
s.listen(1)

print('listening on', addr)

# Listen for connections
while True:
    try:
        cl, addr = s.accept()
        print('client connected from', addr)
        request = cl.recv(1024)
        print(request)
        # Do not unpack request
        # We reply to any request the same way
        # Generate 3 values to send back
        r = random.randint(0,255)
        g = random.randint(0,255)
        b = random.randint(0,255)
        # Join to make a simple string with commas as separators
        rgb = str(r) + "," + str(g) + ","+str(b)

        response = rgb # This is what we send in reply

        cl.send(response)
        print("Sent:" + rgb)
        cl.close()

    except OSError as e:
        cl.close()
        print('connection closed')

We then used our other Pico W and uploaded micropython code as such:

import network
import time
from secret import ssid, password
import socket

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected() and wlan.status() >= 0:
    print("Waiting to connect:")
    time.sleep(1)

# Should be connected and have an IP address
wlan.status() # 3 == success
wlan.ifconfig()
print(wlan.ifconfig())

while True:
    ai = socket.getaddrinfo("IP-ADRESS-HERE", 80) # Address of Web Server
    addr = ai[0][-1]

    # Create a socket and make a HTTP request
    s = socket.socket() # Open socket
    s.connect(addr)
    s.send(b"GET Data") # Send request
    ss=str(s.recv(512)) # Store reply
    # Print what we received
    print(ss)
    # Split into RGB components
    l = len(ss)
    ss = ss[2:l-1]     # Strip to essentials  
    p = ss.find(",")   # Find first comma
    r = int(ss[0:p])   # Extract RED value
    ss = ss[p+1:]      # Remove red part
    p = ss.find(",")   # Find comma separator
    g = int(ss[0:p])   # Extract GREEN value
    b = int(ss[p+1:])  # Extract BLUE value
    print(r,g,b)       # Print RGB values
    print()
    # Set RGB LED here
    s.close()          # Close socket
    time.sleep(0.2)    # wait

This code opneed the socket and sent a request to the other Pico’s IP address. One issue we had was since we were using a hotspot, we had to set “compatiblity mode” on. Once we had the IP address(which is printed in the server code), we used that IP address in this code to connect to that server. It then recied the RGB values, split it, and printed it in the Thonny monitor of the client Pico W. We got this working, and after a few tries, we were able to connect to the network and read the RGB values sent from one address to the other.

We then moved onto making the message do something. Obviously, with the RGB values, it would make sense we use the RGB values to update the colors of a real neopixel. Ryan quickly got milled a simple board to solder onto the Pico W. (He made it small, since it didn’t require many pins, and we didn’t want to waste a Pico W for this was just a learning project). He soldered the tips on, along with soldering a Neopixel.

Ginny worked on updating the code. She needed to get the RGB values being sent and write code that would turn on NeoPixels with the values being sent. She learned from Dylan that all she had to do was write a line with the r, g, and b varibles and that info on how to write those could be found on this website. She learned that she had to include the NeoPixel library by including import machine, neopixel and then by intializing the pin of the NeoPixels by typing np = neopixel.NeoPixel(machine.Pin(pin-number-here), number-of-neopixels). Next, to import the RGB values being sent she had to type the line np[0] = (r, g, b).

# Program to read RGB values from a local Pico Web Server
# Tony Goodhew 5th July 2022
# Connect to network
import network
import time
from secret import ssid, password
import socket

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected() and wlan.status() >= 0:
    print("Waiting to connect:")
    time.sleep(1)

# Should be connected and have an IP address
wlan.status() # 3 == success
wlan.ifconfig()
print(wlan.ifconfig())

import machine, neopixel
np = neopixel.NeoPixel(machine.Pin(15), 1)

while True:
    ai = socket.getaddrinfo("IP-ADRESS-HERE", 80) # Address of Web Server
    addr = ai[0][-1]

    # Create a socket and make a HTTP request
    s = socket.socket() # Open socket
    s.connect(addr)
    s.send(b"GET Data") # Send request
    ss=str(s.recv(512)) # Store reply
    # Print what we received
    print(ss)
    # Split into RGB components
    l = len(ss)
    ss = ss[2:l-1]     # Strip to essentials  
    p = ss.find(",")   # Find first comma
    r = int(ss[0:p])   # Extract RED value
    ss = ss[p+1:]      # Remove red part
    p = ss.find(",")   # Find comma separator
    g = int(ss[0:p])   # Extract GREEN value
    b = int(ss[p+1:])  # Extract BLUE value
    print(r,g,b)       # Print RGB values
    print()
    # Set RGB LED here
    np[0] = (r, g, b)
    np.write()
    s.close()          # Close socket
    time.sleep(0.2)    # wait

Once we had everything set, we navigated back to Thonny, and uploaded the updated code to the client Pico W, which would take the recieved RGB values and print it using the Neopixel Library. THe first time it didn’t work, but Ginny figured out that instead of just setting the color, we needed to add this line np.write() to actually write the values and make the neopixel turn on. Once this was figured out, we had the final setup of two Pico Ws sending a message to each other over the network, and rather than just sending a message, we were able to take the data and make a neopixel turn on and change colors everytime new data was receive from the server.


Last update: June 25, 2023