Web Controlled Raspberry Pi Surveillance Robot

Web Controlled Raspberry Pi Surveillance Robot

Raspberry Pi 4 is the improved version of Raspberry Pi 3 B+. Raspberry Pi 4 comes with Cortex-A72 quad-core processor running at 1.5GHz with memory bumped up to the LPDDR4. It has three times better processing performance and speed than the Raspberry Pi 3. With Raspberry Pi 4, you can run two monitors at once in 4K. Instead of the MicroUSB, Pi 4 has added a USB Type-C connector for power.

 

We previously used Raspberry Pi 3 with Pi camera to build applications like IoT based Smart Wi-Fi doorbell, surveillance camera, and Raspberry Pi cloud camera. Here we are using a Pi camera with Raspberry Pi 4 to build Raspberry Pi Web Controlled Robot. Here we will use Flask to create the webpage which will have controls to move the robot and it will also display a live feed of video. The web page will have five control buttons to move the Robot in Forward, Reverse, Left, Right direction, and Stop.

 

Components Required

  • Raspberry Pi 4 (any model will work)
  • Pi Camera
  • L293D Motor Driver Module
  • DC Motors (2)

 

Interfacing Pi Camera or USB webcam with Raspberry Pi 4

Pi Camera:

Pi Camera

 

1. To use pi-camera with Raspberry Pi, first enable camera interfacing from raspi-config. For it, run the sudo raspi-config and select Interfacing options.

Interfacing Pi Camera with Raspberry Pi 4

 

2. Then select the Camera option and Enable it on the next window and reboot the Pi.

Interfacing Pi Camera or USB webcam with Raspberry Pi 4

 

3. Now to test the camera, use the below command to capture a photo.

 raspistill -o image.jpg

If you get an image in Pi directory, then you are ready to go else check your camera strip and camera module.

 

USB Camera:

If you don’t have Pi Camera, a USB camera can also be used. Just install some packages to enable the webcam functionalities. Install the package using below command

sudo apt-get install fswebcam 

 

Now, check for the working of the camera by capturing a photo using the following command

fswebcam image.jpg

 

Installing ‘Motion’ in Raspberry Pi for Video feed

Motion Software is free, open-source motion detector CCTV software, developed for Linux. It can process images from many different types of cameras. Motion software can monitor video from more than one camera, and it can detect a change in the picture. With the help of Motion software, you can change your Raspberry pi into a CCTV surveillance camera that can detect the motion and send alerts. Motion software can also be used to get the live video feed on a Webpage.

Before installing the Motion, first, update your Raspberry Pi OS using the following command:

sudo apt-get update

 

After that, install the Motion using the below command:

sudo apt-get install motion

 

Now navigate to the /etc/default/motion file to set Motion daemon to yes so that it will always be running. Use the below command to edit the file:

sudo nano /etc/default/motion

Installing ‘Motion’ in Raspberry Pi

Then press CTRL+X > ‘Y’ > Enter to save the file.

 

Now, use the below command to set the permission for the motion Directory (/var/lib/motion/), where it saves all the Video recordings and picture files.

sudo chown motion:motion /var/lib/motion/

 

Now in this final step, turn off the localhost inside the motion configuration file to access the video feed outside the Raspberry Pi on the same network. To turn off the localhost, use the following command:

sudo nano /etc/motion/motion.conf

You can use the ctrl+W to search for a specific word inside the nano editor.

Installing ‘Motion’ in Raspberry Pi for Video feed

Now to check the video feed, start the motion using the below command:

sudo /etc/init.d/motion restart

 

After that, open the video feed page using your Pi’s IP address with port 8081 (192.168.1.207:8081).

Installing Flask in Raspberry Pi

 

After Motion, now install Flask to create a Web Server to control the robot.

The webpage to control the Robot will be created using Flask Web Framework. The webpage will have controls to move the robot in left, right, forward, and backward. In IoT based applications, Webservers are used to control or monitor any sensor values using web browsers, we previously created many webservers using ArduinoESP8266NodeMCUESP32Raspberry Pi, etc.

 

