ESP32-CAM处理多工-使用计时器 - uPython
先前有介绍过多种多工的方式,使用软件:_thread;使用硬件中断:定时器触发与引脚上的电压变化,在此用定时器触发的方式,让 ESP32-CAM 同时可以处理网页的画面,另一方面还可以控制灯光的闪烁。
timer.py
from microdot import Microdot, send_file
from machine import Timer, Pin
import time
# LED状态反转
def toggle_led(led_pin):
led_pin.value(not led_pin.value())
def led_blink_timed(timer, led_pin, millisecond):
period = int(0.5 * millisecond)
timer.init(period=period, mode=Timer.PERIODIC, callback=lambda t: toggle_led(led_pin))
timer = Timer(1)
app = Microdot()
@app.route('/', methods=['GET', 'POST'])
def index(request):
response = send_file('hello.html')
print(request.args)
return response
@app.route('/pin', methods=['GET', 'POST'])
def index(request):
if 'value' not in request.args:
return 'format is URL/pin?value=x&time=y'
pin = int(request.args['value'])
time = int(request.args['time']) if 'time' in request.args else 500
led_pin = Pin(pin, Pin.OUT)
led_blink_timed(timer, led_pin, millisecond=time)
app.run(debug=True)
浏览器画面
hello.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ESP32-CAM</title>
<meta name="robots" content="index,follow">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h1>这是esp32-cam多工示例</h1>
<p><a href="/pin?time=100&value=4">闪光灯 LED 短闪</a>
<p><a href="/pin?time=600&value=4">闪光灯 LED 慢闪</a>
<p><a href="/pin?time=100&value=33">红灯 LED 短闪</a>
<p><a href="/pin?time=600&value=33">红灯 LED 慢闪</a>
</body>
</html>
参考资料
- microdot, https://github.com/miguelgrinberg/microdot
- A Simple Microdot Web Server, https://microdot.readthedocs.io/en/latest/