Questions about saving given status in loop.

#include <SoftwareSerial.h>

#define BT_RXD 9
#define BT_TXD 8
SoftwareSerial bluetooth(BT_RXD, BT_TXD);
byte buffer[255];
#define buzzerPin 12
#define buttonPin2 3
#define buttonPin 2
volatile byte LEFTclick = LOW;
volatile byte RIGHTclick = LOW;
unsigned long pre_time = 0;
unsigned long cur_time = 0;
const int duration = 30 ; 

void setup() {
  pinMode(buzzerPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(buttonPin), LEFTclicked, RISING);
  attachInterrupt(digitalPinToInterrupt(buttonPin2), RIGHTclicked, RISING);

void loop() { 
        if (bluetooth.available()){
        long data = bluetooth.parseInt();
        int BPM = 60000/data;
        int Delay = BPM - 100;
        bluetooth.print(" BPM : ");
        tone(buzzerPin, 1108, 100);
        tone(buzzerPin, 1108, 100);
        tone(buzzerPin, 1108, 100);
        tone(buzzerPin, 2247, 100);
void LEFTclicked() {
  cur_time = millis();
   if(cur_time - pre_time >= duration) {
    pre_time = cur_time;

void RIGHTclicked() {
 cur_time = millis();
   if(cur_time - pre_time >= duration) {
    pre_time = cur_time;

I’m in trouble because of loop in this code.

I want to make a kind of metronome with bluetooth. (Arduino(S), Android(M)).

The functions i wanted in loop are as follows :

first, send the BPM from android to arduino i want to set up

second, ring the buzzer 4 times to the BPM like a metronome.

third, continue given state until send another BPM condition or power disconnect.

(if)fourth, when user change BPM from android to arduino, ring the buzzer 4 times to newly set BPM

When i run this code, first and second are run normally.

But after ring the buzzer 4 times, BPM changes to zero automatically.
( This situation is represented in the attached screenshot. )

So, i tried to find grammar which can save given status until user change, i can’t found examples what can help to solve this problem.

how can i solve this problem?

If you could give me some advice on this matter, I’d be very grateful. thanks.

If you want BPM to retain its value, declare it as a global variable and then just define the value when you get the Bluetooth data: