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

 

Requirements

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

 

Code

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;

//counter
int count = 0;
 
void setup() 
{
  // initialize serial communication
  //Serial.begin(9600);
  DigitShield.begin();
  DigitShield.setPrecision(0);
  DigitShield.setValue(0);
}
 
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);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(5);
  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
  //Serial.print(cm);
  //Serial.print("cm");
  //Serial.println();
 
  //valid press up detected
  if (cm < detected)
  {
      DigitShield.setValue(count);
      count++;
  }
  delay(500);
}
 
long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  return microseconds / 29 / 2;
}

[/codesyntax]

 

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

Share

You may also like