Training Module

Range Finder

Difficulty Level: 2

The goal of this module is to learn about the HC-SR04 Ultrasonic Sensor. This sensor will allow you to measure th edistance from the front of the sensor to an object. The sensor has a range from 2 cm (3/4 inch) to 400 cm (157 inches) with 3 mm (1/10 inch) accuracy.

This module is derived from the module Simple Arduino and HC-SR04 Example.

Breadboard Design Drawing

Note: You make click on the drawing above for a larger version.

LEDs are diodes. Diodes are electrical devices that only allow electricity to flow in one direction. It is very important that you orient the LED the correct way.

When connecting the LED, notice that one leg of the LED is longer than the other. The longer leg is the anode (the positive side). In the drawing the longer leg is the one with the bend in it (the lower leg in the picture above).

Even though both LEDs above are red, I would get one red and one green.


Source Code


#define maxLed 13
#define minLed 12
#define trigPin 11
#define echoPin 10

int maximumRange = 200;
int minimumRange = 0;
int oneThird = (maximumRange - minimumRange) / 3;
int twoThird = 2 * oneThird;
int maxLedState;
int minLedState;

void setup() {
  Serial.begin (9600);
  pinMode(maxLed, OUTPUT);
  pinMode(minLed, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

void loop() {
  long duration;
  long distance;

  digitalWrite(trigPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;

  if ((distance <= minimumRange) || (distance >= maximumRange))
   { // out of range
      maxLedState = LOW;
      minLedState = LOW;
      Serial.println("Out of range");
   } // out of range
   { // in range
     Serial.println(" cm");
     if (oneThird > distance)
      { // within first 1/3 of range
        maxLedState = LOW;
        minLedState = HIGH;
      } // within first 1/3 of range
     if (twoThird > distance)
      { // within middle of range
        maxLedState = HIGH;
        minLedState = HIGH;
      } // within middle of range
      { // at last 1/3 of range
        maxLedState = HIGH;
        minLedState = LOW;
      } // at last 1/3 of range
   } // in range

  delay(500); // wait a bit

Download code


[Arduino index  |  Modules index]