0

I'm trying to make the piezo speaker play a sound of certain frequency. However, although I think the code is fine, the sound plays with a frequency between 130 ~160 only, and the frequency actually drops when it should be going up.

The code is as below:

digitalWrite(buzzer, LOW);
delayMicroseconds(1000000 / frequency);
digitalWrite(buzzer, HIGH);
delayMicroseconds(1);

What could be the problem?

2

Have you looked at the Tone library? That does what you want, with some other niceties besides.

Anyway, the (or at least "a") problem with your code is that you are leaving the signal LOW almost all the time. You want it to spend half the time high, half the time low:

digitalWrite(buzzer, LOW);
delayMicroseconds(500000 / frequency);
digitalWrite(buzzer, HIGH);
delayMicroseconds(500000 / frequency);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.