Getting Started with Matlab Simulink and Raspberry Pi Agus Kurniawan 1st Edition, 2013 ISBN: 978-1-300-95391-3 Copyright
@
2013 Agus Kurniawan
Table of Contents
Preface 1. Introduction to Raspberry Pi 1.1 Raspberry Pi 1.2Getting 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 3.1 Helio World 3.2 Creating Raspberrv Pi Simulink 3.2.1 Configuring Raspberry Pi LED 3.2.2 Configuring Data Type Conversion 3.2.3 Configuring Sine Wave 3.3 Running Simulink 4. Simulink with Raspberry Pi GPIO 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.2 Building Simulink Model 4.4.3 Testing 5. Simulink and Video Capture S.l
Prcparation
5.2 Creating Simulink S.3Testing Contact
Preface
This book was written to help anyone wants to get starte d in Raspberry Pi and Matlab Simulink. It descri bes alI the basic elements of the Raspberry Pi and Matlab Simulink with step-by-step approach.
Agus Kurniawan Berlin, April 2013
I. Introduction to Raspberry Pi
1.1 Raspberry Pi The Ras pberry
Pi is a small size computer
timedia or run an app lication. berry Pi:
(85.60mm x 56mm x 21mm) with completed features so that you can play mul -
This dev ice is developed by the Raspberry
Pi Foundation
in UK. The re ara two type of Ra sp-
• Model A with 256 Mb RAM • Model B with 512 Mb RAM 111efollowing is technical specification • SoC Broadcom
Pi device:
BCM2835 (CPU, GPU, OSP, SORAM)
• CPU: 700 MHz ARMI176JZF-S • GPU: Broadcom
of Raspberry
VideoCore
core (AR Mll
family)
IV, OpenGL ES 2.0, 1080p30
h.264/MPEG-4
• Memory (SORAM): 512 Megabytes (MiB) • Video outputs: Composite
RCA, HOM I
• Audio outputs: 3.5 mm jack, HOMI • Onboard storage: SO, MMC, SOlO card slot • 10/100 Ether net RJ45 onboard
network
• Storage via SOl MMCI SOlO card slot You can see Ras pberry
Pi device with model B on the Figure below.
AVC high-profile
decoder
SPBER Y PI MO DEL B R C A V ID E O
A U D IO
POWER ~
(source: http://www.raspberrypi.org/wp-content/uploads/20 For further information,
11/07 /RaspiModelB.png)
you can visit on Ras pberry Pi, http://www.raspberrypi.org.
1.2 Getting Hardware How to get Ras pberry
Pi device?
Officially you can buy it from the official distributor • 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 buy ing Raspberry
Pi device and found that there are another options to buy
• lhe Pi Hut, http://thepihut.com • EXP- Tech, http://www.exp-tech.de/Mainboards/raspberry-pi.htm1 • Cooking -hack, http://w •••• w.cooking-hacks.com/index. • Amazon, http://www.amazon.com • Ebay, http://www.ebay.com
php/ shoplraspberry
-pi.htm1
2. Matlab Simulink and Raspberry Pi
This chapter explains how to work with MatIab Simulink and Raspb erry
Pi Software.
2.1 Matlab You can wor k with MatIab Simulink with targeting on Ras pberry work with MatIab lOBa Student Version.
Pi using MatIab lOBa or the Iat est version. You aIso can
(""l'e"~ fOl\)
I, J
U,fflt ~
li.'S"O C.j)
7.:~Gt)
7."'~O
"
$ ••
óD'
H~ OO
S. fOr:;:)
(l\}O
7. ?'O,;,
..
,
~.
~
~~?)(!O
2.2 Inst alling Raspberry Pi for Simu link Target Firstly, you prepa re to provide SD card devices. I use SanDisk SDHC 4 GB.
Insert this card into your computer.
Now you are ready to install Raspberry download Raspberry Pi paekage.
Pi and MatIab Simulink for Raspberry
Run your Matlab and then cliek Add -Ons.
Pi. You also need internet eonneetion
to
You ean see t he menu as below. Searc h
DoclJment ati on
P
Get More Apps Get Apps from File Exchange Get Hardware 5upport Packages Find and install hardware support packages Value
M in
Purchase MathWorks Produds Visit Web Store
Seleet Get Har dware
Support
Packages.
Then you will o btain a dialog, ealled Suppo rt
Package Installer.
Support Package Insta ler Install or update support package Where do you want to instaI!or update from?
@ Internet (recommended) O Folder
c: V'1ATLAB \$upportPackages \f'.20 130¥:lownioads
Seleet Internet
(recommended).
After that, cliek Next button.
8rowse...
Support Package Installer
~ Select a support
-
1
package
Select a support package to install or update. Action
D Reinstall
1
D
3
5
:-...
Required Base Produd
3,0
3.0
1.0
8
D Install
10 ~ 11
PandaBoard ",
Raspberry Pi
'.
USRP{ RJR.adio
Imtall
Digilent Analog Discovery A.n310gDevices DSPs
Install
Green Htlls r.."ULTI
Install
l~ Install
Xilinx Zynq-7000
Installation fulder:
~
Windows 132-bit),\
Simulink Simulink
3.0
---
3,0
1.1.1
.'
Simulink
1.0 5.0
Windows (32-bit),\
-
Simulink ~oo
,
L-J
i
Windows 132-bit),\
Simulink
,-
' Simulink
3.0
LEGO MINDSTORMSNXT
Install
7
9
Supported Ho st PI
I
Gumstix Overo
D Install .
6 ~
Installed lates1 Version Version
Windows (32-bit),\ Install
D Install
4
--
Arduino
BeagleBoard D Install
2
'/
Support Package for
V.lindows 132-bit),\ "
'" " " " "
Windows 132-bit),\ ,
,
Communicatíons System Toolbox
"
Windows (32-bitl,\ Windows 132-bit),\
Data Acquisition Toolbox
r
2.0
Embedded Coder
Windows (32-bitl,\
3.0
Embedded Coder
Windows 132-bitl,\
1.0
Embedded Coder
Windows (32-bit),\
.,
I C:Vv\ATLAB\5upportPackages~20 13a
-
I[
Wh y are some rows disabled?
I
Find more supported hardware
Check Raspberry
Pi and then click Next button.
You wil see a license agreement
as below.
I
Next>
I[
Support MATH WOR KS
AUXI LlARY
SOF TWAR E
Package.l nstaHer
UCE NSE AGRE EME NT
IMP ORTA NT NOTI CE ================
RE AO TH E T ER MS ANO CON om ONS OF THI S MAT HWOR KS AUX IL IA RY SOF TWA RE LI CE NSE AGRE EMEN T (T HE " AGRE EMEN í) CARE FUL LY BEF ORE CHECK ING 1 ACCE Pr OR ACCE SSI NG MATE RIA LS (AS DE fI NED BEL OW).
THE SE
THI S AGRE EMEN T REP RES ENT S THE E NTI RE AGRE EME NT BET WEEN VOU (l HE LI CENS EE ") ANO THE MAT HWOR KS, IN C. fM ATH WORK S" ) CON CE RNI NG THE SOF TWA RE AND OOC UME NTA TI ON MADE AVAILABL E f OR ACCESS HEREUNOER (COLL ECTI VELY, THE 'MATER IALS" ). BY CHEC KING AGREEMENT.
1 ACCEP I
OR ACC ESS ING
THE SE MATER IAL S
I
VOU ACCEP T THE T ERMS OF THIS
1. DEFINmONS.
1. 1. Licensee' means vou, whether an individual or an entity, to whom MathWorks grants the License, and who is responsible for compl ying with the cont ractual obligations of the Lic ense, and ensuring that anyone permitted access to the Mater iais also complies with such obligations.
1.2. "Documentation" means the use r guides, if any, accompanying delivery of the Ma teriais, as may be up dated from time to time, as 'Neli as any repo rts or other reedback that MathWorks may, in it s sol e disaetion, provide to Licensee. Documentation may be de livered in printed and/or online form s, and in one or more languages.
~
I accept Next
Cheeked I accept. If done, cliek Next button.
>
II
Cancel
I!
Help
Support Pack:ageInstal ler Thi rd- par ty
softwa re lice nse s
Vou h ave chos en to instaU S imuli nk Suppo rt Pack. age for Raspberry
Pi Hardwa re.
Softw are Vl'illbe ins tall ed from the foll owing loca tion s: SDl
http://wVl'w.libsdl.org
Iicense
Wget for Wind ows
http:/ /gnuwin32.sourcef orge.net/pack. ages/wget.htm
Iicense
]-zip
http://www.]-zip.org
Iicense
This util ity enabl es Vou to download and instal l the third part y soft 1Nare listed above. This list may contain open source softwar e, indud ing soft ware licensed und er the terms of th e General Pub Jicl icen se. By dic king 1nst aU" on the next scr een, vou will be do wnload íng and insta Jling the soft1l 1'ar elisted above. By di cking 'Canc el", you will not downlo ad or inst all the softwa re.
<
Click Next button.
Back
II
Next
>
II
CanceJ
II
Help
Support
Package I nstal ler
Confirm installation
Vou have chose n to inst all Simul ink Su ppor t Packa ge for Raspber ry Pi Hard war e in C: V"'1ATLAB\SupportPackagesljUO 13a.
< Back
Click
InstaU
button.
It will download
Raspberry
Pi package and then instal1 it.
If success, you wül obtain a dialog as beIow.
Install
Cancel
CI
Support Package Installer IMtal/update
complete
Simulink Support Package for Raspb erry
Pi Hardware
has been succe ssfully installed.
To ensure compatibility with Simulink, you may need to update the firm ware for the sele cted support package hardware. Select -Continue- to update firmware now. Select -Close- to exit this utility.
I Click
Continuebutton.
Continue>
I
~ - = = --J
Help
Update firmware
Choose a hard'Nare to start the firmware update processo Hardware:
J
aS):>~~~~Y~i .••.•
Help
Click Next buttol1.
Suppor t Packag e Instal ler
D
Se lec t a boar d
The firmware update process for Ras pberry Pi hardware consists of copying a Raspbian Wheezy Linux image onto a memory cardo We will guide you throu gh this processo Select your board to get started: Board:
I
Model B
.1
<
----_._----
<
Choose Raspberr y Pi board. Then click
Next
button.
Bacl<
II
Next
>
II
Cancel
>
Support Package Installer Get f irmware
Where do you want
to get the firmware from?
@
Dovmload from Internet
O
Get from local folde r
Download folder:
(recommended)
IC ; \M Ã T L A B \S ~ ;;; ;~ ~ tp ~ ~ ~ ~ ~ ~ 2 0 1 & ;\ ;j~ ;;~ ~.. I~..m~ld ~Browse \m •..
WARNING: Download size is approxímately Download may take sever al mínutes.
Choose Download
from Internet
If done, click Download
1GB.
(recommended).
button.
If download process is done, you will see a dialog as below.
D
Cl
Support Package Installer Configure board The board .\lilI be configured
with the foil owing name and IP settings:
Board name: 'raspberrypi-AKUR l . . . _ . . _ . _ . . _
Configure IP settings for wired Ethernet
. .. . . .. . _ . . . _ . . . _ . . _ . . . .
connection
]
_
More inf o
IP Assignment
•
Automatica!ly
get IP aderess
ManuaDy enter IP address IP Settings
IP address:
10.10.10.9
Network mask: Default gateway:
255.255.255.0 10.10.10.1
< Back
<
F ilI hostname for Raspberry P io
Next>
Cancel
Support Packag e lnst aller 5elect a drive
Insert a 4 GB or larger SD memory card into a memory card reader on the host compu ter. Select the driv e letter that corresponds Drive:
I D:
~!
I
to the memory card reader:
RelTesh
If you do not find the memory card reader in the list of dr ives, 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 Then click Next button.
Back
II
Next
>
CancE
Support Package Installer Write firmwa re
Vou chos e to wri te to dri ve D:. The wri te ope ration may tak e sev era
I,
(-
WARNING: Ali data in the memory
I minutes.
card will be erased!
Cana
Click
Write
button to start to write Raspberry
If done, you will see the dialog as below.
Pi image to SD cardo
Support Package Installer Connect lhe Raspberry PíHardware Instructions 1. Remove the 50 mem ory eard ITom the h computer and insert into the Rasp berry Pi I 2. Connect an Ethernet eable to the boar d the other end of the Eth ernet eable to a n l directly to the host compu ter. 3. Connect a SV micro USS power supply te board. The pow er supply should be rat ed least 700 mA.
f
NOTE: Vou may conne ct optional periphera as a monitor, keyboard, etc. at thís ti me.
Power cable
Ethernet connectíon
Make sure that the 'PWR' LED is solid red a the 'OK' LED indícating 50 card activíty starts blinking. Then, dick 'Next ' to continu
<
Plug out SD card from compu ter. Then, plug in it into Raspberry
Now turn on your Raspberry
Pio Read section 2.3.
Pi
Saci<
II
Next
>
II
CancE
You ma y configure After Raspberry
your Raspberry
Pi i s running
Pi for in stance
well, cIi ck Next
SSH. You
c an read it on sec tion
2.4.
button. Th en you will s ee a dialog as below.
Support Package Installer Con firm boar d configur ati on
If y ou want to log in to the board in the fut ure, the host name or I P addr ess, user name , and passwo rd are displa yed below. Vou may also type "raspb errypi " on the MATLAB command window to obtain this information. Host name :
raspber rypi -AKUR
User name:
pí
Pas swor d:
raspber ry
NOTE:
1. YourRaspbe rry Pihardwar e will speak its IP addr ess thr ough the anal og audí o conn ect or when it boots. 2. Voucan configu re your Raspberr y Pi hardwar e to automati cally send an e-mail when IP address changes. Click' Help' for det ailed instr uctions .
<
Cli ck Nex t but ton
Support Package l nstal ler Firm ware upda te comple te
You have successf u!ly updated ~
Click
YOUf
nrmware.
Sho w su ppo rt pac kag e exa mpl es
Finish
button.
You will see the new dialog as below.
Help
+
1
.
i
I
~
i
~
Simulink Support Package for Raspberry Pi Hardware EXAMPLES SimulinkG) lets you design aM run models on Raspberry Pi@hard ware. With this capability. you can assess algorithms in the cla ssroom or lab as they execute in real-time on Raspberry Pi hardware with physicallJO.
I
anã optimize
Product page at mathw(
i i
I
i
I
I 1
:
!
Getting Started with Raspberry Pi Hardware
!
I!tl ModE
~ ~
I
~
i
...-..f~
i
•
~
~ -"rQ:] »
1
~
II
t
F~~'J :
I~ ~'I •
Now you see Raspberry
.~
I~l
r:T w I ~ ~ ]
Communicating
with Raspberry Pi Hardware
.
Pi on Simulink Library Browser.
I!tl ModE
liI fil'
Simulink library Browser
File
Edit
View »
Help
I Enter
search term
__ .J
Libraries
Simulink Com mon ly Use d Bl ocks Continuous Discontinuities Discrete
[ ;>
t>
I :t
t> c,
t>
Library: Simulink Support Package for Ras pberry
ALSAAudio Capture
J'.'
~ .rtr.
Logic and Bit Operat ions Look up Tabl es Math Operat ions Model Verif icat ion Model -Wide Utilities Ports & Subsystems Signal Attri butes Signal Routing Sinks Sources User- Define d Fundiom Addit ion al Math & Discrete Cont rol System Tool box DSP Syste m Toolbox Data Ac quisition Tool box
~
LEO
-rn 1 _
UOP Reoeive
V4L2Video CaptUTe
GPIOWrite
G
SOLVídeo Displsy
~
"'.:.,c:: •••.
_
.rtr. - t - ..: .~
"q r CO -410
ALSAAudio PIsybaO:
PIO G Read
='""':~
Pi Hardware
~
~:-'~I
~ •• '1.
~
SemiUDP
IExsmples
Text to ,',f~ I eSpes.' Speech
Instrumen t Cont rol Toolb ox Simuli nk 3D Animati on Sim ulink Code r Sim ulink Cont rol Desi gn Simuli nk Extra s Simul ink Su ort Packa e for Ard uino Har dwa re
Showing:
Simulink Supp ort Package for Rasp berry
Pi Hardware
2.3 Ru nning Raspberry Pi Now you are ready to boot your Raspberry cable. into Raspberry
Pio
Pi. Please plug in alI devices, for instance, mouse, keyboard,
power, and HDMI
~
Turn on th e power for your Raspberry
Pi.
If success, you will get the first screen of Raspberry
Try to configure your Raspberry
Pi as below
Pi, for instance, timezone and keyboard.
If done, push Finish menu. You will get Rasp berry
Pi console shown in Figure below.
Enter username:
pi and pass word: raspberry
Then, you will get the Raspberry
terminal.
To work with Desktop GUI, you can type
I
startx
2.4 SSH You may need SSH to manage Raspberry
I $ sudo
apt - get
i nst al l
Pi remotely. How to instam You can write his scri pt
ssh
To start a service, try to write this script
I
$ su do / et c/ i ni t . d/ ssh
st ar t
Sometimes, you want to mn SSH service every booting. Try to update update-rc.d
I $ sudo
updat e- r c. d ssh def aul t s
and then reb oot your Raspberry
I $ sudo
Pi
r eboot
For testing, I used PuTTY application Fill IP Address of Raspberry
Categ.ory:
r
~ ..Session Logging
in Windows 8 to remote Raspberry Pi via SSH.
Pi and then c1ick Open button.
PuTTY
L .. .
Configuration
_
I
_ _
1
Basic options for your Pu
TTsession Y
.
Specify the desti nation you wan t to connect to
~. Terrninal
!!
Keyboard
BeU
1192.168.1.61
L .. .
Features
Connection
a"Window
!. . . Appearance . j . • . • Behaviour
!
Translation
i
Selection
L .. . Colours Connection 8 ..
I
Data
!
Telnet
!
RJogin
! Proxy
ctl'
I~~
Host li ame (oraddress) IP
O Ra~
~fo_rt
_
type:
O Ielnet
O RJog[n
O SeDal
@âSH
Load. save or delete a stored session Saved Sessions I~~;b~ ;;; ;pi.. ... ... ... ... ..
..1
Default Settings Mac Mini akurdb .doudapp .net raspbenypi
SSH
L . . . Serial
Oose •••• 'indow on exit:
O A1ways
~out
file
O N-ever
@ On ly on dean ex it
If connected,
you will get a secuity alerto
PuTIY Security Alert The serv er's host key is not cached in the registry. Vou have no guara ntee that the serve r is the com puter you think it is. The server's rsa2 key fingerprint is: ssh-rsa 2048 cb:51:78:65:d6:98:82:be:dd:e9:3b:b6:05:e7:99:el Ifyou trust this host, hit Ves to add the key to PuTTY's cache and carry on connecti ng. Ifyou want to carry on con necting just once, without adding the key to the cache, hit No. Ifyou do not trus t this host, hit Cancel to aban don the connection.
Click Yes button. Entry username
and password.
rf success, you will get Raspb erry
Pi console.
3. He lIo World - Matlab Simulink and Raspberry Pi
In this chapter we create as simple Matlab Simulink with Raspberry Pi.
3.1 HelIo World We are going to build a simple Matlab Simulink with Raspberry Pi, called Hello World. In th is scenario, we work with LED on Ras pberry
Pi. Try to tur n on and off from our model.
If you see Mat lab Simulink Library on Rasp berry
Pi library, you can sce
LED
library. We will use this library on our mod-
cl. D
5imulink library Browser Help
I Enter
search term Library: Simulink Supp ort Package for Rasp berry
5imulink Comm onl y Use d Blocks Continuous Discontinuities Discrete Logi c and Bit Opera tions Look up Tabl es Math Opera tions Model Verificat ion Model - Nide Uti lities Ports & 5ubsystems Signal Attribut es 5ign al Rout ing Sinks Sources User -Def ined Funct ions (>
ALSAAu
GPIO Read
"@
Simulink Supp ort Package for Raspberry
'"~''' G:J n r.
-.
-"
~ ~
UDP Reoeive
V4L2Video
Capture
eSpes, Text t o
Pi Hardware
Speech
GPIOWrite
••
. . ' . ~ , ~ . [!:J rn LEO
••: c ••.
Additional Mat h & Discrete Cont rol Syst em Tool box DSP 5 yst em Tool box Data Acqui sition Tool box Ins trume nt Con trol Too lbox 5imul ink 3D Animat ion Simul ink Coder 5imul ink Contr ol Desi gn Simul ink Extr as 5imul ink Su ort Pa ck a e for Arduino Ha rdwa re
Showing:
ALSAAudio Playbadt:
C~
CD""-.'~
Pi Hardware
r::::::I
L:::-J
SOL Video Oisplay
UDP Seno
[Examples)
3.2 Creati ng Raspberry Pi Simulink Now we are ready to build
a "helIo world" Matlab Simulink with Raspberry Pio FolIowalI steps.
Firstly run your Matlab 20Ba or th e latest version. On Home , click + New icon. Then you will obtain a menu as below.
PLOTS
HOME
APPS
Compare Import Data
Agus
Example Class
System Object
ij
Figure Graphical User Interface Command Shortcut SIMUlINK ~
Simulink Model
L : : I Simulink Select
Project
~ Documents
~ rv 1 0
Function
~
Save Workspace
Ctrl-N
Script
D
-
~
Find Files
}
SimulinkModel.
Then you obtain a Simulink dialog as below.
untitled
File
Edit
View
Display
Diagram
Simulation
An alysis
Code
Tools
He lp Nor mal
•• •.
Model BrO'Nser untitled
«
Ready
100%
Next step, we build a simulink model. On the Sim ulik Model dialog, click menu Tools
am
Simulation ....
Analysis
Code
-> Library
Browser.
Help Libr ary Brows er
~ ~
Model Explo rer Run on Targe t Hardwa re
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 Enter search term
>
Library: Simulink Suppo rt Package for Rasp berry
Simulink Com mon ly Use d Bl ock s Continuous Discontinuities Discrete
ALSAAudio
Logi c and Bit Oper ations Looku p Tabl es Math Operat ions Model Verif icati on Model -Wid e Util ities Ports & Subsystems Signal Attri butes Signal Routing Sinks Sources User- Define d Functi ons & Discrete c ' Addi tional Math Cont rol Sys tem Tool box DSP Sy stem Tool box Data Acqui sition Tool box
Pi Hardware
Capture
ALSAAudio Playbact
GPIORead
GPIOWrite
SOL Vidao
LEO
Oisplay
UOP ReceivE-
~ ~
V4L2Video
I ~ : :-;~ ; I
CapturE-
UOP Send
!ExampI6}
eSpeak Texl to Speec:h
Instrument Cont rol Tool box Simulin k 3D Animatio n Simu link Code r Sim ulink Cont rol Desi gn Simu link Extr as Simulink Su ort Pac ka e for Arduino Ha rdwa re
For our scenario,
helio world, we cr eate a simulink as below.
Model Browser t o a . . helloworld
f R " ;iI
~
RASPBERRYPI
SineWsve
""1' .•••
fi:l1 ledO (Green) _lIDo_lea_o
~
Data Type Coowrsion
LEO
L:
You need three libraries as follows • LED on Sim ulink Support Package for Raspberry Pi Hardware • Data Type Con version • Sine Wave on Sources
After all ite ms connected,
on Commonly
Used Blocks
we configure these.
3.2.1 Configuring Raspberry Pi LED To configure Raspberry
Pi LED, double-click
LED on modeI. lhen you obtain a dialog as below
Sink Block Parameters:
lE D
LEDWrite (mask) Turns an LEDon or off. Select the desir ed LEDfrom the drop-down menu. Do not use the same LEDin multi pie block s within a model. Parameters [
Board:
1 .~ .~ .9 .~....~..... .I ~ey~
LED:
IledO (Green)
__
o_K__
.• .i
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . • . . . . . . . . . . . . . . .!
.•
View LEDlocation
• • ......................• .........• .............
1 !
11
Cancel
Select Board and LED. If finished, click OK but ton. You aIso can clic k View LED loca tion
button to view LED p osition.
Apply
Model
File
O~
Edit
View
Insert
T
0015
B Rev2 L ED loca tions
De sktop
Wi ndow
He lp
r-
3.2.2 Configuri ng Data Type Conversion Double click on Data Type Conversion so you obtain a dialog as below
Functíon Block Parameters: Data Type Conversíon Data Type Conversion Convert the input to the data type and scaling of the output . The conversion has two possible goals. One goal is to have th e 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 outp ut be equal. Overflows and quantization errors can prevent the goal from being fully achie ved. Parameters Output minimum:
Output maximum:
[1[---------] I
Output data boolean type:
I
v
i
»
O Lock output data type setting against changes by the fixe d-point tools Input and outp ut to have equal:
~I
World value (RWV._)
Integer rounding mode: ~o~_n_d
O
.
._ = :J o :]
Saturate on integer overflow
Sample time (-1 for inherited):
__
Due to Raspberry
_11
O_K
Cancel
I [_
Help
Apply
Pi LED input needs boolean data type , you must select boolean
If done, c1ick OK button.
3.2.3 Configuring
Sine Wave
Double click Sine Wave, you will obtain a dialog as below.
on Output
data type.
Samples per period
=
2"'pi I (Frequency '" Sample time)
Number of offset samples
=
phase '" Samples per perio d I (2"'pi)
Use the sampl e-based sine type if numerical problems due to runnin g for large times (e.g. overflow in absolute time) occur. Parameters Sine type: Time (t): [U-;~.-;~I~ti~~--ti.~~;"-'._.'_
'- -. M .• _ .. -- -_
". _
-- _-- ..- -
------'-~ J
-- .. .. .. .. .. .. .. .. .. .. .. •. •• •
Amplitude:
Frequency (rad/sec):
~ Interpret veetor para meters as 1-0 OK
For testing, we use eonfigurations
Apply
as follows:
• Sine type: Time base • Time (t): Use simu lation • Amplitude:
time
1
• Bias: O • Frequeney:
1
• Phase: O • Sample time: 30 • Cheeked lnterpret
veetor parameters
as l-D
lf done, click OK button.
3.3 Running Simulink Save your model, for ins tanee, helloworld. You test and validate your model. Make sure you sclee t Normal.
Then, cliek Arrow, shown in Figure below.
helloworld nulation
Code
Tools
Help
d
Test and Valida te
helloworld
If success, you don't see the error dialogo Now you are ready to deploy to Raspberry To run this model to Raspberry to Run.
--
~._._-_.~---_.
I
••
_ _ ._ ---------------------------
.
...i~Library F ? ':!\
-> Run on Targ et Hardware
Pi, you must configure. How? Clic k menu Tools
Code Tools L~lp_ >
Pi and run it.
,
Browser
Model Expl orer
~
Run on Target Ha rdw are
---:
~
Prepar e to Run ... Install/Up dat e
Supp ort Package .
Updat e Firmwar e ...
lhen you will obtain a dialog as below.
í S,~tt: I
j
Th ••
So~r
i
OAU ~'f>port
!
I'
I
Oí"9OCltiu
I Te ,l'\:!tall
! " Optjmlratiol'l
Implemel\tiitioo
H ii if~ilIrl!
!
Mod.1 RvI•.,.ncinç
i"
ll:un on 1.1'9 .1
i
S'mulat!Otl Taln,et
" ,." " 1
y1ltIf
Hmfw.t'l'
is " " I
" " I to um
""y Lo,gd h.,dw.'e.
hilr ""'lt' e 15 t\ó t Ii:!tf !d ¥ll Íle tJ1etll~
Target M Ilrdwar e
did"Tilol:s', did'R .un RleCUoo
r"9"1 h . . - d v , , , , , , , [!Y'~rr'f ~,_.
i
I
Select Ras pberry
Pi on Target hardware.
Click OK button. After that, you will see Ras pberry
Set ll1<>"Torgol
'Th' get har< hvar e'
Pi configuration.
" " " Ih " " " , '
porilltlld"
opti oos, íl'\:!t lll l the IlI fget
on 1llrgetHMd"'Me'. aro dld:'lnSli3~
foI'
tó miOlâl rou' lorgol
" " "4 • .•"
VOUf hat'
radage",'.
->
Prepare
úmfíguratíon T• • • .9 1 " 1
Parametefs:
ootit1e d/Run an l:'.artlwar~ CtlnJigur a
f,AdiW)
r n . , d ' ' 1 1 I ~ " '"
D.t3 Op(,mllauon Diagntmits
5i9O mo tonng
H••dw••" Impl•••••nLll>On
O EM
MQdellt~lerenong " Sómu Run
Otl
Ovtrrun d
'9ft
'9tt
H
Óftotrt
C [na
ond pcn:m
em.1
tu~
modq
l!àlOn
av.e'1\#lde~et1
Fill Host name, User name and Pass word for your Raspberry Pi device. Note: You ean define hostname's
Raspberry Pi or its IP Address.
You ean do ehe eked Enable ExternaI mode and Enable overrun deteetion. If done, click OK button. Now baek to your Simulink. Change Normal to ExternaI, shown in Figure below. Simul ation
Ana lysis
Code
lools
Help
· ~ lG l~ S
~helloworld
~ ~" =t RASPBERRYPI
SineWsw
"i,'t;'l
~
@
led{) (Gfeen) boolean
LED
Data Type Convers ian
To deploy and run on Rasp berry Pi, click menu Tools -> Run on Target Hardware
-> Run .
Ilysis
Cede
Help ---,
Libr ary Brewse r Medel
Exple rer
Run on Targe t Har dwar e
Ru n Optio ns ... Inst all/Updat e
Suppor t Pacl cage .
Upda te Fir mwar e ...
If process is success, you will see the LED is bl inked.
You also obtain a console dialog to show that simulation
process was dane.
What's happened? Basically Matlab sent and deployed this pro gram 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
111ischapter explains how to program
simulink using Raspberry Pi GPIO
4.1 GPIO General Purpose Input/Output
(GPIO) is a flexible software-controlled
digital signal. You can define input/output
Further information
about GPIO, you can rea d it on http://en.wikipedia.org/wiki/GPIO.
Based on Rasp berry
Pi specification,
you can see Raspberry
easily.
Pi GPIO as below.
, ; /
3.3V
I
12CO_SDA
5V
12CO_SCL
GND
GPI04 GN D GPIO 17 PCM_DIN
When I wrote this boo k, there are two Ras pberry you know Raspberry
cat
UARTO_TXD UARTO~XD GPIO 18 GND
GPIO 22
GPIO 23
3.3 V
GPIO 24
SPlO_MOSI
GN D
SPl O_ ISO
GPIO 25
SPlO_SCLK
SPlO_CEO_N
GN D
SPlO_CE1_N
Pi revision types, revision
1 and
Pi revision?
You can kno w what your Raspberry
I
6V
Pi revision by typing this scri pt on ter minal.
Iproc/cpuinfo
For inst ance, my Ras pberry
has a response as below.
2. Basically, it's not big changes. How do
Ifyou can see, I have Revision ooof. It mea ns my Raspberry
Pi is model B with 512MB and revision 15.
Here is a guideline: • Revision 0004, 0005, 006 ..000f is Raspberry
Pi Model B revision 2
• Revision 0003 is Raspberry
Pi B Revision 1
+
• Revision 0002 is Raspberry
Pi B Revision 1
For input/output
GPIO programming,
I recommend
ECNOOOl
to use unused GPIO pins, for instance, pin 4,1 7, 18,22,23,24.
4.2 Preparation We hava two scenarios to explore Simulink Raspberry use 3 LED connected to Pi GPIO 4,17,18.
Pi with GPIO. The first scenario is to work with GPIO Write. We
The second scenario is to work with GPIO Read. Basically you can use dig ital sensor devices to connect Pi GPIO. If you use analog sensor devices, you should ADC or additional analog component ond scenario, I use Arduino to produce digital values for Pi GPIO inputs. YOll
also need some cables (famale-male)
and a breadboard.
to convert to digital values. To simplify the sec-
Another option, you can buy Raspberry Pi GPIO kit, for instance, Adafruit Pi Cobbler Breakout Kit for Raspberry ther information about this pro duct, you can rea d it on http://adafruit.com/products/914 .
4.3 Sim ulink with GPIO Writ e In this secti on, we're going to a simulink mo dei with Raspberry The following is a LED circuit which is connected
to GPIO.
Pi GPIO Write and LED.
Pi. Fur-
3300
LED
Notes: • LED 1 connect to GP IO 4 • LED 2 c onnect to GP IO 17 • LED 3 connect to GPIO 18
This is m y circuit for LED and Raspberry
Pi
Now we start to build a sirnulink rnodel.
4.3.1 Building Simulink Model Run your Matlab and crea te a Sirnulink Model. Try to build a rnodel as shown in Figure below.
RASPBERRYPI
n n
boolesn + +
Sine W sve
GPI04
Data Type CooW1Sion
GPIO4Wrile RASPBERRYPI Logicsl
n n
Operalof Sccpe
GPIO 17
GPI017Wrile
RASPBERRYPI
n n Logícsl
GPIO 18
Opaator1
GPIO 18Wrile
Notes: • GPIO Write on Simulink Support Package for Raspberry Pi Hardware • Data Type Con version on Com monly Used Bloc ks • Scope on Com monly
Used Blocks
• Logical Operator on Logic and Bit Operations • Sine Wave on Sources
We use 3 GPIO Write. Configure
them for GPIO 4,17, and 18.
Sink Blocl < P
GPIO Write (mask) Sets the logical value of a GPIO pin configured as output. 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
For Sin e Wave, you can configure it as below.
Source Blbck Paramete Number of offset samples
=
Phase '" Sample s per period I(2"'pi)
'"
Use the sample-based sine type if numer ical problems due to running for large time s (e.g. overflow in absolute time) occur. Parameters
'Y . _ I
Sine type: [j_~~~~ased
Time (t): [~se_~~m~ati~_~tim;
.
. _
Amplitude: 1
Bias:
Samples per period:
Number of offset samples:
Sample time:
~
Interpret vectar parameters as 1-0
<
Save this model, for instance, gpio_led.
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 device. 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 tur n on and off on a certain time.
.. "
. . '" ' . . . . .
4.4 Sim ulink with GPIO Read
The second scenarÍo we want to do is to read a GP IO input. In this ill ustration, we Arduino to generate digital outputs for Raspberry Pi. I used Arduino Uno R3 for testing.
4.4.1 Creating Applicati on for Arduino We use digital output 13 and 12 to produce digital values on Arduino. Open Arduino application and create a new application.
G F ile
i nt out 1 i nt out 2
13; 12;
Toid setup () { 1/ i ni t l al i : e t he di gi t al pi nJ l ode( out 1, OUTPUT) ; pi nUode( out 2, OUTPUT) ;
Joid
loop ()
pi n as
~l
out put .
{
di gi t al ~Li t e( out 1,
HI GH) ;
di gi t al ULi t e( out 2, de1ay( l OOO) ; di gi t al WLi t e( out 1, di gi t aHhi t . e( out 2, del ay( l OOO) ; di gi t a1ULi t e( out 1, di gi t a1~Li t e( out 2, de1ay(l OOO);
HI GH) ;
Ii
wai t
f OL a seco nd
Ii
wai t
f OL a seco nd
HI GH) ; LOl J ) ; LO~) ;
HI GH) ; / / wai t fOL a s ec ond
<
Write this code into your Arduino editor.
>
i nt out l - 13; i nt out2 12; voi d set up( ) { 1,1 í ni t i al í z e pi nMode( out l , pi nMode( out 2, } voi d l oop( )
~ t ~. L' Pl ' 11 ° l S '- he dl ' g l ' c. OUTPUT) ; OUTPUT) ;
c .
t an ou _pu ,t,
{
di gi t al Wr i t e( out l , di gi t al Wr i t e( out 2, del ay( 1000) ; di gi t al Wr i t e( out l , di gi t al Wr i t e( out 2, del ay( l OOO) ; di gi t al Wr í t e( out l , di gi t al Wr i t e( out 2, del ay( l OOO) ;
HI GH) ; HI GH) ; II
wai t f or a second
Ii
wai t f or a second
I I
wai t f or a sec ond
HI GH) ; LOW) ; LOW) ; HI GH) ;
Save this code into a file, called arduino_digit. Do verify and upload this application to Arduino board. If done, your Arduino is be connected to Raspberry Pi.
Note: • Arduino digital 13 is connected to Pi GPIO 17 • Arduino digital 12 is connected to Pi GPIO 18
4.4.2 Building Simulink ModeI Run your Matlab and ereate a simulink model. Build the model as below.
El
.~ :.+ :
RASPBERRYPI
~""
n n
=t
GPIO 18
Scope
GPI018 Read
~
D RASPBERRYPI Sccpe1
n n GPIO 17 GPIO 17 Read
Notes: • GPIO Read on Simulink Support Paekage for Raspberry Pi Hardware • Seope on Commonly Used Bloeks
Configure GPIO Read using GPIO 17 and 18. For Sample Time, you assi gn 0.1.
Source Block Parameters: GPIO 17 Read GPIO Read (mask) Reads the logical value of a GPIO pin configured as input. Select the GPIO number. Choose des ired internai resistor configuration. Do not assign the same GPIO number to multiple blocks within a model. Parameters Board:
I Model B Rev2
GPIO number:
17
Sample Time:
0.1
Save this model, ealled gpio_sensor.
.••.
1
[Viewpin mapl
4.4.3 Testing Now you can run it into Raspberry
Pi.
Try to op en Scope library. You will see the resp onse output as below.
Sc ope
You also obtain a console dialog for simulation
process notification.
5. S imulink and Video Capture
This cha pter explains how to work with Video Capture using Raspberry Pi and Matlab Simulink.
5.1 Preparation Matlab Simulink provides library, called V4L2 Vi deo Capture, to capture live video. For Raspberry on toolbox.
RASPBERRYPI
Pi target, you can see it
Y
,..-.-,
(e).
Cb
c::.j
V 4L2 Video Capture
Mathworks
has already testes som e cameras as follows:
• Logitech QuickCam
Pro 9000
• Logitech QuickCam
Pro 300 0
• Logitech Webcam C600 • Logitech HD Webcam C310 For a list ofUVC
cameras supported
by Ubuntu and Raspberry Pi, you can vi sit
In this scenario, I used Microsoft LifeCam VX-700.
After plug-in, you can execute this com mand
to Raspberry Pi console.
http://www.ideasonboard.org/uvc/
.
1
1SUSb
l s / dev/ vi deo*
If success, you will see your webcam usb. Míne ís Idev/videoO. Now you are ready to buíld a simulínk.
5.2 Creatin g Simulink Let's buíld a símulínk. Run your Matlab and create a simulínk. In this scenarío, we use V4L2 Vídeo Capture and Display. If you hav e a Compute r Vísíon System Toolbox, you can use To Video Dísplay, ref/tovideodisplay.html
http://www.mathworks.com/help/vision/
, to show líve video.
1
1
-
DisplsyR
RASPBERRYPI R 1 ".' .,
eJ
'r-'i
G
Displsy G
B
V4l2VideoCaptLIe
Notes: • V4L2 Vídeo Capture on Símulínk Support Package for Raspberry Pi Hardware • Display on Símulink->Sink
Double clíck V4L2 Víde o Capture. Then you obtaín a dialog, shown ín Fígure below.
Source Block Parameters: V4L2 Vídeo Capture V4L2 Video Capture (mask) (link) Captures video from a USBcamer a using V4L2 dri ver framework. During simu lation, the model outputs a moving colorbar image. While running on hardw are, the block outputs vídeo from a USB camera. Set Image size parameter to the desired output size. Use Pixel format parameter to specify the format of the output vídeo str eam. Parameters Device name:
I
1'[dev[videoo'l Image size: ~_ 2 Pixel format:
-:J :J
__0
~ I R_G_B
Sample time:
__
O_K
_11
Cancel
II
Help
J
Apply
Change value on Devic e name, for instance, '/dev/videoO'. For pixel format, change to RGB. If done, click OK but1on. Save this simulink.
5.3 Testing Now you can test it on Raspberry
Pio
Don't forget to change target hardware to Raspberry
Pi.
Confi gura tion Para meter s: videodemo/ Run
on Hardwar e C onfi
Target hardware seleetion
Select: Solver Data ImportjExport t > Optimization I > Diagnostics Hardware Implementation Model Referencing I > Simulation Target
Target hardware: ~~p~be_r_ry_p_i _~~~
__
~
_
Signal monit oring and parameter tuning ~
Enable Externai mode
TCP/IP port (102.4-65535):
Run on Target Hardware
1772.5
Overrun deteetion ~
Enable overrun detee tion
Board information Host name: User name:
Before running,
File
Edit
PassNord:
~ ~ _ ~ £ ~ ~ ~ : ~ _ = : - ~_. _. . _~ _- . .- . .-.-. - - - - . _. . - - - - - . - - - - - - - - - . - - - - : - = ~ = _
Build direetory:
[ 2 ~ ~ _ ~ _ ~ L e - ~ = = : _ - : _ : : ~ : : : : : : : = = ~ = = = : . : = : : _ ~ - : = = = = = - - = _ : ~: =
change Normal to Externai.
View
Display
Diagram
Simulation
An alysis i
TIl:
~
0~
.• .
s i @,
~IG)
\
i
Model Browser videodemo
Now click menu Tools -> Run on Target Hardware If success, you will see RGB value s on Display.
-> Run.
•.
Code
• I
Tools ~J
T
Help
iiõ:õ--
J
..•.
-, -vid-eo-de-m-o ----'--.-----.--------~------------------------------.
-.---.---------~-----
S ~videodemo '~:
6 911 6 311 63
I
-~
riI
li<1i1
~
RASP8ERRYPI R ---,
( 0 )
t......... ,
G B
70 6 4 11 731!
11
1
671 1 72
11
6411
I
11
I'
7 3 1 1 1 :'
7211
-D rs ~ a y R
'-
-
I -
V4L2 Video Ca(iu re
73
..
1 02 1 1
I I I
1031C 971C = 9 s lC
96
11
9811
L
_ _ _ ._ _.___.__ _m _ ~ ~ J I _ _m_ _ _ _. _ ._m_ _ _ _ _ m_ _~_ ~_J_c = _ DísplayG
I
----.1
I L _ _ _ _ _ _ _ _ _ _ .~ ? J
1 0 21 1 961 1 1 0 61 1
11 9 61 1 94 11
102
L _ . _ _ ._ .. __
.2 ~ ~ H ._... _ ._.L ~_~~]
Display B
and you obtained a console about simulation notification.
1031C 971C 1031C
Contact
If you have question related to this book, please contact me
[email protected] . My blog: http:// blog.aguskurniawan.net. Source code can be downloaded on http://www.aguskurniawan.net/book!simulinkcodes.zip.