Raspberry pi pico WiFi PWM
import time
import network
import socket
from machine import Pin, PWM
pwm = PWM(Pin(16), freq=500)
duty = 0
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('wait connecting...')
time.sleep(1)
if wlan.status() != 3:
raise RuntimeError('fail connected')
else:
print('finish connected')
status = wlan.ifconfig()
print('IPaddress = ' + status[0])
password = "your password"
# Wi-Fi connect
# HTML page
html = """
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html {
font-family: Helvetica;
text-align: center;
}
button {
color: white;
padding: 15px 32px;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
border: none;
border-radius: 15px;
}
.green { background-color: #f44336; }
.red { background-color: #00BFFF; }
button, form { display: inline-block; text-align: center; }
</style>
</head>
<body>
<h1>Raspberry Pi Pico W</h1>
<form>
<button class="green" name="pwm" value="on" type="submit">ON</button>
<button class="red" name="pwm" value="off" type="submit">OFF</button>
</form>
<p>%s</p>
</body>
</html>
"""
# Initialize pwm state
pwmState = "PWM State Unknown"
# Start configuring socket
addr = socket.getaddrinfo("0.0.0.0", 80)[0][-1]
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(1)
print("listening on", addr)
# wait for connection from client
while True:
try:
# Accept connections from clients
cl, addr = s.accept()
print("client connected from", addr)
# Receive requests from clients
request = cl.recv(1024)
request = str(request)
# find 'pwm=on' and 'pwm=off' positions from request
pwm_on = request.find("pwm=on")
pwm_off = request.find("pwm=off")
# Control pwm by position of pwm=on' or 'pwm=off' string
if pwm_on == 8:
print("pwm on")
duty = int((65535 * 50) / 100)
pwm.duty_u16(duty) # pwm > 0
if pwm_off == 8:
print("pwm off")
duty = 0
pwm.duty_u16(duty) # pwm = 0
# Set the current state of PWM
pwmState = "State: OFF" if duty == 0 else "State: ON"
# Create a response and send it to the client
response = "HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n" + (html % pwmState)
cl.send(response)
cl.close()
# Close the connection with the client if an error occurs
except OSError as e:
cl.close()
print("connection closed")