Arduinoio Ref
Arduinoio Ref
Hardware
Reference
R2023b
How to Contact MathWorks
Phone: 508-647-7000
iii
Classes
1
Functions
2
BNO055 Functions
3
Serial Functions
4
iv Contents
APDS9960 sensor
10
APPS
11
v
1
Classes
1 Classes
addon
Connection to add-on device for Arduino hardware
Description
An object created by addon represents a connection to an add-on device on Arduino hardware. You
can use the addon function to create add-on libraries such as L3G, LSM303, 1–Wire, HC-SR04, and
Capacitive sensor. These libraries are not part of the MATLAB Support Package for Arduino
Hardware and must be downloaded separately. You can also create your own custom Arduino add-on
libraries as mentioned in “Create Custom Arduino Add-On Library”.
This page is specifically about the 'Adafruit\MotorshieldV2' add-on library for the
motorshieldv2 object, included in the MATLAB Support Package for Arduino Hardware. Attach an
Adafruit® Motor Shield V2 to Arduino hardware, and use 'Adafruit\MotorshieldV2' as an input
argument to create a motorshieldv2 object. You can create connections to motors on the shield
using object functions.
Creation
Syntax
shield = addon(a,'Adafruit\MotorshieldV2')
shield = addon(a,'Adafruit\MotorshieldV2',Name,Value)
Description
Input Arguments
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
1-2
addon
I2C address, specified as the comma-separated pair consisting of 'I2CAddress' and either a
hexadecimal value specified as a character vector or a scalar integer.
Example: shield = addon(a,'Adafruit\MotorshieldV2','I2CAddress',0x61); sets the
I2C address to 97 or 0x61.
PWM frequency of Adafruit Motor Shield V2, specified as the comma-separated pair consisting of
'PWMFrequency' and a number in hertz.
Example: shield = addon(a,'Adafruit\MotorshieldV2','PWMFrequency',3200); sets the
PWM frequency to 3200Hz.
Properties
SCLPin — I2C pin
character vector
Arduino pins used by AdafruitMotor Shield V2. This is a read only property.
Example:
>> shield.SCLPin
ans =
'A5'
Arduino pins used by AdafruitMotor Shield V2. This is a read only property.
Example:
>> shield.SDAPin
ans =
'A4'
1-3
1 Classes
I2C device address, specified as a character vector that represents a hexadecimal value or a scalar
integer.
Example:
>> shield.I2CAddress
ans =
96
>> shield.PWMFrequency
ans =
1600
Object Functions
Use these object functions to create a connection to a motor on the Adafruit Motor Shield V2.
dcmotor Connection to DC motor on Adafruit Motor Shield V2 for Arduino
servo Connection to servo motor on Adafruit Motor Shield V2 for Arduino
stepper Connection to stepper motor on Adafruit Motor Shield V2 for Arduino
Examples
Connect to Arduino hardware, and create an add-on connection to an Adafruit Motor Shield.
a = arduino('COM4','Uno','Libraries','Adafruit/MotorShieldV2');
motor = addon(a,'Adafruit\MotorshieldV2')
motor =
motorshieldv2 with properties:
SCLPin: 'A5'
1-4
addon
SDAPin: 'A4'
I2CAddress: 96 ('0x60')
PWMFrequency: 1600 (Hz)
Connect to Arduino hardware, and create an add-on connection to an Adafruit Motor Shield with an
I2C address of 0x61 and PWM frequency of 1200.
a = arduino('COM4','Uno','Libraries','Adafruit/MotorShieldV2');
Updating server code on board Uno (COM4). This may take a few minutes.
motor = addon(a,'Adafruit/MotorShieldV2','I2CAddress','0x61','PWMFrequency',1200)
motor =
motorshieldv2 with properties:
SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 97 ('0x61')
PWMFrequency: 1200 (Hz)
Version History
Introduced in R2014b
See Also
dcmotor | servo | stepper | arduino
Topics
“Control Motors Using Adafruit Motor Shield V2”
“Create HelloWorld Add-On”
“Create LCD Add-on”
1-5
1 Classes
arduino
Connection to the Arduino and Arduino-compatible ESP32 hardware
Description
An arduino object represents a connection to Arduino or Arduino-compatible ESP32 hardware. Use
the arduino function to connect Arduino or Arduino-compatible ESP32 hardware to MATLAB. After
you create the object, you can program your hardware and use custom add-on libraries directly from
MATLAB using the “Object Functions” on page 1-16.
Use the arduino object to connect to Arduino board over USB, WiFi, or Bluetooth, by specifying the
different arguments based on the connection type. For the supported connection type for each board,
see “Supported Boards” on page 1-15.
1-6
arduino
Creation
Syntax
a = arduino
a = arduino(port,board)
a = arduino( ___ ,Name,Value)
a = arduino(btaddress)
a = arduino(btname)
a = arduino(ipaddress,board)
a = arduino(ipaddress,board,tcpipport)
Description
USB
a = arduino recreates the last successful connection to the Arduino or Arduino-compatible ESP32
hardware. If there is no last successful connection or that connection failed, it creates a connection to
an official Arduino hardware connected to your host computer via USB.
a = arduino( ___ ,Name,Value) creates a connection with additional options specified by one or
more Name,Value pair arguments.
Bluetooth
Input Arguments
Hardware port that your Arduino or ESP32 is connected to, specified as a character vector or string
array. The port can be a USB serial port. To identify the USB serial port number, see “Find Arduino
Port on Windows, Mac, and Linux” or “Find ESP32 Port on Windows, Mac, and Linux”. This argument
can be specified on its own if connected via USB serial port, or with a board name.
1-7
1 Classes
Example: a = arduino('COM5')
Name of the Arduino enabled board, specified as a character vector or string array. This argument
must be specified with a valid serial port, IP address, Bluetooth address, or Bluetooth name. See
“Supported Boards” on page 1-15 for all supported boards.
Example: a = arduino('COM5','Uno') creates a connection to an Arduino Uno board using port
5.
btaddress — Bluetooth address of the Nano 33 BLE, Nano 33 BLE Sense, Nano 33 IoT,
MKR1010, HC-05, HC-06, ESP32-DevKitV1 or ESP32-DevKitC
character vector | string array
For Nano 33 BLE, Nano 33 BLE Sense, Nano 33 IoT, MKR1010, ESP32-DevKitV1 or ESP32-
DevKitC the Bluetooth 4.0 address is the peripheral device's MAC address for Windows. For macOS,
it is a random operating system assigned address.
For HC-05 or HC-06 devices, the Bluetooth Classic address is specified as a character vector or
string array of the form btspp:// followed by the 12-digit hexadecimal value of the address. To
identify the Bluetooth device address, see “Pair a Bluetooth Device and Retrieve the Bluetooth Device
Address”.
Example: a = arduino('btspp://98d331fb3b77') creates a Bluetooth connection to a board
using HC-05 or HC-06.
Example: a = arduino('5A8769A09DA6') creates a Bluetooth 4.0 connection between a Windows
OS and Arduino Nano 33 BLE, Nano 33 BLE Sense, Nano 33 IoT, MKR1010, ESP32-DevKitV1
or ESP32-DevKitC boards.
Example: a = arduino('121B0BAC-0DE7-4FB1-909A-EEA6877DBC5C') creates a Bluetooth 4.0
connection to between a macOS and a Arduino Nano 33 BLE, Nano 33 BLE Sense, Nano 33 IoT,
MKR1010, ESP32-DevKitV1 or ESP32-DevKitC boards.
IP address of the Arduino board with WiFi support, specified as a character vector or string array.
Example: a = arduino('192.168.1.15','MKR1000') creates a WiFi connection to an Arduino
MKR1000 board that uses the IP address 192.168.1.15.
1-8
arduino
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Note If you are connecting an Arduino board using Bluetooth or WiFi, you cannot specify
Name,Value arguments.
Example: a = arduino('COM3','Uno','Libraries','I2C')
Name of the Arduino library, specified as the comma-separated pair consisting of 'Libraries' and a
character vector or a cell array of character vectors. Libraries installed by default extend the Arduino
environment.
Note When you first connect to your Arduino hardware, your Arduino connection is created with
these default libraries {'I2C' 'Servo' 'SPI'}. However, if you create an Arduino connection with
libraries other than the defaults, your Arduino connection will have only the libraries that you
specified, even after you disconnect and reconnect your Arduino hardware.
Note The libraries CAN, Servo, and RotaryEncoder are not supported for ESP32 board.
Type of reference voltage, specified as internal or external. In the external mode, an external
voltage is applied at the AREF pin. In the internal mode, the internal voltage supported by the
Arduino boards is used.
See “Supported Boards” on page 1-15 for supported internal voltages of the Arduino boards.
1-9
1 Classes
Note In the external mode, you must specify the external voltage applied at the AREF pin using
AnalogReference. In the internal mode, you can specify the internal voltage supported on the
boards. If you do not specify a voltage in the internal mode, the default internal reference voltage
of the Arduino boards is used.
Example: a =
arduino('COM9','Uno','AnalogReferenceMode','external','AnalogReference',1.1)
sets the reference voltage externally to 1.1V.
Before using an external reference voltage on the AREF pin, ensure the following for safety:
• Connect the external voltage to the AREF pin through a 5K resistor to prevent damaging the
board. If AnalogReferenceMode is internal and a reference voltage is still connected
externally at the AREF pin, you will short the internal reference voltage and the AREF pin, thus
damaging the board.
• Do not use a voltage less than 0V or more than the maximum voltage supported by the boards.
Note When you change the analog reference voltage, the output of readVoltage may not be
accurate. Run readVoltage until you see the expected value. For Arduino Uno and Mega boards,
see “Incorrect readVoltage results”.
Example: a = arduino('COM9','Uno','AnalogReferenceMode','external',
'AnalogReference',1.1) sets the reference voltage externally to 1.1V.
If 'ForceBuildOn' is not set as true, MATLAB does not reprogram the Arduino board and uses the
existing Arduino server if the libraries that you specify match with libraries that are already on the
existing Arduino server. Use this setting to update the Arduino server with different source code
when you work with custom Arduino libraries.
Example: a =
arduino('COM9','Uno','Libraries','CustomLibrary','ForceBuildOn',true)
reprograms the Arduino board using your latest C++ source code for CustomLibrary.
Note MATLAB does not reprogram the Arduino board and uses the existing Arduino server if the
libraries that you specify match with libraries that are already on the existing Arduino server.
Program log and Arduino commands log, specified as the comma-separated pair consisting of
'TraceOn' and either false or true. If you fail to connect to your Arduino board, set 'TraceOn'
to true to print compilation and upload errors of Arduino IDE at the MATLAB command window. You
1-10
arduino
can also set 'TraceOn' to true to print the Arduino commands executed on the Arduino board for
each MATLAB command.
Example: a = arduino('COM9','Uno','TraceOn',true)
The rate at which information is transferred in the communication channel. For Arduino Pro Mini,
and Digital Sandbox use the BaudRate value of 57600. For all the other boards listed in “Find Board
Name” use the BaudRate value of 115200.
Note Ensure that the Arduino board you are using supports the BaudRate before creating the
arduino object with the value other than the default value.
Example: a = arduino('COM9','Uno','BaudRate',115200);
Dependencies
For streaming data from multiple sensors with Navigation Toolbox™ or Sensor Fusion and Tracking
Toolbox™, set the BaudRate to 921600. This change on Arduino enables MATLAB to acquire real-
time data from the GPS receivers and IMU sensors. For other applications use the default BaudRate
of the Arduino board.
Properties
Port — Hardware port
'COM4' | 'COM5' | character vector | ...
Hardware port that your Arduino or ESP32 is connected to, specified as a character vector or string
array. The port can be a USB serial port. Specify the port when you create the arduino object.
Example:
>> a.Port
ans =
'COM4'
Arduino device connection status over Bluetooth, returned as numeric or logical 1 (true) or 0
(false). Property is available for only Nano 33 BLE, Nano 33 BLE Sense, Nano 33 IoT,
MKR1010, ESP32-DevKitV1, and ESP32-DevKitC boards.
Data Types: logical
1-11
1 Classes
Name of the Arduino enabled board, specified as a character vector or string array. It is the type of
Arduino hardware connected to your system. Specify the board type when you create the arduino
object. See “Supported Boards” on page 1-15 for all supported boards.
Example:
>> a.Board
ans =
'Uno'
Pins available on Arduino device connected to your system, specified as cell array of character
vectors.
Example:
a.AvailablePins
ans =
Columns 1 through 12
{'D2'} {'D3'} {'D4'} {'D5'} {'D6'} {'D7'} {'D8'} {'D9'} {'D10'} {'
Columns 13 through 18
Digital pins available on Arduino device connected to your system, specified as cell array of character
vectors.
Example:
a.AvailableDigitalPins
ans =
1-12
arduino
Columns 1 through 12
{'D2'} {'D3'} {'D4'} {'D5'} {'D6'} {'D7'} {'D8'} {'D9'} {'D10'} {'
Columns 13 through 18
PWM pins available on Arduino device connected to your system, specified as cell array of character
vectors.
Example:
a.AvailablePWMPins
ans =
Analog pins available on Arduino device connected to your system, specified as cell array of character
vectors.
Example:
a.AvailableAnalogPins
ans =
1-13
1 Classes
ans =
[0]
Note The Arduino Due, Mega2560, and MegaADK boards have three serial ports available while the
Arduino Leonardo, Micro, MKR1000, MKR1010, Nano33IoT, Nano33BLE, and ESP32 have one serial
port available.
Example:
a.AvailableSerialPortIDs
ans =
Dependencies
This property is valid only when the serial library is used to create a connection to the Arduino
hardware.
Data Types: double
Installed Arduino add-on libraries downloaded to your hardware, specified as a character vector or
cell array of character vectors. Check the available libraries with listArduinoLibraries to specify
the add-on library you want to use.
Example:
a.Libraries
ans =
1-14
arduino
Type of reference voltage, specified as internal or external. In the external mode, an external
voltage is applied at the AREF pin. In the internal mode, the internal voltage supported by the
Arduino boards is used.
In the external mode, you must specify the external voltage applied at the AREF pin using
AnalogReference. In the internal mode, you can specify the internal voltage supported on the
boards. If you do not specify a voltage in the internal mode, the default internal reference voltage
of the Arduino boards is used.
Example:
a.AnalogReferenceMode
ans =
'internal'
Before using an external reference voltage on the AREF pin, ensure the following for safety:
• Connect the external voltage to the AREF pin through a 5K resistor to prevent damaging the
board. If AnalogReferenceMode is internal and a reference voltage is still connected
externally at the AREF pin, you will short the internal reference voltage and the AREF pin thus
damaging the board.
• Do not use a voltage less than 0V or more than the maximum voltage supported by the boards.
See “Supported Boards” on page 1-15 for supported internal voltages of the Arduino boards.
When you change the analog reference voltage, the output of readVoltage may not be accurate.
Run readVoltage until you see the expected value. For Arduino Uno and Mega boards, see
“Incorrect readVoltage results”.
Example:
a.AnalogReference
ans =
5.0
Supported Boards
1-15
1 Classes
For a list of other Arduino-compatible boards that have been tested and their corresponding input
arguments, see “Find Board Name”.
Object Functions
The object functions device, shiftRegister, rotaryEncoder, servo, addon , and ultrasonic
are used to create objects for each of their respective peripheral devices. Other functions are used to
interact with the pins on your Arduino hardware.
1-16
arduino
Examples
a = arduino()
a =
arduino with properties:
Port: 'COM7'
Board: 'Nano33IoT'
AvailablePins: {'D0-D13', 'A0-A7'}
AvailableDigitalPins: {'D0-D13', 'A0-A7'}
AvailablePWMPins: {'D2-D6', 'D9-D10'}
AvailableAnalogPins: {'A0-A3', 'A6-A7'}
AvailableI2CBusIDs: [0]
AvailableSerialPortIDs: [1]
Libraries: {'SPI'}
Show all properties
Note: If an Arduino object was created previously, the new Arduino object
created on the computer will have the same configuration as the earlier
object.
Connect to an Arduino Uno on port 9. The port and board names depend on your configuration.
1-17
1 Classes
a = arduino('COM9','Uno')
Updating server code on board Uno (COM9). This may take a few minutes.
a =
arduino with properties:
Port: 'COM9'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11'}
AvailableAnalogPins: {'A0-A5'}
AvailableI2CBusIDs: [0]
Libraries: {'SPI'}
Show all properties
Connect to an ESP32-DevKitC on port 4. The port and board names depend on your configuration.
a = arduino('COM4','ESP32-WROOM-DevKitC')
a =
arduino with properties:
Port: 'COM4'
Board: 'ESP32-WROOM-DevKitC'
AvailablePins: {'D0-D5', 'D12-D19', 'D21-D23', 'D25-D27', 'D32-D39'}
AvailableDigitalPins: {'D0-D5', 'D12-D19', 'D21-D23', 'D25-D27', 'D32-D39'}
AvailablePWMPins: {'D1-D5', 'D12-D19', 'D21-D23', 'D25-D27', 'D32-D33'}
AvailableAnalogPins: {'D2', 'D4', 'D12-D15', 'D25-D27', 'D32-D36', 'D39'}
AvailableI2CBusIDs: [0]
AvailableSerialPortIDs: [2]
Libraries: {'I2C', 'SPI', 'Serial'}
Show all properties
a = arduino('btspp://98D331FB3B77')
a =
DeviceAddress: 'btspp://98D331FB3B77'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
1-18
arduino
Connect Nano 33 BLE, Nano 33 BLE Sense, Nano 33 IoT, MKR1010, ESP32-DevKitV1 or
ESP32-DevKitC boards over Bluetooth 4.0 address which is the peripheral device's MAC address
for Windows.
a = arduino('CA89D02FDC71')
Name: 'IMUBLE'
Address: 'CA89D02FDC71'
Connected: 1
Board: 'Nano33BLE'
AvailablePins: {'D0-D13', 'A0-A7'}
AvailableDigitalPins: {'D0-D13', 'A0-A7'}
AvailablePWMPins: {'D2-D6', 'D9-D12'}
AvailableAnalogPins: {'A0-A3', 'A6-A7'}
AvailableI2CBusIDs: [0,1]
AvailableSerialPortIDs: [1]
Libraries: {'I2C'}
In Windows, you can also specify the address in the format CA:89:D0:2F:DC:71.
a = arduino('HC-06')
a =
DeviceAddress: 'HC-06'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11'}
AvailableAnalogPins: {'A0-A5'}
AvailableI2CBusIDs: [0]
1-19
1 Classes
Connect to an Arduino Nano 33 BLE using Bluetooth. The address format is of two types.
a = arduino('CA:89:D0:2F:DC:71')
a =
Name: 'IMUBLE'
Address: 'CA89D02FDC71'
Connected: 1
Board: 'Nano33BLE'
AvailablePins: {'D0-D13', 'A0-A7'}
AvailableDigitalPins: {'D0-D13', 'A0-A7'}
AvailablePWMPins: {'D2-D6', 'D9-D12'}
AvailableAnalogPins: {'A0-A3', 'A6-A7'}
AvailableI2CBusIDs: [0,1]
AvailableSerialPortIDs: [1]
Libraries: {'I2C'}
a =
arduino with properties:
DeviceAddress: '10.10.10.55'
Port: 9500
Board: 'MKR1000'
AvailablePins: {'D0-D14', 'A0-A6'}
AvailableDigitalPins: {'D0-D14', 'A0-A6'}
AvailablePWMPins: {'D0-D8', 'D10', 'A3-A4'}
AvailableAnalogPins: {'A0-A6'}
AvailableI2CBusIDs: [0]
AvailableSerialPortIDs: [1]
Libraries: {'I2C', 'SPI', 'Serial', 'Servo'}
a =
arduino with properties:
1-20
arduino
DeviceAddress: '10.10.10.55'
Port: 9500
Board: 'MKR1000'
AvailablePins: {'D0-D14', 'A0-A6'}
AvailableDigitalPins: {'D0-D14', 'A0-A6'}
AvailablePWMPins: {'D0-D8', 'D10', 'A3-A4'}
AvailableAnalogPins: {'A0-A6'}
AvailableI2CBusIDs: [0]
AvailableSerialPortIDs: [1]
Libraries: {'I2C', 'SPI', 'Serial', 'Servo'}
a = arduino('/dev/tty.usbmodem1421','Uno')
a =
Port: '/dev/tty.usbmodem1421'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11'}
AvailableAnalogPins: {'A0-A5'}
AvailableI2CBusIDs: [0]
Libraries: {'Adafruit/MotorShieldV2', 'I2C', 'SPI', 'Servo'}
Show all properties
Connect to an Arduino Nano 33 BLE,Nano 33 BLE Sense, Nano 33 IoT, or a MKR1010 board
over Bluetooth using a random 128 bit device address assigned by the macOS.
a = arduino('121B0BAC-0DE7-4FB1-909A-EEA6877DBC5C')
a =
Name: 'IMUBLE'
Address: '121B0BAC-0DE7-4FB1-909A-EEA6877DBC5C'
Connected: 1
Board: 'Nano33BLE'
AvailablePins: {'D0-D13', 'A0-A7'}
AvailableDigitalPins: {'D0-D13', 'A0-A7'}
AvailablePWMPins: {'D2-D6', 'D9-D12'}
AvailableAnalogPins: {'A0-A3', 'A6-A7'}
AvailableI2CBusIDs: [0,1]
AvailableSerialPortIDs: [1]
Libraries: {'I2C'}
1-21
1 Classes
Updating server code on board Uno (COM9). This may take a few minutes.
a =
arduino with properties:
Port: 'COM9'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11'}
AvailableAnalogPins: {'A0-A5'}
AvailableI2CBusIDs: [0]
Libraries: {'I2C'}
Show all properties
Limit the Arduino environment to use only the servo and shift register libraries.
a = arduino('COM9','Uno',"Libraries",{"Servo","ShiftRegister"},'ForceBuildOn',true)
Updating server code on board Uno (COM9). This may take a few minutes.
a =
arduino with properties:
Port: 'COM9'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11'}
AvailableAnalogPins: {'A0-A5'}
AvailableI2CBusIDs: [0]
Libraries: {'Servo', 'ShiftRegister'}
Show all properties
Updating server code on board Uno (COM9). This may take a few minutes.
a =
arduino with properties:
1-22
arduino
Port: 'COM9'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11'}
AvailableAnalogPins: {'A0-A5'}
AvailableI2CBusIDs: [0]
Libraries: {'Adafruit/BNO055', 'I2C'}
Show all properties
More About
Code Generation Using MATLAB Function Block
• Use arduino in a MATLAB Function block with the Simulink® Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• Specifying arguments to create the arduino object is not supported in code generation. For more
information see “Deploy Arduino Functions to Arduino Hardware Using MATLAB Function Block”.
Version History
Introduced in R2014b
See Also
listArduinoLibraries | arduinosetup
1-23
1 Classes
matlabshared.addon.LibraryBase class
Package: matlabshared
Description
classdef MyAddonClass < matlabshared.addon.LibraryBase makes MyAddonClass a
subclass of the matlabshared.addon.LibraryBase class.
Properties
LibraryName — Identifier of the library
char
A unique identifier for an add-on library. The library name string uses the name of the package folder
where the library files are located, followed by the name of the library, with a forward slash
separating the two strings.
Example: 'ExampleLCD/LCD'
Data Types: char
A list of other Arduino Add-On libraries required by your Add-On library. The library name string uses
the same syntax as the LibraryName property.
Example: {'ExampleLCD/LCD','ExampleAddon/HelloWorld'}
Data Types: char
The name of the C++ header file that contains your add-on class code.
Example: 'MyAddon.h'
Data Types: char
1-24
matlabshared.addon.LibraryBase class
Methods
sendCommand Send message to Arduino device from MATLAB
configurePinResource Set resource owner and mode of pin
decrementResourceCount Decrement count of number of instances of resource
incrementResourceCount Increment current resource count
getTerminalsFromPins Get terminal numbers from pins
getResourceCount Number of instances of a resource
setSharedResourceProperty Set shared resource property
getSharedResourceProperty Get shared resource property
getResourceOwner Get terminal resource owner
validatePin Validate that pin supports specific functionality
getPinsFromTerminals Get pin numbers from terminal
getTerminalMode Get current terminal mode
isTerminalDigital Check if terminal can be used as a digital pin
isTerminalAnalog Check if terminal can be used as an analog pin
getServoTerminals Get terminals that have servo functionality
getI2CTerminals Get terminals with I2C functionality
getSPITerminals Get terminals that have SPI functionality
getPWMTerminals Get terminals with PWM functionality
getMCU Get microcontroller of Arduino board
getPinAlias Get alias pin number
getInterruptTerminals Get terminals with interrupt functionality
See Also
“Create Custom Arduino Add-On Library”
Topics
“Custom Add-On Library Concepts”
1-25
1 Classes
dcmotor
Connection to DC motor on Adafruit Motor Shield V2 for Arduino
Description
A dcmotor object represents a connection to a DC motor on an Adafruit Motor Shield V2 connected
to Arduino hardware. Attach a motor shield to the Arduino hardware, and connect a DC motor to the
appropriate pins on the motor shield. Create a motor shield object using the addon function, and
create a dcmotor object using the dcmotor function. You can control your DC motor in MATLAB
using the object functions.
Creation
Syntax
dcm = dcmotor(shield,motornum)
dcm = dcmotor(shield,motornum,Name,Value)
Description
Input Arguments
Adafruit Motor Shield connection on Arduino hardware, specified as an adafruit motor shield object
created using the addon function.
Example: dcm = dcmotor(shield,1) creates a connection to a DC motor on the specified adafruit
motor shield object shield.
Port number on the shield that the motor is connected to, specified as a number. Valid port values are
1, 2, 3, and 4.
Example: dcm = dcmotor(shield,1) creates a connection to a DC motor at port 1 on the motor
shield.
1-26
dcmotor
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: dcm = dcmotor(shield,1,'Speed',0.2)
DC motor speed, specified as the comma-separated pair consisting of 'speed' and a number
between —1 and 1.
Example: dcm = dcmotor(shield,1,'Speed',0.2); creates a DC motor connection with the DC
motor speed set to 0.2.
Properties
Speed — DC motor speed
0 (default) | numeric
DC motor speed, specified as a number between —1 and 1. You can specify motor speed when you
create the dcmotor object or after you create the dcmotor object.
Example:
>> dcm.Speed = 0.2
dcm =
MotorNumber: 1 (M1)
Speed: 0.20
IsRunning: 0
DC motor port number on the shield that the DC motor is connected to, specified as a number during
the dcmotor object creation. Valid port values are 1, 2, 3, and 4.
Example:
>> dcm.MotorNumber
ans =
1-27
1 Classes
DC motor state, indicated as a boolean value 0 or 1. IsRunning is 0 if the motor has not started and
1 otherwise.
Example:
>> dcm.IsRunning
ans =
logical
Object Functions
Use these object functions to control your DC motor.
start Start DC motor connected to Adafruit Motor Shield
stop Stop DC motor connected to Adafruit Motor Shield
Examples
dcm =
dcmotorv2 with properties:
MotorNumber: 1 (M1)
Speed: 0.00
IsRunning: 0
1-28
dcmotor
Create a DC motor connection at port 1 on the shield, and set the speed to 0.2.
dcm = dcmotor(dev,1,'Speed',0.2)
dcm =
dcmotorv2 with properties:
MotorNumber: 1 (M1)
Speed: 0.20
IsRunning: 0
Version History
Introduced in R2014b
See Also
start | stop | addon | arduino
Topics
“Control Motors Using Adafruit Motor Shield V2”
1-29
1 Classes
device
Connection to device on I2C bus on Arduino or ESP32 hardware
Description
This object represents a connection to the I2C device on Arduino or ESP32 hardware. Attach an I2C
device to the appropriate pins on the Arduino or ESP32 hardware. You can interact with the I2C
device using the functions listed in “Object Functions” on page 1-32.
Creation
Syntax
deviceObj = device(arduinoObj,'I2CAddress',I2CAddress,Name,Value)
Description
Input Arguments
Arduino or ESP32 hardware connection created using arduino, specified as an arduino object.
Specify at least one comma-separated pair of Name,Value arguments. Name is the argument name
and Value is the corresponding value. Name must appear inside quotes. You can specify several name
and value pair arguments in any order as Name1,Value1,...,NameN,ValueN
Example: deviceObj = device(arduinoObj,'I2CAddress','0x71');
This is a mandatory name value pair argument if you are connecting to an I2C device. Address of the
I2C device connected to the I2C bus, specified as a character vector, string, or integer. The address
can be a hex or a scalar integer. Obtain this address value using the scanI2CBus function.
Example: deviceObj = device(arduinoObj,'I2CAddress','0x68')
1-30
device
Note Bus number 1 is only available on Due and Nano33BLE boards. Other Arduino boards support
Bus number 0.
The maximum speed of I2C communication in bits/s, specified as 100000 or 400000 bits/s.
Example: deviceObj = device(arduinoObj,'I2CAddress','0x71','bitrate',100000)
creates a connection to the I2C device and sets the bitrate to 100000 bits/s.
Data Types: double
Properties
Interface — Type of interface used for communication
'I2C'
>> deviceObj.Interface
ans =
I2C
>> deviceObj.I2CAddress
ans =
104
1-31
1 Classes
>> deviceObj.Bus
ans =
0
This property is read-only. A serial clock pin for the serial clock signal that the I2C central generates.
Example:
>> deviceObj.SCLPin
ans =
'A5'
This property is read-only. A serial data pin for a serial data signal.
Example:
>> deviceObj.SDAPin
ans =
'A4'
The speed at which bus is set for I2C communication, specified as a positive integer in bits/s.
Example:
>> deviceObj.BitRate
ans =
100000
Object Functions
read Read data from I2C bus
readRegister Read data from I2C device register
write Write data to I2C bus
writeRegister Write data to I2C device register
Examples
1-32
device
arduinoObj =
arduino with properties:
Port: 'COM15'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11'}
AvailableAnalogPins: {'A0-A5'}
AvailableI2CBusIDs: [0]
Libraries: {'I2C'}
Show all properties
deviceObj =
device with properties:
Interface: 'I2C'
I2CAddress: 80 ('0x50')
Bus: 0
SCLPin: 'A5'
SDAPin: 'A4'
BitRate: 100000 (bits/s)
Show functions
More About
Code Generation Using MATLAB Function Block
• Use device in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• Specifying BitRate as a name value pair argument is not supported the in MATLAB Function
block. You can set BitRate from the Configuration Parameters dialog box. To set the BitRate:
• On the Simulink Toolstrip, in the Hardware tab, click Hardware Settings to open the
Configuration Parameters dialog box.
• In the Configuration Parameters dialog box, select Hardware Implementation. Verify that the
Hardware board parameter is set to the appropriate Arduino board.
• Go to Hardware board settings > Target hardware resources > I2C properties.
• Enter the value to set BitRate in I2C Bus Speed(Hz).
• The properties Interface, BitRate, SCLPin, and SDAPin are not accessible from the device
object.
1-33
1 Classes
Version History
Introduced in R2019a
See Also
arduino | scanI2CBus
1-34
rotaryEncoder
rotaryEncoder
Connection to quadrature encoder on Arduino or ESP32 hardware
Description
A rotaryEncoder object represents a connection to a quadrature encoder on Arduino or ESP32
hardware. Attach a quadrature encoder to the appropriate pins on the Arduino or ESP32 hardware.
Create a rotaryEncoder object using the rotaryEncoder function. You can read from the
quadrature encoder in MATLAB using object functions.
Creation
Syntax
encoder = rotaryEncoder(a,chA,chB)
encoder = rotaryEncoder(a,chA,chB,ppr)
Description
Input Arguments
Arduino or ESP32 hardware connection created using arduino, specified as an arduino object.
Example: encoder = rotaryEncoder(a,'D2','D3') creates a connection to the rotary encoder
on the specified arduino object a.
Arduino or ESP32 interrupt pin connected to channel A output of encoder, specified as a character
vector of the form 'Dx' or 'Ax' where x is the Arduino pin number. For example, 'D2'.
Example: encoder = rotaryEncoder(a,'D2','D3') creates a connection to a rotary encoder
with channel A output connected to digital pin 2 on the Arduino.
Data Types: char
1-35
1 Classes
Arduino or ESP32 interrupt pin connected to channel B output of encoder, specified as a character
vector of the form 'Dx' or 'Ax' where x is the Arduino pin number. For example, 'D3'.
Example: encoder = rotaryEncoder(a,'D2','D3') creates a connection to a rotary encoder
with channel B output connected to digital pin 3 on the Arduino.
Data Types: char
Properties
ChannelA — Arduino or ESP32 interrupt pin connected to channel A output of encoder
character vector
Arduino or ESP32 interrupt pin connected to channel A output of encoder, specified as a character
vector of the form 'Dx' or 'Ax' where x is the Arduino pin number. For example, 'D2'.
Example:
>> encoder.ChannelA
ans =
'D2'
Arduino interrupt pin connected to channel A output of encoder, specified as a character vector of the
form 'Dx' or 'Ax' where x is the Arduino pin number. For example, 'D3'.
Example:
>> encoder.ChannelB
ans =
'D3'
1-36
rotaryEncoder
>> encoder.PulsesPerRevolution
ans =
180
Object Functions
Use object functions to read from your quadrature encoder.
resetCount Set count value to zero or user-specified value
readCount Read current count value from encoder with X4 decoding
readSpeed Read current rotational speed
Examples
Create an Arduino object with the 'rotaryEncoder' library. In this example, an Arduino Uno is
connected to port 4. The port and board names depend on your configuration.
a = arduino('COM4','Uno','Libraries','rotaryEncoder');
encoder = rotaryEncoder(a,'D2','D3')
encoder =
rotaryEncoder with properties:
ChannelA: 'D2'
ChannelB: 'D3'
PulsesPerRevolution: []
Create an Arduino object with the 'rotaryEncoder' library. In this example, an Arduino Uno is
connected to port 4. The port and board names depend on your configuration.
a = arduino('COM4','Uno','Libraries','rotaryEncoder');
1-37
1 Classes
encoder = rotaryEncoder(a,'D2','D3',180)
encoder =
rotaryEncoder with properties:
ChannelA: 'D2'
ChannelB: 'D3'
PulsesPerRevolution: 180
Version History
Introduced in R2017a
See Also
resetCount | readCount | readSpeed
1-38
servo
servo
Connection to servo motor on Arduino or ESP32 hardware
Description
A servo object represents a connection to a servo motor on Arduino or ESP32 hardware. Attach a
servo motor to the appropriate pins on the Arduino or ESP32 hardware. Create a servo object using
the servo function. You can read from and write to the servo motor in MATLAB using object
functions.
Note This object is different from servo, which is for a servo motor connected to an Adafruit Motor
Shield V2 on the Arduino hardware.
Creation
Syntax
s = servo(a,pin)
s = servo(a,pin,Name,Value)
Description
s = servo(a,pin) creates a connection to the servo motor on the specified pin of the Arduino or
ESP32 hardware, a.
Input Arguments
Arduino or ESP32 hardware connection created using arduino, specified as an arduino object.
Example: s = servo(a,'D4') creates a connection to the servo on the specified arduino object a.
Digital and analog pin number on the Arduino or ESP32 board that the servo motor is connected to,
specified as a character vector of the form 'Dx' or 'Ax' where x is the Arduino pin number.
Example: s = servo(a,'D4') creates a connection to the servo on digital pin 4 on the Arduino
hardware.
1-39
1 Classes
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: s = servo(a,'D4','MaxPulseDuration',2e-3,'MinPulseDuration',1e-3);
Properties
Pin — Digital and Analog pin number
character vector
Digital and analog pin number on the Arduino or ESP32 board that the servo motor is connected to,
specified as a character vector of the form 'Dx' or 'Ax' where x is the Arduino or ESP32 pin
number.
Example:
>> s.Pin
ans =
'D4'
1-40
servo
Minimum pulse duration, specified as a number that represents the duration in seconds. Specified
value is equal to the width of the pulse the motor needs to be at the minimum angle.
Example:
>> s.MinPulseDuration
ans =
5.4400e-04
Maximum pulse duration, specified as a number that represents the duration in seconds. Specified
value is equal to the width of the pulse the motor needs to be at the maximum angle.
Example:
>> s.MaxPulseDuration
ans =
0.0024
Object Functions
Use object functions to read from and write to your servo motor.
readPosition Read servo motor position
writePosition Write position of servo motor
Examples
a = arduino('COM4','Uno','Libraries','Servo');
s = servo(a,'D4')
s =
Servo with properties:
Pin: 'D4'
MinPulseDuration: 5.44e-04 (seconds)
MaxPulseDuration: 2.40e-03 (seconds)
1-41
1 Classes
Create an arduino object, attach the servo object to digital pin 4, and set the pulse durations.
a = arduino('COM4','Uno','Libraries','Servo');
Updating server code on board Uno (COM4). This may take a few minutes.
s = servo(a,'D4','MinPulseDuration',7.00e-4,'MaxPulseDuration',2.3e-3)
s =
Servo with properties:
Pin: 'D4'
MinPulseDuration: 7.00e-04 (seconds)
MaxPulseDuration: 2.30e-03 (seconds)
Version History
Introduced in R2014b
See Also
arduino | readPosition | writePosition
Topics
“Rotate a Servo Motor”
“Servo Motors”
1-42
servo
servo
Connection to servo motor on Adafruit Motor Shield V2 for Arduino
Description
A servo object represents a connection to a servo motor on an Adafruit Motor Shield V2 connected
to Arduino hardware. Attach a motor shield to the Arduino hardware, and connect a servo motor to
the appropriate pins on the motor shield. Create a motor shield object using the addon function, and
create a servo object using the servo function. You can control your servo motor in MATLAB using
the object functions.
Note This object is different from servo, which is for a servo motor directly connected to pins on the
Arduino hardware.
Creation
Syntax
s = servo(shield,motornum)
s = servo(shield,motornum,Name,Value)
Description
s = servo(shield,motornum) creates a servo motor connection with the specified motor number
on an Adafruit Motor Shield.
Input Arguments
Adafruit Motor Shield connection on Arduino hardware, specified as an adafruit motor shield object,
created using the addon function.
Example: s = servo(shield,1) creates a connection to a servo motor on the specified adafruit
motor shield object shield.
Servo motor number where the motor is connected on the Adafruit Motor Shield, specified as a
number. Valid values are 1 and 2. Motor number 1 uses digital pin 10 and motor number 2 uses
digital pin 9.
1-43
1 Classes
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: s = servo(shield,1,'MaxPulseDuration',2e-3,'MinPulseDuration',1e-3);
Properties
MotorNumber — Servo motor number
numeric
Servo motor number where the motor is connected on the Adafruit Motor Shield, specified as a
number. Valid values are 1 and 2. Motor number 1 uses digital pin 10 and motor number 2 uses
digital pin 9.
Example:
>> s.MotorNumber
ans =
1-44
servo
Digital pin number on the Arduino board that the servo motor is connected to, specified as a
character vector of the form 'Dx' where x is the Arduino pin number.
Example:
>> s.Pin
ans =
'D10'
Minimum pulse duration, specified as a number that represents the duration in seconds. Specified
value is equal to the width of the pulse that the motor needs to be at the minimum angle.
Example:
>> s.MinPulseDuration
ans =
5.4400e-04
Maximum pulse duration, specified as a number that represents the duration in seconds. Specified
value is equal to the width of the pulse that the motor needs to be at the maximum angle.
Example:
>> s.MaxPulseDuration
ans =
0.0024
Object Functions
Use these object functions to control your servo motor.
readPosition Read position from servo motor connected to Adafruit Motor Shield
writePosition Write position to servo motor connected to Adafruit Motor Shield
1-45
1 Classes
Examples
Create a servo motor connection to an Adafruit Motor Shield attached to Arduino hardware.
a = arduino('COM4','Uno','Libraries','Adafruit/MotorShieldV2');
shield = addon(a,'Adafruit/MotorShieldV2');
s = servo(shield,1);
Version History
Introduced in R2014b
See Also
arduino | addon | readPosition | writePosition
Topics
“Control Motors Using Adafruit Motor Shield V2”
1-46
shiftRegister
shiftRegister
Connection to shift register on Arduino hardware
Description
A shiftRegister object represents a connection to a shift register on Arduino hardware. The
74HC165, 74HC595, and 74HC164 type shift registers are supported. Attach a shift register to the
appropriate pins on the Arduino hardware. Create a shiftRegister object using the
shiftRegister function. You can read from and write to the shift register in MATLAB using the
object functions. Manipulate peripheral devices attached to the shift register, such as LEDs.
Creation
Syntax
register = shiftRegister(a,'74hc165',dataPin,clockPin,loadPin,clockEnablePin)
register = shiftRegister(a,'74hc595',dataPin,clockPin,latchPin)
register = shiftRegister(a,'74hc595',dataPin,clockPin,latchPin,resetPin)
register = shiftRegister(a,'74hc164',dataPin,clockPin)
register = shiftRegister(a,'74hc164',dataPin,clockPin,resetPin)
Description
register = shiftRegister(a,'74hc165',dataPin,clockPin,loadPin,clockEnablePin)
creates a connection to the 74hc165 shift register connected to your Arduino board using the
Arduino object a, dataPin to input or output data, clockPin to signal read or write, loadPin to
load parallel input data, and clockEnablePin to enable or disable clock.
register = shiftRegister(a,'74hc595',dataPin,clockPin,latchPin,resetPin)
enables reset of the outputs of 74hc595 shift register.
Input Arguments
1-47
1 Classes
Shift register serial pin to input or output data, specified as a character vector of the form 'Dx'
where x is the Arduino pin number. For example, 'D3'. It is usually connected to the DS or SER pin
on the shift register.
Example: register = shiftRegister(a,'74HC165','D3','D6','D7','D10') creates a
connection to a 74HC165 shift register whose serial pin is connected to digital pin 3 on the Arduino
hardware.
Data Types: char
Shift register clock pin to signal read or write, specified as a character vector of the form 'Dx' where
x is the Arduino pin number. For example, 'D6'. It is usually connected to the SHCP or SRCLK pin on
the shift register.
Example: register = shiftRegister(a,'74HC165','D3','D6','D7','D10') creates a
connection to a 74HC165 shift register whose clock pin is connected to digital pin 6 on the Arduino
hardware.
Data Types: char
Shift register latch pin to latch input data, specified as a character vector of the form 'Dx' where x is
the Arduino pin number. For example, 'D7'. It is usually connected to the STCP or RCLK pin on the
shift register.
Example: register = shiftRegister(a,'74HC595','D3','D6','D7') creates a connection to
a 74HC595 shift register whose latch pin is connected to digital pin 7 on the Arduino hardware.
Data Types: char
loadPin — Shift register parallel load pin to load parallel input data
character vector
Shift register parallel load pin to load parallel input data, specified as a character vector of the form
'Dx' where x is the Arduino pin number. For example, 'D7'. It is usually connected to the PL pin on
the shift register.
Example: register = shiftRegister(a,'74HC165','D3','D6','D7','D10') creates a
connection to a 74HC165 shift register whose load pin is connected to digital pin 7 on the Arduino
hardware.
Data Types: char
1-48
shiftRegister
Shift register clock enable pin to enable or disable clock, specified as a character vector of the form
'Dx' where x is the Arduino pin number. For example, 'D10'. It is usually connected to the CE pin
on the shift register.
Example: register = shiftRegister(a,'74HC165','D3','D6','D7','D10') creates a
connection to a 74HC165 shift register whose clock enable pin is connected to digital pin 10 on the
Arduino hardware.
Data Types: char
Shift register reset pin to reset output, specified as a character vector of the form 'Dx' where x is
the Arduino pin number. For example, 'D10'. It is usually connected to the CLR pin on the shift
register.
Example: register = shiftRegister(a,'74HC595','D3','D6','D7','D10') creates a
connection to a 74HC595 shift register whose reset pin is connected to digital pin 10 on the Arduino
hardware.
Data Types: char
Properties
Model — Shift register model number
character vector
Shift register model number, specified as a character vector. Supported shift registers are 74HC165,
74HC595, and 74HC164.
Example:
>> register.Model
ans =
'74HC164'
Shift register serial pin to input or output data, specified as a character vector of the form 'Dx'
where x is the Arduino pin number. For example, 'D3'. It is usually connected to the DS or SER pin
on the shift register.
Example:
>> register.DataPin
ans =
1-49
1 Classes
'D3'
Shift register clock pin to signal read or write, specified as a character vector of the form 'Dx' where
x is the Arduino pin number. For example, 'D6'. It is usually connected to the SHCP or SRCLK pin on
the shift register.
Example:
>> register.ClockPin
ans =
'D6'
Shift register latch pin to latch input data, specified as a character vector of the form 'Dx' where x is
the Arduino pin number. For example, 'D7'. It is usually connected to the STCP or RCLK pin on the
shift register. It is only for the 74HC595 shift register.
Example:
>> register.LatchPin
ans =
'D7'
LoadPin — Shift register parallel load pin to load parallel input data
character vector
Shift register parallel load pin to load parallel input data, specified as a character vector of the form
'Dx' where x is the Arduino pin number. For example, 'D7'. It is usually connected to the PL pin on
the shift register. It is only for the 74HC165 shift register.
Example:
>> register.LoadPin
ans =
'D7'
1-50
shiftRegister
Shift register clock enable pin to enable or disable clock, specified as a character vector of the form
'Dx' where x is the Arduino pin number. For example, 'D10'. It is usually connected to the CE pin
on the shift register. It is only for the 74HC165 shift register.
Example:
>> register.ClockEnablePin
ans =
'D10'
Shift register reset pin to reset output, specified as a character vector of the form 'Dx' where x is
the Arduino pin number. For example, 'D10'. It is usually connected to the CLR pin on the shift
register. It is only for the 74HC164 shift register.
Example:
>> register.ResetPin
ans =
'D10'
Object Functions
Use these object functions to read from and write to your shift register.
read Read data from shift register
write Write data to shift register
reset Clear all outputs of shift register
Examples
1-51
1 Classes
a = arduino('COM4','Uno','Libraries','ShiftRegister');
register = shiftRegister(a,'74HC165','D3','D6','D7','D10')
register =
shiftRegister with properties:
Model: '74HC165'
DataPin: 'D3'
ClockPin: 'D6'
LoadPin: 'D7'
ClockEnablePin: 'D10'
a = arduino('COM4','Uno','Libraries','ShiftRegister');
register = shiftRegister(a,'74HC595','D3','D6','D7')
register =
shiftRegister with properties:
Model: '74HC595'
DataPin: 'D3'
ClockPin: 'D6'
LatchPin: 'D7'
ResetPin: Not specified
Connect to a 74HC595 shift register, and specify the resetPin to reset the outputs.
a = arduino('COM4','Uno','Libraries','ShiftRegister');
register = shiftRegister(a,'74HC595','D3','D6','D7','D8')
register =
shiftRegister with properties:
Model: '74HC595'
DataPin: 'D3'
ClockPin: 'D6'
LatchPin: 'D7'
ResetPin: 'D8'
1-52
shiftRegister
a = arduino('COM4','Uno','Libraries','ShiftRegister');
register = shiftRegister(a,'74HC164','D3','D6')
register =
shiftRegister with properties:
Model: '74HC164'
DataPin: 'D3'
ClockPin: 'D6'
ResetPin: Not specified
Connect to a 74HC164 shift register, and specify the resetPin to reset the outputs.
a = arduino('COM4','Uno','Libraries','ShiftRegister');
register = shiftRegister(a,'74HC164','D3','D6','D7')
register =
shiftRegister with properties:
Model: '74HC164'
DataPin: 'D3'
ClockPin: 'D6'
ResetPin: 'D7'
Version History
Introduced in R2016b
See Also
arduino | write | read | reset
1-53
1 Classes
stepper
Connection to stepper motor on Adafruit Motor Shield V2 for Arduino
Description
A stepper object represents a connection to a stepper motor on an Adafruit Motor Shield V2
connected to Arduino hardware. Attach a motor shield to the Arduino hardware, and connect a
stepper motor to the appropriate pins on the motor shield. Create a motor shield object using the
addon function, and create a stepper object using the stepper function. You can control your
stepper motor in MATLAB using the object functions.
Creation
Syntax
sm = stepper(shield,motornum,sprev)
sm = stepper(shield,motornum,sprev,Name,Value)
Description
Input Arguments
Adafruit Motor Shield connection on Arduino hardware, specified as an adafruit motor shield object
created using the addon function.
Example: sm = stepper(shield,1,200) creates a connection to a stepper motor on the specified
adafruit motor shield object shield.
Stepper motor number where the motor is connected on the Adafruit Motor Shield, specified as a
number. Valid values are 1 and 2. If you are using ports M1 and M2 on the shield, set motor number to
1. If you are using M3 and M4, set motor number to 2.
Example: sm = stepper(shield,1,200) creates a connection to a stepper motor on port M1 or
M2 on the motor shield.
1-54
stepper
Steps per revolution of the stepper motor, specified as a number. Steps per revolution depend on your
motor. For example, a 7.5 degree/step stepper motor has 360/7.5 = 48 steps.
Example: sm = stepper(shield,1,200) creates a connection to a stepper motor with 200 steps
per revolution, or a 1.8 degree/step stepper motor.
Name-Value Pair Arguments
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: sm = stepper(shield,1,200,'RPM',10,'StepType','interleave')
Revolutions per minute, specified as the comma-separated pair consisting of 'RPM' and a number.
RPM determines the speed of the motor.
Example: sm = stepper(shield,1,200,'RPM',10) creates a stepper motor connection with an
RPM of 10.
Coil activation type, specified as the comma-separated pair consisting of 'StepType' and a
character vector. The default value is 'Single'. Valid character vectors are:
• 'Single'
• 'Double'
• 'Interleave'
• 'Microstep'
Properties
RPM — Revolutions per minute
0 (default) | numeric
Revolutions per minute, specified as a number. RPM determines the speed of the motor. You can
specify the revolutions per minute when you create the stepper object or after you create the
stepper object.
Example:
>> sm.RPM = 10
sm =
1-55
1 Classes
MotorNumber: 2
StepsPerRevolution: 200
RPM: 10
StepType: Single ('Single', 'Double', 'Interleave', 'Microstep')
Coil activation type, specified as the comma-separated pair consisting of 'StepType' and a
character vector. The default value is 'Single'. Valid character vectors are:
• 'Single'
• 'Double'
• 'Interleave'
• 'Microstep'
Example:
>> sm.StepType
ans =
'Single'
Motor shield port number that displays the number of the port on the Adafruit Motor Shield to which
the stepper motor is connected, specified as a number during the stepper motor object creation. Valid
port values are 1 and 2.
Example:
>> sm.MotorNumber
ans =
StepsPerRevolution — Number of steps that the stepper motor rotates each revolution
numeric
Number of steps that the stepper motor rotates each revolution, specified as a number during the
stepper motor object creation.
1-56
stepper
Example:
>> sm.StepsPerRevolution
ans =
200
Object Functions
Use these object functions to control your stepper motor.
move Rotate stepper motor connected to Adafruit Motor Shield
release Release stepper motor connected to Adafruit Motor Shield
Examples
Create a stepper motor connection to an Adafruit Motor Shield attached to Arduino hardware.
a = arduino('COM4','Uno','Libraries','Adafruit/MotorShieldV2');
shield = addon(a,'Adafruit/MotorShieldV2');
Create a stepper motor connection to motor number 1 on the shield, with steps per revolution of 200
and an RPM of 10.
sm = stepper(shield,1,200,'RPM',10)
sm =
stepper with properties:
MotorNumber: 1
StepsPerRevolution: 200
RPM: 10
StepType: Single ('Single', 'Double', 'Interleave', 'Microstep')
Create a stepper motor connection to an Adafruit Motor Shield attached to Arduino hardware.
a = arduino('COM4','Uno','Libraries','Adafruit/MotorShieldV2');
shield = addon(a,'Adafruit/MotorShieldV2');
Create a stepper motor connection to motor number 1 on the shield, with the steps per revolution of
200, an RPM of 10, and 'steptype' set to 'Interleave'.
sm = stepper(shield,1,200,'RPM',10,'stepType','Interleave')
sm =
stepper with properties:
1-57
1 Classes
MotorNumber: 1
StepsPerRevolution: 200
RPM: 10
StepType: Interleave ('Single', 'Double', 'Interleave', 'Microstep')
Version History
Introduced in R2014b
See Also
move | release | addon | arduino
Topics
“Control Motors Using Adafruit Motor Shield V2”
1-58
ultrasonic
ultrasonic
Connection to ultrasonic sensor on Arduino hardware
Description
This object represents a connection to an ultrasonic sensor connected to the Arduino hardware. To
measure the distance to an object with the ultrasonic sensor, use this object with the functions listed
in “Object Functions” on page 1-60.
Creation
Syntax
ultrasonicObj = ultrasonic(arduinoObj,triggerPin)
ultrasonicObj = ultrasonic(arduinoObj,triggerPin,echoPin)
ultrasonicObj = ultrasonic(arduinoObj,triggerPin,echoPin,Name,Value)
Description
Input Arguments
Digital pin number on the Arduino hardware that is connected to the trigger pin on the ultrasonic
sensor, specified as a scalar.
Example: ultrasonicObj = ultrasonic(arduinoObj,'D2')
Data Types: char | string
1-59
1 Classes
Digital pin number on the Arduino hardware that is connected to the echo pin on the ultrasonic
sensor, specified as a scalar. If echoPin isn't specified, the connection object sets the echo pin to the
same value as triggerPin.
Data Types: char | string
Name-Value Pair Arguments
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Object Functions
readDistance Distance to object in front of ultrasonic sensor
readEchoTime Read echo time of ultrasound waves
Examples
Updating server code on board Uno (COM9). This may take a few minutes.
arduinoObj =
arduino with properties:
Port: 'COM9'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11'}
AvailableAnalogPins: {'A0-A5'}
AvailableI2CBusIDs: [0]
Libraries: {'Ultrasonic'}
Show all properties
Create an ultrasonic sensor connection object with the trigger pin and echo pin set to D2.
ultrasonicObj = ultrasonic(arduinoObj,'D2')
ultrasonicObj =
Ultrasonic with properties:
1-60
ultrasonic
TriggerPin: 'D2'
EchoPin: 'D2'
arduinoObj = arduino('COM9','Uno','Libraries','Ultrasonic')
arduinoObj =
arduino with properties:
Port: 'COM9'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11'}
AvailableAnalogPins: {'A0-A5'}
AvailableI2CBusIDs: 0
AvailableSPIBusIDs: 1
Libraries: {'Ultrasonic'}
Create an ultrasonic sensor connection object with the trigger pin set to D2 and the echo pin set to
D3.
ultrasonicObj = ultrasonic(arduinoObj,'D2','D3')
ultrasonicObj =
Ultrasonic with properties:
TriggerPin: 'D2'
EchoPin: 'D3'
Create an Ultrasonic Connection Object for Four-Pin Sensor with Double Output
arduinoObj = arduino('COM9','Uno',"Libraries","Ultrasonic")
arduinoObj =
arduino with properties:
Port: 'COM9'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11'}
AvailableAnalogPins: {'A0-A5'}
AvailableI2CBusIDs: [0]
1-61
1 Classes
Libraries: {'Ultrasonic'}
Show all properties
Create an ultrasonic sensor connection object with the trigger pin set to D2 and echo pin set to D3
and the OutputFormat set to 'double'
ultrasonicObj = ultrasonic(arduinoObj,'D2','D3','OutputFormat','double')
ultrasonicObj =
Ultrasonic with properties:
TriggerPin: 'D2'
EchoPin: 'D3'
Version History
Introduced in R2019a
See Also
readDistance | readEchoTime
1-62
lsm9ds1
lsm9ds1
Connect to LSM9DS1 sensor on Arduino hardware I2C bus
Description
The lsm9ds1 object reads acceleration, angular velocity, and magnetic field using the
STMicroelectronics® LSM9DS1 sensor. The LSM9DS1 is a 9 degree of freedom (DOF) inertial
measurement unit (IMU) used to read acceleration, angular velocity, and magnetic field in all three
dimensions.
The lsm9ds1 object represents a connection to the device on the Arduino hardware I2C bus. Attach
an LSM9DS1 sensor to the I2C pins on the Arduino hardware. You can read the data from your sensor
in MATLABusing the object functions.
Before you use the lsm9ds1 object, create an Arduino object using arduino on page 1-6 and set its
properties. When you create the Arduino object, make sure that you include the I2C library. For more
information, see “Connect to Arduino Hardware”.
Creation
Syntax
imu = lsm9ds1(a)
imu = lsm9ds1(a,Name,Value)
Description
imu = lsm9ds1(a) creates a sensor object with default property values. The object represents the
connection to the sensor on the Arduino hardware, a.
imu = lsm9ds1(a,Name,Value) creates a sensor object with properties using one or more
Name,Value pair arguments.
Example: imu =
lsm9ds1(a,'SampleRate',150,'SamplesPerRead',5,'ReadMode','latest');
Input Arguments
Arduino hardware connection created using arduino on page 1-6, specified as an object.
Example: imu = lsm9ds1(a) creates a connection to the LSM9DS1 sensor on the Arduino object, a.
1-63
1 Classes
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LSM9DS1 are connected to the same hardware board. LSM9DS1 can have multiples slave addresses
which depends on the logic level on pins SDO_A/G and SDO_M of the sensor.
'0x6A' is the I2C address of the accelerometer and gyroscope of LSM9DS1. '0x1C' is the I2C
address of the magnetometer of LSM9DS1.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Properties
Note The properties can also be used as name-value pair arguments while creating an lsm9ds1
object.
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LSM9DS1 are connected to the same hardware board. LSM9DS1 can have multiples peripheral
addresses which depends on the logic level on pins SDO_A/G and SDO_M of the sensor.
1-64
lsm9ds1
'0x6A' is the I2C address of the accelerometer and gyroscope of LSM9DS1. '0x1C' is the I2C
address of the magnetometer of LSM9DS1.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Note Except for TimeFormat, all the other properties are non-tunable, which means you cannot
change their values once the object is locked. Objects are locked when you call the read function,
and the release function unlocks them. If a property is tunable, you can change its value at any
time.
Tunable: No
Data Types: double
Number of samples read from the sensor in a single execution of the read function.
Tunable: No
Data Types: double
1-65
1 Classes
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Tunable: No
Data Types: character vector | string
1-66
lsm9ds1
Samples read from the first read. When you release the object, SamplesRead is set to 0.
Data Types: double
Samples available in the host buffer. The data read from the sensor is stored in the MATLAB buffer.
SamplesAvailable property shows the number of SamplesAvailable in this host buffer. When
you release the object, SamplesAvailable is set to 0. When the ReadMode of sensor is set as
latest, SamplesAvailable will always be 0.
Data Types: double
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
When the OutputFormat is set to matrix, the data is returned as matrices of acceleration, angular
velocity, magnetic field, and time stamps. The units for the sensor readings are the same as the
timetable format. The size of each matrix is N-by-3.
N is the number of samples per read specified by SamplesPerRead. The three columns of each field
represent the measurements in x, y, and z axes.
Tunable: No
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Tunable: Yes
Data Types: character vector | string
1-67
1 Classes
Examples
Create LSM9DS1 Sensor Connection
a = arduino();
Or, you can explicitly specify it in the Libraries Name-Value pair while creating the Arduino object.
clear a;
a = arduino('COM4', 'Uno', 'Libraries', 'I2C');
imu = lsm9ds1(a)
imu =
Create a sensor object with additional properties specified as name-value pair arguments.
clear imu;
imu = lsm9ds1(a,'SampleRate',50,'SamplesPerRead',5,'ReadMode','oldest')
imu =
SampleRate: 50 (Samples/s)
SamplesPerRead: 5
ReadMode: 'oldest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions
1-68
lsm9ds1
Object Functions
readAcceleration Read one sample of acceleration from sensor
readAngularVelocity Read one sample of angular velocity from sensor
readMagneticField Read one sample of magnetic field from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
More About
Code Generation Using MATLAB Function Block
• Use lsm9ds1 in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
• The property OutputFormat is always set to matrix.
• The property TimeFormat is always set to duration.
• The property SamplesAvailable is not accessible from sensor object.
• The default value of I2C address will be taken as [0x6B, 0x1E]. Specify I2C address if the sensor
has a different I2C address. The possible values of I2C Addresses are mentioned in the table under
I2Caddress section in this page.
Version History
Introduced in R2019a
See Also
Topics
“Calculate Pitch and Roll on Arduino Using IMU Sensor” (Simulink Support Package for Arduino
Hardware)
1-69
1 Classes
mpu6050
Connect to MPU-6050 sensor on Arduino hardware I2C bus
Description
The mpu6050 object reads acceleration and angular velocity using the InvenSense MPU-6050 sensor.
The MPU-6050 is a 6 degree of freedom (DOF) inertial measurement unit (IMU) used to read
acceleration and angular velocity in all three dimensions.
The mpu6050 object represents a connection to the device on the Arduino hardware I2C bus. Attach
an MPU-6050 sensor to the I2C pins on the Arduino hardware. You can read the data from your
sensor in MATLABusing the object functions.
Before you use the mpu6050 object, create an Arduino object using arduino on page 1-6 and set its
properties. When you create the Arduino object, make sure that you include the I2C library. For more
information, see “Connect to Arduino Hardware”.
Creation
Syntax
imu = mpu6050(a)
imu = mpu6050(a,Name,Value)
Description
imu = mpu6050(a) creates a sensor object with default property values. The object represents the
connection to the sensor on the Arduino hardware, a.
imu = mpu6050(a,Name,Value) creates a sensor object with properties using one or more
Name,Value pair arguments.
Example: imu =
mpu6050(a,'SampleRate',150,'SamplesPerRead',5,'ReadMode','latest');.
Input Arguments
Arduino hardware connection created using arduino on page 1-6, specified as an object.
Example: imu = mpu6050(a) creates a connection to the MPU-6050 sensor on the Arduino object,
a.
1-70
mpu6050
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
MPU-6050 are connected to the same hardware board. MPU-6050 can have two I2C addresses
depending on the logic level on pin AD0 of the sensor.
0x68 is the I2C address of the accelerometer and gyroscope of MPU-6050 connected to Arduino
board.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Properties
Note The properties can also be used as name-value pair arguments while creating an mpu6050
object.
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
MPU-6050 are connected to the same hardware board. MPU-6050 can have two I2C addresses
depending on the logic level on pin AD0 of the sensor.
1-71
1 Classes
0x68 is the I2C address of the accelerometer and gyroscope of MPU-6050 connected to Arduino
board.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Note Except for TimeFormat, all the other properties are non-tunable, which means you cannot
change their values once the object is locked. Objects are locked when you call the read function,
and the release function unlocks them. If a property is tunable, you can change its value at any
time.
Tunable: No
Data Types: double
Number of samples read from the sensor in a single execution of the read function.
Tunable: No
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
1-72
mpu6050
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Tunable: No
Data Types: character vector | string
Samples read from the first read. When you release the object, SamplesRead is set to 0.
Data Types: double
1-73
1 Classes
Samples available in the host buffer. The data read from the sensor is stored in the MATLAB buffer.
SamplesAvailable property shows the number of SamplesAvailable in this host buffer. When
you release the object, SamplesAvailable is set to 0. When the ReadMode of sensor is set as
latest, SamplesAvailable will always be 0.
Data Types: double
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
When the OutputFormat is set to matrix, the data is returned as matrices of acceleration, angular
velocity, and time stamps. The units for the sensor readings are the same as the timetable format.
The size of each matrix is N-by-3.
N is the number of samples per read specified by SamplesPerRead. The three columns of each field
represent the measurements in x, y, and z axes.
Tunable: No
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Tunable: Yes
Data Types: character vector | string
Examples
Create MPU-6050 Sensor Connection
a = arduino();
1-74
mpu6050
Or, you can explicitly specify it in the Libraries Name-Value pair while creating the Arduino object.
clear a;
a = arduino('COM4', 'Uno', 'Libraries', 'I2C');
imu = mpu6050(a)
imu =
Create a sensor object with additional properties specified as name-value pair arguments.
clear imu;
imu = mpu6050(a,'SampleRate',50,'SamplesPerRead',5,'ReadMode','oldest')
imu =
SampleRate: 50 (Samples/s)
SamplesPerRead: 5
ReadMode: 'oldest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions
Object Functions
readAcceleration Read one sample of acceleration from sensor
readAngularVelocity Read one sample of angular velocity from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
1-75
1 Classes
More About
Code Generation Using MATLAB Function Block
• Use mpu6050 in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
• The property OutputFormat is always set to matrix.
• The property TimeFormat is always set to duration.
• The property SamplesAvailable is not accessible from sensor object.
• The default value of I2C address will be taken as 0x68. Specify I2C address if the sensor has a
different I2C address. The possible values of I2C Addresses are mentioned in the table under
I2Caddress section in this page.
Version History
Introduced in R2019a
See Also
Topics
“Calculate Pitch and Roll on Arduino Using IMU Sensor” (Simulink Support Package for Arduino
Hardware)
1-76
mpu9250
mpu9250
Connect to MPU-9250 sensor on Arduino hardware I2C bus
Description
The mpu9250 object reads acceleration, angular velocity, and magnetic field using the InvenSense
MPU-9250 sensor. The MPU-9250 is a 9 degree of freedom (DOF) inertial measurement unit (IMU)
used to read acceleration, angular velocity, and magnetic field in all three dimensions.
The mpu9250 object represents a connection to the device on the Arduino hardware I2C bus. Attach
an MPU-9250 sensor to the I2C pins on the Arduino hardware. You can read the data from your
sensor in MATLABusing the object functions.
Before you use the mpu9250 object, create an Arduino object using arduino on page 1-6 and set its
properties. When you create the Arduino object, make sure that you include the I2C library. For more
information, see “Connect to Arduino Hardware”.
Creation
Syntax
imu = mpu9250(a)
imu = mpu9250(a,Name,Value)
Description
imu = mpu9250(a) creates a sensor object with default property values. The object represents the
connection to the sensor on the Arduino hardware, a.
imu = mpu9250(a,Name,Value) creates a sensor object with properties using one or more
Name,Value pair arguments.
Input Arguments
Arduino hardware connection created using arduino on page 1-6, specified as an object.
Example: imu = mpu9250(a) creates a connection to the MPU-9250 sensor on the Arduino object,
a.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
1-77
1 Classes
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
MPU9250 are connected to the same hardware board. MPU9250 can have multiple I2C addresses
depending on the logic level on pin AD0 of the sensor.
'0x69' is the I2C address of the accelerometer and gyroscope of MPU9250. '0x0C' is the I2C address
of the magnetometer of MPU9250.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Properties
Note The properties can also be used as name-value pair arguments while creating an mpu9250
object.
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
MPU9250 are connected to the same hardware board. MPU9250 can have multiple I2C addresses
depending on the logic level on pin AD0 of the sensor.
1-78
mpu9250
'0x69' is the I2C address of the accelerometer and gyroscope of MPU9250. '0x0C' is the I2C address
of the magnetometer of MPU9250.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Note Except for TimeFormat, all the other properties are non-tunable, which means you cannot
change their values once the object is locked. Objects are locked when you call the read function,
and the release function unlocks them. If a property is tunable, you can change its value at any
time.
Tunable: No
Data Types: double
Number of samples read from the sensor in a single execution of the read function.
Tunable: No
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
1-79
1 Classes
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Tunable: No
Data Types: character vector | string
Samples read from the first read. When you release the object, SamplesRead is set to 0.
Data Types: double
Samples available in the host buffer. The data read from the sensor is stored in the MATLAB buffer.
SamplesAvailable property shows the number of SamplesAvailable in this host buffer. When
you release the object, SamplesAvailable is set to 0. When the ReadMode of sensor is set as
latest, SamplesAvailable will always be 0.
1-80
mpu9250
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
When the OutputFormat is set to matrix, the data is returned as matrices of acceleration, angular
velocity, magnetic field, and time stamps. The units for the sensor readings are the same as the
timetable format. The size of each matrix is N-by-3.
N is the number of samples per read specified by SamplesPerRead. The three columns of each field
represent the measurements in x, y, and z axes.
Tunable: No
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sesnor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Tunable: Yes
Data Types: character vector | string
Examples
Create MPU-9250 Sensor Connection
a = arduino();
Or, you can explicitly specify it in the Libraries Name-Value pair while creating the Arduino object.
clear a;
a = arduino('COM4', 'Uno', 'Libraries', 'I2C');
imu = mpu9250(a)
1-81
1 Classes
imu =
Create a sensor object with additional properties specified as name-value pair arguments.
clear imu;
imu = mpu9250(a,'SampleRate',50,'SamplesPerRead',5,'ReadMode','oldest')
imu =
SampleRate: 50 (Samples/s)
SamplesPerRead: 5
ReadMode: 'oldest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions
Object Functions
readAcceleration Read one sample of acceleration from sensor
readAngularVelocity Read one sample of angular velocity from sensor
readMagneticField Read one sample of magnetic field from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
More About
Code Generation Using MATLAB Function Block
• Use mpu9250 in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
1-82
mpu9250
Version History
Introduced in R2019a
See Also
Topics
“Calculate Pitch and Roll on Arduino Using IMU Sensor” (Simulink Support Package for Arduino
Hardware)
1-83
1 Classes
lis3dh
Connect to LIS3DH sensor on Arduino hardware I2C bus
Description
The lis3dh object reads linear acceleration and temperature using the LIS3DH sensor connected to
the I2C bus of the Arduino hardware. Attach the LIS3DH sensor to the I2C pins on the hardware. You
can read the data from the sensor in MATLAB using the “Object Functions” on page 1-88.
Creation
Syntax
accelSensor = lis3dh(a)
accelSensor = lis3dh(a,Name,Value)
Description
Input Arguments
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
1-84
lis3dh
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LIS3DH are connected to the same hardware board. LIS3DH can have two I2C addresses depending
on the logic level on pin SA0 of the sensor.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Properties
Note
• All the properties except SamplesRead and SamplesAvailable can be set by specifying as
name-value pair arguments while creating an lis3dh object.
• The properties I2CAddress and Bus are immutable (the property value is set during
construction; you cannot change the value of an immutable property after the object is created).
• The TimeFormat property is tunable, which means you can change the value anytime. The
SampleRate, SamplesPerRead, ReadMode, and OutputFormat properties are non-tunable,
which means you cannot change their values once the object is locked. Objects are locked when
you call the read function, and the release function unlocks them. If a property is tunable, you
can change its value at any time.
1-85
1 Classes
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LIS3DH are connected to the same hardware board. LIS3DH can have two I2C addresses depending
on the logic level on pin SA0 of the sensor.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Number of samples read from the sensor in a single execution of the read function.
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
1-86
lis3dh
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Samplesread property outputs the values of samples read so far by executing read function.
Samplesread is set to 0, when the object is created or when you release the object.
Data Types: double
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
1-87
1 Classes
When the OutputFormat is set to matrix, the data is returned as matrices of pressure,
temperature, and time stamps. The units for the sensor readings are the same as the timetable
format.
N is the number of samples per read specified by SamplesPerRead. The three columns of each field
represent the measurements in x, y, and z axes.
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Object Functions
readAcceleration Read one sample of acceleration from sensor
readTemperature Read one sample of temperature from sensor
readVoltage Read voltage from ADC pins on sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
Examples
Create Connection to LIS3DH Sensor
accelSensor = lis3dh(a)
accelSensor =
I2CAddress: 24 ("0x18")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"
1-88
lis3dh
SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions
Create a sensor object with additional properties specified as name-value pair arguments.
clear accelSensor;
accelSensor = lis3dh(a,'SampleRate',50,'SamplesPerRead',5,'ReadMode','oldest')
accelSensor =
I2CAddress: 24 ("0x18")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"
More About
Code Generation Using MATLAB Function Block
• Use lis3dh in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
• The property OutputFormat is always set to matrix.
• The property TimeFormat is always set to duration.
• The property SamplesAvailable is not accessible from sensor object.
• The default value of I2C address will be taken as 0x18. Specify I2C address if the sensor has a
different I2C address. The possible values of I2C Addresses are mentioned in the table under
I2Caddress section in this page.
Version History
Introduced in R2022b
1-89
1 Classes
See Also
lsm6dsl
1-90
bmi160
bmi160
Connect to BMI160 sensor on Arduino hardware I2C bus
Description
The bmi160 object reads acceleration, angular velocity, and temperature using the BMI160 sensor. If
BMM150 sensor is connected as a secondary sensor to BMI160 sensor, the bmi160 object also
outputs magnetic field along x-, y- and z- axes as measured by the BMM150 sensor.
The bmi160 object represents a connection to the device on the Arduino hardware I2C bus. Attach an
BMI160 sensor to the I2C pins on the Arduino hardware. You can read the data from your sensor in
MATLABusing the object functions.
Before you use the bmi160 object, create an Arduino object using arduino on page 1-6 and set its
properties. When you create the Arduino object, make sure that you include the I2C library. For more
information, see “Connect to Arduino Hardware”.
Creation
Syntax
imu = bmi160(a)
imu = bmi160(a,Name,Value)
Description
imu = bmi160(a) creates a sensor object with default property values. The object represents the
connection to the sensor on the Arduino hardware, a.
imu = bmi160(a,Name,Value) creates a sensor object with properties using one or more
Name,Value pair arguments.
Input Arguments
Arduino hardware connection created using arduino on page 1-6, specified as an object.
Example: imu = bmi160(a) creates a connection to the BMI160 sensor on the Arduino object, a.
Name-Value Pair Arguments
You can specify any of the properties on this page as name-value pairs.
1-91
1 Classes
Properties
Note
• All the properties except SamplesRead and SamplesAvailable can be set by specifying as
name-value pair arguments while creating an bmi160 object.
• The properties I2CAddress and Bus are immutable (the property value is set during
construction; you cannot change the value of an immutable property after the object is created).
• The TimeFormat property is tunable, which means you can change the value anytime. The
SampleRate, SamplesPerRead, ReadMode, and OutputFormat properties are non-tunable,
which means you cannot change their values once the object is locked. Objects are locked when
you call the read function, and the release function unlocks them. If a property is tunable, you
can change its value at any time.
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
BMI160 are connected to the same hardware board. BMI160 can have multiple I2C addresses
depending on the logic level on pin AD0 of the sensor.
'0x69' is the I2C address of the accelerometer and gyroscope of BMI160. '0x0C' is the I2C address of
the magnetometer of BMI160.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
1-92
bmi160
SampleRate — Rate at which sample is read during the execution of read function
100 (default) | positive integer in the range [11, 200]
The rate in Samples/s at which data is read from the sensor during execution of read function.
Note Real-time data rate acquisition from BMI160 sensor can be achieved by using the SampleRate
property and read function.
Tunable: No
Data Types: double
Number of samples read from the sensor in a single execution of the read function.
Tunable: No
Data Types: double
ReadMode — Specify which data samples to be returned during the execution of read
function
'latest' (default) | 'oldest'
Specify whether to return the latest or the oldest data samples during execution of read function.
The number of samples depends on the SamplesPerRead value. The data read from the sensor is
stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
• oldest —
1-93
1 Classes
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Tunable: No
Data Types: character vector | string
SamplesRead — Samples read which gets updated with the execution of read
double
Samples read from the first read. This property gets updated with the execution of read function.
When you release the object, SamplesRead is set to 0.
Data Types: double
SamplesAvailable — Samples in the host buffer which gets updated with the execution of
read
double
Samples available in the host buffer. This property gets updated with the execution of read function.
The data read from the sensor is stored in the MATLAB buffer. SamplesAvailable property shows
the number of SamplesAvailable in this host buffer. When you release the object,
SamplesAvailable is set to 0. When the ReadMode of sensor is set as latest,
SamplesAvailable will always be 0.
Data Types: double
OutputFormat — Set output format returned after the execution of read function
'timetable' (default) | 'matrix'
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
1-94
bmi160
When the OutputFormat is set to matrix, the data is returned as matrices of acceleration, angular
velocity, magnetic field, temperature, and time stamps. The units for the sensor readings are the
same as the timetable format. The size of each matrix is N-by-3.
N is the number of samples per read specified by SamplesPerRead. The three columns of each field
represent the measurements in x, y, and z axes.
If secondary sensor is not connected, then nan will be displayed for magnetic fields.
Tunable: No
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read using read function.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Tunable: Yes
Data Types: character vector | string
Examples
Create BMI160 Sensor Connection
a = arduino();
Or, you can explicitly specify it in the Libraries Name-Value pair while creating the Arduino object.
clear a;
a = arduino('COM4', 'Uno', Libraries='I2C');
imu = bmi160(a)
imu =
1-95
1 Classes
: 12 ("0xC")
SCLPin: "A5"
SDAPin: "A4"
Create a sensor object with additional properties specified as name-value pair arguments.
clear imu;
imu = bmi160(a,SampleRate=50,SamplesPerRead=5,ReadMode='latest')
imu =
SampleRate: 50 (Samples/s)
SamplesPerRead: 5
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions
Object Functions
readAcceleration Read one sample of acceleration from sensor
readAngularVelocity Read one sample of angular velocity from sensor
readMagneticField Read one sample of magnetic field from sensor
readTemperature Read one sample of temperature from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
More About
Code Generation Using MATLAB Function Block
• Use bmi160 in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
1-96
bmi160
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
• The property OutputFormat is always set to matrix.
• The property TimeFormat is always set to duration.
• The property SamplesAvailable is not accessible from sensor object.
• The default value of I2C address will be taken as [0x69, 0x0C]. Specify I2C address if the sensor
has a different I2C address. The possible values of I2C Addresses are mentioned in the table under
I2Caddress section in this page.
Version History
Introduced in R2023a
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
See Also
mpu9250 | icm20948
1-97
2
Functions
2 Functions
arduinosetup
Launch Arduino hardware setup interface
Syntax
arduinosetup
Description
arduinosetup launches an interactive hardware setup interface to configure the connection to your
Arduino hardware. For complete information on how to use the interactive hardware setup interface,
see “Set up and Configure Arduino Hardware”.
Note See “Boards Not Listed in Interactive Hardware Setup”, if you are using any of the following
boards on the macOS 10.15 Catalina:
Version History
Introduced in R2017a
See Also
arduino
Topics
“Install Support for Arduino Hardware”
“Set up and Configure Arduino Hardware”
2-2
configurePin
configurePin
Set Arduino pin mode
Syntax
pinMode = configurePin(a,pin)
configurePin(a,pin,mode)
Description
pinMode = configurePin(a,pin) displays the mode the specified pin on the Arduino hardware
in connection a .
Examples
a = arduino('COM4','Uno');
configurePin(a,'A2')
ans =
'Unset'
a = arduino('COM4','Uno');
configurePin(a,'A4','I2C');
pinMode = configurePin(a,'A4')
pinMode =
'I2C'
a = arduino('COM4','Uno');
configurePin(a,'D3','pullup');
pinmode = configurePin(a,'D3')
2-3
2 Functions
pinmode =
'Pullup'
a = arduino('COM4','Uno');
configurePin(a,'D3','pullup');
pinMode = configurePin(a,'D3')
pinMode =
'Pullup'
configurePin(a,'D3','Unset');
pinMode = configurePin(a,'D3')
pinMode =
'Unset'
Input Arguments
a — Arduino hardware connection
object
Note If you connect to ESP32 board and the pin's mode is set to AnalogInput, the pin number must
always correspond to a digital pin. For details, see “Pin-mapping for ESP32 Boards” on page 2-5.
2-4
configurePin
Pins are configured on first usage. You can reset the pin mode to change the mode. If you want to use
a pullup, you must set the mode to 'pullup'.
Output Arguments
pinMode — Current mode of Arduino pin
character vector
More About
Pin-mapping for ESP32 Boards
If you connect to an ESP32 board, use the following table to map the analog pin number to the
corresponding digital pin number, which must be entered as the pin's value.
2-5
2 Functions
• Use configurePin in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• Configure the Arduino peripherals using configurePin before using it in the MATLAB Function
block.
• The function does not return any output during code generation.
• The following modes are currently supported for code generation : AnalogInput,
DigitalInput, DigitalOutput, Pullup, PWM, and Unset.
Version History
Introduced in R2015b
See Also
arduino | readVoltage | readDigitalPin | writeDigitalPin
2-6
listArduinoLibraries
listArduinoLibraries
Display a list of installed Arduino libraries
Syntax
lib = listArduinoLibraries();
Description
lib = listArduinoLibraries(); creates a list of available Arduino libraries and saves the list to
the variable lib.
Examples
lib = listArduinoLibraries()
lib =
{'Adafruit/BNO055' }
{'Adafruit/MotorShieldV2'}
{'I2C' }
{'RotaryEncoder' }
{'SPI' }
{'Serial' }
{'Servo' }
{'ShiftRegister' }
{'Ultrasonic' }
Output Arguments
lib — List of Arduino libraries
object
List of available Arduino libraries specified as an object or a cell array of character vectors.
Version History
Introduced in R2014b
See Also
arduino
2-7
2 Functions
move
Rotate stepper motor connected to Adafruit Motor Shield
Syntax
move(sm,steps)
Description
move(sm,steps) rotates the stepper motor for the specified number of steps. The move command
blocks MATLAB while the stepper motor is rotating.
Examples
Connect to Arduino® hardware and create an add-on connection to an Adafruit® Motor Shield.
a = arduino('COM4','Uno','Libraries','Adafruit/MotorShieldV2');
shield = addon(a,'Adafruit/MotorShieldV2');
Create a stepper motor connection to motor number 1 on the shield, with steps per revolution of 200
and an RPM of 10.
sm = stepper(shield,1,200,'RPM',10);
move(sm,10);
Input Arguments
sm — Stepper motor connection
stepper motor object
Stepper motor connection, specified as a stepper motor object, created using the stepper function.
Version History
Introduced in R2014b
2-8
move
See Also
release | addon | stepper | arduino
Topics
“Control Motors Using Adafruit Motor Shield V2”
2-9
2 Functions
playTone
Play tone on piezo speaker using digital pin
Syntax
playTone(a,pin,frequency,duration)
playTone(a,pin)
playTone(a,pin,frequency)
Description
playTone(a,pin,frequency,duration) plays a tone on a piezo speaker attached to the digital
pin on Arduino hardware at the specified pin and frequency for the specified duration.
playTone(a,pin) plays a tone on a piezo speaker attached to the digital pin on Arduino hardware.
Examples
Play a tone connected to digital pin 5 on the Arduino hardware for 10 seconds at 2400Hz.
a = arduino();
playTone(a,'D5',2400,10);
Input Arguments
a — Arduino hardware connection
object
Frequency of tone to be played, specified as a number between the frequency range 0 and 32767Hz.
2-10
playTone
Duration of tone to be played specified as a number, which represents the number of seconds. Valid
values are between 0 and 60.
Limitations
This function is not supported on the Arduino Due, MKR1000, MKR1010, MKR Zero, Nano33IoT,
Nano33BLE and ESP32 boards.
Version History
Introduced in R2014b
See Also
arduino
2-11
2 Functions
read
Package: arduinoio
Syntax
out = read(dev,numBytes)
out = read(dev,numBytes,precision)
Description
out = read(dev,numBytes) returns data read from the I2C bus based on the number of bytes.
Examples
a = arduino();
dev = device(a,'I2CAddress','0x55');
out = read(dev,1)
out = 4
a = arduino();
dev = device(a,'I2CAddress','0x55');
Read data from the I2C device with the precision of uint16.
out = read(dev,1,'uint16')
out = 4
2-12
read
Input Arguments
dev — I2C device connection
device object
Number of bytes of data to read from the I2C device, specified as a scalar.
• 'uint8'
• 'int8'
• 'uint16'
• 'int16'
• 'uint32'
• 'int32'
• 'uint64'
• 'int64'
Output Arguments
out — Value of data
scalar | vector
Value of data stored at the I2C device register, returned as a scalar or vector based on the
precision .
More About
Code Generation Using MATLAB Function Block
• Use read in a MATLAB Function block with the Simulink Support Package for Arduino Hardware
to generate code that can be deployed on Arduino Hardware.
Version History
Introduced in R2014b
See Also
write | readRegister | writeRegister | arduino
2-13
2 Functions
Topics
“Communicate with an I2C EEPROM Device”
“Arduino I2C Interface”
2-14
read
read
Package: arduinoio
Syntax
out = read(register)
out = read(register,precision)
Description
out = read(register) reads data from the data pin of a parallel-in/serial-out (PISO) shift register.
Examples
a = arduino('COM4','Uno','Libraries','ShiftRegister');
register = shiftRegister(a,'74HC165','D3','D6','D7','D10');
out = read(register)
out = 1×8
1 1 1 1 1 0 0 0
Specify the data precision to read data from the data pin of a PISO shift register.
a = arduino('COM4','Uno','Libraries','ShiftRegister');
register = shiftRegister(a,'74HC165','D3','D6','D7','D10');
2-15
2 Functions
You can specify the precision as 'uint8' to read data from the register.
out = read(register,'uint8')
out = 0
out = read(register,8)
out = 1×8
0 0 0 0 0 0 0 0
Input Arguments
register — Shift register connection
shiftRegister object
• 8
• 16
• 24
• 32
• 'uint8'
• 'uint16'
• 'uint32'
The default precision is 8. The precision value cannot exceed the number of inputs of the shift
register. For a single chip, the number of inputs is eight. For chained shift registers, the number of
inputs is eight times the number of registers.
Output Arguments
out — Data read
double scalar | double vector
Data read from the data pin of a PISO shift register, returned as a double scalar or vector.
Version History
Introduced in R2016b
2-16
read
See Also
arduino | shiftRegister | write | reset
2-17
2 Functions
readCount
Read current count value from encoder with X4 decoding
Syntax
[count,time] = readCount(encoder)
[count,time] = readCount(encoder,Name,Value)
Description
[count,time] = readCount(encoder) returns the current count value from the encoder along
with the elapsed time since the Arduino server started running.
Examples
a = arduino('COM4','Uno','Libraries','rotaryEncoder');
encoder = rotaryEncoder(a,'D2','D3');
Read the current absolute count value that was incremented since the creation of the encoder object.
[count,time] = readCount(encoder)
count = 0
time = 0.1440
a = arduino('COM4','Uno','Libraries','rotaryEncoder');
encoder = rotaryEncoder(a,'D2','D3');
Set 'Reset' to true to read the current count value while also resetting the count value to zero on
the Arduino board.
2-18
readCount
[count,time] = readCount(encoder,'Reset',true)
count = 0
time = 0.1580
If you need the current incremental count value, consecutively call the readCount function with
'Reset' set to true.
Input Arguments
encoder — Quadrature encoder connection
rotaryEncoder object
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: [count, time] = readCount(rotaryEncoderObj, 'reset', true)
Example: [count, time] = readCount(rotaryEncoderObj, 'reset', true,
'OutputFormat', 'duration')
Flag to reset count value to 0 after each read operation, specified as the comma-separated pair
consisting of 'Reset' and either false or true.
Note Set 'Reset' to true to get the incremental count value from the last read.
OutputFormat — Output format of the time elapsed since the Arduino server started
duration
Note Only duration argument is supported. If you need the output as double, don't use the
OutputFormat name-value pair.
2-19
2 Functions
Output Arguments
count — Current count value of the encoder with X4 decoding
numeric
Note If the current count value is greater than 2^32-1, an overflow warning occurs. To prevent this
overflow, use resetCount function to reset count to 0.
Elapsed time since the Arduino server started running in seconds, returned as a number.
Version History
Introduced in R2017a
See Also
rotaryEncoder | resetCount | readSpeed
2-20
readDigitalPin
readDigitalPin
Read data from digital pin on Arduino hardware
Syntax
value = readDigitalPin(a,pin)
Description
value = readDigitalPin(a,pin) reads data from the specified pin on the Arduino hardware in
connection a.
Examples
ans = 1
Input Arguments
a — Arduino hardware connection
object
Output Arguments
value — value acquired from digital pin
double
More About
Code Generation Using MATLAB Function Block
• Use readDigitalPin in a MATLAB Function block with the Simulink Support Package for
Arduino Hardware to generate code that can be deployed on Arduino Hardware.
2-21
2 Functions
• Configure the Arduino peripherals to the appropriate mode using configurePin before using
readDigitalPin in the MATLAB Function block.
Version History
Introduced in R2014b
See Also
configurePin | writeDigitalPin | arduino
2-22
readDistance
readDistance
Distance to object in front of ultrasonic sensor
Syntax
distance = readDistance(ultrasonicObj)
Description
distance = readDistance(ultrasonicObj) measures the distance from the ultrasonic sensor
to an object and returns the measured distance in meters. The function uses 344 m/s for the velocity
of sound.
Examples
arduinoObj = arduino('COM9','Uno','Libraries','Ultrasonic');
Create an ultrasonic sensor connection object with the trigger pin set to D2 and echo pin set to D3.
ultrasonicObj = ultrasonic(arduinoObj,'D2','D3')
ultrasonicObj =
Ultrasonic with properties:
TriggerPin: 'D2'
EchoPin: 'D3'
distance = readDistance(ultrasonicObj);
Input Arguments
ultrasonicObj — ultrasonic object
ultrasonic object
Output Arguments
distance — Distance to object
positive real scalar
2-23
2 Functions
Distance to object, specified as a positive real scalar, in meters. If the object is not in the range of the
sensor, the function returns Inf.
Data Types: double
Version History
Introduced in R2019a
See Also
ultrasonic | readEchoTime
2-24
readEchoTime
readEchoTime
Read echo time of ultrasound waves
Syntax
time = readEchoTime(ultrasonicObj)
Description
time = readEchoTime(ultrasonicObj) measures the time taken by the ultrasound waves
reflected from the object to reach the sensor, represented by the connection object ultrasonicObj.
The distance to the object is computed from the time measured, using the equation distance =
(time x speedOfSound)/2.
Examples
arduinoObj = arduino('COM9','Uno','Libraries','Ultrasonic');
Updating server code on board Uno (COM9). This may take a few minutes.
Create an ultrasonic sensor connection object with the trigger pin set to D2 and echo pin set to D3.
ultrasonicObj = ultrasonic(arduinoObj,'D2','D3','OutputFormat','double')
ultrasonicObj =
Ultrasonic with properties:
TriggerPin: 'D2'
EchoPin: 'D3'
Measure the time taken by the ultrasound waves reflected from the object to reach the sensor.
time = readEchoTime(ultrasonicObj);
Calculate the distance to the object, by assuming the speed of sound to be 344 m/s.
distance = 344*time/2;
Input Arguments
ultrasonicObj — ultrasonic object
ultrasonic object
2-25
2 Functions
Output Arguments
time — echo time
positive real scalar | duration
The time taken for the ultrasound waves reflected from the object to reach the sensor, measured in
seconds. If the name-value pair OutputFormat is specified while creating the ultrasonic on page
1-59 object, the function returns echo time as a double. Otherwise, the function returns the time as a
duration. If the object is not in the range of the sensor, the function returns Inf.
Data Types: double | duration
Version History
Introduced in R2019a
See Also
ultrasonic | readDistance
2-26
readVoltage
readVoltage
Read voltage from analog pin on Arduino hardware
Syntax
voltage = readVoltage(a,pin)
Description
voltage = readVoltage(a,pin) reads the voltage on the specified analog input pins on Arduino
hardware.
Examples
Create an Arduino object and read voltage from and analog input pin.
a = arduino;
readVoltage(a,'A4')
ans = 1.0606
Input Arguments
a — Arduino hardware connection
object
Note If you connect to ESP32 board, the pin number must always correspond to a digital pin. For
details, see “Pin-mapping for ESP32 Boards” on page 2-5.
Output Arguments
voltage — Voltage read from analog pin
numeric
Voltage read from an analog pin on an Arduino hardware specified as a numeric double.
2-27
2 Functions
More About
Code Generation Using MATLAB Function Block
• Use readVoltage in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• Configure the Arduino peripherals to the appropriate mode using configurePin before using
readVoltage in the MATLAB Function block.
Version History
Introduced in R2014b
See Also
arduino | configurePin
2-28
readPosition
readPosition
Read position from servo motor connected to Adafruit Motor Shield
Syntax
position = readPosition(s)
Description
position = readPosition(s) reads the position of the motor shaft and returns the value of the
position in ratio to the maximum angle of the specified servo motor.
Examples
Connect to Arduino hardware, and create an add-on connection to an Adafruit Motor Shield.
a = arduino('COM4','Uno','Libraries','Adafruit/MotorShieldV2');
shield = addon(a,'Adafruit/MotorShieldV2');
position = 0.5200
Input Arguments
s — Servo motor
servo motor object
Output Arguments
position — Position of servo motor
numeric
Position of the servo motor, specified as a number representing the angle from 0 to 1.
Version History
Introduced in R2014b
2-29
2 Functions
See Also
servo | writePosition | arduino
Topics
“Control Motors Using Adafruit Motor Shield V2”
2-30
readPosition
readPosition
Read servo motor position
Syntax
position = readPosition(s)
Description
position = readPosition(s) reads the position of the motor shaft and returns the value of the
position in ratio to the maximum angle of the specified servomotor.
Examples
a = arduino('COM4','Uno','Libraries','Servo');
s = servo(a,'D4');
position = readPosition(s)
position = 0.5200
Input Arguments
s — Servo object
object
Output Arguments
position — Position of servo motor
numeric
Position of the servo motor specified as a number representing the angle from 0 to 1 .
Version History
Introduced in R2014b
2-31
2 Functions
See Also
servo | writePosition | arduino
2-32
readRegister
readRegister
Read data from I2C device register
Syntax
out = readRegister(dev,register)
out = readRegister(dev,register,precision)
Description
out = readRegister(dev,register) returns data read from the I2C device register.
Examples
a = arduino('COM9','Uno','Libraries','I2C');
dev = device(a,'I2CAddress','0x55')
dev =
device with properties:
Interface: 'I2C'
I2CAddress: 85 ('0x55')
Bus: 0
SCLPin: 'A5'
SDAPin: 'A4'
BitRate: 100000 (bits/s)
Show functions
writeRegister(dev,20,10);
value = readRegister(dev,20)
value = 10
2-33
2 Functions
a = arduino('COM9','Uno','Libraries','I2C');
dev = device(a,'I2CAddress','0x54');
Write value 224 to the I2C device register at address 20 with the precision of uint16
Read from the I2C device register at address 20 with the precision of uint16.
value = readRegister(dev,20,'uint16')
value = 224
Input Arguments
dev — I2C device connection
device object
Address of the I2C device register, specified as a scalar integer, hexadecimal, or binary from 0
through 255.
• 'uint8'
• 'int8'
• 'uint16'
• 'int16'
• 'uint32'
• 'int32'
• 'uint64'
• 'int64'
Output Arguments
out — Value of data
scalar | vector
2-34
readRegister
Value of data stored at the I2C device register, returned as a scalar or vector based on the
precision.
More About
Code Generation Using MATLAB Function Block
• Use readRegister in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
Version History
Introduced in R2014b
See Also
writeRegister | arduino | write | read
Topics
“Communicate with an I2C EEPROM Device”
“Arduino I2C Interface”
2-35
2 Functions
readSpeed
Read current rotational speed
Syntax
rpm = readSpeed(encoder)
rpm = readSpeed([encoder1,encoder2])
Description
rpm = readSpeed(encoder) returns the current rotational speed measured by the single
quadrature encoder in revolutions per minute.
Examples
a = arduino('COM4','Uno','Libraries','rotaryEncoder');
encoder = rotaryEncoder(a,'D2','D3',180);
rpm = readSpeed(encoder)
rpm = 0
a = arduino('COM8','Mega2560','Libraries','rotaryEncoder');
encoder1 = rotaryEncoder(a,'D2','D3',180);
encoder2 = rotaryEncoder(a,'D18','D19',180);
rpm = readSpeed([encoder1,encoder2])
2-36
readSpeed
rpm = 1×2
0 0
Input Arguments
encoder — Quadrature encoder connection
single rotaryEncoder object | vector of rotaryEncoder objects
Note Specify pulse per revolution while creating the rotaryEncoder object to use this function.
Output Arguments
rpm — Current rotational speed
double | vector of doubles
Current rotational speed measured by the quadrature encoder in revolutions per minute, returned as
a double or vector of doubles.
Note The speed measurement interval of 20 ms is used to calculate the rotational speed.
Version History
Introduced in R2017a
See Also
rotaryEncoder | resetCount | readCount
2-37
2 Functions
release
Release stepper motor connected to Adafruit Motor Shield
Syntax
release(sm)
Description
release(sm) releases the stepper motor, allowing it to rotate freely.
Examples
Connect to Arduino® hardware, and create an add-on connection to an Adafruit® Motor Shield.
a = arduino('COM4','Uno','Libraries','Adafruit/MotorShieldV2');
shield = addon(a,'Adafruit/MotorShieldV2');
Create a stepper motor connection to motor number 1 on the shield, with steps per revolution of 200
and an RPM of 10.
sm = stepper(shield,1,200,'RPM',10);
move(sm,10);
release(sm);
Input Arguments
sm — Stepper motor connection
stepper motor object
Stepper motor connection, specified as a stepper motor object, created using the stepper function.
Version History
Introduced in R2014b
See Also
arduino | addon | stepper | move
Topics
“Control Motors Using Adafruit Motor Shield V2”
2-38
reset
reset
Clear all outputs of shift register
Syntax
reset(register)
Description
reset(register) clears all the outputs of a serial-in/parallel-out (SIPO) shift register.
Examples
Connect to a 74HC164 shift register connected to your Arduino board, and specify resetPin.
register = shiftRegister(a,'74HC164','D2','D3','D4')
register =
shiftRegister with properties:
Model: '74HC164'
DataPin: 'D2'
ClockPin: 'D3'
ResetPin: 'D4'
Input Arguments
register — Shift register connection
shiftRegister object
Note Specify the resetPin while creating the shift register object to use the reset function.
Version History
Introduced in R2016b
2-39
2 Functions
See Also
arduino | shiftRegister | read | write
2-40
scanI2CBus
scanI2CBus
Scan I2C bus on Arduino hardware for device address
Syntax
addr = scanI2CBus(a,bus)
Description
addr = scanI2CBus(a,bus) scans the specified bus on the Arduino hardware in object a and
stores it in the variable addr.
Examples
Create a connection to an Arduino Due and scan the specified bus number. You can specify bus 1 only
if you are using Arduino Due boards.
a = arduino('COM5','Due','Libraries','I2C');
scanI2CBus(a,1)
Input Arguments
a — Arduino hardware connection
object
Output Arguments
addr — I2C bus address
character vector
I2C bus address returned as a character vector or a cell array of character vectors.
2-41
2 Functions
Note For more details on creating the I2C device object using address returned by the
scanI2CBus function on Bus 1 on the Arduino Due board, ArduinoBLE, and, ArduinoBLE Sense, see
“Board Specific Issues”, .
Version History
Introduced in R2014b
2-42
start
start
Start DC motor connected to Adafruit Motor Shield
Syntax
start(dcm)
Description
start(dcm) starts the DC motor. If the motor speed is set 0, the DC motor will not rotate.
Examples
Start a DC Motor
Create a DC motor connection to an Adafruit Motor Shield connected to Arduino hardware, and start
the motor.
a = arduino('COM4','Uno','Libraries','Adafruit/MotorShieldV2');
shield = addon(a,'Adafruit/MotorShieldV2');
dcm = dcmotor(shield,1)
dcm =
dcmotorv2 with properties:
MotorNumber: 1 (M1)
Speed: 0.00
IsRunning: 0
Change the speed to 0.2, start the DC motor, and display the motor object.
dcm.Speed = 0.2;
start(dcm);
dcm
dcm =
dcmotorv2 with properties:
MotorNumber: 1 (M1)
Speed: 0.20
IsRunning: 1
2-43
2 Functions
Input Arguments
dcm — DC motor connection
dcmotor object
Version History
Introduced in R2014b
See Also
stop | dcmotor
Topics
“Control Motors Using Adafruit Motor Shield V2”
2-44
stop
stop
Stop DC motor connected to Adafruit Motor Shield
Syntax
stop(dcm)
Description
stop(dcm) stops the DC motor.
Examples
Stop a DC Motor
Create a DC motor connection to an Adafruit Motor Shield attached to Arduino hardware. Start and
stop the motor.
a = arduino('COM4','Uno','Libraries','Adafruit/MotorShieldV2');
shield = addon(a,'Adafruit/MotorShieldV2');
dcm = dcmotor(shield,1);
Change the speed to 0.2, start the DC motor, and display the motor object.
dcm.Speed = 0.2;
start(dcm);
dcm
dcm =
dcmotorv2 with properties:
MotorNumber: 1 (M1)
Speed: 0.20
IsRunning: 1
stop(dcm);
dcm
dcm =
dcmotorv2 with properties:
MotorNumber: 1 (M1)
Speed: 0.20
IsRunning: 0
2-45
2 Functions
Input Arguments
dcm — DC motor connection
dcmotor object
Version History
Introduced in R2014b
See Also
start | dcmotor | arduino
Topics
“Control Motors Using Adafruit Motor Shield V2”
2-46
write
write
Package: arduinoio
Syntax
write(dev,dataIn)
write(dev,dataIn,precision)
Description
write(dev,dataIn) writes data to the I2C bus.
Examples
a = arduino('COM9','Uno','Libraries','I2C');
Updating server code on board Uno (COM9). This may take a few minutes.
dev = device(a,'I2CAddress','0x55');
dataIn = [0 1 2 3 4 5];
write(dev,dataIn);
a = arduino('COM9','Uno','Libraries','I2C');
dev = device(a,'I2CAddress','0x55');
dataIn = [0 500];
write(dev,dataIn,'uint16');
2-47
2 Functions
Input Arguments
dev — I2C device connection
device object
Data to write to the I2C device, specified as a scalar, vector, hexadecimal or binary. The range of the
values in the array is based on the precision.
• 'uint8'
• 'int8'
• 'uint16'
• 'int16'
• 'uint32'
• 'int32'
• 'uint64'
• 'int64'
• hexadecimal
• binary
• char
• string
More About
Code Generation Using MATLAB Function Block
• Use write in a MATLAB Function block with the Simulink Support Package for Arduino Hardware
to generate code that can be deployed on Arduino Hardware.
• Values of dataIn is not validated against the precision. The dataIn values will be saturated
when it goes beyond the range of the specified precision.
Version History
Introduced in R2014b
2-48
write
See Also
read | readRegister | writeRegister | arduino
Topics
“Communicate with an I2C EEPROM Device”
“Arduino I2C Interface”
2-49
2 Functions
write
Package: arduinoio
Syntax
write(register,value)
write(register,value,precision)
Description
write(register,value) writes data to the data pin of a serial-in/parallel-out (SIPO) shift register.
Examples
a = arduino('COM4','Uno','Libraries','ShiftRegister');
register = shiftRegister(a,'74HC595','D3','D6','D7');
write(register,23);
a = arduino('COM4','Uno','Libraries','ShiftRegister');
register = shiftRegister(a,'74HC595','D3','D6','D7');
Write data to the data pin of the register with a specified precision.
write(register,300,'uint16');
2-50
write
Input Arguments
register — Shift register connection
shiftRegister object
Data to write to the data pin of a SIPO shift register. Specify the data either as a number or as a
character vector of '1' or '0' or as a vector of 1 or 0, or as a hexadecimal or binary.
Note
• If you specify the data as a number, the value must be within the range of precision.
• If you specify the data as a character vector of '1' or '0', the length of the vector must match
with precision and the vector must start with the most significant bit or the highest bit for the
shift register. For example, if you write a character vector of '00001010' with length 8, specify
the precision as 'uint8'.
• If you specify the data as a vector of 1 or 0, the vector must start with the least significant bit or
the lowest bit for the shift register and the length of the vector must match with precision. For
example, if you write a vector of [0 0 0 0 1 0 1 0] of length 8, specify precision as 'uint8'.
• 'uint8'
• 'uint16'
• 'uint32'
• 'uint64'
• hexadecimal
• binary
• char
• string
Version History
Introduced in R2016b
See Also
arduino | shiftRegister | read | reset
2-51
2 Functions
resetCount
Set count value to zero or user-specified value
Syntax
resetCount(encoder)
resetCount(encoder,count)
Description
resetCount(encoder) resets the count value of the quadrature encoder to zero.
Tip First rotate the motor to a specified starting location, then use resetCount function to set the
count value to a fixed number to start from a known location.
Examples
a = arduino('COM4','Uno','Libraries','rotaryEncoder');
encoder = rotaryEncoder(a,'D2','D3');
resetCount(encoder);
a = arduino('COM4','Uno','Libraries','rotaryEncoder');
encoder = rotaryEncoder(a,'D2','D3');
resetCount(encoder,10);
2-52
resetCount
Input Arguments
encoder — Quadrature encoder connection
rotaryEncoder object
Version History
Introduced in R2017a
See Also
rotaryEncoder | readCount | readSpeed
2-53
2 Functions
writeDigitalPin
Write data to digital pin on Arduino hardware
Syntax
writeDigitalPin(a,pin,value)
Description
writeDigitalPin(a,pin,value) writes the specified value to the specified pin on the Arduino
hardware in the connection a.
Examples
a = arduino();
writeDigitalPin(a,'D5',1);
Input Arguments
a — Arduino hardware connection
object
Value of digital data to write to the specified pin on hardware, specified as a logical value of 0 and 1
or true and false.
More About
Code Generation Using MATLAB Function Block
• Use writeDigitalPin in a MATLAB Function block with the Simulink Support Package for
Arduino Hardware to generate code that can be deployed on Arduino Hardware.
• Configure the Arduino peripherals to the appropriate mode using configurePin before using
writeDigitalPin in the MATLAB Function block.
2-54
writeDigitalPin
Version History
Introduced in R2014b
See Also
configurePin | readDigitalPin | arduino
2-55
2 Functions
writePosition
Write position to servo motor connected to Adafruit Motor Shield
Syntax
writePosition(s,position)
Description
writePosition(s,position) sets servo position to the specified value.
Examples
Connect to Arduino hardware, and create an add-on connection to an Adafruit Motor Shield.
a = arduino('COM4','Uno','Libraries','Adafruit/MotorShieldV2');
shield = addon(a,'Adafruit/MotorShieldV2');
s = servo(shield,1);
writePosition(s,0.5)
Input Arguments
s — Servo object
servo motor object
Position of servo motor shaft, specified as a number representing the angle from 0 to 1.
Version History
Introduced in R2014b
See Also
servo | readPosition | arduino
2-56
writePosition
Topics
“Control Motors Using Adafruit Motor Shield V2”
2-57
2 Functions
writePosition
Write position of servo motor
Syntax
writePosition(s,position)
Description
writePosition(s,position) writes the specified value to the specified servo on the Arduino
hardware.
Examples
a = arduino('COM4','Uno','Libraries','Servo');
s = servo(a,'D4');
writePosition(s,1)
Input Arguments
s — Servo object
object
Position of servo motor shaft specified as a number representing the angle from 0 to 1.
Version History
Introduced in R2014b
See Also
servo | readPosition | arduino
2-58
writePWMDutyCycle
writePWMDutyCycle
Generate PWM signal with specified duty cycle on digital pin
Syntax
writePWMDutyCycle(a, pin, dutyCycle)
Description
writePWMDutyCycle(a, pin, dutyCycle) sets the PWM duty cycle on a digital pin specified for
the Arduino hardware a.
Examples
Specify a 0.33 duty cycle for an LED attached to digital pin 5 on Arduino hardware.
a = arduino();
writePWMDutyCycle(a,'D5',0.33);
Input Arguments
a — Arduino hardware connection
object
Value of digital pin’s PWM duty cycle specified as number between 0 and 1.
More About
Code Generation Using MATLAB Function Block
• Use writePWMDutyCycle in a MATLAB Function block with the Simulink Support Package for
Arduino Hardware to generate code that can be deployed on Arduino Hardware.
• Configure the Arduino peripherals to the appropriate mode using configurePin before using
writePWMDutyCycle in the MATLAB Function block.
2-59
2 Functions
Version History
Introduced in R2014b
See Also
arduino | writePWMVoltage
2-60
writePWMVoltage
writePWMVoltage
Generate PWM signal with specified voltage on digital pin
Syntax
writePWMVoltage(a, pin, voltage)
Description
writePWMVoltage(a, pin, voltage) writes the specified voltage value to the PWM pin on the
Arduino hardware.
Examples
a = arduino();
writePWMVoltage(a,'D5',3);
Input Arguments
a — Arduino hardware connection
object
Voltage of digital pin’s PWM specified as number between 0 and 5 volts. Check your hardware data
sheet for accepted voltage ranges. For example, Arduino Uno accepts 0 – 5 V and Arduino Due
accepts 0 – 3.3 V.
More About
Code Generation Using MATLAB Function Block
• Use writePWMVoltage in a MATLAB Function block with the Simulink Support Package for
Arduino Hardware to generate code that can be deployed on Arduino Hardware.
2-61
2 Functions
• Configure the Arduino peripherals to the appropriate mode using configurePin before using
writePWMVoltage in the MATLAB Function block.
Version History
Introduced in R2014b
See Also
arduino | writePWMDutyCycle
2-62
writeRead
writeRead
Write and read data from SPI device
Syntax
out = writeRead(dev,dataIn)
out = writeRead(dev,dataIn,precision)
Description
out = writeRead(dev,dataIn) writes the data to the SPI device and returns the data from the
SPI device as result of the write operation.
Examples
a = arduino('COM6','Mega2560','Libraries','SPI');
Updating server code on board Mega2560 (COM6). This may take a few minutes.
dev = device(a,'SPIChipSelectPin','D46');
writeEnable = bin2dec('0000 0110');
writeRead(dev,writeEnable);
out = 1×5
0 0 0 0 0
out = 1×5
0 0 0 250 155
2-63
2 Functions
Specify Precision to Write and Read Data from a SPI Device on an Arduino Board
a = arduino('COM6','Mega2560','Libraries','SPI');
dev = device(a,'SPIChipSelectPin','D46');
writeEnable = 6;
writeRead(dev,writeEnable);
writeCmd = 2;
address = [0 0];
data = [51200 51201];
dataIn = [writeCmd address data];
out = writeRead(dev,dataIn,'uint16')
0 0 0 0 0
Read data from the SPI EEPROM with the precision of uint16.
readCmd = 3
readCmd = 3
0 0 0 51200 51201
Input Arguments
dev — SPI device connection
device object
Data to write, specified as a scalar, vector, hexadecimal, or binary. The range of the values in the
array is based on the precision.
2-64
writeRead
• 'uint8'
• 'uint16'
• 'uint32'
• 'uint64'
The precision must match the size of the SPI device register.
• hexadecimal
• binary
• char
• string
Output Arguments
out — Data read or returned from SPI device
scalar | vector
Data read or returned from the SPI device, returned as a scalar or vector.
More About
Code Generation Using MATLAB Function Block
• Use writeRead in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• Values of dataIn is not validated against the precision. The dataIn values will be saturated
when it goes beyond the range of the specified precision.
Version History
Introduced in R2014b
See Also
arduino | device
Topics
“Communicate with a SPI EEPROM Device”
“Arduino and SPI Interface”
2-65
2 Functions
writeRegister
Write data to I2C device register
Syntax
writeRegister(dev,register,dataIn)
writeRegister(dev,register,dataIn,precision)
Description
writeRegister(dev,register,dataIn) writes data to the I2C device register.
Examples
Write value 10 to the I2C device register at address 20 with the precision of uint16.
writeRegister(dev,20,10,'uint16');
Input Arguments
dev — I2C device connection
device object
2-66
writeRegister
Address of the I2C device register, specified as a scalar integer from 0 through 255, hexadecimal, or
binary.
Data to write, specified as a scalar, vector, hexadecimal, or binary. The range of the values in the
array is based on the precision.
• 'uint8'
• 'int8'
• 'uint16'
• 'int16'
• 'uint32'
• 'int32'
• 'uint64'
• 'int64'
• hexadecimal
• binary
• char
• string
More About
Code Generation Using MATLAB Function Block
• Use writeRegister in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• Values of dataIn is not validated against the precision. The dataIn values will be saturated
when it goes beyond the range of the specified precision.
Version History
Introduced in R2014b
2-67
2 Functions
See Also
readRegister | arduino | write | read
Topics
“Communicate with an I2C EEPROM Device”
“Arduino I2C Interface”
2-68
sendCommand
sendCommand
Send message to Arduino device from MATLAB
Syntax
[dataOut,payloadSize] = sendCommand(arduinoObj,libName,commandID,dataIn)
[dataOut,payloadSize] = sendCommand(arduinoObj,libName,commandID,dataIn,
timeout)
Description
[dataOut,payloadSize] = sendCommand(arduinoObj,libName,commandID,dataIn) sends
a command to the Command Handler implemented by your add-on library.
[dataOut,payloadSize] = sendCommand(arduinoObj,libName,commandID,dataIn,
timeout) sends a command to the Command Handler implemented by your add-on library with a
user-specified acknowledgement timeout.
Examples
Hello World!
Input Arguments
arduinoObj — Arduino object
object
2-69
2 Functions
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Unique command identifier, specified as a number. This number must match the ID in the command
handler defined in your custom library header file.
An array of integers, specified as a vector. The size of dataIn is different for different boards. The
below table specifies the size of dataIn for different boards :
Each byte is limited to an unsigned integer between 0 and 255. Any values greater than 255 must be
converted into two unsigned integers between 0 and 255, and will be sent as two separate bytes.
Timeout duration, specified as a numeric value that is the number of seconds to wait for an
acknowledgement from the server code. Specifying a timeout duration blocks the MATLAB command
line until the timeout duration is met. The default is 5 seconds if timeout is not specified.
Output Arguments
dataOut — Data returned
vector
2-70
sendCommand
Version History
Introduced in R2015b
See Also
Topics
“Create Custom Arduino Add-On Library”
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
2-71
2 Functions
getPinAlias
Get alias pin number
Syntax
out = getPinAlias(arduinoObj, pin)
Description
out = getPinAlias(arduinoObj, pin) returns an alias for the specified pin on your Arduino
hardware when there are two labels for the same pin. If your pin does not have two labels, it returns
the same number back.
Examples
Get the alternate pin name for the analog pin 'A6' on your Arduino Leonardo. On Arduino Leonardo,
'D4' is also labeled as 'A6'.
arduinoObj = obj.Parent;
out = getPinAlias(arduinoObj, 'A6')
out =
'D4'
Arduino Uno does not have aliased pins. When asked for an alias, the command returns the same pin
number.
arduinoObj = obj.Parent;
out = getPinAlias(arduinoObj, 'A5')
out =
'A5'
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
2-72
getPinAlias
Output Arguments
out — Alternate name of the specified pin
character vector
Alternate name of the pin on the Arduino device, specified as a character vector. If no alternate pins
names exist, getPinAlias returns the input pin number.
Version History
Introduced in R2015b
See Also
validatePin
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
2-73
2 Functions
getMCU
Get microcontroller of Arduino board
Syntax
result = getMCU(arduinoObj)
Description
result = getMCU(arduinoObj) gets the microcontroller name on the connected Arduino
hardware.
Examples
arduinoObj = obj.Parent;
result = getMCU(arduinoObj)
result
'atmega328p'
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Output Arguments
result — Name of microcontroller
character vector
Version History
Introduced in R2015b
See Also
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
2-74
getMCU
2-75
2 Functions
getPinsFromTerminals
Get pin numbers from terminal
Syntax
pins = getPinsFromTerminals(arduinoObj, terminals)
Description
pins = getPinsFromTerminals(arduinoObj, terminals) retrieves pin numbers for the
specified terminal.
Examples
arduinoObj = obj.Parent;
pins = getPinsFromTerminals(obj, [2 3 4])
pins =
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Output Arguments
pins — Pins from specified terminals
character vector
Pins from specified terminals, returned as a character vector or cell array of character vectors. For
more information on terminal and pin numbers, see “Physical Terminals and Pin Numbers”.
2-76
getPinsFromTerminals
Version History
Introduced in R2015b
See Also
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
“Physical Terminals and Pin Numbers”
2-77
2 Functions
isTerminalAnalog
Check if terminal can be used as an analog pin
Syntax
result = isTerminalAnalog(arduinoObj, terminal)
Description
result = isTerminalAnalog(arduinoObj, terminal) checks to see if the specified
terminal on the Arduino board can be used as an analog pin.
Examples
Check if terminal 14, pin 'A0', on your Arduino Uno device can be used as an analog pin.
arduinoObj = obj.Parent
result = isTerminalAnalog(obj, 14)
result =
1
Note Pin 14 on an Arduino Uno device is an analog output pin and returns 1.
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Terminal number on Arduino hardware, specified as a double. For more information on terminal and
pin numbers, see “Physical Terminals and Pin Numbers”.
Output Arguments
result — Arduino hardware terminal type
boolean
Arduino hardware terminal type, returned as a boolean. Returns true if terminal is analog
2-78
isTerminalAnalog
Version History
Introduced in R2015b
See Also
isTerminalDigital
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
“Physical Terminals and Pin Numbers”
2-79
2 Functions
isTerminalDigital
Check if terminal can be used as a digital pin
Syntax
result = isTerminalDigital(arduinoObj, terminal)
Description
result = isTerminalDigital(arduinoObj, terminal) checks if the specified terminal on the
Arduino board can be used a digital pin.
Examples
Check if terminal 2 on your Arduino Uno hardware can be used as a digital pin.
arduinoObj = obj.Parent
result = isTerminalDigital(arduinoObj, 2)
result =
1
Check if analog pin on your Arduino Leonardo can be used as digital pin. It is useful if you have
multipurpose pins.
Create an arduino object, and get terminal number from analog pin A6.
arduinoObj = obj.Parent
getTerminalsFromPins(obj, 'A6')
ans =
result =
1
Input Arguments
arduinoObj — Arduino object
object
2-80
isTerminalDigital
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Terminal number on Arduino hardware, specified as a double. For more information on terminal and
pin numbers, see “Physical Terminals and Pin Numbers”.
Output Arguments
result — Terminal type
boolean
Version History
Introduced in R2015b
See Also
isTerminalAnalog | getTerminalsFromPins | getPinAlias
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
“Physical Terminals and Pin Numbers”
2-81
2 Functions
getTerminalMode
Get current terminal mode
Syntax
value = getTerminalMode(arduinoObj, terminal)
Description
value = getTerminalMode(arduinoObj, terminal) returns the current mode of the terminal.
Examples
arduinoObj = obj.Parent;
value = getTerminalMode(arduinoObj, 14)
value =
'AnalogInput'
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Output Arguments
value — Mode of specified terminal
character vector
Mode of specified terminal, returned as a character vector. Valid mode values are:
include:
• 'DigitalInput'
• 'DigitalOutput'
2-82
getTerminalMode
• 'AnalogInput'
• 'PWM'
• 'I2C'
• 'Servo'
• 'Unset'
• 'SPI'
• 'Reserved'
• 'Pullup'
Version History
Introduced in R2015b
See Also
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
“Physical Terminals and Pin Numbers”
2-83
2 Functions
getTerminalsFromPins
Get terminal numbers from pins
Syntax
terminals = getTerminalsFromPins(arduinoObj, pins)
Description
terminals = getTerminalsFromPins(arduinoObj, pins) returns terminal numbers for the
specified pins.
Examples
Get terminal numbers from pins 'D2', 'A0' on your Arduino Uno board.
arduinoObj = obj.Parent
terminals = getTerminalsFromPins(arduinoObj, {'D2', 'A0'})
terminals =
2 14
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Pins on Arduino hardware, specified as a character vector or a cell array of character vectors.
Output Arguments
terminals — Terminal numbers for Arduino hardware
double
Terminal number for specified pins on Arduino hardware, returned as a double or an array of doubles.
For more information on terminal and pin numbers, see “Physical Terminals and Pin Numbers”.
2-84
getTerminalsFromPins
Version History
Introduced in R2015b
See Also
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
“Physical Terminals and Pin Numbers”
2-85
2 Functions
getServoTerminals
Get terminals that have servo functionality
Syntax
terminals = getServoTerminals(arduinoObj)
Description
terminals = getServoTerminals(arduinoObj) returns terminals that have servo functionality
on the Arduino board.
Examples
Get terminals on an Arduino Uno device that have specific servo functionality.
arduinoObj = obj.Parent;
terminals = getServoTerminals(arduinoObj)
terminals =
2 3 4 5 6 7 8 9 10 11 12 13
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Output Arguments
terminals — Servo terminals
double
Servo terminals, returned as an array of doubles. For more information on terminal and pin numbers,
see “Physical Terminals and Pin Numbers”.
Version History
Introduced in R2015b
See Also
getI2CTerminals | getSPITerminals | getPWMTerminals | getInterruptTerminals
2-86
getServoTerminals
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
“Physical Terminals and Pin Numbers”
2-87
2 Functions
getPWMTerminals
Get terminals with PWM functionality
Syntax
terminals = getPWMTerminals(arduinoObj)
Description
terminals = getPWMTerminals(arduinoObj) returns terminals that have PWM functionality on
the Arduino board.
Examples
arduinoObj = obj.Parent;
terminals = getPWMTerminals(arduinoObj)
terminals =
3 5 6 9 10 11
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Output Arguments
terminals — PWM terminals
double
PWM terminals, returned as an array of doubles. For more information on terminal and pin numbers,
see “Physical Terminals and Pin Numbers”.
Version History
Introduced in R2015b
See Also
getI2CTerminals | getSPITerminals | getServoTerminals | getInterruptTerminals
Topics
“Create HelloWorld Add-On”
2-88
getPWMTerminals
2-89
2 Functions
getSPITerminals
Get terminals that have SPI functionality
Syntax
terminals = getSPITerminals(arduinoObj)
Description
terminals = getSPITerminals(arduinoObj) returns terminals that have SPI functionality on
the Arduino board
Examples
arduinoObj = obj.Parent;
terminals = getSPITerminals(arduinoObj)
terminals =
10 11 12 13
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Output Arguments
terminals — SPI terminals
double
SPI terminals, returned as an array of doubles. For more information on terminal and pin numbers,
see “Physical Terminals and Pin Numbers”.
Version History
Introduced in R2015b
See Also
getI2CTerminals | getServoTerminals | getPWMTerminals | getInterruptTerminals
2-90
getSPITerminals
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
“Physical Terminals and Pin Numbers”
2-91
2 Functions
getI2CTerminals
Get terminals with I2C functionality
Syntax
terminals = getI2CTerminals(arduinoObj)
terminals = getI2CTerminals(arduinoObj, bus)
Description
terminals = getI2CTerminals(arduinoObj) returns terminals with I2C functionality on your
Arduino board.
terminals = getI2CTerminals(arduinoObj, bus) returns terminals for the specified I2C bus
on your Arduino board.
Examples
Get I2C terminals on an Arduino Uno device that can have I2C functionality.
arduinoObj = obj.Parent;
terminals = getI2CTerminals(arduinoObj)
terminals =
18 19
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
If you are using an Arduino Due device, use bus 0 for SDA and SCL and bus 1 for SDA1 and SCL1.
Output Arguments
terminals — I2C terminals
double
2-92
getI2CTerminals
I2C terminals, returned as a double or an array of doubles. For more information on terminal and pin
numbers, see “Physical Terminals and Pin Numbers”.
Version History
Introduced in R2015b
See Also
getServoTerminals | getSPITerminals | getPWMTerminals | getInterruptTerminals
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
“Physical Terminals and Pin Numbers”
2-93
2 Functions
getInterruptTerminals
Get terminals with interrupt functionality
Syntax
terminals = getInterruptTerminals(arduinoObj)
Description
terminals = getInterruptTerminals(arduinoObj) returns terminals with interrupt
functionality on your Arduino board.
Examples
Get terminals on an Arduino Uno device that can have interrupt functionality.
arduinoObj = obj.Parent;
terminals = getInterruptTerminals(arduinoObj)
terminals =
2,3
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Output Arguments
terminals — Interrupt terminals
double
Interrupt terminals, returned as a double or an array of doubles. For more information on terminal
and pin numbers, see “Physical Terminals and Pin Numbers”.
Version History
Introduced in R2019a
See Also
getServoTerminals | getSPITerminals | getPWMTerminals | getI2CTerminals
2-94
getInterruptTerminals
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
“Physical Terminals and Pin Numbers”
2-95
2 Functions
validatePin
Validate that pin supports specific functionality
Syntax
validatePin(arduinoObj, pin, type)
Description
validatePin(arduinoObj, pin, type) validates specific functionality on the pin and throws an
error if not supported.
Examples
Check if pin D12 supports SPI functionality on the Arduino Uno hardware.
arduinoObj = obj.Parent;
validatePin(arduinoObj,'D12','SPI')
Only pins A4 and A5 support I2C type, the function returns an error for unsupported pins
arduinoObj = obj.Parent;
validatePin(arduinoObj,'A4,'I2C')
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Pin type on Arduino hardware, specified as a character vector. Valid type values are:
• 'I2C'
2-96
validatePin
• 'SPI'
• 'PWM'
• 'Servo'
• 'analog'
• 'digital'
Version History
Introduced in R2014b
See Also
getPinAlias
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
2-97
2 Functions
configurePinResource
Set resource owner and mode of pin
Syntax
mode = configurePinResource(arduinoObj, pin)
configurePinResource(arduinoObj, pin, resourceOwner, mode, forceConfig)
Description
mode = configurePinResource(arduinoObj, pin) returns the specified mode of pin.
Examples
Change the resource owner and mode of the digital pin 'D11' on an Arduino Uno to I2C.
arduinoObj = obj.Parent;
mode = configurePinResource(arduinoObj, 'D11')
mode =
'SPI'
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
2-98
configurePinResource
• 'DigitalInput'
• 'DigitalOutput'
• 'AnalogInput'
• 'PWM'
• 'I2C'
• Interrupt: specify pin in interrupt mode to be used in rotaryEncoder
• 'Servo'
• 'Unset'
• 'SPI'
• Tone: specify pin to use for playTone
• Ultrasonic: specify pin to used with ultrasonic sensor
• 'Reserved'
• 'Pullup'
Specify if mode change on the pin is forced. Specify 'true' to force the change and 'false' to not
force the change. Use this when the current pin mode is not compatible with the new pin mode.
Compatible modes you can change without forcing the configuration include:
Output Arguments
mode — Mode of specified terminal
character vector
Mode of specified terminal, returned as a character vector. Possible output mode values are:
• 'DigitalInput'
• 'DigitalOutput'
• 'AnalogInput'
• 'PWM'
2-99
2 Functions
• 'I2C'
• 'Servo'
• 'Unset'
• 'SPI'
• 'Reserved'
• 'Pullup'
Version History
Introduced in R2015b
See Also
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
2-100
decrementResourceCount
decrementResourceCount
Decrement count of number of instances of resource
Syntax
count = decrementResourceCount(arduinoObj, resource)
Description
count = decrementResourceCount(arduinoObj, resource) decrements current count of
instances of the specified resource by one and returns the updated count. Call this function in your
add-on “Destructor”.
Examples
Decrement the resource count of a servo created with the parent arduino object.
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Name of resource to decrement, specified as a character vector. The resource must be added to the
arduino object before using incrementResourceCount.
Version History
Introduced in R2015b
2-101
2 Functions
See Also
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
2-102
incrementResourceCount
incrementResourceCount
Increment current resource count
Syntax
incrementResourceCount(arduinoObj, resourceName)
Description
incrementResourceCount(arduinoObj, resourceName) increments count of the specified
resource instances by one and returns the updated count. Call this function after you create an
object.
Examples
Increment the resource count of servo created with the parent arduino object.
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Version History
Introduced in R2015b
See Also
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
2-103
2 Functions
getFreeResourceSlot
Get first free slot of resource
Syntax
slot = getFreeResourceSlot(arduinoObj, resourceName)
Description
slot = getFreeResourceSlot(arduinoObj, resourceName) returns the first available slot or
index in a continuous array allocated for the given resource. The slot count starts from 1.
Examples
Get the free resource slot allocated to a servo object on an Arduino Uno. This function runs only in
the “Create and Configure MATLAB Add-On Class” of a custom Arduino add-on library.
a = arduino();
s1 = servo(a,'D7');
Get free resource slot on the servo object. In this example, the add-on object of the Arduino object is
defined as obj in the “Constructor”. The resource name for a servo object is 'Servo'.
arduinoObj = obj.Parent;
slot1 = getFreeResourceSlot(arduinoObj,'Servo')
slot1 =
1
s2 = servo(a,'D5');
slot2 = getFreeResourceSlot(arduinoObj,'Servo')
slot2 =
2
Clear the first servo object and create a third servo object to see if the first slot is cleared. Make sure
to release hardware resources in your “Destructor”.
clear('s1')
s3 = servo(a,'D4');
slot3 = getFreeResourceSlot(arduinoObj,'Servo')
slot3 =
1
2-104
getFreeResourceSlot
Since the slot number is 1 instead of 3, the first slot has been cleared.
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Output Arguments
slot — Slot number of the first free resource
double
Version History
Introduced in R2015b
See Also
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
2-105
2 Functions
getResourceCount
Number of instances of a resource
Syntax
count = getResourceCount(arduinoObj, resourceName)
Description
count = getResourceCount(arduinoObj, resourceName) returns the number of resource
instances with the name resourceName. Use this function to keep track of the number of resource
objects that exist in the current workspace.
Examples
arduinoObj = arduino();
s = servo (arduinoObj, 'D2');
arduinoObj = obj.Parent;
count = getResourceCount(arduinoObj,'servo')
count =
1
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Output Arguments
count — Number of resource instances
double
2-106
getResourceCount
Version History
Introduced in R2015b
See Also
incrementResourceCount | decrementResourceCount
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
2-107
2 Functions
setSharedResourceProperty
Set shared resource property
Syntax
setSharedResourceProperty(arduinoObj, resourceName, propertyName,
propertyValue)
Description
setSharedResourceProperty(arduinoObj, resourceName, propertyName,
propertyValue) sets the specified property of all objects of the given resource to a specified value.
Examples
arduinoObj = obj.Parent;
setSharedResourceProperty(arduinoObj, 'spidev', 'Mode', 1);
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Version History
Introduced in R2015b
2-108
setSharedResourceProperty
See Also
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
2-109
2 Functions
getSharedResourceProperty
Get shared resource property
Syntax
getSharedResourceProperty(arduinoObj, resourceName, propertyName)
Description
getSharedResourceProperty(arduinoObj, resourceName, propertyName) retrieves
shared property value of all objects of the same resource.
Examples
arduinoObj = obj.Parent;
getResourceProperty(arduinoObj, 'spidev', 'Mode');
ans =
1
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Version History
Introduced in R2015b
2-110
getSharedResourceProperty
See Also
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
2-111
2 Functions
getResourceOwner
Get terminal resource owner
Syntax
getResourceOwner(arduinoObj, terminal)
Description
getResourceOwner(arduinoObj, terminal) returns the resource owner of the specified
terminal.
Examples
ans =
'servo'
Input Arguments
arduinoObj — Arduino object
object
Arduino object, specified as an object that is an internal variable called from within classes that
derive from matlabshared.addon.LibraryBase on page 1-24.
Physical terminal number on Arduino hardware, specified as a double. For more information see
“Physical Terminals and Pin Numbers”.
Version History
Introduced in R2015b
See Also
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”
“Custom Add-On Library Concepts”
2-112
getResourceOwner
2-113
2 Functions
flush
Flush the host buffer
Syntax
flush(sensorobj)
Description
flush(sensorobj) clears the buffers and resets the start time.
Input Arguments
sensorobj — sensor object
More About
Code Generation Using MATLAB Function Block
• Use flush in a MATLAB Function block with the Simulink Support Package for Arduino Hardware
to generate code that can be deployed on Arduino Hardware.
• flush does not reset the start time.
Version History
Introduced in R2019a
2-114
info
info
Read information related to sensor
Syntax
SensorInfo = info(sensorobj)
Description
SensorInfo = info(sensorobj) returns the information related to the sensor.
Input Arguments
sensorobj — sensor object
Output Arguments
SensorInfo — Sensor information
SensorInfo is a structure containing the information related to sensors. The information depends
on the specific sensor object for which the function is called. The information can be output data rate
(ODR), bandwidth, and so on.
Data Types: struct
More About
Code Generation Using MATLAB Function Block
Version History
Introduced in R2019a
2-115
2 Functions
read
Read real-time sensor data at a specified rate
Syntax
[sensorReadings,overrun] = read(sensorobj)
[accelReadings, gyroReadings, magReadings, timeStamps, overrun] = read(
sensorobj)
[accelReadings, gyroReadings, magReadings, tempReadings, timeStamps, overrun]
= read(sensorobj)
[accelReadings, gyroReadings, timeStamps, overrun] = read(sensorobj)
[accelReadings, gyroReadings, tempReadings, timeStamps, overrun] = read(
sensorobj)
[accelReadings, magReadings, tempReadings, timeStamps, overrun] = read(
sensorobj)
[accelReadings, timeStamps, overrun] = read(sensorobj)
[humidityReading, tempReadings, timeStamps, overrun] = read(sensorobj)
[pressureReading, tempReadings, timeStamps, overrun] = read(sensorobj)
[accelReadings, tempReadings, timeStamps, overrun] = read(sensorobj)
Description
[sensorReadings,overrun] = read(sensorobj) returns the sensor readings in timetable
format. The timetable contains data read from the sensor associated with time data. The number of
rows in the timetable depends on the SamplesPerRead value specified while creating the sensor
object. These output arguments are returned only when the output format is set to timetable. This
syntax is applicable for all sensors.
2-116
read
sensor object. These output arguments are returned only when the output format is set to matrix
This function signature is available only for the LSM6DS3, LSM6DS3H, LSM6DSL, LSM6DSM, LSM6DSR,
and LSM6DSO sensors.
Examples
Read Data from Sensor as a Timetable
Note The sample code and output in this example is for mpu9250 object. If you are using another
sensor that supports read function, use the corresponding sensor object.
sensorobj = mpu9250(a,'SampleRate',50,'SamplesPerRead',5,'ReadMode','Latest');
2-117
2 Functions
sensorReadings =
5×3 timetable
overrun =
Note The sample code and output in this example is for mpu9250 object. If you are using another
sensor that supports this syntax of read function, use the corresponding sensor object.
accel =
gyro =
mag =
timestamps =
2-118
read
4-Feb-2021 15:53:18.790
4-Feb-2021 15:53:18.800
overrun =
Note The sample code and output in this example is for mpu6050 object. If you are using another
sensor that supports this syntax of read function, use the corresponding sensor object.
accel =
gyro =
timestamps =
4-Feb-2021 15:53:18.790
4-Feb-2021 15:53:18.800
overrun =
Input Arguments
sensorobj — sensor object
Output Arguments
sensorReadings — Data read when output format is set to timetable
2-119
2 Functions
Data read from the sensor when the output format is set to timetable. The timetable returned
has the following fields:
Note The fields of timetable depends on the type of sensor. For example, in case of MPU6050, the
output fields returned are Acceleration and AngularVelocity.
overrun — Overrun
The discarded number of data samples between the previous read and the current read is the
overrun. The overrun is zero when ReadMode is set to oldest.
Data Types: single | double
accelReadings — Acceleration read from sensor when output format is set to matrix
N-by-3 matrix
Acceleration read from the sensor on x, y and z axis. This value is specified as a real, finite N-by-3
matrix in m/s2. N is the number of samples in the current frame, which is equal to the
SamplesPerRead value.
Data Types: double
gyroReadings — Angular velocity read from sensor when output format is set to matrix
N-by-3 matrix
Angular velocity read from the sensor on x, y and z axis. This value is specified as a real, finite N-by-3
matrix in rad/s. N is the number of samples in the current frame, which is equal to the
SamplesPerRead value.
Data Types: double
magReadings — Magnetic field read from sensor when output format is set to matrix
N-by-3 matrix
Magnetic field read from the sensor on x, y and z axis. This value is specified as a real, finite N-by-3
matrix in µT (microtesla). N is the number of samples in the current frame, which is equal to the
SamplesPerRead value.
Data Types: double
2-120
read
Temperature read by the sensor. This value is specified as a real, finite N-by-1 matrix in Celsius . N is
the number of samples in the current frame, which is equal to the SamplesPerRead value.
Data Types: double
humidityReading — Humidity read from sensor when output format is set to matrix
N-by-1 matrix
Humidity value mesaured by the sensor. This value is specified as a real, finite N-by-1 matrix in % . N
is the number of samples in the current frame, which is equal to the SamplesPerRead value.
Data Types: double
pressureReading — Pressure read from sensor when output format is set to matrix
N-by-1 matrix
Barometric pressure read from the sensor. This value is specified as a real, finite N-by-1 matrix in Pa
(Pascals). N is the number of samples in the current frame, which is equal to the SamplesPerRead
value.
Data Types: double
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the first call of the read function or the
last execution of the release function.
More About
Code Generation Using MATLAB Function Block
• Use read in a MATLAB Function block with the Simulink Support Package for Arduino Hardware
to generate code that can be deployed on Arduino Hardware.
• read does not return overrun.
• read always returns matrices.
Version History
Introduced in R2019a
2-121
2 Functions
readAcceleration
Read one sample of acceleration from sensor
Syntax
[accelReadings,timestamp] = readAcceleration(sensorobj)
Description
[accelReadings,timestamp] = readAcceleration(sensorobj) returns one sample of the
acceleration data on x, y, and z axes read from the sensor in units of m/s2 along with the timestamp.
Timestamp is optional.
Note The readAcceleration function is available for the LSM6DS3, LSM6DS3H, LSM6DSL,
LSM6DSM, LSM6DSR, LSM6DSO, MPU6050, MPU9250, LSM9DS1, LSM303C, ICM20948, ADXL345, and
LIS3DH sensors.
Examples
Read Acceleration from Sensor
a = arduino();
Or, you can explicitly specify it in the Libraries Name-Value pair while creating the Arduino object.
clear a;
a = arduino('COM4', 'Uno', 'Libraries', 'I2C');
Note The sample code and output in this example is for mpu9250 object. If you are using another
sensor that supports readAcceleration function, use the corresponding sensor object.
sensorobj = mpu9250(a);
accelReadings = readAcceleration(sensorobj)
accelReadings =
2-122
readAcceleration
Input Arguments
sensorobj — sensor object
Output Arguments
accelReadings — Value read from the sensor
timestamp — Timestamp
datetime
The time at which MATLAB receives acceleration data from the sensor, specified as a datetime.
More About
Code Generation Using MATLAB Function Block
• Use readAcceleration in a MATLAB Function block with the Simulink Support Package for
Arduino Hardware to generate code that can be deployed on Arduino Hardware.
• Timestamp returned is always in seconds.
Version History
Introduced in R2019a
2-123
2 Functions
readAngularVelocity
Read one sample of angular velocity from sensor
Syntax
[gyroReadings,timestamp] = readAngularVelocity(sensorobj)
Description
[gyroReadings,timestamp] = readAngularVelocity(sensorobj) returns one sample of the
angular velocity data on x, y, and z axes read from the sensor in units of rad/s along with the
timestamp. Timestamp is optional.
Note The readAngularVelocity function is available for the LSM6DS3, LSM6DS3H, LSM6DSL,
LSM6DSM, LSM6DSR, LSM6DSO, MPU6050, MPU9250, LSM9DS1, and ICM20948 sensors.
Examples
Read Angular Velocity
a = arduino();
Or, you can explicitly specify it in the Libraries Name-Value pair while creating the Arduino object.
clear a;
a = arduino('COM4', 'Uno', 'Libraries', 'I2C');
Note The sample code and output in this example is for mpu9250 object. If you are using another
sensor that supports readAngularVelocity function, use the corresponding sensor object.
sensorobj = mpu9250(a);
gyroReadings = readAngularVelocity(sensorobj)
gyroReadings =
2-124
readAngularVelocity
Input Arguments
sensorobj — sensor object
Output Arguments
gyroReadings — Value read from the sensor
The angular velocity value on x, y, and z axes read from the sensor.
timestamp — Timestamp
datetime
The time at which MATLAB receives angular velocity data from the sensor, specified as a datetime.
More About
Code Generation Using MATLAB Function Block
• Use readAngularVelocity in a MATLAB Function block with the Simulink Support Package for
Arduino Hardware to generate code that can be deployed on Arduino Hardware.
• Timestamp returned is always in seconds.
Version History
Introduced in R2019a
2-125
2 Functions
readMagneticField
Read one sample of magnetic field from sensor
Syntax
[magReadings,timestamp] = readMagneticField(sensorobj)
Description
[magReadings,timestamp] = readMagneticField(sensorobj) returns one sample of the
magnetic field data on x, y, and z axes read from the sensor in units of µT (microtesla) along with the
timestamp. Timestamp is optional.
Note The readMagneticField function is available for the MPU9250, LSM9DS1, LSM303C, and
ICM20948 sensors.
Examples
Read Magnetic Field
a = arduino();
Or, you can explicitly specify it in the Libraries Name-Value pair while creating the Arduino object.
clear a;
a = arduino('COM4', 'Uno', 'Libraries', 'I2C');
Note The sample code and output in this example is for mpu9250 object. If you are using another
sensor that supports readMagneticField function, use the corresponding sensor object.
sensorobj = mpu9250(a);
magReadings = readMagneticField(sensorobj)
magReadings =
2-126
readMagneticField
Input Arguments
sensorobj — Sensor object
Output Arguments
magReadings — Value read from the sensor
The magnetic field value on x, y, and z axes read from the sensor.
timestamp — Timestamp
datetime
The time at which MATLAB receives magnetic field data from the sensor, specified as a datetime.
More About
Code Generation Using MATLAB Function Block
• Use readMagneticField in a MATLAB Function block with the Simulink Support Package for
Arduino Hardware to generate code that can be deployed on Arduino Hardware.
• Timestamp returned is always in seconds.
Version History
Introduced in R2019a
2-127
2 Functions
release
Release the sensor object
Syntax
release(sensorobj)
Description
release(sensorobj) stops the data collection from the sensor, clears the buffer, and resets the
start time and sets the number of overrun samples to 0.
Input Arguments
sensorobj — Sensor object
More About
Code Generation Using MATLAB Function Block
• Use release in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• release does not reset the start time.
Version History
Introduced in R2019a
2-128
readTemperature
readTemperature
Read one sample of temperature from sensor
Syntax
[tempReadings,timestamp] = readtemperature(sensorobj)
Description
[tempReadings,timestamp] = readtemperature(sensorobj) returns one sample of the
temperature measured in degree Celsius along with the timestamp. Timestamp is optional.
Note The readTemperature function is available for the LSM6DS3, LSM6DS3H, LSM6DSL, LSM6DSM,
LSM6DSR, LSM6DSO, LPS22HB, LSM303C, HTS221, ICM20948, ADXL345, BMP280, and LIS3DH
sensors.
Examples
Read temperature Data from Sensor
a = arduino();
Or, you can explicitly specify it in the Libraries Name-Value pair while creating the Arduino object.
clear a;
a = arduino('COM4', 'Uno', 'Libraries', 'I2C');
Note The sample code and output in this example is for hts221 object. If you are using another
sensor that supports readTemperature function, use the corresponding sensor object.
sensorobj = hts221(a);
temperatureReadings = readTemperature(sensorobj)
temperatureReadings =
28.12
Input Arguments
sensorobj — sensor object
2-129
2 Functions
Output Arguments
tempReadings — Value read from the sensor
timestamp — Timestamp
datetime
The time at which MATLAB receives temperature data from the sensor, specified as a datetime.
More About
Code Generation Using MATLAB Function Block
• Use readTemperature in a MATLAB Function block with the Simulink Support Package for
Arduino Hardware to generate code that can be deployed on Arduino Hardware.
• Timestamp returned is always in seconds.
Version History
Introduced in R2021a
2-130
readHumidity
readHumidity
Read one sample of relative humidity data from the sensor
Syntax
[humidityReading,timestamp] = readHumidity(humiditySensor)
Description
[humidityReading,timestamp] = readHumidity(humiditySensor) returns one sample of
the relative humidity measured in % along with the timestamp. timestamp is optional.
Note The readHumidity function is available for only the HTS221 sensor.
Examples
Read humidity Data from Sensor
Or, you can explicitly specify it in the Libraries Name-Value pair while creating the Arduino object.
clear a;
a = arduino('COM4', 'Uno', 'Libraries', 'I2C');
humidityReading =
69.6077
Input Arguments
humiditySensor — A sensor connection
object
Output Arguments
humidityReading — Value read from the sensor
scalar
2-131
2 Functions
The relative humidity reading from the sensor, specified in percentage (%)
Data Types: double
timestamp — Timestamp
datetime
The time at which MATLAB receives humidity data from the sensor, specified as a datetime.
Data Types: datetime
More About
Code Generation Using MATLAB Function Block
• Use readHumidity in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• Timestamp returned is always in seconds.
Version History
Introduced in R2021a
See Also
hts221
2-132
readPressure
readPressure
Read one sample of barometric air pressure data from the sensor
Syntax
[pressureReading,timestamp] = readPressure(pressureSensor)
Description
[pressureReading,timestamp] = readPressure(pressureSensor) returns one sample of
the barometric air pressure measured in Pascals (Pa) along with the timestamp. timestamp is
optional.
Note The readPressure function is available for LPS22HB and BMP280 sensor.
Examples
Read Pressure Data from Sensor
a = arduino();
Or, you can explicitly specify it in the Libraries Name-Value pair while creating the Arduino object.
clear a;
a = arduino('COM4', 'Uno', 'Libraries', 'I2C');
pressureSensor = lps22hb(a);
pressureReading = readPressure(pressureSensor)
pressureReading =
9.5014e+04
Input Arguments
pressureSensor — sensor connection
object
2-133
2 Functions
Output Arguments
pressureReading — Value read from the LPS22HB sensor
scalar
The barometric air pressure reading from the LPS22HB sensor, specified in Pascals (Pa).
Data Types: double
timestamp — Timestamp
datetime
The time at which MATLAB receives pressure data from the sensor, specified as a datetime.
Data Types: datetime
More About
Code Generation Using MATLAB Function Block
• Use readPressure in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• Timestamp returned is always in seconds.
Version History
Introduced in R2021a
See Also
lps22hb
2-134
readVoltage
readVoltage
Read voltage from ADC pins on sensor
Syntax
voltage = readVoltage(sensorObj,pin)
Description
voltage = readVoltage(sensorObj,pin) reads the voltage on the specified external ADC pin
on lis3dh sensor.
Note The readVoltage function is available only for the LIS3DH sensor.
Examples
Read Voltage
a = arduino();
Or, you can explicitly specify it in the Libraries Name-Value pair while creating the Arduino object.
clear a;
a = arduino('COM8', 'Uno', 'Libraries', 'I2C');
sensorObj = lis3dh(a);
sensorObj =
I2CAddress: 24 ("0x18")
Bus: 0
SCLPin: "D21"
SDAPin: "D20"
2-135
2 Functions
Input Arguments
sensorObj — sensor object
Output Arguments
voltage — Voltage read from ADC pin
numeric
Voltage read from a ADC pin on the sensor specified as a numeric double.
timestamp — Timestamp
datetime
The time at which MATLAB receives voltage data from the sensor, specified as a datetime.
More About
Code Generation Using MATLAB Function Block
• Use readVoltage in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• Timestamp returned is always in seconds.
Version History
Introduced in R2023a
2-136
3
BNO055 Functions
4
Serial Functions
4 Serial Functions
device
Connection to serial device on Arduino or ESP32 hardware
Description
This object represents a connection to the serial device connected to Arduino or ESP32 hardware.
You can interact with the serial device using the functions listed in “Object Functions” on page 4-6.
Creation
Syntax
serialdevObj = device(arduinoObj,'SerialPort',SerialPort)
serialdevObj = device(arduinoObj,'SerialPort',SerialPort,Name,Value)
Description
Input Arguments
The ID of the serial port available on the Arduino or ESP32 hardware specified as a number.
Example: serialdevObj = device(arduinoObj,'SerialPort',1)
Note The Arduino Mega2560, Due, and MegaADK boards have three serial ports available while the
Arduino Leonardo, Micro, MKR1000, MKR1010, MKRZero, Nano33IoT, and Nano33BLE have one
serial port available.
4-2
device
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: serialdevObj = device(arduinoObj,'SerialPort',1,'BaudRate',115200);
Note If you are using more than one device, make sure the devices operate at same BaudRate for
data consistency.
4-3
4 Serial Functions
Properties
Interface — Type of interface used for communication
'Serial'
>> serialdevObj.Interface
ans =
Serial
>> serialdevObj.SerialPort
ans =
1
>> serialdevObj.TxPin
ans =
'D18'
>> serialdevObj.RxPin
ans =
'D19'
4-4
device
Example:
>> serialdevObj.BaudRate
ans =
115200
Number of bytes of data available to read from the serial device, specified as a number.
Example:
>> serialdevObj.NumBytesAvailable
ans =
0
>> serialdevObj.Parity
ans =
'even'
>> serialdevObj.StopBits
ans =
1
>> serialdevObj.DataBits
4-5
4 Serial Functions
ans =
8
>> serialdevObj.Timeout
ans =
1
Object Functions
read Read data from serial device
write Write data to serial device
Examples
arduinoObj = arduino("COM16","Leonardo","Libraries",{'SPI','Serial','I2C'})
arduinoObj =
arduino with properties:
Port: 'COM16'
Board: 'Leonardo'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11', 'D13'}
AvailableAnalogPins: {'A0-A5', 'D4', 'D6', 'D8-D10', 'D12'}
AvailableI2CBusIDs: [0]
AvailableSerialPortIDs: [1]
Libraries: {'I2C', 'SPI', 'Serial'}
serialdevObj = device(arduinoObj,'SerialPort',1)
serialdevObj =
device with properties:
Interface: 'Serial'
SerialPort: 1
TxPin: 'D1'
RxPin: 'D0'
4-6
device
arduinoObj =
arduino with properties:
Port: 'COM16'
Board: 'Leonardo'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11', 'D13'}
AvailableAnalogPins: {'A0-A5', 'D4', 'D6', 'D8-D10', 'D12'}
AvailableI2CBusIDs: [0]
AvailableSerialPortIDs: [1]
Libraries: {'I2C', 'SPI', 'Serial'}
Create a connection to the serial device with the the BaudRate set to 115200 bits/s.
serialdevObj = device(arduinoObj,'SerialPort',1,'BaudRate', 115200)
serialdevObj =
device with properties:
Interface: 'Serial'
SerialPort: 1
TxPin: 'D1'
RxPin: 'D0'
BaudRate: 115200 (bits/s)
NumBytesAvailable: 0
More About
Code Generation Using MATLAB Function Block
• Use device in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino or ESP32 Hardware.
• Specifying BaudRate as a name value pair argument is not supported the in MATLAB Function
block. You can set BaudRate from the Configuration Parameters dialog box. To set the BaudRate:
• On the Simulink Toolstrip, in the Hardware tab, click Hardware Settings to open the
Configuration Parameters dialog box.
4-7
4 Serial Functions
• In the Configuration Parameters dialog box, select Hardware Implementation. Verify that the
Hardware board parameter is set to the appropriate Arduino board.
• Go to Hardware board settings > Target hardware resources > Serial port properties.
• Enter the value to set BaudRate in the particular serial port.
• Default value of Timeout is 0.
• The property DataBits cannot be changed and always uses a default value 8.
• The property Parity cannot be changed and always uses a default valuenone.
• The property StopBit cannot be changed and always uses a default value1.
• The properties Interface, BitRate, SCLPin, and SDAPin are not accessible from the device
object.
Version History
Introduced in R2019b
See Also
arduino | read | write
4-8
read
read
Read data from serial device
Syntax
out = read(serialdevObj,numBytes)
out = read(serialdevObj,numBytes,precision)
Description
out = read(serialdevObj,numBytes) returns number of bytes of data read from serial device.
Examples
arduinoObj = arduino("COM16","Leonardo","Libraries",{'SPI','Serial','I2C'});
serialdevObj =
device with properties:
Interface: 'Serial'
SerialPort: 1
TxPin: 'D1'
RxPin: 'D0'
BaudRate: 115200 (bits/s)
NumBytesAvailable: 0
Connect the Rx and Tx pins in loopback. Write 3 bytes of data to the serial device.
write(serialdevObj,[88 99 65]);
numBytes = serialdevObj.NumBytesAvailable
numBytes = 3
read(serialdevObj,3)
4-9
4 Serial Functions
ans = 1×3
88 99 65
serialdevObj =
device with properties:
Interface: 'Serial'
SerialPort: 1
TxPin: 'D1'
RxPin: 'D0'
BaudRate: 115200 (bits/s)
NumBytesAvailable: 0
Connect the Rx and Tx pins in loopback. Write data to the serial device.
write(serialdevObj,256,'uint16');
numBytes = 2
ans = 256
Input Arguments
serialdevObj — Serial device connection
device object
Number of bytes of data to read from the serial device, specified as a scalar.
4-10
read
Note For the Arduino Mega2560, Mega ADK, Leonardo, and Micro boards read works only for up to
63 bytes of data as the Arduino libraries do not read data into last byte of serial receive buffer. See
this link for more details.
• 'uint8'
• 'int8'
• 'uint16'
• 'int16'
• 'uint32'
• 'int32'
• 'uint64'
• 'int64'
Output Arguments
out — Data read from serial device
scalar | vector
Data read from serial device, returned as a scalar or vector based on the precision.
More About
Code Generation Using MATLAB Function Block
• Use read in a MATLAB Function block with the Simulink Support Package for Arduino Hardware
to generate code that can be deployed on Arduino Hardware.
Version History
Introduced in R2019b
See Also
arduino | write | device
4-11
4 Serial Functions
write
Write data to serial device
Syntax
write(serialdevObj,dataIn)
write(serialdevObj,dataIn,precision)
Description
write(serialdevObj,dataIn) writes data to the serial device.
Examples
arduinoObj = arduino("COM16","Leonardo","Libraries",{'SPI','Serial','I2C'});
serialdevObj = device(arduinoObj,'SerialPort',1)
serialdevObj =
device with properties:
Interface: 'Serial'
SerialPort: 1
TxPin: 'D1'
RxPin: 'D0'
BaudRate: 9600 (bits/s)
NumBytesAvailable: 0
write(serialdevObj,[88 99 65]);
arduinoObj = arduino("COM16","Leonardo","Libraries",{'SPI','Serial','I2C'});
4-12
write
serialdevObj = device(arduinoObj,'SerialPort',1)
serialdevObj =
device with properties:
Interface: 'Serial'
SerialPort: 1
TxPin: 'D1'
RxPin: 'D0'
BaudRate: 9600 (bits/s)
NumBytesAvailable: 0
write(serialdevObj,256,'uint16');
Input Arguments
serialdevObj — serial device connection
serial device object
Data to write to the serial device, specified as a scalar or vector. The range of the values in the
array is based on the precision.
• 'uint8'
• 'int8'
• 'uint16'
• 'int16'
• 'uint32'
• 'int32'
• 'uint64'
• 'int64'
• hexadecimal
• binary
4-13
4 Serial Functions
• char
• string
More About
Code Generation Using MATLAB Function Block
• Use write in a MATLAB Function block with the Simulink Support Package for Arduino Hardware
to generate code that can be deployed on Arduino Hardware.
• Values of dataIn is not validated against the precision. The dataIn values will be saturated
when it goes beyond the range of the specified precision.
Version History
Introduced in R2019b
See Also
arduino | read | device
4-14
5
canChannel
Connection to CAN channel connected to a specified device
Description
This object represents a connection to the CAN channel through the specified device connected to the
Arduino hardware. To transmit and receive data from Arduino hardware through the CAN bus use
“Object Functions” on page 5-5.
Creation
Syntax
ch = canChannel(arduinoObj,device)
ch = canChannel(arduinoObj,'MCP2515',ChipSelectPin,InterruptPin)
ch = canChannel(arduinoObj,device,Name,Value)
ch = canChannel(arduinoObj,'MCP2515',ChipSelectPin,InterruptPin,Name,Value)
Description
ch = canChannel(arduinoObj,'MCP2515',ChipSelectPin,InterruptPin,Name,Value)
creates a CAN channel connected to the MCP2515 chip with specified ChipSelectPin and
InterruptPin and the additional options.
Input Arguments
Name of the CAN device to which the channel is connected, specified as a string. See “Supported
CAN Shields” on page 5-5 for all the supported devices.
5-2
canChannel
Chip select pin of MCP2515, specified as a string or character vector. This is mandatory when you
create a connection to the CAN channel with a MCP2515.
Interrupt pin of MCP2515, specified as a string or character vector. This is mandatory when you
create a connection to the CAN channel with MCP2515.
Specify comma-separated pair of Name,Value arguments. Name is the argument name and Value is
the corresponding value. Name must appear inside quotes. You can specify several name and value
pair arguments in any order as Name1,Value1,...,NameN,ValueN
Example: ch = canChannel(arduinoObj,"MCP2515", "D10", "D2",
"OscillatorFrequency", 16e6);
Example: ch = canChannel(arduinoObj,"Sparkfun CAN-Bus Shield", "D10", "D2",
"BusSpeed", 500e3);
Properties
Device — Name of CAN device
Sparkfun CAN-Bus Shield | Seeed Studio CAN-Bus Shield V2 | MKR CAN Shield |
MCP2515
CAN device to which the channel is connected specified as a string. See “Supported CAN Shields” on
page 5-5 for all the supported devices.
Example:
>> ch.Device
ans =
"MCP2515"
5-3
5 CAN Interface Functions
ans =
"CAN"
ans =
500000
Displays database object of type can.Database if used. This property displays an empty structure,
[ ], if not used.
Example:
>> db = canDatabase(exp.dbc);
>> ch.Database = db;
Dependencies
You can use this property only with Vehicle Network Toolbox™.
ans =
'10000000'
5-4
canChannel
Example:
>> ch.ChipSelectPin
ans =
"D9"
ans =
"D2"
Note If you connect a CAN shield to an Arduino board whose form factor is not the same as the
Arduino board, ensure the RESET pin on the CAN shield is connected to the RESET pin on the
Arduino board.
Object Functions
Use these object functions to transmit and receive messages from the CAN bus.
read Read messages from CAN channel
write Write messages to CAN bus
Examples
Create Connection to CAN Channel on Shield
5-5
5 CAN Interface Functions
arduinoObj =
Port: 'COM24'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11'}
AvailableAnalogPins: {'A0-A5'}
AvailableI2CBusIDs: [0]
Libraries: {'CAN', 'SPI'}
Show all properties
ch =
OscillatorFrequency: 1.600000e+07
ChipSelectPin: "D9"
InterruptPin: "D2"
arduinoObj =
Port: 'COM24'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11'}
AvailableAnalogPins: {'A0-A5'}
AvailableI2CBusIDs: [0]
Libraries: {'CAN', 'SPI'}
Show all properties
5-6
canChannel
ch =
Device: 'MCP2515'
ProtocolMode: 'CAN'
BusSpeed: 500000
Database: []
Show all properties
Device: 'MCP2515'
ProtocolMode: 'CAN'
BusSpeed: 500000
Database: []
OscillatorFrequency: 1.600000e+07
ChipSelectPin: "D10"
InterruptPin: "D2"
arduinoObj =
Port: 'COM24'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11'}
AvailableAnalogPins: {'A0-A5'}
AvailableI2CBusIDs: [0]
Libraries: {'CAN', 'SPI'}
Show all properties
ch =
5-7
5 CAN Interface Functions
OscillatorFrequency: 1.600000e+07
ChipSelectPin: "D9"
InterruptPin: "D2"
arduinoObj =
Port: 'COM24'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}
AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11'}
AvailableAnalogPins: {'A0-A5'}
AvailableI2CBusIDs: [0]
Libraries: {'CAN', 'SPI'}
Show all properties
ch =
Device: 'MCP2515'
ProtocolMode: 'CAN'
BusSpeed: 500000
Database: []
Show all properties
Device: "MCP2515"
ProtocolMode: "CAN"
BusSpeed: 500000
Database: []
OscillatorFrequency: 1.600000e+07
ChipSelectPin: "D10"
InterruptPin: "D2"
Version History
Introduced in R2020a
See Also
arduino | read | write | canDatabase
5-8
read
read
Read messages from CAN channel
Syntax
message = read(ch)
message = read(ch,maxMessages)
Description
message = read(ch) reads a timetable of CAN messages received on the CAN channel ch.
Examples
Read CAN Messages
Use database to see the 'Name' field populated in the output message timetable.
5-9
5 CAN Interface Functions
db = canDatabase(demoVNT_CANdbFiles.dbc);
ch.Database = db;
read(ch,5)
Input Arguments
ch — Connection to CAN channel
object
Maximum number of messages to read, specified as a positive numeric value. If fewer messages are
available than maxMessages , the function returns the currently available messages. If no messages
are available, the function returns an empty timetable.
Output Arguments
message — CAN messages
timetable
CAN messages from the channel, returned as a timetable of messages. With Vehicle Network Toolbox
the message output will have additional information about CAN messages. When database property is
used, the Name and Signals information of messages will also be filled.
Version History
Introduced in R2020a
See Also
canChannel | write
5-10
write
write
Write messages to CAN bus
Syntax
write(ch,identifier,isExtended,dataArray)
write(ch,CANMessage)
Description
write(ch,identifier,isExtended,dataArray) writes CAN messages onto the bus via the CAN
channel.
write(ch,CANMessage) writes the CAN message created using the canMessage of Vehicle
Network Toolbox onto the bus.
Examples
Transmit a CAN Message
Input Arguments
ch — Connection to CAN channel
object
identifier — ID of message
numeric
5-11
5 CAN Interface Functions
Indicates whether the message ID is of standard or extended type, specified as true or false. The
logical value true indicates that the ID is of extended type, false indicates standard type.
Data to write to the CAN channel, specified as a non negative numeric value. The data is truncated to
uint8.
Message to transmit, specified as a CAN message object. These messages are transmitted via a CAN
channel to other CAN nodes.
Dependencies
You can create the message using CANMessage only with Vehicle Network Toolbox.
Version History
Introduced in R2020a
See Also
canChannel | read | canMessage
External Websites
https://en.wikipedia.org/wiki/CAN_bus#Data_frame
5-12
6
gpsdev
Description
The gpsdev object reads position and time data using a Global Positioning System(GPS) module. The
gpsdev object represents a connection to the GPS receiver connected to the serial port of the
Arduino hardware. gpsdev uses GPRMC, GPGGA and GPGSA sentences to read the data. The GPS
receiver must output these sentences for successful creation of the gpsdev object. Ensure your GPS
module is configured to give the sentences.
Creation
Syntax
gpsObj = gpsdev(a)
gpsObj = gpsdev(a,Name,Value)
Description
gpsObj = gpsdev(a) creates a GPS object. The object represents the connection to the GPS on the
Arduino hardware, a.
gpsObj = gpsdev(a,Name,Value) creates a GPS object with default property values. The object
represents the connection to the GPS on the Arduino hardware, a.
Input Arguments
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
The ID of the serial port available on the Arduino hardware specified as a number.
Example: gpsObj = gpsdev(a,'SerialPort',2)
6-2
gpsdev
Properties
Unless otherwise indicated, properties are nontunable, which means you cannot change their values
after calling the object. Objects lock when you call them, and the release function unlocks them.
For more information on changing property values, see System Design in MATLAB Using System
Objects.
The baud rate for serial communication. The baud rate is set at 9600 bits/sec. The GPS receiver must
be configured to work at 9600 bits/sec . If your GPS receiver is configured to some other baud rate,
reconfigure it to 9600 bits/sec to use gpsdev function.
Number of samples read from the GPS in a single execution of the read function. The maximum
value is 10.
Tunable: No
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the GPS receiver is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the GPS
receiver are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first GPS
receiver data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during GPS receiver object creation.
6-3
6 GPS Functions — Alphabetical List
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first GPS
receiver data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during GPS receiver object creation.
Tunable: No
Data Types: character vector | string
Samples read from the first read. When you release the object, SamplesRead is set to 0.
Data Types: double
Samples available in the host buffer. When you release the object, SamplesAvailable is set to 0.
Data Types: double
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the timetable returned has the following fields:
6-4
gpsdev
When the OutputFormat is set to matrix, the data is returned as matrices of Time, LLA, Ground
Speed, Course over ground, DOPs, and GPS receiver time. The units for the GPS receiver readings
are the same as the timetable format.
Tunable: Yes
Data Types: character vector | string
Set the format of the time displayed when the GPS data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the GPS object is locked. The GPS object
gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Tunable: Yes
Data Types: character vector | string
Examples
Create GPS Connection
gpsObj = gpsdev(a)
gpsObj =
SerialPort: 1
BaudRate: 9600 (bits/s)
SamplesPerRead: 2
ReadMode: 'oldest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions
Create a GPS object with additional properties specified as name-value pair arguments.
gpsObj = gpsdev(a,'SamplesPerRead',3,'ReadMode','latest')
6-5
6 GPS Functions — Alphabetical List
gpsObj =
SerialPort: 1
BaudRate: 9600 (bits/s)
SamplesPerRead: 3
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Object Functions
flush Flush the host buffer
info Read Update Rate, GPS Lock information and number of satellites in View for the GPS
receiver
read Read data from GPS
release Release the GPS object
stop Stop data collection from GPS module
writeBytes Write raw data to GPS module
More About
GPS Modules
Version History
Introduced in R2020a
6-6
read
read
Read data from GPS
Syntax
tt = read(gpsObj)
[tt,overrun] = read(gpsObj)
[lla,groundSpeed,course, dops,gpsReceiverTime,timestamp, overrun] = read(
gpsObj)
Description
tt = read(gpsObj) returns the one frame of GPS data in timetable format.
[tt,overrun] = read(gpsObj) returns the GPS readings in timetable format. This is a non
blocking read which returns N datapoints in timetable format where N is specified by
SamplesPerRead and timetable is specified using OutputFormat property of gpsdev object.
Examples
Read Data from GPS
gpsObj = gpsdev(a);
tt = read(gpsObj)
tt =
1×5 timetable
6-7
6 GPS Functions — Alphabetical List
[tt,overruns] = read(gpsObj)
tt =
2×5 timetable
overrun =
Display the time at which GPS data is read from the Arduino hardware in duration format.
gpsObj.TimeFormat = “duration”;
[tt,overruns] = read(gpsObj)
tt =
2×5 timetable
9.4257 sec 12.944 77.692 808.4 0.030867 4.93 1.51 0.78 1.29
10.404 sec 12.944 77.692 808.4 0.051444 41.26 1.1 0.76 0.79
overrun =
755
[lla,speed,course,dops,gpsReceiverTime,timestamp,overruns] = read(gpsObj)
6-8
read
lla =
speed =
0.0154
0.0463
course =
346.0100
270.2100
dops =
gpsReceiverTime =
31-Jan-2020 06:07:01.000
31-Jan-2020 06:07:02.000
timestamp =
31-Jan-2020 11:37:01.734
31-Jan-2020 11:37:02.436
overruns =
75
Input Arguments
gpsObj — GPS object
gpsdev object
Output Arguments
tt — Data read as timetable
6-9
6 GPS Functions — Alphabetical List
Data read from the GPS receiver when the output format is set to timetable. The timetable
returned has the following fields:
Position of the GPS receiver in the geodetic latitude, longitude, and altitude (LLA), returned as a real
finite N-by-3 array. Latitude and longitude are in degrees with North and East being positive. Altitude
is in meters.
Data Types: double
Course over ground relative to true north,returned as a real finite N-by-1 column of values between 0
and 2pi radians.
Data Types: double
Dilution of precisions, returned as a real finite N-by-3 array. The order of the output is
[PDOP,HDOP,VDOP].
Data Types: double
6-10
read
Time at which GPS data is read from the hardware, returned as a real finite N-by-1 column vector. If
the TimeFormat is datetime, the timestamp will be datetime. If the TimeFormat is a duration,
the timestamp will be duration
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the first call of the read function or the
last execution of the release function.
overrun — Overrun
The number of samples lost between consecutive calls to read. The overrun is zero when ReadMode
is set to oldest.
Data Types: double
More About
read Output
The read function outputs NaN and NaT in the following situations:
• If the GPS module does not receive valid data because there is no satellite lock or when GPS does
not give a particular value.
• If there is a checksum failure, corresponding data points will be NaN for numeric outputs (lla,
speed, course, dops) and NaT for gpsRecieverTime. lla is taken from GPGGA sentence,
speed,course, and gpsRecieverTime is taken GPRMC sentence and dops are taken from
GPGSA sentence.
The first read after GPS object creation gives NaN for numeric values and NaT for time values since
acquiring data from GPS takes time.
• If no new data is available, the output of read is the previous data . For example, if the delay
between subsequent reads is less than the UpdateRate of the GPS receiver.
Version History
Introduced in R2020a
6-11
6 GPS Functions — Alphabetical List
info
Read Update Rate, GPS Lock information and number of satellites in View for the GPS receiver
Syntax
gpsInfo = info(gpsObj)
Description
gpsInfo = info(gpsObj) returns the update rate of the GPS receiver, GPS lock information and
number of satellites from which the GPS can read signals. info gets updated after every execution of
read command.
Input Arguments
gpsObj — GPS object
gpsdev object
Output Arguments
gpsInfo — GPS module information
GPS module information such as update rate, and number of satellites. The output has three fields:
• UpdateRate - Update Rate of the GPS Module in Hz. Update Rate of GPS receiver is estimated
from the difference in time at which two RMC sentences are obtained. This value might be slightly
varying from actual Update Rate of the module.
• GPSLocked - This property specifies if GPS has enough information to get valid data. GPS signals
are acquired easily in locations that have a clear view of the sky. It can be either a 0 or 1 (logical).
If GPSLocked is 0, the GPS does not have the lock to compute location or time information. If
GPSLocked is 1, GPS module has enough data to compute location or time information.
• NumberOfSatellitesInView - Number of satellites from which the GPS module can read the
signals.
Version History
Introduced in R2020a
6-12
stop
stop
Stop data collection from GPS module
Syntax
stop(gpsObj)
Description
stop(gpsObj) stops the data collection from the GPS module, clears the buffer, and resets the start
time and sets the number of overrun samples to 0.
Input Arguments
gpsObj — GPS object
gpsdev object
Version History
Introduced in R2020a
6-13
6 GPS Functions — Alphabetical List
flush
Flush the host buffer
Syntax
flush(gpsdevObj)
Description
flush(gpsdevObj) clears the buffers and resets the SamplesRead and SamplesAvailable.
Input Arguments
gpsdevObj — GPS sensor object
Version History
Introduced in R2020a
6-14
release
release
Release the GPS object
Syntax
release(gpsdev)
Description
release(gpsdev) stops the data collection from the GPS receiver, clears the buffer, and resets the
start time and sets the number of overrun samples to 0.
Input Arguments
gpsdev — GPS sensor object
Version History
Introduced in R2020a
6-15
6 GPS Functions — Alphabetical List
writeBytes
Write raw data to GPS module
Syntax
writeBytes(gpsObj,dataArray)
Description
writeBytes(gpsObj,dataArray) writes raw data specified by dataArray to configure the GPS
module.
Input Arguments
gpsObj — GPS object
gpsdev object
Raw data to write to the GPS module to configure the module, specified as an array.
Data Types: uint8
Version History
Introduced in R2020a
6-16
7
motorCarrier
Connection to Arduino MKR Motor Carrier or Nano Motor Carrier
Description
This object represents a connection to an MKR Motor Carrier or a Nano Motor Carrier. To
communicate with peripherals connected to the MKR Motor Carrier or the Nano Motor Carrier,
create connections to the peripherals using the functions listed under “Object Functions” on page 7-
3.
The motorCarrier object uses the arduino object to establish connection to these supported
boards:
Creation
Syntax
mcObj = motorCarrier(arduinoObj)
Description
Input Arguments
Connection to the Arduino hardware, specified as an object. To create a connection to the MKR Motor
Carrier, create the arduino object with the boards MKR1000, MKR1010, or MKRZero. To create a
connection to the Nano Motor Carrier, create the arduino object with the Nano33IoT board.
Example: arduinoObj = arduino('COM11','Nano33IoT','Libraries','MotorCarrier')
creates a connection to the Nano Motor Carrier.
Properties
SCLPin — I2C serial clock pin
character vector
I2C serial clock pin on the Arduino hardware used by the MKR Motor Carrier or Nano Motor Carrier.
7-2
motorCarrier
Example:
>> mcObj.SCLPin
ans =
'A5'
I2C serial data pin on the Arduino hardware used by the MKR Motor Carrier or Nano Motor Carrier.
Example:
>> mcObj.SDAPin
ans =
'A4'
ans =
102
Object Functions
Use these object functions to use the peripherals on the MKR Motor Carrier or Nano Motor Carrier :
servo Connection to servo motor on Arduino MKR Motor Carrier or Nano Motor Carrier
dcmotor Connection to DC Motor on Arduino MKR Motor Carrier or Nano Motor Carrier
pidMotor Connection to motors in closed-loop PID control on Arduino MKR Motor Carrier or
Nano Motor Carrier
rotaryEncoder Connection to rotary encoder on Arduino MKR Motor Carrier or Nano Motor Carrier
Examples
Create a Connection to MKR Motor Carrier
arduinoObj = arduino('COM13','MKR1000','Libraries','MotorCarrier')
arduinoObj =
7-3
7 Motor Carrier Functions
Port: 'COM13'
Board: 'MKR1000'
AvailablePins: {'D0-D14', 'A0-A6'}
AvailableDigitalPins: {'D0-D14', 'A0-A6'}
AvailablePWMPins: {'D0-D8', 'D10', 'A3-A4'}
AvailableAnalogPins: {'A0-A6'}
AvailableI2CBusIDs: [0]
Libraries: {'MotorCarrier'}
Show all properties
mcObj = motorCarrier(arduinoObj)
mcObj =
arduinoObj = arduino('COM11','Nano33IoT','Libraries','MotorCarrier');
arduinoObj =
Port: 'COM11'
Board: 'Nano33IoT'
AvailablePins: {'D0-D13', 'A0-A7'}
AvailableDigitalPins: {'D0-D13', 'A0-A7'}
AvailablePWMPins: {'D2-D6', 'D9-D10'}
AvailableAnalogPins: {'A0-A3','A6-A7'}
AvailableI2CBusIDs: [0]
AvailableSerialPortIDs: [1]
Libraries: {'MotorCarrier'}
Show all properties
mcObj = motorCarrier(arduinoObj);
mcObj =
SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')
7-4
motorCarrier
Version History
Introduced in R2020b
See Also
arduino | dcmotor | pidMotor | rotaryEncoder | servo
7-5
7 Motor Carrier Functions
dcmotor
Connection to DC Motor on Arduino MKR Motor Carrier or Nano Motor Carrier
Description
This object represents a connection to a DC Motor with the specified motor number on an MKR Motor
Carrier or Nano Motor Carrier. You can control the DC motor using “Object Functions” on page 7-
7.
Creation
Syntax
dcmObj = dcmotor(mcObj,motornumber)
dcmObj = dcmotor(mcObj,motornumber,Speed)
Description
Input Arguments
Connection to the MKR Motor Carrier or Nano Motor Carrier, specified as an object.
Example: dcmObj = dcmotor(mcObj,M1) creates a DC motor connection at motor number 1
connected to M1.
DC motor number where the motor is connected on an MKR Motor Carrier or Nano Motor Carrier,
specified as a character vector.
Normalized DC motor duty cycle specified as a number between-1 and 1. A positive number indicates
a forward rotation and a negative number indicates a reverse rotation of the motor shaft.
Example: dcmObj = dcmotor(mcObj,'M1','Speed',0.2); sets the duty cycle to 20% in forward
direction of rotation of the motor shaft.
7-6
dcmotor
Properties
MotorNumber — DC motor number
M1 | M2 | M3 | M4
Motor number on the MKR Motor Carrier or Nano Motor Carrier where the DC motor is connected.
Example:
>> dcmObj.MotorNumber
ans =
'M1'
DC motor duty cycle specified as a number between-1 and 1. A positive number indicates a forward
rotation of the motor shaft and a negative number indicates a reverse rotation of the motor shaft.
Example:
>> dcmObj.Speed
ans =
0.2
DC motor state specified as 0 or 1. Running is 0 if the motor has not started and 1 otherwise.
Running is a read-only property.
Example:
>> dcmObj.Running
ans =
0
Object Functions
Use these object functions to create a connection to the DC Motor.
start Start DC motor connected to MKR Motor Carrier or Nano Motor Carrier
stop Stop DC motor connected to MKR Motor Carrier or Nano Motor Carrier
Examples
7-7
7 Motor Carrier Functions
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier')
arduinoObj =
arduino with properties:
Port: '/dev/ttyACM0'
Board: 'Nano33IoT'
AvailablePins: {'D0-D13', 'A0-A7'}
AvailableDigitalPins: {'D0-D13', 'A0-A7'}
AvailablePWMPins: {'D2-D6', 'D9-D10'}
AvailableAnalogPins: {'A0-A3', 'A6-A7'}
AvailableI2CBusIDs: [0]
AvailableSerialPortIDs: [1]
Libraries: {'MotorCarrier'}
Show all properties
mcObj = motorCarrier(arduinoObj)
mcObj =
MotorCarrier with properties:
SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')
dcmObj = dcmotor(mcObj,'M3')
dcmObj =
DCMotor with properties:
MotorNumber: 'M3'
Running: 0
Speed: 0
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier')
arduinoObj =
arduino with properties:
Port: '/dev/ttyACM0'
Board: 'Nano33IoT'
7-8
dcmotor
mcObj = motorCarrier(arduinoObj)
mcObj =
MotorCarrier with properties:
SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')
dcmObj = dcmotor(mcObj,'M3','Speed',0.2)
dcmObj =
DCMotor with properties:
MotorNumber: 'M3'
Running: 0
Speed: 2.000000e-01
Version History
Introduced in R2020a
See Also
arduino | motorCarrier | pidMotor | rotaryEncoder | servo
7-9
7 Motor Carrier Functions
start
Start DC motor connected to MKR Motor Carrier or Nano Motor Carrier
Syntax
start(dcmObj)
Description
start(dcmObj) starts the DC motor. If the motor speed is set 0, the DC motor will not rotate.
Examples
Start DC Motor
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);
dcmObj = dcmotor(mcObj,'M1')
dcmObj =
DCMotor with properties:
MotorNumber: 'M1'
Running: 0
Speed: 0
Change the speed to 0.2, start the DC motor, and display the motor object.
dcmObj.Speed = 0.2;
start(dcmObj);
dcmObj
dcmObj =
DCMotor with properties:
MotorNumber: 'M1'
Running: 1
Speed: 2.000000e-01
Input Arguments
dcmObj — DC motor connection
object
7-10
start
Connection to the DC Motor on MKR Motor Carrier or Nano Motor Carrier, specified as an object.
Version History
Introduced in R2020a
See Also
motorCarrier | dcmotor | stop
7-11
7 Motor Carrier Functions
stop
Stop DC motor connected to MKR Motor Carrier or Nano Motor Carrier
Syntax
stop(dcmObj)
Description
stop(dcmObj) stops the DC motor.
Examples
Stop DC Motor
dcmObj =
DCMotor with properties:
MotorNumber: 'M1'
Running: 0
Speed: 0
Change the speed to 0.2, start the DC motor, and display the motor object.
dcmObj.Speed = 0.3;
start(dcmObj);
dcmObj
dcmObj =
DCMotor with properties:
MotorNumber: 'M1'
Running: 1
Speed: 3.000000e-01
dcmObj =
DCMotor with properties:
7-12
stop
MotorNumber: 'M1'
Running: 0
Speed: 3.000000e-01
Input Arguments
dcmObj — DC motor connection
object
Connection to the DC Motor on MKR Motor Carrier or Nano Motor Carrier, specified as an object.
Version History
Introduced in R2020a
See Also
motorCarrier | dcmotor | start
7-13
7 Motor Carrier Functions
pidMotor
Connection to motors in closed-loop PID control on Arduino MKR Motor Carrier or Nano Motor
Carrier
Description
This object represents a connection to motors running in closed-loop PID control with the specified
motor number on the MKR Motor Carrier or Nano Motor Carrier. You can control the DC motors M1
and M2 in closed-loop PID control using the functions in “Object Functions” on page 7-17.
Creation
Syntax
pidObj = pidMotor(mcObj,PIDNumber)
pidObj = pidMotor(mcObj,PIDNumber,controlmode)
pidObj = pidMotor(mcObj,PIDNumber,controlmode,ppr)
pidObj = pidMotor(mcObj,PIDNumber,controlmode,ppr,[PIDGains])
Description
Input Arguments
Connection to the MKR Motor Carrier or Nano Motor Carrier, specified as an object.
Example: pidObj = pidMotor(mcObj,1) creates a connection to the motor number 1.
7-14
pidMotor
Motor number where the PID motor is connected on an MKR Motor Carrier or Nano Motor Carrier,
specified as a number. The PIDNumber 1 implies a connection to the motor number 1 (M1) and the
encoder 1 whereas the PIDNumber 2 implies a connection to the motor number 2 (M2) and the
encoder 2.
Example: pidObj = pidMotor(mcObj,2) creates a connection to the motor number 2.
The mode of control of the PID motor, specified as a character vector. To drive the DC motor at the
specified speed, create the connection to the PID motor in speed control mode. To rotate the motor
by the specified angle, create the connection to the PID motor in position control mode.
Example: pidObj = pidMotor(mcObj,1,'Position'); creates a connection to the motor
number 1 in the position control mode.
Proportional (Kp), integral (Ki), and derivative (Kd) gains of the PID motor specified as a 1-by-3
vector. The following are the default values of [Kp,Ki,Kd] in the speed and position control
modes:
Note Tuning gains can lead to the motor and board getting burnt in case of excess current. Also, the
Arduino firmware does not allow setting MaxSpeed to ensure safety.
Properties
PIDNumber — PID Motor number
1|2
PID motor number corresponding to DC motor number and encoder channel number on an MKR
Motor Carrier or Nano Motor Carrier, specified as a number.
7-15
7 Motor Carrier Functions
Example:
>> pidObj.PIDNumber
ans =
1
>> pidObj.ControlMode
ans =
'speed'
>> pidObj.PulsesPerRevolution
ans =
3
Kp — Proportional gain
numeric
>> pidObj.Kp
ans =
2000
Ki — Integral gain
numeric
7-16
pidMotor
>> pidObj.Ki
ans =
200
Kd — Derivative gain
numeric
>> pidObj.Kd
ans =
0
>> pidObj.MaxAcceleration
ans =
2094400000 (rad/s2)
>> pidObj.MaxSpeed
ans =
25000 RPM
Object Functions
Use these object functions to create a connection to the PID motor:
readAngularPosition Read angular position of DC Motor in closed-loop control
readSpeed Read current rotational speed of DC Motor in closed loop control
writeAngularPosition Rotate DC motor by specified angle in closed loop position control
writeSpeed Write speed of PID motor
7-17
7 Motor Carrier Functions
Examples
arduinoObj =
arduino with properties:
Port: '/dev/ttyACM0'
Board: 'Nano33IoT'
AvailablePins: {'D0-D13', 'A0-A7'}
AvailableDigitalPins: {'D0-D13', 'A0-A7'}
AvailablePWMPins: {'D2-D6', 'D9-D10'}
AvailableAnalogPins: {'A0-A3', 'A6-A7'}
AvailableI2CBusIDs: [0]
AvailableSerialPortIDs: [1]
Libraries: {'MotorCarrier'}
Show all properties
mcObj =
MotorCarrier with properties:
SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')
pidObj =
PIDMotor with properties:
PIDNumber: 1
ControlMode:'speed'
PulsesPerRevolution: 3
Kp: 5.200000
Ki: 0.300000
Kd: 0.000000
MaxAcceleration: 2094400000 (rad/s^2)
MaxSpeed: 25000 (RPM)
7-18
pidMotor
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier')
arduinoObj =
arduino with properties:
Port: '/dev/ttyACM0'
Board: 'Nano33IoT'
AvailablePins: {'D0-D13', 'A0-A7'}
AvailableDigitalPins: {'D0-D13', 'A0-A7'}
AvailablePWMPins: {'D2-D6', 'D9-D10'}
AvailableAnalogPins: {'A0-A3', 'A6-A7'}
AvailableI2CBusIDs: [0]
AvailableSerialPortIDs: [1]
Libraries: {'MotorCarrier'}
Show all properties
mcObj = motorCarrier(arduinoObj)
mcObj =
MotorCarrier with properties:
SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')
pidObj = pidMotor(mcObj,1,'position')
pidObj =
PIDMotor with properties:
PIDNumber: 1
ControlMode:'position'
PulsesPerRevolution: 3
Kp: 0.180000
Ki: 0.000000
Kd: 0.010000
MaxAcceleration: 2094400000 (rad/s^2)
MaxSpeed: 25000 (RPM)
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier')
arduinoObj =
arduino with properties:
Port: '/dev/ttyACM0'
7-19
7 Motor Carrier Functions
Board: 'Nano33IoT'
AvailablePins: {'D0-D13', 'A0-A7'}
AvailableDigitalPins: {'D0-D13', 'A0-A7'}
AvailablePWMPins: {'D2-D6', 'D9-D10'}
AvailableAnalogPins: {'A0-A3', 'A6-A7'}
AvailableI2CBusIDs: [0]
AvailableSerialPortIDs: [1]
Libraries: {'MotorCarrier'}
Show all properties
mcObj = motorCarrier(arduinoObj)
mcObj =
MotorCarrier with properties:
SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')
pidObj = pidMotor(mcObj,1,'position',3)
pidObj =
PIDMotor with properties:
PIDNumber: 1
ControlMode:'position'
PulsesPerRevolution: 3
Kp: 0.180000
Ki: 0.000000
Kd: 0.010000
MaxAcceleration: 2094400000 (rad/s^2)
MaxSpeed: 25000 (RPM)
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier')
arduinoObj =
arduino with properties:
Port: '/dev/ttyACM0'
Board: 'Nano33IoT'
AvailablePins: {'D0-D13', 'A0-A7'}
AvailableDigitalPins: {'D0-D13', 'A0-A7'}
AvailablePWMPins: {'D2-D6', 'D9-D10'}
AvailableAnalogPins: {'A0-A3', 'A6-A7'}
AvailableI2CBusIDs: [0]
7-20
pidMotor
AvailableSerialPortIDs: [1]
Libraries: {'MotorCarrier'}
Show all properties
mcObj = motorCarrier(arduinoObj)
mcObj =
MotorCarrier with properties:
SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')
pidObj =
PIDMotor with properties:
PIDNumber: 1
ControlMode:'position'
PulsesPerRevolution: 3
Kp: 0.180000
Ki: 0.000000
Kd: 0.010000
MaxAcceleration: 2094400000 (rad/s^2)
MaxSpeed: 25000 (RPM)
Version History
Introduced in R2020a
See Also
arduino | dcmotor | motorCarrier | rotaryEncoder | servo
7-21
7 Motor Carrier Functions
readAngularPosition
Read angular position of DC Motor in closed-loop control
Syntax
position = readAngularPosition(pidObj)
[position,timestamp] = readAngularPosition(pidObj)
position = readAngularPosition(pidObj,'Reset',reset)
[position,timestamp] = readAngularPosition(pidObj,'Reset',reset)
Description
position = readAngularPosition(pidObj) returns the angular position of the DC motor shaft,
in closed-loop control with the rotary encoder in radians.
Examples
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);
pidObj = pidMotor(mcObj,1,'position');
Rotate the angular position with feedback from encoder 1 in closed-loop control.
position = readAngularPosition(pidObj);
7-22
readAngularPosition
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);
Rotate the angular position with feedback from encoder 1 in closed-loop control.
[position,timestamp] = readAngularPosition(pidObj);
Rotate the angular position with feedback from encoder 1 in closed-loop control.
position = readAngularPosition(pidObj,'Reset',true);
Rotate the angular position with feedback from encoder 1 in closed-loop control along with the
timestamp.
[position,timestamp] = readAngularPosition(pidObj,'Reset',true);
Input Arguments
pidObj — PID motor object
object
Connection to the PID motor on MKR Motor Carrier or Nano Motor Carrier in the position control
mode, specified as an object.
7-23
7 Motor Carrier Functions
Setting reset to true resets the counter to zero for subsequent read. This is an optional argument.
Output Arguments
position — Angular position of the DC motor shaft
double
Angular position of the DC motor shaft obtained from the count of the encoder since the last reset.
Version History
Introduced in R2020a
See Also
pidMotor | readSpeed | writeAngularPosition | writeSpeed
7-24
readSpeed
readSpeed
Read current rotational speed of DC Motor in closed loop control
Syntax
[speed] = readSpeed(pidObj)
[speed,timestamp] = readSpeed(pidObj)
Description
[speed] = readSpeed(pidObj) returns the current rotational speed of the DC motor in closed-
loop control as read by the quadrature encoder connected to encoder channel number corresponding
to PID motor number.
Examples
7-25
7 Motor Carrier Functions
Input Arguments
pidObj — PID motor object
object
PID motor object connected to MKR Motor Carrier or Nano Motor Carrier specified as an object.
Output Arguments
speed — Current rotational speed
double
Current rotational speed in RPM of the DC Motor as read by the encoder, returned as a double.
Version History
Introduced in R2020a
See Also
pidMotor | readAngularPosition | writeAngularPosition | writeSpeed
7-26
writeAngularPosition
writeAngularPosition
Rotate DC motor by specified angle in closed loop position control
Syntax
writeAngularPosition(pidObj,position)
writeAngularPosition(pidObj,position,mode)
Description
writeAngularPosition(pidObj,position) rotates the DC motor shaft with feedback from the
encoder in closed loop position control by the position specified in radians.
Examples
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);
pidObj = pidMotor(mcObj,1,'position');
Rotate the motor by 45 radians with respect to initial position with feedback from encoder 1 in
closed-loop control.
writeAngularPosition(pidObj,45);
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);
pidObj = pidMotor(mcObj,1,'position');
Rotate the motor by 45 radians with respect to initial position with feedback from encoder 1 in
closed-loop control.
7-27
7 Motor Carrier Functions
writeAngularPosition(pidObj,45,'abs');
Input Arguments
pidObj — PID motor object
object
Connection to the PID motor on MKR Motor Carrier or Nano Motor Carrier in the position control
mode, specified as an object.
Mode of calculation of angle of rotation, specified as abs or rel. In both the abs and rel mode, the
angle of rotation of motor shaft is calculated based on current count of the encoder register. In the
abs mode, the motor rotates by a difference in the angle between the current and desired position. In
the rel mode, the motor rotates by the angle that is input.
Version History
Introduced in R2020a
See Also
pidMotor | readAngularPosition | readSpeed | writeSpeed
7-28
writeSpeed
writeSpeed
Write speed of PID motor
Syntax
writeSpeed(pidObj,speed)
Description
writeSpeed(pidObj,speed) drives the DC motor connected to the motor number corresponding
to PID number of PID motor object in closed-loop control while receiving feedback from encoder
channel corresponding to PID number at the specified speed.
Examples
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);
pidObj = pidMotor(mcObj,1);
Set the speed of the DC Motor M1 in closed-loop control with feedback from encoder channel 1 to
100 RPM
writeSpeed(pidObj,100);
Input Arguments
pidObj — PID motor object
object
Connection to the PID motor on MKR Motor Carrier or Nano Motor Carrier in the speed control
mode, specified as an object.
Version History
Introduced in R2020a
7-29
7 Motor Carrier Functions
See Also
pidMotor | readAngularPosition | readSpeed | writeAngularPosition
7-30
rotaryEncoder
rotaryEncoder
Connection to rotary encoder on Arduino MKR Motor Carrier or Nano Motor Carrier
Description
This object represents a connection to the rotary encoder with the specified channel on the MKR
Motor Carrier or Nano Motor Carrier. You can read from the rotary encoder in using “Object
Functions” on page 7-32.
Creation
Syntax
encoder = rotaryEncoder(mcObj,channelNumber)
encoder = rotaryEncoder(mcObj,channelNumber,ppr)
Description
Input Arguments
Connection to the MKR Motor Carrier or Nano Motor Carrier, specified as an object.
Example: encoder = rotaryEncoder(mcObj,1) creates a rotary encoder connection on channel
1.
Channel number on the MKR Motor Carrier or Nano Motor Carrier to which the encoder is
connected, specified as a scalar.
Example: encoder = rotaryEncoder(mcObj,1) creates a connection to a rotary encoder at
channel 1.
7-31
7 Motor Carrier Functions
Properties
Channel — Channel number of encoder
numeric
>> encoder.Channel
ans =
1
>> encoder.Encoding
ans =
'X4'
>> encoder.PulsesPerRevolution
ans =
4
Object Functions
Use object functions to with your rotary encoder.
readCount Read current count value from encoder connected to MKR Motor Carrier or Nano
Motor Carrier
readSpeed Read current rotational speed of motor from rotary encoder
resetCount Set encoder count value to zero or specified value
7-32
rotaryEncoder
Examples
arduinoObj =
arduino with properties:
Port: '/dev/ttyACM0'
Board: 'Nano33IoT'
AvailablePins: {'D0-D13', 'A0-A7'}
AvailableDigitalPins: {'D0-D13', 'A0-A7'}
AvailablePWMPins: {'D2-D6', 'D9-D10'}
AvailableAnalogPins: {'A0-A3', 'A6-A7'}
AvailableI2CBusIDs: [0]
AvailableSerialPortIDs: [1]
Libraries: {'MotorCarrier'}
Show all properties
mcObj =
MotorCarrier with properties:
SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')
encoder =
RotaryEncoder with properties:
Channel: 1
PulsesPerRevolution: 3
Encoding: 'X4'
arduinoObj =
arduino with properties:
7-33
7 Motor Carrier Functions
Port: '/dev/ttyACM0'
Board: 'Nano33IoT'
AvailablePins: {'D0-D13', 'A0-A7'}
AvailableDigitalPins: {'D0-D13', 'A0-A7'}
AvailablePWMPins: {'D2-D6', 'D9-D10'}
AvailableAnalogPins: {'A0-A3', 'A6-A7'}
AvailableI2CBusIDs: [0]
AvailableSerialPortIDs: [1]
Libraries: {'MotorCarrier'}
Show all properties
mcObj = motorCarrier(arduinoObj)
mcObj =
MotorCarrier with properties:
SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')
Create a connection to the rotary encoder on channel 2, and specify the pulses per revolution.
encoder = rotaryEncoder(mcObj,2,4)
encoder =
RotaryEncoder with properties:
Channel: 2
PulsesPerRevolution: 4
Encoding: 'X4'
Version History
Introduced in R2020a
See Also
arduino | dcmotor | motorCarrier | pidMotor | servo
7-34
readCount
readCount
Read current count value from encoder connected to MKR Motor Carrier or Nano Motor Carrier
Syntax
[count] = readCount(encoder)
[count,timestamp] = readCount(encoder)
[count] = readCount(encoder,'Reset',reset)
[count,timestamp] = readCount(encoder,'Reset',reset)
Description
[count] = readCount(encoder) returns the current count value from the encoder.
[count,timestamp] = readCount(encoder) returns the current count value from the encoder
along with the timestamp in datetime format.
Examples
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);
encoder = rotaryEncoder(mcObj,1);
Read the current absolute count value of encoder register of Nano Motor Carrier.
count = readCount(encoder);
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);
7-35
7 Motor Carrier Functions
encoder = rotaryEncoder(mcObj,1);
Read the current absolute count value of encoder register of Nano Motor Carrier.
[count,timestamp] = readCount(encoder);
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);
encoder = rotaryEncoder(mcObj,1);
Read the current absolute count value of encoder register of Nano Motor Carrier.
count = readCount(encoder,'Reset',true);
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);
encoder = rotaryEncoder(mcObj,1);
Read the current absolute count value of encoder register of Nano Motor Carrier.
[count,timestamp] = readCount(encoder,'Reset',true);
Input Arguments
encoder — Rotary encoder connection
object
Connection to the rotary encoder on MKR Motor Carrier or Nano Motor Carrier, specified as an
object.
Flag to reset count value to 0 after each read operation, specified as the comma-separated pair
consisting of 'Reset' and either false or true. This is an optional argument.
Data Types: logical
7-36
readCount
Output Arguments
count — Current count value of the encoder
double
Version History
Introduced in R2020a
See Also
motorCarrier | rotaryEncoder | readSpeed | resetCount
7-37
7 Motor Carrier Functions
readSpeed
Read current rotational speed of motor from rotary encoder
Syntax
[speed] = readSpeed(encoder)
[speed,timestamp] = readSpeed(encoder)
Description
[speed] = readSpeed(encoder) returns the current rotational speed measured by the rotary
encoder in revolutions per minute (RPM).
Examples
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);
encoder = rotaryEncoder(mcObj,1);
speed = readSpeed(encoder);
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);
encoder = rotaryEncoder(mcObj,1);
[speed,timestamp] = readSpeed(encoder);
7-38
readSpeed
Input Arguments
encoder — Rotary encoder connection
object
Connection to the rotary encoder on MKR Motor Carrier or Nano Motor Carrier, specified as an
object.
Output Arguments
speed — Current rotational speed
double
Current rotational speed as measured by the rotary encoder in revolutions per minute (RPM).
Data Types: double
Time at which MATLAB reads the speed data from the board.
Data Types: datetime
Version History
Introduced in R2020a
See Also
motorCarrier | rotaryEncoder | readCount | resetCount
7-39
7 Motor Carrier Functions
resetCount
Set encoder count value to zero or specified value
Syntax
resetCount(encoder)
resetCount(encoder,count)
Description
resetCount(encoder) resets the count value of the rotary encoder to zero.
resetCount(encoder,count) resets the count value of the rotary encoder to a specified value.
Examples
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);
encoder = rotaryEncoder(mcObj,1);
resetCount(encoder);
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);
encoder = rotaryEncoder(mcObj,1);
resetCount(encoder,10);
7-40
resetCount
Input Arguments
encoder — Rotary encoder connection
object
Connection to the rotary encoder on MKR Motor Carrier or Nano Motor Carrier, specified as an
object.
Version History
Introduced in R2020a
See Also
motorCarrier | rotaryEncoder | readCount | readSpeed
7-41
7 Motor Carrier Functions
servo
Connection to servo motor on Arduino MKR Motor Carrier or Nano Motor Carrier
Description
This object represents a connection to a servo motor with the specified motor number on an MKR
Motor Carrier or a Nano Motor Carrier. You can control the servo motor using the functions listed
under “Object Functions” on page 7-43.
Creation
Syntax
servoObj = servo(mcObj,motornumber)
Description
Input Arguments
Connection to the MKR Motor Carrier or Nano Motor Carrier, specified as an object.
Example: servoObj = servo(mcObj,1) creates a servo motor connection at motor number 1
connected to Servo1.
Servo motor number where the motor is connected on an MKR Motor Carrier or Nano Motor Carrier,
specified as a number.
Properties
MotorNumber — Servo motor number
numeric
Servo motor number where the motor is connected on an MKR Motor Carrier or Nano Motor Carrier,
specified as a number.
Example:
7-42
servo
>> servoObj.MotorNumber
ans =
1
Object Functions
Use these object functions to create a connection to the servo motor.
writePosition Write position of servo motor connected to MKR Motor Carrier or Nano Motor Carrier
Examples
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier')
arduinoObj =
arduino with properties:
Port: '/dev/ttyACM0'
Board: 'Nano33IoT'
AvailablePins: {'D0-D13', 'A0-A7'}
AvailableDigitalPins: {'D0-D13', 'A0-A7'}
AvailablePWMPins: {'D2-D6', 'D9-D10'}
AvailableAnalogPins: {'A0-A3', 'A6-A7'}
AvailableI2CBusIDs: [0]
AvailableSerialPortIDs: [1]
Libraries: {'MotorCarrier'}
Show all properties
mcObj = motorCarrier(arduinoObj)
mcObj =
MotorCarrier with properties:
SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')
servoObj = servo(mcObj,4)
servoObj =
Servo with properties:
MotorNumber: 4 (Servo4)
7-43
7 Motor Carrier Functions
Version History
Introduced in R2020a
See Also
arduino | dcmotor | motorCarrier | pidMotor | rotaryEncoder
7-44
writePosition
writePosition
Write position of servo motor connected to MKR Motor Carrier or Nano Motor Carrier
Syntax
writePosition(servoObj,position)
Description
writePosition(servoObj,position) sets the servo motor position to the specified value.
Examples
arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);
servoObj = servo(mcObj,1)
servoObj =
Servo with properties:
MotorNumber: 1 (Servo1)
writePosition(servoObj,0.5);
Input Arguments
servoObj — Servo object
object
Connection to the servo motor on MKR Motor Carrier or Nano Motor Carrier, specified as an object.
Position of servo motor shaft specified as a number representing the normalized angle between 0 to 1
with 1 corresponding to 180 degrees or pi radians. 0 corresponds to the minimum angle of the motor
shaft, 0 degrees or 0 radians
7-45
7 Motor Carrier Functions
Version History
Introduced in R2020a
See Also
arduino | motorCarrier | servo
7-46
8
bno055
Connect to BNO055 sensor on Arduino hardware I2C bus
Description
The bno055 object reads acceleration, angular velocity, magnetic field, and orientation in the
specified mode of the BNO055 inertial measurement unit (IMU) sensor connected to the Arduino
hardware. The BNO055 is a 9 degree of freedom (DOF) inertial measurement unit (IMU) used to read
acceleration, angular velocity, and magnetic field in all three dimensions.
The bno0055 object represents a connection to the device on the Arduino hardware I2C bus. Attach
an BNO055 sensor to the I2C pins on the Arduino hardware. You can read the data from your sensor
in MATLAB using the object functions.
Before you use the bno055 object, create an arduino object with the I2C library. For more
information, see “Connect to Arduino Hardware”.
Creation
Syntax
imu = bno055(a)
imu = bno055(a,Name,Value)
Description
imu = bno055(a) creates a BNO055 sensor object with default property values. The object
represents the connection to the sensor on the Arduino hardware, a.
imu = bno055(a,Name,Value) creates a BNO055 sensor object with properties using one or more
Name,Value pair arguments.
Input Arguments
Connection to the Arduino hardware created using arduino. Ensure the arduino object is created
with the 'I2C' library.
Example: imu = bno055(a) creates a connection to the BNO055 sensor on the Arduino object, a.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
8-2
bno055
Configure the BNO055 sensor to output sensor data in NDOF or AMG mode.
When you set the operating mode to ndof, the sensor operates in NDOF. In this mode you can read
calibrated values of acceleration, angular velocity and magnetic field along with Euler angles, and
calibration status of the sensor.
When you set operating mode to amg, the sensor operates in Accelerometer Magnetometer
Gyroscope (AMG) mode. In this mode you can read raw values of acceleration, angular velocity and
magnetic field.
Example: imu = bno055(a,'OperatingMode', ‘ndof’);
Data Types: string
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
BNO055 are connected to the same hardware board. BNO055 can have two I2C addresses depending
on the logic level on pin COM3 of the sensor.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Properties
Note Except for TimeFormat, all the other properties are non-tunable, which means you cannot
change their values once the object is locked. Objects are locked when you call the read function,
and the release function unlocks them. If a property is tunable, you can change its value at any
time.
8-3
8 Unified BNO055 Functions
The rate in Samples/s at which data is read from the sensor. In ndof mode, an internal fusion
algorithm configures the bandwidth and ODR of the sensor with values from the data sheet. Hence
SampleRate is fixed to 100. However, in amg mode SampleRate can be varied.
Tunable: No
Data Types: double
Number of samples read from the sensor in a single execution of the read function.
Tunable: No
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
8-4
bno055
Tunable: No
Data Types: character vector | string
Samples read from the first read. When you release the object, SamplesRead is set to 0.
Data Types: double
Samples available in the host buffer. The data read from the sensor is stored in the MATLAB buffer.
SamplesAvailable property shows the number of SamplesAvailable in this host buffer. When
you release the object, SamplesAvailable is set to 0. When the ReadMode of sensor is set as
latest, SamplesAvailable will always be 0.
Data Types: double
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
When the OutputFormat is set to matrix, the data is returned as matrices of acceleration, angular
velocity, magnetic field, and time stamps. The units for the sensor readings are the same as the
timetable format. The size of each matrix is N-by-3.
8-5
8 Unified BNO055 Functions
N is the number of samples per read specified by SamplesPerRead. The three columns of each field
represent the measurements in x, y, and z axes.
Tunable: No
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Tunable: Yes
Data Types: character vector | string
Examples
Create Connection to BNO055 in NDOF Mode
imu =
OperatingMode: "ndof"
I2CAddress: 40 ("0x28")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"
Create the sensor object with additional properties specified as name-value pairs.
clear imu;
imu = bno055(a,'OperatingMode','ndof','SamplesPerRead',5,'ReadMode','oldest')
imu =
8-6
bno055
OperatingMode: "ndof"
I2CAddress: 40 ("0x28")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"
imu =
OperatingMode: "amg"
I2CAddress: 40 ("0x28")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"
Create the sensor object with additional properties specified as name-value pairs.
clear imu;
imu = bno055(a,'OperatingMode','amg','SampleRate',50,'SamplesPerRead',5,'ReadMode','oldest')
imu =
OperatingMode: "amg"
I2CAddress: 40 ("0x28")
Bus: 0
SCLPin: "A5"
8-7
8 Unified BNO055 Functions
SDAPin: "A4"
SampleRate: 50 (Samples/s)
SamplesPerRead: 5
ReadMode: "oldest"
SamplesRead: 0
SamplesAvailable: 0
Object Functions
Use these functions to read the sensor data:
info Read output data rate and bandwidth setting of BNO055 sensor
read Read acceleration, angular velocity, magnetic field, time, and overrun data
from BNO055 sensor
readAcceleration Read one sample of acceleration from BNO055 sensor
readAngularVelocity Read one sample of angular velocity from BNO055 sensor
readCalibrationStatus Read calibration status of BNO055 sensor
readMagneticField Read one sample of magnetic field strength from BNO055 sensor
readOrientation Read orientation data from BNO055 sensor
release Release the BNO055 object
flush Flush the host buffer for BNO055 sensor
More About
Code Generation Using MATLAB Function Block
• Use bno055 in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• In the ndof operating mode, ensure you calibrate the sensor before reading values from the
sensor. For steps to calibrate the sensor, see “Calibrate BNO055 Sensors”.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
• The property OutputFormat is always set to matrix.
• The property TimeFormat is always set to duration.
• The property SamplesAvailable is not accessible from sensor object.
• The default value of I2C address will be taken as 0x28. Specify I2C address if the sensor has a
different I2C address. The possible values of I2C Addresses are mentioned in the table under
I2Caddress section in this page.
Version History
Introduced in R2020a
See Also
lsm9ds1 | mpu6050 | mpu9250
8-8
read
read
Read acceleration, angular velocity, magnetic field, time, and overrun data from BNO055 sensor
Syntax
[sensorReadings,overrun] = read(bno055)
[accelReadings, gyroReadings, magReadings, timeStamps, overrun] = read(
bno055)
[accelReadings, gyroReadings, magReadings, orientationReadings,timeStamps,
overrun] = read(bno055)
Description
[sensorReadings,overrun] = read(bno055) returns the acceleration, magnetic field, angular
velocity, and overrun data from BNO055 in the timetable format. The number of samples depends
on the SamplesPerRead value specified while creating the sensor object. These output arguments
are returned only when the output format is set to timetable.
Examples
Read Data from Sensor in NDOF Mode as a Timetable
Calibrate the sensor using steps mentioned in “Calibrate BNO055 Sensors”. Read five samples of
sensor data in datetime format.
sensorReadings = read(imu)
sensorReadings =
5×4 timetable
8-9
8 Unified BNO055 Functions
imu = bno055(a,'OperatingMode','amg','SampleRate',100,'SamplesPerRead',5)
sensorReadings = read(imu)
sensorReadings =
5×3 timetable
imu = bno055(a,’SamplesPerRead’,5,’OutputFormat’,’matrix’,’OperatingMode’,’ndof’)
Calibrate the sensor using steps mentioned in “Calibrate BNO055 Sensors”. Read five samples of
sensor data as a matrix.
accelReadings =
8-10
read
gyroReadings =
0 0.0098 -0.0011
-0.0022 0.0055 0.0011
0.0022 -0.0022 0
-0.0011 -0.0022 0.0011
-0.0022 -0.0022 -0.0011
magReadings =
orientationReadings =
0 -0.0338 0.0022
0 -0.0338 0.0022
0 -0.0338 0.0022
0 -0.0338 0.0022
0 -0.0338 0.0022
timeStamps =
31-Jul-2020 19:10:07.196
31-Jul-2020 19:10:07.206
31-Jul-2020 19:10:07.216
31-Jul-2020 19:10:07.226
31-Jul-2020 19:10:07.236
overrun =
10
8-11
8 Unified BNO055 Functions
accelReadings =
gyroReadings =
0 0.0098 -0.0011
-0.0022 0.0055 0.0011
0.0022 -0.0022 0
-0.0011 -0.0022 0.0011
-0.0022 -0.0022 -0.0011
magReadings =
timeStamps =
31-Jul-2020 19:10:07.196
31-Jul-2020 19:10:07.206
31-Jul-2020 19:10:07.216
31-Jul-2020 19:10:07.226
31-Jul-2020 19:10:07.236
overrun =
10
Input Arguments
bno055 — BNO055 sensor object
Output Arguments
sensorReadings — Sensor data read when output format is set to timetable
Acceleration, angular velocity, and magnetic field data read from the sensor when the output format
is set to timetable. In the ndof operating mode, the orientation values of the sensor is also
returned. The timetable returned has the following fields:
8-12
read
overrun — Overrun
The discarded number of data samples between the previous read and the current read is the
overrun. The overrun is zero when ReadMode is set to oldest.
Data Types: single | double
accelReadings — Acceleration read from sensor when output format is set to matrix
N-by-3 matrix
Acceleration in m/s2 read from the sensor on x, y and z axis. N is the number of samples in the
current frame.
Data Types: double
gyroReadings — Angular velocity read from sensor when output format is set to matrix
N-by-3 matrix
Angular velocity in rad/s read from the sensor on x, y and z axis. N is the number of samples in the
current frame.
Data Types: double
magReadings — Magnetic field read from sensor when output format is set to matrix
N-by-3 matrix
Magnetic field in µT (microtesla) read from the sensor on x, y and z axis. N is the number of samples
in the current frame.
Data Types: double
Orientation in radians read from the sensor along x, y and z axis. N is the number of samples in the
current frame.
Data Types: double
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the first call of the read function or the
last execution of the release function.
8-13
8 Unified BNO055 Functions
More About
Code Generation Using MATLAB Function Block
• Use read in a MATLAB Function block with the Simulink Support Package for Arduino Hardware
to generate code that can be deployed on Arduino Hardware.
• read does not return overrun.
• read always returns matrices.
Version History
Introduced in R2019a
See Also
bno055 | flush | info | readAcceleration | readAngularVelocity |
readCalibrationStatus | readMagneticField | readOrientation | release
Topics
“Calibrate BNO055 Sensors”
8-14
readAcceleration
readAcceleration
Read one sample of acceleration from BNO055 sensor
Syntax
[accelReadings,timestamp] = readAcceleration(bno055)
Description
[accelReadings,timestamp] = readAcceleration(bno055) returns acceleration along x, y,
and z axes of the BNO055 sensor as a 3-by-1 vector in units of m/s2 along with the timestamp. In
ndof mode, the elements of the vector represent calibrated values, whereas in amg mode, the
elements represent raw values.
Examples
Read Acceleration Data from Sensor in NDOF Mode
accelReadings = 1×3
timestamp = datetime
21-Jul-2020 15:47:59.835
8-15
8 Unified BNO055 Functions
imu = bno055(a,'OperatingMode','amg');
accelReadings = readAcceleration(imu)
accelReadings =
Input Arguments
bno055 — BNO055 sensor object
BNO055 sensor object created in either ndof or amg operating mode with the default or specified
properties.
Output Arguments
accelReadings — Value read from the sensor
The acceleration values along x, y, and z axes of the sensor as a 3-by-1 vector. In ndof mode, the
elements of the vector represent calibrated values, whereas in amg mode, the elements represent raw
values.
timestamp — Timestamp
datetime
The time at which MATLAB receives acceleration data from the sensor, specified as a datetime.
More About
Code Generation Using MATLAB Function Block
• Use readAcceleration in a MATLAB Function block with the Simulink Support Package for
Arduino Hardware to generate code that can be deployed on Arduino Hardware.
• Timestamp returned is always in seconds.
• readAcceleration returns raw values of the acceleration if the sensor is not calibrated. Ensure
you calibrate the sensor before using it in the ndof operating mode. See “Calibrate BNO055
Sensors” for the steps.
Version History
Introduced in R2019a
See Also
bno055 | flush | info | read | readAngularVelocity | readCalibrationStatus |
readMagneticField | readOrientation | release
8-16
readMagneticField
readMagneticField
Read one sample of magnetic field strength from BNO055 sensor
Syntax
[magReadings,timestamp] = readMagneticField(bno055)
Description
[magReadings,timestamp] = readMagneticField(bno055) returns the magnetic field along
x, y, and z axes of the BNO055 sensor as a 3-by-1 vector read from the sensor in units of µT
(microtesla) along with the timestamp. In ndof mode, the elements of the vector represent
calibrated values, whereas in amg mode, the elements represent raw values.
Examples
Read Magnetic Field Strength from Sensor in NDOF Mode
magReadings = 3×1
timestamp = datetime
21-Jul-2020 15:00:24.753
8-17
8 Unified BNO055 Functions
imu = bno055(a,'OperatingMode','amg');
[magReadings,timestamp] = readMagneticField(imu)
magReadings =
timestamp = datetime
21-Jul-2020 15:00:24.753
Input Arguments
bno055 — BNO055 sensor object
BNO055 sensor object created in either ndof or amg operating mode with the default or specified
properties.
Output Arguments
magReadings — Value read from the sensor
The magnetic field values along x, y, and z axes of the sensor as a 3-by-1 vector. In ndof mode, the
elements of the vector represent calibrated values, whereas in amg mode, the elements represent raw
values.
timestamp — Timestamp
datetime
The time at which MATLAB receives magnetic field data from the sensor, specified as a datetime.
More About
Code Generation Using MATLAB Function Block
• Use readMagneticField in a MATLAB Function block with the Simulink Support Package for
Arduino Hardware to generate code that can be deployed on Arduino Hardware.
• Timestamp returned is always in seconds.
• readMagneticField returns raw values of the magnetic field strength if the sensor is not
calibrated. Ensure you calibrate the sensor before using it in the ndof operating mode. See
“Calibrate BNO055 Sensors” for the steps.
Version History
Introduced in R2019a
8-18
readMagneticField
See Also
bno055 | flush | info | read | readAcceleration | readAngularVelocity |
readCalibrationStatus | readOrientation | release
8-19
8 Unified BNO055 Functions
readAngularVelocity
Read one sample of angular velocity from BNO055 sensor
Syntax
[gyroReadings,timestamp] = readAngularVelocity(bno055)
Description
[gyroReadings,timestamp] = readAngularVelocity(bno055) returns angular velocity along
x, y, and z axes of the BNO055 sensor as a 3-by-1 vector in units of rad/s along with the timestamp.
In ndof mode, the elements of the vector represent calibrated values, whereas in amg mode, the
elements represent raw values.
Examples
Read Angular Velocity from Sensor in NDOF Mode
gyroReadings = 3×1
0.0011 0.0011 0
timestamp = datetime
21-Jul-2020 14:53:36.836
8-20
readAngularVelocity
imu = bno055(a,'OperatingMode','amg');
[gyroReadings,timestamp] = readAngularVelocity(imu)
gyroReadings = 3×1
timestamp = datetime
21-Jul-2020 14:53:36.836
Input Arguments
bno055 — BNO055 sensor object
BNO055 sensor object created in either ndof or amg operating mode with the default or specified
properties.
Output Arguments
gyroReadings — Value read from the sensor
The angular velocity values along x, y, and z axes of the sensor as a 3-by-1 vector. In ndof mode, the
elements of the vector represent calibrated values, whereas in amg mode, the elements represent raw
values.
timestamp — Timestamp
datetime
The time at which MATLAB receives angular velocity data from the sensor, specified as a datetime.
More About
Code Generation Using MATLAB Function Block
• Use readAngularVelocity in a MATLAB Function block with the Simulink Support Package for
Arduino Hardware to generate code that can be deployed on Arduino Hardware.
• Timestamp returned is always in seconds.
• readAngularVelocity returns raw values of the angular velocity if the sensor is not calibrated.
Ensure you calibrate the sensor before using it in the ndof operating mode. See “Calibrate
BNO055 Sensors” for the steps.
Version History
Introduced in R2019a
8-21
8 Unified BNO055 Functions
See Also
bno055 | flush | info | read | readAcceleration | readCalibrationStatus |
readMagneticField | readOrientation | release
8-22
readCalibrationStatus
readCalibrationStatus
Read calibration status of BNO055 sensor
Syntax
[status,timestamp] = readCalibrationStatus(bno055)
Description
[status,timestamp] = readCalibrationStatus(bno055) returns the calibration status of the
BNO055 sensor in NDOF operating mode. See “Calibrate BNO055 Sensors” for the steps to calibrate
the sensor.
Examples
Read Calibrated Status of Sensor
imu = bno055(a,'OperatingMode','ndof');
pause(50)
[status,timestamp] = readCalibrationStatus(imu)
status =
struct with fields:
System: "uncalibrated"
Accelerometer: "uncalibrated"
Gyroscope: "full"
Magnetometer: "uncalibrated"
timestamp = datetime
21-Jul-2020 08:09:45.785
Input Arguments
bno055 — BNO055 sensor object
BNO055 sensor object created in ndof operating mode with the default or specified properties.
8-23
8 Unified BNO055 Functions
Output Arguments
status — Calibration status
struct
Calibration status of the system, gyroscope, accelerometer, and magnetometer in the BNO055 sensor
specified as a structure array. The values as seen by sensor correspond to the calibration status of the
sensors. The values are in the range 0-3 .The table describes each of the values
timestamp — Timestamp
datetime
The time at which MATLAB receives the calibration status, specified as a datetime.
Data Types: datetime
More About
Code Generation Using MATLAB Function Block
• Use readCalibrationStatus in a MATLAB Function block with the Simulink Support Package
for Arduino Hardware to generate code that can be deployed on Arduino Hardware.
• Timestamp returned is always in seconds.
• The readCalibrationStatus returns integers that correspond the to the calibration status of
the sensor.
Version History
Introduced in R2019b
See Also
bno055 | flush | info | read | readAcceleration | readAngularVelocity |
readMagneticField | readOrientation | release
8-24
readOrientation
readOrientation
Read orientation data from BNO055 sensor
Syntax
[readVal,timestamp] = readOrientation(bno055)
Description
[readVal,timestamp] = readOrientation(bno055) returns the Euler angles that is the
azimuth, pitch and roll of the BNO055 sensor in ndof operating mode.
Examples
Read Orientation from Sensor
imu = bno055(a,'OperatingMode','ndof');
tic;
while (toc < 120)
[status,timestamp] = readCalibrationStatus(imu);
if strcmpi(status.System,'full') && strcmpi(status.Magnetometer,'full') && strcmpi(status.Acc
break; %System is calibrated proceed further
end
end
[readVal,timestamp] = readOrientation(imu)
readVal = 3×1
Input Arguments
bno055 — BNO055 sensor object
BNO055 sensor object created in the ndof operating mode with the default or specified properties.
8-25
8 Unified BNO055 Functions
Output Arguments
readVal — Orientation data
3-by-1 vector
The following illustration shows the default orientation of the x-, y-, and z- axes of the BNO055 sensor.
Orientation of the sensor, returned as a 3-by-1 vector. The elements of the vector represent the
orientation using three angular quantities in radians - azimuth (rotation around z- axis), roll (rotation
around y- axis), and pitch (rotation around x- axis) of the sensor.
timestamp — Timestamp
datetime
The time at which MATLAB receives the orientation from the sensor, specified as a datetime.
Data Types: datetime
8-26
readOrientation
More About
Code Generation Using MATLAB Function Block
• Use readOrientation in a MATLAB Function block with the Simulink Support Package for
Arduino Hardware to generate code that can be deployed on Arduino Hardware.
• readOrientation returns zeroes if the sensor is not calibrated. Ensure you calibrate the sensor
before using it in the ndof operating mode. See “Calibrate BNO055 Sensors” for the steps.
Version History
Introduced in R2019b
See Also
bno055 | flush | info | read | readAcceleration | readAngularVelocity |
readCalibrationStatus | readMagneticField | release
8-27
8 Unified BNO055 Functions
flush
Flush the host buffer for BNO055 sensor
Syntax
flush(bno055)
Description
flush(bno055) clears the buffers for BNO055 sensor and resets the start time.
Input Arguments
bno055 — BNO055 sensor object
More About
Code Generation Using MATLAB Function Block
• Use flush in a MATLAB Function block with the Simulink Support Package for Arduino Hardware
to generate code that can be deployed on Arduino Hardware.
• flush does not reset the start time.
Version History
Introduced in R2019a
See Also
bno055 | info | read | readAcceleration | readAngularVelocity | readCalibrationStatus
| readMagneticField | readOrientation | release
8-28
info
info
Read output data rate and bandwidth setting of BNO055 sensor
Syntax
SensorInfo = info(bno055)
Description
SensorInfo = info(bno055) returns the output data rate (ODR) and bandwidth of the BNO055
sensor in the amg operating mode.
Note In the ndof mode, an internal fusion algorithm configures the bandwidth and ODR of the
sensor with some values. Hence info cannot be used in ndof operating mode.
Examples
Read Info of Sensor
imu = bno055(a,'OperatingMode','amg','SampleRate',100,'Bus',1);
info(imu)
ans =
struct with fields:
AccelerometerBandwidth: 31.2500
GyroscopeBandwidth: 47
MagnetometerODR: 30
Input Arguments
bno055 — BNO055 sensor object
BNO055 sensor object created in the amg operating mode with the default or specified properties.
Output Arguments
SensorInfo — Sensor information
Sensor information such as acceleration and angular velocity bandwidth, and magnetic field output
data rate of the BNO055 sensor.
Data Types: struct
8-29
8 Unified BNO055 Functions
Version History
Introduced in R2019a
See Also
bno055 | flush | read | readAcceleration | readAngularVelocity |
readCalibrationStatus | readMagneticField | readOrientation | release
8-30
release
release
Release the BNO055 object
Syntax
release(bno055)
Description
release(bno055) stops the data collection from the BNO055 sensor, clears the buffer, and resets
the start time and sets the number of overrun samples to 0.
Input Arguments
bno055 — BNO055 sensor object
More About
Code Generation Using MATLAB Function Block
• Use release in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• release does not reset the start time.
Version History
Introduced in R2019a
See Also
bno055 | flush | info | read | readAcceleration | readAngularVelocity |
readCalibrationStatus | readMagneticField | readOrientation
8-31
9
lsm6ds3
Connect to LSM6DS3 sensor on Arduino hardware I2C bus
Description
The lsm6ds3 object reads acceleration, angular velocity, and temperature using the LSM6DS3
sensor connected to the I2C bus of the hardware. The LSM6DS3 is an inertial measurement unit
(IMU) used to read acceleration and angular velocity in all three dimensions. The LSM6DS3 also has
an embedded temperature sensor. Attach an LSM6DS3 sensor to the I2C pins on the hardware. You
can read the data from your sensor in MATLAB using the “Object Functions” on page 9-6.
Creation
Syntax
imu = lsm6ds3(a)
imu = lsm6ds3(a,Name,Value)
Description
imu = lsm6ds3(a,Name,Value) creates a sensor object with properties using one or more
Name,Value pair arguments.
Example: imu = lsm6ds3(a,'I2CAddress',0x6A);.
Input Arguments
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
9-2
lsm6ds3
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LSM6DS3 are connected to the same hardware board. LSM6DS3 can have two I2C addresses
depending on the logic level on pin SDO/SA0 of the sensor.
0x6A is the I2C address of the accelerometer and gyroscope of LSM6DS3 connected to Arduino
board.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Properties
Note The properties can also be used as name-value pair arguments while creating an lsm6ds3
object.
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LSM6DS3 are connected to the same hardware board. LSM6DS3 can have two I2C addresses
depending on the logic level on pin SDO/SA0 of the sensor.
9-3
9 LSMDS Functions — Alphabetical List
0x6A is the I2C address of the accelerometer and gyroscope of LSM6DS3 connected to Arduino
board.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Note Except for TimeFormat, all the other properties are non-tunable, which means you cannot
change their values once the object is locked. Objects are locked when you call the read function,
and the release function unlocks them. If a property is tunable, you can change its value at any
time.
Number of samples read from the sensor in a single execution of the read function.
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
9-4
lsm6ds3
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Samplesread property outputs the values of samples read so far by executing read function.
Samplesread is set to 0, when the object is created or when you release the object.
Data Types: double
Samples available in the host buffer. The data read from the sensor is stored in the MATLAB buffer.
SamplesAvailable property shows the number of SamplesAvailable in this host buffer. When
you release the object, SamplesAvailable is set to 0. When the ReadMode of sensor is set as
latest, SamplesAvailable will always be 0.
9-5
9 LSMDS Functions — Alphabetical List
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
When the OutputFormat is set to matrix, the data is returned as matrices of acceleration, angular
velocity, temperature, and time stamps. The units and size for the sensor readings are the same as
the timetable format.
N is the number of samples per read specified by SamplesPerRead. The three columns of each field
represent the measurements in x, y, and z axes.
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Object Functions
readAcceleration Read one sample of acceleration from sensor
readAngularVelocity Read one sample of angular velocity from sensor
readTemperature Read one sample of temperature from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
Examples
Create Connection to LSM6DS3 Sensor
9-6
lsm6ds3
imu = lsm6ds3(a)
imu =
Create a sensor object with additional properties specified as name-value pair arguments .
clear imu;
imu = lsm6ds3(a,'SampleRate',110,'SamplesPerRead',3,'ReadMode','oldest')
imu =
More About
Code Generation Using MATLAB Function Block
• Use lsm6ds3 in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
• The property OutputFormat is always set to matrix.
• The property TimeFormat is always set to duration.
• The property SamplesAvailable is not accessible from sensor object.
9-7
9 LSMDS Functions — Alphabetical List
• The default value of I2C address will be taken as 0x6A. Specify I2C address if the sensor has a
different I2C address. The possible values of I2C Addresses are mentioned in the table under
I2Caddress section in this page.
Version History
Introduced in R2021a
See Also
lsm6ds3h | lsm6dsl | lsm6dsm | lsm6dso | lsm6dsr | lsm303c
9-8
lsm6ds3h
lsm6ds3h
Connect to LSM6DS3H sensor on Arduino hardware I2C bus
Description
The lsm6ds3h object reads acceleration, angular velocity, and temperature using the LSM6DS3H
sensor connected to the I2C bus of the hardware. The LSM6DS3H is an inertial measurement unit
(IMU) used to read acceleration and angular velocity in all three dimensions. The LSM6DS3H also
has an embedded temperature sensor. Attach an LSM6DS3H sensor to the I2C pins on the hardware.
You can read the data from your sensor in MATLAB using the “Object Functions” on page 9-13.
Creation
Syntax
imu = lsm6ds3h(a)
imu = lsm6ds3h(a,Name,Value)
Description
imu = lsm6ds3h(a,Name,Value) creates a sensor object with properties using one or more
Name,Value pair arguments.
Example: imu = lsm6ds3h(a,'I2CAddress',0x6A);.
Input Arguments
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
9-9
9 LSMDS Functions — Alphabetical List
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LSM6DS3H are connected to the same hardware board. LSM6DS3H can have two I2C addresses
depending on the logic level on pin SDO/SA0 of the sensor.
0x6A is the I2C address of the accelerometer and gyroscope of LSM6DS3H connected to Arduino
board.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Properties
Note The properties can also be used as name-value pair arguments while creating an lsm6ds3h
object.
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LSM6DS3H are connected to the same hardware board. LSM6DS3H can have two I2C addresses
depending on the logic level on pin SDO/SA0 of the sensor.
9-10
lsm6ds3h
0x6A is the I2C address of the accelerometer and gyroscope of LSM6DS3H connected to Arduino
board.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Note Except for TimeFormat, all the other properties are non-tunable, which means you cannot
change their values once the object is locked. Objects are locked when you call the read function,
and the release function unlocks them. If a property is tunable, you can change its value at any
time.
Number of samples read from the sensor in a single execution of the read function.
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
9-11
9 LSMDS Functions — Alphabetical List
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Samplesread property outputs the values of samples read so far by executing read function.
Samplesread is set to 0, when the object is created or when you release the object.
Data Types: double
Samples available in the host buffer. The data read from the sensor is stored in the MATLAB buffer.
SamplesAvailable property shows the number of SamplesAvailable in this host buffer. When
you release the object, SamplesAvailable is set to 0. When the ReadMode of sensor is set as
latest, SamplesAvailable will always be 0.
9-12
lsm6ds3h
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
When the OutputFormat is set to matrix, the data is returned as matrices of acceleration, angular
velocity, and time stamps. The units for the sensor readings are the same as the timetable format.
N is the number of samples per read specified by SamplesPerRead. The three columns of each field
represent the measurements in x, y, and z axes.
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Object Functions
readAcceleration Read one sample of acceleration from sensor
readAngularVelocity Read one sample of angular velocity from sensor
readTemperature Read one sample of temperature from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
Examples
Create Connection to LSM6DS3H Sensor
9-13
9 LSMDS Functions — Alphabetical List
imu = lsm6dsh3(a)
imu =
Create a sensor object with additional properties specified as name-value pair arguments.
clear imu;
imu = lsm6dsh3(a,'SampleRate',110,'SamplesPerRead',3,'ReadMode','oldest')
imu =
More About
Code Generation Using MATLAB Function Block
• Use lsm6ds3h in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
• The property OutputFormat is always set to matrix.
• The property TimeFormat is always set to duration.
• The property SamplesAvailable is not accessible from sensor object.
9-14
lsm6ds3h
• The default value of I2C address will be taken as 0x6A. Specify I2C address if the sensor has a
different I2C address. The possible values of I2C Addresses are mentioned in the table under
I2Caddress section in this page.
Version History
Introduced in R2021a
See Also
lsm6ds3 | lsm6dsl | lsm6dsm | lsm6dso | lsm6dsr
9-15
9 LSMDS Functions — Alphabetical List
lsm6dsl
Connection to LSM6DSL sensor on Arduino hardware I2C bus
Description
The lsm6dsl object reads acceleration, angular velocity, and temperature using the LSM6DSL
sensor connected to the I2C bus of the hardware. The LSM6DSL is an inertial measurement unit
(IMU) used to read acceleration and angular velocity in all three dimensions. The LSM6DSL also has
an embedded temperature sensor. Attach an LSM6DSL sensor to the I2C pins on the hardware. You
can read the data from your sensor in MATLAB using the “Object Functions” on page 9-20.
Creation
Syntax
imu = lsm6dsl(a)
imu = lsm6dsl(a,Name,Value)
Description
imu = lsm6dsl(a,Name,Value) creates a sensor object with properties using one or more
Name,Value pair arguments.
Example: imu = lsm6dsl(a,'I2CAddress',0x6A);.
Input Arguments
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
9-16
lsm6dsl
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LSM6DSL are connected to the same hardware board. LSM6DSL can have two I2C addresses
depending on the logic level on pin SDO/SA0 of the sensor.
0x6A is the I2C address of the accelerometer and gyroscope of LSM6DSL connected to Arduino
board.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Properties
Note The properties can also be used as name-value pair arguments while creating an lsm6dsl
object.
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LSM6DSL are connected to the same hardware board. LSM6DSL can have two I2C addresses
depending on the logic level on pin SDO/SA0 of the sensor.
9-17
9 LSMDS Functions — Alphabetical List
0x6A is the I2C address of the accelerometer and gyroscope of LSM6DSL connected to Arduino
board.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Note Except for TimeFormat, all the other properties are non-tunable, which means you cannot
change their values once the object is locked. Objects are locked when you call the read function,
and the release function unlocks them. If a property is tunable, you can change its value at any
time.
Number of samples read from the sensor in a single execution of the read function.
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
9-18
lsm6dsl
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Samplesread property outputs the values of samples read so far by executing read function.
Samplesread is set to 0, when the object is created or when you release the object.
Data Types: double
Samples available in the host buffer. The data read from the sensor is stored in the MATLAB
buffer.SamplesAvailable property shows the number of SamplesAvailable in this host buffer.
When you release the object, SamplesAvailable is set to 0. When the ReadMode of sensor is set as
latest, SamplesAvailable will always be 0.
9-19
9 LSMDS Functions — Alphabetical List
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
When the OutputFormat is set to matrix, the data is returned as matrices of acceleration, angular
velocity, and time stamps. The units for the sensor readings are the same as the timetable format.
N is the number of samples per read specified by SamplesPerRead. The three columns of each field
represent the measurements in x, y, and z axes.
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Object Functions
readAcceleration Read one sample of acceleration from sensor
readAngularVelocity Read one sample of angular velocity from sensor
readTemperature Read one sample of temperature from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
Examples
Create Connection to LSM6DSL Sensor
9-20
lsm6dsl
imu = lsm6dsl(a)
imu =
Create a sensor object with additional properties specified as name-value pair arguments.
clear imu;
imu = lsm6dsl(a,'SampleRate',110,'SamplesPerRead',3,'ReadMode','oldest')
imu =
More About
Code Generation Using MATLAB Function Block
• Use lsm6dsl in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
• The property OutputFormat is always set to matrix.
• The property TimeFormat is always set to duration.
• The property SamplesAvailable is not accessible from sensor object.
9-21
9 LSMDS Functions — Alphabetical List
• The default value of I2C address will be taken as 0x6A. Specify I2C address if the sensor has a
different I2C address. The possible values of I2C Addresses are mentioned in the table under
I2Caddress section in this page.
Version History
Introduced in R2021a
See Also
lsm6ds3 | lsm6ds3h | lsm6dsm | lsm6dso | lsm6dsr
9-22
lsm6dsm
lsm6dsm
Connect to LSM6DSM sensor on Arduino hardware I2C bus
Description
The lsm6dsm object reads acceleration, angular velocity, and temperature using the LSM6DSM
sensor connected to the I2C bus of the hardware. The LSM6DSM is an inertial measurement unit
(IMU) used to read acceleration and angular velocity in all three dimensions. The LSM6DSM also has
an embedded temperature sensor. Attach an LSM6DSM sensor to the I2C pins on the hardware. You
can read the data from your sensor in MATLAB using the “Object Functions” on page 9-27.
Creation
Syntax
imu = lsm6dsm(a)
imu = lsm6dsm(a,Name,Value)
Description
imu = lsm6dsm(a,Name,Value) creates a sensor object with properties using one or more
Name,Value pair arguments.
Example: imu = lsm6dsm(a,'I2CAddress',0x6A);.
Input Arguments
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
9-23
9 LSMDS Functions — Alphabetical List
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LSM6DSM are connected to the same hardware board. LSM6DSM can have two I2C addresses
depending on the logic level on pin SDO/SA0 of the sensor.
0x6A is the I2C address of the accelerometer and gyroscope of LSM6DSM connected to Arduino
board.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Properties
Note The properties can also be used as name-value pair arguments while creating an lsm6dsm
object.
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LSM6DSM are connected to the same hardware board. LSM6DSM can have two I2C addresses
depending on the logic level on pin SDO/SA0 of the sensor.
9-24
lsm6dsm
0x6A is the I2C address of the accelerometer and gyroscope of LSM6DSM connected to Arduino
board.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Note Except for TimeFormat, all the other properties are non-tunable, which means you cannot
change their values once the object is locked. Objects are locked when you call the read function,
and the release function unlocks them. If a property is tunable, you can change its value at any
time.
Number of samples read from the sensor in a single execution of the read function.
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
9-25
9 LSMDS Functions — Alphabetical List
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Samplesread property outputs the values of samples read so far by executing read function.
Samplesread is set to 0, when the object is created or when you release the object.
Data Types: double
Samples available in the host buffer. The data read from the sensor is stored in the MATLAB buffer.
SamplesAvailable property shows the number of SamplesAvailable in this host buffer. When
you release the object, SamplesAvailable is set to 0. When the ReadMode of sensor is set as
latest, SamplesAvailable will always be 0.
9-26
lsm6dsm
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
When the OutputFormat is set to matrix, the data is returned as matrices of acceleration, angular
velocity, and time stamps. The units for the sensor readings are the same as the timetable format.
N is the number of samples per read specified by SamplesPerRead. The three columns of each field
represent the measurements in x, y, and z axes.
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Object Functions
readAcceleration Read one sample of acceleration from sensor
readAngularVelocity Read one sample of angular velocity from sensor
readTemperature Read one sample of temperature from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
Examples
Create Connection to LSM6DSM Sensor
9-27
9 LSMDS Functions — Alphabetical List
imu = lsm6dsm(a)
imu =
Create a sensor object with additional properties specified as name-value pair arguments.
clear imu;
imu = lsm6dsm(a,'SampleRate',110,'SamplesPerRead',3,'ReadMode','oldest')
imu =
More About
Code Generation Using MATLAB Function Block
• Use lsm6dsm in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
• The property OutputFormat is always set to matrix.
• The property TimeFormat is always set to duration.
• The property SamplesAvailable is not accessible from sensor object.
9-28
lsm6dsm
• The default value of I2C address will be taken as 0x6A. Specify I2C address if the sensor has a
different I2C address. The possible values of I2C Addresses are mentioned in the table under
I2Caddress section in this page.
Version History
Introduced in R2021a
See Also
lsm6ds3 | lsm6ds3h | lsm6dso | lsm6dsr
9-29
9 LSMDS Functions — Alphabetical List
lsm6dso
Connect to LSM6DSO sensor on Arduino hardware I2C bus
Description
The lsm6dso object reads acceleration, angular velocity, and temperature using the LSM6DSO
sensor connected to the I2C bus of the hardware. The LSM6DSO is an inertial measurement unit
(IMU) used to read acceleration and angular velocity in all three dimensions. The LSM6DSO also has
an embedded temperature sensor. Attach an LSM6DSO sensor to the I2C pins on the hardware. You
can read the data from your sensor in MATLAB using the “Object Functions” on page 9-34.
Creation
Syntax
imu = lsm6dso(a)
imu = lsm6dso(a,Name,Value)
Description
imu = lsm6dso(a,Name,Value) creates a sensor object with properties using one or more
Name,Value pair arguments.
Example: imu = lsm6dso(a,'I2CAddress',0x6A);.
Input Arguments
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
9-30
lsm6dso
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LSM6DSO are connected to the same hardware board. LSM6DSO can have two I2C addresses
depending on the logic level on pin SDO/SA0 of the sensor.
0x6A is the I2C address of the accelerometer and gyroscope of LSM6DSO connected to Arduino
board.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Properties
Note The properties can also be used as name-value pair arguments while creating an lsm6dso
object.
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LSM6DSO are connected to the same hardware board. LSM6DSO can have two I2C addresses
depending on the logic level on pin SDO/SA0 of the sensor.
9-31
9 LSMDS Functions — Alphabetical List
0x6A is the I2C address of the accelerometer and gyroscope of LSM6DSO connected to Arduino
board.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Note Except for TimeFormat, all the other properties are non-tunable, which means you cannot
change their values once the object is locked. Objects are locked when you call the read function,
and the release function unlocks them. If a property is tunable, you can change its value at any
time.
Number of samples read from the sensor in a single execution of the read function.
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
9-32
lsm6dso
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Samplesread property outputs the values of samples read so far by executing read function.
Samplesread is set to 0, when the object is created or when you release the object.
Data Types: double
Samples available in the host buffer. The data read from the sensor is stored in the MATLAB buffer.
SamplesAvailable property shows the number of SamplesAvailable in this host buffer. When
you release the object, SamplesAvailable is set to 0. When the ReadMode of sensor is set as
latest, SamplesAvailable will always be 0.
9-33
9 LSMDS Functions — Alphabetical List
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
When the OutputFormat is set to matrix, the data is returned as matrices of acceleration, angular
velocity, and time stamps. The units for the sensor readings are the same as the timetable format.
N is the number of samples per read specified by SamplesPerRead. The three columns of each field
represent the measurements in x, y, and z axes.
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Object Functions
readAcceleration Read one sample of acceleration from sensor
readAngularVelocity Read one sample of angular velocity from sensor
readTemperature Read one sample of temperature from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
Examples
Create Connection to LSM6DSO Sensor
9-34
lsm6dso
imu = lsm6dso(a)
imu =
Create a sensor object with additional properties specified as name-value pair arguments.
clear imu;
imu = lsm6dso(a,'SampleRate',110,'SamplesPerRead',3,'ReadMode','oldest')
imu =
More About
Code Generation Using MATLAB Function Block
• Use lsm6dso in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
• The property OutputFormat is always set to matrix.
• The property TimeFormat is always set to duration.
• The property SamplesAvailable is not accessible from sensor object.
9-35
9 LSMDS Functions — Alphabetical List
• The default value of I2C address will be taken as 0x6A. Specify I2C address if the sensor has a
different I2C address. The possible values of I2C Addresses are mentioned in the table under
I2Caddress section in this page.
Version History
Introduced in R2021a
See Also
lsm6ds3 | lsm6ds3h | lsm6dsm | lsm6dsr
9-36
lsm6dsr
lsm6dsr
Connect to LSM6DSR sensor on Arduino hardware I2C bus
Description
The lsm6dsr object reads acceleration, angular velocity, and temperature using the LSM6DSR
sensor connected to the I2C bus of the hardware. The LSM6DSR is an inertial measurement unit
(IMU) used to read acceleration and angular velocity in all three dimensions. The LSM6DSR also has
an embedded temperature sensor. Attach an LSM6DSR sensor to the I2C pins on the hardware. You
can read the data from your sensor in MATLAB using the “Object Functions” on page 9-41.
Creation
Syntax
imu = lsm6dsr(a)
imu = lsm6dsr(a,Name,Value)
Description
imu = lsm6dsr(a,Name,Value) creates a sensor object with properties using one or more
Name,Value pair arguments.
Example: imu = lsm6dsr(a,'I2CAddress',0x6A);.
Input Arguments
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
9-37
9 LSMDS Functions — Alphabetical List
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LSM6DSR are connected to the same hardware board. LSM6DSR can have two I2C addresses
depending on the logic level on pin SDO/SA0 of the sensor.
0x6A is the I2C address of the accelerometer and gyroscope of LSM6DSR connected to Arduino
board.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Properties
Note The properties can also be used as name-value pair arguments while creating an lsm6dsr
object.
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LSM6DSR are connected to the same hardware board. LSM6DSR can have two I2C addresses
depending on the logic level on pin SDO/SA0 of the sensor.
9-38
lsm6dsr
0x6A is the I2C address of the accelerometer and gyroscope of LSM6DSR connected to Arduino
board.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Note Except for TimeFormat, all the other properties are non-tunable, which means you cannot
change their values once the object is locked. Objects are locked when you call the read function,
and the release function unlocks them. If a property is tunable, you can change its value at any
time.
Number of samples read from the sensor in a single execution of the read function.
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
9-39
9 LSMDS Functions — Alphabetical List
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Samplesread property outputs the values of samples read so far by executing read function.
Samplesread is set to 0, when the object is created or when you release the object.
Data Types: double
Samples available in the host buffer. The data read from the sensor is stored in the MATLAB
buffer.SamplesAvailable property shows the number of SamplesAvailable in this host buffer.
When you release the object, SamplesAvailable is set to 0. When the ReadMode of sensor is set as
latest, SamplesAvailable will always be 0.
9-40
lsm6dsr
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
When the OutputFormat is set to matrix, the data is returned as matrices of acceleration, angular
velocity, and time stamps. The units for the sensor readings are the same as the timetable format.
N is the number of samples per read specified by SamplesPerRead. The three columns of each field
represent the measurements in x, y, and z axes.
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Object Functions
readAcceleration Read one sample of acceleration from sensor
readAngularVelocity Read one sample of angular velocity from sensor
readTemperature Read one sample of temperature from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
Examples
Create Connection to LSM6DSR Sensor
9-41
9 LSMDS Functions — Alphabetical List
imu = lsm6dsr(a)
imu =
Create a sensor object with additional properties specified as name-value pair arguments.
clear imu;
imu = lsm6dsr(a,'SampleRate',110,'SamplesPerRead',3,'ReadMode','oldest')
imu =
More About
Code Generation Using MATLAB Function Block
• Use lsm6dsr in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
• The property OutputFormat is always set to matrix.
• The property TimeFormat is always set to duration.
• The property SamplesAvailable is not accessible from sensor object.
9-42
lsm6dsr
• The default value of I2C address will be taken as 0x6A. Specify I2C address if the sensor has a
different I2C address. The possible values of I2C Addresses are mentioned in the table under
I2Caddress section in this page.
Version History
Introduced in R2021a
See Also
lsm6ds3 | lsm6ds3h | lsm6dsm | lsm6dso
9-43
9 LSMDS Functions — Alphabetical List
hts221
Connect to HTS221 sensor on Arduino hardware I2C bus
Description
The hts221 object reads relative humidity and ambient temperature using the HTS221 sensor
connected to the I2C bus of the Arduino hardware. HTS221 is used to read relative humidity. The
HTS221 also has an embedded temperature sensor. Attach the HTS221 sensor to the I2C pins on the
hardware. You can read the data from the sensor in MATLAB using the “Object Functions” on page 9-
47.
Creation
Syntax
humiditySensor = hts221(a)
humiditySensor = hts221(a,Name,Value)
Description
Input Arguments
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
9-44
hts221
Properties
Note The properties can also be used as name-value pair arguments while creating an hts221
object.
Note Except for TimeFormat, all the other properties are non-tunable, which means you cannot
change their values once the object is locked. Objects are locked when you call the read function,
and the release function unlocks them. If a property is tunable, you can change its value at any
time.
Number of samples read from the sensor in a single execution of the read function.
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
9-45
9 LSMDS Functions — Alphabetical List
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Samplesread property outputs the values of samples read so far by executing read function.
Samplesread is set to 0, when the object is created or when you release the object.
Data Types: double
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
9-46
hts221
When the OutputFormat is set to matrix, the data is returned as matrices of humidity, temperature,
and time stamps. The units for the sensor readings are the same as the timetable format.
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Object Functions
readHumidity Read one sample of relative humidity data from the sensor
readTemperature Read one sample of temperature from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
Examples
Create Connection to HTS221 Sensor
humiditySensor = hts221(a)
humiditySensor =
I2CAddress: 95 ("0x5F")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"
9-47
9 LSMDS Functions — Alphabetical List
SamplesAvailable: 0
Show all properties all functions
Create a sensor object with additional properties specified as name-value pair arguments.
clear humiditySensor;
humiditySensor = hts221(a,'SampleRate',50,'SamplesPerRead',5,'ReadMode','oldest')
humiditySensor =
I2CAddress: 95 ("0x5F")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"
SampleRate: 50 (Samples/s)
SamplesPerRead: 5
ReadMode: 'oldest'
SamplesRead: 0
SamplesAvailable: 0
More About
Code Generation Using MATLAB Function Block
• Use hts221 in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
• The property OutputFormat is always set to matrix.
• The property TimeFormat is always set to duration.
• The property SamplesAvailable is not accessible from sensor object.
Version History
Introduced in R2021a
See Also
lps22hb
9-48
lps22hb
lps22hb
Connect to LPS22HB sensor on Arduino hardware I2C bus
Description
The lps22hb object reads barometric air pressure and ambient temperature using the LPS22HB
sensor connected to the I2C bus of the Arduino hardware. LPS22HB is used to read barometric air
pressure. The LPS22HB also has an embedded temperature sensor. Attach the LPS22HB sensor to
the I2C pins on the hardware. You can read the data from the sensor in MATLAB using the “Object
Functions” on page 9-53.
Creation
Syntax
pressureSensor = lps22hb(a)
pressureSensor = lps22hb(a,Name,Value)
Description
Input Arguments
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
9-49
9 LSMDS Functions — Alphabetical List
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LPS22HB are connected to the same hardware board. LPS22HB can have two I2C addresses
depending on the logic level on pin SA0 of the sensor.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Properties
Note The properties can also be used as name-value pair arguments while creating an lps22hb
object.
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
LPS22HB are connected to the same hardware board. LPS22HB can have two I2C addresses
depending on the logic level on pin SA0 of the sensor.
9-50
lps22hb
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Note Except for TimeFormat, all the other properties are non-tunable, which means you cannot
change their values once the object is locked. Objects are locked when you call the read function,
and the release function unlocks them. If a property is tunable, you can change its value at any
time.
Number of samples read from the sensor in a single execution of the read function.
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
9-51
9 LSMDS Functions — Alphabetical List
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Samplesread property outputs the values of samples read so far by executing read function.
Samplesread is set to 0, when the object is created or when you release the object.
Data Types: double
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
9-52
lps22hb
When the OutputFormat is set to matrix, the data is returned as matrices of pressure,
temperature, and time stamps. The units for the sensor readings are the same as the timetable
format.
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Object Functions
readPressure Read one sample of barometric air pressure data from the sensor
readTemperature Read one sample of temperature from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
Examples
Create Connection to LPS22HB Sensor
pressureSensor = lps22hb(a)
pressureSensor =
I2CAddress: 92 ("0x5C")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"
9-53
9 LSMDS Functions — Alphabetical List
Create a sensor object with additional properties specified as name-value pair arguments.
clear pressureSensor;
pressureSensor = lps22hb(a,'SampleRate',50,'SamplesPerRead',5,'ReadMode','oldest')
pressureSensor =
I2CAddress: 92 ("0x5C")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"
More About
Code Generation Using MATLAB Function Block
• Use lps22hb in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
• The property OutputFormat is always set to matrix.
• The property TimeFormat is always set to duration.
• The property SamplesAvailable is not accessible from sensor object.
• The default value of I2C address will be taken as 0x5C. Specify I2C address if the sensor has a
different I2C address. The possible values of I2C Addresses are mentioned in the table under
I2Caddress section in this page.
Version History
Introduced in R2021a
See Also
hts221
9-54
lsm303c
lsm303c
Connect to LSM303C sensor Arduino hardware I2C bus
Description
The lsm303c object reads linear acceleration, magnetic field strength, and temperature using the
LSM303C sensor connected to the I2C bus of the hardware. The LSM303C is an inertial
measurement unit (IMU) used to read acceleration and magnetic field in all three dimensions. The
LSM303C also has an embedded temperature sensor. Attach an LSM303C sensor to the I2C pins on
the hardware. You can read the data from your sensor in MATLAB using the “Object Functions” on
page 9-58.
Creation
Syntax
imu = lsm303c(a)
imu = lsm303c(a,Name,Value)
Description
imu = lsm303c(a,Name,Value) creates a sensor object with properties using one or more
Name,Value pair arguments.
Example: imu = lsm303c(a, 'Bus', 1);.
Input Arguments
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
9-55
9 LSMDS Functions — Alphabetical List
Properties
Note Except for TimeFormat, all the other properties are non-tunable, which means you cannot
change their values once the object is locked. Objects are locked when you call the read function,
and the release function unlocks them. If a property is tunable, you can change its value at any
time.
Number of samples read from the sensor in a single execution of the read function.
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
• oldest —
9-56
lsm303c
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Samplesread property outputs the values of samples read so far by executing read function.
Samplesread is set to 0, when the object is created or when you release the object.
Data Types: double
Samples available in the host buffer. The data read from the sensor is stored in the MATLAB buffer.
SamplesAvailable property shows the number of SamplesAvailable in this host buffer. When
you release the object, SamplesAvailable is set to 0. When the ReadMode of sensor is set as
latest, SamplesAvailable will always be 0.
Data Types: double
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
9-57
9 LSMDS Functions — Alphabetical List
When the OutputFormat is set to matrix, the data is returned as matrices of acceleration, magnetic
field, temperature, and time stamps. The units and size for the sensor readings are the same as the
timetable format.
N is the number of samples per read specified by SamplesPerRead. The three columns of each field
represent the measurements in x, y, and z axes.
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Object Functions
readAcceleration Read one sample of acceleration from sensor
readMagneticField Read one sample of magnetic field from sensor
readTemperature Read one sample of temperature from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
Examples
Create Connection to LSM303C Sensor
imu = lsm303c(a)
imu =
I2CAddress: 29 ("0x1D")
: 30 ("0x1E")
Bus: 0
SCLPin: "D21"
SDAPin: "D20"
9-58
lsm303c
Create a sensor object with additional properties specified as name-value pair arguments.
clear imu;
imu = lsm303c(a,'SampleRate',110,'SamplesPerRead',3,'ReadMode','oldest')
imu =
More About
Code Generation Using MATLAB Function Block
• Use lsm303c in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
• The property OutputFormat is always set to matrix.
• The property TimeFormat is always set to duration.
• The property SamplesAvailable is not accessible from sensor object.
Version History
Introduced in R2021a
See Also
lsm6ds3 | lsm6ds3h | lsm6dsm | lsm6dso | lsm6dsr
9-59
9 LSMDS Functions — Alphabetical List
adxl345
Connect to ADXL345, ADXL343, ADXL344, or ADXL346 sensor on Arduino hardware I2C bus
Description
The adxl345 object reads linear acceleration using the ADXL345, ADXL343, ADXL344, or ADXL346
sensor connected to the I2C bus of the hardware. The ADXL34x family of accelerometers are used to
read acceleration in all three dimensions. Attach an ADXL34x sensor to the I2C pins on the hardware.
You can read the data from your sensor in MATLAB using the “Object Functions” on page 9-64.
Creation
Syntax
accelSensor = adxl345(a)
accelSensor = adxl345(a,Name,Value)
Description
Input Arguments
Arduino hardware connection created using arduino on page 1-6, specified as an object.
Example: accelSensor = adxl345(a) creates a connection to the ADXL345 sensor on the Arduino
hardware represented as an object, a.
You can specify any of the properties on this page as name-value pairs
9-60
adxl345
Properties
Note
• All the properties except SamplesRead and SamplesAvailable can be set by specifying as
name-value pair arguments while creating an adxl345 object.
• The properties I2CAddress and Bus are immutable (the property value is set during
construction; you cannot change the value of an immutable property after the object is created).
• The TimeFormat property is tunable, which means you can change the value anytime. The
SampleRate, SamplesPerRead, ReadMode, and OutputFormat properties are non-tunable,
which means you cannot change their values once the object is locked. Objects are locked when
you call the read function, and the release function unlocks them. If a property is tunable, you
can change its value at any time.
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
ADXL34x are connected to the same hardware board. ADXL34x can have two I2C addresses
depending on the logic level on pin SA0 of the sensor.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
9-61
9 LSMDS Functions — Alphabetical List
Number of samples read from the sensor in a single execution of the read function.
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
9-62
adxl345
Samplesread property outputs the values of samples read so far by executing read function.
Samplesread is set to 0, when the object is created or when you release the object.
Data Types: double
Samples available in the host buffer. The data read from the sensor is stored in the MATLAB buffer.
SamplesAvailable property shows the number of SamplesAvailable in this host buffer. When
you release the object, SamplesAvailable is set to 0. When the ReadMode of sensor is set as
latest, SamplesAvailable will always be 0.
Data Types: double
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
When the OutputFormat is set to matrix, the data is returned as matrices of acceleration and time
stamps. The units and size for the sensor readings are the same as the timetable format.
N is the number of samples per read specified by SamplesPerRead. The three columns of each field
represent the measurements in x, y, and z axes.
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
9-63
9 LSMDS Functions — Alphabetical List
Object Functions
readAcceleration Read one sample of acceleration from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
Examples
Create Connection to ADXL345 Sensor
accelSensor =
I2CAddress: 83 ("0x53")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"
Create a sensor object with additional properties specified as name-value pair arguments .
clear accelSensor;
accelSensor = adxl345(a,SampleRate=110,SamplesPerRead=3,ReadMode='latest')
imu =
I2CAddress: 83 ("0x53")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"
9-64
adxl345
More About
Code Generation Using MATLAB Function Block
• Use adxl345 in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
• The property OutputFormat is always set to matrix.
• The property TimeFormat is always set to duration.
• The property SamplesAvailable is not accessible from sensor object.
Version History
Introduced in R2022a
See Also
lsm6ds3 | lsm6ds3h | lsm6dsm | lsm6dso | lsm6dsr
9-65
9 LSMDS Functions — Alphabetical List
icm20948
Connect to ICM-20948 sensor on Arduino hardware I2C bus
Description
The icm20948 object reads acceleration, angular velocity, magnetic field, and temperature using the
TDK ICM-20948 sensor. The ICM-20948 is a 9 degree of freedom (DOF) inertial measurement unit
(IMU) used to read acceleration, angular velocity, and magnetic field in all three dimensions.
The icm20948 object represents a connection to the device on the Arduino hardware I2C bus. Attach
an ICM-20948 sensor to the I2C pins on the Arduino hardware. You can read the data from your
sensor in MATLABusing the object functions.
Before you use the icm20948 object, create an Arduino object using arduino on page 1-6 and set its
properties. When you create the Arduino object, make sure that you include the I2C library. For more
information, see “Connect to Arduino Hardware”.
Creation
Syntax
imu = icm20948(a)
imu = icm20948(a,Name,Value)
Description
imu = icm20948(a) creates a sensor object with default property values. The object represents the
connection to the sensor on the Arduino hardware, a.
imu = icm20948(a,Name,Value) creates a sensor object with properties using one or more
Name,Value pair arguments.
Input Arguments
Arduino hardware connection created using arduino on page 1-6, specified as an object.
Example: imu = icm20948(a) creates a connection to the ICM-20948 sensor on the Arduino object,
a.
9-66
icm20948
You can specify any of the properties on this page as name-value pairs.
Properties
Note
• All the properties except SamplesRead and SamplesAvailable can be set by specifying as
name-value pair arguments while creating an icm20948 object.
• The properties I2CAddress and Bus are immutable (the property value is set during
construction; you cannot change the value of an immutable property after the object is created).
• The TimeFormat property is tunable, which means you can change the value anytime. The
SampleRate, SamplesPerRead, ReadMode, and OutputFormat properties are non-tunable,
which means you cannot change their values once the object is locked. Objects are locked when
you call the read function, and the release function unlocks them. If a property is tunable, you
can change its value at any time.
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
ICM-20948 are connected to the same hardware board. ICM-20948 can have multiple I2C addresses
depending on the logic level on pin AD0 of the sensor.
'0x69' is the I2C address of the accelerometer and gyroscope of ICM-20948. '0x0C' is the I2C address
of the magnetometer of ICM-20948.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
9-67
9 LSMDS Functions — Alphabetical List
SampleRate — Rate at which sample is read during the execution of read function
100 (default) | positive integer in the range [11, 200]
The rate in Samples/s at which data is read from the sensor during execution of read function.
Note Real-time data rate acquisition from ICM-20948 sensor can be achieved by using the
SampleRate property and read function.
Tunable: No
Data Types: double
Number of samples read from the sensor in a single execution of the read function.
Tunable: No
Data Types: double
ReadMode — Specify which data samples to be returned during the execution of read
function
'latest' (default) | 'oldest'
Specify whether to return the latest or the oldest data samples during execution of read function.
The number of samples depends on the SamplesPerRead value. The data read from the sensor is
stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
• oldest —
9-68
icm20948
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Tunable: No
Data Types: character vector | string
SamplesRead — Samples read which gets updated with the execution of read
double
Samples read from the first read. This property gets updated with the execution of read function.
When you release the object, SamplesRead is set to 0.
Data Types: double
SamplesAvailable — Samples in the host buffer which gets updated with the execution of
read
double
Samples available in the host buffer. This property gets updated with the execution of read function.
The data read from the sensor is stored in the MATLAB buffer. SamplesAvailable property shows
the number of SamplesAvailable in this host buffer. When you release the object,
SamplesAvailable is set to 0. When the ReadMode of sensor is set as latest,
SamplesAvailable will always be 0.
Data Types: double
OutputFormat — Set output format returned after the execution of read function
'timetable' (default) | 'matrix'
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
9-69
9 LSMDS Functions — Alphabetical List
When the OutputFormat is set to matrix, the data is returned as matrices of acceleration, angular
velocity, magnetic field, temperature, and time stamps. The units for the sensor readings are the
same as the timetable format. The size of each matrix is N-by-3.
N is the number of samples per read specified by SamplesPerRead. The three columns of each field
represent the measurements in x, y, and z axes.
Tunable: No
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read using read function.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sesnor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Tunable: Yes
Data Types: character vector | string
Examples
Create ICM-20948 Sensor Connection
a = arduino();
Or, you can explicitly specify it in the Libraries Name-Value pair while creating the Arduino object.
clear a;
a = arduino('COM4', 'Uno', Libraries='I2C');
imu = icm20948(a)
imu =
9-70
icm20948
SDAPin: "A4"
Create a sensor object with additional properties specified as name-value pair arguments.
clear imu;
imu = icm20948(a,SampleRate=50,SamplesPerRead=5,ReadMode='latest')
imu =
SampleRate: 50 (Samples/s)
SamplesPerRead: 5
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions
Object Functions
readAcceleration Read one sample of acceleration from sensor
readAngularVelocity Read one sample of angular velocity from sensor
readMagneticField Read one sample of magnetic field from sensor
readTemperature Read one sample of temperature from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
More About
Code Generation Using MATLAB Function Block
• Use icm20948 in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
9-71
9 LSMDS Functions — Alphabetical List
Version History
Introduced in R2022a
See Also
mpu9250
9-72
bmp280
bmp280
Description
The bmp280 object reads barometric air pressure and ambient temperature using the BMP280
sensor.
The bmp280 object represents a connection to the device on the Arduino hardware I2C bus. Attach an
BMP280 sensor to the I2C pins on the Arduino hardware. You can read the data from your sensor in
MATLABusing the object functions.
Before you use the bmp280 object, create an Arduino object using arduino on page 1-6 and set its
properties. When you create the Arduino object, make sure that you include the I2C library. For more
information, see “Connect to Arduino Hardware”.
Creation
Syntax
pressureSensor = bmp280(a)
pressureSensor = bmp280(a,Name,Value)
Description
pressureSensor = bmp280(a) creates a sensor object with default property values. The object
represents the connection to the sensor on the Arduino hardware, a.
Input Arguments
Arduino hardware connection created using arduino on page 1-6, specified as an object.
Example: pressureSensor = bmp280(a) creates a connection to the BMP280 sensor on the
Arduino object, a.
9-73
9 LSMDS Functions — Alphabetical List
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
BMP280 are connected to the same hardware board. BMP280 can have two I2C addresses depending
on the logic level on pin SDO of the sensor.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Properties
Note
• All the properties except SamplesRead and SamplesAvailable can be set by specifying as
name-value pair arguments while creating an bmp280 object.
• The properties I2CAddress and Bus are immutable (the property value is set during
construction; you cannot change the value of an immutable property after the object is created).
• The TimeFormat property is tunable, which means you can change the value anytime. The
SampleRate, SamplesPerRead, ReadMode, and OutputFormat properties are non-tunable,
which means you cannot change their values once the object is locked. Objects are locked when
you call the read function, and the release function unlocks them. If a property is tunable, you
can change its value at any time.
9-74
bmp280
Specify the I2C address of the sensors when multiple I2C devices with the expected address for
BMP280 are connected to the same hardware board. BMP280 can have two I2C addresses depending
on the logic level on pin AD0 of the sensor.
0x76 is the I2C address of the accelerometer and gyroscope of BMP280 connected to Arduino board.
If not specified, the object will be created with one of the available I2C device address in the table.
Availability of I2C device with the expected address will be determined by using scanI2CBus.
Tunable: No
Data Types: double
Number of samples read from the sensor in a single execution of the read function.
Tunable: No
Data Types: double
Specify whether to return the latest or the oldest data samples. The number of samples depends on
the SamplesPerRead value. The data read from the sensor is stored in the MATLAB buffer.
• latest —
Provides the latest data samples available in the buffer. All previous data samples in the buffer are
discarded. For example, if SamplesPerRead = 3, the latest three data samples read by the sensor
are returned.
9-75
9 LSMDS Functions — Alphabetical List
The following figure illustrates how latest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
• oldest —
Provides the oldest data samples available in the buffer. In this case, no data samples are
discarded. For example, if SamplesPerRead = 3, the first three data samples read are returned
for the first read, the next three data samples are returned for the second read, and so on.
The following figure illustrates how oldest data samples are returned assuming S1 is the first
sensor data stored in the buffer, S2 is the second data and so on and Sn is the last data stored in
the buffer and SamplesPerRead property is set to 3 during sensor object creation.
Tunable: No
Data Types: character vector | string
Samples read from the first read. When you release the object, SamplesRead is set to 0.
Data Types: double
9-76
bmp280
Samples available in the host buffer. The data read from the sensor is stored in the MATLAB buffer.
SamplesAvailable property shows the number of SamplesAvailable in this host buffer. When
you release the object, SamplesAvailable is set to 0. When the ReadMode of sensor is set as
latest, SamplesAvailable will always be 0.
Data Types: double
Set the output format of the data returned by executing the read function.
When the OutputFormat is set to timetable, the data returned has the following fields:
When the OutputFormat is set to matrix, the data is returned as matrices of pressure,
temperature, and time stamps. The units for the sensor readings are the same as the timetable
format.
Tunable: No
Data Types: character vector | string
Set the format of the time displayed when the sensor data is read.
• datetime — Displays the date and time at which the data is read.
• duration — Displays the time elapsed in seconds after the sensor object is locked. The sensor
object gets locked at the first call of the read function either after the object creation or after the
execution of the release function.
Tunable: Yes
Data Types: character vector | string
Examples
Create BMP280 Sensor Connection
Or, you can explicitly specify it in the Libraries Name-Value pair while creating the Arduino object.
clear a;
a = arduino('COM4', 'Uno', 'Libraries', 'I2C');
9-77
9 LSMDS Functions — Alphabetical List
pressureSensor =
Create a sensor object with additional properties specified as name-value pair arguments.
clear pressureSensor;
pressureSensor = bmp280(a,'SampleRate',50,'SamplesPerRead',5,'ReadMode','oldest')
pressureSensor =
SampleRate: 50 (Samples/s)
SamplesPerRead: 5
ReadMode: 'oldest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions
Object Functions
readPressure Read one sample of barometric air pressure data from the sensor
readTemperature Read one sample of temperature from sensor
read Read real-time sensor data at a specified rate
release Release the sensor object
flush Flush the host buffer
info Read information related to sensor
More About
Code Generation Using MATLAB Function Block
• Use bmp280 in a MATLAB Function block with the Simulink Support Package for Arduino
Hardware to generate code that can be deployed on Arduino Hardware.
• The property ReadMode cannot be changed and is always set to latest.
• The property SamplesPerRead cannot be changed and is always set to 1. So, no framing is
provided.
9-78
bmp280
Version History
Introduced in R2022b
See Also
1ps22hb
Topics
“Calculate Pitch and Roll on Arduino Using IMU Sensor” (Simulink Support Package for Arduino
Hardware)
9-79
10
APDS9960 sensor
10 APDS9960 sensor
apds9960
Connect to APDS9960 sensor on Arduino hardware using I2C bus
Description
The apds9960 object reads gesture, proximity, and measures clear light and color (RGB) values using
the APDS9960 sensor connected to the I2C bus of the Arduino hardware. You can read the data from
the sensor in MATLAB using the “Object Functions” on page 10-6.
Creation
Syntax
apds9960obj = apds9960(arduinoobj)
apds9960obj = apds9960(arduinoobj,Name,Value)
Description
Input Arguments
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
BitRate sets the rate at which data is received from the sensor, ranging 100000 to 400000.
Example: apds9960obj = apds9960(arduinoobj,'BitRate',100000)
Data Types: double
10-2
apds9960
I2C bus number, specified as 0 or 1. The default value is 0 for all Arduino boards except Nano 33
BLE Sense.
Example: apds9960obj = apds9960(arduinoobj, 'Bus', 1) creates the sensor object on the
I2C Bus 1 of the hardware.
Data Types: double
Properties
I2CAddress — I2C address of APDS9960 sensor
numeric
>> apds9960obj.I2CAddress
ans =
57
>> apds9960obj.Bus
ans =
0
The serial clock pin for the serial clock signal that the I2C central generates, returned as a character
vector.
Example:
>> apds9960obj.SCLPin
ans =
'A5'
10-3
10 APDS9960 sensor
A serial data pin for a serial data signal, returned as a character vector.
Example:
>> apds9960obj.SDAPin
ans =
'A4'
The bus speed set for I2C communication, specified as a positive integer in bits/s.
Example:
>> apds9960obj.BitRate
ans =
100000
You can access individual sensor properties for the sensor configurations such as Gesture, Proximity,
and Color.
Proximity
>> apds9960obj.Proximity.Gain = 4;
>> apds9960obj.Proximity.PulseWidth = 8;
Specifies the number of pulses to be generated on LED. For example, if you set the pulse count value
to 8, the LED generates 8 pulses.
10-4
apds9960
Example:
>> apds9960obj.Proximity.PulseCount =8;
Intensity of the IR emission is selectable using four, factory-calibrated, current levels. Sets LED Drive
Strength in proximity mode.
Example:
>> apds9960obj.Proximity.LEDCurrent = 25;
Gesture
Specifies the number of pulses to be generated on LED. For example, if you set the pulse count value
to 8, the LED generates 8 pulses.
Example:
>> apds9960obj.Gesture.PulseCount =8;
Intensity of the IR emission is selectable using four, factory calibrated, current levels. Sets LED Drive
Strength in gesture mode.
Example:
>> apds9960obj.Gesture.LEDCurrent = 25;
Color
10-5
10 APDS9960 sensor
Example:
>> apds9960obj.Color.Gain = 4;
LED boost current — Additional LED drive current for proximity or gesture LED pulses
100% (default) | 150% | 200% | 300%
If a higher intensity is required, then use the LED boost current to boost the current up to an
additional 300%. Changing the LED boost current in the proximity configuration, changes the
value of the gesture configuration and vice versa.
Example:
Object Functions
readColor Reads clear light and RGB components through APDS9960 sensor
readProximity Read the proximity from APDS9960 sensor
readGesture Read gesture through APDS9960 sensor
Examples
Create Connection to APDS9960 Sensor
Port: 'COM4'
Board: 'Nano33BLE'
AvailablePins: {'D0-D13', 'A0-A7'}
AvailableDigitalPins: {'D0-D13', 'A0-A7'}
AvailablePWMPins: {'D0-D13'}
AvailableAnalogPins: {'A0-A3', 'A6-A7'}
AvailableI2CBusIDs: [0, 1]
AvailableSerialPortIDs: [1]
Libraries: {'APDS9960', 'I2C'}
Show all properties
apds9960obj = apds9960(arduinoobj)
I2CAddress: 57 ('0x39')
Bus: 1
SCLPin: 'SCL1'
SDAPin: 'SDA1'
BitRate: 100000 (bits/s)
Show all properties
10-6
apds9960
Create a sensor object with the bus number 1 and bit rate of 400000.
clear apds9960obj;
apds9960obj = apds9960(arduinoobj, 'Bus', 1, 'BitRate', 400000)
I2CAddress: 57 ('0x39')
Bus: 1
SCLPin: 'SCL1'
SDAPin: 'SDA1'
BitRate: 400000 (bits/s)
Show all properties
Create a sensor object with the bus number 1 and bit rate of 400000.
clear apds9960obj;
apds9960obj = apds9960(arduinoobj, 'Bus', 1, 'BitRate', 100000)
I2CAddress: 57 ('0x39')
Bus: 1
SCLPin: 'SCL1'
SDAPin: 'SDA1'
BitRate: 100000 (bits/s)
Gesture: [1x1 GestureConfiguration]
Proximity: [1x1 ProximityConfiguration]
Color: [1x1 ColorConfiguration]
apds9960obj.Gesture
ans =
Gesture Configuration with properties:
Gain: 4
LEDCurrent: 100
LEDBoost: 100
PulseCount: 10
PulseWidth: 8
Change the gesture gain value to 1 and display the gesture properties.
% Sensor configuration
% Change Gain settings of Gesture
apds9960obj.Gesture.Gain = 1;
% Display Gesture
apds9960obj.Gesture
ans =
Gesture Configuration with properties:
10-7
10 APDS9960 sensor
Gain: 1
LEDCurrent: 50
LEDBoost: 100
PulseCount: 50
PulseWidth: 8
Version History
Introduced in R2021b
See Also
readGesture | readProximity | readColor
10-8
readColor
readColor
Reads clear light and RGB components through APDS9960 sensor
Syntax
[colorData,timestamp] = readColor(apds9960obj)
[colorData,timestamp] = readColor(apds9960obj, colorMode)
Description
[colorData,timestamp] = readColor(apds9960obj) returns the RGB component values of
the sensed light along with the timestamp. The object function normalizes the RGB values using the
clear light intensity value. The Timestamp argument is optional.
Examples
Read Color from Sensor
apds9960obj = apds9960(arduinoobj)
Read color data from sensor by setting the ColorMode property to normalized.
Note Sensor readings after 200 ms are accurate while using the readColor function.
The function returns the color data as a three-element vector of the RGB components.
colorData = 1×3
0.6000 0.4000 0.4000
timestamp = datetime
17-Jun-2021 13:25:27
Read color data from sensor by setting the ColorMode property to raw.
The first member of the vector of the output is the clear light intensity and the subsequent members
are the R, G, and B component values.
10-9
10 APDS9960 sensor
Input Arguments
apds9960obj — APDS9960 sensor object
object
When you set the colorMode to normalized, the object function normalizes the RGB values using
the clear light intensity value.
Data Types: Char | String
Output Arguments
colorData — Color data from sensor
nonnegative vector with values in the range [0,65535]
The color data read, varies depending on the value of the colorMode property with 0 representing
complete darkness.
The time at which MATLAB receives the color data from the sensor, specified as a datetime.
Version History
Introduced in R2021b
See Also
readGesture | apds9960 | readProximity
10-10
readGesture
readGesture
Read gesture through APDS9960 sensor
Syntax
[readGesture,timestamp] = readGesture(apds9960obj)
Description
[readGesture,timestamp] = readGesture(apds9960obj) returns the gesture readings as an
enumeration constant. The possible values for the enumeration constant are none, up, down, left,
or right. Timestamp is optional.
Examples
Read Gesture from Sensor
apds9960obj = apds9960(arduinoobj)
[gesture, timestamp] = readGesture(apds9960obj)
down
timestamp = datetime
17-Jun-2021 13:25:38
Input Arguments
apds9960obj — APDS9960 sensor object
object
Output Arguments
readGesture — Gesture readings
enum
The gesture readings can be none, left, right, up, or, down.
Data Types: enum
10-11
10 APDS9960 sensor
The time at which MATLAB receives the gesture data from the sensor, specified as a datetime.
Version History
Introduced in R2021b
See Also
apds9960 | readProximity | readColor
10-12
readProximity
readProximity
Read the proximity from APDS9960 sensor
Syntax
[proximity,timestamp] = readProximity(apds9960obj)
Description
[proximity,timestamp] = readProximity(apds9960obj) returns returns one reading of the
proximity value with the timestamp. Timestamp argument is optional.
Examples
Read Proximity from Sensor
apds9960obj = apds9960(arduinoobj)
proximReadings = readProximity(apds9960obj)
proximReadings = 0.9647
Input Arguments
apds9960obj — APDS9960 sensor object
object
Output Arguments
proximity — Proximity value read from the sensor
scalar in the range of [0,1]
Proximity value read from the sensor, ranges from 0 and 1 with 0 being the most proximal.
Data Types: double
The time at which MATLAB receives the proximity data from the sensor, specified as a datetime.
10-13
10 APDS9960 sensor
Version History
Introduced in R2021b
See Also
readGesture | apds9960 | readColor
10-14
11
APPS
11 APPS
Arduino Explorer
Configure and control Arduino
Description
Use the Arduino Explorer to interactively set up an Arduino board, read, write, and analyze data from
the board, and generate code.
11-2
Arduino Explorer
Examples
• “Measure Temperature and Control Peripherals Using the Arduino Explorer App”
Version History
Introduced in R2021b
See Also
“Using Arduino Explorer App”
Topics
“Measure Temperature and Control Peripherals Using the Arduino Explorer App”
11-3