资料代码分享
- #include "DHT11.h"
- extern unsigned char temperature,humidity;
- //选择PA4作为 data线
- void SET_PA4_OUTPUT(void)
- {
- //Gec_GPIO_Init(GPIOA, GPIO_Pin_4, GPIO_MODE_OUT_PP);
- GPIO_InitTypeDef g;
- RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_GPIOA, ENABLE);
- g.GPIO_Pin = GPIO_Pin_4;
- g.GPIO_Mode = GPIO_Mode_OUT;
- g.GPIO_OType = GPIO_OType_PP;
- g.GPIO_Speed = GPIO_Speed_50MHz;
- GPIO_Init( GPIOA, &g);
- }
- void SET_PA4_INPUT(void)
- {
- // Gec_GPIO_Init(GPIOA, GPIO_Pin_4, GPIO_MODE_IN_PULLUP);
- GPIO_InitTypeDef g;
-
- RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_GPIOA, ENABLE);
- g.GPIO_Pin = GPIO_Pin_4;
- g.GPIO_Mode = GPIO_Mode_IN;
- g.GPIO_PuPd = GPIO_PuPd_NOPULL;
- //g.GPIO_OType = GPIO_OType_PP;
- //g.GPIO_Speed = GPIO_Speed_50MHz;
- GPIO_Init( GPIOA, &g);
-
- }
- static unsigned char Read_Byte(void)
- {
- SET_PA4_INPUT();
- unsigned char i,ByteData=0;
- for(i=0;i<8;i++)
- {
- ByteData <<= 1;//先左移一位,因为数据是高位先出
- while(!(PAin(4)==0));//每个bit都是从50us的低电平开始
- while(!(PAin(4)==1));//等待变为高电平
- udelay(30);//延时30us
-
- if(PAin(4) == 1)//说明该Bit位就是1
- {
- ByteData |= 1;//把最低位变为1
- }
- }
- return ByteData;
- }
- /*
- Read_DHT11:向DHT11发送命令,读取温湿度数据
- 参数:
- 无
- 返回值:
- 读取成功返回1,失败返回0
- */
- int Read_DHT11(void)
- {
- unsigned char ReadBuf[5];
- /*主机发送开始信号*/
- SET_PA4_OUTPUT();//设置为输出模式
- PAout(4) = 0;
- udelay(20000);//至少18ms
- /*主机拉高20~40us*/
- PAout(4) = 1;
- udelay(40);
- /*等待DHT11回响应信号*/
- SET_PA4_INPUT();//设置为输入模式
- while(!(PAin(4)==0));//等待总线变为低电平(响应信号)
- /*等待DHT11拉高80us,DHT11开始传输数据*/
- while(!(PAin(4)==1));
- /*数据总共有40bits,即5个字节*/
- ReadBuf[0] = Read_Byte();
- ReadBuf[1] = Read_Byte();
- ReadBuf[2] = Read_Byte();
- ReadBuf[3] = Read_Byte();
- ReadBuf[4] = Read_Byte();
- /*校验*/
- if((ReadBuf[0]+ReadBuf[1]+ReadBuf[2]+ReadBuf[3])%256 == ReadBuf[4])//校验成功
- {
- humidity = ReadBuf[0];
- temperature = ReadBuf[2];
- return 1;
- }
- else
- {
- return 0;
- }
- }
复制代码
下载:
DHT11.zip
(2 MB, 下载次数: 0)
|