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