from machine import I2C, Pin
from pico_i2c_lcd import I2cLcd
import time
import dht
import network
import ujson
from umqtt.simple import MQTTClient
import neopixel
# MQTT Server Parameters
MQTT_CLIENT_ID = "esp32-neopixel-timer"
MQTT_BROKER = "34.243.217.54"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "neopixel/timer"
# NeoPixel Configuration
NUM_PIXELS = 16 # Количество светодиодов в кольце
np = neopixel.NeoPixel(Pin(14), NUM_PIXELS) # Подключите к нужному пину
# Функция для сброса всех светодиодов
def reset_neopixels():
for i in range(NUM_PIXELS):
np[i] = (0, 0, 0) # Выключаем светодиоды
np.write()
# Функция для обновления светодиодов в зависимости от заданного процента
def update_neopixels(percent):
reset_neopixels() # Сбрасываем светодиоды
num_lit = int((percent / 60) * NUM_PIXELS) # Количество закрашенных ячеек
for i in range(num_lit):
np[i] = (255, 0, 0) # Зеленый цвет для закрашенных ячеек
np.write()
# Обработчик сообщений MQTT
def sub_callback(topic, msg):
print("message is: ", msg)
try:
percent = int(msg) # Преобразуем сообщение в число
print("percent is: ", percent)
if 0 <= percent <= 60:
update_neopixels(percent) # Обновляем светодиоды
countdown(percent) # Запускаем обратный таймер
else:
print("Invalid input. Please enter a number between 0 and 60.")
except ValueError:
print("Received non-numeric message.")
# Функция обратного таймера
def countdown(start_percent):
num_lit = int((start_percent / 60) * NUM_PIXELS) # Начальное количество закрашенных ячеек
for i in range(num_lit):
time.sleep(60 / NUM_PIXELS) # Ждем 4 секунду
np[num_lit - i - 1] = (0, 0, 0) # Гасим светодиод
np.write()
# Подключаемся к WiFi
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# Подключаемся к MQTT серверу
print("Connecting to MQTT server... ", end="")
print(MQTT_BROKER)
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
# Подписываемся на топик
client.set_callback(sub_callback)
client.subscribe(MQTT_TOPIC)
print("pre connect")
# Основной цикл
reset_neopixels() # Сбрасываем светодиоды при запуске
while True:
client.check_msg() # Проверяем входящие сообщения
time.sleep(1) # Пауза между проверками
tm = 0
sensor = dht.DHT22(Pin(22))
humpin = Pin(15, Pin.OUT)
tempin = Pin(17, Pin.OUT)
dht_interval = 500
hum=40
temp=40
i2c_bus = I2C(0, sda=Pin(12), scl=Pin(13), freq=400000)
i2c_address = i2c_bus.scan()[0]
lcd = I2cLcd(i2c_bus, i2c_address, 2, 16)
print("Подключение к WiFi", end="")
lcd.putstr('Connect to WIFI')
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Подключено!")
lcd.putstr(' Подклено!')
print("Поключение к серверу MQTT... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
prev_weather = ""
while True:
if time.ticks_ms()-tm>=dht_interval:
sensor.measure()
hum = sensor.humidity()
temp = sensor.temperature()
lcd.putstr("hum="+str(hum)+" ")
lcd.move_to(0, 1)
lcd.putstr("temp="+str(temp)+" ")
lcd.move_to(0, 0)
tm = time.ticks_ms()
if hum<20 or hum>60:
humpin.value(1)
else:
humpin.value(0)
if temp>45 or temp<18:
tempin.value(1)
else:
tempin.value(0)
sensor.measure()
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity(),
})
if message != prev_weather:
print(message)
client.publish(MQTT_TOPIC, message)
prev_weather = message
else:
print(message)
time.sleep(1)