資料代碼分享
- #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;
- }
- }
復制代碼
51hei.png (4.35 KB, 下載次數: 11)
下載附件
2023-10-22 22:20 上傳
下載:
DHT11.zip
(2 MB, 下載次數: 0)
2023-10-22 21:29 上傳
點擊文件名下載附件
|