You are on page 1of 11

Getting Started with MATLAB Support Package for

Raspberry Pi Hardware
This example shows you how to use the MATLAB Support Package for Raspberry Pi
Hardware to perform basic operations on the hardware such as executing shell commands,
turning an on-board LED on or off and manipulating files.
Introduction
The MATLAB Support Package for Raspberry Pi Hardware enables you to communicate
with Raspberry Pi hardware remotely from a computer running MATLAB. The support
package includes a MATLAB command line interface for accessing Raspberry Pi hardware's
I/O peripherals and communication interfaces. Using this command line interface, you can
collect data from sensors connected to Raspberry Pi hardware and actuate devices attached to
Raspberry Pi hardware.
In this example you learn how to create a raspi object to connect to Raspberry Pi hardware
from within MATLAB. You examine the properties and methods of this object to learn about
the status of basic peripherals such as digital I/O pins (also known as GPIO), SPI, I2C, and
Serial. Using this object, you execute shell commands on your Raspberry Pi hardware and
manipulate files on the Raspberry Pi hardware.
Prerequisites

If you are new to MATLAB, it is helpful to complete the Interactive MATLAB


Tutorial, reading the Getting Started section of the MATLAB documentation and
running Getting Started with MATLAB example.

You must complete the firmware update for Raspberry Pi hardware to be able to use
the MATLAB interface for Raspberry Pi hardware. MATLAB communicates with the
Raspberry Pi hardware by connecting to a server running on Raspberry Pi. This server
is built into the firmware shipped with the support package. If you did not use Support
Package Installer to update the Raspberry Pi firmware, enter targetupdater in the
MATLAB Command Window and follow the on-screen instructions.

Required hardware
To run this example you need the following hardware:

Raspberry Pi hardware
A power supply with at least 1A output

Create a raspi object


Create a raspi object.
rpi = raspi();

The rpi is a handle to a raspi object. While creating the rpi object, the MATLAB connects to a
server running on the Raspberry Pi hardware through TCP/IP. If you have any issues with
creating a raspi object, see the troubleshooting guide to diagnose connection issues.
The properties of the raspi object show information about your Raspberry Pi hardware and
the status of some of the hardware peripherals available. Either the numeric IP address or the
hostname of your Raspberry Pi hardware and the port used for TCP/IP communication are
displayed in the DeviceAddress and Port properties. The raspi object detects the model and
version number of your board and displays it in the BoardName property. The GPIO pinouts
and available peripherals change with the model and version of your Raspberry Pi hardware.
The AvailableLEDs property of the raspi object lists user controllable LED's. You can turn a
user LED on or off using the writeLED method.
AvailableDigitalPins, AvailableI2CBuses, and AvailableSPIChannels properties of the raspi
object indicate the pins that you can use for digital I/O, I2C buses, and SPI channels that can
be used to communicate with sensors and actuators supporting the I2C and SPI
communication protocols. It is not an issue if nothing is listed for AvailableSPIChannels. The
Raspbian Wheezy image shipped with MATLAB does not enable the SPI peripheral to
provide you with more general purpose digital I/O pins. You can enable and disable I2C and
SPI peripherals to suit your needs by loading and unloading Linux kernel modules
responsible for these peripherals.
Turn an LED on and off
There is a user LED on Raspberry Pi hardware that you can turn on and off. Execute the
following command at the MATLAB prompt to turn the LED off and then turn it on again.
led = rpi.AvailableLEDs{1};
writeLED(rpi, led, 0);
writeLED(rpi, led, 1);

While executing the preceding commands, observe the 'ACT' (or 'OK') LED on the Raspberry
Pi hardware and visually confirm the LED operation. If you are unsure where the user LED is
located, execute the following command.
showLEDs(rpi);

You can make the LED "blink: in a loop with a period of 1 second.
for i = 1:10
writeLED(rpi, led, 0);
pause(0.5);
writeLED(rpi, led, 1);
pause(0.5);
end

Execute system commands


The raspi object has a number of methods that allow you to execute system commands on
Raspberry Pi hardware from within MATLAB. You can accomplish quite a lot by executing
system commands on your Raspberry Pi hardware. Try taking a directory listing.

system(rpi, 'ls -al /home/pi')

