arduino / arduino-examples

Arduino IDE bundled examples
Creative Commons Zero v1.0 Universal
92 stars 42 forks source link

Better code for Tone() tutorial [imported] #9

Open cmaglie opened 11 years ago

cmaglie commented 11 years ago

This is Issue 443 moved from a Google Code project. Added by 2011-01-01T08:42:15.000Z by fvdma...@gmail.com. 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.

kengdahl commented 3 years ago

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

per1234 commented 3 years ago

@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.
}