#include <Servo.h>

Servo myservoP;
Servo myservoH;
int Index;
String voiceSting;
int n = 10;

void setup() {
  pinMode(6, OUTPUT); //Enable
  pinMode(5, OUTPUT); //Step
  pinMode(4, OUTPUT); //Direction
  digitalWrite(6, LOW);
  Serial.begin(9600);
  moveBackward(1000);
}



void loop() {
  voiceSting = "";

  while (Serial.available())   //Check if there is an available byte to read
  {
    delay(10);                   //Delay added to make thing stable
    char c = Serial.read();      //Conduct a serial read
    voiceSting += c;                  //Shorthand for voice = voice + c
  }

  if (voiceSting.length() > 0) {
    Serial.println(voiceSting);
    for (int v = 0; voiceSting.length() > v ; v++) {
      String voice = (String) voiceSting.charAt(v);
      if (voice == "f") {
        moveForward(10 * n);
      }
      else if (voice == "b") {
        moveBackward(10 * n);
      }
      else if (voice == "n") {
        movehead();
      }
      else if (voice == "p") {
        movepaper(100);
      }
    }
    Serial.println(n);
  }

}

void moveBackward(int mm) {
  Serial.println("inside moveback");
  digitalWrite(4, HIGH);
  for (Index = 0; Index < mm; Index++) {
    digitalWrite(5, HIGH);
    delayMicroseconds(500);
    digitalWrite(5, LOW);
    delayMicroseconds(500);
  }
  delayMicroseconds(500);
}

void moveForward(int mm) {
  Serial.println("inside move forward");
  digitalWrite(4, LOW);
  for (Index = 0; Index < mm; Index++) {
    digitalWrite(5, HIGH);
    delayMicroseconds(500);
    digitalWrite(5, LOW);
    delayMicroseconds(500);
  }
  delayMicroseconds(500);
}

void movepaper(int delayS) {
  Serial.println("inside move paper");
  myservoP.attach(9);
  myservoP.write(0);
  delay(delayS);
  myservoP.detach();
}

void movehead() {
  Serial.println("inside move pen");
  myservoH.attach(8);
  myservoH.write(0);
  delay(500);
  myservoH.write(90);
  delay(500);
  myservoH.write(0);
  delay(500);
  myservoH.detach();
}

