Why won't this work?

Why won't this code work. There's an error and it says val was not declared in scope.

Here's the code:

void setup() {

int val = 0;

}

void loop () {

val = analogRead(0);

Serial.print(val);

}

Scope. The variable is defined inside setup, so can't be seen in any other function.

Try moving the line inside setup() to above setup(). Then val will be global scope.

Thanks ! But I am trying to make a LDR tell my computer the light level through the serial port. And it won't display the light level when I click serial monitor. What do I do to make it work?

Heres the code for you guys to look at so you can help me:

int val = 0;

void setup() { }

void loop () {

val = analogRead(0);

Serial.print(val);

}

Also, the way you have loop you will read (and print!) val hundreds or thousands of times a second. For this toy application include a delay(1000) statement to read only once per second.

What light are you trying to display? Is it attached to the Arduino? How do you have the LDR hooked up? LDR's do not provide voltage of their own, you need to hook it up to a voltage through a resistor.

I have LDR connected to a 5V port on the arduino and the other leg on the LDR connected to ground and analog in put port "A0".

I found this reply (by robtillaart) about that:

To connect an LDR correctly it must be part of a voltage divider

+5V <----> [ LDR ] <-----> [A0]  <------> [Resistor] <-----> GND

The value of resistor must be in the same order as the LDR when in the dark. (a 10 K will work probably too)

Robotbuilder9999: ... the other leg on the LDR connected to ground and analog in put port "A0".

If A0 is connected to Gnd, clearly it will always read zero.

I believe inside setup you need:

Serial.begin(baud)

Put

int val;

inside your loop.