Project

General

Profile

RE: Water flow sensor ยป watersensor.ino

joostn, 2014-09-12 11:35

 
// arduino built in led:
int LEDPIN = 13;

// connect yellow sensor wire to this pin:
int SENSORPIN = 2;

// output pin: HIGH-Z if no water flowing, 0V is water flowing
int OUTPUTPIN = 3;

// the water is considered flowing if pulses arrive at
// most within this number of microseconds:
unsigned long MAXFLOWPERIOD = 200000;

// after water has started flowing, wait this number of
// microseconds before asserting the output pin:
unsigned long STARTUPDELAY = 1000000;

unsigned long lastFlowSensorToggleTime = 0;
boolean lastFlowSensorToggleTimeValid = false;
int lastSensorPinState;
long lastSensorPeriodMicroSeconds = -1;
boolean waterFlowStartArmed=false;
unsigned long waterFlowStartTime=0;
boolean waterFlowingForSomeTime=false;

void setup() {
// initialize the digital pin as an output.
pinMode(LEDPIN, OUTPUT);
pinMode(OUTPUTPIN, INPUT);
pinMode(SENSORPIN, INPUT_PULLUP);
delay(1);
lastSensorPinState=digitalRead(SENSORPIN);
}

void checkSensorPin()
{
unsigned long now=micros();
int sensorPinState=digitalRead(SENSORPIN);
if(sensorPinState != lastSensorPinState)
{
// sensor activity
lastSensorPinState = sensorPinState;
if(lastFlowSensorToggleTimeValid)
{
lastSensorPeriodMicroSeconds = now - lastFlowSensorToggleTime;
}
lastFlowSensorToggleTime = now;
lastFlowSensorToggleTimeValid = true;
}
else
{
if(lastFlowSensorToggleTimeValid)
{
unsigned long delta = now - lastFlowSensorToggleTime;
if(delta > 1000000)
{
lastFlowSensorToggleTimeValid = false;
lastSensorPeriodMicroSeconds = -1;
}
}
}
}

long getSensorPeriodMicroSeconds()
{
long result = lastSensorPeriodMicroSeconds;
if(result >= 0)
{
unsigned long now=micros();
long currentperiod = now - lastFlowSensorToggleTime;
if(result < currentperiod) result = currentperiod;
}
return result;
}

boolean isWaterFlowingNow()
{
long sensorperiod = getSensorPeriodMicroSeconds();
boolean waterFlowing = ( (sensorperiod >= 0) && (sensorperiod <= MAXFLOWPERIOD) );
return waterFlowing;
}

void checkWaterFlowing()
{
if(isWaterFlowingNow())
{
if(!waterFlowingForSomeTime)
{
unsigned long now=micros();
if(waterFlowStartArmed)
{
unsigned long delta=now - waterFlowStartTime;
if(delta > STARTUPDELAY)
{
waterFlowingForSomeTime = true;
waterFlowStartArmed = false;
}
}
else
{
waterFlowStartTime=now;
waterFlowStartArmed = true;
}
}
}
else
{
waterFlowingForSomeTime=false;
waterFlowStartArmed=false;
}
}

boolean isWaterFlowingForSomeTime()
{
return waterFlowingForSomeTime;
}

void loop() {
checkSensorPin();
checkWaterFlowing();
boolean waterFlowing = isWaterFlowingForSomeTime();
digitalWrite(LEDPIN, waterFlowing? HIGH:LOW);
if(waterFlowing)
{
pinMode(OUTPUTPIN, OUTPUT);
digitalWrite(OUTPUTPIN, LOW);
}
else
{
pinMode(OUTPUTPIN, INPUT);
}
}
    (1-1/1)