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

Dependents:   DISCO-F746NG_rtos_test MbedTableControl

Revision:
1:026034717620
Parent:
0:3ab5e47dde1e
Child:
2:7e0453895727
--- a/HC06Bluetooth.cpp	Sun Jun 05 20:44:21 2016 +0000
+++ b/HC06Bluetooth.cpp	Mon Jun 06 02:40:00 2016 +0000
@@ -6,15 +6,17 @@
  */
 
 #include <HC06Bluetooth.hpp>
+#include <algorithm>
 
 HC06Bluetooth::HC06Bluetooth(PinName TX, PinName RX, std::string deviceName)
-: btSerialObj(TX, RX){
+: btSerialObj(TX, RX) {
     // 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() {
@@ -26,10 +28,31 @@
     btSerialObj.puts(buffer);
 }
 
-void HC06Bluetooth::setCallback(void (*callbackFunc) (std::string readString)) {
-
+void HC06Bluetooth::setCallback(void (*callbackFunc) (const char* readString)) {
+    HC06Bluetooth::callbackFunc = callbackFunc;
 }
 
 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++;
+        }
+    }
 
 }