02 Distance light switch

In this circuit, the proximity sensor acts as a switch for LED bulb. Here, if an object is less than 10cm distance from the sensor, the LED will glow, else it will turn off.

Circuit diagram

(credits: https://www.circuito.io/)

Here, you can connect resistor and LED to board directly without breadboard. If you do not have LED, replace 5 with 13 in the code below which will make the on-board LED blink.

Code
const int trigPin = 3;
const int echoPin = 2;

void setup() {
  pinMode(5, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  long duration = pulseIn(echoPin, HIGH);
  float distance = duration * 0.034 / 2; // Convert to centimeters
  float bright = 306 - (distance* 10.2 );

  if (distance<10){
    digitalWrite(5,HIGH);
  }
  else digitalWrite(5,LOW);

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  
  delay(100); 
}

Liked what you saw?

get in touch :)

© 2025 Made with ❤️