import machine
from machine import Pin, ADC
from math import log
import network
import time
import urequests
# LCD Setup
rs = Pin(27, Pin.OUT)
en = Pin(26, Pin.OUT)
d4 = Pin(25, Pin.OUT)
d5 = Pin(33, Pin.OUT)
d6 = Pin(32, Pin.OUT) # Assuming it's D32
d7 = Pin(34, Pin.OUT)
lcd = LCD(rs, en, d4, d5, d6, d7)
# Motion Sensor Setup
motion_sensor = Pin(18, Pin.IN)
# Built-in LED Setup
led_builtin = Pin(2, Pin.OUT)
# ADC Setup
adc = ADC(Pin(15)) # ADC1, Channel 0 (Pin 15)
def calculate_temperature(ntc_value):
ntc_resistance = 10000.0 * (1023.0 / ntc_value - 1.0)
steinhart = ntc_resistance / 10000.0
steinhart = log(steinhart)
steinhart /= 3950.0
steinhart += 1.0 / (25.0 + 273.15)
kelvin = 1.0 / steinhart
celsius = kelvin - 273.15
return celsius
# Firebase configuration
FIREBASE_URL = "https://your-firebase-url.firebaseio.com"
FIREBASE_SECRET = "your-firebase-secret"
def connect_to_wifi():
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '') # Replace with your WiFi SSID and password
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
def send_data_to_firebase(data):
url = "{}/data.json?auth={}".format(FIREBASE_URL, FIREBASE_SECRET)
headers = {"Content-Type": "application/json"}
response = urequests.put(url, json=data, headers=headers)
print("Firebase Response:", response.text)
response.close()
def main():
connect_to_wifi()
baseline_temp = 0
celsius = 0
lcd.init()
lcd.clear()
while True:
# Read motion sensor state
sensor_state = motion_sensor.value()
# Set threshold temperature to activate LEDs
baseline_temp = 40
# Read analog value from NTC thermistor
ntc_value = adc.read()
# Calculate temperature
celsius = calculate_temperature(ntc_value)
lcd.clear()
# Check if the motion sensor is triggered
if sensor_state == 1:
lcd.set_cursor(0, 0)
lcd.print("Door: Open ")
led_builtin.value(1) # Turn on the light
else:
lcd.set_cursor(0, 0)
lcd.print("Door: Closed ")
led_builtin.value(0) # Turn off the light
# Display temperature on LCD
lcd.set_cursor(0, 1)
lcd.print("Temp: {:.2f} C".format(celsius))
# Log temperature
print("Temperature: {:.2f} C".format(celsius))
# Control LEDs based on temperature
if celsius < baseline_temp:
lcd.set_cursor(0, 1)
lcd.print("Fan: OFF ")
elif baseline_temp <= celsius < 75:
lcd.set_cursor(0, 1)
lcd.print("Fan: ON ")
else: # celsius >= 75
lcd.set_cursor(0, 1)
lcd.print("Detected Fire ")
utime.sleep_ms(1000) # Add a delay to prevent rapid LCD updates
# Prepare data to send to Firebase
firebase_data = {
"temperature": celsius,
"motion": "Open" if sensor_state == 1 else "Closed"
}
# Send data to Firebase
send_data_to_firebase(firebase_data)
if __name__ == "__main__":
main()