Skip to content

Instantly share code, notes, and snippets.

@santolucito
Last active April 21, 2023 20:06
Show Gist options
  • Save santolucito/70ecb94ce297eb1b8b8034f78683447b to your computer and use it in GitHub Desktop.
Save santolucito/70ecb94ce297eb1b8b8034f78683447b to your computer and use it in GitHub Desktop.
Sending UDP on ESP32 in AP mode
#include <WebServer.h>
#include <WiFi.h>
#include <WiFiUdp.h>
// the IP of the machine to which you send msgs - this should be the correct IP in most cases (see note in python code)
#define CONSOLE_IP "192.168.1.2"
#define CONSOLE_PORT 4210
const char* ssid = "ESP32";
const char* password = "12345678";
WiFiUDP Udp;
IPAddress local_ip(192, 168, 1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
WebServer server(80);
void setup()
{
Serial.begin(115200);
WiFi.softAP(ssid, password);
WiFi.softAPConfig(local_ip, gateway, subnet);
server.begin();
}
void loop()
{
Udp.beginPacket(CONSOLE_IP, CONSOLE_PORT);
// Just test touch pin - Touch0 is T0 which is on GPIO 4.
Udp.printf(String(touchRead(T0)).c_str());
Udp.endPacket();
delay(1000);
}
# read UPD message from the ESP32
# this code should be run on a laptop/rasp pi that is connected to the wifi network created by the ESP32
# note that since you are connecting your laptop to the ESP32's wifi network, you will not be able to access the internet
# you will only be able to communicate with the ESP32
# for a version of this communication code that allows your laptop to still connect to the internet, see https://gist.github.com/santolucito/4016405f54850f7a216e9e453fe81803
import socket
# use ifconfig -a to find this IP. If your pi is the first and only device connected to the ESP32,
# this should be the correct IP by default on the raspberry pi
LOCAL_UDP_IP = "192.168.1.2"
SHARED_UDP_PORT = 4210
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Internet # UDP
sock.bind((LOCAL_UDP_IP, SHARED_UDP_PORT))
def loop():
while True:
data, addr = sock.recvfrom(2048)
print(data)
if __name__ == "__main__":
loop()
@shubhankar000
Copy link

Hi! This is great code!
I was wondering if the same functionality could be implemented in reverse, such that both the laptop and esp are able to send and receive messages over udp asynchronously. Can you share code on how to achieve this?

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