Merging 2 codes into one project

Recently trying to merge 2 projects. One is the secret knock shown here

and another one is the DC motor direction controller using 2 limit switches here

the objective is to have door opened by secret knock motor moves to open and stops at max open limit switch. Then at the same secret knock the motor moves the opposite direction till door closes and hits the closed limit switch.
the code for the secret knock is here

/* Detects patterns of knocks and triggers a motor to unlock
   it if the pattern is correct.
   
   By Steve Hoefer http://grathio.com
   Version 0.1.10.20.10
   Licensed under Creative Commons Attribution-Noncommercial-Share Alike 3.0
   http://creativecommons.org/licenses/by-nc-sa/3.0/us/
  */
 
// Pin definitions
const int knockSensor = 0;         // Piezo sensor on pin 0.
const int programSwitch = 2;       // If this is high we program a new code.
const int lockMotor = 3;           // Gear motor used to turn the lock.
const int redLED = 4;              // Status LED
const int greenLED = 5;            // Status LED
 
// Tuning constants.
const int threshold = 3;          
const int rejectValue = 25;       
const int averageRejectValue = 15; 
const int knockFadeTime = 150;   
const int lockTurnTime = 650;     

const int maximumKnocks = 20;       
const int knockComplete = 1200; 

// Variables.
int secretCode[maximumKnocks] = {50, 25, 25, 50, 100, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};  // Initial setup: "Shave and a Hair Cut, two bits."
int knockReadings[maximumKnocks];   // When someone knocks this array fills with delays between knocks.
int knockSensorValue = 0;      
int programButtonPressed = false;   

void setup() {
  pinMode(lockMotor, OUTPUT);
  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(programSwitch, INPUT);
  
  Serial.begin(9600);                    
  Serial.println("Program start.");      
  
  digitalWrite(greenLED, HIGH);      // Green LED on, everything is go.
}

void loop() {
  // Listen for any knock at all.
  knockSensorValue = analogRead(knockSensor);
  
  if (digitalRead(programSwitch)==HIGH){  // is the program button pressed?
    programButtonPressed = true;          // Yes, so lets save that state
    digitalWrite(redLED, HIGH);     
    programButtonPressed = false;
    digitalWrite(redLED, LOW);
  }
  
  if (knockSensorValue >=threshold){
    listenToSecretKnock();
  }
} 

// Records the timing of knocks.
void listenToSecretKnock(){
  Serial.println("knock starting");   

  int i = 0;
  // First lets reset the listening array.
  for (i=0;i<maximumKnocks;i++){
    knockReadings[i]=0;
  }
  
  int currentKnockNumber=0;               // Incrementer for the array.
  int startTime=millis();                 // Reference for when this knock started.
  int now=millis();
  
  digitalWrite(greenLED, LOW);       
  if (programButtonPressed==true){
     digitalWrite(redLED, LOW);                        
  }
  delay(knockFadeTime);                                
  digitalWrite(greenLED, HIGH);  
  if (programButtonPressed==true){
     digitalWrite(redLED, HIGH);                        
  }
  do {
    //listen for the next knock or wait for it to timeout. 
    knockSensorValue = analogRead(knockSensor);
    if (knockSensorValue >=threshold){                   //got another knock...
      //record the delay time.
      Serial.println("knock.");
      now=millis();
      knockReadings[currentKnockNumber] = now-startTime;
      currentKnockNumber ++;                             //increment the counter
      startTime=now;          
      // and reset our timer for the next knock
      digitalWrite(greenLED, LOW);  
      if (programButtonPressed==true){
        digitalWrite(redLED, LOW);                       // and the red one too if we're programming a new knock.
      }
      delay(knockFadeTime);                              // again, a little delay to let the knock decay.
      digitalWrite(greenLED, HIGH);
      if (programButtonPressed==true){
        digitalWrite(redLED, HIGH);                         
      }
    }

    now=millis();
    
    //did we timeout or run out of knocks?
  } while ((now-startTime < knockComplete) && (currentKnockNumber < maximumKnocks));
  
  //we've got our knock recorded, lets see if it's valid
  if (programButtonPressed==false){             // only if we're not in progrmaing mode.
    if (validateKnock() == true){
      triggerDoorUnlock(); 
    } else {
      Serial.println("Secret knock failed.");
      digitalWrite(greenLED, LOW);     
      for (i=0;i<4;i++){          
        digitalWrite(redLED, HIGH);
        delay(100);
        digitalWrite(redLED, LOW);
        delay(100);
      }
      digitalWrite(greenLED, HIGH);
    }
  } else { // if we're in programming mode we still validate the lock, we just don't do anything with the lock
    validateKnock();
    // and we blink the green and red alternately to show that program is complete.
    Serial.println("New lock stored.");
    digitalWrite(redLED, LOW);
    digitalWrite(greenLED, HIGH);
    for (i=0;i<3;i++){
      delay(100);
      digitalWrite(redLED, HIGH);
      digitalWrite(greenLED, LOW);
      delay(100);
      digitalWrite(redLED, LOW);
      digitalWrite(greenLED, HIGH);      
    }
  }
}


