//https://arduinogetstarted.com/tutorials/arduino-button-debounce

//the number of the pushbutton pin
const int FireButton = 11;

//the number of the Laser pin
const int LASER = 12;

int Fire_State;  // variable for reading the pushbutton status
int button_state = 0;

const int DEBOUNCE_DELAY = 1;   // the debounce time; increase if the output flickers
const unsigned long pulseDuration = 50;  // Duration for which LED stays ON (in ms)
unsigned long ledOnTime = 0;   // To track when the LED was turned ON

// Variables will change:
int lastSteadyState = LOW;       // the previous steady state from the input pin
int lastFlickerableState = LOW;  // the previous flickerable state from the input pin

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled

void setup() {
  pinMode(FireButton, INPUT_PULLUP); 
  pinMode(LASER, OUTPUT);  
}

void loop() {
  // read the state of the pushbutton value:
  Fire_State = digitalRead(FireButton);

  // Turn off the laser if the button is not pressed and the pulse duration is over
  if (digitalRead(LASER) == HIGH && millis() - ledOnTime > pulseDuration) {
    digitalWrite(LASER, LOW);  // Turn off the LED after the pulse duration
  }

  // If the switch/button changed, due to noise or pressing:
  if (Fire_State != lastFlickerableState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
    // save the the last flickerable state
    lastFlickerableState = Fire_State;
  }

  if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
    // If the button state has changed:
    if (lastSteadyState == HIGH && Fire_State == LOW) {          
      digitalWrite(LASER, HIGH);      // Turn on the LED
      ledOnTime = millis();           // Record the time when LED was turned on
    }
    // Save the last steady state
    lastSteadyState = Fire_State;
  }
}