### ex4-1 ### import esp32 import time while True: print(esp32.hall_sensor()) time.sleep(0.1) ### ex4-2 (LAB06.py) ### import esp32 import time while True: hall = esp32.hall_sensor() print(hall) if (hall < 100 and hall > 0): # 如果磁鐵距離太遠 (1 ~ 99) print("收藏盒已開啟") time.sleep(0.1) ''' 霍爾感測值會根據 ESP32 個體的差異產生誤差,有些 ESP32 的霍爾感測值會在沒有磁鐵的狀況下, 維持在 100 ~ 150 上下。如果執行上述程式就會出現問題 (磁鐵距離太遠也不會顯示『收藏盒已開啟』) 如果您的 ESP32 有遇到此問題, 可以將第 9 行的程式更改為: if ((hall < 250 and hall > 0)): 調整完就可以正常執行囉!如果此程式有更改,也請記得更改 LAB07 的第 25 行喔! ''' ### ex4-3 ### import network # 新增 network 模組 sta_if = network.WLAN(network.STA_IF) # 設定為 STA_IF 模式 sta_if.active(True) # 啟用 wifi 介面 sta_if.connect('無線網路名稱', '無線網路密碼') # 設定 wifi 帳號與密碼 while not sta_if.isconnected(): pass print(sta_if.ifconfig()[0]) # 取出並印出 IP 位置 >>> type(sta_if.ifconfig()) # 檢查回傳值的資料型別 >>> sta_if.ifconfig()[0] # 以 tuple 的索引方式取值 ### ex4-4 ### >>> string = "52python" # 字串容器:由字元組成 >>> string[2] # 以字串的索引方式取值,結果為字串 'p' >>> tuple = (1, (2, ), 3) # tuple 容器:由資料物件組成 >>> tuple[1] # 以 tuple 的索引方式取值,結果為 tuple (2, ) >>> list = [1, [2], 3] # 串列容器:由資料物件組成 >>> list[1] # 以串列的索引方式取值,結果為串列 [2] >>> set = {1, '2', 3} # 集合容器:由資料物件組成 # 集合為無序,沒有索引 >>> dick = {'A':1, 'B':'2', 'C':3} # 字典容器:由資料物件組成,以鍵:值表示 >>> dick['B'] ### ex4-5 ### # IFTTT https://ifttt.com/ ### ex4-6 ### import network, urequests # 新增 urequests 模組 sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect('無線網路名稱', '無線網路密碼') while not sta_if.isconnected(): pass print(sta_if.ifconfig()[0]) res = urequests.get("http://micropython.org/ks/test.html") # 使用 urequests 模組的 get() 函數,取得網頁內容 print(res.text) res.close() ### ex4-7 (LAB07.py) ### import esp32 import time import network # 匯入 network 模組 import urequests # 匯入 urequests 模組 url = 'IFTTT請求網址' # IFTTT 的觸發網址 sta=network.WLAN(network.STA_IF) sta.active(True) sta.connect('無線網路名稱','無線網路密碼') while not sta.isconnected(): pass print('Wi-Fi連線成功') while True: hall = esp32.hall_sensor() print(hall) if (hall < 100 and hall > 0): print("發送警訊!!!!") res = urequests.get(url) if (res.status_code == 200): print("傳送成功") else: print("傳送失敗") print("錯誤碼:", res.status_code) res.close() time.sleep(10) time.sleep(0.1)