用DHT11和GY30写一个温室大棚的51单片机程序
时间: 2023-12-03 12:02:35 浏览: 26
以下是一个基本的温室大棚的51单片机程序,使用DHT11和GY30传感器来监测温度和光照强度:
```c
#include<reg52.h>
#include<stdio.h>
sbit DHT11_PIN=P1^7;
sbit SDA=P2^0;
sbit SCL=P2^1;
void delay_us(unsigned int i)
{
while(i--);
}
void delay_ms(unsigned int i)
{
while(i--)
{
delay_us(1000);
}
}
void IIC_start()
{
SDA=1;
SCL=1;
delay_us(5);
SDA=0;
delay_us(5);
SCL=0;
}
void IIC_stop()
{
SDA=0;
SCL=1;
delay_us(5);
SDA=1;
delay_us(5);
SCL=0;
}
unsigned char IIC_read_ack()
{
unsigned char ack;
SDA=1;
SCL=1;
ack=SDA;
delay_us(5);
SCL=0;
return ack;
}
void IIC_write_ack()
{
SDA=0;
SCL=1;
delay_us(5);
SCL=0;
}
void IIC_write(unsigned char dat)
{
unsigned char i;
for(i=0;i<8;i++)
{
SDA=dat&0x80;
dat<<=1;
SCL=1;
delay_us(5);
SCL=0;
}
IIC_read_ack();
}
unsigned char IIC_read()
{
unsigned char i,dat=0;
SDA=1;
for(i=0;i<8;i++)
{
dat<<=1;
SCL=1;
dat|=SDA;
delay_us(5);
SCL=0;
}
return dat;
}
void DHT11_start()
{
DHT11_PIN=1;
delay_ms(30);
DHT11_PIN=0;
delay_ms(20);
DHT11_PIN=1;
delay_us(30);
}
unsigned char DHT11_read_byte()
{
unsigned char i,dat=0;
for(i=0;i<8;i++)
{
while(!DHT11_PIN);
delay_us(30);
if(DHT11_PIN)
{
dat=(dat<<1)|(0x01);
}
else
{
dat<<=1;
}
while(DHT11_PIN);
}
return dat;
}
void main()
{
unsigned char rh,temp,check,sum;
unsigned int light;
float temp_c,temp_f;
IIC_start();
IIC_write(0x40);
IIC_write(0x01);
IIC_write(0x20);
IIC_stop();
while(1)
{
DHT11_start();
if(!DHT11_PIN)
{
delay_us(80);
if(DHT11_PIN)
{
delay_us(40);
rh=DHT11_read_byte();
temp=DHT11_read_byte();
check=DHT11_read_byte();
sum=rh+temp;
if(check==sum)
{
temp_c=temp;
temp_f=((float)temp_c*9/5)+32;
printf("Temperature: %d.%dC %d.%dF\n",temp_c/10,temp_c%10,temp_f/10,temp_f%10);
printf("Humidity: %d%%\n",rh);
}
}
}
IIC_start();
IIC_write(0x41);
IIC_write(0x10);
IIC_start();
IIC_write(0x41|0x01);
light=IIC_read()<<8;
IIC_write_ack();
light|=IIC_read();
IIC_write_ack();
light/=1.2;
IIC_stop();
printf("Light: %d\n",light);
delay_ms(1000);
}
}
```
该程序使用DHT11和GY30传感器来分别监测温度和光照强度,并将数据通过串口输出。需要注意的是,该程序只是一个基本的示例,具体的实现需要根据具体的硬件和实际应用进行调整。