Arduino Ultrasonic Sensor

Published

Introduction: 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

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

2 People Made This Project!

Recommendations

  • Casting Contest

    Casting Contest
  • Planter Challenge

    Planter Challenge
  • Oil Contest

    Oil Contest
user

We have a be nice policy.
Please be positive and constructive.

Tips

Questions

Comments