树莓派dht11代码qt代码
时间: 2023-07-03 19:31:54 浏览: 91
以下是在Qt中使用wiringPi库读取DHT11传感器数据的C++代码:
```c++
#include <wiringPi.h>
#include <iostream>
#include <QCoreApplication>
#include <QTimer>
using namespace std;
#define DHT11PIN 7
int dht11_val[5]={0,0,0,0,0};
void dht11_read_val()
{
unsigned char lststate=HIGH;
unsigned char counter=0;
unsigned char j=0,i;
for(i=0;i<5;i++)
dht11_val[i]=0;
pinMode(DHT11PIN,OUTPUT);
digitalWrite(DHT11PIN,LOW);
delay(18);
digitalWrite(DHT11PIN,HIGH);
delayMicroseconds(40);
pinMode(DHT11PIN,INPUT);
for(i=0;i<85;i++)
{
counter=0;
while(digitalRead(DHT11PIN)==lststate)
{
counter++;
delayMicroseconds(1);
if(counter==255)
break;
}
lststate=digitalRead(DHT11PIN);
if(counter==255)
break;
if((i>=4)&&(i%2==0))
{
dht11_val[j/8]<<=1;
if(counter>16)
dht11_val[j/8]|=1;
j++;
}
}
if((j>=40)&&(dht11_val[4]==((dht11_val[0]+dht11_val[1]+dht11_val[2]+dht11_val[3])& 0xff)))
cout << "Humidity = " << dht11_val[0] << "." << dht11_val[1] << " % Temperature = " << dht11_val[2] << "." << dht11_val[3] << " *C" << endl;
else
cout << "Invalid Data!!" << endl;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
if(wiringPiSetup()==-1)
exit(1);
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, dht11_read_val);
timer.start(5000); // 5000ms执行一次
return a.exec();
}
```
该代码在Qt中通过QTimer定时器,实现了每隔五秒钟读取一次DHT11传感器的温湿度数据。在主函数中,通过连接定时器的timeout信号和dht11_read_val()槽函数,实现了定时执行读取数据的操作。在dht11_read_val()函数中,同样通过wiringPi库中的GPIO控制函数,读取DHT11传感器的输出,并将温湿度数据打印到控制台上。
阅读全文