I'm writing a (seemingly simple) program to read an encoder on a flow meter using interrupts, and then convert those pulses into a flow rate in L/min, and then output the flow rate number to the serial port so I can see it on my screen. I have a button to press to start this 'test' which tells the program to a) open the solenoid valve to let water flow and b) start the interrupt and start counting pulses.
Here's my code
// reading liquid flow rate using adapted program from Seeeduino and Water Flow Sensor from Seeedstudio.com
volatile int NbTopsFan; //measuring the rising edges of the signal
int Calc;
int hallsensor = 2; //The pin location of the sensor
int val = 0; //val is the value of the button (1 = on)
void rpm () //This is the function that the interupt calls
{
NbTopsFan++; //This function measures the rising and falling edge of the hall effect sensors signal
}
void setup() //
{
pinMode(hallsensor, INPUT); //connected to flow meter sensor
Serial.begin(115200);
attachInterrupt(0, rpm, RISING);
pinMode(13, OUTPUT); //connected to solenoid
pinMode(3, INPUT); //connected to button input
}
void loop ()
{
val = digitalRead(3); //read the button
cli();
if (val == 1) //if the button is pressed down, start the test
{
digitalWrite(13, HIGH); //open solenoid valve
NbTopsFan = 0; //Set NbTops to 0 ready for calculations
sei(); //Enables interrupts
delay (1000); //Wait 1 second
cli(); //Disable interrupts
digitalWrite(13, LOW); //close solenoid valve
delay(100);
}
if (NbTopsFan != 0) //if we have new data, calculate flow rate and output to serial port
{
Calc = (NbTopsFan *60 / 73); //(number of pules in 1 second *60 seconds /1 min) / 73L/min (calibrated by seeed), = flow rate in L/min
Serial.print (Calc, DEC); //Prints the flow rate in L/min
Serial.print (" L/min \n");
NbTopsFan = 0; //reset data for next test
Calc = 0;
delay(100);
}
}
Everything is 'pretty much' working fine aside from the serial port. When i press the button once, I don't see anything written to the screen. But when I press it again, I get the flow rate from the previous 'test' (ie the flow rate calculated on the previous button press). Why is the serial data one button press behind?