jce
Published © MIT

IoT basics: Remote-control GPIOs in MicroPython

A simple example showing how to set up a WiFi access point on your MicroPython board, run a webserver and use it to remote-control GPIOs.

BeginnerProtip30 minutes287
IoT basics: Remote-control GPIOs in MicroPython

Things used in this project

Hardware components

CY8CPROTO-062-4343W
Infineon CY8CPROTO-062-4343W
×1

Software apps and online services

MicroPython
MicroPython

Story

Read more

Code

main.py

MicroPython
Application code
from machine import Pin
import network
import uasyncio
from nanoweb import Nanoweb

# GPIO initialisation
led = Pin("P13_7")   # LED pin for CY8CPROT-062-4343W
led.init(Pin.OUT)

# WiFi access point setup
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid='PSoC', key='infineon')

# Nanoweb webserver setup
naw = Nanoweb()

@naw.route("/")
async def index(request):
    await request.write("HTTP/1.1 200 OK\r\n\r\n")
    await request.write('<html>')
    await request.write('''<button onclick="window.location.href='/on';">Turn LED on</button>''')
    await request.write('''<button onclick="window.location.href='/off';">Turn LED off</button>''')
    await request.write('</html>')

@naw.route("/on")
async def on(request):
    led.on()
    await index(request)

@naw.route("/off")
async def off(request):
    led.off()
    await index(request)

# uasyncio loop for webserver
loop = uasyncio.get_event_loop()
loop.create_task(naw.run())
loop.run_forever()

Nanoweb

Lightweight webserver module for MicroPython by hugokernel

Credits

jce

jce

1 project • 2 followers
Thanks to hugokernel.

Comments