Raspberry Pi b

82
RASPBERRY PI B+ MATLAB TRANING GUIDE

description

Raspberry Pi b

Transcript of Raspberry Pi b

  • 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

  • 1

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

    Port: 18726

    BoardName: 'Raspberry Pi Model B+'

    AvailableLEDs: {'led0'}

    AvailableDigitalPins: [4 5 6 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27]

    AvailableSPIChannels: {'CE0' 'CE1'}

    AvailableI2CBuses: {'i2c-1'}

    I2CBusSpeed: 100000

  • 2

    Methods for class raspi:

    cameraboard i2cdev

    configureDigitalPin openShell

    configurePin putFile

    deleteFile readDigitalPin

    details scanI2CBus

    disableI2C serialdev

    disableSPI showLEDs

    disp showPins

    display spidev

    enableI2C system

    enableSPI writeDigitalPin

    getDigitalPinConfiguration writeLED

    getFile

    Methods of raspi inherited from handle.

    Methods for class handle:

    addlistener findobj gt lt

    delete findprop isvalid ne

    eq ge le notify

  • 3

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

  • 4

    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

  • 5

    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)

  • 6

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

  • 7

    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.

  • 8

    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.

  • 9

    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

  • 10

    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

  • 11

    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.

  • 12

    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

  • 13

    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.

  • 14

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

    digit 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

  • 15

    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

  • 16

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

  • 17

    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;

  • 18

    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.

  • 19

    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.

  • 20

    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.

  • 21

    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, '', '0x71');

  • 22

    Where '' 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, , )

    clr(sd); % Clear screen

  • 23

    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.

  • 24

    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.

  • 25

    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.

  • 26

    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.

  • 27

    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.

  • 28

    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.

  • 29

    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.

  • 30

    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

  • 31

    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.

  • 32

    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

  • 33

    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)

  • 34

    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.

  • 35

    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

  • 36

    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.

  • 37

    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

  • 38

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

    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

  • 39

    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.

  • 40

    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 cam

    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

    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

  • 41

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

  • 42

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

  • 43

    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

  • 44

    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

  • 45

    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.

  • 46

    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.

  • 47

    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.

  • 48

    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.

  • 49

    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

  • 50

    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

  • 51

    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, , '0x20')

    The parameter '' 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.

  • 52

    RASPBERRY PI B+ DATA

  • 53

  • 54

  • 55

  • 56

    RASPBERRY PI B+ SCHEMATICS

  • 57

  • 58

  • 59

  • 60

    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.

  • 61

    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

  • 62

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

    MISO P1-21

    SCLK P1-23 P1-24 CE0

    GND P1-25 P1-26 CE1

    Software

  • 63

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

    CE - Chip Enable (often called Chip Select)

    MOSI - Master Out Slave In

    MISO - Master In Slave Out

    MOMI - Master Out Master In

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

  • 64

    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

  • 65

    The default Linux driver is spi-bcm2708.

    The following information was valid 2014-07-05.

    Speed

    The driver supports the following speeds:

    cdiv speed

    2 125.0 MHz

    4 62.5 MHz

    8 31.2 MHz

    16 15.6 MHz

    32 7.8 MHz

    64 3.9 MHz

    128 1953 kHz

    256 976 kHz

    512 488 kHz

    1024 244 kHz

    2048 122 kHz

    4096 61 kHz

    8192 30.5 kHz

    16384 15.2 kHz

    32768 7629 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 - Clock polarity

    SPI_CPHA - Clock phase

    SPI_CS_HIGH - Chip Select active high

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

  • 66

    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

    te