Ultrasonic sensor and potentiometer (HELP!)

I have a question regarding the ultrasonic sensor, can you please help me out.

So the problem is that I have an ultrasonic sensor and a potentiometer and I want to set the ultrasonic sensor distance limit using a potentiometer and once the ultrasonic distance has attained the distance limit (that we have set using the potentiometer) I want to stop the ultrasonic sensor.

Can you please help me out, I have searched a lot about this but still not able to figure out anything.

It’s unlikely that you will find code that exactly matches your requirements.

Why don’t you start by showing what you have been able to do. Do you have the ultrasonic sensor working? Show your code (using the code tags…see </> in toolbar). Can you read the potentiometer? Show that code, too.

Also, read up on the map function - that will help you convert your potentiometer reading to your distance limit (although you could also just do it using math…can you think of how that would be done?) And if you don’t know much about programming (how much DO you know?), then you should also read that reference section’s info on control structures. Then go here and read all of the sections on basics and control structures.

hey dave
here is the code that I have written, can you suggest any improvements

const int TRIG=5;
const int ECHO=7;
const int LimitSettingPin=A0;
int minDistance=0;
int maxDistance=100;
long duration;
long distance;

void setup()
{

Serial.begin(9600);
pinMode(TRIG,OUTPUT);
pinMode(ECHO,INPUT);
}

void loop()
{

boolean DistanceSensorEnabled = true;

if (DistanceSensorEnabled)
{
int currentDistance = getDistance();
int distanceLimit = map(analogRead(LimitSettingPin), 0, 1023, minDistance,maxDistance);
if (currentDistance > distanceLimit)
{
DistanceSensorEnabled = false;
Serial.print("MAXIMUM LIMIT REACHED");
}

}

Serial.println(distance);

}

long getDistance()
{
digitalWrite(TRIG,LOW);
delay(2);
digitalWrite(TRIG,HIGH);
delay(10);
digitalWrite(TRIG,LOW);
duration=pulseIn(ECHO,HIGH);
distance=.343*(duration/2);

return distance;
}

It looks reasonable. Does it do what you want? If so it's fine.

Variables duration and distance could be local to getDistance() rather than global but it doesn't make any real difference.

Steve

Every time through loop(), DistanceSensorEnabled will be set to true, so the "if" conditional will always evaluate to "true," even after the max distance is reached. To prevent that from happening, insert "static" thus:

static boolean DistanceSensorEnabled = true;

That will set the variable to "true" the first time through loop and then that line of code will be ignored for all other loops.

Read more about it here in post #7.