Piezo speaker - volume problem

I am having a little trouble with the piezo speaker. I connected it to digital pin 5 (because it has PWM) and GND - no resistors or anything. When I do analogWrite, I can hear the melody that I want but I have to have my ear realy close to the speaker. I am using very similar piezo (both are from computer motherboards) in one of my other projects and it is quite loud. But for some reason this one is not. I also tryed a normal "system speaker" - not piezo. I connected it via 100 ohm resistor - nothing. But without the resistor I can get some sound but again you can't realy hear it if you are not close to the speaker.

EDIT: tryed it on pin 11 - and for some reason here the whole thing plays a melody loud enough. Tryed another pin without PWM and it plays melody too. So why is it so quiet with pin 5 on two different boards?

Question: Why are you using analogWrite()?

Question: Why are you using analogWrite()?

I would guess because square waves in the audio spectrum are a good way to drive a piezo element! PWM outputs are about 500 and 1000 Hz depending on which timer the pin uses.

Yes, but unless you overcompicate things, analogWrite() only does one frequency.

Wouldn't one use something like:

digitalWrite(speakerPin, HIGH);
    delayMicroseconds(freq);
    digitalWrite(speakerPin, LOW);
    delayMicroseconds(freq);

My guesss for the volume switching pins solution is that pin 11 does not have PWM, so it essentially does digitalWrite() instead of analogWrite(). IDK though.

pwm is not what you want to be using, you do want to use the tone function or bitbang it like above

pwm does not effect the frequency anything oscillates at, it just varies the on time vs the off time

Yeah, definitely pwm is not the way to go.
I forgot about the tone library though.
Even easier than bitbanging!
Haven't used it though.

The library also allows for multiple tones at once!

well yea there is the way cool tone library, but also in arduino 18

  • Added tone() and noTone() functions for frequency generation.

http://arduino.cc/en/Reference/Tone

either would work, the arduino function is simpler (as in capability AND use)