from machine import Pin, ADC, I2C, SoftI2C
from ssd1306 import SSD1306_I2C
import onewire, ds18x20
import time
# Initialize I2C for OLED
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled = SSD1306_I2C(128, 64, i2c) # 128x64 OLED Display
# Initialize DS18B20 temperature sensor
# Using GPIO 4 for DS18B20 DATA pin
ds_pin = Pin(4)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
# Scan for DS18B20 devices
ds_roms = ds_sensor.scan()
if not ds_roms:
raise RuntimeError('No DS18B20 found!')
# Initialize light sensor
# Using GPIO 36 (ADC1_CH0) for analog reading (A0)
light_sensor_analog = ADC(Pin(36))
light_sensor_analog.atten(ADC.ATTN_11DB) # Full range: 3.3v
# Using GPIO 35 for digital reading (D0)
light_sensor_digital = Pin(35, Pin.IN)
# Initialize ADC for microphone
# Using GPIO 39 (ADC1_CH3)
mic = ADC(Pin(39))
mic.atten(ADC.ATTN_11DB)
def get_sound_level():
# Take multiple samples to get a more stable reading
samples = 100
sound_level = 0
for _ in range(samples):
sound_level += mic.read()
return sound_level // samples
def get_light_level():
# Get analog reading and convert to percentage
raw = light_sensor_analog.read()
analog_value = int((raw / 4095) * 100)
# Get digital reading (0 = bright, 1 = dark)
digital_value = light_sensor_digital.value()
return analog_value, digital_value
def display_data(temp, light_data, sound):
oled.fill(0) # Clear the display
# Display Temperature
oled.text("Temp: {:.2f}C".format(temp), 0, 0)
# Display Light Level
light_analog, light_digital = light_data
oled.text("Light: {}%".format(light_analog), 0, 16)
oled.text("Status: {}".format("Dark" if light_digital else "Bright"), 0, 32)
# Display Sound Level
oled.text("Sound: {}".format(sound), 0, 48)
oled.show()
def main():
while True:
try:
# Read temperature from DS18B20
ds_sensor.convert_temp() # Start temperature conversion
time.sleep_ms(750) # Wait for conversion to complete
temperature = ds_sensor.read_temp(ds_roms[0]) # Read temperature
# Read light level
light_level = get_light_level()
# Read sound level
sound_level = get_sound_level()
# Update display
display_data(temperature, light_level, sound_level)
# Wait before next reading
time.sleep(1)
except Exception as e:
print("Error:", e)
time.sleep(2)
if __name__ == "__main__":
main()