Re: Web server In/out + physical button control via gpio
Posted: Sat May 01, 2021 11:18 am
Interesting. I'm sure you're right about it being easily done, but for web programming n00bs like myself it would be good to see a code example
Please see the new forum at
https://forum.micropython.org/
Code: Select all
try:
import asyncio
except:
import uasyncio as asyncio
import network
from uasyncio.stream import Server
from femtoweb import FemtoWeb
from machine import Pin
app = FemtoWeb()
@app.route('/')
async def index(http_req):
""" index.html """
http_req.start_response()
repl_vars["{{button_placeholder}}"] = button_html % ""
await http_req.render_file("index.html", repl_vars)
@app.route('/update')
async def update(http_req):
""" update """
global ledState, repl_vars
ledState = not ledState
if ledState:
ledstate = "checked"
else:
ledstate = ""
http_req.start_response()
repl_vars["{{button_placeholder}}"] = button_html % ledstate
await http_req.render_file("index.html", repl_vars)
@app.route('/state')
async def state(http_req):
""" state """
http_req.start_response()
if ledState:
http_req.ws.write(b"1")
else:
http_req.ws.write(b"0")
await http_req.ws.drain()
async def main():
try:
wlan = network.WLAN(network.STA_IF) # create station interface
print(wlan.ifconfig()[0])
await Server()._serve(app.handle, '0.0.0.0', 80, 8)
except:
server = await asyncio.start_server(app.handle, '127.0.0.1', 80)
async with server:
await server.serve_forever()
async def switch():
global ledState
while True:
await asyncio.sleep(0)
if but.value() == 0:
ledState = not ledState
await asyncio.sleep(1)
async def loop():
while True:
led.value(not ledState)
await asyncio.sleep(0)
led = Pin(2, Pin.OUT)
but = Pin(4, Pin.IN, Pin.PULL_UP)
ledState = True
ledstate = ""
button_html = '''<h4>Output - GPIO 2 - State <span id="outputState"></span></h4><label class="switch"><input type="checkbox" onchange="toggleCheckbox(this)" id="output" %s ><span class="slider"></span></label>'''
repl_vars = {}
asyncio.create_task(loop())
asyncio.create_task(switch())
asyncio.run(main())
Code: Select all
while True :
# Test for button pushed, save result
# read/poll web request with zero time out
# If request is present return reply
# sleep for 100ms