(一)查阅DHT11数据数据手册
(二) 为了使用printf打印函数 需要进行修改。
usart.h增加:int fputc(int ch, FILE *f);
usart.c增加:
int fputc(int ch, FILE *f)
{
USART_SendData(USART1, (uint8_t) ch);
while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
return ch;
}
(三)DHT11函数代码
dht11.h文件:
//
#ifndef __DHT11_H__
#define __DHT11_H__
#include "stm32f10x_gpio.h"
#define DHT11_GPIO_TYPE GPIOB
#define DHT11_GPIO_PIN GPIO_Pin_8
#define DHT11_RCC RCC_APB2Periph_GPIOB
#define DHT11_OUT_H GPIO_SetBits(DHT11_GPIO_TYPE, DHT11_GPIO_PIN)
#define DHT11_OUT_L GPIO_ResetBits(DHT11_GPIO_TYPE, DHT11_GPIO_PIN)
#define DHT11_IN GPIO_ReadInputDataBit(DHT11_GPIO_TYPE, DHT11_GPIO_PIN)
void dht11_gpio_input(void);
void dht11_gpio_output(void);
u16 dht11_scan(void);
u16 dht11_read_bit(void);
u16 dht11_read_byte(void);
u16 dht11_read_data(u8 buffer[4]);
#endif
//
dht11.c文件
//
#include "dht11.h"
#include "delay.h"
u8 checksum;
void dht11_gpio_input(void)
{ GPIO_InitTypeDef g;
RCC_APB2PeriphClockCmd(DHT11_RCC, ENABLE);
g.GPIO_Pin = DHT11_GPIO_PIN;
g.GPIO_Speed = GPIO_Speed_50MHz;
g.GPIO_Mode = GPIO_Mode_IN_FLOATING; //
GPIO_Init(DHT11_GPIO_TYPE, &g);
}
void dht11_gpio_output(void)
{ GPIO_InitTypeDef g;
RCC_APB2PeriphClockCmd(DHT11_RCC, ENABLE);
g.GPIO_Pin = DHT11_GPIO_PIN;
g.GPIO_Speed = GPIO_Speed_50MHz;
g.GPIO_Mode = GPIO_Mode_Out_PP; //
GPIO_Init(DHT11_GPIO_TYPE, &g);
}
void dht11_reset(void)
{
//
dht11_gpio_output();
DHT11_OUT_L;
delay_us(19000);
DHT11_OUT_H;
delay_us(30);
dht11_gpio_input();
}
u16 dht11_scan(void)
{
return DHT11_IN;
}
u16 dht11_read_bit(void)
{
while (DHT11_IN == RESET);
delay_us(40);
if (DHT11_IN == SET)
{
while (DHT11_IN == SET);
return 1;
}
else
{
return 0;
}
}
u16 dht11_read_byte(void)
{
u16 i;
u16 data = 0;
for (i = 0; i < 8; i++)
{
data <<= 1;
data |= dht11_read_bit();
}
return data;
}
u16 dht11_read_data(u8 buffer[5])
{
u16 i = 0;
dht11_reset();
if (dht11_scan() == RESET)
{
//检测到DHT11响应
while (dht11_scan() == RESET);
while (dht11_scan() == SET);
for (i = 0; i < 5; i++)
{
buffer[ i] = dht11_read_byte();[ i]
}
while (dht11_scan() == RESET);
dht11_gpio_output();
DHT11_OUT_H;
checksum = buffer[0] + buffer[1] + buffer[2] + buffer[3];
if (checksum != buffer[4])
{
// checksum error
return 1;
}
}
return 0;
}
(三)主函数main.c代码
[ i]
//
#include "stm32f10x.h"
#include "delay.h"
#include "digital.h"
#include "usart.h"
#include "dht11.h"
int main (void){
SMG_Init();//
USART1_Config();
while(1){
u8 buffer[5];
double hum;
double temp;
UART1SendByte(1);
if (dht11_read_data(buffer) == 0)
{
hum = buffer[0] + buffer[1] / 10.0;
temp = buffer[2] + buffer[3] / 10.0;
Display_N(buffer[3]);//
}
printf("___{\"temperature\": %.2f, \"humidness\": %.2f}___\n", temp, hum);
delay_us(200000);
}
}
|