mercoledì 27 marzo 2013

Buzzer su Arduino

In questo esempio viene presentato l'utilizzo di un Buzzer alimentato su Arduino
Utilizzare questo componente permette di ottenere un suono di volume piu' alto rispetto ad un buzzer passivo


Quando arriva il componente e' dotato di una pellicola di protezione che deve essere rimossa dopo la saldatura


La pedinatura e' piuttosto semplice (+,- ed S) che corrispondono a (VCC,GND e Segnale)
Nello sketch successivo (ricopiato dal Playground di Arduino) il segnale e' collegato al Pin Digitale 4

-----------------------------------------------------------

#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);
  }
}

---------------------------------------------------
Aggiornamento:
a distanza di tempo mi sono reso conto che il codice e' poco leggibile e ridondante. Il codice minimale per emettere un suono e' il seguente
----------------------------------------------------
int speakerPin = 9;

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

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


void loop() {
playTone(400,1000);
delay(1000);
}

Nessun commento:

Posta un commento

FTP Bash script

 Uno script rubato su stack overflow per fare l'upload automatico su FTP senza criptazione   #!/bin/sh HOST='ftp.xxxxx.altervista.or...