Informatic a (n limba englez a) [602034]
Universitatea de Vest din Timis oara
Facultatea de Matematic a s i Informatic a
Informatic a (^n limba englez a)
Diploma Thesis
Motion control of a Raspberry-Pi
based robot using a Mobile Device.
Author:
Stoica Romina-GabrielaSupervisor:
dr. Ciprian Pungila
Timi soara, 2015
Contents
1 Introduction 2
2 Raspberry-Pi 3
2.1 History of Raspberry-Pi . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 Hardware and Software specication . . . . . . . . . . . . . . . . . . . . . 4
3 Pi2Go Lite 7
4 Android Platform 9
4.1 The Development Environment . . . . . . . . . . . . . . . . . . . . . . . . 9
4.2 Android Application Structure . . . . . . . . . . . . . . . . . . . . . . . . . 10
5 Program implementation 12
5.1 Programming the GPIO with Python . . . . . . . . . . . . . . . . . . . . . 13
5.2 Mobile Application Design . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5.3 Connectivity and Communication . . . . . . . . . . . . . . . . . . . . . . . 22
6 Survey of related works 29
7 Conclusion and future work 30
List of References 31
List of Figures 32
List of Tables 33
Acronyms 34
1
1 Introduction
Robotics is an extremely dynamic eld with thriving advancement in its technology.
Along with other emerging technologies such as information technology, biotechnology,
and nanotechnology, robotics will contribute to increasing opportunities for economic
growth and greatly aect future generations with substantial social and economic im-
pacts. Telerobotics is the area of robotics concerned with the control of semi-autonomous
robots from a distance, chie
y using Wireless network (like Wi-Fi, Bluetooth, the Deep
Space Network, and similar) or tethered connections.
Robot control refers to the way in which the sensing and action of a robot are co-
ordinated. I developed a mobile device application in order to have wireless control of
aPi2Go-Lite robot. My application controls the Raspberry-Pi based robot motors
from any Android Mobile Phone, only by changing the port number and IP address on the
interface. Using Wi-Fi the robot can be controllable anywhere in the world, so long as it
is within range of the mobile phone hotspot. In order to do that I created a Python server
on the board which awaits incoming requests from the Java client Android Application.
I chose Android Platform because it's open source, easy to integrate and the appli-
cations are scripted in Java programming language with the help of a rich set of libraries.
This allows a clean and optimal way to interact with the Raspberry-Pi, which is a small
low cost computer designed specically for education. It is based around an ARM proces-
sor which can run the open source Linux operating system and includes a GPIO (General
Purpose Input Output) connector which can be used to interface to electronic circuits
that can control the robot.
This thesis study starts with some information of the Raspberry-Pi board and Pi2Go-
Lite Robot. It also focuses on the Android Platform specications, client-server model
and the development of the program. Further it deals with a survey of related projects,
future work and nally the conclusion of the thesis.
2
2 Raspberry-Pi
Raspberry-Pi is basically a mini-computer, the size of a credit-card developed in the
UK by the Raspberry Pi Foundation with the intention of promoting the teaching of basic
computer science in schools. The Foundation provides Debian and Arch Linux ARM
distributions for download. Tools are available for Python as the main programming
language, with support for BBC BASIC, C, C++, Java, Perl and Ruby. The Raspberry-
Pi I think is denitely a serious contender for robotics, especially because it has more
software abilities.
Figure 1: Raspberry-Pi 1 Model B+
2.1 History of Raspberry-Pi
The Raspberry-Pi sprang out of a desire by colleagues at the University of Cambridge's
Computer Laboratory to see a return to the days of kids programming inexpensive com-
puters. The rise of expensive PCs and games consoles put paid to the BBC B, Spectrum
and C64 generation of home programmers, leading to applicants for computer studies
courses lacking the necessary skills.
In 2006, early concepts of the Raspberry Pi were based on the Atmel ATmega644 mi-
crocontroller. Its schematics and PCB layout are publicly available. Foundation trustee
3
Eben Upton assembled a group of teachers, academics and computer enthusiasts to devise
a computer to inspire children. The computer is inspired by Acorn's BBC Micro of 1981.
Pi's model A, model B and model B+ are references to the original models of the British
educational BBC Micro computer, developed by Acorn Computers. The rst ARM pro-
totype version of the computer was mounted in a package the same size as a USB memory
stick. It had a USB port on one end and an HDMI port on the other.
The basic concepts behind the Raspberry-Pi were to make it as aordable as possible,
supply only the basics and provide it with a programming environment and hardware
connections for electronics projects. The Foundation's goal was to oer two versions,
priced at US$25 and US$35. They started accepting orders for the higher priced model
B on 29 February 2012, the lower cost model A on 4 February 2013. and the even lower
cost (US$20) A+ on 10 November 2014.
In 2014, the Raspberry Pi Foundation launched the Compute Module, which packages
a BCM2835 with 512 MB RAM and an eMMC
ash chip into a module for use as a part
of embedded systems. The ocial Raspberry Pi blog announced the Raspberry Pi 2 on 2
February 2015. Looking like a Model B+, it has a 900 MHz quad-core ARMv7 Cortex-A7
CPU, twice the memory (for a total of 1 GB) and complete compatibility with the original
generation of Raspberry Pis.
Although the Raspberry Pi is a relatively new device it has generated a massive amount
of interest due to the low cost of the device, this has resulted in a massive amount of
projects being undertaken on the Raspberry Pi in the short time it has been available.
2.2 Hardware and Software specication
The Raspberry Pi hardware has evolved through several versions that feature varia-
tions in hardware performance, memory capacity, and peripheral device support.
My robot is supported by the B+ model of Raspberry Pi. Although Model A is
cheaper than Model B, there are some other dierences in these two versions of Rasp-
berry Pi. Model A has a 256 MB memory, comes with a single USB port and does not
have any Ethernet port whereas model B and B+ have a 512 MB memory, 2 USB ports,
respectively 4 USB ports, and an Ethernet port as well. The system has Secure Digital
(SD) (models A and B) or MicroSD (models A+ and B+) sockets for boot media and
persistent storage.
A Raspberry Pi consists of many important hardware parts with some useful func-
tions. The main part of a Raspberry Pi is its Processor. The B+ Raspberry Pi has a
Broadcom BCM2835 chip which embodies an ARM1176JZF-S CPU core. The chip has a
clock speed of 700 MHz and it is a 32-bit System. My Raspberry Pi has a MicroSD card
with a 8 GB MicroSD card which acts as the storage media for it. Everything including
the operating system and other les are stored in the MicroSD card. The HDMI port is
used as audio and video output. A HDMI to DVI (Digital Visual Interface) converter can
be used to convert the HDMI signals to DVI which is normally used by monitors.
A Status LED is incorporated in the Raspberry-Pi board which provides the visual
information. For instance, the rst green light (marked as ACT on Raspberry Pi board)
4
indicates that the SD card is accessed, the second green LED (marked as FDX) indicates
the full duplex network and the third green LED (marked as LNK) indicates the link
activity. Similarly, the red light (marked as PWR) announces the power of 3.3v and the
yellow LED (marked as 100) hints the 100 Mbps network connection.
Table 1: Raspberry-Pi's specications (Raspberry-Pi 1 Model A, B, A+, B+, Raspberry-
Pi 2 Model B and Raspberry-Pi Compute Module Comparison 2015)
The 5v DC through a micro USB powers up the Raspberry Pi. This device also has
a RCA composite video connector for video output as well as a 3.5 mm stereo jack for
audio output. The Raspberry Pi has 26 GPIO pins which help to connect to low level
peripherals and expansion boards.
5
The Raspberry Pi does not come with a real-time clock, which means it cannot keep
track of the time of day while it is not powered on. As alternatives, a program running
on the Pi can get the time from a network time server or user input at boot time. A
real-time clock (such as the DS1307) with battery backup can be added (often via the
Inter-IC interface).
Raspian (Debian Wheezy) is the recommended Operating System for Raspberry-Pi
board and the one I have installed for my robot. Debian is a Unix-like computer oper-
ating system and a Linux distribution that is composed entirely of free and open-source
software. Raspbian is an unocial port of Debian Wheezy armhf (Acorn Risc Machine)
with compilation settings adjusted to produce code that uses "hardware
oating point",
the "hard
oat" ABI (Application Binary Interface) and will run on the Raspberry Pi.
The port is necessary because the ocial Debian Wheezy armhf release is compatible
only with versions of the ARM architecture later than the one used on the Raspberry Pi
(ARMv7-A CPUs and higher, vs the Raspberry Pi's ARMv6 CPU).
The Debian Squeeze image issued by the Raspberry Pi foundation was based on De-
bian armel which uses software
oating point and the "soft
oat" ABI. The foundation
used the existing Debian port for less capable ARM devices. Therefore, it did not use
of the Pi's processor's
oating point hardware – reducing the Pi's performance during
oating point intensive applications – or the advanced instructions of the ARMv6 CPU.
The "soft
oat" ABI passes
oating point parameters in integer registers while the "hard
oat ABI" passes them in vfp (
oating point) registers. The two ABIs are not compatible
because they use dierent registers. It is possible to use hardware
oating point with the
soft-
oat ABI but doing so means that whenever a
oating point value is passed to or
returned from a function it must be transferred to an integer register incurring a perfor-
mance penalty.
As for the programming language, the Raspberry Pi Foundation recommends Python,
but they also have support for BBC BASIC, C, C++, Java, Perl and Ruby. I chose
Python because is a wonderful and powerful programming language that's easy to use
(easy to read and write) and with Raspberry Pi lets you connect your project to the real
world. Python syntax is very clean, with an emphasis on readability and uses standard
English keywords. Python 2 was released in 2000, and Python 3 was released in 2008.
Python 3 is recommended, but some libraries have not yet been ported to Python 3 which
is why Python 2 is still present and widely used.
6
3 Pi2Go Lite
The Pi2Go Lite is a new fully integrated robot kit released by 4tronix, created to un-
leash the power of Raspberry Pi. Gareth Davies is the founder of 4tronix and the designer
of Pi2Go Lite. He has been developing educational computer and robotics projects for
years and designed the popular BeeBot and Pro Bot Turtle robots used in thousands of
schools around the world.
Besides the fact that its packed with a raft of sensors and is priced lower than most
Raspberry Pi robot kits on the market, the Pi2Gos most interesting asset is its chassis
design the circuit board itself makes up the body of the robot. Pi2Go Lite also features
a 5V switching regulator that will supply power to the Raspberry Pi as well as its two
motors, two IR obstacle sensors, two IR line sensors and an Ultrasonic distance sensor
from a set of four AA batteries.
Figure 2: Pi2Go Lite Robot
According to 4Tronix, the Pi2Go Lite takes around 90 minutes to solder and assemble
and compatibility between Raspberry Pi Model A/B and Model B+/B2 is catered for
with a quick change of support pillars on the chassis. With a wide range of inputs and
outputs to program, the Pi2Go is the ultimate programmable robot and is perfect for
project based work. The Pi2Go can be controlled and programmed wirelessly using Wi
7
or programs can be downloaded onto Pi2Go using the USB drive.
Other features included in the Pi2Go Lite kit are: a push button non-dedicated switch
use in you programs to change mode, switch o, or whatever you want, 4 pairs of fully
controllable RGB LEDS – any colour, any brightness; 4 light sensors with analog to digital
converter built in; servo outputs controlled by onboard hardware and Active Power supply
monitor – shuts down motors if battery getting low and sends signal to Pi if getting very
low.
Table 2: Pi2Go Lite Specications
As for the software part, 4tronix is providing a Python library module with some
example programs like: move motors forwards, backwards, spin left/right or do sweep-
ing turns, read the values from all the IR sensors (On or O), read the distance using
the ultrasonic sensor, read the value of the switch, set the white LEDs on or o (vary
brightness) and ScratchGPIO version 7.
8
4 Android Platform
Android is a mobile operating system (OS) based on the Linux kernel and currently
developed by Google. With a user interface based on direct manipulation, Android is
designed primarily for touchscreen mobile devices such as smartphones and tablet com-
puters, with specialized user interfaces for televisions (Android TV), cars (Android Auto),
and wrist watches (Android Wear). The OS uses touch inputs that loosely correspond to
real-world actions, like swiping, tapping, pinching, and reverse pinching to manipulate on-
screen objects, and a virtual keyboard. Despite being primarily designed for touchscreen
input, it has also been used in game consoles, digital cameras, regular PCs, and other
electronics. As of 2015, Android has the largest installed base of all operating systems.
Applications ("apps"), which extend the functionality of devices, are written using
the Android software development kit (SDK) and, often, the Java programming language
that has complete access to the Android APIs. The SDK includes a comprehensive set of
development tools, including a debugger, software libraries, a handset emulator based on
QEMU, documentation, sample code, and tutorials.
Android is also the Java class library used to build applications for the Android soft-
ware environment. Java on Android makes use of XML for variables such as strings and
integers. XML is also used to control the layout and style of an application. This sepa-
rate layer convention is similar to Hyper Text Markup Language (HTML) for content and
Cascading Style Sheet (CSS) for style. There are dierences due to dierent languages
and functionalities as HTML is not a programming language. As far as practical aspects
are concerned, Java denes the button's functionality, while XML denes the button's
text, color, font – weight and size.
4.1 The Development Environment
Android SDK makes use of the Java programming language, similar to Java Standard
Edition (J2SE), called Java Android Library. The SDK is mandatory to Android devel-
opers, it contains all the packages, applications framework and class libraries needed to
develop an Android application.
Every version of Android has a dierent Android Virtual Device (AVD). The ADV is
an emulator which actually contains the specic Smartphone OS.
AVDs are essentially emulators that allow Android applications to be tested without
the necessity to install the application on a physical Android based device. An AVD may
be congured to emulate a variety of hardware features including options such as screen
size, memory capacity and the presence or otherwise of features such as a camera, GPS
navigation support or an accelerometer. As part of the standard Android Studio installa-
tion, a number of emulator templates are installed allowing AVDs to be congured for a
9
range of dierent devices. Additional templates may be loaded or custom congurations
created to match any physical Android device by specifying properties such as process or
type, memory capacity and the size and pixel density of the screen. When launched, an
AVD will appear as a window containing an emulated Android device environment.
4.2 Android Application Structure
Every Android project contains several folders:
src: This folder contains the Java source les.
gen: Generated Java library, this library is for Android internal use only.
Res: Here we can store resource les such as pictures, XML les for dening layouts,
and so forth. Within this folder there are additional folders such as Drawable,
Layout, and Values.
Drawable : Here we store the various graphic les. We can see three types of draw-
able folders. This is because there are many Android devices with dierent screen
resolutions. By default, there are several versions of this folder such as: Drawable-
mdpi, drawable-hdpi, and so forth. This is required in order to adapt to dierent
screen resolutions.
Layout : This is the place for XML layout les. Layout les are XML les which
dene how various Android objects (such as textboxes, buttons, etc.) are organized
on the screen.
Values : XML les which store various string values (titles, labels, etc.).
Major les in the Android project:
AndroidManifest.xml : This is the Android denition le. It contains information
about the Android application such as minimum Android version, permission to
access Android device capabilities such as internet access permission, ability to use
phone permission, etc.
MainLayout.xml : This le describes the layout of the page. This means the place-
ment of every component (such as textboxes, labels, radio buttons, user dened
components, etc.) on the app screen.
Activity class: Every application that occupies the entire device screen needs at
least one class which inherits from the Activity class. One major method is called
OnCreate . This method initiates the app and loads the layout page.
It is essential to manage the lifecycle of our activities in order to develop a strong and
exible application. An activity has three states:
Resumed : The activity is in the foreground of the screen and has user focus.
Paused : Another activity is in the foreground (visible) and has focus, but this one
is still visible. Paused activities are completely alive but can be killed by the system
in low memory situations.
Stopped : The activity is running in the background and is no longer visible by the
user. Stopped activities are also alive and can be killed by the system.
10
Figure 3: Activity Lifecycle
In order to manage the lifecycle of our activity, we need to implement the callback
methods. Callback methods can be overridden to do the appropriate work when the state
of the activity changes. The most important callback methods are:
onCreate() method is called when the activity is created for the rst time. This is
where all the set up needs to be done such as create views, bind data to lists, and
so on.
onResume() method is called just before the activity starts interacting with the
user.
onPause() method is called when the system is about to start resuming another
activity.
onDestroy() method is called before the activity is destroyed.
11
5 Program implementation
The main purpose of my thesis was to control a Raspberry-Pi based robot from a
mobile phone. The Pi2Go Lite robot kit was a perfect choice for this project, providing
with all hardware components I needed and being easy to assemble. Next step was to
congure the Raspberry-Pi board. First I downloaded the Raspian OS disk image, write
it on a 8 GB microSD and insert it into the board. Connecting the Raspberry-Pi with
an HDMI cable to a monitor, inserting the power cable to the microUSB then hook up
a mouse and keyboard into the USB ports gave me the access to install the operating
system easily.
Once the board is turned on via the power switch (it has no power button) the boot up
screen appears (Debian Command Line), it contains a Raspberry Pi logo in the top right
hand corner and logs of white writing (System boot information). When the process has
completed, a login prompt apears. The default login for Raspbian is username: piwith
the password: raspberry . Entering the command startx the graphical user interface
will load.
Figure 4: Raspian User Iterface
12
5.1 Programming the GPIO with Python
General-purpose input/output (GPIO) is a generic pin on an integrated circuit whose
behavior, including whether it is an input or output pin, can be controlled by the user
at run time. GPIO pins have no special purpose dened, and go unused by default. The
idea is that sometimes the system integrator building a full system that uses the chip
might nd it useful to have a handful of additional digital control lines, and having these
available from the chip can avoid the eort of having to arrange additional circuitry to
provide them.
GPIO peripherals vary quite widely. In some cases, they are very simple, a group of
pins that can be switched as a group to either input or output. In others, each pin can be
set up
exibly to accept or source dierent logic voltages, with congurable drive strengths
and pull ups/downs. The input and output voltages are typically, though not universally,
limited to the supply voltage of the device with the GPIOs on and may be damaged by
greater voltages. A GPIO pin's state may be exposed to the software developer through
one of a number of dierent interfaces, such as a memory mapped peripheral, or through
dedicated IO port instructions.
Figure 5: The Raspberry-Pi's GPIO port and its pin denitions
13
The Raspberry Pi's GPIO port is located on the top-left of the printed circuit board,
labelled P1. It's a 40-pin port, tted with two rows of 20 male 2.54 mm headers at the
factory. The spacing of these headers is particularly important: 2.54 mm pin spacing is a
very common sight in electronics, and is the standard spacing for prototyping platforms
that include stripboards and breadboards. Each pin of the GPIO port has its own pur-
pose, with several pins working together to form particular circuits. Pi2Go-Lite uses only
the rst 26 pins of the Raspberry-Pi board.
Since the launch of the Pi, numerous developers created software modules known as
libraries for making full use of its various functions. In particular, programmers have
addressed the Pi users' need to access the GPIO port without having to know low-level
programming. There are several GPIO Python libraries designed to extend the function-
ality of the base Python language. For my project I installed the python-smbus , this
Python module allows SMBus (System Management Bus) access through the I2C/dev
interface on Linux hosts.
A Python library module is provided by 4tronix to externalise all Pi2Go specic hard-
ware, this helped me to easily access and control the motors from my keyboard. The
rst part of my program is a pi2go.py le that contains some general function: initiates
GPIO pins, switches motors, cleanup; and also motor function: start the motors forward
and backwards independently.
In order to make use of the python-smbus module, I included the library in my pro-
gram.
Next I declared some variables for the motor pins: 24, 26 for the left motor and 19,
21 for the right motor
Having the motor pins declared I made an initialization function, that congures the
type of pin numbering, sets up a channel and create a PWM instance for each motor pin.
GPIO.setmode(GPIO.BOARD) – sets pin numbering to BOARD numbering system. This
refers to the pin numbers on the P1 header of the Raspberry Pi board. The advantage
of using this numbering system is that the hardware will always work, regardless of the
board revision of the Raspberry Pi.
GPIO.setup(channel, GPIO.OUT) – congure a channel as an output, where channel
is the channel number based on the BOARD numbering.
p = GPIO.PWM(channel, frequency) – creates a PWM instance. Pulse-width mod-
ulation (PWM), or pulse-duration modulation (PDM), is a modulation technique used to
encode a message into a pulsing signal.
14
p.start(dc) – starts the PWN instance, where dcis the duty cycle (0.0 <= dc<=
100.0).
It is recommended to clean up any resources used in the program. This is done by the
cleanup() andstop() method. GPIO.cleanup() cleans up GPIO channels used in the
script and also clears the pin numbering system in use. p.ChangeDutyCycle(dc) changes
the duty cycle, where 0.0 <= dc<= 100.0.
For the last part of the pi2go.py module, but the most important one, I imple-
mented the motors control functions. For each motor's movement, using the functions
from RPi.GO library, I changed the frequency and duty cycle of each motor pin, depend-
ing on the movement direction and the speed parameter. Frequency is the number of
occurrences of a repeating event per unit time and a duty cycle is the percentage of one
period (the time it takes for a signal to complete an on-and-o cycle) in which a signal is
active.
15
5.2 Mobile Application Design
This section presents the main mobile application structure and also the Gracal User
Interface. The RobotClient application must be able to give the user a simple and clean
interface in order to access the robot and control it easily.
Figure 6: RobotClient application structure
16
This application is made in Android Studio which is a very powerful IDE for developing
Android apps. When a blank application project is created, the Android Studio auto-
generates all the basic les and folders needed. Considering that my application will give
the user the posibility to control the robot throw buttons, edit the IP address and the port
number, I will only interact with three les: AndroidManifest.xml ,activity_main.xml
andMainActivity.java .
An activity is an application component providing a view users can interact with. An
application can consists of multiple activities. The main activity is presented to the user
when the application is launched for the rst time. Activities must be declared in the
manifest le in order to be accessible to the system. This manifest le presents essen-
tial information about the app to the Android system. Information like: minimum SDK
(Software Development Kit) version, permissions, activities, services, etc.
Figure 7: Android manifest le
The User Interface is build using Views and ViewGroup objects. Android UI is re-
sponsible for the Layout manager and the widget organizer. View objects are the basic 11
units of user interface expression on the Android platform. The View class serves as the
base for subclasses called "widgets", which oer fully implemented User Interface (UI)
objects, like text elds and buttons. The ViewGroup class serves as the base for subclasses
called "layouts", which oer dierent kinds of layout architecture, like linear, tabular and
relative. A View object is a data structure whose properties store the layout parameters
and content for a specic rectangular area of the screen. A View object handles its own
measurement, layout, drawing, focus change, scrolling, and key/gesture interactions for
the rectangular area of the screen in which it resides. As an object in the user interface, a
View is also a point of interaction for the user and the receiver of the interaction events.
17
The RobotClient application has one view containing: four large buttons and two
text edit boxes (for the IP address and port number). The buttons give users the posi-
bility to control robot's motors and inside the text boxes they can change the IP address
given by the Raspberry Pi board and the port number.
Figure 8: RobotClient GUI
As was stated before, Android applications use XML layout for displaying the content.
The XML document consists of several tags with given properties. The parent tag denes
the main type of view for the document. Also it is allowed to use several views inside
of one main view. Like any other XML tag, this tag can have several properties which
will dene its identication, style, onclick action, etc. Identication is one of the most
important part of the tag, by dening the idit can be used in the Java code. Styles can
be hard coded in the statement or linked to separate le which will specify the element's
style. Action properties can call the event action that are dened in the code part of the
project.
18
The view of my application has a simple look, for this I used the <LinearLayout/> par-
ent tag that arranges its children in a single column or a single row. The layout_width at-
tribute tells to the mobile device how to display this view. In this case I used match_parent
keyword that sets the dimension to match with the parent element. layout_height is
the same as width but it uses vertical scale to display the view. orientation displays
the view depending on device orientation, it can be vertical or horizontal. In this case it
is horizontal so it means that device's screen is used in portrait mode.
Inside this main view I created another <LinearLayout/> tag for the buttons in the
left-side of the screen, where <Button/> represents a push-button widget. Push-buttons
can be pressed, or clicked, by the user to perform an action. Every Button is styled using
the system's default button background , this can be either a reference to a full drawable
resource (such as a PNG image, 9-patch, XML state list description, etc), or a solid color.
For the Raspberry Pi IP address and host number I made a second <LinearLayout/>
containing <TextView/> , that displays text to the user, and <EditText/> tag which is a
thin semblance over <TextView/> that congures itself to be editable. After this part I
made another linear view composed of the same two buttons but placed on right-side of
the screen.
19
In the MainActivity.java all those UI elements get functionality though java code
and they are manipulated accordingly in order to achieve robot's motors control. The
wiring is possible via the findViewById method, where the integer argument is the unique
ID that the element was given in the XML declaration le.
A very important aspect of the Android UI widgets is that they provide 'hooks' that
allow to get notications when the user performs an action, such as when he clicks a
button or traverses along the widgets.
To make use of the UI views I implemented rst a focus listener –
setOnFocusChangeListener() for the serverIpEditText andserverPortEditText
elements. This interface registers a callback to be invoked when focus of this view changed.
Its only method is onFocusChange() , which is called when focus state is changed, if focus
is lost then the value of serverIp orserverPort is updated.
20
In order to have clicking events on the buttons I implemented for each button the
setOnTouchListener() interface which denes a callback to be invoked when a touch
event is sent to the buttons. The interface contains only one method named onClick() ,
which gets called when the view has been clicked. Inside this method the MotionEvent
object keeps track of event movements. Motion events describe movements in terms of
an action code and a set of axis values. The action code species the state change that
occurred such as a pointer going down or up. Multi-touch screens emit one movement
trace for each nger. The individual ngers or other objects that generate movement
traces are referred to as pointers. Each pointer has a unique id that is assigned when it
rst goes down (indicated by ACTION_DOWN ). A pointer id remains valid until the pointer
eventually goes up (indicated by ACTION_UP ). These methods determine when the robot's
motor to start or stop moving, depending on button's state.
21
5.3 Connectivity and Communication
After considering the pros and cons of the two main options for providing connectiv-
ity (Bluetooth or Wi-Fi), it has been decided that the best choice would be the Wi-Fi
module. Wi-Fi (or WiFi) is a local area wireless computer networking technology that
allows electronic devices to network, mainly using the 2.4 gigahertz (12 cm) UHF and 5
gigahertz (6 cm) SHF ISM radio bands. The Wi-Fi Alliance denes Wi-Fi as any 'wireless
local area network' (WLAN) product based on the Institute of Electrical and Electronics
Engineers' (IEEE) 802.11 standards. Wi-Fi is better suited because it enables a faster
connection, better range from the base station, and better wireless security (if congured
properly) than Bluetooth.
Table 3: Wi and Bluetooth table comparison
My project uses the client-server architecture for data transmission between the robot
and mobile phone. The client-server model of computing is a distributed application
structure that partitions tasks or workloads between the providers of a resource or service,
called servers, and service requestors, called clients. Often clients and servers communi-
cate over a computer network on separate hardware, but both client and server may reside
in the same system. A server host runs one or more server programs which share their
resources with clients. A client does not share any of its resources, but requests a server's
content or service function. Clients therefore initiate communication sessions with servers
which await incoming requests.
22
Figure 9: Connection between RobotClient Application and Pi2Go-Lite Robot
To communicate, a client program and a server program establish a connection to one
another. Each program binds a socket to its end of the connection. The client and the
server each reads from and writes to the socket bound to the connection. A socket is a
software endpoint that establishes bidirectional communication between a server program
and one or more client programs. The socket associates the server program with a spe-
cic hardware port on the machine where it runs so any client program anywhere in the
network with a socket associated with that same port can communicate with the server
program.
Figure 10: Socket Connection between Client and Server
A server runs on a specic computer and has a socket that is bound to a specic port
number. The server just waits, listening to the socket for a client to make a connection
23
request. The client knows the IP address of the machine on which the server is running
and the port number on which the server is listening. To make a connection request, the
client creates a socket with servers machine IP address and port number, which will be
notied to server. The client also needs to identify itself to the server so sever can bind
to a local port number that it will use during this connection.
Once socket on client side is notied, the server accepts the connection. Upon ac-
ceptance, the server gets a new socket bound to the same local port it used when it is
initialized, and also has its remote endpoint set to the address and port of the client. It
needs a new socket so that it can continue to listen to the original socket for connection
requests while tending to the needs of the connected client. On the client side, if the
connection is accepted, a socket is successfully created and the client can use the socket
to communicate with the server.
My program has a Python socket server running on the Raspberry-Pi board. This
provides a socket on which the Android client can invoke commands. This Python server
also interacts with the Python scripts made in the robot.py le for the motors' move-
ments. The socket is bound to a port, and then continually listens for incoming data. In
order to process incoming commands from the client and set the motors' speed, the server
uses one thread that manages a queue of the received data.
A thread is like a process, and may even be a process, depending on the thread sys-
tem. In fact, threads are sometimes called 'lightweight' processes, because threads occupy
much less memory, and take less time to create, than do processes. Also, just as processes
can be interrupted at any time, the same is generally true for threads.
24
Python threads are accessible via two modules, thread.py and threading.py . My
server uses the second one because is a higher-level interface and it's modeled after the
Java thread facilities. The threading.py module contains a class Thread , that is ex-
tended by my ProcesssCommandThread class. This class overrides the __init__(self)
method to add supplementary arguments ( running and q), and the run(self) method
to implement a loop that checks if there is an element in the queue, if yes, then it takes
out the rst element and processes it. The q.get() parameters block the execution for 1
second to have a chance to stop the thread even if the queue is empty.
After the new Thread subclass has been implemented, I created an instance of it and
then start a new thread by invoking the start() method, which invokes the run() func-
tion.
In the process(value) method the robot's motors are controlled using the pi2go
module depending on the data received from the Android client.
25
In the main() function I created the socket with the socket.socket() method in-
cluded in the socket and uses the following commands:
socket.gethostname() – gets local machine name
s.bind() – binds address (hostname, port number pair) to socket
s.listen() – sets up and start TCP listener.
s.accept() – passively accept TCP client connection, waiting until connection ar-
rives (blocking)
client.recv(4096) – receives TCP message; the return value is a string represent-
ing the data received and the maximum amount of data to be received at once is
specied by bufsize = 4096
The socket is bound to a port, and then continually listens for incoming data. Once
some data is received, it is added onto a queue, which is then sequentially executed. The
server can be stopped by pressing CTRL+C .
The cleanup() method stops the thread nicely: it changes a variable to False , thus
the thread quits from its innite loop. With commandThread.join() the program waits
until the thread has completed its work.
26
The last piece of the Python server code is at the end of the le: using the name
__main__ from the global namespace determines whether this program has been run di-
rectly. By placing this code here, this program can easily be imported and used as a
module.
Moving to the Android Java client program, I used the AsyncTask class for enabling
proper and easy use of the UI thread. This class allows to perform background opera-
tions and publish results on the UI thread without having to manipulate threads and/or
handlers. AsyncTask 's generic types are:
Params , the type of the parameters sent to the task upon execution.
Progress , the type of the progress units published during the background compu-
tation.
Result , the type of the result of the background computation.
Not all types are always used by an asynchronous task, my application marks the
unused ones with the Void type.
In order to make use of the AsyncTask it must be subclassed, in my case by the
SendCommandTask . This subclass overrides the method doInBackground() which is in-
27
voked on the background thread and is used to perform background computation that
can take a long time. The parameters of the asynchronous task are passed to this method.
The rst statement in the try-catch block creates a new Socket object and names
itsocket . The Socket constructor used here requires the name of the computer and the
port number to which the client connects.
The second statement gets the socket's output stream and opens a PrintWriter
on it. To send data through the socket to the server, the client needs to write to the
PrintWriter .PrintWriter prints formatted representations of objects to a text-output
stream while the BufferedWriter writes text to a character-output stream, buering
characters so as to provide for the ecient writing of single characters, arrays, and strings.
AnOutputStreamWriter is a bridge from character streams to byte streams: char-
acters written to it are encoded into bytes using a specied charset. The program uses
writers so that it can write Unicode characters over the socket.
The write(command) method writes all the bytes in the command byte array to the
OutputStream , afterwards the flush() method
ushes all data written to the OutputStream
to the underlying data destination.
28
6 Survey of related works
29
7 Conclusion and future work
30
List of References
31
List of Figures
1 Raspberry-Pi 1 Model B+ . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 Pi2Go Lite Robot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3 Activity Lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4 Raspian User Iterface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
5 The Raspberry-Pi's GPIO port and its pin denitions . . . . . . . . . . . . 13
6 RobotClient application structure . . . . . . . . . . . . . . . . . . . . . . . 16
7 Android manifest le . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
8 RobotClient GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
9 Connection between RobotClient Application and Pi2Go-Lite Robot . . . . 23
10 Socket Connection between Client and Server . . . . . . . . . . . . . . . . 23
32
List of Tables
1 Raspberry-Pi's specications (Raspberry-Pi 1 Model A, B, A+, B+, Raspberry-
Pi 2 Model B and Raspberry-Pi Compute Module Comparison 2015) . . . 5
2 Pi2Go Lite Specications . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3 Wi and Bluetooth table comparison . . . . . . . . . . . . . . . . . . . . . 22
33
Acronyms
ABI Application Binary Interface
API Application Program Interface
ARM Acorn RISC Machine
AVD Android Virtual Device
CSS Cascading Style Sheet
DC Direct Current
DVI Digital Visual Interface
GPIO General Purpose Input Output
GPS Global Positioning System
GUI/UI Graphical User Interface
HDMI High-Denition Multimedia Interface
HTML Hyper Text Markup Language
IDE Integrated Development Environment
IEEE Institute of Electrical and Electronics Engineers
IP Internet Protocol
IR Infrared
ISM Industrial, Scientic and Medical
LED Light-emitting diode
OS Operating System
PCB Printed Circuit Board
PNG Portable Network Graphics
PWM Pulse Width Modulation
QEMU Quick Emulator
RGB Red, Green, Blue
SD Secure Digital
34
SDK Software Development Kit
SHF Super High Frequency
SMBus System Management Bus
TCP Transmission Control Protocol
UHF Ultra High Frequency
USB Universal Serial Bus
WLAN Wireless Local Area Network
XML Extensible Markup Language
35
Copyright Notice
© Licențiada.org respectă drepturile de proprietate intelectuală și așteaptă ca toți utilizatorii să facă același lucru. Dacă consideri că un conținut de pe site încalcă drepturile tale de autor, te rugăm să trimiți o notificare DMCA.
Acest articol: Informatic a (n limba englez a) [602034] (ID: 602034)
Dacă considerați că acest conținut vă încalcă drepturile de autor, vă rugăm să depuneți o cerere pe pagina noastră Copyright Takedown.
