For any newbies/lurkers: remove the comment on #define DEBUG, and the serial output will give you a look at what a circular buffer looks like in operation.

The buffer is the key to the algorithm. Without it, you'd only be turning off the water *at* the 20-minute mark. With it, the water gets turned off within 30 seconds of the trip point being reached. Now, because our sensitivity is set to 90%, this is 18 minutes of water running. The sketch could be made more sensitive by reducing this, at the cost of possible false positives. It really depends on the cows.

You know - this sort of problem is very amenable to baysean analysis. By getting records of the switch operation, we get prior probabilities for the sensor behaviour when the water thing is working correctly and for when it is stuck. We can then ask, "If the sensor is more than A% on over B time period, what's the probability that the switch is stuck?" Then one asks the question, "for a given time period B, what setting for A will give us no more than a 5% chance per day of getting a false alarm?" Finally, one can ask "what's the optimal A and B that wastes the least water while giving us a false alarm no more than about once every couple of weeks?".

That's the trade-off, of course. Water waste vs. walking out to the cow trough to reset a false alarm. There's no avoiding that.

Now, if we could hook this baby up to a solenoid whose job it was to give the lever a thump with a rubber mallet when it was stuck …