基于qt dh11传感器(三个引脚)获取温湿度代码
时间: 2023-11-16 15:06:18 浏览: 93
以下是一个基于Qt获取3引脚DHT11传感器温湿度数据的示例代码:
```cpp
#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <QString>
#define MAXTIMINGS 85
#define DHTPIN 7
int dht11_dat[5] = { 0, 0, 0, 0, 0 };
bool read_dht11_dat()
{
uint8_t laststate = HIGH;
uint8_t counter = 0;
uint8_t j = 0, i;
dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;
pinMode(DHTPIN, OUTPUT);
digitalWrite(DHTPIN, LOW);
delay(18);
digitalWrite(DHTPIN, HIGH);
delayMicroseconds(40);
pinMode(DHTPIN, INPUT);
for (i = 0; i < MAXTIMINGS; i++) {
counter = 0;
while (digitalRead(DHTPIN) == laststate) {
counter++;
delayMicroseconds(1);
if (counter == 255) {
break;
}
}
laststate = digitalRead(DHTPIN);
if (counter == 255) {
break;
}
if ((i >= 4) && (i % 2 == 0)) {
dht11_dat[j / 8] <<= 1;
if (counter > 16) {
dht11_dat[j / 8] |= 1;
}
j++;
}
}
if ((j >= 40) && (dht11_dat[4] == ((dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF))) {
return true;
} else {
return false;
}
}
int main(int argc, char *argv[])
{
wiringPiSetup();
pinMode(DHTPIN, OUTPUT);
digitalWrite(DHTPIN, LOW);
delay(18);
digitalWrite(DHTPIN, HIGH);
delayMicroseconds(40);
pinMode(DHTPIN, INPUT);
delayMicroseconds(10);
while (1) {
if (read_dht11_dat()) {
float h = (float)dht11_dat[0] * 256 + (float)dht11_dat[1];
h /= 10;
float t = (float)(dht11_dat[2] & 0x7F) * 256 + (float)dht11_dat[3];
t /= 10.0;
if (dht11_dat[2] & 0x80) {
t *= -1;
}
QString str = QString("Humidity = %.1f %% Temperature = %.1f *C\n").arg(h).arg(t);
printf("%s", str.toLocal8Bit().data());
} else {
printf("Failed to read sensor data\n");
}
delay(2000); // 每 2 秒获取一次数据
}
return 0;
}
```
这段代码与之前的代码类似,但需要在读取数据前先对传感器进行初始化,包括设置引脚为输出模式、发送开始信号、设置引脚为输入模式等。在读取数据时,需要忽略传感器返回的第一个80us的低电平信号,只读取后面的40位数据。编译和运行方式同之前的代码。
阅读全文