flickering problem Ping sensor to light fade

The problem is that the led flickers. I am looking for a smooth transition from dark to light as a person approaches the sensor. The problem may lie in my code, hardware, powersource, light, etc. I amy need to rework the whole system... any help would be appreciated.

Details are below:

-This is my physical setup: http://itp.nyu.edu/physcomp/uploads/arduino_transistor_lamp.png
-Power source is a 12 volt battery
-light is a 12v dc 6w led: http://www.homedepot.com/h_d1/N-5yc1v/R-202324434/h_d2/ProductDisplay?langId=-1&storeId=10051&catalogId=10053

here is my code:

int ledpin = 9;
int val;
const int pingPin = A0;

void setup() {

// initialize serial communication:
Serial.begin(9600);
delay(1000);

pinMode(ledpin, OUTPUT);

}

void loop() {

long duration, inches, cm;

pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);

// convert the time into a distance
cm = microsecondsToCentimeters(duration);

// alberto's debugging block
Serial.print("duration = ");
Serial.print(duration);
Serial.print("\t");
Serial.print("cm = ");
Serial.println(cm);
Serial.println("----------");

if (cm > 200)
{
analogWrite(ledpin, 0);
}
else{

val = cm; // reads the value of the potentiometer (value between 0 and 1023)
val = map(val, 200, 10, 0, 255); // scale it to use it with the LED (value between 0 and 255)

analogWrite(ledpin, val);
delay(10);

}

if (cm > 61)
{
analogWrite(ledpin, HIGH);
}

}

// The following functions won't compile if not used in the code so no need to comment any out.
// Your code left out the closing curly bracket, not sure how it cmpiled without it but maybe
// it was only in the version you emailed me.
long microsecondsToInches(long microseconds) {
return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
return microseconds / 29 / 2;
}

The ping sensor takes time to generate a response. You will not be able to update the LED more often than that.

  analogWrite(ledpin, val);
  delay(10);

The ping sensor already takes a fair amount of time. Why do you want to waste more time/update even less frequently?

What kind of FET are you using? Does it saturate at 40mA/5V or less, at the speed that the Arduino is setting it HIGH/LOW?

The ping sensor already takes a fair amount of time. Why do you want to waste more time/update even less frequently?

Potentially, there could be echoes in flight, but the time taken to print out the results should have taken care of those.

Potentially, there could be echoes in flight, but the time taken to print out the results should have taken care of those.

Good point. If one were to decide that the prints were no longer needed (after all, everything works), the delay() could again become necessary.