20  Pulse sensors

20.1 Square wave

Try it · Count the pulses

How many pulses did we count?

Change how fast the pulses arrive and how long you count. Each jump from LOW to HIGH adds one pulse.

The pulses-per-litre value is an example. Use the value measured for your flow sensor.

One extra pulse changes the flow reading by 0.067 L/min.

Pulses counted
10
Measured pulses/s
5.00
Flow (L/min)
0.667
Pulses during the counting timeTen pulses counted in two seconds.
Orange dots: counted pulses2.0 seconds

10 pulses ÷ 2.0 s = 5.00 pulses/s

10 pulses ÷ 450 pulses/L = 0.0222 L

This example uses evenly spaced pulses. The first pulse arrives after one full interval; a pulse exactly at the end is counted. Starting at a different point in a real signal can change the count by one.

20.1.1 Pulse counter

Download code
int sensorPin = A4;
volatile long pulse_count;

float volume;

void setup() {
  pinMode(sensorPin, INPUT);
  Serial.begin(115200);
  attachInterrupt(digitalPinToInterrupt(sensorPin), increase, RISING);
}

void loop() {
  Serial.print(pulse_count);
  Serial.println(" counts");
  delay(50);
}

ICACHE_RAM_ATTR void increase() {
  pulse_count++;
}

20.1.2 Calculate frequency from counts

Download code
int sensorPin = A4;
volatile long pulse_count;
unsigned long last_print_time;
long total_pulse_count = 0;
float volume;

void setup() {
  pinMode(sensorPin, INPUT);
  Serial.begin(115200);
  attachInterrupt(digitalPinToInterrupt(sensorPin), increase, RISING);
  last_print_time = millis();
}

void loop() {
  unsigned long current_time = millis();
  if (current_time - last_print_time >= 1000) { // print every second
    float frequency = (float)pulse_count / ((current_time - last_print_time) / 1000.0);
    total_pulse_count += pulse_count; // update total pulse count
    Serial.print(total_pulse_count);
    Serial.print(" total counts, ");
    Serial.print(frequency);
    Serial.println(" counts per second");
    pulse_count = 0; // reset pulse count
    last_print_time = current_time;
  }
}

ICACHE_RAM_ATTR void increase() {
  pulse_count++;
}