typestar

Interrupts in Arduino

An ISR runs the instant the pin falls, mid-loop.

// An interrupt routine runs the instant the pin falls, mid-loop.
const int FLOW_PIN = 2;

volatile unsigned long pulses = 0;

void countPulse() {
  pulses++;  // keep ISRs short; volatile shares the count safely
}

void setup() {
  pinMode(FLOW_PIN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(FLOW_PIN), countPulse, FALLING);
  Serial.begin(9600);
}

void loop() {
  Serial.print("Flow pulses: ");
  Serial.println(pulses);
  delay(1000);
}

How it works

  1. attachInterrupt binds the pin's falling edge to countPulse.
  2. volatile tells the compiler the ISR changes pulses.
  3. Keep ISRs short: increment, get out, report from loop.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
439
Tokens
84
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 84 seconds.

Type this snippet

Step 1 of 3 in Peripherals, step 22 of 27 in Language basics.

← Previous Next →