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;
}