#include <stdio.h>
#include "pico/stdlib.h"
int buttonPin = 22; // Define the GPIO pin used for the button
int buttonState = 0; // Current button state (0 for not pressed, 1 for pressed)
int lastButtonState = 0; // Last recorded button state
int buttonCount = 0; // Count of button presses
void setup() {
stdio_init_all(); // Initialize standard I/O for printing to the console
gpio_init(22); // Initialize GPIO pin 22
gpio_set_dir(22, GPIO_IN); // Set pin 22 as an input
gpio_set_input_hysteresis_enabled(22, 1); // Enable input hysteresis for better button debounce
lastButtonState = gpio_get(buttonPin); // Initialize lastButtonState with the initial button state
// This is used to store the state of the button at the previous iteration of the loop
// In a nutshell, it prevents the program from printing a false button press during boot
// And apparently prevents the user from holding down the button to increase the amount
printf("Initialization done\n"); // Print an initialization message to the console
}
void loop() {
buttonState = gpio_get(buttonPin); // Read the current state of the button
if (buttonState != lastButtonState) {
if (buttonState == 1) { // Check if the button has just been pressed (changed from 0 to 1)
buttonCount++; // Increment the button press count
if (buttonCount == 1) {
printf("Joku on painanut nappia nyt %d kerran!\n", buttonCount);
} else {
printf("Joku on painanut nappia nyt %d kertaa!\n", buttonCount);
}
}
}
lastButtonState = buttonState; // Update lastButtonState with the current button state
sleep_ms(100); // Sleep for 100 milliseconds (button state check every 100ms)
}
int main() {
setup(); // Call the setup function to initialize the environment
while (true) {
loop(); // Call the loop function repeatedly to monitor the button and print messages
}
return 0;
}