Skip to content

MicroWeb-Examples is a collection of MicroPython-based IoT projects using the MicroWeb framework on ESP32. Featuring three apps—Laser Diode Control, Microwave Radar Motion Detector, and Ultrasonic Distance Monitor—these examples showcase web-based hardware control and monitoring with clean, beginner-friendly code. 🚀

Notifications You must be signed in to change notification settings

Ishanoshada/Microweb-Examples

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MicroWeb Example Apps 🚀

Welcome to the MicroWeb Example Apps repository, your launchpad for crafting dazzling IoT projects with the MicroWeb framework on ESP32 microcontrollers! 🌐 This vibrant collection showcases three web-based applications—Laser Diode Control, Microwave Radar Motion Detector, and Ultrasonic Distance Monitor—that make controlling and monitoring hardware a breeze. With the MicroWeb framework, you’ll write concise, elegant code compared to raw MicroPython, saving time and effort while building powerful IoT solutions. Whether you’re a beginner or an IoT pro, these examples will ignite your creativity! 💡

Each project transforms your ESP32 into a Wi-Fi hub, serving user-friendly web interfaces to interact with hardware from any browser. Below, we include the full app.py code for each project to demonstrate how MicroWeb simplifies web server setup, routing, and templating compared to the verbose setup required in raw MicroPython. Let’s dive in and make your hardware shine! 🎉

img

Table of Contents

Prerequisites

  • Hardware:
    • ESP32 microcontroller (e.g., ESP32-DevKitC) – your IoT powerhouse! ⚡
    • Laser diode module (for laser-diode).
    • Radar sensor (e.g., RCWL-0516) for microwave-radar).
    • Ultrasonic sensor (e.g., HC-SR04) for ultra-sonic).
    • Jumper wires, a breadboard, and a 330Ω resistor (for laser-diode).
  • Software:
    • MicroPython firmware (grab it from MicroPython).
    • The MicroWeb CLI tool (install via pip install microweb or from Ishanoshada/Microweb).
    • mpremote for running scripts and viewing logs (included with MicroPython or install via pip install mpremote).
    • The MicroWeb framework (included in the repository or available at Ishanoshada/Microweb).

Setup Instructions

