ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • raspberry pi GPIO control C language
    RaspberryPi 2023. 8. 28. 18:33

    1. initialize

     

    write(fd, pinnumber, pinnumber sring length);

    #include <errno.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <unistd.h>
    
    //////////////////////////////////////////////////
    
    fd = open("/sys/class/gpio/export", O_WRONLY);
    if (fd == -1) {
        fprintf (stdout, "Unable to open /sys/class/gpio/export");
    }
    
    if (write(fd, QString::number(DEF_OUT_1).toLocal8Bit().data(), QString::number(DEF_OUT_1).length()) != QString::number(DEF_OUT_1).length()) {
        strTemp = "Error writing " + QString::number(DEF_OUT_1);
        fprintf (stdout, strTemp.toLocal8Bit().data());
    }
     close(fd);

     

    2. direction

    strTemp = "/sys/class/gpio/gpio" + QString::number(DEF_OUT_1) + "/direction";
    fd = open(strTemp.toLocal8Bit().data(), O_WRONLY);
    if (fd == -1) {
        strTemp = "Unable to open " + strTemp;
        fprintf (stdout, strTemp.toLocal8Bit().data());
    }
    if (write(fd, "out", 3) != 3) {
        strTemp = "Error writing direction " + QString::number(DEF_OUT_1);
        fprintf (stdout, strTemp.toLocal8Bit().data());
    }
    close(fd);

    3. gpio out

    strTemp = "/sys/class/gpio/gpio" + QString::number(DEF_OUT_1) + "/value";
    fd = open(strTemp.toLocal8Bit().data(), O_RDONLY);
    if (fd == -1) {
        strTemp = "Unable to open " + strTemp;
        fprintf (stdout, strTemp.toLocal8Bit().data());
    }
    else {
        if (write(fd, "0", 1) != 1) {
            strTemp = "Error writing " + strTemp;
            fprintf (stdout, strTemp.toLocal8Bit().data());
        }
    }
    ::close(fd);

    4.gpio read

    strTemp = "/sys/class/gpio/gpio" + QString::number(DEF_IN_1) + "/value";
    fd = open(strTemp.toLocal8Bit().data(), O_RDONLY);
    if (fd == -1) {
        strTemp = "Unable to open " + strTemp;
        fprintf (stdout, strTemp.toLocal8Bit().data());
    }
    else {
        read(fd, &szIO_read, 1);
        szInput_val[0] = szIO_read&0x01;
    }
    ::close(fd);

    댓글

Designed by Tistory.