from machine import Pin
from HCSR04 import HCSR04
import network # 引入network模組,用於連接Wi-Fi
import time
import urequests # 引入urequests模組,用於發送HTTP請求
# 連接到 Wi-Fi 網絡
sta = network.WLAN(network.STA_IF) # 建立Wi-Fi station(STA)物件
sta.active(True) # 啟用Wi-Fi介面
sta.connect('Wokwi-GUEST','') # 連接到指定的Wi-Fi網絡,請替換成你的Wi-Fi SSID和密碼
while not sta.isconnected(): # 等待直到連接成功
pass
# 定義 ThingSpeak API 的主機和 API 金鑰
host = 'http://api.thingspeak.com' # ThingSpeak API 的主機位址
api_key = '5LMSE9MIB2JUZCCN' # 你的 ThingSpeak API 金鑰,請替換成自己的金鑰
sr04_L = HCSR04(trigPin = 25, echoPin = 26 )
sr04_R = HCSR04(trigPin = 19, echoPin = 18 )
LED_red = Pin(5, Pin.OUT) # 紅色 LED
LED_green = Pin(17, Pin.OUT) # 綠色 LED
LED_blue = Pin(16, Pin.OUT) # 藍色 LED
try :
while True :
try :
L = sr04_L.distance()
R = sr04_R.distance()
print ('Left Distance:' , L, 'cm' )
print ('Right Distance:' , R, 'cm' )
url = '%s/update?api_key=%s&field4=%s&field5=%s'%(host, api_key, L, R) # 製作上傳 URL
r = urequests.get(url) # 發送 GET 請求將數據上傳到 ThingSpeak
if (L > 100 or R > 100):
print('hello')
except Exception as e:
print (e.args [0])
time.sleep (1)
except KeyboardInterrupt :
print ('Program stopped!' )