e

Dependencies:   NeoStrip USBDevice mbed

bluetoothComm.cpp

Committer:
baraki
Date:
2015-09-22
Revision:
0:5b9f87a086ce

File content as of revision 0:5b9f87a086ce:

#include "bluetoothComm.h"

//USBSerial console1; // tx, rx
Serial bt(p9,p10); // tx, rx
bool bluetoothConnected;
bool validBluetoothData;
char bluetoothData[50]={0};
int getIndex=0;
// Read data from the bluetooth
// Stores data in the bluetoothData array
// Messages must end in the null termination character ('\0')
// Will return true if a complete bluetooth message has been received (and thus if the data in bluetoothData is valid)
// This method DOES NOT BLOCK
//   it will read as long as data is available and then stop, whether or not the message is complete
//   at the next call, it will continue reading and adding to the array until '\0' is received
//  Thus, this method is meant to be called once per loop
bool getBluetoothData()
{
  if(validBluetoothData) // reset array
  {
    getIndex = 0;
    validBluetoothData = false;
  }

  if(!bt.readable())
    return false;

  while(bt.readable() && !validBluetoothData)
  {
    bluetoothData[getIndex] = getBluetoothChar();
    validBluetoothData = (bluetoothData[getIndex] == '\0');
    getIndex++;
  }
  return validBluetoothData;
}

// Returns the value of bluetoothConnected
// This variable must be set somewhere, probably in processBluetoothData
bool isBluetoothConnected()
{
  return bluetoothConnected;
}

void setBluetoothConnected(bool btCon){
    bluetoothConnected = btCon;
}

// Read bluetooth data and then process it
void processBluetoothData()
{
  if(!getBluetoothData())
    return;
  // DO SOMETHING WITH bluetoothData HERE
  // If it is a valid message, set bluetoothConnected = true
  bluetoothConnected = true;
}

char* returnBluetoothData(){
  return bluetoothData;
}

bool isBluetoothDataValid()
{
  return validBluetoothData;
}

void robotLoop()
{
  //robotPrintlnDebug();
  processBluetoothData();
}

void robotSetup(int baud_rate)
{
  bt.baud(baud_rate);
  bluetoothConnected = false;
  validBluetoothData = false;
  bluetoothData[0] = '\0';
}

void sendBluetoothData(const char* data)
{
  //robotPrintDebug("Sending BT data <"); robotPrintDebug(data); robotPrintlnDebug(">");
  int index = 0;
  for(; index < length(data); index++)
    {
      sendBluetoothChar(data[index]);
      wait_ms(5);
    }
  if(data[index-1] != '\0')
    sendBluetoothChar('\0');
  //robotPrintDebug("Sent BT data <"); robotPrintDebug(data); robotPrintlnDebug(">");
}