You are on page 1of 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 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 (85.60mm x 56mm x 21mm) with completed features so that you can play multimedia or run an application. This device is developed by the Raspberry Pi Foundation in UK. There ara two type of Raspberry 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 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 MODEL B
RCA VIDEO AUDIO

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. php/ shoplraspberry Amazon, http://www.amazon.com Ebay, http://www.ebay.com

-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"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 download Raspberry Pi paekage. Run your Matlab and then cliek Add-Ons. You ean see the menu as below. Search DoclJmentation

to

Get More Apps Get Apps from File Exchange Get Hardware 5upport Packages Find and install hardware support packages Value Purchase MathWorks Produds Visit Web Store

Min

Seleet Get Hardware

Support

Packages. Package Installer.

Then you will obtain a dialog, ealled Support

Support Package Insta ler


Install or update support package
Where do you want to instaI! or update from?

@ Internet (recommended)

Folder 8rowse ...

c: V'1ATLAB \$upportPackages \f'.20 130:lownioads

Seleet Internet

(recommended).

After that, cliek Next button.

~
Select a support package

Support Package Installer

Select a support package to install or update. Action 1 2 3 4 5 Support Package for Arduino BeagleBoard Gumstix Overo LEGO MINDSTORMSNXT PandaBoard
",

Installed Version 3.0

lates1 Version 3,0 3.0 1.0 3.0 3,0

Required Base Produd Simulink

Supported Host PI Windows 132-bit),\ Windows 132-bit),\ Windows (32-bit),\

D Reinstall D Install D Install D Install D Install


Install Imtall

,I

' Simulink Simulink Simulink

Windows (32-bit),\ V.lindows 132-bit),\

'/

-- .
7 8 9

:-...

6 ~
L-J

Raspberry Pi USRP{RJ R.adio

'.

~oo

1.0
,

-- Simulink
,

Simulink

.'

'"""""

"

Windows 132-bit),\
, "

5.0 1.1.1 2.0 3.0 1.0

Communicatons System Toolbox Data Acquisition Toolbox

