I'm really confused. I have a program that's supposed to take sensor readings (it's a Sharp long-distance IR sensor). It's supposed to print them out on the serial monitor in values ranging from 0 to 1023. It worked just fine before, and then it suddenly started acting strangely; now the values seldom go any higher than 200, and they are totally inconsistent. I'll place my hand directly in front of the sensor and start to move it away, and the numbers start to grow larger, which is what it's supposed to do…but then they fluctuate like crazy, even when my hand is barely moving! What have I done? Here is my code:
int sensorvar = 0;
int led = 9;
int outputValue = 0;
I don't think it's the wiring; I have the signal wire connected to analog pin 1, and the power and ground wires are connected to the power and ground rails on the breadboard. Also, I doubt that it's dirt, because I tried using my other Sharp sensor in case this one is defective, and that one produced the same results.
scjurgen, thank you so much for your helpful debugging tips. It reads 1023 when I connect the pin to power and 0 when I connect it to ground. I also tried a different analog pin. I even tried snipping off the edge of the wire a bit (it's the stranded kind, so it tends to split easily). I revised my program so that it looks like this:
int analogPin = 4; // potentiometer wiper (middle terminal) connected to analog pin 3
// outside leads to ground and +5V
int val = 0; // variable to store the value read
void setup()
{
Serial.begin(9600); // setup serial
}
void loop()
{
val = analogRead(analogPin); // read the input pin
Serial.println(val); // debug value
delay(500);
}
Still, no results…
I'm wondering if it's a problem with the sensor itself.
Oh wow, now it mysteriously works just fine. I tried connecting a wire from analog pin 4 (I switched from 1 to 4) to the breadboard and then connecting the sensor to the same node on the breadboard. I had it wired that way before, but then while I was in the process of debugging, I tried connecting the wire directly to the pin. Go figure. o.O