import machine
from machine import Pin , SoftI2C
import uasyncio as asyncio
import utime
import dht
import urequests as requests
import network
from hx711 import HX711
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
import ntptime
# Define the pin number where the buzzer is connected
buzzer_pin = 26
# Create a PWM object on the buzzer pin
buzzer = machine.PWM(machine.Pin(buzzer_pin))
# to display with 1602-i2c
I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000) #initializing the I2C method for ESP32
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
# Function To display Battery level
adc_pin = machine.ADC(machine.Pin(34))
raw_min = 0 # The minimum raw sensor reading
raw_max = 4095 # The maximum raw sensor reading
output_min = 0 # The desired minimum output value
output_max = 100 # The desired maximum output value
# Read the raw analog value (0-4095)
def Battery_task():
raw_value = adc_pin.read()
# Map the raw value to the desired output range
calibrated_value = (raw_value - raw_min) / (raw_max - raw_min) * (output_max - output_min) + output_min
# Print the calibrated value
print("Calibrated Value:", calibrated_value)
return calibrated_value
# Function to mesure weight
def hx711_task():
capteur_hx711 = HX711(19,18,1)
capteur_hx711.power_on()
while (capteur_hx711.is_ready()) :
pass
mesure = capteur_hx711.read(False)
print(mesure)
while (capteur_hx711.is_ready()) :
pass
mesure = capteur_hx711.read(True)
print(mesure)
#Calibration
mesure = mesure/420
return mesure
# Function of buzzer
async def buzzer_task(frequency, duration_s, state):
state=True
while state :
# Set the frequency (in Hz) of the buzzer
buzzer.freq(frequency)
# Start the buzzer with a 50% duty cycle
buzzer.duty(512)
# Wait for the specified duration
await asyncio.sleep(1)
# Turn off the buzzer
buzzer.duty(0)
await asyncio.sleep(0.5)
def hc_sr04_task():
# Define pins for trigger and echo
trigger_pin = Pin(4, Pin.OUT)
echo_pin = Pin(5, Pin.IN)
# Generate a 10us pulse on the trigger pin to start the measurement
trigger_pin.value(1)
utime.sleep_us(10)
trigger_pin.value(0)
# Measure the duration of the pulse on the echo pin
pulse_duration = 0
while echo_pin.value() == 0:
pulse_duration = utime.ticks_us()
while echo_pin.value() == 1:
pulse_duration_end = utime.ticks_us()
# Calculate duration in microseconds
pulse_duration = pulse_duration_end - pulse_duration
# Calculate distance using the speed of sound (343 m/s)
distance = (pulse_duration / 2) * 0.0343 # Divide by 2 for two-way travel
return distance
# Function of api and gps with api
def gps_ip_api_task():
response = requests.get("https://ipinfo.io")
location_data = response.json()
return location_data
# Function to read temperature and humidity from DHT22
def dht_task():
dht22 = dht.DHT22(machine.Pin(23)) # your DHT22 pin number
try:
dht22.measure()
temperature = dht22.temperature()
humidity = dht22.humidity()
print("Temperature: {}°C, Humidity: {}%".format(temperature, humidity))
return temperature,humidity
except Exception as e:
print("Error reading DHT22 sensor:", e)
# tasks just run for once time
from wifi import WifiManager
ssid , password = "Wokwi-GUEST",""
wifi=WifiManager(ssid, password)
lcd.clear()
lcd.putstr(" ASH ")
lcd.putstr(" Technologies ")
utime.sleep(2)
for i in range(3) :
lcd.hal_backlight_off()
utime.sleep(0.1)
lcd.hal_backlight_on()
utime.sleep(0.3)
lcd.clear()
lcd.putstr("Smart Frigo-Syst")
utime.sleep(1)
for i in range(16):
lcd.putstr("*")
x=(i+1)/2
utime.sleep(int(1/x))
utime.sleep(1)
print(wifi.connect(6))
lcd.clear()
lcd.putstr(wifi.connect(1))
# Funtion For Time Display
UTC_OFFSET = 3600 #change to tunisia timezonen +01 h
ntptime.settime() # Sync time with NTP server
year, month, day, hour, minute, second ,weekday,subsecond = utime.localtime(utime.time() + UTC_OFFSET)
rtc = machine.RTC()
print (utime.localtime(utime.time() + UTC_OFFSET))
rtc.datetime(( year, month, day, weekday, hour, minute, second, subsecond))
def time_task():
year, month, day, weekday, hour, minute, second, subsecond = rtc.datetime()
# Use string formatting to ensure two digits with leading zeros
formatted_hour = f"{hour:02}"
formatted_minute = f"{minute:02}"
formatted_second = f"{second:02}"
return f" {formatted_hour}:{formatted_minute}:{formatted_second} "
print (time_task())
lcd.move_to(0,1)
lcd.putstr(time_task())
while True :
temp , hum = dht_task()
utime.sleep(5)
lcd.clear()
lcd.putstr("Temp : "+str(temp)+" C")
lcd.move_to(0,1)
lcd.putstr("Humd : "+str(hum)+" %")
distance = hc_sr04_task()
utime.sleep(5)
print("Distance: {:.2f} cm".format(distance))
lcd.clear()
lcd.putstr("Distance: {:03d} Cm".format(int(distance)))
lcd.move_to(0,1)
lcd.putstr("The Door Is Open")
mesure = hx711_task()
utime.sleep(5)
lcd.clear()
lcd.putstr("W.Frigo:" + str(mesure) + " Kg")
bat = Battery_task()
utime.sleep(5)
lcd.move_to(0,1)
lcd.putstr("Battery:" + str(bat) + " %")
utime.sleep(5)