This statement executes a Linux directory listing command and returns the resulting text
output at the MATLAB command prompt. You can store the result in a MATLAB variable to
perform further processing. Establish who is the owner of the Desktop folder under /home/pi.
output = system(rpi, 'ls -al /home/pi');
ret = regexp(output, '\s+[\w-]+\s+\d\s+(\w+)\s+.+Desktop\s+', 'tokens');
ret{1}

You can also achieve the same result using a single shell command.
system(rpi, 'stat --format="%U" /home/pi/Desktop')

Perform the LED exercise this time using system commands.


system(rpi, 'echo "none" | sudo tee /sys/class/leds/led0/trigger');
system(rpi, 'echo 0 | sudo tee /sys/class/leds/led0/brightness');
system(rpi, 'echo 1 | sudo tee /sys/class/leds/led0/brightness');

These commands are equivalent to the writeLED method with arguments 0 and 1 for the LED
state. The user LED is, by default, wired to trigger off of SD card activity. The LED is rewired to not have a trigger, enabling setting the LED state manually. You can return the LED
back to its original state.
system(rpi, 'echo "mmc0" | sudo tee /sys/class/leds/led0/trigger');

You cannot execute interactive system commands using the system() method. To execute
interactive commands on the Raspberry Pi hardware, you must open a terminal session.
openShell(rpi)

This command opens a PuTTY terminal. Log in with your user name and password. The
default user name is 'pi' and the default password is 'raspberry'. After logging in, you can
execute interactive shell commands like 'top'.
Manipulate files
The raspi object provides the basic file manipulation capabilities. To transfer a file on
Raspberry Pi hardware to your host computer you use the getFile() method.
getFile(rpi, '/home/pi/ocr_pi.png');

You can then open the file 'ocr_pi.png' containing an image in MATLAB:
img = imread('ocr_pi.png');
image(img);

The getFile() method takes an optional second argument that allows you to define the file
destination. To transfer a file on your host computer to Raspberry Pi hardware, you use
putFile() method.

putFile(rpi, 'ocr_pi.png', '/home/pi/ocr_pi.png.copy');

Make sure that file is copied.


system(rpi, 'ls -l /home/pi/ocr_pi.png.copy')

You can delete files on your Raspberry Pi hardware using the deleteFile() command.
deleteFile(rpi, '/home/pi/ocr_pi.png.copy');

Make sure that file is deleted.


system(rpi, 'ls -l /home/pi/ocr_pi.png.copy')

The preceding command should result in an error indicating that the file cannot be found.
Summary
This example introduced the workflow for using the MATLAB Support Package for
Raspberry Pi Hardware. Using the Raspberry Pi support package, you turned the user LED on
and off, executed system commands and manipulated files on Raspberry Pi hardware.

Open a Command-Line Session with Raspberry Pi


Hardware
This topic shows you how to configure and open a command-line session with the target
hardware.
To open a connection to your board:

If you configured your Raspberry Pi to automatically obtain an IP address using


DHCP, communicate with your board using the host name you assigned to the board
during the firmware update process.
For example, if the board is named raspberrypi-ah, enter the following in a
MATLAB Command Window:
h = raspberrypi('raspberrypi-ah')
h.openShell('ssh')

If you configured your Raspberry Pi to use a static IP address during the firmware
update process, use that IP address to communicate with your board.
For example, if the board's IP address is 192.168.1.2, enter the following in a
MATLAB Command Window:
h = raspberrypi('192.168.1.2')
h.openShell('ssh')

1. Connect an Ethernet cable from your host computer to the board.


2. Communicate with the board:

If you configured your Raspberry Pi to automatically obtain an IP address


using DHCP, communicate with your board using the host name you assigned
to the board during the firmware update process.
For example, if the board is named raspberrypi-ah, enter the following in a
MATLAB Command Window:
h = raspberrypi('raspberrypi-ah')
h.openShell('ssh')

If you configured your Raspberry Pi to use a static IP address during the


firmware update process, use that IP address to communicate with your board.
For example, if the board's IP address is 192.168.1.2, enter the following in a
MATLAB Command Window:
h = raspberrypi('192.168.1.2')
h.openShell('ssh')

