const int PIN_IR_SENSOR = 2;
const unsigned long TIME_THRESHOLD_MIN = 1000;
const unsigned long TIME_THRESHOLD_MAX = 2000;

volatile unsigned long timestampPrevEdge = 0;
volatile char signalCode[30];
volatile byte signalBitsRead = 0;
volatile bool gotSomething = false;

void signalChanged() {
  if (digitalRead(PIN_IR_SENSOR)==1) {
    // Rising edge: start time measurement
    timestampPrevEdge = micros();
  } 
  else {
    // Falling edge: Check pulse length
  	unsigned long signalTime = micros()-timestampPrevEdge;
    // Short pulse: 0
    if (signalTime<TIME_THRESHOLD_MIN) {
      signalCode[signalBitsRead] = '0';
      signalBitsRead++;
    }
    // Long pulse: 1
    else if (signalTime<TIME_THRESHOLD_MAX) {
      signalCode[signalBitsRead] = '1';
      signalBitsRead++;
    }
    // Else: Timeout
  } 
}

void setup()
{
  Serial.begin(9600);
  pinMode(PIN_IR_SENSOR, INPUT);
  attachInterrupt(digitalPinToInterrupt(PIN_IR_SENSOR), signalChanged, CHANGE);
}

void loop()
{
  // Check whether one signal finished
  if ((micros()-timestampPrevEdge)>TIME_THRESHOLD_MAX) {
    // Check for detected pulses
    if (signalBitsRead>0) {
      // Print signal
      for (byte i=0; i<signalBitsRead; i++) {
        Serial.print(signalCode[i]);
      }
      Serial.println();
      // Reset index
      signalBitsRead = 0;
    }
  }
}