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
attachInterruptbinds the pin's falling edge tocountPulse.volatiletells the compiler the ISR changespulses.- Keep ISRs short: increment, get out, report from loop.
Keywords and builtins used here
INPUT_PULLUPSerialattachInterruptbeginconstcountPulsedelayintlonglooppinModeprintprintlnsetupunsignedvoidvolatile
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.
Step 1 of 3 in Peripherals, step 22 of 27 in Language basics.