Loop problems - probably impossible

Hi guys. I’m new to arduino and this is my very first project (I know I should’ve started smaller). I’m trying to do an active keyless go thing for my car, where when you approach it unlocks and vice-versa. I’m using 2 HC-05 BT modules and I did managed to connect them to each other. The ‘State’ pin on the modules go ‘HIGH’ when they automatically connect to each other so I’m using that pin as my ‘HIGH’ or ‘LOW’ presented in my code as ‘btState’ to pin 2. Pins 3&4 will be physically wired to the lock and unlock buttons from my car’s original remote so this pins will act like me pressing either of the buttons. Now the problem is that by looking at my code you will see that depending of ‘btState’ the button is continuously pressed-simulating me holding the lock or unlock button permanently thus me adding those delays in there, but useless because now they are just ‘blinking’ on and off. I just want to find a way- any way- that after either of the buttons are activated for a short amount of time (simulating a finger press) they won’t be activated again and again in a loop. I still need the loop to continue work to keep checking for ‘btState’ and do the opposite action. I looked online like crazy every and I couldn’t find a solution, or found it but I wasn’t able to understand it since as I said- this is my first project ever. Thank you very much and I would really appreciate a solution.


int btState = 2;
int unlocked = 3;
int locked = 4;

void setup() {
  pinMode(btState, INPUT);
  pinMode(unlocked, OUTPUT);
  pinMode(locked, OUTPUT);
}

void loop() {
  if (digitalRead(btState) == HIGH) {
    digitalWrite(unlocked, HIGH);
    delay(500);
    digitalWrite(unlocked, LOW);
    delay(500);
  }
  else {
    digitalWrite(unlocked, LOW);
  }

  if (digitalRead(btState) == LOW) {
    digitalWrite(locked, HIGH);
    delay(500);
    digitalWrite(locked, LOW);
    delay(500);
  }
  else {
    digitalWrite(locked, LOW);
  }

}

Use a flow chart and describe every fase of what should happen.

Don't use the HIGH/LOW levels. Use the transition from one level to the other and launch a pulse.

Thanks. I'll start looking into it!

New code lines added. Few extra lines- those with the "flag". It seems to be working on simulation. Is this solution ok?

int btState = 2;
int unlocked = 3;
int locked = 4;
boolean flag1 = false;

void setup() {
  pinMode(btState, INPUT);
  pinMode(unlocked, OUTPUT);
  pinMode(locked, OUTPUT);
}
void loop() {

  if ((digitalRead(btState) == HIGH) && (flag1==false)) {
    digitalWrite(unlocked, HIGH);
    delay(500);
    digitalWrite(unlocked, LOW);
    delay(500);
    flag1 = true;
  }
  else {
    digitalWrite(unlocked, LOW);
  }

  if ((digitalRead(btState) == LOW) && (flag1==true)) {
    digitalWrite(locked, HIGH);
    delay(500);
    digitalWrite(locked, LOW);
    delay(500);
    flag1 = false;
  }
  else {
    digitalWrite(locked, LOW);
  }
}