Hysteresis in Arduino
Two thresholds keep the pump from chattering at the line.
// Hysteresis: two thresholds keep the pump from chattering.
const int SOIL_PIN = A0;
const int PUMP_PIN = 7;
const int DRY = 700;
const int WET = 500;
bool watering = false;
void setup() {
pinMode(PUMP_PIN, OUTPUT);
}
void loop() {
int soil = analogRead(SOIL_PIN);
if (!watering && soil > DRY) watering = true;
if (watering && soil < WET) watering = false;
digitalWrite(PUMP_PIN, watering ? HIGH : LOW);
delay(200);
}
How it works
DRYarms the pump; onlyWET, lower, releases it.- The
wateringflag holds the decision between readings. - One flag, two ifs: the classic thermostat pattern.
Keywords and builtins used here
HIGHLOWOUTPUTanalogReadboolconstdelaydigitalWritefalseifintlooppinModesetuptruevoid
The run, in numbers
- Lines
- 19
- Characters to type
- 421
- Tokens
- 100
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 92 seconds.
Step 3 of 3 in Analog, step 9 of 27 in Language basics.