donfanning
8/15/2018 - 1:29 PM

SPHERICALBOT.ino

#include <SoftwareSerial.h>
#include <Servo.h>

// Bluetooth(RX, TX),
// RX and TX pins on Arduino board.
SoftwareSerial Bluetooth(10, 11);
Servo servoTurn;
Servo servoMove;

#define MAX_UARTCMDLEN 128
byte uartCmdBuff[MAX_UARTCMDLEN];
int uartCmdLen = 0;
char val;

void setup()
{
    servoMove.attach(12);
    servoTurn.attach(8);
    servoMove.write(90);
    servoTurn.write(90);
    
    // this pin will pull the BLE-module CE pin HIGH to enable the module
    pinMode(9, OUTPUT);
    digitalWrite(9, HIGH);

    Serial.begin(9600);
    Serial.println("AT Command:");

    // XM-10 default speed: 9600
    Bluetooth.begin(9600);
}

void loop()  
{

    // read from BLE-module then write to Serial Monitor
    if ( Bluetooth.available() ) {
      Serial.write(Bluetooth.read());
    }

    // read from Serial Monitor then write to BLE-module
    if ( listenSerialCmd()>0 ) {
      executeSerialCmd();
    }
}

int listenSerialCmd() {
    char tmp; 
    uartCmdLen = 0;
    memset(uartCmdBuff,0,MAX_UARTCMDLEN);
    while( Bluetooth.available()>0 ) {
        if( (tmp=Bluetooth.read())=='O' ){
            uartCmdLen = 0;
        }
        
        Serial.write(tmp);
        uartCmdBuff[(uartCmdLen++)%MAX_UARTCMDLEN] = tmp;
        delay(5); // wait RX signal
    }
    return uartCmdLen;
}

void executeSerialCmd() {
    char cmd[MAX_UARTCMDLEN];
    char* p;
    int value = 0; // angle or speed value
           
    // parse UART command
    sprintf(cmd,"%s",uartCmdBuff);
    if ( (p=strchr(cmd,','))==NULL )
        return;
    *p = '\0';
       
    // get speed or angle
    value = atoi(p+1);
    Serial.print("Dir:"); Serial.print(cmd); 
    Serial.print(", Value:"); Serial.println(value);

    switch ( cmd[0] ) {
        case 'm':
            servoMove.attach(12);
            servoMove.write(value);
            break;
        case 't':
            servoTurn.write(value);
            break;
        case 's':
            servoMove.detach();
            break;
    }
    delay(20);
}