基于合宙esp32c3的micropython自动联网模块

之前给esp8266写的放到esp32c3上老报错,加上原代码太乱就重写了一下

之前无储存文件会报错,已修复

连接失败可能会报错,需要重启(有解决方法求告知)

萌新,求教

# wificonnect v2.0.esp32c3 by tdccj
from machine import Pin  # 加载运行库
import network
import time

try:
    with open('wifi.txt', 'r') as wifi:     #读取账号密码
        print('测试可用性')

except OSError:
    with open("wifi.txt", 'w') as wifi:     #如果没有储存文件则新建

        print('第一次启动')

        name = input('请输入wifi名:')
        pwd = input('请输入wifi密码:')

        wifi.write(name)
        wifi.write('\n')
        wifi.write(pwd)

print('开始读取账号密码')
with open('wifi.txt', 'r') as wifi:
    name = wifi.readline()
    name = name.strip('\n')
    pwd = wifi.readline()

print(name)
print(pwd)

wlan = network.WLAN(network.STA_IF)    #启用终端模式
wlan.active(True)       #一定要有这个!!!不然connect不工作(8266不一定)

light = Pin(12, Pin.OUT)
light.value(1)

print("wifi连接中")
wlan.connect(name, pwd)      #连接wifi

time.sleep(0.2)
STime = time.time()

while not wlan.isconnected():
    print('等待连接')
    light.value(1)
    time.sleep(1)
    light.value(0)
    time.sleep(1)
    if time.time() - STime > 10:
        print('连接失败,请重新输入')
        with open("wifi.txt", 'w') as wifi:
            name = input('请输入wifi名:')
            pwd = input('请输入wifi密码:')

            wifi.write(name)
            wifi.write('\n')
            wifi.write(pwd)

        print('开始读取账号密码')
        with open('wifi.txt', 'r') as wifi:
            name = wifi.readline()
            name = name.strip('\n')
            pwd = wifi.readline()

        print(name)
        print(pwd)

        wlan = network.WLAN(network.STA_IF)  # 启用终端模式
        wlan.active(True)  # 一定要有这个!!!不然connect不工作(8266不一定)

        light = Pin(12, Pin.OUT)
        light.value(1)

        print("wifi连接中")
        wlan.connect(name, pwd)     # 连接wifi

        time.sleep(0.2)
        STime = time.time()
if wlan.isconnected():
    for num in range(3):
        light.value(0)
        time.sleep(0.2)
        light.value(1)
        time.sleep(0.2)
    light.value(0)
    print('wifi连接成功')  # 反馈
    print('wifi信息:=%s' % str(wlan.ifconfig()))

你可能感兴趣的:(micro,python,物联网,python,iot)