0%

A Distance Sensor Demo For Arduino

Distance sensor can be very useful in some conditons, such as obstacles detecting and avoiding. By using arduino, it’s very easy for us to use distance sensor. This demo show us a simple example to use distance sensor. For better display, we will use LCD1602 to show the distance. It’s modified from example in arduino.

Supplies

  • Arduino uno R3
  • HC-SR04
  • Breadboard
  • LCD1602
  • Red LED
  • Spotter
  • Two 100 Ohm resistance
  • some DuPont lines

Step 1 Design and connect circuit

Browsering internet, it’s easy to find instructions of HC-SR04 and LCD1602. And there are so many libraries for us in arduino. In our circuit, arduino digital pin 2, 3, 4, 5, 11 and 12 are used for LCD1602 while digital pin 7 and 8 are for HC-SR04. LED uses digital pin 13. Finally, following is our circuits.

Step2 Code

As we said before, our program is based on libraries. So it’s simple to write code. Later I will display complete code.

Outside the loop, we define a function readUltrasonicDistance used for HC-SR04. Calling this readUltrasonicDistance, we get distance in centimeter. Inside the function setup, we initialize a LCD1604. In the loop, we get distance in centimeter by calling function readUltrasonicDistance. Then we clear LCD screen and print some characters and distance we just got. Finally, we turn on the LED if distance less than 90cm, or turn off the LED if not less than 90cm.

Here shows complete code.

distanceDemo.cview raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int cm = 0;

long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
int LED = 13;
void setup()
{
Serial.begin(9600);
lcd.begin(16, 2);
lcd.print("DistanceSensor:");
pinMode(LED,OUTPUT);
}

void loop()
{
// measure the ping time in cm
cm = 0.01723 * readUltrasonicDistance(7, 8);
// convert to inches by dividing by 2.54
Serial.print(cm);
Serial.println("cm");
lcd.clear();
lcd.print("DistanceSensor:");
lcd.setCursor(0, 1);
lcd.print(cm);
lcd.print("cm");
if (cm < 90) {
digitalWrite(LED, HIGH);
delay(1000);
} else {
digitalWrite(LED, LOW);
delay(500); // Wait for 100 millisecond(s)
}
}

Summary

In this post, we show a demo to use distance sensor HC-SR04 and LCD1602. It’s a good example to use the sensor. Also, there are many possible usages.