0% found this document useful (0 votes)
58 views

Arduinoio Ref

Uploaded by

mahmoudzezoglal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Arduinoio Ref

Uploaded by

mahmoudzezoglal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 460

MATLAB® Support Package for Arduino®

Hardware
Reference

R2023b
How to Contact MathWorks

Latest news: www.mathworks.com

Sales and services: www.mathworks.com/sales_and_services

User community: www.mathworks.com/matlabcentral

Technical support: www.mathworks.com/support/contact_us

Phone: 508-647-7000

The MathWorks, Inc.


1 Apple Hill Drive
Natick, MA 01760-2098
MATLAB® Support Package for Arduino® Hardware Reference
© COPYRIGHT 2014–2023 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used or copied
only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form
without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through
the federal government of the United States. By accepting delivery of the Program or Documentation, the government
hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer
software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014.
Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain
to and govern the use, modification, reproduction, release, performance, display, and disclosure of the Program and
Documentation by the federal government (or other entity acquiring for or through the federal government) and shall
supersede any conflicting contractual terms or conditions. If this License fails to meet the government's needs or is
inconsistent in any respect with federal procurement law, the government agrees to return the Program and
Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be
trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see www.mathworks.com/patents for
more information.
Revision History
September 2014 Online only Revised for Version 14.2.0 (R2014b)
March 2015 Online only Revised for Version 15.1.0 (R2015a)
September 2015 Online only Revised for Version 15.2.0 (R2015b)
March 2016 Online only Revised for Version 16.1.0 (R2016a)
September 2016 Online only Revised for Version 16.2.0 (R2016b)
March 2017 Online only Revised for Version 17.1.0 (R2017a)
September 2017 Online only Revised for Version 17.2.0 (R2017b)
March 2018 Online only Revised for Version 18.1.0 (R2018a)
September 2018 Online only Revised for Version 18.2.0 (R2018b)
March 2019 Online only Revised for Version 19.1.0 (R2019a)
September 2019 Online only Revised for Version 19.2.0 (R2019b)
March 2020 Online only Revised for Version 20.1.0 (R2020a)
September 2020 Online only Revised for Version 20.2.0 (R2020b)
March 2021 Online only Revised for Version 21.1.0 (R2021a)
September 2021 Online only Revised for Version 21.2.0 (R2021b)
March 2022 Online only Revised for Version 22.1.0 (R2022a)
September 2022 Online only Revised for Version 22.2.0 (R2022b)
March 2023 Online only Revised for Version 23.1.0 (R2023a)
September 2023 Online only Revised for Version 23.2.0 (R2023b)
Contents

iii
Classes
1

Functions
2

BNO055 Functions
3

Serial Functions
4

CAN Interface Functions


5

GPS Functions — Alphabetical List


6

Motor Carrier Functions


7

Unified BNO055 Functions


8

LSMDS Functions — Alphabetical List


9

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

shield = addon(a,'Adafruit\MotorshieldV2') creates an add-on connection to Adafruit


Motor Shield V2 connected to the Arduino hardware a.

shield = addon(a,'Adafruit\MotorshieldV2',Name,Value) adds additional options


specified by one or more Name,Value pair arguments.

Input Arguments

a — Arduino hardware connection


arduino object

Arduino hardware connection created using arduino, specified as an arduino object.


Example: shield = addon(a,'Adafruit\MotorshieldV2') creates a connection to motor shield
on the specified arduino object a.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

1-2
addon

Example: motor = addon(a, 'Adafruit\MotorshieldV2','I2CAddress', '0x07'


'pwmfrequency', 3200);

I2CAddress — I2C device address


96 ('0x60') (default) | numeric | character vector | hexadecimal | binary

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.

PWMFrequency — PWM frequency of Adafruit Motor Shield V2


1600 (default) | numeric

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

This property is read-only.

Arduino pins used by AdafruitMotor Shield V2. This is a read only property.
Example:

>> shield.SCLPin

ans =

'A5'

Data Types: char

SDAPin — I2C pin


character vector

This property is read-only.

Arduino pins used by AdafruitMotor Shield V2. This is a read only property.
Example:

>> shield.SDAPin

ans =

'A4'

Data Types: char

1-3
1 Classes

I2CAddress — I2C device address


96 ('0x60') (default) | numeric | character vector | hexadecimal | binary

This property is read-only.

I2C device address, specified as a character vector that represents a hexadecimal value or a scalar
integer.
Example:

>> shield.I2CAddress

ans =

96

Data Types: double | char

PWMFrequency — PWM frequency of Adafruit Motor Shield V2


1600 (default) | numeric

This property is read-only.

PWM frequency of Adafruit Motor Shield V2, specified as a number in hertz.


Example:

>> shield.PWMFrequency

ans =

1600

Data Types: double

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

Create a Motorshieldv2 Object

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)

Specify I2C Address and PWM Frequency

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.

Connection Type Type of Valid Arguments Option for Additional Name-


Value Arguments
USB • port Yes
• port and board
Specify one or more “Name-
Value Arguments” on page 1-
9 from these options:

• Name of Arduino libraries to


which the programming
environment must be limited
• Type of reference voltage
• Analog reference voltage
• Reprogram the Arduino
board or not
• Program log and Arduino
commands log (for
debugging)
• Baud rate
Bluetooth • btaddress No
• btname
WiFi • ipaddress No
• ipaddress and board
• ipaddress, board, and
tcpipport

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(port,board) creates a connection to Arduino or Arduino-compatible ESP32


hardware on the specified serial port. The serial port can be a USB serial port.

a = arduino( ___ ,Name,Value) creates a connection with additional options specified by one or
more Name,Value pair arguments.
Bluetooth

a = arduino(btaddress) uses the Bluetooth® address of the supported Arduino or Arduino-


compatible ESP32 hardware. For the list of Bluetooth connection type supported hardware, see
“Supported Boards” on page 1-15.

a = arduino(btname) uses the name of the of the supported Arduino or Arduino-compatible


ESP32 hardware Bluetooth device to create a connection to the Arduino hardware. For the list of
Bluetooth connection type supported hardware, see “Supported Boards” on page 1-15.
WiFi

a = arduino(ipaddress,board) creates a connection to the WiFi supported Arduino boards or


ESP32 board at the specified IP address.

a = arduino(ipaddress,board,tcpipport) creates a connection to the WiFi supported


Arduino boards or ESP32 board at the specified IP address and TCP/IP remote port.

Input Arguments

port — Hardware port


character vector | string array

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

board — Name of Arduino enabled board


character vector | string array

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.

btname — Bluetooth name of the device


character vector | string array

Bluetooth name of the device, specified as a character vector or string array.


Example: a = arduino('HC-05') creates a wireless Bluetooth connection to an Arduino Uno board
that uses an HC-05 Bluetooth device.
Example: a = arduino('IMUBLE') creates a wireless Bluetooth connection to an Arduino Nano 33
BLE,Nano 33 BLE Sense, Nano 33 IoT, MKR1010, ESP32-DevKitV1 or ESP32-DevKitC boards
that uses a Bluetooth 4.0 device.

ipaddress — IP address of Arduino board with WiFi support or ESP32 board


character vector | string array

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.

tcpipport — TCP/IP port on Arduino or ESP32 board


numeric

1-8
arduino

TCP/IP port on the Arduino or ESP32 board, specified as a number.


Example: a = arduino('192.168.1.15','MKR1000',9500) creates a WiFi connection to an
Arduino MKR1000 board that uses the TCP/IP port at 9500.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

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

Libraries — Name of Arduino library


{'I2C' 'Servo' 'SPI'} (default) | APDS9960 | Adafruit/MotorShieldV2 | CAN |
MotorCarrier | RotaryEncoder | Serial | ShiftRegister | Ultrasonic | character vector |
cell array of character vectors

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.

Example: a = arduino('COM9','Uno','Libraries','spi') limits the environment to the SPI


library.
Example: a = arduino('COM9','Uno','Libraries','Adafruit/MotorShieldV2') limits the
environment to the Adafruit Motor Shields V2 library and its dependent libraries.
Example: a = arduino('COM9','Uno','Libraries','ShiftRegister') limits the
environment to shift register library.

AnalogReferenceMode — Type of reference voltage


internal (default) | external | character vector

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.

AnalogReference — Analog reference voltage


double

Reference voltage of the analog input, specified as a double.

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.

ForceBuildOn — Reprogramming of the Arduino board


false (default) | true

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.

TraceOn — Program log and Arduino commands log


false (default) | true

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)

BaudRate — Bit transmission rate

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

This property is read-only.

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'

Data Types: char

Connected — Arduino device connection status over Bluetooth


true or 1 | false or 0

This property is read-only.

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

Board — Name of Arduino enabled board


'Uno' | 'Due' | 'Mega2560' | character vector | ...

This property is read-only.

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'

Data Types: char

AvailablePins — Pins available on Arduino device


{'D2-D13', 'A0-A5'} | cell array of character vectors | ...

This property is read-only.

Pins available on Arduino device connected to your system, specified as cell array of character
vectors.
Example:

a.AvailablePins

ans =

1×18 cell array

Columns 1 through 12

{'D2'} {'D3'} {'D4'} {'D5'} {'D6'} {'D7'} {'D8'} {'D9'} {'D10'} {'

Columns 13 through 18

{'A0'} {'A1'} {'A2'} {'A3'} {'A4'} {'A5'}

Data Types: cell

AvailableDigitalPins — Digital pins available on Arduino device


{'D2-D13', 'A0-A5'} (default) | cell array of character vectors

This property is read-only.

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

{'A0'} {'A1'} {'A2'} {'A3'} {'A4'} {'A5'}

Data Types: cell

AvailablePWMPins — PWM pins available on Arduino device


{'D3', 'D5-D6', 'D9-D11'} (default) | cell array of character vectors

This property is read-only.

PWM pins available on Arduino device connected to your system, specified as cell array of character
vectors.
Example:
a.AvailablePWMPins

ans =

{'D3'} {'D5'} {'D6'} {'D9'} {'D10'} {'D11'}

Data Types: cell

AvailableAnalogPins — Analog pins available on Arduino device


{'A0-A5'} (default) | cell array of character vectors

This property is read-only.

Analog pins available on Arduino device connected to your system, specified as cell array of character
vectors.
Example:
a.AvailableAnalogPins

ans =

1×6 cell array

{'A0'} {'A1'} {'A2'} {'A3'} {'A4'} {'A5'}

Data Types: cell

AvailableI2CBusIDs — I2C bus IDs available on Arduino device


0 (default) | numeric

This property is read-only.

The ID of I2C bus available on Arduino device connected to your system.


Example:
a.AvailableI2CBusIDs

1-13
1 Classes

ans =

[0]

Data Types: double

AvailableSerialPortIDs — Serial ports available on Arduino device


numeric

The serial bus ID available on Arduino device connected to your system.

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

Libraries — Installed Arduino add-on libraries


{'I2C', 'Servo', 'SPI'} (default) | 'Adafruit/MotorShieldV2' | 'ShiftRegister' |
character vector | cell array of character vectors

This property is read-only.

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×3 cell array

{'I2C'} {'Servo'} {'SPI'}

Data Types: cell | char

AnalogReferenceMode — Type of reference voltage


internal (default) | external | character vector

This property is read-only.

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'

AnalogReference — Analog reference voltage


double

This property is read-only.

Reference voltage of the analog input, specified as a double.

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

The board input argument currently support these boards:

Arduino Board Input Argument WiFi Support Bluetooth Supported


Support Internal Voltage
(V)
Arduino Uno 'Uno' No Yes 5.0(default), 1.1
Arduino Due 'Due' No Yes 3.3(default)

1-15
1 Classes

Arduino Board Input Argument WiFi Support Bluetooth Supported


Support Internal Voltage
(V)
Arduino Mega 'Mega2560' No Yes 5.0(default), 1.1,
2560 2.56
Arduino Leonardo 'Leonardo' No Yes 5.0(default), 2.56
Arduino Mega ADK 'MegaADK' No No 5.0(default), 1.1,
2.56
Arduino Micro 'Micro' No Yes 5.0(default), 2.56
Arduino MKR1000 'MKR1000' Yes No 3.3(default), 1.0,
1.65, 2.23
Arduino MKR 'MKR1010' Yes Yes 3.3(default), 1.0,
WiFi1010 1.65, 2.23
Arduino MKR Zero 'MKRZero' No No 3.3(default), 1.0,
1.65, 2.23
Arduino Nano 3.1 'Nano3' No Yes 5.0(default), 1.1
Arduino Nano 33 'Nano 33IoT' Yes Yes 3.3(default), 1.0,
IoT 1.65, 2.23
Arduino Pro Mini • ProMini328_3 No No • 3.3(default),
V 1.1
• ProMini328_5 • 5.0(default),
V 1.1
Sparkfun Digital DigitalSandbox No No 3.3(default), 1.1
Sandbox
Arduino Nano 33 'Nano33BLE' No Yes 3.3(default)
BLE
Arduino Nano 33 'Nano33BLE' No Yes 3.3(default)
BLE SENSE
ESP32-DevKitV1 'ESP32-WROOM- Yes Yes 3.3(default)
DevKitV1'
ESP32-DevKitC 'ESP32-WROOM- Yes Yes 3.3(default)
DevKitC'

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.

device Connection to device on I2C bus on Arduino or ESP32 hardware


device Connection to device on SPI bus on Arduino or ESP32 hardware
device Connection to serial device on Arduino or ESP32 hardware

1-16
arduino

shiftRegister Connection to shift register on Arduino hardware


rotaryEncoder Connection to quadrature encoder on Arduino or ESP32 hardware
servo Connection to servo motor on Arduino or ESP32 hardware
servo Connection to servo motor on Arduino MKR Motor Carrier or Nano Motor Carrier
addon Connection to add-on device for Arduino hardware
ultrasonic Connection to ultrasonic sensor on Arduino hardware
motorCarrier Connection to Arduino MKR Motor Carrier or Nano Motor Carrier
apds9960 Connect to APDS9960 sensor on Arduino hardware using I2C bus
canChannel Connection to CAN channel connected to a specified device

configurePin Set Arduino pin mode


readDigitalPin Read data from digital pin on Arduino hardware
writeDigitalPin Write data to digital pin on Arduino hardware
writePWMVoltage Generate PWM signal with specified voltage on digital pin
writePWMDutyCycle Generate PWM signal with specified duty cycle on digital pin
playTone Play tone on piezo speaker using digital pin
readVoltage Read voltage from analog pin on Arduino hardware
scanI2CBus Scan I2C bus on Arduino hardware for device address
motorCarrier Connection to Arduino MKR Motor Carrier or Nano Motor Carrier
canChannel Connection to CAN channel connected to a specified device

Examples

Connect to Arduino Hardware

Autodetect an Arduino Nano33IoT.

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.

Specify Port Number and Arduino Board Type

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

Specify Port Number and ESP32 Board Type

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

Specify Bluetooth Address

Connect an HC-05 with a Arduino Uno using Bluetooth.

a = arduino('btspp://98D331FB3B77')

a =

arduino with properties:

DeviceAddress: 'btspp://98D331FB3B77'
Board: 'Uno'
AvailablePins: {'D2-D13', 'A0-A5'}
AvailableDigitalPins: {'D2-D13', 'A0-A5'}

1-18
arduino

AvailablePWMPins: {'D3', 'D5-D6', 'D9-D11'}


AvailableAnalogPins: {'A0-A5'}
AvailableI2CBusIDs: [0]
Libraries: {'I2C', 'Servo', 'SPI'}
Show all properties

Specify Bluetooth Address

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

a = arduino with properties:

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

Show all properties

In Windows, you can also specify the address in the format CA:89:D0:2F:DC:71.

Specify Bluetooth Device Name

Connect an HC-06 with a Arduino Uno using Bluetooth.

a = arduino('HC-06')

a =

arduino with properties:

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

Libraries: {'I2C', 'Servo', 'SPI'}


Show all properties

Specify Bluetooth Formatted Address

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 =

arduino with properties:

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

Specify IP Address to Connect to Arduino MKR1000 Board

Connect to an Arduino MKR1000 board using WiFi.


a = arduino('10.10.10.55','MKR1000')

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

Specify IP Address and TCP/IP Port to Connect to an Arduino MKR1000 Board


a = arduino('10.10.10.55','MKR1000',9500)

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

Connect to an Arduino Board on a Mac

Connect to an Arduino Uno on port /dev/tty.usbmodem1421.

a = arduino('/dev/tty.usbmodem1421','Uno')

a =

arduino with properties:

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 =

arduino with properties:

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

Show all properties

1-21
1 Classes

Specify an Arduino Library

Limit the Arduino environment to use only an I2C library.


a = arduino('COM9','Uno','Libraries','I2C')

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 Two Libraries

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

Specify Analog Reference Voltage

Set AnalogReference internally to 1.1 V


a = arduino('COM9','Uno','AnalogReferenceMode','internal','AnalogReference',1.1)

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

Abstract class for deriving Arduino add-on libraries

Description
classdef MyAddonClass < matlabshared.addon.LibraryBase makes MyAddonClass a
subclass of the matlabshared.addon.LibraryBase class.

An object with matlabshared.addon.LibraryBase as a parent class is an Arduino Add-On. The


matlabshared.addon.LibraryBase class provides your Arduino Add-On subclass several
protected methods to interact with the arduino object, interact with hardware resources, and
communicate with C++ code on the Arduino hardware board.

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

DependentLibraries — List of dependent Arduino Add-On libraries


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

LibraryHeaderFile — Identifier of the add-on C++ header file


char

The name of the C++ header file that contains your add-on class code.
Example: 'MyAddon.h'
Data Types: char

CppClassName — Identifier of C++ add-on class name


char

The name of the class name in the C++ header file.


Example: 'MyAddon'

1-24
matlabshared.addon.LibraryBase class

Data Types: char

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

dcm = dcmotor(shield,motornum) creates a DC motor connection with the specified motor


number on an Adafruit Motor Shield connected to an Arduino board.

dcm = dcmotor(shield,motornum,Name,Value) adds additional options specified by one or


more Name,Value pair arguments.

Input Arguments

shield — Adafruit Motor Shield connection


adafruit motor shield object

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.

motornum — Port number on shield


numeric

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

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: dcm = dcmotor(shield,1,'Speed',0.2)

speed — DC motor speed


0 (default) | numeric

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 =

dcmotorv2 with properties:

MotorNumber: 1 (M1)
Speed: 0.20
IsRunning: 0

Data Types: double

MotorNumber — DC motor port number


numeric

This property is read-only.

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 =

Data Types: double

1-27
1 Classes

IsRunning — DC motor state


0 (default) | 1

This property is read-only.

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

Data Types: 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

Create a DC Motor Connection

Create a DC motor connection to an Adafruit Motor Shield attached to Arduino hardware.


a = arduino('COM4','Uno','Libraries','Adafruit/MotorShieldV2');
dev = addon(a,'Adafruit/MotorShieldV2');

Create a DC motor connection at port 1.


dcm = dcmotor(dev,1)

dcm =
dcmotorv2 with properties:

MotorNumber: 1 (M1)
Speed: 0.00
IsRunning: 0

Specify Speed for a DC Motor Connection

Create a DC motor connection to an Adafruit Motor Shield attached to Arduino hardware.


a = arduino('COM4','Uno','Libraries','Adafruit/MotorShieldV2');
dev = addon(a,'Adafruit/MotorShieldV2');

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

deviceObj = device(arduinoObj,'I2CAddress',I2CAddress,Name,Value) creates an


object that represents the connection between an I2C peripheral connected to the central Arduino or
ESP32 hardware. The Arduino or ESP32 hardware is represented by an arduino object. You can also
customize the connection further using one or more name-value pairs. The 'I2CAddress' name-
value pair is mandatory for creating the I2C device connection.

Input Arguments

arduinoObj — Arduino or ESP32 hardware connection


arduino object

Arduino or ESP32 hardware connection created using arduino, specified as an arduino object.

Name-Value Pair Arguments

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

I2CAddress — Address of I2C device


character vector | string | integer scalar | hexadecimal | binary

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

Bus — I2C bus number


0 (default) | 1

1-30
device

I2C bus number, specified as 0 or 1. The default value is 0.

Note Bus number 1 is only available on Due and Nano33BLE boards. Other Arduino boards support
Bus number 0.

Example: deviceObj = device(arduinoObj,'I2CAddress','0x61','bus',0) creates a


connection to the I2C bus on the hardware.

BitRate — Maximum speed of I2C communication


100000 (default) | 400000

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'

This property is read-only.

Specifies the type of interface used for communication.


Example:

>> deviceObj.Interface
ans =
I2C

I2CAddress — Address of I2C device


numeric

This property is read-only.

I2C device address on the Arduino hardware, specified as a number.


Example:

>> deviceObj.I2CAddress
ans =
104

Data Types: double

Bus — I2C bus number


0 (default) | 1

This property is read-only.

I2C bus number, specified as 0 or 1. The default value is 0.


Example:

1-31
1 Classes

>> deviceObj.Bus
ans =
0

Data Types: double

SCLPin — Serial clock pin


character vector

This property is read-only.

This property is read-only. A serial clock pin for the serial clock signal that the I2C central generates.
Example:
>> deviceObj.SCLPin
ans =
'A5'

Data Types: char

SDAPin — Serial data pin


character vector

This property is read-only. A serial data pin for a serial data signal.
Example:
>> deviceObj.SDAPin
ans =
'A4'

Data Types: char

BitRate — Speed at which bus is set for I2C communication


100000 | positive integer

This property is read-only.

The speed at which bus is set for I2C communication, specified as a positive integer in bits/s.
Example:
>> deviceObj.BitRate
ans =
100000

Data Types: double

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

Create I2C Device Connection

Create an arduino object with I2C library.


arduinoObj = arduino("COM15","Uno","Libraries","I2C")

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

Create a device object.


deviceObj = device(arduinoObj,'I2CAddress','0x50')

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

encoder = rotaryEncoder(a,chA,chB) creates a connection to the rotary encoder using the


arduino object a. chA and chB are the Arduino or ESP32 interrupt pins connected to the output of
channel A and channel B of the encoder.

encoder = rotaryEncoder(a,chA,chB,ppr) also specifies the pulses per revolution.

Input Arguments

a — Arduino hardware connection


arduino object

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.

chA — 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 = 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

chB — Arduino or ESP32 interrupt pin connected to channel B output of encoder


character vector

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

ppr — Pulses per revolution


numeric

Pulses per revolution of the encoder, specified as a number.


Example: encoder = rotaryEncoder(a,'D2','D3',180) creates a connection to a rotary
encoder and sets the pulses per revolution to 180.

Properties
ChannelA — Arduino or ESP32 interrupt pin connected to channel A output of encoder
character vector

This property is read-only.

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'

Data Types: char

ChannelB — Arduino or ESP32 interrupt pin connected to channel B output of encoder


character vector

This property is read-only.

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'

Data Types: char

PulsesPerRevolution — Pulses per revolution


numeric

This property is read-only.

1-36
rotaryEncoder

Pulses per revolution of the encoder, specified as a number.


Example:

>> encoder.PulsesPerRevolution

ans =

180

Data Types: double

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 a Connection to a Quadrature Encoder

Connect to a quadrature encoder using your Arduino board.

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

Connect to the encoder that is connected to your Arduino board.

encoder = rotaryEncoder(a,'D2','D3')

encoder =
rotaryEncoder with properties:

ChannelA: 'D2'
ChannelB: 'D3'
PulsesPerRevolution: []

Specify Pulses per Revolution to a Quadrature Encoder

Connect to a quadrature encoder, and specify the pulses per revolution.

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

Connect to the encoder that is connected to your Arduino board.

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.

s = servo(a,pin,Name,Value) creates a connection to the servo motor with additional options


specified by one or more Name,Value pair arguments.

Input Arguments

a — Arduino or ESP32 hardware connection


arduino object

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.

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

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

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

MinPulseDuration — Minimum pulse duration


5.44e-4 seconds (default) | numeric

Minimum pulse duration, specified as the comma-separated pair consisting of 'MinPulseDuration'


and a number that represents the duration in seconds. Specified value must be equal to the width of
the pulse the motor needs to be at the minimum angle. Refer to your device data sheet for valid
values.
Example: s = servo(a,'D4','MaxPulseDuration',2e-3,'MinPulseDuration',1e-3) sets
the minimum pulse duration to 1 millisecond.

MaxPulseDuration — Maximum pulse duration


2.4e-3 seconds (default) | numeric

Maximum pulse duration, specified as the comma-separated pair consisting of


'MaxPulseDuration' and a number that represents the duration in seconds. Specified value must
be equal to width of the pulse the motor needs to be at the maximum angle. Refer to your device data
sheet for valid values.
Example: s = servo(a,'D4','MaxPulseDuration',2.4e-3,'MinPulseDuration',1e-3)
sets the maximum pulse duration to 2.4 milliseconds.

Properties
Pin — Digital and Analog pin number
character vector

This property is read-only.

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'

Data Types: char

MinPulseDuration — Minimum pulse duration


5.44e-4 seconds (default) | numeric

This property is read-only.

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

Data Types: double

MaxPulseDuration — Maximum pulse duration


2.4e-3 seconds (default) | numeric

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

Data Types: double

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

Create a Servo Object

Create a servo object using pin 4.

Create an arduino object, and attach the servo object to pin 4.

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

Specify Minimum and Maximum Pulse Duration for a Servo

Set the minimum duration to 7e-4 and maximum to 2.3e-3 seconds.

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.

s = servo(shield,motornum,Name,Value) adds additional options specified by one or more


Name,Value pair arguments.

Input Arguments

shield — Adafruit Motor Shield connection


adafruit motor shield object

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.

motornum — 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.

1-43
1 Classes

Example: s = servo(shield,1) creates a connection to a servo motor on digital pin 10 on the


motor shield.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

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

MinPulseDuration — Minimum pulse duration


5.44e-4 seconds (default) | numeric

Minimum pulse duration, specified as the comma-separated pair consisting of 'MinPulseDuration'


and a number that represents the duration in seconds. Specified value must be equal to the width of
the pulse the motor needs to be at the minimum angle. Refer to your device data sheet for valid
values.
Example: s = servo(shield,1,'MaxPulseDuration',2e-3,'MinPulseDuration',1e-3);
sets the minimum pulse duration to 1 millisecond.

MaxPulseDuration — Maximum pulse duration


2.4e-3 seconds (default) | numeric

Maximum pulse duration, specified as the comma-separated pair consisting of


'MaxPulseDuration' and a number that represents the duration in seconds. Specified value must
be equal to width of the pulse that the motor needs to be at the maximum angle. Refer to your device
data sheet for valid values.
Example: s = servo(shield,1,'MaxPulseDuration',2.4e-3) sets the maximum pulse
duration to 2.4 milliseconds.

Properties
MotorNumber — Servo motor number
numeric

This property is read-only.

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 =

Data Types: double

1-44
servo

Pin — Digital pin number


character vector

This property is read-only.

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'

Data Types: char

MinPulseDuration — Minimum pulse duration


5.44e-4 seconds (default) | numeric

This property is read-only.

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

Data Types: double

MaxPulseDuration — Maximum pulse duration


2.4e-3 seconds (default) | numeric

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

Data Types: double

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 Object

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

Create a servo motor connection to motor number 1 on the shield.

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) creates a


