how code to count a pulse on water flow meter with interrupt program?
thanks
Send a link to the library you are using...
But generally, there will be a variable that is defined as volatile which is in the library, which the interrupt service routine increments (increases by one), every time the ISR is executed, and the ISR is executed when there is a transition on the interrupt pin (which transition depends on how the interrupt was configured)
Send a link to the library you are using...
Why use a library ?
Set up a counter variable as a global volatile unsigned int
Use attachInterrupt() to associate a hardware interrupt with a function and a trigger event
In the function called by the interrupt increment the counter variable.
In the loop() function print the value of the counter variable every so often.
Something like this ?
volatile unsigned long pulseCount;
void setup() {
// usual stuff
attachInterrupt(0, countPulse, RISING);
}
void loop() {
// whatever
}
void countPulse() {
pulseCount ++;
}
...R
Something like this ?
I'm glad that I was able to help ![]()
To read the counter outside the interrupt routine without risking catching
it mid-change, do something like:
unsigned long readCount ()
{
noInterrupts () ;
unsigned long copy = pulseCount ; // read 4 bytes of counter knowing they can't change
interrupts () ;
return copy ;
}
Because the processor is 8-bit an u long variable takes 4 memory accesses to read
and interrupt could happen between those instructions.
Another way to read such a variable without disabling interrupts is to sample repeatedly
until no change:
unsigned long readCount ()
{
unsigned long sample = pulseCount ;
unsigned long sample2 = pulseCount ;
while (sample != sample2)
{
sample = sample2 ;
sample2 = pulseCount ;
}
return sample ;
}
UKHeliBob:
I'm glad that I was able to help
Sorry - mental overlap or underlap.
I hadn't read your post.
...R
I hadn't read your post.
No problem.
My post (and smiley) was not meant to be sarcastic. Two great minds were bound to suggest the same solution ![]()