Go Down

Topic: playFreq problem - no sound (Read 736 times) previous topic - next topic

sugardelta

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 ?
Code: [Select]


//********************************************************

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);
    delayMicroseconds(halfPeriod);
    digitalWrite(buzzerPin, LOW);
    delayMicroseconds(halfPeriod);
  }
}

//*******************************************************

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) {
   
    }
    else
    {
     delay(50);
     if(enableSound == true){
      playFreq(659.255, 75);
      playFreq(783.991, 75);
      playFreq(1046.500, 75);
    }
   
  }
  }

pert

Which Arduino board are you using?

Grumpy_Mike

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.

sugardelta

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.

pert

Code: [Select]
  int startTime = millis();
From the documentation for int:
https://www.arduino.cc/reference/en/language/variables/data-types/int/
Quote
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().

sugardelta

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. 

sugardelta

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 .

pert

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

Go Up