connection to the 74hc595 shift register using the latchPin to latch input data.

register = shiftRegister(a,'74hc595',dataPin,clockPin,latchPin,resetPin)
enables reset of the outputs of 74hc595 shift register.

register = shiftRegister(a,'74hc164',dataPin,clockPin) creates a connection to the


74hc164 shift register.

register = shiftRegister(a,'74hc164',dataPin,clockPin,resetPin) enables reset of


the outputs of 74hc164 shift register.

Input Arguments

a — Arduino hardware connection


arduino object

Arduino hardware connection created using arduino, specified as an arduino object.

1-47
1 Classes

Example: register = shiftRegister(a,'74HC165','D3','D6','D7','D10') creates a


connection to the 74HC165 shift register on the specified arduino object a.

dataPin — Shift register serial pin to input or output data


character vector

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

clockPin — Shift register clock pin to signal read or write


character vector

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

latchPin — Shift register latch pin to latch input data


character vector

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

clockEnablePin — Shift register clock enable pin to enable or disable clock


character vector

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

resetPin — Shift register reset pin to reset output


character vector

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

This property is read-only.

Shift register model number, specified as a character vector. Supported shift registers are 74HC165,
74HC595, and 74HC164.
Example:

>> register.Model

ans =

'74HC164'

Data Types: char

DataPin — Shift register serial pin to input or output data


character vector

This property is read-only.

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'

Data Types: char

ClockPin — Shift register clock pin to signal read or write


character vector

This property is read-only.

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'

Data Types: char

LatchPin — Shift register latch pin to latch input data


character vector

This property is read-only.

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'

Data Types: char

LoadPin — Shift register parallel load pin to load parallel input data
character vector

This property is read-only.

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

Data Types: char

ClockEnablePin — Shift register clock enable pin to enable or disable clock


character vector

This property is read-only.

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'

Data Types: char

ResetPin — Shift register reset pin to reset output


character vector

This property is read-only.

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'

Data Types: char

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

Create a Connection to 74HC165 Shift Register

Connect to a 74HC165 shift register using your Arduino® board.

Create an Arduino object with the 'ShiftRegister' library.

1-51
1 Classes

a = arduino('COM4','Uno','Libraries','ShiftRegister');

Connect to the shift register connected to your Arduino board.

register = shiftRegister(a,'74HC165','D3','D6','D7','D10')

register =
shiftRegister with properties:

Model: '74HC165'
DataPin: 'D3'
ClockPin: 'D6'
LoadPin: 'D7'
ClockEnablePin: 'D10'

Create a Connection to 74HC595 Shift Register

Connect to a 74HC595 shift register using your Arduino board.

Connect to the shift register connected to your Arduino board.

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

Specify the resetPin of 74HC595 Shift Register

Connect to a 74HC595 shift register, and specify the resetPin to reset the outputs.

Connect to the shift register on your Arduino board.

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

Create a Connection to 74HC164 Shift Register

Connect to a 74HC164 shift register using your Arduino board.

Connect to the shift register connected to your Arduino board.

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

Specify the resetPin of 74HC164 Shift Register

Connect to a 74HC164 shift register, and specify the resetPin to reset the outputs.

Connect to the shift register on your Arduino board.

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

sm = stepper(shield,motornum,sprev) creates a stepper motor connection with the specified


motor number and steps per revolution on an Adafruit Motor Shield.

sm = stepper(shield,motornum,sprev,Name,Value) adds additional options specified by one


or more Name,Value pair arguments.

Input Arguments

shield — Adafruit Motor Shield connection


adafruit motor shield object

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.

motornum — Stepper motor number


numeric

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.

sprev — Steps per revolution


numeric

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

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

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

RPM — Revolutions per minute


0 (default) | numeric

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.

StepType — Coil activation type


'Single' (default) | character vector

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 = stepper(shield,1,200,'stepType','interleave') creates a stepper motor


connection with an interleaved step type.

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 =

stepper with properties:

1-55
1 Classes

MotorNumber: 2
StepsPerRevolution: 200
RPM: 10
StepType: Single ('Single', 'Double', 'Interleave', 'Microstep')

Data Types: double

StepType — Coil activation type


'Single' (default) | character vector

This property is read-only.

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'

Data Types: char

MotorNumber — Motor shield port number


numeric

This property is read-only.

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 =

Data Types: double

StepsPerRevolution — Number of steps that the stepper motor rotates each revolution
numeric

This property is read-only.

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

Data Types: double

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 Object

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 Object and Specify RPM and Step Type

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

ultrasonicObj = ultrasonic(arduinoObj,triggerPin) creates an ultrasonic sensor


connection for a three-pin sensor connected to the specified trigger pin on the Arduino hardware.

ultrasonicObj = ultrasonic(arduinoObj,triggerPin,echoPin) creates an ultrasonic


sensor connection for a four-pin sensor connected to the specified pins on the Arduino hardware.

ultrasonicObj = ultrasonic(arduinoObj,triggerPin,echoPin,Name,Value) creates an


ultrasonic sensor connection for a four-pin sensor with the specified pins on Arduino hardware. For a
three-pin sensor,the echo pin is the same as the trigger pin.

Input Arguments

arduinoObj — Arduino hardware connection


arduino object

Arduino hardware connection created using arduino, specified as an arduino object.

triggerPin — Digital trigger pin number


char vector

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

echoPin — Digital echo pin number


scalar

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

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

OutputFormat — Format of echo time output


'double'

Format of the echo time output specified as a double.


Example: ultrasonicObj =
ultrasonic(arduinoObj,'D2','D3','OutputFormat','double')

Object Functions
readDistance Distance to object in front of ultrasonic sensor
readEchoTime Read echo time of ultrasound waves

Examples

Create Ultrasonic Sensor Connection Object for Three-Pin Sensor

Create an arduino object with the Ultrasonic library.


arduinoObj = arduino('COM9','Uno',"Libraries","Ultrasonic")

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'

Create Ultrasonic Sensor Connection Object for Four-Pin Sensor

Create an arduino object with the Ultrasonic library.

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

Create an arduino object with the Ultrasonic library.

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

a — Arduino hardware connection

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.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

1-63
1 Classes

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

I2CAddress — Specify I2C address of sensor


[0x6A, 0x1C] | [0x6A, 0x1E] | [0x6B 0x1C] | [0x6B, 0x1E]

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.

SDO_A/G Pin State SDO_M Pin State I2C Address


Low Low [0x6A, 0x1C]
Low High [0x6A, 0x1E]
High Low [0x6B 0x1C]
High Low [0x6B, 0x1E]

You can specify the I2C address in:

• Numeric array of hexadecimal, decimal, or binary format of I2C Addresses


• String array of hexadecimal value of I2C Addresses
• Cell array of character vector of hexadecimal value of I2C Addresses

Example: imu = lsm9ds1(a,'I2CAddress',{'0x6A','0x1C'})

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

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Example: imu = lsm9ds1(a, 'Bus', 1) creates the sensor object on Bus 1 of Arduino Due board
Data Types: double

Properties

Note The properties can also be used as name-value pair arguments while creating an lsm9ds1
object.

I2CAddress — Specify I2C address of sensor


[0x6A, 0x1C] | [0x6A, 0x1E] | [0x6B 0x1C] | [0x6B, 0x1E]

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

SDO_A/G Pin State SDO_M Pin State I2C Address


Low Low [0x6A, 0x1C]
Low High [0x6A, 0x1E]
High Low [0x6B 0x1C]
High Low [0x6B, 0x1E]

You can specify the I2C address in:

• Numeric array of hexadecimal, decimal, or binary format of I2C Addresses


• String array of hexadecimal value of I2C Addresses
• Cell array of character vector of hexadecimal value of I2C Addresses

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

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Data Types: double

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.

SampleRate — Rate at which sample is read


100 (default) | positive integer in the range [28, 200]

The rate in samples/s at which data is read from the sensor.

Tunable: No
Data Types: double

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

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


'latest' (default) | 'oldest'

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

SamplesRead — Samples read


double

This property is read-only.

1-66
lsm9ds1

Samples read from the first read. When you release the object, SamplesRead is set to 0.
Data Types: double

SamplesAvailable — Samples in the host buffer


double

This property is read-only.

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

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2
• AngularVelocity — N-by-3 array in units of rad/s
• MagneticField — N-by-3 array in units of µT (microtesla)

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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

Create an Arduino object and include the I2C library.

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

Create the sensor object.

imu = lsm9ds1(a)

imu =

lsm9ds1 with properties:

I2CAddress: 107 ("0x6B")


: 30 ("0x1E")
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

Create LSM9DS1 Sensor Connection with Additional Name-Value Pair Arguments

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 =

lsm9ds1 with properties:

I2CAddress: 107 ("0x6B")


: 30 ("0x1E")
SCLPin: "A5"
SDAPin: "A4"

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

a — Arduino hardware connection

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.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

1-70
mpu6050

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

I2CAddress — Specify I2C address of sensor


'0x68' | '0x69'

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.

Pin Name Pin State I2C Address


AD0 Low 0x68
High 0x69

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format


• String of hexadecimal value of I2C Address
• Character vector of hexadecimal value of I2C Address

Example: imu = mpu6050(a,'I2CAddress','0x68')

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Example: imu = mpu6050(a, 'Bus', 1) creates the sensor object on Bus 1 of Arduino Due board
Data Types: double

Properties

Note The properties can also be used as name-value pair arguments while creating an mpu6050
object.

I2CAddress — Specify I2C address of sensor


'0x68' | '0x69'

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.

Pin Name Pin State I2C Address


AD0 Low 0x68

1-71
1 Classes

Pin Name Pin State I2C Address


High 0x69

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format


• String of hexadecimal value of I2C Address
• Character vector of hexadecimal value of I2C Address

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Data Types: double

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.

SampleRate — Rate at which sample is read


100 (default) | positive integer in the range [10, 200]

The rate in samples/s at which data is read from the sensor.

Tunable: No
Data Types: double

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

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


'latest' (default) | 'oldest'

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

SamplesRead — Samples read


double

This property is read-only.

Samples read from the first read. When you release the object, SamplesRead is set to 0.
Data Types: double

1-73
1 Classes

SamplesAvailable — Samples in the host buffer


double

This property is read-only.

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

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2
• AngularVelocity — N-by-3 array in units of rad/s

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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

Create an Arduino object and include the I2C library.

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

Create the sensor object.

imu = mpu6050(a)

imu =

mpu6050 with properties:

I2CAddress: 104 ("0x68")


SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

Create MPU-6050 Sensor Connection with Additional Name-Value Pair Arguments

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 =

mpu6050 with properties:

I2CAddress: 104 ("0x68")


SCLPin: "A5"
SDAPin: "A4"

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

a — Arduino hardware connection

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.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

1-77
1 Classes

I2CAddress — Specify I2C address of sensor


[0x68, 0x0C] | [0x69, 0x0C]

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.

Pin Name Pin State I2C Address


AD0 Low [0x68, 0x0C]
High [0x69, 0x0C]

You can specify the I2C address in:

• Numeric array of hexadecimal, decimal, or binary format of I2C Addresses


• String array of hexadecimal value of I2C Addresses
• Cell array of character vector of hexadecimal value of I2C Addresses

Example: imu = mpu9250(a,'I2CAddress',[0x68, 0x0C])

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

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Example: imu = mpu9250(a, 'Bus', 1) creates the sensor object on Bus 1 of Arduino Due board
Data Types: double

Properties

Note The properties can also be used as name-value pair arguments while creating an mpu9250
object.

I2CAddress — Specify I2C address of sensor


[0x68, 0x0C] | [0x69, 0x0C]

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.

Pin Name Pin State I2C Address


AD0 Low [0x68, 0x0C]
High [0x69, 0x0C]

You can specify the I2C address in:

1-78
mpu9250

• Numeric array of hexadecimal, decimal, or binary format of I2C Addresses


• String array of hexadecimal value of I2C Addresses
• Cell array of character vector of hexadecimal value of I2C Addresses

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

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Data Types: double

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.

SampleRate — Rate at which sample is read


100 (default) | positive integer in the range [11, 200]

The rate in samples/s at which data is read from the sensor.

Tunable: No
Data Types: double

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

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


'latest' (default) | 'oldest'

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

SamplesRead — Samples read


double

This property is read-only.

Samples read from the first read. When you release the object, SamplesRead is set to 0.
Data Types: double

SamplesAvailable — Samples in the host buffer


double

This property is read-only.

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

Data Types: double

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2
• AngularVelocity — N-by-3 array in units of rad/s
• MagneticField — N-by-3 array in units of µT (microtesla)

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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

Create an Arduino object and include the I2C library.

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

Create the sensor object.

imu = mpu9250(a)

1-81
1 Classes

imu =

mpu9250 with properties:

I2CAddress: 104 ("0x68")


: 12 ("0xC")
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

Create MPU-9250 Sensor Connection with Additional Name-Value Pair Arguments

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 =

mpu9250 with properties:

I2CAddress: 104 ("0x68")


: 12 ("0xC")
SCLPin: "A5"
SDAPin: "A4"

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

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

accelSensor = lis3dh(a) creates a sensor object with default property values.


Example: accelSensor = lis3dh(a);.

accelSensor = lis3dh(a,Name,Value) creates a sensor object with properties using one or


more Name,Value pair arguments.
Example: accelSensor = lis3dh(a,'I2CAddress',0x19);.

Input Arguments

a — Connection to the hardware


object

Connection to the hardware specified as an object.


Example: accelSensor = lis3dh(a) creates a connection to the LIS3DH sensor on the hardware
represented as an object, a.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

I2CAddress — Specify I2C address of sensor


'0x18' (default) | '0x19'

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.

Pin Name Pin State I2C Address


SA0 Low 0x18
High 0x19

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format


• String of hexadecimal value of I2C Address
• Character vector of hexadecimal value of I2C Address

Example: accelSensor = lis3dh(a,'I2CAddress',0x18)

0x18 is the I2C address of the LIS3DH 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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Example: accelSensor = lis3dh(a, 'Bus', 1) creates the sensor object on Bus 1 of the
hardware.
Data Types: double

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.

I2CAddress — Specify I2C address of sensor


'0x18' (default) | '0x19'

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.

Pin Name Pin State I2C Address


SA0 Low 0x18
High 0x19

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format


• String of hexadecimal value of I2C Address
• Character vector of hexadecimal value of I2C Address

0x18 is the I2C address of the LIS3DH 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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Data Types: double

SampleRate — Rate at which sample is read


100 (default) | positive integer in the range [1, 200]

The rate in samples/s at which data is read from the sensor.


Data Types: double

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

Number of samples read from the sensor in a single execution of the read function.
Data Types: double

ReadMode — Specify which data samples to be returned


