import time
import machine
import dht
from machine import Pin, PWM
# Set up the temperature sensor
d = dht.DHT11(machine.Pin(4))
# Set up the ultrasonic sensor
trig = Pin(17, Pin.OUT)
echo = Pin(16, Pin.IN)
# Set up the buzzer
buzzer_pin = machine.Pin(2)
buzzer = PWM(buzzer_pin, freq=2000)
# Define the temperature range
min_temp = 20
max_temp = 30
# Define the buzzer volume range
min_distance = 30
max_distance = 100
def get_temperature():
d.measure()
return d.temperature()
def get_distance():
trig.low()
time.sleep_us(2)
trig.high()
time.sleep_us(10)
trig.low()
duration = machine.time_pulse_us(echo, 1)
distance = duration / 58
return distance
def map_range(value, low1, high1, low2, high2):
return low2 + (high2 - low2) * (value - low1) / (high1 - low1)
while True:
# Read the temperature
temp = get_temperature()
# Check if the temperature is outside the desired range
if temp < min_temp or temp > max_temp:
# Set the buzzer volume based on the distance to the nearest obstacle
distance = get_distance(10)
volume = map_range(distance, min_distance, max_distance, 0, 65535)
buzzer.duty(int(volume))
# Trigger the buzzer
buzzer.freq(1000)
time.sleep(1)
buzzer.freq(0)
time.sleep(1)
else:
# Turn off the buzzer
buzzer.duty(0)
time.sleep(1)
Loading
ds18b20
ds18b20