Problem coding mosfets side by side.

Hi I’m coding a couple mosfets to activate two different motors depending on a door knock and the first one works like a charm with this coding
/* 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/

  (In short: Do what you want, just be sure to include this line and the four above it, and don't sell it or use it in anything you sell without contacting me.)



  Analog Pin 0: Piezo speaker (connected to ground with 1M pulldown resistor)

  Digital Pin 2: Switch to enter a new code.  Short this to enter programming mode.

  Digital Pin 3: DC gear reduction motor attached to the lock. (Or a motor controller or a solenoid or other unlocking mechanisim.)

  Digital Pin 4: Red LED.

  Digital Pin 5: Green LED.



  Update: Nov 09 09: Fixed red/green LED error in the comments. Code is unchanged.

  Update: Nov 20 09: Updated handling of programming button to make it more intuitive, give better feedback.

  Update: Jan 20 10: Removed the "pinMode(knockSensor, OUTPUT);" line since it makes no sense and doesn't do anything.

*/



// Pin definitions

const int knockSensor = 0;         // Piezo sensor on pin 0.

const int lockMotor = 2;           // Gear motor used to turn the lock.





// Tuning constants.  Could be made vars and hoooked to potentiometers for soft configuration, etc.

const int threshold = 3;           // Minimum signal from the piezo to register as a knock

const int rejectValue = 25;        // If an individual knock is off by this percentage of a knock we don't unlock..

const int averageRejectValue = 15; // If the average timing of the knocks is off by this percent we don't unlock.

const int knockFadeTime = 150;     // milliseconds we allow a knock to fade before we listen for another one. (Debounce timer.)

const int lockTurnTime = 1200;      // milliseconds that we run the motor to get it to go a half turn.



const int maximumKnocks = 20;       // Maximum number of knocks to listen for.

const int knockComplete = 1200;     // Longest time to wait for a knock before we assume that it's finished.





// 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;           // Last reading of the knock sensor.

int programButtonPressed = false;   // Flag so we remember the programming button setting at the end of the cycle.



void setup() {

 pinMode(lockMotor, OUTPUT);



 Serial.begin(9600);                     // Uncomment the Serial.bla lines for debugging.

 Serial.println(" This highly intelegent program has started.");       // but feel free to comment them out after it's working right.



}



void loop() {

 // Listen for any knock at all.

 knockSensorValue = analogRead(knockSensor);





 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();



 

 delay(knockFadeTime);                                 // wait for this peak to fade before we listen to the next one.

 

 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

     

     delay(knockFadeTime);                              // again, a little delay to let the knock decay.

     

   }

  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.");

     for (i = 0; i < 4; i++) {

     }

   }

 } 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.");

   for (i = 0; i < 3; i++) {

   }

 }

}





// 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);



 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++) {

 }



}



// 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.

   for (i = 0; i < maximumKnocks ; i++) {

     // only turn it on if there's a delay

     if (secretCode[i] > 0) {

       delay( map(secretCode[i], 0, 100, 0, maxKnockInterval)); // Expand the time back out to what it was.  Roughly.

     }

     delay(50);

   }

   return false;   // We don't unlock the door when we are recording a new knock.

 }



 if (currentKnockCount != secretKnockCount) {

   return false;

 }



 /*  Now we compare the relative intervals of our knocks, not the absolute time between them.

     (ie: if you do the same pattern slow or fast it should still open the door.)

     This makes it less picky, which while making it less secure can also make it

     less of a pain to use if you're tempo is a little slow or fast.

 */

 int totaltimeDifferences = 0;

 int timeDiff = 0;

 for (i = 0; i < maximumKnocks; i++) { // Normalize the times

   knockReadings[i] = map(knockReadings[i], 0, maxKnockInterval, 0, 100);

   timeDiff = abs(knockReadings[i] - secretCode[i]);

   if (timeDiff > rejectValue) { // Individual value too far out of whack

     return false;

   }

   totaltimeDifferences += timeDiff;

 }

 // It can also fail if the whole thing is too inaccurate.

 if (totaltimeDifferences / secretKnockCount > averageRejectValue) {

   return false;

 }



 return true;



}

