-->
Page 1 of 2

direction on how to read/calculate freq with esp8266 arduino

PostPosted: Wed Mar 02, 2016 3:04 pm
by canta
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!

Re: direction on how to read/calculate freq with esp8266 ard

PostPosted: Thu Mar 03, 2016 12:31 pm
by penatenjoe
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?

Re: direction on how to read/calculate freq with esp8266 ard

PostPosted: Thu Mar 03, 2016 12:39 pm
by onehorse
There is an example here (mostly commented out) for using an interrupt to calculate frequency of a square wave on a Teensy GPIO pin.

https://github.com/kriswiner/M41T62_HTS ... M24M02.ino

Re: direction on how to read/calculate freq with esp8266 ard

PostPosted: Thu Mar 03, 2016 2:47 pm
by danbicks
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