NXT Functions Bluetooth

From ROBOTC API Guide
Jump to: navigation, search
NXTFunctions and Variables → Bluetooth


For information about Bluetooth and the NXT, see: Bluetooth Overview.
For a complete setup guide on Bluetooth for the NXT, see: NXT Bluetooth Setup.


Color Key
Function:
Variable:


bBTBusy

const bool bBTBusy
(bool) Read-only boolean variable that indicates whether Bluetooth is currently busy processing a command.
while(bBTBusy)                                   // while the Bluetooth is busy (bBTBusy == true):
{
  nxtDisplayCenteredBigTextLine(3, "BT is BUSY");   // display, "BT is BUSY" in big, centered type
  wait1Msec(100);                                   // wait 100 milliseconds (helps display correctly)
}


bBTDebugTrace

bool bBTDebugTrace
(bool) Boolean variable for advanced users. Enables output of a debug trace of Bluetooth activity to the "Debug Stream" debugger output window.
bBTDebugTrace = true;   // generate messages on internal BT operation to "debug stream" output
bBTDebugTrace = false;  // do NOT generate messages on internal BT operation to "debug stream" output


bBTHasProgressSounds

bool bBTHasProgressSounds
(bool) Boolean variable that enables or disables sound feedback on Bluetooth connect/disconnect and failure activities. Depending on whether a connection is "paired" connect and disconnect activities can occur silently. This variable will enable audible output to inform you of these actions.
bBTHasProgressSounds = true;   // play speaker tones when BT connected / disconnected
bBTHasProgressSounds = false;  // do NOT play speaker tones when BT connected / disconnected


bBTRawMode

const bool bBTRawMode
(bool) Read-only variable that can be used to test whether NXT Bluetooth is currently in "raw data transmission mode". When in "raw mode" the LEGO defined higher level protocol (i.e. Fantom messages) is disabled and the application program can directly 'read' and 'write' bytes over an existing Bluetooth connection.
setBluetoothRawDataMode();  // set Bluetooth to "raw mode"
while (!bBTRawMode)         // while the Bluecore is still NOT in raw mode (bBTRawMode == false):
{
  wait1Msec(1);               // wait for Bluecore to enter raw data mode
}


bBTSkipPswdPrompt