Flask is a popular Python web framework developed by Armin Ronacher of Pocoo. It is a third-party Python library used for developing web applications. Flask is classified as micro-framework, and it is based on the Pocoo projects Werkzeug and Jinja2. Flask is very commonly used with Raspberry Pi, as RPi has Linux OS which can easily process Python script. Raspberry Pi is also popular for creating webserver and making IoT based projects because of its high processing power and inbuilt Wi-Fi capabilities.

Use the below command to install the Flask:

pip install Flask

 

We previously used Flask to control the Servo motor and stepper motor through the webpage.

 

Raspberry Pi Surveillance Robot Circuit Diagram

Circuit diagram for Raspberry Pi based surveillance robot is given below.

Raspberry Pi Surveillance Robot Circuit Diagram

In this project, we don’t need to make many connections. We only need to connect two DC motors to the raspberry pi using the L293D Motor driver module. After this, mount the DC motors and Raspberry Pi to the robot chassis. The four pins (A1, A2, and B1, B2) of the motor driver module are connected to the GPIO pins 18, 23, 24 & 25 of Raspberry Pi.

Raspberry Pi Surveillance Robot

 

HTML Code for Raspberry Pi controlled Robot

A webpage is created using HTML to control the robot and for displaying the video feed. In this HTML code, we have assigned different integers for different direction buttons. For example, 1 for Forward and 2 for Left. So whenever the Forward button is pressed on the web page, it will send 1.

 

Complete HTML code for controlling the robot using webserver is given below. Create a directory named SurveillanceRobot, and inside this directory, create a new folder called templates. Then copy the below code and save it inside the templates folder as index.html.

Surveillance Robot using Raspberry Pi

<!DOCTYPE html>
<html>
            <head>
                        <title>Surveillance Robot</title>
                        <meta name="viewport" content="width=device-width, initial-scale=1">
            </head>
<style>
table ,td, tr {
                        width: 30%;
}
</style>
            <body>
                        <img src="http://192.168.1.207:8081/" style="float:left; width:100%; max-width: 700px; max-height:600px; border-radius:10px"></img>
                <table style="float:right; width:100%; max-width: 400px; height:300px;">
                 <tr style="text-align:center">
                    <td >
                         <h2>Web Controlled Surveillance Robot</h2>
                            <td >                 
                 <tr>
                 <tr>
                             <td style="text-align: center">
                                    <form action="/1" method="POST">
                                  <button id="FWD" class="robot">FORWARD</button>
                                  </br>
                                </form>
                             </td>
                 <tr>
                 <tr style="text-align: left">
                             <td style="text-align: left>
                            <form action="/2" method="POST">
                                     <button id="LFT" class="robot">LEFT</button>
                                     </br>
                                </form>
                             </td>
                     <td style="text-align: left>
                                    <form action="/4" method="POST">
                                     <button id="RGT" class="robot">RIGHT</button>
                                  </br>
                                    </form>
                             </td>
                             <td >
                                    <form action="/3" method="POST">
                                     <button id="STP" class="robot">STOP</button>
                                      </br>
                                    </form>
                     </td>                          
                   <tr>
                   <tr>
                             <td style="text-align: center">
                                    <form action="/5" method="POST">
                                     <button id="REV" class="robot">REVERSE</button>
                                     </br>
                                </form>
                             </td>
                   </tr>
                        </table>
        </body>
</html>

 

Python Code

Complete python code for this IoT Raspberry Pi robot is given at the end of this document. Copy the provided code and save it inside the SurveillanceRobot folder by using the following commands:

cd SurveillanceRobot
sudo nano robot.py

In the python code, there are five functions for moving the robot Forward, Left, Right, Reverse, and Stop. Five different integers are assigned to these five functions. Received integer from the web page will be saved in a variable named changePin, and it will be compared with all the functions. So when we press the Forward button on the web page, it will send one and based on that, the robot will move in the forward direction.

 

Testing the IoT controlled Robot

