Transmit Data Using Bluetooth Communication
You can read and write both text data (ASCII based) and binary data. For text data, use
writeline functions. For binary data,
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.
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,
C3POis the device name of the NXT robot and is shown in the output. To connect to the device, create a Bluetooth object called
1of 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
writefunction. In this example, specific characters are sent to the device that this particular device (the NXT robot
C3PO) understands. You can write to the device and then view the
NumBytesWrittenproperty to check that the values were sent.
ans = 35
You can see that the 35 bytes of data have been written to the device.
NumBytesAvailableproperty to see the number of bytes available to read.
ans = 35
readfunction 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.
The following functions can be used with the Bluetooth object.
|Read data from Bluetooth device|
|Read line of ASCII string data from Bluetooth device|
|Write data to Bluetooth device|
|Write line of ASCII data to Bluetooth device|
|Set terminator for ASCII string communication with Bluetooth device|
|Set callback function and trigger condition for communication with Bluetooth device|
|Clear Bluetooth device buffers|