小工具知识网

当前位置: 首页 > 行业知识 > 基于esp32 C3的micropython开热点web配置无线网络保姆级教程

行业知识

基于esp32 C3的micropython开热点web配置无线网络保姆级教程

2026-11-13 09:45:09 来源:互联网转载

看了很多大佬写的给esp32 配网的教程,打算写一篇用esp32开启热点,然后用手机连接到热点接入web的方式来给esp32配置无线网络的方法。

首先我们要下载microdot的压缩包,地址:

GitHub - miguelgrinberg/microdot: The impossibly small web framework for Python and MicroPython.

将压缩包解压,并将里面的utemplate文件夹、templates文件夹、microdot.py、microdot_utemplate.py、microdot_websocket.py、microdot_jinja.py、microdot_session.py上传进入esp32.。

新建一个wificonfig.txt,写入:

wifissid=nonewifipassword=none

保存后,重命名为wificonfig.ini,上传入esp32。

将esp32的templates文件夹中的文件全都删除,新建一个index.html,写入以下代码:

      连接wifi            

连接wifi

请输入wifi名称和密码

wifi名称:

wifi密码:

.disabled { background-color: grey; pointer-events: none; /* 防止按钮被点击 */ } document.getElementById('wifiname').addEventListener('input', function() { var inputField = document.getElementById('wifiname'); var submitBtn = document.getElementById('submitBtn'); if (inputField.value.trim() !== '') { // 如果输入框中有内容,则启用按钮 submitBtn.classList.remove('disabled'); } else { // 如果输入框中没有内容,则禁用按钮 submitBtn.classList.add('disabled'); } });

将index.html保存,并上传入esp32的templates文件夹中。

在esp32中新建main.py,写入以下代码:

from microdot import Microdot, Responsefrom microdot_utemplate import render_templateimport uosimport networkimport utimeapp = 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_dictdef 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('index.html')@app.post('/submit_data')def submit_form(req):    wifiname = req.form.get('wifiname')      wifipwd = req.form.get('wifipwd')    print(wifiname,wifipwd)    config = {      'wifissid': wifiname,      'wifipassword': wifipwd      }    write_ini_file('wificonfig.ini', config)    return 'wifi信息已配置'if __name__ == '__main__':    wlan = network.WLAN(network.STA_IF)  # 创建WLAN对象,STA模式表示Station模式,即客户端模式      wlan.active(True)  # 激活接口    while not wlan.isconnected():        config = read_ini_file('wificonfig.ini')        # 检查是否已经连接          print('connecting to network...')        print((config['wifissid'],config['wifipassword']))          # 连接到指定的SSID和密码        try:            wlan.connect(config['wifissid'],config['wifipassword'])            print('network config:', wlan.ifconfig())        except OSError as e:                    ap = network.WLAN(network.AP_IF)            ap.active(True)            ap.config(essid='MyMicroPythonAP', password='mysecretpassword')            print('Network config:', ap.ifconfig())            app.run(debug=True)    print('wifi已连接')

至此,结束

上一篇:如何在电脑上使用U盘下载歌曲

下一篇:买到域名网站怎么做推广