#include <EEPROM.h>    // Inclode the following libraries.  EEPROM.h/Arduino.h should already be available to you.  Download IRremote.h from github
#include <Arduino.h>
#include <IRremote.hpp>
float hold = 0;        // 'hold' is a float, which means that it can store very large numbers.  Hold will be used primarily to store raw IR stream data
int returned_number = 0; // Depending on which button was pressed, this integer returns a value.  If button 1 is pressed, retuend)number will = 1
int x = 0;             // 'x' is a variable that is used as a pointer value in the getcompare() function.
int RECV_PIN = 7;      // GPIO 7 is our IR receiver pin
int state = 0;         // 'state' is a variable that keeps us looking while loops until a goal is achieved.
int state2 = 0;        // 'state2' works just like 'state'.  Sometimes we need to have two while loops running at the same time in different fuctions.  This is the backup.
int counter = 0;       // 'counter' is used to count matching IR signals.  When a new IR stream is compared to a saved stream, counter will hold a number of compared matches.
int pointer = 0;       // 'pointer' is literally a pointer used to point to specific values in a list.  Found in the getIrandSave() function
float hundredmil = 0;  // Used to decode raw IR stream data.  
float tenmils = 0;     // Used to decode raw IR stream data.  
float mils = 0;        // Used to decode raw IR stream data.  
float hunredthou = 0;  // Used to decode raw IR stream data.  
float tenthou = 0;     // Used to decode raw IR stream data.  
float thou = 0;        // Used to decode raw IR stream data.   
float hundred = 0;     // Used to decode raw IR stream data.  
float remainder = 0;   // Used to decode raw IR stream data.  
float saveval[] ={0,0,0};       // saveval is a list/array used to compare incoming IR signals against one another to ensure that saves are correct.  Found in the getIRandSave() function.
float buildval[] ={0,0,0,0,0};  // This float array is used to rebuild saved IR streams
int oneval[] ={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};  // When we read the EEPROM for saved IR streams, all stream data is loaded here.
int holdval[] ={0,0,0,0,0};     // This array is used during the decode function. We will temporarily hold stream data in this array/list. 
// 
int combocode[] = {4,5,4,3};
int incoming_combo_code[] = {0,0,0,0};
//
#define PG 4                    // The PG Program jumper pin on the IR clip connects to GPIO#4
#define GD 5                    // GD is the simulated ground for the IR clip.  We'll set this GPIO pin to 0v/LOW which will act as a ground.
#define PWR 6                   // PWR is the power pin for the IR clip, and connects to GPIO#6
int hold2 = 0;                  // hold2 is used in the getcompare() function, and acts as a stop value in a for loop
IRrecv irrecv(RECV_PIN);        // Sets up the IR receiver within the IRremote library.
int savecount = 0;              // savecount acts as a counter/pointer that is used when writing to the EEPROM



void setup()                // Let's set up our IOs, and read the EEPROM
{ 
  delay(1000);              // This is optional.  It is just a one second delay
  Serial.begin(9600);       // Set up the serial monitor with a baud rate of 9600
  pinMode(PG,INPUT);        // Set the program jumper as an input
  pinMode(GD,OUTPUT);       // Set the GD pin as an output 
  digitalWrite(GD,LOW);     // Turn the GD pin off/low/0v.  This will efffectively connect a ground to the IR clip GD pin.
  delay(10);                // Wait 10ms
  pinMode(PWR,OUTPUT);      // Set the PWR pin on the IR clip as an outout
  digitalWrite(PWR,HIGH);   // Turn the PWR pin on to apply 5v tothe IR clip as a power supply.  The IR clip is now powered.
  delay(100);               // Wait 100ms
  // In case the interrupt driver crashes on setup, give a clue
  // to the user what's going on.
  irrecv.enableIRIn();      // Enable the IR receiver
  EEPROMREAD();             // call the EEPROMREAD() function to read back previously saved IR stream data.
}


