1
0
Fork 0
WorkSwitch/main.c

63 lines
1.2 KiB
C
Raw Normal View History

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