Windows (32-bitl,\ Windows 132-bit),\ Windows (32-bitl,\ ., Windows 132-bitl,\ Windows (32-bit),\

D Install
i

Digilent Analog Discovery A.n310gDevices DSPs Green Htlls r.."ULTI Xilinx Zynq-7000

Install Install

Embedded Coder Embedded Coder Embedded Coder

10 ~ 11

l~ Install

Installation fulder:

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

I[

Why are some rows disabled?

Find more supported hardware

<Ba~

Next>

I[

Check Raspberry

Pi and then click Next button. as below.

You wil see a license agreement

Support Package.lnstaHer
MATHWORKS AUXILlARY 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 AGREEMENT. OR ACCESSING THESE MATERIALS VOU ACCEPT THE TERMS OF THIS
I

SOFTWARE UCENSE 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
Wget for Windows ]-zip

http://wVl'w.libsdl.org http://gnuwin32.sourceforge.net/pack.ages/wget.htm http://www.]-zip.org

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


IMtal/update complete
Simulink Support Package for Raspberry Pi Hardware has been successfully installed.

CI

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
Click Continue button.

Continue>

I ~-==--J

Help

Update firmware Choose a hard'Nare to start the firmware update processo Hardware: aS):>~~~~Y~i ..

Help

Click Next buttol1.

Support Package Installer


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:

Model B

.1

< Bacl< < ----_._----

II

Next

>

II

Cancel

>

Choose Raspberry Pi board. Then click Next button.

Support Package Installer


Get firmware
Where do you want to get the firmware from?

Dovmload from Internet local folder

(recommended)

O Get from

Download folder:

IC;\MTLAB\S~;;;;~~tp~~~~~~201&;\;j~;;~~I~~d~\m ....ml Browse ..


1GB.

WARNING: Download size is approxmately Download may take several mnutes.

Choose Download from Internet If done, click Download button.

(recommended).

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

Support Package Installer


Configure board
The board .\lilI be configured Board name: with the foilowing name and
.. .... ..... __ ..

Cl

IP

settings: ] _

'raspberrypi-AKUR l .... __ .. _. __ .

... __ ....

Configure IP settings for wired Ethernet

connection

More info

IP

Assignment Automatica!ly ManuaDy enter get IP aderess

IP address

IP

Settings

IP address:

10.10.10.9

Network mask: Default gateway:

255.255.255.0
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 Drive: to the memory card reader:

D:

~!

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

your Raspberry

Pi for instance

SSH. You can read it on section 2.4.

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: User name: Password:
NOTE:

raspberrypi-AKUR p raspberry

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

+
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. an optimize

i
i

Product page at mathw(

I
1 :
!

Getting Started with Raspberry Pi Hardware

I!tl ModE

~ ~

I ~
i
i

I
t

rQ:] ~ -"
: ~~

...-..f~
I~l .~
Communicating with Raspberry Pi Hardware

F~~'J r:TwI ~~] I ~~'I

I!tl ModE

Now you see Raspberry

Pi on Simulink Library Browser.

liI fil'

Simulink library Browser


Edit View

File

Help
Enter search term

Libraries

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

Library: Simulink Support Package for Raspberry ALSAAudio Capture

Pi Hardware

J'.'

ALSAAudio PIsybaO:

.rtr. ~
='""':~

GPIO Read

G
.rtr.
-t-..: .~

GPIOWrite

"qr CO
"'.:.,c:: . -410 _
1_

LEO

~
UOP Reoeive

SOL Vdeo Displsy

-rn

~
V4L2Video CaptUTe

~:-'~I
~ '1.

UDP Semi

IExsmples

[;>

Text to ,',f~ I eSpes.' Speech

t>

I:t

t>

c,
t>

Showing:

Simulink Support Package for Raspberry

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 If done, push Finish menu.

Pi, for instance, timezone and keyboard.

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

startx

2.4 SSH
You may need SSH to manage Raspberry Pi remotely. How to instam You can write his script

I I I I

$ sudo apt-get

install ssh

To start a service, try to write this script $ sudo /etc/init.d/ssh

start

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

file

$ sudo update-rc.d

ssh defaults

and then reboot your Raspberry

Pi

$ sudo reboot

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.

PuTTY Configuration
Categ.ory: ~ ..Session

r
I

Basic options for your Pu TTY session Specify the destination you want to connect to Host liame (or

L... Logging
~. Terrninal

Keyboard

IP address)

BeU L... Features


a"Window

1192.168.1.61
Connection type:

I~~
@SH

~fo_rt

!....Appearance
j.. Behaviour

O Ra~

O Ielnet O RJog[n

O SeDal

Load. save or delete a stored session Saved Sessions I~~;b~;;;;pi................ Default Settings Mac Mini akurdb .doudapp .net raspbenypi

!
i

Translation Selection

.. 1

L... Colours

8.. Connection

I
!
!

Data Telnet RJogin

! Proxy

ctl' SSH
L... Serial

O A1ways
~out

Oose 'indow on exit: 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 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


Help
D

Enter search term Library: Simulink Support Package for Raspberry Pi Hardware

(>

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

ALSAAu<iio Capture

GPIO Read

CD""-.'~
"@
LEO
: c .

G:J'"~'''
nr.
C~

ALSAAudio Playbadt:

GPIOWrite

. ..,~ '~ [!:J rn


-. .-" UDP Reoeive V4L2Video Capture

~ ~

SOL Video Oisplay

UDP Seno

r::::::I

L:::-J

[Examples)

eSpes,Textto Speech

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
Workspace

Data
Script Function Ctrl-N Agus

~ Documents

rv

01

D
~

Example Class System Object Figure Graphical User Interface Command Shortcut SIMUlINK ~ Simulink Model Simulink Project }

ij

L::I

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

.... ~ ~

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 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 c' 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
Capture

ALSAAudio Playbact

GPIORead

GPIOWrite

LEO

SOL Vidao Oisplay

UOP ReceivE-

~ ~

UOP Send

V4L2Video
CapturE-

I ~::-;~;I

!ExampI6}

eSpeak Speec:h

Texl to

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

1.~.~.9.~.I .... ~..... ~ey~


IledO (Green)

[ ............................................. ..! ..
.. i

............................................

View LED location

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

[1[---------]
Output data type:

Output minimum:

Output maximum:

I boolean

Ii

O Lock output

data type setting against changes by the fixed-point tools World value (RWV._) .

Input and output to have equal: ~I Integer rounding mode: ~o~_n_d

._=:J

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 If done, c1ick OK button.

data type.

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) per period

Number of offset samples

= phase '" Samples

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.~~;"-'._.'_ Amplitude:
'--.M ._.. ---_ "._ -- _-- ..---.......................

------'-~J

Frequency (rad/sec):

~ Interpret veetor parameters as 1-0 OK Apply

For testing, we use eonfigurations Sine type: Time base Time (t): Use simulation Amplitude: 1 Bias: O Frequeney: 1

as follows:

time

Phase: O Sample time: 30 Cheeked lnterpret lf done, click OK button.

veetor parameters

as l-D

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

d helloworld

Test and Validate

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. Pi and run it.

Pi, you must configure. How? Click menu Tools -> Run on Target Hardware

-> Prepare

-Code
>

I Tools
F?':!\

~._._-_.~---_. __ ._----------------------------L~lp_ . , Library Browser Model Explorer Run on Target Hardware ~ Prepare to Run ... Install/Update Support Package.

...i~
~

---:

Update Firmware ...

lhen you will obtain a dialog as below.

S,~tt: I So~r
i

Th

",.""1 is ""I ""I to um


hilr""'lt'

""y Lo,gd h.,dw.'e.

Set ll1<> "Torgol

"""Ih""",'

porilltlld"

t miOll rou' lorgol

"""4 ."

!" !
i

I
I

~'f>port Optjmlratiol'l O"9OCltiu


OAU
Hiiif~ilIrl!

! I' y1ltIf

e 15 t\t Ii:!tf!d llle

'Th'get har<hvare'

optioos, l'\:!tllll the IlIfget foI' VOUfhat'<l""llt~, aro dld:'lnSli3~ 5uwmt

Te ,l'\:!tall tJ1e tll~

did"Tilol:s', did'R.un on 1llrgetHMd"'Me'.


RleCUoo

radage",'.

Implemel\tiitioo

Target MIlrdware

i " S'mulat!Otl Taln,et


i

Mod.1 RvI.,.ncin

r"9"1

h..-dv,,,,,,,,

[!Y'~rr'f ~,_.

ll:un on 1.1'9.1 Hmfw.t'l'

Select Raspberry Click OK button.

Pi on Target hardware.

After that, you will see Raspberry

Pi configuration.

mfguraton Parametefs: ootit1ed/Run an l:'.artlwar~CtlnJigura


T.91"1 D.t3 Op(,mllauon
Diagntmits H dw " Impl nLll>On

f,AdiW)

rn.,d''''11I ~"'"
tu~

5i9O mo tonng ond pcn:m

MQdellt~lerenong
" Smu Run Otl '9ft '9tt H ftotrt

O EM
Ovtrrun d

em.1 modq
l!lOn

C [na

av.e'1\#lde~et1

Fill Host name, User name and Password Note: You ean define hostname's Raspberry

for your Raspberry Pi device. 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 Simulation Analysis Code lools to ExternaI, shown in Figure below. Help

~ lGl~
S ~helloworld ~ ~" =t
SineWsw RASPBERRYPI

~
boolean

"i,'t;'l

led{) (Gfeen)

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

,;

/ I

3.3 V

6V 5V

12CO_SDA 12CO_SCL GPI04 GND GPIO 17 PCM_DIN GPIO 22 3.3 V SPlO_MOSI SPlO_ ISO SPlO_SCLK GND

GND UARTO_TXD UARTO~XD GPIO 18 GND GPIO 23 GPIO 24 GND GPIO 25 SPlO_CEO_N SPlO_CE1_N

When I wrote this book, there are two Raspberry you know Raspberry Pi revision?

Pi revision types, revision 1 and 2. Basically, it's not big changes. How do

You can know what your Raspberry

Pi revision by typing this script on terminal.

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 second 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. Further 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 ++ Sine W sve Data Type CooW1Sion

nn
GPI04 GPIO 4Wrile
RASPBERRYPI Logicsl

Operalof Sccpe

nn
GPIO 17

GPI017Wrile

RASPBERRYPI

nn
Logcsl Opaator1

GPIO 18 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: GPIO number: I B Rev2

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 Time (t): [~se_~~m~ati~_~tim; Amplitude: 1 Bias: . . _

'Y._I

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

13; 12;
{
~l

Toid setup ()

1/ initlali:e the digital pin as pinJlode(out1, OUTPUT); pinUode(out2,OUTPUT);

output.

Joid loop ()

digital~Lite(out1, digitalULite(out2, de1ay(lOOO); digitalWLite(out1, digitaHhit.e(out2, delay(lOOO); digita1ULite(out1, digita1~Lite(out2, de1ay(lOOO);

HIGH); HIGH);
Ii wait fOL a second

HIGH);
LOlJ); Ii wait fOL a second LO~);

HIGH);
// wait fOL a second

<

>

Write this code into your Arduino editor.

int outl - 13; int out2 12; void setup() { 1,1 nitialze pinMode(outl, pinMode(out2,

~he dl'gl't~.L'Pl'11 lS an ou t_pu t, , 'c. c. OUTPUT); OUTPUT);

}
void loop() { digitalWrite(outl, digitalWrite(out2, delay(1000); digitalWrite(outl, digitalWrite(out2, delay(lOOO) ; digitalWrte(outl, digitalWrite(out2, delay(lOOO);

HIGH); HIGH);

II wait for a second


HIGH); LOW);

Ii wait for a second


LOW); HIGH);

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 GPI018 Read Scope

D
RASPBERRYPI

nn
GPIO 17 GPIO 17 Read

Sccpe1

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: GPIO number: Sample Time:

I Model B Rev2
17 0.1

.. 1

[Viewpin mapl

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 Cb

(e).
c::.j
V 4L2 Video Capture

Mathworks has already testes some cameras as follows: Logitech Logitech Logitech Logitech QuickCam Pro 9000 QuickCam Pro 3000 Webcam C600 HD Webcam C310 by Ubuntu and Raspberry Pi, you can visit http://www.ideasonboard.org/uvc/ .

For a list ofUVC cameras supported

In this scenario, I used Microsoft LifeCam VX-700.

After plug-in, you can execute this command

to Raspberry Pi console.

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.

1DisplsyR

RASPBERRYPIR
1".'.,

eJ 'r-'i

G
B

Displsy G

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 Image size: ~_2 __ 0

Pixel format: ~IR_G_B Sample time:

-:J :J

__

O_K

_11

Cancel

II

Help

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


Select: Solver Data ImportjExport t> Optimization I> Diagnostics Hardware Implementation Model Referencing I> Simulation Target Run on Target Hardware Target hardware seleetion Target hardware: ~~p~be_r_ry_p_i _~~~ Signal monitoring and parameter tuning ~ Enable Externai mode 1772.5 __ ~

on Hardware Confi

TCP/IP port (102.4-65535): Overrun deteetion ~ Enable overrun deteetion

Board information Host name: User name: PassNord: Build direetory:

~~_~~~~:~_=:-~___ __ ... _~-..-..-.-.----... _-----.---------.----:-=~=_

[2~~_~_~Le-~==:_-:_::~:::::::==~===:.:=::_~-:=====--=_:~:==

Before running, File Edit

change Normal to Externai. View Display Diagram Simulation Analysis


i

Code

Tools
T

Help

IT:l
Model Browser videodemo

0~

..

si ~IG)

@,

I ~J

ii:--

...

Now click menu Tools -> Run on Target Hardware -> Run. If success, you will see RGB values on Display.

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

-.---.---------~-----

S '~:
-~ ~
li<1i1

~videodemo

RASP8ERRYPIR
(0)

---, t......... ,

ri
I
I-

I I .. I I

6911 6311 6311


6411

6711
7211

7311

70 I' 6411 731!


1

G 'B -

-Drs~ayR

7211

73111:'

V4L2 Video Ca(iure

10211
9611

.____ .__.__ m_~~JI ___ m______ ._.m_________ m~~Jc=_L ______


DsplayG

9811

1031C 971C= 9slC

102

----.1

I
L__________.~?J

11 9611 9411

10211 1031C 9611 971C 10611 1031C 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 blog.aguskurniawan.net.

. My blog: http://

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

You might also like