Accessing GPIO from Qt5

By | June 21, 2020

Qt5 is has many useful classes for handling the filesystem, but I didn’t find anything for handling the GPIOs in an embedded system. You need to handle the GPIO configuration by opening a standard file descriptor and reading/writing from/to with the standard QFile methods.

This is just a snippet that shows briefly how to change the direction of a GPIO. In my case I have for buttons that must be configured as inputs:

#define GPIO_INPUT_UP 83
#define GPIO_INPUT_DOWN 84
#define GPIO_INPUT_LEFT 6
#define GPIO_INPUT_RIGHT 1

static bool setup_gpio_input()
{
    QString     gpio_file,
                gpio_num;
    QFile       exportFile,
                directionFile;
    QByteArray  ba; 

    for (int i = 0; i < 4; i++) {
        if (i == 0)
            gpio_num.setNum(GPIO_INPUT_UP);
        else if (i == 1)
            gpio_num.setNum(GPIO_INPUT_DOWN);
        else if (i == 2)
            gpio_num.setNum(GPIO_INPUT_LEFT);
        else if (i == 3)
            gpio_num.setNum(GPIO_INPUT_RIGHT);

        // Export GPIO
        gpio_file = "/sys/class/gpio/export";
        exportFile.setFileName(gpio_file);
        exportFile.open(QIODevice::WriteOnly);
        ba = gpio_num.toLatin1();
        exportFile.write(ba); 
        exportFile.close();

        // Set GPIO direction
        gpio_file = "/sys/class/gpio/gpio" + gpio_num + "/direction";
        directionFile.setFileName(gpio_file);
        directionFile.open(QIODevice::WriteOnly);
        directionFile.write("in");
        directionFile.close(); 
    }   

    return true;
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    if (!setup_gpio_input())
        qDebug() << "Fail to set GPIOs input";
}

Leave a Reply

Your email address will not be published. Required fields are marked *