void loop() {                       // This is our main loop.  We're going to achieve one of two things here.  Program in new IR data, or compare incoming IR data against saved values.
if(digitalRead(PG) == HIGH){        // If the PG pin is left without a jumper on it, then it will be pulled to 5v through a pull-up resistor.  If this is the case, let's program some buttons!();
  Serial.println("GETTING NEW IR!  PRESS THE SAME BUTTON SEQUENTIALLY THREE TIMES AND FOLLOW MY INSTRUCTIONS...");  // Print this to the serial monitor
  getIRandSave();                          // Make sure that your serial monitor is open.  You'll need to probram in buttons 0 through 9, and then the power button.  Once done ,the program will freeze
}
else{      // If the jumper is present on the PG pin, then we're going to compare incoming IR streams against saved streams.
  IRcombo();
}
}

void IRcombo(){
  state2 = 0;
  while(state2 == 0){
  Serial.println("Enter in a 4 digit code...");
  for(int i = 0; i < 4 ; i++){
  compareIR();
  //Serial.print(returned_number);
  incoming_combo_code[i] = returned_number;
  }
  if(incoming_combo_code[0] == combocode[0] && incoming_combo_code[1] == combocode[1] && incoming_combo_code[2] == combocode[2] && incoming_combo_code[3] == combocode[3]){
     Serial.println("GREAT SUCCESS!  Door Open!");
     delay(10000);
     }
     else{
     Serial.println("SECURITY BREACH!  INCORRECT COMBINATION!");
    }
  }
  }

void compareIR(){                      // In this functon we wait for an incoming stream, and then we'll compare said stream against our 11x saved streams.
  getIR();                             // Wait for a stream to be accepted, and processed.
  hold = 0;                            // Set hold to 0.  This is a reference pointer.  It will make more sense once you look at the getcomare() function below.
  returned_number = 50;                // The returned number will be placed in this integer.  Set it to 50 as default.  Returning a value of 50 means that the IR stream wasn't recognised. 
  getcompare();                        // Call the getcompare() function to compare the IR stream that we just processed against our saved button#0 stream data
  if(counter == 5){                    // If counter equals 5, then we matched all sections of the two streams.  Button#0 was pressed!
  Serial.println("0 button received");  // IMPORTANT!  THIS IS WHERE YOU CAN ADD PROGRAMS OR INSTRUCTIONS.  YOU JUST MATCHED BUTTON#0.  WHAT DO YOU WANT TO DO WITH THAT?  ADD IT HERE!
  returned_number = 0;                  // If an invalid button is pressed, returend_number will remain 0, so instead of returning 0 here, we'll return 11.
  }
  hold = 5;               // The rest of this function is basically a copy of a copy of a piece of code, pasted 11 times, with one large exception: the hold value.  
  getcompare();           // Remember, the value in hold acts as a pointer to the IR stream data that we loaded from EEPROM on power up.  Check the getcompare() function for a better understanding.
  if(counter == 5){
  Serial.println("1 button received");
  returned_number = 1;
  }
  hold = 10;
  getcompare();
  if(counter == 5){
  returned_number = 2;
  Serial.println("2 button received");
  }
   hold = 15;
  getcompare();
  if(counter == 5){
  returned_number = 3;
  Serial.println("3 button received");
  }
   hold = 20;
  getcompare();
  if(counter == 5){
  returned_number = 4;
  Serial.println("4 button received");
  }
   hold = 25;
  getcompare();
  if(counter == 5){
  returned_number = 5;
  Serial.println("5 button received");
  }
   hold = 30;
  getcompare();
  if(counter == 5){
  returned_number = 6;
  Serial.println("6 button received");
  }
   hold = 35;
  getcompare();
  if(counter == 5){
  returned_number = 7;
  Serial.println("7 button received");
  }
   hold = 40;
  getcompare();
  if(counter == 5){
  returned_number = 8;
  Serial.println("8 button received");
  }
   hold = 45;
  getcompare();
  if(counter == 5){
  returned_number = 9;
  Serial.println("9 button received");
  }
   hold = 50;
  getcompare();
  if(counter == 5){
  returned_number = 10;
  Serial.println("POWER button received");
  }
  if(returned_number == 50){
    Serial.println("Unknown button received");
  }
}
  
