import machine
import time
import network
import socket
# Define the pin number where the relay module is connected
relay_pin = machine.Pin(27, machine.Pin.OUT)
# Function to turn the relay on
def relay_on():
relay_pin.value(1) # Set the pin to HIGH
# Function to turn the relay off
def relay_off():
relay_pin.value(0) # Set the pin to LOW
# Connect to your Wi-Fi network
wifi_ssid = "YourWiFiSSID"
wifi_password = "YourWiFiPassword"
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect(wifi_ssid, wifi_password)
while not sta.isconnected():
pass
# Create a socket server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', 80))
server.listen(1)
try:
while True:
# Wait for a client to connect
conn, addr = server.accept()
# Read the request from the client
request = conn.recv(1024).decode()
# Check if the request is to turn the relay on or off
if "GET /on" in request:
relay_on()
elif "GET /off" in request:
relay_off()
# Send an HTTP response to the client
response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"
conn.send(response)
# Close the connection
conn.close()
except KeyboardInterrupt:
# If you press Ctrl+C, this will stop the loop and turn off the relay
relay_off()