'latest' (default) | 'oldest'

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.

Data Types: character vector | string

SamplesRead — Samples read


double

This property is read-only.

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

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2

1-87
1 Classes

• Temperature — Temperature in units of celsius

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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.

Data Types: character vector | string

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

Create an arduino object with the I2C library.

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the sensor object.

accelSensor = lis3dh(a)

accelSensor =

lis3dh with properties:

I2CAddress: 24 ("0x18")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)

1-88
lis3dh

SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

Create LIS3DH Sensor Connection with Additional Name-Value Pair Arguments

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 =

lis3dh with properties:

I2CAddress: 24 ("0x18")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (samples/s)


SamplesPerRead: 10
ReadMode: "oldest"
SamplesRead: 0
SamplesAvailable: 0

Show all properties all functions

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

a — Arduino hardware connection


arduino object

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

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.
Example: imu = bmi160(a,'I2CAddress',0x69);

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.

I2CAddress — Specify I2C address of sensor


[0x68, 0x0A] | [0x68, 0x0B] | [0x68, 0x0C] | [0x68, 0x0D] | [0x69, 0x0A] | [0x69,
0x0B] | [0x69, 0x0C] | [0x69, 0x0D]

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.

Pin Name Pin State I2C Address


SDO Low 0x68
High 0x69

You can specify the I2C address in:

• Numeric array of hexadecimal, decimal, or binary format of I2C Addresses


• String array of hexadecimal value of I2C Addresses
• Cell array of character vector of hexadecimal value of I2C Addresses

0x68 is the I2C address of the BMI160 connected to Arduino board.


Example: imu = bmi160(a,I2CAddress=[0x69, 0x0C])

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

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Example: imu = bmi160(a, Bus=1) creates the bmi160 sensor object if BMI160 sensor is
connected to bus 1 of Arduino Due board.
Data Types: double

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

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

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

This property is read-only.

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

This property is read-only.

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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2
• AngularVelocity — N-by-3 array in units of rad/s
• MagneticField — N-by-3 array in units of µT (microtesla)
• Temperature — N-by-1 array in units of celsius

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

TimeFormat — Set time format during the execution of read function


'datetime' (default) | 'duration'

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

Create an arduino object and include the I2C library.

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

Create the sensor object.

imu = bmi160(a)

imu =

bmi160 with properties:

I2CAddress: 104 ("0x68")

1-95
1 Classes

: 12 ("0xC")
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

Create BMI160 Sensor Connection with Additional Name-Value Pair Arguments

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 =

bmi160 with properties:

I2CAddress: 104 ("0x68")


: 12 ("0xC")
SCLPin: "A5"
SDAPin: "A4"

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:

• Arduino Nano 3.1


• Arduino Pro Mini
• Sparkfun Red Board Uno
• Sparkfun Digital Sandbox

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 .

configurePin(a,pin,mode) sets the specified pin on the Arduino hardware in connection a to


the specified mode.

Examples

Display Current Pin Mode

a = arduino('COM4','Uno');
configurePin(a,'A2')

ans =
'Unset'

Configure Analog Pin to I2C Mode

a = arduino('COM4','Uno');
configurePin(a,'A4','I2C');

Display current pin mode.

pinMode = configurePin(a,'A4')

pinMode =
'I2C'

Configure Digital Pin to Pullup Mode

a = arduino('COM4','Uno');
configurePin(a,'D3','pullup');

Display current pin mode.

pinmode = configurePin(a,'D3')

2-3
2 Functions

pinmode =
'Pullup'

Clear Pin Mode

Display current pin mode and reset it to 'Unset'.

a = arduino('COM4','Uno');
configurePin(a,'D3','pullup');
pinMode = configurePin(a,'D3')

pinMode =
'Pullup'

Change mode to 'Unset' and display the current mode.

configurePin(a,'D3','Unset');
pinMode = configurePin(a,'D3')

pinMode =
'Unset'

Input Arguments
a — Arduino hardware connection
object

Arduino hardware connection created using arduino, specified as an object.


Example: a = arduino;

pin — Pin number


character vector

Pin number on the physical hardware, specified as a character vector.


Example: D3 or A1.

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.

mode — Pin mode


'unset' (default) | character vector

Pin mode specified as a character vector. Valid pin modes are:

• AnalogInput: acquire analog signals from pin


• DigitalInput: acquire digital signals from pin
• DigitalOutput: generate digital signals from pin
• I2C: specify a pin to use with I2C protocol

2-4
configurePin

• Interrupt: specify pin in interrupt mode to be used in rotaryEncoder


• Pullup: specify pin to use a pullup switch
• PWM: specify pin to use a pulse width modulator
• CAN: specify pin to use a Controller Area Network bus
• Servo: specify pin to use a servo
• SPI: specify a pin to use with SPI protocol
• Tone: specify pin to use for playTone
• Ultrasonic: specify pin to use with ultrasonic sensor
• CAN: specify pin to use with CAN shield
• Unset: clears pin designation. The pin is no longer reserved and can be automatically set at the
next operation.

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

Current mode of pin, returned as a 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.

Analog pin on ESP32-DevKitV1 and ESP32- Digital pin number to be useda


DevKitC
A0 D36
A3 D39
A4 D32
A5 D33
A6 D34
A7 D35
A10 D4
A12 D2
A13 D15
A14 D13
A15 D12
A16 D14

2-5
2 Functions

Analog pin on ESP32-DevKitV1 and ESP32- Digital pin number to be useda


DevKitC
A17 D27
A18 D25
A19 D26
a If you connect to ESP32 board over WiFi from the MATLAB PC, transferring data through the following pins may not
work properly: D2, D12, D13, D14, D15, D25, D26, and D27. For communication over WiFi, it is recommended that you
use the other pins listed in this table.

Code Generation Using MATLAB Function Block

• 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

List Arduino libraries

List libraries installed on your system.

lib = listArduinoLibraries()

lib =

9×1 cell array

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

Move the Stepper Motor

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

Rotate the motor 10 steps.

move(sm,10);

The move command blocks MATLAB while it executes.

Input Arguments
sm — Stepper motor connection
stepper motor object

Stepper motor connection, specified as a stepper motor object, created using the stepper function.

steps — Number of steps


number

Number of steps that the stepper motor rotates, specified as a number.

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.

playTone(a,pin,frequency) plays a tone on a piezo speaker attached to the digital pin on


Arduino hardware at the specified pin and frequency.

Examples

Play a Tone on a Piezo Speaker

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

Arduino hardware connection created using arduino, specified as an object.

pin — Digital pin number


character vector

Digital pin number on the physical hardware, specified as a character vector.

frequency — Frequency of tone


numeric

Frequency of tone to be played, specified as a number between the frequency range 0 and 32767Hz.

duration — Duration of tone


numeric

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

Read data from I2C bus

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.

out = read(dev,numBytes,precision) also specifies the data precision.

Examples

Read Data from an I2C Device on Arduino Hardware

Create an Arduino object and attach an I2C device object to it.

a = arduino();

Use an address to create the I2C device connection.

dev = device(a,'I2CAddress','0x55');

Read data from the I2C device.

out = read(dev,1)

out = 4

Specify Precision to Read Data from an I2C Device on Arduino Hardware

Create an Arduino object and attach an I2C device object to it.

a = arduino();

Use an address to create the I2C device connection.

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

I2C device connection, specified as a device object.

numBytes — Number of bytes to read


scalar

Number of bytes of data to read from the I2C device, specified as a scalar.

precision — Data precision


'uint8' (default) | 'int8' | 'uint16' | 'int16' | 'uint32' | 'int32' | 'uint64' | 'int64'

Data precision, specified as one of the following character vectors:

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

Read data from shift register

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.

out = read(register,precision) also specifies the data precision.

Examples

Read Data from a Shift Register

Create an Arduino® object with the 'ShiftRegister' library.

a = arduino('COM4','Uno','Libraries','ShiftRegister');

Connect to the 8-bit PISO shift register on your Arduino board.

register = shiftRegister(a,'74HC165','D3','D6','D7','D10');

Read data from the data pin of the register.

out = read(register)

out = 1×8

1 1 1 1 1 0 0 0

Specify Precision to Read Data

Specify the data precision to read data from the data pin of a PISO shift register.

Create an Arduino® object with the 'ShiftRegister' library.

a = arduino('COM4','Uno','Libraries','ShiftRegister');

Connect to the 8-bit PISO shift register on your Arduino board.

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

Or you can specify the precision as a multiple of 8.

out = read(register,8)

out = 1×8

0 0 0 0 0 0 0 0

Input Arguments
register — Shift register connection
shiftRegister object

Shift register connection, specified as a shiftRegister object.

precision — Data precision


8 (default) | 16 | 24 | 32 | 'uint8' | 'uint16' | 'uint32'

Data precision, specified as one of the following multiples of 8:

• 8
• 16
• 24
• 32

or as one of the following character vectors:

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

[count,time] = readCount(encoder,Name,Value) also returns options specified by one or


more Name,Value pair arguments.

Examples

Read the Current Absolute Count Value

Create an Arduino object with the 'rotaryEncoder' library.

a = arduino('COM4','Uno','Libraries','rotaryEncoder');

Connect to the encoder that is connected to your Arduino board.

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

Read the Current Incremental Count Value

Create an Arduino object with the 'rotaryEncoder' library.

a = arduino('COM4','Uno','Libraries','rotaryEncoder');

Connect to the encoder that is connected to your Arduino board.

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

Quadrature encoder connection, specified as a rotaryEncoder object.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

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

Reset — Flag to reset count value to 0


false (default) | true

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.

Data Types: logical

OutputFormat — Output format of the time elapsed since the Arduino server started
duration

Flag to control the output format of time.

Note Only duration argument is supported. If you need the output as double, don't use the
OutputFormat name-value pair.

Data Types: duration

2-19
2 Functions

Output Arguments
count — Current count value of the encoder with X4 decoding
numeric

Current count value of the encoder with X4 decoding, returned as a number.

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.

time — Elapsed time


numeric

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

Read the Value of a Digital Pin

Create a connection to Arduino hardware and read digital pin 13.


a = arduino;
readDigitalPin(a,'D13')

ans = 1

Input Arguments
a — Arduino hardware connection
object

Arduino hardware connection created using arduino, specified as an object.

pin — Digital pin number


character vector

Digital pin number on the physical hardware, specified as a character vector.

Output Arguments
value — value acquired from digital pin
double

Value acquired from digital pin, returned as a numeric 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

Measure Distance to Object

Create an arduino object with Ultrasonic library.

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'

Measure the distance to the object.

distance = readDistance(ultrasonicObj);

Input Arguments
ultrasonicObj — ultrasonic object
ultrasonic object

Ultrasonic sensor connection object, specified as an ultrasonic on page 1-59 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

Calculate Distance to Object

Create an arduino object with the Ultrasonic library.

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

Ultrasonic sensor connection object, specified as an ultrasonic on page 1-59 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

Read Voltage from Analog Pin

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

Arduino hardware connection created using arduino, specified as an object.

pin — Analog pin number


character vector

Analog pin number on the physical hardware, specified as a character vector.

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

Read Servo Motor Position

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 servo motor connection to motor number 1 on the shield.


s = servo(shield,1);

Read the position of the servo.


position = readPosition(s)

position = 0.5200

Input Arguments
s — Servo motor
servo motor object

Servo motor connection, specified as a 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

Read Servo Motor Position

Create servo object.

a = arduino('COM4','Uno','Libraries','Servo');
s = servo(a,'D4');

Read the position of the servo.

position = readPosition(s)

position = 0.5200

Input Arguments
s — Servo object
object

Servo object connected to Arduino hardware specified as an 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.

out = readRegister(dev,register,precision) also specifies the data precision.

Examples

Read from an I2C Device Register

Create an Arduino object and attach an I2C device object to it.

a = arduino('COM9','Uno','Libraries','I2C');

Use an address to create the I2C device connection.

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

Write value 10 to the I2C device register at address 20.

writeRegister(dev,20,10);

Read from the I2C device register at address 20.

value = readRegister(dev,20)

value = 10

2-33
2 Functions

Specify Precision to Read from an I2C Device Register

Create an Arduino object and attach an I2C device object to it.

a = arduino('COM9','Uno','Libraries','I2C');

Use an address to create the I2C device connection.

dev = device(a,'I2CAddress','0x54');

Write value 224 to the I2C device register at address 20 with the precision of uint16

writeRegister(dev, 20, 224,'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

I2C device connection, specified as a device object.

register — Address of I2C device register


scalar integer from 0 through 255 | hexadecimal | binary

Address of the I2C device register, specified as a scalar integer, hexadecimal, or binary from 0
through 255.

precision — Data precision


'uint8' (default) | 'int8' | 'uint16' | 'int16' | 'uint32' | 'int32' | 'uint64' | 'int64'

Data precision, specified as one of the following character vectors:

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

rpm = readSpeed([encoder1,encoder2]) also returns the current rotational speeds measured


by the two quadrature encoders in revolutions per minute.

Examples

Read the Current Rotational Speed

Create an Arduino® object with the 'rotaryEncoder' library.

a = arduino('COM4','Uno','Libraries','rotaryEncoder');

Connect to the encoder that is connected to your Arduino board.

encoder = rotaryEncoder(a,'D2','D3',180);

Read the current rotational speed.

rpm = readSpeed(encoder)

rpm = 0

Read Speed from a Vector of Rotary Encoder Objects

Create an Arduino object with the 'rotaryEncoder' library.

a = arduino('COM8','Mega2560','Libraries','rotaryEncoder');

Connect to the encoders that are connected to your Arduino board.

encoder1 = rotaryEncoder(a,'D2','D3',180);
encoder2 = rotaryEncoder(a,'D18','D19',180);

Read the current rotational speed.

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

Quadrature encoder connection, specified as a single rotaryEncoder object or a 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

Release the Stepper Motor

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

Rotate the motor 10 steps, and release it.

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

Clear the Output of Shift Register

Create an Arduino® object with the 'ShiftRegister' library.


a = arduino('COM4','Uno','Libraries','ShiftRegister');

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'

Clear all outputs.


reset(register);

Input Arguments
register — Shift register connection
shiftRegister object

Shift register connection, specified as a 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

Scan I2C Bus 1 on Arduino Hardware

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)

ans = 1×1 cell array


{'0x48'}

Input Arguments
a — Arduino hardware connection
object

Arduino hardware connection created using arduino, specified as an object.

bus — I2C bus number


0 (default) | numeric

I2C bus number specified as a number.

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

Create a DC motor connection at port 1.

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

DC motor connection, specified as a dcmotor object, created using dcmotor function.

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

Create a DC motor connection at port 1.

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 the motor, and display the object.

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

DC motor connection, specified as a dcmotor object, created using dcmotor function.

Version History
Introduced in R2014b

See Also
start | dcmotor | arduino

Topics
“Control Motors Using Adafruit Motor Shield V2”

2-46
write

write
Package: arduinoio

Write data to I2C bus

Syntax
write(dev,dataIn)
write(dev,dataIn,precision)

Description
write(dev,dataIn) writes data to the I2C bus.

write(dev,dataIn,precision) also specifies the precision.

Examples

Write Data to an I2C device on Arduino Hardware

Create a connection to an I2C device on Arduino hardware.

a = arduino('COM9','Uno','Libraries','I2C');

Updating server code on board Uno (COM9). This may take a few minutes.

Use an address to create the I2C device connection.

dev = device(a,'I2CAddress','0x55');

Write data to the I2C device.

dataIn = [0 1 2 3 4 5];
write(dev,dataIn);

Specify Precision to Write Data to an I2C Device on Arduino Hardware

Create a connection to an I2C device on Arduino hardware.

a = arduino('COM9','Uno','Libraries','I2C');

Use an address to create the I2C device connection.

dev = device(a,'I2CAddress','0x55');

Write data to the I2C device with the precision of uint16.

dataIn = [0 500];
write(dev,dataIn,'uint16');

2-47
2 Functions

Input Arguments
dev — I2C device connection
device object

I2C device connection specified as a device object.

dataIn — Data to write to I2C device


scalar | vector

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.

precision — Data precision


'uint8' (default) | 'int8' | 'uint16' | 'int16' | 'uint32' | 'int32' | 'uint64' | 'int64'

Data precision, specified as one of the following character vectors:

• 'uint8'
• 'int8'
• 'uint16'
• 'int16'
• 'uint32'
• 'int32'
• 'uint64'
• 'int64'

Data can be also be specified in the following formats:

• 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

Write data to shift register

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.

write(register,value,precision) also specifies the data precision.

Examples

Write Data to a Shift Register

Create an Arduino® object with the 'ShiftRegister' library.

a = arduino('COM4','Uno','Libraries','ShiftRegister');

Connect to the SIPO shift register on your Arduino board.

register = shiftRegister(a,'74HC595','D3','D6','D7');

Write data to the data pin of the register.

write(register,23);

Specify Precision to Write Data

Create an Arduino® object with the 'ShiftRegister' library.

a = arduino('COM4','Uno','Libraries','ShiftRegister');

Connect to the SIPO shift register on your Arduino board.

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

Shift register connection, specified as a shiftRegister object.

value — Data to write


numeric | character vector of '1' or '0' | vector of 1 or 0

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

precision — Data precision


'uint8' (default) | 'uint16' | 'uint32' | 'uint64'

Data precision, specified as one of the following character vectors:

• 'uint8'
• 'uint16'
• 'uint32'
• 'uint64'

Data can be also be specified in the following formats:

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

resetCount(encoder,count) resets the count value of the quadrature encoder to a user-specified


value.

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

Reset Count Value to Zero

Create an Arduino® object with the 'rotaryEncoder' library.

a = arduino('COM4','Uno','Libraries','rotaryEncoder');

Connect to the encoder that is connected to your Arduino board.

encoder = rotaryEncoder(a,'D2','D3');

Reset encoder count value to 0.

resetCount(encoder);

Set Count Value of an Encoder to a Specified Value

Create an Arduino object with the 'rotaryEncoder' library.

a = arduino('COM4','Uno','Libraries','rotaryEncoder');

Connect to the encoder that is connected to your Arduino board.

encoder = rotaryEncoder(a,'D2','D3');

Set encoder count value to 10.

resetCount(encoder,10);

2-52
resetCount

Input Arguments
encoder — Quadrature encoder connection
rotaryEncoder object

Quadrature encoder connection, specified as a rotaryEncoder object.

count — Encoder count value to set


numeric

Encoder count value to set, specified as a number.

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

Write to Digital Pin

Write a value to digital pin 5 with an LED to turn it on.

a = arduino();
writeDigitalPin(a,'D5',1);

Input Arguments
a — Arduino hardware connection
object

Arduino hardware connection created using arduino, specified as an object.

pin — Digital pin number


character vector

Digital pin number on the hardware, specified as a character vector.

value — Value of the digital data


logical

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

Set Servo Motor Position

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 servo motor connection to motor number 1 on the shield.

s = servo(shield,1);

Rotate the motor to its mid position.

writePosition(s,0.5)

Input Arguments
s — Servo object
servo motor object

Servo motor connection, specified as a servo motor object.

position — Position of servo motor shaft


numeric

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

Set Servo Motor Position

Create servo object.

a = arduino('COM4','Uno','Libraries','Servo');
s = servo(a,'D4');

Rotate the motor to its maximum position.

writePosition(s,1)

Input Arguments
s — Servo object
object

Servo object connected to an Arduino hardware specified as an object.

position — Position of shaft


numeric

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 the Duty Cycle of Digital Pin

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

Arduino hardware connection created using arduino, specified as an object.

pin — Digital pin number


character vector

Digital pin number on the physical hardware, specified as a character vector.

dutyCycle — Value of the digital pin duty cycle


numeric

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

Specify the Voltage of Digital Pin

Specify digital pin 5 on Arduino hardware to have 3 volts.

a = arduino();
writePWMVoltage(a,'D5',3);

Input Arguments
a — Arduino hardware connection
object

Arduino hardware connection created using arduino, specified as an object.

pin — Digital pin number


character vector

Digital pin number on the physical hardware, specified as a character vector.

voltage — Voltage of the digital pin


numeric

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.

out = writeRead(dev,dataIn,precision) also specifies the precision.

Examples

Write and Read Data from a SPI Device on an Arduino Board

Create a connection to a SPI device on an Arduino® board.

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

Write data to the SPI EEPROM.

writeCmd = bin2dec('0000 0010');


address = [255 0];
data = [250 155];
dataIn = [writeCmd address data];
out = writeRead(dev,dataIn)

out = 1×5

0 0 0 0 0

Read data from the SPI EEPROM

readCmd = bin2dec('0000 0011');


dataIn = [readCmd address zeros(1,2)];
out = writeRead(dev,dataIn)

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

Create a connection to a SPI device on an Arduino® board.

a = arduino('COM6','Mega2560','Libraries','SPI');
dev = device(a,'SPIChipSelectPin','D46');

Enable write on EEPROM

writeEnable = 6;
writeRead(dev,writeEnable);

Write data to the SPI EEPROM with the precision of uint16.