But when I add the coding for the second mosfet it takes something that worked fine before (validateKnock) and says it wasn’t declared in this scope. This is the second one that doesn’t compile

I’ve tried everything, but I’m not a good coder all that code I copied from a bunch of different ones to get a hybrid of what’s perfect for me.

basiclly, hELp!

bestest_knock_coode_v3.ino (8.14 KB)

Your links do not work for me. Post the code here where everyone can see it. I hate to go off to other sites to download code in order to help someone.

Read the how to use this forum-please read sticky to see how to properly post code and some advice on how to ask an effective question. Remove useless white space and format the code with the IDE autoformat tool (crtl-t or Tools, Auto Format) before posting code.

See... I tried that but the code exceeds the 9000 limit for characters

This is the second code

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/

   (In short: Do what you want, just be sure to include this line and the four above it, and don't sell it or use it in anything you sell without contacting me.)



   Analog Pin 0: Piezo speaker (connected to ground with 1M pulldown resistor)

   Digital Pin 2: Switch to enter a new code.  Short this to enter programming mode.

   Digital Pin 3: DC gear reduction motor attached to the lock. (Or a motor controller or a solenoid or other unlocking mechanisim.)

   Digital Pin 4: Red LED.

   Digital Pin 5: Green LED.



   Update: Nov 09 09: Fixed red/green LED error in the comments. Code is unchanged.

   Update: Nov 20 09: Updated handling of programming button to make it more intuitive, give better feedback.

   Update: Jan 20 10: Removed the "pinMode(knockSensor, OUTPUT);" line since it makes no sense and doesn't do anything.

*/



// Pin definitions

const int knockSensor = 0;         // Piezo sensor on pin 0.

const int lockMotor = 2;           // Gear motor used to turn the lock.

const int gunMotor  = 4;



// Tuning constants.  Could be made vars and hoooked to potentiometers for soft configuration, etc.

const int threshold = 3;           // Minimum signal from the piezo to register as a knock

const int rejectValue = 25;        // If an individual knock is off by this percentage of a knock we don't unlock..

const int averageRejectValue = 15; // If the average timing of the knocks is off by this percent we don't unlock.

const int knockFadeTime = 150;     // milliseconds we allow a knock to fade before we listen for another one. (Debounce timer.)

const int lockTurnTime = 1200;      // milliseconds that we run the motor to get it to go a half turn.



const int maximumKnocks = 20;       // Maximum number of knocks to listen for.

const int knockComplete = 1200;     // Longest time to wait for a knock before we assume that it's finished.





// 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;           // Last reading of the knock sensor.

int programButtonPressed = false;   // Flag so we remember the programming button setting at the end of the cycle.



void setup() {

  pinMode(lockMotor, OUTPUT);

  pinMode(gunMotor, OUTPUT);

  Serial.begin(9600);                     // Uncomment the Serial.bla lines for debugging.

  Serial.println(" This highly intelegent program has started.");       // but feel free to comment them out after it's working right.



}



void loop() {

  // Listen for any knock at all.

  knockSensorValue = analogRead(knockSensor);





  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();



  

  delay(knockFadeTime);                                 // wait for this peak to fade before we listen to the next one.

  

  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

      

      delay(knockFadeTime);                              // again, a little delay to let the knock decay.

      

    }



    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, unforgiveness commencing.");

}

      for (i = 0; i < 4; i++) {

      }      }

    }

  } 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.");

    for (i = 0; i < 3; i++) {

    }

  }

}





// 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);



  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++) {

  }



}

void doorUnforgiveness() {

  Serial.println("Secret knock failed, unforgiveness commencing.");

  int i = 0;



   // turn the motor on for a bit.

  digitalWrite(gunMotor, HIGH);



  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++) {

  }

