实现显示湿度和温度变化
.ino
#include "dht11.h"
DHT11 mydht11(13);
void setup() {
Serial.begin(9600);
}
void loop() {
mydht11.DHT11_Read();
Serial.print("Humidity:");
Serial.print(mydht11.humi);
Serial.print(".");
Serial.println(mydht11.humiP);
delay(500);
Serial.print("Temperature:");
Serial.print(mydht11.temp);
Serial.print(".");
Serial.println(mydht11.tempP);
delay(1000);
}
.cpp
#include "dht11.h"
#include "arduino.h"
unsigned char Humi = 0;
unsigned char temp = 0;
DHT11::DHT11(int pin){
DHT11_DQ = pin;
}
void DHT11::DHT11_Init(){
pinMode(DHT11_DQ,OUTPUT);
digitalWrite(DHT11_DQ,LOW);
delay(30);
digitalWrite(DHT11_DQ,HIGH);
delayMicroseconds(40);
pinMode(DHT11_DQ,INPUT_PULLUP);
while(digitalRead(DHT11_DQ)==HIGH);
delayMicroseconds(80);
if(digitalRead(DHT11_DQ)==LOW);
delayMicroseconds(80);
}
unsigned char DHT11::DHT11_Read_Byte(){
unsigned char i = 0;
unsigned char dat = 0;
pinMode(DHT11_DQ,INPUT_PULLUP);
delayMicroseconds(2);
for(i= 0;i<8;i++){
while(digitalRead(DHT11_DQ)==LOW);
delayMicroseconds(50);
if(digitalRead(DHT11_DQ)== HIGH){
dat |= (1<<(7-i));
}
while(digitalRead(DHT11_DQ)==HIGH);
}
return dat;
}
void DHT11::DHT11_Read(){
DHT11_Init();
humi = DHT11_Read_Byte();
humiP = DHT11_Read_Byte();
temp = DHT11_Read_Byte();
tempP = DHT11_Read_Byte();
delayMicroseconds(50);
pinMode(DHT11_DQ,OUTPUT);
digitalWrite(DHT11_DQ,HIGH);
}
.h
class DHT11{
public:
unsigned char humi;
unsigned char humiP;
unsigned char temp;
unsigned char tempP;
DHT11(int pin);
void DHT11_Init();
void DHT11_Read();
unsigned char DHT11_Read_Byte();
private:
int DHT11_DQ;
};
Ps: VDD可以置空