You are on page 1of 13

Lab Handout #9: Raspberry Pi Remote Access

Instructor: Dr. Afaque Manzoor Soomro

Name: UNSA JAN


CMS ID:033-19-0048
Semester: VII

Department of Electrical Engineering


TEL-413: Introduction to Robotics
Rubrics for Lab Task Assessment

Rubrics for Marks Breakdown


Demonstration
Design Manual Total (Out of 100)
Manual

Criteria 100% 70% 30% 0%


Design (40%) Designed as per Partially designed Not designed as Code not
instructions. as per instructions. per instructions. submitted.
Demonstration Successfully Successfully Demonstrated Failed to
(40%) demonstrated the demonstrated with with Major demonstrate the
task as intended. minor mistakes. mistakes. project.
Manual (20%) The manual The manual The manual not The manual not
submitted on time submitted on time submitted on time submitted.
with proper without proper but with proper
solution code. solution code. solution.
Lab Objective:Access Raspberry Pi remotely and control your robot

Required components
1. Raspberry Pi
2. Micro SD card (Raspbian OS Pre-installed)
3. HDMI Cable
4. Monitor with HDMI port
5. Keyboard
6. Mouse
7. USB-Micro USB cable
8. Mobile Robot Chassis with motors
9. Battery
10. Motor Driver circuit board
11. Connecting wires
12. Laptop/Mobile phone

There could be many reasons to access your Raspberry Pi remotely, without connecting any
monitor and peripheral device (i.e., keyboard, mouse). For example if Raspberry Pi is embedded in
a robot, from where it is not possible to connect monitor to it. Or you may want to view some
information from Pi or any process running on it from elsewhere/remotely. Or your not present at
physical location of your Raspberry Pi, or you do not have any other monitor to connect with Pi.
For all of these reasons you need to access your Pi remotely using another
Desktop/Pi/Laptop/Phone.

Pi can be accessed several ways on Local network and over the internet. The remote connection can
also be made using Remote desktop (using VNC or RDP) protocol or just remote terminal (using
SSH). In this lab we will be working remote terminal access of Raspberry Pi on a local network.

In order to access your Raspberry Pi remotely, you need to get familiarise yourself with following
terms.

Pi Username & Password: Username and password is used to access Super User control of
the Pi. This is need when you need to install/remove any software/library or access your Pi
remotely. Default username and password is “pi” and “raspberry” respectively. You can change
your password by typing following commands on the terminal;

>passwd
>(Your current password i.e., raspberry)
>(Your new password)
>(Confirm your new password)

IP Address: Any device connected to a Network (LAN/WAN) is assigned an IP address. In this


lab we will connect the raspberry pi to a Wi-Fi network. In order to display IP address of your Pi
run following command on a terminal;

>hostname -I

SSH (Secure Shell): You can access the command line (terminal) of a Raspberry Pi remotely
from another computer or device on the same network using SSH. The Raspberry Pi will act as a
remote device and you can connect to it using a client on another machine on same network. Figure
1 shows a laptop connected to a Pi through SSH and Wi-Fi router.

Figure 1. Laptop connection with Pi using SSH through Wi-Fi

Is is possible that SSH is not enabled on your Raspberry Pi. In that case, raspi-config command can
be used in the terminal in order to enable it:
1. Enter sudoraspi-config in a terminal window
2. Select Interfacing Options
3. Navigate to and select SSH
4. Choose Yes
5. Select Ok
6. Choose Finish

Remote terminal Applications:


