Sie sind auf Seite 1von 82

RASPBERRY PI B+

MATLAB TRANING GUIDE

TABLE OF CONTENT
Getting Started with MATLAB Support Package for Raspberry Pi Hardware .......................... 3
Working with Raspberry Pi Camera Board................................................................................. 8
Controlling a 4-Digit 7-Segment Display Using Serial Port ..................................................... 14
Controlling a 4-Digit 7-Segment Display Using I2C ................................................................ 19
Analog Input Using SPI ............................................................................................................ 24
Working with Raspberry Pi Hardware ...................................................................................... 29
Build a Digital Voltmeter .......................................................................................................... 35
Tracking a Green Ball ............................................................................................................... 40
Build a Motion Sensor Camera ................................................................................................. 45
Add Digital I/O Pins to Raspberry Pi Hardware Using MCP23017 ......................................... 48
RASPBERRY PI B+ SCHEMATICS ....................................................................................... 56
BCM2835 .................................................................................................................................. 60
Power Supply ............................................................................................................................ 60
Backpowering............................................................................................................................ 60
GPIO.......................................................................................................................................... 61
General Purpose Input/Output pins on the Raspberry Pi .......................................................... 61
Overview ................................................................................................................................... 61
GPIO Pads ................................................................................................................................. 61
Power-On States ........................................................................................................................ 61
Interrupts ................................................................................................................................... 61
Alternative Functions ................................................................................................................ 62
SPI ............................................................................................................................................. 62
Page Contents ............................................................................................................................ 62
Overview ................................................................................................................................... 62
Software .................................................................................................................................... 62
WiringPi .................................................................................................................................... 63
bcm2835 library ........................................................................................................................ 63
Use spidev from C ..................................................................................................................... 63
Shell........................................................................................................................................... 63
Hardware ................................................................................................................................... 63
Master modes ............................................................................................................................ 63
Transfer modes .......................................................................................................................... 64
Speed ......................................................................................................................................... 64
Chip Select ................................................................................................................................ 64
Linux driver ............................................................................................................................... 64
Speed ......................................................................................................................................... 65
Supported Mode bits ................................................................................................................. 65
Supported bits per word ............................................................................................................ 65
Transfer modes .......................................................................................................................... 65
Deprecated warning................................................................................................................... 66
SPI driver latency ...................................................................................................................... 66
DMA capable driver .................................................................................................................. 66

Troubleshooting ........................................................................................................................ 66
Loopback test ............................................................................................................................ 66
USB ........................................................................................................................................... 67
Page Contents ............................................................................................................................ 67
Overview ................................................................................................................................... 67
Supported devices ..................................................................................................................... 67
General limitations .................................................................................................................... 68
Port Power Limits...................................................................................................................... 68
Devices with known issues ....................................................................................................... 68
Troubleshooting ........................................................................................................................ 69
If your device doesn't work at all .............................................................................................. 69

Contents of raspi:
raspi Access Raspberry Pi hardware peripherals.
raspi is both a directory and a function.
raspi Access Raspberry Pi hardware peripherals.
obj = raspi(DEVICEADDRESS, USERNAME, PASSWORD) creates a raspi object
connected to the Raspberry Pi hardware at DEVICEADDRESS with login
credentials USERNAME and PASSWORD. The DEVICEADDRESS can be an
IP address such as '192.168.0.10' or a hostname such as 'raspberrypi-MJONES.foo.com'.
obj = raspi creates a raspi object connected to Raspberry Pi hardware using saved values for
DEVICEADDRESS, USERNAME and PASSWORD.
Type methods('raspi') for a list of methods of the raspi object.
Type properties('raspi') for a list of properties of the raspi object.
Properties for class raspi:
DeviceAddress
Port
BoardName
AvailableLEDs
AvailableDigitalPins
AvailableSPIChannels
AvailableI2CBuses
I2CBusSpeed
raspi with properties:
DeviceAddress:
Port:
BoardName:
AvailableLEDs:
AvailableDigitalPins:
AvailableSPIChannels:
AvailableI2CBuses:
I2CBusSpeed:

'169.254.0.2'
18726
'Raspberry Pi Model B+'
{'led0'}
[4 5 6 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27]
{'CE0' 'CE1'}
{'i2c-1'}
100000

Methods for class raspi:


cameraboard
configureDigitalPin
configurePin
deleteFile
details
disableI2C
disableSPI
disp
display
enableI2C
enableSPI
getDigitalPinConfiguration
getFile

i2cdev
openShell
putFile
readDigitalPin
scanI2CBus
serialdev
showLEDs
showPins
spidev
system
writeDigitalPin
writeLED

Methods of raspi inherited from handle.


Methods for class handle:
addlistener
delete
eq

findobj
findprop
ge

gt
isvalid
le

lt
ne
notify

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();
3

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

Working with Raspberry Pi Camera Board


This example shows you how to capture and process images from Raspberry Pi Camera Board
module using the MATLAB Support Package for Raspberry Pi Hardware.
Introduction
The Raspberry Pi Camera Board is a custom designed add-on module for Raspberry Pi hardware.
It attaches to Raspberry Pi hardware through a custom CSI interface. The sensor has 5 megapixel
native resolution in still capture mode. In video mode it supports capture resolutions up to 1080p
at 30 frames per second. The camera module is light weight and small making it an ideal choice
for mobile projects.
In this example you will learn how to create a cameraboard object to connect to the Raspberry
Pi Camera Board, capture images from the camera and process them in MATLAB.
Prerequisites

We recommend completing Getting Started with MATLAB Support Package for


Raspberry Pi Hardware example.

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

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

Connect Camera Board


The camera board attaches to the Raspberry Pi via a ribbon cable. One end of the ribbon cable
goes to the camera PCB and the other end attached to Raspberry Pi hardware itself. You need to
get the ribbon cable connections the right way, or the camera will not work. On the camera PCB,
the blue backing on the cable should be facing away from the PCB, and on the Raspberry Pi
hardware it should be facing towards the Ethernet connection.

Create a Camera Board object


Create a camera board object by executing the following command on the MATLAB prompt.
clear rpi
rpi = raspi();
cam = cameraboard(rpi, 'Resolution', '640x480');
The cam is a handle to a cameraboard object. Let's display the images captured from Raspberry
Pi Camera Board in MATLAB.
for i = 1:100
img = snapshot(cam);
imagesc(img);
drawnow;
end
Inspect object properties
The MATLAB command line interface for Camera Board has a number of properties that expose
the features of the Camera. To view the properties of the cameraboard class type the following
on the MATLAB prompt.
cam
Using the properties of the cameraboard object, you can flip the images horizontally or
vertically, change image quality parameters such as brightness, contrast, saturation and sharpness
and access advanced camera features such as image stabilization and image effects. The
Resolution and FrameRate properties cannot be changed after instantiation. If you want to

change these properties, clear the cameraboard object from MATLAB workspace and create a
new object by specifying the new Resolution and FrameRate parameters.
clear cam
cam = cameraboard(rpi, 'Resolution', '320x240', 'FrameRate',
30);
Other properties of the cameraboard object can be changed at any time. But it takes 5 frames for
the new setting to take effect. Let's try flipping the image horizontally.
figure(1);
for i = 1:5
img = snapshot(cam);
end
imagesc(img);
cam.HorizontalFlip = true;
for i = 1:5
img = snapshot(cam);
end
figure(2);
imagesc(img);
Image effects
Let's try a simple image inversion algorithm on the images captured from Raspberry Pi Camera
Board.
figure(1);
for i = 1:100
img = snapshot(cam);
img = 255 - img;
imagesc(img);
drawnow;
end

10

The image inversion creates a color negative effect. The Raspberry Pi Camera Board itself can
invert the images by setting ImageEffect property to 'negative'.
figure(1);
cam.ImageEffect = 'negative';
for i = 1:100
img = snapshot(cam);
imagesc(img);
drawnow;
end
Here is a more interesting image effect.
figure(1);
cam.ImageEffect = 'sketch';
for i = 1:100
img = snapshot(cam);
imagesc(img);
drawnow;
end
Digital zoom
Raspberry Pi Camera Board allows a region of the sensor to be used as the image capture area.
This region, called region of interest (ROI), is specified as a normalized vector [x y w h] where
x, y defines the top left corner and w and h specifies the width and height.

Reducing ROI while holding the output image size constant results in a digital zooming effect.
The following MATLAB code varies the x and y parameters of the ROI to zoom into the lower
right part of the sensor. The approximate area of the sensor being captured is indicated by a red
rectangle.

11

figure(1);
roi = [0 0 1 1];
cam.ROI = [0 0 1 1];
for i = 1:10
img = snapshot(cam);
end
subplot(211);
imagesc(img);
drawnow;
rect = rectangle('Position', [1 1 320 240]);
rect.EdgeColor = 'red';
for i = 1:200
img = snapshot(cam);
if i > 20
fc = (i - 5)*0.0025;
roi(1:2) = [fc, fc];
roi(3:end) = [1-fc, 1-fc];
cam.ROI = roi;
subplot(211);
rect.Position = roi.*[320 240 320 240];
drawnow;
subplot(212);
imagesc(img);
drawnow;
end
end
Record Video
You can record video using the MATLAB command line interface for Raspberry Pi Camera
Board. You start recording video by executing the record command. The record command
returns to the MATLAB command prompt immediately after execution and does not wait for the
entire video to be recorded. During video recording, images captured by the Camera Board are
saved to a file on the Raspberry Pi hardware in raw H264 format. After video recording is
complete, you can bring the video file to your host computer for playback. You cannot take
snapshots while video recording is in progress. Since the recorded video is in raw H264 format,
most players cannot play the video file directly. The recorded H264 stream must be converted to
an appropriate format, such as an MP4, before you can play it back or load it in MATLAB.
Execute the following on the MATLAB command prompt to record video to a file called
'vid.h264' for 30 seconds.
record(cam, 'vid.h264', 30)
The record command starts video recording. It does not block the MATLAB command prompt.
You can perform MATLAB operations while video recording is in progress. However, you
12

