MicroWebSrv2 with Micropython and ESP32, how to toggle a LED

microwebsrv2

Microwebsrv2 is a library written in micropython that allows you to create your personal webserver by using a simple ESP32, the library is great but there is not so much information in the web.

In this post i want to share with you my progress of lighting an LED via an HTML button that through a script allow the Web Route to send and receive information from the Hardware of your Microcontroller to the webserver.

The code divide in two parts, the main.py:

from MicroWebSrv2  import *
from time          import sleep
from _thread       import allocate_lock
import network
import machine
 ============================================================================
#MANAGE NETWORK
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
    print('connecting to network...')
    sta_if.active(True)
    sta_if.connect('ssid', 'password')
    while not sta_if.isconnected():
        pass
print('network config:', sta_if.ifconfig())
 ============================================================================
led = machine.Pin(14, machine.Pin.OUT)


# Add the handler function to handle HTTP GET requests for "/button" URL
@WebRoute(GET,'/toggle')

# Define the handler function for the HTML button
def ButtonGet(microWebSrv2, request) :
    led.value(not led.value()) # Toggle the LED state
    html = """<html><body>
              <form action="/button-test" method="post">
                  <button style="font-size:24px">Toggle LED</button>
                </form>
             </body></html>"""
    ContentType = none



# ------------------------------------------------------------------------

# Loads the WebSockets module globally and configure it,
#wsMod = MicroWebSrv2.LoadModule('WebSockets')
# wsMod.OnWebSocketAccepted = OnWebSocketAccepted

# Instanciates the MicroWebSrv2 class,
mws2 = MicroWebSrv2()
# SSL is not correctly supported on MicroPython.
# But you can uncomment the following for standard Python.
# mws2.EnableSSL( certFile = 'SSL-Cert/openhc2.crt',
#                 keyFile  = 'SSL-Cert/openhc2.key' )

# For embedded MicroPython, use a very light configuration,
mws2.SetEmbeddedConfig()

# All pages not found will be redirected to the home '/',
mws2.NotFoundURL = '/'

# Starts the server as easily as possible in managed mode,
mws2.StartManaged()

# Main program loop until keyboard interrupt,
try :
    while mws2.IsRunning :
        sleep(1)
except KeyboardInterrupt :
    pass

# End,
print()
mws2.Stop()
print('Bye')
print()


And naturally the HTML file has to have a button with a script front-end side:

<!DOCTYPE html>

<html lang=it>

    <head>
     <script>
      function toggleLED() {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "/toggle", true);
        xhr.send();
      }
      
    </script>
        <meta charset="UTF-8" />
        <title>MicroWebSrv2</title>
        <link rel="stylesheet" href="style.css" />
    </head>

   
           
		
 <button id="toggle-button" onclick="toggleLED()">Toggle LED</button>

           
        </div>
    </body>

</html>

Et Voila’, you’ll be able to finally light an LED with this specific library, don’t forget to add the Pin of your Microcontroller and Network credentials,

To program the ESP32 i use REPL with PYBOARD within Linux that i find the most comfortable and you?

let me know if there is interest in this fantastic library, i could write more posts!

Lascia un commento

Il tuo indirizzo email non sarĂ  pubblicato. I campi obbligatori sono contrassegnati *