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

Was going well until I tried to "open the video feed page using your Pi’s IP address with port 8081 (192.168.1.207:8081)." Camera worked fine from line command. When i did the sudo /etc/init.d/motion restart the light on the camera came on but when I type 192.168.1.207:8081 in my browser (I also tried the raspberry pi IP address with :8081 appended to it) but both efforts timed out, "Site could not be reached".
I used a Raspberry Pi 3 (article said it was ok). Any idea how to get this baby broadcasting??

I found the problem, I was looking at the wrong IP address. So now, I can see the picture and control buttons fine on the RPi through the wifi address using the RPi browser, but if I go to my windows PC or my iphone and try to connect, I get a "site can't be reached, response took too long error message. I tried using my iPhone Hotspot and again, works nicely on the RPi but not on iPhone. Any suggestions?

Got my old router out that has only main network, no guest network. PC and RPi got internet fine. Got the new IP address on the RPi and was able to see robot on the RPi browser like I had before on my Guest network. Went over to my PC and at the same IP address, still acts like there is nothing at that IP address. Looking on the internet someone suggested that it would be at a different IP address but I have no idea how to determine that address (ipconfig justs gives me my PC IP address). Help!!!

I in addition to my pals came taking note of the best tips and hints from the blog and so suddenly I got a terrible suspicion I had not thanked the web site owner for those techniques. All of the people came consequently thrilled to read all of them and have in effect in actuality been taking advantage of them. Appreciate your being considerably considerate and for selecting this sort of decent things millions of individuals are really desperate to know about. Our sincere regret for not saying thanks to sooner.

Thanks for your entire labor on this web page. My aunt really loves managing internet research and it's really obvious why. My spouse and i hear all about the compelling way you provide powerful guides by means of this website and therefore increase participation from other people about this concept plus my daughter is becoming educated so much. Have fun with the remaining portion of the year. You're the one doing a tremendous job.

Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your weblog? My blog is in the exact same niche as yours and my visitors would definitely benefit from some of the information you present here. Please let me know if this alright with you. Many thanks!|

I really wanted to jot down a message to appreciate you for all the precious suggestions you are sharing here. My incredibly long internet research has now been paid with reasonable facts and strategies to exchange with my guests. I 'd state that that most of us site visitors are very endowed to be in a notable community with very many lovely individuals with helpful advice. I feel really lucky to have encountered your entire web page and look forward to really more amazing moments reading here. Thanks once again for all the details.

I'm just commenting to let you be aware of of the useful encounter my cousin's child experienced reading your blog. She even learned numerous details, not to mention what it is like to have a marvelous giving nature to have many people without problems know precisely certain tricky subject areas. You actually surpassed my expectations. I appreciate you for producing those practical, healthy, informative not to mention easy tips on this topic to Janet.

I must voice my passion for your kind-heartedness giving support to people that really need guidance on this particular study. Your personal dedication to getting the message across had become unbelievably productive and has constantly permitted others just like me to arrive at their aims. Your own warm and helpful information entails a great deal a person like me and far more to my office workers. Thanks a lot; from all of us.

Needed to send you that bit of note to help give many thanks as before for the wonderful concepts you've documented in this article. It was certainly wonderfully open-handed with people like you to convey freely what exactly a few individuals might have marketed as an e book in making some cash on their own, chiefly seeing that you might have done it in case you considered necessary. Those thoughts likewise served to become a fantastic way to be aware that other individuals have a similar keenness similar to my personal own to see a great deal more with respect to this matter. I'm certain there are millions of more fun occasions up front for many who looked at your blog post.

I've been browsing on-line more than three hours today, but I by no means found any interesting article like yours. It's lovely value sufficient for me. In my opinion, if all site owners and bloggers made just right content material as you did, the internet will probably be much more useful than ever before.|

Thanks a lot for providing individuals with a very nice possiblity to read articles and blog posts from this site. It is usually so useful and stuffed with fun for me and my office colleagues to visit your blog nearly three times in one week to study the newest stuff you have got. Of course, we're certainly fulfilled with all the staggering solutions you serve. Selected 1 points in this post are certainly the most beneficial we have all had.

I'm writing to let you be aware of what a brilliant discovery my princess obtained going through the blog. She learned a wide variety of pieces, which include how it is like to possess an amazing helping mindset to have certain people smoothly have an understanding of various complex topics. You truly surpassed readers' expected results. Thank you for showing the important, trusted, informative and in addition cool tips on your topic to Kate.

My wife and i ended up being really cheerful when Edward could complete his basic research from your precious recommendations he gained from your very own web site. It is now and again perplexing to simply continually be making a gift of guides which often people may have been selling. And we know we now have the writer to appreciate for that. All of the explanations you've made, the straightforward website menu, the friendships your site assist to promote - it is all incredible, and it's making our son in addition to us recognize that that theme is satisfying, and that's wonderfully indispensable. Thanks for the whole thing!

Thanks a lot for providing individuals with a very special opportunity to read from this blog. It is often very pleasurable and as well , packed with amusement for me and my office acquaintances to visit the blog minimum thrice weekly to learn the latest things you have. And of course, I am also certainly amazed considering the effective secrets served by you. Certain 1 ideas in this article are definitely the simplest we have had.

I would like to thank you for the efforts you've put in writing this blog. I'm hoping to check out the same high-grade blog posts by you later on as well. In truth, your creative writing abilities has motivated me to get my own website now ;)|

My husband and i have been so relieved that Raymond managed to conclude his preliminary research through your ideas he obtained while using the web page. It is now and again perplexing to simply always be handing out guides that many the others have been making money from. And we also do understand we have you to give thanks to because of that. The illustrations you have made, the straightforward website menu, the friendships you can help foster - it's mostly astonishing, and it is helping our son in addition to our family recognize that the subject matter is satisfying, and that's particularly important. Thank you for the whole thing!