cannot take snapshots from the camera. To check if the recording is complete, use the Recording
property of the cameraboard object.
cam.Recording
This property returns false when recording is completed. If you want to stop the video recording
at any time, use the stop method of the cameraboard object.
Bring the recorded raw H264 video stream to your host computer.
getFile(rpi, 'vid.h264')
The raw H264 stream needs to be converted to a video file format, such as MP4, before you can
play it in a media player or load it in MATLAB. You can use FFmpeg to convert the raw
H264 to an MP4 video file. Install FFmpeg to your host computer using the appropriate
download links in the ffmpeg.org web site following appropriate installation instructions. After
you install the FFmpeg, define a MATLAB variable storing the install location. For example:
ffmpegDir = 'C:\ffmpeg-20140218-git-61d5970-win32-static'
Replace the path above with the appropriate FFmpeg installation path in your computer. To
create an MP4 video file out of the raw H264 stream you captured, execute the following on the
MATLAB command prompt.
cmd = ['"' fullfile(ffmpegDir, 'bin', 'ffmpeg.exe') '" -r 30 -i
vid.h264 -vcodec copy myvid.mp4 &'];
[status, message] = system(cmd)
After FFmpeg completes video conversion, you end up with an MP4 video file that you can play
in a media player. You can also load the video to MATLAB for processing. To play the captured
video in MATLAB, execute the following on the MATLAB command prompt.
vid = VideoReader('myvid.mp4')
for k = 1:vid.NumberOfFrames
image(read(vid, k));
drawnow;
end
Summary
This example introduced the workflow for using MATLAB Support Package for Raspberry Pi
Camera Board.

13

Controlling a 4-Digit 7-Segment Display Using Serial Port


This example shows you how to use the serial UART on Raspberry Pi hardware to control a 4digit 7-segment display.
Introduction
Raspberry Pi hardware includes a hardware serial UART port. The serial port enables you to
connect devices supporting serial communications directly to Raspberry Pi hardware. There is a
wide variety of sensors, displays, ADC's, DAC's, etc. supporting serial communications. By
using these devices you can add new capabilities to your Raspberry Pi projects.
In this example, we will concentrate on controlling a 4-digit 7-segment display via serial port.
Note that we will be using the same display as in "Controlling a 4-digit 7-Segment Display
Using I2C". However, this time around we will be using serial port instead of I2C as the
communications interface. We will start by providing an overview of serial communications in
general and then focus on the display and specifics of serial communications interface it
supports. We will learn about MATLAB command interface for serial communication devices
and finally finish the example by displaying numbers and simple characters.
Prerequisites

We recommend completing Getting Started with MATLAB Support Package for


Raspberry Pi Hardware example.

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

Raspberry Pi hardware
A power supply with at least 1A output
Breadboard and jumper cables
A 4-digit, 7-segment display with serial interface from SparkFun

Overview of serial communications


The serial port on Raspberry Pi implements a version of the RS-232 communications where
0/+3.3V TTL logic levels are used instead of +/-12V. RS-232 is a series of standards for serial
binary single-ended data and control signals connecting between data terminal equipment (DTE)
and DCE data circuit-terminating equipment (DCE). RS-232 was once a common peripheral
found in personal computers. It has been largely replaced by USB. Today, TTL logic level
implementation of RS-232 is commonly used for attaching low-speed peripherals to an
embedded system.
Raspberry Pi hardware has a serial port exposed on the 2x13 expansion header. The serial port
has two signals. A transmit signal line, TXD, and a receive signal line, RXD. Peripheral devices
14

supporting serial communications are attached to these pins. There are other signal lines such as
RTS/CTS but these are rarely used.
The RS-232 communications does not have a clock signal. The clock is derived from the
incoming waveform. The transmission starts with a start bit followed by a number of data bits
(usually 8) and ends with a stop bit. The data rate is called baud rate and specifies signaling rate
in bits per second.
Disable serial console
In the default Raspbian Wheezy Linux image, the serial port is configured to be used as Linux
console input/output. This means that you can't use the serial port to communicate with external
devices. In order to use the serial port, you need to disable serial console. First, let's find out the
status of the serial console.
clear rpi
rpi = raspi();
system(rpi, 'rpi-serial-console status')
The command above returns the status of the serial console. If the serial console is disabled,
proceed to the next step. If not, execute the following to disable the serial console.
system(rpi, 'sudo rpi-serial-console disable')
Then reboot your Raspberry Pi hardware.
system(rpi, 'sudo shutdown -r now')
clear rpi;
Overview of 4-digit 7-segment display
The 4-digit 7-segment display from SparkFun is a 4-digit alpha-numeric display with TTL serial,
SPI and I2C interfaces.

This device can display numbers, most letters and a few special characters. Decimal points,
apostrophes and colons are supported. Brightness of the display can be adjusted. The display has
a simple control interface where the master device, Raspberry Pi hardware in this case, issues
commands with parameters to the display device over I2C bus. For example, to clear the display
master sends a command byte of '0x76'. To set the cursor to a particular position, master sends a
15

command byte of '0x79' followed by a byte indicating cursor position (0 to 3). A comprehensive
list of commands is shown in the table below.
Connect the display
To interface the display to Raspberry Pi hardware you need to do some light soldiering. Since we
are using the serial interface of the display in this example, soldier jumper wires to the RX, GND
and VCC pins of the display. You may also choose to soldier some straight male headers to be
able to mount the display on a breadboard for prototyping. Before going any further, you may
also want to follow manufacturer's hardware assembly guide.
Follow the circuit diagram shown below to connect the display to Raspberry Pi hardware.

Display a number
Let's start by creating a serialdev object that will allow us to talk to the display using serial
communications.
segmentDisp = serialdev(rpi, '/dev/ttyAMA0', 9600);
The second argument, '/dev/ttyAMA0', is the name of the serial port. We open this serial port
with a baud rate of 9600 which is the default baud rate supported by the display. According to
the command table for the display, sending a byte in the range 0 - 0xf results in a hexadecimal
number represented by the byte to be displayed. The cursor is initially at position 0, which is the
left most digit, and advances one position each time a character is displayed.
write(segmentDisp, 0);
This should display a '0' on the left most digit of the display. Let's display a couple of more
characters.
write(segmentDisp, 7);
write(segmentDisp, hex2dec('a'));
16

write(segmentDisp, hex2dec('b'));
After executing the commands above, you should see '07ab' displayed on the segmented display.
Clear display screen
To clear the display screen we will follow the datasheet and send '0x76' to the display.
write(segmentDisp, hex2dec('76'));
Set cursor position
To display a particular character at a particular cursor position, you may want to set the cursor
position.
write(segmentDisp, [hex2dec('79'), 2]);
write(segmentDisp, 9);
The commands above will display a '9' at the second digit position of the display.
Advanced: Create a MATLAB class for segment display
You can put all the things we learned about the segment display together and create a MATLAB
class for it. This MATLAB class has methods for setting the cursor position, clearing the display
screen, printing numbers, etc. As an example, we created such a class. Here is an example of
how you would use this class.
clear segmentDisp
sd = raspi.internal.serialsegmentdisplay(rpi);
clr(sd); % Clear screen
print(sd, '112');
print(sd, 'dead');
print(sd, 'beef');
Note that before creating the class, we cleared the original serialdev object called segmentDisp.
You are allowed to create a single object per serial device. The segmentdisplay class internally
creates a serialdev object. Hence you need to clear any serialdev object connected to the display
from MATLAB workspace before instantiating the segmentdisplay.
The segmentdisplay class tries to reduce flickering caused by clearing / re-displaying numbers. It
does so by caching the displayed characters and updating only those that are different. Not all
features supported by the segmented display are implemented. You can use the MATLAB class
we created as a starting point for your own implementation. Here is a MATLAB code snippet
implementing an up counter:
N = 1000;
17

delay = 0.01;
clr(sd);
for i = 1:N
print(sd,num2str(i));
pause(delay);
end
Summary
This example introduced the workflow for working with serial communications interface. You
learned how to control a 4-digit 7-segment display to display hexadecimal numbers.

18

Controlling a 4-Digit 7-Segment Display Using I2C


This example shows you how to use the I2C peripheral on Raspberry Pi hardware to control a
4-digit 7-segment display.
Introduction
Raspberry Pi hardware includes an I2C peripheral. The I2C peripheral enables you to connect
devices supporting I2C protocol directly to Raspberry Pi hardware. There is a wide variety of
sensors, displays, ADC's, DAC's, etc. supporting I2C communications. By using these devices
you can add new capabilities to your Raspberry Pi projects.
In this example, we will concentrate on controlling a 4-digit 7-segment display via I2C. We will
start by providing an overview of I2C communications in general and then focus on the display
and specifics of I2C commands it supports. We will learn about MATLAB command interface
for I2C devices and finally finish the example by displaying numbers and simple characters.
Prerequisites

We recommend completing Getting Started with MATLAB Support Package for


Raspberry Pi Hardware example.

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

Raspberry Pi hardware
A power supply with at least 1A output
Breadboard and jumper cables
A 4-digit, 7-segment display with I2C interface from SparkFun

Overview of I2C
Inter-Integrated Circuit (I2C) is a multi-master serial single-ended communication protocol used
for attaching low-speed peripherals to an embedded system.

19

I2C uses two bidirectional lines, serial data line (SDA) and serial clock (SCL). Both of these
lines are pulled up with resistors. Each slave device on the I2C bus is assigned a 7-bit or 10-bit
address. I2C devices with 10-bit addresses are rare and not supported by the Raspberry Pi
hardware. With a 7-bit address space, up to 128 devices can be connected to an I2C bus. I2C bus
speeds can range from 100 Kbits/s for slow mode to 400 Kbits/s for high speed mode.
Raspberry Pi hardware has two I2C buses. Depending on the model and revision of your board,
one of the I2C buses may not be available. The I2C pins on the 2x13 expansion pins are pulled
up with 1.8 KOhm resistors.
View available I2C buses
In the default Raspbian Wheezy Linux image, the I2C peripheral is enabled. You can find out
available I2C buses on the Raspberry Pi hardware by inspecting the AvailableI2CBuses property
of the raspi object.
clear rpi
rpi = raspi();
rpi.AvailableI2CBuses
Inspecting the AvailableI2CBuses property of the rpi should yield at least one I2C bus being
listed on the MATLAB command prompt.
Overview of 4-digit 7-segment display
The 4-digit 7-segment display from SparkFun is a 4-digit alpha-numeric display with TTL serial,
SPI or I2C interface.

This device can display numbers, most letters and a few special characters. Decimal points,
apostrophes and colons are supported. Brightness of the display can be adjusted. The display has
a simple control interface where the master device, Raspberry Pi hardware in this case, issues
commands with parameters to the display device over I2C bus. For example, to clear the display
master sends a command byte of '0x76'. To set the cursor to a particular position, master sends a
command byte of '0x79' followed by a byte indicating cursor position (0 to 3). A comprehensive
list of commands is shown in the table below.

20

Connect the display


To interface the display to Raspberry Pi hardware you need to do some light soldiering. Since we
are using the I2C interface of the display in this example, soldier jumper wires to the SDA, SCL,
GND and VCC pins of the display. You may also choose to soldier some straight male headers to
be able to mount the display on a breadboard for prototyping. Before going any further, you may
also want to follow manufacturer's hardware assembly guide.
Follow the circuit diagram shown below to connect the display to Raspberry Pi hardware.

Scan I2C bus


Once you connected the display to the Raspberry Pi hardware, you are ready to test if Raspberry
Pi hardware sees it on the I2C bus.
clear rpi
rpi = raspi();
for i = 1:length(rpi.AvailableI2CBuses)
scanI2CBus(rpi, rpi.AvailableI2CBuses{i})
end
The scanI2CBus() method scans the given I2C bus and returns a cell array of device addresses on
the bus. If you connected the display to Raspberry Pi hardware correctly, the snippet of
MATLAB code above should return a device address of '0x71'. This is the factory default
address of the display.
Display a number
Let's start by creating an i2cdev object that will allow us to talk to the display using I2C.
segmentDisp = i2cdev(rpi, '<I2C bus>', '0x71');

21

Where '<I2C bus>' is the name of the I2C bus the display is detected. Remember that depending
on the version of your Raspberry Pi hardware, the bus name may change. So make sure that you
supply the correct I2C bus when constructing the segmentDisp object.
According to the command table for the display, sending a byte in the range 0 - 0xf results in a
hexadecimal number represented by the byte to be displayed. The cursor is initially at position 0,
which is the left most digit, and advances one position each time a character is displayed.
write(segmentDisp, 0);
This should display a '0' on the left most digit of the display. Let's display a couple of more
characters.
write(segmentDisp, 7);
write(segmentDisp, hex2dec('a'));
write(segmentDisp, hex2dec('b'));
After executing the commands above, you should see '07ab' displayed on the segmented display.
Clear display screen
To clear the display screen we will follow the datasheet and send '0x76' to the display.
write(segmentDisp, hex2dec('76'));
Set cursor position
To display a particular character at a particular cursor position, you may want to set the cursor
position.
write(segmentDisp, [hex2dec('79'), 2]);
write(segmentDisp, 9);
The commands above will display a '9' at the second digit position of the display.
Advanced: Create a MATLAB class for segment display
You can put all the things we learned about the segment display together and create a MATLAB
class for it. This MATLAB class has methods for setting the cursor position, clearing the display
screen, printing numbers, etc. As an example, we created such a class. Here is an example of
how you would use this class.
clear segmentDisp
sd = raspi.internal.segmentdisplay(rpi, <I2C bus>, <I2C
address>)
clr(sd); % Clear screen
22

print(sd, '112');
print(sd, 'dead');
print(sd, 'beef');
Note that before creating the class, we cleared the original i2cdev object called segmentDisp.
You are allowed to create a single object per I2C device. The segmentdisplay class internally
creates an i2cdev object. Hence you need to clear any i2cdev objects connected to the display
from MATLAB workspace before instantiating the segmentdisplay.
The segmentdisplay class tries to reduce flickering caused by clearing / re-displaying numbers. It
does so by caching the displayed characters and updating only those that are different. Not all
features supported by the segmented display are implemented. You can use the MATLAB class
we created as a starting point for your own implementation. Here is a MATLAB code snippet
implementing an up counter:
N = 1000;
delay = 0.01;
clr(sd);
for i = 1:N
print(sd,num2str(i));
pause(delay);
end
Summary
This example introduced the workflow for working with I2C interface. You learned how to
control a 4-digit 7-segment display to display hexadecimal numbers.

23

Analog Input Using SPI


This example shows you how to use the SPI peripheral on Raspberry Pi hardware to connect to
an MCP3008 10-bit 8-channel ADC.
Introduction
A wide variety of sensors output analog voltage levels in response to environmental stimulus.
Examples of analog sensors are TMP36 temperature sensor, and photo resistors. Raspberry Pi
hardware does not have any built-in analog input ports. Too use analog sensors, you need an
external ADC. In this example, you interface an ADC chip to Raspberry Pi hardware using the
SPI peripheral.
Prerequisites

It is helpful if you complete the Getting Started with MATLAB Support Package for
Raspberry Pi Hardware example.

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

Raspberry Pi hardware
A power supply with at least 1A output
Breadboard and jumper cables
MCP3008 ADC
10 kOhm Potentiometer

Overview of SPI
The Serial Peripheral Interface (SPI) is a synchronous serial data link that you use to interface
one or more slave peripheral devices to a single master SPI device. SPI uses three signal lines
common to all slave peripherals:

Master in slave out (MISO). Data is moved from slave to master on this wire.
Master out slave in (MOSI). Data is moved from master to slave on this wire.
Serial clock (SCLK). The master SPI device generates this clock.

Each slave peripheral is wired to an individual chip-select or slave-transmit enable line. During
SPI communication, the master selects only one slave device at a time. Any other slave on the
bus that has not been activated using its chip-select line must disregard the input clock and MOSI
signals. It also must not drive the MISO line.

24

SPI communications are full duplex. When the master sends a bit on the MOSI line, the slave
reads the bit and at the same time sends a bit on the MISO line that is in turn read by the master.
Therefore, to read from a slave device, you must write to it.
There are four different SPI modes you can use. Each mode defines a particular clock phase
(CPHA) and polarity (CPOL) with respect to the data. Mode 0 (CPOL = 0, CPHA = 0) is the
most common use case. The Raspberry Pi hardware has two SPI channels on the board: 0 and 1.
It can support up to two SPI slave devices. Each SPI channel has a corresponding bus speed that
can range from 500 KHz to 32 MHz. The number of data bits that are exchanged in each SPI
transaction can vary between 8 to 16 bits with 8-bits being the most common.
Enable SPI Peripheral
In the default Raspbian Wheezy Linux image, the SPI peripheral is not enabled to provide you
with more pins to use as digital I/O. Enabling SPI consists of loading the SPI kernel module.
You can determine if the SPI is enabled on your Raspberry Pi hardware by inspecting the
AvailableSPIChannels property of the raspi object.
clear rpi
rpi = raspi();
rpi.AvailableSPIChannels
If the SPI peripheral is not enabled, you will see an empty cell array. To enable the SPI
peripheral execute the following command.
enableSPI(rpi);
After you execute the preceding command, inspecting the AvailableSPIChannels property of the
rpi object should yield 'CE0' and 'CE1' SPI channels listed as available.

25

Overview of MCP3008
MCP3008 is a 10-bit, 8-channel analog to digital converter (ADC) with an SPI interface.

As seen in this diagram, pins 1 through 8 are analog input channels. Pin 16 is the digital supply
voltage and pin 9 is the digital ground.
and
are the pins used for reference voltage level
for analog measurements. The digital 10-bit voltage measurement value is scaled so that a value
of 0 corresponds to
and a value of 1023 (2^10 - 1) corresponding to
. Pins 10 through
13 are connections for SPI interface.

Connect MCP3008
Connect MCP3008 to the Raspberry Pi hardware as seen in the following circuit diagram. To
simulate a variable voltage applied to CH0, use a 10 kOhm potentiometer connected to CH0.

26

In this example, the potentiometer (POT) is a three-terminal device with terminals 1 and 3
comprising the end points of a resistor embedded in the POT. The second terminal is connected
to a variable wiper. As the wiper moves, the resistance across terminals 1 and 2 and terminals 2
and 3 changes. In this circuit, POT acts as a variable voltage divider. As you move the knob of
the potentiometer, the voltage seen at terminal 2 changes between 3.3 Volts and 0 volts.
Measure Voltage at CH0
MCP3008 uses the SPI interface to communicate with the SPI master which in this case is
Raspberry Pi hardware. An SPI transaction between MCP3008 and Raspberry Pi consist of 3
bytes. Raspberry Pi hardware sends a byte containing a value of '1' to MCP3008. At the same
time, MCP3008 sends a do not care byte to Raspberry Pi hardware. Raspberry Pi hardware sends
another byte to the MCP3008 with the most significant 4 bits containing a value of '1000'. This
byte indicates to the MCP3008 that a single-ended voltage measurement at CH0 is requested. At
the same time, MCP3008 sends the bits 9 and 10 of the ADC measurement. Finally, Raspberry
Pi hardware sends a do not care byte and at the same time reads the least significant 8 bits of the
voltage measurement. The 10-bit value read from MCP3008 is then converted to a voltage value.

27

Read Voltage
To read the voltage value from MCP3008, first create an spidev object connected to SPI channel
'CE0'. Perform the SPI transaction as previously described.
clear mcp3008
mcp3008 = spidev(rpi, 'CE0');
data = uint16(writeRead(mcp3008,[1, bin2dec('10000000'), 0]));
highbits = bitand(data(2), bin2dec('11'));
voltage = double(bitor(bitshift(highbits, 8), data(3)));
voltage = (3.3/1024) * voltage;
The variable voltage holds the voltage value read from the CH0 pin of the MCP3008. You can
substitute various analog sensors, such as a TMP36 temperature sensor, in place of the POT in
this circuit.
Advanced: Create a MATLAB class for MCP3008
You can create a MATLAB class for MCP3008 that makes it easy to use this device from
MATLAB command-line interface. You can condense the steps in this example using this
MATLAB class.
clear mcp3008
mcp3008 = raspi.internal.mcp3008(rpi, 'CE0');
for i = 1:20
voltage = readVoltage(mcp3008, 0);
fprintf('Voltage = %0.2f\n', voltage);
pause(0.2);
end
Experiment with the POT knob while executing the preceding loop. You see that the voltage
value printed on the MATLAB prompt changes.
Summary
This example introduced the workflow for working with the SPI interface. You learned how to
use MCP3008 ADC to read analog input voltages.

28

Working with Raspberry Pi Hardware


This example shows you basics of working with Raspberry Pi Hardware.
Introduction
Raspberry Pi is a single board, credit-card size computer that can run Linux. Raspberry Pi
hardware has low-level interfaces intended to connect directly with external devices such as A/D
converters, sensors, motor drivers, etc. You can take advantage of these low-level interfaces to
develop meaningful real-world applications. The Raspberry Pi support package includes
MATLAB command-line interfaces to communicate with external devices connected to
Raspberry Pi hardware. You can, for example, turn a LED connected to one of the GPIO pins on
or off or sense the position of a push button from the MATLAB command prompt.
Most of the low-level interfaces of Raspberry Pi hardware are not plug-and-play. To use these
low-level interfaces, you must have a sound understanding of basic electrical concepts. If you
mis-wire a GPIO pin, for example, you risk losing a GPIO pin, and, in some cases, your
Raspberry Pi hardware.
This example is intended to familiarize you with low level interfaces of the Raspberry Pi
hardware, establish sound practices for wiring and connections when working with external
electrical components and use MATLAB command-line interface for Raspberry Pi hardware to
control simple devices like LEDs, push buttons, and relays.
Prerequisites

It is helpful to complete the Getting Started with MATLAB Support Package for
Raspberry Pi Hardware example.

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

Raspberry Pi hardware
A power supply with at least 1A output
Breadboard and jumper cables
Red LED
330 Ohm, 1 kOhm and 10 kOhm resistors
A push button or switch

Overview of Raspberry Pi Hardware


In addition to USB, Ethernet, HDMI, and Audio Out ports, the Raspberry Pi hardware has
expansion headers that offer general purpose digital I/O, SPI, I2C, and serial UART. Depending
on the revision of your Raspberry Pi hardware, the available digital I/O pins, pinouts for I2C,
SPI, and serial ports change.
29

All versions of the Raspberry Pi hardware have one or more expansion headers. You can use
some of the pins on the expansion headers for digital I/O. To see a diagram of the pins of your
Raspberry Pi hardware, use showPins() method of raspi object.
rpi = raspi();
showPins(rpi);
The showPins() method displays a MATLAB figure showing a diagram of pins available. The
raspi object determines the version number of your Raspberry Pi hardware and displays the
correct pin diagram for your version of the board. Raspberry Pi Model B+ board has more I/O
pins exposed than Raspberry Pi Model B board.
The GPIO pins use 3.3 volt logic levels and are not 5 volt tolerant. There is no over-voltage
protection on the CPU chip. A CSI (camera serial interface) is available so that you can connect
an available Camera Board. You can use some of the pins available on the Raspberry Pi
hardware for multiple purposes. For example, if you do not need to use SPI interface, you can
use SPI pins as general purpose digital I/O. The pins marked as SDA0 and SCL0 are preset to be
used as an I2C interface. There are 1.8 kOhm pull-up resistors on the board for these pins.
You can power external components using 3.3 volt and 5 volt power pins on the expansion
headers. The maximum permitted current draw from the 3.3 volt pins is 50 mA.
Best Practices and Restrictions

Do not connect electrical components to Raspberry Pi expansion headers while


Raspberry Pi hardware is running. If you want to connect an electrical component, turn
off your board first. Instructions for turning off you board are provided below.

Raspberry Pi pins use 3.3 volt logic levels. Do not connect devices using 5 volt logic
levels directly to the Raspberry Pi pins.

Use logic level converters when interfacing devices using 5 volt logic levels to Raspberry
Pi hardware.

Do not short a GPIO pin configured as digital output.

Do not short 5 volt power pins to any other pin on the expansion header. Be extremely
careful when working in the vicinity of 5 volt power pins.

Do not touch bare expansion header pins while Raspberry Pi hardware is on. You can
accidentally short some of the pins.

Turning Your Raspberry Pi Hardware On and Off

30

Raspberry Pi runs a Linux operating system. Turning off the power can result in corrupting the
operating system image on the SD card. To turn off your board, first shut down the Linux
operating system by executing the following:
system(rpi, 'sudo shutdown -h now');
clear rpi
You can also execute the preceding command above on an interactive command shell as
described in the Getting Started with MATLAB Support Package for Raspberry Pi Hardware
example. After executing the command, wait until the operating system shuts down all LED's on
the board except for PWR LED. Then, unplug the power cable from the board. To restart your
board, plug the power cable back into the board. It takes approximately a minute for the board to
fully reboot.
Working with LEDs
A light-emitting diode (LED) is a semiconductor light source. An LED has two legs. One is
called anode and the other is called cathode. The two legs of LED have different names because
LED works only in one direction. The anode leg is longer than the cathode leg, and must be
attached to the positive voltage terminal while the cathode is attached to the negative voltage
terminal. The current going through an LED goes from anode to cathode. If you wire an LED
backwards, it does not light up.
LEDs come in different colors and sizes. Common sizes are 3mm, 5mm and 10mm and refer to
the diameter of the LED. A red LED, when it is on will have a forward voltage anywhere from
1.8 volts to 2.5 volts. When a LED is on, it behaves like a diode and passes a large amount of
current that may produce enough heat to cause the LED to burn out. Therefore, you should
always use a current-limiting resistor when working with an LED.
In this example, you connect a red LED across a GPIO pin and turn the LED on and off using the
MATLAB command-line interface. You need a red LED and a 330 Ohm resistor. You connect
the LED and the resistor as shown in the circuit diagram.

31

Here is another view showing the actual connections on a breadboard.

The anode (positive or long leg) is connected to the GPIO24 pin and the cathode is connected to
the ground through the resistor. Once you make the connections, execute the following command
at the MATLAB command prompt to turn the LED on.
clear rpi
rpi = raspi();
writeDigitalPin(rpi, 24, 1);
The writeDigitalPin() method configures GPIO pin 24 as output and sets the logical value of the
digital pin to one (logic high) causing 3.3 volts to be output at the pin. Writing a zero to a digital
pin results in an output of logic low, which is digital ground in this case.
Make the LED "blink" for 10 seconds.
for i = 1:10
writeDigitalPin(rpi, 24, 1);
pause(0.5);
writeDigitalPin(rpi, 24, 0);
pause(0.5);
end

32

Working with Pushbuttons


A push button is a simple switch mechanism. When pressed or in closed position, the legs of a
push button are shorted allowing electrical current to pass. When in open position, the switch
does not conduct electricity. You can use a digital input pin to sense if the push button is in an
open or closed position.
For this task, you need a breadboard-friendly pushbutton and 1 kOhm and 10 kOhm resistors.
Connect the push button to GPIO pin 23, as shown in the following circuit diagram.

In this circuit, the GPIO pin sees ground when the push button is not pressed. When the
pushbutton is pressed, the GPIO pin sees 3.3 volts. You can read the position of the push-button
using the readDigitalPin() method.
readDigitalPin(rpi, 23)

33

Push button Controlled LED


Blink the LED rapidly for 1 second whenever the push button is pressed.
for i = 1:100
buttonPressed = readDigitalPin(rpi, 23);
if buttonPressed
for j = 1:10
writeDigitalPin(rpi, 24, 1);
pause(0.05);
writeDigitalPin(rpi, 24, 0);
pause(0.05);
end
end
pause(0.1);
end
Summary
This example introduced the workflow for working with GPIO pins. You learned how to connect
LEDs and push buttons to GPIO pins.

34

Build a Digital Voltmeter


This example shows you how to build a digital voltmeter using MATLAB Support Package for
Raspberry Pi Hardware.
Introduction
In this example you combine the MCP3008 ADC with a 4-digit 7-segment display module to
build a digital voltmeter. You connect the MCP3008 ADC to the Raspberry Pi hardware using
SPI peripheral. You connect the 4-digit 7-segment display to the Raspberry Pi hardware using
the I2C peripheral. A potentiometer connected to one of the analog inputs of the MCP3008 ADC
provides a variable input voltage. You measure this voltage and display it on the segmented
display.
You can replace the potentiometer with an analog temperature sensor or a photoresistor to build
a digital thermometer or a digital light sensor.
Prerequisites
It is helpful to complete the following examples

Analog Input Using SPI example.

Controlling a 4-digit 7-Segment Display Using I2C example.

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

Raspberry Pi hardware
A power supply with at least 1A output
Breadboard and jumper cables
MCP3008 ADC
10 kOhm potentiometer
A 4-digit, 7-segment display with I2C interface from SparkFun

35

Connect MCP3008
Connect MCP3008 to the Raspberry Pi hardware as seen in the following circuit diagram. To
simulate a variable voltage applied to CH0, use a 10 kOhm potentiometer connected to CH0.

The potentiometer (POT), in this example, is a three-terminal device with terminals 1 and 3
comprising the end points of a resistor embedded in the POT. The second terminal is connected
to a variable wiper. As the wiper moves, the resistance values across terminals 1 and 2 and
terminals 2 and 3 change. In this circuit, POT acts as a variable voltage divider. As you move the
knob of the potentiometer, the voltage seen at terminal 2 changes between 3.3 Volts and 0 volts.
Connect the Display
To connect the display to Raspberry Pi hardware, you need to do some light soldiering. Since
you use the I2C interface of the display in this example, soldier jumper wires to the SDA, SCL,
GND and VCC pins of the display. You can also choose to soldier some straight male headers to
be able to mount the display on a breadboard for prototyping. Before going any further, follow
manufacturer's hardware assembly guide.
Connect the display to the Raspberry Pi hardware following the circuit diagram below.

36

Enable SPI Peripheral


In the default Raspbian Wheezy Linux image, the SPI peripheral is not enabled to provide you
with more pins to use as digital I/O. Enabling SPI consists of loading the SPI kernel module.
You can determine if the SPI is enabled on your Raspberry Pi hardware by inspecting the
AvailableSPIChannels property of the raspi object.
clear rpi
rpi = raspi();
rpi.AvailableSPIChannels
If the SPI peripheral is not enabled, you will see an empty cell array. To enable the SPI
peripheral execute the following command.
enableSPI(rpi);
After you execute the preceding command, inspecting the AvailableSPIChannels property of the
rpi object should yield 'CE0' and 'CE1' SPI channels listed as available.
Scan I2C bus
Once the display is connected to the Raspberry Pi hardware, test the presence of the display on
the I2C bus.
for i = 1:length(rpi.AvailableI2CBuses)
scanI2CBus(rpi, rpi.AvailableI2CBuses{i})
end
The scanI2CBus() method scans the given I2C bus and returns a cell array of device addresses on
the bus. If you connected the display to Raspberry Pi hardware correctly, the snippet of
37

MATLAB code above should return a device address of '0x71' for one of the I2C buses available
on the Raspberry Pi hardware. '0x71' is the factory default address of the display.
Read voltage
Create an MCP3008 object to read the voltage value at Channel 0 of the ADC.
clear mcp3008
mcp3008 = raspi.internal.mcp3008(rpi, 'CE0');
for i = 1:20
voltage = readVoltage(mcp3008, 0);
fprintf('Voltage = %0.2f\n', voltage);
pause(0.2);
end
Try playing with the POT knob while executing the loop above. You should observe that the
voltage value printed on the MATLAB prompt change.
Test the Segmented Display
Create a segmented display object connected to the appropriate I2C bus on the Raspberry Pi
hardware.
clear sd
sd = raspi.internal.segmentdisplay(rpi, <I2C bus>, <I2C
address>)
clr(sd); % Clear screen
print(sd, '112');
print(sd, 'dead');
print(sd, 'beef');
Substitute the correct I2C bus and I2C address for your segmented display.
Display Voltage Measurements
Read the voltage at Channel 0 of the MCP3008 ADC and display it on the segmented display
every 0.1 seconds.
delay = 0.1;
adcChannel = 0;
clr(sd);
for i = 1:N
voltage = readVoltage(mcp3008,adcChannel);
print(sd,sprintf('%0.0f', voltage*100));
pause(delay);
end
38

Summary
This example showed how to use a MCP3008 ADC and a segmented display connected to
Raspberry Pi hardware to build a digital voltmeter application.

39

Tracking a Green Ball


This example shows you how to use MATLAB to process images captured from a Raspberry Pi
Camera Board module to track a green ball.
Introduction
The Raspberry Pi Camera Board is a custom designed add-on module for Raspberry Pi hardware.
The MATLAB Support Package for Raspberry Pi Hardware allows you to capture images from
the Raspberry Pi Camera Board and bring those right into MATLAB for processing. Using this
capability we will develop an ball tracking algorithm.
Prerequisites

We recommend completing Working with Raspberry Pi Camera Board example.

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

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

Create a Camera Board object


Create a camera board object by executing the following on the MATLAB prompt.
clear
clear
rpi =
cam =

cam
rpi
raspi();
cameraboard(rpi, 'Resolution', '640x480');

The cam is a handle to a cameraboard object. Let's display the images captured from Raspberry
Pi Camera Board in MATLAB.
for i = 1:100
img = snapshot(cam);
imagesc(img);
drawnow;
end
Extract color components
We will extract three 2D matrices from the 3D image data corresponding to the red, green, and
blue components of the image. Before proceeding with the rest of the example, we will load a
40

saved image. We will make sure our algorithm works on the test image before moving on to live
data.
img = imread('tennis_ball.jpg');
imagesc(img);
r = img(:, :, 1);
g = img(:, :, 2);
b = img(:, :, 3);

Calculate green
Next we approximate the intensity of the green component
justGreen = g - r/2 - b/2;
Threshold the green image
We threshold the image to find the regions of image that we consider to be green enough.
bw = justGreen > 40;
imagesc(bw);

41

Find center
Find the center of the image and mark it with a red dot.
[x, y] = find(bw);
if ~isempty(x) && ~isempty(y)
xm = round(mean(x));
ym = round(mean(y));
xx = max(1, xm-5):min(xm+5, size(bw, 1));
yy = max(1, ym-5):min(ym+5, size(bw, 2));
bwbw = zeros(size(bw), 'uint8');
bwbw(xx, yy) = 255;
end
imagesc(justGreen + bwbw);

42

Run detection algorithm on live data


We can create a MATLAB function, trackball.m, out of the MATLAB code we developed in the
previous sections of this example. View the MATLAB function in the editor.
edit('trackball.m');
The function trackball() takes an image and a threshold for green detection and returns the results
of green detection algorithm. We will call this function on the images captured in a loop. Before
running the MATLAB code snippet below, get hold of a tennis ball and place it in the view of
the Raspberry Pi Camera Board. While the MATLAB code is running, move the ball around.
figure(1);
for i = 1:200
[img, bw] = trackball(snapshot(cam), 40);
subplot(211);
imagesc(img);
subplot(212);
imagesc(bw);
drawnow;
end
Summary
43

This example introduced the an application example where images coming from Raspberry Pi
Camera Board are processed with a simple green detection algorithm. This algorithm has
subsequently been used to track a tennis ball.
% LocalWords: rpi bw cameraboard

44

Build a Motion Sensor Camera


This example shows you how to build a motion sensor camera using MATLAB Support
Package for Raspberry Pi Hardware.
Introduction
In this example you combine a passive infrared (PIR) sensor with a Raspberry Pi Camera Board
to build a motion sensor camera. A PIR sensor measures infrared light radiating from objects.
The sensor detects the change in the infrared radiation and triggers an alarm if the gradient of the
change is higher than a predefined value. You connect the PIR sensor to one of the digital input
pins of the Raspberry Pi hardware and monitor the output of the PIR sensor. When PIR sensor
detects motion it outputs a logic high value. When you detect a logic high value on the digital
input pin, you take a picture and save it on the host computer.
Prerequisites
It is helpful to complete the following examples

Getting Started with MATLAB Support Package for Raspberry Pi Hardware example.

Getting Started with Raspberry Pi Hardware example.

Working with Raspberry Pi Camera Board example.

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

Raspberry Pi hardware
A power supply with at least 1A output
Breadboard and jumper cables
A Raspberry Pi Camera Board
A PIR sensor

Connect PIR Motion Sensors


A PIR sensor has three pins: VCC, GND, and OUT. You connect the VCC pin to +3.3 Volt
voltage rail and the GND pin to the ground. The OUT pin is the logic signal indicating motion.
This pin will be connected to a GPIO pin on the Raspberry Pi hardware as shown in the
following circuit diagram.

45

If you do not have a motion sensor available, you can substitute a push button instead. See
Getting Started with Raspberry Pi Hardware example for details.
Test Motion Sensor
When motion sensor detects movement, an LED on the sensor board
turns
on. Move your hand in front of the PIR motion sensor and make
sure the
sensor responds by turning on an LED. Then, execute the
following at the
MATLAB prompt.
clear rpi
rpi = raspi();
motionDetected = readDigitalPin(rpi, 23);
disp(motionDetected);
The displayed value of the variable motionDetected should be one. The PIR motion detector
holds the value of the OUT pin at logic high for approximately 5 seconds. Wait until the PIR
sensor LED goes off and execute the preceding MATLAB code again. This time, you should
observe a value of zero for the displayed value of motionDetected.
Test Camera Board
Create a camera board object by executing the following command on the MATLAB prompt.
cam = cameraboard(rpi);
The cam is a handle to a cameraboard object. Display an image captured from Camera Board in
MATLAB.
46

img = snapshot(cam);
imagesc(img);
Motion Sensor Camera
N = 100;
delay = 0.1;
frameNo = 0;
for i = 1:N
motionDetected = readDigitalPin(rpi, 23);
if motionDetected
fprintf('Motion detected on %s\n', datestr(now));
for i = 1:3
% Clear image buffer
snapshot(rpi);
end
img = snapshot(rpi);
imagesc(img);
drawnow;
imwrite(img, sprintf('image%d.jpg', frameNo));
% Wait until the motion detector output goes low
pause(5);
end
pause(delay);
end
Summary
This example showed how to use a PIR motion sensor and a Raspberry Pi Camera Board to build
a motion sensor camera.

47

Add Digital I/O Pins to Raspberry Pi Hardware Using MCP23017


This example shows you how to increase the number of digital I/O pins by connecting a
MCP23017 I/O expander chip to the Raspberry Pi hardware.
Introduction
Raspberry Pi hardware has a limited number of digital I/O pins. You can add 16 digital I/O pins
by connecting a MCP23017 I/O expander chip to the Raspberry Pi hardware. Then, using I2C,
you can use the additional pins as digital inputs or outputs.
Prerequisites
It is helpful to complete the following examples

Getting Started with MATLAB Support Package for Raspberry Pi Hardware example.

Getting Started with Raspberry Pi Hardware example.

Controlling a 4-digit 7-Segment Display Using I2C example.

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

Raspberry Pi hardware
A power supply with at least 1A output
Breadboard and jumper cables
A MCP23017 I/O expander
A red LED
330 Ohm resistor.

Overview of MCP23017 I/O Expander


MCP23017 is a 16-port digital I/O expander with an I2C interface.

48

MCP23017 uses just two pins to communicate with a master controller providing you 16 digital
I/O pins in exchange. These digital I/O pins can be configured as either inputs or outputs and
operate similarly to the built-in digital I/O ports on the Raspberry Pi hardware.
Connect MCP23017
Connect the MCP23017 I/O expander as shown in the following circuit diagram.

To power the MCP23017, connect the VDD pin to +5V voltage rail, and the VSS pin to the
ground rail. Connect the SCL and SDA pins on the MCP23017 to the I2C pins on the Raspberry
Pi hardware. Set the I2C device address of the MCP23017 to '0x20' by grounding the A0, A1, A2
pins. Connect the RESET pin to the +5V voltage rail.
Since MCP23017 is powered by +5V, the output pins show +5V when they are set to logic high.
The +5V voltage rail on the Raspberry Pi expansion header is not subject to a 50 mA limit as is
the case for +3.3V voltage rail, providing more latitude for power consumption. It is safe to
49

connect the SDA and SCL pins directly to the Raspberry Pi hardware because there are resistors
on the Raspberry Pi hardware that pull these two signal lines to +3.3V. Make sure that you do
not connect any of the MCP23017 output pins directly to the Raspberry Pi hardware.
Test MCP23017
After connecting the MCP23017 to the Raspberry Pi hardware, scan the I2C bus for its device
address.
clear rpi
rpi = raspi();
for i = 1:length(rpi.AvailableI2CBuses)
address = scanI2CBus(rpi, rpi.AvailableI2CBuses{i})
end
The scanI2CBus() method scans the given I2C bus and returns a cell array of device addresses on
the bus. If you connected the MCP23017 correctly, the output should include an I2C device
address of '0x20'.
Connect an LED
To test the operation of the MCP23017 I/O expander, connect a red LED to GPIA7 pins with a
330 Ohm resistor. Connect the long leg of the LED directly to the GPIA7 pin of the MCP23017
and the short leg of the LED to one of the terminals of the 330 Ohm resistor. Connect the other
terminal of the resistor to the ground rail.

Blink the LED


50

We created an example MATLAB class for MCP23017 I/O expander. You can control the
digital I/O pins of the MCP23017 by creating an object and using the readDigitalPin(),
writeDigitalPin() and configurePin() methods. This example class does not implement all
available features of the MCP23017.
Create a MCP23017 object by executing the following commands at the MATLAB prompt.
clear mcp
mcp = raspi.internal.mcp23017(rpi, <I2C Bus>, '0x20')
The parameter '<I2C Bus>' is the bus MCP23017 is attached to and is either 'i2c-0' or 'i2c-1',
depending on the revision of your Raspberry Pi hardware. Blink the LED by executing the
following MATLAB commands.
for i = 1:10
writeDigitalPin(mcp, 7, 1);
pause(0.5);
writeDigitalPin(mcp, 7, 0);
pause(0.5);
end
The pins of the MCP23017 I/O expander are assigned a numeric value from 0 to 15 with 0 to 7
corresponding to GPA0 through GPA7, and 8 to 15 corresponding to GPIB0 through GPIB7.
Summary
This example showed how use a MCP23017 I/O expander chip to add digital I/O pins to
Raspberry Pi hardware.

51

RASPBERRY PI B+ DATA

52

53

54

55

RASPBERRY PI B+ SCHEMATICS

56

57

58

59

BCM2835
The Broadcom chip used in the Raspberry Pi Model A, B, B+ and Compute Module
Please refer to:

BCM2835
Peripheral specification
GPU documentation and open source driver
ARM1176 Processor
ARM1176JZF-S

Power Supply
The device is powered by a 5V micro USB supply. Exactly how much current (mA) the
Raspberry Pi requires is dependent on what you connect to it. We have found that purchasing a
1.2A (1200mA) power supply from a reputable retailer will provide you with ample power to run
your Raspberry Pi.
Typically, the model B uses between 700-1000mA depending on what peripherals are connected;
the model A can use as little as 500mA with no peripherals attached. The maximum power the
Raspberry Pi can use is 1 Amp. If you need to connect a USB device that will take the power
requirements above 1 Amp, then you must connect it to an externally-powered USB hub.
The power requirements of the Raspberry Pi increase as you make use of the various interfaces
on the Raspberry Pi. The GPIO pins can draw 50mA safely, distributed across all the pins; an
individual GPIO pin can only safely draw 16mA. The HDMI port uses 50mA, the camera
module requires 250mA, and keyboards and mice can take as little as 100mA or over 1000mA!
Check the power rating of the devices you plan to connect to the Pi and purchase a power supply
accordingly.
Backpowering
Backpowering occurs when USB hubs do not provide a diode to stop the hub from powering
against the host computer. Other hubs will provide as much power as you want out each port.
Please also be aware that some hubs will backfeed the Raspberry Pi. This means that the hubs
will power the Raspberry Pi through its USB cable input cable, without the need for a separate
micro-USB power cable, and bypass the voltage protection. If you are using a hub that backfeeds
to the Raspberry Pi and the hub experiences a power surge, your Raspberry Pi could potentially
be damaged.

60

GPIO
General Purpose Input/Output pins on the Raspberry Pi
Overview
This page expands on the technical features of the GPIO pins available on BCM2835 in general.
For usage examples, see the GPIO Usage section. When reading this page, reference should be
made to the BCM2835 ARM Peripherals Datasheet, section 6.
GPIO pins can be configured as either general-purpose input, general-purpose output or as one of
up to 6 special alternate settings, the functions of which are pin-dependant.
There are 3 GPIO banks on BCM2835.
Each of the 3 banks has its own VDD input pin. On Raspberry Pi, all GPIO banks are supplied
from 3.3V. Connection of a GPIO to a voltage higher than 3.3V will likely destroy the GPIO
block within the SoC.
A selection of pins from Bank 0 is available on the P1 header on Raspberry Pi.
GPIO Pads
The GPIO connections on the BCM2835 package are sometimes referred to in the peripherals
datasheet as "pads" - a semiconductor design term meaning "chip connection to outside world".
The pads are configurable CMOS push-pull output drivers/input buffers. Register-based control
settings are available for

Internal pull-up / pull-down enable/disable


Output drive strength
Input Schmitt-trigger filtering

Power-On States
All GPIOs revert to general-purpose inputs on power-on reset. The default pull states are also
applied, which are detailed in the alternate function table in the ARM peripherals datasheet. Most
GPIOs have a default pull applied.
Interrupts
Each GPIO pin, when configured as a general-purpose input, can be configured as an interrupt
source to the ARM. Several interrupt generation sources are configurable:

Level-sensitive (high/low)
Rising/falling edge
Asynchronous rising/falling edge

61

Level interrupts maintain the interrupt status until the level has been cleared by system software
(e.g. by servicing the attached peripheral generating the interrupt).
The normal rising/falling edge detection has a small amount of synchronisation built into the
detection. At the system clock frequency, the pin is sampled with the criteria for generation of an
interrupt being a stable transition within a 3-cycle window, i.e. a record of "1 0 0" or "0 1 1".
Asynchronous detection bypasses this synchronisation to enable the detection of very narrow
events.
Alternative Functions
Almost all of the GPIO pins have alternative functions. Peripheral blocks internal to BCM2835
can be selected to appear on one or more of a set of GPIO pins, for example the I2C busses can
be configured to at least 3 separate locations. Pad control, such as drive strength or Schmitt
filtering, still applies when the pin is configured as an alternate function.
For more detailed information see the Low level peripherals page on the elinux wiki
SPI
Page Contents

Overview
Software
Hardware
Linux driver
Troubleshooting

Overview
The Raspberry Pi is equipped with one SPI bus that has 2 chip selects.
The SPI master driver is disabled by default on Raspian. To enable it, remove the blacklisting for
spi-bcm2708 in /etc/modprobe.d/raspi-blacklist.conf, or use raspi-config.
Reboot or load the driver manually with:
$ sudo modprobe spi-bcm2708
The SPI bus is available on the P1 Header:
MOSI
MISO
SCLK
GND

P1-19
P1-21
P1-23
P1-25

P1-24
P1-26

CE0
CE1

Software
62

WiringPi
WiringPi includes a library which can make it easier to use the Raspberry Pi's on-board SPI
interface. Accesses the hardware registers directly.
http://wiringpi.com/
bcm2835 library
This is a C library for Raspberry Pi (RPi). It provides access to GPIO and other IO functions on
the Broadcom BCM 2835 chip. Accesses the hardware registers directly.
http://www.airspayce.com/mikem/bcm2835/
Use spidev from C
There's a loopback test program in the Linux documentation that can be used as a starting point.
See the Troubleshooting section. Uses the Linux spidev driver to access the bus.
Shell
# Write binary 1, 2 and 3
echo -ne "\x01\x02\x03" > /dev/spidev0.0
Hardware
The BCM2835 on the Raspberry Pi has 3 SPI Controllers. Only the SPI0 controller is available
on the header. Chapter 10 in the BCM2835 ARM Peripherals datasheet describes this controller.
Master modes
Signal name abbreviations
SCLK
CE
MOSI
MISO
MOMI
MIMO

Serial CLocK
Chip Enable (often called Chip Select)
Master Out Slave In
Master In Slave Out
Master Out Master In
Master In Master Out

Standard mode
In Standard SPI master mode the peripheral implements the standard 3 wire serial protocol
(SCLK, MOSI and MISO).
Bidirectional mode
63

In bidirectional SPI master mode the same SPI standard is implemented except that a single wire
is used for data (MIMO) instead of two as in standard mode (MISO and MOSI).
LoSSI mode (Low Speed Serial Interface)
The LoSSI standard allows issuing of commands to peripherals (LCD) and to transfer data to and
from them. LoSSI commands and parameters are 8 bits long, but an extra bit is used to indicate
whether the byte is a command or parameter/data. This extra bit is set high for a data and low for
a command. The resulting 9-bit value is serialized to the output. LoSSI is commonly used with
MIPI DBI type C compatible LCD controllers.
Note:
Some commands trigger an automatic read by the SPI controller, so this mode can't be used as a
multipurpose 9-bit SPI.
Transfer modes

Polled
Interrupt
DMA

Speed
The CDIV (Clock Divider) field of the CLK register sets the SPI clock speed:
SCLK = Core Clock / CDIV
If CDIV is set to 0, the divisor is 65536. The divisor must be a
power of 2. Odd numbers rounded down. The maximum SPI clock rate
is of the APB clock.
Errata: "must be a power of 2" probably should be "must be a multiple of 2"
See the Linux driver section for more info.
Chip Select
Setup and Hold times related to the automatic assertion and de-assertion of the CS lines when
operating in DMA mode are as follows:

The CS line will be asserted at least 3 core clock cycles before the msb of the first byte of
the transfer.
The CS line will be de-asserted no earlier than 1 core clock cycle after the trailing edge of
the final clock pulse.

Linux driver
64

The default Linux driver is spi-bcm2708.


The following information was valid 2014-07-05.
Speed
The driver supports the following speeds:
cdiv
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768

speed
125.0
62.5
31.2
15.6
7.8
3.9
1953
976
488
244
122
61
30.5
15.2
7629

MHz
MHz
MHz
MHz
MHz
MHz
kHz
kHz
kHz
kHz
kHz
kHz
kHz
kHz
Hz

When asking for say 24 MHz, the actual speed will be 15.6 MHz.
Forum post: SPI has more speeds
Supported Mode bits
SPI_CPOL
SPI_CPHA
SPI_CS_HIGH
SPI_NO_CS

Clock polarity
Clock phase
Chip Select active high
1 device per bus, no Chip Select

Bidirectional mode is currently not supported.


Supported bits per word

8 - Normal
9 - This is supported using LoSSI mode.

Transfer modes
Only interrupt mode is supported.
65

Deprecated warning
The following appears in the kernel log:
bcm2708_spi bcm2708_spi.0: master is unqueued, this is
deprecated
SPI driver latency
This thread discusses latency problems.
DMA capable driver
This is a fork of spi-bcm2708 which enables DMA support for SPI client drivers that support
DMA.
https://github.com/notro/spi-bcm2708 (wiki)
Troubleshooting
Loopback test
This can be used to test SPI send and receive. Put a wire between MOSI and MISO. It does not
test CE0 and CE1.
wget https://raw.githubusercontent.com/raspberrypi/linux/rpi3.10.y/Documentation/spi/spidev_test.c
gcc -o spidev_test spidev_test.c
./spidev_test -D /dev/spidev0.0
spi mode: 0
bits per word: 8
max speed: 500000 Hz (500 KHz)
FF
40
FF
FF
FF
DE
F0

FF
00
FF
FF
FF
AD
0D

FF
00
FF
FF
FF
BE

FF
00
FF
FF
FF
EF

FF
00
FF
FF
FF
BA

FF
95
FF
FF
FF
AD

If you get compilation errors, try the latest version instead:


wget
https://raw.github.com/torvalds/linux/master/Documentation/spi/s
pidev_test.c
66

USB
Page Contents

Overview
o Supported Devices
o General Limitations
o Port Power Limits
Known Issues
Troubleshooting

Overview
The Raspberry Pi Model B is equipped with two USB2.0 ports. These are connected to the
LAN9512 combo hub/Ethernet chip IC3, which is itself a USB device connected to the single
upstream USB port on BCM2835.
On the Model A, the single USB2.0 port is directly wired to BCM2835.
The USB ports enable the attachment of peripherals such as keyboards, mice, webcams that
provide the Pi with additional functionality.
There are some differences between the USB hardware on the Raspberry Pi and the USB
hardware on desktop computers or laptop/tablet devices.
The USB host port inside the Pi is an On-The-Go (OTG) host as the application processor
powering the Pi, BCM2835, was originally intended to be used in the mobile market: i.e. as the
single USB port on a phone for connection to a PC, or to a single device. In essence, the OTG
hardware is simpler than the equivalent hardware on a PC.
OTG in general supports communication to all types of USB device, but to provide an adequate
level of functionality for most of the USB devices that one might plug into a Pi, the system
software has to do more work.
Supported devices
In general, every device supported by Linux is possible to use with the Pi, subject to a few
caveats detailed further down. Linux has probably the most comprehensive driver database for
legacy hardware of any operating system (it can lag behind for modern device support as it
requires open-source drivers for Linux to recognise the device by default).
If you have a device and wish to use it with a Pi, then plug it in. Chances are that it'll "just work".
If you are running in a graphical interface (such as the LXDE desktop environment in Raspbian),
then it's likely that an icon or similar will pop up announcing the new device.
If the device doesn't appear to work, then refer to the Troubleshooting section.
67

General limitations
The OTG hardware on Raspberry Pi has a simpler level of support for certain devices, which
may present a higher software processing overhead. The Raspberry Pi also has only one root
USB port: all traffic from all connected devices is funnelled down this bus, which operates at a
maximum speed of 480mbps.
The USB specification defines three device speeds - Low, Full and High. Most mice and
keyboards are Low-speed, most USB sound devices are Full-speed and most video devices
(webcams or video capture) are High-speed.
Generally, there are no issues with connecting multiple High-speed USB devices to a Pi.
The software overhead incurred when talking to Low- and Full-speed devices means that there
are soft limitations on the number of simultaneously active Low- and Full-speed devices. Small
numbers of these types of devices connected to a Pi will cause no issues.
Port Power Limits
USB devices have defined power requirements, in units of 100mA from 100mA to 500mA. The
device advertises its own power requirements to the USB host when it is first connected. In
theory, the actual power consumed by the device should not exceed its stated requirement.
The USB ports on a Raspberry Pi have a design loading of 100mA each - sufficient to drive
"low-power" devices such as mice and keyboards. Devices such as WiFi adapters, USB hard
drives, USB pen drives all consume much more current and should be powered from an external
hub with its own power supply. While it is possible to plug a 500mA device into a Pi and have it
work with a sufficiently powerful supply, reliable operation is not guaranteed.
In addition, hotplugging high-power devices into the Pi's USB ports may cause a brownout
which can cause the Pi to reset.
See Power for more information.
Devices with known issues
1. Interoperability between the Raspberry Pi and USB3.0 hubs
There is an issue with USB3.0 hubs in conjunction with the use of Full- or Low-speed devices
(most mice, most keyboards) and the Raspberry Pi. A bug in most USB3.0 hub hardware means
that the Raspberry Pi cannot talk to Full- or Low-speed devices connected to a USB3.0 hub.
USB2.0 high-speed devices, including USB2.0 hubs, operate correctly when connected via a
USB3.0 hub.
Avoid connecting Low- or Full-speed devices into a USB3.0 hub. As a workaround, plug a
USB2.0 hub into the downstream port of the USB3.0 hub and connect the low-speed device, or
68

use a USB2.0 hub between the Pi and the USB3.0 hub, then plug low-speed devices into the
USB2.0 hub.
2. USB1.1 webcams
Old webcams may be Full-speed devices. Because these devices transfer a lot of data and incur
additional software overhead, reliable operation is not guaranteed.
As a workaround, try to use the camera at a lower resolution.
3. Esoteric USB sound cards
Expensive "audiophile" sound cards typically use far more bandwidth than is necessary to stream
audio playback. Reliable operation with 96kHz/192kHz DACs is not guaranteed.
As a workaround, forcing the output stream to be CD quality (44.1kHz/48kHz 16-bit) will reduce
the stream bandwidth to reliable levels.
4. Single-TT USB hubs
USB2.0 and 3.0 hubs have a mechanism for talking to Full- or Low-speed devices connected to
their downstream ports called a Transaction Translator. This device buffers high-speed requests
from the host (i.e. the Pi) and transmits them at Full- or Low-speed to the downstream device.
Two configurations of hub are allowed by the USB specification: Single-TT (one TT for all
ports) and Multi-TT (one TT per port).
Because of the OTG hardware limitations, if too many Full- or Low-speed devices are plugged
into a single-TT hub, unreliable operation of the devices may occur. It is recommended to use a
Multi-TT hub to interface with multiple lower-speed devices.
As a workaround, spread lower-speed devices out between the Pi's own USB port and the singleTT hub.
Troubleshooting
If your device doesn't work at all
The first step is to see if it is detected at all. There are two commands that can be entered into a
terminal for this: lsusb and dmesg. The first will print out all devices attached to USB,
whether they are actually recognised by a device driver or not, and the second will print out the
kernel message buffer (which can be quite big after booting - try doing sudo dmesg -C then
plug in your device and retype dmesg to see new messages).
As an example with a USB pendrive:
pi@raspberrypi
Bus 001 Device
Bus 001 Device
Bus 001 Device
Bus 001 Device
pi@raspberrypi
... Stuff that

~ $ lsusb
002: ID 0424:9512 Standard Microsystems Corp.
001: ID 1d6b:0002 Linux Foundation 2.0 root hub
003: ID 0424:ec00 Standard Microsystems Corp.
005: ID 05dc:a781 Lexar Media, Inc.
~ $ dmesg
happened before ...

69

[ 8904.228539] usb 1-1.3: new high-speed USB device number 5


using dwc_otg
[ 8904.332308] usb 1-1.3: New USB device found, idVendor=05dc,
idProduct=a781
[ 8904.332347] usb 1-1.3: New USB device strings: Mfr=1,
Product=2, SerialNumber=3
[ 8904.332368] usb 1-1.3: Product: JD Firefly
[ 8904.332386] usb 1-1.3: Manufacturer: Lexar
[ 8904.332403] usb 1-1.3: SerialNumber: AACU6B4JZVH31337
[ 8904.336583] usb-storage 1-1.3:1.0: USB Mass Storage device
detected
[ 8904.337483] scsi1 : usb-storage 1-1.3:1.0
[ 8908.114261] scsi 1:0:0:0: Direct-Access
Lexar
JD
Firefly
0100 PQ: 0 ANSI: 0 CCS
[ 8908.185048] sd 1:0:0:0: [sda] 4048896 512-byte logical
blocks: (2.07 GB/1.93 GiB)
[ 8908.186152] sd 1:0:0:0: [sda] Write Protect is off
[ 8908.186194] sd 1:0:0:0: [sda] Mode Sense: 43 00 00 00
[ 8908.187274] sd 1:0:0:0: [sda] No Caching mode page present
[ 8908.187312] sd 1:0:0:0: [sda] Assuming drive cache: write
through
[ 8908.205534] sd 1:0:0:0: [sda] No Caching mode page present
[ 8908.205577] sd 1:0:0:0: [sda] Assuming drive cache: write
through
[ 8908.207226] sda: sda1
[ 8908.213652] sd 1:0:0:0: [sda] No Caching mode page present
[ 8908.213697] sd 1:0:0:0: [sda] Assuming drive cache: write
through
[ 8908.213724] sd 1:0:0:0: [sda] Attached SCSI removable disk
In this case, there are no error messages in dmesg and the pendrive is detected by the usbstorage driver. If your device did not have a driver available, then typically only the first 6 new
lines will appear in the dmesg printout.
If a device enumerates without any errors, but doesn't appear to do anything, then it is likely
there are no drivers installed for it. Search around, based on the manufacturer's name for the
device or the USB IDs that are displayed in lsusb (e.g. 05dc:a781). The device may not be
supported with default Linux drivers - and you may need to download or compile your own
third-party software.
If your device has intermittent behaviour
Poor quality power is the most common cause of devices not working, disconnecting or
generally being unreliable.

70

If you are using an external powered hub, try swapping the power adapter supplied with
the hub for another compatible power supply with the same voltage rating and polarity.
Check to see if the problem resolves itself if you remove other devices from the hub's
downstream ports.
Temporarily plug the device directly into the Pi and see if the behaviour improves.

71

RPi GPIO Interface Circuits


This page shows a number of common circuits used for interfacing the Raspberry Pi's GPIO pins
to various other electronic circuits.
Input circuits
Buttons and switches

A simple pushbutton or switch is very easy to connect to a GPIO, as shown above. When the
button is pressed (or the switch is closed) the GPIO input will be '0'. When it is released (or the
switch is opened) the GPIO will be '1'. R1 is a pull-up resistor, which "pulls" the GPIO input to
3.3V when the switch is open.
Voltage divider

This circuit may be used to connect a digital signal from a 5V device to a GPIO pin on the Pi,
which requires a 3.3V input level. The Ov point in the schematic should be connected to one of
the Ground lines on the Pi's GPIO connector, and also to the 0v (or Ground) signal on the input
device.
The important thing here is the ratio of R1 to R2; R1 should be just over half R2's value to
ensure 5V is divided down to 3.3V. The values shown here should be suitable for most uses.
(For more information, see the Wikipedia article on voltage dividers).

72

Output circuits
The GPIO pins are connected directly to the BCM2835 chip at the heart of the Raspberry Pi.
These provide only a 3.3V output level, and are not capable of supplying much power. More
importantly, if they are damaged through misuse the Pi itself will need to be replaced.
So, if you are connecting anything more than a small LED to the GPIO output, you should use an
additional circuit to boost the voltage and/or current.
Using an NPN transistor

This shows a cheap NPN transistor being used to switch a load on and off. When the GPIO is
'high' (logic 1) the load will be turned on; when it is 'low' the load will be off. The circuit shows a
5V power rail, but with the 2N3904 transistor shown, a supply of up to 40V may be used (this is
the VCEO value given in the transistor's datasheet). It should be suitable for a load current of up to
100mA.
For bigger loads, you will need a bigger transistor to switch higher voltages (the V CEO value) or
currents (the IC value), but note that you will need a transistor with a higher gain (the hFE value)
as well. The gain is the ratio of the current in R1 (in this case, about 2.5mA), to the current in the
load: a 1A load will need a gain of 400. So-called Darlington transistors, such as the TIP112
(1A, 100V) provide high gain at high currents.
Note! Transistors designed for high power operation generally need a heat sink. The current
ratings quoted in the data sheet assume ideal cooling is provided: you will not get anywhere
close to these without adequate cooling.
Using a FET

73

A field-effect transistor is another alternative to the ('bipolar') transistor shown above. Again,
when the GPIO is 'high' (or 1), the load will be switched on, and 'low' or 0 switches the load off.
Resistor R1 is provided for safety; it ensures that the load is switched off if the GPIO is set to be
an input.
As with the bipolar transistor circuit, supply voltages higher than 5V may be used for the load.
The 2N7000 device has a maximum (VDS) voltage of 60V; it is suitable for load currents of about
100mA.
For bigger loads, you can choose a bigger FET: the current rating (ID) and voltage rating (VDS)
are given in the data sheet. Unlike bipolar transistors, FETs do not have a 'gain' to worry about.
Instead you should look for a 'threshold' voltage (the input voltage at which the FET begins to
turn on) of 3V or less, so that it is properly 'on' when driven from the GPIO's 3.3 volts. Some
datasheets don't give a threshold voltage - instead they give a value RDS(on) measured at 2.5 or
2.7 volts. If the FET isn't suitable for 3.3V logic input, this value won't be given. Fairchild's
FQP30N06L has a low threshold voltage (2.5V max) and can switch 32 amps at 60 volts.
As with bipolar transistors, a power FET will need a good heatsink if you are using it at
anywhere near its rated current.
Driving a relay

74

If you are connecting an inductive load (essentially this means anything with windings, such as a
relay, a motor, or a solenoid) it is advisable to fit a diode D1 as shown above (note that the
cathode is connected to the positive supply rail). When an inductive load is switched off, a
voltage spike is produced which can exceed the maximum rating of transistor Q1; the diode
'clamps' this voltage to prevent damage.
Level Shifters
Many digital logic circuits (particularly older ones) use a 5 volt power supply. These cannot be
connected to the GPIO signals on the Pi, which uses a 3.3V power supply: the Pi GPIO will
output +3.3V for a logic 'high', which is less than the 3.5V (= 0.7 * VDD) required by most 5V
CMOS logic [1]. Also, a 5V logic output will send an excessively high voltage into a GPIO input,
which may damage either or both of them.
The solution is a level shifter circuit. Level shifters are available in IC form or as pre-built
modules from many suppliers (e.g. Adafruit, Sparkfun, Cool Components), but it's quite easy to
make your own.
Classic MOSFET level shifter

This uses a single MOSFET; when the GPIO is 'low', the MOSFET is turned on (because the
gate-source voltage is 3.3V), so the 5V side is connected to the GPIO pin - it is therefore also
low. When the GPIO is 'high' the MOSFET is off (the gate-source voltage is near zero), and R2
pulls the 5V side high.

75

The circuit also works in the other direction, and lets you safely drive a 3.3V GPIO input from a
5V source. Q1 has a (hidden) diode between the source and drain terminals - if the 5V logic side
is driven low, this will pull the GPIO low through the diode. When the 5V logic side is high,
everything is off and the GPIO will be pulled to 3.3V via R1.
For this reason, the above circuit is often used to convert levels on bidirectional buses such as
I2C. Note that for an I2C bus, you will need two copies of the circuit, one for the SDA line, and
one for SCL.
Simple diode circuit

This quick-and-dirty circuit has been used successfully to connect the serial port of a 5V
ATMega328 processor (as used on many Arduinos) to the Pi's serial port. The 0 and 3.3V logic
levels on the Pi's TxD pin are shifted (via D1 and R1) to approximately 0.7V and 4.0V. This is
within specification for the ATMega328's RxD pin, so the logic levels are recognised correctly.
Note that it is only just within specification; this means electrical noise (interference) can cause
errors more easily than when using a 'proper' level shifter.
There is no level conversion between the ATMega328's TxD and the Pi's RxD. Instead, resistor
R2 limits the current flowing from one device to the other to a safe value (under 0.5mA).
SN7407 IC

76

The SN7407 open-collector buffer IC is useful for a variety of level shifting and output-driver
tasks. When the GPIO output is '0' (low), the 7407 output will be low. When the GPIO is '1', the
7407 output is 'not driven', and R1 will pull the circuit output high. The output-high voltage can
be as high as 30V.
The 7407 output can sink up to 30mA when the output is low, so low-current loads (e.g. LEDs)
can be connected directly in place of R1. The IC has six independent circuits in a 14-pin DIP
package, and is quite cheap (roughly 0.50)

77

78