示例 2:C 程序响应按键输入
下面是一个简单的 C 程序,读取按键输入并控制 LED 灯。
c
复制代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define LED_GPIO "22"
#define BUTTON_GPIO "23"
void export_gpio(const char *gpio) {
FILE *fp = fopen("/sys/class/gpio/export", "w");
fprintf(fp, "%s", gpio);
fclose(fp);
}
void set_direction(const char *gpio, const char *direction) {
char path[35];
snprintf(path, sizeof(path), "/sys/class/gpio/gpio%s/direction", gpio);
FILE *fp = fopen(path, "w");
fprintf(fp, "%s", direction);
fclose(fp);
}
void set_value(const char *gpio, const char *value) {
char path[35];
snprintf(path, sizeof(path), "/sys/class/gpio/gpio%s/value", gpio);
FILE *fp = fopen(path, "w");
fprintf(fp, "%s", value);
fclose(fp);
}
int get_value(const char *gpio) {
char path[35];
char value[3];
snprintf(path, sizeof(path), "/sys/class/gpio/gpio%s/value", gpio);
FILE *fp = fopen(path, "r");
fgets(value, sizeof(value), fp);
fclose(fp);
return atoi(value);
}
int main() {
// 导出 GPIO
export_gpio(LED_GPIO);
export_gpio(BUTTON_GPIO);
// 设置 GPIO 方向
set_direction(LED_GPIO, "out");
set_direction(BUTTON_GPIO, "in");
while (1) {
// 读取按钮状态
if (get_value(BUTTON_GPIO) == 1) {
set_value(LED_GPIO, "1"); // 点亮 LED
} else {
set_value(LED_GPIO, "0"); // 熄灭 LED
}
usleep(100000); // 100 ms
}
// 卸载 GPIO
set_value(LED_GPIO, "0"); // 熄灭 LED
export_gpio(LED_GPIO);
export_gpio(BUTTON_GPIO);
return 0; |