void getcompare(){                   // In this function, we are going to call saved stream data loaded on power up from EEPROM and compare it against the last incoming signal
hold2 = hold + 5;                    // hold2 equals the value in hold plus 5.  So if hold = 0, then hold2 = 5.  Why?  See below.
x = 0;                               // x always starts at 0 here, and we will use it below as a reference point. 
counter = 0;                         // Five pieces of stream data neet to match.  If all five match at the end of this function,then a match has occurred.
for(int i = hold ; i < hold2 ; i++){ // i equals hold, which is 5x less than hold2  but both values are variable dependong on what hold was loaded with before this function was called.
    if(holdval[x] == oneval[i]){     // The holdval list has 5 slots (0-through 4).  x starts at 0 and increments after every loop in this FOR loop. i = hold, which points to the position...
      counter++;                     // in the oneval[] list. Positions - through 4 in oneval correspond to saved button#0 data.  So we compare our small holdval[] list values to a much...
    }                                // large list (oneval) by making use of x and i as pointers.  If a match is made, add 1 to counter.  Make all five comparisons before this FOR loop ends.
    x++;                             // Add 1 to x after each loop
  }
}


void getIR(){                  // When this function is called, the system waits for an incoming IR signal.  Once received, it is processed.                                 
  state = 0;                   // Set state to 0
  while(state == 0){           // Run the following code while state equals 0
    if(IrReceiver.decode()){   // If a code is received, capture it, and run the following code.
    hold = IrReceiver.decodedIRData.decodedRawData;  // Take the RAW data stream number and place it in hold (Remember, hold is a float, so we can store huge numbers within it).
    //Serial.print("The original value: ");            // Print this to the serial monitor
    //Serial.println(hold);                            // Print the raw data to the serial monitor, and start a new line on the serial monitor
    decoder();                                       // Call the decoder function.  This breaks down the huge raw data number into five smaller numbers which can be saved to EEPROM.  
    delay(100);
    //rebuild();                                     // The rebuild function() is commented out here, but it shows you how put back together the raw IR stream data broken down in decode()
    irrecv.resume(); // Receive the next value       // This instruction allows for us to receive another IR stream
    state = 1;                                       // Set state to 1, which will end the while loop.
  }
}
}



    
void getIRandSave(){
    state = 0;                   // Set state to 0
    pointer = 0;                 // Set pointer to 0
    while(state == 0){
    if(IrReceiver.decode()){                         // If a code is received, capture it, and run the following code.
    hold = IrReceiver.decodedIRData.decodedRawData;  // Take the RAW data stream number and place it in hold (Remember, hold is a float, so we can store huge numbers within it).
    Serial.println(hold);
    saveval[pointer] = hold;
    pointer++;
    delay(200);
    irrecv.resume(); // Receive the next value       // This instruction allows for us to receive another IR stream
    if(pointer == 3){
      if(saveval[0] == saveval[1] && saveval[1] == saveval[2]){
        hold = saveval[0];
        state = 1;
        Serial.println("IR stream successfully captured...");
      }
      else{
        Serial.println("Failure to capture.  Try again");
        pointer = 0;
      }
    }
    }
    }
    decoder();                                       // Call the decoder function.  This breaks down the huge raw data number into five smaller numbers which can be saved to EEPROM.  
    EEPROMSAVE();                                    // Call the EEPROMSAVE() function.  See below.  If PG was LOW, skip this step.
    delay(700);                                   // The rebuild function() is commented out here, but it shows you how put back together the raw IR stream data broken down in decode()
    irrecv.resume(); // Receive the next value       // This instruction allows for us to receive another IR stream
    state = 1;                                       // Set state to 1, which will end the while loop.
}
    
    
    
    




