Introduction: Arduino Ultrasonic Sensor

Picture of Arduino Ultrasonic Sensor

this is example to use ultrasonic sensor( HC-SR04 ) in arduino.

Step 1: Part List :

  1. Arduino UNO R3 Board
  2. HC-SR04 Ultrasonic Sensor
  3. Red LED
  4. Green LED
  5. 560 ohm (Green, Blue, Brown, Gold) Resistors
  6. HalfBreadboard
  7. wires

Step 2: Connect the Components

Picture of Connect the Components

Step 3: Write Your Code

#define trigPin 13

#define echoPin 12

#define greenLED 11

#define redLED 10

void setup() {

Serial.begin (9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

pinMode(greenLED, OUTPUT);

pinMode(redLED, OUTPUT);

}

void loop() {

long duration, distance;

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

digitalWrite(trigPin, HIGH);

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(greenLED,HIGH); // When the Red condition is met, the Green LED should turn off digitalWrite(redLED,LOW);

} else {

digitalWrite(greenLED,LOW); digitalWrite(redLED,HIGH);

}

if (distance >= 200 || distance <= 0){

Serial.println("Out of range");

} else {

Serial.print(distance); Serial.println(" cm");

} delay(500);

}

Step 4: Upload and Run

Picture of Upload and Run

Comments

Lintang_Wisesa made it! (author)2016-04-04

nice bro..

bang @lintang_wisesa base camp nya dimana nih bang? siapa tau bisa main2 nyuri ilmu dari bang lintang

di Solo ^_^

MGO_Count made it! (author)2016-04-13

Thanks!

I turned on the serial prompt and get feedback!

About This Instructable

2,371views

21favorites

License:

Add instructable to: