Hello, i'm running the following code with an initial setting for "dayMode" and "light" as 1. If the photoresists detects darkness on start-up, then it's supposed to overwright with "0". But the code doesn't make it happen. What am I missing? FYI in the dark, sensor reads between 1 and 5. Thx in advance.
int lightSensor = A0;
int sensor = 0;
int dayMode = 1;
int light = 1;
void setup(){
Serial.begin(9600);
int reading = analogRead(lightSensor);
if (reading < 462){
int dayMode = 0;
int light = 0;
}
}
void loop(){
Serial.println(dayMode);
Serial.println(light);
delay(1000);
}
Look up variable scope. You've declared two variables (dayMode and light) globally and then two more of the same name in setup(). They're not the same; the ones you play with in setup() are not visible outside setup().
If you turn up the compile warnings you will see that you created two variables inside setup() that are given initial values but never used:
/Users/john/Documents/Arduino/sketch_dec01a/sketch_dec01a.ino: In function 'void setup()':
/Users/john/Documents/Arduino/sketch_dec01a/sketch_dec01a.ino:13:9: warning: unused variable 'dayMode' [-Wunused-variable]
int dayMode = 0;
^~~~~~~
/Users/john/Documents/Arduino/sketch_dec01a/sketch_dec01a.ino:14:9: warning: unused variable 'light' [-Wunused-variable]
int light = 0;
^~~~~
You declared them with the same names as two global variables and gave them initial values but they are NOT the global variables and the global variables still have the initial values you gave them.