Sie sind auf Seite 1von 61

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.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

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 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

Berlin, April 2013


I. Introduction to Raspberry Pi

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:

Model A with 256 Mb RAM


Model B with 512 Mb RAM

111efollowing is technical specification of Raspberry Pi device:

SoC Broadcom BCM2835 (CPU, GPU, OSP, SORAM)


CPU: 700 MHz ARMI176JZF-S core (ARMll family)
GPU: Broadcom VideoCore IV, OpenGL ES 2.0, 1080p30 h.264/MPEG-4 AVC high-profile decoder
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.
SPBER Y PI MODEL B
RCA VIDEO AUDIO

POWER
~

(source: http://www.raspberrypi.org/wp-content/uploads/20 11/07 /RaspiModelB.png)

For further information, 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. php/ shoplraspberry -pi.htm1
Amazon, http://www.amazon.com
Ebay, http://www.ebay.com
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"OC.j) 7.:~Gt) (l\}O


,..

7."'~O " H~OO 7. ?'O,;, ~.~

$ D' S. fOr:;:) ~ ~?)(!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 Pi and MatIab Simulink for Raspberry Pi. You also need internet eonneetion to
download Raspberry Pi paekage.

Run your Matlab and then cliek Add-Ons. You ean see the menu as below.

Search DoclJmentation P

Get More Apps


Get Apps from File Exchange

Get Hardware 5upport Packages


Find and install hardware support packages
Value Min
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'1ATLAB \$upportPackages \f'.20 130:lownioads 8rowse ...

Seleet Internet (recommended).

After that, cliek Next button.


~ Support Package Installer 1
-
Select a support package
Select a support package to install or update.

Installed lates1
Action Support Package for Required Base Produd Supported Host PI
Version Version

1 D Reinstall Arduino 3.0 3,0 Simulink Windows 132-bit),\


