You are on page 1of 238

Documentation RWTH - Mindstorms NXT Toolbox

Home

News

Preview

Press

Features

Projects

Download

Docs

FAQ

Login

Wiki
Timeline
Browse Source
View Tickets
New Ticket
Search

Search
LoginAbout TracPreferencesForgot your password?
Start PageIndexHistoryLast Change

Table of Contents

1. Toolbox Documentation
1. Toolbox v4.03 (latest stable release)
2. Command Layer Structure
3. Older versions
1. Toolbox v4.02
http://www.mindstorms.rwth-aachen.de/trac/wiki/Documentation (1 of 5)7/6/2010 8:11:56 AM

Documentation RWTH - Mindstorms NXT Toolbox

2. Toolbox v2.03
3. Toolbox v2.00
4. Toolbox v1.00

Toolbox Documentation
Toolbox v4.03 (latest stable release)
List of functions
By Categories (opens in a new window)
Alphabetical List (opens in a new window)
Command Layers

Tutorial: Programming Robots


Preparing the workspace (opens in a new window)
PC - NXT Communication (opens in a new window)
Motor Control (opens in a new window)
Sensor Reading (opens in a new window)
Direct NXT Commands (opens in a new window)

Command Layer Structure


Command Layer Structure of previous releases

The functions of the RWTH - Mindstorms NXT Toolbox can be categorized into a multiple layer structure. On the lowest layer Low Level and Helper functions are
available, which mostly convert parameter modes to bytes words, determined by the LEGO direct commands documentation. The second layer includes Direct NXT
Commands which are mapped from the LEGO direct command documentation without any limitations and can be identified by the NXT_* prefix. Also Bluetooth packet
related functions can be found in this layer. Layer 3 provides High Level Functions for controlling the NXT motors, sensors and the Bluetooth connection. These functions
are basically using the Direct NXT Commands of layer 2 to make the motor and sensor controlling more convenient and easily readable for the user. The top layer
provides High Level Regulation functions for precise motor regulation and various utilities.

Layer

Description

High Level
Regulation /
Utilities

Output/Motors
NXTMotor
.display
.ReadFromNXT
.SendToNXT
.Stop
.WaitFor
.ResetPosition

Input/Sensors

General

Bluetooth / USB

OptimizeToolboxPerformance

COM_MakeBTConfigFile

GUI_WatchMotorState
GUI_WatchSensor

NXC_MotorControl

2
http://www.mindstorms.rwth-aachen.de/trac/wiki/Documentation (2 of 5)7/6/2010 8:11:56 AM

Documentation RWTH - Mindstorms NXT Toolbox

DirectMotorCommand
StopMotor
SwitchLamp
NXC_ResetErrorCorrection

OpenLight
GetLight
OpenSound
GetSound
OpenSwitch
GetSwitch
OpenUltrasonic
GetUltrasonic
USMakeSnapshot
USGetSnapshotResults

readFromIniFile
MAP_GetCommModule
MAP_GetInputModule
MAP_GetOutputModule
MAP_GetSoundModule
MAP_GetUIModule

COM_OpenNXT
COM_OpenNXTEx
COM_CloseNXT
COM_ReadI2C

MAP_SetOutputModule
NXC_GetSensorMotorData

OpenAccelerator
GetAccelerator
3

OpenColor
CalibrateColor
GetColor

High Level
Functions

OpenCompass
CalibrateCompass
GetCompass
OpenGyro
CalibrateGyro
GetGyro
OpenInfrared
GetInfrared
OpenRFID
GetRFID
CloseSensor

NXT_SetOutputState

NXT_SetInputMode

NXT_GetOutputState

NXT_GetInputValues

NXT_ResetMotorPosition

NXT_ResetInputScaledValue

Direct NXT
Commands

NXT_LSRead
NXT_LSWrite
NXT_LSGetStatus

NXT_PlayTone
NXT_PlaySoundFile
NXT_StopSoundPlayback

COM_CreatePacket
COM_SendPacket
COM_CollectPacket

NXT_StartProgram
NXT_GetCurrentProgramName
NXT_StopProgram

COM_SetDefaultNXT
COM_GetDefaultNXT

NXT_SendKeepAlive
NXT_GetBatteryLevel
NXT_GetFirmwareVersion
NXT_SetBrickName
NXT_ReadIOMap
NXT_WriteIOMap
NXT_MessageWrite
NXT_MessageRead

http://www.mindstorms.rwth-aachen.de/trac/wiki/Documentation (3 of 5)7/6/2010 8:11:56 AM

Documentation RWTH - Mindstorms NXT Toolbox

MOTOR_A
MOTOR_B
MOTOR_C

Low Level
Functions:
Helper,
Conversion
and
Lookup
Functions

SetMotor (o)
SetPower (o)
SetAngleLimit (o)
SetRampMode (o)
SetTurnRatio (o)
SpeedRegulation (o)
SyncToMotor (o)
GetMotor (o)
SetMemoryCount (o)
GetMemoryCount (o)

SENSOR_1
SENSOR_2
SENSOR_3
SENSOR_4

DebugMode
isdebug

byte2sensortype
byte2sensormode
sensortype2byte
sensormode2byte

dec2wordbytes
name2commandbytes
commandbyte2name
wordbytes2dec

textOut

waitUntilI2CReady

checkStatusByte
createHandleStruct
checkHandleStruct
getLibusbErrorString
getVISAErrorString
getReplyLengthFromCmdByte
fantom_proto
libusb_proto

byte2outputmode
byte2regmode
byte2runstate
outputmode2byte
regmode2byte
runstate2byte
initializeGlobalMotorStateVar
(o)

legend: NXT_* = NXT Direct commands without any limitations (mapped to the LEGO direct command documentation)
COM_* = Functions related to the NXT communication
MAP_* = Functions related to the NXT module maps
NXC_* = Functions communicating with the embedded NXC program MotorControl
bold = Main funcions or main group functions
italic = private functions
(o) = obsolete / deprecated functions (might be removed in a future release)

Older versions
Toolbox v4.02
List of functions

By Categories (opens in a new window)


Alphabetical List (opens in a new window)

Tutorial: Programming Robots

Preparing the workspace (opens in a new window)


PC - NXT Communication (opens in a new window)
Motor Control (opens in a new window)
Sensor Reading (opens in a new window)
Direct NXT Commands (opens in a new window)

http://www.mindstorms.rwth-aachen.de/trac/wiki/Documentation (4 of 5)7/6/2010 8:11:56 AM

Functions by Category

RWTH - Mindstorms NXT Toolbox

Functions by Category
NXT Communication
COM_CloseNXT
COM_CollectPacket
COM_CreatePacket
COM_GetDefaultNXT
COM_MakeBTConfigFile
COM_OpenNXT
COM_OpenNXTEx
COM_ReadI2C
COM_SendPacket
COM_SetDefaultNXT

Closes and deletes a specific NXT handle, or


clears all existing handles
Reads data from a USB or serial/Bluetooth
port, retrieves exactly one packet
Generates a valid Bluetooth packet ready for
transmission (i.e. sets length)
Returns the global default NXT handle if it was
previously set
Creates a Bluetooth configuration file (needed
for Bluetooth connections)
Opens USB or Bluetooth connection to NXT
device and returns a handle
Opens USB or Bluetooth connection to NXT;
advanced version, more options
Requests and reads sensor data via I2C from a
correctly configured digital sensor.
Sends a communication protocol packet (bytearray) via a USB or Bluetooth
Sets global default NXT handle (will be used by
other functions as default)

NXT Sensors
CalibrateColor
CalibrateCompass
CalibrateGyro

Enables calibration mode of the HiTechnic color


sensor
Enables calibration mode of the HiTechnic
compass sensor
Calibrates the HiTechnic Gyro sensor
(measures/sets an offset while in rest)
5

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/categories.html (1 of 6)7/6/2010 8:12:13 AM

Functions by Category

CloseSensor
GetAccelerator
GetColor
GetCompass
GetGyro
GetInfrared
GetLight
GetRFID
GetSound
GetSwitch
GetUltrasonic
OpenAccelerator
OpenColor
OpenCompass
OpenGyro
OpenInfrared
OpenLight
OpenRFID
OpenSound

Closes a sensor port (e.g. turns off active light


of the light sensor)
Reads the current value of the HiTechnic
acceleration sensor
Reads the current value of the HiTechnic Color
sensor
Reads the current value of the HiTechnic
compass sensor
Reads the current value of the HiTechnic Gyro
sensor
Reads the current value of the Hitechnic
infrared sensor (infrared seeker)
Reads the current value of the NXT light sensor
Reads the transponder ID detected by the
Codatex RFID sensor
Reads the current value of the NXT sound
sensor
Reads the current value of the NXT switch /
touch sensor
Reads the current value of the NXT ultrasonic
sensor
Initializes the HiTechnic acceleration sensor,
sets correct sensor mode
Initializes the HiTechnic color sensor, sets
correct sensor mode
Initializes the HiTechnic magnetic compass
sensor, sets correct sensor mode
Initializes the HiTechnic Gyroscopic sensor,
sets correct sensor mode
Initializes the HiTechnic infrared seeker sensor,
sets correct sensor mode
Initializes the NXT light sensor, sets correct
sensor mode
Initializes the Codatex RFID sensor, sets
correct sensor mode
Initializes the NXT sound sensor, sets correct
sensor mode
6

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/categories.html (2 of 6)7/6/2010 8:12:13 AM

Functions by Category

OpenSwitch
OpenUltrasonic

Initializes the NXT touch sensor, sets correct


sensor mode
Initializes the NXT ultrasonic sensor, sets
correct sensor mode

SENSOR_1

Symbolic constant SENSOR_1 (returns 0)

SENSOR_2

Symbolic constant SENSOR_2 (returns 1)

SENSOR_3

Symbolic constant SENSOR_3 (returns 2)

SENSOR_4

Symbolic constant SENSOR_4 (returns 3)

USGetSnapshotResults
USMakeSnapshot

Retrieves up to eight echos (distances) stored


inside the US sensor
Causes the ultrasonic sensor to send one
snapshot ("ping") and record the echos

NXTMotor Class Methods


NXTMotor
ReadFromNXT
ResetPosition

Constructs an NXTMotor object


Reads current state of specified motor(s) from
NXT brick
Resets the position counter of the given motor
(s).

SendToNXT

Send motor settings to the NXT brick

Stop

Stops or brakes specified motor(s)

WaitFor

Wait for motor(s) to stop (busy waiting)

Classic NXT Motor Functions


DirectMotorCommand

Sends a direct command to the specified motor

MOTOR_A

Symbolic constant MOTOR_A (returns 0)

MOTOR_B

Symbolic constant MOTOR_B (returns 1)

MOTOR_C

Symbolic constant MOTOR_C (returns 2)

NXC_MotorControl

Sends advanced motor-command to the NXCprogram MotorControl on the NXT brick


7

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/categories.html (3 of 6)7/6/2010 8:12:13 AM

Functions by Category

NXC_ResetErrorCorrection
StopMotor
SwitchLamp

Sends reset error correction command to the


NXC-program MotorControl on the NXT
Stops / brakes specified motor.
(Synchronisation will be lost after this)
Switches the LEGO lamp on or off (has to be
connected to a motor port)

NXT Direct Commands


NXT_GetBatteryLevel
NXT_GetCurrentProgramName
NXT_GetFirmwareVersion
NXT_GetInputValues
NXT_GetOutputState
NXT_LSGetStatus
NXT_LSRead
NXT_LSWrite
NXT_MessageRead
NXT_MessageWrite

Returns the current battery level in milli volts


Returns the name of the current running
program
Returns the protocol and firmware version of
the NXT
Executes a complete sensor reading (requests
and retrieves input values)
Requests and retrieves an output motor state
reading
Gets the number of available bytes for digital
low speed sensors (I2C)
Reads data from a digital low speed sensor
port (I2C)
Writes given data to a digital low speed sensor
port (I2C)
Retrieves a "NXT-to-NXT message" from the
specified inbox
Writes a "NXT-to-NXT message" to the NXT's
incoming BT mailbox queue

NXT_PlaySoundFile

Plays the given sound file on the NXT Brick

NXT_PlayTone

Plays a tone with the given frequency and


duration

NXT_ReadIOMap

Reads the IO map of the given module ID

NXT_ResetInputScaledValue
NXT_ResetMotorPosition

Resets the sensor's ScaledVal back to 0


(depends on current sensor mode)
Resets NXT internal counter for specified
motor, relative or absolute counter
8

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/categories.html (4 of 6)7/6/2010 8:12:13 AM

Functions by Category

NXT_SendKeepAlive
NXT_SetBrickName
NXT_SetInputMode
NXT_SetOutputState

Sends a KeepAlive packet. Optional: requests


sleep time limit.
Sets a new name for the NXT Brick (connected
to the specified handle)
Sets a sensor mode, configures and initializes
a sensor to be read out
Sends previously specified settings to current
active motor.

NXT_StartProgram

Starts the given program on the NXT Brick

NXT_StopProgram

Stops the currently running program on the


NXT Brick

NXT_StopSoundPlayback

Stops the current sound playback

NXT_WriteIOMap

Writes the IO map to the given module ID

NXT Module Map Functions


MAP_GetCommModule

Reads the IO map of the communication


module

MAP_GetInputModule

Reads the IO map of the input module

MAP_GetOutputModule

Reads the IO map of the output module

MAP_GetSoundModule

Reads the IO map of the sound module

MAP_GetUIModule

Reads the IO map of the user interface module

MAP_SetOutputModule

Writes the IO map to the output module

General Functions
Interpretes the status byte of a return
package, returns error message
Copies binary versions of typecastc to toolbox
OptimizeToolboxPerformance
for better performance
Reads parameters from a configuration file
readFromIniFile
(usually *.ini)
Wrapper for fprintf() which can optionally write
textOut
screen output to a logfile
checkStatusByte

9
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/categories.html (5 of 6)7/6/2010 8:12:13 AM

Functions by Category

Debug Functions
DebugMode

Gets or sets debug state (i.e. if textOut prints


messages to the command window)

Future Functions
NXC_GetSensorMotorData

Retrieves selected data from all analog sensors


and all motors in a single packet

10
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/categories.html (6 of 6)7/6/2010 8:12:13 AM

COM_CloseNXT

COM_CloseNXT
Closes and deletes a specific NXT handle, or clears all existing handles

Contents

Syntax
Description
Limitations
Example
See also
Signature

Syntax
COM_CloseNXT(handle)
COM_CloseNXT('all')
COM_CloseNXT('all', inifilename)

