Sunteți pe pagina 1din 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)

7."'~O

" H~OO

7. ?'O,;,

S. fOr:;:)

~ ~?)(!O

D'

(l\}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.

to

You ean see the menu as below.


Search DoclJmentation

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)

Folder

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

Seleet Internet

(recommended).

After that, cliek Next button.

8rowse ...

Support Package Installer

Select a support

package

Select a support package to install or update.


Action
1

D Reinstall

Arduino

D Install

BeagleBoard

D Install
D Install
D Install

4
5

'/

:-...

Support Package for

-- .

Installed
Version

lates1
Version

Required Base Produd

3,0

Supported Host PI

Simulink

Windows 132-bit),\

3.0

' Simulink

Windows 132-bit),\

Gumstix Overo

1.0

Simulink

Windows (32-bit),\

LEGO MINDSTORMSNXT

3.0

Simulink

PandaBoard

3,0

3.0

",

'.

,I

Windows (32-bit),\

V.lindows 132-bit),\

Simulink

-- Simulink

~oo

1.0

.'

'"""""

"

Windows 132-bit),\

6 ~

Install

Raspberry Pi

L-J

Imtall

USRP{RJR.adio

5.0

Communicatons System Toolbox

D Install

Digilent Analog Discovery

1.1.1

Data Acquisition Toolbox

Windows 132-bit),\

Install

A.n310gDevices DSPs

2.0

Embedded Coder

