首先请参考我前面写的文章《基于esp32 C3的micropython开热点web配置无线网络保姆级教程》,学会如何在esp32c3上部署网站,本文只讲关键代码。
首先说下templates文件夹里面的html代码:
<!doctype html>
<html lang="en">
<html>
<head>
<title>点亮led灯</title>
<meta charset="UTF-8">
</head>
<body>
<button id="myButton" value="myValue">让灯闪烁</button>
<script>
document.getElementById('myButton').addEventListener('click', function(event) {
// 阻止按钮的默认行为(如果有的话)
event.preventDefault();
// 获取按钮的值
var buttonValue = this.value;
// 创建一个新的XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// 定义请求完成后的回调函数
xhr.onload = function() {
if (this.status === 200) {
// 请求成功,处理响应数据
console.log(this.responseText);
} else {
// 请求失败,处理错误情况
console.error('AJAX请求失败: ' + this.statusText);
}
};
// 定义请求发生错误时的回调函数
xhr.onerror = function() {
console.error('AJAX请求发生错误');
};
// 打开请求,指定请求方法和URL
// 这里的URL应该替换为你想要发送请求的服务器端脚本的URL
xhr.open('POST', '/receive_ajax', true);
xhr.send('buttonValue=' + encodeURIComponent(buttonValue));
});
</script>
</body>
</html>
在本教程中,我们使用AJAX方法,向后端发送信号。
后端主程序:
from microdot import Microdot, Response
from microdot_utemplate import render_template
import uos
import network
import utime
import machine
import time
LED_PIN = 2
# 初始化 GPIO 引脚为输出模式
led = machine.Pin(LED_PIN, machine.Pin.OUT)
app = Microdot()
Response.default_content_type = 'text/html'
def write_ini_file(filename, config_dict):
with open(filename, 'w') as f:
for key, value in config_dict.items():
f.write(f'{key} = {value}\n')
def read_ini_file(filename):
config_dict = {}
with open(filename, 'r') as f:
for line in f:
line = line.strip() # 去除行尾的换行符和空格
if line and not line.startswith('#'): # 忽略空行和注释行(以 # 开头的行)
key, value = line.split('=') # 分割键和值
config_dict[key.strip()] = value.strip() # 将键和值添加到字典中,并去除前后的空格
return config_dict
def connect_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF) # 创建WLAN对象,STA模式表示Station模式,即客户端模式
wlan.active(True) # 激活接口
if not wlan.isconnected(): # 检查是否已经连接
wlan.scan()
print('connecting to network...')
wlan.connect(ssid, password) # 连接到指定的SSID和密码
while not wlan.isconnected(): # 等待连接成功
print('.', end='')
utime.sleep(1)
print('network config:', wlan.ifconfig()) # 打印网络配置信息
@app.route('/')
def index(req):
return render_template('lightled.html')
@app.post('/receive_ajax')
def submit_form(req):
for i in range(8):
led.value(not led.value()) # 切换 LED 的状态
time.sleep(1) # 等待一
led.value(0)
return 'wifi信息已配置'
if __name__ == '__main__':
wlan = network.WLAN(network.STA_IF) # 创建WLAN对象,STA模式表示Station模式,即客户端模式
wlan.active(True) # 激活接口
config = read_ini_file('wificonfig.ini')
# 检查是否已经连接
print('connecting to network...')
print((config['wifissid'],config['wifipassword']))
# 连接到指定的SSID和密码
wlan.connect(config['wifissid'],config['wifipassword'])
print('network config:', wlan.ifconfig())
print('wifi已连接')
app.run(debug=True)
运行之后,控制台会打印esp3c3的IP地址,比如我的是:
Network config: ('192.168.4.1', '255.255.255.0', '192.168.4.1', '0.0.0.0')
Starting sync server on 0.0.0.0:5000...
那么我们再在电脑上打开我们的极点云(注意!电脑要和esp32c3在同一网络),再参考我之前写的文章《树莓派部署网站(内网穿透)点亮LED灯保姆级教程(五)》,
点击左侧仪表盘的隧道管理——创建隧道:
- 隧道名称:可自定义,注意不要重复
- 协议:http
- 本地地址:
- 端口类型:随机域名
- 地区:China vip
输入ip地址和端口(比如我是:192.168.4.1:5000),填写完毕后点击创建,隧道创建成功后,点击左侧的状态——在线隧道列表,可以看到刚刚创建的隧道已经有生成了相应的公网地址,将其复制下来,即可测试访问。