Telegram Control

ICT 360: Introduction to IoT

Mr. Seng Theara

Let's wake up

Your brain needs this 🧠

Content 

Content 

  • PINs of ESP32 

  • Understand how a relay works

  • Read temperature & humidity using DHT11

  • Control devices using ESP32 + MicroPython

  • Control hardware remotely using Telegram Bot

PINs of ESP32

Expansion Board or External Shield

PINs of ESP32

Expansion Board or External Shield

Signal

Signal

Vcc/5V

Vcc/5V

GND

GND

PINs of ESP32

Expansion Board or External Shield

Signal

Signal

Vcc/5V

Vcc/5V

GND

GND

Function of Relay

Function of Relay

DC- 

DC+

Signal Trigger

GND

Vcc

If LOW

-> Common connect to Normally Close

If HIGH

-> Common connect to 

Normally Open

Function of Relay

DC- 

DC+

Signal Trigger

GND

Vcc

If LOW

-> Common connect to Normally Close

If HIGH

-> Common connect to 

Normally Open

Function of Relay

DC- 

DC+

Signal Trigger

GND

Vcc

If LOW

-> Common connect to Normally Close

If HIGH

-> Common connect to 

Normally Open

Testing with Relay

IN

DC-

DC+

D15

GND

Vcc

IN

DC-

DC+

from machine import Pin
import time

# Initialize relay pin (GPIO15 / D15)
relay = Pin(15, Pin.OUT)

print("Relay control started...")

while True:
    # Turn relay ON
    relay.value(1)
    print("Relay ON")
    time.sleep(2)

    # Turn relay OFF
    relay.value(0)
    print("Relay OFF")
    time.sleep(2)

Testing with Relay

IN

DC-

DC+

D15

GND

Vcc

IN

DC-

DC+

from machine import Pin
import time

# Initialize relay pin (GPIO15 / D15)
relay = Pin(15, Pin.OUT)

print("Relay control started...")

while True:
    # Turn relay ON
    relay.value(1)
    print("Relay ON")
    time.sleep(2)

    # Turn relay OFF
    relay.value(0)
    print("Relay OFF")
    time.sleep(2)

DHT11 Sensor

DHT11 Sensor

How to read data from the DHT11

DHT11 Measures

  • 🌡 Temperature (°C)

  • 💧 Humidity (%)

DHT11 Sensor Reading

D33

GND

Vcc

DHT11 Sensor Reading

D33

GND

Vcc

from machine import Pin
import dht
import time

sensor = dht.DHT11(Pin(33))

print("DHT11 Sensor Reading Started...")

while True:
    try:
        sensor.measure() 
        
        temperature = sensor.temperature()  # °C
        humidity = sensor.humidity()        # %
        
        print("Temperature: {} °C".format(temperature))
        print("Humidity: {} %".format(humidity))
        print("---------------------------")
        
    except OSError:
        print("Failed to read from DHT11 sensor")

    time.sleep(2)  # DHT11 needs at least 1 second delay

And then...

Getting everyone aligned

And...

And then...

wiring everything together...

Telegram Bot

Telegram Bot

A Telegram Bot is a program  that can:

  • Receive messages

  • Send messages

  • Respond to commands

  • Control hardware (via ESP32, Raspberry Pi, server, etc.)

I've been around.

And I've got opinions...

Key Components of a Telegram Bot

Key Components of a Telegram Bot

1️⃣ Bot Account

  • Created using BotFather

  • Gets a BOT TOKEN

  • Token = password for your bot

 

3️⃣ Telegram Bot API

       Telegram provides an HTTP-based API:

  • ESP32 sends requests
  • Telegram responds with messages

2️⃣ Chat ID

  • Needed so ESP32 knows where to send messages

Create a Telegram Bot

  • Open Telegram

  • Search @BotFather

with tick

  • Send /newbot

This is your Token. Never share this publicly

Get your chat ID

  • Search for IDBot
  • Send /getid

This is your chatid

Telegram Bot API

  • Get new messages

getUpdates

  • Full URL Example

 

 

https://api.telegram.org/bot<BOT_TOKEN>/getUpdates

  • Used for

Reading commands (/on, /off, /temp)

  • Send message

                sendMessage

https://api.telegram.org/bot<BOT_TOKEN>/sendMessage

  • Used for

- Replying to user

- Sending sensor data

  •  Full URL Example

Telegram Bot Control LED

Telegram Bot Control LED

import network
import urequests
import time
from machine import Pin

# -------- SETTINGS --------
SSID = "YOUR_WIFI_NAME"
PASSWORD = "YOUR_WIFI_PASSWORD"

BOT_TOKEN = "YOUR_BOT_TOKEN"
CHAT_ID = "YOUR_CHAT_ID"

# -------- LED --------
led = Pin(2, Pin.OUT)
led.value(0)

# -------- WIFI --------
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(SSID, PASSWORD)

while not wifi.isconnected():
    time.sleep(1)

print("WiFi connected")

# -------- TELEGRAM --------
URL = "https://api.telegram.org/bot{}/getUpdates".format(BOT_TOKEN)
last_id = 0

# -------- MAIN LOOP --------
while True:
    try:
        r = urequests.get(URL + "?offset={}".format(last_id + 1))
        messages = r.json()["result"]
        r.close()

        for msg in messages:
            last_id = msg["update_id"]
            text = msg["message"]["text"]
            chat_id = msg["message"]["chat"]["id"]

            if str(chat_id) == CHAT_ID:
                if text == "/on":
                    led.value(1)

                elif text == "/off":
                    led.value(0)

    except:
        pass

    time.sleep(2)

Flowchart

Code

Telegram Bot Reading Temp & Humidity

import network
import urequests
import time
from machine import Pin
import dht

# ---------- WIFI ----------
SSID = "YOUR_WIFI_NAME"
PASSWORD = "YOUR_WIFI_PASSWORD"

# ---------- TELEGRAM ----------
BOT_TOKEN = "YOUR_BOT_TOKEN"
CHAT_ID = "YOUR_CHAT_ID"

URL_SEND = "https://api.telegram.org/bot{}/sendMessage".format(BOT_TOKEN)

# ---------- DHT11 ----------
sensor = dht.DHT11(Pin(33))

# ---------- WIFI CONNECT ----------
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(SSID, PASSWORD)

print("Connecting to WiFi...")
while not wifi.isconnected():
    time.sleep(1)

print("WiFi connected")

# ---------- MAIN LOOP ----------
while True:
    try:
        sensor.measure()
        temp = sensor.temperature()
        hum = sensor.humidity()

        message = "Temperature: {} °C\n Humidity: {} %".format(temp, hum)

        urequests.post(URL_SEND, json={
            "chat_id": CHAT_ID,
            "text": message
        })

        print("Sent:", message)

    except Exception as e:
        print("Error:", e)

    time.sleep(10)   # send every 10 seconds (change if needed)

Flowchart

Code

Thank you!