Skip to main content

How to: Pulse counter

The pulse counter counts pulses on the channels A, B and C of the Sensor Module, for example from the S0 output of an electricity meter, the reed contact of a water meter or a flow sensor.

References​

Wiring​

Connect the contact or the S0 output between a channel and GND. The pulse counter turns on the internal pull-up of the channel. Where switching relays or solenoids nearby add false pulses, use the stronger 4.7 kΩ pull-up of the Sensor Module after the initialization: twr_module_sensor_set_pull(TWR_MODULE_SENSOR_CHANNEL_A, TWR_MODULE_SENSOR_PULL_UP_4K7).

For channel C on Sensor Module R1.1, see the revisions of the Sensor Module.

Example​

The node reports the count every 5 minutes. A meter can give thousands of pulses, so report the count in intervals rather than for each pulse.

Pulse Counter Code Example

#include <application.h>

#define REPORT_INTERVAL (5 * 60 * 1000)

void application_init(void)
{
twr_radio_init(TWR_RADIO_MODE_NODE_SLEEPING);

// Count falling edges on channel A of the Sensor Module
twr_pulse_counter_init(TWR_MODULE_SENSOR_CHANNEL_A, TWR_PULSE_COUNTER_EDGE_FALL);

twr_radio_pairing_request("pulse-counter", FW_VERSION);
}

void application_task(void *param)
{
(void) param;

uint32_t count = twr_pulse_counter_get(TWR_MODULE_SENSOR_CHANNEL_A);
twr_radio_pub_uint32("pulse-counter/a/count", &count);

twr_scheduler_plan_current_relative(REPORT_INTERVAL);
}

The ready-made Pulse Counter firmware counts on channel A and publishes node/{id}/pulse-counter/a/count every 5 minutes; channel B works as a button.

Contacts that stay closed for long​

For a contact that changes slowly and can stay closed for weeks, for example a rain gauge or a door contact, use twr_switch with a dynamic pull-up. It turns the pull-up on only while it reads the input, so a closed contact does not draw current all the time:

static twr_switch_t contact;

twr_switch_init(&contact, TWR_GPIO_P4, TWR_SWITCH_TYPE_NO, TWR_SWITCH_PULL_UP_DYNAMIC);
twr_switch_set_event_handler(&contact, contact_event_handler, NULL);