#include "mbed.h"
 
InterruptIn device1(p11);
InterruptIn device2(p12);
InterruptIn device3(p13);

DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);

Serial pc(USBTX, USBRX);
Timer t;

int interruptionMoments[3];
int toPrint[3];
bool hasToPrint = false;
bool cagada = false;
int interruptionQty = 0;
int tandaTime;
int currentInterruptTime = 0;

void interruptionCommon(int deviceId, DigitalOut led){
    currentInterruptTime = t.read_us();
    
    if (interruptionQty == 0) {
        tandaTime = currentInterruptTime + 1000000;
    }
    
    if (currentInterruptTime > tandaTime) {
        if (interruptionQty < 3) {
            led1 = led2 = led3 = false;
            led = true;
        }
        cagada = interruptionQty != 3;
        hasToPrint = true;
        for (int i=0; i<3; toPrint[i] = interruptionMoments[i], i++);
        tandaTime = currentInterruptTime + 1000000;
        interruptionQty = 0;
    }
    
    interruptionMoments[deviceId-1] = currentInterruptTime;
    interruptionQty++;           
}

void device1Interruption() {
    led1 = !led1;
    interruptionCommon(1, led1);
}

void device2Interruption() {
    led2 = !led2;
    interruptionCommon(2, led2);
}

void device3Interruption() {
    led3 = !led3;
    interruptionCommon(3, led3);
}

 
int main() {
    pc.printf("Hello World!\n");
    device1.rise(&device1Interruption);
    device2.rise(&device2Interruption);
    device3.rise(&device3Interruption);
    
    tandaTime = 2147483647;
    t.start();
    while(1) {
        if (hasToPrint) {
            pc.printf("%i\t%i\t%i\t%i\n", toPrint[0], toPrint[1], toPrint[2], cagada);
            hasToPrint = false;
        }
    }

}