writeCmd = 2;
address = [0 0];
data = [51200 51201];
dataIn = [writeCmd address data];
out = writeRead(dev,dataIn,'uint16')

out = 1×5 uint16 row vector

0 0 0 0 0

Read data from the SPI EEPROM with the precision of uint16.

readCmd = 3

readCmd = 3

dataIn = [readCmd address zeros(1,2)];


out = writeRead(dev,dataIn,'uint16')

out = 1×5 uint16 row vector

0 0 0 51200 51201

Input Arguments
dev — SPI device connection
device object

SPI device connection, specified as a device object.

dataIn — Data to write to SPI device


scalar | vector

Data to write, specified as a scalar, vector, hexadecimal, or binary. The range of the values in the
array is based on the precision.

precision — Data precision


'uint8' (default) | 'uint16' | 'uint32' | 'uint64'

2-64
writeRead

Data precision, specified as one of the following character vectors:

• 'uint8'
• 'uint16'
• 'uint32'
• 'uint64'

The precision must match the size of the SPI device register.

Data can be also be specified in the following formats:

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

writeRegister(dev,register,dataIn,precision) also specifies the data precision.

Examples

Write to an I2C Device Register

Create an Arduino object and attach an I2C device object to it.


a = arduino('COM9','Uno','Libraries','I2C');

Use an address to create the I2C device connection.


dev = device(a,'I2CAddress','0x55');

Write value 10 to the I2C device register at address 20.


writeRegister(dev,20,10);

Specify Precision of Data to Write to an I2C Register

Create an Arduino object and attach an I2C device object to it.


a = arduino('COM9','Uno','Libraries','I2C');

Use an address to create the I2C device connection.


dev = device(a,'I2CAddress','0x55');

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

I2C device connection, specified as a device object.

register — Address of I2C device register


scalar integer from 0 through 255 | hexadecimal | binary

Address of the I2C device register, specified as a scalar integer from 0 through 255, hexadecimal, or
binary.

dataIn — Data to write


scalar | vector

Data to write, specified as a scalar, vector, hexadecimal, or binary. The range of the values in the
array is based on the precision.

precision — Data precision


'uint8' (default) | 'int8' | 'uint16' | 'int16' | 'uint32' | 'int32' | 'uint64' | 'int64'

Data precision, specified as one of the following character vectors:

• 'uint8'
• 'int8'
• 'uint16'
• 'int16'
• 'uint32'
• 'int32'
• 'uint64'
• 'int64'

Data can be also be specified in the following formats:

• 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

Send a Command to HelloWorld Add-On

Create a command, and use sendCommand to send it to the Arduino hardware.

Get the parent Arduino object.


arduinoObj = obj.Parent;

Define the library name.


libName = 'ExampleAddon/HelloWorld';

Define the command ID, and create data to send.


commandID = obj.READ_COMMAND;
dataIn = [];

Send the message.


[dataOut, payloadSize] = sendCommand(obj, libName, commandID, dataIn);

Show the result in the MATLAB command line.


disp(char(dataOut))

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.

libName — Name of library


character vector

Name of library defined in the custom class, specified as a character vector.

commandID — Unique command identifier


numeric

Unique command identifier, specified as a number. This number must match the ID in the command
handler defined in your custom library header file.

dataIn — Array of integers


vector

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 :

Boards dataIn size


Leonardo, Micro 150 bytes
MKR1000, MKR1010, MKR Zero, 720 bytes
Mega2560,MegaADK, Due, Nano 33 IoT, Nano 33
BLE, Nano 33 BLE Sense
Uno, Nano, Pro Mini, Digital Sandbox 57 bytes

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 — timeout duration


5 sec (default) | numeric

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

Data returned, as an array of doubles


Data Types: uint8

payloadSize — Length of output returned


numeric

Length of the output returned by sendCommand, as a number.

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 Alternate Pin Name on Arduino Leonardo Device

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'

Get Alternate Pin Name on Arduino Uno

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.

pin — Pin number


character vector

2-72
getPinAlias

Pin number, specified as a character vector.

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

Get Arduino Microcontroller Information

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

Name of Arduino microcontroller, returned as a character vector. For example, 'atmega328p'.

Version History
Introduced in R2015b

See Also
Topics
“Create HelloWorld Add-On”
“Create LCD Add-on”

2-74
getMCU

“Custom Add-On Library Concepts”

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

Get Pin Numbers From Terminals

Get pin numbers from terminals 2, 3, 4 on your Arduino hardware.

arduinoObj = obj.Parent;
pins = getPinsFromTerminals(obj, [2 3 4])

pins =

{'D2', 'D3', 'D4'}

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.

terminals — Terminal numbers on Arduino hardware


double

Terminal number on Arduino hardware, specified as a double or an array of doubles.

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 Can be Used as Analog Pin

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 — Terminal number on Arduino hardware


double

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 Can be Used As Digital Pin on Arduino Uno Device

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 Terminal Can be Used as Digital Pin on Arduino Leonardo Device

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 =

Check if the terminal can be used as a digital pin.


result = isTerminalDigital(obj, 4)

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 — Terminal number on Arduino hardware


double

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

Terminal type, returned as a boolean to indicate if terminal is digital

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

Get Terminal Mode

Get the mode of terminal 14 on your Arduino hardware.

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.

terminal — Terminal number on Arduino hardware


double

Terminal number on Arduino hardware, specified as a double.

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

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 — Pins on Arduino hardware


character vector

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 That Have Servo Functionality on Arduino Uno Device

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

Get Terminals with PWM Functionality for an Arduino Uno Device

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

“Create LCD Add-on”


“Custom Add-On Library Concepts”
“Physical Terminals and Pin Numbers”

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

Get Terminals with SPI Functionality for Arduino Uno Device

Get terminals on an Arduino Uno device with specific SPI functionality.

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 Terminals with I2C Functionality on Arduino Uno Device

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.

bus — I2C device bus


0 (default) | numeric

I2C device bus, specified a number.

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 with Interrupt Functionality on Arduino Uno Device

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

Validate SPI Pin

Check if pin D12 supports SPI functionality on the Arduino Uno hardware.

arduinoObj = obj.Parent;
validatePin(arduinoObj,'D12','SPI')

Validate I2C Pin

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 — Pin on Arduino hardware


character vector

Pin on Arduino hardware, specified as a character vector.

type — Pin type on Arduino hardware


character vector

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.

configurePinResource(arduinoObj, pin, resourceOwner, mode, forceConfig)


configures the mode of pin to the specified mode and the specified resourceOwner. You can
optionally force this configuration on the pin using forceConfig.

Examples

Configure Digital Pin to I2C

Change the resource owner and mode of the digital pin 'D11' on an Arduino Uno to I2C.

Query pins current mode.

arduinoObj = obj.Parent;
mode = configurePinResource(arduinoObj, 'D11')

mode =
'SPI'

Change the resource owner to 'i2cdev' and mode to 'I2C'.

