from machine import Pin, ADC, PWM
from time import sleep
import time
import ifttt
import network
import dht
import wifi
from umqtt.simple import MQTTClient
from machine import SoftI2C
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
import thing_speak as tsp
ssid = 'Wokwi-GUEST'
password = ''
sensor = ADC(Pin(34))
pinLed = Pin(14,Pin.OUT)
humidifier = Pin(27,Pin.OUT)
sen = PWM(Pin(15, mode=Pin.OUT))
sen.freq(50)
d = dht.DHT22(Pin(12, Pin.IN))
motion = Pin(12, Pin.IN)
I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
i2c = SoftI2C(scl=Pin(22), sda=Pin(23), freq=10000)
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
lcd.putstr("Farm")
h = -1
t = -1
buzzer_pin = Pin(21, Pin.OUT)
buzzer_pwm = PWM(buzzer_pin)
def connect_internet():
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, password)
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
def thingspeak_display():
d.measure()
t = d.temperature()
h = d.humidity()
print("Update to thingspeak....")
tsp.update_temp_and_hum(t, h)
def send_email():
d.measure()
t = d.temperature()
h = d.humidity()
if(t > 35 or t < 30 or h > 65 or h < 60):
ifttt.sent_email(t,h)
print("sent email")
def send_to_sheet():
d.measure()
t = d.temperature()
h = d.humidity()
if(t > 35 or t < 30 or h > 65 or h < 60):
ifttt.send_to_sheet(t,h)
print("sent to sheet")
if __name__ == "__main__":
connect_internet()
last_thingspeak_display=time.time()
while True:
current_time= time.time()
if current_time - last_thingspeak_display >= 60:
thingspeak_display()
time.sleep(5)
send_email()
time.sleep(5)
send_to_sheet()
time.sleep(5)
last_thingspeak_display = current_time
val = sensor.read()
d.measure()
temperature = d.temperature()
humidity = d.humidity()
#mo cua
if temperature>35:
pinLed.value(0)
sen.duty(123)
time.sleep(0.5)
else: #dong cua, tat den suoi
if temperature>=30:
pinLed.value(0)
sen.duty(74)
else: #dong cua, bat den suoi
pinLed.value(1)
sen.duty(74)
if humidity<60:
#bat may tao am
humidifier.value(1)
time.sleep(0.5)
else:
#tat may tao am
humidifier.value(0)
if h != d.humidity():
h = d.humidity()
lcd.clear()
lcd.putstr("The Humidity: ")
lcd.putstr(str(h))
sleep(1)
if t != d.temperature():
t = d.temperature()
lcd.clear()
lcd.putstr("The Temperature: ")
lcd.putstr(str(t))
if (temperature>70):
buzzer_pwm.duty(10)
else:
buzzer_pwm.duty(0)
sleep(1)