使用51单片机驱动TM1668显示DHT11温湿度的简单代码程序
时间: 2023-06-20 17:07:59 浏览: 566
以下是使用51单片机驱动TM1668显示DHT11温湿度的简单代码程序:
```c
#include<reg52.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit DHT11=P3^5;
sbit STB=P1^0;
sbit CLK=P1^1;
sbit DIO=P1^2;
uchar code table[]={
0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,
0x77,0x7c,0x39,0x5e,0x79,0x71
}; //共阴数码管0~9,A~F的段码
void delay(uint z) //延时函数
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void write_byte(uchar dat) //写入一个字节
{
uchar i;
for(i=0;i<8;i++)
{
CLK=0;
if(dat&0x01) DIO=1;
else DIO=0;
dat>>=1;
CLK=1;
}
}
void write_com(uchar com) //写入命令
{
STB=0;
write_byte(com);
STB=1;
}
void write_data(uchar addr,uchar dat) //写入数据
{
write_com(0x44);
STB=0;
write_byte(0xc0|addr);
write_byte(dat);
STB=1;
}
void init() //初始化
{
write_com(0x88); //亮度全调
write_com(0x40); //点地址方式
write_com(0xc0); //从第一位开始显示
}
void display(uchar x,uchar y) //显示温度和湿度
{
uchar wendu,shidu;
write_data(y,table[x/10]); //显示十位
write_data(y+1,table[x%10]); //显示个位
write_data(y+2,0x38); //显示小数点
write_data(y+3,table[shidu/10]); //显示十位
write_data(y+4,table[shidu%10]); //显示个位
}
void main()
{
uchar h,l,check;
init();
while(1)
{
DHT11=1;
delay(1);
DHT11=0; //起始信号
delay(18);
DHT11=1;
delay(1);
if(!DHT11) //判断DHT11响应信号是否存在
{
while(!DHT11);
while(DHT11);
h=0;
l=0;
h|=DHT11<<7;
h|=DHT11<<6;
h|=DHT11<<5;
h|=DHT11<<4;
h|=DHT11<<3;
h|=DHT11<<2;
h|=DHT11<<1;
h|=DHT11;
l|=DHT11<<7;
l|=DHT11<<6;
l|=DHT11<<5;
l|=DHT11<<4;
l|=DHT11<<3;
l|=DHT11<<2;
l|=DHT11<<1;
l|=DHT11;
check=0;
check|=DHT11<<7;
check|=DHT11<<6;
check|=DHT11<<5;
check|=DHT11<<4;
check|=DHT11<<3;
check|=DHT11<<2;
check|=DHT11<<1;
check|=DHT11;
if(h+l==check) display(h,l); //判断数据是否正确
}
}
}
```
请注意,上述代码仅供参考,实际使用时需要根据具体硬件和软件环境进行适当修改。
阅读全文