Main Content

Connecting to Raspberry Pi Hardware Board

You can use MATLAB® to connect to and interact with Raspberry Pi® hardware. For example, you can:

  • Control on-board LEDs.

  • Read and write values to GPIO pins.

  • Connect to devices that are connected to:

    • Serial port

    • I2C interface

    • SPI interface

  • Record video and take still images using Camera Board.

  • Use the Linux® command shell. This functionality is limited in MATLAB Online™. See Security Considerations for Raspberry Pi in MATLAB Online for details.

When you create a connection to the Raspberry Pi hardware, you assign that connection to a handle whose name you specify. For example:

mypi = raspi

Use the handle to control the Raspberry Pi hardware. For example, you can use the handle to illuminate an LED or read the logical state of a GPIO pin:

writeLED(mypi,'led0',1)
readDigitalPin(mypi,4)

You can also use the handle to create a connection to serial, I2C, and SPI devices attached to the Raspberry Pi hardware. For example, you can create a connection to a serial device and assign that connection to a handle:

myserial = serialdev(mypi,'/dev/ttyAMA0',9600)

A connection remains active until you clear all of the handles that use the connection. You cannot create a new connection to a board while the previous connection to the same board is active. For example, the mypi and myserial handles from preceding examples both use the same connection. Even if you clear mypi, the connection remains active while myserial exists. Trying to create a new connection produces an error.

clear mypi
mynewpi = raspi
Error using raspi (line 146)
An active connection to raspberrypi-computername already exists. 
You cannot create another connection.
Clearing myserial closes the connection. You can then create a new connection to the Raspberry Pi hardware without producing an error.
clear myserial
mynewpi = raspi

See Also

| |

Related Topics