// This function was used for debug.  I am keeping it here for the time being.  No need to comment it.
void getIRtest(){  
  state = 0;
  Serial.println("Press a button for test...");
  while(state == 0){
    if(IrReceiver.decode()){
    delay(1000);
    state = 1;
    irrecv.resume(); // Receive the next value
    Serial.println("SUCCESS!  YOU HAVE A COMPATIBLE REMOTE!");
  }
  }
}


void decoder(){              // This function acts to take the number stored in 'hold' that represents the IR stream that we just captured, and break it down into 5 smaller numbers.
clearints();                 // This function clears all relative integeres for this function to 0.
if(hold > 100000000){        // This is our first of five breakdowns.  As you can see, the raw numbers that we're working with are in the billions.  If the value is larger than 100MIL...
while(hold > 100000000){     // ...then start this while  loop.  While hold is greater than 100 million...
  hold = hold - 100000000;   // Subtract 100 million and add 1 to the hundredmil variable.  For every 100 million that we subtract from 'hold', we add '1' to hundredmil.
  hundredmil++;              // Add 1  hundredmil
}                            // At this point, we have shaved off a huge amount of this raw data, but we have a value that will help us to reconstruct the number later.
}                            // When 'holh' is finally less than 100 million, this while loop ends, and we can move on.
holdval[0] = hundredmil;     // Save the hundredmil value to holdval[0].  We're going to get all five values saved to 'holdval' in this function.  The remainder of this function is much of the same.
//Serial.print("Remainder = "); // Print this to the serial monitor
//Serial.println(hold);         // Print the amount that remains of the raw number after removing the multiples of 100 million.
//Serial.print(hundredmil);     // Print the multiple of hundred millions that we removed.  These prints are not necessary, but help you to learn how this algorithm works.
//Serial.println(" is the hundredmillion multiplier");  // Print this to the serial monitor.
if(hold > 1000000){           // FINALLY!  We can now move onto the next step.  Here, we're going to do the same thing that we did above, except that we're going to subtract millions...
while(hold > 1000000){        // ...as opposed to hundred millions.  For every subraction, we add 1 to 'mils'  If you understand the first section of this code, you'll understnad the rest.
  hold = hold - 1000000;
  mils++;
}
}                             // Once the remainder of the raw data in 'hold' is less than a million, then the above while loop ends,and have our multiples of millions now stored in 'mils'
holdval[1] = mils;            // Store this value in holdval[2] for later.
//Serial.print("Remainder = "); // Print all of the relavent new data like we did above.  There's no need for me to comment on it further.
//Serial.println(hold);
//Serial.print(mils);
//Serial.println(" is the million multiplier");
if(hold > 10000){             // Now we're going to do the same, only for multiples of 10 thousand.  We'll have the factors of 10k into 'tenthou' 
while(hold > 10000){
  hold = hold - 10000;
  tenthou++;
}
}
holdval[2] = tenthou;         // Store the final 10k multiple vales from 'tenthou' into holdval[2].
//Serial.print("Remainder = ");
//Serial.println(hold);
//Serial.print(tenthou);
//Serial.println(" is the tenthousand multiplier");
if(hold > 100){               // We are getting close now.  Let's find out how many hundreds can be subtracted in the remaining raw data stored in hold.
while(hold > 100){
  hold = hold - 100;
  hundred++; 
}
}
holdval[3] = hundred;         // Store the value into holdval[3].
remainder = hold;
holdval[4] = remainder;       // Because the remainder in 'hold' has to be less than 100, we can store the remainder in holdvavl[4] withour further decoding.
//Serial.print("Remainder = "); // We need to make sure that the values that we're saving to memory are less than 255, as the EEPROM cannot handle numbers higher than that.
//Serial.println(hold);         // By decoding using this method, we are always able to keep the numbers under 255.
//Serial.print(hundred);        // In the above line,we print the remainder.  On this line we print the hundred value.
//Serial.println(" is the hundred multiplier");
//remainder = hold;
} // In many ways, this algorithm is silly, but in a way it is a little brilliant =)  We have saved a number that is in the billions, and we've compressed it down to 5 small numbers.
                              
