63 lines
1.2 KiB
C
63 lines
1.2 KiB
C
#define SENSOR_PIN A3
|
|
#define RELAY_PIN 3
|
|
|
|
#define SENSOR_SAMPLE_COUNT 50
|
|
#define SENSOR_THRESHOLD 50
|
|
#define RELAY_SHUTOFF_DELAY 5000
|
|
|
|
|
|
// Relay is active low, so HIGH disables the output.
|
|
bool RELAY_STATE = HIGH;
|
|
|
|
|
|
// Get the maximum sensor value over 50 readings.
|
|
int getSensorValue()
|
|
{
|
|
int maxValue = 0;
|
|
for (int i = 0; i < SENSOR_SAMPLE_COUNT; i++)
|
|
{
|
|
int currentValue = abs(analogRead(SENSOR_PIN) - 512);
|
|
if (currentValue > maxValue)
|
|
{
|
|
maxValue = currentValue;
|
|
}
|
|
delay(10);
|
|
}
|
|
return maxValue;
|
|
}
|
|
|
|
|
|
void setup()
|
|
{
|
|
pinMode(RELAY_PIN, OUTPUT);
|
|
digitalWrite(RELAY_PIN, HIGH);
|
|
}
|
|
|
|
|
|
void loop()
|
|
{
|
|
int sensorValue = getSensorValue();
|
|
if (sensorValue < SENSOR_THRESHOLD)
|
|
{
|
|
// If the relay is turned on sleep then remeasure sensor value.
|
|
if (RELAY_STATE == LOW)
|
|
{
|
|
delay(RELAY_SHUTOFF_DELAY);
|
|
sensorValue = getSensorValue();
|
|
}
|
|
|
|
// If the sensor value has definitely dropped since the first measurement, then turn the relay off.
|
|
if (sensorValue < SENSOR_THRESHOLD)
|
|
{
|
|
// Vacuum off.
|
|
RELAY_STATE = HIGH;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// Vacuum on.
|
|
RELAY_STATE = LOW;
|
|
}
|
|
|
|
digitalWrite(RELAY_PIN, RELAY_STATE);
|
|
} |