from machine import Pin,unique_id
import urequests as requests
import utime
import ujson
import ubinascii
import sys, os
import urandom as random
import wlan
# --- 設定區 ---
INTERVAL = 1000 # millisecond
Line_user_id = ""
# Line Developers https://developers.line.biz/
Line_access_token = ""
Line_webhook_URL = "https://api.line.me/v2/bot/message/push"
if(sys.platform=="esp8266"):
led_pin = 2 # GPIO2(D4)
buzzer_pin = 5 # GPIO5(D1)
button_pin = 4 # GPIO4(D2)
elif(sys.platform=="esp32"):
led_pin = 2
buzzer_pin = 5
button_pin = 35
elif(sys.platform=="rp2"):
led_pin = "LED"
buzzer_pin = 15
button_pin = 21
def randint(min, max):
span = max - min + 1
div = 0x3FFFFFFF // span
offset = random.getrandbits(30) // div
val = min + offset
return val
# 發送LINE訊息
def send_line_message(text):
headers = {"Content-Type": "application/json",
"Authorization": "Bearer " + Line_access_token
}
payload = {"to": Line_user_id,
"messages": [
{
"type": "text",
"text": text
}
]
}
# 先轉成 JSON 字串,再手動編碼為 utf-8 bytes
binary_data = ujson.dumps(payload).encode('utf-8')
print("Send Data:", binary_data)
try:
wlan.connect_wifi() # Connecting to WiFi Router
response = requests.post(Line_webhook_URL,
headers=headers,
data=binary_data)
print("Response Status:", response.status_code)
print("Response Text:", response.text)
response.close()
print("Send success!")
except Exception as e:
print("Error sending message:", e)
# Function to handle button press interrupt (optional)
def button_press(pin):
global button_down
button_down = True
# Start Function
if __name__ == '__main__':
print(os.uname())
print("Hello, " + os.uname().sysname + "!")
# Unique ID
CLIENT_ID = ubinascii.hexlify(unique_id())
print("Unique ID: ", end="")
print(CLIENT_ID)
# Define GPIO pins for LED and push button
led = Pin(led_pin, Pin.OUT)
led.off()
button = Pin(button_pin, Pin.IN, Pin.PULL_UP) # 按鍵接在 GPxx, Internal pull-up resistor
button_down = False
# Attach interrupt to the push button pin
button.irq(trigger=Pin.IRQ_FALLING, handler=button_press)
utime.sleep_ms(1000)
led.on()
payload = """你好!這是來自{:s}的測試訊息。""".format(os.uname().sysname)
send_line_message(payload)
led.off()
lastTime = utime.ticks_ms()
while True:
try:
currTime = utime.ticks_ms()
if (currTime - lastTime) > INTERVAL:
led.value(not led.value())
# led.toggle()
lastTime = currTime
if button_down == True:
led.on()
# 模擬溫濕度數據
temp = randint(20, 35) # 假設攝氏 20~35℃
humi = randint(40, 80) # 假設濕度 40~80%
Temp="Temp: %2d" % (temp)
Humi="Humi: %2d" % (humi)
payload = "{:s}, {:s}..".format(Temp,Humi)
send_line_message(payload)
button_down = False
led.off()
# Do other tasks while waiting for button press
utime.sleep_ms(100)
except KeyboardInterrupt: # 使用者中斷執行(通常是輸入^C)
print("Stop")
Loading
pi-pico-w
pi-pico-w
Loading
ds18b20
ds18b20