Simple Button Question


I am sure it is super easy but has me a bit stumped, wondering if there is a easy way of calling another routine etc only ONCE after a button press. The user presses the button and the routine gets called only once no matter how long the user has the button pressed. With the code below as long as the user has the button pressed the digitalWrite(ledPin, HIGH); code would be repeatedly called. I am sure I could put a flag in the function so if true the routine does not execute, and when the button is LOW the flag is reset

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);      
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);    

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {    
    // turn LED on:    
    digitalWrite(ledPin, HIGH);  //For example only want this to fire once when the button is constantly pressed
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);


You call the routine when the button IS NOW pressed and WAS NOT pressed before. In other words, you look for a transition, not whether or not it is pressed.

Thank you very much Nick. Much appreciated.