网络对于现代的人们来说就和衣食住行一样重要,MicroPython 提供了非常方便的API操作网络,今天就演示一下使用ESP8266连接WIFI,话不多说,直接上代码。
import network
import time
def do_connect(essid, password):
'''
根据给定的eddid和password连接wifi
:param essid: wifi sid
:param password: password
:return: None
'''
if essid == None or essid == '':
raise BaseException('essid can not be null')
if password == None or password == '':
raise BaseException('password can not be null')
sta_if = network.WLAN(network.STA_IF)
if not sta_if.active():
print("set sta active")
sta_if.active(True)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.connect(essid, password)
retry_times = 30
while not sta_if.isconnected() and retry_times > 0:
print(" wait a moment i will try %s items,please" % retry_times)
time.sleep(2)
retry_times -= 1
print('network config:', sta_if.ifconfig())
def disconnect():
'''
断开网络连接
:return: None
'''
sta_if = network.WLAN(network.STA_IF)
if sta_if.isconnected():
sta_if.disconnect()
print('the network had been disconnect')
if __name__ == "__main__":
essid = input('please input your essid:')
password = input('please input your password:')
do_connect(essid, password)
while True:
exit = input("press Q to exit:")
if exit == 'Q':
disconnect()
break
这个小程序非常简单,相信大家一眼就看明白了,主要有3个方法,分别是do_connect(essid,password)
,disconnect()
以及main()
方法,虽然代码很少,但是已经基本满足了我们网络连接的基本需求。
最终运行效果如下:
正确连接
正确连接
未输入ssid及密码
未输入ssid及密码
搞定收工~ 下次研究一下如何连接阿里云物联网平台并与之通信,感兴趣的同学可以留言一起交流哈。
作者简介:
一个java小学生,瞎学一点python做点有趣的事情,欢迎大家留言交流。