Your function is a little wrong. If you look at the debounce example, there is only one digitalRead. From your code
int reading = digitalRead(buttonPin);
buttonState = digitalRead(buttonPin);
and
if (reading != buttonState) {
Chances are slim that they differ after the debounce period.
The readButton function in below code is basically the debounce example placed in a function; I've stripped the things that don't relate to the button.
Note that the code does not use LOW and HIGH but ISPRESSED; makes it easier to read. LOW does not mean much, ISPRESSED a lot more. I think that you use an external pull-up; if not, add one or change the pinMode statement to use the internal pull-up. If you use an external pull-down, change LOW in the first line to HIGH.
For demonstration purposes, I've added loop and setup.
#define ISPRESSED LOW
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
// Variables will change:
int buttonState = !ISPRESSED; // the current reading from the input pin
int lastButtonState = !ISPRESSED; // the previous reading from the input pin
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
void setup()
{
Serial.begin(57600);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop()
{
static int lastState = !ISPRESSED;
int state = readButton();
if (state != lastState)
{
Serial.print(millis());
Serial.print(": Button state = ");
Serial.println(state == ISPRESSED ? "Pressed" : "Released");
lastState = state;
}
}
/*
read button
Returns:
last statble state
*/
int readButton()
{
// read the state of the switch into a local variable:
int reading = digitalRead(buttonPin);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited long enough
// since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState)
{
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay)
{
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState)
{
buttonState = reading;
}
}
// save the reading. Next time through the loop, it'll be the lastButtonState:
lastButtonState = reading;
// return the last stable button state
return buttonState;
}
The loop contains the state change detection.
I suggest that you use the readButton function, move the functionality of loop to checkButton and take it from there.