Windows (32-bitl,\
., -

Install

Green Htlls r.."ULTI

3.0

Embedded Coder

Windows 132-bitl,\

Xilinx Zynq-7000

1.0

Embedded Coder

Windows (32-bit),\

10 ~
11

l~ Install

Installation fulder:

"

Windows (32-bitl,\

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

I[

Why are some rows disabled?

Find more supported hardware

Check Raspberry

Pi and then click Next button.

You wil see a license agreement

as below.

<Ba~

Next>

I[

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

OR ACCESSING THESE MATERIALS VOU ACCEPT THE TERMS OF THIS


I

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

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

Choose Raspberry Pi board. Then click Next button.

----_._----

II

Next

>

II

Cancel

>

Support Package Installer


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

Dovmload from Internet

O Get from

(recommended)

local folder

Download folder:

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

WARNING: Download size is approxmately


Download may take several mnutes.

Choose Download from Internet

1GB.

(recommended).

If done, click Download button.


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

Cl

Support Package Installer


Configure board
The board .\lilI be configured
Board name:

with the foilowing name and

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

.. .... .....
__
..

Configure IP settings for wired Ethernet

IP

...
__
....

settings:
]
_

More info

Assignment
get IP aderess

Automatica!ly
ManuaDy enter

IP

connection

IP

IP address

Settings

IP address:

10.10.10.9

Network mask:
Default gateway:

255.255.255.0
10.10.10.1

< Back
<

FilI hostname for Raspberry Pio

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:

D:

~!

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

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

Now turn on your Raspberry

Pio Read section 2.3.

II

Next

>

II

CancE

You may configure


After Raspberry

your Raspberry

Pi is running

Pi for instance

SSH. You can read it on section 2.4.

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:

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

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

Product page at mathw(

i
i

I
1:

Getting Started with Raspberry Pi Hardware

I!tl ModE

~
~

I~
i

...-..f~

I
t

rQ:] ~
-"

I~l
.~

F~~'J r:TwI ~~]


I ~~'I

Communicating

: ~~

Now you see Raspberry

Pi on Simulink Library Browser.

with Raspberry Pi Hardware

I!tl ModE

liI
fil'

Simulink library Browser

File

Edit

View

Help
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

J'.'

ALSAAudio
Capture

.rtr.

GPIO Read

"qr
CO

rn-_

G
.rtr.

1_

~
UOP Reoeive

~
V4L2Video
CaptUTe

GPIOWrite

SOL Vdeo
Displsy

LEO

"'.:.,c:: .

-410

ALSAAudio
PIsybaO:

-t-..: .~

='""':~

Pi Hardware

~:-'~I

UDP Semi

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

startx

2.4 SSH
You may need SSH to manage Raspberry

$ sudo apt-get

Pi remotely. How to instam You can write his script

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

$ sudo update-rc.d

and then reboot your Raspberry

file

ssh defaults

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

L... Logging

Basic options for your Pu TTY session

Specify the destination you want to connect to

~. Terrninal

Keyboard

BeU
L... Features
a"Window

!....Appearance
j.. Behaviour

Translation

Selection

L... Colours

8..Connection

Data

! Proxy

Telnet

RJogin

Host liame (or

IP address)

~fo_rt

I~~

1192.168.1.61
Connection

type:

O Ra~

O Ielnet O RJog[n

O SeDal

@SH

Load. save or delete a stored session


Saved Sessions
I~~;b~;;;;pi................

..1

Default Settings
Mac Mini
akurdb .doudapp .net
raspbenypi

ctl' SSH
L... Serial

Oose
'indow on exit:
N-ever

O A1ways
~out

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

5imulink library Browser


Help

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

GPIO Read

ALSAAudio
Playbadt:

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

CD""-.'~
"@

LEO

-. .-"

~
~

UDP Reoeive

V4L2Video
Capture

eSpes,Textto
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

Example

ij

Class
System Object
Figure
Graphical User Interface
Command Shortcut

SIMUlINK
~

Simulink Model

L::I

Simulink Project

~ Documents

01

Function

Save
Workspace

Ctrl-N
Agus

Select Simulink Model.


Then you obtain a Simulink dialog as below.

rv

untitled
File

Edit

View

Display

Diagram

Simulation

Analysis

Code

Tools

Help
Normal

Model BrO'Nser
untitled

100%

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

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

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

Pi Hardware

Capture

ALSAAudio
Playbact

GPIORead

GPIOWrite

SOL Vidao

LEO

Oisplay

UOP ReceivE-

~
~

V4L2Video

I ~::-;~;I

CapturE-

eSpeak

UOP Send

!ExampI6}

Texl to

Speec:h

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

Model Browser

toa.. helloworld

fR";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 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~

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

Edit

O~

r-

View

Insert

T 0015

Desktop

Window

Help

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:

O Lock output

I boolean

data type setting against changes by the fixed-point tools

Input and output to have equal: ~I

World value (RWV._)

Integer rounding mode: ~o~_n_d

Ii

._=:J

o:]

Saturate on integer overflow

Sample time (-1 for inherited):

__

_11

O_K

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.

3.2.3 Configuring

Sine Wave

Double click Sine Wave, you will obtain a dialog as below.

data type.

Samples per period

= 2"'pi I (Frequency

Number of offset samples

'" Sample time)

= 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

Sine type: Time base


Time (t): Use simulation
Amplitude: 1
Bias: O
Frequeney: 1

Phase: O
Sample time: 30
Cheeked lnterpret

Apply

as follows:

time

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

Test and Validate

helloworld

If success, you don't see the error dialogo


Now you are ready to deploy to Raspberry

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

To run this model to Raspberry


to Run.

-Code

I Tools

...i~

>

F?':!\

Pi and run it.

~._._-_.~---_. __ ._----------------------------L~lp_
.
,
Library Browser
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:
I So~r
i

!"

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

Hiiif~ilIrl!

Implemel\tiitioo

Mod.1 RvI.,.ncin

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

i " S'mulat!Otl Taln,et

Th

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

! I' y1ltIf

hilr""'lt'

Te ,l'\:!tall tJ1e tll~

Target MIlrdware

r"9"1

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

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

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

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

Pi on Target hardware.

Click OK button.
After that, you will see Raspberry

Pi configuration.

"""Ih""",'

porilltlld"

t miOll rou' lorgol

optioos, l'\:!tllll the IlIfget foI' VOUfhat'<l""llt~,

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


RleCUoo

Select Raspberry

Set ll1<>"Torgol

'Th'get har<hvare'

aro dld:'lnSli3~

5uwmt

radage",'.

"""4 ."

-> Prepare

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


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

MQdellt~lerenong
" Smu
Run Otl

'9ft
'9tt H ftotrt

f,AdiW)

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

5i9O mo tonng ond pcn:m

O EM
Ovtrrun d

C [na

l!lOn

av.e'1\#lde~et1

Fill Host name, User name and Password


Note: You ean define hostname's

tu~

em.1 modq

for your Raspberry Pi device.

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
Simulation

Analysis

Code

lools

to ExternaI, shown in Figure below.


Help

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

SineWsw

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

When I wrote this book, there are two Raspberry


you know Raspberry

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

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

Pi revision?

You can know what your Raspberry

UARTO_TXD

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

nn

boolesn
++
Sine W sve

GPI04

Data Type CooW1Sion

GPIO 4Wrile
RASPBERRYPI
Logicsl

nn

Operalof
Sccpe

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

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

Toid setup ()

1/ initlali:e the digital pin as


pinJlode(out1, OUTPUT);
pinUode(out2,OUTPUT);

Joid loop ()

~l

output.

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

~""

nn

=t

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

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.

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

(e).
c::.j

Y
Cb

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

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.

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

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

-:J
:J

__
0

Pixel format: ~IR_G_B


Sample time:

__

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

on Hardware Confi

Target hardware seleetion

Select:
Solver
Data ImportjExport
t> Optimization
I> Diagnostics
Hardware Implementation
Model Referencing
I> Simulation Target
Run on Target Hardware

Target hardware: ~~p~be_r_ry_p_i


_~~~

__

Signal monitoring and parameter tuning


~

Enable Externai mode

TCP/IP port (102.4-65535):

1772.5

Overrun deteetion
~

Enable overrun deteetion

Board information
Host name:
User name:

Before running,
File

Edit

PassNord:

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

Build direetory:

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

change Normal to Externai.


View

Display

Diagram

Simulation

Analysis
i

IT:l

0~

..

si
~IG)

@,

Model Browser
videodemo

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

Code

I ~J

Tools
T

Help

ii:--

...

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

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

~videodemo

'~:

-~

ri

li<1i1

RASP8ERRYPIR

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

(0)

I-

7211

6411

7211

73111:'

10211

I
.. I
I

V4L2 Video Ca(iure

6711

70 I'
6411
731!

7311

-Drs~ayR

G 'B

6911
6311
6311

9611

9811

1031C
971C=
9slC

.____
.__.__m_~~JI ___m______
._.m_________
m~~Jc=_L ______
DsplayG

----.1

I
L__________.~?J

10211
1031C
9611
971C
10611
1031C
L_ .. __ .._ .... __ .2~~H_
.... __
._.~_~~]
L

11
9611
9411

102

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.

S-ar putea să vă placă și