import machine
import ssd1306
import time
import bme280 # Ensure the bme280.py file is uploaded to the ESP32
# I2C configuration
i2c = machine.SoftI2C(scl=machine.Pin(22), sda=machine.Pin(21))
# Scan for I2C devices
devices = i2c.scan()
# Assuming the OLED address is found at 0x3C (default for many SSD1306 displays)
oled_addr = 0x3C
# Configure the OLED SSD1306 module
oled = ssd1306.SSD1306_I2C(128, 64, i2c, addr=oled_addr) # Adjust the address if needed
# Create a BME280 object
bme = bme280.BME280(i2c=i2c)
# Configure the LED pins
red_led = machine.Pin(15, machine.Pin.OUT)
yellow_led = machine.Pin(14, machine.Pin.OUT)
green_led = machine.Pin(13, machine.Pin.OUT)
blue_led = machine.Pin(12, machine.Pin.OUT)
def classify_weather(temperature):
"""Classify weather based on temperature and control LEDs."""
if temperature < 10:
red_led.off()
yellow_led.off()
green_led.off()
blue_led.on()
return "Cold"
elif 10 <= temperature < 20:
red_led.off()
yellow_led.off()
green_led.on()
blue_led.off()
return "Cool"
elif 20 <= temperature < 30:
red_led.off()
yellow_led.on()
green_led.off()
blue_led.off()
return "Warm"
else:
red_led.on()
yellow_led.off()
green_led.off()
blue_led.off()
return "Hot"
while True:
try:
# Read the temperature, pressure, and humidity from the BME280 sensor
temperature, pressure, humidity = bme.read_compensated_data()
# Convert temperature to Celsius
temperature /= 100
# Convert pressure to hPa
pressure /= 100
# Convert humidity to percentage
humidity /= 1024
# Classify the weather based on the temperature and control LEDs
weather_classification = classify_weather(temperature)
# Clear the OLED screen
oled.fill(0)
# Display the temperature, humidity, pressure, and weather classification on the OLED
oled.text("Temp:", 0, 0)
oled.text(f"{temperature:.1f} C", 40, 0)
oled.text("Hum:", 0, 16)
oled.text(f"{humidity:.1f} %", 34, 16)
oled.text("Pres:", 0, 32)
oled.text(f"{pressure:.0f} hPa", 40, 32)
oled.text("Weather:", 0, 48)
oled.text(weather_classification, 64, 48)
# Update the OLED display
oled.show()
# Print the results to the terminal
print("-----------------------------------")
print(f"Temperature: {temperature:.1f} C")
print(f"Humidity: {humidity:.1f} %")
print(f"Pressure: {pressure:.0f} hPa")
print(f"Weather Classification: {weather_classification}")
print("-----------------------------------")
# Wait for a while before the next measurement
time.sleep(2)
except Exception as e:
print("Error:", e)
# Wait for a while before retrying
time.sleep(2)