Calculation mistake

Hi, i have an issue with my code : I am working on a buzzer that goes faster and faster and so i am using the formula : timeBetweenBeep = 100 + 900 * (timeLeft / InitialTime ) to get the time between each beeps but my issue is that it always give me 100 when i execute it instead of a number between 1 and 0
Here is the code :

int timeBetweenBeep = 0;
int timeByBeep = 125;

void setup() {
  Serial.begin(9600);
  
}


void loop() {
  int timeLeft = 40000 - millis();
    if(timeLeft > 0){
  Serial.println(timeLeft);
  delay(100);
  int timeBetweenBeep = 100 + 900 * (timeLeft / 40000);
  Serial.println(timeBetweenBeep);
  }
}

If hopefully someone can help me.

if you only have 100, either timeLeft or InitialTime are zero... or if InitialTime is very large compared to timeLeft that will bring 900 close to zero.

It is not the case because

Serial.println(timeLeft);

give me more than 0

and InitialTime is 40000ms

You will want anything using millis() to be unsigned long... because int can not hold such a large value.... so try unsigned long timeLeft

Couple of issues.

Max int is 32,767... (16 bit).

timeLeft is an int... so biggest timeLeft / 40000 can ever be is 32,767 / 40000 ... and since it can't hold decimal places... this will equate to 0.

Changed the variables from int to unsigned long but still the same issue

timeBetweenBeep can never be 1 or 0, or anything in between.

So what is "it"?

It's the time in ms between each beep but my bad i said between 1 and 0 but it's 1000 and 0

Needs to be signed or it will always be > 0.

Did you consider the division (timeLeft / 40000) when the result is an integer ? What do you think that produces?

Try this...

void setup() 
{
  Serial.begin(9600);
}

void loop()
{
  long timeLeft = 40000 - millis();

  if (timeLeft > 0)
  {
    int timeBetweenBeep = 100 + 900 * (timeLeft / 40000.0);
    Serial.println(timeBetweenBeep);
  }
  delay(100);
}

Looks like it's working thank you very much

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.