bool bBTSkipPswdPrompt
(bool) Boolean variable used to indicate whether manual entry of Bluetooth password should be disabled. If set, then the default value stored in RAM (see the set/get session passcode functions will always be used. Password entry using the NXT buttons and LCD can be awkward. This is a convenient way to bypass this entry if you're always going to use the same passcode.
bBTSkipPswdPrompt = true;   // manual entry of Bluetooth password will be disabled
bBTSkipPswdPrompt = false;  // manual entry of Bluetooth password will NOT be disabled


bBTVisble

const bool bBTVisble
(bool) Read-only boolean variable that indicates whether Bluetooth is 'visible' (true) or 'invisible' (false).
if(bBTVisble)                                      // If the Bluetooth is Visible:
{
  eraseDisplay();                                    // Erase the current display.
  nxtDisplayCenteredBigTextLine(3, "Going Loud");    // Display in big, centered type on line 3.
}
else                                               // Else (the Bluetooth is Invisible):
{
  eraseDisplay();                                    // Erase the current display.
  nxtDisplayCenteredBigTextLine(3, "Going Silent");  // Display in big, centered type on line 3.
}


btConnect

void btConnect(int nPort, string sFriendlyName)
(void) Attempts to connect a BT device with a specified sFriendlyName on port nPort. nPort should be either 1, 2, or 3.
Parameter Explanation Data Type
nPort BT comm port (1,2,3) int
sFriendlyName A string representing the device you'd like to connect to. string
btConnect(1, "NXT2");  // connects to an NXT named "NXT2" on port 1


btDisconnect

void btDisconnect(int nPort)
(void) This function will disconnect a single existing BT connection on the NXT. nPort ranges from 0 to 3. Port 0 is used of this is a slave BT device. Ports 1, 2, and 3 are used when this is a master BT device and are for the three possible slaves under it's command.
Parameter Explanation Data Type
nPort BT comm port (1,2,3) int
btDisconnect(1);  // disconnects from port 1


btDisconnectAll

void btDisconnectAll()
(void) This function disconnects all existing Bluetooth connections on the NXT.
btDisconnectAll();  // disconnects from ALL the ports!


btFactoryReset

void btFactoryReset()
(void) This command will reset the NXT's BT module to the default factory settings. All existing connections are disconnected. The "My Contacts" list is emptied. Any existing paired connections are lost. This command is used for restoring the NXT BT operation to its original condition. It's really only needed because it's possible that the BT hardware gets confused and in an inconsistent state and thsi is a method of last resort to recover.
btFactoryReset();  // resets the Bluetooth to factory defaults


btRemoveDevice

void btRemoveDevice(string sFriendlyName)
(void) Removes a device with the specified sFriendlyName from the "My Contacts" list. Removing a device will erase the paired connection for the device.
Parameter Explanation Data Type
sFriendlyName A string representing the device you'd like to connect to. string
btRemoveDevice("HAL9000");  // HAL 9000 is no longer a friendly


btRequestLinkQuality

int btRequestLinkQuality(int nPort)
(int) Requests the current BT link quality from a specified port. The function returns immediately before the link quality has been retrieved. The NXT CPU will send a message to the BT module requesting the data. The data is the returned to the NXT CPU within a few 100 milliseconds.
Parameter Explanation Data Type
nPort BT comm port (1,2,3) int
int nPortQuality = btRequestLinkQuality(1);


btSearch

void btSearch()
(void) Begins a search for BT devices and adds new entries to the "My Contacts" lists. The search can take up to 30 seconds to perform. This function returns immediately. Application code should continuously check the status to wait for the search to complete.
btSearch();  // search for new bluetooth devices


btStopSearch

void btStopSearch()
This function terminates an existing search on the NXT.
btStopSearch();  // stop searching on bluetooth


cCmdBTCheckStatus

void cCmdBTCheckStatus(int nStream)
(void) Used to check the status of the BT
Parameter Explanation Data Type
nStream int
cCmdBTCheckStatus(nBTCurrentStreamIndex);


cCmdBTPurgeRcvBuffer

void cCmdBTPurgeRcvBuffer()
(void) Used to purge data from the BT input buffer
cCmdBTPurgeRcvBuffer();  // purge the buffer!


cCmdMessageAddToQueue

void cCmdMessageAddToQueue(int nQueueID, ubyte* pData, const short nLength)
(void) Adds the message at pData to the queue nQueueID. nLength is the length of the message.
Parameter Explanation Data Type
nQueueID The queue to add message to. int
pData The data to add the queue. ubyte
nLength The length of the data being added to the queue. short
const int kMaxSizeOfMessage = 5;
const TMailboxIDs kQueueID = mailbox1;
ubyte nXmitBuffer[kMaxSizeOfMessage] = {0x01, 0x02, 0x03, 0x04, 0x00};
 
cCmdMessageAddToQueue(kQueueID, nXmitBuffer, kMaxSizeOfMessage);  // add message to queue to be sent via Bluetooth


cCmdMessageGetSize

int cCmdMessageGetSize(int nQueueID)
(int) Returns the size of the message at the head of queue nQueueID. A non-zero value indicates that a message is available in the NXT's queue of received messages. A zero value indicates that the queue is empty.
Parameter Explanation Data Type
nQueueID The queue to get the size of. int
int nMessageSize = cCmdMessageGetSize(mailbox1);


cCmdMessageRead

TFileIOResult cCmdMessageRead(ubyte* pData, const short nLengthToRead, const TMailboxIDs nQueueID = kDefaultBTQueue)
(TFileIOResult) Reads a Bluetooth message from nQueueID. The message data is stored in the buffer at pData. nLengthToRead is the maximum number of bytes to read -- it is used to prevent overwriting beyond the length of the buffer at pData.
Parameter Explanation Data Type
pData Where the message is stored (gets read to). ubyte
nLength The length of the data being read. short
nQueueID The queue to read the message from. TMailboxIDs
const int kMaxSizeOfMessage = 5;
ubyte nReceiveBuffer[kMaxSizeOfMessage];
 
TFileIOResult messageIn = cCmdMessageRead(nReceiveBuffer, kMaxSizeOfMessage, mailbox1);


cCmdMessageWriteToBluetooth

TFileIOResult cCmdMessageWriteToBluetooth(const short nStream, ubyte *pData, const short nLength, const TMailboxIDs nQueueID = kDefaultBTQueue)
(TFileIOResult) Writes a Bluetooth message to nQueueID. The message will be written to the specified port or nStream which should be in the range of 0 to 3. This command is only useful when multiple ports are simultaneously open on the NXT; a configuration that is not recommended because of the much slower communications when multiple ports are in use. The message data is taken from the buffer at pData. nLength is the number of bytes in the message; the maximum length is 58 bytes.
Parameter Explanation Data Type
nStream The stream (0 to 3) to write over.
(note: this is not necessary)
short
pData The data being sent. ubyte
nLength The length of the data being sent. short
nQueueID The queue to write the message to. TMailboxIDs
const int kMaxSizeOfMessage = 5;
ubyte nTransmitBuffer[kMaxSizeOfMessage];
 
TFileIOResult messageOut = cCmdMessageWriteToBluetooth(2, nTransmitBuffer, kMaxSizeOfMessage, mailbox1);


getDefaultPIN

void getDefaultPIN(string sPasscode)
(TFileIOResult) Function retrieves the default BT passcode stored in flash. Immediately after firmware download, the default is set to "1234". ROBOTC has a function that will let you redefine the default port; either for a single power on session or on a permanent basis.
Parameter Explanation Data Type
sPasscode The string to store the retrieved default PIN. string
string passcode = "";     // creates and empty string variable, 'passcode'
getDefaultPIN(passCode);  // stores the default pin ("1234") to the string variable, 'passCode'


getSessionPIN

void getSessionPIN(string sPasscode)
(TFileIOResult) Function retrieves the "session" BT passcode stored in RAM. Upon power up, the default passcode is copied to the "session" passcode. Whenever firmware needs a BT passcode, it uses the current setting of the "session" passcode. F/W needs passcode for initializing the manual entry passcode. Also needs passcode if the "use default (i.e. session) passcode without entering manually" variable is set.
Parameter Explanation Data Type
sPasscode The string to store the retrieved session PIN. string
string passcode = "";     // creates and empty string variable, 'passcode'
getSessionPIN(passCode);  // stores the session pin to the string variable, 'passCode'


message

word message
(word) Contains the value (value -32767 to + 32767) of the last message received over the bluetooth channel. Many messages can be queued at the receiving NXT. See the sample programs for a technique to skip all but the last queued message. A value of '0' indicates that no message has been received of that the last received message has been processed by the user's program. The next time 'message' variable is accessed, it will get the next message, if available, from the queue of received messages stored by the NXT firmware. Call the ClearMessage() function to indicate that processing of the current message is complete.
int lastMessage = message;  // 'lastMessage' is set equal to the last message received


nBluetoothCmdStatus

TFileIOResult nBluetoothCmdStatus
(TFileIOResult) Gets the status/progress of the last BT issued 'command'. Can be used to check whether the command is still in progress. Once completed the status contains the success or fail status of the command.
TFileIOResult status = nBluetoothCmdStatus;  // 'status' gets set to the current Bluetooth status


nBTCurrentStreamIndex

const short nBTCurrentStreamIndex
(short) Read-only variable containing the current active stream index. Value 0 is used for slave bluetooth devices. Value 1 to 3 is used for the three possible devices that can be connected on a master BT device. Value -1 is used if BT if there are no current BT connections. This variable is useful for checking if there is a current BT connection and whether the device is master or slave.
if(nBTCurrentStreamIndex >= 0)  // if there is currently an open Bluetooth connection:
{
  return;                         // return success
}


nLastBTCommand

TBTCommands nLastBTCommand
(TBTCommands) Gets the last command processed by the Bluetooth firmware.
TFileIOResult 'lastCmd' = nLastBTCommand;  // 'lastCmd' gets set to the last Bluetooth command


nxtReadRawBluetooth

short nxtReadRawBluetooth(ubyte &pData, const int nMaxBufferSize)
(short) Function used to read "raw" data bytes from the bluetooth module. pData is the location of buffer where bytes should be stored and nMaxBufferSize is the size of this buffer. The returned value is the number of bytes that was actually read. The data is retrieved from the currently open port or stream. A typical use of this advanced function is for communicating with devices -- like a BT enabled GPS receiver -- that do not follow the LEGO defined "Fantom" messaging protocol. Raw data transmission should only be used when there is a single BT connection on the NXT. The function setBluetoothRawDataMode() needs to be called to setup raw transmission.
Parameter Explanation Data Type
pData The buffer to store read data to. ubyte
nMaxBufferSize The size of the data being read. int
int bufferSize = 1;                             // will be the size of buffer.
ubyte BytesRead[bufferSize];                    // create a ubyte array, 'BytesRead' of size 'bufferSize'.
nxtReadRawBluetooth(BytesRead[0], bufferSize);  // store 'bufferSize' amount of bytes into 'BytesRead[0]'.


nxtWriteRawBluetooth

TFileIOResult nxtWriteRawBluetooth(const short nStream, ubyte *pData, const short nLength)
(TFileIOResult) Function used to write "raw" data bytes from the bluetooth module. pData is the location of buffer where bytes should be stored and nMaxBufferSize is the size of this buffer. The returned value is the number of bytes that was actually read. The data is sent to the specified nSstream. A typical use of this advanced function is for communicating with devices -- like a BT enabled GPS receiver -- that do not follow the LEGO defined "Fantom" messaging protocol. Raw data transmission should only be used when there is a single BT connection on the NXT. The function setBluetoothRawDataMode() needs to be called to setup raw transmission.
Parameter Explanation Data Type
nStream The BT stream to send the data over. short
pData The data to send. ubyte
nLength The size of the data being sent. short
int sendSize = 1;                                   // we will be sending this many bytes at a time.
ubyte BytesToSend[sendSize];                        // create a ubyte array, 'BytesToSend' of size 'sendSize'.
 
nxtReadRawBluetooth(nBTCurrentStreamIndex , BytesToSend[0], bufferSize);  /* send 'sendSize' amount of bytes */
                                                                          /* from 'BytesToSend' to the       */
                                                                          /* currently open stream.          */


resetSessionPIN

void resetSessionPIN()
(void) Function resets the default BT passcode stored in RAM to the default value stored in flash.
resetSessionPIN();  // reset the session PIN to default


sendMessage

void sendMessage(const short nMessageID)
(void) Sends a single 16-bit word message. nMessageID should range in value form -32767 to +32767. Message value 0 is invalid and should not be used. It is a special value to indicate "no message" received when using the "message" variable. The message is sent over BT. Do not send messages faster than about 1 message per 30 milliseconds or it is possible for some messages to be lost.
Parameter Explanation Data Type
nMessageID A integer message to send. short
int nMessageID = 4246;    // create 'nMessageID' to hold the 16-bit word message
sendMessage(nMessageID);  // sends 'nMessageID' over an existing Bluetooth Connection


sendMessageWithParm

void sendMessageWithParm(short nMessageID, short nParm1 = 0, short nParm2 = 0)
(void) Identical in function to the sendMessage opcode except that the message is three 16-bit values. This is useful in easily sending separate items of information in a single message. Do not use a value of zero for nMessageID.
Parameter Explanation Data Type
nMessageID A integer message to send. short
nParm1 A second integer message to send. short
nParm2 A third integer message to send. short
int nMessageID = 4246;                            // create 'nMessageID' to hold a 16-bit word message
int nParm1 = messageParm[1];                      // create 'nParm1' to hold a 16-bit word message
int nParm2 = messageParm[2];                      // create 'nParm2' to hold a 16-bit word message
sendMessageWithParm(nMessageID, nParm1, nParm2);  // sends messages over Bluetooth Connection


setBluetoothOff

TFileIOResult setBluetoothOff()
(TFileIOResult) This function turns the Bluetooth module OFF. Setting BT off will disconnect any existing connections.
setBluetoothOff();  // turn Bluetooth OFF


setBluetoothOn

TFileIOResult setBluetoothOn()
(TFileIOResult) This function turns the Bluetooth module ON.
setBluetoothOn();  // turn Bluetooth ON


setBluetoothRawDataMode

TFileIOResult setBluetoothRawDataMode()
(TFileIOResult) This function sets the NXT Bluetooth configuration to "raw data transmission" mode. When in "raw mode" the LEGO defined higher level protocol (i.e. Fantom messages) is disabled and the application program can directly 'read' and 'write' bytes over an existing Bluetooth connection. "raw mode" can only be exited by the NXT firmware when an application program terminates execution.
setBluetoothRawDataMode();  // set Bluetooth to "RAW mode"


setBluetoothVisibility

TFileIOResult setBluetoothVisibility(const bool bBluetoothVisible)
(TFileIOResult) This functions makes the NXT 'visible' or 'invisible' to search requests from other bluetooth devices. Connections can still be made to an 'invisible' device as long as the far end device already knows the BT address of the device.
Parameter Explanation Data Type
bBluetoothVisible A boolean flag. FALSE = invisible, TRUE = visible. bool
setBluetoothVisibility(true);   // NXT is now Visible
setBluetoothVisibility(false);  // NXT is now Invisible


setDefaultPIN

void setDefaultPIN(const string &passCode)
(void) Function sets the default BT passcode stored in flash. Immediately after firmware download, the default is set to "1234". This function allows you to change the default. The new default value is "permanent"; it is retained until the firmware is reloaded.
Parameter Explanation Data Type
passCode A string representing the new default password. string
string PIN1 = "4246";  // create a string variable, 'PIN1' and initialize it to "4246"
setDefaultPIN(PIN1);   // sets the default passcode to "4246"


setFriendlyName

TFileIOResult setFriendlyName(string sFriendlyName)
(TFileIOResult) This function is used to set the "friendly name" of the NXT. This is the name displayed centered on the top line of the NXT's LCD display.
Parameter Explanation Data Type
sFriendlyName A string representing the new name of the NXT. string
setFriendlyName("Odysseus");  // The NXT is now named, "Odysseus"


setSessionPIN

void setSessionPIN(const string &passCode)
(void) Function sets the "session" BT passcode stored in RAM. Upon power up, the default passcode is copied to the "session" passcode. Whenever firmware needs a BT passcode, it uses the current setting of the "session" passcode. Firmware needs a passcode for initializing the manual entry passcode. Also needs passcode if the "use default (i.e. session) passcode without entering manually" variable is set.
Parameter Explanation Data Type
passCode A string representing the new session passcode. string
string PIN2 = "6670";  // create a string variable, 'PIN2' and initialize it to "6670"
setSessionPIN(PIN2);   // sets the session passcode to "6670"


transferFile

TFileIOResult transferFile(const int nPort, const string &sFileName)
(TFileIOResult) Transfers the file sFileName from this NXT to the NXT connected to port nPort.
Parameter Explanation Data Type
nPort The BT port to send the file over (0 to 3) int
sFileName A string representing the name of the file to send over Bluetooth string
string file = "EnigmaCodes.dat";  // create a string variable, 'file' and initialize it to "EnigmaCodes.dat"
transferFile(2, file);            // send file, EnigmaCodes.dat to BT device connected on port 2