Posts: 2
Joined: Wed Aug 28, 2013 3:37 pm

GPIO "interrupts" using Qt

Wed Aug 02, 2017 3:06 pm

This isn't a problem I'm seeking an answer to; I just thought it might be of interest. I can't find any reference to this anywhere else but if it's common knowledge accept my apologies. Note it doesn't require the use of sudo.

GPIO pins can be accessed and manipulated using the /sys/class/gpio/ pseudo-directory. So the command lines:

Code: Select all

echo  5  > /sys/class/gpio/export
echo out > /sys/class/gpio/gpio5/direction
echo true > /sys/class/gpio/gpio5/value
cat /sys/class/gpio/gpio5/value
will "open" pin 5, set it as output, set it to true and confirm this.

I thought I could use the class QFileSytemWatcher to monitor input pins by using the kernel's notify system to tell a program that a switch has changed rather than continually monitoring it. To this end I created a program using Qt Creator by selecting New Project->Qt Widgets Application and putting a QLabel widget on the GUI.

I then modified mainwindow.h and mainwindow.cpp as follows

Code: Select all


#include <QMainWindow>
#include <QFileSystemWatcher>
namespace Ui {
class MainWindow;

class MainWindow : public QMainWindow

    QFileSystemWatcher watcher;
    explicit MainWindow(QWidget *parent = 0);
public slots:
void   switchChanged(QString);
    Ui::MainWindow *ui;

#endif // MAINWINDOW_H

Code: Select all

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileSystemWatcher>

MainWindow::MainWindow(QWidget *parent) :
    ui(new Ui::MainWindow)
    watcher.addPath ("/sys/class/gpio/gpio5/value");
    QObject::connect(&watcher, SIGNAL (fileChanged(QString)),\
                         this, SLOT   (switchChanged(QString)));

void MainWindow::switchChanged(QString str)

    delete ui;
After executing the command line:

Code: Select all

echo in > /sys/class/gpio/gpio5/direction
I expected that the program would show "/sys/class/gpio/gpio5/value" when I pressed the switch connected to pin 5. It didn't work.
However when I executed the command line:

Code: Select all

echo both > /sys/class/gpio/gpio5/edge
it did work. It took me some time to find the "edge" pseudo-file (it's hard to find when you don't know it exists). It takes the values "none" (the default), "rising", "falling" or "both".

Posts: 1
Joined: Mon May 07, 2018 7:39 am

Re: GPIO "interrupts" using Qt

Tue Jul 31, 2018 11:43 am

Hey, thank you for this great example code.
I actually managed to change the label, but I cant for the sake of... manage to trigger a second interrupt when the value changes from 1 to 0.
I mean reading and using the value to compare and debounce a button input using QFile.readAll() and such.

Would you mind giving me a lil something of your other code which turns this example into a viable option instead of trying to get a QSocketNotifier to work with a filedescriptor? You would be my hero. :mrgreen:

Thanks in advance,
Erwin Rompe

Return to “C/C++”