Last active
July 8, 2025 05:27
-
-
Save juangl/8f9a5b663349e98d6be0b57498fc33a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Chip, Line } = require('node-libgpiod'); | |
const COIN_GPIO = 21; // ⚠️ cambia al pin correcto | |
const GAP_US = 60_000; // hueco >60 ms - fin del tren | |
const WAIT_MS = 5; // pooling corto para minimizar pérdidas | |
/* ───── Inicialización ─────────────────────────────────────────────── */ | |
const chip = new Chip(0); // /dev/gpiochip0 | |
const line = new Line(chip, COIN_GPIO); | |
const FLAGS = Line.RequestFlags.BIAS_PULL_UP; // mantén la línea en alto | |
line.requestFallingEdgeEvents('coin', FLAGS); | |
console.log('Coin-acceptor ready; waiting for pulses…'); | |
/* ───── Lazo de adquisición ───────────────────────────────────────── */ | |
let pulses = 0; | |
let lastEdge = 0; // timestamp µs del último flanco | |
for (;;) { | |
/* Bloquea hasta WAIT_MS por el siguiente flanco; devuelve false en timeout. */ | |
if (!line.eventWait(WAIT_MS)) { | |
/* ¿ha terminado el tren de pulsos? */ | |
const nowUs = Date.now() * 1_000; // ms → µs | |
if (pulses && nowUs - lastEdge > GAP_US) { | |
/* → tren terminado: publica el valor y reinicia el contador */ | |
console.log(`Moneda detectada: ${pulses} pulso(s)`); | |
pulses = 0; | |
} | |
continue; // vuelve a esperar | |
} | |
/* Se recibió un evento; léelo. */ | |
const ev = line.eventRead(); // { type, timestampNs, ... } | |
if (ev.type !== Line.RequestType.Event.FALLING_EDGE) continue; | |
pulses += 1; | |
lastEdge = Number(ev.timestampNs / 1_000n); // ns → µs | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment