#include "sht31.h"
#include "I2C.h"
#include "systick.h"
#include "CRC.h"

	uint8_t CRC_calc(uint8_t *data, uint8_t cnt);
	
	void SHT31_init(void)
	{
		RCC->AHB1ENR 	 |=	RCC_AHB1ENR_CRCEN;
		RCC->AHB2ENR   |=   RCC_AHB2ENR_GPIOAEN;	
		GPIOA->MODER   &= ~(0x03U<<16);
		GPIOA->MODER   |=  (0x01U<<16);
		GPIOA->OTYPER  &= ~(0x01U<<8);
		GPIOA->OSPEEDR &= ~(0x03U<<16);
		GPIOA->PUPDR   &= ~(0x03U<<16);
		GPIOA->BSRR		 |= 0x01<<8;
		I2C_transmit(SHT31_ADDRESS,SHT31_CMD_RESET,2);

	}

	int16_t SHT31_ReadTRH(uint16_t* T, uint16_t* RH)
	{
		uint8_t nack=0;
		uint8_t TRHData[8] = {0};
		nack=I2C_transmit(SHT31_ADDRESS,SHT31_CMD_CLEAR_STATUS,2);		
		nack=I2C_transmit(SHT31_ADDRESS,SHT31_CMD_READ,2);
		nack=I2C_receive(SHT31_ADDRESS,TRHData,6);	
		if(CRC8_calc(TRHData,3)==0)
			*T = ((uint16_t)TRHData[1] | (uint16_t)(TRHData[0]<<8));
		else
			return -1;
		if(CRC8_calc(TRHData+3,3)==0)
			*RH = ((uint16_t)TRHData[4] | (uint16_t)(TRHData[3]<<8));
		else
			return -2;
	/*	*T=-45+(175*Traw/(65535.0f));
		*RH=100*RHraw/(65535.0f);*/
		return nack;
	}
	