// 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.

    for (i = 0; i < maximumKnocks ; i++) {

      // only turn it on if there's a delay

      if (secretCode[i] > 0) {

        delay( map(secretCode[i], 0, 100, 0, maxKnockInterval)); // Expand the time back out to what it was.  Roughly.

      }

      delay(50);

    }

    return false;   // We don't unlock the door when we are recording a new knock.

  }



  if (currentKnockCount != secretKnockCount) {

    return false;

  }



  /*  Now we compare the relative intervals of our knocks, not the absolute time between them.

      (ie: if you do the same pattern slow or fast it should still open the door.)

      This makes it less picky, which while making it less secure can also make it

      less of a pain to use if you're tempo is a little slow or fast.

  */

  int totaltimeDifferences = 0;

  int timeDiff = 0;

  for (i = 0; i < maximumKnocks; i++) { // Normalize the times

    knockReadings[i] = map(knockReadings[i], 0, maxKnockInterval, 0, 100);

    timeDiff = abs(knockReadings[i] - secretCode[i]);

    if (timeDiff > rejectValue) { // Individual value too far out of whack

      return false;

    }

    totaltimeDifferences += timeDiff;

  }

  // It can also fail if the whole thing is too inaccurate.

  if (totaltimeDifferences / secretKnockCount > averageRejectValue) {

    return false;

  }



  return true;



}

(deleted)

Then attach the code. See #8 in the how to use this forum post.

If the code is that long, crating a minimal program that shows the problem will make it easier to find the solution. Often, in the act of creating the minimal program the solution will present itself.

Take the advice to break down your/the code down into very small stand-alone functions and test one thing at a time until that aspect is working working, ie, a nibble by nibble approach.

When copying, pasting and "glueing" code together, the most common problems are missing or extra curly brackets, semi colons, and comment slashes, and these are very hard to find in a "long" program. It's not about how clever a programmer one is, it's about working with achieveable bite-size chunks until both the hardware and software are correct. But it's certainly smart to work on one small aspect at a time, and even write various kinds of test code to understand how things work.

Using serial print and serial println (and comment out later) to send messages, and contents or state of variables to the serial monitor at various suitable points can also be very useful. ie, the program gives feedback at various breakpoints instead of sittting there mutely.

Using LED's on output pins to indicate outputs operate as expected before connecting power devices is useful too.

Thanks guys, that really helped and I got the code up and running. The problem was actually 2 things, a missing wiggly bracket and some reprograming button thing that I removed. The code in the first place is to add some “security” to my shed fort where if you put a key in and knock “open” in morse code then the door open, however if you knock wrong an goes to an actuater that activates a nerf gun; shooting the trespasser. I’m gonna install as soon as summer roles around.

Great, no problem, and some useful things learnt I'm sure. A door entry system sounds like a worthy addition to a fort, it sounds great but you may want to rethink using a nerf gun as a "surprise" / deterrent. If a kid brother or sister (or anyone) got a projectile in their eye for example, funs over and things may get more serious.

You may want to think about a graded fail entry system maybe, like a fail beep followed by some sort of surprise (but surprises only work once!) after 3 failed attempts. Some people have used water sprays for this... You may also want an "administrator" override once it's installed. Anyway, your project, and plenty of time to test ideas out if it's a summer install.

There are also projects/ideas around that can send sensor/alarm status wirelessly to a base unit, cellphone, or cloud service, so plenty of other ideas to investigate/learn aboout.

YertleTheTechyTurtle: Thanks guys, that really helped and I got the code up and running. The problem was actually 2 things, a missing wiggly bracket and some reprograming button thing that I removed. The code in the first place is to add some "security" to my shed fort where if you put a key in and knock "open" in morse code then the door open, however if you knock wrong an goes to an actuater that activates a nerf gun; shooting the trespasser. I'm gonna install as soon as summer roles around.

Please post your final code. Others using the forum may benefit from reading the thread.

Final code.

Knock_Code_V4.ino (7.93 KB)