Help With Understanding/Merging Code

This may be a long one so bear with me...

What I have is an RFID reader outputting the card data to the serial monitor. Connected to this is a Piezo buzzer capable of different pitches/tones. When I run a card over the reader the buzzer beeps.

Code for this.

This program gets data from the ID12 RFID reader and displays it to the serial monitor
*/

char val = 0; // Value of read from Serial 

void setup() { 
      
      Serial.begin(9600);                   // connect to the serial port 
      } //end of setup


void loop () { 

      char IDstring[13]; 
      int i; 
      
        //if data is available on the serial buffer
      if (Serial.available() > 0 ) { 
            if ( (val = Serial.read()) == 02 ) {             // look for Start Of Text marker (i.e ASCII "02") 
                  Serial.print("[SOT] ");       
      
                  // read until you get End Of Text 
                  for ( i = 0; (val = Serial.read()) != 03 ; i++) { 
                     Serial.print(val, DEC); // Display val in Hexadecimal  
                           Serial.print(" "); 
                     IDstring[i] = val; 
                  } 
                  
                        Serial.println("[EOT]"); 
                  Serial.println(); 
                  Serial.print(" IDString = "); 
                  IDstring[10] = 0x00; //             tie off IDstring at the CR-LF 
                  Serial.print(IDstring); 
                  Serial.println(" "); 
                  Serial.println(); 
                  
            } 
      } 

}//end of loop

Wiring Diagram -

The buzzer is currently in place of the LED. It beeps briefly when any card is ran over it.

What I want to do is have the ID's of different cards corresponding with different notes. An example I found that describes the notes that I want is as follows.

/* Play Melody
 * -----------
 *
 * Program to play a simple melody
 *
 * Tones are created by quickly pulsing a speaker on and off 
 *   using PWM, to create signature frequencies.
 *
 * Each note has a frequency, created by varying the period of 
 *  vibration, measured in microseconds. We'll use pulse-width
 *  modulation (PWM) to create that vibration.

 * We calculate the pulse-width to be half the period; we pulse 
 *  the speaker HIGH for 'pulse-width' microseconds, then LOW 
 *  for 'pulse-width' microseconds.
 *  This pulsing creates a vibration of the desired frequency.
 *
 * (cleft) 2005 D. Cuartielles for K3
 * Refactoring and comments 2006 clay.shirky@nyu.edu
 * See NOTES in comments at end for possible improvements
 */

// TONES  ==========================================
// Start by defining the relationship between 
//       note, period, &  frequency. 
#define  c     3830    // 261 Hz 
#define  d     3400    // 294 Hz 
#define  e     3038    // 329 Hz 
#define  f     2864    // 349 Hz 
#define  g     2550    // 392 Hz 
#define  a     2272    // 440 Hz 
#define  b     2028    // 493 Hz 
#define  C     1912    // 523 Hz 
// 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;
// Do we want debugging on serial out? 1 for yes, 0 for no
int DEBUG = 1;

void setup() { 
  pinMode(speakerOut, OUTPUT);
  if (DEBUG) { 
    Serial.begin(9600); // Set serial out if we want debugging
  } 
}

// 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,  g,  C,  b,   e,  R,  C,  c,  g, a, C };
int beats[]  = { 16, 16, 16,  8,  8,  16, 32, 16, 16, 16, 8, 8 }; 
int MAX_COUNT = sizeof(melody) / 2; // Melody length, for looping.

// Set overall tempo
long tempo = 10000;
// Set length of pause between notes
int pause = 1000;
// Loop variable to increase Rest length
int rest_count = 100; //<-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);  
    }                                
  }                                 
}

// LET THE WILD RUMPUS BEGIN =============================
void loop() {
  // Set up a counter to pull from melody[] and beats[]
  for (int i=0; i<MAX_COUNT; i++) {
    tone = melody[i];
    beat = beats[i];

    duration = beat * tempo; // Set up timing

    playTone(); 
    // A pause between notes...
    delayMicroseconds(pause);

    if (DEBUG) { // If debugging, report loop, tone, beat, and duration
      Serial.print(i);
      Serial.print(":");
      Serial.print(beat);
      Serial.print(" ");    
      Serial.print(tone);
      Serial.print(" ");
      Serial.println(duration);
    }
  }
}

I left the entire thing there for both credit and clarification as I'm not aiming for anything elaborate such as the entire song playing. Just a single note (from C to C (8 cards)) per card ID.

An example of a card id... IDString = 2500ABD554

The problem I have is that I don't understand what activates the buzzer in the first place, and I don't know how to merge code properly.

Thanks for any help I receive/whoever reads this :slight_smile:

The problem I have is that I don't understand what activates the buzzer in the first place, and I don't know how to merge code properly.

