import network
import urequests as requests
import utime
from machine import Pin, PWM
# Налаштування Wi-Fi для Wokwi
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
# Налаштування Telegram (Вставте свій токен!)
BOT_TOKEN = "ВАШ_ТЕЛЕГРАМ_ТОКЕН_ТУТ"
URL = f"https://api.telegram.org/bot{BOT_TOKEN}/"
# Периферія
buzzer = PWM(Pin(26))
buzzer.duty(0)
led = Pin(2, Pin.OUT)
# Частоти нот (До-Ре-Мі...)
C4=262; D4=294; E4=330; F4=349; G4=392; A4=440; B4=494; C5=523
def play_note(freq, duration):
if freq == 0:
buzzer.duty(0)
else:
buzzer.duty(512)
buzzer.freq(freq)
led.value(1)
utime.sleep_ms(duration)
buzzer.duty(0)
led.value(0)
utime.sleep_ms(30)
# Мелодія 1: Маленькій ялинці холодно взимку (початок)
def play_melody_1():
notes = [G4, E4, E4, G4, E4, E4, G4, F4, E4, D4, C4]
durations = [300, 300, 400, 300, 300, 400, 200, 200, 200, 200, 600]
for n, d in zip(notes, durations):
play_note(n, d)
# Мелодія 2: Звук Імперського маршу (Зоряні війни)
def play_melody_2():
notes = [A4, A4, A4, F4, C5, A4, F4, C5, A4]
durations = [350, 350, 350, 250, 150, 350, 250, 150, 500]
for n, d in zip(notes, durations):
play_note(n, d)
# Звук тривоги (Сирена)
def play_siren():
for _ in range(3):
for f in range(400, 1000, 20): play_note(f, 10)
for f in range(1000, 400, -20): play_note(f, 10)
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
print("Підключення до Wi-Fi...", end="")
while not wlan.isconnected():
utime.sleep(0.5)
print(".", end="")
print("\nWi-Fi підключено!")
def send_message(chat_id, text):
try:
requests.get(f"{URL}sendMessage?chat_id={chat_id}&text={text}")
except:
pass
def check_messages(last_update_id):
try:
# Запит нових повідомлень
response = requests.get(f"{URL}getUpdates?offset={last_update_id + 1}&timeout=1")
data = response.json()
response.close()
if "result" in data and len(data["result"]) > 0:
for update in data["result"]:
last_update_id = update["update_id"]
if "message" in update and "text" in update["message"]:
text = update["message"]["text"]
chat_id = update["message"]["chat_id"]
user_name = update["message"]["from"].get("first_name", "Користувач")
print(f"Отримано команду від {user_name}: {text}")
if text == "/start":
msg = "Привіт! Я музичний бот ESP32. Обери команду:\\n/melody1 - Ялинка\\n/melody2 - Марш\\n/siren - Сирена"
send_message(chat_id, msg)
elif text == "/melody1":
send_message(chat_id, "🎵 Граю мелодію 'Ялинка'...")
play_melody_1()
elif text == "/melody2":
send_message(chat_id, "🚀 Граю 'Імперський марш'...")
play_melody_2()
elif text == "/siren":
send_message(chat_id, "🚨 Вмикаю сирену!")
play_siren()
else:
send_message(chat_id, "🤷 Невідома команда. Надішліть /start для меню.")
return last_update_id
except Exception as e:
print("Помилка запиту до Telegram:", e)
return last_update_id
# Основний цикл програми
connect_wifi()
last_update_id = 0
print("Бот запущено. Очікування команд у Telegram...")
while True:
last_update_id = check_messages(last_update_id)
utime.sleep(1) # Перевірка нових повідомлень щосекунди