Check to see if button state has changed?

Hi guys,

First, a little background...

I came here a while back asking about the feasibility of using an Arduino Leonardo and push buttons to control a PowerPoint for part of my Chemistry project. Well, I've got it all working, and it's wonderful.

My code (only for two buttons right now, will be for fifteen by the end):

void setup()
 {
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() 
{
  //if the button is pressed
  if(digitalRead(0)==LOW)
  {
    //Send the message
    Keyboard.println("2");
  }
  if(digitalRead(1)==LOW)
  {
    Keyboard.println("3");
  }
}

It works wonderfully, but when you push a button it sends a slew of whatever number is assigned to that button. Now, that doesn't really affect the PowerPoint, but it would make me happier knowing it was cleaner. So what I'd like to do is just have the program check if the button state has changed, and then send only ONE number. Does that make sense?

I've done some searching but I honestly am pretty new to Arduino so I'm not really sure of what I'm looking for. Any help or nudge in the right direction would be great!

You look for a state change. If the new reading is different from the old reading. Then if the new reading is LOW, the button is pressed. After you check, save the current reading as the old reading.

You also might want to debounce. Something like:

  //if the button is pressed
  byte newReading0 = digitalRead(0);
  static byte oldReading0 = HIGH;     // 'static' is remembered each time through loop

  if((newReading0 != oldReading0) && (newReading0 == LOW))
  {
    delay (10);  // debounce
    //Send the message
    Keyboard.println("2");
  }

  oldReading0 = newReading0;

An array might help you here, rather than repeating the same code 10 times.

Fairly easy.

#define BUTTON0_PRESSED 0x01 //if button0 is pressed
#define BUTTON1_PRESSED 0x02 //if button1 is pressed

unsigned char read_buttons(unsigned char button0, unsigned char button1) {
  static unsigned char buttons_prev= 0x00; // previous button
  unsigned char tmp;

  //save the previous value
  tmp = buttons_prev;
  //read buttons
  buttons_prev = (digitalRead(button1)?0x00: BUTTON1_PRESSED) | (digitalRead(button0)?0x00:BUTTON0_PRESSED); //buttons active low
  return buttons_prev ^ tmp; //0x01 is button 0 changed state, 0x02 if button 1 changed state, 0x03 if both changed state
}

You can also detect rising or falling edges from this easily.