Skip to content

Changing Color Lamp with IR Distance Sensor

This time, I had fun exploring RGB LED. Since I’m more attracted to colors than sounds, I wanted to explore LED more. I wanted to make a color changing lamp using distance sensor.

I was struggling with the RGB LED at first. When I bought it, I didn’t notice the difference between common anode and cathode. I looked up on Google, it says that the common anode LED shares an anode. So, instead of connecting it to ground, I needed to connect it to 5V source. Meanwhile, I’m still confused, so it doesn’t really connect to ground? The Red, Green, and Blue pins connect to digital output pins, and the anode connects to +5V source, how does it become a circuit?

Then I also struggled how to combine colours using this RGB LED common anode. I figured out RGB LED common anode it’s not the same as common cathode when turning on each color. In common cathode, to turn on the Red LED we need to use HIGH on Red pin. However, in common anode, we use LOW on Red pin to turn on Red LED.

Here’s my circuit sketch.

Circuit Sketch

And here’s the circuit IRL.

Circuit

Here’s my code.


onst int redPin = 3; // Red pin output
const int greenPin = 5; // Green pin output
const int bluePin = 6; // Blue pin output

int distance; // distance variable
int mapLed; // color variable

void setup() {
Serial.begin(9600);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}

void loop() {
distance = analogRead(A0);

distance = constrain(distance, 100, 700); // restrain the distance, only from 100-700

mapLed = map(distance, 100, 600, 1, 6); // map the distance to match 6 colors

// changing color based on mapped distance
if (mapLed == 1) { // red color
digitalWrite(redPin, LOW);
digitalWrite(greenPin, HIGH);
digitalWrite(bluePin, HIGH);
} else if (mapLed == 2) { // magenta color
digitalWrite(greenPin, HIGH);
digitalWrite(redPin, LOW);
digitalWrite(bluePin, LOW);
} else if (mapLed == 3) { // blue color
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, HIGH);
digitalWrite(bluePin, LOW);
} else if (mapLed == 4) { // cyan color
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, LOW);
digitalWrite(bluePin, LOW);
} else if (mapLed == 5) { // green color
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, LOW);
digitalWrite(bluePin, HIGH);
} else { // yellow color
digitalWrite(redPin, LOW);
digitalWrite(greenPin, LOW);
digitalWrite(bluePin, HIGH);
}

Serial.println(mapLed);
delay(200);
}

Since I wanted to change the color at certain distance, I used map() to map the actual distance into 6 color range.

Here’s my final result.

RGB LED & IR Distance Sensor: Changing Color Lamp from Vidia Anindhita on Vimeo.

 

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *