Hello. I've started Arduino about month ago. Recently I wrote a code mingled from official tutorials with witch I have a problem.
The program is supposed to, when I press a button, fade in a LED, then light it until i press the button again and fade out. The problem is, when I press the button, LED keeps fading in from zero in circles.
const int buttonPin = 5;
const int ledPin = 9;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
int brightness = 0;
int fadeAmount = 10;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
buttonState = digitalRead(buttonPin);
if (buttonState != lastButtonState) {
if (buttonState == HIGH) {
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
}
else {
Serial.println("off");
}
}
lastButtonState = buttonState;
if (buttonPushCounter % 2 == 0)
{
for (brightness = 0; brightness <= 245; brightness = brightness + fadeAmount)
{
analogWrite(ledPin, brightness);
delay (50);
}
digitalWrite(ledPin, HIGH);
}
if (buttonPushCounter % 2 != 0)
{
for (brightness = 0; brightness >= 10; brightness = brightness - fadeAmount)
{
analogWrite(ledPin, brightness);
delay(50);
}
digitalWrite(ledPin, LOW);
}
}
Thanks for any help.