1
0
Fork 0

Update 'main.c'

This commit is contained in:
Jack Hadrill 2020-06-25 20:33:03 +00:00
parent 3f38258a20
commit 1e68eac6f1
1 changed files with 12 additions and 19 deletions

31
main.c
View File

@ -6,34 +6,24 @@
#define RELAY_SHUTOFF_DELAY 5000
// Relay is active low, so HIGH disables the output.
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;
}
// Get the maximum sensor value over 50 readings.
int getSensorValue()
{
int maxValue = 0;
for (int i = 0; i < SENSOR_SAMPLE_COUNT; i++)
{
INDEX = (INDEX + 1) % SENSOR_SAMPLE_COUNT;
SAMPLES[INDEX] = abs(analogRead(SENSOR_PIN) - 512);
int currentValue = abs(analogRead(SENSOR_PIN) - 512);
if (currentValue > maxValue)
{
maxValue = currentValue;
}
delay(10);
}
return getMaxIntFromArray(SAMPLES, SENSOR_SAMPLE_COUNT);
return maxValue;
}
@ -49,12 +39,14 @@ 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.
@ -66,5 +58,6 @@ void loop()
// Vacuum on.
RELAY_STATE = LOW;
}
digitalWrite(RELAY_PIN, RELAY_STATE);
}