/*
 * serial_stepper 2軸制御 (同時2軸は不可)
 * コマンド 移動パルス
 *           x[-]*****g または y[-]*****g [-]は方向 *は数値 32,767,-32768範囲
 *           移動速度 rpm
 *           f***g *は数値 メカに合わせる
 *          モーターはコマンド入力10秒されないと励磁OFF 少し安全省エネソフト
 * フォーマットのチェックはしてません。間違えると暴走?
 * 2009/5/5
 */
#include <Stepper.h>
#define STEPS 200

Stepper stepper1(STEPS, 4, 6, 5, 7);
Stepper stepper2(STEPS, 8, 10, 9,11);

void setup()
{
    stepper1.setSpeed(60);
    stepper2.setSpeed(60);
    Serial.begin(9600);
    //Serial.println("start");
    Serial.print("Ready");
}

void motor_off(){
  digitalWrite(4, LOW);    // sets the motor off
  digitalWrite(6, LOW);    // sets the motor off
  digitalWrite(5, LOW);    // sets the motor off
  digitalWrite(7, LOW);    // sets the motor off

  digitalWrite(8, LOW);    // sets the motor off
  digitalWrite(10, LOW);   // sets the motor off
  digitalWrite(9, LOW);    // sets the motor off
  digitalWrite(11, LOW);   // sets the motor off
}

static int v = 0;
static int count = 0;
boolean flg_x = false;
boolean flg_y = false;
boolean flg_n = false;
boolean flg_f = false;

void loop(){

  if ( Serial.available()) {
    char ch = Serial.read();

    switch(ch) {
      case 'f':
        flg_f = true;
        break;
      case 'x':
        flg_x = true;
        break;
      case 'y':
        flg_y = true;
        break;
      case '-':
        flg_n = true;
        break;
      case '0'...'9':
        v = v * 10 + ch - '0';
        break;
      case ('g'):
       if(flg_f == true){
          stepper1.setSpeed((long)v);
          stepper2.setSpeed((long)v);
          Serial.print('F');
          Serial.println(v,DEC);
          flg_f = false;
       }
       if(flg_x == true){
          Serial.print('X');
          if(flg_n == true) v = 0 - v;
          Serial.println(v,DEC);
          stepper1.step(v);
          flg_x = false;
        }else if(flg_y == true){
          Serial.print('Y');
          if(flg_n == true) v = 0 - v;
          Serial.println(v,DEC);
          stepper2.step(v);
          flg_y = false;
        }
        flg_n = false;
        v = 0;
        count = 0;
        break;
      default:
        flg_x = false;
        flg_y = false;
        flg_n = false;
        flg_f = false;
        v = 0;
        Serial.println("error");
        break;
    }

  }else{
      if(count > 100) motor_off() ;
      count++;
      delay(100);      // waits for a second
  }
}