%% Communicate with HC-06 over Bluetooth®
% This example shows how to communicate with a HC-06 Bluetooth module using Serial Port Profile.
%% Hardware Requirements
% Windows 10 or macOS machine with built-in or external Bluetooth 2.0 compatible adapter
% HC-06 Bluetooth module
% 5 V source, such as an FTDI converter or Arduino board
% A few wires
%% Hardware Setup
% This example uses a HC-06 Bluetooth transceiver module configured as a loopback device. On the HC-06 module:
% Connect the VCC pin to the 5 V source.
% Connect the GND pin to the ground.
% Connect the TXD pin to the RXD pin.
% A blinking LED on the HC-06 module indicates that the device is powered. Next, pair the device on the host computer to allow connection in MATLAB. The default PIN code is 1234 unless configured otherwise.
%
%% Get Device Information
% Identify the Bluetooth device address or name and SPP channel number by calling the bluetoothlist function. Make sure the device status is "Ready to connect", indicating that it is powered on and paired. If you already know the device information, you can skip this step.

bluetoothlist

%
%% Connect to Device
% Use the device address or name and SPP channel number to connect to the device by calling bluetooth. Specify the device name if it is unique or specify the device address.

hc06 = bluetooth("HC-06", 1)

%
%% Write and Read Data
% After you connect the HC-06 to MATLAB, write byte data or string data to the device by calling write.

write(hc06, 1:10);
write(hc06, "helloworld");

% Since the device is configured as a loopback, the data received on the device is immediately returned to MATLAB. Read the data by calling read.

read(hc06, 10)
read(hc06, 10, "string")

% For information on sending and receiving terminated string data, see readline and writeline.
%
%% Collect Data Asynchronously
% You can use a callback function to read data as it is written to the Bluetooth device. Call configureCallback to read and collect data each time five bytes are sent by the device and received in MATLAB.
% function collectData(src, evt)
%     % Read received data and store it in the UserData property on the bluetooth object
%     src.UserData = [src.UserData; read(src,src.BytesAvailableFcnCount)];
% end

configureCallback(hc06, "byte", 5, @collectData);

% Write data to the device. The data is immediately sent back to MATLAB, triggering the callback function to read and display the data.

write(hc06, 1:20);
% Wait for all callbacks to be processed
pause(1);
disp(hc06.UserData);

%
%% Disconnect from Device
% Clear the device object when you are finished working with it.

clear hc06

% Copyright 2020 The MathWorks, Inc.