configurePinResource(a, 'A4', 'I2C', '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 — Pin on Arduino hardware


character vector

Pin on Arduino hardware, specified as a character vector.

resourceOwner — Owner of pin resource


character vector

2-98
configurePinResource

Owner of pin resource, specified as a character vector.

mode — Mode of terminal


character vector

Mode of terminal, specified as a character vector. Possible mode values are:

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

forceConfig — Forced mode change


boolean

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:

• 'unset' to any mode


• 'Reserved' to any mode
• 'DigitalOutput' to 'PWM'
• 'PWM' to 'DigitalOutput'
• 'DigitalInput' to 'AnalogInput'
• 'AnalogInput' to 'DigitalInput'

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 Count of Servo

Decrement the resource count of a servo created with the parent arduino object.

arduinoObj = obj.Parent; % In the constructor


incrementResourceCount (arduinoObj, 'servo')

decrementResourceCount (arduinoObj, 'servo'); % In destructor

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.

resource — Name of resource to decrement


character vector

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 Count of Servo

Increment the resource count of servo created with the parent arduino object.

arduinoObj = obj.Parent; % In the constructor


incrementResourceCount (arduinoObj, '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.

resourceName — Name of resource


character vector

Name of resource to increment, specified as a character vector.

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 Free Resource Slot On Servo

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.

Create a servo object.

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

Create a second servo object to see the free resource slot.

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.

resourceName — Name of resource


character vector

Name of resource, specified as a character vector.

Output Arguments
slot — Slot number of the first free resource
double

Slot or index number of the next free resource, returned as a 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

Get Number of Servo Resource

Create a servo object, and get a count of resources.

Create a servo object.

arduinoObj = arduino();
s = servo (arduinoObj, 'D2');

Check the current resource count.

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.

resourceName — Name of the resource


character vector

Name of resource to count, specified as a character vector.

Output Arguments
count — Number of resource instances
double

2-106
getResourceCount

Number of instances for a given resource, returned as a double.

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

Set SPI Resource Property

Set the mode of all SPI devices to 1.

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.

resourceName — Name of shared resource


character vector

Name of shared resource, specified as a character vector.

propertyName, propertyValue — Name-Value properties of shared resource


character vector

Specify optional comma-separated pairs of propertyName, propertyValue arguments. Name is


the argument name and Value is the corresponding value. Name must appear inside single quotes ('
'). You can specify several name and value pair arguments in any order as
Name1,Value1,...,NameN,ValueN.
Example: setSharedResourceProperty (arduinoObj, 'spidev', 'Mode', 1);

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

Get SPI Resource Mode

Retrieve the mode of all spidev objects.

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.

resourceName — Name of shared resource


character vector

Name of shared resource, specified as a character vector.

propertyName — Name of shared property


character vector

Name of shared property to retrieve, specified as a character vector.

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

Get Resource Owner

Get resource owner for terminal 14 on your arduino object.


arduinoObj = obj.Parent
getResourceOwner(arduinoObj, 14)

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.

terminal — Physical terminal number on Arduino hardware


double

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

“Physical Terminals and Pin Numbers”

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

The sensor object with the default or specified properties.

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

The sensor object with the default or specified properties.

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

• info function is not supported.

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.

[accelReadings, gyroReadings, magReadings, timeStamps, overrun] = read(


sensorobj) returns matrices of acceleration, angular velocity, magnetic field, time stamps, and
overrun. 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 matrix.
This function signature is available only for the MPU9250 and LSM9DS1 sensors.

[accelReadings, gyroReadings, magReadings, tempReadings, timeStamps, overrun]


= read(sensorobj) returns matrices of acceleration, angular velocity, magnetic field, temperature,
time stamps, and overrun. 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 matrix. This function signature is available only for the ICM20948 sensor.

[accelReadings, gyroReadings, timeStamps, overrun] = read(sensorobj) returns


matrices of acceleration, angular velocity, time stamps, and overrun. 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 matrix. This function signature is available only
for the MPU6050 sensor.

[accelReadings, gyroReadings, tempReadings, timeStamps, overrun] = read(


sensorobj) returns matrices of acceleration, angular velocity, temperature, time stamps, and
overrun. The number of samples depends on the SamplesPerRead value specified while creating the

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.

[accelReadings, magReadings, tempReadings, timeStamps, overrun] = read(


sensorobj) returns matrices of acceleration, magnetic field, temperature, time stamps, and
overrun. 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 matrix.
This function signature is available only for the LSM303C sensor.

[accelReadings, timeStamps, overrun] = read(sensorobj) returns matrices of


acceleration, time stamps, and overrun. 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 matrix. This function signature is available only for the ADXL34x family of
sensors connected using the adxl345 object.

[humidityReading, tempReadings, timeStamps, overrun] = read(sensorobj) returns


matrices of humidity, temperature, time stamps, and overrun. 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 matrix. This function signature is available only for
the HTS221 sensor.

[pressureReading, tempReadings, timeStamps, overrun] = read(sensorobj) returns


matrices of pressure, temperature, time stamps, and overrun. 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 matrix. This function signature is available for
LPS22HB and BMP280 sensors.

[accelReadings, tempReadings, timeStamps, overrun] = read(sensorobj) returns


matrices of acceleration, temperature, time stamps, and overrun. 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 matrix This function signature is available only for
the LIS3DH,

Examples
Read Data from Sensor as a Timetable

Create an Arduino object and include the I2C library.


a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create a sensor object with additional properties.

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

Read five samples of sensor data in datetime format.


[sensorReadings,overrun] = read(sensorobj)

2-117
2 Functions

sensorReadings =

5×3 timetable

Time Acceleration AngularVelocity


________________________ ________________________________ _____________________________

14-Dec-2018 15:01:34.832 -0.28261 0.30836 10.395 0.018968 -0.0050405 -


14-Dec-2018 15:01:34.852 -0.28261 0.30836 10.395 0.018968 -0.0050405 -
14-Dec-2018 15:01:34.872 -0.2874 0.31375 10.432 0.021356 0.001857 0
14-Dec-2018 15:01:34.892 -0.29339 0.30896 10.327 0.020427 -0.0013265 -0
14-Dec-2018 15:01:34.912 -0.29339 0.30896 10.327 0.020427 -0.0013265 -0

overrun =

Read Accel, Gyro, and Mag Data from Sensor as a Matrix

Create an Arduino object and include the I2C library.

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create a sensor object with additional properties.

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.

sensorobj = mpu9250(a,'OutputFormat', 'matrix', 'SamplesPerRead', 2);

Read two samples of sensor data in matrix format.

[accel, gyro, mag, timeStamps, overrun] = sensorobj.read

accel =

-0.6239 1.2747 9.5986


-0.6263 1.2730 9.5861

gyro =

0.0114 -0.0397 0.0155


0.0106 -0.0382 0.0147

mag =

41.0133 101.0625 -13.1813


40.2937 100.3406 -13.8750

timestamps =

2×1 datetime array

2-118
read

4-Feb-2021 15:53:18.790
4-Feb-2021 15:53:18.800

overrun =

Read Accel and Gyro Data from Sensor as a Matrix

Create an Arduino object and include the I2C library.

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create a sensor object with additional properties.

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.

sensorobj = mpu6050(a,'OutputFormat', 'matrix', 'SamplesPerRead', 2);

Read two samples of sensor data in matrix format.

[accel, gyro, timeStamps, overrun] = sensorobj.read

accel =

-0.6239 1.2747 9.5986


-0.6263 1.2730 9.5861

gyro =

0.0114 -0.0397 0.0155


0.0106 -0.0382 0.0147

timestamps =

2×1 datetime array

4-Feb-2021 15:53:18.790
4-Feb-2021 15:53:18.800

overrun =

Input Arguments
sensorobj — sensor object

The sensor object with the default or specified properties.

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:

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2
• AngularVelocity — N-by-3 array in units of rad/s
• MagneticField — N-by-3 array in units of µT (microtesla)
• Temperature — N-by-1 array in units of celsius
• Humidity — N-by-1 array specified in %
• Pressure — N-by-1 array in units of Pascals

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.

Data Types: timetable

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

tempReadings — Sample of the temperature measured in degree Celsius sensor when


output format is set to matrix
N-by-1 matrix

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

timeStamps — Time displayed when sensor data is read


datetime (default) | duration

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

Create an Arduino object and include the I2C library.

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

Create the sensor object for the sensor in use.

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

Return one sample of acceleration data.

accelReadings = readAcceleration(sensorobj)

accelReadings =

-0.7023 0.1317 10.3968

2-122
readAcceleration

Input Arguments
sensorobj — sensor object

The sensor object.

Output Arguments
accelReadings — Value read from the sensor

The acceleration value on x, y, and z axes 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

Create an Arduino object and include the I2C library.

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

Create the sensor object for the sensor in use.

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

Return one sample of angular velocity data.

gyroReadings = readAngularVelocity(sensorobj)

gyroReadings =

0.0138 0.0092 0.0034

2-124
readAngularVelocity

Input Arguments
sensorobj — sensor object

The 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

Create an Arduino object and include the I2C library.

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

Create the sensor object for the sensor in use.

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

Return one sample of magnetic field data.

magReadings = readMagneticField(sensorobj)

magReadings =

16.2797 9.1711 -19.0969

2-126
readMagneticField

Input Arguments
sensorobj — Sensor object

The 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

The sensor object with the default or specified properties.

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

Create an Arduino object and include the I2C library.

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

Create the sensor object for the sensor in use.

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

Return one sample of temperature data.

temperatureReadings = readTemperature(sensorobj)

temperatureReadings =
28.12

Input Arguments
sensorobj — sensor object

2-129
2 Functions

The sensor object with the default or specified properties.

Output Arguments
tempReadings — Value read from the sensor

The temperature 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

Create an Arduino object and include the I2C library.


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

Create the sensor object for the sensor in use.


humiditySensor = hts221(a);

Return one sample of humidity data.


humidityReading = readHumidity(humiditySensor)

humidityReading =
69.6077

Input Arguments
humiditySensor — A sensor connection
object

A sensor connection, specified as a hts221 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

Create an Arduino object and include the I2C library.

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

Create the sensor object for the sensor in use.

pressureSensor = lps22hb(a);

Return one sample of pressure data.

pressureReading = readPressure(pressureSensor)

pressureReading =
9.5014e+04

Input Arguments
pressureSensor — sensor connection
object

A sensor connection, specified as a lps22hb 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

Create an Arduino object and include the I2C library.

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

Create the sensor object for the sensor in use.

sensorObj = lis3dh(a);

Return one sample of voltage data.

sensorObj =

lis3dh with properties:

I2CAddress: 24 ("0x18")
Bus: 0
SCLPin: "D21"
SDAPin: "D20"

SampleRate: 100 (samples/s)


SamplesPerRead: 10
ReadMode: "latest"
SamplesRead: 0
SamplesAvailable: 0
AvailableADCPins: ["ADC1","ADC2","ADC3"]

2-135
2 Functions

Input Arguments
sensorObj — sensor object

The sensor object.

pin — ADC pin


character vector

ADC pin on the sensor, specified as a character vector.

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

serialdevObj = device(arduinoObj,'SerialPort',SerialPort) creates an object that


represents the connection between the serial device connected to the Arduino or ESP32 hardware at
the serial port specified by SerialPort. The Arduino hardware is represented by an arduino
object.

serialdevObj = device(arduinoObj,'SerialPort',SerialPort,Name,Value) creates an


object that represents the connection with additional options specified by one or more Name,Value
pair arguments between the serial device connected to the Arduino or ESP32 hardware.

Input Arguments

SerialPort — Serial port ID


numeric

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.

Note For ESP32 modules, the supported SerialPort value is 2.

arduinoObj — Arduino or ESP32 hardware connection


arduino object

Arduino or ESP32 hardware connection, specified as an arduino object.

4-2
device

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: serialdevObj = device(arduinoObj,'SerialPort',1,'BaudRate',115200);

BaudRate — Bit transmit rate


9600 (default) | 300 | 600 | 1200 | 2400 | 4800 | 14400 | 19200 | 28800 | 38400 | 57600 | 115200

The rate at which bits are transmitted in bits/s specified as a number.


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.

DataBits — Number of data bits to transmit


8 (default) | 5 | 6 | 7

Number of data bits to transmit, specified as a number.


Example: serialdevObj = device(arduinoObj,'SerialPort',1,'BaudRate',115200,
'DataBits',8);

StopBits — Number of bits to indicate end of byte


1 (default) | 2

Number of bits to indicate the end of data transmission, specified as a number.


Example: serialdevObj = device(arduinoObj,'SerialPort',1,'BaudRate',115200,
'DataBits',8, 'StopBits',1);
Data Types: double

Parity — Type of parity check


none (default) | odd | even

Parity for the serial communication specified as a character vector.


Example: serialdevObj = device(arduinoObj,'SerialPort',1,'BaudRate',115200,
'DataBits',8, 'StopBits',1, 'Parity','even');

Timeout — Maximum time to wait for serial data


1 (default) | [0 8]

Maximum time in seconds to wait for serial data, specified as a number.


Example: serialdevObj = device(arduinoObj,'SerialPort',1,'BaudRate',115200,
'DataBits',8, 'StopBits',1, 'Parity','even','Timeout',2);

4-3
4 Serial Functions

Properties
Interface — Type of interface used for communication
'Serial'

This property is read-only.

Type of interface used for communication.


Example:

>> serialdevObj.Interface
ans =
Serial

SerialPort — Serial port ID


numeric

Serial port available on the Arduino or ESP32 hardware, specified as a number.


Example:

>> serialdevObj.SerialPort
ans =
1

Data Types: double

TxPin — Transmission pin


character vector

Transmission pin for serial communication.


Example:

>> serialdevObj.TxPin
ans =
'D18'

Data Types: char

RxPin — Receive pin


character vector

Receive pin for serial communication.


Example:

>> serialdevObj.RxPin
ans =
'D19'

Data Types: char

BaudRate — Bit transmit rate


9600 (default) | 300 | 600 | 1200 | 2400 | 4800 | 14400 | 19200 | 28800 | 38400 | 57600 | 115200

The rate at which bits are transmitted in bits/s specified as a number.

4-4
device

Example:

>> serialdevObj.BaudRate
ans =
115200

Data Types: double

NumBytesAvailable — Number of bytes to read


numeric

This property is read-only.

Number of bytes of data available to read from the serial device, specified as a number.
Example:

>> serialdevObj.NumBytesAvailable
ans =
0

Data Types: double

Parity — Type of parity check


none (default) | odd | even

Parity for the serial communication specified as a character vector.


Example:

>> serialdevObj.Parity
ans =
'even'

Data Types: char

StopBits — Number of bits to indicate end of byte


1 (default) | 2

Number of bits to indicate the end of data transmission, specified as a number.


Example:

>> serialdevObj.StopBits

ans =
1

Data Types: double

DataBits — Number of data bits to transmit


8 (default) | 5 | 6 | 7

Number of data bits to transmit, specified as a number.


Example:

>> serialdevObj.DataBits

4-5
4 Serial Functions

ans =
8

Data Types: double

Timeout — Maximum time to wait for serial data


1 (default) | [0 8]

Maximum time in seconds to wait for serial data, specified as a number.


Example:

>> serialdevObj.Timeout

ans =
1

Data Types: double

Object Functions
read Read data from serial device
write Write data to serial device

Examples

Create Connection to Serial Device on Arduino Hardware

Create an arduino connection.

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

Create a connection to the serial device on the Arduino hardware.

serialdevObj = device(arduinoObj,'SerialPort',1)

serialdevObj =
device with properties:

Interface: 'Serial'
SerialPort: 1
TxPin: 'D1'
RxPin: 'D0'

4-6
device

BaudRate: 9600 (bits/s)


NumBytesAvailable: 0

Show all properties, functions

Specify Baud Rate of Serial Device

Create an arduino connection.


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

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

Show all properties, 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 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.

out = read(serialdevObj,numBytes,precision) also specifies the data precision.

Examples

Read Data from Serial Device on Arduino Hardware

Create an arduino connection.

arduinoObj = arduino("COM16","Leonardo","Libraries",{'SPI','Serial','I2C'});

Create a connection to the serial device on the Arduino hardware.

serialdevObj = device(arduinoObj,'SerialPort',1,'BaudRate', 115200, 'DataBits',8, 'StopBits', 1,

serialdevObj =
device with properties:

Interface: 'Serial'
SerialPort: 1
TxPin: 'D1'
RxPin: 'D0'
BaudRate: 115200 (bits/s)
NumBytesAvailable: 0

Show all properties, functions

Connect the Rx and Tx pins in loopback. Write 3 bytes of data to the serial device.

write(serialdevObj,[88 99 65]);

Check if data is available to read.

numBytes = serialdevObj.NumBytesAvailable

numBytes = 3

Read data from the serial device.

read(serialdevObj,3)

4-9
4 Serial Functions

ans = 1×3

88 99 65

Specify Precision to Read Data from Serial Device on Arduino Hardware

Create an arduino connection


arduinoObj = arduino("COM16","Leonardo","Libraries",{'SPI','Serial','I2C'});

Create a connection to the serial device on the Arduino hardware.


serialdevObj = device(arduinoObj,'SerialPort',1,'BaudRate', 115200, 'DataBits',8, 'StopBits', 1,

serialdevObj =
device with properties:

Interface: 'Serial'
SerialPort: 1
TxPin: 'D1'
RxPin: 'D0'
BaudRate: 115200 (bits/s)
NumBytesAvailable: 0

Show all properties, functions

Connect the Rx and Tx pins in loopback. Write data to the serial device.
write(serialdevObj,256,'uint16');

Check if data is available to read.


numBytes = serialdevObj.NumBytesAvailable

numBytes = 2

Read data from serial device with precision of uint16.


read(serialdevObj,1,'uint16')

ans = 256

Input Arguments
serialdevObj — Serial device connection
device object

Serial device connection, specified as a device object.

numBytes — Number of bytes to read


scalar

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.

precision — Data precision


'uint8' (default) | 'int8' | 'uint16' | 'int16' | 'uint32' | 'int32' | 'uint64' | 'int64'

Data precision, specified as one of the following character vectors:

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

write(serialdevObj,dataIn,precision) also specifies the precision.

Examples

Write Data to Serial Device Connected to Arduino Hardware

Create an arduino connection.

arduinoObj = arduino("COM16","Leonardo","Libraries",{'SPI','Serial','I2C'});

Create a connection to the serial device on the Arduino hardware.

serialdevObj = device(arduinoObj,'SerialPort',1)

serialdevObj =
device with properties:

Interface: 'Serial'
SerialPort: 1
TxPin: 'D1'
RxPin: 'D0'
BaudRate: 9600 (bits/s)
NumBytesAvailable: 0

Show all properties, functions

Write 3 bytes of data to the serial device.

write(serialdevObj,[88 99 65]);

Specify Precision to Write Data to Serial Device on Arduino Hardware

Create an arduino connection.

arduinoObj = arduino("COM16","Leonardo","Libraries",{'SPI','Serial','I2C'});

4-12
write

Create a connection to the serial device on the Arduino hardware.

serialdevObj = device(arduinoObj,'SerialPort',1)

serialdevObj =
device with properties:

Interface: 'Serial'
SerialPort: 1
TxPin: 'D1'
RxPin: 'D0'
BaudRate: 9600 (bits/s)
NumBytesAvailable: 0

Show all properties, functions

Write data to the serial device with the precision of uint16.

write(serialdevObj,256,'uint16');

Input Arguments
serialdevObj — serial device connection
serial device object

Serial device connection specified as a device object.

dataIn — Data to write to serial device


scalar | vector

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.

precision — Data precision


'uint8' (default) | 'int8' | 'uint16' | 'int16' | 'uint32' | 'int32' | 'uint64' | 'int64'

Data precision, specified as one of the following character vectors:

• 'uint8'
• 'int8'
• 'uint16'
• 'int16'
• 'uint32'
• 'int32'
• 'uint64'
• 'int64'

Data can be also be specified in the following formats:

• hexadecimal
• binary

4-13
4 Serial Functions

• char
• string

For example, write(serialdevObj,0x28) writes data in hexadecimal and


write(serialdevObj,0b0010) writes data in binary.

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

CAN Interface Functions


5 CAN Interface Functions

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,device) creates a CAN channel connected to the specified


device.

ch = canChannel(arduinoObj,'MCP2515',ChipSelectPin,InterruptPin) creates a CAN


channel connected to the MCP2515 chip with specified ChipSelectPin and InterruptPin .

ch = canChannel(arduinoObj,device,Name,Value) creates a CAN channel connected to the


specified device with the specified additional options.

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

arduinoObj — Arduino hardware connection


arduino object

Arduino hardware connection created using arduino, specified as an arduino object.

device — Name of CAN device


Sparkfun CAN-Bus Shield | Seeed Studio CAN-Bus Shield V2 | MKR CAN Shield |
MCP2515

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.

ChipSelectPin — Chip select pin number for SPI communication


string

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.

InterruptPin — Interrupt pin number


string

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.

Name-Value Pair Arguments

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

BusSpeed — Frequency at which the CAN bus runs


500000 Hz (default) | 1000000 Hz | 250000 Hz | 200000 Hz | 125000 Hz | 100000 Hz | 62500 Hz |
50000 Hz | 40000 Hz | 31250 Hz | 25000 Hz | 20000 Hz | 12500 Hz | 10000 Hz | 8000 Hz | 5000 Hz

The frequency at which the CAN bus runs, specified as a number.

OscillatorFrequency — Frequency of the oscillator


16000000 Hz (default) | 10000000 Hz | 8000000 Hz

Frequency of the oscillator specified in Hertz.

Properties
Device — Name of CAN device
Sparkfun CAN-Bus Shield | Seeed Studio CAN-Bus Shield V2 | MKR CAN Shield |
MCP2515

This property is read-only.

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"

Data Types: string

ProtocolMode — Communication protocol


CAN (default)

This property is read-only.

5-3
5 CAN Interface Functions

Specifies the protocol used for communication.


Example:
>> ch.ProtocolMode

ans =
"CAN"

Data Types: string

BusSpeed — Frequency at which the CAN bus runs


500000 Hz (default) | 1000000 Hz | 250000 Hz | 200000 Hz | 125000 Hz | 100000 Hz | 62500 Hz |
50000 Hz | 40000 Hz | 31250 Hz | 25000 Hz | 20000 Hz | 12500 Hz | 10000 Hz | 8000 Hz | 5000 Hz

This property is read-only.

The frequency at which the CAN bus runs, specified in Hertz.


Example:
>> ch.BusSpeed

ans =
500000

Database — CAN database information


can.Database

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

OscillatorFrequency — Frequency of the oscillator


16000000 Hz (default) | 10000000 Hz | 8000000 Hz

This property is read-only.

Frequency of the oscillator specified in Hertz.


Example:
>> ch.OscillatorFrequency

ans =
'10000000'

ChipSelectPin — Chip select pin number for SPI communication


string

Chip select pin of MCP2515, specified as a string or character vector.

5-4
canChannel

Example:
>> ch.ChipSelectPin

ans =
"D9"

Data Types: string

InterruptPin — Interrupt pin number


string

Interrupt pin of MCP2515, specified as a string or character vector.


Example:
>> ch.InterrupPin

ans =
"D2"

Data Types: string

Supported CAN Shields

These device input arguments currently support these shields:

Shield Chip Select Pin InterruptPin Oscillator Supported


Frequency Boards
MKR CAN Shield D3 D7 16MHz MKR Form factor
boards
Sparkfun CAN-Bus D10 D2 16MHz Uno
Shield
Seeed Studio CAN- D9 D2 16MHz Uno, Mega, Due,
Bus Shield V2 Leonardo

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

Create an arduino object


arduinoObj = arduino('COM24', 'Uno', 'Libraries', 'CAN')

5-5
5 CAN Interface Functions

arduinoObj =

arduino with properties:

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

Create a connection to the CAN channel on Sparkfun CAN-Bus Shield

ch = canChannel(arduinoObj,"Sparkfun CAN-Bus Shield")

ch =

canChannel with properties:

Device: 'Sparkfun CAN-Bus Shield'


ProtocolMode: 'CAN'
BusSpeed: 500000
Database: []
Show all properties

Device: 'Sparkfun CAN-Bus Shield'


ProtocolMode: 'CAN'
BusSpeed: 500000
Database: []

OscillatorFrequency: 1.600000e+07
ChipSelectPin: "D9"
InterruptPin: "D2"

Create Connection to CAN Channel on MCP2515

Create an arduino object

arduinoObj = arduino('COM24', 'Uno', 'Libraries', 'CAN')

arduinoObj =

arduino with properties:

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

Create a connection to the CAN channel on MCP2515

5-6
canChannel

ch = canChannel(arduinoObj, "MCP2515", "D10", "D2")

ch =

canChannel with properties:

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"

Create Connection to CAN Channel on Shield with Specified Bus Speed

Create an arduino object


arduinoObj = arduino('COM24', 'Uno', 'Libraries', 'CAN')

arduinoObj =

arduino with properties:

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

Create a connection to the CAN channel on Sparkfun CAN-Bus Shield


ch = canChannel(arduinoObj,"Sparkfun CAN-Bus Shield", "BusSpeed", 500e3)

ch =

canChannel with properties:

Device: 'Sparkfun CAN-Bus Shield'


ProtocolMode: 'CAN'
BusSpeed: 500000
Database: []
Show all properties

Device: 'Sparkfun CAN-Bus Shield'


ProtocolMode: 'CAN'
BusSpeed: 500000
Database: []

5-7
5 CAN Interface Functions

OscillatorFrequency: 1.600000e+07
ChipSelectPin: "D9"
InterruptPin: "D2"

Create Connection to CAN Channel on MCP2515 with Specified Bus Speed

Create an arduino object

arduinoObj = arduino('COM24', 'Uno', 'Libraries', 'CAN')

arduinoObj =

arduino with properties:

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

Create a connection to the CAN channel on MCP2515

ch = canChannel(arduinoObj, "MCP2515", "D10", "D2", "OscillatorFrequency", 16e6, "BusSpeed", 500e

ch =

canChannel with properties:

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.

message = read(ch,maxMessages) reads a timetable of CAN messages less than or equal to


maxMessages received on the CAN channel ch.

Examples
Read CAN Messages

Read messages as a timetable.

arduinoObj = arduino('COM24', 'Uno', 'Libraries', 'CAN');


ch = canChannel(arduinoObj,"Sparkfun CAN-Bus Shield", "BusSpeed", 500e3);
read(ch)

The output message timetable

Read Specified Number of CAN Messages

Read messages as a timetable.

arduinoObj = arduino('COM24', 'Uno', 'Libraries', 'CAN');


ch = canChannel(arduinoObj,"Sparkfun CAN-Bus Shield", "BusSpeed", 500e3);
read(ch,5)

The output message timetable

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

Connection to the CAN channel specified as an object.

maxMessages — Maximum number of messages to read


numeric

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.

Note Error and Remote frames are not supported.

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

Transmit messages to the CAN bus.

arduinoObj = arduino('COM24', 'Uno', 'Libraries', 'CAN');


ch = canChannel(arduinoObj,"Sparkfun CAN-Bus Shield", "BusSpeed", 500e3);
write(ch,1,true,[1:8]);

Transmit a CAN Message using Vehicle Network Toolbox

Transmit messages to the CAN bus.

arduinoObj = arduino('COM24', 'Uno', 'Libraries', 'CAN');


ch = canChannel(arduinoObj,"Sparkfun CAN-Bus Shield", "BusSpeed", 500e3);
message = canMessage(500,false,5);
message.Data = [200:204];
write(ch,message);

Input Arguments
ch — Connection to CAN channel
object

Connection to the CAN channel specified as an object.

identifier — ID of message
numeric

ID of the message, specified as a numeric value.

isExtended — Indicates if message ID is extended


true | false

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.

dataArray — Data to write to CAN channel


non negative numeric

Data to write to the CAN channel, specified as a non negative numeric value. The data is truncated to
uint8.

CANMessage — Message to transmit


CAN message object

Message to transmit, specified as a CAN message object. These messages are transmitted via a CAN
channel to other CAN nodes.

Note Error and Remote frames are not supported.

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

GPS Functions — Alphabetical List


6 GPS Functions — Alphabetical List

gpsdev

Connect to GPS receiver on Arduino hardware

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

a — Arduino hardware connection

Arduino hardware connection created using arduino, specified as an object.


Example: gpsObj = gpsdev(a) creates a connection to the GPS receiver on the Arduino object, a.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

SerialPort — Serial port ID


1 (default)

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.

If a property is tunable, you can change its value at any time.

For more information on changing property values, see System Design in MATLAB Using System
Objects.

BaudRate — Baud rate


9600

This property is read-only.

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.

SamplesPerRead — Number of samples read in a single execution of the read function


2 (default)

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

ReadMode — Specify which data samples to be returned


'oldest' (default) | 'latest'

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

SamplesRead — Samples read


double

This property is read-only.

Samples read from the first read. When you release the object, SamplesRead is set to 0.
Data Types: double

SamplesAvailable — Samples in the host buffer


double

This property is read-only.

Samples available in the host buffer. When you release the object, SamplesAvailable is set to 0.
Data Types: double

OutputFormat — Set output format


'timetable' (default) | 'matrix'

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:

• LLA (Latitude, Longitude, Altitude)


• Ground Speed
• Course over ground
• Dilution of Precisions(DOPs), VDOP,HDOP,PDOP,

6-4
gpsdev

• GPS Receiver Time


• Time — Time stamps read from the Arduino hardware in datetime or duration format

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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

Create an Arduino object and include the Serial library.

a = arduino('COM4', 'Mega2560', 'Libraries', 'Serial');

Create the GPS object.

gpsObj = gpsdev(a)

gpsObj =

gpsdev with properties:

SerialPort: 1
BaudRate: 9600 (bits/s)

SamplesPerRead: 2
ReadMode: 'oldest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

Create GPS Connection with Additional Name-Value Pair Arguments

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 =

gpsdev with properties:

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

To verify the functionality, the following GPS modules were used:

• Adafruit Ultimate GPS


• Ublox NEO 6M
• Ublox NEO 7M

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.

[lla,groundSpeed,course, dops,gpsReceiverTime,timestamp, overrun] = read(


gpsObj) returns matrices of measurements from the GPS. This is a non blocking read which returns
N data points in matrix format where N is specified by SamplesPerRead and matrix is specified
using OutputFormat property of the gpsdev object.

Examples
Read Data from GPS

Create an Arduino object and include the Serial library.

a = arduino('COM4', 'Mega2560', 'Libraries', 'Serial');

Create GPS object.

gpsObj = gpsdev(a);

Read samples of GPS data.

tt = read(gpsObj)

tt =

1×5 timetable

Time LLA GroundSpeed Course DO


________________________ __________________________ ___________ ______ __________

31-Jan-2020 11:41:42.475 12.944 77.692 807.7 0.0463 266.6 1.72 0.

Read Data from GPS as a timetable

Create an Arduino object and include the Serial library.

6-7
6 GPS Functions — Alphabetical List

a = arduino('COM4', 'Mega2560', 'Libraries', 'Serial');

Create GPS object with additional properties.

gpsObj = gpsdev(a, "OutputFormat","timetable",'SamplesPerRead',2);

Read samples of GPS data.

[tt,overruns] = read(gpsObj)

tt =

2×5 timetable

Time LLA GroundSpeed Course DO


________________________ __________________________ ___________ ______ __________

31-Jan-2020 11:32:49.459 12.944 77.692 806.8 0.0463 258.87 1.31 0.


31-Jan-2020 11:32:50.416 12.944 77.692 806.9 0.12861 262.7 1.31 0.

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

Time LLA GroundSpeed Course DOPs


__________ __________________________ ___________ ______ ____________________

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

Read Data from GPS as a Matrix

Create an Arduino object and include the Serial library.

a = arduino('COM4', 'Mega2560', 'Libraries', 'Serial');

Create GPS object with additional properties.

gpsObj = gpsdev(a, "OutputFormat","matrix",'SamplesPerRead',2);

Read samples of GPS data.

[lla,speed,course,dops,gpsReceiverTime,timestamp,overruns] = read(gpsObj)

6-8
read

lla =

12.9437 77.6916 807.4000


12.9437 77.6916 807.4000

speed =

0.0154
0.0463

course =

346.0100
270.2100

dops =

1.2400 0.9200 0.8300


1.7700 0.9900 1.4700

gpsReceiverTime =

2×1 datetime array

31-Jan-2020 06:07:01.000
31-Jan-2020 06:07:02.000

timestamp =

2×1 datetime array

31-Jan-2020 11:37:01.734
31-Jan-2020 11:37:02.436

overruns =

75

Input Arguments
gpsObj — GPS object
gpsdev object

The GPS object with the default or specified properties.

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:

• LLA (Latitude, Longitude, Altitude)


• Ground Speed
• Course over ground
• Dilution of Precisions(DOPs), VDOP,HDOP,PDOP,
• GPS Receiver Time
• Time — Time stamps read from the Arduino hardware in datetime or duration format

Data Types: timetable

lla — Position in LLA coordinate system


N-by-3

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

groundSpeed — Speed in m/s


N-by-1

Speed over ground, returned as a real finite N-by-1 column vector.


Data Types: double

course — Course over ground


N-by-1

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

dops — Dilution of precisions


N-by-3

Dilution of precisions, returned as a real finite N-by-3 array. The order of the output is
[PDOP,HDOP,VDOP].
Data Types: double

gpsReceiverTime — UTC time


N-by-1

UTC time returned by the GPS module.


Data Types: datetime

timestamp — Time at which GPS data is read


N-by-1

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.

Data Types: datetime | duration

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.

Since read is non blocking, the following is expected:

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

The GPS object with the default or specified properties.

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.

Data Types: struct

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

The GPS object with the default or specified properties.

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

The GPS sensor object with the default or specified properties.

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

The GPS sensor object with the default or specified properties.

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

The GPS object with the default or specified properties.

dataArray — Raw data


array

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

Motor Carrier Functions


7 Motor Carrier Functions

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:

• MKR1000, MKR1010, and MKRZero (for MKR Motor Carrier)


• Nano33IoT (for Nano Motor carrier)

Creation

Syntax
mcObj = motorCarrier(arduinoObj)

Description

mcObj = motorCarrier(arduinoObj) creates a connection to the MKR Motor Carrier or Nano


Motor Carrier.

Input Arguments

arduinoObj — Arduino hardware connection


object

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

This property is read-only.

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'

Data Types: char

SDAPin — I2C serial data pin


character vector

This property is read-only.

I2C serial data pin on the Arduino hardware used by the MKR Motor Carrier or Nano Motor Carrier.
Example:
>> mcObj.SDAPin
ans =
'A4'

Data Types: char

I2CAddress — I2C device address


102

I2C device address that represents a hexadecimal value, specified as a double.


Example:
>> mcObj.I2CAddress

ans =
102

Data Types: double

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

Create an arduino object with the 'MotorCarrier' library.

arduinoObj = arduino('COM13','MKR1000','Libraries','MotorCarrier')

arduinoObj =

arduino with properties:

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

Create a connection to the MKR Motor Carrier.

mcObj = motorCarrier(arduinoObj)

mcObj =

MotorCarrier with properties:


SCLPin: 'D11'
SDAPin: 'D12'
I2CAddress: 102 ('0x66')

Create a Connection to Nano Motor Carrier

Create an arduino object with the 'MotorCarrier' library.

arduinoObj = arduino('COM11','Nano33IoT','Libraries','MotorCarrier');

arduinoObj =

arduino with properties:

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

Create a connection to the Nano Motor Carrier.

mcObj = motorCarrier(arduinoObj);

mcObj =

MotorCarrier with properties:

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

dcmObj = dcmotor(mcObj,motornumber) creates a connection to the DC motor at the specified


motor number on the MKR Motor Carrier or Nano Motor Carrier.

dcmObj = dcmotor(mcObj,motornumber,Speed) creates a connection to the DC motor at the


specified motor number and specified additional options on the MKR Motor Carrier or Nano Motor
Carrier.

Input Arguments

mcObj — MKR Motor Carrier or Nano Motor Carrier connection


object

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.

motornumber — DC motor number


M1 | M2 | M3 | M4

DC motor number where the motor is connected on an MKR Motor Carrier or Nano Motor Carrier,
specified as a character vector.

Speed — Normalized duty cycle


0 (default)

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

This property is read-only.

Motor number on the MKR Motor Carrier or Nano Motor Carrier where the DC motor is connected.
Example:

>> dcmObj.MotorNumber
ans =
'M1'

Data Types: char

Speed — Normalized duty cycle of DC motor


[-1 1]

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

Data Types: double

Running — DC Motor State


0 (default) | 1

This property is read-only.

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

Data Types: double

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

Create Connection to DC Motor on Nano Motor Carrier

Create an arduino object with the 'MotorCarrier' library.

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

Create a connection to the Nano Motor Carrier

mcObj = motorCarrier(arduinoObj)

mcObj =
MotorCarrier with properties:

SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')

Create a connection to the DC Motor M3.

dcmObj = dcmotor(mcObj,'M3')

dcmObj =
DCMotor with properties:

MotorNumber: 'M3'
Running: 0
Speed: 0

Specify Speed of DC Motor on Nano Motor Carrier

Create an arduino object with the 'MotorCarrier' library.

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier')

arduinoObj =
arduino with properties:

Port: '/dev/ttyACM0'
Board: 'Nano33IoT'

7-8
dcmotor

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

Create a connection to the Nano Motor Carrier.

mcObj = motorCarrier(arduinoObj)

mcObj =
MotorCarrier with properties:

SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')

Create a connection to the DC Motor M3 setting the speed to 0.2

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

Create a connection to the Nano Motor Carrier.

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the DC motor M1.

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

Create a connection to the Nano Motor Carrier.


arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the DC motor M1.


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

dcmObj =
DCMotor with properties:

MotorNumber: 'M1'
Running: 1
Speed: 3.000000e-01

Stop the motor, and display the object.


stop(dcmObj);
dcmObj

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

pidObj = pidMotor(mcObj,PIDNumber) creates a connection to the PID motor at the specified


port number on the Arduino MKR Motor Carrier or the Nano Motor Carrier.

pidObj = pidMotor(mcObj,PIDNumber,controlmode) creates a connection to the PID motor at


the specified port number and the specified control mode on the Arduino MKR Motor Carrier or the
Nano Motor Carrier.

pidObj = pidMotor(mcObj,PIDNumber,controlmode,ppr) creates a connection to the PID


motor at the specified port number with the specified pulses per revolution on the Arduino MKR
Motor Carrier or the Nano Motor Carrier.

pidObj = pidMotor(mcObj,PIDNumber,controlmode,ppr,[PIDGains]) creates a connection


to the PID motor at the specified port number and specified PID gains on the Arduino MKR Motor
Carrier or the Nano Motor Carrier.

Input Arguments

mcObj — MKR Motor Carrier or Nano Motor Carrier connection


object

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.

PIDNumber — PID motor number


1|2

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.

controlmode — Mode of control


'speed' (default) | 'position'

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.

ppr — Number of pulses per revolution


3 (default)

Number of pulses per revolution of the rotary encoder, specified as a number.


Example: pidObj = pidMotor(mcObj,1,'Position',3); sets the pulses pulse per revolution to
3.

[PIDGains] — Proportional, intergral and derivative gains


1-by-3 vector

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:

Board speed Control Mode position Control Mode


Arduino MKR Motor Carrier [2000,200, 0] [25,0,3]
Arduino Nano Motor Carrier [5.2,0.3,0.0] [0.18, 0.0, 0.01]

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.

Example: pidObj = pidMotor(mcObj,1,'Position',3,[25,0,3]); sets the PID gains of the


PID motor on the MKR Motor Carrier to 25, 0, and 3.
Data Types: double

Properties
PIDNumber — PID Motor number
1|2

This property is read-only.

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

Data Types: double

ControlMode — Mode of control


'speed' (default) | 'position'

This property is read-only.

The mode of control of the PID motor, specified as a string.


Example:

>> pidObj.ControlMode
ans =
'speed'

Data Types: char

PulsesPerRevolution — Number of pulses per revolution


3 (default)

This property is read-only.

Number of pulses per revolution of encoder, specified as a number.


Example:

>> pidObj.PulsesPerRevolution
ans =
3

Data Types: double

Kp — Proportional gain
numeric

Proportional gain of the PID control.


Example:

>> pidObj.Kp
ans =
2000

Data Types: double

Ki — Integral gain
numeric

Integral gain of the PID control.


Example:

7-16
pidMotor

>> pidObj.Ki
ans =
200

Data Types: double

Kd — Derivative gain
numeric

Derivative gain of the PID control.


Example:

>> pidObj.Kd
ans =
0

Data Types: double

MaxAcceleration — Maximum acceleration


scalar

This property is read-only.

Maximum acceleration in radians per seconds squared.


Example:

>> pidObj.MaxAcceleration
ans =
2094400000 (rad/s2)

Data Types: double

MaxSpeed — Maximum speed


scalar

This property is read-only.

Maximum acceleration in revolutions per minute.


Example:

>> pidObj.MaxSpeed
ans =
25000 RPM

Data Types: double

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

Create Connection to PID Motor on Nano Motor Carrier

Create an arduino object with the 'MotorCarrier' library.


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

Create a connection to the Nano Motor Carrier.


mcObj = motorCarrier(arduinoObj)

mcObj =
MotorCarrier with properties:

SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')

Create a connection to the PID motor.


pidObj = pidMotor(mcObj,1)

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)

Specify Mode of Control

Create an arduino object with the 'MotorCarrier' library.

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

Create a connection to the Nano Motor Carrier.

mcObj = motorCarrier(arduinoObj)

mcObj =
MotorCarrier with properties:

SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')

Create a connection to the PID motor in 'Position' control mode.

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)

Specify Pulses Per Revolution

Create an arduino object with the 'MotorCarrier' library.

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

Create a connection to the Nano Motor Carrier.

mcObj = motorCarrier(arduinoObj)

mcObj =
MotorCarrier with properties:

SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')

Create a connection to the PID motor in 'Position' control mode.

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)

Specify PID Gains

Create an arduino object with the 'MotorCarrier' library.

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

Create a connection to the Nano Motor Carrier.

mcObj = motorCarrier(arduinoObj)

mcObj =
MotorCarrier with properties:

SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')

Create a connection to the PID motor in 'Position' control mode.

pidObj = pidMotor(mcObj,1,'position',3,[0.18, 0.0, 0.01])

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.

[position,timestamp] = readAngularPosition(pidObj) returns the angular position of the


DC motor shaft, in closed-loop control with the rotary encoder, in radians and the timestamp in the
datetime format.

position = readAngularPosition(pidObj,'Reset',reset) returns the angular position of


the DC motor shaft in radians and resets the encoder count to zero after reading its current value.

[position,timestamp] = readAngularPosition(pidObj,'Reset',reset) returns the


angular position of the DC motor shaft in radians; timestamp in datetime format and resets the
encoder count to zero after reading its current value.

Examples

Read Angular Position of DC Motor in Closed-Loop Control

Create a connection to the Nano Motor Carrier.

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the PID Motor in position control mode.

pidObj = pidMotor(mcObj,1,'position');

Rotate the angular position with feedback from encoder 1 in closed-loop control.

position = readAngularPosition(pidObj);

Read Angular Position of DC Motor in Closed-Loop Control with Timestamp

Create a connection to the Nano Motor Carrier.

7-22
readAngularPosition

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the PID Motor in position control mode.


pidObj = pidMotor(mcObj,1,'position');

Rotate the angular position with feedback from encoder 1 in closed-loop control.
[position,timestamp] = readAngularPosition(pidObj);

Reset Value in Encoder

Create a connection to the Nano Motor Carrier.


arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the PID Motor in position control mode.


pidObj = pidMotor(mcObj,1,'position');

Rotate the angular position with feedback from encoder 1 in closed-loop control.
position = readAngularPosition(pidObj,'Reset',true);

Reset Value in Encoder with Timestamp

Create a connection to the Nano Motor Carrier.


arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the PID Motor in position control mode.


pidObj = pidMotor(mcObj,1,'position');

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.

reset — Reset the count value


false (default) | true

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.

timestamp — Time elapsed


datetime

Time at which MATLAB reads angular position data, specified as a datetime.

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.

[speed,timestamp] = 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, and the timestamp in datetime format.

Examples

Read Current Rotational Speed

Create a connection to the Nano Motor Carrier.


arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the PID Motor in speed control mode.


pidObj = pidMotor(mcObj,1,'speed');

Read the current rotational speed.


speed = readSpeed(pidObj);

Read Current Rotational Speed with Timestamp

Create a connection to the Nano Motor Carrier.


arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the PID Motor in speed control mode.


pidObj = pidMotor(mcObj,1,'speed');

Read the current rotational speed.


[speed,timestamp] = readSpeed(pidObj);

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.

timestamp — Time elapsed


datetime

Time at which MATLAB reads speed data, specified as a datetime.

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.

writeAngularPosition(pidObj,position,mode) rotates the DC motor shaft with feedback


from the encoder in closed loop position control by the position specified in radians, and the specified
mode.

Examples

Set Angular Position of DC Motor in Closed-Loop Control

Create a connection to the Nano Motor Carrier.

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the PID Motor in position control mode.

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

Set Angular Position of DC Motor in Closed-Loop Control with Specified Mode

Create a connection to the Nano Motor Carrier.

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the PID Motor in position control mode.

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.

position — Position of the shaft


double

Position of DC motor shaft, specified in radians.

mode — Mode of calculation of angle of rotation


abs | rel

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

Set Speed of DC Motor in Closed-Loop Control

Create a connection to the Nano Motor Carrier.

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the PID Motor in speed control mode.

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.

speed — Speed of PID motor


numeric

Speed of the motor, specified in revolutions per minute (RPM).

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

encoder = rotaryEncoder(mcObj,channelNumber) creates a connection to the rotary encoder


at the specified channel on the MKR Motor carrier or Nano Motor Carrier.

encoder = rotaryEncoder(mcObj,channelNumber,ppr) creates a connection to the rotary


encoder at the specified channel with the specified pulses per revolution on the MKR Motor Carrier
or Nano Motor Carrier.

Input Arguments

mcObj — MKR Motor Carrier or Nano Motor Carrier connection


object

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.

channelNumber — Encoder channel number


numeric

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.

ppr — Pulses per revolution


3 (default)

Pulses per revolution of the encoder, specified as a number.

7-31
7 Motor Carrier Functions

Example: encoder = rotaryEncoder(mcObj,1,4) creates a connection to a rotary encoder and


sets the pulses per revolution to 4.

Properties
Channel — Channel number of encoder
numeric

This property is read-only.

Channel output of encoder, specified as a scalar.

>> encoder.Channel
ans =
1

Data Types: double

Encoding — Encoding scheme


X4

This property is read-only.

Encoding scheme of the encoder.


Example:

>> encoder.Encoding
ans =
'X4'

Data Types: char

PulsesPerRevolution — Pulses per revolution


3 (default)

This property is read-only.

Pulses per revolution of the encoder, specified as a number.


Example:

>> encoder.PulsesPerRevolution
ans =
4

Data Types: double

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

Create Connection to Rotary Encoder

Create an arduino object with the 'MotorCarrier' library.


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

Create a connection to the Nano Motor Carrier.


mcObj = motorCarrier(arduinoObj)

mcObj =
MotorCarrier with properties:

SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')

Create a connection to the rotary encoder on channel 1.


encoder = rotaryEncoder(mcObj,1)

encoder =
RotaryEncoder with properties:

Channel: 1
PulsesPerRevolution: 3
Encoding: 'X4'

Specify Pulses per Revolution

Create an arduino object with the 'MotorCarrier' library.


arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier')

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

Create a connection to the Nano Motor Carrier.

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.

[count] = readCount(encoder,'Reset',reset) resets the count value from the encoder to


zero when 'Reset' is set to 'true' .

[count,timestamp] = readCount(encoder,'Reset',reset) resets the count value from the


encoder to zero when 'Reset' is set to 'true' and the timestamp in datetime format.

Examples

Read Current Absolute Count Value

Create a connection to the Nano Motor Carrier.

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the rotary encoder.

encoder = rotaryEncoder(mcObj,1);

Read the current absolute count value of encoder register of Nano Motor Carrier.

count = readCount(encoder);

Read Current Absolute Count Value with Timestamp

Create a connection to the Nano Motor Carrier.

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the rotary encoder.

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

Read Current Incremental Count Value

Create a connection to the Nano Motor Carrier.

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the rotary encoder.

encoder = rotaryEncoder(mcObj,1);

Read the current absolute count value of encoder register of Nano Motor Carrier.

count = readCount(encoder,'Reset',true);

Read Current Incremental Count Value with Timestamp

Create a connection to the Nano Motor Carrier.

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the rotary encoder.

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.

reset — Flag to reset count value to 0


false (default) | true

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

Current count value of the encoder, returned as a number.


Data Types: int32

timestamp — Elapsed time


datetime

Time at which MATLAB reads the count, specified as datetime.


Data Types: datetime

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

[speed,timestamp] = readSpeed(encoder) returns the current rotational speed measured by


the rotary encoder in revolutions per minute (RPM) and timestamp in datetime format.

Examples

Read Current Rotational Speed

Create a connection to the Nano Motor Carrier.

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the rotary encoder.

encoder = rotaryEncoder(mcObj,1);

Read the current rotational speed.

speed = readSpeed(encoder);

Read Current Rotational Speed with Timestamp

Create a connection to the Nano Motor Carrier.

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the rotary encoder.

encoder = rotaryEncoder(mcObj,1);

Read the current rotational speed.

[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

timestamp — Time elapsed


datetime

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

Reset Count Value to Zero

Create a connection to the Nano Motor Carrier.

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the rotary encoder.

encoder = rotaryEncoder(mcObj,1);

Reset encoder count value to 0.

resetCount(encoder);

Set Count Value Encoder to Specific Value

Create a connection to the Nano Motor Carrier.

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the rotary encoder.

encoder = rotaryEncoder(mcObj,1);

Reset encoder count value to 10.

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.

count — Encoder count value to set


numeric

Encoder count value to set, specified as a number.

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

servoObj = servo(mcObj,motornumber) creates a connection to the servo motor at the


specified motor number on the Arduino MKR Motor Carrier or Nano Motor Carrier.

Input Arguments

mcObj — MKR Motor Carrier or Nano Motor Carrier connection


object

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.

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.

Properties
MotorNumber — Servo motor number
numeric

This property is read-only.

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

Data Types: numeric

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

Create Connection to Servo Motor on Nano Motor Carrier

Create an arduino object with the 'MotorCarrier' library.

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

Create a connection to the Nano Motor Carrier.

mcObj = motorCarrier(arduinoObj)

mcObj =
MotorCarrier with properties:

SCLPin: 'A5'
SDAPin: 'A4'
I2CAddress: 102 ('0x66')

Create a servo motor connection.

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

Set Servo Motor Position

Create a connection to the Nano Motor Carrier.

arduinoObj = arduino('/dev/ttyACM0','Nano33IoT','Libraries','MotorCarrier');
mcObj = motorCarrier(arduinoObj);

Create a connection to the servo motor 1.

servoObj = servo(mcObj,1)

servoObj =
Servo with properties:

MotorNumber: 1 (Servo1)

Rotate the motor shaft to 90 degrees or pi/2 radians.

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 — Position of shaft


numeric

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

Unified BNO055 Functions


8 Unified BNO055 Functions

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

a — Arduino hardware connection


arduino object

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.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

8-2
bno055

OperatingMode — Option to output data in NDOF or AMG mode


ndof (default) | amg

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

I2CAddress — Specify I2C address of sensor


'0x28' (default) | '0x29'

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.

Pin Name Pin State I2C Address


COM3 Low 0x28
High 0x29

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format


• String of hexadecimal value of I2C Address
• Character vector of hexadecimal value of I2C Address

Example: imu = bno055(a,'I2CAddress','0x28')

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1.


Example: imu = bno055(a, 'Bus', 1)
Data Types: double

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

SampleRate — Rate at which sample is read


100 (default) | positive numeric in the range [24, 200]

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

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

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


'latest' (default) | 'oldest'

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

SamplesRead — Samples read


double

This property is read-only.

Samples read from the first read. When you release the object, SamplesRead is set to 0.
Data Types: double

SamplesAvailable — Samples in the host buffer


double

This property is read-only.

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

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2
• AngularVelocity — N-by-3 array in units of rad/s
• MagneticField — N-by-3 array in units of µT (microtesla)
• Orientation — N-by-3 array in units of radians

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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

Create an arduino object and include the I2C library.


a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the sensor object.


imu = bno055(a,'OperatingMode','ndof')

imu =

bno055 with properties:

OperatingMode: "ndof"

I2CAddress: 40 ("0x28")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

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

bno055 with properties:

OperatingMode: "ndof"

I2CAddress: 40 ("0x28")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 5
ReadMode: "oldest"
SamplesRead: 0
SamplesAvailable: 0

Show all properties, functions

Create Connection to BNO055 in AMG Mode

Create an arduino object and include the I2C library.


a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create a sensor object.


imu = bno055(a,'OperatingMode','amg')

imu =

bno055 with properties:

OperatingMode: "amg"

I2CAddress: 40 ("0x28")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

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 =

bno055 with properties:

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

Show all properties, functions

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.

[accelReadings, gyroReadings, magReadings, timeStamps, overrun] = read(


bno055) returns matrices of acceleration, gyroscope, magnetic field, orientation, time stamps, and
overrun data in AMG mode. 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 matrix.

[accelReadings, gyroReadings, magReadings, orientationReadings,timeStamps,


overrun] = read(bno055) returns matrices of acceleration, gyroscope, magnetic field, time
stamps, and overrun data in NDOF mode. 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 matrix.“Calibrate BNO055 Sensors” before using the read to ensure accurate
values are read from sensor in NDOF operating mode.

Examples
Read Data from Sensor in NDOF Mode as a Timetable

Create an arduino object.


a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create a sensor object with additional properties.


imu = bno055(a,'OperatingMode','ndof','SamplesPerRead',5,'ReadMode','Latest')

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

Time Acceleration AngularVelocity


________________________ _______________________ ______________________________________

21-Jul-2020 16:24:25.538 0 0.35 9.82 0.0032725 -0.0054542 -0.0021817


21-Jul-2020 16:24:25.548 -0.05 0.32 9.84 -0.0021817 0.0010908 0.0010908
21-Jul-2020 16:24:25.558 -0.03 0.32 9.75 -0.0010908 0.0010908 -0.0010908
21-Jul-2020 16:24:25.568 0 0.34 9.82 0.0010908 -0.0021817 0
21-Jul-2020 16:24:25.578 0 0.36 9.77 0.006545 -0.0010908 -0.0021817

Read Data from Sensor in AMG Mode as a Timetable

Create an arduino object.

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create a sensor object with additional properties.

imu = bno055(a,'OperatingMode','amg','SampleRate',100,'SamplesPerRead',5)

Read five samples of sensor data in datetime format.

sensorReadings = read(imu)

sensorReadings =

5×3 timetable

Time Acceleration AngularVelocity


________________________ _______________________ ______________________________________

21-Jul-2020 16:29:51.323 -0.02 0.32 9.87 0.0032725 -0.01309 0.0021817


21-Jul-2020 16:29:51.333 -0.02 0.32 9.87 0.0032725 -0.0032725 0.0021817
21-Jul-2020 16:29:51.343 0.02 0.35 9.82 -0.0032725 0.0076358 0.0032725
21-Jul-2020 16:29:51.353 0.02 0.35 9.82 -0.0032725 0.0021817 0.0010908
21-Jul-2020 16:29:51.363 -0.03 0.32 9.86 0 -0.0098175 0.0010908

Read Data from Sensor in NDOF Mode as a Matrix

Create an arduino object.

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create a sensor object with additional properties.

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, gyroReadings, magReadings, orientationReadings,timeStamps, overrun] = read(imu)

accelReadings =

-0.0400 0.3000 9.7500


-0.0500 0.3100 9.8400
-0.0200 0.3300 9.8100
0 0.3400 9.8800

8-10
read

-0.0400 0.3200 9.7700

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 =

23.8750 -20.5625 -4.0000


23.8750 -20.5625 -4.0000
23.8750 -20.5625 -4.0000
23.0625 -20.8750 -4.7500
23.0625 -20.8750 -4.7500

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 =

5×1 datetime array

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

Read Data from Sensor in AMG Mode as a Matrix

Create an arduino object.


a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create a sensor object with additional properties.


imu = bno055(a,’SamplesPerRead’,5,’OutputFormat’,’matrix’,’OperatingMode’,’amg’)

Read five samples of sensor data as a matrix.


[accelReadings, gyroReadings, magReadings, orientationReadings,timeStamps, overrun] = read(imu)

8-11
8 Unified BNO055 Functions

accelReadings =

-0.0400 0.3000 9.7500


-0.0500 0.3100 9.8400
-0.0200 0.3300 9.8100
0 0.3400 9.8800
-0.0400 0.3200 9.7700

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 =

23.8750 -20.5625 -4.0000


23.8750 -20.5625 -4.0000
23.8750 -20.5625 -4.0000
23.0625 -20.8750 -4.7500
23.0625 -20.8750 -4.7500

timeStamps =

5×1 datetime array

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

BNO055 sensor object with the default or specified properties.

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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2
• AngularVelocity — N-by-3 array in units of rad/s
• MagneticField — N-by-3 array in units of µT (microtesla)
• Orientation — N-by-3 array in units of radians

Data Types: timetable

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

orientationReadings — Orientation of sensor when output format is set to matrix


N-by-3 matrix

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

timeStamps — Time displayed when sensor data is read


datetime (default) | duration

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

Create an arduino object


a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the BNO055 sensor object.


imu = bno055(a,'OperatingMode','ndof');

Calibrate the sensor using steps mentioned in “Calibrate BNO055 Sensors”


tic;
while (toc < 120)
[status,timestamp] = readCalibrationStatus(imu);
if strcmpi(status.Accelerometer,'full')
break; %Accelerometer is calibrated proceed further
end
pause(1);
end

Read acceleration data.


[accelReadings,timestamp] = readAcceleration(imu)

accelReadings = 1×3

-1.4600 0.4300 -9.6000

timestamp = datetime
21-Jul-2020 15:47:59.835

Read Acceleration Data from Sensor in AMG Mode

Create an arduino object


a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

8-15
8 Unified BNO055 Functions

Create the BNO055 sensor object.

imu = bno055(a,'OperatingMode','amg');

Read acceleration data.

accelReadings = readAcceleration(imu)

accelReadings =

-0.7023 0.1317 10.3968

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

Create an arduino object


a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the BNO055 sensor object.


imu = bno055(a,'OperatingMode','ndof');

Calibrate the sensor using steps mentioned in “Calibrate BNO055 Sensors”


tic;
while (toc < 120)
[status,timestamp] = readCalibrationStatus(BNO055Sensor);
if strcmpi(status.Magnetometer,'full')
break; %If Magnetometer is calibrated proceed further
end
pause(1);
end

Read angular velocity data.


[magReadings,timestamp] = readMagneticField(imu)

magReadings = 3×1

9.5625 18.1875 23.0625

timestamp = datetime
21-Jul-2020 15:00:24.753

Read Magnetic Field Strength from Sensor in AMG Mode

Create an arduino object


a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

8-17
8 Unified BNO055 Functions

Create the BNO055 sensor object.

imu = bno055(a,'OperatingMode','amg');

Read angular velocity data.

[magReadings,timestamp] = readMagneticField(imu)

magReadings =

16.2797 9.1711 -19.0969

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

Create an arduino object


a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the BNO055 sensor object.


imu = bno055(a,'OperatingMode','ndof');

Calibrate the sensor using steps mentioned in “Calibrate BNO055 Sensors”


tic;
while (toc < 50)
[status,timestamp] = readCalibrationStatus(imu);
if strcmpi(status.Gyroscope,'full')
break; %If Gyroscope is calibrated proceed further
end
pause(1);
end

Read angular velocity data.


[gyroReadings,timestamp] = readAngularVelocity(imu)

gyroReadings = 3×1

0.0011 0.0011 0

timestamp = datetime
21-Jul-2020 14:53:36.836

Read Angular Velocity from Sensor in AMG Mode

Create an arduino object


a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

8-20
readAngularVelocity

Create the BNO055 sensor object.

imu = bno055(a,'OperatingMode','amg');

Read angular velocity data.

[gyroReadings,timestamp] = readAngularVelocity(imu)

gyroReadings = 3×1

0.0138 0.0092 0.0034

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

Create an arduino object

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the BNO055 sensor object.

imu = bno055(a,'OperatingMode','ndof');

Calibrate the sensor using steps mentioned in “Calibrate BNO055 Sensors”.

pause(50)

Read calibration status of sensor.

[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

Value as seen by the Sensor status Sensor Status


0 "uncalibrated" Sensor is uncalibrated
1 "partial" Sensor is partially calibrated
2 "partial" Sensor is partially calibrated
3 "full" Sensor is fully calibrated

Data Types: struct

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.

Value Calibration Status


0 uncalibrated
1 or 2 partially calibrated
3 fully calibrated

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

Create an arduino object

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the BNO055 sensor object.

imu = bno055(a,'OperatingMode','ndof');

Calibrate the sensor using steps mentioned in “Calibrate BNO055 Sensors”

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

Read orientation data.

[readVal,timestamp] = readOrientation(imu)

readVal = 3×1

6.2046 3.0729 -0.3011

timestamp = datetime datetime


21-Jul-2020 14:09:57.615

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.

Angular Quantity Description Range in Radians


Azimuth Angle between y- axis of the [0,2pi]
sensor and magnetic north
Pitch Angle between z- axis and y- [-pi,pi]
axis of the sensor
Roll Angle between z- axis and x- [-pi/2,pi/2]
axis of the sensor

Data Types: double

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

BNO055 sensor object with the default or specified properties.

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

Create an arduino object and include the I2C library.

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the sensor object and read info.

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

BNO055 sensor object with the default or specified properties.

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

LSMDS Functions — Alphabetical List


9 LSMDS Functions — Alphabetical List

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) creates a sensor object with default property values.


Example: imu = lsm6ds3(a);.

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

a — Connection to the hardware


object

Connection to the hardware specified as an object.


Example: imu = lsm6ds3(a) creates a connection to the LSM6DS3 sensor on the hardware
represented as an object, a.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

I2CAddress — Specify I2C address of sensor


0x6A | 0x6B

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.

Pin Name Pin State I2C Address


SDO/SA0 Low 0x6A
High 0x6B

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format


• String of hexadecimal value of I2C Address
• Character vector of hexadecimal value of I2C Address

Example: imu = lsm6ds3(a,'I2CAddress',0x6A)

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Example: imu = lsm6ds3(a, 'Bus', 1) creates the sensor object on Bus 1 of the hardware.
Data Types: double

Properties

Note The properties can also be used as name-value pair arguments while creating an lsm6ds3
object.

I2CAddress — Specify I2C address of sensor


0x6A | 0x6B

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.

Pin Name Pin State I2C Address


SDO/SA0 Low 0x6A
High 0x6B

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format

9-3
9 LSMDS Functions — Alphabetical List

• String of hexadecimal value of I2C Address


• Character vector of hexadecimal value of I2C Address

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Data Types: double

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.

SampleRate — Rate at which sample is read


100 (default) | positive integer in the range [12.5, 200]

The rate in samples/s at which data is read from the sensor.


Data Types: double

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

Number of samples read from the sensor in a single execution of the read function.
Data Types: double

ReadMode — Specify which data samples to be returned


'latest' (default) | 'oldest'

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.

Data Types: character vector | string

SamplesRead — Samples read


double

This property is read-only.

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

SamplesAvailable — Samples in the host buffer


double

This property is read-only.

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

Data Types: double

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2
• AngularVelocity — N-by-3 array in units of rad/s
• Temperature — N-by-1 array in units of degree Celsius

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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.

Data Types: character vector | string

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

Create an arduino object with the I2C library.


a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the sensor object.

9-6
lsm6ds3

imu = lsm6ds3(a)

imu =

lsm6ds3 with properties:

I2CAddress: 106 ("0x6B")


SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

Create LSM6DS3 Sensor Connection with Additional Name-Value Pair Arguments

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 =

lsm6ds3 with properties:

I2CAddress: 107 ("0x6B")


Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 110 (samples/s)


SamplesPerRead: 3
ReadMode: "oldest"
SamplesRead: 0
SamplesAvailable: 0

Show all properties all functions

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) creates a sensor object with default property values.


Example: imu = lsm6ds3h(a);.

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

a — Connection to the hardware


object

Connection to the hardware specified as an object.


Example: imu = lsm6ds3h(a) creates a connection to the LSM6DS3H sensor on the hardware
represented as an object, a.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

I2CAddress — Specify I2C address of sensor


0x6A | 0x6B

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.

Pin Name Pin State I2C Address


SDO/SA0 Low 0x6A
High 0x6B

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format


• String of hexadecimal value of I2C Address
• Character vector of hexadecimal value of I2C Address

Example: imu = lsm6ds3h(a,'I2CAddress',0x6A)

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Example: imu = lsm6ds3h(a, 'Bus', 1) creates the sensor object on Bus 1 of the hardware.
Data Types: double

Properties

Note The properties can also be used as name-value pair arguments while creating an lsm6ds3h
object.

I2CAddress — Specify I2C address of sensor


0x6A | 0x6B

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.

Pin Name Pin State I2C Address


SDO/SA0 Low 0x6A
High 0x6B

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format

9-10
lsm6ds3h

• String of hexadecimal value of I2C Address


• Character vector of hexadecimal value of I2C Address

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Data Types: double

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.

SampleRate — Rate at which sample is read


100 (default) | positive integer in the range [12.5, 200]

The rate in samples/s at which data is read from the sensor.


Data Types: double

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

Number of samples read from the sensor in a single execution of the read function.
Data Types: double

ReadMode — Specify which data samples to be returned


'latest' (default) | 'oldest'

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.

Data Types: character vector | string

SamplesRead — Samples read


double

This property is read-only.

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

SamplesAvailable — Samples in the host buffer


double

This property is read-only.

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

Data Types: double

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2
• AngularVelocity — N-by-3 array in units of rad/s
• Temperature — N-by-1 array in units of degree Celsius

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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.

Data Types: character vector | string

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

Create an arduino object with the I2C library.

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the sensor object.

9-13
9 LSMDS Functions — Alphabetical List

imu = lsm6dsh3(a)

imu =

lsm6ds3h with properties:

I2CAddress: 106 ("0x6B")


SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

Create LSM6DS3H Sensor Connection with Additional Name-Value Pair Arguments

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 =

lsm6dsh3 with properties:

I2CAddress: 107 ("0x6B")


Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 110 (samples/s)


SamplesPerRead: 3
ReadMode: "oldest"
SamplesRead: 0
SamplesAvailable: 0

Show all properties all functions

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) creates a sensor object with default property values.


