I have been always wanting to use my programming skills for something other than computers, so I got myself a small starter kit with a bunch of sensors, a microcontroller, LEDs, etc. This first project will be about using the HC-SR04 distance calculator (using ultrasound) with an Arduino UNO board. This module calculates distance using the speed of sound.

The HC-SR04 Ultrasound distance calculator
HC-SR04

This is the HC-SR04 ultrasonic distance sensor. This economical sensor provides 2cm to 400cm of non-contact measurement functionality with a ranging accuracy that can reach up to 3mm. Each HC-SR04 module includes an ultrasonic transmitter, a receiver and a control circuit.

There are only four pins that you need to worry about on the HC-SR04: VCC (Power), Trig (Trigger), Echo (Receive), and GND (Ground). You will find this sensor very easy to set up and use for your next range-finding project!

This sensor has additional control circuitry that can prevent inconsistent “bouncy” data depending on the application.

The project wiring
The wiring
#define trigPin 10
#define echoPin 13

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

void loop() {
  float duration, distance;
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2);
 
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) * 0.0344;
  
  if (distance >= 400 || distance <= 2){
    Serial.print("Distance = ");
    Serial.println("Out of range");
  }
  else {
    Serial.print("Distance = ");
    Serial.print(distance);
    Serial.println(" cm");
    delay(500);
  }
  delay(500);
}
The output on the Serial Monitor
The output on the Serial Monitor

The Serial Monitor is something like the console for most programming languages, it is where one can output the programs data and messages. This is pretty convenient for beginners, because setting up a LED screen is more complicated. If you seek displaying data from your programs/projects. So in this screen, I am displaying the distance from the ultrasound calculator at a rate of 1000 milliseconds.

Check my other programming articles.

Project credit: Circuit Basics

Leave a comment