Arduino Sketch for Distance Measurement through Ultrasonic Sensor and Controlling the brightness of LED with Distance. (Using PWM)

A program that allows the user to control the Brightness of the LED . When the program is started, the Ultrasonic sensor will measure the distance. The user should open the serial monitor to communicate with the Arduino. Now this Distance is the Input for the LED. The brightness of the LED will be maximum when the Object is Closest and will be Minimum when the Object is Far Away. Pulse Width Modulation concept will be used. Map function will also be used.

Code:-


const int trigPin=13;
const int echoPin=12;
long duration; 
int distance;
int led=11;
int x;


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

void loop() 
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(20);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(20); 
  digitalWrite(trigPin, LOW);
  
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  x = map(distance , 5, 140, 255, 0);
  Serial.println(distance);
  analogWrite(led, x);
  delay(10);

}

Comments

Post a Comment

Popular Posts