Skip to content

Instantly share code, notes, and snippets.

@MechanicalCoder
Last active April 20, 2016 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MechanicalCoder/a14fa1dabbdf29df71d55f9695198750 to your computer and use it in GitHub Desktop.
Save MechanicalCoder/a14fa1dabbdf29df71d55f9695198750 to your computer and use it in GitHub Desktop.
#define trigPin 13
#define echoPin 12
#define led 11
#define led2 10
#define threshold_distance 10
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
pinMode(led2, OUTPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
// delayMicroseconds(1000);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance < 4) { // This is where the LED On/Off happens
digitalWrite(led,HIGH); // When the Red condition is met, the Green LED should turn off
digitalWrite(led2,LOW);
}
else {
digitalWrite(led,LOW);
digitalWrite(led2,HIGH);
}
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
if(distance < threshold_distance){
print();
}
delay(500);
}
void print(){
Serial.print("Dustbin Full");
Serial.print("\n");
}
@MechanicalCoder
Copy link
Author

Introduction

It is a sample code to work with HC-SR04 Ultrasonic Distance Measuring Module. I am using this for my 'Smart Dustbin' project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment