////////////////////////////////////////////////////////////////////////////////////////////////////
//KSP Launcher button by diytronics
//https://www.instructables.com/member/diytronics/
////////////////////////////////////////////////////////////////////////////////////////////////////

#include "Keyboard.h"

const int stagebutton = 3; //Pin for stage button
const int togglebutton = 2; //Pin for throttle toggle button
int previousStageButtonState = LOW; //Make the previous state LOW as it is normally closed
int previousToggleButtonState = HIGH; //Make the previous state HIGH as it is normally open
int counter; //Counter for z and x toggle


void setup() {
  Keyboard.begin(); //Start keyboard emulation
  pinMode(stagebutton, INPUT); 
  pinMode(togglebutton, INPUT);
  counter = 1; //Set start value for counter as 1 (z)
}

void loop() {
  stage(); //Run stage function
  toggle(); //Run toggle function
}


void stage() { //Function for sending a space every time launch button is low
  int stageState = digitalRead(stagebutton); //assign a new variable to current button state
  if ((stageState != previousStageButtonState) //if current button state is not equal to previous state, and it is low send a space
      && (stageState == LOW)){
        Keyboard.press(32); //32 is space
        delay(100);
        Keyboard.release(32); 
  }
  previousStageButtonState = stageState; // make previous state current state

}

void toggle() {
  int toggleState = digitalRead(togglebutton);
  if ((toggleState != previousToggleButtonState) //if current button state is not equal to previous state, and it is low send a space
      && (toggleState == HIGH)) {
    switch(counter){ //look at counter value
      case 1: //counter is 1 so sent character needs to be z
      Keyboard.println("z");
      counter = 2; //make counter 2 for toggle effect
      break;
    
    case 2: //counter is 2 so sent character needs to be x
    Keyboard.println("x");
    counter = 1; //make counter 1 for toggle effect
    break;
  }
      }
  previousToggleButtonState = toggleState; // make previous state current state
}



