#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <unistd.h>
/* Button pin definitions (BCM numbering) */
#define BUTTON_UP RPI_V2_GPIO_P1_36 // GPIO 16
#define BUTTON_DOWN RPI_V2_GPIO_P1_28 // GPIO 1
#define BUTTON_LEFT RPI_V2_GPIO_P1_26 // GPIO 7
#define BUTTON_RIGHT RPI_V2_GPIO_P1_24 // GPIO 8
/* Array of button pins */
const uint8_t buttons[] = {BUTTON_UP, BUTTON_DOWN, BUTTON_LEFT, BUTTON_RIGHT};
/* Array of direction names */
const char *direction_map[] = {"Up", "Down", "Left", "Right"};
/* Configure button pins */
void configura_pinos() {
for (int i = 0; i < 4; i++) {
bcm2835_gpio_fsel(buttons[i], BCM2835_GPIO_FSEL_INPT); // Set as input
bcm2835_gpio_set_pud(buttons[i], BCM2835_GPIO_PUD_UP); // Enable pull-up
bcm2835_gpio_fen(buttons[i]); // Enable falling edge detection
}
}
/* Signal handler for clean exit */
void trata_interrupcao(int sinal) {
bcm2835_close();
exit(0);
}
int main(int argc, char **argv) {
if (!bcm2835_init()) {
printf("Failed to initialize bcm2835 library\n");
return 1;
}
configura_pinos();
signal(SIGINT, trata_interrupcao);
while (1) {
for (int i = 0; i < 4; i++) {
bcm2835_gpio_set_eds(buttons[i]); // Clear event status
if (bcm2835_gpio_eds(buttons[i])) { // Check for event
printf("Direction: %s\n", direction_map[i]);
fflush(stdout);
/* Wait for button release to prevent multiple triggers */
while (bcm2835_gpio_lev(buttons[i]) == LOW) {
usleep(100000); // 100ms delay for debouncing
}
}
}
usleep(100000); // 100ms sleep to reduce CPU usage
}
bcm2835_close();
return 0;
}