The buzzer is an electrical device. Something needs to send current to it to make it do something. The thing that sends current to it is a digital pin, activated with a call to digitalWrite, in the playTone function.

What you want to do is call playTone function, after setting tone to the appropriate value, based on which RFID tag was scanned.

Thanks for the quick reply. Stupid question... but how does that mean I need to plug the buzzer in through one of the digital pins on the board? How would that work with its current position/the RFID being on the board.

An update... I now have each card working with a note from a low C to B (7 cards). I also have an 8th card that plays back what notes have been played and then clears the memory.

In short... my work is done on this one :smiley:

The code if anyone is interested, it's not properly commented etc yet and it's kinda hacky but that will be done in future.

/* RFID Loop * by Alexander Reeder, Nov 16, 2007 * Modified by Brian Riley January 2008 */ 
/* Modified by Riccardo Lazzarini October 2009 
This program gets data from the ID12 RFID reader and displays it to the serial monitor
*/

char val = 0; // Value of read from Serial 
int notes[512];
int counter = 0;
int speakerOut = 9;
void setup() { 
       pinMode(speakerOut, OUTPUT);

      
      Serial.begin(9600);                   // connect to the serial port 
} //end of setup






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

// SETUP ============================================


// Do we want debugging on serial out? 1 for yes, 0 for no
int DEBUG = 1;



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

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

// Initialize core variables
int sound = 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 (sound > 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(sound / 2);

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

      // Keep track of how long we pulsed
      elapsed_time += (sound);
    } 
  }
  else { // Rest beat; loop times delay
    for (int j = 0; j < rest_count; j++) { // See NOTE on rest_count
      delayMicroseconds(duration);  
    }                                
  }                                 
}

// LET THE WILD RUMPUS BEGIN =============================
void loop1() {
  // Set up a counter to pull from melody[] and beats[]
  for (int i=0; i<MAX_COUNT; i++) {
    sound = melody[i];
    beat = beats[i];

    duration = beat * tempo; // Set up timing

    playTone(); 
    // A pause between notes...
    delayMicroseconds(pause);

    if (DEBUG) { // If debugging, report loop, tone, beat, and duration
      Serial.print(i);
      Serial.print(":");
      Serial.print(beat);
      Serial.print(" ");    
     // Serial.print(tone);
      Serial.print(" ");
      Serial.println(duration);
    }
  }
}



void loop () { 

      char IDstring[13]; 
      int i; 
      
        //if data is available on the serial buffer
      if (Serial.available() > 0 ) { 
            if ( (val = Serial.read()) == 02 ) {             // look for Start Of Text marker (i.e ASCII "02") 
                  Serial.print("[SOT] ");       
      
                  // read until you get End Of Text 
                  for ( i = 0; (val = Serial.read()) != 03 ; i++) { 
                     Serial.print(val, DEC); // Display val in Hexadecimal  
                           Serial.print(" "); 
                     IDstring[i] = val; 
                  } 
                  
                        Serial.println("[EOT]"); 
                  Serial.println(); 
                  Serial.print(" IDString = "); 
                  IDstring[10] = 0x00; //             tie off IDstring at the CR-LF 
                  Serial.print(IDstring); 
                  Serial.println(" "); 
                  Serial.println(); 
                        selectCard(IDstring);
                  
            } 
      } 

}//end of loop
      
void selectCard(char cardID[13]){
  
  boolean cardFound = true;
  
  char* cards [] = {"2500ABE4F6","2500AC1DBC","2500AC02C1","2500AC072E","2500ABD5F1","2500AC17E0","2500ABD554",
                    "2500AC07CE"};
  
  
  for(int n = 0; n < 8; n++){
    
    char* currentCard = cards[n];
    cardFound = true;
    for(int i = 0; i<10;i++){
        if(cardID [i] == currentCard[i]){}
        else{
            cardFound = false;
            break;
        }
     }
     if(cardFound == true && n!=7){
     Serial.println("Note Found");
     Serial.println(cardID);
     sound = melody[n];
     beat = 16;
     notes[counter] = n;
     duration = beat * tempo; // Set up timing
     playTone();
     counter++;
     break;}
     
     if(cardFound == true && n == 7){
     Serial.println("End Found");
     Serial.println(cardID); 
     notes[counter] = 10;
      int current = 0;
      counter = 0;
      current = notes[counter];
       while(current < 8){
         Serial.print(" ");
         Serial.println(current);
         Serial.println(" ");
         sound = melody[current];
         beat = 16;
         duration = beat * tempo; // Set up timing
         playTone();
         counter ++;
         current = notes[counter];
         delayMicroseconds(pause);  
       }
       counter = 0;
       break;
     }
  

  
  
 
    
  
  }
}

Congrats. Feels good to get one working, doesn't it?

Absolutely, helps that my brother has a degree in CS I guess... but still haha.