Combining two arduino sketches

Discussion in 'Embedded Systems and Microcontrollers' started by Rickpercy87, Apr 29, 2016.

  1. Rickpercy87

    Thread Starter New Member

    Nov 20, 2015
    16
    0
    Hi, I have 2 separate sketches which work fine on their own. I am struggling to get them working on one arduino.

    Sketch number 1:
    Deals with the input from a microwave doppler sensor

    Sketch number 2:
    Is a piezeo buzzer

    I would like the microwave sensor to activate the buzzer once a threshold it met (I have already got an LED lighting up when the threshold is met) but I cannot combine them.

    Below is the code for the microwave sensor: Can anybody tell me where to put the code for my simple PWM pieze sound alarm so that
    it triggers at the same time as the ledPin?
    Code (Text):
    1. [/B]
    2. const int analogPin = 0;
    3. const int threshold = 500;
    4. int ledPin = 13;
    5.  
    6. void setup()
    7. {
    8.   Serial.begin(9600);
    9.   pinMode (ledPin, OUTPUT);
    10. }
    11.  
    12. void loop() {
    13.   int mn = 1023;     // mn only decreases
    14.   int mx = 0;        // mx only increases
    15.  
    16.   // Perform 10000 reads. Update mn and mx for each one.
    17.   for (int i = 0; i < 700; ++i) {
    18.     int val = analogRead(analogPin);
    19.     mn = min(mn, val);
    20.     mx = max(mx, val);
    21.  
    22.   }
    23.  
    24. if (threshold > mn)
    25. {
    26. digitalWrite (ledPin, HIGH);
    27.  
    28. }
    29.  
    30. else {
    31. digitalWrite (ledPin, LOW);
    32.  
    33. }
    34.  
    35.   // Send min, max and delta over Serial
    36.   Serial.print("m=");
    37.   Serial.print(mn);
    38.   Serial.print(" M=");
    39.   Serial.print(mx);
    40.   Serial.print(" D=");
    41.   Serial.print(mx-mn);
    42.   Serial.println();
    43. }
    44.  
     
  2. dannyf

    Well-Known Member

    Sep 13, 2015
    1,775
    360
    Easy:

    Code (Text):
    1.  
    2. //sketch1/2 variables here
    3. varable 1....;
    4.  
    5. //sketch1 setup here
    6. void setup1(void) {
    7. ...
    8. }
    9.  
    10. //sketch2 setup here
    11. void setup2(void) {
    12. ...
    13. }
    14.  
    15. //sketch1 loop here
    16. void loop1(void) {
    17. ...}
    18.  
    19. //sketch 2 loop here
    20. void loop2(void) {
    21. ...
    22. }
    23.  
    24. //combined setup
    25. void setup(void) {
    26.   setup1();  //sketch 1 setup
    27.   setup2();  //skethc 2 setup
    28. }
    29.  
    30. //combined loop
    31. void loop(void) {
    32.   loop1();  //sketch 1 loop
    33.   loop2();  //sketch 2 loop
    34. }
    35.  
    Done.
     
    Rickpercy87 likes this.
  3. Rickpercy87

    Thread Starter New Member

    Nov 20, 2015
    16
    0
    Thanks for the clear example! I'll get right on it.

    This is exactly what I have been looking for.
     
  4. Rickpercy87

    Thread Starter New Member

    Nov 20, 2015
    16
    0
    Iv'e failed practically straight away. I think i'm missing something.

    void setup 1(void)

    {
    Serial.begin(9600);
    pinMode (ledPin, OUTPUT);
    pinMode (speakerOut, OUTPUT);

    }

    I get the error:

    Arduino: 1.6.7 (Windows 7), Board: "Arduino/Genuino Uno"

    UPDATED_MICROWAVE_CODE.ino:22: error: expected initializer before numeric constant

    void setup 1(void)

    ^

    exit status 1
    expected initializer before numeric constant

    This report would have more information with
    "Show verbose output during compilation"
    enabled in File > Preferences.
     
  5. dacflyer

    Member

    Nov 19, 2010
    13
    0
    why not just connect the buzzer to the light ?
    simple and no code to change..
     
  6. Rickpercy87

    Thread Starter New Member

    Nov 20, 2015
    16
    0
    I have already done that and it does work fine, but it is too plain. I want the speaker to use my PWM alarm tone I have made.
     
  7. dacflyer

    Member

    Nov 19, 2010
    13
    0
    oh, ok,,
    how about a pizo alarm that has already a driver inside of it ?
    different tones, sirens etc.
    but either way.. i know what you mean now..
    good luck
     
  8. nerdegutta

    Moderator

    Dec 15, 2009
    2,515
    785
    Don't think you're supposed to have a space between p and 1.
     
  9. djsfantasi

    AAC Fanatic!

    Apr 11, 2010
    2,802
    832
    Put the buzzer code in a function. When the LED is lit, call the buzzer function. I don't know what your code looks like or what your piezo requires to drive, so I have made some generic code just as an example

    Code (C):
    1.  
    2.   const int analogPin = 0;
    3.        const int buzzerPin=10; // add this line
    4.   const int threshold = 500;
    5.   int ledPin = 13;
    6.  
    7.   void setup()
    8.   {
    9.   Serial.begin(9600);
    10.   pinMode (ledPin, OUTPUT);
    11.       pinMode (buzzerPin, OUTPUT);  // add this pin
    12.   }
    13.  
    14.   void loop() {
    15.   int mn = 1023; // mn only decreases
    16.   int mx = 0; // mx only increases
    17.  
    18.   // Perform 10000 reads. Update mn and mx for each one.
    19.   for (int i = 0; i < 700; ++i) {
    20.   int val = analogRead(analogPin);
    21.   mn = min(mn, val);
    22.   mx = max(mx, val);
    23.  
    24.   }
    25.  
    26.   if (threshold > mn)
    27.   {
    28.   digitalWrite (ledPin, HIGH);
    29.        buzzer(); // add this line
    30.  
    31.   }
    32.  
    33.   else {
    34.   digitalWrite (ledPin, LOW);
    35.  
    36.   }
    37.  
    38.   // Send min, max and delta over Serial
    39.   Serial.print("m=");
    40.   Serial.print(mn);
    41.   Serial.print(" M=");
    42.   Serial.print(mx);
    43.   Serial.print(" D=");
    44.   Serial.print(mx-mn);
    45.   Serial.println();
    46.   }
    47.  
    48. // new buzzer function
    49. void buzzer()
    50.   const unsigned long timeBuzzer=1000; // milliseconds
    51.   unsigned long endTime=millis() + timeBuzzer;
    52.   digitalWrite(buzzerPin,HIGH);
    53.   while (millis() < endTime);
    54.   digitalWrite(buzzerPin,LOW);
    55. }
    56.  
    57.  
     
    Rickpercy87 likes this.
  10. Rickpercy87

    Thread Starter New Member

    Nov 20, 2015
    16
    0
    Thanks a lot, i'm trying to get my head around the structure of the code. Here is what mine looks like at the moment.

    1. The code reads analogue pin 0
    2. if analogue pin zero is equal to or greater than 3 I want it to light a LED (which it does) && activate the speaker. But the tone the speaker produces is PWM and uses different notes.

    I am having trouble calling for the tone to be produced.

    At the moment, everyhting works but the PWM tone is not being produced.

    Here is my code at the moment (I know its a bit unorganised iv'e cleaned it up quite a lot):

    const int analogPin = 0;
    const int threshold = 3;
    int ledPin = 13;
    int speakerOut = 9;

    // TONES ==========================================
    // Start by defining the relationship between
    // note, period, & frequency.
    #define c 3830
    #define d 3400
    #define e 3038
    #define f 2864
    #define g 2550
    #define a 2272
    #define b 2028
    #define C 1912
    // Define a special note, 'R', to represent a rest
    #define R 0

    // SETUP ============================================
    // Set up speaker on a PWM pin (digital 9, 10 or 11)int speakerOut = 9;

    void setup()

    {
    Serial.begin(9600);
    pinMode (ledPin, OUTPUT);
    pinMode (speakerOut, OUTPUT);

    // MELODY and TIMING =======================================
    // melody[] is an array of notes, accompanied by beats[],
    // which sets each note's relative length (higher #, longer note)
    int melody[] = { C, b, a, g, f, e, b, a, C, b };
    int beats[] = { 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 };
    int MAX_COUNT = sizeof(melody) / 2; // Melody length, for looping.

    // Set overall tempo
    long tempo = 2500;
    // Set length of pause between notes
    int pause = 100;
    // Loop variable to increase Rest length
    int rest_count = 10; //<-BLETCHEROUS HACK; See NOTES

    // Initialize core variables
    int tone_ = 0;
    int beat = 0;
    long duration = 0;

    // PLAY TONE ==============================================
    // Pulse the speaker to play a tone for a particular duration
    void playTone() ;
    long elapsed_time = 0;
    if (tone_ > 0) { // if this isn't a Rest beat, while the tone has
    // played less long than 'duration', pulse speaker HIGH and LOW
    while (elapsed_time < duration) {

    digitalWrite(speakerOut,HIGH);
    delayMicroseconds(tone_ / 2);

    // DOWN
    digitalWrite(speakerOut, LOW);
    delayMicroseconds(tone_ / 2);

    // Keep track of how long we pulsed
    elapsed_time += (tone_);

    }
    } else { // Rest beat; loop times delay
    for (int j = 0; j < rest_count; j++) { // See NOTE on rest_count delayMicroseconds(duration);
    }
    }
    }



    void loop() {
    int mn = 1023; // mn only decreases
    int mx = 0; // mx only increases

    // Perform 10000 reads. Update mn and mx for each one.
    for (int i = 0; i < 5; ++i) {
    int val = analogRead(analogPin);
    mn = min(mn, val);
    mx = max(mx, val);


    }


    if (threshold > mn){
    digitalWrite (ledPin, HIGH); // lights the LED
    delay (100); // time LED stays lit once a rigger is met
    analogWrite (speakerOut, HIGH);
    delay (110);

    }

    else {
    digitalWrite (ledPin, LOW); //LED is turned off if there is no movement
    analogWrite (speakerOut, LOW);

    }

    // Send min, max and delta over Serial
    Serial.print("m=");
    Serial.print(mn);
    Serial.print(" M=");
    Serial.print(mx);
    Serial.print(" D=");
    Serial.print(mx-mn);
    Serial.println();
    }
     
  11. DNA Robotics

    Member

    Jun 13, 2014
    123
    26
    This is in Examples\Digital\toneMelody
    They are using tone(8, melody[thisNote], noteDuration); instead of digitalWrite(speakerOut,HIGH);

    Code (Text):
    1. /*
    2.   Melody
    3.  
    4. Plays a melody
    5.  
    6. circuit:
    7. * 8-ohm speaker on digital pin 8
    8.  
    9. created 21 Jan 2010
    10. modified 30 Aug 2011
    11. by Tom Igoe
    12.  
    13. This example code is in the public domain.
    14.  
    15. http://www.arduino.cc/en/Tutorial/Tone
    16.  
    17. */
    18. #include "pitches.h"
    19.  
    20. // notes in the melody:
    21. int melody[] = {
    22.   NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
    23. };
    24.  
    25. // note durations: 4 = quarter note, 8 = eighth note, etc.:
    26. int noteDurations[] = {
    27.   4, 8, 8, 4, 4, 4, 4, 4
    28. };
    29.  
    30. void setup() {
    31.   // iterate over the notes of the melody:
    32.   for (int thisNote = 0; thisNote < 8; thisNote++) {
    33.  
    34.     // to calculate the note duration, take one second
    35.     // divided by the note type.
    36.     //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    37.     int noteDuration = 1000 / noteDurations[thisNote];
    38.     tone(8, melody[thisNote], noteDuration);
    39.  
    40.     // to distinguish the notes, set a minimum time between them.
    41.     // the note's duration + 30% seems to work well:
    42.     int pauseBetweenNotes = noteDuration * 1.30;
    43.     delay(pauseBetweenNotes);
    44.     // stop the tone playing:
    45.     noTone(8);
    46.   }
    47. }
    48.  
    49. void loop() {
    50.   // no need to repeat the melody.
    51. }
     
  12. djsfantasi

    AAC Fanatic!

    Apr 11, 2010
    2,802
    832
    I downloaded your code and compiled it in the Arduino IDE. In reviewing your buzzer code, I noticed a couple of things...

    One, is that the code to play a melody is included in the setup function and hence cannot be executed by your main loop. I am working on creating a playMelody function that uses playTone...
    Hence, in your loop function, where you perform a digitalWrite, that line of code would be replaced by playMelody().

    However secondly, in trying to understand your code to play the melody, you have a while loop in a function playTone that is dependent on the variable "duration". This variable is set to a value of 0 and never modified. Your while loop condition is "while (elapsed_time < duration)", will never be true. The initial conditions are false, (0 < 0) is false. And if it could get executed once, as elapsed_time is incremented, it will still be false. So your statements to play a tone are for naught. "duration" should be set to some value. I am assuming it should be the corresponding value to melody[] that is found in beats[]?

    Let me know what "duration" is and to what value it should be set, if you'd like me to continue work.

    Thirdly, I will make some minor adjustments to where you define and initialize your variables. Some can be set globally; others are local to functions. Some can be constants, saving memory.

    Code (C):
    1.  
    2. const int analogPin = 0;
    3. const int threshold = 3;
    4. const int ledPin = 13;
    5. const int speakerOut = 9;
    6.  
    7. // TONES ==========================================
    8. // Start by defining the relationship between
    9. // note, period, & frequency.
    10. #define c 3830
    11. #define d 3400
    12. #define e 3038
    13. #define f 2864
    14. #define g 2550
    15. #define a 2272
    16. #define b 2028
    17. #define C 1912
    18. // Define a special note, 'R', to represent a rest
    19. #define R 0
    20.  
    21. // SETUP ============================================
    22. // Set up speaker on a PWM pin (digital 9, 10 or 11)int speakerOut = 9;
    23.  
    24. void setup()
    25.  
    26. {
    27.   Serial.begin(9600);
    28.   pinMode (ledPin, OUTPUT);
    29.   pinMode (speakerOut, OUTPUT);
    30. }
    31.  
    32. // PLAY MELODY  ============================================
    33. void playMelody() {
    34.   // MELODY and TIMING
    35.   // melody[] is an array of notes, accompanied by beats[],
    36.   // which sets each note's relative length (higher #, longer note)
    37.   const int melody[] = { C, b, a, g, f, e, b, a, C, b };
    38.   const int beats[] = { 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 };
    39.   int MAX_COUNT = sizeof(melody) / 2; // Melody length, for looping.
    40.  
    41.   // Set overall tempo
    42.   const long tempo = 2500; // Not used
    43.  
    44.   // Initialize core variables
    45.   int tone_ = 0;
    46.   int beat = 0;
    47.   long duration = 0;
    48.  
    49.   for (int note = 0; note <= MAX_COUNT; note++) {
    50.   playTone(melody[note], beats[note]);
    51.   }
    52. }
    53.  
    54.  
    55. }
    56. // PLAY TONE ==============================================
    57. // Pulse the speaker to play a tone for a particular duration
    58. void playTone(int tone_, int duration_) ;
    59. // Loop variable to increase Rest length
    60. const int rest_count = 10; //<-BLETCHEROUS HACK; See NOTES
    61. long elapsed_time = 0;
    62.   // Set length of pause between notes
    63.   const int pause = 100;
    64.  
    65. if (tone_ > 0) { // if this isn't a Rest beat, while the tone has
    66.   // played less long than 'duration', pulse speaker HIGH and LOW
    67.   while (elapsed_time < duration_) {
    68.  
    69.   digitalWrite(speakerOut, HIGH);
    70.   delayMicroseconds(tone_ / 2);
    71.  
    72.   // DOWN
    73.   digitalWrite(speakerOut, LOW);
    74.   delayMicroseconds(tone_ / 2);
    75.  
    76.   // Keep track of how long we pulsed
    77.   elapsed_time += (tone_);
    78.  
    79.   }
    80. } else { // Rest beat; loop times delay
    81.   for (int j = 0; j < rest_count; j++) { // See NOTE on rest_count delayMicroseconds(duration);
    82.   }
    83. delayMicrosecond(pause);
    84.  
    85. }
    86. }
    87.  
    88.  
    89.  
    90. void loop() {
    91.   int mn = 1023; // mn only decreases
    92.   int mx = 0; // mx only increases
    93.  
    94.   // Perform 10000 reads. Update mn and mx for each one.
    95.   for (int i = 0; i < 5; ++i) {
    96.   int val = analogRead(analogPin);
    97.   mn = min(mn, val);
    98.   mx = max(mx, val);
    99.  
    100.  
    101.   }
    102.  
    103.  
    104.   if (threshold > mn) {
    105.   digitalWrite (ledPin, HIGH); // lights the LED
    106.   delay (100); // time LED stays lit once a rigger is met
    107.   playMelody();
    108.   delay (110); // this may no longer be necessary, since playMelody will cause a delay
    109.  
    110.   }
    111.  
    112.   else {
    113.   digitalWrite (ledPin, LOW); //LED is turned off if there is no movement
    114.   }
    115.  
    116.   // Send min, max and delta over Serial
    117.   Serial.print("m=");
    118.   Serial.print(mn);
    119.   Serial.print(" M=");
    120.   Serial.print(mx);
    121.   Serial.print(" D=");
    122.   Serial.print(mx - mn);
    123.   Serial.println();
    124. }
     
  13. Rickpercy87

    Thread Starter New Member

    Nov 20, 2015
    16
    0
    Thank you, I understand a little better now. I have decided to keep it simple and just use the tone feature. Im still very new to arduino and programming.
     
  14. odm4286

    Active Member

    Sep 20, 2009
    155
    5
Loading...