I want to create an Arduino based auto flush using 3 LEDs and a servo motor. The problem statement is:
When the person is detected the first LED should glow and after a second should go low.
Till the person is standing the second LED should get high.
When the person leaves the second LED should go low and the 3 LED should get high and then go low.
I am stuck at the second part.
int trigPin = 12; //triggor pin
int echoPin = 11; // echo pin
long timeperiod;
float cm, distance;
int r = 10, g = 9, rg = 8;
int PreparingToFlush = 0;
void setup()
{
Serial.begin(9600); //serial port communication
pinMode(trigPin, OUTPUT); // defining pinmode for trig
pinMode(echoPin, INPUT); // defining pinmode for echo pin
pinMode(r, OUTPUT);
pinMode(g, OUTPUT);
pinMode(rg, OUTPUT);
}
void loop()
{
digitalWrite(trigPin, LOW); // sending 10 us pulse
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(echoPin, LOW);
timeperiod = pulseIn(echoPin, HIGH); // integrating pulse
cm = (timeperiod / 2) / 29.1;
distance = cm;
Serial.print(" distance in centimeters=");
Serial.println(cm);
delay(1000);
/* while(distance<=20)
{
pinMode(r,HIGH); //person detected
delay(1000);
pinMode(r,LOW);
delay(1000);
pinMode(rg,HIGH); //wait
delay(1000); //Want delay such that till the person is standing in range of 20cm rg should be high
pinMode(rg,LOW);
delay(1000);
pinMode(g,HIGH);// ready to flush
delay(1000);
pinMode(g,LOW);
delay(1000);
}
while(distance<=20)
{
pinMode(r,HIGH); //person detected
delay(1000);
pinMode(r,LOW);
delay(1000);
pinMode(rg,HIGH);
}
pinMode(rg,LOW);
delay(1000);
pinMode(g,HIGH);
delay(1000);
pinMode(g,LOW);
*/
if (distance < 100) { //if distance sensor detects someone
Serial.println("person detected");
delay(2000); // wait
digitalWrite(r, HIGH);
delay(2000);
digitalWrite(r, LOW);
//sensor=analogRead(sensorPin);
if (distance < 100) { // check again to make sure someone is actually there
Serial.println("again check");
digitalWrite(g, HIGH);
PreparingToFlush = 1;
}
}
if (PreparingToFlush == 1) { //if a person has been detected
if (distance > 100) { // if the person has now left
digitalWrite(g, LOW);
delay(2000);
digitalWrite(rg, HIGH);
delay(2000);
digitalWrite(rg, LOW);
Serial.println("left");
//servo1.write(175); FLUSH
delay(5000);
//servo1.write(3);
delay(1000);
PreparingToFlush = 0; //reset the trigger
}
}
delay(10);
}
You can solve your task by a simple state machine.
1. Define variable "State", it would hold one of the states "wait" (waiting while somebody gets near), "near" (when person moved in to the sensor), "out" (when person moved out), "flush" (when flush is in progress).
2. Create some variable to monitor time passed from some event
3. Move from one state to another when some conditions are satisfied.
Initial:
In the loop: