Getting Started with Matlab Simulink and Raspberry Pi Agus Kurniawan 1st Edition Edition,, 2013 ISBN: 978-1-300-95391-3 Copyright
@
2013 Agus Kurniawan
Table of Contents
Preface 1. Introd Introduct uction ion to Raspb Raspberr erry y Pi 1.1 Raspberr Raspberry y Pi 1.2Getting Hardware Hardware 2. Matlab Matlab Simulink Simulink and Raspberr Raspberrv v Pi 2.1 Matlab 2.2 Installin Installin 2.3 Runnin Running g Raspb Raspberr erry y Pi 2.4 SSH 3. Helio World World - Matlab Matlab Simulink Simulink and Raspberry Raspberry Pi 3.1 Helio World 3.2 Creating Creating Raspberr Raspberrv v Pi Simuli Simulink nk 3.2.1 3.2.1 Config Configurin uring g Raspberr Raspberry y Pi LED 3.2.2 Configuring Configuring Data Type Conversion 3.2.3 Configuring Configuring Sine Wave 3.3 Running Simulink 4. Simulin Simulink k with Raspberr Raspberry y Pi GPIO GPIO 4.1 GPIO 4.2 Preparation 4.3 Simulink with GPIO Write 4.3.1 Building Simulink Madel 4.3.2 4.3.2 Testinz 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 S.l Prcparation
5.2 Creating Creating Simulink 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 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 Raspberry
Pi is a small size computer
timedia or run an application. berry Pi:
(85.60mm x 56mm x 21mm) with completed
This device is developed by the Raspberry
Pi Foundation
features so that you can play mulin UK. There ara two type of Rasp-
• 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
core (ARMll
family)
VideoCore IV, OpenGL ES 2.0, 1080p30
h.264/MPEG-4
• Memory (SORAM): 512 Megabytes (MiB) • Video outputs: Composite
RCA, HOMI
• Audio outputs: 3.5 mm jack, HOMI • Onboard
storage: SO, MMC, SOlO card slot
• 10/100 Ethernet RJ45 onboard network • Storage via SOl MMCI SOlO card slot You can see Raspberry
Pi device with model B on the Figure below.
AVC high-profile
decoder
SPBER Y PI M ODEL 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 Raspberry Pi, http://www.raspberrypi.org.
1.2 Getting Hardware How to get Raspberry
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 buying 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 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 ~
li.'S "O C .j)
7.:~Gt)
7."'~O
"
$ •• óD'
S. fOr:;:)
(l\}O
7. ?'O,;,
H ~O O
,
..
~.
~
~~?)(!O
2.2 Installing Raspberry Pi for Simulink Target Firstly, you prepare 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 Pi. You also need internet eonneetion
Run your Matlab and then cliek Add-Ons.
to
You ean see the menu as below. S e a r ch
D o c l J m e n ta t io n
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 Hardware
Support
Packages.
Then you will obtain a dialog, ealled Support
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 ' 1 A T L A B \$upportPackages \f'.20 130¥:lownioads
Seleet Internet
(recommended).
After that, cliek Next button.
8rowse...
Support Package Installer
~
1
Select a support
package
Select a support package to install or update. Action
Installed Version
lates1 Version
Required Base Produd
Supported Host PI
1
D Reinstall
Arduino
2
D Install
BeagleBoard
3.0
' Simulink
Windows 132-bit),\
3
D Install
Gumstix Overo
1.0
Simulink
Windows (32-bit),\
4
D Install
LEGO MINDSTORMSNXT
3.0
Simulink
Windows (32-bit),\
5
D Install
PandaBoard
3,0
Simulink
--
'/
:-...
Support Package for
6
.
3.0
Raspberry Pi
Install
'.
1.0
L -J
8
D Install
9
i
10 ~
Imtall
Digilent Analog Discovery
.'
Simulink
V.lindows 132-bit),\ '" " " " "
"
Windows 132-bit),\ ,
,
5.0
Communicatíons System Toolbox
1.1.1
Data Acquisition Toolbox
r
"
Windows (32-bitl,\
Windows 132-bit),\ Windows (32-bitl,\
Embedded Coder
Install
A.n310gDevices DSPs
2.0
Install
Green Htlls r.."ULTI
3.0
Embedded Coder
Windows 132-bitl,\
Xilinx Zynq-7000
1.0
Embedded Coder
Windows (32-bit),\
11 l~ Install Installation fulder:
~
USRP{RJR.adio
-
---
~oo
,
7
Windows 132-bit),\
Simulink
,I
",
~
3,0
.,
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 Package.lnstaHer M A T HW O RK S
I M PO R T AN T
A U X IL l A R Y
S O FT W A RE
U C EN S E A G R EE M EN T
N O T IC E
================
R EA O T HE TE RM S A N O C O No mO N S O F T H IS M A TH W O RK S A U XI LI AR Y S O FT W AR E L IC EN S E A G R EE M E NT ( TH E "A G R EE M E Ní ) C A R EF U LL Y B E FO R E C H E C KI N G 1 A C C EP r O R A C C ES S IN G M A T ER I AL S ( A S D Ef IN E D B E LO W ) .
T H ES E
T H IS A G R EE M E NT R E PR E SE N TS T H E EN T IR E A G R EE M EN T B E TW E E N V O U ( lH E L IC E N SE E" ) A N O T H E M A TH W O RK S , I NC . f MA T HW O R KS ") C O NC ER N IN G T H E S O FT W AR E A N D O O CU M EN T AT IO N M A D E A V A I L A B LE fO R A C C E S S H E R E U N O E R ( C O L LE C T IV E L Y , T H E ' M A T E RI A L S ") . B Y C H E CK I N G 1 A C C E PI AGREEMENT.
O R A C CE S SI N G T H ES E M A T E RI A LS
I
V O U A C C E PT T H E TE R M S O F T H I S
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 Next
Cheeked I accept. If done, cliek Next button.
>
II
Cancel
I!
Help
Support Pack:ageInstaller Third-party
software licenses
Vou have chosen to instaU Simulink Support Pack.age for Raspberry Pi Hardware. Software Vl'illbe installed from the following locations: S Dl
http://wVl'w.libsdl.org
Iicense
Wget for Windows
http://gnuwin32.sourceforge.net/pack.ages/wget.htm
Iicense
]-zip
http://www.]-zip.org
Iicense
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 downloadíng and instaJling the soft1l1'arelisted above. By dicking 'Cancel", you will not download or install the software.
< Back
Click Next button.
II
Next
>
II
CanceJ
II
Help
Support Package Installer Confirm installation
Vou have chosen to install Simulink Support Package for Raspberry Pi Hardware 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 Raspberry
Pi Hardware
has been successfully
installed.
To ensure compatibility with Simulink, you may need to update the firmware for the selected support package hardware. Select -Continue- to update firmware now. Select -Close- to exit this utility.
I Continue> Click Continue button.
I
~ - = = --J
Help
Update firmware
Choose a hard'Nare to start the firmware update processo Hardware:
J
aS):>~~~~Y~i .••.•
Help
Click Next buttol1.
Support Package Installer
D
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
< Bacl<
<
Choose Raspberry Pi board. Then click Next button.
----_._----
II
Next
>
II
Cancel
>
Support Package Installer Get f irmware
Where do you want to get the firmware from?
@ Dovmload
O Get from
from Internet
(recommended)
local folder
Download folder:
IC ;\M Ã T L A B \S ~ ;;;;~ ~ tp ~ ~ ~ ~ ~ ~ 2 0 1 & ;\;j~ ;;~....~mI~l ~ dBrowse ~ \m •..
WARNING: Download size is approxímately Download may take several 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 Board name:
with the foilowing name and IP settings:
'raspberrypi-AKUR l . . _ . . _ _ . _ . . _
. .. . . .. . _ . . . . _ . . . _ ._ . . . .
Configure IP settings for wired Ethernet
connection
] _
More info
IP Assignment
•
Automatica!ly
get IP aderess
ManuaDy enter IP address IP Settings
IP address: 10.10.10.9 Network mask:
255.255.255.0
Default gateway:
10.10.10.1
< Back
<
F ilI hostname for Raspberry P io
Next>
Cancel
Support Package lnstaller 5elect a drive
Insert a 4 GB or larger SD memory card into a memory card reader on the host compu ter. Select the drive 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 drives, reinsert the memory card fully and dick "RelTesh',
~ Slide lock switch up to unlocked position
< Back
This dialog cal1 detect your SD cardo If 110t,select the drive of your SD cardo Then click Next button.
II
Next
>
CancE
Support Package Installer Write firmware
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
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 memory eard ITom the h computer and insert into the Raspberry Pi I 2. Connect an Ethernet eable to the board the other end of the Ethernet eable to a nl directly to the host compu ter. 3. Connect a SV micro USS power supply te board. The power supply should be rated f least 700 mA. NOTE: Vou may connect optional periphera as a monitor, keyboard, etc. at thís time.
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
< Saci<
Plug out SD card from compu ter. Then, plug in it into Raspberry
Now turn on your Raspberry
Pio Read section 2.3.
Pi
II
Next
>
II
CancE
You may configure After Raspberry
your Raspberry
Pi is running
Pi for instance
SSH.
well, cIick Next button.
You can read it on section
2.4.
Then you will see a dialog as below.
Support Package Installer Confirm board configuration
If you want to log in to the board in the future, the host name or IP address, user name, and password are displayed below. Vou may also type "raspberrypi" on the M A T L A B command window to obtain this information. Host name:
raspberrypi-AKUR
User name:
pí
Password:
raspberry
NOTE:
1. YourRaspberry Pihardware willspeak its IP address through the analog audío 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.
<
Click Next button
Support Package lnstaller Firmware update complete
You have successfu!ly updated ~
YOUf
nrmware.
Show support package examples
Click 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@hardware. With this capability. you can assess algorithms in the classroom 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 M o d E
~
~
I ~
i
...-..f~
i
•
»rQ:] -"
~ 1
I
I t
~
F~~'J r:T w I
I~l .~
~~]
Communicating
I ~~'I • :
Now you see Raspberry
~~
Pi on Simulink Library Browser.
with Raspberry Pi Hardware
I!tl M o d E
.
liI fil'
Simulink library Browser
File
Edit
View
Help
I
» Enter search term
__ .J
Libraries
[ ;>
t>
I :t
t> c,
t>
Simulink Commonly Used Blocks Continuous Discontinuities Discrete Logic and Bit Operations Lookup Tables Math Operations Model Verification Model-Wide Utilities Ports & Subsystems Signal Attributes Signal Routing Sinks Sources User-Defined Fundiom Additional Math & Discrete Control System Toolbox DSP System Toolbox Data Acquisition Toolbox Instrument Control Toolbox Simulink 3D Animation Simulink Coder Simulink Control Design Simulink Extras Simulink Su ort Packa e for Arduino Hardware
Showing:
Simulink Support Package for Raspberry
Library: Simulink Support Package for Raspberry
ALSAAudio Capture
J'.'
~ .rtr.
~
GPIO Read
LEO
"'.:.,c:: •••.
.rtr.
1 _
-rn _
G - t - ..: .~
"q r CO - 41 0
ALSAAudio PIsybaO:
='""':~
UOPReoeive
V4L2Video CaptUTe
Pi Hardware
SOLVídeo Displsy
~
~:-'~I
~ ~
GPIOWrite
~
UDPSemi
• • ' 1.
IExsmples
Text to ,',f~ I eSpes.' Speech
Pi Hardware
2.3 Running 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 the power for your Raspberry
Pi.
If success, you will get the first screen of Raspberry Pi as below
Try to configure your Raspberry
Pi, for instance, timezone and keyboard.
If done, push Finish menu. You will get Raspberry
Pi console shown in Figure below.
Enter username: pi and password: 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 $ sudo I
apt - get
i nst al l
Pi remotely. How to instam You can write his script
ssh
To start a service, try to write this script $ sudo I
/ 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
$ sudo I
updat e- r c. d
and then reboot your Raspberry
I $ sudo
file
ssh def aul t s
Pi
r eboot
For testing, I used PuTTY application Fill IP Address of Raspberry
in Windows 8 to remote Raspberry Pi via SSH.
Pi and then c1ick Open button.
P u T T Y Configuration Categ.ory:
r
~ ..Session
L .. . Logging
_
I
_
1
Basic options for your PuTT Y session
_
.
Specify the destination you want to connect to
~. Terrninal
!
Keyboard
Host liame
(or I P address)
! BeU
1192.168.1.61
L .. . Features
Connection type:
a"Window
!. . . .Appearance
j . • . • Behaviour
!
i
Translation Selection
L .. . Colours Connection 8 ..
I Data
! Proxy
O Ra~
O Ielnet
~fo_rt
I~~
O RJog[n
@âSH
O SeDal
Load. save or delete a stored session Saved Sessions I~~;b~ ;;;;pi................
..1
Default Settings Mac Mini akurdb .doudapp .net raspbenypi
! Telnet ! RJogin
ctl'
SSH
L . . . Serial
Oose •••• 'indow on exit:
O A1ways
~out
O N-ever
_
@ Only on dean exit
If connected,
you will get a secuity alerto
PuTIY Security Alert The server's host key is not cached in the registry. Vou have no guarantee that the server is the computer 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 connecting. Ifyou want to carry on connecting just once, without adding the key to the cache, hit No. Ifyou do not trust this host, hit Cancel to abandon the connection.
Click Yes button. Entry username
and password.
rf success, you will get Raspberry
Pi console.
3. HelIo 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 LED on Raspberry
Pi, called Hello World. In this scenario, we work with
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. D
5imulink library Browser Help
I Enter
search term Library: Simulink Support Package for Raspberry
(>
5imulink Commonly Used Blocks Continuous Discontinuities Discrete Logic and Bit Operations Lookup Tables Math Operations Model Verification Model- Nide Utilities Ports & 5ubsystems Signal Attributes 5ignal Routing Sinks Sources User-Defined Functions Additional Math & Discrete Control System Toolbox DSP 5ystem Toolbox Data Acquisition Toolbox Instrument Control Toolbox 5imulink 3D Animation Simulink Coder 5imulink Control Design Simulink Extras 5imulink Su ort Packa e for Arduino Hardware
Showing:
Simulink Support Package for Raspberry
Pi Hardware
ALSAAu
GPIO Read
ALSAAudio Playbadt:
'"~''' G:J n r. C~
""-.'~ CD "@
LEO
-.
-"
~ ~
UDP Reoeive
V4L2Video
Capture
eSpes, Text t o Speech
GPIOWrite
••
.. - ..,~ '~ [!:J rn ••: c ••.
Pi Hardware
r::::::I
L:::-J
SOL Video Oisplay
UDP Seno
[Examples)
3.2 Creating 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 the latest version. On Home, click + New icon. Then you will obtain a menu as below.
PLOTS
HOME
APPS
-
Find Files
~
Compare
Import Data
Script
Workspace
Ctrl-N Agus
Example
~
Class
ij
System Object Figure Graphical User Interface Command Shortcut
SIMUlINK ~
Simulink Model
L ::I
Simulink Project
~ Documents
~ rv 1 0
Function
D
Save
}
Select Simulink Model. Then you obtain a Simulink dialog as below.
untitled
File
Edit
View
D isplay
D iagram
Simulation
A nalysis
Code
Tools
H elp N o rm a l
• •• .
Model BrO'Nser untitled
«
Ready
100%
Next step, we build a simulink model. On the Simulik Model dialog, click menu Tools -> Library Browser.
am
Simulation . . . .
Analysis
Code
Help Library Browser
~ ~
Model Explorer Run on Target Hardware
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 Support Package for Raspberry
c'
Simulink Commonly Used Blocks Continuous Discontinuities Discrete Logic and Bit Operations Lookup Tables Math Operations Model Verification Model-Wide Utilities Ports & Subsystems Signal Attributes Signal Routing Sinks Sources User-Defined Functions Additional Math & Discrete Control System Toolbox DSP System Toolbox Data Acquisition Toolbox Instrument Control Toolbox Simulink 3D Animation Simulink Coder Simulink Control Design Simulink Extras Simulink Su ort Packa e for Arduino Hardware
ALSAAudio
Pi Hardware
ALSAAudio Playbact
Capture
GPIORead
GPIOWrite
SOL Vidao
LEO
Oisplay
UOP ReceivE-
~ ~
V4L2Video
I ~ : : - ; ~ ;I
CapturE-
UOP Send
!ExampI6}
eSpeak Texl to Speec:h
For our scenario, helio world, we create 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 Simulink Support Package for Raspberry Pi Hardware • Data Type Conversion • Sine Wave on Sources
After all items 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 desired LEDfrom the drop-down menu. Do not use the same LEDin multi pie blocks within a model. Parameters Board:
1 .~ .~ .9.... .~~..... .I~ey~
LED:
IledO (Green)
_ _
o_K__
[ . • .i
....... ....... ....... ....... ...•.. ....... ..... . . !
. •.
View LED location ••......................•.........•.............
1 !
11
Cancel
Select Board and LED. If finished, click OK button. You aIso can click View LED location
button to view LED position.
Apply
Model B Rev2 LED locations
File
O~
Edit
View
Insert
T 0015
D esktop
W indow
H elp
r-
3.2.2 Configuring 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 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 Output minimum:
Output maximum:
[1[---------] Output data type:
I boolean
v
I
i
»
O Lock output data type setting against changes by the fixed-point tools Input and output to have equal: ~I
World value (RWV._)
._ = :J
.
o :]
Integer rounding mode: ~o~_n_d
O Saturate
on integer overflow
Sample time (-1 for inherited):
__
_ 1 1
O_K
Cancel
I [_ Help
Apply
Due to Raspberry 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 period I (2"'pi)
Use the sample-based sine type if numerical problems due to running 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 parameters as 1-0 OK
For testing, we use eonfigurations
Apply
as follows:
• Sine type: Time base • Time (t): Use simulation • 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 instanee, helloworld. You test and validate your model. Make sure you scleet Normal.
Then, cliek Arrow, shown in Figure below.
helloworld nulation
C o de
T o o ls
H e lp
d
Test and Validate alidate
helloworld
If succe success, ss, you you don't don't see the the error error dialog dialogo o Now you are ready to deploy to Raspberry
Pi, you you must must conf config igur ure. e. How? How? Click Click menu menu Tool Toolss -> Run on Target Target Hardwa Hardware re
To run run this this mode modell to Rasp Raspbe berr rry y to Run. Run.
--
~._._-_.~---_.
I T o o ls L ~ l p _ ...i~ Library Library •••
_ _ ._ -
Code >
F ? ':!\
Pi and run it.
.
,
Browser
Model Explore Explorer r
~
---:
R un un o n T ar arg e t H ar ard wa wa re
~
Prepar Preparee to Run ... ... Instal Install/Up l/Updat datee
Support Support Package Package..
Update Update Firmwar Firmwaree ... ...
lhen lhen you you will will obta obtain in a dia dialo log g as belo below. w.
í S,~tt: I
i
j Th •• " ,." " 1 is " " I " " I to um !
So~r OAU ~'f>port
I
!
Oí"9OCltiu H i ii f ~ i l I r l !
i " S'mulat!Otl i
Implemel\tiitioo
Mod.1 RvI•.,.ncinç
tJ1etll~ tJ1etll~
did"Ti did"Tilol lol:s' :s',, did'R.un did'R.un
Target M Ilrdware Ilrdware RleCUoo
r"9"1 h . . - d v , , , , , , , [!Y'~rr'f ~,_.
Taln,et
ll:un on 1.1'9.1 1.1'9.1 Hmfw.t'l'
i
I
Select Select Raspb Raspberr erry y
Set ll1<>"Torgol ll1<>"Torgol
I' y1ltIf hilr""' hilr""'lt' l t' e 15 t\ót t\ót Ii:!tf!d Ii:!tf!d ¥llÍle ¥llÍle 'Th'get g et har
I Te ,l'\:!tall
! " Optjmlratiol'l
""y Lo,gd h.,dw.'e.
Pi on on Target Target hardwa hardware. re.
Click OK button. button. After After that, that, you will see Raspb Raspberr erry y
Pi confi configu gurat ration ion..
" " " I h " " " , ' porilltlld"
tó miOlâl rou' lorgol
optioos, optioos, íl'\:!tlll \ :!tlllll the IlIfget IlIfget foI' VOUf hat'
1llrgetHMd"'M HMd"'Me'. e'. aro dld:'lnSli3~ lnSli3~ on 1llrget
5uwmt radage",'.
" " " 4 • .•"
-> Prepare
úmfíguratíon T• • • .9 1 " 1
Parametefs:
ootit1ed/Run ootit1ed/Run an l:'.artlwar~ l:'.artlwar~CtlnJigura CtlnJigura
f,AdiW)
r n . , d ' ' '1 1 I ~ " '"
D.t3 Op(,mllauon Diagntmits
5i9O mo tonng tonng ond pcn:m
H••dw••" Impl••••• Impl••••• nLll>On
O EM
MQdellt~lerenong " Sómu Run
Otl '9tt
H
em.1 modq
Ovtrru Ovtrrunn d
'9ft
Óftotrt
C [na
tu~
l!àlOn
av.e'1\#l 1\#lde~et1 de~et1
Fill Fill Host Host name, name, User User name name and Passwor Passwordd for for you yourr Rasp Raspber berry ry Pi devi device. ce. Note: You ean define hostname's
Raspberry Pi or its IP Address.
You You ean do eheek eheeked ed Enabl Enablee Exter ExternaI naI mode mode and and Enabl Enablee ove overr rrun un detee deteeti tion on.. If done done,, click click OK button. button. Now baek to your Simulink. Change Normal to ExternaI, shown in Figure below. Simul Simulat atio ionn
Analy Analysi siss
Code
lools
Help
· ~ lG l~ S
~helloworld
~
~" =t RASPBERRYPI
SineWsw
"i,'t;'l
~
@
led{) (Gfeen) (Gfeen) boolean
LED
Data Data Type Type Conv Convers ers ian
To deplo deployy and run run on Raspber Raspberry ry Pi, Pi, click click menu menu Tool Toolss -> Run on Target Target Hardwar Hardwaree -> Run Run .
Ilysis Cede
Help ,
Library Library Brewser Brewser Medel Explerer Explerer Run on Target Target Hardwar Hardwaree
Ru n Options Options ... Install Install/Updat /Updatee
Support Support Paclcage Paclcage..
Update Update Firmwar Firmwaree ... ...
If proces processs is succ success ess,, you will will see the LED is blink blinked. ed.
You also also obtain obtain a consol consolee dialog dialog to show show that simula simulatio tion n
proces processs was dane. 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
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 read it on http://en.wikipedia.org/wiki/GPIO.
Based on Raspberry
Pi specification,
easily.
you can see Raspberry Pi GPIO as below.
, ; / I
3.3 V
6V
12CO_SDA
5V
12CO_SCL
GND
GPI04
UARTO_TXD
GN D
UARTO~XD
GPIO 17
GPIO 18
PCM_DIN
GND
GPIO 22
GPIO 23
3.3 V
GPIO 24
SPlO_MOSI
GN D
SPlO_ ISO
GPIO 25
SPlO_SCLK GN D
When I wrote this book, there are two Raspberry you know Raspberry
SPlO_CEO_N SPlO_CE1_N
Pi revision types, revision
1 and
Pi revision?
You can know what your Raspberry
Pi revision by typing this script on terminal.
I
cat Iproc/cpuinfo
For instance, my Raspberry
has a response as below.
2. Basically, it's not big changes. How do
Ifyou can see, I have Revision ooof. It means 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,
+ ECNOOOl
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 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 digital 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 product, you can read it on http://adafruit.com/products/914 .
4.3 Simulink with GPIO Write In this section, 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 GPIO 4 • LED 2 connect to GPIO 17 • LED 3 connect to GPIO 18
This is my circuit for LED and Raspberry
Pi
Now we start to build a sirnulink rnodel.
4.3.1 Building Simulink Model Run your Matlab and create a Sirnulink Model. Try to build a rnodel as shown in Figure below.
RASPBERRYPI
n n
boolesn + +
Sine W sve
GPI04
Data Type CooW1Sion
GPIO 4Wrile 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 Conversion on Commonly Used Blocks • Scope on Commonly
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 Sine Wave, you can configure it as below.
Source Blbck Paramete Number of offset samples
=
Phase '" Samples per period I (2"'pi)
'"
Use the sample-based sine type if numerical problems due to running for large times (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 turn on and off on a certain time.
.. "
. . '" ' . . . ..
4.4 Simulink with GPIO Read
The second scenarÍo we want to do is to read a GPIO input. In this illustration, we Arduino to generate digital outputs for Raspberry Pi. I used Arduino Uno R3 for testing.
4.4.1 Creating Application 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 n t o ut 1 i nt out 2
13; 12;
Toid setup () {
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) ; 1/
Joid
pi n as
~l
out put .
loop () {
di gi t al ~Li t e( out 1, 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) ; HI GH) ; Ii wa i
t
f OL a s e c on d
Ii wa i
t
f OL a s e c on d
/ / wai t
f OL a s ec ond
HI GH) ; LOl J ) ; LO~) ;
HI GH) ;
<
Write this code into your Arduino editor.
>
i nt out l - 13; i nt out 2 12; voi d s et up( ) { 1,1 í ni t i al í z e pi nMode( out l , pi nMode( out 2, }
dl ' g l ' t c~.. L' Pl ' 11 ° l S an ou t _put, , OUTPUT) ; OUTPUT) ; ~ '- he
voi d l oop( ) { 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) ;
c .
HI GH) ; HI GH) ; II wai
t
f or a second
HI GH) ; LOW) ; Ii
wai t f or a second
LOW) ; HI GH) ; II
wai t
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
f or a second
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
n n
Sccpe1
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 assign 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 desired 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 open Scope library. You will see the response output as below.
Sc ope
You also obtain a console dialog for simulation
process notification.
5. Simulink and Video Capture
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 on toolbox.
RASPBERRYPI
Pi target, you can see it
Y
, .. . ,
(e).
Cb
c::.j
V 4L2 Video Capture
Mathworks has already testes some cameras as follows: • Logitech QuickCam
Pro 9000
• Logitech QuickCam
Pro 3000
• Logitech Webcam C600 • Logitech HD Webcam C310 For a list ofUVC
cameras supported
by Ubuntu and Raspberry Pi, you can visit http://www.ideasonboard.org/uvc/
In this scenario, I used Microsoft LifeCam VX-700.
After plug-in, you can execute this command
to Raspberry
Pi console.
.
1
1 S U S b
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 Creating 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 have a Compute r Vísíon System Toolbox, you can use To Video Dísplay, http://www.mathworks.com/help/vision/ ref/tovideodisplay.html
, 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ídeo 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 USBcamera using V4L2 driver framework. During simulation, the model outputs a moving colorbar image. While running on hardware, 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 stream. Parameters Device name:
I
1'[dev[videoo'l Image size: ~_2 Pixel format:
-:J :J
__ 0
~ I R_G_B
Sample time:
_ _
_1 1
O_K
Cancel
II
Help
Change value on Device name, for instance, '/dev/videoO'. 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.
J
Apply
For pixel format, change to RGB.
Configuration Parameters: videodemo/Run
on Hardware 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 monitoring and parameter tuning ~
Enable Externai mode
TCP/IP port (102.4-65535):
1772.5
Run on Target Hardware Overrun deteetion ~
Enable overrun deteetion
Board information Host name: User name:
Before running,
File
Edit
PassNord:
~ ~ _ ~ £ ~ ~ ~ : ~ _ = : - _~ _. _. ._~ _- . .- . .-.-. - - - - _. . . - - - - - . - - - - - - - - - . - - - - : - = ~ = _
Build direetory:
[ 2 ~ ~ _ ~ _ ~ L e - ~ = = : _ - : _ : : ~ : : : : : : : = = ~ = = = : . : = : : _ ~ - : = = = = = - - = _ : ~ : =
change Normal to Externai.
View
Display
D ia gra m
S im ula tio n
A na ly sis i
IT :l
0~
~
.••.
s i @, ~IG)
i
Model Browser videodemo
Now click menu Tools -> Run on Target Hardware -> Run. If success, you will see RGB values on Display.
\
•.
Code
• I
Tools ~J
T
Help
iiõ:õ--
J
..•.
-, -vid-eo-de-m-o ----'--.-----.--------~------------------------------.
-.---.---------~-----
S ~videodemo
'~:
I
-~
riI
li<1i1
~
RASP8ERRYPI R ---,
( 0 )
t......... ,
G B
6411
7211
72
7 0 I' 6 4 11 731!
11
1
11
7 3 1 1 1 :'
-D rs ~ a y R
'-
-
V4L2 Video Ca(iure
671 1
73
11
I
I -
6 911 6 3 1 1 63
..
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