Fading LED 4 times with a push of a buttton

My assignment request is to make a program that fade in and out a led 4 times with a push button, then completely stop until the button is pressed again. Can someone help me, im new to this.

Welcome to the forum

What have you tried so far ?

Forget the button and counter for now, can you make the LED fade up and down ?

The LED can fade up and down, but i cant make it stop after 4 cycles, it just kept fading, and it just start fading after i upload the code even though i didnt press the button

Please post your current code, using code tags when you do

How is the button wired to the Arduino ?

const int ledpin = 9;
const int buttonPin= 2;
int buttonState = 0;

void setup() {
  
 pinMode(ledpin, OUTPUT);
 pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
  
 buttonState = digitalRead(buttonPin);
 if (buttonState == HIGH) {
  for( int x=0; x<=255; x++) {
  analogWrite(ledpin, x);
  delay(10);
  }
  for( int x=255; x>=0; x--) {
  analogWrite(ledpin, x);
  delay(10);
  }
 for( int x=0; x<=255; x++) {
  analogWrite(ledpin, x);
  delay(10);
  }
  for( int x=255; x>=0; x--) {
  analogWrite(ledpin, x);
  delay(10);
 }
 for( int x=0; x<=255; x++) {
  analogWrite(ledpin, x);
  delay(10);
  }
  for( int x=255; x>=0; x--) {
  analogWrite(ledpin, x);
  delay(10);
  }
 for( int x=0; x<=255; x++) {
  analogWrite(ledpin, x);
  delay(10);
  }
  for( int x=255; x>=0; x--) {
  analogWrite(ledpin, x);
  delay(10);
 }
}
}

Here is my code, can you check it

the button is wired like in the picture

if (buttonState == HIGH)

As you have used INPUT_PULLUP in pinMode() for the button then the input pin will normally be HIGH so this test will return true and the for loops will run. Change the test to LOW. Can you now control whether the LED fades up and down by pressing the button ?

Thank you, everything turns out ok after i changed it to LOW

Be careful when wiring the button as you may not use a pair of pins that are across its contacts. The safest way to wire it would be to use diagonally opposite pins as they will always be connected to opposite sides of the contacts

Do you understand what the problem was and have you now implemented the counter ?

yes, i understand what was the problem and solved it with your guide, thanks

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.