sysfs interface를 사용한 gpio 컨트롤 및 sample c code

Linux user 모드에서의 일반적으로 많이 사용되는 sysfs interface를 통한 gpio조작 방법에 관한 내용을 기술하였다.


1. 리눅스 커널에서 GPIO드라이버를 지원하도록 설정한다.




< 위 사진은 a64의 menuconfig 화면이다. >


2. /sys/class/gpio에 아래와 같이 생성된다.



export를 통해 gpioxxx 폴더를 생성하고, unexport를 통해 gpioxxx폴더를 삭제한다.

#echo “235” > ./export
#echo “235” > ./unexport

gpioxxx 폴더는 아래와 같으며 ./direction을 통해 in/out을 설정할 수 있고, ./value를 통해 값을 설정하거나 읽을 수 있다.




3. Sample source 

-       export gpio pin
int gpio_export(int gpio)
{
 int fd = 0;
 int len = 0;
 char buf[64] = { 0, };

  len = snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d", gpio);
 if (0 == access(buf, F_OK))
 {
 return 0;
 }

  fd = open("/sys/class/gpio/export", O_WRONLY);
 if (fd < 0)
 {
 return -1;
 }

  len = snprintf(buf, sizeof(buf), "%d", gpio);
 write(fd, buf, len);
 close(fd);

  return 0;
}


-       set gpio direction
int gpio_set_outdir(int gpio, int isout)
{
      int fd = 0;
      char buf[64] = { 0, };

      snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d/direction", gpio);
      fd = open(buf, O_WRONLY);
      if (fd < 0)
      {
            return -1;
      }
     
      if (isout)
      {
            write(fd, "out", 3);
      }
      else
      {
            write(fd, "in", 3);
      }

      close(fd);

      return 0;
}

-       write/read gpio value
int gpio_set(int gpio, int level)
{
      int fd;
      char buf[64] = { 0, };
      if (gpio <= 0) return -1;

      sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
      fd = open(buf, O_WRONLY);
      if (fd < 0)
      {
            return -1;
      }

      if (level == 1)
            write(fd, "1", 1);
      else
            write(fd, "0", 1);

      close(fd);

      return 1;
}

int gpio_get(int gpio)
{
      int fd;
      char buf[64] = { 0, };
      if (gpio <= 0) return -1;

      sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
      fd = open(buf, O_RDONLY);
      if (fd < 0)
      {
            return -1;
      }

      read(fd, buf, 1);
      close(fd);

      if (buf[0] != '0')
            return 1;
     
      return 0;
}


댓글

이 블로그의 인기 게시물

간단한 cfar 알고리즘에 대해

windows에서 간단하게 크롬캐스트(Chromecast)를 통해 윈도우 화면 미러링 방법

쉽게 설명한 파티클 필터(particle filter) 동작 원리와 예제

딥러닝을 사용한 로또 번호 예측 실험

바로 프로젝트 적용 가능한 FIR Filter (low/high/band pass filter )를 c나 python으로 만들기