void clearints(){    // In this function, we clear all  of the decode() integers.  There are some extra ones here that we don't use.  I keep them here in case I want to...
hundredmil = 0;      // Change the algotithm at any point.  We don't use tenmils, hundredthou, or thou...
tenmils = 0;
mils = 0;
hunredthou = 0;
tenthou = 0;
thou = 0;
hundred = 0;
remainder = 0;
}


void rebuild(){                       // This function takes the number broken down in decode(), and reassembles it  into it's original RAW state
clearbuildval();                      // This function is called to clear the entire buildval[] list.  See below.  We need this list empty to rebuild our RAW stream number.
buildval[0] = 100000000 * hundredmil; // Take the number in hundredmil, and multiply it by 100 million. Store the value in buildval[0]
//Serial.println(buildval[0]);          // Print the number that we just assembled.
buildval[1] = 1000000 * mils;         // Take the number in mils, and multiply it by 1 million. Store the value in buildval[1]
//Serial.println(buildval[1]);
buildval[2] = 10000 * tenthou;        // Take the number in tenthou, and multiply it by 10,000. Store the value in buildval[2]
//Serial.println(buildval[2]);
buildval[3] = 100 * hundred;          // Take the number in 'hundred', and multiply it by 100 . Store the value in buildval[3]
//Serial.println(buildval[3]);
buildval[4] = remainder;              // The number stored in buildval[4] is always less than 255, which is the maximum EEPROM value, so we don't need to multiply anything.
//Serial.println(buildval[4]); 
hold = 0;                             // Clear 'hold'
hold = buildval[0] + buildval[1] + buildval[2] + buildval[3] + buildval[4];  // Add all of the values in the list to hold.  The sum is the rebuilt raw data!
//Serial.print("The rebuild value is: ");  // Print this to the serial monitor
//Serial.println(hold);                    // Print the rebuilt value
}

void clearbuildval(){  // This function clears the buildval[] list.  We can create a for loop to do this with a couple less lines of code, but this was just faster with cut and paste =)
buildval[0] = 0;
buildval[1] = 0;
buildval[2] = 0;
buildval[3] = 0;
buildval[4] = 0;
}

