# ============================================================
# File: main_system.py
# Board: Raspberry Pi Pico (MicroPython)
# Purpose: Full integration for 3.3 - reads occupancy,
# temperature and light level, then displays all
# three on the 16x2 I2C LCD, updating continuously.
# Requires lcd_api.py and pico_i2c_lcd.py (standard
# community I2C LCD driver files) saved on the Pico.
# Wiring: PIR OUT -> GP16
# LED -> GP15 (+330ohm resistor)
# Thermistor -> GP26 / ADC0
# Photoresistor-> GP27 / ADC1
# LCD SDA -> GP4
# LCD SCL -> GP5
# ============================================================
from machine import Pin, ADC, I2C
from pico_i2c_lcd import I2cLcd
import time
import math
# --- Pin setup ---
pir = Pin(16, Pin.IN)
led = Pin(15, Pin.OUT)
thermistor_adc = ADC(Pin(26))
ldr_adc = ADC(Pin(27))
# --- LCD setup (I2C0 on GP4/GP5, default PCF8574 address 0x27) ---
i2c = I2C(0, sda=Pin(4), scl=Pin(5), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
# --- Thermistor conversion constants ---
SERIES_RESISTOR = 10000.0
NOMINAL_RESISTANCE = 10000.0
NOMINAL_TEMP = 25.0
B_COEFFICIENT = 3950.0
def read_temperature():
raw = thermistor_adc.read_u16()
ratio = raw / 65535.0
if ratio <= 0.0 or ratio >= 1.0:
return 0.0
resistance = SERIES_RESISTOR * (1.0 / ratio - 1.0)
steinhart = math.log(resistance / NOMINAL_RESISTANCE)
steinhart /= B_COEFFICIENT
steinhart += 1.0 / (NOMINAL_TEMP + 273.15)
return round((1.0 / steinhart) - 273.15, 1)
def read_light_level():
raw = ldr_adc.read_u16()
return round((raw / 65535.0) * 100, 1)
print("Smart Campus Monitor running...")
while True:
occupied = pir.value() == 1
led.value(1 if occupied else 0)
temperature = read_temperature()
light = read_light_level()
# --- Update LCD: line 1 = temperature + occupancy, line 2 = light ---
lcd.clear()
lcd.putstr("T:{}C {}".format(temperature, "OCC" if occupied else "EMPTY"))
lcd.move_to(0, 1)
lcd.putstr("Light: {}%".format(light))
# --- Also log to the console/serial for a historical record ---
print(time.time(), "| Temp:", temperature, "| Light:", light, "| Occupied:", occupied)
time.sleep(2)