#Carlos Benito Ramirez Vazquez / GDS0641 / Unidad 1 / Evaluacion
from servo import Servo
from dht import DHT22
import math
from machine import Pin, I2C, ADC, PWM
from esp8266_i2c_lcd import I2cLcd
from time import sleep
from ssd1306 import SSD1306_I2C
RL10 = 50
GAMMA = 0.7
led1 = Pin(16, Pin.OUT)
led2 = Pin(17, Pin.OUT)
led3 = Pin(23, Pin.OUT)
bOn = Pin(19, Pin.IN, Pin.PULL_UP)
bOff = Pin(18, Pin.IN, Pin.PULL_UP)
bTwo = Pin(4, Pin.IN, Pin.PULL_UP)
I2C_ADDR = 0x27
I2C_NUM_ROWS = 4
I2C_NUM_COLS = 20
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
i2c_lcd = I2C(1, scl=Pin(33), sda=Pin(32), freq=400000)
lcd = I2cLcd(i2c_lcd, I2C_ADDR, I2C_NUM_ROWS, I2C_NUM_COLS)
sensor = DHT22(Pin(27))
oled = SSD1306_I2C(128, 64, i2c)
rgb_red = Pin(12, Pin.OUT)
rgb_green = Pin(13, Pin.OUT)
servo = Servo(Pin(15))
#Estado del led
state = False
state2 = False
ldr_pin = ADC(Pin(26))
ldr_pin.atten(ADC.ATTN_11DB)
ldr_pin.width(ADC.WIDTH_12BIT)
ledLuz = Pin(14, Pin.OUT)
#funcion para encendido y apagado del LED
def toggle(pin):
global state2
state2 = not state2
led3.value(state2)
#funcion para encender el led
def on(pin):
global state
state = True
led1.value(state)
led2.value(state)
#funcion que apaga el led
def off(pin):
global state
state = False
led1.value(state)
led2.value(state)
bOn.irq(trigger=Pin.IRQ_FALLING, handler=on)
bOff.irq(trigger=Pin.IRQ_FALLING, handler=off)
bTwo.irq(trigger=Pin.IRQ_FALLING, handler=toggle)
def semaforo_temperatura(temperatura):
if temperatura < 30:
rgb_red.value(0)
rgb_green.value(1)
else:
rgb_red.value(1)
rgb_green.value(0)
def calculate_lux(analog_value):
voltage = analog_value / 4095.0 * 3.3
resistance = 2000 * voltage / (1 - voltage / 3.3)
lux = math.pow(RL10 * 1e3 * math.pow(10, GAMMA) / resistance, (1 / GAMMA)) / 1.808
return lux
while True:
sensor.measure()
t = sensor.temperature()
h = sensor.humidity()
oled.fill(0)
oled.text("T: %3.1f grados" % t, 10, 13)
oled.text("H: %3.1f%% humedad" % h, 10, 40)
lcd.clear()
lcd.putstr("T: %3.1f grados" % t)
lcd.move_to(0, 1)
lcd.putstr("H: %3.1f%% humedad" % h)
if t > 50:
lcd.move_to(0, 2)
lcd.putstr("TEMPERATURA ALTA")
oled.text("TEMPERA ALTA", 10, 25)
else:
oled.text("", 10, 25)
oled.show()
semaforo_temperatura(t)
if t > 30:
servo.move(90)
else:
servo.move(0)
analog_value = ldr_pin.read()
lux = calculate_lux(analog_value)
print("Lux:", lux)
if lux < 1000:
ledLuz.value(1)
else:
ledLuz.value(0)
sleep(1)