Lesson 35 Distance Detection by Ultrasonic

Share for us


The ultrasonic sensor uses sound to accurately detect objects and measure distances. It sends out ultrasonic waves and converts them into electronic signals


– 1 * SunFounder Uno board

– 1 * USB data cable

– 1 * Ultrasonic sensor

– 1 * I2C LCD1602

– 2 * 4-Pin anti-reverse cable

– 1 * Dupont wire (F to F)

Experimental Principle

The sensor works by sending a sound wave out and calculating the time it takes for the sound wave to get back to the ultrasonic sensor. By doing this, it can tell us how far away objects are relative to the ultrasonic sensor.

Experimental Procedures

Step 1: Build the circuit

The wiring between the ultrasonic sensor and SunFounder Uno board:

Ultrasonic SensorSunFounder Uno

Step 2: Program (Please refer to the example code in LEARN -> Get Tutorial on our website)

Note: Here you need to add a library. Refer to the description in Lesson 1 previously in the manual.

Step 3: Compile

Step 4: Upload the sketch to SunFounder Uno board

Now, move a piece of paper close to the sensor or remove it farther. You can see the value displayed on the LCD changes accordingly; it indicates the distance between the paper and the ultrasonic sensor.


// —————————————————————————
// Example NewPing library sketch that does a ping about 20 times per second.
// —————————————————————————// include the library code
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <NewPing.h>LiquidCrystal_I2C lcd(0x27,16,2);#define TRIGGER_PIN 2 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 3 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.void setup(){
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}void loop(){
  delay(100); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
  Serial.print(“Ping: “);
  Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
  lcd.setCursor(0, 0);
  lcd.setCursor(0, 1);
  lcd.print(” “);
  lcd.setCursor(9, 1);
  lcd.print(uS / US_ROUNDTRIP_CM);
  lcd.setCursor(12, 1);