Home Code Ultrasonic measurement project part 2

Ultrasonic measurement project part 2

by shedboy71

In this example we fit the Digit shield to our Arduino Uno and then connect the HC-SR04 ultrasonic module as per the previous example

You can read about the digit shield here



HC-SR04 Ultrasonic module
Arduino Uno and USB cable
Digit shield



Here is the code example, you will need the Digit Shield library installed, you can get it from https://github.com/arduinolearning/Arduino-Libraries/blob/master/digitshieldlibrary.zip

[codesyntax lang=”cpp”]

#include <DigitShield.h>

//HCSR-04 pins
const int trigPin = 13;
int echoPin = 11;

//anything within 5 cm triggers on board LED
int detected = 5;
//LED pin numbers
int testLED = 13;

int count = 0;
void setup() 
  // initialize serial communication
void loop()

  long duration, cm;
  //initializing the pin states
  pinMode(trigPin, OUTPUT);
  pinMode(testLED, OUTPUT);
  //sending the signal, starting with LOW for a clean signal
  digitalWrite(trigPin, LOW);
  digitalWrite(trigPin, HIGH);
  digitalWrite(trigPin, LOW);
  //setting up the input pin, and receiving the duration in microseconds for the sound to bounce off the object
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  // convert the time into a distance
  cm = microsecondsToCentimeters(duration);
  //printing the current readings to ther serial display
  //valid press up detected
  if (cm < detected)
long microsecondsToCentimeters(long microseconds)
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  return microseconds / 29 / 2;



To test this move an object inside 5 cm of the module and the count should increment by 1 on the Digit shield


You may also like