from machine import Pin, PWM
import utime
# Pin definition
relay1_pin = 14
relay2_pin = 15
lpg_detector_pin = 12
fire_detector_pin = 13
trigger_pin = 10
echo_pin = 11
led_pin = 16
# GPIO pins setup
relay1 = Pin(relay1_pin, Pin.OUT)
relay2 = Pin(relay2_pin, Pin.OUT)
lpg_detector = Pin(lpg_detector_pin, Pin.IN)
fire_detector = Pin(fire_detector_pin, Pin.IN)
trigger = Pin(trigger_pin, Pin.OUT)
echo = Pin(echo_pin, Pin.IN)
red_led = Pin(led_pin, Pin.OUT)
# Sound an alarm (using a PWM pin for now, connect to a buzzer)
alarm = PWM(Pin(2))
def sound_alarm(frequency):
alarm.freq(frequency) # 1kHz frequency
alarm.duty_u16(512) # 50% duty cycle
def stop_alarm(): # Stop the alarm
alarm.deinit()
def read_distance():
# this function will read distance from distance sensor
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(5)
trigger.low()
while echo.value() == 0:# Wait until we get sound back on echo pin
pass
start = utime.ticks_us() # note down current receiving time
while echo.value() == 1: # Wait until we are getting sound signal back
pass
end = utime.ticks_us() # note down the time
distance = (end - start) / 2 / 29.1 # Calculate distance in cm
return distance
while True:
# Relay Control
relay1.high() # turn on relay
relay2.low() # turn off relay
utime.sleep(1)
relay1.low() # turn off relay
relay2.high() # turn on relay
utime.sleep(1)
# LPG & Fire Detection if signal is high
if lpg_detector.value():
sound_alarm(420)
elif fire_detector.value():
sound_alarm(840)
else:
stop_alarm()
# Distance Sensor Check
print("Distance:", read_distance())
if read_distance() < 50: # if anything gets in this distance turn on red led
red_led.high()
else:
red_led.low()
utime.sleep(0.1)