edensheiko

button press command.

Jan 21st, 2023
1,172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.11 KB | Software | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4.  
  5. #define BUTTON_PIN "P8_11"
  6. #define LED_PIN "P8_13"
  7.  
  8. int main(int argc, char *argv[]) {
  9.     // Export the button and LED pins
  10.     system("echo " BUTTON_PIN " > /sys/class/gpio/export");
  11.     system("echo " LED_PIN " > /sys/class/gpio/export");
  12.  
  13.     // Set the button pin as an input
  14.     system("echo in > /sys/class/gpio/gpio" BUTTON_PIN "/direction");
  15.  
  16.     // Set the LED pin as an output
  17.     system("echo out > /sys/class/gpio/gpio" LED_PIN "/direction");
  18.  
  19.     while (1) {
  20.         // Read the button state
  21.         FILE *button_file = fopen("/sys/class/gpio/gpio" BUTTON_PIN "/value", "r");
  22.         int button_state = fgetc(button_file) - '0';
  23.         fclose(button_file);
  24.  
  25.         // If the button is pressed, turn on the LED
  26.         if (button_state == 0) {
  27.             system("echo 1 > /sys/class/gpio/gpio" LED_PIN "/value");
  28.         } else {
  29.             system("echo 0 > /sys/class/gpio/gpio" LED_PIN "/value");
  30.         }
  31.  
  32.         // Wait for a bit before reading the button state again
  33.         usleep(100000);
  34.     }
  35.  
  36.     return 0;
  37. }
  38.  
Tags: bbg
Advertisement
Add Comment
Please, Sign In to add comment