Arduino Ultrasonic Sensor

1,874

19

2

Introduction: Arduino Ultrasonic Sensor

Here is the Ultrasonic Sensor device that I created

This device will change the pitch of the buzzer and the amount of LEDs lit up depending on the distance you stand away from it. Enjoy!

Teacher Notes

Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.

Step 1: Step 1: Equipment

- 1 x ultrasonic sensor HC-SR04

- 6 x LED s (2 x green, 2 x red, 2 x yellow)

- 13 x jumper wires

- 1 x buzzer

- 7 x 220 ohm resistors

Step 2: Step 2: Connections

Connect all of the components to look the same as the image above.

Ports 13-8 are the LEDs

Ports 7,6 is the Ultrasonic Sensor

Port 3 is the buzzer

Step 3: Step 3: Code

The final product should work like this ^^ and below is the code.

#define trigPin 7

#define echoPin 6

#define led 13

#define led2 12

#define led3 11

#define led4 10

#define led5 9

#define led6 8

#define buzzer 3

int sound = 250;

void setup() {

Serial.begin (9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

pinMode(led, OUTPUT);

pinMode(led2, OUTPUT);

pinMode(led3, OUTPUT);

pinMode(led4, OUTPUT);

pinMode(led5, OUTPUT);

pinMode(led6, OUTPUT);

pinMode(buzzer, 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) / 49.1;

if (distance <= 50) {

digitalWrite(led, HIGH);

sound = 250;

for (int i=0; i<500; i++) { // generate a 1KHz tone for 1/2 second

digitalWrite(buzzer, HIGH);

delayMicroseconds(500);

digitalWrite(buzzer, LOW);

delayMicroseconds(500);

}

}

else {

digitalWrite(led,LOW);

}

if (distance < 45) {

digitalWrite(led2, HIGH);

sound = 260;

}

else {

digitalWrite(led2, LOW);

}

if (distance < 40) {

digitalWrite(led3, HIGH);

sound = 270;

}

else {

digitalWrite(led3, LOW);

}

if (distance < 35) {

digitalWrite(led4, HIGH);

sound = 280;

}

else {

digitalWrite(led4,LOW);

}

if (distance < 30) {

digitalWrite(led5, HIGH);

sound = 290;

}

else {

digitalWrite(led5,LOW);

}

if (distance < 25) {

digitalWrite(led6, HIGH);

sound = 300;

}

else {

digitalWrite(led6,LOW);

}

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

Serial.println("Out of range");

noTone(buzzer);

}

else {

Serial.print(distance);

Serial.println(" cm");

tone(buzzer, sound);

}

delay(500);

}

1 Person Made This Project!

Recommendations

  • LED Strip Speed Challenge

    LED Strip Speed Challenge
  • Sculpting Challenge

    Sculpting Challenge
  • Clocks Contest

    Clocks Contest

2 Discussions

0
wold630
wold630

4 years ago

Nice! What do you use it for?

0
foneill
foneill

Reply 4 years ago

Hi!

I intended it to be used for sensing if someone walked outside of the door to my bedroom :)