Handle GPIO Interrupts and Alerts
masterThe Gpio class is an EventEmitter that provides two ways to monitor state changes:
Interrupts
Best for: Low latency.
enableInterrupt(edge[, timeout]): Enables interrupts.edgecan beRISING_EDGE,FALLING_EDGE, orEITHER_EDGE.timeoutis optional (ms).disableInterrupt(): Disables interrupts.- Event:
'interrupt'is emitted. Thelevelargument is the level read at the time of the interrupt. If atimeoutexpires,levelisTIMEOUT(2).
Alerts
Best for: High frequency/detecting more changes.
enableAlert(): Enables alerts. An event is emitted every time the state changes.disableAlert(): Disables alerts.- Event:
'alert'is emitted. Thelevelis the state (0 or 1) andtickis the microsecond timestamp since boot. - Note: Alerts have higher latency than interrupts as they are queued and fired once per millisecond.
Glitch Filter
glitchFilter(steady): Sets a filter that ignores level changes shorter thansteadymicroseconds. This only affects'alert'events.
const { Gpio } = require('pigpio');
const gpio = new Gpio(4, { mode: 'INPUT', edge: 'EITHER_EDGE' });
gpio.on('interrupt', (level) => {
console.log(`Interrupt detected! Level: ${level}`);
});
// Using alerts with a glitch filter
gpio.glitchFilter(50); // Ignore changes shorter than 50us
gpio.enableAlert();
gpio.on('alert', (level, tick) => {
console.log(`Alert! Level: ${level} at tick: ${tick}`);
});