Description
After using NXT handles, a user should free the device (and the memory occupied
by the handle) by calling this method. After the clean up invoked by this call, an
NXT brick can be accessed and used again (by COM_OpenNXT or COM_OpenNXTEx.
COM_CloseNXT(handle) will close and erase the specified device. handle has to be
a valid handle struct created by either COM_OpenNXT or COM_OpenNXTEx.
COM_CloseNXT('all') will close and erase all existing NXT devices from memory
(as long as the toolbox could keep track of them). All USB handles will be
destroyed, all open serial ports (for Bluetooth connections) will be closed. This can
be useful at the beginning of a program to create a "fresh start" and a welldefined starting environment. Please note that a clear all command can cause
this function to fail (in such a way, that not all open USB devices can be closed,
since all information about them has be cleare from MATLAB's memory). If this
happens, an NXT device might appear to be busy and cannot be used. Usually
11
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_CloseNXT.html (1 of 3)7/6/2010 8:12:23 AM

COM_CloseNXT

rebooting the NXT helps, if not try to restart MATLAB as well. So be careful with
using clear all before |COM_CloseNXT('all').
COM_CloseNXT('all', inifilename) will do the same as above, but instead of
closing all open serial ports, only the COM-Port specified in inifilename will be
used (a valid Bluetooth configuration file can be created by the function
COM_MakeBTConfigFile). This syntax helps to avoid interference with other serial
ports that might be used by other (MATLAB) programs at the same time. Note
that still all open USB devices will be closed.

Limitations
If you call COM_CloseNXT('all') after a clear all command has been issued,
the function will not be able to close all remaining open USB handles, since they
have been cleared out of memory. This is a problem on Linux systems. You will
not be able to use the NXT device without rebooting it. Solution: Either use only
clear in your programs, or you use the COM_CloseNXT('all') statement before
clear all. The best way however is to track your handles carefully and close
them manually before exiting whenever possible!

Example
handle = COM_OpenNXT('bluetooth.ini', check');
COM_SetDefaultNXT(handle);
NXT_PlayTone(440,10);
COM_CloseNXT(handle);

See also
COM_OpenNXT, COM_OpenNXTEx, COM_MakeBTConfigFile,
COM_SetDefaultNXT,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2009/08/31
Copyright: 2007-2009, RWTH Aachen University
12

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_CloseNXT.html (2 of 3)7/6/2010 8:12:23 AM

COM_CloseNXT

Published with wg_publish; V1.0

13
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_CloseNXT.html (3 of 3)7/6/2010 8:12:23 AM

COM_CollectPacket

COM_CollectPacket
Reads data from a USB or serial/Bluetooth port, retrieves exactly one packet

Contents

Syntax
Description
Example
See also
Signature

Syntax
[type cmd statusbyte content] = COM_CollectPacket(handle)
[type cmd statusbyte content] = COM_CollectPacket(handle, 'dontcheck')

Description
[type cmd statusbyte content] = COM_CollectPacket(handle) reads one
packet on the communication channel specified by the handle struct (PC system:
handle struct containing e.g. serial handle, Linux system: handle struct containing
file handle). The USB / Bluetooth handle struct can be obtained by the
COM_OpenNXT or COM_GetDefaultNXT command. The return value type specifies
the telegram type according to the LEGO Mindstorms communication protcol. The
cmd value determines the specific command. status indicates if an error occured
on the NXT brick. The function checkStatusByte is interpreting this information
per default. The content column vector represents the remaining payload of the
whole return packet. E.g. it contains the current battery level in milli volts, that
then has to be converted to a valid integer from its byte representation (i.e. using
wordbytes2dec).
[type cmd statusbyte content] = COM_CollectPacket(handle,
'dontcheck') disables the validation check of the status value by function
checkStatusBytes.
varargin : set to 'dontcheck' if the status byte should not automatically be
14
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_CollectPacket.html (1 of 3)7/6/2010 8:12:25 AM

COM_CollectPacket

checked. Only use this if you expect error messages. Possible usage is for
LSGetStatus, where this can happen...
For more details about the syntax of the return packet see the LEGO Mindstorms
communication protocol.
Note:
This function uses the specific Bluetooth settings from the ini-file that was
specified when opening the handle. Parameters used here are SendSendPause and
SendReceivePause, which will cause this function to wait a certain amount of
milliseconds between each consecutive send or receive operation to avoid packet
loss or buffer overflows inside the blutooth stack.

Example
COM_MakeBTConfigFile();
handle = COM_OpenNXT('bluetooth.ini');
[type cmd] = name2commandbytes('KEEPALIVE');
content = []; % no payload in NXT command KEEPALIVE
packet = COM_CreatePacket(type, cmd, 'reply', content);
COM_SendPacket(packet, handle);
[type cmd statusbyte content] = COM_CollectPacket(handle);
% Now you could check the statusbyte or interpret the content.
% Or maybe check for valid type and cmd before...

See also
COM_CreatePacket, COM_SendPacket, COM_OpenNXT,
COM_GetDefaultNXT, COM_MakeBTConfigFile, checkStatusByte,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2009/08/31

15

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_CollectPacket.html (2 of 3)7/6/2010 8:12:25 AM

COM_CollectPacket

Copyright: 2007-2009, RWTH Aachen University


Published with wg_publish; V1.0

16
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_CollectPacket.html (3 of 3)7/6/2010 8:12:25 AM

COM_CreatePacket

COM_CreatePacket
Generates a valid Bluetooth packet ready for transmission (i.e. sets length)

Contents

Syntax
Description
Example
See also
Signature

Syntax
bytes = COM_CreatePacket(CommandType, Command, ReplyMode,
ContentBytes)

Description
bytes = COM_CreatePacket(CommandType, Command, ReplyMode,
ContentBytes) creates a valid Bluetooth packet conform to the LEGO Mindstorms
communication protocol. The CommandType specifies the telegram type (direct or
system command (see the LEGO Mindstorms communication protocol
documentation for more details)). This type is determined from the function
name2commandbytes. The Command specifies the actual command according to the
LEGO Mindstorms communication protocol. By the ReplyMode one can request an
acknowledgement for the packet transmission. The two strings 'reply' and
'dontreply' are valid. The content byte-array is given by the ContentBytes.
The return value bytes represents the complete Bluetooth packet conform to the
LEGO Mindstorms Communication protocol.
Note:
The activated ReplyMode should only be used if it is necessary. According to the
official LEGO statement "Testing during development has shown that the Bluetooth
Serial Port communication has some disadvantages when it comes to streaming
data. ... One problem is a time penalty (of around 30ms) within the Bluecore
chip
17
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_CreatePacket.html (1 of 2)7/6/2010 8:12:50 AM

COM_CreatePacket

when switching from receive-mode to transmit-mode. ... To handle the problem of


the time penalty within the Bluecore chip, users should send data using Bluetooth
without requesting a reply package. This will mean that the Bluecore chip won't
have to switch direction for every received package and will not incur a 30ms
penalty for every data package."

Example
[type cmd] = name2commandbytes('PLAYTONE');
content(1:2) = dec2wordbytes(frequency, 2);
content(3:4) = dec2wordbytes(duration, 2);
packet = COM_CreatePacket(type, cmd, 'dontreply', content);

See also
COM_SendPacket, COM_CollectPacket, name2commandbytes,
dec2wordbytes,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2008/07/09
Copyright: 2007-2009 RWTH Aachen University
Published with wg_publish; V1.0

18
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_CreatePacket.html (2 of 2)7/6/2010 8:12:50 AM

COM_GetDefaultNXT

COM_GetDefaultNXT
Returns the global default NXT handle if it was previously set

Contents

Syntax
Description
Example
See also
Signature

Syntax
h = COM_GetDefaultNXT()

Description
h = COM_GetDefaultNXT() returns the global default NXT handle h if it was
previously set. The default global NXT handle is used by all NXT-Functions per
default if no other handle is specified. To set this global handle the function
COM_SetDefaultNXT is used.

Example
handle = COM_OpenNXT('bluetooth.ini');
COM_SetDefaultNXT(handle);
MyNXT = COM_GetDefaultNXT();
% now MyNXT and handle refer to the same device

See also
COM_SetDefaultNXT, COM_OpenNXT, COM_OpenNXTEx,

Signature
19
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_GetDefaultNXT.html (1 of 2)7/6/2010 8:13:34 AM

COM_GetDefaultNXT

Author: Linus Atorf (see AUTHORS)


Date: 2008/07/07
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

20
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_GetDefaultNXT.html (2 of 2)7/6/2010 8:13:34 AM

COM_MakeBTConfigFile

COM_MakeBTConfigFile
Creates a Bluetooth configuration file (needed for Bluetooth connections)

Contents

Syntax
Description
Example
See also
Signature

Syntax
COM_MakeBTConfigFile()

Description
COM_MakeBTConfigFile() starts a user guided dialog window to select the output
directory, the file name and the Bluetooth paramters like e.g. COM port.
The little program creates a specific Bluetooth configuration file for the current PC
system. Make sure the configuration file is accessible under MATLAB if you try to
open a Bluetooth connection using COM_OpenNXT and the correct file name.

Example
COM_MakeBTConfigFile();
handle = COM_OpenNXT('bluetooth.ini');

See also
COM_OpenNXT, COM_CloseNXT, COM_OpenNXTEx,
21
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_MakeBTConfigFile.html (1 of 2)7/6/2010 8:13:44 AM

COM_MakeBTConfigFile

Signature

Author: Alexander Behrens, Linus Atorf (see AUTHORS)


Date: 2008/07/09
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

22
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_MakeBTConfigFile.html (2 of 2)7/6/2010 8:13:44 AM

COM_OpenNXT

COM_OpenNXT
Opens USB or Bluetooth connection to NXT device and returns a handle

Contents

Syntax
Description
Limitations of COM_CloseNXT
Example
See also
Signature

Syntax
handle = COM_OpenNXT()
handle = COM_OpenNXT(inifilename)

Description
handle = COM_OpenNXT() tries to open a connection via USB. The first NXT device
that is found will be used. Device drivers (Fantom on Windows, libusb on Linux)
have to be already installed for USB to work.
handle = COM_OpenNXT(inifilename) will search the USB bus for NXT devices,
just as the syntax without any parameters. If this fails for some reason (no USB
connection to the NXT available, no device drivers installed, or NXT device is
busy), the function will try to establish a connection via Bluetooth, using the given
Bluetooth configuration file (you can create one easily with
COM_MakeBTConfigFile.
Note that this function is the most simple way to get an NXT handle. If you need a
method to access multiple NXTs or more options, see the advanced function
COM_OpenNXTEx. In fact, COM_OpenNXT is just a convenient wrapper to
COM_OpenNXTEx('Any', ...).
23
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_OpenNXT.html (1 of 2)7/6/2010 8:13:54 AM

COM_OpenNXT

Limitations of COM_CloseNXT
If you call COM_CloseNXT('all') after a clear all command has been issued,
the function will not be able to close all remaining open USB handles, since they
have been cleared out of memory. This is a problem on Linux systems. You will
not be able to use the NXT device without rebooting it. Solution: Either use only
clear in your programs, or you use the COM_CloseNXT('all') statement before
clear all. The best way however is to track your handles carefully and close
them manually (COM_CloseNXT(handle)) before exiting whenever possible!

Example
handle = COM_OpenNXT('bluetooth.ini');
COM_SetDefaultNXT(handle);
NXT_PlayTone(440,10);
COM_CloseNXT(handle);

See also
COM_OpenNXTEx, COM_CloseNXT, COM_MakeBTConfigFile,
COM_SetDefaultNXT,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2009/07/10
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

24
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_OpenNXT.html (2 of 2)7/6/2010 8:13:54 AM

COM_OpenNXTEx

COM_OpenNXTEx
Opens USB or Bluetooth connection to NXT; advanced version, more options

Contents

Syntax
Description
Limitations of COM_CloseNXT
Examples
See also
Signature

Syntax
handle = COM_OpenNXTEx('USB', UseThisNXTMAC)
handle = COM_OpenNXTEx('Bluetooth', UseThisNXTMAC, inifilename)
handle = COM_OpenNXTEx('Any', UseThisNXTMAC, inifilename)
handle = COM_OpenNXTEx('USB' , UseThisNXTMAC, 'MotorControlFilename',
motorcontrolfile)
handle = COM_OpenNXTEx('Bluetooth', UseThisNXTMAC, inifilename,
'MotorControlFilename', motorcontrolfile)
handle = COM_OpenNXTEx('Any' , UseThisNXTMAC, inifilename,
'MotorControlFilename', motorcontrolfile)

Description
This function establishes a connection to an NXT brick and returns the handle
structure that has to be used with NXT-functions (you can call COM_SetDefaultNXT
(handle) afterwards for easier use).
For a more convenient way to open an NXT handle with less parameters, the
25
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_OpenNXTEx.html (1 of 4)7/6/2010 8:14:13 AM

COM_OpenNXTEx

function COM_OpenNXT is provided.


Different types of connection modes are supported. In all modes, you can set
UseThisNXTMAC to a string with the NXT's MAC address (serial number). A
connection will then only be estabslished to a matching NXT brick. This can be
useful for programs with multiple NXT devices. Set it to an empty string '' to use
any NXT available (usually the first one found). The string can have the format
'001612345678' or '00:16:12:34:56:78'.
handle = COM_OpenNXTEx('USB', UseThisNXTMAC)
This will try to open a connection via USB. Device drivers (Fantom on Windows,
libusb on Linux) have to be installed.
handle = COM_OpenNXTEx('Bluetooth', UseThisNXTMAC, inifilename)
Uses Bluetooth as communication method. A valid inifile containing parameters
like the COM-Port has to be specified in inifilename. To create an inifile with
Bluetooth settings, the function COM_MakeBTConfigFile is available.
Note that as of right now, the parameter UseThisNXTMAC will be ignored for
Bluetooth connections until implemented in a future version.
handle = COM_OpenNXTEx('Any', UseThisNXTMAC, inifilename)
This syntax combines the two parameter settings from above. inifilename has to
be given. The function will try to locate an NXT device on the USB bus first. If this
fails for some reason (no USB connection to the NXT available, no device drivers
installed, or NXT device is busy), the function will silently try to establish a
connection via Bluetooth.
The advantage is that this version works with both Bluetooth and USB connections
without changing any code. Plug or unplug the USB cable to switch between
connection types...
The optional string-parameter 'MotorControlFilename' can be used to override
the default file name for the embedded NXC program MotorControl, which will be
launched by the method. Specify 'MotorControlFilename', followed by a the
actual filename to be started in motorcontrolfile. You can set this to any
executable file present on the NXT. The filename conventions are the same as for
NXT_StartProgram. Set it to an empty string '' to disable the embedded
26

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_OpenNXTEx.html (2 of 4)7/6/2010 8:14:13 AM

COM_OpenNXTEx

MotorControl program. In this case, the class NXTMotor will not completely be
available for usage. This option is intended for advanced users.

Limitations of COM_CloseNXT
If you call COM_CloseNXT('all') after a clear all command has been issued,
the function will not be able to close all remaining open USB handles, since they
have been cleared out of memory. This is a problem on Linux systems. You will
not be able to use the NXT device without rebooting it. Solution: Either use only
clear in your programs, or you use the COM_CloseNXT('all') statement before
clear all. The best way however is to track your handles carefully and close
them manually (COM_CloseNXT(handle)) before exiting whenever possible!%

Examples
myNXT = COM_OpenNXTEx('Any', '001612345678', 'bluetooth.ini');
% This will connect to an NXT device with the MAC/serial number
001612345678,
% first trying via USB. If this fails (no drivers installed or
no matching USB
% device found), a connection via Bluetooth will be established,
using
% the paramters found in the given config file.

myNXT = COM_OpenNXTEx('USB', '', 'MotorControlFilename,


'MyProgram.rxe');
% This will try to connect to an NXT device via USB, using the
first
% one found (we set |UseThisNXTMAC| to |''|). Instead of the
embedded
% default MotorControl program, a custom user file MyProgram.rxe
will
% try to be launched...

See also
COM_OpenNXT, COM_CloseNXT, COM_MakeBTConfigFile,
COM_SetDefaultNXT,

27

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_OpenNXTEx.html (3 of 4)7/6/2010 8:14:13 AM

COM_OpenNXTEx

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2009/08/31
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

28
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_OpenNXTEx.html (4 of 4)7/6/2010 8:14:13 AM

COM_ReadI2C

COM_ReadI2C
Requests and reads sensor data via I2C from a correctly configured digital sensor.

Contents

Syntax
Description
Example
See also
Signature

Syntax
ReturnBytes = COM_ReadI2C(Port, RequestLen, DeviceAddress,
RegisterAddress)
ReturnBytes = COM_ReadI2C(Port, RequestLen, DeviceAddress,
RegisterAddress, handle)

Description
This function is used to retrieve data from digital sensors (like the ultrasonic) in a
comfortable way. It is designed as a helping function for developers wanting to
access new sensors. For already implemented sensors (e.g. ultrasound, as well as
HiTechnic's acceleration and infrared sensors), use the provided high-level
functions such as GetUltrasonic, GetInfrared, etc.
For I2C communication, usually the NXT_SetInputMode command has to be used
with the LOWSPEED_9V or LOWSPEED setting. Afterwards, commands can be send
with NXT_LSWrite. Once a sensor is correctly working, i.e. has data available, you
can use this function to retrieve them.
In COM_ReadI2C(Port, RequestLen, DeviceAddress, RegisterAddress), Port
is the sensor-port the sensor is connected to. RequestLen specifies the amount of
bytes you want to retrieve. For ultasound, this is 1. DeviceAddress is the sensor's
address on the I2C bus. This sometimes can be changed, but not for the ultrasonic
sensor. Default value is 0x02 (2 in decimal). Finally, RegisterAddress is 29
the
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_ReadI2C.html (1 of 3)7/6/2010 8:14:23 AM

COM_ReadI2C

address where you want to read data from. For the ultrasound and many other
sensors, the "data section" starts at 0x42 (66 in decimal).
As last argument you can pass a valid NXT-handle to be used by this function. If
no handle is passed, the default set by COM_SetDefaultNXT will be used.
Returns: ReturnBytes, byte-array (column vector) of uint8. This array contains
the raw sensor-data you requested. How to interpret them depends on the sensor.
If communication failed (even after automatic retransmission) -- e.g. when the
sensor get's disconnected while in use -- an empty vector [] will be returned.
Note:
Please note that the return values of this function are of type uint8. You have to
convert them to double (using double()) before performing calculations with
them, otherwise you might get unexpected results!
The sensor you are addressing with this command has to be correctly opened and
initialized of course -- otherwise no valid data can be received.

Example
This example opens and reads the ultrasonic sensor
port = SENSOR_1;
handle = COM_OpenNXT('bluetooth.ini');
OpenUltrasonic(port);
% retrieve 1 byte from device 0x02, register 0x42
data = COM_ReadI2C(port, 1, uint8(2), uint8(66));
if isempty(data)
DistanceCM = -1;
else
% don'f forget this double()!!!
DistanceCM = double(data(1));
end%if

See also
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_ReadI2C.html (2 of 3)7/6/2010 8:14:23 AM

30

COM_ReadI2C

NXT_LSWrite, NXT_LSRead, NXT_LSGetStatus, NXT_SetInputMode,


OpenUltrasonic, GetUltrasonic, SENSOR_1, SENSOR_2, SENSOR_3,
SENSOR_4,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2008/09/23
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

31
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_ReadI2C.html (3 of 3)7/6/2010 8:14:23 AM

COM_SendPacket

COM_SendPacket
Sends a communication protocol packet (byte-array) via a USB or Bluetooth

Contents

Syntax
Description
Example
See also
Signature

Syntax
COM_SendPacket(Packet, handle)

Description
COM_SendPacket(Packet, handle) sends the given byte-array Packet (column
vector), (which can easily be created by the function COM_CreatePacket) over the
USB or Bluetooth channel specified by the given handle (struct) created by the
function COM_OpenNXT or COM_OpenNXTEx, or obtained from COM_GetDefaultNXT.
Note:
In the case of a Bluetooth connection this function uses the specific settings from
the ini-file that was specified when opening the handle. Parameters used here are
SendSendPause and SendReceivePause, which will cause this function to wait a
certain amount of milliseconds between each consecutive send or receive
operation to avoid packet loss or buffer overflows inside the blutooth stack.

Example
COM_MakeBTConfigFile();
handle = COM_OpenNXT('bluetooth.ini');
32
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_SendPacket.html (1 of 2)7/6/2010 8:14:30 AM

COM_SendPacket

[type cmd] = name2commandbytes('KEEPALIVE');


content = []; % no payload in NXT command KEEPALIVE
packet = COM_CreatePacket(type, cmd, 'dontreply', content);
COM_SendPacket(packet, bt_handle);

See also
COM_CreatePacket, COM_CollectPacket, COM_OpenNXT,
COM_GetDefaultNXT, COM_MakeBTConfigFile,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2009/08/31
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

33
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_SendPacket.html (2 of 2)7/6/2010 8:14:30 AM

COM_SetDefaultNXT

COM_SetDefaultNXT
Sets global default NXT handle (will be used by other functions as default)

Contents

Syntax
Description
Example
See also
Signature

Syntax
COM_SetDefaultNXT(h)

Description
COM_SetDefaultNXT(h) sets the given handle h to the global NXT handle, which is
used by all NXT-Functions per default if no other handle is specified. To create and
open an NXT handle (Bluetooth or USB), the functions COM_OpenNXT and
COM_OpenNXTEx can be used. To retrieve the global default handle user
COM_GetDefaultNXT.

Example
MyNXT = COM_OpenNXT('bluetooth.ini');
COM_SetDefaultNXT(MyNXT);

See also
COM_GetDefaultNXT, COM_OpenNXT, COM_OpenNXTEx,

Signature
34
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_SetDefaultNXT.html (1 of 2)7/6/2010 8:14:37 AM

COM_SetDefaultNXT

Author: Linus Atorf (see AUTHORS)


Date: 2008/07/07
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

35
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/COM_SetDefaultNXT.html (2 of 2)7/6/2010 8:14:37 AM

CalibrateColor

CalibrateColor
Enables calibration mode of the HiTechnic color sensor

Contents

Syntax
Description
Example
See also
Signature

Syntax
CalibrateColor(port, mode)
CalibrateColor(port, mode, handle)

Description
Calibrate the color sensor with white balance and black value. I don't know
whether calibration of color sensor makes sence Hitech doku says nothing, some
internet freaks say it is necessary, but it works and has effect ;-) The sensor LEDs
make a short flash after successful calibration. When calibrated, the sensor keeps
this information in non-volatile memory. There are two different modes for
calibration: mode = 1: white balance calibration Puts the sensor into white balance
calibration mode. For best results the sensor should be pointed at a diffuse white
surface at a distance of approximately 15mm before calling this method. After a
fraction of a second the sensor lights will flash and the calibration is done. mode =
2: black level calibration Puts the sensor into black/ambient level calibration
mode. For best results the sensor should be pointed in a direction with no
obstacles for 50cm or so. This reading the sensor will use as a base level for other
readings. After a fraction of a second the sensor lights will flash and the calibration
is done. When calibrated, the sensor keeps this information in non-volatile
memory.
The color sensor has to be opened (using OpenColor) before execution.
36
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/CalibrateColor.html (1 of 2)7/6/2010 8:14:46 AM

CalibrateColor

The given port number specifies the connection port. The value port can be
addressed by the symbolic constants SENSOR_1 , SENSOR_2, SENSOR_3 and
SENSOR_4 analog to the labeling on the NXT Brick.
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).

Example
% color must be open for calibration
OpenColor(SENSOR_2);
% white calibration mode
CalibrateColor(SENSOR_2, 1);
% pause for changing position
pause(5);
% black calibration mode
CalibrateColor(SENSOR_2, 2);

See also
OpenColor, GetColor, CloseSensor,

Signature

Author: Rainer Schnitzler, Linus Atorf (see AUTHORS)


Date: 2008/08/01
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

37
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/CalibrateColor.html (2 of 2)7/6/2010 8:14:46 AM

CalibrateCompass

CalibrateCompass
Enables calibration mode of the HiTechnic compass sensor

Contents

Syntax
Description
Example
See also
Signature

Syntax
CalibrateCompass(port, f_start)
CalibrateCompass(port, f_start, handle)

Description
Calibrate the compass to reduce influence of metallic objects, especially of the
NXT motor and brick on compass values. You have to calibrate a roboter only once
until the design changes. During calibration the compass should make two full
rotations very slowly. The compass sensor has to be opened (using OpenCompass)
before execution.
Set f_start = true to start calibration mode, and f_start = false to stop it. In
between those commands, the calibration (compass rotation) should occur.
The given port number specifies the connection port. The value port can be
addressed by the symbolic constants SENSOR_1 , SENSOR_2, SENSOR_3 and
SENSOR_4 analog to the labeling on the NXT Brick.
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).

Example
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/CalibrateCompass.html (1 of 2)7/6/2010 8:15:26 AM

38

CalibrateCompass

% compass must be open for calibration


OpenCompass(SENSOR_2);
% enable calibration mode
CalibrateCompass(SENSOR_2, true);
% compass is attached to motor A, rotate 2 full turns
m = NXTMotor('A', 'Power', 5, 'TachoLimit', 720)
m.SendToNXT();
m.WaitFor();
% calibration should now be complete!
CalibrateCompass(SENSOR_2, false);

See also
OpenCompass, GetCompass, CloseSensor, NXT_LSRead, NXT_LSWrite,

Signature

Author: Rainer Schnitzler, Linus Atorf (see AUTHORS)


Date: 2008/08/01
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

39
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/CalibrateCompass.html (2 of 2)7/6/2010 8:15:26 AM

CalibrateGyro

CalibrateGyro
Calibrates the HiTechnic Gyro sensor (measures/sets an offset while in rest)

Contents

Syntax
Description
Examples
See also
Signature

Syntax
offset = CalibrateGyro(port, 'AUTO')
offset = CalibrateGyro(port, 'AUTO', handle)
offset = CalibrateGyro(port, 'MANUAL', manualOffset)
offset = CalibrateGyro(port, 'MANUAL', manualOffset, handle)

Description
In order to use the HiTechnic Gyro Sensor, it has first to be opened using
OpenGyro. Then CalibrateGyro should be called (or a warning will be issued).
Only after this you can safely use GetGyro to retrieve values.
This function will set (and return) the new offset (i.e. reading during reast) of the
according Gyro sensor. Normally users should use the
automatic calibration mode: offset = CalibrateGyro(port, 'AUTO')
The offset will be calculated automatically. During this function the Gyro sensor
value will be measured for at least 1 second (or for at least 5 times). During this
period, the sensor must be at full rest!
40
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/CalibrateGyro.html (1 of 3)7/6/2010 8:15:37 AM

CalibrateGyro

If you want to save time during your program with a well-known Gyro sensor, or
you cannot assure that the sensor is at rest during calibration, you can use the
automatic calibration once in the command line and remember the determined
offset value. Using manual calibration, you can then set a hardcoded value
manually (saving you time and the calibration for this sensor in the future in that
specific program).
Use CalibrateGyro(port, 'MANUAL', manualOffset) to achieve this, with a
correct offset obtained from automatic calibration. This call won't require that the
sensor doesn't move. Also the call is very fast (as compared to at least 1 second
in automatic mode). Use integers for manualOffset, as the gyro sensor is only
accurate to +/- 1 degree per second anyway.
The last optional argument (for both modes) can be a valid NXT handle. If none is
specified, the default handle will be used (call COM_SetDefaultNXT to set one).
Note:
Manual calibration only works for one specific sensor (i.e. one unique piece of
hardware). Other sensors might have different offsets. Also it could be possible
that the offset changes over time or is dependent on your working environment
(humidity, temperature, etc).

Examples
% in this example the gyro is used with automatic
% calibration, very straight forward
port = SENSOR_2;
OpenGyro(port);
CalibrateGyro(port, 'AUTO');
% now the gyro is ready to be used!
% do something, main program etc...
speed = GetGyro(port);
% do something else, loop etc...
% don't forget to clean up
CloseSensor(port);
41
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/CalibrateGyro.html (2 of 3)7/6/2010 8:15:37 AM

CalibrateGyro

% in this example we save the time and effort of


% automatic calibration each time the main program is run...
% on a command window, type:
h = COM_OpenNXT();
COM_SetDefaulNXT(h);
OpenGyro(SENSOR_1);
% now, once the automatic calibration:
offset = CalibrateGyro(SENSOR_1, 'AUTO');
% remember this value...

% our main program looks like this:


% always open gyro first:
OpenGyro(SENSOR_1);
% now use the offset value determined earlier:
CalibrateGyro(SENSOR_1, 'MANUAL', offset);
% ready to use GetGyro now...

See also
OpenGyro, GetGyro, CloseSensor, NXT_SetInputMode,
NXT_GetInputValues,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2009/04/14
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

42
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/CalibrateGyro.html (3 of 3)7/6/2010 8:15:37 AM

CloseSensor

CloseSensor
Closes a sensor port (e.g. turns off active light of the light sensor)

Contents

Syntax
Description
Examples
See also
Signature

Syntax
CloseSensor(port)
CloseSensor(port, handle)

Description
CloseSensor(port) closes the sensor port opened by the Open... functions. The
value port can be addressed by the symbolic constants SENSOR_1 , SENSOR_2,
SENSOR_3 and SENSOR_4 analog to the labeling on the NXT Brick. Closing the light
sensor deactives the active light mode (the red light is turned off), closing the
Ultrasonic sensor stops sending out ultrasound.
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).

Examples
OpenLight(SENSOR_3, 'ACTIVE');
light = GetLight(SENSOR_3);
CloseSensor(SENSOR_3);

See also
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/CloseSensor.html (1 of 2)7/6/2010 8:16:01 AM

43

CloseSensor

NXT_SetInputMode, OpenLight, OpenSound, OpenSwitch, OpenUltrasonic,


SENSOR_1, SENSOR_2, SENSOR_3, SENSOR_4,

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

44
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/CloseSensor.html (2 of 2)7/6/2010 8:16:01 AM

GetAccelerator

GetAccelerator
Reads the current value of the HiTechnic acceleration sensor

Contents

Syntax
Description
Example
See also
Signature

Syntax
acc_vector = GetAccelerator(port)
acc_vector = GetAccelerator(port, handle)

Description
acc_vector = GetAccelerator(port) returns the current 1x3 accelerator vector
acc_vector of the HiTechnic acceleration sensor. The column vector contains the
readings of the x, y, and z-axis, respectively. A reading of 200 is equal to the
acceleration of 1g. Maximum range is -2g to +2g. The given port number
specifies the connection port. The value port can be addressed by the symbolic
constants SENSOR_1 , SENSOR_2, SENSOR_3 and SENSOR_4 analog to the labeling on
the NXT Brick.
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).

Example
OpenAccelerator(SENSOR_4);
acc_Vector = GetAccelerator(SENSOR_4);
CloseSensor(SENSOR_4);
45
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/GetAccelerator.html (1 of 2)7/6/2010 8:16:12 AM

GetAccelerator

See also
OpenAccelerator, CloseSensor, COM_ReadI2C,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2008/09/25
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

46
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/GetAccelerator.html (2 of 2)7/6/2010 8:16:12 AM

GetColor

GetColor
Reads the current value of the HiTechnic Color sensor

Contents

Syntax
Description
Example
See also
Signature

Syntax
[index r g b] = GetColor(port)
[index r g b] = GetColor(port, handle)

Description
degree = GetColor(port) returns the index color value and the RGB-values of
the HiTechnic Color sensor. The color index for mode=0 and mode=1 corresponds
to the following table, but the color values don't be pure RGB-values. Tests give
best results for RGB-colors in brackets:
%
%
%
%
%
%
%
%
%
%
%
%
%

0 = black (0-0-0)
1 = violet
2 = purple
3 = blue
4 = green
5 = lime
6 = yellow
7 = orange
8 = red
9 = crimson
10 = magenta
11 to 16 = pastels
17 = white

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/GetColor.html (1 of 3)7/6/2010 8:32:55 AM

47

GetColor

The color index (0..63) for mode=2 and mode=3 will return a 6 bit color index
number, which encodes red in bit 5 an 4, green in bit 3 and 2 and blue in bit. It
gives good results to identify a color by one value.
The RGB-Values will be returned depending on the mode parameter mode = 0 :
RGB = the current detection level for the color components red, green and blue in
an range of 0 to 255 mode = 1 : RGB = the current relative detection level for the
color components red, green and blue in an range of 0 to 255. The highest value
of red, green and blue is set to 255 and the other components are adjusted
proportionally. mode = 2 : RGB = the analog signal levels for the three color
components red, green and blue with an accurancy of 10 bit (0 to 1023). mode =
3 : RGB = the current relative detection level for the color components red, green
and blue in an range of 0 to 3.
The given port number specifies the connection port. The value port can be
addressed by the symbolic constants SENSOR_1 , SENSOR_2, SENSOR_3 and
SENSOR_4 analog to the labeling on the NXT Brick.
For more complex settings the functions NXT_LSRead and NXT_LSWrite can be
used.
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).

Example
OpenColor(SENSOR_4);
[index r g b] = GetColor(SENSOR_4, 0);
CloseSensor(SENSOR_4);

See also
OpenColor, CalibrateColor, CloseSensor, COM_ReadI2C,

Signature

Author: Rainer Schnitzler, Linus Atorf (see AUTHORS)

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/GetColor.html (2 of 3)7/6/2010 8:32:55 AM

48

GetColor

Date: 2008/10/01
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

49
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/GetColor.html (3 of 3)7/6/2010 8:32:55 AM

GetCompass

GetCompass
Reads the current value of the HiTechnic compass sensor

Contents

Syntax
Description
Example
See also
Signature

Syntax
degree = GetCompass(port)
degree = GetCompass(port, handle)

Description
degree = GetCompass(port) returns the current heading value of the HiTechnic
magnetic compass sensor ranging from 0 to 360 where 0 is north and
counterclockwise (90 = west etc.). The given port number specifies the
connection port. The value port can be addressed by the symbolic constants
SENSOR_1 , SENSOR_2, SENSOR_3 and SENSOR_4 analog to the labeling on the NXT
Brick.
For more complex settings the functions NXT_LSRead and NXT_LSWrite can be
used.
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).

Example
OpenCompass(SENSOR_4);
degree = GetCompass(SENSOR_4);
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/GetCompass.html (1 of 2)7/6/2010 8:33:02 AM

50

GetCompass

CloseSensor(SENSOR_4);

See also
OpenCompass, CalibrateCompass, CloseSensor, COM_ReadI2C,

Signature

Author: Rainer Schnitzler, Alexander Behrens (see AUTHORS)


Date: 2008/08/01
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

51
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/GetCompass.html (2 of 2)7/6/2010 8:33:02 AM

GetGyro

GetGyro
Reads the current value of the HiTechnic Gyro sensor

Contents

Syntax
Description
Example
See also
Signature

Syntax
angularVelocity = GetGyro(port)
angularVelocity = GetGyro(port, handle)

Description
angularVelocity = GetGyro(port) returns the current rotational speed detected
by the HiTechnic Gyroscopic sensor. Maximum range is from -360 to 360 degrees
per second (according to HiTechnic documentation), however greater values have
been observed. Returned values are accurate to +/- 1 degree.
Integration over time gives the rotational position (in degrees). Tests give quite
good results. The given port number specifies the connection port. The value port
can be addressed by the symbolic constants SENSOR_1, SENSOR_2, SENSOR_3 and
SENSOR_4 analog to the labeling on the NXT Brick.
Before using this function, the gyro sensor must be initialized using OpenGyro and
calibrated using CalibrateGyro.
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).

Example
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/GetGyro.html (1 of 2)7/6/2010 8:33:12 AM

52

GetGyro

OpenGyro(SENSOR_2);
CalibrateGyro(SENSOR_2, 'AUTO');
speed = GetGyro(SENSOR_2);
CloseSensor(SENSOR_2);

See also
OpenGyro, CalibrateGyro, CloseSensor, NXT_SetInputMode,
NXT_GetInputValues,

Signature

Author: Linus Atorf, Rainer Schnitzler (see AUTHORS)


Date: 2009/08/31
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

53
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/GetGyro.html (2 of 2)7/6/2010 8:33:12 AM

GetInfrared

GetInfrared
Reads the current value of the Hitechnic infrared sensor (infrared seeker)

Contents

Syntax
Description
Example
See also
Signature

Syntax
[direction rawData] = GetInfrared(port)
[direction rawData] = GetInfrared(port, handle)

Description
[direction rawData] = GetInfrared(port) returns the current direction an the
raw data of the detected infrared signal. direction represents the main direction
(1-9) calculated based on the measured raw data given in the rawData vector
(1x5). Five sensors are provided by the infrared seeker. For more information see
http://www.hitechnic.com
The given port number specifies the connection port. The value port can be
addressed by the symbolic constants SENSOR_1 , SENSOR_2, SENSOR_3 and
SENSOR_4 analog to the labeling on the NXT Brick.
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).

Example
OpenInfrared(SENSOR_4);
54
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/GetInfrared.html (1 of 2)7/6/2010 8:33:23 AM

GetInfrared

[direction rawData] = GetInfrared(SENSOR_4);


CloseSensor(SENSOR_4);

See also
OpenInfrared, CloseSensor, COM_ReadI2C,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2008/09/25
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

55
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/GetInfrared.html (2 of 2)7/6/2010 8:33:23 AM

OpenLight

OpenLight
Initializes the NXT light sensor, sets correct sensor mode

Contents

Syntax
Description
Example
See also
Signature

Syntax
OpenLight(port, mode)
OpenLight(port, mode, handle)

Description
OpenLight(port, mode) initializes the input mode of NXT light sensor specified by
the sensor port and the light mode. The value port can be addressed by the
symbolic constants SENSOR_1 , SENSOR_2, SENSOR_3 and SENSOR_4 analog to the
labeling on the NXT Brick. The mode represents one of two modes
'ACTIVE' (active illumination: red light on) and 'INACTIVE' (passive illumination
red light off). To deactive the active illumination the function CloseSensor is used.
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).
For more complex settings the function NXT_SetInputMode can be used.

Example
OpenLight(SENSOR_1, 'ACTIVE');
light = GetLight(SENSOR_1);
56
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/OpenLight.html (1 of 2)7/6/2010 8:33:31 AM

OpenLight

CloseSensor(SENSOR_1);

See also
NXT_SetInputMode, CloseSensor, GetLight, SENSOR_1, SENSOR_2,
SENSOR_3, SENSOR_4,

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

57
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/OpenLight.html (2 of 2)7/6/2010 8:33:31 AM

OpenRFID

OpenRFID
Initializes the Codatex RFID sensor, sets correct sensor mode

Contents

