Flow sensor library

canada7764, it seems I left out the code for the ISR for the water sensor!! Here is the full code that compiles correctly. The Serial.print code can be removed. I added it for simpler debugging.

/*
    Water flow sensor test sketch

*/


unsigned long oldTime = 0;
volatile unsigned int WaterPulseCount = 0;

// conversion from pps to litres, plastic sensor (485 for metal)
const float pulsesPerLiter = 450;

// Spark Digial Pin D2
#define WATER_SENSOR_PIN	D2		// Water sensor using pin D2

// Define Spark variable - not sure "float" type works so define as INT
// so decimal is shifted left with * 100 (so xx.yy becomes xxyy)
int liters = 0;


//-----------------------------------------------------------------------------
// Water Sensor interrupts
//-----------------------------------------------------------------------------
void WaterPulseCounter(void)
{
	// Increment the water pulse counter
	detachInterrupt (WATER_SENSOR_PIN) ;
	++WaterPulseCount;
	attachInterrupt(WATER_SENSOR_PIN, WaterPulseCounter, FALLING) ;
}


void setup()
{
  Serial.begin(115200);
  
  Spark.variable("liters",&liters, INT);

  // Set Digital pin WATER_SENSOR_PINT to INPUT mode and set
  // interrupt vector (water flow sensor) for FALLING edge interrupt
  pinMode(WATER_SENSOR_PIN, INPUT_PULLUP);
  attachInterrupt(WATER_SENSOR_PIN, WaterPulseCounter, FALLING) ;
}


void loop()
{
  unsigned long t;

  t = (millis() - oldTime);
  if(t >= 1000)    			// Only process counters once per second
  {
    //Read water sensor pulse count and process
    if (WaterPulseCount != 0)		// Do nothing if water is not flowing!
    {
    detachInterrupt (WATER_SENSOR_PIN);	// Disable water flow interrupt to read value
    //Calculate litres and adjust for 1 sec offset, if any
    liters = (WaterPulseCount / pulsesPerLiter) * (t / 1000) *100;
    oldTime = millis();				// Reset base delay time
    WaterPulseCount = 0;			// Reset the water pulse counter
    attachInterrupt(WATER_SENSOR_PIN, WaterPulseCounter, FALLING);
    Serial.print("WaterPulseCount= ");
    Serial.print(WaterPulseCount);
    Serial.print(", liters= ");
    Serial.println(liters);
    }
  }
}

Cheers!

1 Like