您的位置:首页 > 编程语言 > PHP开发

[開發記錄] 函式庫調用 - GPIO控制 之二

2012-08-16 15:01 162 查看
參考網路資料,找到另外的IO控制文件,

其中,devmem2是另外的工具程式,很容易在網路上找到相關的source code,編輯為執行檔後,讓IO控制程式可連結執行devmem2即可,

System命令,可用來執行shell層命令,先將須使用的Pin腳進行設定,將BeagleBoard-xM的GPIO130設定為GPIO功能,並設定是否pull-high等相關參數,

透過系統的 /sys/class/gpio/export 寫入需要控制的GPIO編號,系統將自行產生/sys/class/gpio/gpio<編號> 的資料夾,

便可使用 /sys/class/gpio/gpio<編號>/direction 設定為IN or OUT(此範例中設定為輸出),

以及使用 /sys/class/gpio/gpio<編號>/value 設定輸出的狀態數值 0 or 1 。

/*
*	IOCtrl_K_1.c
*
*	Author: Kim.Lui
*
*	Date: 2012-08-16
*
*	gpio 130 blanky
*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <time.h>
#include <string.h>

FILE *fp;

int main(void)
{
system("devmem2 0x48002158 w 0x010C010C");
char set_value[4];

int toggle = 0;

if (( fp = fopen("/sys/class/gpio/export", "ab")) == NULL)
{
printf("Can not open export file \n");
exit(1);
}
rewind(fp);
strcpy(set_value, "130");
fwrite(&set_value, sizeof(char), 3, fp);
fclose(fp);
printf("GPIO 130 now exported \n");

if((fp = fopen("/sys/class/gpio/gpio130/direction", "rb+")) == NULL)
{
printf("Can not open GPIO130 direction file \n");
exit(1);
}
rewind(fp);
strcpy(set_value, "out");
fwrite(&set_value, sizeof(char), 3, fp);
fclose(fp);
printf("GPIO 130 direction set to output\n");

if((fp = fopen("/sys/class/gpio/gpio130/value", "rb+")) == NULL)
{
printf("Can't open GPIO 130 value file");
exit(1);
}
rewind(fp);
strcpy(set_value, "1");
fwrite(&set_value, sizeof(char), 1, fp);
fclose(fp);
printf("GPIO 130 set to 1\n");
sleep(2);	//IO keep high 3 sec

if((fp = fopen("/sys/class/gpio/gpio130/value", "rb+")) == NULL)
{
printf("Can't open GPIO 130 value file");
exit(1);
}
rewind(fp);
strcpy(set_value, "0");
fwrite(&set_value, sizeof(char), 1, fp);
fclose(fp);
printf("GPIO 130 set to 0\n");
sleep(2);	//IO keep low 3sec

// IO blinky
unsigned char i;
for(i=0;i<100;i++)
{
if((fp = fopen("/sys/class/gpio/gpio130/value", "rb+")) == NULL)
{
printf("Can not open value file\n");
exit(1);
}

if(toggle == 0)
{
toggle=1;
rewind(fp);
strcpy(set_value, "1");
fwrite(&set_value, sizeof(char), 1 ,fp);
fclose(fp);
printf("...value set to 1\n");
}
else
{
toggle=0;
rewind(fp);
strcpy(set_value, "0");
fwrite(&set_value, sizeof(char), 1 ,fp);
fclose(fp);
printf("...value set to 0\n");
}
sleep(1);
}
return 0;
exit(1);
}


此方式已測試過,可正確執行控制,但似乎過多的程式碼,且不斷的寫入文字,應該有更為簡易的方式,或是將其中重複的設定整理為副程式,

可較有效率的控制IO,在程式閱讀上也會較容易理解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  fp file null system output c