Study Lamp

In this assignment, I decided to make study lamp which can be turned on or off and have adjustable brightness. To implement this, I decided to make an LED respond to how close I am to it. The LED is turned on using the switch and its brightness is varied using the ultrasonic sensor. I calculate the distance away from the ultrasonic sensor in centimeters using the time it takes for the ultrasonic sensor to read the trigger pulses.  Now, the closer I am to the ultrasonic sensor, the brighter the LED becomes if it is switched on. So, when I am studying, I can change the brightness levels depending on how close I sit next to the ultrasonic sensor.

Here is the circuit:

 

Here is the code:

const int trigPin = 3;
const int echoPin = 2;
const int led = 9;
const int buttonInp = 11;

bool run = false;
bool prevButtonState = LOW;

long duration;
int distance;

void setup() {
  pinMode(trigPin, OUTPUT); 
  pinMode(echoPin, INPUT); 
  pinMode(led, OUTPUT); 
  pinMode(buttonInp, INPUT);
  Serial.begin(9600);
}
void loop() {
  byte buttonState  = digitalRead(buttonInp);

  Serial.println(buttonState);

  // check to see if the button is pressed and last time it wasn't
  if (buttonState == HIGH && prevButtonState == LOW) {
    //toggle run
    run = !run;
  }
  // record the current button state for use next time through loop
  prevButtonState = buttonState;
  
  if(run){
    // Clear trigPin
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    
    //Set trigPin to HIGH state for 10 micro seconds
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    
    // Reads the echoPin, returns the sound wave travel time in microseconds
    duration = pulseIn(echoPin, HIGH);
    
    // Calculating the distance
    distance = duration * 0.034 / 2;
    // Serial.println(distance);

    // Adjusting brightness of LED to be distance mapped to 0-255
    int brightness = map(distance, 0, 15, 0, 255);
    brightness = constrain(brightness, 0, 255);
    brightness = 255 - brightness;
    analogWrite(led, brightness);
  }
  else {
    //LED off
    digitalWrite(led, LOW);
  }
}

Here is the final product:

 

Leave a Reply