Go Down

Topic: Why won't this work? (Read 600 times) previous topic - next topic

Robotbuilder9999

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

}


AWOL

Scope.
The variable is defined inside setup, so can't be seen in any other function.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

GoForSmoke

Try moving the line inside setup() to above setup(). Then val will be global scope.
Nick Gammon on multitasking Arduinos:
1) http://gammon.com.au/blink
2) http://gammon.com.au/serial
3) http://gammon.com.au/interrupts

Robotbuilder9999

#3
Jan 23, 2013, 09:20 pm Last Edit: Jan 23, 2013, 09:23 pm by Robotbuilder9999 Reason: 1
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?

Robotbuilder9999

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

}

KeithRB

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.

KeithRB

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.

Robotbuilder9999

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".

Nick Gammon

I found this reply (by robtillaart) about that:

Quote

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

Code: [Select]
+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)

Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

Nick Gammon


... 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.
Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

jerseyguy1996

I believe inside setup you need:

Code: [Select]
Serial.begin(baud)

Put

Code: [Select]
int val;

inside your loop.
Arduino Uno;
Mega328

Go Up