# MicroPython code for DS18B20, DHT22, and I2C LCD

# Import necessary libraries
import machine
import time
import onewire, ds18x20
from machine import Pin, SoftI2C, sleep, PWM
import dht
from machine import I2C
from lcd_api import LcdApi
from i2c_lcd import I2cLcd

# Configure DS18B20 sensor
ds_pin = Pin(4)  # DS18B20 data pin (GPIO4)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
buzzer_pin = Pin(16)

roms = ds_sensor.scan()
print('Found DS devices: ', roms)

# Configure DHT22 sensor
dht_sensor = dht.DHT22(Pin(5))  # DHT22 data pin (GPIO5)

# Configure I2C LCD
I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
#initializing the I2C method for ESP32
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000)     
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
buzzer = PWM(Pin(buzzer_pin)) # Initialize PWM for the buzzer

def activate_buzzer_tone(frequency, duration, cycle):
    buzzer.freq(frequency)  # Set the frequency
    buzzer.duty(cycle)      # Set the duty cycle (50% = 512 out of 1023 for ESP32)
    time.sleep(duration)    # Keep the tone active for the duration

# Function to read temperature from DS18B20 sensor
def read_ds18b20_temp():
    roms = ds_sensor.scan()
    ds_sensor.convert_temp()
    time.sleep_ms(750)
    for rom in roms:
        return ds_sensor.read_temp(rom)

# Function to read temperature and humidity from DHT22 sensor
def read_dht22_data():
    dht_sensor.measure()
    return dht_sensor.temperature(), dht_sensor.humidity()

buzzer.duty(0)

# Main loop
while True:
    # Read temperature from DS18B20 sensor
    #ds_temp = read_ds18b20_temp()
    ds_sensor.convert_temp()
    time.sleep_ms(750)
    for rom in roms:
        print(rom)
        print(ds_sensor.read_temp(rom))

    # Read temperature and humidity from DHT22 sensor
    dht_temp, dht_humidity = read_dht22_data()

    if dht_temp >= 36.5:
        print("Temperatura Alta")
        activate_buzzer_tone(frequency=2500, duration=10, cycle=512)
    else:
        buzzer.duty(0)
    
    # Display temperature and humidity on LCD
    lcd.clear()
    #lcd.putstr("DS Temp: {:.2f}C\n".format(ds_temp))
    #time.sleep(2)
    #lcd.putstr("DHT Temp: {:.2f}C\n".format(dht_temp))
    lcd.putstr("DHTHumid:{:.2f}%".format(dht_humidity))
    
    # Wait for a while before reading again
    time.sleep(2)

Loading
ds18b20