void EEPROMSAVE(){          // OK! We're on the way to the end here.  In this function, we save decoded IR streams to EEPROM.  Where we save it to depends on value in 'savecount'
if(savecount == 0){         // If we have the program jumper removed, then we will call EEPROM save after every new IR stream is received.  'savecount' starts at 0, so...
EEPROM.write(0,holdval[0]); // We take the decoded IR stream that current resides in the holdval[] list, and we write them to EEPROM address 0 through 4.
EEPROM.write(1,holdval[1]);
EEPROM.write(2,holdval[2]);
EEPROM.write(3,holdval[3]);
EEPROM.write(4,holdval[4]);
savecount++;                 // This is important.  After we made the saves above, we've about to exit this function.  Before doing so, we need to increment savecount.  Why?...
Serial.println("Saved as 0 ");  // Because the next time we get an IR stream, we'll want to save to the NEXT set of EEPROM addresses (5-9). We increment each time we get a new stream.
}                   
else if(savecount == 1){        // See?  If savecount was still 0 after the last save, we'd just be resaving to EEPROM adddress 0 through 4.  Not anymore!  The rest of this function...
EEPROM.write(5,holdval[0]);     // More of the same over and over again.  It should make sense to you if you understand the few lines above with the help of these comments =)
EEPROM.write(6,holdval[1]);
EEPROM.write(7,holdval[2]);
EEPROM.write(8,holdval[3]);
EEPROM.write(9,holdval[4]);
savecount++;
Serial.println("Saved as 1 ");
}
else if(savecount == 2){
EEPROM.write(10,holdval[0]);
EEPROM.write(11,holdval[1]);
EEPROM.write(12,holdval[2]);
EEPROM.write(13,holdval[3]);
EEPROM.write(14,holdval[4]);
savecount++;
Serial.println("Saved as 2 ");
}
else if(savecount == 3){
EEPROM.write(15,holdval[0]);
EEPROM.write(16,holdval[1]);
EEPROM.write(17,holdval[2]);
EEPROM.write(18,holdval[3]);
EEPROM.write(19,holdval[4]);
savecount++;
Serial.println("Saved as 3 ");
}
else if(savecount == 4){
EEPROM.write(20,holdval[0]);
EEPROM.write(21,holdval[1]);
EEPROM.write(22,holdval[2]);
EEPROM.write(23,holdval[3]);
EEPROM.write(24,holdval[4]);
savecount++;
Serial.println("Saved as 4 ");
}
else if(savecount == 5){
EEPROM.write(25,holdval[0]);
EEPROM.write(26,holdval[1]);
EEPROM.write(27,holdval[2]);
EEPROM.write(28,holdval[3]);
EEPROM.write(29,holdval[4]);
savecount++;
Serial.println("Saved as 5 ");
}
else if(savecount == 6){
EEPROM.write(30,holdval[0]);
EEPROM.write(31,holdval[1]);
EEPROM.write(32,holdval[2]);
EEPROM.write(33,holdval[3]);
EEPROM.write(34,holdval[4]);
savecount++;
Serial.println("Saved as 6 ");
}
else if(savecount == 7){
EEPROM.write(35,holdval[0]);
EEPROM.write(36,holdval[1]);
EEPROM.write(37,holdval[2]);
EEPROM.write(38,holdval[3]);
EEPROM.write(39,holdval[4]);
savecount++;
Serial.println("Saved as 7 ");
}
else if(savecount == 8){
EEPROM.write(40,holdval[0]);
EEPROM.write(41,holdval[1]);
EEPROM.write(42,holdval[2]);
EEPROM.write(43,holdval[3]);
EEPROM.write(44,holdval[4]);
savecount++;
Serial.println("Saved as 8 ");
}
else if(savecount == 9){
EEPROM.write(45,holdval[0]);
EEPROM.write(46,holdval[1]);
EEPROM.write(47,holdval[2]);
EEPROM.write(48,holdval[3]);
EEPROM.write(49,holdval[4]);
Serial.println("Saved as 9 ");
savecount++;
}
else{
EEPROM.write(50,holdval[0]);
EEPROM.write(51,holdval[1]);
EEPROM.write(52,holdval[2]);
EEPROM.write(53,holdval[3]);
EEPROM.write(54,holdval[4]);
Serial.println("Saved as POWER BUTTON - Done prorgramming.  Please change DIP SWITCH Selection and reset...");
state = 0;
while(state == 0){   // When the last button is pressed, the 11th, this will freeze rhe program.  Connect the PG jumper on the IR clip and reset.
}
}
}


void EEPROMREAD(){             // This is the last function.  It is called during void setup().  It does two things...
for(int i = 0; i < 55 ; i++){  // Firstly, it reads the relative EEPROM memory slots and places the data in each slot to the same slot in the list oneval[].
  oneval[i] = EEPROM.read(i);  // 'i' increments every time this loops (55 times).
}
for(int i = 0; i < 51 ; i++){  // The second reason is that we want to print all of these numbers to the serial monitor to make sure that they are what we expect.
  Serial.println(oneval[i]);   // Print all of the relative slots now stored in oneval to a new line on the serial monitor.  Comment this specific for loop out if you'd like. 
}                              // It isn't needed.
}
