1

I'm using pulseIn on an ESP32 for measuring a frequency between 500 Hz and 10 KHz. I measure both the HIGH and the LOW time, as all simple examples suggest. 95% of the time the result is correct, but sometimes pulseIn returns 0. It can happen on the HIGH or the LOW measure. I'm using GPIO27, which should not be a problem. On a digital scope the signal is very steady and clean.The code is very basic.

const int pulsePin = 27; // Input signal connected to Pin 12 of Arduino

unsigned long Htime;
unsigned long Ltime;
unsigned long Ttime;
float Frequency; // Calculated Frequency

void setup() {
  pinMode(pulsePin, INPUT);
  Serial.begin(9600);
}

void loop() {
  Htime=pulseIn(pulsePin,HIGH);
  delay(10);
  Ltime=pulseIn(pulsePin,LOW);
  Ttime=Htime+Ltime;
  Serial.print(Htime);
  Serial.print(", ");
  Serial.println(Ltime);
  delay(100);
}

The output looks like below:

enter image description here

Of course I can add code to ignore measurements with a 0 result, but any ideas on why they appear?

3
  • 1
    pulseIn() returns 0 in case of a timeout
    – Sim Son
    Sep 20, 2019 at 13:44
  • I'm aware of the time-out, but then it will take some time before it results to 0. In this case the 0 result come just af fast as the normal readings. If I disconnect the signal it all return zero, but also the reading becomes very slow. The zero-result above come just as fast as the normal readings. And even if I use the time-out parameter, with like a few seconds, the zero-readings come jus as fast as the normal, so there is no time-out, otherwise I would have to wait a few seconds.
    – Thiqua
    Sep 22, 2019 at 15:16
  • It might be noise on the signal. If you just want to measure a frequency you can use the counter modules to count pulses in a specific range. This would probably be more precise than you approach
    – Sim Son
    Sep 24, 2019 at 14:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.