how to use a speaker?

Hi all,

I wrote a little program that plays a note on the speaker whenever it receives input, but I am having a problem. The program does not play a note, but a "clicking" sound. I based myself on the play_melody example to do this (which works perfectly), but since I don't really know what I'm doing :wink: I can't see why it doesn't work.

Both calls give a different "click", so the tone value does do something.

int speakerOut = 5;
int paddleTone = 1136;
int wallTone = 956;
int inData = 0;
  
 
void setup() {
  // set the pin modes
  pinMode(speakerOut, OUTPUT); 
  
  // begin sending over serial port
  Serial.begin(19200);
}


void loop() {
  if (Serial.available() > 0) {
    // read the incoming data
    inData = Serial.read();
     
    if (inData == 60) {
      // paddle collision
      digitalWrite(speakerOut,HIGH);
      delayMicroseconds(paddleTone);
      digitalWrite(speakerOut, LOW);
      delayMicroseconds(paddleTone);
    } else if (inData == 62) {
      // wall collision
      digitalWrite(speakerOut,HIGH);
      delayMicroseconds(wallTone);
      digitalWrite(speakerOut, LOW);
      delayMicroseconds(wallTone);
    }
  }
}

Thanks for the help!

dear

Each note has to have a "duration". In your code you are turning on and of the speaker just once. this produces the click you hear. You need to loop that click multiple times in order for it to become an audible sound.

great! that fixed it

i just wrapped the play sound code in a loop:

  ...
  for (int i=0; i < 75; i++) {
    digitalWrite(speakerOut,HIGH);
    delayMicroseconds(wallTone);
    digitalWrite(speakerOut, LOW);
    delayMicroseconds(wallTone);
  }
  ...