Do only once when threshold is crossed?

Hi, I’m working on an interactive gingerbread house, and I’m trying to make it so the door opens when a person walks within ~20 inches. I’m using a ping sensor and a servo. I’m trying to run a ping reading every second and only send a pulse to the servo once when the 20 inch is crossed either way. Here’s what I’ve got:

takereading();
if(inches < 20){
    open();
  }
  else{
    close();
  }

void open(){    
  door.write(50);
  Serial.print("open");
  Serial.println();
}

void close(){      
  door.write(90);
  Serial.print("close");
  Serial.println();
}

this obviously gives an “open” command to the servo every time the ping sensor takes a reading of <20, and a “close” command to it every time it is >=20. I’d like it to send it once when the threshold is crossed the one way, then wait until the distance crosses the threshold again to send the matching command. I know this is probably a simple question, but I seem to have blanked out. :roll_eyes: Thanks!
~Alex

Global variables:
bool doorOpen = false;
bool doorClosed = true;

Add some code:

takereading();
if(inches < 20)
{
    if(doorClosed && !doorOpen)
    {
      open();
      doorClosed = false;
      doorOpen = true;
    }
}
else
{
    if(doorOpen && !doorClosed)
    {
       close();
       doorClosed = true;
       doorOpen = false;
    }
}

On the other hand, writing the same value to a servo many times makes do difference to the servo. The hardware is doing that, anyway.

Add a boolean variable recording whether the door is currently closed.

If it's closed and you decide it should be open, open it and record that it's open. If it's open and you decide it should be closed, close it and record that it's closed.

thank you both! I tried boolean variables, but couldn't seem to get them in the right spot. Got it now!