"""
MicroPython IoT Weather Station Example for Wokwi.com
To view the data:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"
Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
from machine import Pin, PWM, ADC
import time
import network
import ujson
from umqtt.robust import MQTTClient
sta=network.WLAN(network.STA_IF)
sta.active(True)
sta.connect('Wokwi-GUEST','')
while not sta.isconnected() :
pass
print('Wifi連線成功')
LED=Pin(14,Pin.OUT)
LED2=Pin(12,Pin.OUT)
SW=Pin(26,Pin.IN)
mqtt_client_id = 'FACTORY'
CHT_URL='iot.cht.com.tw'
CHT_USERNAME = 'DKPE9TUMB95FTSEK4C'
CHT_IO_KEY = 'DKPE9TUMB95FTSEK4C'
client = MQTTClient(client_id=mqtt_client_id,
server=CHT_URL,
user=CHT_USERNAME,
password=CHT_IO_KEY)
j=0
i=0
b=0
a=0
while True:
client.connect()
f=open('sw.txt','w')
while True:
print("開始")
time.sleep(5)
val=SW.value()
if val==a :
print("沒按")
elif val%2==1 :
print("開")
i =i+1
print("Alert! SW Touched!")
for b in range (1,6):
print("亮:",b,"次")
LED.on()
LED2.on()
time.sleep(1)
LED.off()
LED2.off()
time.sleep(1)
else:
print("關")
i =i+1
print("Alert Disable!")
for b in range (1,3):
print("亮:",b,"次")
LED.on()
LED2.on()
time.sleep(1)
LED.off()
LED2.off()
time.sleep(1)
print("按開關次數"+str(i))
payload=[{"id":"SW","value":[val]}]
client.publish(
b'/v1/device/35006634958/rawdata',str(payload).encode()
)
j=j+1
a = val
print('第'+str(j)+'筆資料'+'publish finish')
f.write(str(val))
break
f.close()
client.disconnect()