[

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图5

](https://medium.com/@rovai?source=post_page——-49ecad3a5ee8———————————)

Pan-Tilt Camera position controlled over local internet, using Flask and Python.

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图6

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图7

On previous tutorials we explored:

In this tutorial, we will combine what we have learned before, controlling our camera position thru internet, as shown in the example:

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图8

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图9

The above gif shows the camera controlled by buttons, pre-programmed with fixed Pan/Tilt angles. In this tutorial, we will also explore other alternatives to control the camera position thru internet.

Below the block diagram of our project:

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图10

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图11

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图12

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图13

With your RPi turned-off, install the Camara on its special port as shown below:

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图14

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图15

Turn on your Pi and go to Raspberry Pi Configuration Tool at main menu and verify if Camera Interface is enabled:

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图16

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图17

If you needed to Enabled it, press [OK] and reboot your Pi. Make a simple test to verify if everything is OK:

raspistill -o /Desktop/image.png

You will realize that an image icon appears on your Rpi desktop. Click on it to open. If an image appears, your Pi is ready to stream video! If you want to know more about the camera, visit the link: Getting started with picamera.

There are several ways to stream video. The best (and “lighther”) way to do it that I found was with Flask, as developed by Miguel Grinberg. For a detailed explanation about how Flask does this, please see his great tutorial: flask-video-streaming-revisited.

On my tutorial: Python WebServer With Flask and Raspberry Pi, we learned in more details how Flask works and how to implement a web-server to capture data from sensors and show their status on a web page. Here, on the first part of this tutorial, we will do the same, only that the data to be sent to our front end, will be a video stream.

Creating a web-server environment:

The first thing to do is to install Flask on your Raspberry Pi. If you do not have it yet, go to the Pi Terminal and enter:

sudo apt-get install python3-flask

The best when you start a new project is to create a folder where to have your files organized. For example:

From home, go to your working directory:

cd Documents

Create a new folder, for example:

mkdir camWebServer

The above command will create a folder named “camWebServer”, where we will save our python scripts:

/home/pi/Documents/camWebServer

Now, on this folder, let’s create 2 sub-folders: static for CSS and eventually JavaScript files and templates for HTML files. Go to your newer created folder:

cd camWebServer

And create the 2 new sub-folders:

mkdir static

and

mkdir templates

The final directory “tree”, will look like:

├── Documents
├── camWebServer
├── templates
└── static

OK! With our environment in place let’s create our Python WebServer Application to stream video.

First, download Miguel Grinberg’s picamera package: camera_pi.py and save it on created directory camWebServer. This is the heart of our project, Miguel did a fantastic job!

Now, using Flask, let’s change the original Miguel’s web Server application (app.py), creating a specific python script to render our video. We will call it appCam.py:

from flask import Flask, render_template, Response

Raspberry Pi camera module (requires picamera package, developed by Miguel Grinberg)

from camerapi import Camera
app = Flask(name)
@app.route(‘/‘)
def index():
“””Video streaming home page.”””
return rendertemplate(‘index.html’)
def gen(camera):
“””Video streaming generator function.”””
while True:
frame = camera.getframe()
yield (b’—frame\r\n’
b’Content-Type: image/jpeg\r\n\r\n’ + frame + b’\r\n’)
@app.route(‘/videofeed’)
def video_feed():
“””Video streaming route. Put this in the src attribute of an img tag.”””
return Response(gen(Camera()),
mimetype=’multipart/x-mixed-replace; boundary=frame’)
if __name
== ‘__main
‘:
app.run(host=’0.0.0.0’, port =80, debug=True, threaded=True)

The above script streams your camera video on an index.html page as below:

MJRoBot Lab Live Streaming

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图18 }}#width=90)


@2018 Developed by MJRoBot.org
The most important line of index.html is:

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图19 }}#width=50)

There is where the video will be “feed” to our web page.

You must also include the style.css file on the static directory to get the above result in terms of style.

All the files can be downloaded from my GitHub: camWebServer

Only to be sure that everything is in the right location, let’s check our environment after all updates:

├── Documents
└── camWebServer
├── camera_pi.py
├── appCam.py
├── templates
| └── index.html
└── static
└── style.css

Now, run the python script on the Terminal:

sudo python3 appCam.py

Go to any browser in your network and enter with _http://YOUR_RPI_IP_ (for example, in my case: 10.0.1.27)

NOTE: If you are not sure about your RPi IP address, run on your terminal:

ifconfig

at wlan0: section you will find it.

The results:

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图20

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图21

That’s it! From now it is only a matter to sophisticate a page, embedded your video on another page etc.

Now that we have the camera working and our Flask WebServer streaming its video, let’s install our Pan/tilt mechanism to position the camera remotely.

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图22

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图23

For details, please visit my tutorial: Pan-Tilt-Multi-Servo-Control

The servos should be connected to an external 5V supply, having their data pin (in my case, their yellow wiring) connect to Raspberry Pi GPIO as below:

  • GPIO 17 ==> Tilt Servo
  • GPIO 27 ==> Pan Servo

Do not forget to connect the GNDs together ==> Raspberry Pi — Servos — External Power Supply)