After completing all the setups and mounting the Raspberry Pi on Robot chassis, run the python code. Then open Raspberry Pi IP address with port 8000 (http://192.168.1.207:8000) in a web browser. Now you will see video streaming on the left side of the page and control buttons on the right side of the page as shown in the below image. Now this Raspberry Pi surveillance robot can be controlled through the webpage.

Raspberry Pi Surveillance Robot Working

A demonstration video with a complete python code is given below.

Code

HTML Code:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<img src="http://192.168.43.199:8081" /> <!--Enter the IP Address of your Raspberry Pi-->
<div style="float:right">
</div>
<div style=" height:400px; width:300px; float:right;">
<center>
<h2>Web Controlled</h2>
<h2>Surveillance Robot</h2><br><br>
<a href="#" id="up" style="font-size:30px;text-decoration:none;">  &#x1F881;&#x1F881;<br>Forward</a><br><br></center>
<a href="#" id="left" style="font-size:30px;text-decoration:none;"> &#x1F880;&#x1F880;Left</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="#" id="right" style="font-size:30px; text-decoration:none;"> Right &#x1F882;&#x1F882;</a><br><br>
<center><a href="#" id="down" style="font-size:30px;text-decoration:none;"> Backward<br> &#x1F883;&#x1F883;</a></center>
</div>
<script>
$( document ).ready(function(){
    $("#down").on("mousedown", function() {
     $.get('/down_side');
     }).on('mouseup', function() {
     $.get('/stop');
    });
    $("#up").on("mousedown", function() {
     $.get('/up_side');
     }).on('mouseup', function() {
     $.get('/stop');
    });
    $("#left").on("mousedown", function() {
     $.get('/left_side');
     }).on('mouseup', function() {
     $.get('/stop');
    });
    $("#right").on("mousedown", function() {
     $.get('/right_side');
     }).on('mouseup', function() {
     $.get('/stop');
    });
});
</script>
</body>
</html>

 

Python Code:

from flask import Flask, render_template, request, redirect, url_for, make_response
import time
import RPi.GPIO as GPIO
mA1=18
mA2=23
mB1=24
mB2=25
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(mA1, GPIO.OUT)
GPIO.setup(mA2, GPIO.OUT)
GPIO.setup(mB1, GPIO.OUT)
GPIO.setup(mB2, GPIO.OUT)
GPIO.output(mA1 , 0)
GPIO.output(mA2 , 0)
GPIO.output(mB1, 0)
GPIO.output(mB2, 0)
app = Flask(__name__) #set up flask server
#when the root IP is selected, return index.html page
@app.route('/')
def index():
    return render_template('index.html')
#recieve which pin to change from the button press on index.html
#each button returns a number that triggers a command in this function
#
#Uses methods from motors.py to send commands to the GPIO to operate the motors
@app.route('/<changepin>', methods=['POST'])
def reroute(changepin):
    changePin = int(changepin) #cast changepin to an int
    if changePin == 1:
        print "Left"
                GPIO.output(mA1 , 0)
                GPIO.output(mA2 , 0)
                GPIO.output(mB1 , 1)
                GPIO.output(mB2 , 0)
    elif changePin == 2:
        print "Forward"
                GPIO.output(mA1 , 1)
                GPIO.output(mA2 , 0)
                GPIO.output(mB1 , 1)
                GPIO.output(mB2 , 0)
    elif changePin == 3:
        print "Right"
                GPIO.output(mA1 , 1)
                GPIO.output(mA2 , 0)
                GPIO.output(mB1 , 0)
                GPIO.output(mB2 , 0)
    elif changePin == 4:
        print "Reverse"
                GPIO.output(mA1 , 0)
                GPIO.output(mA2 , 1)
                GPIO.output(mB1 , 0)
                GPIO.output(mB2 , 1)
    else:
        GPIO.output(mA1 , 0)
                GPIO.output(mA2 , 0)
                GPIO.output(mB1 , 0)
                GPIO.output(mB2 , 0)
    response = make_response(redirect(url_for('index')))
    return(response)
app.run(debug=True, host='0.0.0.0', port=8000) #set up the server in debug mode to the port 8000

Video

100 Comments

An outstanding share! I have just forwarded this onto a coworker who was doing a little homework on this. And he in fact bought me lunch because I found it for him... lol. So allow me to reword this.... Thank YOU for the meal!! But yeah, thanx for spending the time to talk about this subject here on your website.|

I wish to express appreciation to you just for bailing me out of this challenge. Right after exploring throughout the search engines and meeting methods which are not beneficial, I was thinking my entire life was over. Being alive without the presence of strategies to the issues you have solved as a result of your blog post is a crucial case, as well as the ones which could have negatively damaged my entire career if I had not come across your web site. Your good capability and kindness in dealing with all the things was crucial. I don't know what I would have done if I had not discovered such a stuff like this. It's possible to at this point look forward to my future. Thank you so much for the professional and result oriented help. I will not be reluctant to recommend the sites to any individual who needs and wants direction on this situation.

Thanks a lot for providing individuals with such a breathtaking possiblity to discover important secrets from this site. It really is very nice plus packed with fun for me and my office mates to search your website particularly 3 times every week to see the latest issues you will have. And definitely, I am also actually happy concerning the effective guidelines served by you. Some 2 ideas on this page are particularly the most impressive we have all had.

I simply wanted to send a word so as to appreciate you for those unique pointers you are giving on this site. My time-consuming internet lookup has at the end of the day been recognized with good know-how to share with my family members. I 'd assert that we visitors actually are undoubtedly endowed to live in a superb network with very many lovely professionals with interesting points. I feel extremely grateful to have used your weblog and look forward to tons of more pleasurable times reading here. Thanks a lot again for all the details.

I am just commenting to make you understand what a magnificent discovery my wife's princess had viewing your blog. She figured out a good number of details, which included what it is like to possess an incredible helping character to make the others with no trouble know several impossible subject matter. You truly surpassed visitors' expectations. I appreciate you for showing such invaluable, trusted, educational as well as easy tips on this topic to Gloria.

I precisely needed to say thanks once more. I'm not certain the things I could possibly have followed in the absence of the entire tips revealed by you relating to such problem. It truly was an absolute frightful setting in my position, nevertheless spending time with a professional manner you handled it took me to cry over contentment. I am happier for the help and even hope you recognize what a great job you have been providing teaching others using your websites. More than likely you've never got to know all of us.

I precisely wished to thank you very much all over again. I am not sure the things that I could possibly have achieved in the absence of those basics contributed by you on such subject. It became a horrifying problem in my opinion, nevertheless viewing a new specialised style you dealt with that made me to jump with happiness. I'm happy for the help and as well , have high hopes you realize what a great job you're undertaking teaching many people through the use of your blog post. I am certain you've never come across any of us.

Thank you a lot for giving everyone remarkably splendid possiblity to read in detail from this site. It is always so fantastic plus packed with a lot of fun for me and my office co-workers to search the blog a minimum of three times every week to find out the new things you have. Of course, I'm so certainly satisfied with your outstanding hints you give. Selected 3 ideas in this article are in fact the most impressive I've ever had.

I was suggested this web site by way of my cousin. I'm no longer positive whether or not this put up is written via him as nobody else recognize such exact approximately my trouble. You are incredible! Thanks!|

I want to get across my admiration for your kind-heartedness in support of men and women who actually need guidance on your topic. Your special dedication to getting the solution up and down ended up being rather important and has without exception enabled somebody much like me to get to their dreams. Your entire warm and helpful tips and hints means a great deal a person like me and much more to my office colleagues. With thanks; from each one of us.

I wanted to send you this very small observation in order to say thanks a lot over again about the awesome basics you've contributed in this case. It has been certainly pretty open-handed of you to present unhampered precisely what a number of people would have offered for sale as an electronic book in making some dough for themselves, most importantly seeing that you could have tried it if you ever wanted. The strategies in addition served to become a great way to know that other individuals have similar keenness really like my own to figure out a little more when considering this issue. I am sure there are a lot more pleasant moments in the future for folks who looked at your blog post.

I was wondering if you ever considered changing the layout of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or two pictures. Maybe you could space it out better?|

I wish to express my appreciation to the writer just for rescuing me from this particular scenario. Just after researching through the the web and getting opinions that were not powerful, I figured my life was done. Living devoid of the approaches to the difficulties you've sorted out by means of this article is a serious case, as well as ones which may have negatively affected my entire career if I hadn't come across your blog. That understanding and kindness in maneuvering all the details was priceless. I am not sure what I would've done if I had not come across such a subject like this. It's possible to now look ahead to my future. Thanks very much for the reliable and amazing help. I won't hesitate to refer your web sites to any person who would need guide on this area.

Thanks for each of your work on this web site. My mum loves going through research and it is easy to see why. All of us hear all relating to the dynamic way you produce invaluable information on this web blog and encourage response from other ones on the subject matter while our simple princess is in fact studying so much. Have fun with the remaining portion of the year. You're conducting a powerful job.

I am commenting to make you know of the superb discovery our girl enjoyed visiting your site. She learned a lot of things, not to mention what it is like to have an awesome teaching mood to let certain people really easily thoroughly grasp specific extremely tough matters. You truly did more than our own expectations. Many thanks for presenting the warm and helpful, healthy, edifying and as well as easy tips on the topic to Mary.

I simply desired to appreciate you yet again. I am not sure what I might have followed without the tips contributed by you on such situation. This has been a very distressing issue for me personally, nevertheless discovering a expert technique you handled the issue made me to jump with delight. I'm just thankful for the assistance and then believe you realize what a great job you have been doing educating people via your blog. More than likely you have never met any of us.

I would like to show my gratitude for your kind-heartedness for those who have the need for assistance with this one question. Your very own dedication to passing the solution all through came to be incredibly functional and has all the time encouraged somebody like me to attain their desired goals. The informative help implies this much to me and somewhat more to my mates. Thank you; from each one of us.

Very good blog! Do you have any suggestions for aspiring writers? I'm planning to start my own site soon but I'm a little lost on everything. Would you suggest starting with a free platform like Wordpress or go for a paid option? There are so many choices out there that I'm completely confused .. Any suggestions? Thank you!|

I wish to get across my passion for your kindness for men and women who need help with in this concern. Your personal dedication to passing the message all over ended up being rather informative and have without exception enabled most people just like me to reach their desired goals. Your personal useful help and advice denotes a great deal to me and even further to my colleagues. Thanks a ton; from all of us.

I simply wanted to thank you very much all over again. I'm not certain the things that I would've implemented in the absence of the actual points revealed by you regarding my industry. It seemed to be a horrifying matter in my position, but spending time with the very specialized fashion you processed the issue forced me to jump for happiness. I am just thankful for this assistance and in addition hope that you know what a great job your are carrying out training men and women through your web page. More than likely you've never encountered any of us.

Howdy would you thoughts allowing me know which webhost you’re using? I’ve loaded your blog in three different web browsers and I have to say this website loads lots more quickly then most. Could you advise a fantastic World-wide-web hosting provider at a good price tag? Several thanks, I recognize it!

I precisely needed to thank you so much once again. I am not sure what I would have handled without the type of tips and hints documented by you on my situation. This was an absolute alarming situation for me personally, nevertheless finding out the very well-written fashion you processed it made me to cry with joy. I'm just grateful for the service and then pray you recognize what an amazing job that you're putting in teaching men and women via your website. Most likely you've never got to know any of us.

Your type is so one of a kind in comparison to Other individuals I’ve read through things from.<br />Quite a few thanks for putting up any time you’ve obtained The chance, Guess I<br />will just bookmark this site.

Does one intellect if I estimate a handful of of your respective posts as long as I offer credit history and sources back again towards your weblog? My web site is in the very same spot of desire as yours and my buyers will surely benefit from a great deal of the data you supply here. Please allow me to know if this okay along with you. Thanks!

I think everything said made a great deal of sense. However, think about this, suppose you added a little information? I mean, I don't wish to tell you how to run your blog, but what if you added something to maybe get people's attention? I mean %BLOG_TITLE% is kinda plain. You should glance at Yahoo's home page and note how they create news headlines to grab people interested. You might add a video or a related pic or two to get people excited about what you've written. In my opinion, it could make your posts a little livelier.|

Hmm is anyone else experiencing problems with the pictures on this blog loading? I'm trying to find out if its a problem on my end or if it's the blog. Any responses would be greatly appreciated.|

I enjoy you because of every one of your labor on this website. Gloria take interest in setting aside time for investigation and it's really obvious why. A number of us notice all relating to the compelling medium you render great techniques by means of this web blog and encourage contribution from other people about this matter plus my princess is becoming educated a lot. Have fun with the rest of the new year. You have been carrying out a dazzling job.

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.