bool x = 0; //holds one of two values, true or false int relayPin = 2; //defines PIN 2 as relay const int trigPin = 9; //defines PIN 9 as trigPin of Ultrasonic sensor const int echoPin = 10; //defines PIN 10 as echoPin of Ultrasonic sensor long duration; //defines a variable int distance; //defines a variable void setup() { pinMode(trigPin, OUTPUT); //sets trigPin as OUTPUT pinMode(echoPin, INPUT); //sets echoPin as INPUT pinMode(relayPin, OUTPUT); //sets relayPin as OUTPUT Serial.begin(9600); //starts the Serial Communication } void loop() { digitalWrite(trigPin, LOW); // Clears the trigPin delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds duration = pulseIn(echoPin, HIGH); distance = duration * 0.034 / 2; // Calculating the distance Serial.print("Distance: "); // Prints the distance on the Serial Monitor Serial.println(distance); // The minimum distance needed to activate the switch if (distance < 10) { x = !x; if (x == 0) { digitalWrite(relayPin, HIGH); // ON the Light Serial.println("Light is OFF"); //prints light is OFF } } if (x == 1) { digitalWrite(relayPin, LOW); // OFF the Light Serial.println("Light is ON"); //prints light is ON } delay(500); }