Syntax
Description
Example
See also
Signature

Syntax
status = OpenRFID(port)

Description
OpenRFID(port) initializes the input mode of Codatex RFID sensor specified by
the sensor port. The value port can be addressed by the symbolic constants
SENSOR_1, SENSOR_2, SENSOR_3 and SENSOR_4 analog to the labeling on the NXT
Brick.
The RF ID Sensor works with 125 kHz transponders compatible with EM4102
modulation type. With this sensor you can read 5-byte-long transponder numbers
into the NXT. Since the NXT RFID sensor is a digital sensor (that uses the IC
protocol), the function NXT_SetInputMode cannot be used as for analog sensors.
Note:
Opening the sensor can take a while. Via Bluetooth, delays of more than 1 second
are not uncommon.

Example
OpenRFID(SENSOR_2);
transID = GetRFID(SENSOR_2,'single');
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/OpenRFID.html (1 of 2)7/6/2010 8:33:38 AM

58

OpenRFID

CloseSensor(SENSOR_2);

See also
GetRFID, CloseSensor,

Signature

Author: Linus Atorf, Rainer Schnitzler (see AUTHORS)


Date: 2008/12/1
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

59
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/OpenRFID.html (2 of 2)7/6/2010 8:33:38 AM

OpenSound

OpenSound
Initializes the NXT sound sensor, sets correct sensor mode

Contents

Syntax
Description
Examples
See also
Signature

Syntax
OpenSound(port, mode)
OpenSound(port, mode, handle)

Description
OpenSound(port, mode) initializes the input mode of NXT sound sensor specified
by the sensor port and the sound mode. The value port can be addressed by the
symbolic constants SENSOR_1 , SENSOR_2, SENSOR_3 and SENSOR_4 analog to the
labeling on the NXT Brick. The mode represents one of two modes 'DB' (dB
measurement) and 'DBA' (dBA measurement)
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).
For more complex settings the function NXT_SetInputMode can be used.

Examples
OpenSound(SENSOR_1, 'DB');
sound = GetSound(SENSOR_1);
CloseSensor(SENSOR_1);
60
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/OpenSound.html (1 of 2)7/6/2010 8:33:44 AM

OpenSound

See also
NXT_SetInputMode, GetSound, CloseSensor, SENSOR_1, SENSOR_2,
SENSOR_3, SENSOR_4,

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

61
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/OpenSound.html (2 of 2)7/6/2010 8:33:44 AM

OpenSwitch

OpenSwitch
Initializes the NXT touch sensor, sets correct sensor mode

Contents

Syntax
Description
Example
See also
Signature

Syntax
OpenSwitch(port)
OpenSwitch(port, handle)

Description
OpenSound(port) initializes the input mode of NXT switch / touch sensor specified
by the sensor port. The value port can be addressed by the symbolic constants
SENSOR_1 , SENSOR_2, SENSOR_3 and SENSOR_4 analog to the labeling on the NXT
Brick.
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).
For more complex settings the function NXT_SetInputMode can be used.

Example
OpenSwitch(SENSOR_4);
switchState = GetSwitch(SENSOR_4);
CloseSensor(SENSOR_4);
62
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/OpenSwitch.html (1 of 2)7/6/2010 8:33:53 AM

OpenSwitch

See also
NXT_SetInputMode, GetSwitch, CloseSensor, SENSOR_1, SENSOR_2,
SENSOR_3, SENSOR_4,

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

63
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/OpenSwitch.html (2 of 2)7/6/2010 8:33:53 AM

OpenUltrasonic

OpenUltrasonic
Initializes the NXT ultrasonic sensor, sets correct sensor mode

Contents

Syntax
Description
Limitations
Examples
See also
Signature

Syntax
OpenUltrasonic(port)
OpenUltrasonic(port, mode)
OpenUltrasonic(port, mode, handle)

Description
OpenUltrasonic(port) initializes the input mode of NXT ultrasonic sensor
specified by the sensor port. The value port can be addressed by the symbolic
constants SENSOR_1 , SENSOR_2, SENSOR_3 and SENSOR_4 analog to the labeling on
the NXT Brick.
OpenUltrasonic(port, mode) can enable the snapshot mode if the value mode is
equal to the string 'snapshot'. This mode provides the snap shot mode (or
SINGLE_SHOT mode) of the NXT ultrasonic sensor, which provides several sensor
readings in one step. See USMakeSnapshot for more information.
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).
Since the NXT ultrasonic sensor is a digital sensor (that uses the IC protocol), the
64
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/OpenUltrasonic.html (1 of 3)7/6/2010 8:34:00 AM

OpenUltrasonic

function NXT_SetInputMode cannot be used as for analog sensors.


Note:
When the US sensor is opened in snapshot mode, the function GetUltrasonic
does not work correctly!

Limitations
Since the Ultrasonic sensors all operate at the same frequency, multiple US
sensors will interfere with each other! If multiple US sensors can "see each
other" (or their echos and reflections), results will be unpredictable (and probably
also unusable). You can avoid this problem by turning off US sensors, or operating
them in snapshot mode (see also USMakeSnapshot and USGetSnapshotResults).

Examples
OpenUltrasonic(SENSOR_4);
distance = GetUltrasonic(SENSOR_4);
CloseSensor(SENSOR_4);

port = SENSOR_4;
OpenUltrasonic(port, 'snapshot');
% send out the ping
USMakeSnapshot(port);
% wait some time for the sound to travel
pause(0.1); % 100ms is probably too much, calculate using
c_sound ;-)
% retrieve all the echos in 1 step
echos = USGetSnapshotResults(port);
CloseSensor(SENSOR_4);

See also
GetUltrasonic, USMakeSnapshot, USGetSnapshotResults, CloseSensor,

Signature
65
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/OpenUltrasonic.html (2 of 3)7/6/2010 8:34:00 AM

OpenUltrasonic

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2008/01/08
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

66
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/OpenUltrasonic.html (3 of 3)7/6/2010 8:34:00 AM

SENSOR_1

SENSOR_1
Symbolic constant SENSOR_1 (returns 0)

Contents

Syntax
Description
Example
See also
Signature

Syntax
port1 = SENSOR_1()

Description
port1 = SENSOR_1() returns 0 as the value port1.

Example
port1 = SENSOR_1()
%result: >> port1 = 0

See also
SENSOR_2, SENSOR_3, SENSOR_4,

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
67

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/SENSOR_1.html (1 of 2)7/6/2010 8:34:06 AM

SENSOR_1

Published with wg_publish; V1.0

68
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/SENSOR_1.html (2 of 2)7/6/2010 8:34:06 AM

SENSOR_2

SENSOR_2
Symbolic constant SENSOR_2 (returns 1)

Contents

Syntax
Description
Example
See also
Signature

Syntax
port2 = SENSOR_2()

Description
port2 = SENSOR_2() returns 1 as the value port2.

Example
port2 = SENSOR_2()
%result: >> port2 = 1

See also
SENSOR_1, SENSOR_3, SENSOR_4,

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
69

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/SENSOR_2.html (1 of 2)7/6/2010 8:34:12 AM

SENSOR_2

Published with wg_publish; V1.0

70
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/SENSOR_2.html (2 of 2)7/6/2010 8:34:12 AM

SENSOR_3

SENSOR_3
Symbolic constant SENSOR_3 (returns 2)

Contents

Syntax
Description
Example
See also
Signature

Syntax
port3 = SENSOR_3()

Description
port3 = SENSOR_3() returns 2 as the value port3.

Example
port3 = SENSOR_3()
%result: >> port3 = 2

See also
SENSOR_1, SENSOR_2, SENSOR_4,

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
71

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/SENSOR_3.html (1 of 2)7/6/2010 8:34:18 AM

SENSOR_3

Published with wg_publish; V1.0

72
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/SENSOR_3.html (2 of 2)7/6/2010 8:34:18 AM

SENSOR_4

SENSOR_4
Symbolic constant SENSOR_4 (returns 3)

Contents

Syntax
Description
Example
See also
Signature

Syntax
port4 = SENSOR_4()

Description
port4 = SENSOR_4() returns 3 as the value port4.

Example
port4 = SENSOR_4()
%result: >> port4 = 3

See also
SENSOR_1, SENSOR_2, SENSOR_3,

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
73

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/SENSOR_4.html (1 of 2)7/6/2010 8:34:24 AM

SENSOR_4

Published with wg_publish; V1.0

74
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/SENSOR_4.html (2 of 2)7/6/2010 8:34:24 AM

USGetSnapshotResults

USGetSnapshotResults
Retrieves up to eight echos (distances) stored inside the US sensor

Contents

Syntax
Description
Example
See also
Signature

Syntax
echos = USGetSnapshotResults(port)
echos = USGetSnapshotResults(port, handle)

Description
echos = USGetSnapshotResults(port) retrieves the echos originating from the
ping that was sent out with USMakeSnapshot(port) for the ultrasonic sensor
connected to port. In order for this to work, the sensor must have been opened in
snapshot mode using OpenUltrasonic(port, 'snapshot').
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).
The return-vector echos always contains exactly 8 readings for up to 8 echos that
were recorded from one single signal. Depending on the structure and reflections,
this can only be one valid echo, or a lot of interference. The values are distances,
just as you'd expect from GetUltrasonic. The values are sorted in order of
appearance, so they should also be sorted with increasing distances.
It is not known how exactly the measurements are to be interpreted!
Please make sure that after calling USGetSnapshotResults, there is a little time
75
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/USGetSnapshotResults.html (1 of 2)7/6/2010 8:34:30 AM

USGetSnapshotResults

period for the sound waves to travel, to be reflected, and be recorded by the
sensor. You can estimate this using the speed of sound and the maximum distance
you expect to measure.
Note: When the US sensor is opened in snapshot mode, the function
GetUltrasonic does not work correctly!

Example
port = SENSOR_4;
OpenUltrasonic(port, 'snapshot');
% send out the ping
USMakeSnapshot(port);
% wait some time for the sound to travel
pause(0.1); % 100ms is probably too much, calculate using
c_sound ;-)
% retrieve all the echos in 1 step
echos = USGetSnapshotResults(port);
CloseSensor(SENSOR_4);
You should also try the file Example_4_NextGenerationUltrasound, m
from the demos-folder,

See also
OpenUltrasonic, GetUltrasonic, USMakeSnapshot, CloseSensor

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2008/01/08
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

76
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/USGetSnapshotResults.html (2 of 2)7/6/2010 8:34:30 AM

USMakeSnapshot

USMakeSnapshot
Causes the ultrasonic sensor to send one snapshot ("ping") and record the echos

Contents

Syntax
Description
Example
See also
Signature

Syntax
USMakeSnapshot(port)
USMakeSnapshot(port, handle)

Description
Call USMakeSnapshot(port) to make the specific ultrasonic sensor connected to
port send out one single signal (called "ping"). In contrast to the US sensor's
continous mode (that is invoked by a normal OpenUltrasonic without the
'snapshot' parameter), the sensor will only send out ultrasonic signals when this
function is called. Up to 8 multiple echos will be recorded, and the according
distances stored in the sensor's internal memory. Use USGetSnapshotResults to
retrieve those 8 readings in one step!
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).
Note: When the US sensor is opened in snapshot mode, the function
GetUltrasonic does not work correctly!

Example
port = SENSOR_4;
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/USMakeSnapshot.html (1 of 2)7/6/2010 8:34:37 AM

77

USMakeSnapshot

OpenUltrasonic(port, 'snapshot');
% send out the ping
USMakeSnapshot(port);
% wait some time for the sound to travel
pause(0.1); % 100ms is probably too much, calculate using
c_sound ;-)
% retrieve all the echos in 1 step
echos = USGetSnapshotResults(port);
CloseSensor(SENSOR_4);
You should also try the file Example_4_NextGenerationUltrasound, m
from the demos-folder,

See also
OpenUltrasonic, GetUltrasonic, USGetSnapshotResults, CloseSensor

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2008/01/08
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

78
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/USMakeSnapshot.html (2 of 2)7/6/2010 8:34:37 AM

NXTMotor

NXTMotor
Constructs an NXTMotor object

Contents

Syntax
Description
Limitations
Example:
See also
Signature

Syntax
M = NXTMotor()
M = NXTMotor(PORT)
M = NXTMotor(PORT, 'PropName1', PropValue1, 'PropName2',
PropValue2, ...)

Description
M = NXTMotor(PORT) constructs an NXTMotor object with motor port PORT and
default attributes. PORT may be either the port number (0, 1, 2 or MOTOR_A,
MOTOR_B, MOTOR_C) or a string specifying the port ('A', 'B', 'C'). To have two
motors synchronized PORT may be a vector of two ports in ascending order.
M = NXTMotor(PORT, 'PropName1', PropValue1, 'PropName2',
PropValue2, ...) constructs an NXTMotor object with motor port(s) PORT in
which the given Property name/value pairs are set on the object. All properties
can also be set after creation by dot-notation (see example).
Available properties are:

Port - the motor port(s) being used, either a string composed of the letters
79

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXTMotor.html (1 of 5)7/6/2010 8:34:44 AM

NXTMotor

'A', 'B', 'C', or a single value or array of the numbers 0, 1, 2. A maximum


of 2 motors is allowed. If 2 motors are specified, the bot will drive in sync
mode, good for driving straight ahead.

Power - integer from -100 to 100, sets power level and direction of rotation
(0 to 100%)
SpeedRegulation - if set to true (default), the motor will try to hold a
constant speed by adjusting power output according to load (e.g. friction) this is only valid for single motors. It must be deactivated when using two
motors! If you'd like to have motor movement with preferrably constant
torque, it's advisable to disable this option. SpeedRegulation must be false
for "normal", unregulated motor control. If set to true, single motors will be
operated in speed regulation mode. This means that the motor will increase
its internal power setting to reach a constant turning speed. Use this option
when working with motors under varying load. If you'd like to have motor
movement with preferrably constant torque, it's advisable to disable this
option. In conjunction with multiple motors (i.e. when Port is an array of 2
ports), you have to disable SpeedRegulation! Multiple motors will enable
synchronization between the two motors. They will run at the same speed as
if they were connected through and axle, leading to straight movement for
driving bots.
TachoLimit - integer from 0 to 99999, specifies the angle in degrees the
motor will try to reach, set 0 to run forever. Note that direction is specified
by the sign of Power.
ActionAtTachoLimit is a string parameter with valid options 'Coast',
'Brake' or 'HoldBrake'. It specifies how the motor(s) should react when
their position counter reaches the set TachoLimit.

In COAST mode, the motor(s) will simply be turned of when the


TachoLimit is reached, leading to free movement until slowly stopping
(called coasting). The TachoLimit won't be met, the motor(s) move
way too far (overshooting), depending on their angular momentum.
Use BRAKE mode (default) to let the motor(s) automatically slow down
nice and smoothly shortly before the TachoLimit. This leads to a very
high precision, usually the TachoLimit is met within +/- 1 degree
(depending on the motor load and speed of course). After this braking,
power to the motor(s) is turned off when they are at rest.
80

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXTMotor.html (2 of 5)7/6/2010 8:34:44 AM

NXTMotor

HOLDBRAKE is similar to BRAKE, but in this case, the active brake of


the motors stays enabled (careful, this consumes a lot of battery
power), causing the motor(s) to actively keep holding their position.

SmoothStart can be set to true to smoothly accelerate movement. This


"manual ramp up" of power will occur fairly quickly. It's comfortable for
driving robots so that they don't loose traction when starting to move. If
used in conjunction with SpeedRegulation for single motors, after
accleration is finished and the full power is applied, the speed regulation can
possibly even accelerate a bit more. This option is only available for
TachoLimit > 0 and ActionAtTachoLimit = 'Brake' or 'HoldBrake'.

For a list of valid methods, see the "See also" section below.
Note:
When using a motor object with two ports set, the motors will be operated in
synchronous mode. This means an internal regulation of the NXT firmware tries to
move both motors at the same speed and to the same position (so that driving
robots can go a straight line for example). With ActionAtTachoLimit == 'Coast'
the sync mode will stay enabled during coasting, allowing for the firmware to
correct the robot's position (align it straight ahead again). If you want to use
those motors again, you must reset/stop the synchonization before by sending a .
Stop() to the motors!

Limitations
If you send a command to the NXT without waiting for the previous motor
operation to have finished, the command will be dropped (the NXT indicates this
with a high and low beep tone). Use the classes method WaitFor to make sure the
motor is ready for new commands, or stop the motor using the method .Stop.
The option SmoothStart in conjunction with ActionAtTachoLimit == 'Coast' is
not available. As a workaround, disable SmoothStart for this mode. SmoothStart
will generally only work when TachoLimit > 0 is set.
With ActionAtTachoLimit = 'Coast' and synchronous driving (two motors), the
motors will stay synced after movement (even after .WaitFor() has finished).
This is by design. To disable the synchonization, just use .Stop('off').
SpeedRegulation = true does not always produce the expected result. Due
to
81
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXTMotor.html (3 of 5)7/6/2010 8:34:44 AM

NXTMotor

internal PID regulation, the actually achieved speed can vary or oscillate when
using very small values for Power. This happens especially when using the motor
with a heavy load for small speeds. In this case it can be better to disable
SpeedRegulation. In general, speed regulation should only be enabled if a
constant rotational velocity is desired. For constant torque, better disable this
feature.

Example:
% Construct a NXTMotor object on port 'B' with a power of
% 60, disabled speed regulation, a TachoLimit of 360 and
% send the motor settings to the NXT brick.
motorB = NXTMotor('B', 'Power', 60)
motorB.SpeedRegulation
motorB.TachoLimit
motorB.ActionAtTachoLimit

= false;
= 360;
= 'Brake'; % this is the default

anyway
motorB.SmoothStart

= true;

% enough setting up params, let's go!


motorB.SendToNXT();
% let MATLAB wait until the motor has stopped moving
motorB.WaitFor();
% Play tone when motor is ready to be used again
NXT_PlayTone(400,500);

% let's use a driving robot


m = NXTMotor('BC', 'Power', 60);
m.TachoLimit
= 1000;
m.SmoothStart
= true,
% start soft
m.ActionAtTachoLimit = 'coast'; % we want very smooth
"braking", too :-)
m.SendToNXT();
% go!
m.WaitFor();

% are we there yet?

% we're here, motors are still moving / coasting, so give the


bot time!
82
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXTMotor.html (4 of 5)7/6/2010 8:34:44 AM

NXTMotor

pause(3);
% you can still hear the synchronization (high noisy beeping)
% before we go back, we have to disable the synchronization
quickly
m.Stop();
% reverse direction
m.Power = -m.Power;
m.SendToNXT();
m.WaitFor();
pause(3);
m.Stop();
NXT_PlayTone(500, 100); % all done

See also
SendToNXT, ReadFromNXT, WaitFor, Stop, ResetPosition,
DirectMotorCommand,

Signature

Author: Linus Atorf, Aulis Telle, Alexander Behrens (see AUTHORS)


Date: 2009/08/24
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

83
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXTMotor.html (5 of 5)7/6/2010 8:34:44 AM

ReadFromNXT

ReadFromNXT
Reads current state of specified motor(s) from NXT brick

Contents

Syntax
Description
Limitations:
Examples:
See also
Signature

Syntax
DATA = OBJ.ReadFromNXT
DATA = OBJ.ReadFromNXT(HANDLE)
[DATA1 DATA2] = OBJ.ReadFromNXT
[DATA1 DATA2] = OBJ.ReadFromNXT(HANDLE)

Description
Request the current state of the motor object OBJ from the NXT brick. NXTMotor
object OBJ is not modified. DATA is a structure with property/value pairs.
If the NXTMotor object OBJ controls two motors, DATA1 and DATA2 hold the
parameters of the first and the second motor respectively. If only one output
argument is given, the parameters of the first motor are returned.
Use the optional parameter HANDLE to identifiy the connection to use for this
command. Otherwise the default handle (see COM_SetDefaultNXT) will be used.
The returned struct contains the following fields:
84
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/ReadFromNXT.html (1 of 4)7/6/2010 8:34:50 AM

ReadFromNXT

Port - The motor port these data apply to.

Power - The currently set power level (from -100 to 100).

Position - The motor's position in degrees (of the internal rotation sensor).
These encoders should be accurate to +/- 1 degree. Values will increase
positively during forward motion, and decrease during reverse motion. You
can reset this counter by using the method .ResetPosition.
IsRunning - A boolean indicating wether the motor is currently spinning or
actively braking (after having called Stop('brake'). It will only be false
once the motor is in free-running "coast" mode, i.e. when the power to this
motor is turned off (i.e. after calling Stop('off') or when the set
TachoLimit was reached). To clarify: if a motor was stopped using .Stop
('brake'), or if .ActionAtTachoLimit was set to 'HoldBrake', IsRunning
will keep returning true! Use the method .WaitFor to check wether a motor
is ready to accept new commands!
SpeedRegulation - A boolean indicating wether the motor currently uses
speed regulation. This is turned off during synchronous driving (when driving
with 2 motors at the same time).
TachoLimit - The currently set goal for the motor to reach. If set to 0, the
motor is spinning forever.
TachoCount - This counter indicates the progress of the motor for its current
goal -- i.e. if a TachoLimit ~= 0 is set, TachoCount will count up to this
value during movement.

Note:
The values of TachoCount and TachoLimit (which can nicely be used as progress
indicators) are not guaranteed to keep being valid once motor movement has
finished. They can/will be cleared by the next SendToNXT, Stop, StopMotor or
maybe even DirectMotorCommand.
For advanced users: The field Position maps to the NXT firmware's register /
IOmap counter RotationCount, and TachoCount maps to TachoCount as expected.

Limitations:
85
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/ReadFromNXT.html (2 of 4)7/6/2010 8:34:50 AM

ReadFromNXT

Apart from the previously mentioned limitation of IsRunning (return values


slightly differ from what would be expected), the value of SpeedRegulation can
sometimes be unexpected: The DATA struct returned by ReadFromNXT always
returns the true state of the NXT's firmware registers (it's basically just a wrapper
for NXT_GetOutputState). When using an NXTMotor object with SpeedRegulation
= true, the regulation will only be enabled during drivin. When the motor control
starts braking, regulation will be disabled, and this is what ReadFromNXT shows
you. So don't worry when you receive SpeedRegulation = false using this
method, also you clearly enabled speed regulation. This is by design, and the
motor did in fact use speed regulation during its movement.

Examples:
% Move motor A and show its state after 3 seconds
motorA = NXTMotor('A', 'Power', 50);
motorA.SendToNXT();
pause(3);
data = motorA.ReadFromNXT();

% Construct a NXTMotor object on port 'A' with a power of


% 50, TachoLimit of 1000, and send the motor settings to the NXT.
% Show the progress of the motor movement "on the fly".
motorA = NXTMotor('A', 'Power', 50, 'TachoLimit', 1000);
% this example wouldn't work with 'HoldBrake'
motorA.ActionAtTachoLimit = 'Brake';
motorA.SendToNXT();
% monitor during movement
data = motorA.ReadFromNXT();
while(data.IsRunning)
percDone = abs(data.TachoCount / data.TachoLimit) * 100;
disp(sprintf('Motor movement is %d % complete/n', percDone));
data = motorA.ReadFromNXT(); % refresh
end%while

See also
86
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/ReadFromNXT.html (3 of 4)7/6/2010 8:34:50 AM

ReadFromNXT

NXTMotor, SendToNXT, ResetPosition, NXT_GetOutputState,

Signature

Author: Aulis Telle, Linus Atorf (see AUTHORS)


Date: 2008/11/12
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

87
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/ReadFromNXT.html (4 of 4)7/6/2010 8:34:50 AM

ResetPosition

ResetPosition
Resets the position counter of the given motor(s).

Contents

Syntax
Description
Example:
See also
Signature

Syntax
OBJ.ResetPosition()
OBJ.ResetPosition(HANDLE)

Description
Reset the position of the motor specified in OBJ. Only the internal states of the
NXT brick corresponding to the specified motor(s) are reset. The motor is not
moved. This resets the field .Position you can read out using .ReadFromNXT.
Specify HANDLE (optional) to identifiy the connection to use for this command.
Otherwise the defaul handle (set using COM_SetDefaultNXT) will be used.
Note:
For advanced users: The field Position maps to the NXT firmware's register /
IOmap counter RotationCount. It can also be reset using
NXT_ResetMotorPosition(port, false). That's in fact what this method does.

Example:
motorC = NXTMotor('C', 'Power', -20, 'TachoLimit', 120);
88
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/ResetPosition.html (1 of 2)7/6/2010 8:34:56 AM

ResetPosition

motorC.SendToNXT();
motorC.WaitFor();
data = motorC.ReadFromNXT()
%>> data =
%
Port: 2
%
Power: 0
%
IsRunning: 0
% SpeedRegulation: 0
%
TachoLimit: 120
%
TachoCount: -120
%
Position: -120
motorC.ResetPosition();
data = motorC.ReadFromNXT()
%>> data =
%
Port: 2
%
Power: 0
%
IsRunning: 0
% SpeedRegulation: 0
%
TachoLimit: 120
%
TachoCount: -120
%
Position: 0

See also
NXTMotor, ReadFromNXT, NXT_ResetMotorPosition, NXT_GetOutputState,
NXC_ResetErrorCorrection,

Signature

Author: Aulis Telle, Linus Atorf (see AUTHORS)


Date: 2009/08/25
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

89
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/ResetPosition.html (2 of 2)7/6/2010 8:34:56 AM

SendToNXT

SendToNXT
Send motor settings to the NXT brick

Contents

Syntax
Description
Limitations
Example:
See also
Signature

Syntax
OBJ.SendToNXT
OBJ.SendToNXT(HANDLE)

Description
OBJ.SendToNXT sends the motor settings in OBJ to the NXT brick.
OBJ.SendToNXT(HANDLE) uses HANDLE to identifiy the connection to use for this
command. This is optional. Otherwise the defaul handle (set using
COM_SetDefaultNXT) will be used.
For a valid list of properties and how they affect the motors' behaviour, see the
documentation for the class constructor NXTMotor.

Limitations
With ActionAtTachoLimit = 'Coast' and synchronous driving (two motors), the
motors will stay synced after movement (even after .WaitFor() has finished).
This is by design. To disable the synchonization, just use .Stop.
If you send a command to the NXT without waiting for the previous motor

90

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/SendToNXT.html (1 of 2)7/6/2010 8:35:03 AM

SendToNXT

operation to have finished, the command will be dropped (the NXT indicates this
with a high and low beep tone). Use the motor-objects method .WaitFor to make
sure the motor is ready for new commands, or stop the motor(s) using .Stop.

