Arduino temperature and humidity sensor DHT11 (with code)

insert image description here

product introduction

In our daily life, temperature and humidity have a great impact on our lives, especially for the production of factories. If we can't grasp it well and take relevant measures, the losses it will bring will be great , But now, there is a sensor that can not only measure temperature but also measure humidity, which can really solve our troubles. Well, let's learn how to use it together and let it bring convenience to your life.

technical parameter

Power supply voltage: 3.3~5.5V DC
output: single bus digital signal
Measuring range: Humidity 20-90%RH, temperature 0~50℃ Measurement accuracy: Humidity ±5%RH, Temperature ±2℃
Resolution: Humidity 1%RH, Temperature 1°C Long-term stability: <±1%RH/year

wiring

  • The "+" terminal of the module is connected to +5V output
  • "-" terminal connected to GND
  • The "S" terminal is connected to pin 7 of the digital port (of
    course, you can also define the digital pin yourself); the connection method is very simple, and the test stage is left. . . . . .
    insert image description here
int DHpin = 8; 
byte dat[5]; 
byte read_data(){
    
    
	byte data;
	for(int i=0; i<8; i++){
    
    
		if(digitalRead(DHpin) == LOW){
    
    
			while(digitalRead(DHpin) == LOW);	//等待 50us;
			delayMicroseconds(30);	//判断高电平的持续时间,以判定数据是‘0’还是‘1’; if(digitalRead(DHpin) == HIGH)
			data |= (1<<(7-i));	//高位在前,低位在后;
			while(digitalRead(DHpin) == HIGH);	//数据‘1’,等待下一位的接收;
		}
	}
	return data;
}

void start_test()
{
    
    
	digitalWrite(DHpin,LOW);	//拉低总线,发开始信号; delay(30); //延时要大于 18ms,以便 DHT11 能检测到开始信号; digitalWrite(DHpin,HIGH);
	delayMicroseconds(40);	//等待DHT11 响应; pinMode(DHpin,INPUT); while(digitalRead(DHpin) == HIGH);
	delayMicroseconds(80);	//DHT11 发出响应,拉低总线 80us; if(digitalRead(DHpin) == LOW);
	delayMicroseconds(80);	//DHT11 拉高总线 80us 后开始发送数据;
	for(int i=0;i<4;i++)	//接收温湿度数据,校验位不考虑; dat[i] = read_data();
	pinMode(DHpin,OUTPUT);
	digitalWrite(DHpin,HIGH);	//发送完一次数据后释放总线,等待主机的下一次开始信号;
}

void setup()
{
    
    
	Serial.begin(9600); pinMode(DHpin,OUTPUT);
}

void loop()

{
    
    
	start_test();
	
	Serial.print("Current humdity = "); Serial.print(dat[0], DEC);	//显示湿度的整数位; Serial.print('.');
	Serial.print(dat[1],DEC);	//显示湿度的小数位; Serial.println('%');
	Serial.print("Current temperature = "); Serial.print(dat[2], DEC);	//显示温度的整数位; Serial.print('.');
	Serial.print(dat[3],DEC);	//显示温度的小数位; Serial.println('C');
	delay(700);
}

Ok, let's compile the test code, and we can see the result after the compilation is passed. I really want to see what the temperature and humidity are in the current environment. They are invisible and intangible. Let's burn the program into the Arduino board. Then I can't wait to open the Serial Monitor window, see, the result is out, wow, are you a little excited!
insert image description here

Guess you like

Origin blog.csdn.net/weixin_50153843/article/details/125384051