,-
I
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 V.lindows 132-bit),\
'/ -- . ",
'. ~oo
-- - .' '""""" "
Windows 132-bit),\
6 ~ Install Raspberry Pi 1.0 Simulink
:-... , , ,
"
7 L-J Imtall USRP{RJR.adio 5.0 Communicatons System Toolbox Windows (32-bitl,\

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,\

11 l~ Install Xilinx Zynq-7000 1.0 Embedded Coder Windows (32-bit),\

Installation fulder: IC:Vv\ATLAB\5upportPackages~20 13a I[


~ Why are some rows disabled?

Find more supported hardware I <Ba~ I Next> I[

Check Raspberry Pi and then click Next button.

You wil see a license agreement as below.


Support Package.lnstaHer

MATHWORKS AUXILlARY SOFTWARE UCENSE AGREEMENT

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

Next > II Cancel I! Help

Cheeked I accept. If done, cliek Next button.


Support Pack:age Installer
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:

SDl 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 downloadng and instaJling the soft1l1'arelisted above.

By dicking 'Cancel", you will not download or install the software.

< Back II Next > II CanceJ II Help

Click Next button.


Support Package Installer
Confirm installation
Vou have chosen to install Simulink Support Package for Raspberry Pi Hardware in
C: V"'1ATLAB\SupportPackagesljUO 13a.

< Back Install Cancel

Click InstaU button.

It will download Raspberry Pi package and then instal1 it.

If success, you wl obtain a dialog as beIow.


Support Package Installer CI

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> I ~-==--J Help

Click Continue button.


Update firmware

Choose a hard'Nare to start the firmware update processo

Hardware: aS):>~~~~Y~i J
..

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< II Next > II Cancel

< ----_._---- >

Choose Raspberry Pi board. Then click Next button.


Support Package Installer D

Get firmware

Where do you want to get the firmware from?

@ Dovmload from Internet (recommended)

O Get from local folder

Download folder: IC;\MTLAB\S~;;;;~~tp~~~~~~201&;\;j~;;~~I~~d~\m


....ml Browse ..
WARNING: Download size is approxmately 1GB.
Download may take several mnutes.

Choose Download from Internet (recommended).

If done, click Download button.

If download process is done, you will see a dialog as below.


Support Package Installer Cl

Configure board

The board .\lilI be configured with the foilowing name and IP settings:

Board name: '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 Next> Cancel

<

FilI hostname for Raspberry Pio


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 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

< Back II Next > CancE

This dialog cal1 detect your SD cardo If 110t,select the drive of your SD cardo

Then click Next button.


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 Pi image to SD cardo

If done, you will see the dialog as below.


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 ths time.

Make sure that the 'PWR' LED is solid red a


the 'OK' LED indcating 50 card activty
starts blinking. Then, dick 'Next' to continu
Power cable Ethernet connecton

< Saci< II Next > II CancE

Plug out SD card from compu ter. Then, plug in it into Raspberry Pi

Now turn on your Raspberry Pio Read section 2.3.


You may configure your Raspberry Pi for instance SSH. You can read it on section 2.4.

After Raspberry Pi is running well, cIick Next button. 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 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.

<

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 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 : ~~ .

Now you see Raspberry Pi on Simulink Library Browser.


liI
fil' Simulink library Browser
File Edit View Help

I Enter search term

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

Sinks ~ '1. IExsmples


CaptUTe
~
Sources

[;>
User-Defined Fundiom
Additional Math & Discrete
I eSpes.'
,',f~ Speech
Text to

Control System Toolbox


t> DSP System Toolbox
Data Acquisition Toolbox
Instrument Control Toolbox
I:t Simulink 3D Animation
t> Simulink Coder
c, Simulink Control Design
t> Simulink Extras
Simulink Su ort Packa e for Arduino Hardware

Showing: Simulink Support Package for Raspberry Pi Hardware

2.3 Running Raspberry Pi


Now you are ready to boot your Raspberry Pi. Please plug in alI devices, for instance, mouse, keyboard, power, and HDMI
cable. into Raspberry Pio
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 Pi remotely. How to instam You can write his script

I $ sudo apt-get install ssh

To start a service, try to write this script

I $ sudo /etc/init.d/ssh start

Sometimes, you want to mn SSH service every booting. Try to update update-rc.d file

I $ sudo update-rc.d ssh defaults

and then reboot your Raspberry Pi

I $ sudo reboot

For testing, I used PuTTY application in Windows 8 to remote Raspberry Pi via SSH.

Fill IP Address of Raspberry Pi and then c1ick Open button.

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 _

! BeU 1192.168.1.61 I~~


L... Features Connection type:
a"Window O Ra~ O Ielnet O RJog[n @SH O SeDal
!....Appearance Load. save or delete a stored session
j.. Behaviour
! Translation Saved Sessions
I~~;b~;;;;pi................ ..1
i Selection
L... Colours
Default Settings
8..Connection Mac Mini
I Data akurdb .doudapp .net
! Proxy raspbenypi

! 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

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
If you 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 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.

5imulink library Browser D

Help

I Enter search term

Library: Simulink Support Package for Raspberry Pi Hardware

5imulink
ALSAAu<iio ALSAAudio
Commonly Used Blocks
Capture Playbadt:
Continuous

G:J'"~'''
Discontinuities
Discrete GPIO Read nr. GPIOWrite
C~

Logic and Bit Operations

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

5ignal Routing V4L2Video r::::::I [Examples)


Sinks
Sources
Capture
L:::-J
User-Defined Functions eSpes,Textto
(> Additional Math & Discrete Speech
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


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.

HOME PLOTS APPS

Find Files ~ -
Compare Import Save
Data Workspace

Script Ctrl-N
Agus ~ Documents ~ rv
Function 01
D Example

Class
~

ij System Object

Figure

Graphical User Interface

Command Shortcut

SIMUlINK

~ Simulink Model

L::I Simulink Project }

Select Simulink Model.

Then you obtain a Simulink dialog as below.


untitled
File Edit View Display Diagram Simulation Analysis Code Tools Help

Normal .

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 Pi Hardware L:


Simulink
ALSAAudio ALSAAudio
Commonly Used Blocks
Capture Playbact
Continuous
Discontinuities
Discrete GPIORead GPIOWrite
Logic and Bit Operations
Lookup Tables SOL Vidao
Math Operations LEO
Oisplay
Model Verification
Model-Wide Utilities
UOP ReceivE- ~ UOP Send
Ports & Subsystems
~
Signal Attributes
Signal Routing
Sinks
V4L2Video
CapturE-
I ~::-;~;I !ExampI6}

Sources
User-Defined Functions eSpeak Texl to
c' Additional Math & Discrete Speec:h

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

For our scenario, helio world, we create a simulink as below.

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

LED on Simulink Support Package for Raspberry Pi Hardware


Data Type Conversion on Commonly Used Blocks
Sine Wave on Sources

After all items connected, 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: lED


LEDWrite (mask)

Turns an LED on or off.

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
............................................

LED: IledO (Green) .. 1


!

__ o_K __ 11 Cancel Apply

Select Board and LED. If finished, click OK button.

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-

3.2.2 Configuring Data Type Conversion


Double click on Data Type Conversion so you obtain a dialog as below
Functon Block Parameters: Data Type Converson
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 Ii

O Lock output data type setting against changes by the fixed-point tools

Input and output to have equal: ~I World value (RWV._) ._=:J


Integer rounding mode: ~o~_n_d . o:]
O Saturate on integer overflow

Sample time (-1 for inherited):

__ O_K_11 Cancel I [_ Help Apply

Due to Raspberry Pi LED input needs boolean data type, you must select boolean on Output data type.

If done, c1ick OK button.

3.2.3 Configuring Sine Wave


Double click Sine Wave, you will obtain a dialog as below.
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 Apply

For testing, we use eonfigurations as follows:

Sine type: Time base


Time (t): Use simulation time
Amplitude: 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 Code Tools Help

helloworld Test and Validate

If success, you don't see the error dialogo

Now you are ready to deploy to Raspberry Pi and run it.

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

---: Run on Target Hardware ~ Prepare to Run ...


Install/Update Support Package.
Update Firmware ...

lhen you will obtain a dialog as below.

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

Select Raspberry Pi on Target hardware.

Click OK button.

After that, you will see Raspberry Pi configuration.


mfguraton Parametefs: ootit1ed/Run an l:'.artlwar~CtlnJigura f,AdiW)
T.91"1 rn.,d''''11I ~"'"
D.t3
Op(,mllauon
5i9O mo tonng ond pcn:m tu~
Diagntmits
H dw " Impl nLll>On O EM em.1 modq
MQdellt~lerenong
" Smu '9ft Ovtrrun d l!lOn
Run Otl '9tt H ftotrt
C [na av.e'1\#lde~et1

Fill Host name, User name and Password for your Raspberry Pi device.

Note: You ean define hostname's Raspberry Pi or its IP Address.

You ean do eheeked 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.

Simulation Analysis Code lools Help

~ 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

Run on Target Hardware Run


Options ...
Install/Update Support Paclcage.
Update Firmware ...

If process is success, you will see the LED is blinked.

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

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 easily.
Further information about GPIO, you can read it on http://en.wikipedia.org/wiki/GPIO.

Based on Raspberry Pi specification, you can see Raspberry Pi GPIO as below.

,;

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_ ISO GPIO 25

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

For instance, my Raspberry has a response as below.


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 + ECNOOOl
Revision 0002 is Raspberry Pi B Revision 1

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.

YOll also need some cables (famale-male) and a breadboard.


Another option, you can buy Raspberry Pi GPIO kit, for instance, Adafruit Pi Cobbler Breakout Kit for Raspberry Pi. Fur-
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 Pi GPIO Write and LED.

The following is a LED circuit which is connected to GPIO.


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

++
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:

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

Sine type: [j_~~~~ased 'Y._I

Time (t): [~se_~~m~ati~_~tim; . . _

Amplitude:

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 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.

.."
.. '"' .....

4.4 Simulink with GPIO Read


The second scenaro 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
File

int out1 13;


int out2 12;

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

< >

Write this code into your Arduino editor.


int outl - 13;
int out2 12;

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

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
~""
=t
nn
GPIO 18 Scope
GPI018 Read
~
D
RASPBERRYPI
Sccpe1
nn
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 .. 1 [Viewpin mapl

GPIO number: 17

Sample Time: 0.1

Save this model, ealled gpio_sensor.


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.

Scope

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 Pi target, you can see it
on toolbox.

RASPBERRYPI 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 1SUSb
ls /dev/video*

If success, you will see your webcam usb. Mne s Idev/videoO.

Now you are ready to buld a simulnk.

5.2 Creating Simulink

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:

V 4L2 Vdeo Capture on Smulnk Support Package for Raspberry Pi Hardware


Display on Smulink->Sink

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)

Captures video from a USB camera using V4L2 driver framework.


During simulation, the model outputs a moving colorbar image. While
running on hardware, the block outputs vdeo from a USB camera.

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:

__ O_K _11 Cancel II Help J Apply

Change value on Device 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.


Configuration Parameters: videodemo/Run on Hardware Confi

Select: Target hardware seleetion


Solver
Target hardware: ~~p~be_r_ry_p_i
_~~~ __ ~ _
Data ImportjExport
t> Optimization
Signal monitoring and parameter tuning
I> Diagnostics
Hardware Implementation ~ Enable Externai mode
Model Referencing
I> Simulation Target TCP/IP port (102.4-65535): 1772.5
Run on Target Hardware
Overrun deteetion

~ Enable overrun deteetion

Board information

Host name:

User name:

PassNord: ~~_~~~~:~_=:-~___
__..._~-..-..-.-.----..._-----.---------.----:-=~=_
Build direetory: [2~~_~_~Le-~==:_-:_::~:::::::==~===:.:=::_~-:=====--=_:~:==

Before running, change Normal to Externai.

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.

If success, you will see RGB values on Display.


-, -vid-eo-de-m-o
----'--.-----.--------~------------------------------. -.---.---------~-----

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

I 10211 10211 1031C


----.1 9611 9611 971C
I 9411 10611 1031C
L__________.~?J L_ .. __ .._ .... __ .2~~H_ .... __
._.~_~~]
L
Display B

and you obtained a console about simulation notification.


Contact

If you have question related to this book, please contact me at aguskur@hotmail.com . My blog: http://
blog.aguskurniawan.net.

Source code can be downloaded on http://www.aguskurniawan.net/book!simulinkcodes.zip.

Das könnte Ihnen auch gefallen