We can use Arduino like FPGA (Actually, I made a joke on this article in Turkish but I can’t make it in English ­čśÇ ). Anyway, we use attachInterrupt() for a controller which works parallel.

About attachInterrupt():

In this way, we can constantly check the changes on a pin so we never hit the barrier. For example, we make a robot which check the barriers and goes forward. Algorithm of this robot, checks the barriers firstly and then goes forward or stops motors. If there is a delay() after checking barriers, we could be in danger because a barrier may appear at close while in delay(), but motors can’t stop… And we will crash!

If there is an irrelevant controller from the delay() lines, we are safe ­čÖé┬á We can use attachInterrupt() for safe or parallel controlling. But we have to be careful when writing the algorithm that contains attachInterrupt(). Because, Arduino notices the change on the pin but motors can’t stop ­čÖé This is completely related to the algorithm.

Warn for Linux Users: A code contains attachInterrupt() can’t be compiled by Arduino IDE on Linux system. (I tried on Debian.)

For example, Algorithm with Faulty:


const byte ledPin = 13;
const byte interruptPin = 3;
volatile byte state = LOW;

void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(interruptPin, CHANGE);
attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}

void loop() {
digitalWrite(ledPin, state);
delay(4000);
}

void blink() {
Serial.println("Interrupt pininde de─či┼čim alg─▒land─▒.");
state = !state;
Serial.print("Led durumu: ");
Serial.println(state);
}

Output:

Arduino noticed the changing on the pin but led continuous on status because of algorithm.

True Algorithm:


const byte ledPin = 13;
const byte interruptPin = 3;
volatile byte state = LOW;

void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(interruptPin, CHANGE);
attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}

void loop() {
digitalWrite(ledPin, state);
delay(4000);
}

void blink() {
Serial.println("Interrupt pininde de─či┼čim alg─▒land─▒.");
state = !state;
Serial.print("Led durumu: ");
Serial.println(state);
loop();
}

Output:

Arduino noticed the changing on the pin and delay breaked.