typestar

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

  1. DRY arms the pump; only WET, lower, releases it.
  2. The watering flag holds the decision between readings.
  3. One flag, two ifs: the classic thermostat pattern.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Analog, step 9 of 27 in Language basics.

← Previous Next →