Example: imu = lsm6dsl(a);.

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

a — Connection to the hardware


object

Connection to the hardware specified as an object.


Example: imu = lsm6dsl(a) creates a connection to the LSM6DSL sensor on the hardware
represented as an object, a.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

I2CAddress — Specify I2C address of sensor


0x6A | 0x6B

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.

Pin Name Pin State I2C Address


SDO/SA0 Low 0x6A
High 0x6B

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format


• String of hexadecimal value of I2C Address
• Character vector of hexadecimal value of I2C Address

Example: imu = lsm6dsl(a,'I2CAddress',0x6A)

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Example: imu = lsm6dsl(a, 'Bus', 1) creates the sensor object on Bus 1 of the hardware.
Data Types: double

Properties

Note The properties can also be used as name-value pair arguments while creating an lsm6dsl
object.

I2CAddress — Specify I2C address of sensor


0x6A | 0x6B

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.

Pin Name Pin State I2C Address


SDO/SA0 Low 0x6A
High 0x6B

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format

9-17
9 LSMDS Functions — Alphabetical List

• String of hexadecimal value of I2C Address


• Character vector of hexadecimal value of I2C Address

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Data Types: double

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.

SampleRate — Rate at which sample is read


100 (default) | positive integer in the range [12.5, 200]

