Telegram Controlled Home Automation using Raspberry Pi

Telegram controlled Home Automation Project using Raspberry Pi

Home automation now becomes an essential part of IoT applications and people use their smartphone to control home appliances from anywhere over internet. There are various ways to control AC appliances with smartphone, some of them we have covered in our previous IoT Home Automation Tutorials including the Telegram controlled AC Appliances with NodeMCU. This time we will use Raspberry Pi in place of NodeMCU to control appliance through our smart phone. In this IoT project we will control an AC lamp with a text message from Telegram application using Raspberry Pi.

 

In our previous projects, we controlled Raspberry Pi GPIO with various IoT platforms, some of them are listed below:

 

Components Required

  • Raspberry Pi
  • Lamp
  • Jumper wires
  • Telegram Application

 

Circuit Diagram

Circuit diagram for this Raspberry Pi Telegram controlled Home Automation project is given below:

Raspberry Pi Home Automation with Telegram App

Also check Telegram Home Automation with ESP8266 NodeMCU.

 

Code Explanation

To build this project using Raspberry Pi and Python, we need to install two important libraries. One for Telegram and another is for using GPIO pins of Raspberry Pi. To install the libraries open the terminal and type following commands. Update the Raspberry Pi before installing libraries.

sudo apt-get update
sudo apt-get install Rpi.GPIO
sudo pip install telepot

 

Complete Python code with a working video is given at the end of this tutorial, here we are explaining few important parts of the program.

Start by importing all the necessary libraries:

import time
import RPi.GPIO as GPIO
import telepot
from telepot.loop import MessageLoop

 

GPIO pin 26 is set as output pin to change the state of the relay. Initially the relay is set at “0” state to keep the Lamp in Off state.

bulb = 26
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(bulb, GPIO.OUT)
GPIO.output(bulb, 0) 

 

A function “action” is created which is called when some message is sent to the telegram bot by the user. For each message there is some particular chat id and command so that the bot can communicate with the user. This function checks if the command received has “on” or “off” string in it. If it contains “on” then change the relay state to “1” to turn on the lamp, and if the message received has “off” in the command then change the relay state to “0” to turn off the lamp.

def action(msg):
    chat_id = msg['chat']['id']
    command = msg['text']
    print 'Received: %s' % command

    if 'on' in command:
        message = "Turned on the light"
        GPIO.output(bulb, 1)
        telegram_bot.sendMessage (chat_id, message)

    if 'off' in command:
        message = "Turned off the light"
        GPIO.output(bulb, 0)
        telegram_bot.sendMessage (chat_id, message)

 

The code given below takes the unique token number, which we got while creating the bot, to establish a connection between telegram bot and Raspberry Pi. On successful connection it prints a message to indicate that system is ready to accept the command.

