Calling a C function (that return a pointer to struct) every X seconds



  • Hi all,
    I cannot find a simple method for call a c function that read a temperature from a sensor and display the the value using a QLCDNumber.

    The c function look like this :

    temperature* readCelsius(void) {
    
        int fd;
        int fault;
        temperature *tmp = (temperature *) malloc(sizeof(*tmp));
    
        
        char buf[4];
        
    
    
    
        fd = open("/dev/spidev32766.0", O_RDWR);
        if (fd<=0) {
                printf("Device not found\n");
                exit(1);
        }
    
        if (read(fd, buf, ARRAY_SIZE(buf)) != ARRAY_SIZE(buf))
                perror("SPI read Error");
        close(fd);
    
        
        fault = buf[1] & FAULT;
    
       
        if(fault) {
                tmp->scv = buf[3] & SCV;
                tmp->scg = buf[3] & SCG;
                tmp->oc = buf[3] & OC;
    
                printf("Fault detected: scv: %X, scg: %X, oc: %X\n", tmp->scv, tmp->scg, tmp->oc);
        } else {
                tmp->celsius = ( buf[0] << 4 ) + ( buf[1] >> 2 ) / 4.0;
                printf("Thermocouple temperature: %.2f degrees Celsius\n", tmp->celsius);
        }
    
        tmp->internal_celsius = ( buf[2] << 2) + ( buf[3] >> 4 )  / 4.0;
        printf("Reference junction temperature: %.2f degrees Celsius\n", tmp->internal_celsius);
    
        return tmp;
    
    
    }
    

    From MainWindow i call the function :

    temperature *vis = readCelsius();
    
    ui->lcdNumber->display(vis->celsius);
    free(vis);
    

    Now i want to call readCelsius() every X seconds and update the value on lcdNumber.
    How can i do?
    Can i use Qtimer?
    Thanks a lot.
    Giovanni.


  • Moderators

    Hi! Yes, you can use QTimer for this:

    mainwindow.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    // your c function
    static int getTempC()
    {
        static int temp = 0;
        return ++temp;
    }
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        connect(&m_timer, &QTimer::timeout, this, &MainWindow::updateTemperature);
        m_timer.start(1000);
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    
    void MainWindow::updateTemperature()
    {
        const auto display = QString("%1").arg(getTempC());
        ui->lcdNumber->display(display);
    }
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.