# This version shows using the slider with Microdot to control the PWM.
# The project uses special tricks to avoid limitations of the files that you can store in Wokwi
# The project was created with assistance of ChatGPT: https://chatgpt.com/share/68a7113c-5d8c-800c-b20e-c204f29aac84
import network
import asyncio
import sys
import microdot
from microdot import Microdot,Response
# Work around Wokwi flat FS limitations
sys.modules["microdot.microdot"] = microdot
import microdot_helpers
sys.modules["microdot.helpers"] = microdot_helpers
import microdot_websocket
sys.modules["microdot.websocket"] = microdot_websocket
from microdot.websocket import with_websocket
from machine import Pin, PWM, lightsleep
wlan = network.WLAN()
wlan.active(True)
wlan.connect('Wokwi-GUEST', '')
pwm0 = PWM(Pin(14), freq=5000, duty_u16=32768)
# Shared state
state = {"slider": 32768}
# Function to apply slider value (e.g., control hardware)
def apply_slider(val: int):
print("Slider value:", val)
pwm0.duty_u16(val)
html = open("html.txt").read()
app = Microdot()
Response.default_content_type = "text/html"
@app.route("/")
def index(request):
return html
import ujson # Use MicroPython's JSON module
@app.route("/ws")
@with_websocket
async def ws_handler(request, ws):
# Send initial state
await ws.send(ujson.dumps({"slider": state["slider"]}))
while True:
try:
msg = await ws.receive() # <-- receive one message
if msg is None:
break # connection closed
data = ujson.loads(msg)
if "slider" in data:
val = int(data["slider"])
state["slider"] = val
apply_slider(val)
# Echo state back
await ws.send(ujson.dumps({"slider": val}))
except Exception as e:
print("WS error:", e)
break
async def main():
#ip = connect_wifi()
#print("Open http://%s/ in your browser" % ip)
await app.start_server(host="0.0.0.0", port=80)
while True:
await asyncio.sleep(3600)
try:
asyncio.run(main())
except (KeyboardInterrupt, Exception) as e:
print("Stopped:", e)