70 lines
1.1 KiB
C
70 lines
1.1 KiB
C
|
#define SENSOR_PIN A3
|
||
|
#define RELAY_PIN 3
|
||
|
|
||
|
#define SENSOR_SAMPLE_COUNT 50
|
||
|
#define SENSOR_THRESHOLD 50
|
||
|
#define RELAY_SHUTOFF_DELAY 5000
|
||
|
|
||
|
|
||
|
bool RELAY_STATE = HIGH;
|
||
|
int INDEX = 0;
|
||
|
int SAMPLES[SENSOR_SAMPLE_COUNT] = {0};
|
||
|
|
||
|
|
||
|
int getMaxIntFromArray(int *arr, int len)
|
||
|
{
|
||
|
int maxValue = 0;
|
||
|
for (int i = 0; i < len; i++)
|
||
|
{
|
||
|
if (arr[i] > maxValue)
|
||
|
{
|
||
|
maxValue = arr[i];
|
||
|
}
|
||
|
}
|
||
|
return maxValue;
|
||
|
}
|
||
|
|
||
|
|
||
|
int getSensorValue()
|
||
|
{
|
||
|
for (int i = 0; i < SENSOR_SAMPLE_COUNT; i++)
|
||
|
{
|
||
|
INDEX = (INDEX + 1) % SENSOR_SAMPLE_COUNT;
|
||
|
SAMPLES[INDEX] = abs(analogRead(SENSOR_PIN) - 512);
|
||
|
delay(10);
|
||
|
}
|
||
|
return getMaxIntFromArray(SAMPLES, SENSOR_SAMPLE_COUNT);
|
||
|
}
|
||
|
|
||
|
|
||
|
void setup()
|
||
|
{
|
||
|
pinMode(RELAY_PIN, OUTPUT);
|
||
|
digitalWrite(RELAY_PIN, HIGH);
|
||
|
}
|
||
|
|
||
|
|
||
|
void loop()
|
||
|
{
|
||
|
int sensorValue = getSensorValue();
|
||
|
if (sensorValue < SENSOR_THRESHOLD)
|
||
|
{
|
||
|
if (RELAY_STATE == LOW)
|
||
|
{
|
||
|
delay(RELAY_SHUTOFF_DELAY);
|
||
|
sensorValue = getSensorValue();
|
||
|
}
|
||
|
|
||
|
if (sensorValue < SENSOR_THRESHOLD)
|
||
|
{
|
||
|
// Vacuum off.
|
||
|
RELAY_STATE = HIGH;
|
||
|
}
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
// Vacuum on.
|
||
|
RELAY_STATE = LOW;
|
||
|
}
|
||
|
digitalWrite(RELAY_PIN, RELAY_STATE);
|
||
|
}
|