-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpoweroff-button.c
More file actions
65 lines (54 loc) · 1.68 KB
/
poweroff-button.c
File metadata and controls
65 lines (54 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <poll.h>
// Set up the button pin and the system poweroff command
#define BUTTON_PIN "2"
// const char *POWER_OFF_COMMAND[] = {"sudo", "poweroff", NULL};
// Define the button press callback function
void button_callback(void) {
printf("Button pressed, powering off system...\n");
system("poweroff");
}
int main(void) {
int fd, len;
char buf[2];
struct pollfd pfd;
// Export the button pin
fd = open("/sys/class/gpio/export", O_WRONLY);
len = snprintf(buf, sizeof(buf), "%s", BUTTON_PIN);
write(fd, buf, len);
close(fd);
// Set the button pin direction and edge
fd = open("/sys/class/gpio/gpio2/direction", O_WRONLY);
write(fd, "in", 2);
close(fd);
fd = open("/sys/class/gpio/gpio2/edge", O_WRONLY);
write(fd, "rising", 6);
close(fd);
// Open the button value file descriptor for polling
fd = open("/sys/class/gpio/gpio2/value", O_RDONLY);
// Set up the poll structure for the button file descriptor
pfd.fd = fd;
pfd.events = POLLPRI;
// Wait for button press
printf("Waiting for button press...\n");
int first_interrupt = 0;
for (;;) {
poll(&pfd, 1, -1);
lseek(fd, 0, SEEK_SET);
read(fd, buf, 2);
if (first_interrupt == 0) {
first_interrupt = 1;
} else {
button_callback();
}
}
// Unexport the button pin on exit
fd = open("/sys/class/gpio/unexport", O_WRONLY);
len = snprintf(buf, sizeof(buf), "%s", BUTTON_PIN);
write(fd, buf, len);
close(fd);
return 0;
}