#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

/*
**
** 事前に /sys/class/gpio で以下の処理をしておく
** echo 6 > export
** cd  gpio6
** echo in > direction
**
*/

int main()
{
    int fd;
    int ret;
    char buf[8];
    int flag;

    /* input */
    fd = open("/sys/class/gpio/gpio6/value", O_RDONLY);
    if(fd < 0)
    {
        printf("Open Error.\n");
        return -1;
    }
    
    while(1)
    {
        lseek(fd, 0, SEEK_SET);
        ret = read(fd, buf, sizeof(buf) - 1);
        if (ret < 0) 
        {
            printf("read error.\n");
            goto End;
        }
        
        buf[ret] = '\0';
        printf("value is: %s\n", buf);
        
        sleep(1);
    }

#if 0
    /* output */
    fd = open("/sys/class/gpio/gpio6/value", O_RDWR);
    if(fd < 0)
    {
        printf("Open Error.\n");
        return -1;
    }
    
    flag = 0;
    while(1)
    {
        sprintf(buf, "%d\n", flag);
        ret = write(fd, buf, strlen(buf));
        if (ret < 0) 
        {
            printf("wirte error.\n");
            goto End;
        }
        printf("value is: %s", buf);
        flag = (flag + 1) & 0x1;
        sleep(5);
    }
#endif

End:
    close(fd);    
    
    return 0;
}

/* EOF */

