Random/floating input on Arduino Uno w/photoresistor or w/potentiometer [solved]

I am trying to read from a photoresistor using an Arduino Uno (see wiring diagram and code below ) and use Serial.println to show the value read on the analog pin. Ultimately I would like to use this as a speed control in a larger project. The diagram I have included is a minimal case that illustrates the problem.

I expected to see a range of numbers from 0 to 1023 in the Serial Monitor, based on the light level. However, when I open Serial Monitor, the display always starts with a value in the 400s that gradually counts down - regardless of the light value. In other words, it starts at the same value regardless of the light level, and counts down at the same rate even if the light level doesn't change, or increases, etc.

I am new to the Arduino world but believe this behavior is sometimes called "floating input" and also occurs when a pin is not connected.

I believe that the photoresistor is wired correctly and works, because I have an LED wired to it as well, and the LED brightens and darkens when the light changes.

I have tried the following:

  1. Replacing the photoresistor with a 10K pot.

Result: LED still varied correctly; Arduino still behaved incorrectly (i.e., reading from the pin counted down from a value in the 400s).

  1. Tried connecting to different analog pins (and changing code).

Result: Same behavior (countdown from the 400s).

  1. Wired the analog pin directly to ground.

Expected: AnalogRead() on the pin to return 0
Result: Same behavior (countdown from the 400s).

  1. Adding a pull-down resistor.

Result: No change in behavior.

I am running the Uno directly from the USB cable. I've had the board a few days, and have successfully been able to read digital input from switches and buttons - but I have never been able to get an analog reading.

Any advice would be greatly appreciated. Please let me know if there is any further information that I can provide.

Code:

int val = 0;
int analogPin = 2;

void setup() {
Serial.begin(9600);
}

void loop() {
val = analogRead(analogPin);
Serial.println(val);
delay(1000);
}

Arduino Uno with Photoresistor.JPG

Analog pin 2 should be referred as A2 or 16 in your code.. Pin 2 is actually the digital pin no 2..

So change this:

int analogPin = 2;

To this:

int analogPin = A2;

Thank you for the response!

Funnily enough, even though the code change didn't fix the problem by itself, it did make me realize what the problem was. I had checked everything in the wiring several times ... except the pin itself. My lead was plugged into 2 instead of A2.

BTW, I was using a number alone because the code comes directly from the reference page for AnalogRead - which gives just a number rather than the channel.