Guest User

Arduino Wireless Proximity-Based Power Switch

a guest
Jun 18th, 2013
260
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. int trigPin = 13;
  2. int echoPin = 12;
  3. int switchPin = 8;
  4.  
  5. int maxDist = 200;// 3m
  6. int cutoff = 0;
  7. int absenseCounter = 0;
  8. int timeout = 10;
  9. int cycleTime = 1500; //ms between checks
  10. boolean active = false;
  11.  
  12. void setup() {
  13.   Serial.begin (9600);
  14.   pinMode(trigPin, OUTPUT);
  15.   pinMode(echoPin, INPUT);
  16.   pinMode(switchPin, OUTPUT);
  17. }
  18.  
  19. void loop() {
  20.  
  21.   cutoff = map(analogRead(A5),0,1023,0,maxDist);
  22.  
  23.   long duration, distance;
  24.   digitalWrite(trigPin, LOW);
  25.   delayMicroseconds(2);
  26.   digitalWrite(trigPin, HIGH);
  27.   delayMicroseconds(10);
  28.   digitalWrite(trigPin, LOW);
  29.   duration = pulseIn(echoPin, HIGH);
  30.   distance = (duration/2) / 29.1;
  31.  
  32.   Serial.print("(");
  33.   Serial.print(cutoff);
  34.   Serial.print(") ");
  35.   Serial.print(distance);
  36.   Serial.print(" cm");
  37.  
  38.   if (distance <= cutoff) {
  39.     if( !active) {
  40.       trigger();
  41.       active = true;
  42.     }
  43.     absenseCounter = 0;
  44.     Serial.println("");
  45.   }else if (distance > cutoff || distance <= 0){
  46.     Serial.println(" (Out of range)");
  47.     if(++absenseCounter >= timeout && active) {
  48.       trigger();
  49.       active = false;
  50.     }
  51.   }
  52.   delay(cycleTime);
  53. }
  54.  
  55. void trigger() {
  56.   digitalWrite(switchPin,HIGH);
  57.   delay(20);
  58.   digitalWrite(switchPin,LOW);
  59.  
  60.   Serial.println("TRIGGERING");
  61. }
RAW Paste Data