Flow sensor library

canada7764,

I got the code working and running solidly with a few caveats. First, some of my code must have been written WAY too late at night so I fixed my own bugs. Seconds, the Spark Cloud API is not quite ready for prime time. That is, the FLOAT and DOUBLE types are not parsed correctly by the Cloud API so a GET request will get garbage. I ended up using a FLOAT for liters and then converted it to a STRING for the Spark.variable. Another oddity I experienced is that I could not use digital pin D2 as it would not work! I changed over to D3 and all was fine so I have to do some digging on that issue. So, here is the code for your enjoyment:

/*
    Water flow sensor test sketch

*/


unsigned long oldTime;
volatile unsigned int WaterPulseCount = 0;

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

// Spark Digial Pin D3 (D2 did not work)
#define WATER_SENSOR_PIN	D3	// Water sensor digital pin

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

//-----------------------------------------------------------------------------
// 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(9600);
  
  Spark.variable("litersS", &liters_S, STRING);

  // 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);
  attachInterrupt(WATER_SENSOR_PIN, WaterPulseCounter, FALLING) ;
  oldTime = millis();
}


void loop()
{
  unsigned long t;
  static unsigned int pc;

  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);
    oldTime = millis();				// Reset base delay time
    pc = WaterPulseCount;
    WaterPulseCount = 0;			// Reset the water pulse counter
    attachInterrupt(WATER_SENSOR_PIN, WaterPulseCounter, FALLING);

    sprintf(liters_S, "%4.3f", liters);
    
    Serial.print("WaterPulseCount= ");
    Serial.print(pc);
    Serial.print(", liters= ");
    Serial.print(liters,3);
    Serial.print(", liters_S= ");
    Serial.println(liters_S);
    }
  }
}

:smile: