#include <stdio.h> // Standard input-output library
#include "pico/stdlib.h" // Standard library for Raspberry Pi Pico
#include "hardware/gpio.h" // Hardware-specific GPIO library
class GPIOControl {
private:
const uint FIRST_GPIO = 2; // Starting GPIO pin for 7-segment display
const uint BUTTON_GPIO = FIRST_GPIO + 7; // GPIO pin for the button
const int bits[10] = { // Bit patterns for displaying digits 0-9 on the 7-segment display
0x3f, // 0
0x06, // 1
0x5b, // 2
0x4f, // 3
0x66, // 4
0x6d, // 5
0x7d, // 6
0x07, // 7
0x7f, // 8
0x67 // 9
};
public:
GPIOControl() {}
void setup() {
stdio_init_all(); // Initialize standard I/O
// Initialize GPIO pins for 7-segment display
for (uint gpio = FIRST_GPIO; gpio < FIRST_GPIO + 7; gpio++) {
gpio_init(gpio); // Initialize GPIO pin
gpio_set_dir(gpio, GPIO_OUT); // Set GPIO pin direction to output
gpio_set_outover(gpio, GPIO_OVERRIDE_INVERT); // Set GPIO output override to invert
}
// Initialize button GPIO pin
gpio_init(BUTTON_GPIO); // Initialize GPIO pin for the button
gpio_set_dir(BUTTON_GPIO, GPIO_IN); // Set GPIO pin direction to input
gpio_pull_up(BUTTON_GPIO); // Enable pull-up resistor for the button
}
void updateCounter() {
int val = 0; // Initialize counter value
// Continuous loop for updating counter
while (true) {
if (!gpio_get(BUTTON_GPIO)) { // Check if the button is pressed
if (val == 9) {
val = 0; // Reset counter if it reaches 9
} else {
val++; // Increment counter
}
} else { // Button not pressed
if (val == 0) {
val = 9; // Reset counter to 9 if it reaches 0
} else {
val--; // Decrement counter
}
}
// Set GPIO pins based on the value of the counter to display the corresponding digit
uint32_t mask = bits[val] << FIRST_GPIO; // Shift the bit pattern to the correct GPIO pins
gpio_set_mask(mask); // Set GPIO pins according to the mask
sleep_ms(1000); // Delay for 1 second
gpio_clr_mask(mask); // Clear GPIO pins
}
}
};
int main() {
stdio_init_all(); // Initialize standard I/O
printf("Hello! Nice to see you! - press button to count up or down!\n"); // Print a greeting message
GPIOControl gpioControl; // Create an instance of GPIOControl class
gpioControl.setup(); // Call setup function to initialize GPIO pins
gpioControl.updateCounter(); // Call updateCounter function to update counter based on button press
return 0; // Return 0 to indicate successful execution
}