Code for automatic room lights

 Arduino code:


long val;

int pos;

const int TRIG_PIN  = 11; 

const int ECHO_PIN  = 12; 

const int RELAY_PIN = 10; 

const int DISTANCE_THRESHOLD = 100; // centimeters


float duration_us, distance_cm;


void setup() {

  Serial.begin (9600);        

  pinMode(TRIG_PIN, OUTPUT);  // set arduino pin to output mode

  pinMode(ECHO_PIN, INPUT);   // set arduino pin to input mode

  pinMode(RELAY_PIN, OUTPUT); // set arduino pin to output mode

}


void loop() {

  digitalWrite(TRIG_PIN, HIGH);

  delayMicroseconds(10);

  digitalWrite(TRIG_PIN, LOW);


  duration_us = pulseIn(ECHO_PIN, HIGH);

  distance_cm = 0.017 * duration_us;


  if(distance_cm < DISTANCE_THRESHOLD && pos == 0)

  {

    digitalWrite(RELAY_PIN, LOW); // turn off Relay

    pos = 1;

    delay(500);

  }

  else if(distance_cm < DISTANCE_THRESHOLD && pos == 1)

    {

    digitalWrite(RELAY_PIN, HIGH);  // turn on Relay

    pos = 0;

    delay(500);

    }

  Serial.print("distance: ");

  Serial.print(distance_cm);

  Serial.println(" cm");


  delay(500);

}

Post a Comment

0 Comments