The rate in samples/s at which data is read from the sensor.


Data Types: double

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

Number of samples read from the sensor in a single execution of the read function.
Data Types: double

ReadMode — Specify which data samples to be returned


'latest' (default) | 'oldest'

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.

Data Types: character vector | string

SamplesRead — Samples read


double

This property is read-only.

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

SamplesAvailable — Samples in the host buffer


double

This property is read-only.

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

Data Types: double

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2
• AngularVelocity — N-by-3 array in units of rad/s
• Temperature — N-by-1 array in units of degree Celsius

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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.

Data Types: character vector | string

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

Create an arduino object with the I2C library.

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the sensor object.

9-20
lsm6dsl

imu = lsm6dsl(a)

imu =

lsm6dsl with properties:

I2CAddress: 106 ("0x6B")


SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

Create LSM6DSL Sensor Connection with Additional Name-Value Pair Arguments

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 =

lsm6dsl with properties:

I2CAddress: 107 ("0x6B")


Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 110 (samples/s)


SamplesPerRead: 3
ReadMode: "oldest"
SamplesRead: 0
SamplesAvailable: 0

Show all properties all functions

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) creates a sensor object with default property values.


Example: imu = lsm6dsm(a);.

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

a — Connection to the hardware


object

Connection to the hardware specified as an object.


Example: imu = lsm6dsm(a) creates a connection to the LSM6DSM sensor on the hardware
represented as an object, a.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

I2CAddress — Specify I2C address of sensor


0x6A | 0x6B

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.

Pin Name Pin State I2C Address


SDO/SA0 Low 0x6A
High 0x6B

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format


• String of hexadecimal value of I2C Address
• Character vector of hexadecimal value of I2C Address

Example: imu = lsm6dsm(a,'I2CAddress',0x6A)

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Example: imu = lsm6dsm(a, 'Bus', 1) creates the sensor object on Bus 1 of the hardware.
Data Types: double

Properties

Note The properties can also be used as name-value pair arguments while creating an lsm6dsm
object.

I2CAddress — Specify I2C address of sensor


0x6A | 0x6B

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.

Pin Name Pin State I2C Address


SDO/SA0 Low 0x6A
High 0x6B

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format

9-24
lsm6dsm

• String of hexadecimal value of I2C Address


• Character vector of hexadecimal value of I2C Address

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Data Types: double

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.

SampleRate — Rate at which sample is read


100 (default) | positive integer in the range [12.5, 200]

The rate in samples/s at which data is read from the sensor.


Data Types: double

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

Number of samples read from the sensor in a single execution of the read function.
Data Types: double

ReadMode — Specify which data samples to be returned


'latest' (default) | 'oldest'

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.

Data Types: character vector | string

SamplesRead — Samples read


double

This property is read-only.

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

SamplesAvailable — Samples in the host buffer


double

This property is read-only.

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

Data Types: double

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2
• AngularVelocity — N-by-3 array in units of rad/s
• Temperature — N-by-1 array in units of degree Celsius

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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.

Data Types: character vector | string

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

Create an arduino object with the I2C library.

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the sensor object.

9-27
9 LSMDS Functions — Alphabetical List

imu = lsm6dsm(a)

imu =

lsm6dsm with properties:

I2CAddress: 106 ("0x6B")


SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

Create LSM6DSM Sensor Connection with Additional Name-Value Pair Arguments

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 =

lsm6dsm with properties:

I2CAddress: 107 ("0x6B")


Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 110 (samples/s)


SamplesPerRead: 3
ReadMode: "oldest"
SamplesRead: 0
SamplesAvailable: 0

Show all properties all functions

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) creates a sensor object with default property values.


Example: imu = lsm6dso(a);.

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

a — Connection to the hardware


object

Connection to the hardware specified as an object.


Example: imu = lsm6dso(a) creates a connection to the LSM6DSO sensor on the hardware
represented as an object, a.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

I2CAddress — Specify I2C address of sensor


0x6A | 0x6B

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.

Pin Name Pin State I2C Address


SDO/SA0 Low 0x6A
High 0x6B

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format


• String of hexadecimal value of I2C Address
• Character vector of hexadecimal value of I2C Address

Example: imu = lsm6dso(a,'I2CAddress',0x6A)

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Example: imu = lsm6dso(a, 'Bus', 1) creates the sensor object on Bus 1 of the hardware.
Data Types: double

Properties

Note The properties can also be used as name-value pair arguments while creating an lsm6dso
object.

I2CAddress — Specify I2C address of sensor


0x6A | 0x6B

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.

Pin Name Pin State I2C Address


SDO/SA0 Low 0x6A
High 0x6B

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format

9-31
9 LSMDS Functions — Alphabetical List

• String of hexadecimal value of I2C Address


• Character vector of hexadecimal value of I2C Address

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Data Types: double

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.

SampleRate — Rate at which sample is read


100 (default) | positive integer in the range [12.5, 200]

The rate in samples/s at which data is read from the sensor.


Data Types: double

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

Number of samples read from the sensor in a single execution of the read function.
Data Types: double

ReadMode — Specify which data samples to be returned


'latest' (default) | 'oldest'

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.

Data Types: character vector | string

SamplesRead — Samples read


double

This property is read-only.

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

SamplesAvailable — Samples in the host buffer


double

This property is read-only.

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

Data Types: double

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2
• AngularVelocity — N-by-3 array in units of rad/s
• Temperature — N-by-1 array in units of degree Celsius

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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.

Data Types: character vector | string

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

Create an arduino object with the I2C library.

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the sensor object.

9-34
lsm6dso

imu = lsm6dso(a)

imu =

lsm6dso with properties:

I2CAddress: 106 ("0x6B")


SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

Create LSM6DSO Sensor Connection with Additional Name-Value Pair Arguments

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 =

lsm6dso with properties:

I2CAddress: 107 ("0x6B")


Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 110 (samples/s)


SamplesPerRead: 3
ReadMode: "oldest"
SamplesRead: 0
SamplesAvailable: 0

Show all properties all functions

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) creates a sensor object with default property values.


Example: imu = lsm6dsr(a);.

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

a — Connection to the hardware


object

Connection to the hardware specified as an object.


Example: imu = lsm6dsr(a) creates a connection to the LSM6DSR sensor on the hardware
represented as an object, a.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

I2CAddress — Specify I2C address of sensor


0x6A | 0x6B

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.

Pin Name Pin State I2C Address


SDO/SA0 Low 0x6A
High 0x6B

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format


• String of hexadecimal value of I2C Address
• Character vector of hexadecimal value of I2C Address

Example: imu = lsm6dsr(a,'I2CAddress',0x6A)

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Example: imu = lsm6dsr(a, 'Bus', 1) creates the sensor object on Bus 1 of the hardware.
Data Types: double

Properties

Note The properties can also be used as name-value pair arguments while creating an lsm6dsr
object.

I2CAddress — Specify I2C address of sensor


0x6A | 0x6B

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.

Pin Name Pin State I2C Address


SDO/SA0 Low 0x6A
High 0x6B

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format

9-38
lsm6dsr

• String of hexadecimal value of I2C Address


• Character vector of hexadecimal value of I2C Address

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Data Types: double

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.

SampleRate — Rate at which sample is read


100 (default) | positive integer in the range [12.5, 200]

The rate in samples/s at which data is read from the sensor.


Data Types: double

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

Number of samples read from the sensor in a single execution of the read function.
Data Types: double

ReadMode — Specify which data samples to be returned


'latest' (default) | 'oldest'

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.

Data Types: character vector | string

SamplesRead — Samples read


double

This property is read-only.

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

SamplesAvailable — Samples in the host buffer


double

This property is read-only.

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

Data Types: double

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2
• AngularVelocity — N-by-3 array in units of rad/s
• Temperature — N-by-1 array in units of degree Celsius

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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.

Data Types: character vector | string

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

Create an arduino object with the I2C library.

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the sensor object.

9-41
9 LSMDS Functions — Alphabetical List

imu = lsm6dsr(a)

imu =

lsm6dsr with properties:

I2CAddress: 106 ("0x6B")


SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

Create LSM6DSR Sensor Connection with Additional Name-Value Pair Arguments

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 =

lsm6dsr with properties:

I2CAddress: 107 ("0x6B")


Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 110 (samples/s)


SamplesPerRead: 3
ReadMode: "oldest"
SamplesRead: 0
SamplesAvailable: 0

Show all properties all functions

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

humiditySensor = hts221(a) creates a sensor object with default property values.


Example: humiditySensor = hts221(a);.

humiditySensor = hts221(a,Name,Value) creates a sensor object with properties using one or


more Name,Value pair arguments.
Example: humiditySensor = hts221(a, 'Bus', 1);.

