from machine import Pin,PWM #加入函式庫
from HCSR04 import HCSR04
import time
import network
import urequests
from umqtt.simple import MQTTClient
import machine
from machine import SoftI2C, Pin
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
#初始化設定LCD
I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000) #設定LCD腳位
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns) #設定LCD
make_url = 'https://hook.eu2.make.com/i4i8iv9qpvcuw41c2gcv76buo69sz31f' #設定make網址
sta=network.WLAN(network.STA_IF) #建立網路
sta.active(True) #建立網路
sta.connect('Wokwi-GUEST','') #設定連到虛擬網路
print('Linking...') #顯示正在連線
while not sta.isconnected() : #當網路連上線時就會執行下段程式,不然就會卡在這循環
pass
print('Link OK') #連上線時顯示
THINGSPEAK_MQTT_CLIENT_ID = b"LjYwJwUROCQvACIELwkZNx4" #設定ID 使用者 密碼 頻道id設定,並化簡名字
THINGSPEAK_MQTT_USERNAME = b"LjYwJwUROCQvACIELwkZNx4"
THINGSPEAK_MQTT_PASSWORD = b"TRsgVocCrBz3Oh3sTXnxXDc+"
THINGSPEAK_CHANNEL_ID = b'2579435'
client = MQTTClient(server=b"mqtt3.thingspeak.com", #設定MQTT連線所需使用的資料
client_id=THINGSPEAK_MQTT_CLIENT_ID,
user=THINGSPEAK_MQTT_USERNAME,
password=THINGSPEAK_MQTT_PASSWORD,
ssl=False) #加密為否
sr04=HCSR04(trigPin=18,echoPin=19) #設定超音波腳位
sr05=HCSR04(trigPin=16,echoPin=4) #設定超音波腳位
try:
while True: #主要迴圈
try:
lcd.clear()
print('Distance:',sr04.distance(),'cm') #顯示距離
print('Distance:',sr05.distance(),'cm') #顯示距離
if sr04.distance()<100 or sr05.distance()<100: #超音波感測任一距離小於100
lcd.clear() #清除LCD
lcd.move_to(0,0) #移動到LCD的第一排一位
lcd.putstr("Alarm!") #顯示警告
time.sleep(1) #延遲1秒
lcd.clear() #清除LCD
lcd.move_to(0,0) #移動到LCD的第一排一位
lcd.putstr("Left:"+str(sr04.distance())+"cm") #顯示左邊超音波的距離
lcd.move_to(0,1) #移動到LCD的第二排一位
lcd.putstr("Right:"+str(sr05.distance())+"cm") #顯示右邊超音波的距離
client.connect() #連線
credentials = bytes("channels/{:s}/publish".format(THINGSPEAK_CHANNEL_ID), 'utf-8') #設定MQTT發布的channel
payload = bytes("field1={:.1f}&field2={:.1f}&field3={:.1f}\n".format(sr04.distance(),sr05.distance(),1), 'utf-8') #把發布內容打包,數值抓到小數點後一位
client.publish(credentials, payload) #把資料發出去
res=urequests.post(make_url+'?sonic_L='+str(sr04.distance())+"&sonic_R="+str(sr05.distance())) #上傳超音波距離
res.close()
else: #其他時候
lcd.clear() #清除LCD
lcd.move_to(0,1) #移動到LCD的第二排一位
lcd.putstr("Under Detection")#顯示沒偵測到
time.sleep(1) #延遲1秒
lcd.clear() #清除LCD
lcd.move_to(0,0) #移動到LCD的第一排一位
lcd.putstr("Left:"+str(sr04.distance())+"cm") #顯示左邊超音波的距離
lcd.move_to(0,1) #移動到LCD的第二排一位
lcd.putstr("Right:"+str(sr05.distance())+"cm") #顯示右邊超音波的距離
client.connect() #連線
credentials = bytes("channels/{:s}/publish".format(THINGSPEAK_CHANNEL_ID), 'utf-8') #設定MQTT發布的channel
payload = bytes("field1={:.1f}&field2={:.1f}&field3={:.1f}\n".format(sr04.distance(),sr05.distance(),0), 'utf-8') #把發布內容打包,數值抓到小數點後一位
client.publish(credentials, payload) #把資料發出去
except Exception as e:
print(e.args[0])
time.sleep(5)
except KeyboardInterrupt:
print('Program stopped!')