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:
Of course I can add code to ignore measurements with a 0 result, but any ideas on why they appear?
pulseIn()
returns 0 in case of a timeout