// Runs the motor (or whatever) to unlock the door.
void triggerDoorUnlock(){
  Serial.println("Door unlocked!");
  int i=0;
  
  // turn the motor on for a bit.
  digitalWrite(lockMotor, HIGH);
  digitalWrite(greenLED, HIGH);            // And the green LED too.
  
  delay (lockTurnTime);                    // Wait a bit.
  
  digitalWrite(lockMotor, LOW);            // Turn the motor off.
  
  // Blink the green LED a few times for more visual feedback.
  for (i=0; i < 5; i++){   
      digitalWrite(greenLED, LOW);
      delay(100);
      digitalWrite(greenLED, HIGH);
      delay(100);
  }
   
}

// Sees if our knock matches the secret.
// returns true if it's a good knock, false if it's not.
// todo: break it into smaller functions for readability.
boolean validateKnock(){
  int i=0;
 
  // simplest check first: Did we get the right number of knocks?
  int currentKnockCount = 0;
  int secretKnockCount = 0;
  int maxKnockInterval = 0;               // We use this later to normalize the times.
  
  for (i=0;i<maximumKnocks;i++){
    if (knockReadings[i] > 0){
      currentKnockCount++;
    }
    if (secretCode[i] > 0){           //todo: precalculate this.
      secretKnockCount++;
    }
    
    if (knockReadings[i] > maxKnockInterval){   // collect normalization data while we're looping.
      maxKnockInterval = knockReadings[i];
    }
  }
  
  // If we're recording a new knock, save the info and get out of here.
  if (programButtonPressed==true){
      for (i=0;i<maximumKnocks;i++){ // normalize the times
        secretCode[i]= map(knockReadings[i],0, maxKnockInterval, 0, 100); 
      }
      // And flash the lights in the recorded pattern to let us know it's been programmed.
      digitalWrite(greenLED, LOW);
      digitalWrite(redLED, LOW);
      delay(1000);
      digitalWrite(greenLED, HIGH);
      digitalWrite(redLED, HIGH);
      delay(50);
      for (i = 0; i < maximumKnocks ; i++){
        digitalWrite(greenLED, LOW);
        digitalWrite(redLED, LOW);  
        // only turn it on if there's a delay
        if (secretCode[i] > 0){                                   
          delay( map(secretCode[i],0, 100, 0, maxKnockInterval)); 
          digitalWrite(greenLED, HIGH);
          digitalWrite(redLED, HIGH);
        }
        delay(50);
      }
    return false;   // We don't unlock the door when we are recording a new knock.
  }

the other code is control motor in 2 directions with limit switch at both ends is here

const int activate = 2; //set up our button constants
const int gateOpen = 3;
const int gateClosed = 4;
const int bridgeOneA = 5;
const int bridgeTwoA = 6;
const int enable = 7;
const int statLED = 13;
unsigned long currentTime = 0;
boolean gateState = false; //false = closed true = open
void setup() {
  Serial.begin(9600);
  pinMode(activate, INPUT); //set up I/O
  pinMode(gateOpen, INPUT);
  pinMode(gateClosed, INPUT);
  pinMode(bridgeOneA, OUTPUT);
  pinMode(bridgeTwoA, OUTPUT);
  pinMode(enable, OUTPUT);
  digitalWrite(enable, LOW); //make sure H-Bridge is off
  pinMode(statLED, OUTPUT); //setup our status LED
}
void loop() {
  if (digitalRead(activate) == HIGH && gateState == false) { //check to see if the button is pressed and the gate is closed
    digitalWrite(enable, HIGH); //enable h-bridge
    digitalWrite(bridgeOneA, HIGH); //configure for CW rotation
    digitalWrite(bridgeTwoA, LOW);
    while(1){ //run motor until switch is tripped
      if (digitalRead(gateOpen) == LOW) { //check switch state
        gateState = true;
        digitalWrite(statLED, LOW); //turn off LED
        digitalWrite(enable, LOW); //disable h-bridge
        digitalWrite(bridgeOneA, LOW); //reset h-bridge config
        break;
      }
      if (millis() > currentTime + 500) { //flash status LED once
        digitalWrite(statLED, HIGH);
        delay(500);
        currentTime = millis();
      }
      else {
        digitalWrite(statLED, LOW);
      }
    }
  }
  if (digitalRead(activate) == HIGH && gateState == true) { //check to see if the button is pressed and the gate is open
    digitalWrite(enable, HIGH);
    digitalWrite(bridgeOneA, LOW); //configure for CCW rotation
    digitalWrite(bridgeTwoA, HIGH);
    while(1){
      if (digitalRead(gateOpen) == LOW) {
        gateState = false;
        digitalWrite(statLED, LOW);
        digitalWrite(enable, LOW);
        digitalWrite(bridgeTwoA, LOW);
        break;
      }
      if (millis() > currentTime + 500) { //flash status LED once
        digitalWrite(statLED, HIGH);
        delay(500);
        currentTime = millis();
      }
      else {
        digitalWrite(statLED, LOW);
      }
    }
  }
}

There is something about this in the guides on this site.

Really you need to know how each of the sketches work , then IMO write your own, maybe inspired by those . The danger is you’ve copied some code from somewhere that may of may not be good and put it together with another , with maybe the same problems , library conflicts and so on . When it doesn’t work, if you don’t understand the sketches , you won’t be able to debug.

So show us the attempt you made at combining them. Since the originals use the same pin numbers for different purposes I expect you'll have sorted that out first and drawn a new circuit diagram showing the complete system so post that schematic too. Then what did you try? And what happened?

Steve

Learn about tabs. Create a tab label it knock Create a tab label it motor Declare everything. Libraries pins etc before setup Merge both setups into one Loop() // contains If knock=1 Then. Motor() If knock = 0

Then knock()

If this makes sense good If not ask and we will fill in the details

declare : libraries global variables int knock_valid ; // global variable

other things

NOTE : make sure variables are not duplicated or have duplicate names

setup() all needed statements for both sketches

/* void loop becomes very simple * it only needs to see of the program should be listening for a knock * or of the program should be driving the motor */

void loop(){ if ( knock_valid == 0 ) { knock() ; }

if (knock_valid ==1 ) { motor(); } } // end of loop

// TAB KNOCK void knock () { // all the stuff that would be in void loop() from the knock sketch // at the end, if the knock_valid pattern is correct, then set knock_valid = 1 } // end of void knock

//TAB MOTOR void motor() { // all the stuff that would be in void loop() from the motor sketch // at the end, if the motor activity is complete and you want to go back to listening for a new knock pattern, then knock_valid = 0 } // end of void motor

Step by step here http://www.thebox.myzen.co.uk/Tutorial/Merging_Code.html

But haven’t I pointed you at that before?

Dave & GMike, good guide to start, will follow these steps and attempt to compile..for a poor coder will be a great excersize to fix & refix...then will post here if hit the wall..thanks

Grumpy_Mike: Step by step here http://www.thebox.myzen.co.uk/Tutorial/Merging_Code.html

But haven’t I pointed you at that before?

I did merge the 2 codes but it showed error.(expected unqualified-id before 'void' ) The way I merged like this: copy parts of the code for limit switch demo for L293d sheild and paste them into the secret knock code. So instead secret knock of triggering a motor directly, it will trigger L293D chip to run motor in a certain direction and stops once it hits a limit switch. another secret knock would move the motor the opposite direction, then stops once hits the other side limit switch... I am unable to insert code here, because it exceeds the 9000 chr limit...even after cleaning alot of remarks...can I upload it to a file share site and paste the link here ? I just need someone to comment & help understand since first time I merge codes...?thanks

I did merge the 2 codes but it showed error.(expected unqualified-id before 'void' )

Which simply means you miscounted the number of braces you have { }. If you put your cursor on an opening brace { the the matching closing brace has a small box round it. If it is not where you think it should be then your braces are not matched.

I will go through them one by one tonight and see. thanks for advice. I will try reduce code and post here if possible.