Here is example code showing how to use the state change detection to sense the transition of the button switch from unpressed to pressed to actuate the reading and saving of the humidity value.
// by C Goulding aka groundFungus
const byte buttonPin = 2; // the pin to which the pushbutton is attached
void setup()
{
// initialize the button pin as a input with internal pullup enabled
pinMode(buttonPin, INPUT_PULLUP);
// initialize serial communication:
Serial.begin(115200);
Serial.println("Read and save humidity with push button");
}
void loop()
{
static bool lastButtonState = 0; // previous state of the button
static unsigned long timer = 0;
unsigned long interval = 50; // check switch 20 times per second
if (millis() - timer >= interval)
{
timer = millis();
// read the pushbutton input pin:
bool buttonState = digitalRead(buttonPin);
// compare the new buttonState to its previous state
if (buttonState != lastButtonState)
{
if (buttonState == LOW)
{
// if the current state is LOW then the button
Serial.println("Reading and saving humidity");
// *********************************************************
// read the humidity sensor and save the value
//**********************************************************
}
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;
}
}