ESP8266 Projects

Switch the light on and off with Telegram

Switch on light with Telegram

In this project you will learn how to switch a light source on and off from your smartphone. You can also use it to check whether the light is on or off.

For a first test, use an LED connected to your ESP8266. If you want to do this later – and provided you feel comfortable with it – you can turn to a “real” lamp. For this, you need a relay that you control via telegram, which in turn opens and closes the circuit of the lamp.

This project is the fourth part of a series and builds on the previous projects. In this article you will find everything about the setup and the appropriate sketch, but we will not discuss all parts of the code. If you want to know more details, please have a look at the following projects:

  1. A silent alarm with Telegram and an ESP8266
  2. Monitor the temperature with Telegram and an ESP8266
  3. Request the current temperature by Telegram

If you have not yet created a project with Telegram, first learn how to create a Telegram bot.

Beginner

1 – 2 hours

ca. $10

For this project you need (quantities see description):

The set up of the project

For this project you need your ESP8266, an LED with resistor (e.g. 220 Ohm), a breadboard and wires. Use the following schematic for orientation:

Set up LED control

As you can see above, you connect the anode (long leg) of the LED to pin D5 on your ESP8266. The cathode (short leg) is connected to GND via a resistor.

The sketch

Copy the following sketch into your Arduino IDE, complete your data and load it onto your ESP8266

View Sketch as .txt

/*
   Switch the light on and off with Telegram - polluxlabs.net
*/

//Libraries
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>

// WiFi Credentials
const char* ssid = "NETWORK";
const char* password = "PASSWORD";

// Initialize Telegram-Bot
#define botToken "TOKEN"  // Bot-Token from Botfather)

//Your User-ID
#define userID "USERID"

WiFiClientSecure client;
UniversalTelegramBot bot(botToken, client);

//Variable for the ligth
const int lightPin = 14; //At ESP8266 Pin D5
bool lightState = LOW;

//Variable for number of requests
int numNewRequests;

//Variable for the text
String text = "";

//User-ID of Sender
String chat_id = "";

//Name of Sender
String from_name = "";

//Variable for Welcome Message
String welcome = "";

//Handling requests
void handleNewRequests(int numNewRequests) {

  for (int i = 0; i < numNewRequests; i++) { //loops through requests

    //Checks if you've made the request
    chat_id = String(bot.messages[i].chat_id);
    if (chat_id != userID) {
      bot.sendMessage(chat_id, "You are not authorized!", "");
      continue;
    }

    // Save request text
    text = bot.messages[i].text;
    Serial.println(text);

    from_name = bot.messages[i].from_name;

    if (text == "/start") {
      welcome = "Willkommen, " + from_name + ".\n";
      welcome += "Use these commands: \n\n";
      welcome += "/lichtEin \n";
      welcome += "/lichtAus \n";
      welcome += "/status \n";
      bot.sendMessage(chat_id, "http://gph.is/1Rc70ke", "");
      bot.sendMessage(chat_id, welcome, "");
    }

    if (text == "/lichtEin") {
      lightState = HIGH;
      digitalWrite(14, lightState);
      bot.sendMessage(chat_id, "The light is on.", "");
    }

    if (text == "/lichtAus") {
      lightState = LOW;
      digitalWrite(14, lightState);
      bot.sendMessage(chat_id, "The light is off.", "");
    }

    if (text == "/status") {
      if (digitalRead(lightPin)) {
      bot.sendMessage(chat_id, "The light is on.", "");
      }
      else {
        bot.sendMessage(chat_id, "The light is off.", "");
      }
    }
  }
}

void setup() {

  Serial.begin(115200);
  client.setInsecure();

  pinMode(lightPin, OUTPUT);
  digitalWrite(lightPin, lightState);

  //Verbindung zum WLAN
  Serial.print("Verbinde mich mit: ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(300);
  }
  Serial.println("");
  Serial.println("Connected!");
}

void loop() {

  //check if there are new requests
  int numNewRequests = bot.getUpdates(bot.last_message_received + 1);

  while (numNewRequests) { //executed if numNewRequests == 1
    Serial.println("Request received");
    handleNewRequests(numNewRequests);
    numNewRequests = bot.getUpdates(bot.last_message_received + 1);
  }
  delay(1000);
}

What is new in this sketch?

You don’t have to change much in your code to switch the light on and off instead of the temperature query. Let’s have a look at the details.

First you need a constant for the pin to which the LED is connected and a variable for the state of the LED – whether it is on or off.

const int lightPin = 14;
bool lightState = LOW;

In the setup function you set the pinMode for the LED pin and assign the LED the state which is in the variablelightState – i.e. LOW at the beginning.

pinMode(lightPin, OUTPUT);
digitalWrite(lightPin, lightState);

The function handleNewRequests()

You already know this function from the previous project. Here your requests are processed, which you send from your smartphone.

Switch on light with Telegram
You can also use GIFs, just send the corresponding URL. There is already one in the sketch above.

In this project there are three requests (or commands) that you can send: /lightOn, /lightOff and /status. With the last prompt you request whether the LED is currently on or off and get the corresponding answer back.

So if you send the text /lightOn to your ESP8266, it sets the variable lightState to HIGH and switches the LED on with digitalWrite(). Finally, it sends you feedback using the well-known function bot.sendMessage().

if (text == "/lichtEin") {
  lightState = HIGH;
  digitalWrite(14, lightState);
  bot.sendMessage(chat_id, "The light is on.", "");
}

The /lightOff command works similarly, except that it turns off the LED, of course. When you send /status, your ESP8266 checks whether the LED is on or off:

if (text == "/status") {
  if (digitalRead(lightPin)) {
  bot.sendMessage(chat_id, "The light is on.", "");
  }
  else {
    bot.sendMessage(chat_id, "The light is off.", "");
  }
}

What’s next?

As mentioned in the beginning, you can control a relay instead of the LED. Depending on the signal you send to it from your smartphone, it will open and close the circuit of another device – e.g. a lamp or a coffee machine.

Letzte Aktualisierung am 2021-01-09 / Affiliate Links / Bilder von der Amazon Product Advertising API

You may also like

Comments are closed.