3. When a PuTTY terminal window opens, press the Enter key on your keyboard. The
terminal window displays the Linux command line.
4. At the Linux command line, log in by entering the user name and password. For
example:
5. raspberrypi-boardname login: pi
6. Password: raspberry
7. When you are finished, enter logout on

the Linux command line, and close PuTTY

to end the serial connection.

Your Raspberry Pi hardware is a mini-Linux computer. Disconnecting the power cable


without properly shutting down can corrupt the SD card and cause Linux boot failures. To
avoid this problem, shut down your Raspberry Pi hardware using Linux commands.
Using the MATLAB Command Window, enter:
h = raspberrypi
h.execute('sudo shutdown -h now')

When the Raspberry Pi shuts down, all LEDs except for the PWR LED turn off. Power
recycle your Raspberry Pi hardware when you want to boot into Linux kernel again.
To reboot your Raspberry Pi hardware, execute the following command:
h.execute('sudo shutdown -r now')

Remote Execution of Linux Commands

This example shows you how to run remote Linux command on your Raspberry Pi
hardware.
Introduction
Raspberry Pi hardware runs a Linux distribution as the operating system. Using utilities
shipped in the Simulink Support Package for Raspberry Pi Hardware, you can remotely
execute Linux commands on the Raspberry Pi hardware directly from the MATLAB
command line. For example, you can run and stop a Simulink model, list the contents of a
directory, look up the CPU load of a process running on the Raspberry Pi hardware, etc. You
can also launch an interactive PuTTY SSH session directly from within MATLAB.
Prerequisites

We recommend completing Getting Started with Raspberry Pi Hardware example.

Create a Communication Object


Simulink Support Package for Raspberry Pi Hardware uses an SSH connection over TCP/IP
to remotely execute Linux commands while building and running Simulink models on the
Raspberry Pi hardware. You can use the infrastructure developed for this purpose to
communicate with the Raspberry Pi hardware.
1. Create a raspberrypi object by executing the following on the MATLAB command line:
h = raspberrypi

The raspberrypi function returns a connection object, h, for Raspberry Pi hardware that has
been set up using the targetupdater function. The hostname, user name, and password used to
construct the raspberrypi object are the default MATLAB session values for these parameters.
Simulink Support Package for Raspberry Pi Hardware saves one set of communication
parameters, i.e. hostname, user name and password, for the Raspberry Pi hardware as default
MATLAB session values. Note, the default MATLAB session values for the communication
parameters are first determined during the firmware update process. The communication
parameters may subsequently be changed using the Tools > Run on Target Hardware >
Options UI in a Simulink model and are sticky, meaning that once you change the
communication parameter values they are saved as default MATLAB session values, and are
used for all Simulink models.
You may explicitly specify the hostname or IP address, user name, password when you create
the raspberrypi object:
h = raspberrypi('<hostname or IP address>', '<user name>', '<password>');

The command above shows how to specify hostname, user name, and password. You may
want to use this form if you have multiple Raspberry Pi hardware in your network that you
need to distinguish individually.
2. Test connection to your Raspberry Pi hardware by executing the following command on
the MATLAB command line:

message = h.connect

If successful, the connect method returns 'Connection successful' in the output argument
message. The connect method executes the "echo Connection successful" Linux command
over SSH. In case of a connection failure, a diagnostics error message is reported on the
MATLAB command line. If the connection has failed, the most likely cause is incorrect IP
address. To diagnose connection problems refer to the Troubleshooting Connection
Problems section below.
Use Execute Method to Get a Directory Listing
You can use the execute method of the raspberrypi object to execute various Linux
commands on the Raspberry Pi hardware from MATLAB.
1. Execute the following on the MATLAB command line:
[status, message] = execute(h,['ls -al ~'])

If successful, the command above returns a status of 0 and a message representing the output
returned by the executed command. The returned message is a directory listing of the home
directory.
2. Execute the following on the MATLAB command line:
execute(h,['ls -al ~'], true)

This command executes the same Linux command as in Step 1 of this task but directly
outputs the result on the MATLAB command line rather than returning it in a variable.
Open an Interactive PuTTY SSH Session
The execute method of the raspberrypi object runs a Linux command on the Raspberry Pi
hardware using SSH protocol. Alternatively, you can open a PuTTY SSH terminal by
executing the following command:
openShell(h,'ssh')

