playFreq problem - no sound

Hello friends, I need some help, please. I just want to make a box with some push-buttons. Each one I press generate a kind of sound. I started with one button but this code below is not working good. Problem is after pressing 5 or 6 times (sound OK), there is no sound in the buzzer, just silence. What is wrong with this code ?


int buzzerPin = 4;
boolean enableSound = false;      //by default, there is no sound for this game
int btn = 7;


  void playFreq(double freqHz, int durationMs){
  // Calculate the period in microseconds
  int periodMicro = int((1/freqHz)*1000000);
  int halfPeriod = periodMicro/2;
  // store start time
  int startTime = millis();
  // (millis() - startTime) is elapsed play time
    while((millis() - startTime) < durationMs){
    digitalWrite(buzzerPin, HIGH);
    digitalWrite(buzzerPin, LOW);


void setup() {
  enableSound = true;  //turn on the sound for this game
  pinMode(buzzerPin, OUTPUT);

  //set swt and btn as input
  pinMode(btn, INPUT_PULLUP);


  void loop() {  
  if(digitalRead(btn) == HIGH) {
     if(enableSound == true){
      playFreq(659.255, 75);
      playFreq(783.991, 75);
      playFreq(1046.500, 75);

Which Arduino board are you using?

Have you wired the switch between the input and ground? Is that ground wired back to the Arduino ground?

If it is a 3V3 Arduino then try an external pull up resistor to 3V3 of 1K.

Grumpy_Mike , yes, I have wired the switch between input and GND , also using 10K resistor pull-up. Pert sorry for no info before but the Arduino that I am using is UNO.


  int startTime = millis();

From the documentation for int:

On the Arduino Uno (and other ATmega based boards) an int stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767

That means your code will only work as expected for the first 32 seconds. You should use the unsigned long data type with millis().

Hi pert , Many thanks for this information, I am not very good with this code, I used for long time ASM for microcontrollers .I will change this into the code. Soon I hope to give good news about.

Hi friends , I just to thank you for fast replay and for help. Now the code is working very good. Pert I used unsigned long in the code and it is OK now. Problem solved .

You're welcome. I'm glad to hear it's working now. Enjoy!