/*

 --- Code for 6 3-way Switch Puzzle ---
         (swch0, swch1, etc.)

         
 * Each switch has 3 states, those are named 0, 1, and 2 
 * Each variable can be set as  0, 1, or 2 based on what position is intended 
 * In order to change what state is the "correct state" for the puzzle
change the variable value for each of the correctpos variables to 0, 1, or 2 (correctpos0, correctpos1, etc.)


 * To change number of switches:
    Add or remove from list of switch variables (swch0, swch1, etc.)
    Add or remove from list of correct position variables (correctpos0, correctpos1, etc.)
    Add or remove from list of check variables (chck0, chck1, etc.)
    Add or remove from each of "Arrays for Iteration" to make them match variable lists
    Change number that i and j need to be less than in for loops to one greater than the number of switches
    Add or remove "&& checked[#] == 1" from final if statement based on number of switches

 * Code is set to run a relay through Digital Pin 2
   Once all switches are in the correct positions the relay will activate
   This was tested with an LED being controlled by the relay
   Might want to include a delay before relay gets activated to avoid random switch inputs 

 */

void setup() {
  
pinMode(2, OUTPUT);

}

void loop() {

//Variables for array

int swch0 = 0;
int swch1 = 0;
int swch2 = 0;
int swch3 = 0;
int swch4 = 0;
int swch5 = 0;

int correctpos0 = 0;
int correctpos1 = 0;
int correctpos2 = 0;
int correctpos3 = 0;
int correctpos4 = 0;
int correctpos5 = 0;

int chck0 = 0;
int chck1 = 0;
int chck2 = 0;
int chck3 = 0;
int chck4 = 0;
int chck5 = 0;

int correct = 0;


// Arrays for iteration

const int analog_pins[] =   {A0, A1, A2, A3, A4, A5};
int positions[] =           {swch0, swch1, swch2, swch3, swch4, swch5};
int correct_pos[] =         {correctpos0, correctpos1, correctpos2, correctpos3, correctpos4, correctpos5};
int checked[] =             {chck0, chck1, chck2, chck3, chck4, chck5};


// Iteration to find switch positions 

while(correct == 0) {
  
  for (int i=0; i < 7; i++) {
    int sensorValue = analogRead(analog_pins[i]);
    float voltage = sensorValue * (5.0/1023.0);

    if (voltage < 0.1){
      positions[i] = 1;
    }
    else if (0.1 <= voltage && voltage < 4.5){
      positions[i] = 0;
    }
    else{
      positions[i] = 2;
    };
  }


//Check for switches in correct positions

  for (int j=0; j<7; j++) {
    if (positions[j] == correct_pos[j]){
      checked[j] = 1;
      }
    else{
      checked[j] = 0;
      };
    }

  if (checked[0] == 1 && checked[1] == 1 && checked[2] == 1 && checked[3] == 1 && checked[4] == 1 && checked[5] == 1){
    correct++;
    digitalWrite(2, HIGH);
    break;
    }
    
  else{
    digitalWrite(2, LOW);
    return;
    };
};
}