You can have as an option, a resistor of 1K ohm in series, between Raspberry Pi GPIO and Server data input pin. This would protect your RPi in case of a servo problem.

Let’s also use the opportunity and test our servos inside our Virtual Python Environment.

Let’s use Python script to execute some tests with our drivers:

from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
def setServoAngle(servo, angle):
pwm = GPIO.PWM(servo, 50)
pwm.start(8)
dutyCycle = angle / 18. + 3.
pwm.ChangeDutyCycle(dutyCycle)
sleep(0.3)
pwm.stop()
if name == ‘main‘:
import sys
servo = int(sys.argv[1])
GPIO.setup(servo, GPIO.OUT)
setServoAngle(servo, int(sys.argv[2]))
GPIO.cleanup()

The core of above code is the function setServoAngle(servo, angle). This function receives as arguments, a servo GPIO number, and an angle value to where the servo must be positioned. Once the input of this function is “angle”, we must convert it to an equivalent duty cycle.

To execute the script, you must enter as parameters, servo GPIO, and angle.

For example:

sudo python angleServoCtrl.py 17 45

The above command will position the servo connected on GPIO 17 (“tilt”) with 45 degrees in “elevation”. A similar command could be used for Pan Servo control (position to 45 degrees in “azimuth”:

sudo python angleServoCtrl.py 27 45

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图24

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图25

The file angleServoCtrl.py can be downloaded from my GitHub

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图26

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图27

Let’s start creating a new directory calling it:

mkdir PanTiltControl1

On this directory we should have the following environment and files:

├── Documents
└── PanTiltControl1
├── camera_pi.py
├── angleServoCtrl.py
├── appCamPanTilt1.py
├── templates
| └── index.html
└── static
└── style.css

The file camera_pi.py is Miguel’s script and angleServoCtrl.py, both used before. You can download both from my GitHub, clicking on correspondent links.

Now we need the appCamPanTilt1.py, the index.html and style.css. You can download those files from my GitHub, clicking on correspondent links. Pay attention to its correct position on your directory.

Let’s see the index.html:

MJRoBot Lab Live Streaming

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图28 }}#width=80)


PAN: 30 45 60 75 90 105 120 135 150 ==> Angle: [ {{ panServoAngle }} ]

TILT: 30 45 60 75 90 105 120 135 150 ==> Angle: [ {{ tiltServoAngle }} ]


@2018 Developed by MJRoBot.org
The index.html was created from the previous file, used when we streamed our video. The new bunch of lines on this new file is related to each one of the buttons that appear on the page.

Let’s analyze one of them:

30

This is a simple HTML hyperlink TAG, that we have styled as a button (the button style is described in style.css). When we click on this link, we generate a “GET //”, where is “pan” and is “30 degrees”. Those parameters will be passed to the Web Server App (appCamPanTilt1.py).

Let’s see this part of code on appCamPanTilt1.py:

@app.route(“//“)
def move(servo, angle):
global panServoAngle
global tiltServoAngle
if servo == ‘pan’:
panServoAngle = int(angle)
os.system(“python3 angleServoCtrl.py “ + str(panPin) + “ “ + str(panServoAngle))
if servo == ‘tilt’:
tiltServoAngle = int(angle)
os.system(“python3 angleServoCtrl.py “ + str(tiltPin) + “ “ + str(tiltServoAngle))

  1. templateData = {
  2. 'panServoAngle' : panServoAngle,
  3. 'tiltServoAngle' : tiltServoAngle
  4. }
  5. return render\_template('index.html', \*\*templateData)

In this example, “servo” is equal to “pan”, and the 2 lines below will be executed:

panServoAngle = int(angle)
os.system(“python3 angleServoCtrl.py “ + str(panPin) + “ “ + str(panServoAngle))

What we are doing here is the same as we did when we tested the servo position on Pi Terminal. PanPin will be translated by “27” and panServoAngle to “30”. The app will generate the command:

python3 angleServoCtrl 27 30

Note that we do not need use “sudo” in this case, because the app was already started using “sudo”.

The video shows the project working and how the GET requests appear on Pi Terminal:

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图29

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图30

Sometimes what we only need is a few buttons to move our servos in steps:

  • Pan: Left / Right
  • Tilt: Up / Down

We can also use +/- buttons (Incremental — decremental angle), your choice. Let’s create a new directory:

mkdir PanTiltControl2

On this directory we should have the following environment and files:

├── Documents
└── PanTiltControl2
├── camera_pi.py
├── angleServoCtrl.py
├── appCamPanTilt2.py
├── templates
| └── index.html
└── static
└── style.css

The files camera_pi.py and angleServoCtrl.py are the same used before. You can download both from my GitHub, clicking on correspondent links or use the ones that you have downloaded before.

Now we need the appCamPanTilt2.py, the index.html and style.css. You can download those files from my GitHub, clicking on correspondent links. Pay attention to its correct position on your directory.

Let’s see the NEW index.html:

MJRoBot Lab Live Streaming

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图31 }}#width=80)


PAN Angle: - [ {{ panServoAngle }} ] +

TILT Angle: - [ {{ tiltServoAngle }} ] +


