Driver for the JY-MCU v1.06 HC-06 Bluetooth module.

Dependents:   DISCO-F746NG_rtos_test MbedTableControl

HC06Bluetooth.cpp

Committer:
Electrotiger
Date:
2016-06-07
Revision:
2:7e0453895727
Parent:
1:026034717620
Child:
3:ee17212e838e

File content as of revision 2:7e0453895727:

/*
 * HC06Bluetooth.cpp
 *
 *  Created on: Jun 4, 2016
 *      Author: Developer
 */

#include <HC06Bluetooth.hpp>
#include <algorithm>

HC06Bluetooth::HC06Bluetooth(PinName TX, PinName RX, std::string deviceName, void (*callbackFunc) (const char* readString))
: btSerialObj(TX, RX), callbackFunc (callbackFunc) {
    // The default baud rate is 9600. Overwrite it to 230400.
    btSerialObj.puts("AT+BAUD9");
    btSerialObj.baud(230400);
    // Set the name of the device.
    btSerialObj.puts(("AT+NAME" + deviceName).c_str());
    // Set the interrupt to be called when a byte is received.
    btSerialObj.attach(this, &HC06Bluetooth::receiveByteISR);
}

HC06Bluetooth::~HC06Bluetooth() {
    // TODO Auto-generated destructor stub
}


void HC06Bluetooth::print(const char *buffer) {
    btSerialObj.puts(buffer);
}

void HC06Bluetooth::receiveByteISR() {
    while(btSerialObj.readable()) {
        // Get the character from the input.
        char receivedChar = btSerialObj.getc();
        // If the character is a newline, then a full command has been read.
        if (receivedChar == '\n') {
            // Terminate the buffer with a null character, since that is what strings end with.
            receivedChar = '\0';
            dataReceivedBuffer[dataReceivedBufferPos] = receivedChar;
            // Copy data from the buffer to a copy.
            std::copy(dataReceivedBuffer, dataReceivedBuffer + dataReceivedBufferPos, dataReceivedBufferCopy);
            // Reset the buffer position.
            dataReceivedBufferPos = 0;
            // Call the callback function.
            callbackFunc((const char*)dataReceivedBuffer);
        }
        // Otherwise, just place it in the buffer and move on.
        else {
            dataReceivedBuffer[dataReceivedBufferPos] = btSerialObj.getc();
            dataReceivedBufferPos++;
        }
    }
}