arduino-examples icon indicating copy to clipboard operation
arduino-examples copied to clipboard

Better code for Tone() tutorial [imported]

Open cmaglie opened this issue 12 years ago • 2 comments

This is Issue 443 moved from a Google Code project. Added by 2011-01-01T08:42:15.000Z by [email protected]. Please review that bug for more context and additional comments, but update this bug.

Original labels: Type-Enhancement, Priority-Medium, Component-Examples

Original description

Addition of rest notes in melody[] by specifying a note with value 0. Better name for noteDurations[], they are divisions, not durations. Real melody as example. Automatic counting of melody size with sizeof(). See attached file.

cmaglie avatar Nov 15 '12 18:11 cmaglie

@cmaglie The attached file does not exist anymore. Is this issue still relevant or can we archive it?

kengdahl avatar Jan 15 '21 10:01 kengdahl

@kengdahl it is available from the Wayback Machine: https://web.archive.org/web/20160708175612/http://code.google.com/p/arduino/issues/detail?id=443 Here are the contents of the file:

/*
 Melody
 
 Plays a melody 
 
 circuit:
 * 8-ohm speaker on digital pin 8
 
 created 21 Jan 2010, oct 2010
 by Tom Igoe 

 Modified 31-12-2010 by Frans van der Markt
 
 
This example code is in the public domain.
 
 http://arduino.cc/en/Tutorial/Tone
 
 */
#include "pitches.h"


int tonePin = 8;

// notes in the melody:

int melody[] = { // Hertog Jan, 0 is rest
   NOTE_C5, NOTE_C5,  NOTE_F5,  NOTE_F5, NOTE_G5, NOTE_G5, NOTE_A5, NOTE_G5, NOTE_F5, 0,
   NOTE_G5, NOTE_A5,  NOTE_F5,  NOTE_G5, NOTE_G5, NOTE_A5, NOTE_F5, NOTE_G5, 0,
   NOTE_C5, NOTE_F5,  NOTE_F5,  NOTE_G5, NOTE_G5, NOTE_A5, NOTE_G5, NOTE_F5, 0,
   NOTE_A5, NOTE_AS5, NOTE_C6,  NOTE_A5, NOTE_G5, NOTE_F5, NOTE_G5, NOTE_F5
};


// note types: 1 = whole note, 2 = half note 4 = quarter note, 8 = eighth note, etc.:
int noteDiv[] = {
   4, 4, 2, 2, 2, 2, 1, 4, 4,   4,
   2, 2, 2, 2, 2, 2, 2, 2,      4,
   2, 2, 2, 2, 2, 1, 4, 4,      4,
   4, 4, 2, 2, 4, 4, 2, 1
   
};

int num = sizeof(melody)/sizeof(int);

void setup() {
  // iterate over the notes of the melody:
  for (int thisNote = 0; thisNote < num; 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/noteDiv[thisNote];
    if (melody[thisNote] > 0) {
       tone(tonePin, melody[thisNote], noteDuration);
    }
    // to distinguish the notes, set a minimum time between them.
    // value 50 seems to work well:
    int pauseBetweenNotes = noteDuration + 50;
    delay(pauseBetweenNotes);
    noTone(tonePin);
  }
}

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

per1234 avatar Jan 15 '21 10:01 per1234