#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define KEY_OK_GPIO 32
void KeyGpioInit(unsigned int GPIO)
{
unsigned char buf[100];
sprintf(buf,"echo \"%d\" > /sys/class/gpio/export",GPIO);
printf("%s\n",buf);
system(buf);
sprintf(buf,"echo \"in\" > /sys/class/gpio/gpio%d/direction",GPIO);
printf("%s\n",buf);
system(buf);
}
void KeyInit(void)
{
KeyGpioInit(KEY_OK_GPIO);
}
static int gpio_read(int pin)
{
char path[64];
char value_str[3];
int fd;
snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/value", pin);
fd = open(path, 0); //O_RDONLY=0
if (fd < 0) {
printf("Failed to open gpio value for reading 1!\n");
return -1;
}
if (read(fd, value_str, 3) < 0) {
printf("Failed to read value!\n");
return -1;
}
close(fd);
return (atoi(value_str));
}
int getKeyValue(void)
{
int sta = 0;
if (gpio_read(KEY_OK_GPIO) == 1)
{
sta = 1;
}
return sta;
}
void main(void)
{
KeyInit();
while(1)
{
printf("key=%d\n",getKeyValue());
sleep(1);
}
}
# 目标架构
CROSS_COMPILE := arm-rockchip830-linux-uclibcgnueabihf-
# 编译器
CC := $(CROSS_COMPILE)gcc
# 目标文件
TARGET := key_test
# 源文件
SRCS := key1_test.c
# 依赖文件
OBJS := $(SRCS:.c=.o)
# 编译选项
CFLAGS := -Wall -O2
# 连接选项
LDFLAGS :=
# 默认目标
all: $(TARGET)
$(TARGET): $(OBJS)
$(CC) $(LDFLAGS) -o $@ $^
%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $<
# 清理生成的文件
clean:
rm -f $(OBJS) $(TARGET)
# 伪目标
.PHONY: all clean
执行make即可生成可执行文件。运行将间隔1s循环读取按键值。
1165

被折叠的 条评论
为什么被折叠?



