2016年9月12日 星期一

[Raspberry] 在Raspberry Pi 2 使用GPIO(二)

程式:

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


using namespace std;


int pin=14;

void CloseExport()
{
    int fd;
    ssize_t byte_write;
    char buf[3];
   
    fd=open("/sys/class/gpio/unexport",O_WRONLY);
       
    if(fd==-1) printf("Failed to open unexport \r\n");
           
    byte_write=snprintf(buf,3,"%d",pin);
       
    if(write(fd,buf,byte_write)<0)   printf("Failed 1\r\n");
 
    close(fd);
}


int main(int argc, char** argv) {

    ssize_t byte_write0;

    int fd1;
   
    char buf0[3];
    fd1=open("/sys/class/gpio/export",O_WRONLY);
   
    if(fd1==-1) {  printf("failed to open export for writing\r\n");return -1;}
   
    byte_write0=snprintf(buf0,3,"%d",pin);
    if(write(fd1,buf0,byte_write0)<0)
    {
        close(fd1);
       
        printf("fail 0\r\n");    
   
        CloseExport();
   
        return-1;
       
    }
    close(fd1);

   
    int fd3;
    char buf1[35];
    snprintf(buf1,35,"/sys/class/gpio/gpio%d/direction",pin);
    fd3=open(buf1,O_WRONLY);
    if(fd3==-1)
    {  
        printf("failed to open gpio direction for writing\r\n");
       
        CloseExport();
     
        return-1;
    }
    if(write(fd3,"out",3)<0)
    {
        close(fd3);
       
        printf("Failed to set direction\r\n");
   
        CloseExport();
   
        return-1;
    }
    close(fd3);
   

    int fd5;
    char buf2[30];
   
    snprintf(buf2,30,"/sys/class/gpio/gpio%d/value",pin);
    fd5=open(buf2,O_WRONLY);
    if(fd5==-1)
    {
        printf("Failed to open gpio value for writing\r\n");
        CloseExport();
        return -1;
    }
   
    if(write(fd5,"1",1)<0)
    {
        close(fd5);
        printf("Failedto set 1");
        CloseExport();
        return -1;
    }
    close(fd5);

    sleep(1);
    printf("Success !!\r\n");
    CloseExport();
     
    return 0;
}

沒有留言:

張貼留言