#include
#include
#include
#include
#include //define O_WRONLY and O_RDONLY
// LED 引脚
#define SYSFS_GPIO_EXPORT "/sys/class/gpio/export"
#define SYSFS_GPIO_UNEXPORT "/sys/class/gpio/unexport"
#define SYSFS_GPIO_RST_PIN_VAL "440"
#define SYSFS_GPIO_RST_DIR "/sys/class/gpio/gpio440/direction"
#define SYSFS_GPIO_RST_DIR_VAL "out"
#define SYSFS_GPIO_RST_VAL "/sys/class/gpio/gpio440/value"
#define SYSFS_GPIO_RST_VAL_H "1"
#define SYSFS_GPIO_RST_VAL_L "0"
int main()
{
int fd;
int count = 30;
int fp;
int gpio_num=440;//gpio_num 为要操作的 GPIO 编号,该编号等于”GPIO 组号 + 组内偏移号”
printf("Hello Worldy!rn");
//步骤 1: 将要操作的 GPIO 编号写到 export:
//向文件"/sys/class/gpio/export"写入要操作的IO口
//GPIO0 对应 linux 组号值为 480
//GPIO1 对应 linux 组号值为 448
//GPIO2 对应 linux 组号值为 416
//GPIO3 对应 linux 组号值为 384
//PWR_GPIO 对应 linux 组号值为 352
//GPIO 编号 =GPIO 组号值 + 偏移值 eg.以原理图中 GPIO1_2 管脚为例,GPIO1 对应 GPIO 组号值 448, 偏移值为 2. 因此 GPIO 编号 N 为 448+2=450
fp = open(SYSFS_GPIO_EXPORT,O_WRONLY);// "w");
if (fp == -1)
{
printf("ERR: export open error.n");
return EXIT_FAILURE;
}
write(fp, SYSFS_GPIO_RST_PIN_VAL,sizeof(SYSFS_GPIO_RST_PIN_VAL));
close(fp);
//步骤 2: 设置 GPIO 方向:
fp=open(SYSFS_GPIO_RST_DIR,O_WRONLY);
if (fp == -1)
{
printf("ERR: direction open error.n");
return EXIT_FAILURE;
}
//对于输入:写入"in";,注意大小写,测试过,大写字符程序将不起作用
//对于输出:写入"out";
write(fp, SYSFS_GPIO_RST_DIR_VAL,sizeof(SYSFS_GPIO_RST_DIR_VAL));
close(fp);
//步骤 3: 查看 GPIO 输入值或设置 GPIO 输出值:
fp=open(SYSFS_GPIO_RST_VAL,O_RDWR);
if (fp == -1)
{
printf("ERR: value open error.n");
return EXIT_FAILURE;
}
int n=1000;
while(n>0)
{
printf("N=%drn",n);
write(fp, SYSFS_GPIO_RST_VAL_H, sizeof(SYSFS_GPIO_RST_VAL_H));
usleep(200000);
write(fp, SYSFS_GPIO_RST_VAL_L, sizeof(SYSFS_GPIO_RST_VAL_L));
usleep(200000);
n--;
if(n%5==0)
usleep(1800000); //暂停1.8秒
}
close(fp);
//步骤 4: 将操作的 GPIO 编号写入 unexport:
fp = open("/sys/class/gpio/unexport",O_WRONLY);// "w");
if (fp == -1)
{
printf("ERR: unexport open error.n");
return EXIT_FAILURE;
}
//fprintf(fp, "%d",gpio_num);
write(fp, SYSFS_GPIO_RST_PIN_VAL,sizeof(SYSFS_GPIO_RST_PIN_VAL));
close(fp);
return 0;
}