I wanted to draft you one little bit of word to give thanks again relating to the magnificent secrets you've contributed on this page. It is so incredibly generous with people like you to present freely just what some people would've distributed as an ebook to earn some bucks for themselves, notably considering that you might well have tried it in case you considered necessary. The pointers as well acted as a great way to be sure that other people have the same dreams just like my very own to figure out more pertaining to this condition. I believe there are a lot more enjoyable times ahead for those who looked at your website.

I together with my pals appeared to be reviewing the excellent tactics located on your web page then the sudden I had a terrible suspicion I never expressed respect to the web blog owner for those secrets. Most of the young men were definitely totally passionate to read through them and now have in actuality been enjoying these things. I appreciate you for being so kind and also for picking out this sort of very good subject areas millions of individuals are really needing to understand about. My personal sincere regret for not expressing gratitude to sooner.

I precisely had to thank you so much again. I'm not certain the things I would've created without the type of techniques documented by you on such theme. Entirely was a real horrifying situation in my position, however , discovering the very specialized tactic you treated that forced me to jump for joy. I am just grateful for your work and thus hope you comprehend what a great job you are doing training some other people via a site. Most probably you've never met any of us.

I want to show my thanks to the writer for rescuing me from this particular setting. Right after surfing throughout the world wide web and getting proposals which were not beneficial, I thought my life was over. Living without the strategies to the difficulties you've fixed through your good posting is a crucial case, and those which might have in a negative way damaged my career if I had not noticed your website. That natural talent and kindness in playing with almost everything was priceless. I am not sure what I would have done if I had not come across such a stuff like this. I can also now look forward to my future. Thanks for your time so much for your specialized and effective guide. I will not think twice to endorse the website to anyone who desires guidelines on this subject.

Just a few more comments. In order to get Forward from the FORWARD button, etc. the robot.py needs to assign the numbers differently. The robot.py above associates the changepin value of 1 to print "Left", but the button in the index.html file says 1 is FORWARD. If one changes the order in robot.py to process changepin values in the order of 2, 1, 4, 5, top to bottom instead of 1,2, 3, 4, then the button names match the printout from robot.py. I can't verify the motor directions except to say that the GPIO values for 3 are all zeros which makes sense to be STOP, not Right as in the robot.py code above.
Another thing to watch for is if you copy paste robot.pf, Python doesn't like the indentation on the GPIO lines and seemed to work if I used tab instead of blanks. Just FYI

It's a pity you don't have a donate button! I'd certainly donate to this excellent blog! I suppose for now i'll settle for book-marking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this website with my Facebook group. Chat soon!|

OK, so I fought with this for 2 weeks and then decided something was major messed up, So I copied the Robot filed to a USB drive and re-loaded Raspberry Pi from scratch. Once I re-installed the system and the Robot files, I was then able to see the image on my PC and iPhone. The camera is about 3 seconds delayed using the RPi 3, but still pretty neat project.

I wanted to draft you a little remark to be able to give thanks once again just for the pretty secrets you have contributed on this website. It is quite wonderfully open-handed of people like you to give publicly what exactly most of us would have marketed as an ebook to make some bucks for themselves, most importantly considering the fact that you could have done it if you ever decided. These ideas as well acted to become great way to realize that other people have a similar keenness the same as my personal own to realize more with respect to this issue. I'm sure there are several more pleasurable times in the future for individuals who see your site.

Needed to send you that tiny remark just to give many thanks once again over the beautiful opinions you've discussed on this page. It has been quite remarkably generous with you to deliver unhampered precisely what a few individuals would have offered as an electronic book to help with making some profit on their own, most importantly since you could have tried it if you ever desired. The basics likewise worked like a easy way to fully grasp that many people have a similar dreams much like my very own to realize a lot more when it comes to this matter. I believe there are many more fun periods in the future for folks who take a look at your website.

Guess I'm the real noob... I was able to get rid of the camera delay. I did 2 things; 1). In /etc/motion/motion.conf,
changed following:
daemon was off, now on
stream_maxrate was 1, now 50
framerate was 2, now 50
Also, I removed fswebcam, thinking I don't need it since I have the Raspberry Pi Rev 1.3 camera.
Anyway, it's working good, delay is fraction of a second.

Couldn't find the same L923D motor drive in the Circuit Diagram, but will muscle through using the Arduino Board shield.
Hope I provided helpful details so others can benefit from my struggle.

I precisely had to thank you very much again. I do not know the things that I might have handled in the absence of the entire thoughts shown by you on such area. Completely was an absolute hard circumstance in my view, but observing the skilled approach you treated the issue forced me to weep over delight. I'm thankful for your advice and then hope you realize what a great job you happen to be doing instructing other individuals with the aid of your webblog. I know that you have never encountered all of us.

hey there and thank you for your info – I've definitely picked up anything new from right here. I did however expertise several technical issues using this website, as I experienced to reload the site many times previous to I could get it to load correctly. I had been wondering if your web hosting is OK? Not that I'm complaining, but sluggish loading instances times will often affect your placement in google and can damage your quality score if advertising and marketing with Adwords. Well I am adding this RSS to my email and could look out for much more of your respective intriguing content. Make sure you update this again very soon.|

Thanks a lot for providing individuals with a very breathtaking chance to discover important secrets from here. It can be very pleasurable and stuffed with fun for me personally and my office mates to search your website at least 3 times in a week to find out the latest stuff you have. Of course, I'm just at all times amazed for the great pointers you give. Some 3 areas in this posting are unquestionably the very best we have all ever had.

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.