/*
  Based on button by DojoDave <http://www.0j0.org>
  modified 30 Aug 2011 by Tom Igoe
  Inspiration from https://arduinogetstarted.com/tutorials/arduino-button-toggle-led
  Toggle idea borrowed there. Brightness rotation made by me.
*/


// Pin3 to led, pin 2 to button.

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 0;     // the number of the pushbutton pin
const int ledPin =  1;      // the number of the LED pin

// variables will change:
int buttonState = 0;        // variable for reading the pushbutton status


// Variables added by A ( my changes)
int buttonStateLast = 0;  // variable for reading the pushbutton history
                       
int ledState = LOW;       // State for the led
int brightness = 4;       // brightness
                          // next change displays the dimmest value

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT_PULLUP); /* modified by A */
  
  buttonState= 4; // Next state 1, start from lowest value

}

/* loop() is mostly re-written */
void loop() {
  // read the state of the pushbutton value:
  buttonStateLast = buttonState; 
  buttonState = digitalRead(buttonPin); /* This was in original */

  /* Test if buttonstate moves from low to high */
  if (buttonState == HIGH && buttonStateLast  == LOW)
  {
    ledState = !ledState;  /* LedState inverts */
    delayMicroseconds(200); /* Delay for key ripple to stop */

    // brightness grows
    
    if (brightness == 4 && ledState)
      { 
        brightness = 1;
      } else 
      
      if (brightness == 3 && ledState)
      {
        brightness = 4;
      } else if (brightness == 2 && ledState)
      { 
        brightness = 3;
      } else if (brightness == 1 && ledState)
      brightness = 2;
  
  };

  if (!ledState)
  {
    digitalWrite(ledPin, LOW);
  } else {

    // Brightness rotation by alternating the light and dark periods
    switch (brightness) {
      case 1:
        digitalWrite(ledPin, HIGH);
        delay(2);
        digitalWrite(ledPin, LOW);
        delay(25);
        digitalWrite(ledPin, HIGH);
        break;

      case 2:
        digitalWrite(ledPin, HIGH);
        delay(2);
        digitalWrite(ledPin, LOW);
        delay(10);
        digitalWrite(ledPin, HIGH);
        break;

      case 3:
        digitalWrite(ledPin, HIGH);
        delay(2);
        digitalWrite(ledPin, LOW);
        delay(1);
        digitalWrite(ledPin, HIGH);
        break;
      case 4:
        digitalWrite(ledPin, HIGH);

        break;
    }

  }

}