Ready to spark some IoT magic? Follow these steps to get started! ✨

  1. Install MicroPython and MicroWeb:

    • Flash MicroPython firmware to your ESP32 with the MicroWeb CLI:
      microweb flash --port COM10
      • For ESP8266, add --esp8266. For custom firmware, use --firmware firmware.bin.
      • Use --erase to clear flash memory if needed.
    • Install the MicroWeb CLI tool. Choose one method:
      • Option 1: Via pip (recommended):
        pip install microweb
      • Option 2: From source:
        git clone https://github.com/Ishanoshada/Microweb.git
        cd Microweb
        python -m venv venv
        source venv/bin/activate  # On Windows: venv\Scripts\activate
        pip install .
    • Ensure the MicroWeb framework (microweb.py) is uploaded to the ESP32 (included in the repository or from Ishanoshada/Microweb).
  2. Clone the Repository:

    • Grab this exciting collection of examples:
      git clone https://github.com/Ishanoshada/Microweb-Examples.git
  3. Upload and Run an Application:

    • Navigate to a project folder (e.g., laser-diode) and upload app.py and the static/ folder (containing index.html and style.css where applicable) using:
      cd laser-diode
      microweb run app.py --port COM10
      • This validates the script, checks for MicroPython, uploads changed files, and runs the app.
      • If MicroPython is missing, the CLI prompts to run microweb flash.
    • To auto-run the app on power-up:
      microweb run app.py --add-boot --port COM10
      • Remove the boot script with --remove-boot if needed.
    • Before switching to another project, clear the current project’s files to avoid conflicts:
      microweb remove --remove --port COM10
  4. Connect Hardware:

    • Follow the wiring instructions for each example below to bring your hardware to life! 🔌
  5. Access the Web Interface:

    • After running microweb run, the CLI shows the ESP32’s IP (e.g., http://192.168.4.1 in AP mode or a network IP like http://192.168.8.102).
    • Connect to the app’s Wi-Fi network (e.g., LaserESP32, password: laser1234) in AP mode.
    • Open a browser and visit the displayed IP address.
    • Check the IP manually:
      mpremote connect COM10 exec "import app; print(app.app.get_ip())"
    • View real-time logs:
      mpremote connect COM10 run app.py
  6. List Files on Device:

    • Check uploaded files:
      microweb ls --port COM10

Repository Structure

Microweb-Examples/
├── laser-diode/
│   ├── app.py
│   └── static/
│       ├── index.html
│       └── style.css
├── microwave-radar/
│   ├── app.py
│   └── static/
│       └── index.html
├── ultra-sonic/
│   ├── app.py
│   └── static/
│       ├── index.html
│       └── style.css
├── microweb.py  (MicroWeb framework, if included)
└── README.md

Code Size Comparison (Line Count)

The MicroWeb framework simplifies web server setup, routing, and templating compared to raw MicroPython, which requires manual HTTP handling with usocket and uasyncio. Below is a table comparing the line counts of app.py for each project using MicroWeb versus a raw MicroPython implementation (estimated based on equivalent functionality):

Project MicroWeb Line Count Raw MicroPython Line Count Difference
Laser Diode Control 24 ~60 -36
Microwave Radar 22 ~55 -33
Ultrasonic 34 ~70 -36

Notes:

  • MicroWeb Line Count: Derived from the provided app.py files, counting non-empty, non-comment lines.
  • Raw MicroPython Line Count: Estimated based on implementing an equivalent HTTP server with usocket, handling routes, serving static files, and rendering HTML without a templating engine. Raw MicroPython requires additional code for socket setup, request parsing, and response formatting.
  • Difference: Negative values indicate MicroWeb’s concise routing and templating reduce code size significantly, making it ideal for resource-constrained devices.

Example Applications

Laser Diode Control

img1

Description

Light up your world with the laser-diode example! This project lets you toggle a laser diode connected to GPIO 4 using a sleek web interface. Watch the laser’s state ("ON" or "OFF") glow green or red, and control it remotely with a JSON endpoint. Perfect for experimenting with GPIO output and web-based control! 🌟

Why MicroWeb Shines

MicroWeb makes this project a breeze by handling HTTP routing, static file serving, and templating in just 24 lines of app.py code. With raw MicroPython, you’d need ~60 lines to set up a usocket-based server, parse POST requests, and manually render HTML, making MicroWeb’s concise syntax a game-changer!

app.py Code

from machine import Pin
from microweb import MicroWeb

# Laser setup
laser_pin = Pin(4, Pin.OUT)
laser_state = False  # Initially off
print("Laser initialized on GPIO 4")

# Initialize MicroWeb with Access Point
print("Starting MicroWeb...")
app = MicroWeb(
    debug=True,
    ap={"ssid": "LaserESP32", "password": "laser1234"},
    mode="ap"
)

# Route for home page
@app.route('/')
def home(req):
    return app.render_template('index.html', state="ON" if laser_state else "OFF", color="green" if laser_state else "red")

# Route for toggling laser
@app.route('/laser/toggle', methods=['POST', 'GET'])
def toggle_laser(req):
    global laser_state
    laser_state = not laser_state
    laser_pin.value(1 if laser_state else 0)
    print(f"Laser turned {'ON' if laser_state else 'OFF'}")
    return app.json_response({"state": "ON" if laser_state else "OFF"})

# Register static files
app.add_static('/style.css', 'style.css')

# Start the server
print("Starting web server...")
app.run()

Files

  • app.py: Sets up the ESP32 as an Access Point (LaserESP32, password: laser1234), controls the laser diode, and serves the web interface.
  • static/index.html: Displays the laser state and a toggle button.
  • static/style.css: Styles the interface with dynamic green/red colors based on laser state.

Hardware Requirements

  • ESP32 microcontroller.
  • Laser diode module.
  • 330Ω resistor (for safety).
  • Jumper wires and breadboard.

Wiring Instructions

  1. Connect the laser diode’s positive (anode) pin to GPIO 4 on the ESP32 through a 330Ω resistor to limit currentestn2. Connect the laser diode’s negative (cathode) pin to a GND pin on the ESP32.
  2. Verify the laser diode’s voltage rating (typically 3-5V) matches the ESP32’s 3.3V output, or use a level shifter if needed.

Setup

  1. Wire the laser diode as described above.
  2. Navigate to the laser-diode folder and run:
    microweb run app.py --port COM10
  3. Optionally, set the app to auto-run on boot:
    microweb run app.py --add-boot --port COM10
  4. Connect to the LaserESP32 Wi-Fi network (password: laser1234).
  5. Access the interface at the displayed IP (e.g., http://192.168.4.1).
  6. Before moving to the next project, remove the current project’s files:
    microweb remove --remove --port COM10

Features

  • Toggle the laser with a stylish web button.
  • Displays laser state with green (ON) or red (OFF) text.
  • JSON endpoint (/laser/toggle) for remote control and status.

Microwave Radar Motion Detector

img2

Description

Become a motion-sensing master with the microwave-radar example! This project uses a radar sensor (e.g., RCWL-0516) on GPIO 5 to detect motion. The web interface shows "Motion Detected" or "No Motion" with a 2-second auto-refresh, and a JSON endpoint lets you integrate it with other systems. Ideal for security or automation projects! 🔍

Why MicroWeb Shines

In just 22 lines of app.py code, MicroWeb handles the web server, routing, and templating effortlessly. A raw MicroPython version would require ~55 lines to set up a usocket server, handle HTTP requests, and serve HTML, highlighting MicroWeb’s streamlined approach.

app.py Code

from machine import Pin
from microweb import MicroWeb
import time

# Radar setup
radar_pin = Pin(5, Pin.IN)  # GPIO 5 for radar OUT
print("Radar initialized on GPIO 5")

# Initialize MicroWeb with Access Point
print("Starting MicroWeb...")
app = MicroWeb(
    debug=True,
    ap={"ssid": "RadarESP32", "password": "radar1234"},
    mode="ap"
)

# Route for home page
@app.route('/')
def home(req):
    motion_detected = radar_pin.value()
    status = "Motion Detected" if motion_detected else "No Motion"
    print(f"Motion status: {status}")
    return app.render_template('index.html', status=status)

# Route for JSON motion status
@app.route('/status')
def get_status(req):
    motion_detected = radar_pin.value()
    status = "Motion Detected" if motion_detected else "No Motion"
    print(f"Status request: {status}")
    return app.json_response({"status": status})

# Start the server
print("Starting web server...")
app.run()

Files

  • app.py: Configures the ESP32 as an Access Point (RadarESP32, password: radar1234), reads the radar sensor, and serves the web interface.
  • static/index.html: Displays the motion status with auto-refresh.

Hardware Requirements

  • ESP32 microcontroller.
  • Radar sensor (e.g., RCWL-0516).
  • Jumper wires and breadboard.

Wiring Instructions

  1. Connect the radar sensor’s OUT pin to GPIO 5 on the ESP32.
    1. Connect the radar sensor’s VCC pin to the 3.3V or 5V pin on the ESP32 (check sensor’s voltage requirements).
  2. Connect the radar sensor’s GND pin to a GND pin on the ESP32.

Setup

  1. Wire the radar sensor as described above.
  2. Navigate to the microwave-radar folder and run:
    microweb run app.py --port COM10
  3. Optionally, set the app to auto-run on boot:
    microweb run app.py --add-boot --port COM10
  4. Connect to the RadarESP32 Wi-Fi network (password: radar1234).
  5. Access the interface at the displayed IP (e.g., http://192.168.4.1).
  6. Before moving to the next project, remove the current project’s files:
    microweb remove --remove --port COM10

Features

  • Real-time motion status display.
  • Auto-refreshes every 2 seconds.
  • JSON endpoint (/status) for motion data.

Ultrasonic Distance Monitor

img3

Description

Measure the world around you with the ultra-sonic example! This project uses an ultrasonic sensor (e.g., HC-SR04) on GPIO 5 (trigger) and GPIO 18 (echo) to calculate distances in centimeters. The web interface updates every 2 seconds, and a JSON endpoint provides data for your apps. Perfect for robotics or proximity projects! 📡

Why MicroWeb Shines

With just 34 lines in app.py, MicroWeb simplifies distance measurement, web serving, and JSON responses. A raw MicroPython implementation would need ~70 lines to handle the HTTP server, request parsing, and HTML rendering manually, showcasing MicroWeb’s efficiency.

app.py Code

from machine import Pin
import time
from microweb import MicroWeb

# Ultrasonic sensor setup
trigger_pin = Pin(5, Pin.OUT)  # Trigger pin (GPIO 5)
echo_pin = Pin(18, Pin.IN)     # Echo pin (GPIO 18)

def measure_distance():
    # Send 10us pulse to trigger
    trigger_pin.value(0)
    time.sleep_us(2)
    trigger_pin.value(1)
    time.sleep_us(10)
    trigger_pin.value(0)
    
    # Wait for echo
    while echo_pin.value() == 0:
        pass
    start_time = time.ticks_us()
    
    while echo_pin.value() == 1:
        pass
    end_time = time.ticks_us()
    
    # Calculate distance (speed of sound = 343 m/s, or 0.0343 cm/us)
    duration = time.ticks_diff(end_time, start_time)
    distance = (duration * 0.0343) / 2  # Divide by 2 for round trip
    return round(distance, 2)  # Return distance in cm

# Initialize MicroWeb with Access Point
app = MicroWeb(
    debug=True,
    ap={"ssid": "UltraESP32", "password": "ultra1234"},
    mode="ap"
)

# Route for home page
@app.route('/')
def home(req):
    distance = measure_distance()
    return app.render_template('index.html', distance=distance)

# Route for JSON distance data
@app.route('/distance')
def get_distance(req):
    distance = measure_distance()
    return app.json_response({"distance": distance, "unit": "cm"})

# Register static files
app.add_static('/style.css', 'style.css')

# Start the server
app.run()

Files

  • app.py: Configures the ESP32 as an Access Point (UltraESP32, password: ultra1234), measures distance, and serves the web interface.
  • static/index.html: Displays the distance with auto-refresh.
  • static/style.css: Styles the interface with a vibrant blue distance display.

Hardware Requirements

  • ESP32 microcontroller.
  • Ultrasonic sensor (e.g., HC-SR04).
  • Jumper wires and breadboard.

Wiring Instructions

  1. Connect the ultrasonic sensor’s TRIGGER pin to GPIO 5 on the ESP32.
  2. Connect the ultrasonic sensor’s ECHO pin to GPIO 18 on the ESP32.
  3. Connect the ultrasonic sensor’s VCC pin to the 5V pin on the ESP32 (HC-SR04 typically requires 5V).
  4. Connect the ultrasonic sensor’s GND pin to a GND pin on the ESP32.

Setup

  1. Wire the ultrasonic sensor as described above.
  2. Navigate to the ultra-sonic folder and run:
    microweb run app.py --port COM10
  3. Optionally, set the app to auto-run on boot:
    microweb run app.py --add-boot --port COM10
  4. Connect to the UltraESP32 Wi-Fi network (password: ultra1234).
  5. Access the interface at the displayed IP (e.g., http://192.168.4.1).
  6. Before moving to the next project, remove the current project’s files:
    microweb remove --remove --port COM10

Features

  • Displays distance in centimeters with a clean interface.
  • Auto-refreshes every 2 seconds.
  • JSON endpoint (/distance) for distance data.

MicroWeb Framework

The MicroWeb framework is your ticket to building lightweight, powerful web servers on MicroPython for IoT applications. Designed for resource-constrained devices like the ESP32, it streamlines web development with easy routing and templating. Explore more at the MicroWeb GitHub repository! 🚀

Notes

  • Safety First: Use a resistor for the laser diode to prevent damage, and ensure proper power supply for all components.
  • Port Customization: Replace COM10 with your ESP32’s serial port (e.g., /dev/ttyUSB0 on Linux/Mac).
  • Tweak Refresh Rates: Adjust the 2-second auto-refresh in index.html for faster or slower updates.
  • Production Tips: Add error handling (e.g., sensor timeouts in ultra-sonic) and use stronger Wi-Fi passwords for security.
  • Real-Time Logs: Monitor your app with:
    mpremote connect COM10 run app.py

Contributing

Got a brilliant idea for a new example or improvement? We’d love to see it! Submit pull requests or open issues to share your creativity with the community. Let’s build the future of IoT together! 🤝

License

This project is licensed under the MIT License. Check the LICENSE file or the MicroWeb repository for details.

About

MicroWeb-Examples is a collection of MicroPython-based IoT projects using the MicroWeb framework on ESP32. Featuring three apps—Laser Diode Control, Microwave Radar Motion Detector, and Ultrasonic Distance Monitor—these examples showcase web-based hardware control and monitoring with clean, beginner-friendly code. 🚀

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published