@2018 Developed by MJRoBot.org
The index.html is very similar to the previous one. The bunch of lines used on the last index.html was replaced by only 2 lines, where we will only have now 4 buttons Pan [+], Pan [-], Tilt [+] and Tilt [-].

Let’s analyze one of the 4 buttons:

-

This is also a simple HTML hyperlink TAG, that we have styled as a button (the button style is described in style.css). When we click on this link, we generate a “GET //”, where is “pan” and <-> is “decrease angle”. Those parameters will be passed to the Web Server App (appCamPanTilt2.py).

Let’s see this part of code on appCamPanTilt2.py:

@app.route(“//“)
def move(servo, angle):
global panServoAngle
global tiltServoAngle
if servo == ‘pan’:
if angle == ‘+’:
panServoAngle = panServoAngle + 10
else:
panServoAngle = panServoAngle - 10
os.system(“python3 angleServoCtrl.py “ + str(panPin) + “ “ + str(panServoAngle))
if servo == ‘tilt’:
if angle == ‘+’:
tiltServoAngle = tiltServoAngle + 10
else:
tiltServoAngle = tiltServoAngle - 10
os.system(“python3 angleServoCtrl.py “ + str(tiltPin) + “ “ + str(tiltServoAngle))

  1. templateData = {
  2. 'panServoAngle' : panServoAngle,
  3. 'tiltServoAngle' : tiltServoAngle
  4. }
  5. return render\_template('index.html', \*\*templateData)

In this example, “servo” is equal to “pan”, the lines below will be executed:

if angle == ‘+’:
panServoAngle = panServoAngle + 10
else:
panServoAngle = panServoAngle - 10
os.system(“python3 angleServoCtrl.py “ + str(panPin) + “ “ + str(panServoAngle))

Once the “angle” is equal to “-”, we will decrease 10 from panServoAngle and pass this parameter to our command. Suppose that the actualpanServoAngle is 90. The new parameter will be 80.

So, PanPin will be translated by “27” and panServoAngle to “80”. The app will generate the command:

python3 angleServoCtrl 27 80

Note that we do not need use “sudo” in this case, because the app was already started using “sudo”.

The gif shows the webpage working :

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图32

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图33

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图34

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图35

Sometimes could be interesting to send specific angle commands like:

  • Pan Angle ==> 35 degrees
  • Tilt Angle ==> 107 degrees

What means that or you will define your increment to “1” on the last step, what will take a lot of time to reach the required position, or you create a POST from your webpage. Let’s explore this last possibility.

Let’s again create a new directory:

mkdir PanTiltControl3

On this directory we should have the following environment and files:

├── Documents
└── PanTiltControl3
├── camera_pi.py
├── angleServoCtrl.py
├── appCamPanTilt3.py
├── templates
| └── index.html
└── static
└── style.css

The files camera_pi.py and angleServoCtrl.py are the same used before. You can download both from my GitHub, clicking on correspondent links or use the ones that you have downloaded before.

Now we need the appCamPanTilt3.py, the index.html and style.css. You can download those files from my GitHub, clicking on correspondent links. Pay attention to its correct position on your directory.

Let’s see the NEW index.html:

MJRoBot Lab Live Streaming

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图36 }}#width=80)

Enter Pan Tilt Servo Angle:

  1. PAN:
  2. TILT:

@2018 Developed by MJRoBot.org
The index.html now is a little bit different from the previous one. We will create here a “Form”, which method will be POST. An HTML form input TAG, will be used to pass as parameters the Pan/Tilt angle values digited by users. Those parameters will be passed to the Web Server App (appCamPanTilt3.py) when the button “submit” is pressed.

Let’s see this part of code on appCamPanTilt3.py:

@app.route(‘/‘, methods=[‘POST’])
def my_form_post():
global panServoAngle
global tiltServoAngle
panNewAngle = int(request.form[‘panServoAngle’])
if (panNewAngle != panServoAngle):
panServoAngle = panNewAngle
os.system(“python3 angleServoCtrl.py “ + str(panPin) + “ “ + str(panServoAngle))
tiltNewAngle = int(request.form[‘tiltServoAngle’])
if (tiltNewAngle != tiltServoAngle):
tiltServoAngle = tiltNewAngle
os.system(“python3 angleServoCtrl.py “ + str(tiltPin) + “ “ + str(tiltServoAngle))
templateData = {
‘panServoAngle’ : panServoAngle,
‘tiltServoAngle’ : tiltServoAngle
}
return render_template(‘index.html’, **templateData)

What we will do is to check which angle was changed generating the correspondent command similar what were done before.

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图37

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图38

As always, I hope this project can help others find their way into the exciting world of electronics!

For details and final code, please visit my GitHub depository: WebCam-Pan-Tilt-Control-via-Flask

For more projects, please visit my blog: MJRoBot.org

Below a glimpse of my next tutorial, where we will explore how to control our Pan-Tilt, but not with buttons, but with our face! ;-)

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图39

Raspberry Pi Cam Pan-Tilt Controlled Over Local Internet - 图40

Saludos from the south of the world!

See you in my next tutorial!

Thank you,

Marcelo