The PuTTY SSH terminal enables you to run interactive Linux commands on Raspberry Pi
hardware. You may, for example, execute the same Linux commands introduced in the
previous section to get a listing of the home directory.
Run/Stop a Simulink Model
Simulink Support Package for Raspberry Pi Hardware generates a Linux executable for each
Simulink model you run on the Raspberry Pi hardware. The generated executable has the
same name as the Simulink model and is stored in a directory under the Build directory you
selected. To run/stop a Simulink model, you can use the run and stop methods of the
raspberrypi communication object.
1. To run a Simulink model you previously run on the Raspberry Pi hardware, execute the
following command on the MATLAB command line:

run(h,'<model name>')

where the string '<model name>' is the name of the Simulink model you want to run on the
Raspberry Pi hardware. The run method launches the Linux process corresponding to the
Simulink model you specified.
2. To stop a Simulink model running on the Raspberry Pi hardware, execute the following
command on the MATLAB command line:
stop(h,'<model name>')

This command kills the Linux process with the name '<model name>' on the Raspberry Pi
hardware. Alternatively, you may execute the following commands to accomplish the same:
[~, pid] = execute(h,'pidof <model name>');
[st, msg] = execute(h,['echo ', h.Password, ' |sudo -S kill -9 ', pid])

Troubleshooting Connection Problems


1. How do I verify my Ethernet connection?
Verify that the FDX, LNK and 10M LEDs on your Raspberry Pi hardware is on and that the
green LNK LED is blinking. If not, then the other end of the Ethernet connection may not be
live or the Ethernet cable might be bad.
2. What are the different Ethernet connection options for the Raspberry Pi hardware?
Your Raspberry Pi hardware must be connected to:
a) a LAN/WAN network with an Ethernet cable
b) the host computer directly with an Ethernet cable

If your Raspberry Pi hardware has a direct connection to the host computer, you must set a
static IP address for your Raspberry Pi hardware. You must also ensure that the Ethernet card
in your host computer talking to your Raspberry Pi hardware has been assigned a static
IP address.
3. How do I find the IP address of the Raspberry Pi hardware?
You can use your Raspberry Pi hardware in one of the following configurations:
i). Desktop with a monitor and keyboard attached
ii). Headless (i.e. no monitor or keyboard)

Below you will find instructions on how to find the IP address of the board according to the
configuration you are using:
i) Desktop: If you are operating your Raspberry Pi hardware with a keyboard and monitor
attached, you can find the IP address of the board by logging in to your Raspberry Pi
hardware and typing the following command on a Linux shell:

# ifconfig

This command lists the network information for all Ethernet interfaces on your board.
Example output looks like the following:
eth0

Link encap:Ethernet HWaddr b8:27:eb:63:40:b8


inet addr:172.28.145.190 Bcast:172.28.145.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:27224 errors:0 dropped:0 overruns:0 frame:0
TX packets:733 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:2801074 (2.6 MiB) TX bytes:107019 (104.5 KiB)
.....

The wired Ethernet connection on your Raspberry Pi hardware corresponds to the network
interface 'eth0'. The IP address of the wired connection 'eth0' is displayed in the 'inet addr'
field.
ii) Headless: If you are using your Raspberry Pi hardware in headless configuration, there are
a number of ways to find the IP address:
a) If you configured your board to automatically get an IP address, you can simply use the
hostname you assigned to communicate with your board. Assuming that you assigned
'raspberrypi-john' as the hostname during firmware update, you can connect to your board
using the following commands:
h = raspberrypi('raspberrypi-john')
h.connect

You may also try pinging your board by executing the following on the MATLAB command
line:
!ping raspberrypi-john

b) Your Raspberry Pi will speak its IP address when it boots. In order to hear the IP address,
you must connect a pair of headphones / speakers to the analog audio output connector.
c) You can configure your board to automatically send an e-mail whenever the IP address
changes. The Raspbian Wheezy image distributed by MathWorks is configured to include the
'ssmtp' package that helps you send an e-mail from the Raspberry Pi hardware. The ssmtp
package is a simple mail transfer agent (MTA) that requires an authenticated e-mail server to
send e-mail. For simplicity, we configured ssmtp to use Gmail. The configuration file for the
ssmtp is located in '/etc/ssmtp/ssmtp.conf' file on the Raspberry Pi hardware. The contents of
this file is given below:
#
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
root=postmaster
# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
mailhub=smtp.gmail.com:587

