2016-03-17 00:00:00
#define trigPin 4
#define echoPin 5
#define irPin 3
#define warnPin 2
int count = 0;
int countThreshold = 5;
int warnTime = 200;
int postureDistance = 20; //cm
int maxDistance = 3000;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(irPin, INPUT);
pinMode(warnPin, OUTPUT);
}
void loop() {
long duration, distance;
// for ultra sound distance sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// head position
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
Serial.print(distance);
Serial.println(" cm");
// ir 0 means object detected, so someone is sitting
int ir = !digitalRead(irPin);
digitalWrite(13, ir);
Serial.print("ir: ");
Serial.println(ir);
if (ir && distance > postureDistance && distance < maxDistance) {
// accumulate count when person detected
count++;
} else {
// cool down
count = 0;
}
Serial.print("count:");
Serial.println(count);
delay(1000);
if ( count >= countThreshold ) {
// need to warn you
digitalWrite(warnPin, HIGH);
Serial.println("###########Warning!!#############");
count = 0;
delay(warnTime);
digitalWrite(warnPin, LOW);
} else {
digitalWrite(warnPin, LOW);
}
}