LCD problem.

I am trying to create a project where the frequency of a blinking LED increases until the blinking can’t be seen anymore. At that time I want to press a button, the blinking stops, and the frequency (measured in Hz) is printed on an LCD.

However, when I go to press the button it won’t work if I only press on it momentarily. I have to hold it down for a few seconds and even then the LCD only displays “inf” instead of a numerical value as I want it to.

What do I need to change in my code and/or my circuit in order to make this work? (I have attached my circuit diagram as a picture)

#include <LiquidCrystal.h>


LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
float dtime;
int LEDpin=13;
int Bpin=6;

void setup() {
  
  lcd.begin(16, 2);
  
  lcd.print("frequency");
  while (digitalRead(Bpin) == HIGH) {
  for (float dtime = 500; dtime > 2; dtime = dtime * 0.8) {
  digitalWrite(LEDpin, HIGH);
  delay(dtime);
  digitalWrite(LEDpin, LOW);
  delay(dtime);
}
}
  
  lcd.setCursor(0, 1);
  
  lcd.print(1 / dtime);
}

void loop() {
  
}

your for() loop has to completely finish before you get around to the while() statement again at which time you check your button press.

You need to study the Blink Without Delay example in the IDE to learn how to get rid of those delay() functions so your program is more responsive to button presses.

You should also check out the Several Things at the Same time to see how to adjust your frequency and check buttons and ... without any for() loop

As for why you are getting 'Inf' in your output - You are declaring a global variable dtime which gets initialized to 0.0. Inside your for loop, you are creating a different local variable that just happens to have the same name. After you exit the for(), that local variable you have been changes goes out of scope and the global variable is still at 0.0