1

I am recording a varying distance with an Ultrasonic sensor and Arduino but my problem is I want to display the number of times this variable reaches peak (at an instance the value will be increasing and the next instance decreasing in that order) on an LCD.

So far this is my code:

//Libraries
#include <Ultrasonic.h>
#include <LiquidCrystal.h>

//Setup connection with LCD and HC-SR04
LiquidCrystal lcd(12, 10, 5, 4, 3, 2);
Ultrasonic ultrasonic(A0,A1);

void setup() {
  //Lcd init
  lcd.begin(16, 2); //16 rows, 2 columns
}

void loop()
{
  lcd.clear();
  lcd.print("  Ardumotive ;)  "); // You can change this message.
  lcd.setCursor(0, 1);
  lcd.print("Distance: ");
  lcd.print(ultrasonic.Ranging(CM));
  lcd.print("cm");

  delay(300); // 1sec delay
}
1
  • 1
    So far this just looks like a copy-paste code from an example for the Ultrasonic sensor. You need to show us that you've thought about how you're going to achieve your goal. Commented Jun 6, 2015 at 14:08

2 Answers 2

1

The counting portion of what you want to achieve is simple - you just increment a variable. The hard part is knowing when to count.

You need to remember what your value has been doing in the past in order to know if you have had a peak or not. Also you have to define exactly what a peak is.

The simplest method (I'm not going to spoon feed you code, just help you understand the concepts) is to set a couple of thresholds, and maintain a flag.

You decide upon a value "above which the value enters the peak zone", and another "below which the value leaves the peak zone". They could be the same value, but don't need to be.

You then have a flag which remembers if you are in the peak zone or not.

If you're not currently in the peak zone and the new value is above the peak zone entry threshold then you have entered the peak zone. Set the flag to remember that fact.

If you are currently in the peak zone and the new value is below the peak zone leaving threshold then you have just left the peak zone. Clear the flag to remember the fact that you're not in the peak zone and increment your peak counter now you have left the peak.

enter image description here

It can be very good to have the leaving threshold lower than the entering threshold so that the value has to drop significantly out of the peak zone before it will register another peak. This is known as hysteresis and is great for getting rid of the noise you may get if the value is hovering around the peak zone entry threshold.

0

If ((current distance - previous distance) < 0) Max = previous distance;

Current distance = previous distance;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.