Here is the code for people who don’t want to download it.
#include <LiquidCrystal.h>
#define echoPin 2 // Echo Pin
#define trigPin 3 // Trigger Pin
#define LEDPin 13 // Onboard LED
int maximumRange = 1000; // Maximum range needed
int minimumRange = 100; // Minimum range needed
long duration, distance; // Duration used to calculate distance
int incrementState = 0; //variable that will read the increment button (either HIGH or LOW)
int decrementState = 0; //variable that will read the decrement button (either HIGH or LOW)
int counter = 0; //variable that will store the count
int lastIncrementState = 0;
int lastDecrementState = 0;
int currentState = 0;
int previousState = 0;
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
void setup() {
Serial.begin(9600);
lcd.begin(5, 1);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}
void loop() {
/* The following trigPin/echoPin cycle is used to determine the
distance of the nearest object by bouncing soundwaves off of it. */
lcd.setCursor(0,0);
lcd.print(counter ); //print it on serial monitor
digitalWrite(trigPin, LOW);
delayMicroseconds(50);
digitalWrite(trigPin, HIGH);
delayMicroseconds(100);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;
if (distance >= maximumRange || distance <= minimumRange){
/* Send a negative number to computer and Turn LED ON
to indicate "out of range" */
lcd.setCursor(0,0);
Serial.println("-1");
digitalWrite(LEDPin, HIGH);
currentState = 1;
}
else {
/* Send the distance to the computer using Serial protocol, and
turn LED OFF to indicate successful reading. */
Serial.println(distance);
digitalWrite(LEDPin, LOW);
currentState = 0;
}
if(currentState != previousState){
if(currentState == 1){
counter = counter + 1;
lcd.setCursor(0,0);
lcd.println(counter );
}
}
previousState = currentState;
//Delay 50ms before next reading.
delay(200);
}