Help needed with proximity sensor.

Hi,

I am trying to use a proximity sensor that I found here: (Ultrasonic Range Finder - LV-MaxSonar-EZ1 - SEN-00639 - SparkFun Electronics) and interfacing it with my ATmega328. I am able to get the input on the analog pin and everything is working great. I want to control the light in the room when the proximity sensor detects something that is closer than say 8 feet (approx 240cms). I would need to put a decimal value in my program with an if loop so that when the decimal value(as seen by the arduino) is below a certain value, it will turn the light on. My problem is, how do I get that value??

Here is the code

int sensePin=5;                 // proximity sensor output obtained at this pin
int ledPin1 = 4;     // LED connected to digital pin 4
int a=0;   //just a variable to check the current value of sensePin

void setup()
{
  pinMode(ledPin1,OUTPUT);
       // sets the digital pin as output
  Serial.begin(9600);
  digitalWrite(ledPin1,LOW);
  delay(5000);
}

void loop()
{
  
a = analogRead(sensePin);
  if(a<=50)
  {
     digitalWrite(ledPin1, HIGH);   // sets the LED on
  delay(2000); 
  }
  else {
     digitalWrite(ledPin1,LOW);
  delay(2000);
  }
  
  Serial.println(analogRead(sensePin));
  delay(800);
}

The if statement here has 50 in there which I have chosen randomly, what value will I choose to get an equivalent distance of 240 cms and how? Can anyone explain please ?

I would need to put a decimal value in my program with an if loop so that when the decimal value(as seen by the arduino) is below a certain value, it will turn the light on. My problem is, how do I get that value??

Experimentation.

The if statement here has 50 in there which I have chosen randomly, what value will I choose to get an equivalent distance of 240 cms and how?

Use Serial.print() to print the value from the sensor, as you move something to known positions relative to the sensor. What value do you generally see when the object to sensor distance is 240 cm? That is the value that should be in the if statement.

a = analogRead(sensePin);
  if(a<=50)

Read and make decisions on one value.

  Serial.println(analogRead(sensePin));

Then, two seconds later, read again, and print that value. That won't give you good feedback. Either move the statement before the delay() statements or, even better, print a, not a new reading. Best would be to do both.