Counting pulses with wb-rules
Counting pulses on a digital input
A meter or button with a dry-contact output is connected to the controller's universal input A1. The rule counts how often A1 is connected to ground and displays the result in a virtual device. The device also includes a counter-reset button.
The WB-MCM8 provides the same pulse-counting function with counter values stored in its own non-volatile memory. The manufacturer recommends it for real installations; the example below is for demonstration and learning.
In a real installation, consider the frequency of writes to PersistentStorage. These writes reach the controller's eMMC storage, and saving on every pulse at high pulse rates can accelerate storage wear.
Example rule
The rule restores the saved count at startup, counts only rising edges (0 → 1), and saves both increments and resets.
defineVirtualDevice("pulse_counter", {
title: "Pulse counter",
cells: {
impulses: {
type: "value",
value: 0
},
reset: {
type: "pushbutton"
}
}
});
var ps = new PersistentStorage("pulse-counter-storage", { global: true });
var inputChannel = "wb-gpio/A1_IN";
var impulseCount = (ps["impulseCount"] === undefined) ? 0 : ps["impulseCount"];
dev["pulse_counter"]["impulses"] = impulseCount;
defineRule("count_impulses", {
whenChanged: inputChannel,
then: function (newValue) {
if (newValue) {
impulseCount += 1;
dev["pulse_counter"]["impulses"] = impulseCount;
ps["impulseCount"] = impulseCount;
}
}
});
defineRule("reset_counter", {
whenChanged: "pulse_counter/reset",
then: function () {
impulseCount = 0;
dev["pulse_counter"]["impulses"] = impulseCount;
ps["impulseCount"] = impulseCount;
}
});
For WBE2-DI-DR-3, replace the A1 input channel with the required channel from its MQTT channel table, for example wb-gpio/MOD1_IN1.
