Android Bluetooth joystick

@thornlv

I updated the Andro_Pan&Tilt code to make it compatible with Joystick BT commander V4.0,
should work right out of the box :wink:

EDIT: now Android BT Commander V5.x compatible

#define VERSION     "\n\nAndro_Pan&Tilt V3.6 - @kas2014\n** Stepper demo for V5.x App **"

// Controls two servo motors

// V3.6: Android BT Commander V5.X compatible, no button data management
// V3.0: Android BT Commander V3.X compatible, no button data management
// V2.5 can receive both Byte & Integer data
// V2.0: removed SoftwareSerial

// Android BT Commander settings:
// Options/Options for advanced users/Data Range        >>>  -100 to +100
// Options/Options for advanced users/Refresh interval  >>>  50ms

//  Arduino pin #0 to TX BlueTooth module
// BT TX to be disconnected from D0 during sketch upload

#include <Servo.h> 

boolean    DEBUG =         true;

#define    pinServo_X     9
#define    pinServo_Y     10
#define    STX            0x02
#define    ETX            0x03
#define    MIN_Y          45             // vertical move limitation
#define    MAX_Y          180
#define    ZERO_Y         60             // vertical offset

byte cmd[8] = {0, 0, 0, 0, 0, 0, 0, 0};
Servo myservoX;                         // create servo objects
Servo myservoY; 

void setup()  {
  Serial.begin(57600);
  myservoX.attach(pinServo_X);  
  myservoY.attach(pinServo_Y);  
  if(DEBUG)    Serial.println(VERSION);
}

void loop() {
   if(Serial.available())  {                            // data received from smartphone
    delay(2);
    cmd[0] =  Serial.read();  
    if(cmd[0] == STX)  {
      int i=1;      
      while(Serial.available())  {
        delay(1);
        cmd[i] = Serial.read();
        if(cmd[i]>127 || i>7)                 break;     // Communication error
        if((cmd[i]==ETX) && (i==2 || i==7))   break;     // Button or Joystick data
        i++;
      }
      if(i==7)     setServoPosition(cmd);
    }
  }
}

void setServoPosition(byte data[8])    {
  int joyX = (data[1]-48)*100 + (data[2]-48)*10 + (data[3]-48);       // obtain the Int from the ASCII representation
  int joyY = (data[4]-48)*100 + (data[5]-48)*10 + (data[6]-48);
  joyX = joyX - 200;                                                  // Offset to avoid
  joyY = joyY - 200;                                                  // transmitting negative numbers

  if(joyX<-100 || joyX>100 || joyY<-100 || joyY>100)     return;      // commmunication error
  
  joyX = map(joyX, -100, 100, 180, 0);   //  << adjust to change motor direction
  joyY = map(joyY, -100, 100, 0, 180);   //  <<

  joyY+=ZERO_Y;
  joyY = constrain(joyY, MIN_Y, MAX_Y);
  myservoX.write(joyX);
  myservoY.write(joyY);
  if(DEBUG)    {Serial.print(joyX); Serial.print(", "); Serial.println(joyY);}
}

Tell me if it works