I'm trying to use a joystick to dim a LED. This part works fine. The idea is to use the push button for on/off. The idea is when I push the button the value of brightness is stored in the variable brightnessMemory and them brightness=0. But for some reason that I don't understand the value of brightnessMemory goes back to 0. What I'm doing wrong?
Thanks
int xPin = A1;
int yPin = A0;
int buttonPin = 2;
//*********************************
int led = 7; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
int brightnessMemory;
//*********************************
int xPosition = 0;
int yPosition = 0;
int buttonState = 0;
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
//*********************************
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
//*********************************
pinMode(xPin, INPUT);
pinMode(yPin, INPUT);
//activate pull-up resistor on the push-button pin
pinMode(buttonPin, INPUT_PULLUP);
// For versions prior to Arduino 1.0.1
// pinMode(buttonPin, INPUT);
// digitalWrite(buttonPin, HIGH);
}
void loop() {
xPosition = analogRead(xPin);
yPosition = analogRead(yPin);
buttonState = digitalRead(buttonPin);
//*********************************
// set the brightness of pin 9:
analogWrite(led, brightness);
//analogWrite(led, 255);
//*********************************
if (yPosition >=540) {
brightness=brightness+5;
}
if (yPosition <=500) {
brightness=brightness-5;
}
if (brightness >=255) {
brightness=255;
}
if (brightness <=0) {
brightness=0;
}
Serial.print("X: ");
Serial.print(xPosition);
Serial.print(" | Y: ");
Serial.print(yPosition);
Serial.print(" brightness: ");
Serial.print(brightness);
Serial.print(" | Button: ");
Serial.print(buttonState);
Serial.print(" memory ");
Serial.print(brightnessMemory);
Serial.println("");
//-------------------------------------------------------PROBLEM?--------------------------
if (buttonState == 0) {
brightnessMemory=brightness;
brightness=0;
//-------------------------------------------------------PROBLEM?--------------------------
}
delay(100); // add some delay between reads
}