Valve Control

Valve Control

animation
actuators

Valve Control

Solenoid valves control fluid flow in irrigation, HVAC, and industrial systems.

#define VALVE_PIN 25
#define FLOW_SENSOR_PIN 34

void setup() {
  pinMode(VALVE_PIN, OUTPUT);
  pinMode(FLOW_SENSOR_PIN, INPUT);
  digitalWrite(VALVE_PIN, LOW);  // Valve closed
}

// Water for specified duration
void water(int seconds) {
  Serial.print("Watering for ");
  Serial.print(seconds);
  Serial.println(" seconds");

  digitalWrite(VALVE_PIN, HIGH);  // Open valve
  delay(seconds * 1000);
  digitalWrite(VALVE_PIN, LOW);   // Close valve

  Serial.println("Watering complete");
}

// Water until flow sensor detects specified volume
void waterVolume(float liters) {
  float flowRate;  // Liters per minute
  float totalVolume = 0;

  digitalWrite(VALVE_PIN, HIGH);

  while (totalVolume < liters) {
    // Read flow sensor (pulse counting)
    // This is simplified - real implementation needs interrupt
    flowRate = readFlowSensor();
    totalVolume += flowRate / 60.0;  // Convert to liters/second
    delay(1000);

    Serial.print("Volume: ");
    Serial.print(totalVolume);
    Serial.print(" / ");
    Serial.print(liters);
    Serial.println(" L");
  }

  digitalWrite(VALVE_PIN, LOW);
}

Back to the chapter