#include "dht11.h"
#include "tim.h"


void dht11_gpio_input(void)
{
	GPIO_InitTypeDef GPIO_InitStruct;
	
	GPIO_InitStruct.Pin = GPIO_DHT11_PIN;
	GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
	GPIO_InitStruct.Pull = GPIO_PULLUP;
	HAL_GPIO_Init(GPIO_DHT11_PORT, &GPIO_InitStruct);
}

void dht11_gpio_output(void)
{
	GPIO_InitTypeDef GPIO_InitStruct;
	
	GPIO_InitStruct.Pin = GPIO_DHT11_PIN;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
  HAL_GPIO_Init(GPIO_DHT11_PORT, &GPIO_InitStruct);
}

void dht11_reset(void)
{
	dht11_gpio_output();
	DHT11_OUT_L;
	delay_us(18000);
	DHT11_OUT_H;
	delay_us(30);
	dht11_gpio_input();
}

uint16_t dht11_scan(void)
{
	return DHT11_IN;
}

uint16_t dht11_read_bit(void)
{
	while (DHT11_IN == GPIO_PIN_RESET);
	delay_us(40);
	if (DHT11_IN == GPIO_PIN_SET)
	{
		while (DHT11_IN == GPIO_PIN_SET);
		return 1;
	}
	else
	{
		return 0;
	}
}

uint16_t dht11_read_byte(void)
{
	uint16_t i;
	uint16_t data = 0;
	for (i = 0; i < 8; i++)
	{
		data <<= 1;
		data |= dht11_read_bit();
	}
	return data;
}

uint16_t dht11_read_data(uint8_t *buffer)
{
	uint16_t i = 0;
	
	dht11_reset();
	if (dht11_scan() == GPIO_PIN_RESET)
	{
		while (dht11_scan() == GPIO_PIN_RESET);
		while (dht11_scan() == GPIO_PIN_SET);
		for (i = 0; i < 5; i++)
		{
			buffer[i] = dht11_read_byte();
		}
		
		while(dht11_scan() == GPIO_PIN_RESET);
		
		uint8_t checksum = buffer[0] + buffer[1] + buffer[2] + buffer[3];
		if(checksum == buffer[4])
		{
			return 1;
		}
	}
	
	return 0;
}