Example:
motor = NXTMotor('A', 'Power', 50, 'TachoLimit', 200);
motor.SendToNXT();
motor.WaitFor();
NXT_PlayTone(400,500);

See also
NXTMotor, ReadFromNXT, Stop, WaitFor, DirectMotorCommand,

Signature

Author: Linus Atorf, Aulis Telle, Alexander Behrens (see AUTHORS)


Date: 2009/07/12
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

91
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/SendToNXT.html (2 of 2)7/6/2010 8:35:03 AM

Stop

Stop
Stops or brakes specified motor(s)

Contents

Syntax
Description
Example:
See also
Signature

Syntax
OBJ.Stop()
OBJ.Stop(BRAKEMODE)
OBJ.Stop(BRAKEMODE, HANDLE)

Description
OBJ.Stop() is the same as OBJ.Stop('off').
OBJ.Stop(BRAKEMODE) stops the motor specified in OBJ with the brakemode
specified in BRAKEMODE:
BRAKEMODE can take the following values:
'nobrake', 'off', 0, false: The electrical power to the specified motor is simply
disconnected, the so-called "COAST" mode. Motor will keep spinning until it comes
to a soft stop.
'brake', 'on', 1, true: This will actively halt the motor at the current position
(until the next movement command); it's a "hard brake".
Use HANDLE to identify the connection to use for this command (optional).

92

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/Stop.html (1 of 2)7/6/2010 8:35:08 AM

Stop

Note:
To stop all motors at precisely the same time, please see the command
StopMotor. It can be called with the syntax StopMotor('all', 'off') or
StopMotor('all', 'brake'). When comparing this to the obj.Stop method, it
acts more precise when wanting to stop multiple motors at the same time...
Using the active brake (e.g. .Stop('brake')) can be very power consuming, so
watch your battery level when using this functionality for long periods of time.

Example:
motorC = NXTMotor('C', 'Power', -100, 'TachoLimit', 0);
motorC.SendToNXT();
pause(4);
% wait 4 seconds
motorC.Stop('brake');

See also
NXTMotor, WaitFor, StopMotor,

Signature

Author: Aulis Telle, Linus Atorf (see AUTHORS)


Date: 2009/07/20
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

93
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/Stop.html (2 of 2)7/6/2010 8:35:08 AM

WaitFor

WaitFor
Wait for motor(s) to stop (busy waiting)

Contents

Syntax
Description
Examples:
See also
Signature

Syntax
OBJ.WaitFor TIMEDOUT = OBJ.WaitFor(TIMEOUT)
OBJ.WaitFor(HANDLE) TIMEDOUT = OBJ.WaitFor(TIMEOUT, HANDLE)

Description
OBJ.WaitFor waits for motor specified by OBJ to stop. We do this by reading the
motor state from the NXT brick repeatedly until controlled movement is finished. If
the motor is set to run infinitely, the method returns immediately and displays a
warning.
TIMEDOUT = OBJ.WaitFor(TIMEOUT) does the same as described above but has
an additional timeout TIMEOUT (given in seconds). After this time the function
stops waiting and returns true. Otherwise it returns false. This functionality is
useful to avoid that your robot (and your program) get stuck in case the motor
should somehow get stalled (e.g.by driving against a wall).
Use HANDLE (optional) to identify the connection to use for this command.
Note:
If you specify TIMEOUT and the motor is not able to finish its current movement
command in time (maybe because the motor is blocked?), waiting will be aborted.
94
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/WaitFor.html (1 of 3)7/6/2010 8:35:14 AM

WaitFor

The motor is probably still busy in this case, so you have to make sure it is ready
to accept commands before using it again (i.e. by calling .Stop()).

Examples:
% If a |SendToNXT| command is immediately followed by a |
Stop|
% command without using |WaitFor| MATLAB does not wait to
send
% the stop command until the motor has finished its
rotation.
% Thus, the motor does not rotate at all, since the stop
command
% reaches the NXT before the motor starts its rotation due
to
% its mechanical inertia.
motorA = NXTMotor('A', 'Power', 60, 'TachoLimit', 1000);
motorA.SendToNXT();
motorA.Stop('off');
% motor A barely moved at all...
% To avoid this issue, WaitFor has to be used!
motorC = NXTMotor('C', 'Power', -20, 'TachoLimit', 120);
motorC.SendToNXT();
motorC.WaitFor();
data = motorC.ReadFromNXT();

% Instantiate motor A and run it


m = NXTMotor('A', 'Power', 50, 'TachoLimit', 1000);
m.SendToNXT();
% Wait for the motor, try waiting for max. 10 seconds
timedOut = WaitFor(m, 10);
if timedOut
disp('Motor timed out, is it stalled?')
m.Stop('off'); % this needed to "unlock" the motor
end%if
% now we can send new motor commands again...

See also
95
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/WaitFor.html (2 of 3)7/6/2010 8:35:14 AM

WaitFor

NXTMotor, ReadFromNXT, SendToNXT, Stop, StopMotor,

Signature

Author: Aulis Telle, Linus Atorf (see AUTHORS)


Date: 2009/07/20
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

96
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/WaitFor.html (3 of 3)7/6/2010 8:35:14 AM

DirectMotorCommand

DirectMotorCommand
Sends a direct command to the specified motor

Contents

Syntax
Description
Limitations:
Examples
See also
Signature

Syntax
DirectMotorCommand(port, power, angle, speedRegulation,
syncedToMotor, turnRatio, rampMode)

Description
DirectMotorCommand(port, power, angle, speedRegulation,
syncedToMotor, turnRatio, rampMode) sends the given settings like motor port
(MOTOR_A, MOTOR_B or MOTOR_C), the power (-100...100), the angle limit (also
called TachoLimit), speedRegulation ('on', 'off'), syncedToMotor (MOTOR_A,
MOTOR_B, MOTOR_C), turnRatio (-100...100) and rampMode ('off', 'up',
'down').
This function is basically a convenient wrapper for NXT_SetOutputState. It
provides the fastest way possible to send a direct command to the motor(s) via
Bluetooth or USB. Complex parameter combinations which are needed for speed
regulation or synchronous driving when using NXT_SetOutputState are not
necessary, this function does make sure the motor "just works". See below for
examples.
Note:
When driving synced motors, it's recommended to stop the motors between
consecutive direct motor command (using StopMotor) and to reset their position
97
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/DirectMotorCommand.html (1 of 3)7/6/2010 8:35:20 AM

DirectMotorCommand

counters (using NXT_ResetMotorPosition).


This function is intended for the advanced user. Knowledge about the LEGO
MINDSTORMS NXT Bluetooth Communication Protocol is not required, but can help
to understand what this function does.

Limitations:
Generally spoken, using DirectMotorCommand together with the class NXTMotor
(and its method SendToNXT) for the same motor is strongly discouraged. This
function can interfer with the on-brick embedded NXC program MotorControl and
could cause it to crash. It ignores whatever is happening on the NXT when sending
the direct command. The only advantage is the low latency.
When using the parameter angleLimit, the motor tries to reach the desired
position by turning off the power at the specified position. This will lead to
overshooting of the motor (i.e. the position it stops will be too high or too low).
Additionally, the LEGO firmware applies an error correction mechanism which can
lead to confusing results. Please look inside the chapter "Troubleshooting" of this
toolbox documentation for more details.

Examples
% let a driving robot go straight a bit.
% we use motor synchronization for ports B & C:
DirectMotorCommand(MOTOR_B, 60, 0, 'off', MOTOR_C, 0, 'off');
pause(5); % driving 5 seconds
StopMotor(MOTOR_B, 'off');
StopMotor(MOTOR_C, 'off');

% let motor A rotate for 1000 degrees (with COAST after "braking"
and
% the firmware's error correction) and with speed regulation:
DirectMotorCommand(MOTOR_A, 50, 1000, 'on', 'off', 0, 'off');

% this command
DirectMotorCommand(MOTOR_A, 0, 0, 'off', 'off', 0, 'off');
% does exactly the same as calling

98

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/DirectMotorCommand.html (2 of 3)7/6/2010 8:35:20 AM

DirectMotorCommand

StopMotor(MOTOR_A, 'off');
% or as using
m = NXTMotor('A');
m.Stop('off');

See also
NXT_SetOutputState, NXT_GetOutputState, NXTMotor, SendToNXT, Stop,
StopMotor,

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2009/08/25
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

99
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/DirectMotorCommand.html (3 of 3)7/6/2010 8:35:20 AM

MOTOR_A

MOTOR_A
Symbolic constant MOTOR_A (returns 0)

Contents

Syntax
Description
Example
See also
Signature

Syntax
portA = MOTOR_A()

Description
portA = MOTOR_A() returns 0 as the value portA.

Example
portA = MOTOR_A()
%result: >> portA = 0

See also
MOTOR_B, MOTOR_C,

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
100

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MOTOR_A.html (1 of 2)7/6/2010 8:35:26 AM

MOTOR_A

Published with wg_publish; V1.0

101
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MOTOR_A.html (2 of 2)7/6/2010 8:35:26 AM

MOTOR_B

MOTOR_B
Symbolic constant MOTOR_B (returns 1)

Contents

Syntax
Description
Example
See also
Signature

Syntax
portB = MOTOR_B()

Description
portB = MOTOR_B() returns 1 as the value portB.

Example
portB = MOTOR_B()
%result: >> portB = 1

See also
MOTOR_A, MOTOR_C,

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
102

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MOTOR_B.html (1 of 2)7/6/2010 8:35:31 AM

MOTOR_B

Published with wg_publish; V1.0

103
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MOTOR_B.html (2 of 2)7/6/2010 8:35:31 AM

MOTOR_C

MOTOR_C
Symbolic constant MOTOR_C (returns 2)

Contents

Syntax
Description
Example
See also
Signature

Syntax
portC = MOTOR_C()

Description
portC = MOTOR_C() returns 2 as the value portC.

Example
portC = MOTOR_C()
%result: >> portC = 2

See also
MOTOR_A, MOTOR_B,

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
104

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MOTOR_C.html (1 of 2)7/6/2010 8:35:41 AM

MOTOR_C

Published with wg_publish; V1.0

105
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MOTOR_C.html (2 of 2)7/6/2010 8:35:41 AM

NXC_MotorControl

NXC_MotorControl
Sends advanced motor-command to the NXC-program MotorControl on
the NXT brick,

Contents

Syntax
Description
Limitations
Example
See also
Signature

Syntax
NXC_MotorControl(Port, Power, TachoLimit, SpeedRegulation,
ActionAtTachoLimit, SmoothStart)
NXC_MotorControl(Port, Power, TachoLimit, SpeedRegulation,
ActionAtTachoLimit, SmoothStart, handle)

Description
The NXC-program "MotorControl" must be running on the brick, otherwise this
function will not work. It is used to send advanced motor commands to the NXT
that can perform better and more precise motor regulation than possible with only
classic direct commands.
While one command is being executed (i.e. when the motor is still being controlled
if a TachoLimit other than 0 was set), this motor cannot accept new commands.
Use the NXTMotor classes command .WaitFor to make sure the motor has
finished it's current operation, before sending a new one. If the NXC-program
receives a new command while it is still busy, a warning signal (high beep, then
low beep) will be played.
The command StopMotor (or NXTMotor's method .Stop) is always available to
stop a controlled motor-operation, even before the TachoLimit is reached.
106
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXC_MotorControl.html (1 of 4)7/6/2010 8:35:47 AM

NXC_MotorControl

Input:

Port has to be a port number between 0 and 2, or an array with max. 2


different motors specified.
Power is the power level applied to the motor, value between -100 and 100
(sign changes direction)
TachoLimit - integer from 0 to 99999, specifies the angle in degrees the
motor will try to reach, set 0 to run forever. Note that direction is specified
by the sign of Power.
SpeedRegulation must be false for "normal", unregulated motor control. If
set to true, single motors will be operated in speed regulation mode. This
means that the motor will increase its internal power setting to reach a
constant turning speed. Use this option when working with motors under
varying load. If you'd like to have motor movement with preferrably constant
torque, it's advisable to disable this option. In conjunction with multiple
motors (i.e. when Port is an array of 2 ports), you have to disable
SpeedRegulation! Multiple motorss will enable synchronization between the
two motors. They will run at the same speed as if they were connected
through and axle, leading to straight movement for driving bots.
ActionAtTachoLimit is a string parameter with valid options 'Coast',
'Brake' or 'HoldBrake'. It specifies how the motor(s) should react when
their position counter reaches the set TachoLimit. In COAST mode, the
motor(s) will simply be turned of when the TachoLimit is reached, leading
to free movement until slowly stopping (called coasting). The TachoLimit
won't be met, the motor(s) move way too far (overshooting), depending on
their angular momentum. Use BRAKE mode (default) to let the motor(s)
automatically slow down nice and smoothly shortly before the TachoLimit.
This leads to a very high precision, usually the TachoLimit is met within +/1 degree (depending on the motor load and speed of course). After this
braking, power to the motor(s) is turned off when they are at rest.
HOLDBRAKE is similar to BRAKE, but in this case, the active brake of the
motors stays enabled (careful, this consumes a lot of battery power),
causing the motor(s) to actively keep holding their position.
SmoothStart can be set to true to smoothly accelerate movement. This
"manual ramp up" of power will occur fairly quickly. It's comfortable for
107

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXC_MotorControl.html (2 of 4)7/6/2010 8:35:47 AM

NXC_MotorControl

driving robots so that they don't loose traction when starting to move. If
used in conjunction with SpeedRegulation for single motors, after
accleration is finished and the full power is applied, the speed regulation can
possibly even accelerate a bit more.

handle (optional) defines the given NXT connection. If no handle is specified,


the default one (COM_GetDefaultNXT()) is used.

Limitations
If you send a command to the NXT without waiting for the previous motor
operation to have finished, the command will be dropped (the NXT indicates this
with a high and low beep tone). Use NXTMotor classes WaitFor to make sure the
motor is ready for new commands, or stop the motor using NXTMotor's method .
Stop.
The option SmoothStart in conjunction with ActionAtTachoLimit == 'Coast' is
not available. As a workaround, disable SmoothStart for this mode.
With ActionAtTachoLimit = 'Coast' and synchronous driving (two motors), the
motors will stay synced after movement (even after .WaitFor() has finished).
This is by design. To disable the synchonization, just use StopMotor(port,
'off').

Example
See also
WaitForMotor, NXT_SetOutputState, NXT_GetOutputState,
NXC_ResetErrorCorrection, MOTOR_A, MOTOR_B, MOTOR_C

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2009/07/20
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

108
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXC_MotorControl.html (3 of 4)7/6/2010 8:35:47 AM

NXC_MotorControl

109
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXC_MotorControl.html (4 of 4)7/6/2010 8:35:47 AM

NXC_ResetErrorCorrection

NXC_ResetErrorCorrection
Sends reset error correction command to the NXC-program MotorControl on the
NXT

Contents

Syntax
Description
Limitations
Example
See also
Signature

Syntax
NXC_ResetErrorCorrection(port)
NXC_ResetErrorCorrection(port, handle)

Description
The NXC-program "MotorControl" must be running on the brick, otherwise this
function will not work. It is used to sent advanced motor commands to the NXT
that can perform better and more precise motor regulation than possible with only
classic direct commands.
This function resets the "internal error correction memory" for the according
motor. Usually, you cannot move the NXT motors by hand in between two
commands that control the motors, since the modified motor position does not
match the internal counters any more. This leads to unexpected motor behaviour
(when the NXT firmware tries to correct the manual movements you just made).
To work around this problem, it is possible to reset the error correction counter by
hand using this function. It will clear the counter TachoCount, since this counter is
internally attached to the error correction. The counter BlockTachoCount (see
direct commands specification of the LEGO Mindstorms Bluetooth Developer Kit)
will also be reset (since it is used to coordinate multiple motors during
110

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXC_ResetErrorCorrection.html (1 of 3)7/6/2010 8:35:57 AM

NXC_ResetErrorCorrection

synchronous driving).
It is recommended to call this function before using classic direct commands (i.e.
like NXT_SetOutputState), to get the intuitively expected results.
Input:
port has to be a port number between 0 and 2. It can also be an array of valid
port-numbers, i.e. [0; 1], [0; 2], [1; 2] or [0; 1; 2]. The named constants
MOTOR_A to MOTOR_C can be used for clarity (i.e. port = [MOTOR_A; MOTOR_B].
handle is optional and determines the NXT handle to be used, if specified.
Otherwise the default handle will be used (set using COM_SetDefaultNXT).

Limitations
This function has a built-in waiting-period. A pause of 75ms will be made after
sending the actual command to the NXT.

Example
% This will reset the TachoCount counter for port A on the NXT,
which
% also resets the error correction
NXC_ResetErrorCorrection(MOTOR_A);
% Now MOTOR_A behaves as if the NXT was freshly booted up...
% The "personal" position counter (field |Position| when calling
% a motor object's method |ReadFromNXT()|) won't be affected
through this
% -- it will stay untouched until reset by a motor object's method
% |ResetPosition()|)

See also
NXTMotor, NXC_MotorControl, NXT_SetOutputState,
NXT_GetOutputState, NXT_ResetMotorPosition, ReadFromNXT,

Signature
111
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXC_ResetErrorCorrection.html (2 of 3)7/6/2010 8:35:57 AM

NXC_ResetErrorCorrection

Author: Alexander Behrens, Linus Atorf (see AUTHORS)


Date: 2008/11/12
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

112
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXC_ResetErrorCorrection.html (3 of 3)7/6/2010 8:35:57 AM

StopMotor

StopMotor
Stops / brakes specified motor. (Synchronisation will be lost after this)

Contents

Syntax
Description
Limitations:
Example
See also
Signature

Syntax
StopMotor(port, mode)
StopMotor(port, mode, handle)

Description
StopMotor(port, mode) stops the motor connected to the given port. The value
port can be addressed by the symbolic constants MOTOR_A, MOTOR_B, MOTOR_C and
'all' (all motor at at the same time) analog to the labeling on the NXT Brick. The
argument mode can be equal to 'off' (or 'nobrake' or false) which cuts off the
electrical power to the specific motor, so called "COAST" mode. The option
'brake' (or 'on' or true) will actively halt the motor at the current position (until
the next command).
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).
Note:
The value port equal to 'all' can be used to stopp all motors at the same time
using only one single Bluetooth packet. After a StopMotor command the motor
snychronization will be lost.
113
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/StopMotor.html (1 of 3)7/6/2010 8:36:02 AM

StopMotor

With mode equal to 'off', the motor will slowly stop spinning, but using 'brake'
applies real force to the motor to stand still at the current position, just like a real
brake.
Using the active brake (e.g. StopMotor(MOTOR_A, 'brake')) can be very power
consuming, so watch your battery level when using this functionality for long
periods of time.

Limitations:
When working with a motor object that contains multiple motors (e.g. created by
NXTMotor('BC')), stopping only one motor (in this case with e.g. StopMotor
(MOTOR_B, 'off')) can lead to unexpected behavior. When working with
synchronized motors, always stop those motors together. It's generally
recommended to use the motor object's method Stop if possible.

Example
% regular stop
StopMotor(MOTOR_B, 'brake');

% imagine we have all motors moving at once:


m1 = NXTMotor('A', 'Power', 80);
m2 = NXTMotor('BC', 'Power', 50);
m1.SendToNXT();
m2.SendToNXT();
% a great way to stop all motors at once at the same time now:
StopMotor('all', 'off');
% the other possibility would not stop movement at precisely
% the same moment:
m1.Stop();
m2.Stop();

See also
NXTMotor, Stop, NXT_SetOutputState, MOTOR_A, MOTOR_B, MOTOR_C,
114

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/StopMotor.html (2 of 3)7/6/2010 8:36:02 AM

StopMotor

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2009/08/24
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

115
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/StopMotor.html (3 of 3)7/6/2010 8:36:02 AM

SwitchLamp

SwitchLamp
Switches the LEGO lamp on or off (has to be connected to a motor port)

Contents

Syntax
Description
Examples
See also
Signature

Syntax
SwitchLamp(port, mode)
SwitchLamp(port, mode, handle)

Description
SwitchLamp(port, mode) turns the LEGO lamp on or off. The given port number
specifies the used motor port. The value port can be addressed by the symbolic
constants MOTOR_A , MOTOR_B and MOTOR_C analog to the labeling on the NXT Brick.
The value mode supports two modes 'on' and 'off' to turn the lamp on and off.
The last optional argument can be a valid NXT handle. If none is specified, the
default handle will be used (call COM_SetDefaultNXT to set one).
This function simply sets power 100 to the specified motor port to turn on the
lamp, or sets power 0 to turn it off. Note that dimming is not possible, even a
power of just 1 will be enough to switch the lamp to full brightness (after a short
while).
A StopMotor command with parameter 'off' will also turn off the lamp, but it is
recommended to use this function when working with lamps for better readability.

Examples
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/SwitchLamp.html (1 of 2)7/6/2010 8:36:07 AM

116

SwitchLamp

SwitchLamp(MOTOR_B, 'on');

SwitchLamp(MOTOR_A, 'off');

See also
NXTMotor, StopMotor, MOTOR_A, MOTOR_B, MOTOR_C,

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

117
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/SwitchLamp.html (2 of 2)7/6/2010 8:36:07 AM

NXT_GetBatteryLevel

NXT_GetBatteryLevel
Returns the current battery level in milli volts

Contents

Syntax
Description
Examples
See also
Signature

Syntax
voltage = NXT_GetBatteryLevel()
voltage = NXT_GetBatteryLevel(handle)

Description
voltage = NXT_GetBatteryLevel() returns the current battery level voltage of
the NXT Brick in milli voltage.
voltage = NXT_GetBatteryLevel(handle) uses the given Bluetooth connection
handle. This should be a serial handle on a PC system and a file handle on a Linux
system.
If no Bluetooth handle is specified the default one (COM_GetDefaultNXT) is used.

Examples
voltage = NXT_GetBatteryLevel();

handle = COM_OpenNXT('bluetooth.ini');
voltage = NXT_GetBatteryLevel(handle);
118
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_GetBatteryLevel.html (1 of 2)7/6/2010 8:36:15 AM

NXT_GetBatteryLevel

See also
COM_GetDefaultNXT, NXT_SendKeepAlive,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

119
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_GetBatteryLevel.html (2 of 2)7/6/2010 8:36:15 AM

NXT_GetCurrentProgramName

NXT_GetCurrentProgramName
Returns the name of the current running program

Contents

Syntax
Description
Examples
See also
Signature

Syntax
[name prog_run] = NXT_GetCurrentProgramName()
[name prog_run] = NXT_GetCurrentProgramName(handle)

Description
[name prog_run] = NXT_GetCurrentProgramName() returns the name of the
current running program. and the boolean flag prog_run (false == no program is
running).
[name prog_run] = NXT_GetCurrentProgramName(handle) uses the given NXT
handle.
If no NXT handle is specified the default one (COM_GetDefaultNXT) is used.

Examples
name = NXT_GetCurrentProgramName();

handle = COM_OpenNXT('bluetooth.ini');
name = NXT_GetCurrentProgramName(handle);
120
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_GetCurrentProgramName.html (1 of 2)7/6/2010 8:36:21 AM

NXT_GetCurrentProgramName

See also
NXT_StartProgram, NXT_StopProgram,

Signature

Author: Alexander Behrens (see AUTHORS)


Date: 2008/10/18
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

121
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_GetCurrentProgramName.html (2 of 2)7/6/2010 8:36:21 AM

NXT_GetFirmwareVersion

NXT_GetFirmwareVersion
Returns the protocol and firmware version of the NXT

Contents

Syntax
Description
Examples
See also
Signature

Syntax
[protocol_version firmware_version] = NXT_GetFirmwareVersion()
[protocol_version firmware_version] = NXT_GetFirmwareVersion(handle)

Description
[protocol_version firmware_version] = NXT_GetFirmwareVersion() returns
the protocol and firmware version of the NXT as strings.
[protocol_version firmware_version] = NXT_GetFirmwareVersion(handle)
uses the given NXT connection handle. This should be a struct containing a serial
handle on a PC system and a file handle on a Linux system.
If no NXT handle is specified the default one (COM_GetDefaultNXT) is used.

Examples
[protocol_version firmware_version] = NXT_GetFirmwareVersion();

handle = COM_OpenNXT('bluetooth.ini');
[protocol_version firmware_version] = NXT_GetFirmwareVersion
122
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_GetFirmwareVersion.html (1 of 2)7/6/2010 8:36:30 AM

NXT_GetFirmwareVersion

(handle);

See also
COM_GetDefaultNXT,

Signature

Author: Alexander Behrens (see AUTHORS)


Date: 2008/05/22
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

123
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_GetFirmwareVersion.html (2 of 2)7/6/2010 8:36:30 AM

NXT_GetInputValues

NXT_GetInputValues
Executes a complete sensor reading (requests and retrieves input values)

Contents

Syntax
Description
Examples
See also
Signature

Syntax
data = NXT_GetInputValues(port)
data = NXT_GetInputValues(port, handle)

Description
data = NXT_GetInputValues(port) processes a complete sensor reading, i.e.
requests input values and collects the answer of the given sensor port. The value
port can be addressed by the symbolic constants SENSOR_1, SENSOR_2, SENSOR_3
and SENSOR_4 analog to the labeling on the NXT Brick. The return value data is a
struct variable. It contains several sensor settings and information.
data = NXT_GetInputValues(port, handle) uses the given Bluetooth
connection handle. This should be a serial handle on a PC system and a file handle
on a Linux system.
If no Bluetooth handle is specified the default one (COM_GetDefaultNXT) is used.
Output:
data.Port % current port number (0..3)
data.Valid % validation flag
124
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_GetInputValues.html (1 of 3)7/6/2010 8:36:35 AM

NXT_GetInputValues

data.Calibrated % boolean, true if calibration file found and used


data.TypeByte % sensor type
data.TypeName % sensor mode
data.ModeByte % mode
data.ModeName % mode name
data.RawADVal % raw A/D value
data.NormalizedADVal % normalized A/D value
data.ScaledVal % scaled value
data.CalibratedVal % calibrated value
Note:
Data are only valid if .Valid is ~= 0. This should usually be the case, but a short
while after setting a new sensor mode using NXT_SetInputMode, you have to
carefully check .Valid on your own! Experience shows that only .ScaledVal is
influenced by this, apparently .NormalizedADVal seems valid all the time, but
closer examination is needed...
For more details see the official LEGO Mindstorms communication protocol.

Examples
data = NXT_GetInputValues(SENSOR_3);

handle = COM_OpenNXT('bluetooth.ini');
data = NXT_GetInputValues(SENSOR_1, handle);

See also
125
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_GetInputValues.html (2 of 3)7/6/2010 8:36:35 AM

NXT_GetInputValues

NXT_SetInputMode, GetLight, GetSwitch, GetSound, GetUltrasonic,


SENSOR_1, SENSOR_2, SENSOR_3, SENSOR_4,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

126
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_GetInputValues.html (3 of 3)7/6/2010 8:36:35 AM

NXT_GetOutputState

NXT_GetOutputState
Requests and retrieves an output motor state reading

Contents

Syntax
Description
Examples
See also
Signature

Syntax
data = NXT_GetOutputState(port)
data = NXT_GetOutputState(port, handle)

Description
data = NXT_GetOutputState(port) requests and retrieves an output motor state
reading of the given motor port. The value port can be addressed by the
symbolic constants MOTOR_A, MOTOR_B and MOTOR_C analog to the labeling on the
NXT Brick. The return value data is a struct variable. It contains several motor
settings and information.
data = NXT_GetOutputState(port, handle) uses the given Bluetooth
connection handle. This should be a serial handle on a PC system and a file handle
on a Linux system.
If no Bluetooth handle is specified the default one (COM_GetDefaultNXT) is used.
Output:
data.Port % current port number (0..3)
data.Power % current motor power
127
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_GetOutputState.html (1 of 3)7/6/2010 8:36:40 AM

NXT_GetOutputState

data.Mode % motor mode byte


data.ModeIsMOTORON % flag: "motor is on"
data.ModeIsBRAKE % flag: "motor uses the advanced brake mode (PVM)"
data.ModeIsREGULATED % flag: "motor uses a regulation"
data.RegModeByte % motor regulation byte
data.RegModeName % name of regulation mode
data.TurnRatio % turn ratio value
data.RunStateByte % motor run state byte
data.RunStateName % name of run state
data.TachoLimit % tacho / angle limit
data.TachoCount % current absolute tacho count
data.BlockTachoCount % current relative tacho count
data.RotationCount % current second relative tacho count
For more details see the official LEGO Mindstorms communication protocol.

Examples
data = NXT_GetOutputState(MOTOR_B);

handle = COM_OpenNXT('bluetooth.ini');
data = NXT_GetOutputState(MOTOR_A, handle);

See also
128
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_GetOutputState.html (2 of 3)7/6/2010 8:36:40 AM

NXT_GetOutputState

ReadFromNXT, NXT_SetOutputState, DirectMotorCommand, MOTOR_A,


MOTOR_B, MOTOR_C,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

129
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_GetOutputState.html (3 of 3)7/6/2010 8:36:40 AM

NXT_LSGetStatus

NXT_LSGetStatus
Gets the number of available bytes for digital low speed sensors (I2C)

Contents

Syntax
Description
Examples
See also
Signature

Syntax
[BytesReady status] = NXT_LSGetStatus(port)
[BytesReady status] = NXT_LSGetStatus(port, handle)

Description
[BytesReady status] = NXT_LSGetStatus(port) gets the number of available
bytes from the low speed (digital) sensor reading of the given sensor port. The
value port can be addressed by the symbolic constants SENSOR_1, SENSOR_2,
SENSOR_3 and SENSOR_4 analog to the labeling on the NXT Brick. The return value
BytesReady contains the number of bytes available to read. status indicates if an
error occures by the packet transmission. Function checkStatusBytes is
interpreting this information per default.
[BytesReady status] = NXT_LSGetStatus(port, handle) uses the given
Bluetooth connection handle. This should be a serial handle on a PC system and a
file handle on a Linux system.
If no Bluetooth handle is specified the default one (COM_GetDefaultNXT) is used.
For more details see the official LEGO Mindstorms communication protocol.
Note:
130
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_LSGetStatus.html (1 of 2)7/6/2010 8:37:00 AM

NXT_LSGetStatus

This function's status byte sometimes contains an error message: "Pending


communication transaction in progress". This is by design (see documentation of
NXTCommLSCheckStatus on page 70 of the "LEGO Mindstorms NXT Executable
File Specification" document).
Before using LS commands, the sensor mode has to be set to LOWSPEED_9V using
the NXT_SetInputMode command.

Examples
[BytesReady status] = NXT_LSGetStatus(SENSOR_3);

handle = COM_OpenNXT('bluetooth.ini');
NXT_SetInputMode(SENSOR_1, 'LOWSPEED_9V', 'RAWMODE',
'dontreply');
% note that status can contain errorsmessages, use
checkStatusByte
[BytesReady status] = NXT_LSGetStatus(SENSOR_1, handle);

See also
NXT_SetInputMode, checkStatusByte, NXT_LSWrite, NXT_LSRead,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

131
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_LSGetStatus.html (2 of 2)7/6/2010 8:37:00 AM

NXT_LSWrite

NXT_LSWrite
Writes given data to a digital low speed sensor port (I2C)

Contents

Syntax
Description
Example
See also
Signature

Syntax
NXT_LSWrite(port, RXLength, data, ReplyMode)
NXT_LSWrite(port, RXLength, data, ReplyMode, handle)

Description
NXT_LSWrite(port, RXLength, data, ReplyMode) writes the given data to a
low speed (digital) sensor of the given sensor port. The value port can be
addressed by the symbolic constants SENSOR_1, SENSOR_2, SENSOR_3 and
SENSOR_4 analog to the labeling on the NXT Brick. The value RXLength represents
the data length of the expected receiving packet. By the ReplyMode one can
request an acknowledgement for the packet transmission. The two strings
'reply' and 'dontreply' are valid.
NXT_LSWrite(port, RXLength, data, ReplyMode, handle) uses the given
Bluetooth connection handle. This should be a serial handle on a PC system and a
file handle on a Linux system.
If no Bluetooth handle is specified the default one (COM_GetDefaultNXT) is used.
For more details see the official LEGO Mindstorms communication protocol.
Note:
132
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_LSWrite.html (1 of 2)7/6/2010 8:37:06 AM

NXT_LSWrite

For LS communication on the NXT, data lengths are limited to 16 bytes per
command. Rx Data Length MUST be specified in the write command since reading
from the device is done on a master-slave basis.
Before using LS commands, the sensor mode has to be set to LOWSPEED_9V using
the NXT_SetInputMode command.

Example
RequestLen = 1;
I2Cdata = hex2dec(['02'; '42']); % specific ultrasonic IC
command
handle = COM_OpenNXT('bluetooth.ini');
NXT_SetInputMode(SENSOR_1, 'LOWSPEED_9V', 'RAWMODE',
'dontreply');
NXT_LSWrite(SENSOR_1, RequestLen, I2Cdata, 'dontreply', handle);

See also
NXT_SetInputMode, NXT_LSRead, NXT_LSGetStatus, COM_ReadI2C,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

133
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_LSWrite.html (2 of 2)7/6/2010 8:37:06 AM

NXT_LSRead

NXT_LSRead
Reads data from a digital low speed sensor port (I2C)

Contents

Syntax
Description
Examples
See also
Signature

Syntax
[data BytesRead] = NXT_LSRead(port)
[data BytesRead] = NXT_LSRead(port, handle)
[data BytesRead optionalStatusByte] = NXT_LSRead(port)
[data BytesRead optionalStatusByte] = NXT_LSRead(port, handle)

Description
[data BytesRead] = NXT_LSRead(port)) gets the data of the low speed (digital)
sensor value of the given sensor port. The value port can be addressed by the
symbolic constants SENSOR_1, SENSOR_2, SENSOR_3 and SENSOR_4 analog to the
labeling on the NXT Brick. The return value BytesRead contains the number of
bytes available to read.
[data BytesRead] = NXT_LSRead(port, handle) uses the given Bluetooth
connection handle. This should be a serial handle on a PC system and a file handle
on a Linux system.
[data BytesRead optionalStatusByte] = NXT_LSRead(port, [handle]) will
ignore the automatic statusbyte check and instead return it as output argument.
This causes the function to ignore erronous I2C calls or crashes if the sensor is not
134
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_LSRead.html (1 of 3)7/6/2010 8:37:16 AM

NXT_LSRead

yet ready. You can effectively save a call to NXT_LSGetStatus with this, if you
interpret the statusbytes correctly. This may vary, depending on your I2C sensor.
The handle argument is still optional, like above.
If no NXT handle is specified the default one (COM_GetDefaultNXT) is used.
For more details see the official LEGO Mindstorms communication protocol.
Note:
For LS communication on the NXT, data lengths are limited to 16 bytes per
command. Furthermore, this protocol does not support variable-length return
packages, so the response will always contain 16 data bytes, with invalid data
bytes padded with zeros.
Before using LS commands, the sensor mode has to be set to LOWSPEED_9V using
the NXT_SetInputMode command.

Examples
handle = COM_OpenNXT('bluetooth.ini');
NXT_SetInputMode(SENSOR_1, 'LOWSPEED_9V', 'RAWMODE',
'dontreply');
% usually we would use NXT_LSWrite before, to request some sort
of reply
[data BytesRead] = NXT_LSRead(SENSOR_1, handle);

See also
NXT_SetInputMode, NXT_LSWrite, NXT_LSGetStatus, COM_ReadI2C,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
135

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_LSRead.html (2 of 3)7/6/2010 8:37:16 AM

NXT_LSRead

Published with wg_publish; V1.0

136
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_LSRead.html (3 of 3)7/6/2010 8:37:16 AM

NXT_MessageRead

NXT_MessageRead
Retrieves a "NXT-to-NXT message" from the specified inbox

Contents

Syntax
Description
Examples
See also
Signature

Syntax
[message localInboxReturn] = NXT_MessageRead(LocalInbox, RemoteInbox,
RemoveFromRemote)
[message localInboxReturn] = NXT_MessageRead(LocalInbox, RemoteInbox,
RemoveFromRemote, handle)
[message localInboxReturn statusByte] = NXT_MessageRead(LocalInbox,
RemoteInbox, RemoveFromRemote)
[message localInboxReturn statusByte] = NXT_MessageRead(LocalInbox,
RemoteInbox, RemoveFromRemote, handle)

Description
This function reads a NXT-to-NXT bluetooth message from a mailbox queue on the
NXT. LocalInbox and RemoteInbox are the mailbox numbers and must be
between 0 and 9. The difference between local and remote mailbox is not fully
understood, so it's best to use the same value for both parameters. For more
details see the official LEGO Mindstorms communication protocol.
Set RemoveFromRemote to true to clear the just retrieved message from the NXT's
mailbox (and free occupied memory). Set it to false to just "look into" the
message while it will still remain on the NXT's message queue.
137
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_MessageRead.html (1 of 3)7/6/2010 8:37:25 AM

NXT_MessageRead

message contains the actual message (string) that has been retrieved.
localInboxReturn is just the mailbox number that the message was read from
(again, see official Mindstorms communication protocol).
Optionally, the packet's statusbyte is returned in the output argument
statusByte, if requested. Warning from this functions will then be supressed (i.e.
no warnings are raised then).
If no NXT handle is specified the default one (COM_GetDefaultNXT) is used.
Note:
This command can only be used when an external program (e.g. written in NXT-G,
NXC or NBC) is running on the NXT. Otherwise a warning will be thrown (and an
empty message will be returned).
Use this function to read data locally stored on the NXT. There are 10 usable
mailbox queues, each with a certain size (so be careful to avoid overflows).
Maximum message limit is 58 bytes / chars. This function can be used to
communicate with NXC programs (the NXC-function "SendMessage" can be used
to write the data on the NXT).

Examples
NXT_MessageWrite('Test message', 0);
pause(1)
% an NXC program will process this message from inbox 0
% and generate / "send" an answer to inbox 1 for us
reply = NXT_MessageRead(1, 1, true);

See also
NXT_MessageWrite,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2009/08/31
Copyright: 2007-2009, RWTH Aachen University

138

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_MessageRead.html (2 of 3)7/6/2010 8:37:25 AM

NXT_MessageRead

Published with wg_publish; V1.0

139
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_MessageRead.html (3 of 3)7/6/2010 8:37:25 AM

NXT_MessageWrite

NXT_MessageWrite
Writes a "NXT-to-NXT message" to the NXT's incoming BT mailbox queue

Contents

Syntax:
Description:
Examples:
See also
Signature

Syntax:
NXT_MessageWrite(message)
NXT_MessageWrite(message, mailbox)
NXT_MessageWrite(message, mailbox, handle)

Description:
NXT_MessageWrite(message) sends given message to the NXT brick
NXT_MessageWrite(message, mailbox) stores message in the specified mailbox.
If no mailbox is specified, default one is 0 (zero)
NXT_MessageWrite(message, mailbox, handle) uses the given NXT connection
handle. If no handle is specified, the default one (COM_GetDefaultNXT()) is used.
Note:
Use this function to store data locally on the NXT. There are 10 usable mailbox
queues, each with a certain size (so be careful to avoid overflows). Maximum
message limit is 58 bytes / chars. This function can be used to communicate with
NXC programs (the NXC-function "ReceiveRemoteString" can be used to read the
data on the NXT).
140
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_MessageWrite.html (1 of 2)7/6/2010 8:37:32 AM

NXT_MessageWrite

Examples:
NXT_MessageWrite('F010045');

NXT_MessageWrite('F010045', 1);

handle = COM_OpenNXT();
NXT_MessageWrite('F010045', 0, handle);

See also
NXT_MessageRead,

Signature

Author: Laurent Vaylet, The MathWorks SAS (France), Alexander Behrens


(see AUTHORS)
Date: 2008/12/17
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

141
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_MessageWrite.html (2 of 2)7/6/2010 8:37:32 AM

NXT_PlaySoundFile

NXT_PlaySoundFile
Plays the given sound file on the NXT Brick

Contents

Syntax
Description
Examples
See also
Signature

Syntax
NXT_PlaySoundFile(filename, 'loop')
NXT_PlaySoundFile(filename, '', handle)

Description
NXT_PlaySoundFile(filename, loop) plays the soundfile stored on NXT Brick
determined by the string filename. The maximum length is limited to 15
characters. The file extension '.rso' is added automatically if it was omitted. If the
loop parameter is equal to 'loop' the playback loop is activated.
NXT_PlaySoundFile(name, loop, handle) uses the given NXT connection
handle. This should be a a struct containing a serial handle on a PC system and a
file handle on a Linux system.
If no Bluetooth handle is specified the default one (COM_GetDefaultNXT) is used.
For more details see the official LEGO Mindstorms communication protocol.

Examples
NXT_PlaySoundFile('Goodmorning', 0);
142
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_PlaySoundFile.html (1 of 2)7/6/2010 8:37:42 AM

NXT_PlaySoundFile

handle = NXT_OpenNXT('bluetooth.ini');
NXT_StartProgram('Goodmorning.rso', 1, handle);

See also
NXT_StopSoundPlayback,

Signature

Author: Alexander Behrens (see AUTHORS)


Date: 2008/05/22
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

143
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_PlaySoundFile.html (2 of 2)7/6/2010 8:37:42 AM

NXT_PlayTone

NXT_PlayTone
Plays a tone with the given frequency and duration

Contents

Syntax
Description
Examples
See also
Signature

Syntax
NXT_PlayTone(frequency, duration)
NXT_PlayTone(frequency, duration, handle)

Description
NXT_PlayTone(frequency, duration) plays a tone of the frequency in Hz (200 14000Hz) and the duration in milli seconds.
NXT_PlayTone(frequency, duration, handle) sends the play tone command
over the specific NXT handle (e.g. struct containing a serial handle (PC) / file
handle (Linux)).
If no NXT handle is specified the default one (COM_GetDefaultNXT) is used.
For more details see the official LEGO Mindstorms communication protocol.

Examples
NXT_PlayTone(440, 100);

144
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_PlayTone.html (1 of 2)7/6/2010 8:37:46 AM

NXT_PlayTone

handle = COM_OpenNXT('bluetooth.ini');
COM_SetDefaultNXT(handle);
NXT_PlayTone(1200, 120);

See also
COM_GetDefaultNXT,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

145
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_PlayTone.html (2 of 2)7/6/2010 8:37:46 AM

NXT_ReadIOMap

NXT_ReadIOMap
Reads the IO map of the given module ID

Contents

Syntax
Description
Examples
See also
Signature

Syntax
bytes = NXT_ReadIOMap(mod_id, offset, n_bytes)
bytes = NXT_ReadIOMap(mod_id, offset, n_bytes, handle)

Description
bytes = NXT_ReadIOMap(mod_id, offset, n_bytes) returns the data bytes of
the module identified by the given module ID mod_id. The total number of bytes is
determined by n_bytes and the position of the first byte index by the offset
parameter.
bytes = NXT_ReadIOMap(mod_id, offset, n_bytes, handle) sends the IO map
read command over the specific NXT handle (e.g. serial handle (PC) / file handle
(Linux)).
If no NXT handle is specified the default one (COM_GetDefaultNXT) is used.
For more details see the official LEGO Mindstorms communication protocol.

Examples
OutputModuleID = 131073
146
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_ReadIOMap.html (1 of 2)7/6/2010 8:37:51 AM

NXT_ReadIOMap

bytes = NXT_ReadIOMap(OutputModuleID, 0, 29);

handle = COM_OpenNXT('bluetooth.ini');
OutputModuleID = 131073
SoundModuleID = 524289, 0, 30, handle);

