单片机DHT11温湿度显示代码,不用指针
时间: 2023-12-14 08:12:37 浏览: 76
以下是DHT11温湿度传感器的单片机代码示例,适用于STC89C52单片机,不使用指针:
```
#include <reg52.h>
#include <stdio.h>
#define DHT11_PIN P2_0
void delay(unsigned int i)
{
while(i--);
}
void start_signal()
{
DHT11_PIN = 0;
delay(18000);
DHT11_PIN = 1;
delay(20);
DHT11_PIN = 0;
}
unsigned char read_byte()
{
unsigned char i, j, value = 0;
for(i = 0; i < 8; i++)
{
while(!DHT11_PIN);
delay(30);
if(DHT11_PIN)
value |= (1 << (7 - i));
while(DHT11_PIN);
}
return value;
}
unsigned char read_dht11(unsigned char *temp, unsigned char *humi)
{
unsigned char buffer[5], i;
start_signal();
if(!DHT11_PIN)
return 0;
while(DHT11_PIN);
for(i = 0; i < 5; i++)
buffer[i] = read_byte();
if(buffer[4] != (buffer[0] + buffer[1] + buffer[2] + buffer[3]))
return 0;
*humi = buffer[0];
*temp = buffer[2];
return 1;
}
void main()
{
unsigned char temp, humi;
char buf[50];
UART_Init();
while(1)
{
if(read_dht11(&temp, &humi))
{
sprintf(buf, "Temperature = %d, Humidity = %d\r\n", temp, humi);
UART_SendString(buf);
}
delay(500);
}
}
void UART_Init()
{
TMOD = 0x20;
TH1 = 0xfd;
TL1 = 0xfd;
TR1 = 1;
SM0 = 0;
SM1 = 1;
REN = 1;
EA = 1;
ES = 1;
}
void UART_SendByte(unsigned char dat)
{
SBUF = dat;
while(!TI);
TI = 0;
}
void UART_SendString(char *str)
{
while(*str)
{
UART_SendByte(*str++);
}
}
void UART_ISR() interrupt 4
{
if(RI)
{
RI = 0;
}
if(TI)
{
TI = 0;
}
}
```
在此代码中,我们依然使用单片机的IO口来读取DHT11传感器。首先,我们定义了delay函数和start_signal函数,和之前的代码一样。然后,我们定义了read_byte函数和read_dht11函数,也和之前的代码一样。在主函数中,我们使用UART_Init函数初始化串口,并在读取到传感器的值时,使用sprintf函数将温湿度值转换为字符串,并使用UART_SendString函数发送到串口。注意:在使用sprintf函数之前,需要在代码中添加对应的头文件;在使用UART_SendString函数之前,需要定义UART_Init、UART_SendByte和UART_ISR函数,并在代码中添加对应的中断向量。
阅读全文