参考代码- 温湿度传感器程序文件
- #include "DHT11/dht11.h"
- u8 TEMP,HUMI,MAXTEMP;
- void dht_delay_us(u16 us)
- {
- u16 i=0;
- while(us--)
- {
- i = 10;
- while(i--);
- }
- }
- void dht_delay_ms(u16 ms)
- {
- u16 i=0;
- while(ms--)
- {
- i = 10000;
- while(i--);
- }
- }
- //复位DHT11
- void DHT11_Rst(void)
- {
- //SET OUTPUT
- GPIO_InitTypeDef GPIO_InitStructure;
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //使能BP端口时钟
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5; //PB8端口配置
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出
- GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
- GPIO_Init(GPIOB, &GPIO_InitStructure); //初始化IO口
- GPIO_SetBits(GPIOB,GPIO_Pin_5); //PB5 输出高
-
- DHT11_IO_Clr(); //拉低DQ
- delay_ms(20); //拉低至少18ms
- DHT11_IO_Set(); //DQ=1
- dht_delay_us(30); //主机拉高ß20~40us
- }
- //等待DHT11的回应
- //返回1:未检测到DHT11的存在
- //返回0:存在
- unsigned char DHT11_Check(void)
- {
- u8 retry=0;
- //SET INPUT
- GPIO_InitTypeDef GPIO_InitStructure;
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
- /*初始化上拉输入*/
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
- GPIO_Init(GPIOB, &GPIO_InitStructure);
-
- while (DHT11_DQ_IN&&retry<100)//DHT11拉低40~80us
- {
- retry++;
- dht_delay_us(1);
- };
- if(retry>=100)return 1;
- else retry=0;
- while (!DHT11_DQ_IN&&retry<100)//DHT11再次拉低40~80us
- {
- retry++;
- dht_delay_us(1);
- };
- if(retry>=100)return 1;
- return 0;
- }
- unsigned char DHT11_Read_Bit(void)
- {
- u8 retry=0;
- while(DHT11_DQ_IN&&retry<100)
- {
- retry++;
- dht_delay_us(1);
- }
- retry=0;
- while(!DHT11_DQ_IN&&retry<100)
- {
- retry++;
- dht_delay_us(1);
- }
- dht_delay_us(40);
- if(DHT11_DQ_IN)return 1;
- else return 0;
- }
- unsigned char DHT11_Read_Byte(void)
- {
- u8 i,dat;
- dat=0;
- for (i=0;i<8;i++)
- {
- dat<<=1;
- dat|=DHT11_Read_Bit();
- }
- return dat;
- }
- unsigned char DHT11_Read_Data(u8 *temp,u8 *humi)
- {
- u8 buf[5];
- u8 i;
- DHT11_Rst();
- if(DHT11_Check()==0)
- {
- for(i=0;i<5;i++)
- {
- buf[i]=DHT11_Read_Byte();
- }
- if((buf[0]+buf[1]+buf[2]+buf[3])==buf[4])
- {
- *humi=buf[0];
- *temp=buf[2];
- }
- }else return 1;
- return 0;
- }
- unsigned char DHT11_Init(void)
- {
- GPIO_InitTypeDef GPIO_InitStructure;
-
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
-
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
- GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
- GPIO_Init(GPIOB, &GPIO_InitStructure);
- GPIO_SetBits(GPIOB,GPIO_Pin_5);
- DHT11_Rst(); //¸′λDHT11
- return DHT11_Check();//μè′yDHT11μÄ»Øó|
- }
复制代码 |