See also
NXT_WriteIOMap, COM_GetDefaultNXT,

Signature

Author: Alexander Behrens (see AUTHORS)


Date: 2008/05/22
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

147
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_ReadIOMap.html (2 of 2)7/6/2010 8:37:51 AM

NXT_ResetInputScaledValue

NXT_ResetInputScaledValue
Resets the sensor's ScaledVal back to 0 (depends on current sensor mode)

Contents

Syntax
Description
Examples
See also
Signature

Syntax
NXT_ResetInputScaledValue(port)
NXT_ResetInputScaledValue(port, handle)

Description
NXT_ResetInputScaledValue(port) resets the sensors ScaledVal back to 0 of
the given sensor port. The value port can be addressed by the symbolic
constants SENSOR_1, SENSOR_2, SENSOR_3 and SENSOR_4 analog to the labeling on
the NXT Brick. The ScaledVal is set by function NXT_SetInputMode.
NXT_ResetInputScaledValue(port, handle) uses the given NXT connection
handle. This should be a struct containing a serial handle on a PC system and a
file handle on a Linux system.
If no NXT handle is specified the default one (COM_GetDefaultNXT) is used.
For more details see the official LEGO Mindstorms communication protocol.
Note:
This function should be called after using NXT_SetInputMode, before you want to
actually use your new special input value (to make sure counting starts at zero).
148
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_ResetInputScaledValue.html (1 of 2)7/6/2010 8:38:00 AM

NXT_ResetInputScaledValue

See NXT_GetInputValues for more details about what kind of values are returned.

Examples
NXT_ResetInputScaledValue(SENSOR_2);

handle = COM_OpenNXT('bluetooth.ini');
NXT_ResetInputScaledValue(SENSOR_4, handle);

See also
NXT_SetInputMode, NXT_GetInputValues,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

149
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_ResetInputScaledValue.html (2 of 2)7/6/2010 8:38:00 AM

NXT_ResetMotorPosition

NXT_ResetMotorPosition
Resets NXT internal counter for specified motor, relative or absolute counter

Contents

Syntax
Description
Examples
See also
Signature

Syntax
NXT_ResetMotorPosition(port, isRelative)
NXT_ResetMotorPosition(port, isRelative, handle)

Description
NXT_ResetMotorPosition(port, isRelative) resets the NXT internal counter of
the given motor port. The value port can be addressed by the symbolic constants
MOTOR_A, MOTOR_B, MOTOR_C analog to the labeling on the NXT Brick. The boolean
flag isRelative determines the relative (BlockTachoCount) or absolute counter
(RotationCount).
NXT_ResetMotorPosition(port, handle) uses the given NXT connection handle.
This should be a struct containing a serial handle on a PC system and a file handle
on a Linux system.
If no NXT handle is specified the default one (COM_GetDefaultNXT) is used.
For more details see the official LEGO Mindstorms communication protocol.

Examples
150
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_ResetMotorPosition.html (1 of 2)7/6/2010 8:38:07 AM

NXT_ResetMotorPosition

NXT_ResetMotorPosition(MOTOR_B, true);

handle = COM_OpenNXT('bluetooth.ini');
NXT_ResetMotorPosition(MOTOR_A, false, handle);

See also
NXTMotor, ResetPosition, NXC_ResetErrorCorrection,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

151
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_ResetMotorPosition.html (2 of 2)7/6/2010 8:38:07 AM

NXT_SendKeepAlive

NXT_SendKeepAlive
Sends a KeepAlive packet. Optional: requests sleep time limit.

Contents

Syntax
Description
Examples
See also
Signature

Syntax
[status SleepTimeLimit] = NXT_SendKeepAlive(ReplyMode)
[status SleepTimeLimit] = NXT_SendKeepAlive(ReplyMode, handle)

Description
[status SleepTimeLimit] = NXT_SendKeepAlive(ReplyMode) sends a KeepAlive
packet to the NXT Brick to get the current sleep time limit of the Brick in
milliseconds. By the ReplyMode one can request an acknowledgement for the
packet transmission. The two strings 'reply' and 'dontreply' are valid. status
indicates if an error occures by the packet transmission. Function
checkStatusBytes is interpreting this information per default. The value
SleepTimeLimit contains the time in milliseconds after the NXT brick will turn off
automatically. The variable will only be set if ReplyMode is 'reply'. The sleep
time limit setting can only be modified using the on-screen-menu on the brick
itself.
Using 'dontreply' will just send a keep-alive packet. This means, the NXT
internal counter when to shut down automatically (this is a setting that can only
be accessed directly on the NXT) will be reset. This counter is not an inactivity
counter: Bluetooth traffic will NOT stop the NXT from turning off. E.g. if the sleep
limit is set to 10 minutes, the only way to keep the NXT Brick from turning off is to
send a keep-alive packet within this time.
152
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_SendKeepAlive.html (1 of 3)7/6/2010 8:38:13 AM

NXT_SendKeepAlive

If you use replymode 'reply', SleepTimeLimit tells you the current setting on the
brick, in milliseconds. 0 means sleep timer is disabled. -1 is an invalid answer: You
obviously didn't use 'reply' and still tried to get an answer.
[status SleepTimeLimit] = NXT_SendKeepAlive(ReplyMode, handle) uses the
given NXT connection handle. This should be a struct containing a serial handle on
a PC system and a file handle on a Linux system.
If no NXT handle is specified the default one (COM_GetDefaultNXT) is used.
For more details see the official LEGO Mindstorms communication protocol.
Note:
This function is also called by COM_OpenNXT(). Then a keep-alive packet is send
and the answer will be received to check for a correctly working bidirectional
bluetooth connection.

Examples
[status SleepTimeLimit] = NXT_SendKeepAlive('reply');

NXT_SendKeepAlive('dontreply');

handle = COM_OpenNXT('bluetooth.ini');
[status SleepTimeLimit] = NXT_SendKeepAlive('reply', handle);

See also
COM_OpenNXT, NXT_GetBatteryLevel,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University

153

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_SendKeepAlive.html (2 of 3)7/6/2010 8:38:13 AM

NXT_SendKeepAlive

Published with wg_publish; V1.0

154
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_SendKeepAlive.html (3 of 3)7/6/2010 8:38:13 AM

NXT_SetBrickName

NXT_SetBrickName
Sets a new name for the NXT Brick (connected to the specified handle)

Contents

Syntax
Description
Examples
See also
Signature

