Combining two arduino sketches

Thread Starter

Rickpercy87

Joined Nov 20, 2015
18
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:
[/B]
const int analogPin = 0;
const int threshold = 500;
int ledPin = 13;

void setup()
{
  Serial.begin(9600);
  pinMode (ledPin, OUTPUT); 
}

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 < 700; ++i) {
    int val = analogRead(analogPin);
    mn = min(mn, val);
    mx = max(mx, val);

  }

if (threshold > mn)
{
digitalWrite (ledPin, HIGH);

}

else {
digitalWrite (ledPin, 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(); 
}
 

dannyf

Joined Sep 13, 2015
2,197
Easy:

Code:
//sketch1/2 variables here
varable 1....;

//sketch1 setup here
void setup1(void) {
...
}

//sketch2 setup here
void setup2(void) {
...
}

//sketch1 loop here
void loop1(void) {
...}

//sketch 2 loop here
void loop2(void) {
...
}

//combined setup
void setup(void) {
  setup1();  //sketch 1 setup
  setup2();  //skethc 2 setup
}

//combined loop
void loop(void) {
  loop1();  //sketch 1 loop
  loop2();  //sketch 2 loop
}
Done.
 

Thread Starter

Rickpercy87

Joined Nov 20, 2015
18
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.
 

dacflyer

Joined Nov 19, 2010
31
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
 

djsfantasi

Joined Apr 11, 2010
9,163
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

C:
  const int analogPin = 0;
       const int buzzerPin=10; // add this line
  const int threshold = 500;
  int ledPin = 13;

  void setup()
  {
  Serial.begin(9600);
  pinMode (ledPin, OUTPUT);
      pinMode (buzzerPin, OUTPUT);  // add this pin
  }

  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 < 700; ++i) {
  int val = analogRead(analogPin);
  mn = min(mn, val);
  mx = max(mx, val);

  }

  if (threshold > mn)
  {
  digitalWrite (ledPin, HIGH);
       buzzer(); // add this line

  }

  else {
  digitalWrite (ledPin, 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();
  }

// new buzzer function
void buzzer() 
  const unsigned long timeBuzzer=1000; // milliseconds
  unsigned long endTime=millis() + timeBuzzer;
  digitalWrite(buzzerPin,HIGH);
  while (millis() < endTime);
  digitalWrite(buzzerPin,LOW);
}
 

Thread Starter

Rickpercy87

Joined Nov 20, 2015
18
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();
}
 

DNA Robotics

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

Code:
/*
  Melody

Plays a melody

circuit:
* 8-ohm speaker on digital pin 8

created 21 Jan 2010
modified 30 Aug 2011
by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Tone

*/
#include "pitches.h"

// notes in the melody:
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

void setup() {
  // iterate over the notes of the melody:
  for (int thisNote = 0; thisNote < 8; thisNote++) {

    // to calculate the note duration, take one second
    // divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(8, melody[thisNote], noteDuration);

    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    // stop the tone playing:
    noTone(8);
  }
}

void loop() {
  // no need to repeat the melody.
}
 

djsfantasi

Joined Apr 11, 2010
9,163
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.

C:
const int analogPin = 0;
const int threshold = 3;
const int ledPin = 13;
const 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);
}

// PLAY MELODY  ============================================
void playMelody() {
  // MELODY and TIMING
  // melody[] is an array of notes, accompanied by beats[],
  // which sets each note's relative length (higher #, longer note)
  const int melody[] = { C, b, a, g, f, e, b, a, C, b };
  const 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
  const long tempo = 2500; // Not used

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

  for (int note = 0; note <= MAX_COUNT; note++) {
  playTone(melody[note], beats[note]);
  }
}


}
// PLAY TONE ==============================================
// Pulse the speaker to play a tone for a particular duration
void playTone(int tone_, int duration_) ;
// Loop variable to increase Rest length
const int rest_count = 10; //<-BLETCHEROUS HACK; See NOTES
long elapsed_time = 0;
  // Set length of pause between notes
  const int pause = 100;

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);
  }
delayMicrosecond(pause);

}
}



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
  playMelody();
  delay (110); // this may no longer be necessary, since playMelody will cause a delay

  }

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

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

Thread Starter

Rickpercy87

Joined Nov 20, 2015
18
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.
 
Top