# Where will the mail seem to come from?


rewriteDomain=gmail.com
# The full hostname
hostname=gmail.com
# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
FromLineOverride=YES
AuthUser=pi
AuthPass=raspberry
UseSTARTTLS=YES

Modify the 'AuthUser' and 'AuthPass' entries in this file to reflect you Gmail account user
name and the password to enable automatic e-mail feature. For example if your Gmail
account user name is 'michael_doe' and your password is 'michael101', modify the relevant
entries in the '/etc/ssmtp/ssmtp.conf' file as shown in the following:
AuthUser=Michael_doe
AuthPass=michael101

You may also change the mail server if you wish to use a mail server other than Gmail.
Modify the appropriate entries in the '/etc/ssmtp/ssmtp.conf' to match your e-mail server
settings. The auto-email feature uses a shell script to send an e-mail whenever IP address
changes. As a last step, you need to make this script executable. Execute the following
command on a Linux shell on your Raspberry Pi hardware
sudo chmod ugo+x /etc/network/if-up.d/mailip

To test the auto-email feature, execute the following on a Linux shell on your Raspberry Pi
hardware:
sudo /etc/network/if-up.d/mailip

d) You can configure your Raspberry Pi hardware to use Dynamic DNS (DDNS). Dynamic
DNS is a method of updating the Domain Name System to point to a changing IP address on
the Internet. Dynamic DNS requires a DDNS server. You can, for example, use
dnsdynamic.org. The instructions for setting up a dynamic DNS client on Raspberry Pi
hardware can be found elsewhere on the Internet.
4. How do I test the SSH connection to Raspberry Pi hardware?
To test the SSH connection to your Raspberry Pi hardware, create a raspberrypi
communication object and execute the following command on the MATLAB command line:
message = connect(h)

If successful, the connect method returns 'Connection successful' in the output argument
message. In case of a connection failure, a diagnostics error message is reported on the
MATLAB command line. If the connection has failed, the most likely cause is the wrong
hostname or IP address. Follow 3 above to find the IP address. If you found the IP address
and still cannot connect to the Raspberry Pi hardware, refer to 5.
5. I know the IP address of the Raspberry Pi hardware but SSH connection still fails.

There are a couple of likely scenarios. If your Raspberry Pi hardware is connected directly to
the host computer using an Ethernet cable, you must make sure that the Ethernet card on your
host computer to which the Raspberry Pi hardware is connected has a static IP address. For
instructions on how to assign a static IP address to your Ethernet card under Windows refer to
the following guide. You must also ensure that the Raspberry Pi hardware and your computer
is on the same subnet. For example, if you assigned a static IP address of 192.168.1.1 to your
Ethernet card on the host computer, and the subnet mask is set to 255.255.255.0, you must
assign an IP address in the range 192.168.1.2 to 192.168.1.254 to the Raspberry Pi hardware
and a subnet mask that matches that of your host computer (usually 255.255.255.0).
If you are on a LAN/WAN network and cannot establish an SSH connection to the Raspberry
Pi hardware, check that you do not have a firewall or anti-virus program that blocks TCP/IP
port 22 used by the PuTTY SSH client. If you do, add this port to the list of TCP/IP ports that
are not blocked or disable your firewall or anti-virus program. If SSH connection still fails,
check that the SSH daemon is running on the Raspberry Pi hardware. To do this, execute the
following on your Raspberry Pi hardware:
ps aux | grep /usr/sbin/sshd

This command returns the status of the SSH server. You should see an output similar to the
following if the SSH server is running:
root
1915
/usr/sbin/sshd
...

0.0

0.5

6200

1008 ?

Ss

10:57

0:00

If SSH server is not running for some reason, try restarting the server by executing the
following command on your Raspberry Pi hardware:
sudo /etc/init.d/ssh restart

If SSH connection is still failing, restart network:


sudo /etc/init.d/networking restart

Was this topic helpful?