Millie function problems

I am working on a project to measure liquid flow and essentially if there is 0 input the tap is closed and If there is a reading of 1 the tap is open. What I need to happen is have my code time the interval for which the tap is open timed. Im trying to reference the milli ( ) function to calculate total time by continuously going through the loop and adding up the time the reading spends at 1. What I want to happen is when the reading is 1 the millis value at that instant is saved and then the next time the loop is gone through the new millis function will be subtracted from that to give a time interval. These small intervals will be added up for a large sum of seconds. What is currently happening the “lastime” in my function is just being set equal to millis instead of just drawing out one value. Does anyone know how to do this/is it possible? Code portion is below.

   if (reading == 0);
                 {    
                     pourtime = 0;
                     lasttime = millis();
                  }
    
            if (reading == 1);
                 {
                     pourtime =  millis() - lasttime;
                     lasttime = millis();
                 }
       totaltime = pourtime + totaltime;  

             }

What sensor are you using to detect if the tap is open or not? Interrupts might be more appropriate, then you can set flags capture current millis() in your ISR. Say “open” means a rising edge, you could do something like this (you will need to use setup to set your pinMode and attach your interrupt but you get the point).


volatile bool tapOpen;
uint32_t runTapTime;
uint16_t totalTapTime;
//might need to use a float depending on the level of accuracy desired and 
//you can probably use a smaller int like uint16_t depending on how long you 
//expect the tap to be open 16_t is max 65535

loop() {
if (tapOpen && runTapTime == 0){
  runTapTime = millis();
  }
if (!tapOpen && runTapTime != 0){
  totalTapTime = (millis() - runTapTime)/1000;
  runTapTime = 0;
  }
}
myISR(){
if (pinReadFast(tapPin) == HIGH){
  tapOpen = TRUE;
  }
if (pinReadFast(tapPin) == LOW){
 tapOpen = FALSE;
 }
}

Not tested but I think this might be the right approach, if not I am sure one of the smarter folks will provide helpful corrections.

My guess would be - since you don’t show your full code - that your lasttime is a local variable which will lose its value each time you drop out of loop()
You need to use a global variable (as @LukeUSMC shows in his code) or make it static.

1 Like