// Can a Arduino Uno read its own servo signal ?
//
//
// Code to read the Servo signal from:
//   https://www.camelsoftware.com/2015/12/25/reading-pwm-signals-from-an-rc-receiver-with-arduino/

#include <Servo.h>

Servo myServo;

const int servoInputPin = 2;      // to read the servo signal, must be interrupt pin

//micros when the pin goes HIGH
volatile unsigned long timer_start;

//difference between timer_start and micros() is the length of time that the pin 
//was HIGH - the PWM pulse length
volatile int pulse_time; 

//this is the time that the last interrupt occurred. 
//you can use this to determine if your receiver has a signal or not. 
volatile int last_interrupt_time; 

//calcSignal is the interrupt handler
void calcSignal() 
{
  //record the interrupt time so that we can tell if the receiver has a signal from the transmitter 
  last_interrupt_time = micros(); 
  //if the pin has gone HIGH, record the microseconds since the Arduino started up 
  if(digitalRead(servoInputPin) == HIGH) 
  { 
    timer_start = micros();
  } 
  //otherwise, the pin has gone LOW 
  else
  { 
    //only worry about this if the timer has actually started
    if(timer_start != 0)
    { 
      //record the pulse time
      pulse_time = ((volatile int)micros() - timer_start);
      //restart the timer
      timer_start = 0;
    }
  } 
} 
 
//this is all normal arduino stuff 
void setup() 
{
    Serial.begin(115200);
    Serial.println( "The sketch has started");
    myServo.attach(10);

    timer_start = 0; 
    attachInterrupt(digitalPinToInterrupt(servoInputPin), calcSignal, CHANGE);
} 
 
void loop()
{
  int pot = analogRead( A0);
  int angle = map( pot, 0, 1023, 0, 180);
  myServo.write( angle);

  Serial.println(pulse_time);
  delay(20);
}