Sunday, September 6, 2015

Arduino Ultrasonic Sensor HC-SR04

Hi guys!! Today I am going to show you how to use HC-SR04 ultrasonic sensor. First check out my video!





Yes, it's working!(As always).Now here is list of the parts.

-Arduino
-Led's
-Buzzer
-HC-SR04 Sensor
-Jumper Wires

And here is our schematic


The working principle of this sensor

There is one microphone and one little speaker in this sensor. The speaker sends 40MHz sound waves .If there is an object the waves hits the object then the microphone collects that waves which returned.

Did somebody said code?


#define triggerPin 3
#define echoPin 2
#define buzzerPin 4
#define red 5
#define yellow 6
#define green 7

int maxDistance = 200;
int minDistance = 3;
long microsecondTime, cmDistance;


void setup() {
 Serial.begin(9600);
 pinMode(triggerPin, OUTPUT);
 pinMode(buzzerPin, OUTPUT);
 pinMode(echoPin, INPUT);
 pinMode(red, OUTPUT);
 pinMode(yellow, OUTPUT);
 pinMode(green, OUTPUT); 
}

void loop() {
  digitalWrite(triggerPin,LOW);
  delayMicroseconds(2);
  
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10);
  microsecondTime = pulseIn(echoPin, HIGH);
  cmDistance = microsecondTime/58.3;
          Serial.print(cmDistance);
        Serial.println(" cm");

  if(cmDistance >= maxDistance)
  {
    Serial.println("Too Far >200cm");
    digitalWrite(buzzerPin, LOW);
    }
    else if(cmDistance <=minDistance)
    {
      Serial.println("Too Close < 3cm");
      digitalWrite(buzzerPin, HIGH);
      digitalWrite(red, HIGH);
      digitalWrite(yellow, LOW);
      digitalWrite(green, LOW);
      }
      else if(cmDistance>100)
      {
      digitalWrite(red, LOW);
      digitalWrite(yellow, LOW);
      digitalWrite(green, HIGH);
      digitalWrite(buzzerPin, LOW);
        }
        else if(cmDistance<30)
        {
      digitalWrite(red, LOW);
      digitalWrite(yellow, HIGH);
      digitalWrite(green, LOW);
      digitalWrite(buzzerPin, LOW);
          }
      delay(50);
      }

----------------------------
You can ask about codes,blog and other things in the comment section.^-^Thanks for reading.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...