树莓派dht11代码qt驱动代码
时间: 2023-07-03 14:31:54 浏览: 110
以下是使用Qt编写的DHT11传感器驱动代码,可以通过调用该驱动代码,获取DHT11传感器的温湿度数据:
DHT11.h文件
```c++
#ifndef DHT11_H
#define DHT11_H
#include <QObject>
#include <wiringPi.h>
class DHT11 : public QObject
{
Q_OBJECT
public:
explicit DHT11(QObject *parent = nullptr);
public slots:
void readData();
signals:
void humidityAndTemperature(double humidity, double temperature);
private:
int dht11_val[5]={0,0,0,0,0};
};
#endif // DHT11_H
```
DHT11.cpp文件
```c++
#include "DHT11.h"
#include <iostream>
using namespace std;
#define DHT11PIN 7
DHT11::DHT11(QObject *parent) : QObject(parent)
{
if(wiringPiSetup()==-1)
exit(1);
}
void DHT11::readData()
{
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)))
{
double humidity = dht11_val[0] + dht11_val[1] * 0.1;
double temperature = dht11_val[2] + dht11_val[3] * 0.1;
emit humidityAndTemperature(humidity, temperature);
}
else
cout << "Invalid Data!!" << endl;
}
```
在DHT11类中,实现了一个readData()函数,用于读取DHT11传感器的温湿度数据。在读取完数据后,通过信号humidityAndTemperature(),将温湿度数据发送出去。在主程序中,可以通过连接该信号,实现对温湿度数据的获取。
阅读全文