Syntax
[NXT_SetBrickName(name)
NXT_SetBrickName(name, handle)

Description
NXT_SetBrickName(name) sets a new name for the NXT Brick. The value name is a
string value and determines the new name of the Brick. The maximum length is
limited to 15 characters.
NXT_SetBrickName(name, handle) uses the given NXT connection handle. This
should be a struct containing a serial handle on a PC system and a file handle on a
Linux system.
If no NXT handle is specified the default one (COM_GetDefaultNXT) is used.
For more details see the official LEGO Mindstorms communication protocol.

Examples
NXT_SetBrickName('MyRobot');
155
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_SetBrickName.html (1 of 2)7/6/2010 8:38:31 AM

NXT_SetBrickName

handle = COM_OpenNXT('bluetooth.ini');
NXT_SetBrickName('Mindy', handle);

See also
COM_GetDefaultNXT, NXT_SendKeepAlive, NXT_GetBatteryLevel,

Signature

Author: Linus Atorf, Alexander Behrens (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

156
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_SetBrickName.html (2 of 2)7/6/2010 8:38:31 AM

NXT_SetInputMode

NXT_SetInputMode
Sets a sensor mode, configures and initializes a sensor to be read out

Contents

Syntax
Description
Examples
See also
Signature

Syntax
status = NXT_SetInputMode(port, SensorTypeDesc, SensorModeDesc,
ReplyMode)
status = NXT_SetInputMode(port, SensorTypeDesc, SensorModeDesc,
ReplyMode, handle)

Description
status = NXT_SetInputMode(InputPort, SensorTypeDesc, SensorModeDesc,
ReplyMode) sets mode, configures and initializes the given sensor port to be
ready to be read out. The value port can be addressed by the symbolic constants
SENSOR_1, SENSOR_2, SENSOR_3 and SENSOR_4 analog to the labeling on the NXT
Brick. The value SensorTypeDesc determines the sensor type. See all valid types
below. SensorModeDesc represents the sensor mode. It specifies what mode the .
ScaledVal from NXT_GetInputValues should be. Valid parameters see below. By
the ReplyMode one can request an acknowledgement for the packet transmission.
The two strings 'reply' and 'dontreply' are valid. The return value status
indicates if an error occures by the packet transmission.
status = NXT_SetInputMode(InputPort, SensorTypeDesc, SensorModeDesc,
ReplyMode, handle) uses the given NXT connection handle. This should be a
struct containing a serial handle on a PC system and a file handle on a Linux
system.
157
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_SetInputMode.html (1 of 4)7/6/2010 8:38:35 AM

NXT_SetInputMode

If no NXT handle is specified the default one (COM_GetDefaultNXT) is used.


Input:
SensorTypeDesc: Valid types are (all strings):
NO_SENSOR (nothing, use to close sensor port)
SWITCH (NXT touch sensor, "binary")
LIGHT_ACTIVE (NXT light sensor, red LED is on)
LIGHT_INACTIVE (NXT light sensor, red LED is off)
SOUND_DB (NXT sound sensor, unit dB)
SOUND_DBA (NXT sound sensor, unit dBA)
LOWSPEED (NXT, passive digital sensor)
LOWSPEED_9V (NXT, active digital sensor, e.g. UltraSonic)
TEMPERATURE (old RCX sensor)
REFLECTION (old RCX sensor)
ANGLE (old RCX sensor)
CUSTOM (user defined)
SensorModeDesc: Valid modes are (all strings):
RAWMODE (Fastest. RawADVal will be used)
BOOLEANMODE (1 if above 45% threshold, else 0)
TRANSITIONCNTMODE (count transitions of booleanmode)
PERIODCOUNTERMODE (counr periods (up and down transition) of boolean mode)
158
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_SetInputMode.html (2 of 4)7/6/2010 8:38:35 AM

NXT_SetInputMode

PCTFULLSCALEMODE (normalized percentage between 0 and 100, use .


NormalizedADVal instead!)
More exotic modes are: CELSIUSMODE (RCX temperature only)
FAHRENHEITMODE (RCX temperature only)
ANGLESTEPSMODE (RCX rotation only)
SLOPEMASK (what's this???)
MODEMASK (what's this???)
For more details see the official LEGO Mindstorms communication protocol.

Examples
status = NXT_SetInputMode(SENSOR_1, 'SOUND_DB', 'RAWMODE',
'dontreply');

handle = COM_OpenNXT('bluetooth.ini');
status = NXT_SetInputMode(SENSOR_3, 'LIGHT_ACTIVE', 'RAWMODE',
'dontreply', handle);

See also
NXT_GetInputValues, OpenLight, OpenSound, OpenSwitch,
OpenUltrasonic, CloseSensor, SENSOR_1, SENSOR_2, SENSOR_3,
SENSOR_4,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
159

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_SetInputMode.html (3 of 4)7/6/2010 8:38:35 AM

NXT_SetInputMode

Published with wg_publish; V1.0

160
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_SetInputMode.html (4 of 4)7/6/2010 8:38:35 AM

NXT_SetOutputState

NXT_SetOutputState
Sends previously specified settings to current active motor.

Contents

Syntax
Description
Example
See also
Signature

Syntax
status = NXT_SetOutputState(port, power, IsMotorOn, IsBrake,
RegModeName, TurnRatio, RunStateName, TachoLimit, ReplyMode)
status = NXT_SetOutputState(port, power, IsMotorOn, IsBrake,
RegModeName, TurnRatio, RunStateName, TachoLimit, ReplyMode, handle)

Description
status = NXT_SetOutputState(OutputPort, Power, IsMotorOn, IsBrake,
RegModeName, TurnRatio, RunStateName, TachoLimit, ReplyMode) sends the
given settings like motor port (MOTOR_A, MOTOR_B or MOTOR_C), the power (100...100, the IsMotorOn boolean flag, the IsBrake boolean flag, the regulation
mode name RegModeName ('IDLE', 'SYNC', 'SPEED'), the TurnRatio (100...100), the RunStateName ('IDLE', 'RUNNING', 'RAMUP', 'RAMPDOWN'), the
TachoLimit (angle limit) in degrees, and the ReplyMode. By the ReplyMode one
can request an acknowledgement for the packet transmission. The two strings
'reply' and 'dontreply' are valid. The return value status indicates if an error
occures by the packet transmission.
status = NXT_SetOutputState(OutputPort, Power, IsMotorOn, IsBrake,
RegModeName, TurnRatio, RunStateName, TachoLimit, ReplyMode, handle)
uses the given NXT connection handle. This should be a serial handle on a PC
system and a file handle on a Linux system.
161
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_SetOutputState.html (1 of 2)7/6/2010 8:38:39 AM

NXT_SetOutputState

Example
NXT_SetOutputState(MOTOR_A, 80, true, true, 'SPEED', 0,
'RUNNING', 360, 'dontreply');

See also
DirectMotorCommand, NXT_GetOutputState, ReadFromNXT, MOTOR_A,
MOTOR_B, MOTOR_C,

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

162
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_SetOutputState.html (2 of 2)7/6/2010 8:38:39 AM

NXT_StartProgram

NXT_StartProgram
Starts the given program on the NXT Brick

Contents

Syntax
Description
Examples
See also
Signature

Syntax
NXT_StartProgram(filename, [handle])
status = NXT_StartProgram(filename, [handle])

Description
NXT_StartProgram(filename) starts the embedded NXT Brick program
determined by the string filename. The maximum length is limited to 15
characters. The file extension '.rxe' is added automatically if it was omitted. The
output argument status is optional and return the error status of the collected
packet. If it is omitted, not reply packet will be requested (this is significantly
faster via Bluetooth).
The last parameter handle is optional. If no NXT handle is specified the default
one (COM_GetDefaultNXT) is used.
For more details see the official LEGO Mindstorms communication protocol.

Examples
NXT_StartProgram('ResetCounter');
163
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_StartProgram.html (1 of 2)7/6/2010 8:38:45 AM

NXT_StartProgram

handle = COM_OpenNXT('bluetooth.ini');
NXT_StartProgram('Demo.rxe', handle);

See also
NXT_StopProgram, NXT_GetCurrentProgramName,

Signature

Author: Alexander Behrens, Linus Atorf (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

164
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_StartProgram.html (2 of 2)7/6/2010 8:38:45 AM

NXT_StopProgram

NXT_StopProgram
Stops the currently running program on the NXT Brick

Contents

Syntax
Description
Examples
See also
Signature

Syntax
NXT_StopProgram()
NXT_StopProgram(handle)

Description
NXT_StopProgram() stops the current running embedded NXT Brick program.
NXT_StopProgram(handle) uses the given NXT connection handle. This should be
a struct containing a serial handle on a PC system and a file handle on a Linux
system.
If no Bluetooth handle is specified the default one (COM_GetDefaultNXT) is used.
For more details see the official LEGO Mindstorms communication protocol.

Examples
NXT_StopProgram();

handle = COM_OpenNXT('bluetooth.ini');
165
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_StopProgram.html (1 of 2)7/6/2010 8:38:49 AM

NXT_StopProgram

NXT_StopProgram(handle);

See also
NXT_StartProgram, NXT_GetCurrentProgramName,

Signature

Author: Alexander Behrens, Linus Atorf (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

166
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_StopProgram.html (2 of 2)7/6/2010 8:38:49 AM

NXT_StopSoundPlayback

NXT_StopSoundPlayback
Stops the current sound playback

Contents

Syntax
Description
Examples
See also
Signature

Syntax
NXT_StopSoundPlayback()
NXT_StopSoundPlayback(handle)

Description
NXT_StopSoundPlayback() stops the current sound playback.
NXT_StopSoundPlayback(handle) sends the stop sound playback command over
the specific Bluetooth handle (serial handle (PC) / file handle (Linux)).
If no NXT handle is specified the default one (COM_GetDefaultNXT) is used.
For more details see the official LEGO Mindstorms communication protocol.

Examples
NXT_StopSoundPlayback();

handle = COM_OpenNXT('bluetooth.ini');
NXT_StopSoundPlayback(handle);
167
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_StopSoundPlayback.html (1 of 2)7/6/2010 8:39:10 AM

NXT_StopSoundPlayback

See also
NXT_PlaySoundFile, NXT_PlayTone, COM_GetDefaultNXT,

Signature

Author: Alexander Behrens (see AUTHORS)


Date: 2008/05/22
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

168
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_StopSoundPlayback.html (2 of 2)7/6/2010 8:39:10 AM

NXT_WriteIOMap

NXT_WriteIOMap
Writes the IO map to the given module ID

Contents

Syntax
Description
Examples
See also
Signature

Syntax
NXT_WriteIOMap(mod_id, offset, n_bytes, data)
NXT_WriteIOMap(mod_id, offset, n_bytes, data, handle)

Description
NXT_WriteIOMap(mod_id, offset, n_bytes, data) write the data bytes to the
given module ID (mod_id). The total number of bytes is given by n_bytes. The
offset parameter determines the index position of the first byte.
NXT_WriteIOMap(mod_id, offset, n_bytes, data, handle) sends the IO map
write command over the specific NXT handle handle (e.g. serial handle (PC) / file
handle (Linux)).
If no NXT handle is specified the default one (COM_GetDefaultNXT) is used.
For more details see the official LEGO Mindstorms communication protocol.

Examples
OutputModuleID = 131073
169
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_WriteIOMap.html (1 of 2)7/6/2010 8:39:25 AM

NXT_WriteIOMap

NXT_WriteIOMap(OutputModuleID, 0, 30, bytes;

handle = COM_OpenNXT('bluetooth.ini');
OutputModuleID = 131073
NXT_WriteIOMap(OutputModuleID, 0, 30, bytes, handle);

See also
NXT_ReadIOMap, COM_GetDefaultNXT,

Signature

Author: Alexander Behrens (see AUTHORS)


Date: 2008/05/22
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

170
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXT_WriteIOMap.html (2 of 2)7/6/2010 8:39:25 AM

MAP_GetCommModule

MAP_GetCommModule
Reads the IO map of the communication module

Contents

Syntax
Description
Examples
See also
Signature

Syntax
map = MAP_GetCommModule()

Description
map = MAP_GetCommModule() returns the IO map of the communication module.
The return value map is a struct variable. It contains all communication module
information.
Output:
map.PFunc % ?
map.PFuncTwo % ?
map.BTPort % 1x4 cell array contains Bluetooth device information of each NXT
Bluetooth port (i = 0..3)
map.BTPort{i}.BtDeviceTableName % name of the Bluetooth device
map.BTPort{i}.BtDeviceTableClassOfDevice % class of the Bluetooth device
map.BTPort{i}.BtDeviceTableBdAddr % MAC address of the Bluetooth device
171
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_GetCommModule.html (1 of 3)7/6/2010 8:39:42 AM

MAP_GetCommModule

map.BTPort{i}.BtDeviceTableDeviceStatus % status of the Bluetooth device


map.BTPort{i}.BtConnectTableName % name of the connected Bluetooth device
map.BTPort{i}.BtConnectTableClassOfDevice % class of the connected
Bluetooth device
map.BTPort{i}.BtConnectTablePinCode % pin code of the connected Bluetooth
device
map.BTPort{i}.BtConnetTableBdAddr % MAC address of the connected
Bluetooth device
map.BTPort{i}.BtConnectTableHandleNr % handle nr of the connected
Bluetooth device
map.BTPort{i}.BtConnectTableStreamStatus % stream status of the connected
Bluetooth device
map.BTPort{i}.BtConnectTableLinkQuality % link quality of the connected
Bluetooth device
map.BrickDataName % name of the NXT brick
map.BrickDataBluecoreVersion % Bluecore version number
map.BrickDataBdAddr % MAC address of the NXT brick
map.BrickDataBtStateStatus % Bluetooth state status
map.BrickDataBtHwStatus % NXT hardware status
map.BrickDataTimeOutValue % time out value
map.BtDeviceCnt % number of devices defined within the Bluetooth device table
map.BtDeviceNameCnt % number of devices defined within the Bluetooth device
table (usually equal to BtDeviceCnt)
map.HsFlags % High Speed flags

172

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_GetCommModule.html (2 of 3)7/6/2010 8:39:42 AM

MAP_GetCommModule

map.HsSpeed % High Speed speed


map.HsState % High Speed state
map.HsSpeed % High Speed speed
map.UsbState % USB state

Examples
map = MAP_GetCommModule();

See also
NXT_ReadIOMap,

Signature

Author: Alexander Behrens (see AUTHORS)


Date: 2008/05/23
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

173
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_GetCommModule.html (3 of 3)7/6/2010 8:39:42 AM

MAP_GetInputModule

MAP_GetInputModule
Reads the IO map of the input module

Contents

Syntax
Description
Examples
See also
Signature

Syntax
map = MAP_GetInputModule(port)

Description
map = MAP_GetInputModule(port) returns the IO map of the input module at the
given sensor port. The sensor port can be addressed by SENSOR_1, SENSOR_2,
SENSOR_3, SENSOR_4 and 'all'. The return value map is a struct variable or cell
array ('all' mode). It contains all input module information.
Output:
map.CustomZeroOffset % custom sensor zero offset value of a sensor.
map.ADRaw % raw 10-bit value last read from the ananlog to digital converter.
Raw values produced by sensors typically cover some subset of the full 10-bit
range.
map.SensorRaw % raw sensor value
map.SensorValue % tacho/angle limit, 0 means none set
map.SensorType % sensor value
174
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_GetInputModule.html (1 of 2)7/6/2010 8:39:49 AM

MAP_GetInputModule

map.SensorMode % sensor mode


map.SensorBoolean % boolean sensor value
map.DigiPinsDir % digital pins direction value of a sensor
map.DigiPinsIn % digital pins status value of a sensor ?
map.DigiPinsOut % digital pins output level value of a sensor
map.CustomPctFullScale % custom sensor percent full scale value of the sensor.
map.CustomActiveStatus % custom sensor active status value of the sensor
map.InvalidData % value of the InvalidData flag of the sensor

Examples
map = MAP_GetInputModule(SENSOR_2);

map = MAP_GetInputModule('all');

See also
NXT_ReadIOMap,

Signature

Author: Alexander Behrens (see AUTHORS)


Date: 2008/05/23
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

175
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_GetInputModule.html (2 of 2)7/6/2010 8:39:49 AM

MAP_GetOutputModule

MAP_GetOutputModule
Reads the IO map of the output module

Contents

Syntax
Description
Examples
See also
Signature

Syntax
map = MAP_GetOutputModule(motor)

Description
map = MAP_GetOutputModule(motor) returns the IO map of the output module at
the given motor port. The motor port can be addressed by MOTOR_A, MOTOR_B,
MOTOR_C and 'all'. The return value map is a struct variable or cell array ('all'
mode). It contains all output module information.
Output:
map.TachoCount % internal, non-resettable rotation-counter (in degrees)
map.BlockTachoCount % block tacho counter, current motor position, resettable
using, ResetMotorAngle (NXT-G counter since block start)
map.RotationCount % rotation tacho counter, current motor position (NXT-G
counter since program start)
map.TachoLimit % tacho/angle limit, 0 means none set
map.MotorRPM % current pulse width modulation ?
176
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_GetOutputModule.html (1 of 3)7/6/2010 8:39:56 AM

MAP_GetOutputModule

map.Flags % should be always ''. Flags are considered in MAP_SetOutputModule.


map.Mode % output mode bitfield 1: MOTORON, 2: BRAKE, 4: REGULATED
map.ModeName % output mode name interpreted by output mode bitfield
map.Speed % motor power/speed
map.ActualSpeed % current actual percentage of full power (regulation mode)
map.RegPParameter % proportional term of the internal PID control algorithm
map.RegIParameter % integral term of the internal PID control algorithm
map.RegDParameter % derivate term of the internal PID control algorithm
map.RunStateByte % run state byte
map.RunStateName % run state name interpreted by run state byte
map.RegModeByte % regulation mode byte
map.RegModeName % regulation mode name interpreted by regulation mode byte
map.Overloaded % overloaded flag (true: speed regulation is unable to
onvercome physical load on the motor)
map.SyncTurnParam % current turn ratio, 1: 25%, 2:50%, 3:75%, 4:100% of full
volume

Examples
map = MAP_GetOutputModule(MOTOR_A);

map = MAP_GetOutputModule('all');

See also

177

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_GetOutputModule.html (2 of 3)7/6/2010 8:39:56 AM

MAP_GetOutputModule

NXT_ReadIOMap,

Signature

Author: Alexander Behrens (see AUTHORS)


Date: 2008/05/22
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

178
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_GetOutputModule.html (3 of 3)7/6/2010 8:39:56 AM

MAP_GetSoundModule

MAP_GetSoundModule
Reads the IO map of the sound module

Contents

Syntax
Description
Examples
See also
Signature

Syntax
map = MAP_GetSoundModule()

Description
map = MAP_GetSoundModule() returns the IO map of the sound module. The
return value map is a struct variable. It contains all sound module information.
Output:
map.Frequency % frequency of the last played ton in Hz
map.Duration % duration of the last played ton in ms
map.SamplingRate % current sound sample rate
map.SoundFileName % sound file name of the last played sound file
map.Flags % sound module flag, 'IDLE': sound module is idle, 'UPDATE': a
request for plackback is pending, 'RUNNING': playback in progress.
map.State % sound module state, 'IDLE'; sound module is idel, 'PLAYING_FILE':
sound module is playing a .rso file, 'PLAYING_TONE': a tone is playing, 'STOP': a
request to stop playback is in progress.
179

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_GetSoundModule.html (1 of 2)7/6/2010 8:40:04 AM

MAP_GetSoundModule

map.Mode % sound module mode, 'ONCE': only play file once , 'LOOP': play file in
a loop, 'TONE': play tone.
map.Volume % volume: 0: diabled, 1: 25%, 2:50%, 3:75%, 4:100% of full volume

Examples
map = MAP_GetSoundModule();

See also
NXT_ReadIOMap,

Signature

Author: Alexander Behrens (see AUTHORS)


Date: 2008/05/22
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

180
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_GetSoundModule.html (2 of 2)7/6/2010 8:40:04 AM

MAP_GetUIModule

MAP_GetUIModule
Reads the IO map of the user interface module

Contents

Syntax
Description
Examples
See also
Signature

Syntax
map = MAP_GetUIModule()

Description
map = MAP_GetUIModule() returns the IO map of the user interface module. The
return value map is a struct variable. It contains all user interface module
information.
Output:
map.PMenu % ?
map.BatteryVoltage % battery voltage in mili volt.
map.LMSfilename % ?
map.Flags % flag bitfield
map.State % state value
map.Button % button value
map.RunState % VM run state

181

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_GetUIModule.html (1 of 3)7/6/2010 8:40:13 AM

MAP_GetUIModule

map.BatteryState % battery level (0..4)


map.BluetoothState % bluetooth state bitfield
map.UsbState % USB state
map.SleepTimout % sleep timeout value in minutes
map.SleepTimer % current sleep timer in minutes
map.Rechargeable % true if reachargeable battery is used
map.Volume % volume level (0..4)
map.Error % error value
map.OBPPointer % on brick program pointer
map.ForceOff % turn off brick if value is true

Examples
map = MAP_GetUIModule();

See also
NXT_ReadIOMap,

Signature

Author: Alexander Behrens (see AUTHORS)


Date: 2008/05/23
Copyright: 2007- 2008, RWTH Aachen University
Published with wg_publish; V1.0

182
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_GetUIModule.html (2 of 3)7/6/2010 8:40:13 AM

MAP_GetUIModule

183
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_GetUIModule.html (3 of 3)7/6/2010 8:40:13 AM

MAP_SetOutputModule

MAP_SetOutputModule
Writes the IO map to the output module

Contents

Syntax
Description
Examples
See also
Signature

Syntax
MAP_SetOutputModule(motor, map)
MAP_SetOutputModule(motor, map, varargin)

Description
map = MAP_SetOutputModule(motor, map) writes the IO map to the output
module at the given motor motor. The motor port can be addressed by MOTOR_A,
MOTOR_B, MOTOR_C. The map structure has to provide all output module
information, listed below.
Input:
map.TachoCount % internal, non-resettable rotation-counter (in degrees)
map.BlockTachoCount % block tacho counter, current motor position, resettable
using, ResetMotorAngle (NXT-G counter since block start)
map.RotationCount % rotation tacho counter, current motor position (NXT-G
counter since program start)
map.TachoLimit % current set tacho/angle limit, 0 means none set
184
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_SetOutputModule.html (1 of 3)7/6/2010 8:40:19 AM

MAP_SetOutputModule

map.MotorRPM % current pulse width modulation ?


map.Flags % update flag bitfield, commits any changing (see also varargin)
map.Mode % output mode bitfield 1: MOTORON, 2: BRAKE, 4: REGULATED
map.Speed % current motor power/speed
map.ActualSpeed % current actual percentage of full power (regulation mode)
map.RegPParameter % proportional term of the internal PID control algorithm
map.RegIParameter % integral term of the internal PID control algorithm
map.RegDParameter % derivate term of the internal PID control algorithm
map.RunStateByte % run state byte
map.RegModeByte % regulation mode byte
map.Overloaded % overloaded flag (true: speed regulation is unable to
onvercome physical load on the motor)
map.SyncTurnParam % current turn ratio, 1: 25%, 2:50%, 3:75%, 4:100% of full
volume
map = MAP_SetOutputModule(motor, map, varargin) sets the update flags explicit
by the given arguments. 'UpdateMode': commits changes to the mode property
'UpdateSpeed': commits changes to the speed property 'UpdateTachoLimit':
commits changes to the tacho limit property 'ResetCounter': resets internal
movement counters, cancels current goal, and resets internal error-correction
system 'UpdatePID': commits changes to PID regulation parameters
'ResetBlockTachoCount': resets block tacho count (block-relative position counter
(NXT-G)) 'ResetRotationCount': resets rotation count (program-relative position
counter (NXT-G))

Examples
MAP_SetOutputModule(MOTOR_A, map);
185
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_SetOutputModule.html (2 of 3)7/6/2010 8:40:19 AM

MAP_SetOutputModule

map = MAP_GetOutputModule(MOTOR_A);
map.RegPParameter = 20;
MAP_SetOutputModule(MOTOR_A, map, 'UpdatePID');

See also
MAP_GetOutputModule, NXT_WriteIOMap,

Signature

Author: Alexander Behrens (see AUTHORS)


Date: 2008/05/22
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

186
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/MAP_SetOutputModule.html (3 of 3)7/6/2010 8:40:19 AM

checkStatusByte

checkStatusByte
Interpretes the status byte of a return package, returns error message

Contents

Syntax
Description
Example
See also
Signature

Syntax
[flag err_message] = checkStatusByte(response)

Description
[flag err_message] = checkStatusByte(response) interpretes the response
byte (not hexadecimal). The return value flag indicates wether an error has
occured (true = error, false = success). The string value err_message contains
the error message (or '' in case of success).

Example
[status SleepTimeLimit] = NXT_SendKeepAlive('reply');
[err errmsg] = checkStatusByte(status);

See also
COM_CollectPacket, NXT_LSGetStatus,

Signature

Author: Linus Atorf (see AUTHORS)

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/checkStatusByte.html (1 of 2)7/6/2010 8:40:26 AM

187

checkStatusByte

Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

188
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/checkStatusByte.html (2 of 2)7/6/2010 8:40:26 AM

OptimizeToolboxPerformance

OptimizeToolboxPerformance
Copies binary versions of typecastc to toolbox for better performance

Contents

Syntax
Description
Example
See also
Signature

Syntax
OptimizeToolboxPerformance

Description
This script automates toolbox optimization. The private functions wordbytes2dec
and dec2wordbytes are very frequently called and thus most critical for
performance (mostly, but not only CPU load), especially at high packet rates
(USB). Profiling shows the bottleneck: typecast. When using the binary version
from the MATLAB directory, speed-ups up to 300% can be experienced. However
this binary version is in a private directory, so cannot be called directly. Also it
depends on the OS, CPU architecture and MATLAB version used. So, the only
solution: We copy those binary files to our own toolboxes private directory.
The script asks the user for permission and performs the file actions automatically.
After each step the results will be checked to avoid a corrupt toolbox.
During the process, the m-files for the above named functions will be overwritten.
This is the reason we provide 2 versions in the private dir, .m.slow (the original
with typecast) and .m.fast (optimized version that needs binary typecastc files in
the same directory).

Example
189
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/OptimizeToolboxPerformance.html (1 of 2)7/6/2010 8:40:33 AM

OptimizeToolboxPerformance

OptimizeToolboxPerformance
Published with wg_publish; V1.0

190
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/OptimizeToolboxPerformance.html (2 of 2)7/6/2010 8:40:33 AM

readFromIniFile

readFromIniFile
Reads parameters from a configuration file (usually *.ini)

Contents

Syntax
Description
Examples:
See also
Signature

Syntax
ret = readFromIniFile(AppName, KeyName, filename)

Description
ret=readFromIniFile(AppName, KeyName, filename)
This function works like GetPrivateProfileString() from the Windows-API that is
well known for reading ini-file data. The parameters are:
AppName = Section name of the type [xxxx] KeyName = Key name separated by
an equal to sign, of the type abc = 123 filename = ini file name to be used
ret = string (!) value of the key found, empty ('') if key was not found. Since it's a
string, you have to convert to integers / floats on your own.
Note that AppName and KeyName are NOT case sensitive, and that whitespace
between '=' and the value will be ignored (removed).
If the key or the AppName is not found, or if the inifile does not exist or could not
be opened, '' will be returned (this will also be returned when the key is empty).

Examples:
191
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/readFromIniFile.html (1 of 2)7/6/2010 8:40:38 AM

readFromIniFile

%a sample ini file (sample.ini) may have entries:


%
%
[XYZ]
%
abc=123
%
def=7
%
; lines starting with a ; are comments
%
[ZZZ]
%
abc=890

readFromIniFile('XYZ','abc', 'sample.ini') % will return '123'

readFromIniFile('ZZZ','abc', 'sample.ini') % will return '890'

readFromIniFile('XYZ','def', 'sample.ini') % will return '7'


Published with wg_publish; V1.0

192
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/readFromIniFile.html (2 of 2)7/6/2010 8:40:38 AM

textOut

textOut
Wrapper for fprintf() which can optionally write screen output to a logfile

Contents

Syntax
Description
Examples
See also
Signature

Syntax
textOut(strMsg)
textOut(strMsg, 'screenonly')
textOut(strMsg, 'logonly')

Description
textOut(strMsg) will write to screen (command window) AND logfile, if global
logging is enabled.
textOut(strMsg, 'screenonly') writes to screen (command window) only.
textOut(strMsg, 'logonly') writes to logfile only (global logging must be
enabled). If logging is disabled or somehow failes, the message will not be logged
or displayed at all...
Note:
To enable logging (to file), set the global var EnableLogging to true and set
Logfilename to a valid filename. This function distinguishes between Windows
and Linux systems to use proper linebreaks. The global variable
DisableScreenOut is an on/off switch for the complete textOut()-messages that
193
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/textOut.html (1 of 3)7/6/2010 8:40:47 AM

textOut

would appear on the command window. Default setting is false, i.e. there will be
no output.
Recommended usage is together with sprintf(), in order to add linebreaks for
example.

Examples
textOut('This is a message\n');

x = 'world';
y = 2007;
textOut(sprintf('Hello %s, it is the year %d!\n', x, y));
%Results in: >> Hello world, it is the year 2007!

global EnableLogging
global Logfilename
EnableLogging = true;
Logfilename = 'logfile.txt';
textOut(sprintf('Whatever I say here will be logged to the file
as well.\n'));

textOut(sprintf('Only appears in the command window\n'),


'screenonly');

textOut(sprintf('Only appears in the logfile, if logging enabled


\n'), 'logonly');

global DisableScreenOut
DisableScreenOut = true;
textOut(sprintf(['If logging is enabled, this goes to the
logfile, ', ...
'if not, this goes nowhere\n']));
194
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/textOut.html (2 of 3)7/6/2010 8:40:47 AM

textOut

See also
DebugMode, isdebug (private),

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2007/10/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

195
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/textOut.html (3 of 3)7/6/2010 8:40:47 AM

DebugMode

DebugMode
Gets or sets debug state (i.e. if textOut prints messages to the command window)

Contents

Syntax
Description
Example
See also
Signature

Syntax
state = DebugMode();
DebugMode(state);

Description
The function textOut can be used to display text messages inside the command
window. These messages can optionally be logged to a file (see textOut for
details) or the output can be disable. To turn off those debug messages, the global
variable DisableScreenOut had to be modified in earlier toolbox versions. Now
the function DebugMode provides easier access.
state = DebugMode(); returns the current debug state, the return value is either
'on' or 'off'.
DebugMode(state); is used to switch between displaying messages and silent
mode. The paramter state has to be 'on' or 'off'.
Note: If you need a fast alternative to strcmpi(DebugMode(), 'on'), please
consider the private toolbox function isdebug.

Example
196
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/DebugMode.html (1 of 2)7/6/2010 8:40:53 AM

DebugMode

% enable debug messages


DebugMode on

% remember old setting


oldState = DebugMode();
DebugMode('on');
% do something with textOut(), it will be displayed!
% restore previous setting
DebugMode(oldState);

See also
textOut, isdebug (private),

Signature

Author: Linus Atorf (see AUTHORS)


Date: 2008/07/04
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

197
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/DebugMode.html (2 of 2)7/6/2010 8:40:53 AM

NXC_GetSensorMotorData

NXC_GetSensorMotorData
Retrieves selected data from all analog sensors and all motors in a single
packet,

Contents

Syntax
Description
Limitations
Example
See also
Signature

Syntax
[sensorData motorData] = NXC_GetSensorMotorData(handle)

Description
This function uses the embedded NXC program MotorControl to retrieve certain
data from all analog sensors and all motors connected to the NXT. The sensors
must already be opened. The function does no interprete any data for you. The big
advantage of this function is that it retrieves all the data within one single
Bluetooth / USB packet, which is faster than retrieving all information one by one
after each other...

Limitations
This function is not yet implemented and does not return any data!

Example
See also
Signature

198

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXC_GetSensorMotorData.html (1 of 2)7/6/2010 8:40:59 AM

NXC_GetSensorMotorData

Author: Linus Atorf (see AUTHORS)


Date: 2009/07/15
Copyright: 2007-2009, RWTH Aachen University
Published with wg_publish; V1.0

199
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/help/NXC_GetSensorMotorData.html (2 of 2)7/6/2010 8:40:59 AM

Functions - Alphabetical List

RWTH - Mindstorms NXT Toolbox

Functions - Alphabetical List


COM_CloseNXT
COM_CollectPacket
COM_CreatePacket
COM_GetDefaultNXT
COM_MakeBTConfigFile
COM_OpenNXT
COM_OpenNXTEx
COM_ReadI2C
COM_SendPacket
COM_SetDefaultNXT
CalibrateColor
CalibrateCompass
CalibrateGyro
CloseSensor
DebugMode
DirectMotorCommand

Closes and deletes a specific NXT handle, or


clears all existing handles
Reads data from a USB or serial/Bluetooth
port, retrieves exactly one packet
Generates a valid Bluetooth packet ready for
transmission (i.e. sets length)
Returns the global default NXT handle if it was
previously set
Creates a Bluetooth configuration file (needed
for Bluetooth connections)
Opens USB or Bluetooth connection to NXT
device and returns a handle
Opens USB or Bluetooth connection to NXT;
advanced version, more options
Requests and reads sensor data via I2C from a
correctly configured digital sensor.
Sends a communication protocol packet (bytearray) via a USB or Bluetooth
Sets global default NXT handle (will be used by
other functions as default)
Enables calibration mode of the HiTechnic color
sensor
Enables calibration mode of the HiTechnic
compass sensor
Calibrates the HiTechnic Gyro sensor
(measures/sets an offset while in rest)
Closes a sensor port (e.g. turns off active light
of the light sensor)
Gets or sets debug state (i.e. if textOut prints
messages to the command window)
Sends a direct command to the specified motor
200

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/abc.html (1 of 5)7/6/2010 8:42:27 AM

Functions - Alphabetical List

GetAccelerator
GetColor
GetCompass
GetGyro
GetInfrared
GetLight
GetRFID
GetSound
GetSwitch
GetUltrasonic
MAP_GetCommModule

Reads the current value of the HiTechnic


acceleration sensor
Reads the current value of the HiTechnic Color
sensor
Reads the current value of the HiTechnic
compass sensor
Reads the current value of the HiTechnic Gyro
sensor
Reads the current value of the Hitechnic
infrared sensor (infrared seeker)
Reads the current value of the NXT light sensor
Reads the transponder ID detected by the
Codatex RFID sensor
Reads the current value of the NXT sound
sensor
Reads the current value of the NXT switch /
touch sensor
Reads the current value of the NXT ultrasonic
sensor
Reads the IO map of the communication
module

MAP_GetInputModule

Reads the IO map of the input module

MAP_GetOutputModule

Reads the IO map of the output module

MAP_GetSoundModule

Reads the IO map of the sound module

MAP_GetUIModule

Reads the IO map of the user interface module

MAP_SetOutputModule

Writes the IO map to the output module

MOTOR_A

Symbolic constant MOTOR_A (returns 0)

MOTOR_B

Symbolic constant MOTOR_B (returns 1)

MOTOR_C

Symbolic constant MOTOR_C (returns 2)

NXC_GetSensorMotorData
NXC_MotorControl
NXC_ResetErrorCorrection
NXTMotor

Retrieves selected data from all analog sensors


and all motors in a single packet
Sends advanced motor-command to the NXCprogram MotorControl on the NXT brick
Sends reset error correction command to the
NXC-program MotorControl on the NXT
Constructs an NXTMotor object
201

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/abc.html (2 of 5)7/6/2010 8:42:27 AM

Functions - Alphabetical List

NXT_GetBatteryLevel
NXT_GetCurrentProgramName
NXT_GetFirmwareVersion
NXT_GetInputValues
NXT_GetOutputState
NXT_LSGetStatus
NXT_LSRead
NXT_LSWrite
NXT_MessageRead
NXT_MessageWrite

Returns the current battery level in milli volts


Returns the name of the current running
program
Returns the protocol and firmware version of
the NXT
Executes a complete sensor reading (requests
and retrieves input values)
Requests and retrieves an output motor state
reading
Gets the number of available bytes for digital
low speed sensors (I2C)
Reads data from a digital low speed sensor
port (I2C)
Writes given data to a digital low speed sensor
port (I2C)
Retrieves a "NXT-to-NXT message" from the
specified inbox
Writes a "NXT-to-NXT message" to the NXT's
incoming BT mailbox queue

NXT_PlaySoundFile

Plays the given sound file on the NXT Brick

NXT_PlayTone

Plays a tone with the given frequency and


duration

NXT_ReadIOMap

Reads the IO map of the given module ID

NXT_ResetInputScaledValue
NXT_ResetMotorPosition
NXT_SendKeepAlive
NXT_SetBrickName
NXT_SetInputMode
NXT_SetOutputState
NXT_StartProgram

Resets the sensor's ScaledVal back to 0


(depends on current sensor mode)
Resets NXT internal counter for specified
motor, relative or absolute counter
Sends a KeepAlive packet. Optional: requests
sleep time limit.
Sets a new name for the NXT Brick (connected
to the specified handle)
Sets a sensor mode, configures and initializes
a sensor to be read out
Sends previously specified settings to current
active motor.
Starts the given program on the NXT Brick
202

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/abc.html (3 of 5)7/6/2010 8:42:27 AM

Functions - Alphabetical List

NXT_StopProgram

Stops the currently running program on the


NXT Brick

NXT_StopSoundPlayback

Stops the current sound playback

NXT_WriteIOMap

Writes the IO map to the given module ID

Initializes the HiTechnic acceleration sensor,


sets correct sensor mode
Initializes the HiTechnic color sensor, sets
OpenColor
correct sensor mode
Initializes the HiTechnic magnetic compass
OpenCompass
sensor, sets correct sensor mode
Initializes the HiTechnic Gyroscopic sensor,
OpenGyro
sets correct sensor mode
Initializes the HiTechnic infrared seeker sensor,
OpenInfrared
sets correct sensor mode
Initializes the NXT light sensor, sets correct
OpenLight
sensor mode
Initializes the Codatex RFID sensor, sets
OpenRFID
correct sensor mode
Initializes the NXT sound sensor, sets correct
OpenSound
sensor mode
Initializes the NXT touch sensor, sets correct
OpenSwitch
sensor mode
Initializes the NXT ultrasonic sensor, sets
OpenUltrasonic
correct sensor mode
Copies binary versions of typecastc to toolbox
OptimizeToolboxPerformance
for better performance
Reads current state of specified motor(s) from
ReadFromNXT
NXT brick
Resets the position counter of the given motor
ResetPosition
(s).
SENSOR_1
Symbolic constant SENSOR_1 (returns 0)
OpenAccelerator

SENSOR_2

Symbolic constant SENSOR_2 (returns 1)

SENSOR_3

Symbolic constant SENSOR_3 (returns 2)

SENSOR_4

Symbolic constant SENSOR_4 (returns 3)

SendToNXT

Send motor settings to the NXT brick

Stop

Stops or brakes specified motor(s)


203

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/abc.html (4 of 5)7/6/2010 8:42:27 AM

Functions - Alphabetical List

StopMotor
SwitchLamp
USGetSnapshotResults
USMakeSnapshot
WaitFor
checkStatusByte
readFromIniFile
textOut

Stops / brakes specified motor.


(Synchronisation will be lost after this)
Switches the LEGO lamp on or off (has to be
connected to a motor port)
Retrieves up to eight echos (distances) stored
inside the US sensor
Causes the ultrasonic sensor to send one
snapshot ("ping") and record the echos
Wait for motor(s) to stop (busy waiting)
Interpretes the status byte of a return
package, returns error message
Reads parameters from a configuration file
(usually *.ini)
Wrapper for fprintf() which can optionally write
screen output to a logfile

204
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/abc.html (5 of 5)7/6/2010 8:42:27 AM

Preparing the workspace

Preparing the workspace


Before you develop a new robot control application you should make sure that all
NXT handles, global variables and settings are resetted and the old figures are
closed. To make sure you are working with a clean workspace use:
COM_CloseNXT('all')
close all
clear all
at the beginning of your main robot application. The important thing here is that
clear all comes after COM_CloseNXT, otherwise it won't work.
If you also want a clean command window (which helps cleaning previous error
messages when tracking bugs), you can optionally use
clc % clear old messages from command line
This leavey your command history fully untouched by the way. Now you should
have a clean environment for your program.
Proceed to next chapter.
Published with MATLAB 7.9

205
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/prepare.html7/6/2010 8:42:46 AM

PC - NXT Communication

PC - NXT Communication
The first thing (after preparing the workspace) in every MATLAB program
controlling an NXT is actually connecting to it. There are several functions which
do the work for you. To identify an NXT device, we use things called handles. For
you (the user) it just looks like a normal variable (actually a struct with a lot of
data on it). Once you connect to an NXT brick, you get a handle for the
connection. Whenever you want to talk to this specific brick, you can do so by
passing the according handle to the function. It's also possible to specify a default
handle, so that you don't have to worry about handles at all after the first line.

Contents

Introduction
Quick start
Easy Bluetooth
Using multiple NXTs
Understanding Bluetooth connections
Sending and receiving data

Introduction
All examples here assume you correctly setup MATLAB, the toolbox, and installed
the correct drivers (Fantom or libusb, depending on your OS) as documented in
the installation guide.
As mentioned in the previous chapter "Preparing the workspace", you always have
to create a clean environment for your program. So never forget to call
COM_CloseNXT all
at the beginning of each program (followed by close all and clear all if you
like), it really makes things easier. But enough about closing handles, how do we
open them? There are two functions:

COM_OpenNXT - this is the easiest and most convenient way and will be all
you need most of the time.
206

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/pc_nxt_communication.html (1 of 8)7/6/2010 8:43:00 AM

PC - NXT Communication

COM_OpenNXTEx - this advanced version gives you more control and takes
more parameters. You can specify which NXT you exactly want to connect
you. You'll usually need this for multi-NXT applications.

Quick start
We first focus on USB connections. This is the easiest and fastest way to connect
an NXT to a computer.
hNXT = COM_OpenNXT(); % look for USB devices
NXT_PlayTone(440, 500, hNXT);
That's it! The variable / struct hNXT is the handle describing the device we talked
about. In the mini example above, a tone is played right after connecting. That is
why we pass hNXT as last argument to NXT_PlayTone(), otherwise PlayTone
wouldn't know which NXT to use.
The best way to go with normal NXT programs is to set the default NXT device. By
doing so you can stop passing the NXT handle to every function later on. This is
the recommended procedure for most single-NXT programs:
COM_CloseNXT all
hNXT = COM_OpenNXT();
COM_SetDefaultNXT(hNXT);

% look for USB devices


% sets global default handle

% now we don't have to use hNXT anymore!


NXT_PlayTone(440, 500);
pause(0.5);
NXT_PlayTone(440, 500);
% but never forget to clean up after your work!!!
COM_CloseNXT(hNXT);
As you can see, we also have to clean up at the end of a program and close all
handles we opened. If your program crashes and the end with the clean up is
never reached, well: that's bad luck. That is why we have the COM_CloseNXT all
at the beginning of each program to absolutely make sure all handles are closed.
Still: Better be safe than sorry. Forgetting to close handles can lead to memory
leaks or MATLAB crashes.
207

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/pc_nxt_communication.html (2 of 8)7/6/2010 8:43:00 AM

PC - NXT Communication

One thing left to note: COM_CloseNXT() will always take the first NXT device on
the USB bus it finds. That is why it's not really useful for multi-NXT applications.

Easy Bluetooth
We've covered USB connections now. If we want to connect wireless to our NXT,
we need a Bluetooth configuration file first. The command COM_MakeBTConfigFile
helps, see documentation there or the section "Understanding Bluetooth
connections" below in this article. The most important thing of your bluetooth.ini
file is that the virtual serial port (COM-Port on Windows) matches the one your
Bluetooth driver creates. But that's about it.
So let's try it!
COM_CloseNXT all
hNXT = COM_OpenNXT('bluetooth.ini');
for Bluetooth
COM_SetDefaultNXT(hNXT);

% look for USB devices, THEN


% set global default handle

NXT_PlayTone(440, 500);
% clean up
COM_CloseNXT(hNXT);
As you can see, the only difference is passing the 'bluetooth.ini' parameter. In
this case, bluetooth.ini has to be a valid BT config file in the current directory or
MATLAB search path of course. Please note that COM_OpenNXT looks for USB
devices first. If it finds one, Bluetooth will totally be ignored! While this may sound
strange at first, it's a very convenient feature: The above program works with
both USB and Bluetooth connections, without changing a single character of the
program. Just plug your NXT in or remove the USB cable to toggle between
wireless and USB functionality.

Using multiple NXTs


When using more than one NXT in your programs, COM_OpenNXT is not so useful.
You should have a look at the documentation of COM_OpenNXTEx instead. There
you can specify whether you explicitely want to look for USB or Bluetooth
connections only. Also you can pass a certain MAC-adress, something like a
208

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/pc_nxt_communication.html (3 of 8)7/6/2010 8:43:00 AM

PC - NXT Communication

unique NXT's serial number. This helps identifying different bricks in your
programs (so that you don't confuse the different devices, and MATLAB always
knows which NXT you mean).
This is enough for starters, if you're interested in more details about Bluetooth
connections and how the toolbox internally works, read on. Otherwise you can skip
to the next chapter.

Understanding Bluetooth connections


To communicate with the NXT via bluetooth, we have to use the SPP (serial port
profile), which basically works like a virtual serial port. This is why we can send
and receive data from within MATLAB through the serial port commands.
To handle different connections or bluetooth adapters on different computers
easily, a certain ini-file with settings for the MATLAB functions must be present in
the current directory (or one that can be found through path settings).
The ini-file format looks like this
[Bluetooth]
SerialPort=COM3
BaudRate=57600
DataBits=8
SendSendPause=10
SendReceivePause=30
TimeOut=2
The serial settings should be self explaining. Explanation of the send-pause-values
will follow later on. The TimeOut parameter only has an effect when using
Windows. It sets the period the bluetooth stack should wait when it is "missing
data". The MATLAB-internal default value of 10 causes annoying freezes in certain
robot programs on certain computers (a direct cause is not yet found). By setting
2 (the toolbox default value), one should get a fairly stable experience with very
rare execution pauses of 2 seconds. Smaller timeout values can lead to real
packet loss which has not been examined yet. More information on this can also
be read in the section "Troubleshooting" of the toolbox help.
209
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/pc_nxt_communication.html (4 of 8)7/6/2010 8:43:00 AM

PC - NXT Communication

To create a bluetooth configuration ini-file, a standard editor can be used. A more


comfortable way is to use the GUI-guided program:
COM_MakeBTConfigFile;
The following functions work under Windows as well as Linux and Mac OS. The
returned structure (referred to as "handle" in the future) contains many
information and function pointers. There is no need to use them. If you do, your
program can easily crash
Now first have a look how to obtain a handle to a bluetooth connection.
% Before we open a handle, we clean up to avoid errors:
COM_CloseNXT('all', 'bluetooth.ini');
% This only closes all open serial ports matching the COM-port from
the
% ini-file. More drastical is to close all open COM-ports and USBhandles like this:
COM_CloseNXT('all');
Now we can open a connection. Make sure the bluetooth dongle is connected to
the NXT brick (using the according software or scripts) before calling this. Using
this syntax, MATLAB will actually look for a USB connection first, and only go on to
connect via Bluetooth if there is no USB device present.
h = COM_OpenNXT('bluetooth.ini');
The function sends a keep-alive-packet and waits for the answer before returning
a valid handle. This is very comfortable as it detects a malfunctioning / closed
bluetooth connection before the execution of other program code.
Set the global default handle, so that later on, whenever we're calling functions,
we don't have to pass the handle every time.
COM_SetDefaultNXT(h);
% This is self-explanatory

210

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/pc_nxt_communication.html (5 of 8)7/6/2010 8:43:00 AM

PC - NXT Communication

handle = COM_GetDefaultNXT;
To close an open connection / handle, just call
COM_CloseNXT(h);
% although this would also do the trick:
COM_CloseNXT('all');

Sending and receiving data


This section is mainly about the way the toolbox sends data to the NXT or how it
retrieves them. There is no need for normal users to read this section. It's only
interesting for developers. We have:

COM_CreatePacket
COM_SendPacket
COM_CollectPacket

These functions are very "low level" and you should usually not use them on your
own, unless you're implementing new NXT functions. All the already implemented
NXT functions make use of these.
First we've got
packet = COM_CreatePacket(CommandType, Command, ReplyMode,
ContentBytes);
where ReplyMode either has to be 'reply' or 'dontreply', specifying wether we want
an answer from the NXT or not. This command essentially creates the binary data
for a packet, taking care of payload size and similar things. For more details see
inside the "Bluetooth Engine Demo" file.
Now it's getting interesting. We've got two functions to send and receive data
respectively. Because the LEGO NXT brick has a 30ms latency when switching
from transmit to receive mode, we can expect a 60ms latency for a whole sensor
reading request.
211
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/pc_nxt_communication.html (6 of 8)7/6/2010 8:43:00 AM

PC - NXT Communication

Very important is that the NXT can apparently lose packets / commands, because
the input buffer (or queue) is of limited size. As we do not know any more details
about this, the send and receive functions have the option to wait between
subsequent send operations (i.e. to be less "aggressive"). This is where the earlier
mentioned settings from the ini file come in:
SendSendPause=10
SendReceivePause=30
In this case we demand a 10ms delay between two consecutive send operations.
On the other hand, a 30ms pause is required between each send and receive
operation (and vice versa receive and send). This should give the NXT enough
time so switch between bluetooth transmission modes without loosing any packets.
Note: The functions are "intelligent" and only pause execution if it is necessary. So
if you only try to send a packet once every second, you will not notice this
automatic delay, as it is not required.
% for this function, we always have to specify a valid serial port
handle
COM_SendPacket(packet, handle);
Receiving packets is as easy. Make sure you have requested one before you try to
collect something.
[type cmd statusbyte content] = COM_CollectPacket(handle);
The statusbyte will be checked automatically by this function, and if it contains an
error message, an according warning will be issued. You can disable the automatic
status byte check by calling COM_CollectPacket(handle, 'dontcheck'). There is
really just one special situation where this is needed: NXT_LSGetStatus (see
documentation and function code). To manually inspect the statusbyte, you can
have a look at the function checkStatusByte.
COM_CollectPacket exactly retrieves one packet from the internal receive buffer.
It does so by checking the length of the packet (first two bytes) and then only
reads the amount of data that belongs to this specific packet. Be very careful
though: If you call it without previously requesting data, there will be nothing to
collect, hence the function will return nothing after a timeout or crash, depending
212
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/pc_nxt_communication.html (7 of 8)7/6/2010 8:43:00 AM

PC - NXT Communication

on your bluetooth adapter. Even worse, under Linux it will block without the
possibility to break until you physically turn off the bluetooth device.
Proceed to next chapter.
Published with MATLAB 7.9

213
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/pc_nxt_communication.html (8 of 8)7/6/2010 8:43:00 AM

Controlling NXT motors

Controlling NXT motors


Being able to control the NXT motors is crucial for most robots. Only very few
models work without moving parts. So read on to learn all you need about the
class NXTMotor.

Contents

Getting ready
The basics
Constructing objects and setting properties
Precise moves
Different braking modes
Speed regulation and smooth start
Using two motors
Driving bots the easy way
Reading motor positions
Full example
Limitations of NXTMotor
For experts: DirectMotorCommand

Getting ready
If you want to execute the examples from this tutorial directly in the command
window, I recommend this little sequence of commands to establish a connection
to your NXT:
COM_CloseNXT all
h = COM_OpenNXT('bluetooth.ini');
COM_SetDefaultNXT(h);
Now all following examples should work right away by copy-pasting...

The basics
To operate the motors, we need to create motor objects, i.e. instances of the class
214

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/motor_control.html (1 of 15)7/6/2010 8:43:10 AM

Controlling NXT motors

NXTMotor. Those objects are capable of sending various commands to one or two
motors, or can be used to retrieve data from them. To create such an object, the
simplest way is just
mA = NXTMotor('A')
Now the object mA provides properties and methods to control the NXT motor on
port A. First, we probably just want to see if the motor works at all. Ok then, let's
go:
mA.Power = 50; % let's start with half the maximum power
mA.SendToNXT(); % this is actually the moment we start the motor
Motor A keeps on running... To stop it, we use
mA.Stop('off');
This will turn off the power, causing the motor to come to a soft stop (so called
"coasting"). If we wanted to brake all of a sudden at once, we'd call
mA.Stop('brake');
In this case, the NXT's active brake will be enabled, causing the motor to stop
hard at the instance it receives the command. The brake alsp keeps the motor
actively at its position. It's surprisingly strong, however it also consumes a lot of
power, so we better turn it off again. The motor is now completely turned off just
as in the beginning of our tutorial session:
mA.Stop('off');

Constructing objects and setting properties


You've already seen the basic concept of motor control which consits of these 3
basic steps:
215
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/motor_control.html (2 of 15)7/6/2010 8:43:10 AM

Controlling NXT motors

1. Create an NXTMotor object


2. Set up the parameters as you need them
3. Send the command to the NXT using SendToMotor()
You've already seen how to specify the motor settings by setting properties.
mB1
= NXTMotor();
mB1.Port = MOTOR_B;
mB1.Power = -100;

% create a blank motor object


% this is the same as using mB.Port = 'B';
% full power backwards

The example above shows two things:


1. You can use the old-fashioned motor constants (i.e. MOTOR_C) to specify port
names, or do it by giving strings (like 'C').
2. To reverse the direction the motor should turn, set negative power values
(as in electronics you'd swap the sign of the current)
A shorter way to create exactly the same object as mB1 is to use NXTMotor's
constructor. The first argument always has to be the port you want to use,
followed by combinations of 'Property', value as you might know from other
MATLAB commands:
mB2 = NXTMotor('B', 'Power', -100, 'SpeedRegulation', false);
As said before: mB1 and mB2 do exactly the same, so use whichever way you
prefer. To inspect motor objects on the command line, just type their name:
mB1
mB2

Precise moves
Knowing how we control the motor's speed by setting a certain value to Power is
not enough in most cases. One could try to move the motor a certain distance by
using something like this:
mA = NXTMotor('A', 'Power', 50);
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/motor_control.html (3 of 15)7/6/2010 8:43:10 AM

216

Controlling NXT motors

mA.SendToNXT();
pause(3);
% wait exactly 3 seconds
mA.Stop('brake');
Using this technique we get the motor running 3 seconds, but due to several
influences (for example Bluetooth lag or subtle differences in NXT motors) this
won't lead to the same distance travelled by the motor. Also we can't manage
different loads on the motors. This is why we have to specify the distance the
motor should turn in degrees. The according property is called TachoLimit.
mA.TachoLimit = 360;
mA.SendToNXT();
Now the motor will make exactly 1 whole turn and then stop at about 360 degrees
(accurate to +/- 1 degree in most cases). It is very important to understand that
the motor does this movement "on its own", while MATLAB can execute the next
command right away. If we say:
mB = NXTMotor('B', 'Power', 50, 'TachoLimit', 1000);
mB.SendToNXT();
NXT_PlayTone(440, 500);
then the NXT will start turning motor B and beep right away! If we want to beep
only when the motor has reached its position, we have be patient and wait for the
motor:
mB.SendToNXT();
mB.WaitFor();
NXT_PlayTone(440, 500);

% this command will hold MATLAB a while


% now the motor has stopped!

This brings us to the next important point: In order for a motor to accept a
command with SendToNXT(), it must be idle, i.e. at rest (and not carrying out
a movement already). We can achieve this by either:

Waiting for the last motor command to finish by using WaitFor() before
calling the next SendToNXT(). If the motor is currently idle, WaitFor() won't
wait at all and continue with the next statement right away.
Abort the current motor movement using the Stop() method.
217

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/motor_control.html (4 of 15)7/6/2010 8:43:10 AM

Controlling NXT motors

If we don't follow this rule, the NXT will ignore the second motor command and
tell you it has just dropped a command by a beeping signal. Example:
% imagine we want our motor to make 2 turns of 360 degrees
mB = NXTMotor('B', 'Power', 50, 'TachoLimit', 360);
mB.Stop('off'); % Just to make sure motor is ready!
mB.SendToNXT(); % Motor is busy now
mB.SendToNXT(); % THIS DOES NOT WORK!!! MOTOR IS BUSY
% This example is wrong.
% We have to use a .WaitFor between the two .SendToNXT()
To switch back to unlimited movement, just set TachoLimit back to 0.

Different braking modes


So setting a value to TachoLimit specifies the angle the motor should spin to, and
by the sign of Power we can decide the turning direction. We still have some more
options to control how the motor should brake. The property is called
ActionAtTachoLimit. Quoting possible parameters from the documentation of
NXTMotor:

In 'Coast' mode, the motor(s) will simply be turned off when the|
TachoLimit| is reached, leading to free movement until slowly stopping
(called coasting). The TachoLimit won't be met, the motor(s) move way too
far (overshooting), depending on their angular momentum.
Use 'Brake' mode (default) to let the motor(s) automatically slow down
nice and smoothly just before the TachoLimit. This leads to a very high
precision, usually the TachoLimit is met within +/- 1 degree (depending on
the motor load and speed of course). After this braking, power to the motor
(s) is turned off when they are at rest.
'Holdbrake' is similar to 'Brake', but in this case the active brake of the
motors stays enabled (careful, this consumes a lot of battery power),
causing the motor(s) to actively keep holding their position.

Speed regulation and smooth start


There are two more options left we'll shortly discuss here. For further details you
should consider the documentation of NXTMotor.
218
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/motor_control.html (5 of 15)7/6/2010 8:43:10 AM

Controlling NXT motors

SpeedRegulation - this property is set to true by default, but you should


carefully evaluate wether you need it or not for every motor object. It
basically tries to keep your motor running at a constant speed, no matter
how much load you put on it. If a motor has heavy lifting to do, the
Firmware will internally increase the power value (if possible) to keep the
motor running fast enough. While this is a nice thing to have, be careful: The
torque of your motor will be dynamically adjusted. Imagine you've got a
robotic arm with a limited area of operation and a sensitive gearing. If you
enable speed regulation and somehow your arm get's stuck (for example by
a programming error of yours) or moves too far, the Firmware will increase
the power value to overcome the obstacle. This behavior could destroy your
gears or the arm. Sometimes it's desirable to have a constant torque. In that
case, better deactivate speed regulation. Another thing to mention: With low
speeds, speed regulation sometimes achieves the opposite of what you
want: the motor keeps cogging or stuttering. In these cases, speed
regulation should also be turned off.
SmoothStart - enable this if you want your motor(s) to accelerate softly.
Desirable especially for driving robots so that their wheels won't slip when
they start driving. The motor will increase its power value in the beginning of
movement stepwise until the full speed is reached. This option does only
work when a TachoLimit > 0 is set. It doesn't work with
ActionAtTachoLimit = 'Coast' either.

Using two motors


Until now we've always talked about motor objects controlling one single motor.
You could create two of these objects to start a driving robot (where the wheels
are attached to ports B and C):
mB = NXTMotor('B', 'Power', 50);
mC = NXTMotor('C', 'Power', 50);
mB.SendToNXT();
mC.SendToNXT();
There are two problems with this simple approach:

The commands are sent one after each other to the NXT, causing motor C to
start a tiny bit after motor B. This will result in your robot making a little
turn in the beginning.
The motors are running at slightly different speeds, since they aren't
219

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/motor_control.html (6 of 15)7/6/2010 8:43:10 AM

Controlling NXT motors

perfectly unique. This causes the bot to drive a curve, rather than a straight
line. The solution: Use a single motor object to control two motors at the
same time. They will be operated in "synchronization mode". This means the
NXT makes sure that they run at both the same speed for your bot to drive a
straight line. This also means that speed regulation does not work when
driving two motors synced. But let's look at an example first:
mBC = NXTMotor('BC', 'Power', 50);
mBC.SendToNXT();
Easy, huh? We can also use the commands WaitFor() or stop as we're used to.
And the property Port can of course be accessed as usual. Another example:
myMotors
= NXTMotor();
myMotors.Port
= [MOTOR_B; MOTOR_C]; % same as myMotors.
Port = 'BC';
myMotors.Power
= 50;
myMotors.TachoLimit = 1000;
myMotors.SmoothStart = true;
myMotors.SpeedRegulation = false; % don't forget this!
% If we tell the constructor that we use two ports, speed
regulation will
% automatically turned off, i.e.:
% m = NXTMotor('BC'); % <-- m.SpeedRegulation = false is set
already!
myMotors.Stop('off');
myMotors.SendToNXT();

% make sure motors are off before we start.

There is one certain behavior you should get familiar with. Let's assume you use
the following code:
mBC = NXTMotor('BC', 'Power', 50, 'TachoLimit', 1000);
mBC.ActionAtTachoLimit = 'Coast';
mBC.SendToNXT();
mBC.WaitFor();
pause(3);
During the final pause of 3 seconds, we can notice a certain high-pitched220
noise
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/motor_control.html (7 of 15)7/6/2010 8:43:10 AM

Controlling NXT motors

coming from the motors. Also they seem to be powered up and slightly moving or
vibrating. This is the motor synchronization in action. If you try to move one
wheel, the other will be moved automatically, too. This ensures the wheels are
(roughly) in the same position, as if they were connected through an axle. We can
manually turn off this synchronization with Stop():
mBC.Stop('off');

Driving bots the easy way


Using the knowledge we now have about NXTMotor, it's time to get used working
with multiple motor objects. In the following example, we set up a basic set of
objects. To
% Set some parameters:
leftWheel
= MOTOR_B;
rightWheel = MOTOR_C;
bothWheels = [leftWheel; rightWheel];
drivingPower = 60;
turningPower = 40;
drivingDist = 1000; % in degrees
turningDist = 220; % in degrees
% now create the objects for straigt driving:
mForward = NXTMotor(bothWheels, 'Power', drivingPower,
'TachoLimit', drivingDist);
mReverse = mForward; % clone object
mReverse.Power = -mForward.Power; % just swap the power sign
Now we can already drive our bot a certain distance forward or reverse. We just
have to send the objects to the NXT and wait until they complete:
% let the bot drive forward
mForward.SendToNXT();
mForward.WaitFor();
% and now return to the origin
mReverse.SendToNXT();
mReverse.WaitFor();
% done!
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/motor_control.html (8 of 15)7/6/2010 8:43:10 AM

221

Controlling NXT motors

NXT_PlayTone(440, 500);
In order to make nice turns (by 90 degrees for example), it's best to use a 2-way
motion: First let one wheel spin one direction (now the bot has made half of its
turn and faces 45 degrees), then turn the other wheel into the opposite direction.
Now the 90-degree-turn should be complete.
% for turning the bot, we have two objects each:
mTurnLeft1 = NXTMotor(leftWheel, 'Power', -turningPower,
'TachoLimit', turningDist);
mTurnLeft1.SpeedRegulation = false; % don't need this for turning
% for the 2nd part of turning, use first
mTurnLeft2 = mTurnLeft1;
mTurnLeft2.Port
= rightWheel;
mTurnLeft2.Power
= -mTurnLeft1.Power;

part's settings and modify:


% copy object
% but use other wheel
% swap power again

% the right-turn objects are the same, but mirrored:


mTurnRight1 = mTurnLeft1;
% first copy...
mTurnRight2 = mTurnLeft2;
mTurnRight1.Power = -mTurnRight1.Power; % now mirror powers
mTurnRight2.Power = -mTurnRight2.Power;
% Instead of mirroring the powers, we could've also changed
% the ports (swapped left and right wheels).
You can now use these objects like this:
% make a left-turn
mTurnLeft1.SendToNXT();
mTurnLeft1.WaitFor();
mTurnLeft2.SendToNXT();
mTurnLeft2.WaitFor();
% wait here a moment
pause(1);
% turn back to the origin
mTurnRight1.SendToNXT();
mTurnRight1.WaitFor();
mTurnRight2.SendToNXT();
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/motor_control.html (9 of 15)7/6/2010 8:43:10 AM

222

Controlling NXT motors

mTurnRight2.WaitFor();

Reading motor positions


Apart from sending commands to the motors, we can also retrieve information
from them, the most important being the current position in degrees. For more
documentation on this, see the help texts for ReadFromNXT and ResetPosition.
These are the commands we'll use in this section.
So, when calling ReadFromNXT() on a motor object, a MATLAB struct is returned,
containing some useful fields. We'll just focus on Position, i.e. where the motor
has currently turned to. This rotation counter keeps on tracking every movement,
wether you turn the motor by hand or by a commend, it always tells you the exact
position of the axle at the time the NXT receives your request. The change of
Position corresponds to the turning direction: If the motor turns the way as it
would if operated with a positive Power, Position increases. Otherwise (spinning
reverse), Position decreases (and can become negative). Enough of the theory, a
simple example:
% We need a motor object to get access to the methods
% also we do a little driving...
m = NXTMotor('A', Power, '50');
% clear position counter:
m.ResetPosition();
m.SendToNXT();
pause(1);
m.Stop('off');
% motor is still coasting at the moment...
% now retrieve motor info
data = m.ReadFromNXT();
% show it to the user:
disp(sprintf('Motor A is currently at position %d', data.Position));
% wait until the motor doesn't move anymore
pause(2);
% and display the position again:
data = m.ReadFromNXT();
disp(sprintf('Motor A is finally at position %d', data.Position));
223
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/motor_control.html (10 of 15)7/6/2010 8:43:10 AM

Controlling NXT motors

Please note that all other properties of the motor object except Port do not matter
to use the method the methods ReadFromNXT() and ResetPosition. Also the
returned data-structure from ReadFromNXT() only reflects the current state of the
NXT motor, and does not necessarily have something to do with the motor object's
properties you used to retrieve the data (e.g. TachoLimit and Power of the
retrieved data and of the object can be different).

Full example
Now let's imagine we want to control a robotic arm. For the sake of this example,
we want it to move up and down, alternatingly for 10 times. Let the arm just have
one joint, so we only control one motor. A little problem is gravity: The arm has a
certain weight. So if we aren't careful, moving it downwards will sometimes result
in a little lower position than we expect, and moving upwards won't move the
motor as far as we hope all the time. After all, the motor control is only accurate
to a couple of degrees (+/- 1 most of the time, but not necessarily equally
distributed). So without reading the motor's position and accounting for those
inaccuracies, the errors would accumulate over time and cause a significant
displacement of the arm. By simply retrieving the arm's position and making sure
that it moves a bit more upwards if necessary, or a bit less downwards, we can
avoid the accumulating errors and have precise movement even after a long
period of operation. Here is how its done:
% Example which should move a motor (or robotic arm) 10 times back
and
% forth (up and down), as precisely as possible without blindly
trusting
% the motor commands. Very simple error compensation (i.e. trying
absolute
% movements instead of always relative).
% Prepare MATLAB
COM_CloseNXT all
close all
clear all
% Connect to NXT, via USB or BT
h = COM_OpenNXT('bluetooth.ini');
COM_SetDefaultNXT(h);
% set params
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/motor_control.html (11 of 15)7/6/2010 8:43:10 AM

224

Controlling NXT motors

power = 30;
port = MOTOR_A;
dist = 200;
% distance to move in degrees
% create motor objects
% we use holdbrake, make sense for robotic arms
mUp
= NXTMotor(port, 'Power', power, 'ActionAtTachoLimit',
'HoldBrake');
mDown = NXTMotor(port, 'Power', -power, 'ActionAtTachoLimit',
'HoldBrake');
% prepare motor
mUp.Stop('off');
mUp.ResetPosition();
% repeat 10 times
for j=1:10
% where are we?
data = mUp.ReadFromNXT();
pos = data.Position;
% where do we want to go?
% account for errors, i.e. if pos is not 0
mDown.TachoLimit = dist + pos;
% move
mDown.SendToNXT();
mDown.WaitFor();
% now we are at the bottom, repeat the game:
% where are we?
data = mUp.ReadFromNXT(); % doesn't matter which object we use
to read!
pos = data.Position;
% pos SHOULD be = dist in an ideal world
% but calculate new "real" distance to move
% based on current error...
mUp.TachoLimit = pos;
% this looks very simple now, but it comes from
%
TachoLimit = dist + (pos - dist);
% i.e. real distance + error correction
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/motor_control.html (12 of 15)7/6/2010 8:43:10 AM

225

Controlling NXT motors

% Imagine it this way: We are currently at pos,


% and want to go back to 0, so this is exactly the distance
% to go!
mUp.SendToNXT();
mUp.WaitFor();
end%for
% mode was HOLDBRAKE, so don't forget this:
mUp.Stop('off')
% clean up
COM_CloseNXT(h);

Limitations of NXTMotor
As nice and easy as working with NXTMotor is, the class has its limitations (you
can read more about it in the documentation of NXTMotor). One minor problem is
that you can't change the speed (i.e. setting a different Power and then call
SendToNXT()) of an already running motor. You have to use WaitFor() or Stop()
before updating the power, which might not do what you want (changing the
speed smoothly during runtime).
Well, there is one exception: If a motor is running infinitely with TachoLimit = 0
set, you actually can send a motor command with a new power, and it will work.
A sometimes bigger problem is latency: Motor commands are not necessarily sent
to the NXT at once. Sometimes SendToNXT() takes roughlpy up to 20ms for the
actual motor instruction to be executed. Same goes for WaitFor() or Stop(). This
is the price you have to pay for the great accuracy that NXTMotor gives you. The
reason has to do with the embedded NXC program MotorControl, which is running
on the NXT and handles high precision motor movement for you.
What to do if you need fast motor control instead of high precision (i.e. when
building a Segway)? Well, you can trade accuracy for performance. The answer is:
Use DirectMotorCommand. The last chapter explains how.

For experts: DirectMotorCommand


DirectMotorCommand is a remainder from previous toolbox versions 1.x and 2.x (it
226
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/motor_control.html (13 of 15)7/6/2010 8:43:10 AM

Controlling NXT motors

was called SendMotorSettings before). It works without a program running the


brick by sending "direct commands" (a term from the LEGO NXT Mindstorms
communication protocol) only. First of all:
Warning: Do not use DirectMotorCommand and NXTMotor.SendToNXT() for the
same motor at one time together (or only if you know exactly what you're doing).
It can mess up your motor control and lead to unexpected results! You can still
use NXTMotor.ReadFromNXT() if you like.
Direct motor command gives access to some advanced features:

Ramp up & ramp down: You can let motors linearly accelerate or decelerate
over a distance of your choice.
TurnRatio: You can run motors synchronized, but with different speeds of
each motor. This feature doesn't work reliable however.

There are however more problems:

Movement is not accurate anymore. Basically you only have something like
ActionAtTachoLimit = 'Coast', but with even less quality.
Sometimes the NXT's error correction does changes to your TachoLimit
which seem hard to understand. Read the section Troubleshooting of this
toolbox documentation for more on that.

The big advantage is execution speed: Nothing else is faster than


DirectMotorCommand or NXT_SetOutputState. Latency via USB connections is
usually about 3ms, and via Bluetooth it can be between 5ms and 30ms, or even
more for synchronized driving.
Make sure to read the documentation page for DirectMotorCommand.
I might help to also read the documents "Executable File and Bytecode
Reference" (LEGO MINDSTORMS NXT Executable File Specification) and "Bluetooth
Developer Kit (BDK)" from http://mindstorms.lego.com/Overview/nxtreme.
aspx ; it may help you getting familiar with the communication protocol. Other
useful commands are NXT_GetOutputState and NXT_SetOutputState.

Proceed to next chapter.


Published with227
MATLAB 7.9
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/motor_control.html (14 of 15)7/6/2010 8:43:10 AM

Controlling NXT motors

228
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/motor_control.html (15 of 15)7/6/2010 8:43:10 AM

High level sensor control

High level sensor control


Using sensors with the RWTH - Mindstorms NXT Toolbox is very simple. That is
why this chapter is relatively short. You can look up sensor-specific parameters in
the according function help:

Contents

List of functions
Retrieving values
Advanced sensor modes

List of functions
Functions for the standard NXT sensors:

OpenSwitch
GetSwitch
OpenSound
GetSound
OpenLight
GetLight

OpenUltrasonic
GetUltrasonic

CloseSensor

More advanced functions and 3rd party external sensor support:

USMakeSnapshot
USGetSnapshotResults
OpenAccelerator
GetAccelerator
229

http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/sensor_control.html (1 of 5)7/6/2010 8:43:18 AM

High level sensor control

OpenInfrared
GetInfrared
OpenColor
CalibrateColor
GetColor
OpenCompass
CalibrateCompass
GetCompass
OpenGyro
CalibrateGyro
GetGyro
OpenRFID
GetRFID

Retrieving values
The functions mentioned above provide an easy and simple way to access all
sensors. The ultrasonic sensor uses a digital interface and has to be handled in a
different way internally, but using these high level functions, you won't see a
difference. The only thing worth mentioning: GetUltrasonic is about 1.5 up to 2
times slower than the other Get* functions (because internally 3 or sometimes 4
packets are needed instead of just 2). Same goes for most external 3rd party
sensors: Except the HiTechnic Gyro sensor, they're all digital.
The Open* functions use NXT_SetInputMode, while Get* calls
NXT_GetInputValues. CloseSensor is necessary to turn off a specific sensor, e.g.
turn off the light sensor's red LED in active mode. This will save power.
You can use raw port numbers starting with 0 just as seen in the official
Mindstorms documentation, or you can use the named constants SENSOR_1 to
SENSOR_4 for better readability. So let's open a few sensors:
OpenSwitch(SENSOR_1);
OpenSound(SENSOR_2, 'DB');
% have to specify mode, DB or DBA
OpenLight(SENSOR_3, 'ACTIVE'); % have to specify mode, ACTIVE or
INACTIVE
OpenUltrasonic(SENSOR_4);
230
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/sensor_control.html (2 of 5)7/6/2010 8:43:18 AM

High level sensor control

Sensors are ready to be used now, very easy:


if GetSwitch(SENSOR_1) % always specify port number!
% the touch sensor is "pressed" now, do something
end%if
if GetSound(SENSOR_2) < 100 % remember, values range from 0 to 1023
% quite silent right now
end%if
if GetLight(SENSOR_3) > 1000
% VERY bright sunshine :-)
end%if
if GetUltrasonic(SENSOR_4) < 30 % unit is cm
% we seem close to a wall
end%if
Clean up when you are done, just as with handles. This saves battery power of
your NXT!
% don't forget :-)
CloseSensor(SENSOR_1);
CloseSensor(SENSOR_2);
CloseSensor(SENSOR_3);
CloseSensor(SENSOR_4);

Advanced sensor modes


Note that it is possible to use NXT_SetInputMode with a custom mode you like
instead of Open*, and the Get-functions will still work (this is not true for the
ultrasonic sensor, but it has totally different modes anyway). Internally they just
return the .NormalizedADVal value. This makes it possible to automatically count
claps and still use the simple functions. Example:
% your old code looks like this
OpenSound(SENSOR_2, 'DB');
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/sensor_control.html (3 of 5)7/6/2010 8:43:18 AM

231

High level sensor control

% do something
while(something)
% note how you continously have to poll the sensor
if GetSound(SENSOR_2) > 700
ClapCount = ClapCount + 1;
end%if
end%while
We now replace OpenSound by this:
NXT_SetInputMode(SENSOR_2, 'SOUND_DB', 'PERIODCOUNTERMODE',
'dontreply');
NXT_ResetInputScaledValue(SENSOR_2); % this is needed if you want
to start with 0
if GetSound(SENSOR_2) > 500 % GetSound still works!
% hey, this is a loud atmosphere...
end%if
% we could do whatever we wanted here:
pause(10) % take a little 10s nap
data = NXT_GetInputValues(SENSOR_2);
ClapCount = data.ScaledVal;
CloseSensor(SENSOR_2);
That was easy. The NXT did the counting for us. For more details about sensor
modes see the LEGO documentation, but in a few words: A
"transition" (TRANSITIONCNTMODE) is whenever the value (.NormalizedADVal)
changes between the 45% threshold (45% of 1023 is 460). As
"period" (PERIODCOUNTERMODE) counts when the value goes down from somewhere
above 45%, and then changes back up. The "count" happens during the raising
part. To see what exactly is happening try the GUI_WatchAnalogSensor tool.
The main point I wanted to make: As you can see, GetSound / GetLight etc. can
peacefully coexist with the NXT_ functions.

232
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/sensor_control.html (4 of 5)7/6/2010 8:43:18 AM

High level sensor control

Proceed to next chapter.


Published with MATLAB 7.9

233
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/sensor_control.html (5 of 5)7/6/2010 8:43:18 AM

Direct NXT commands

Direct NXT commands


In this final chapter we only list some more examples and commands. Usually
they aren't needed in the daily life of a MATLAB Mindstorms NXT programmer.

Contents

Keep alive and battery level


Important direct commands

All functions beginning with NXT_ are basically just ported from the official LEGO
NXT Bluetooth Protocol and Direct Commands documentation (download Bluetooth
Developer Kit from LEGO).
We just list some examples and commands...

Keep alive and battery level


To keep the NXT from turning off automatically, send a keep-alive packet from
time to time (if needed):
NXT_SendKeepAlive('dontreply');
If you're interested in the internal sleep time limit setting, just request it:
[status SleepTimeLimit] = NXT_SendKeepAlive('reply');
% To see after how many minutes the NXT will shut down:
minutes = SleepTimeLimit / 1000 / 60;
So how much energy does my bot have left?
voltage = NXT_GetBatteryLevel;
% actually, the unit is milli volts, so
voltage = voltage / 1000; % :-)
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/direct_commands.html (1 of 5)7/6/2010 8:43:26 AM

234

Direct NXT commands

Every function that retrieves (i.e. "gets") values from the NXT is internally split
into two parts. But this doesn't have to concern you right now. Note how we called
the functions without passing a blutooth handle - we simply set the default handle
at the beginning of our program or session.

Important direct commands


These are the interesting ones. The list is not complete however!

NXT_PlayTone
NXT_SetInputMode
NXT_ResetInputScaledValue
NXT_GetInputValues
NXT_ResetMotorPosition
NXT_SetOutputState
NXT_GetOutputState
NXT_StartProgram, NXT_StopProgram
NXT_LSWrite, NXT_LSGetStatus, NXT_LSRead

This section only covers the syntax, for details what the functions do please
consider the official LEGO documentation or the function help.
% frequency is in Hz, duration in ms
NXT_PlayTone(frequency, duration);

% the common way would be this


NXT_SetInputMode(InputPort, SensorTypeDesc, SensorModeDesc,
'dontreply');
% but if you want an acknowledgement (usually not needed), then use
status = NXT_SetInputMode(InputPort, SensorTypeDesc,
SensorModeDesc, 'reply');
% note: the statusbyte will be automatically checked anyway (and a
warning
% issued if necessary), but you can still check the status now to
handle the
% consequences properly...
235
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/direct_commands.html (2 of 5)7/6/2010 8:43:26 AM

Direct NXT commands

NXT_ResetInputScaledValue(port);
% in this function there is no way to request an acknowledgement...

% only call this after you've set a proper input mode


data = NXT_GetInputValues(port);
% simple function, heavy output:
out.Port
out.Valid
discard?
out.Calibrated
out.TypeByte
out.TypeName
out.ModeByte
out.ModeName
out.RawADVal
out.NormalizedADVal
and 1023
out.ScaledVal
out.CalibratedVal

% from what port


% is this sensorreading valid? if not, well...
%
%
%
%
%
%
%

for future use of NXT firmware


sensor type
sensor type, but human readable
sensor mode
sensor mode, human readable
raw digital value, do nut use
use THIS, normalized value, 10bits, between 0

% use this, depends on the input mode you set


% for future use of NXT firmware

% Notation as seen in the Direct Commands doc:


% true = relative = BlockTachoCount, false = absolute =
RotationCount
NXT_ResetMotorPosition(port, true);

% more lines for better readability


NXT_SetOutputState(whatmotor, ... % port
20, ...
% power
true, ...
% motoron?
true, ...
% brake?
'SPEED', ...
% regulation
0, ...
% turnratio
'RUNNING', ... % runstate
0, ...
% tacho limit (0 = forever)
'dontreply');
% replymode
236
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/direct_commands.html (3 of 5)7/6/2010 8:43:26 AM

Direct NXT commands

out = NXT_GetOutputState(port);
% just like with GetInputValues: simple call, complex output:
out.Port
% motornumber
out.Power
% power
out.Mode
% complete mode-byte (bitfield), see below
for easier usage
out.ModeIsMOTORON
% boolean, state of MOTORON bit (false
means motor has no power)
out.ModeIsBRAKE
% boolean, state of electronic braking
(improves motor performance)
out.ModeIsREGULATED
% boolean, if set, see RegModeName, if not
set, reg mode will be IDLE
out.RegModeByte
% regulation mode, binary
out.RegModeName
% name of regulation mode: IDLE, SPEED, or
SYNC
out.TurnRatio
% turn ratio, 0 = straight forward
out.RunStateByte
% run state, binary
out.RunStateName
% name of run state: IDLE, RUNNING, RAMPUP
or RAMPDOWN
out.TachoLimit
% current tacho limit (we'll call it
AngleLimit later on)
out.TachoCount
% TachoCount = internal cumulative motordegree-counter.
out.BlockTachoCount
% motor-degree-counter, resettable using
"ResetMotorPosition relative"
out.RotationCount
% motor-degree-counter, resettable using
"ResetMotorPosition absolute"
To execute "real" Mindstorms programs on the NXT (i.e. programs that you
created using the official LEGO software and stored it locally on the NXT), you can
call this function:
NXT_StartProgram('MyDemo.rxe');
% the file extension '.rxe' can be omitted, it will then be
automatically added
Stopping the currently running program can be accomplished with
237
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/direct_commands.html (4 of 5)7/6/2010 8:43:26 AM

Direct NXT commands

NXT_StopProgram();
There are three more NXT direct commands: NXT_LSGetStatus, NXT_LSWrite,
NXT_LSRead. They all have one purpose: Address digital sensors that use the ICProtocol. An example is the ultrasonic sensor, and for more documentation you
might want to see the sourcecode of OpenUltrasonic and GetUltrasonic.
The idea is to send data (containing IC payload) first with NXT_LSWrite. Then
check the sensor status in a loop using NXT_LSGetStatus until it is ready, i.e. until
the status byte reports no error and all requested bytes are available. Those bytes
can then be received using NXT_LSRead.
Published with MATLAB 7.9

238
http://www.mindstorms.rwth-aachen.de/documents/downloads/doc/version-4.03/direct_commands.html (5 of 5)7/6/2010 8:43:26 AM

You might also like