Input Arguments

a — Connection to the hardware


object

Connection to the hardware specified as an object.


Example: humiditySensor = hts221(a) creates a connection to the HTS221 sensor on the
hardware represented as an object, a.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Bus — I2C Bus Number


0 (default) | 1

9-44
hts221

I2C bus number, specified as 0 or 1. The default value is 0.


Example: humiditySensor = hts221(a, 'Bus', 1) creates the sensor object on Bus 1 of the
hardware.
Data Types: double

Properties

Note The properties can also be used as name-value pair arguments while creating an hts221
object.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Data Types: double

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.

SampleRate — Rate at which sample is read


100 (default) | positive integer in the range [1, 200]

The rate in samples/s at which data is read from the sensor.


Data Types: double

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

Number of samples read from the sensor in a single execution of the read function.
Data Types: double

ReadMode — Specify which data samples to be returned


'latest' (default) | 'oldest'

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.

Data Types: character vector | string

SamplesRead — Samples read


double

This property is read-only.

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

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Humidity — N-by-1 array in units of %

9-46
hts221

• Temperature — N-by-1 array in units of degree Celsius

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.

N is the number of samples per read specified by SamplesPerRead.


Data Types: character vector | string

TimeFormat — Set time format


'datetime' (default) | 'duration'

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.

Data Types: character vector | string

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

Create an arduino object with the I2C library.

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the sensor object.

humiditySensor = hts221(a)

humiditySensor =

hts221 with properties:

I2CAddress: 95 ("0x5F")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0

9-47
9 LSMDS Functions — Alphabetical List

SamplesAvailable: 0
Show all properties all functions

Create HTS221 Sensor Connection with Additional Name-Value Pair Arguments

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 =

hts221 with properties:

I2CAddress: 95 ("0x5F")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 50 (Samples/s)
SamplesPerRead: 5
ReadMode: 'oldest'
SamplesRead: 0
SamplesAvailable: 0

Show all properties, functions

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

pressureSensor = lps22hb(a) creates a sensor object with default property values.


Example: pressureSensor = lps22hb(a);.

pressureSensor = lps22hb(a,Name,Value) creates a sensor object with properties using one


or more Name,Value pair arguments.
Example: pressureSensor = lps22hb(a,'I2CAddress',0x5D);.

Input Arguments

a — Connection to the hardware


object

Connection to the hardware specified as an object.


Example: pressureSensor = lps22hb(a) creates a connection to the LPS22HB sensor on the
hardware represented as an object, a.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

I2CAddress — Specify I2C address of sensor


'0x5C' (default) | '0x5D'

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.

Pin Name Pin State I2C Address


SA0 Low 0x5C
High 0x5D

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format


• String of hexadecimal value of I2C Address
• Character vector of hexadecimal value of I2C Address

Example: pressureSensor = lps22hb(a,'I2CAddress',0x5C)

0x5C is the I2C address of the LPS22HB 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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Example: pressureSensor = lps22hb(a, 'Bus', 1) creates the sensor object on Bus 1 of the
hardware.
Data Types: double

Properties

Note The properties can also be used as name-value pair arguments while creating an lps22hb
object.

I2CAddress — Specify I2C address of sensor


'0x5C' (default) | '0x5D'

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.

Pin Name Pin State I2C Address


SA0 Low 0x5C
High 0x5D

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format

9-50
lps22hb

• String of hexadecimal value of I2C Address


• Character vector of hexadecimal value of I2C Address

0x5C is the I2C address of the LPS22HB 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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Data Types: double

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.

SampleRate — Rate at which sample is read


100 (default) | positive integer in the range [1, 200]

The rate in samples/s at which data is read from the sensor.


Data Types: double

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

Number of samples read from the sensor in a single execution of the read function.
Data Types: double

ReadMode — Specify which data samples to be returned


'latest' (default) | 'oldest'

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.

Data Types: character vector | string

SamplesRead — Samples read


double

This property is read-only.

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

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Pressure — Barometric air pressure in Pascals (Pa)

9-52
lps22hb

• Temperature — Temperature in units of celsius

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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.

Data Types: character vector | string

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

Create an arduino object with the I2C library.

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the sensor object.

pressureSensor = lps22hb(a)

pressureSensor =

lps22hb with properties:

I2CAddress: 92 ("0x5C")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0

9-53
9 LSMDS Functions — Alphabetical List

Show all properties, functions

Create LPS22HB Sensor Connection with Additional Name-Value Pair Arguments

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 =

lps22hb with properties:

I2CAddress: 92 ("0x5C")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (samples/s)


SamplesPerRead: 10
ReadMode: "oldest"
SamplesRead: 0
SamplesAvailable: 0

Show all properties all functions

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) creates a sensor object with default property values.


Example: imu = lsm303c(a);.

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

a — Connection to the hardware


object

Connection to the hardware specified as an object.


Example: imu = lsm303c(a) creates a connection to the LSM303C sensor on the hardware
represented as an object, a.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Bus — I2C Bus Number


0 (default) | 1

9-55
9 LSMDS Functions — Alphabetical List

I2C bus number, specified as 0 or 1. The default value is 0.


Data Types: double

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.

SampleRate — Rate at which sample is read


100 (default) | positive integer in the range [11, 200]

The rate in samples/s at which data is read from the sensor.


Data Types: double

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

Number of samples read from the sensor in a single execution of the read function.
Data Types: double

ReadMode — Specify which data samples to be returned


'latest' (default) | 'oldest'

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.

Data Types: character vector | string

SamplesRead — Samples read


double

This property is read-only.

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

SamplesAvailable — Samples in the host buffer


double

This property is read-only.

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

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2
• MagneticField — N-by-3 array in units of µT

9-57
9 LSMDS Functions — Alphabetical List

• Temperature — N-by-1 array in units of degree Celsius

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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.

Data Types: character vector | string

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

Create an arduino object with the I2C library.

a = arduino('COM4', 'Uno', 'Libraries', 'I2C');

Create the sensor object.

imu = lsm303c(a)

imu =

lsm303c with properties:

I2CAddress: 29 ("0x1D")
: 30 ("0x1E")
Bus: 0
SCLPin: "D21"
SDAPin: "D20"

9-58
lsm303c

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

Show all properties all functions

Create LSM303C Sensor Connection with Additional Name-Value Pair Arguments

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 =

lsm303c with properties:

I2CAddress: 107 ("0x6B")


Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 110 (samples/s)


SamplesPerRead: 3
ReadMode: "oldest"
SamplesRead: 0
SamplesAvailable: 0

Show all properties all functions

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

accelSensor = adxl345(a) creates a sensor object with default property values.


Example: accelSensor = adxl345(a);.

accelSensor = adxl345(a,Name,Value) creates a sensor object with properties using one or


more Name,Value pair arguments.
Example: accelSensor = adxl345(a, Bus=1);.

Input Arguments

a — Arduino hardware connection


arduino object

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.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.
Example: accelSensor = adxl345(a,Bus=1);

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.

I2CAddress — Specify I2C address of sensor


'0x53' (default) | '0x1D'

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.

Pin Name Pin State I2C Address


ALT Low 0x53
High 0x1D

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format


• String of hexadecimal value of I2C Address
• Character vector of hexadecimal value of I2C Address

0x53 is the I2C address of the ADXL345 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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Data Types: double

SampleRate — Rate at which sample is read


100 (default) | positive integer in the range [0.1, 200]

The rate in samples/s at which data is read from the sensor.


Data Types: double

9-61
9 LSMDS Functions — Alphabetical List

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

Number of samples read from the sensor in a single execution of the read function.
Data Types: double

ReadMode — Specify which data samples to be returned


'latest' (default) | 'oldest'

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

Data Types: character vector | string

SamplesRead — Samples read


double

This property is read-only.

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

SamplesAvailable — Samples in the host buffer


double

This property is read-only.

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

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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.

Data Types: character vector | string

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

Create an arduino object with the I2C library.


a = arduino('COM4', 'Uno', Libraries='I2C');

Create the sensor object.


accelSensor = adxl345(a)

accelSensor =

adxl345 with properties:

I2CAddress: 83 ("0x53")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0

Show all properties, functions

Create ADXL345 Sensor Connection with Additional Name-Value Pair Arguments

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 =

accelSensor with properties:

I2CAddress: 83 ("0x53")
Bus: 0
SCLPin: "A5"
SDAPin: "A4"

SampleRate: 110 (samples/s)


SamplesPerRead: 3
ReadMode: "latest"
SamplesRead: 0
SamplesAvailable: 0

9-64
adxl345

Show all properties, functions

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

a — Arduino hardware connection


arduino object

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.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.
Example: imu = icm20948(a,Bus=1);

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.

I2CAddress — Specify I2C address of sensor


[0x68, 0x0C] | [0x69, 0x0C]

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.

Pin Name Pin State I2C Address


AD0 Low [0x68, 0x0C]
High [0x69, 0x0C]

You can specify the I2C address in:

• Numeric array of hexadecimal, decimal, or binary format of I2C Addresses


• String array of hexadecimal value of I2C Addresses
• Cell array of character vector of hexadecimal value of I2C Addresses

Example: imu = icm20948(a,I2CAddress=[0x69, 0x0C])

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

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Example: imu = icm20948(a, Bus=1) creates the icm20948 sensor object if ICM-20948 sensor is
connected to bus 1 of Arduino Due board.
Data Types: double

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

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

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

This property is read-only.

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

This property is read-only.

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

• Time — Time stamps in datetime or duration format


• Acceleration — N-by-3 array in units of m/s2
• AngularVelocity — N-by-3 array in units of rad/s
• MagneticField — N-by-3 array in units of µT (microtesla)
• Temperature — N-by-1 array in units of celsius

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

TimeFormat — Set time format during the execution of read function


'datetime' (default) | 'duration'

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

Create an Arduino object and include the I2C library.

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

Create the sensor object.

imu = icm20948(a)

imu =

icm20948 with properties:

I2CAddress: 104 ("0x68")


: 12 ("0xC")
SCLPin: "A5"

9-70
icm20948

SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

Create ICM-20948 Sensor Connection with Additional Name-Value Pair Arguments

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 =

icm20948 with properties:

I2CAddress: 104 ("0x68")


: 12 ("0xC")
SCLPin: "A5"
SDAPin: "A4"

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

• 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 R2022a

See Also
mpu9250

9-72
bmp280

bmp280

Connect to BMP280 sensor on Arduino hardware I2C bus

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.

pressureSensor = bmp280(a,Name,Value) creates a sensor object with properties using one or


more Name,Value pair arguments.
Example: pressureSensor =
bmp280(a,'SampleRate',150,'SamplesPerRead',5,'ReadMode','latest');.

Input Arguments

a — Arduino hardware connection

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.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

9-73
9 LSMDS Functions — Alphabetical List

I2CAddress — Specify I2C address of sensor


'0x76' | '0x77'

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.

Pin Name Pin State I2C Address


SDO Low 0x76
High 0x77

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format


• String of hexadecimal value of I2C Address
• Character vector of hexadecimal value of I2C Address

Example: pressureSensor = bmp280(a,'I2CAddress','0x76')

0x76 is the I2C address of the 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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Example: pressureSensor = bmp280(a, 'Bus', 1) creates the sensor object on Bus 1 of
Arduino Due board
Data Types: double

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.

I2CAddress — Specify I2C address of sensor


'0x76' | '0x77'

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.

Pin Name Pin State I2C Address


SD0 Low 0x76
High 0x77

You can specify the I2C address in:

• Hexadecimal, decimal, or binary format


• String of hexadecimal value of I2C Address
• Character vector of hexadecimal value of I2C Address

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.

Bus — I2C Bus Number


0 (default) | 1

I2C bus number, specified as 0 or 1. The default value is 0.


Data Types: double

SampleRate — Rate at which sample is read


100 (default) | positive integer in the range [10, 200]

The rate in samples/s at which data is read from the sensor.

Tunable: No
Data Types: double

SamplesPerRead — Number of samples read in a single execution of the read function


10 (default) | [1 500]

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


'latest' (default) | 'oldest'

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

SamplesRead — Samples read


double

This property is read-only.

Samples read from the first read. When you release the object, SamplesRead is set to 0.
Data Types: double

SamplesAvailable — Samples in the host buffer


double

This property is read-only.

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

OutputFormat — Set output format


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

• Time — Time stamps in datetime or duration format


• Pressure — Barometric air pressure in Pascals (Pa)
• Temperature — Temperature in units of Celsius

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

TimeFormat — Set time format


'datetime' (default) | 'duration'

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

Create an Arduino object and include the I2C library.


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

Create the sensor object.


pressureSensor = bmp280(a)

9-77
9 LSMDS Functions — Alphabetical List

pressureSensor =

bmp280 with properties:

I2CAddress: 104 ("0x76")


SCLPin: "A5"
SDAPin: "A4"

SampleRate: 100 (Samples/s)


SamplesPerRead: 10
ReadMode: 'latest'
SamplesRead: 0
SamplesAvailable: 0
Show all properties, functions

Create BMP280 Sensor Connection with Additional Name-Value Pair Arguments

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 =

bmp280 with properties:

I2CAddress: 104 ("0x76")


SCLPin: "A5"
SDAPin: "A4"

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

• 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 0x76. 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

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

apds9960obj = apds9960(arduinoobj) creates a sensor object with default property values.

apds9960obj = apds9960(arduinoobj,Name,Value) creates a sensor object with properties


using one or more name-value pair arguments.

Input Arguments

arduinoobj — Connection to the hardware


object

Connection to the hardware specified as an object.


Example: arduinoobj = arduino('COM4', 'Nano33BLE', 'Libraries', 'APDS9960')
creates a connection to the APDS9960 sensor.

Name-Value Pair Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the


argument name and Value is the corresponding value. Name-value arguments must appear after
other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

BitRate — Sensor bit rate


100000 (default) | 400000

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

Bus — I2C Bus Number


0 (default) | 1

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

This property is read-only.

I2C device address of the APDS9960 sensor, specified as a nonnegative integer.


Example:

>> apds9960obj.I2CAddress
ans =
57

Data Types: double

Bus — I2C bus number


0 (default) | 1

This property is read-only.

I2C bus number, specified as 0 or 1. The default value is 0.


Example:

>> apds9960obj.Bus
ans =
0

Data Types: double

SCLPin — Serial clock pin


character vector

This property is read-only.

The serial clock pin for the serial clock signal that the I2C central generates, returned as a character
vector.
Example:

>> apds9960obj.SCLPin
ans =
'A5'

Data Types: char

10-3
10 APDS9960 sensor

SDAPin — Serial data pin


character vector

This property is read-only.

A serial data pin for a serial data signal, returned as a character vector.
Example:

>> apds9960obj.SDAPin
ans =
'A4'

Data Types: char

BitRate — Bus speed for I2C communication


100000 | 400000

This property is read-only.

The bus speed set for I2C communication, specified as a positive integer in bits/s.
Example:

>> apds9960obj.BitRate
ans =
100000

Data Types: double

You can access individual sensor properties for the sensor configurations such as Gesture, Proximity,
and Color.

Proximity

Gain — Proximity gain control


4x (default) | 1x | 2x | 8x

Select gain for the proximity data value.


Example:

>> apds9960obj.Proximity.Gain = 4;

Pulse width — Time period of each proximity pulse


8 μs (default) | 4 μs | 16 μs | 32 μs

Sets the LED pulse width during a proximity pulse.


Example:

>> apds9960obj.Proximity.PulseWidth = 8;

Pulse count — Number of proximity pulses generated on LED


10 (default) | positive scalar in the range [1 to 64]

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;

LED current — Proximity LED Drive strength


100mA (default) | 50mA | 25mA | 12.5mA

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

Gain — Gesture gain control


4x (default) | 1x | 2x | 8x

Select gain for the gesture data value.


Example:
>> apds9960obj.Gesture.Gain = 4;

Pulse width — Time period of each gesture pulse


8 μs (default) | 4 μs | 16 μs | 32 μs

Sets the LED pulse width during a gesture pulse.


Example:
>> apds9960obj.Gesture.PulseWidth = 8;

Pulse count — Number of gesture pulses generated on LED


10 (default) | positive scalar in the range [1 to 64]

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;

LED current — Gesture LED Drive strength


100mA (default) | 50mA | 25mA | 12.5mA

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

Gain — Color gain control


1x (default) | 4x | 16x | 64x

Select gain for the color data value.

10-5
10 APDS9960 sensor

Example:

>> apds9960obj.Color.Gain = 4;

Proximity and Gesture

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:

>> apds9960obj.Gesture.LEDBoost = 100;

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

Create an arduino object.

arduinoobj = arduino('COM4', 'Nano33BLE', 'Libraries', 'APDS9960')

arduino with properties:

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

Create the sensor object.

apds9960obj = apds9960(arduinoobj)

APDS9960 with properties:

I2CAddress: 57 ('0x39')
Bus: 1
SCLPin: 'SCL1'
SDAPin: 'SDA1'
BitRate: 100000 (bits/s)
Show all properties

10-6
apds9960

Create Connection to APDS9960 Sensor with Name-Value pair arguments

Create a sensor object with the bus number 1 and bit rate of 400000.

clear apds9960obj;
apds9960obj = apds9960(arduinoobj, 'Bus', 1, 'BitRate', 400000)

APDS9960 with properties:

I2CAddress: 57 ('0x39')
Bus: 1
SCLPin: 'SCL1'
SDAPin: 'SDA1'
BitRate: 400000 (bits/s)
Show all properties

Change APDS9960 Sensor Configuration

Create a sensor object with the bus number 1 and bit rate of 400000.

clear apds9960obj;
apds9960obj = apds9960(arduinoobj, 'Bus', 1, 'BitRate', 100000)

APDS9960 with properties:

I2CAddress: 57 ('0x39')
Bus: 1
SCLPin: 'SCL1'
SDAPin: 'SDA1'
BitRate: 100000 (bits/s)
Gesture: [1x1 GestureConfiguration]
Proximity: [1x1 ProximityConfiguration]
Color: [1x1 ColorConfiguration]

Access the gesture properties.

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.

[colorData,timestamp] = readColor(apds9960obj, colorMode) returns the RGB


component values of the sensed light along with the timestamp depending on the ColorMode
argument. The Timestamp argument is optional. The RGB values are normalised using the clear light
intensity value

Examples
Read Color from Sensor

Create an Arduino object.

arduinoobj = arduino('COM4', 'Nano33BLE', 'Libraries', 'APDS9960');

Create the sensor object for the 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, timestamp] = readColor(apds9960obj, 'normalized')

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.

[colorData, timestamp] = readColor(apds9960obj, 'raw')

10-9
10 APDS9960 sensor

colorData = 1×4 uint16 row vector


5 2 2 2
timestamp = datetime
17-Jun-2021 13:25:28

Input Arguments
apds9960obj — APDS9960 sensor object
object

APDS9960 sensor connection, specified as a apds9960 sensor object.

colorMode — Sensor output mode


'normalized' (default) | 'raw'

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.

Color Mode Output Size Output


'normalized' 1 by 3 vector with datatype The output vector contains the
double R, G, B component values
'raw' 1 by 4 vector with datatype The output vector contains the
uint16 clear light value and R, G, B
component values

Data Types: Vector

timestamp — Timestamp of the sensor data


datetime

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

Create an Arduino object.

arduinoobj = arduino('COM4', 'Nano33BLE', 'Libraries', 'APDS9960');

Create the sensor object for the sensor.

apds9960obj = apds9960(arduinoobj)
[gesture, timestamp] = readGesture(apds9960obj)

The gesture enum returns the gesture.

gesture = Gestures enumeration

down
timestamp = datetime
17-Jun-2021 13:25:38

Input Arguments
apds9960obj — APDS9960 sensor object
object

APDS9960 sensor connection, specified as a apds9960 sensor 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

timestamp — Timestamp of the sensor data


datetime

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

Create an Arduino object.

arduinoobj = arduino('COM4', 'Nano33BLE', 'Libraries', 'APDS9960');

Create the sensor object for the sensor in use.

apds9960obj = apds9960(arduinoobj)

Return one sample of the proximity data.

proximReadings = readProximity(apds9960obj)

proximReadings = 0.9647

Input Arguments
apds9960obj — APDS9960 sensor object
object

APDS9960 sensor connection, specified as a apds9960 sensor 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

timestamp — Timestamp of the sensor data


datetime

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.

Using this app, you can:

• Set up the Arduino board


• Connect to an Arduino board over USB, Bluetooth, and Wi-Fi®
• Configure, read from, and write to the Arduino pins
• Interface with I2C, SPI, and Serial Communication devices, and configure the interfaces to
transfer and decode data
• Visualize data from Arduino pins using Plot and Log panels
• Record and save data from Arduino pins to the MATLAB workspace
• Analyze the recorded data
• Generate equivalent MATLAB code

11-2
Arduino Explorer

Open the Arduino Explorer App


• MATLAB Toolstrip: On the Apps tab, under Test and Measurement, click the app.
• MATLAB command prompt: Enter arduinoExplorer.

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

You might also like