'''
https://wokwi.com/projects/423651135158928385
'''
from machine import Pin, I2C, unique_id
import utime
import sys, os
import ssd1306
from dht import DHT22 as DHT # 如果傳感器是 DHT11,請導入 DHT11,而不是 DHT22
# from dht import DHT11 as DHT
# define in what intervals we want to do something
INTERVAL = 2000 # do something every 2000 ms
button_down = False
TimerDone = False
oled_width = 128
oled_height = 64
currentBoard=""
I2C_FREQ = 400000
if(sys.platform=="esp8266"): # ESP8266 Pin assignment
currentBoard="esp8266"
led_pin = 2 # Initialize LED on GPIO2(D4)
# button_pin = 4 # GPIO4(D2)
I2C_SDA = 4 # GPIO4(D2)
I2C_SCL = 5 # GIPO5(D1)
# Initialize I2C
i2c = I2C(scl=Pin(I2C_SCL), sda=Pin(I2C_SDA), freq=I2C_FREQ)
elif(sys.platform=="esp32"): # ESP32 Pin assignment
machine_info = os.uname().machine.upper()
if "S3" in machine_info:
currentBoard="esp32-S3"
print("正在初始化 ESP32-S3 的腳位...")
led_pin = None # 有板載 LED 時填 GPIO 編號,例如 48;沒有就維持 None
button_pin = 0 # BOOT 鍵
OWI_PIN = 13
I2C_SDA = 5 # GPIO5
I2C_SCL = 4 # GPIO4
else:
currentBoard="esp32"
print("正在初始化傳統 ESP32 的腳位...")
led_pin = 2 # Initialize LED on GPIO2
button_pin = 35
OWI_PIN = 15
I2C_SDA = 21 # GPIO21
I2C_SCL = 22 # GPIO22
# Initialize I2C
i2c = I2C(0, scl=Pin(I2C_SCL), sda=Pin(I2C_SDA), freq=I2C_FREQ) # 初始化硬體I2C0
elif(sys.platform=="rp2"):
currentBoard="Pi-Pico"
led_pin = "LED" # Initialize LED
button_pin = 21
OWI_PIN = 22
I2C_SDA = 16 # GPIO16
I2C_SCL = 17 # GPIO17
# Initializing the I2C method for pi Pico
i2c = I2C(0, scl=Pin(I2C_SCL), sda=Pin(I2C_SDA), freq=I2C_FREQ)
def button_press(pin):
global button_down
button_down = True
# Start Function
if __name__ == "__main__":
print("Hello, " + currentBoard + "!")
# 等待一段時間,確保總線初始化
utime.sleep(0.5)
led = Pin(led_pin, Pin.OUT) if led_pin is not None else None
if led:
led.value(0)
key = Pin(button_pin, Pin.IN, Pin.PULL_UP)
key.irq(trigger=Pin.IRQ_FALLING, handler=button_press)
# 掃描 I2C 設備
devices = i2c.scan() # I2C scanning
if len(devices) != 0:
print('Number of I2C devices found=',len(devices))
for device in devices:
print("Device Hexadecimel Address= ",hex(device))
if devices.count(0x3c) > 0:
OLED_N = True
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c, addr=0x3c)
else:
OLED_N = False
else:
# raise OSError("No i2c device found!")
OLED_N = False
dht = DHT(Pin(OWI_PIN)) # Initialize the DHT sensor
utime.sleep(1) #首次啟動間隔1S讓傳感器穩定
print("--- Start measurement ---")
lastTime = 0
# Read data from the sensor every 2 seconds
try:
while not button_down:
currTime = utime.ticks_ms()
#如果延時時間過短,DHT溫濕度傳感器不工作
if utime.ticks_diff(currTime, lastTime) >= INTERVAL:
lastTime = currTime #save the current time.
# 測量溫度和濕度
dht.measure() #調用DHT類庫中測量數據的函數
temp = dht.temperature() # Gets the temperature in Celsius
humi = dht.humidity() # Gets the relative humiidity in %
if temp==None: # 打印測量結果
print("DHT傳感器檢測失敗!")
else:
print(f"Temperature: {temp}°C, Humidity: {humi}%")
# print("Temperature=%d°C Humidity=%dRH" %(temp,humi))
# print("Temperature: {:.2f}°C, humiidity: {:.2f}%".format(temp, humi))
if OLED_N == True :
# 將讀數顯示到控制台
oled.fill(0)
msg1 = f"Temp: {temp} "
msg2 = f"Humid: {humi}%"
oled.text(msg1, 10, 10)
oled.text(msg2, 10, 30)
oled.show()
if led:
led.value(0)
utime.sleep_ms(100)
except Exception as e:
print("Error occurred while reading from sensor:", str(e))
except KeyboardInterrupt: # 使用者中斷執行(通常是輸入^C)
print("Stop")
finally:
print("Exit measurement.")
Loading
ssd1306
ssd1306