telegram_bot = telepot.Bot(66****885:A*G-X**dTYdSCt******aCQPCk***SL**b4')
print (telegram_bot.getMe())
MessageLoop(telegram_bot, action).run_as_thread()
print 'Send the command to turn on or off the light...'

 

Testing the Telegram controlled Home Appliances

Make the connections as shown in the circuit diagram above. Connect the data pin of the relay to the GPIO pin 26 of the Raspberry Pi. Connect the AC powered lamp correctly with the relay.

Now create a new file with extension “.py” in the pi and copy-paste the code given at the end of the tutorial then save the newly created file. Now open the terminal of Raspberry Pi and run the file using command below command

python file_name.py

 

Make sure to change the directory where your python file is saved before executing the python code. The terminal will show you the output similar to as shown in the screenshot below.

Testing the Telegram controlled Home Appliances

 

Now the connection between Telegram bot and Raspberry Pi is established and we are ready to send the command to telegram bot to turn on or turn off the light. Try to turn on and turn off the lamp by sending text messages to telegram bot as shown in the screenshot below

Testing the Home Appliances Control with Telegram App

 

You will be able to observe the commands sent to the bot in the terminal of the Raspberry Pi.

Telegram controlled Home Automation using Raspberry Pi in action

 

Circuit Hardware for Telegram controlled Home Automation using Raspberry Pi

Find the complete program and demonstration Video below. Also check other IoT Home Automation Projects.

Code

import time
import RPi.GPIO as GPIO
import telepot
from telepot.loop import MessageLoop

bulb = 26
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

GPIO.setup(bulb, GPIO.OUT)
GPIO.output(bulb, 0) 

def action(msg):
    chat_id = msg['chat']['id']
    command = msg['text']

    print 'Received: %s' % command

    if 'on' in command:
        message = "Turned on the light"
        GPIO.output(bulb, 1)
        telegram_bot.sendMessage (chat_id, message)
    
    if 'off' in command:
        message = "Turned off the light"
        GPIO.output(bulb, 0)
        telegram_bot.sendMessage (chat_id, message)
    

telegram_bot = telepot.Bot('668923885:AAG-XHddTYdSCta8vvoiaCQPCk8toSLXpb4')
print (telegram_bot.getMe())

MessageLoop(telegram_bot, action).run_as_thread()
print 'Send the command to turn on or off the light...'

while 1:
    time.sleep(10)
 

Video

32 Comments

I enjoy you because of your own labor on this website. My aunt really likes getting into research and it's simple to grasp why. We all hear all concerning the compelling ways you produce efficient steps through this blog and as well invigorate response from people on this issue plus our own child is always being taught a great deal. Enjoy the rest of the year. You are always carrying out a terrific job.

I simply wished to appreciate you yet again. I'm not certain the things that I might have tried without the solutions contributed by you on such question. Entirely was a fearsome case for me personally, but coming across the well-written mode you handled it made me to jump for joy. Now i'm happy for this support and as well , sincerely hope you recognize what a powerful job you have been getting into instructing the rest by way of a web site. Probably you have never got to know any of us.

That is the proper blog for anybody who needs to find out about this topic. You understand a lot its virtually onerous to argue with you (not that I actually would need匟aHa). You definitely put a new spin on a topic thats been written about for years. Great stuff, simply nice!

Oh my goodness! a tremendous article dude. Thank you Nonetheless I'm experiencing subject with ur rss . Don抰 know why Unable to subscribe to it. Is there anyone getting equivalent rss drawback? Anyone who is aware of kindly respond. Thnkx

Needed to put you one bit of word to finally thank you very much as before just for the wonderful views you've documented here. This has been pretty generous of people like you to give without restraint just what many people could possibly have offered for sale as an e book to generate some cash for themselves, certainly since you might have tried it if you ever desired. These ideas likewise worked like the fantastic way to fully grasp that some people have the same desire much like my own to know a little more pertaining to this condition. I'm sure there are some more pleasurable moments up front for folks who find out your blog.

My spouse and i were very glad Ervin could conclude his web research through your precious recommendations he got from your very own web pages. It is now and again perplexing just to be making a gift of solutions some others could have been trying to sell. Therefore we discover we have got you to appreciate because of that. All the explanations you made, the easy site navigation, the friendships you will help to promote - it is everything superb, and it's really letting our son and the family consider that the idea is exciting, and that's especially essential. Many thanks for the whole thing!

I actually wanted to construct a small note to express gratitude to you for these awesome information you are giving out at this site. My incredibly long internet investigation has now been compensated with awesome know-how to share with my family members. I would declare that many of us website visitors actually are unquestionably blessed to exist in a remarkable network with many special professionals with great things. I feel rather fortunate to have come across your entire website and look forward to plenty of more amazing moments reading here. Thanks a lot once more for a lot of things.

I simply desired to thank you very much once again. I'm not certain what I would have implemented without the actual creative ideas shared by you concerning such a subject matter. It actually was the frightening crisis in my opinion, however , encountering your expert style you managed it forced me to cry with fulfillment. I am happier for this advice as well as believe you know what an amazing job that you are getting into teaching men and women by way of your web site. More than likely you haven't encountered all of us.

I am also commenting to make you be aware of what a cool discovery my wife's child went through reading your webblog. She came to find so many details, which include what it's like to possess an amazing teaching character to make most people just know specific extremely tough issues. You truly did more than our own expected results. Thank you for showing these great, trusted, informative and even cool thoughts on the topic to Ethel.

I intended to post you that little bit of note to thank you very much over again on your fantastic tips you've contributed in this article. It is simply unbelievably open-handed of people like you to present extensively precisely what most of us could possibly have made available as an e-book to get some dough for their own end, certainly now that you could possibly have done it if you decided. These secrets also served to provide a easy way to understand that the rest have a similar keenness just like my own to learn whole lot more on the topic of this issue. I know there are some more pleasant times in the future for those who browse through your website.

I as well as my guys came taking note of the best tips and tricks located on the blog and then instantly developed a terrible suspicion I had not thanked the blog owner for those tips. The people had been for this reason stimulated to read all of them and already have certainly been loving them. I appreciate you for genuinely considerably kind and for opting for variety of important things most people are really needing to discover. My honest apologies for not expressing gratitude to you sooner.

I would like to express some thanks to you just for bailing me out of this setting. Just after exploring throughout the the web and obtaining concepts that were not powerful, I figured my life was over. Living without the solutions to the difficulties you've sorted out by way of your good short post is a critical case, and the ones that could have in a negative way affected my career if I hadn't come across your blog. The training and kindness in handling a lot of things was important. I am not sure what I would've done if I hadn't come upon such a step like this. It's possible to at this moment look ahead to my future. Thanks very much for your expert and amazing guide. I won't think twice to endorse your web site to any individual who should have assistance about this subject.

I intended to write you one very little note to thank you over again for all the superb principles you have documented on this website. This is quite seriously open-handed with people like you to provide unreservedly exactly what a few individuals would have marketed for an ebook to help with making some money for their own end, most notably seeing that you could possibly have tried it if you ever decided. Those concepts additionally acted to be the good way to fully grasp many people have the identical eagerness just as my personal own to find out more and more when considering this matter. I believe there are a lot more pleasurable opportunities up front for those who start reading your site.

I must show my respect for your kind-heartedness supporting folks who need help with this important study. Your real dedication to passing the solution around ended up being amazingly useful and have consistently helped those like me to achieve their ambitions. The informative help and advice can mean much to me and further more to my peers. Thanks a lot; from all of us.

My wife and i have been really thankful when Louis managed to conclude his survey through the entire precious recommendations he discovered in your blog. It's not at all simplistic just to continually be making a gift of techniques that people today may have been making money from. So we figure out we have the writer to appreciate because of that. All of the illustrations you've made, the straightforward blog navigation, the friendships you help to engender - it's many awesome, and it's really aiding our son in addition to our family consider that that topic is excellent, which is tremendously pressing. Thanks for all!

I and my friends have been looking through the good key points from the blog and so the sudden developed a horrible feeling I had not expressed respect to the web blog owner for those tips. These boys ended up as a result thrilled to see them and have in effect very much been tapping into them. Appreciate your genuinely considerably considerate and for picking out this sort of remarkable guides most people are really desperate to learn about. My honest regret for not expressing gratitude to earlier.

There are some attention-grabbing cut-off dates in this article but I don抰 know if I see all of them middle to heart. There is some validity however I will take hold opinion until I look into it further. Good article , thanks and we would like extra! Added to FeedBurner as effectively

Can I simply say what a aid to search out somebody who actually knows what theyre speaking about on the internet. You definitely know the way to convey a problem to light and make it important. More folks need to read this and understand this facet of the story. I cant consider youre not more common since you undoubtedly have the gift.

When I originally commented I clicked the -Notify me when new feedback are added- checkbox and now each time a remark is added I get 4 emails with the identical comment. Is there any approach you'll be able to remove me from that service? Thanks!

Good post. I learn something more difficult on different blogs everyday. It'll at all times be stimulating to read content material from other writers and practice a little one thing from their store. I抎 desire to make use of some with the content on my blog whether or not you don抰 mind. Natually I抣l provide you with a hyperlink on your internet blog. Thanks for sharing.

I'm also commenting to make you be aware of of the incredible discovery my princess found browsing yuor web blog. She noticed a good number of things, which include what it's like to possess an amazing helping nature to get the mediocre ones without problems comprehend some impossible topics. You undoubtedly did more than her expectations. I appreciate you for churning out these necessary, healthy, informative not to mention easy thoughts on that topic to Sandra.

I抦 impressed, I have to say. Really not often do I encounter a blog that抯 each educative and entertaining, and let me tell you, you have got hit the nail on the head. Your concept is excellent; the difficulty is something that not sufficient persons are talking intelligently about. I am very joyful that I stumbled across this in my seek for something referring to this.

I really wanted to jot down a simple remark to thank you for all the precious items you are sharing here. My extensive internet investigation has now been paid with reasonable facts and techniques to exchange with my close friends. I 'd admit that we website visitors actually are extremely fortunate to dwell in a really good community with very many awesome professionals with very beneficial pointers. I feel quite grateful to have come across your entire web page and look forward to tons of more thrilling minutes reading here. Thank you once again for everything.

Oh my goodness! an incredible article dude. Thank you Nonetheless I'm experiencing situation with ur rss . Don抰 know why Unable to subscribe to it. Is there anyone getting an identical rss problem? Anybody who is aware of kindly respond. Thnkx

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.