Transmit Data Using Bluetooth Communication
You can read and write both text data (ASCII based) and binary data. For text data, use
the readline
and writeline
functions. For binary data,
use the read
and write
functions.
In this example, a LEGO®
MINDSTORMS® NXT robot with the name C3PO
is connected to the computer.
Communicate with the NXT device by following these steps.
Determine what Bluetooth® devices are accessible from your computer.
bluetoothlist
ans = 4×4 table Name Address Channel Status _____________ ______________ _______ __________________ "C3PO" "0016530FD63D" 1 "Ready to connect" "HC-06" "98D331FB3B77" 1 "Requires pairing" "mjin-maci" "A886DDA44062" 3 "Requires pairing" "DMTDevice" "B0B448F47A4C" Unknown "Unknown"
In this case,
C3PO
is the device name of the NXT robot and is shown in the output. To connect to the device, create a Bluetooth object calledbt
using channel1
of the NXT device.bt = bluetooth("C3PO",1);
bt = bluetooth with properties: Name: "C3PO" Address: "0016530FD63D" Channel: 1 NumBytesAvailable: 0 NumBytesWritten: 0 Show all properties
Send a message to the remote device using the
write
function. In this example, specific characters are sent to the device that this particular device (the NXT robotC3PO
) understands. You can write to the device and then view theNumBytesWritten
property to check that the values were sent.write(bt,[2,0,1,155]) bt.NumBytesWritten
ans = 35
You can see that the 35 bytes of data have been written to the device.
View the
NumBytesAvailable
property to see the number of bytes available to read.bt.NumBytesAvailable
ans = 35
Use the
read
function to read 35 bytes from the remote device.name = read(bt,35); char(name(7:10))
ans = 'C3PO'
The device returns the characters
'C3PO'
, which is the name of the device. That was a reply to the instructions that were sent to it. See the documentation for your device for this type of device-specific communication information.Clean up by clearing the object.
clear bt
Other Functionality
The following functions can be used with the Bluetooth object.
read | Read data from Bluetooth device |
readline | Read line of ASCII string data from Bluetooth device |
write | Write data to Bluetooth device |
writeline | Write line of ASCII data to Bluetooth device |
configureTerminator | Set terminator for ASCII string communication with Bluetooth device |
configureCallback | Set callback function and trigger condition for communication with Bluetooth device |
flush | Clear Bluetooth device buffers |