Beruflich Dokumente
Kultur Dokumente
Agus Kurniawan
ISBN: 978-1-300-95391-3
Preface
1. Introduction to Raspberry Pi
1.1 Raspberry Pi
1.2 Getting Hardware
2. Matlab Simulink and Raspberrv Pi
2.1 Matlab
2.2 Installin
2.3 Running Raspberry Pi
2.4 SSH
3. Helio World - Matlab Simulink and Raspberry Pi
4.1 GPIO
4.2 Preparation
4.3 Simulink with GPIO Write
4.3.1 Building Simulink Madel
4.3.2 Testinz
4.4 Simulink with GPIO Read
4.4.1 Creating Application for Arduino
4.4.3 Testing
S.l Prcparation
S.3Testing
Contact
Preface
This book was written to help anyone wants to get started in Raspberry Pi and Matlab Simulink. It describes alI the ba-
sic elements of the Raspberry Pi and Matlab Simulink with step-by-step approach.
Agus Kurniawan
1.1 Raspberry Pi
The Raspberry Pi is a small size computer (85.60mm x 56mm x 21mm) with completed features so that you can play mul-
timedia or run an application. This device is developed by the Raspberry Pi Foundation in UK. There ara two type of Rasp-
berry Pi:
You can see Raspberry Pi device with model B on the Figure below.
SPBER Y PI MODEL B
RCA VIDEO AUDIO
POWER
~
RS, http://uk.rs-online.com/web/generalDisplay.html?id=raspberrypi
Element 14, http://www.element14.com/raspberrypi
You a1so buy Raspberry Pi periphera1 devices for instance, keyboard, mouse, HDMI cab1e, SD card, USE hub, etc.
I tried to 100k for buying Raspberry Pi device and found that there are another options to buy
This chapter explains how to work with MatIab Simulink and Raspberry Pi Software.
2.1 Matlab
You can work with MatIab Simulink with targeting on Raspberry Pi using MatIab lOBa or the Iatest version. You aIso can
work with MatIab lOBa Student Version.
(""l'e"~ fOl\)
I,J U,fflt ~
Run your Matlab and then cliek Add-Ons. You ean see the menu as below.
Search DoclJmentation P
@ Internet (recommended)
O Folder
Installed lates1
Action Support Package for Required Base Produd Supported Host PI
Version Version
8 D Install Digilent Analog Discovery 1.1.1 Data Acquisition Toolbox Windows 132-bit),\
r
9 i Install A.n310gDevices DSPs 2.0 Embedded Coder Windows (32-bitl,\
., -
10 ~ Install Green Htlls r.."ULTI 3.0 Embedded Coder Windows 132-bitl,\
IMPORTANT NOTICE
================
REAO THE TERMS ANO CONomONS OF THIS MATHWORKS AUXILIARY SOFTWARE LICENSE
AGREEMENT (THE "AGREEMEN) CAREFULLY BEFORE CHECKING 1 ACCEPr OR ACCESSING THESE
MATERIALS (AS DEfINED BELOW).
THIS AGREEMENT REPRESENTS THE ENTIRE AGREEMENT BETWEEN VOU (lHE LICENSEE") ANO THE
MATHWORKS, INC. fMATHWORKS") CONCERNING THE SOFTWARE AND OOCUMENTATION MADE
AVAILABLE fOR ACCESS HEREUNOER (COLLECTIVELY, THE 'MATERIALS").
BY CHECKING 1 ACCEPI OR ACCESSING THESE MATERIALS VOU ACCEPT THE TERMS OF THIS
I
AGREEMENT.
1. DEFINmONS.
1. 1. Licensee' means vou, whether an individual or an entity, to whom MathWorks grants the
License, and who is responsible for complying with the contractual obligations of the License, and
ensuring that anyone permitted access to the Materiais also complies with such obligations.
1.2. "Documentation" means the user guides, if any, accompanying delivery of the Materiais, as may
be updated from time to time, as 'Neli as any reports or other reedback that MathWorks may, in its sole
disaetion, provide to Licensee. Documentation may be delivered in printed and/or online forms, and in
one or more languages.
~ I accept
Vou have chosen to instaU Simulink Support Pack.age for Raspberry Pi Hardware.
Software Vl'illbe installed from the following locations:
This utility enables Vou to download and install the third party soft1Nare listed above. This list may contain
open source software, induding software licensed under the terms of the General PubJiclicense.
By dicking 1nstaU" on the next screen, vou will be downloadng and instaJling the soft1l1'arelisted above.
IMtal/update complete
Simulink Support Package for Raspberry Pi Hardware has been successfully installed.
Hardware: aS):>~~~~Y~i J
..
Help
Select a board
The firmware update process for Raspberry Pi hardware consists of copying a
Raspbian Wheezy Linux image onto a memory cardo We will guide you through
this processo Select your board to get started:
Board: I
Model B .1
Get firmware
Configure board
The board .\lilI be configured with the foilowing name and IP settings:
IP Settings
IP address: 10.10.10.9
<
Select the drive letter that corresponds to the memory card reader:
Drive: I D: ~! I RelTesh
If you do not find the memory card reader in the list of drives, reinsert the memory card fully
and dick "RelTesh',
~
Slide lock switch
up to unlocked
position
This dialog cal1 detect your SD cardo If 110t,select the drive of your SD cardo
Vou chose to write to drive D:. The write operation may take severa I minutes.
I,
(- WARNING: Ali data in the memory card will be erased!
Cana
Instructions
Plug out SD card from compu ter. Then, plug in it into Raspberry Pi
After Raspberry Pi is running well, cIick Next button. Then you will see a dialog as below.
If you want to log in to the board in the future, the host na me or IP address, user name, and password are
displayed below. Voumay also type "raspberrypi" on the MATLAB command window to obtain this information.
Host name: raspberrypi-AKUR
User name: p
Password: raspberry
NOTE:
1. Your Raspberry Pi hardware willspeak its IP address through the analog audo connector when
it boots.
2. Voucan configure your Raspberry Pi hardware to automatically send an e-mail when IP address
changes. Click'Help' for detailed instructions.
<
1 + .
i
I
~
i
Simulink Support Package for Raspberry Pi Hardware EXAMPLES
SimulinkG) lets you design aM run models on Raspberry Pi@ hardware. With this capability. you can assess an optimize
algorithms in the classroom or lab as they execute in real-time on Raspberry Pi hardware with physicallJO.
~
I
i
Product page at mathw(
i
I
i
I
I
1:
!
! Getting Started with Raspberry Pi Hardware
I!tl ModE
~
~
I~
i
i ...-..f~
~
1 rQ:] ~
-" I~l
.~
I F~~'J r:TwI ~~] Communicating with Raspberry Pi Hardware I!tl ModE
I I ~~'I
t : ~~ .
Libraries
__
.J Library: Simulink Support Package for Raspberry Pi Hardware ~
Simulink
Commonly Used Blocks ALSAAudio ALSAAudio
J'.'
Continuous ~ Capture PIsybaO:
Discontinuities
Discrete
Logic and Bit Operations
Lookup Tables
~
.rtr.
='""':~
GPIO Read
G .rtr.
-t-..: .~
GPIOWrite
Math Operations
Model Verification CO
"qr"'.:.,c:: .
LEO
~
SOL Vdeo
Displsy
Model-Wide Utilities
Ports & Subsystems
Signal Attributes
Signal Routing
rn-- -410 _ 1_ UOP Reoeive
V4L2Video
~
~:-'~I UDP Semi
[;>
User-Defined Fundiom
Additional Math & Discrete
I eSpes.'
,',f~ Speech
Text to
Try to configure your Raspberry Pi, for instance, timezone and keyboard.
I startx
2.4 SSH
You may need SSH to manage Raspberry Pi remotely. How to instam You can write his script
Sometimes, you want to mn SSH service every booting. Try to update update-rc.d file
I $ sudo reboot
For testing, I used PuTTY application in Windows 8 to remote Raspberry Pi via SSH.
PuTTY Configuration
Categ.ory:
r _ _ _ 1
~ ..Session I Basic options for your Pu TTY session .
L... Logging
Specify the destination you want to connect to
~. Terrninal
! Keyboard
Host liame (or IP address) ~fo_rt _
! Telnet
! RJogin
ctl' SSH
L... Serial
Oose
'indow on exit:
O A1ways O
N-ever @ Only on dean exit
~out
If connected, you will get a secuity alerto
We are going to build a simple Matlab Simulink with Raspberry Pi, called Hello World. In this scenario, we work with
LED on Raspberry Pi. Try to turn on and off from our model.
If you see Matlab Simulink Library on Raspberry Pi library, you can sce LED library. We will use this library on our mod-
cl.
Help
5imulink
ALSAAu<iio ALSAAudio
Commonly Used Blocks
Capture Playbadt:
Continuous
G:J'"~'''
Discontinuities
Discrete GPIO Read nr. GPIOWrite
C~
CD""-.'~
Lookup Tables SOL Video
"@ LEO ~
. ..,~
'~
Math Operations Oisplay
: c . ~
Model Verification
Model- Nide Utilities
Ports & 5ubsystems
Signal Attributes
rn [!:J
-. .- -"
UDP Reoeive UDP Seno
Now we are ready to build a "helIo world" Matlab Simulink with Raspberry Pio FolIowalI steps.
On Home, click + New icon. Then you will obtain a menu as below.
Find Files ~ -
Compare Import Save
Data Workspace
Script Ctrl-N
Agus ~ Documents ~ rv
Function 01
D Example
Class
~
ij System Object
Figure
Command Shortcut
SIMUlINK
~ Simulink Model
Normal .
Model BrO'Nser
untitled
Ready 100%
On the Simulik Model dialog, click menu Tools -> Library Browser.
Then you wil! the list of Simulink library include Raspberry Pi library.
Click Simulink Support Package for Raspberry Pi Hardware, then you wil! see all Raspberry Pi installed library.
File Edit View Help
Sources
User-Defined Functions eSpeak Texl to
c' Additional Math & Discrete Speec:h
Model Browser
toa.. helloworld
fR";iI
~
SineWsve RASPBERRYPI
""1'.
fi:l1
ledO (Green)
_lIDo_lea_o ~ LEO
Data Type Coowrsion
You need three libraries as follows
Select the desired LED from the drop-down menu. Do not use the
same LED in multi pie blocks within a model.
Parameters
[
Board: 1.~.~.9.~.I
....
~.....
~ey~ .. i
...............................................!
View LED location
............................................
You aIso can click View LED location button to view LED position.
Model B Rev2 LED locations
File Edit View Insert T 0015 Desktop Window Help
O~ r-
Convert the input to the data type and scaling of the output.
The conversion has two possible goals. One goal is to have the Real World
values of the input and the output be equal. The other goal is to have the
Stored Integer Values of the input and the output be equal. Overflows and
quantization errors can prevent the goal from being fully achieved.
Parameters
O Lock output data type setting against changes by the fixed-point tools
Due to Raspberry Pi LED input needs boolean data type, you must select boolean on Output data type.
Parameters
Sine type:
Time (t): [U-;~.-;~I~ti~~--ti.~~;"-'._.'_ '--.M ._.. ---_ "._ -- _-- ..-- ------'-~J
--.......................
Amplitude:
Frequency (rad/sec):
OK Apply
You test and validate your model. Make sure you scleet Normal. Then, cliek Arrow, shown in Figure below.
helloworld
nulation Code Tools Help
To run this model to Raspberry Pi, you must configure. How? Click menu Tools -> Run on Target Hardware -> Prepare
to Run.
-- ~._._-_.~---_. __ ._-----------------------------
Code I Tools L~lp_ . ,
>
...i~
Library Browser
F?':!\
~ Model Explorer
S,~tt: j Th ",.""1 is ""I ""I to um ""y Lo,gd h.,dw.'e. Set ll1<>"Torgol """Ih""",' porilltlld" t miOll rou' lorgol """4 ."
I So~r ! I' y1ltIf hilr""'lt' e 15 t\t Ii:!tf!d llle 'Th'get har<hvare' optioos, l'\:!tllll the IlIfget foI' VOUfhat'<l""llt~,
i OAU ~'f>port
!" Optjmlratiol'l
O"9OCltiu
I Te ,l'\:!tall tJ1e tll~ did"Tilol:s', did'R.un on 1llrgetHMd"'Me'. aro dld:'lnSli3~ 5uwmt radage",'.
I Hiiif~ilIrl! Implemel\tiitioo Target MIlrdware RleCUoo
! Mod.1 RvI.,.ncin
h..-dv,,,,,,,, [!Y'~rr'f ~,_.
i " S'mulat!Otl Taln,et
i ll:un on 1.1'9.1 Hmfw.t'l'
r"9"1
i
I
Click OK button.
Fill Host name, User name and Password for your Raspberry Pi device.
You ean do eheeked Enable ExternaI mode and Enable overrun deteetion.
Now baek to your Simulink. Change Normal to ExternaI, shown in Figure below.
~ lGl~
S ~helloworld
~
~"
=t
SineWsw RASPBERRYPI
"i,'t;'l
~
@
led{) (Gfeen)
boolean
LED
Data Type Convers ian
To deploy and run on Raspberry Pi, click menu Tools -> Run on Target Hardware -> Run .
Ilysis Cede Help
---,
Library Brewser
Medel Explerer
You also obtain a console dialog to show that simulation process was dane.
What's happened?
Basically Matlab sent and deployed this program to Raspberry Pi and then executed it.
You can check your Raspberry Pi using SSH. You wiII obtain our progran, helloworld, that has deployed.
pi @raspberrypi-AKUR: ~/helloworldJtt/MW
4. Simulink with Raspberry Pi GPIO
4.1 GPIO
General Purpose Input/Output (GPIO) is a flexible software-controlled digital signal. You can define input/output easily.
Further information about GPIO, you can read it on http://en.wikipedia.org/wiki/GPIO.
,;
I 3.3 V 6V
12CO_SDA 5V
12CO_SCL GND
GPI04 UARTO_TXD
GND UARTO~XD
GPIO 17 GPIO 18
PCM_DIN GND
GPIO 22 GPIO 23
3.3 V GPIO 24
SPlO_MOSI GND
SPlO_SCLK SPlO_CEO_N
GND SPlO_CE1_N
When I wrote this book, there are two Raspberry Pi revision types, revision 1 and 2. Basically, it's not big changes. How do
you know Raspberry Pi revision?
You can know what your Raspberry Pi revision by typing this script on terminal.
I cat Iproc/cpuinfo
Here is a guideline:
For input/output GPIO programming, I recommend to use unused GPIO pins, for instance, pin 4,17, 18,22,23,24.
4.2 Preparation
We hava two scenarios to explore Simulink Raspberry Pi with GPIO. The first scenario is to work with GPIO Write. We
use 3 LED connected to Pi GPIO 4,17,18.
The second scenario is to work with GPIO Read. Basically you can use digital sensor devices to connect Pi GPIO. If you
use analog sensor devices, you should ADC or additional analog component to convert to digital values. To simplify the sec-
ond scenario, I use Arduino to produce digital values for Pi GPIO inputs.
LED
Notes:
RASPBERRYPI
++
boolesn nn
Sine W sve Data Type CooW1Sion
GPI04
GPIO 4Wrile
RASPBERRYPI
Logicsl
Sccpe
Operalof nn
GPIO 17
GPI017Wrile
RASPBERRYPI
nn
Logcsl GPIO 18
Opaator1 GPIO 18 Wrile
Notes:
We use 3 GPIO Write. Configure them for GPIO 4,17, and 18.
Sink Blocl< P
GPIO Write (mask)
Select the GPIO number. Do not assign the same GPIO number to
multiple blocks within a mode!.
Parameters
Board: I B Rev2
GPIO number:
OK
Parameters
Amplitude:
Bias:
Sample time:
<
4.3.2 Testing
Now you can run this model on Raspberry Pi device. Please read section 3.3 for deploying and running on Raspberry Pi de-
vice.
If success, you will obtain a console dialogo Here is a sample output for console.
c:\Windows\SYSTEM32\cmd.exe
You also see the LEDs will turn on and off on a certain time.
.."
.. '"' .....
G
File
Toid setup () {
1/ initlali:e the digital pin as ~l output.
pinJlode(out1, OUTPUT);
pinUode(out2,OUTPUT);
Joid loop () {
digital~Lite(out1, HIGH);
digitalULite(out2, HIGH);
de1ay(lOOO); Ii wait fOL a second
digitalWLite(out1, HIGH);
digitaHhit.e(out2, LOlJ);
delay(lOOO); Ii wait fOL a second
digita1ULite(out1, LO~);
digita1~Lite(out2, HIGH);
de1ay(lOOO); // wait fOL a second
< >
void setup() {
1,1 nitialze ~he
'- dl'gl't~.L'Pl'11
c. lS an ou t_pu t, ,
c.
pinMode(outl, OUTPUT);
pinMode(out2, OUTPUT);
}
void loop() {
digitalWrite(outl, HIGH);
digitalWrite(out2, HIGH);
delay(1000); II wait for a second
digitalWrite(outl, HIGH);
digitalWrite(out2, LOW);
delay(lOOO) ; Ii wait for a second
digitalWrte(outl, LOW);
digitalWrite(out2, HIGH);
delay(lOOO); I I wait for a second
Note:
El
.~
:.+ :
RASPBERRYPI
~""
=t
nn
GPIO 18 Scope
GPI018 Read
~
D
RASPBERRYPI
Sccpe1
nn
GPIO 17
GPIO 17 Read
Notes:
Configure GPIO Read using GPIO 17 and 18. For Sample Time, you assign 0.1.
Parameters
GPIO number: 17
Try to open Scope library. You will see the response output as below.
Scope
This chapter explains how to work with Video Capture using Raspberry Pi and Matlab Simulink.
5.1 Preparation
Matlab Simulink provides library, called V4L2 Video Capture, to capture live video. For Raspberry Pi target, you can see it
on toolbox.
RASPBERRYPI Y
,..-.-,
(e). Cb
c::.j
V 4L2 Video Capture
For a list ofUVC cameras supported by Ubuntu and Raspberry Pi, you can visit http://www.ideasonboard.org/uvc/ .
Let's buld a smulnk. Run your Matlab and create a simulnk. In this scenaro, we use V4L2 Vdeo Capture and Display.
If you have a Compute r Vson System Toolbox, you can use To Video Dsplay, http://www.mathworks.com/help/vision/
ref/tovideodisplay.html , to show lve video.
1
1-
DisplsyR
RASPBERRYPIR
1".'.,
eJ G Displsy G
'r-'i B
V4l2VideoCaptLIe
Notes:
Double clck V4L2 Vdeo Capture. Then you obtan a dialog, shown n Fgure below.
Source Block Parameters: V4L2 Vdeo Capture
V4L2 Video Capture (mask) (link)
Set Image size parameter to the desired output size. Use Pixel format
parameter to specify the format of the output vdeo stream.
Parameters
Device name:
1'[dev[videoo'l I
Image size: ~_2 __
0 -:J
Pixel format: ~IR_G_B :J
Sample time:
Change value on Device name, for instance, '/dev/videoO'. For pixel format, change to RGB.
5.3 Testing
Now you can test it on Raspberry Pio
Board information
Host name:
User name:
PassNord: ~~_~~~~:~_=:-~___
__..._~-..-..-.-.----..._-----.---------.----:-=~=_
Build direetory: [2~~_~_~Le-~==:_-:_::~:::::::==~===:.:=::_~-:=====--=_:~:==
File Edit View Display Diagram Simulation Analysis Code Tools Help
i
IT:l
0~
~ .. si
~IG)
@,
\
. I ~J T ii:-- J ...
i
Model Browser
videodemo
Now click menu Tools -> Run on Target Hardware -> Run.
S ~videodemo
'~:
-~ I 6911 7311 70 I'
ri
1
li<1i1
~
6311 6711 6411
I 6311 7211 731!
RASP8ERRYPIR
---,
(0)
I 6411 7211 73111:'
t.........
, G '- -Drs~ayR
B -
I-
I 10211 1031C
V4L2 Video Ca(iure
.. I 9611 971C=
I 9811 9slC
L ______
.____
.__.__m_~~JI ___m______
._.m_________
m~~Jc=_-
DsplayG
If you have question related to this book, please contact me at aguskur@hotmail.com . My blog: http://
blog.aguskurniawan.net.