// Variables that remain constant
const byte pinSwitch = 8; // Digital input pin from momentary switch
const byte pinLED = 3; // PWM pin for LED
int dimSpeedUp = 32; // Larger number = faster
int dimSpeedDown = 4; // Smaller number = slower

// Variables that can change
int brightness = 0;

void setup()
{
  // Only necessary for debugging the code
  Serial.begin(9600);

  // Initialise momentary switch pin with an internal pull-up resistor
  // so that the momentary switch is read as open (= HIGH) at start
  pinMode (pinSwitch, INPUT_PULLUP);

  // Initialise the microcontroller's digital pin specified above
  pinMode(pinLED, OUTPUT);
}

void loop()
{
  int switchState = digitalRead(pinSwitch); // Read the momentary switch state

  if (switchState == LOW) // If the momentary switch button was pressed
  {
    brightness = brightness + dimSpeedUp; // Then dim up

    if (brightness > 255) // If at maximum PWM value
      brightness = 255; // Then keep it there
  }
  else // If the momentary switch button was released
  {
    brightness = brightness - dimSpeedDown; // Then dim down

    if (brightness < 0) // If at minimum PWM value
      brightness = 0; // Then keep it there
  }

  analogWrite(pinLED, brightness); // Set the LED's brightness

  delay(50); // Wait a little after each dimming step

  Serial.println(brightness); // Only necessary for debugging the code
}