BPM coding incorrect

My LCD display is showing the name of my device (MACHA), and the diagnosis next and the BPM is supposed to be shown last.

But the BPM is varying and changing really fast, it's showing 6 numbers and it's supposed to be less than 3 numbers.

Please advice

#define PEAK_THRESHOLD 0.3
#define ROLLING_SIZE 3
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16,2);
 
int value = 0;
float voltage;
bool peaked = false;
int bpm;
 
unsigned long beat_times[ROLLING_SIZE] = {0, 0, 0};
unsigned long current_time;
 
bool contains_zero() {
  for (int i = 0; i < ROLLING_SIZE; i++) {
    if (beat_times[i] == 0) {
      return true;
    }
  }
  return false;
}
 
void shift_times() {
  for (int i = 1; i < ROLLING_SIZE; i++) {
    beat_times[i - 1] = beat_times[i];
  }
}

void setup() {
    lcd.init();
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("MACHA TES");          
  Serial.begin(9600);
  delay(500);
}

void loop() {

   
  
  value = analogRead(A0);
  voltage = (value * 5.0/1023);
 
  current_time = millis();
 
  if (voltage > PEAK_THRESHOLD && !peaked) {
    peaked = true;
 
    shift_times();
    beat_times[ROLLING_SIZE - 1] = current_time;
  } else if (voltage <= PEAK_THRESHOLD && peaked) {
    peaked = false;
  }
  
  if (contains_zero()) {
    return;
  }
 
  bpm = (ROLLING_SIZE - 1) * 60000 / ( beat_times[ROLLING_SIZE - 1] - beat_times[0]);
  
    if (bpm >= 100){
      lcd.setCursor(0,1);
         lcd.print("Sinus Tachycardia");
         
    }
    else if (bpm <= 60){
      lcd.setCursor(0,1);
         lcd.print("Sinus Bradycardia");
          
    }
    else {
      lcd.setCursor(0,1);
         lcd.print("Normal Sinus");
          
    }
  lcd.setCursor(0,2);
    lcd.print(bpm);
     
}

make that constant explicitly an unsigned long so the entire equation uses unsigned long.
You also need to explicitly write a space or a leading 0 if bpm is less than 3 digits
And your messages are longer than 16 chars

  int bpm = (ROLLING_SIZE - 1) * 60000UL / ( beat_times[ROLLING_SIZE - 1] - beat_times[0]);

  lcd.setCursor(0, 1);
  if (bpm >= 100) {
    lcd.print("Sinus Tachycardia");
  }
  else if (bpm <= 60) {
    lcd.print("Sinus Bradycardia");
  }
  else {
    lcd.print("Normal Sinus");
  }

  lcd.setCursor(0, 2);
  if ( bpm < 100 ) lcd.print(' ');
  if ( bmp < 10  ) lcd.print(' ');
  lcd.print(bpm);

Thank you for your fast reply. My BPM is still going a little bit higher and now it’s showing this :sweat_smile::sweat_smile:

If any characters from previous print statements remain on the line after "bpm" is printed, you will be confused. Add another blank or two to erase them.

  lcd.setCursor(0, 2);
  if ( bpm < 100 ) lcd.print(' ');
  if ( bmp < 10  ) lcd.print(' ');
  lcd.print(bpm);
  lcd.print("    ");   //erase a few trailing characters

Or appropriately declare your variable. An int can be -32768..32767 but your bpm should really only be 0..255. if you make it a byte type, it cannot print more than 3 digits