You are free to use your laptop or phone to access your Raspberry Pi remotely. Run following
program to access the Pi.
For Linux laptop (Connected with Wi-Fi): Open a terminal and run following commands;
>sshpi@192.168.10.20
where pi is the username and 192.168.10.20 is the IP address of the Pi. You will be prompted to
enter the password for the Pi.
>(enter password)
You will have access to your Raspberry Pi on your laptop terminal.
For Windows laptop (Connected with Wi-Fi): If you use windows, then you will need to
download a free program called “PuTTY” from here: http://www.putty.org/.
1. Having downloaded and installed PuTTY (it's a single file called putty.exe), run the program.
2. Enter the IP address that you found earlier and click “Open”. This will give you a warning (the
first time) and then prompt you for the user (“pi”) and password (“raspberry”).
SHH window (terminal) connected with the Pi will be available.
For (Android) Phone:
Termius App: Download Termius App from the Play Store.
1. Open Host tab, click + button and then new host.
2. Add following credentials for your Pi.
Alias → <Your name> Pi
Host IP → <Your Pi IP address>
SSH → Checked
Username → pi
Password → raspberry
Click check sign on top corner to save the credentials.
Your Alias for the host, we just created, will appear on the screen. Click on the Alias to establish
the connection with Pi.
Raspcontroller App: Download Raspcontroller application from the Play store.
1. Open the app and click + button.
2. Add device name (e.g., yournamePI), username, password and IP address.
3. Click save button to save the device.
4. Click on the device name to make the connection.
Once the connection is established, a list of possible actions, including GPIO control and SSH,
appears on the list. You can use GPIO control to control GPIO pins. Click SSH shell to access the
Pi terminal.

Practice Tasks:
1. Write a program to control an LED remotely.
Code

import RPi.GPIO as GPIO


import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(21,GPIO.OUT)
print "LED on"
GPIO.output(21,GPIO.HIGH)
time.sleep(10)
print "LED off"
GPIO.output(21,GPIO.LOW)

2. Connect a USB camera with the Pi and watch live video transmission remotely.
Code

import io

import picamera

import logging

import socketserver

from threading import Condition

from http import server

PAGE="""\

<html>

<head>

<title>Raspberry Pi - Surveillance Camera</title>

</head>

<body>

<center><h1>Raspberry Pi - Surveillance Camera</h1></center>

<center><img src="stream.mjpg" width="640" height="480"></center>

</body>

</html>

"""

class StreamingOutput(object):
def __init__(self):

self.frame = None

self.buffer = io.BytesIO()

self.condition = Condition()

def write(self, buf):

if buf.startswith(b'\xff\xd8'):

# New frame, copy the existing buffer's content and


notify all

# clients it's available

self.buffer.truncate()

with self.condition:

self.frame = self.buffer.getvalue()

self.condition.notify_all()

self.buffer.seek(0)

return self.buffer.write(buf)

class StreamingHandler(server.BaseHTTPRequestHandler):

def do_GET(self):

if self.path == '/':

self.send_response(301)

self.send_header('Location', '/index.html')

self.end_headers()

elif self.path == '/index.html':

content = PAGE.encode('utf-8')
self.send_response(200)

self.send_header('Content-Type', 'text/html')

self.send_header('Content-Length', len(content))

self.end_headers()

self.wfile.write(content)

elif self.path == '/stream.mjpg':

self.send_response(200)

self.send_header('Age', 0)

self.send_header('Cache-Control', 'no-cache, private')

self.send_header('Pragma', 'no-cache')

self.send_header('Content-Type', 'multipart/x-mixed-
replace; boundary=FRAME')

self.end_headers()

try:

while True:

with output.condition:

output.condition.wait()

frame = output.frame

self.wfile.write(b'--FRAME\r\n')

self.send_header('Content-Type', 'image/jpeg')

self.send_header('Content-Length', len(frame))

self.end_headers()

self.wfile.write(frame)

self.wfile.write(b'\r\n')

except Exception as e:
logging.warning(

'Removed streaming client %s: %s',

self.client_address, str(e))

else:

self.send_error(404)

self.end_headers()

class StreamingServer(socketserver.ThreadingMixIn,
server.HTTPServer):

allow_reuse_address = True

daemon_threads = True

with picamera.PiCamera(resolution='640x480', framerate=24) as


camera:

output = StreamingOutput()

#Uncomment the next line to change your Pi's Camera rotation


(in degrees)

#camera.rotation = 90

camera.start_recording(output, format='mjpeg')

try:

address = ('', 8000)

server = StreamingServer(address, StreamingHandler)

server.serve_forever()

finally:

camera.stop_recording()

Exercise Task: Write program(s) to access sensor data on your remote terminal.
Code

import gpiozero # GPIO Zero library

import time # Time library

# File name: test_ultrasonic_sensor.py

# Code source (Matt-Timmons Brown): https://github.com/the-


raspberry-pi-guy/raspirobots

# Date created: 5/28/2019

# Python version: 3.5.3

# Description: Test the HC-SR04 ultrasonic

# distance sensor

# Assign the GPIO pin number to these variables.

TRIG = 23

ECHO = 24

# This sends out the signal to the object

trigger = gpiozero.OutputDevice(TRIG)

# This variable is an input that receives

# the signal reflected by the object

echo = gpiozero.DigitalInputDevice(ECHO)

# Send out a 10 microsecond pulse (ping)

# from the trasmitter (TRIG)


trigger.on()

time.sleep(0.00001)

trigger.off()

# Start timer as soon as the reflected sound

# wave is "heard" by the receiver (echo)

while echo.is_active == False:

pulse_start = time.time() # Time of last LOW reading

# Stop the timer one the reflected sound wave

# is done pushing through the receiver (ECHO)

# Wave duration is proportional to duration of travel

# of the original pulse.

while echo.is_active == True:

pulse_end = time.time() # Time of last HIGH reading

pulse_duration = pulse_end - pulse_start

# 34300 cm/s is the speed of sound

distance = 34300 * (pulse_duration/2)

# Round to two decimal places

round_distance = round(distance,2)
# Display the distance

print("Distance: ", round_distance)


Rubrics for Lab Task Assessment

Rubrics for Marks Breakdown


Task Completion Manual Submission Total (Out of 10)

80% 20 % 100 %

Criteria Accurately Partially None


Design (40%) Designed as per Designed as per Not designed as per
instructions instructions instructions
Demonstration (40%) Successfully Successfully Failed to demonstrate
demonstrated and demonstrated but failed the project.
answered the asked to answer the asked
questions during the questions during the
demonstration. demonstration.
Manual (20%) The manual submitted The manual submitted The manual not
on time with the on time without the submitted.
solution code. solution code.

You might also like