網(wǎng)絡(luò)對于現(xiàn)代的人們來說就和衣食住行一樣重要,MicroPython 提供了非常方便的API操作網(wǎng)絡(luò)咕晋,今天就演示一下使用ESP8266連接WIFI雹拄,話不多說,直接上代碼掌呜。
import network
import time
def do_connect(essid, password):
'''
根據(jù)給定的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():
'''
斷開網(wǎng)絡(luò)連接
: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()
方法势篡,雖然代碼很少翩肌,但是已經(jīng)基本滿足了我們網(wǎng)絡(luò)連接的基本需求。
最終運(yùn)行效果如下:
正確連接
未輸入ssid及密碼
搞定收工~ 下次研究一下如何連接阿里云物聯(lián)網(wǎng)平臺并與之通信禁悠,感興趣的同學(xué)可以留言一起交流哈念祭。
作者簡介:
一個java小學(xué)生,瞎學(xué)一點python做點有趣的事情碍侦,歡迎大家留言交流粱坤。