/*
  Fade

  This example shows how to fade an LED on pin 9 using the analogWrite()
  function.

  The analogWrite() function uses PWM, so if you want to change the pin you're
  using, be sure to use another PWM capable pin. On most Arduino, the PWM pins
  are identified with a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/Fade
*/

unsigned int led = 9;           // the PWM pin the LED is attached to
//unsigned  int brightness = 0;    // how bright the LED is
//unsigned int fadeAmount = 5;    // how many points to fade the LED by

// the setup routine runs once when you press reset:
//void setup()
/*{
  Serial.begin(9600);
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
/*void loop()
{
  delay(10);
  // set the brightness of pin 9:
  analogWrite(led, brightness);
  Serial.println(brightness);

  // change the brightness for next time through the loop:
 brightness = brightness + fadeAmount;
  Serial.println(brightness);

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) 
  {
    fadeAmount = -fadeAmount;
    Serial.println(fadeAmount);
  }
 
 
}*/

#define   DOWN  0
#define   UP    1

static void fading_led_statemachine(void);

unsigned char brightness=0;
unsigned char fadeamount=5;
static unsigned char LED_state;

void setup()
{
  Serial.begin(9600);
  LED_state=UP;
  pinMode(led, OUTPUT);
  
}

void loop()
{
  delay(100);
  
  fading_led_statemachine();
  analogWrite(led,brightness);
 
  
  
}
  
static void fading_led_statemachine(void)
{
  switch(LED_state)
  {
    case UP:

      if(brightness==255)
      {
        LED_state=DOWN;
         Serial.println(brightness);
      }
      else
      {
        brightness=brightness+fadeamount;
         Serial.println(brightness);
      }
    break;

    case DOWN:
      if(brightness==0)
      {
        LED_state=UP;
         Serial.println(brightness);
      }
      else
      {
        brightness=brightness-fadeamount;
         Serial.println(brightness);
      }
    break;
    }

}