Hello,
I'm trying to figure out why the serial monitor doesn't reflect the interaction with the momentary button outside the conditional. A particular print serial occurs outside the conditional (immediately after), but both the conditional and the print serial outside the conditional are inside void loop. I do not think I am misunderstanding variable scope. The variable "switchState" is declared as a global since it comes before void setup. The conditional reflects the changes but the serial print for the same variable that the conditional changed before it is not changing.... Why not?
Any help would be greatly appreciated. Here's my code:
int analogPin = A0; // pin that the sensor is attached to
int ledPin = 13; // pin that the LED is attached to
int threshold = 670; // an arbitrary threshold level that's in the range of the analog input
int switchState;
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communications:
Serial.begin(9600);
}
void loop() {
// read the value of the potentiometer:
int analogValue = analogRead(analogPin);
// if the analog value is high enough, turn on the LED:
if (analogValue > threshold) {
digitalWrite(ledPin, HIGH);
Serial.println("Origin ON");
int switchState = 1;
Serial.println(switchState); // this changes to 1 when I press the button
}
else {
digitalWrite(ledPin,LOW);
Serial.println("Origin OFF");
int switchState = 0;
Serial.println(switchState); // this changes back to 0 when I release the button
}
Serial.println(switchState); // PROBLEM, switchState never changes to 1 when I press the button!
delay(1); // delay in between reads for stability
}