Example sketches for the new Arduino IDE for ESP8266

Moderator: igrr

User avatar
By canta
#42256 Hi All,

this is my issue, I need to read /calculate Freq from GPIO12, the source will has range from 0 Hz to 1KHz..

are there any suggestion on how to calculate Freq?
I am thiniking using interrupt and compare old time to recent time (raised by intterupt) to calculate Freq...

Thanks!
User avatar
By penatenjoe
#42340 I had to do something similar in one of my recent projects. There I was just counting pulses for one second. This worked astonishingly well up to 100 kHz or so.
Code: Select all// =====================================================
// measure flowmeter
volatile unsigned long cnt; // volatile var is stored in RAM (not register) for interrupt handler
void rpm() {
  cnt++;
}

// measure flow in l/min
float measureflow() {
  cli();
  unsigned long cnt1 = cnt;
  sei();
  // count for 1000 msec
  delay(1000);

  cli();
  unsigned long cnt2 = cnt;
  sei();
  // calculate results
  volume = cnt2 * coeff;
  return (cnt2 - cnt1) * coeff * 60; // l/min
}

void resetflowcounter() {
  cli();
  cnt = 0;
  sei();
  volume = 0;
}

void setup(){

  pinMode(flowpin, INPUT);
  attachInterrupt(digitalPinToInterrupt(flowpin), rpm, RISING);

}


At low frequencies (say <50 Hz) this is not as accurate. Then you may use something like the code below and calculate the frequency using 1e-6/(tick-lasttick).

Code: Select allunsigned long tick, lasttick
void rpm(){
     lasttick = tick;
     tick = micros();
}

An even simpler way to accomplish the same is using the pulseIn function of the Arduino library
Code: Select allpulselength = pulseIn(pin, HIGH, timeout)+ pulseIn(pin, LOW, timeout);

Is that what you were looking for?
User avatar
By danbicks
#42350 Hi @penatenjoe,

Great example, what is the value of the coeff? this must be like a constant value to fine tune accuracy.

I have a wind speed detector that has simple read switch's, I think your approach would work for measuring wind speed.
A single revolution of this wind sensor generated 2 pulses. Any pointers on how to tweak your code to fit?
Cheers mate

Dans