import machine
import ssd1306
import dht
from machine import Pin, I2C
from time import sleep
# Configura el sensor PIR y el DHT22
pir = Pin(14, Pin.IN)
dht_sensor = dht.DHT22(Pin(15))
# Configura el sensor HC-SR04
trigger = Pin(12, Pin.OUT)
echo = Pin(13, Pin.IN)
# Configura el joystick y los botones
x_pin = 34 # Conecta el eje X del joystick a GPIO 34
y_pin = 35 # Conecta el eje Y del joystick a GPIO 35
select_pin = 32 # Conecta el botón de selección a GPIO 32
confirm_pin = 33 # Conecta el botón de confirmación a GPIO 33
# Configura el ADC para leer los valores del joystick
adc_x = machine.ADC(Pin(x_pin))
adc_y = machine.ADC(Pin(y_pin))
# Configura el display OLED
i2c = I2C(scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# ... (código previo)
def read_pir():
return pir.value()
def read_dht22():
dht_sensor.measure()
return dht_sensor.temperature(), dht_sensor.humidity()
def read_hc_sr04():
trigger.value(1)
sleep(0.00001)
trigger.value(0)
while echo.value() == 0:
pulse_start = machine.time()
while echo.value() == 1:
pulse_end = machine.time()
duration = pulse_end - pulse_start
distance = (duration * 34300) / 2
return distance
def show_menu(selected_option):
oled.fill(0)
options = ["Sensor PIR", "Sensor DHT22", "Sensor HC-SR04"]
for i, option in enumerate(options):
if i == selected_option:
oled.text("* " + option, 0, i * 10)
else:
oled.text(option, 0, i * 10)
oled.show()
def read_joystick():
valuerx = adc_x.read()
valuery = adc_y.read()
if valuerx < 200:
return "left"
elif valuerx > 200:
return "right"
elif valuery < 200:
return "up"
elif valuery > 200:
return "down"
else:
return None
selected_option = 0
def show_result(result):
oled.fill(0)
oled.text("Resultado:", 0, 0)
oled.text(str(result), 0, 20)
oled.show()
selected_option = 0
while True:
show_menu(selected_option)
while True:
direction = read_joystick()
if direction == "up":
selected_option = (selected_option - 1) % 3
show_menu(selected_option)
elif direction == "down":
selected_option = (selected_option + 1) % 3
show_menu(selected_option)
elif direction == "left" or direction == "right":
break
user_choice = None
while user_choice not in ['s', 'c']:
user_choice = input("Presiona 's' para seleccionar o 'c' para cancelar: ")
if user_choice == 's':
if selected_option == 0:
result = read_pir()
elif selected_option == 1:
result = read_dht22()
elif selected_option == 2:
result = read_hc_sr04()
show_result(result)
sleep(2)
elif user_choice == 'c':
sleep(2)