07-05-2025, 06:39 PM
this code of python in esp32 works:
Now, I'm going to try to do it with Ethernet
Code:
import network
import socket
from machine import Pin
import time
# Wi-Fi credentials
WIFI_SSID = "WIFI_NAME"
WIFI_PASS = "WIFI_PASSWORD"
# GPIO pins for relays (active LOW)
RELAY1_GPIO = 15
RELAY2_GPIO = 2
# Setup GPIOs
relay1 = Pin(RELAY1_GPIO, Pin.OUT, value=1)
relay2 = Pin(RELAY2_GPIO, Pin.OUT, value=1)
def set_relay(relay_num, on):
gpio = relay1 if relay_num == 1 else relay2
gpio.value(0 if on else 1)
# Connect to Wi-Fi
def wifi_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print(f"Connecting to {WIFI_SSID} ...")
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
time.sleep(0.5)
print(".", end="")
print("\nConnected, IP:", wlan.ifconfig()[0])
# HTTP response helpers
def http_response(conn, body):
conn.send(b"HTTP/1.1 200 OK\r\n")
conn.send(b"Content-Type: text/plain\r\n")
conn.send(b"Content-Length: %d\r\n" % len(body))
conn.send(b"\r\n")
conn.send(body)
# HTTP server
def start_server():
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print("HTTP server listening on port 80")
while True:
try:
conn, addr = s.accept()
print("Client connected from", addr)
request = conn.recv(1024).decode()
print("Request:", request)
path = ""
try:
path = request.split(" ")[1]
except:
pass
if path == "/":
body = (
"ESP32 Relay Control:\n"
"/relay1/on or /relay1/off\n"
"/relay2/on or /relay2/off\n"
)
elif path == "/relay1/on":
set_relay(1, True)
body = "Relay 1 ON"
elif path == "/relay1/off":
set_relay(1, False)
body = "Relay 1 OFF"
elif path == "/relay2/on":
set_relay(2, True)
body = "Relay 2 ON"
elif path == "/relay2/off":
set_relay(2, False)
body = "Relay 2 OFF"
else:
body = "Invalid path"
http_response(conn, body.encode())
conn.close()
except Exception as e:
print("Error handling connection:", e)
# Main app
wifi_connect()
start_server()Now, I'm going to try to do it with Ethernet

