
Access Point (AP) enables your ESP32 to act as a web server that other devices can connect to

Station (STA) mode allows your ESP32 to connect to an existing network, such as Barnard Guest.
Part 1: Programing your ESP32 to set up a Web Server
#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"; // TODO - replace with a unique name
const char* password = "12345678"; // you can replace with your own password
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); // setup the wifi server with the ssid & password from above
WiFi.softAPConfig(local_ip, gateway, subnet);
server.begin();
}
void loop()
{
Udp.beginPacket(CONSOLE_IP, CONSOLE_PORT);
// Get the value of the Touch2 sensor on the ESP32 (GPIO2, marked as Pin 2 on the board)
// The value will typically be close to 0 when touched, and higher (~100s) when not touched
// The value is dependent on some environmental conditions like humidity and temperature
uint16_t touch2value = touchRead(T2);
Serial.println(touch2value);
Udp.printf(String(touch2value).c_str()); // adds Touch2 sensor value to packet payload
Udp.endPacket();
delay(1000);
}
const char* ssid = "ESP32-<YourFirstName>"Part 2: Reading values from ESP32 on your Laptop
You will be reading the UDP messages using a Python script.
python in your terminal and it returns a response, you should be good to go.python -m pip install socket.pyreader.py# read UPD message from the ESP32
# this code should be run on a laptop 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
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.decode())
if __name__ == "__main__":
loop()
python reader.py