03 Distance light intensity control

In this circuit, the proximity sensor acts as a regulator for LED bulb. Here -

  • If an object is less than 5cm distance from the sensor, the LED will glow with full intensity

  • If an object is between 5cm to 30cm distance from the sensor, LED will change intensity based on distance

  • If there is no object within 30cm from sensor, LED 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<5){
    // digitalWrite(7,HIGH);
    analogWrite(5, 255);
  }
  else if (distance >=5 && distance <= 30){
    analogWrite(5, bright);
  }
  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 ❤️