Rayan kiwan
Created August 9, 2022 © MPL-2.0

RGB LED Based on Distance

Make a circuit that show how far away something is by either shinning a red, green, or blue LED

IntermediateFull instructions provided25
RGB LED Based on Distance

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
LED (generic)
LED (generic)
×1
5 mm LED: Green
5 mm LED: Green
×1
LED, Blue
LED, Blue
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
Jumper wires (generic)
Jumper wires (generic)
×1
Resistor 220 ohm
Resistor 220 ohm
×3
Breadboard (generic)
Breadboard (generic)
×1
Buzzer
Buzzer
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

RGB LED Based on Distance

Code

RGB LED Based on Distance

Arduino
int distance = 0;

int cm = 0;

long readUltrasonicDistance(int triggerPin, int echoPin)
{
  pinMode(triggerPin, OUTPUT);  // Clear the trigger
  digitalWrite(triggerPin, LOW);
  delayMicroseconds(2);
  // Sets the trigger pin to HIGH state for 10 microseconds
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(triggerPin, LOW);
  pinMode(echoPin, INPUT);
  // Reads the echo pin, and returns the sound wave travel time in microseconds
  return pulseIn(echoPin, HIGH);
}

void setup()
{
  Serial.begin(9600);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
}

void loop()
{
  // Ultrasonic sensor with three LED and buzzer
  distance = 330;
  // Distance in cm
  cm = 0.01723 * readUltrasonicDistance(6, 7);
  Serial.print(cm);
  Serial.println("cm");
  // Distance more than 4 cm
  if (cm > distance) {
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
  } else {
    // Distance between 4 cm and 3 cm
    if (cm > 3) {
      digitalWrite(2, LOW);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
    } else {
      // Distance between 3 cm and 2cmcm
      if (cm > 2) {
        digitalWrite(2, LOW);
        digitalWrite(3, HIGH);
        digitalWrite(4, LOW);
      } else {
        // Distance between 2cm and 1cm
        if (cm > 1) {
          digitalWrite(2, HIGH);
          digitalWrite(3, LOW);
          digitalWrite(4, LOW);
        } else {
          // Distance below 1cm
          digitalWrite(2, LOW);
          digitalWrite(3, LOW);
          digitalWrite(4, LOW);
        }
      }
    }
  }
  delay(100); // Wait for 100 millisecond(s)
}

Credits

Rayan kiwan
36 projects • 2 followers
Contact

Comments

Please log in or sign up to comment.