GPIO Counter
The GpioCounter class provides a high-level, intelligent interface for counting pulses on a GPIO pin. It is designed to work seamlessly across different hardware generations (Raspberry Pi 4 and 5) and includes a fallback simulation mode for testing on non-hardware environments.
Its primary feature is Automatic Stop Detection. Instead of just counting indefinitely, the class monitors the time interval between pulses. If the interval becomes too long—indicating that the machine or process has stopped—the counter automatically transitions to a stopped state.
This detection works in two modes:
Average Mode (Default): Ideal for processes with variable speeds. It calculates the running average interval between pulses. If a new pulse takes significantly longer than this average (multiplied by a configurable factor), the counter stops.
Target Mode: Ideal for machines with a known, fixed cycle time. You define a target interval (e.g., "one part every 5 seconds"). If a pulse takes longer than this target (plus a defined tolerance), it is flagged as an "exceeded target" or triggers a stop.
You must create an instance of this class to start counting on a specific pin.
Constructor and Member Functions
create
Creates a new GpioCounter instance. The arguments you provide determine whether the counter operates in Average Mode or Target Mode.
Parameters
options: The configuration object.Hardware Settings:
gpio: The GPIO pin number (BCM numbering).pullUpDown: Internal resistor configuration ('none','pullup','pulldown'). Defaults to'none'.edge: The edge on which to count ('rising','falling','both'). Defaults to'rising'.debounceTimeout: Time in milliseconds to ignore signal noise. Defaults to10.activeLow: Iftrue, inverts the logic (useful if your sensor sends a 0 when active). Defaults tofalse.
Logic Settings:
minCount: The minimum number of pulses required before the auto-stop logic becomes active. Defaults to5.stopInterval: (Average Mode Only) The factor multiplied by the current average interval to determine the stop timeout. Defaults to2.0(twice the average speed).targetInterval: (Target Mode Only) The expected time in seconds between pulses.deviation: (Target Mode Only) The allowed deviation in percent before a pulse is considered "too slow".
Example 1: Average Mode
Goal: Count parts on a conveyor belt that changes speed. Stop if the gap between parts is double the current average.
# options
gpio: 17
pullUpDown: 'pulldown'
minCount: 3
stopInterval: 2.0Example 2: Target Mode
Goal: Monitor a machine that produces exactly one part every 5 seconds. Allow for a 10% variance.
# options
gpio: 27
pullUpDown: 'pullup'
edge: 'falling'
# The expected interval in seconds
targetInterval: 5
# Allow 10% slower (stop if gap > 5.5s)
deviation: 10Output
Returns a new GpioCounter instance.
onCount
Registers a listener that is triggered every time a valid pulse is counted.
Parameters
callback: The function to execute. It receives an object with detailed statistics about the count.
Payload Structure
The callback receives an object like this:
{
"count": 120,
"exceededTargetCount": 5,
"avgInterval": 450.5,
"delta": 455,
"timestamp": 1678886405000,
"gpio": 17
}count: Total pulses counted.exceededTargetCount: Number of times the interval was longer than the target (Target Mode only).avgInterval: The calculated average time between pulses in milliseconds.delta: Time in milliseconds since the previous pulse.
onStateChange
Registers a listener that is triggered whenever the counter transitions between states (e.g., from counting to stopped).
Parameters
callback: The function to execute.
Payload Structure
{
"state": "stopped",
"previousState": "counting",
"count": 120,
"timestamp": 1678886410000
}start
Manually starts the counting process.
This transitions the state to counting immediately, even before the first pulse is received. This is useful if you want to initialize the "watchdog" timer to detect if the machine never starts.
stop
Manually stops the counting process.
This transitions the state to stopped and clears any active timers. The current count is preserved.
reset
Resets the counter completely.
Sets the count to 0, clears all average statistics, and transitions the state back to initialized.
simulatePulse
Simulates a hardware pulse on the pin.
Note: This only works if the class is running in software simulation mode (i.e., no compatible Raspberry Pi hardware was detected). If real hardware is active, this function does nothing to prevent interference.
Parameters
value: The value to simulate (0or1). Defaults to1.
Example
# value
1getCount
Retrieves the current total count.
Output
An integer representing the number of pulses counted.
getAverageInterval
Retrieves the current calculated average interval between pulses in milliseconds.
Output
A number (e.g., 500.5).
getState
Retrieves the current state of the counter.
Output
A string: 'initialized', 'counting', or 'stopped'.
dispose
Releases all resources, stops timers, and cleans up the underlying GPIO pin. Use this when you are done with the counter to free up the hardware pin.
Last updated