int motor1 = 10;
int motor2 = 13;
int sensor = 3;  
int led = 5;
int value=40;
unsigned long startT, endT, timeout;
float rpm;

void setup() {
  pinMode(motor1, OUTPUT);  
  pinMode(motor2, OUTPUT); 
  pinMode(led, OUTPUT);  
  pinMode(sensor, INPUT); 
  TCCR1B = TCCR1B & B11111000 | B00000001; 
  Serial.begin(9600);
}

void loop(){
  // set speed
  analogWrite(motor1,value);
  digitalWrite(motor2, LOW); 
  // measure disk
  timeout=false;
  startT=millis();
  while (digitalRead(sensor)==HIGH and timeout==false){
    delay(10);
    if ((millis()-startT)>1000){ 
      timeout=true;
    }
  }
  timeout=false;
  startT=millis();  
  digitalWrite(led, HIGH);
  while (digitalRead(sensor)==LOW and timeout==false){
    delay(10);
    if ((millis()-startT)>1000) {
      timeout=true;
    }
  }
  // calculate rpm
  endT=millis()-startT;
  if (timeout==true or endT==0){
    rpm=0; 
  }
  else{
    rpm=60000.0/(4*endT);
  }
  digitalWrite(led, LOW); 
  // correct PWM setting
  if (rpm>60) value=value-5;
  if (rpm<60) value=value+5; 
  // display data
  Serial.write(27); 
  Serial.print("[7;8H");
  Serial.print("Motor speed: ");
  Serial.print(rpm);
  Serial.print(" rpm        ");
  Serial.write(27); 
  Serial.print("[9;8H");
  Serial.print("PWM setting: ");
  Serial.print(100*value/255);
  Serial.print(" %        ");
}
