int const outpin = 13;
volatile int state = LOW;
int reading;
int previous = LOW;
volatile long previousmillis = 0;
volatile long starttime;
volatile long elapsedtime;
void setup() {
pinMode(outpin, OUTPUT);
attachInterrupt(digitalPinToInterrupt(2), blink, CHANGE);
}
void loop()
{
reading = state; //read state
if (reading == HIGH && previous == LOW) //if state is detected
{
detachInterrupt(2); //first, disbale interrupt to enable calculations
if (state == HIGH)
starttime = millis(); //starttime is taken from millis, which counts all the time at background
}
previous = reading; //take previous from current reading
elapsedtime = millis () - starttime; //calculate time; millis is bigger than starttime
if (elapsedtime ==0 && elapsedtime <= 4) //turn led on between 0-4ms
{
digitalWrite (outpin, HIGH);
}
if (elapsedtime >=4) //turn led off at 5ms
{
digitalWrite (outpin, LOW);
}
attachInterrupt(digitalPinToInterrupt(2), blink, CHANGE); //after calculations, enable interrupt
}
void blink() {
state = !state;
}