const byte interruptPin = 2; // in uno/nano only pin 2 and 3 can use. 2has the priority.
volatile bool runAllowed = false;
void setup()
{
Serial.begin(9600);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), interruptServiseRoutine, FALLING);// interrupt will call when pin 2 falls from high to low
}
void loop()
{
runAllowed = digitalRead(interruptPin);
if(runAllowed)
{
for(int i=0; i<1000; i++)
{
//runAllowed = digitalRead(5);// now this not need since this will done by interrupt attach.
Serial.print("i = ");
Serial.print(i);
Serial.print(" ");
Serial.println("Motor running");
if(not runAllowed)
{
Serial.println("Interrupt called");
break; // you have to use break commoand even if you use interrupt. otherwise loop wil continue after executing interrupt.
// see what will happen if you remove break by inserting //.
runAllowed = true; // this will reset the effect of interrupt. otherwise if you remove break it will appear like interrupt called repeatedly try // ing this and see the effect
}
delay(500);
}
}
Serial.println("Motor not running");
delay(2000);
}
void interruptServiseRoutine() {
runAllowed = false;
}