1. An Arduion IDE based sketch/program has the following four spaces:
//Global Space (to hold global variables, header files. and the like)
void setup() //Setup Space (holds tasks to be executed only once or a number of times)
{
}
void loop() //Loop Space (holds tasks that will be excuted repeatedly)
{
}
//User Space (holds user-defined functions and Interrupt Sub Routines (ISR))
2. The program execution begins from the setup() function and then the control goes into loop() function from where the user-defined functions and ISRs are called upon as needed and dictated.
3. When an interrupt occurs, the MCU disables the "interrupt logic" before entering into the corresponding ISR. This is to ensure that the MCU is not interrupted until the current ISR is completed. The interrupt logic is re-enabled at the time of returning to the MLP (main line program), and it happens just after the excution of the ISR.
4. In a system, there could be many other processes that are interrupt driven; therefore, the ISR must contain minimum number of codes so that they are executed as quick as possible and the interrupt logic is re-enabled without much appreciable delay. This arrangement helps the interrupt driven processes to appear as in the "running states".
5. The arrangemnt of Step-4 is implemented with the help of the flag concept, which is set to "true" state when an interrupt happens and the MCU goes to the ISR. The ISR codes are placed in the loop() function; where, the codes are executed by testing the flag's value. the flag is reset to "false" state after the execution of the ISR codes in the loop() function. The following example may help to understand the role of flag.
6. Create a sketch to blink L (bulit-in LED of UNO) for five times at 1-sec interval using delay() function when the MCU is interrupted over the INT0-pin.
Note that the delay() function needs "enabled interrupt logic" to work.; so, the delay() function can not be put in the ISR() as the interrupt logic remains disabled in the ISR(). This is just an example. If someone really needs to insert this amount of high delay in the loop() function, then he will be required to implemet it in some other ways (like using TC Module) where interrupt logic is not disabled.
volatile bool flag = false; //Global space
void setup()
{
pinMode(2, INPUT_PULLUP); //internal pull-up is enabled for DPin-2 (INT0-pin)
pinMode(13, OUTPUT); //L is connected at DPin-13 of UNO
attachInterrupt(digitalPinToInterrupt(2), ISRINT0, FALLING);
}
void loop()
{
if(flag == true)
{
for(int i = 0; i<5; i++)
{
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
flag = false;
}
}
void ISRINT0()
{
flag = true;
}