Operácie

Acrob005: Rozdiel medzi revíziami

Z SensorWiki

(Advanced example)
(Make Music)
Riadok 11: Riadok 11:
 
void setup()
 
void setup()
 
{
 
{
 +
 
// Example 1: tone of specified frequency and duration
 
// Example 1: tone of specified frequency and duration
  
Riadok 16: Riadok 17:
  
 
   delay(500);    //small pause
 
   delay(500);    //small pause
 +
 +
// Example 2: tone of specified frequency without duration
 
    
 
    
   tone(SPEAKER, 3000);        // 2kHz, forever
+
   tone(SPEAKER, 2000);        // 2kHz, forever
 
   delay(1000);                 
 
   delay(1000);                 
 
   noTone(SPEAKER);            // turn off sound.
 
   noTone(SPEAKER);            // turn off sound.

Verzia zo dňa a času 10:13, 12. jún 2010

Make Music

Speaker is a small electronic device which can make sounds if appropriate driven. Lets connect the speaker to the Arduino pin D4 (see schematic diagram and connection diagram below) and program it to make few tones.

ArduinoSpeaker.png
#define SPEAKER 4  // Piezospeaker connected to pin 4

void setup()
{

// Example 1: tone of specified frequency and duration

  tone(SPEAKER, 4000, 1000);   // 4kHz, 1 sec.

  delay(500);     //small pause

// Example 2: tone of specified frequency without duration
  
  tone(SPEAKER, 2000);         // 2kHz, forever
  delay(1000);                 
  noTone(SPEAKER);             // turn off sound.
}

void loop()
{
  /* do nothing */
}

For more details about the tone command see the Reference


How it works

Why robot needs to play music?

Advanced example

Following example shows more sound effects. It comes from the http://www.arduino.cc/en/Tutorial/Melody with just one minor (but important) change: the pinnumber is 4, not 9.

#define SPEAKER_Pin 4

  int length = 15;                                              // the number of notes
char notes[] = "ccggaagffeeddc ";                               // a space represents a rest
 int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
  int tempo = 300;

void playTone(int tone, int duration)
{
  for (long i = 0; i < duration * 1000L; i += tone * 2)
   {
     digitalWrite(SPEAKER_Pin, HIGH);
     delayMicroseconds(tone);
     digitalWrite(SPEAKER_Pin, LOW);
     delayMicroseconds(tone);
   }
}


void playNote(char note, int duration)
{
  char names[] = { 'c',  'd',  'e',  'f',  'g',  'a',  'b', 'C'  };
   int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };

  // play the tone corresponding to the note name
  for (int i = 0; i < 8; i++) {
    if (names[i] == note) {
      playTone(tones[i], duration);
    }
  }
}



void setup()
{
  pinMode(SPEAKER_Pin, OUTPUT);
}


void loop()
{
  for (int i = 0; i < length; i++) {
    if (notes[i] == ' ') {
      delay(beats[i] * tempo); // rest
    } else {
      playNote(notes[i], beats[i] * tempo);
    }

    // pause between notes
    delay(tempo / 2);
  }
}


< Previous | Home | Next >