lewiskell
Published © GPL3+

HC-SR04 Ultrasonic Sensor with LED feedback

A project utilising the HC-SR04 ultrasonic sensor with an RGB LED that fades from green to red as an object gets closer to the sensor.

BeginnerFull instructions provided1,308
HC-SR04 Ultrasonic Sensor with LED feedback

Things used in this project

Hardware components

Arduino Leonardo
Arduino Leonardo
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1

Story

Read more

Schematics

HC-SR04 wiring diagram

Code

HC-SR04 Code

Arduino
#define echoPin 8 // echo pin connected to pin 8 
#define trigPin 9 // trig pin connected to pin 9 
#define RED 5 // red led connected to pwm pin 5
#define GREEN 6 // green led connected to pwm pin 6 

int time;
int dist; 
const int MAX_DIST = 400; // Anything over 20 cm (120us pulse) is "out of range"
char outputValue; //8bit 0 to 255

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  Serial.begin(9600);//start serial monitor
}

void loop() {
  // trigger sensor for 10us pulse
  digitalWrite(trigPin, LOW); //reset trig condition 
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH); // set trig HIGH for 10 us
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW); // return to LOW
  
  // read echo pin, output in us
  time = pulseIn(echoPin, HIGH);
  
  // Calculate distance in cm
  dist = time * 0.0343 / 2; // time * speed of sound through air, divided by 2 (pulse is there and back)
  outputValue = map(dist, 0, MAX_DIST, 0, 255); //map int to 8 char 
  
  Serial.print("Distance: ");//Prints distance in serial monitor
  Serial.print(dist);
  Serial.println(" cm");
  
  if (dist < MAX_DIST){
    analogWrite(RED, outputValue); // more red when close
    analogWrite(GREEN, 255 - outputValue); // more green when far away
  }

  else{
    analogWrite(RED, 255);
    analogWrite(GREEN, 255); 
  }

}

Credits

lewiskell
0 projects • 2 followers

Comments