// The Servo library comes with the IDE #include // The rain board's AO (analog) output const int RAIN_PIN = A0; // The board's VCC comes from this pin: // on only while measuring, so the plate // does not corrode (an analog pin works // as a digital output too) const int RAIN_POWER = A1; const int BUZZER_PIN = 8; // The servo's orange (signal) wire const int SERVO_PIN = 9; // The window's open and closed angles: // swap them if the arm is fitted the // other way round const int OPEN_ANGLE = 90; const int CLOSED_ANGLE = 0; // Wetness above this percentage is rain const int RAIN_ON = 30; // Below this percentage counts as dry const int DRY_BELOW = 10; // Dry this long, the window opens again // (make it 10-15 min for a real one) const unsigned long REOPEN_AFTER = 60000; // Time between readings (ms) const unsigned long MEASURE_EVERY = 1000; // The servo turns 1 degree, then waits // this long: the window closes gently // (ms) const unsigned long STEP_TIME = 15; Servo window; int angle = OPEN_ANGLE; int target = OPEN_ANGLE; bool raining = false; unsigned long dryStart = 0; unsigned long lastMeasure = 0; unsigned long lastStep = 0; // How wet the plate is: 0 dry, 100 soaked int readWetness() { digitalWrite(RAIN_POWER, HIGH); delay(10); int value = analogRead(RAIN_PIN); digitalWrite(RAIN_POWER, LOW); // A dry plate reads close to 1023 return (1023L - value) * 100 / 1023; } // Rain warning: ding-dong three times void rainChime() { for (int i = 0; i < 3; i++) { tone(BUZZER_PIN, 1200, 150); delay(200); tone(BUZZER_PIN, 900, 250); delay(450); } } void setup() { pinMode(RAIN_POWER, OUTPUT); Serial.begin(9600); // Raining at start: the window starts // closed if (readWetness() >= RAIN_ON) { raining = true; angle = CLOSED_ANGLE; target = CLOSED_ANGLE; } window.attach(SERVO_PIN); window.write(angle); Serial.println(raining ? "Raining: window closed." : "Ready: window open."); } void loop() { unsigned long now = millis(); if (now - lastMeasure >= MEASURE_EVERY) { lastMeasure = now; int wet = readWetness(); Serial.print("Wetness: "); Serial.print(wet); if (!raining && wet >= RAIN_ON) { raining = true; dryStart = 0; Serial.println("% | Rain! Closing the window."); rainChime(); target = CLOSED_ANGLE; } else if (raining && wet < DRY_BELOW) { // Drying time: starts over if it // gets wet again if (dryStart == 0) dryStart = now; unsigned long dry = now - dryStart; if (dry >= REOPEN_AFTER) { raining = false; Serial.println("% | Dry again, opening the window."); tone(BUZZER_PIN, 1500, 100); target = OPEN_ANGLE; } else { Serial.print("% | Window opens in "); Serial.print((REOPEN_AFTER - dry) / 1000); Serial.println(" s."); } } else { if (raining) dryStart = 0; Serial.println(raining ? "% | Raining, window closed." : "% | No rain, window open."); } } // The window goes to the target angle // one step at a time if (angle != target && now - lastStep >= STEP_TIME) { lastStep = now; angle += angle < target ? 1 : -1; window.write(angle); } }