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! 🎉
- 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 viapip install microweb
or from Ishanoshada/Microweb). mpremote
for running scripts and viewing logs (included with MicroPython or install viapip install mpremote
).- The
MicroWeb
framework (included in the repository or available at Ishanoshada/Microweb).
Ready to spark some IoT magic? Follow these steps to get started! ✨
-
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.
- For ESP8266, add
- 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 .
- Option 1: Via pip (recommended):
- Ensure the
MicroWeb
framework (microweb.py
) is uploaded to the ESP32 (included in the repository or from Ishanoshada/Microweb).
- Flash MicroPython firmware to your ESP32 with the
-
Clone the Repository:
- Grab this exciting collection of examples:
git clone https://github.com/Ishanoshada/Microweb-Examples.git
- Grab this exciting collection of examples:
-
Upload and Run an Application:
- Navigate to a project folder (e.g.,
laser-diode
) and uploadapp.py
and thestatic/
folder (containingindex.html
andstyle.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.
- Remove the boot script with
- Before switching to another project, clear the current project’s files to avoid conflicts:
microweb remove --remove --port COM10
- Navigate to a project folder (e.g.,
-
Connect Hardware:
- Follow the wiring instructions for each example below to bring your hardware to life! 🔌
-
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 likehttp://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
- After running
-
List Files on Device:
- Check uploaded files:
microweb ls --port COM10
- Check uploaded files:
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
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.
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! 🌟
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!
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()
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.
- ESP32 microcontroller.
- Laser diode module.
- 330Ω resistor (for safety).
- Jumper wires and breadboard.
- 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.
- Verify the laser diode’s voltage rating (typically 3-5V) matches the ESP32’s 3.3V output, or use a level shifter if needed.
- Wire the laser diode as described above.
- Navigate to the
laser-diode
folder and run:microweb run app.py --port COM10
- Optionally, set the app to auto-run on boot:
microweb run app.py --add-boot --port COM10
- Connect to the
LaserESP32
Wi-Fi network (password:laser1234
). - Access the interface at the displayed IP (e.g.,
http://192.168.4.1
). - Before moving to the next project, remove the current project’s files:
microweb remove --remove --port COM10
- 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.
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! 🔍
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.
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()
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.
- ESP32 microcontroller.
- Radar sensor (e.g., RCWL-0516).
- Jumper wires and breadboard.
- Connect the radar sensor’s OUT pin to GPIO 5 on the ESP32.
-
- Connect the radar sensor’s VCC pin to the 3.3V or 5V pin on the ESP32 (check sensor’s voltage requirements).
- Connect the radar sensor’s GND pin to a GND pin on the ESP32.
- Wire the radar sensor as described above.
- Navigate to the
microwave-radar
folder and run:microweb run app.py --port COM10
- Optionally, set the app to auto-run on boot:
microweb run app.py --add-boot --port COM10
- Connect to the
RadarESP32
Wi-Fi network (password:radar1234
). - Access the interface at the displayed IP (e.g.,
http://192.168.4.1
). - Before moving to the next project, remove the current project’s files:
microweb remove --remove --port COM10
- Real-time motion status display.
- Auto-refreshes every 2 seconds.
- JSON endpoint (
/status
) for motion data.
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! 📡
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.
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()
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.
- ESP32 microcontroller.
- Ultrasonic sensor (e.g., HC-SR04).
- Jumper wires and breadboard.
- Connect the ultrasonic sensor’s TRIGGER pin to GPIO 5 on the ESP32.
- Connect the ultrasonic sensor’s ECHO pin to GPIO 18 on the ESP32.
- Connect the ultrasonic sensor’s VCC pin to the 5V pin on the ESP32 (HC-SR04 typically requires 5V).
- Connect the ultrasonic sensor’s GND pin to a GND pin on the ESP32.
- Wire the ultrasonic sensor as described above.
- Navigate to the
ultra-sonic
folder and run:microweb run app.py --port COM10
- Optionally, set the app to auto-run on boot:
microweb run app.py --add-boot --port COM10
- Connect to the
UltraESP32
Wi-Fi network (password:ultra1234
). - Access the interface at the displayed IP (e.g.,
http://192.168.4.1
). - Before moving to the next project, remove the current project’s files:
microweb remove --remove --port COM10
- Displays distance in centimeters with a clean interface.
- Auto-refreshes every 2 seconds.
- JSON endpoint (
/distance
) for distance data.
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! 🚀
- 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
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! 🤝
This project is licensed under the MIT License. Check the LICENSE
file or the MicroWeb repository for details.