vimport machine
import time
import bme280
import ssd1306
# --- Configuration ---
# I2C Pins for Raspberry Pi Pico
I2C_SDA_PIN = 0 # GP0
I2C_SCL_PIN = 1 # GP1
I2C_FREQ = 400000
# OLED Display Settings
OLED_WIDTH = 128
OLED_HEIGHT = 64
# --- Initialization ---
# Initialize I2C
try:
i2c = machine.I2C(0, sda=machine.Pin(I2C_SDA_PIN), scl=machine.Pin(I2C_SCL_PIN), freq=I2C_FREQ)
print("I2C initialized successfully")
except Exception as e:
print(f"Error initializing I2C: {e}")
# Initialize BME280 Sensor
try:
sensor = bme280.BME280(i2c=i2c)
print("BME280 sensor found")
except Exception as e:
sensor = None
print(f"BME280 sensor not found: {e}")
# Initialize OLED Display
try:
oled = ssd1306.SSD1306_I2C(OLED_WIDTH, OLED_HEIGHT, i2c)
print("OLED display initialized")
except Exception as e:
oled = None
print(f"OLED display not found: {e}")
def update_display(temp, press, hum):
if oled:
oled.fill(0)
oled.text("Weather Station", 0, 0)
oled.hline(0, 10, 128, 1)
oled.text(f"Temp: {temp:.1f} C", 0, 20)
oled.text(f"Hum: {hum:.1f} %", 0, 35)
oled.text(f"Press: {press:.1f} hPa", 0, 50)
oled.show()
def main():
print("Starting Weather Station...")
while True:
try:
if sensor:
# Read data from BME280
t, p, h = sensor.read_compensated_data()
# Print to Serial/USB
print(f"Temp: {t:.2f} C, Pressure: {p:.2f} hPa, Humidity: {h:.2f} %")
# Update OLED
update_display(t, p, h)
else:
print("Sensor not available. Retrying...")
if oled:
oled.fill(0)
oled.text("Sensor Error!", 0, 20)
oled.show()
except Exception as e:
print(f"Error reading sensor: {e}")
# Wait for 2 seconds before next reading
time.sleep(2)
if __name__ == "__main__":
main()