Go Down

Topic: Problem with Piezo - it just keeps buzzing (Read 732 times) previous topic - next topic

111windmills

Hi There,
I'm quite new to arduino and trying to learn as much as I can. I am only posting this because I have come up with a problem I just don't understand.

I'm using a Lilypad Protosnap Development Board to test out sketches before I make an actual "project".

I've been testing sounds using the buzzer.
When I use the example sketch, everything is fine, but on on my most recent attempt to create the BTTF theme song, the buzzer keeps buzzing after the melody has finished.
I've tested going back to the example sketch, which ends and goes silent. But on mine, it creates a distorted feedback noise.

Does anyone have any suggestions on why this is happening or how to fix it?
I greatly appreciate your time. Ive added my sketch below

Code: [Select]
/*
  Melody

 Plays Back to the Future music

 circuit:
 * 8-ohm speaker on digital pin 7


 */
 
#include "pitches.h"

// notes in the melody:
int melody[] = {
  NOTE_G5, 
  NOTE_C5,
 
  NOTE_FS5,
  0,
  NOTE_G5,
  NOTE_A5,
 
  NOTE_G5,
  NOTE_E5,
  NOTE_C5,
  NOTE_FS5,
  NOTE_G5,
  NOTE_A5,

  NOTE_G5,
  NOTE_D5,
  NOTE_G5,
  NOTE_D6,

  NOTE_D6,
  NOTE_CS6,
  NOTE_B5,
  NOTE_CS6,

  NOTE_D6
 



 
 
 
 
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  2,2,
  3,8,14,14,
  5,5,5,6,14,14,
  4,4,4,4,
  2,6,14,14,
  1
 

 
};

void setup() {
// iterate over the notes of the melody:
  for (int thisNote = 0; thisNote < sizeof(melody);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(7, 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(7);
   
  }
}

void loop() {
 

 
  }

jurs

Does anyone have any suggestions on why this is happening or how to fix it?
It is happening because you create buffer overflows in your melody array.
And you can possibly fix it by avoiding buffer overflows.

This for-loop is trying to play much more notes than you have defined:
Code: [Select]
for (int thisNote = 0; thisNote < sizeof(melody);thisNote++)

As "sizeof(int)==2" with 8-bit Atmega controllers, "sizeof(melody)" is twice as many bytes in size as the number of notes your array actually has defined.

When using a 32-bit DUE with "sizeof(int)==4" it's even worse by the number of buffer overflows you create in your sketch.

Go Up