51单片机数字温湿度计代码
时间: 2024-02-18 18:02:56 浏览: 64
以下是51单片机数字温湿度计的代码:
```c
#include <reg52.h>
typedef unsigned char uchar;
typedef unsigned int uint;
sbit DHT11 = P1^0;
uchar code table[] = "0123456789";
uchar humi_data, temp_data;
void delay(uint z)
{
uint x,y;
for(x = z; x > 0; x--)
{
for(y = 114; y > 0; y--);
}
}
void start_dht11()
{
DHT11 = 0;
delay(25);
DHT11 = 1;
delay(30);
}
uchar dht11_receive()
{
uint time_out = 0;
while(DHT11 == 1 && time_out < 100)
{
time_out++;
delay(1);
}
time_out = 0;
while(DHT11 == 0 && time_out < 100)
{
time_out++;
delay(1);
}
time_out = 0;
while(DHT11 == 1 && time_out < 100)
{
time_out++;
delay(1);
}
uchar i,j = 0;
uchar data = 0;
for(i = 0; i < 8; i++)
{
while(DHT11 == 0);
delay(30);
if(DHT11 == 1)
{
j = 1;
while(DHT11 == 1);
}
if(j == 1)
{
data <<= 1;
if(DHT11 == 1)
{
data |= 0x01;
}
}
}
return data;
}
void display(uchar dat)
{
P0 = table[dat / 100];
P2 = 0xfe;
delay(5);
P2 = 0xff;
P0 = table[dat % 100 / 10];
P2 = 0xfd;
delay(5);
P2 = 0xff;
P0 = table[dat % 10];
P2 = 0xfb;
delay(5);
P2 = 0xff;
}
void main()
{
while(1)
{
start_dht11();
humi_data = dht11_receive();
dht11_receive();
temp_data = dht11_receive();
dht11_receive();
display(humi_data);
display(temp_data);
}
}
```
说明:
该代码使用DHT11传感器测量温湿度,通过单片机进行显示。使用了三个数码管,每个数码管都能显示一个数字。温度和湿度的数据分别通过两个数码管显示。
阅读全文