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

看了很多大佬写的给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=none
wifipassword=none

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

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

<!doctype html>
<html lang="en">
<html>
  <head>
    <title>连接wifi</title>
    <meta charset="UTF-8">
  </head>
  <body>
    <h1>连接wifi</h1>
    <p>请输入wifi名称和密码</p>
<form method="post" action="/submit_data">
  <p>
    wifi名称:
    <input name="wifiname" id='wifiname' autofocus />
  </p>
    <p>
    wifi密码:
    <input name="wifipwd" autofocus />
  </p>
  <input name="submitBtn" id='submitBtn' type="submit" value="Submit" class="disabled" />
</form>
    <style>  
        .disabled {  
            background-color: grey;  
            pointer-events: none; /* 防止按钮被点击 */  
        }  
    </style> 
<script>  
    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');  
        }  
    });  
</script>  
  </body>
</html>

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

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

from microdot import Microdot, Response
from microdot_utemplate import render_template
import uos
import network
import utime



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('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已连接')

至此,结束

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大初哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值