Skip to content

Instantly share code, notes, and snippets.

@todbot
Last active October 22, 2023 13:30
Show Gist options
  • Save todbot/877b2037b6c7b2c4c11545c83c6e2182 to your computer and use it in GitHub Desktop.
Save todbot/877b2037b6c7b2c4c11545c83c6e2182 to your computer and use it in GitHub Desktop.
UDP sender and receiver in CircuitPython
# udp_recv_code.py -- receive UDP messages from any receiver, can be another CircuitPython device
# 24 Aug 2022 - @todbot / Tod Kurt
# cribbing from code at https://github.com/adafruit/circuitpython/blob/main/tests/circuitpython-manual/socketpool/datagram/ntp.py
import time, wifi, socketpool
from secrets import secrets
print("Connecting to WiFi...")
wifi.radio.connect(ssid=secrets['ssid'],password=secrets['password'])
print("my IP addr:", wifi.radio.ipv4_address)
pool = socketpool.SocketPool(wifi.radio)
udp_host = str(wifi.radio.ipv4_address) # my LAN IP as a string
udp_port = 5005 # a number of your choosing, should be 1024-65000
udp_buffer = bytearray(64) # stores our incoming packet
sock = pool.socket(pool.AF_INET, pool.SOCK_DGRAM) # UDP socket
sock.bind((udp_host, udp_port)) # say we want to listen on this host,port
print("waiting for packets on",udp_host, udp_port)
while True:
size, addr = sock.recvfrom_into(udp_buffer)
msg = udp_buffer.decode('utf-8') # assume a string, so convert from bytearray
print(f"Received message from {addr[0]}:", msg)
# udp_send_code.py -- send UDP messages to specified receiver, can be another CircuitPython device
# 24 Aug 2022 - @todbot / Tod Kurt
# cribbing from code at https://github.com/adafruit/circuitpython/blob/main/tests/circuitpython-manual/socketpool/datagram/ntp.py
import time, wifi, socketpool
from secrets import secrets
print("Connecting to WiFi...")
wifi.radio.connect(ssid=secrets['ssid'],password=secrets['password'])
print("my IP addr:", wifi.radio.ipv4_address)
pool = socketpool.SocketPool(wifi.radio)
udp_host = "192.168.1.123" # LAN IP of UDP receiver
udp_port = 5005 # must match receiver!
my_message = "hi there from CircuitPython!"
sock = pool.socket(pool.AF_INET, pool.SOCK_DGRAM) # UDP, and we'l reuse it each time
num = 0
while True:
# stick a nubmer on the end of the message to show progress and conver to bytearray
udp_message = bytes(f"{my_message} {num}", 'utf-8')
num += 1
print(f"Sending to {udp_host}:{udp_port} message:", udp_message)
sock.sendto(udp_message, (udp_host,udp_port) ) # send UDP packet to udp_host:port
time.sleep(1)
@daanzu
Copy link

daanzu commented Oct 22, 2023

@todbot You should consider updating this with the above correction from @aceg00 . The current code is a real foot gun. Many thanks for this gist nonetheless though!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment