import time
import sys
from machine import Pin, SoftI2C, PWM
from i2c_lcd import I2cLcd
import network
import urequests
# Define pins for ultrasonic sensor
trig_pin = Pin(16, Pin.OUT)
echo_pin = Pin(17, Pin.IN)
# Define pins for IR sensor
ir_pin = Pin(14, Pin.IN)
# Define I2C LCD parameters
I2C_ADDR = 0x27
totalRows = 4
totalColumns = 20
# WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# Define pin for buzzer
buzzer_pin = Pin(4, Pin.OUT)
buzzer_pwm = PWM(buzzer_pin)
buzzer_pwm.freq(500) # Set PWM frequency
# Initialize I2C communication for LCD
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000)
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
# Function to connect to WiFi
def connect_wifi():
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
wifi.connect(WIFI_SSID, WIFI_PASSWORD)
if not wifi.isconnected():
print('Connecting to WiFi...')
timeout = 0
while not wifi.isconnected() and timeout < 10:
print(10 - timeout)
timeout += 1
time.sleep(1)
if wifi.isconnected():
print('Connected to WiFi')
else:
print('Failed to connect to WiFi')
sys.exit()
print('Network config:', wifi.ifconfig())
# Connecting to WiFi Router
connect_wifi()
# ThingSpeak parameters
HTTP_HEADERS = {'Content-Type': 'application/json'}
THINGSPEAK_WRITE_API_KEY = 'JT8RALN0OLL0XBPC' # Write API of the Channel
# Function to measure distance using ultrasonic sensor
def measure_distance():
trig_pin.value(1) # Send a 10us pulse to trigger the ultrasonic sensor
time.sleep_us(10)
trig_pin.value(0)
while echo_pin.value() == 0: # Wait for echo pin to go high and then low
pulse_start = time.ticks_us()
while echo_pin.value() == 1:
pulse_end = time.ticks_us()
pulse_duration = time.ticks_diff(pulse_end, pulse_start) # Calculate duration of echo pulse
# Convert pulse duration to distance in centimeters
distance = pulse_duration * 0.034 / 2
return distance
# Function to detect object using IR sensor
def detect_fire():
return ir_pin.value()
# Function to activate the buzzer
def activate_buzzer():
buzzer_pwm.duty(512) # 50% duty cycle
# Function to deactivate the buzzer
def deactivate_buzzer():
buzzer_pwm.duty(0) # Turn off the buzzer
# Main loop
while True:
try:
distance = measure_distance()
ir_state = detect_fire()
print("Distance:", distance, "cm")
lcd.clear()
lcd.move_to(0,0)
if ir_state:
lcd.putstr('Fire detected')
print("Fire detected")
else:
lcd.putstr('Distance:'+ str(distance)+"cm")
dht_readings = {'field1': distance, 'field2': ir_state}
request = urequests.post('http://api.thingspeak.com/update?api_key=' + THINGSPEAK_WRITE_API_KEY, json=dht_readings, headers=HTTP_HEADERS)
request.close()
if distance < 100 or ir_state: # If an object is closer than 100cm or IR sensor detects an object
activate_buzzer()
else:
deactivate_buzzer()
time.sleep(0.1) # Wait for a short time before next measurement
except OSError as e:
print('Failed to read sensor.')