/*
 * hp206c.c
 *
 *  Created on: Oct 6, 2022
 *      Author: user
 */

#include "main.h"
#include "hp206c.h"
#include "i2c.h"

void HP20X_I2C_WriteCmd(uint8_t HpCmd)
{

	HAL_I2C_Master_Transmit(&HP20X_I2C_PORT, HP20X_I2C_DEV_ID, &HpCmd, 1, 100);
}

void HP20X_I2C_WriteReg(uint8_t HpReg, uint8_t HpData)
{

	uint8_t HpTemp[2] =
	{ HpReg | HP20X_WR_REG_MODE, HpData };

	HAL_I2C_Master_Transmit(&HP20X_I2C_PORT, HP20X_I2C_DEV_ID, (uint8_t*) (&HpTemp), 2,
			100);
}

uint8_t HP20X_I2C_ReadReg(uint8_t HpReg)
{

	uint8_t HpTemp = 0;

	HP20X_I2C_WriteCmd(HpReg | HP20X_RD_REG_MODE);

	HAL_I2C_Master_Receive(&HP20X_I2C_PORT, HP20X_I2C_DEV_ID, &HpTemp, 1, 100);
	return HpTemp;
}

uint32_t HP20X_I2C_ReadData(void)
{

//	uint8_t Cmd0 = HP20X_I2C_DEV_ID|I2C_DID_RD_MASK;
//	HAL_I2C_Master_Transmit(&hi2c1, HP20X_I2C_DEV_ID, &Cmd0, 1, 100);

	return HP20X_I2C_ReadData3Bytes();

}

uint32_t HP20X_I2C_ReadData3Bytes(void)
{
	uint8_t Data[3];

	uint32_t TempData = 0;
	HAL_I2C_Master_Receive(&HP20X_I2C_PORT, HP20X_I2C_DEV_ID, Data, 3, 100);

	TempData = (((uint32_t) (Data[0])) << 16) | (((uint32_t) (Data[1])) << 8)
			| ((uint32_t) (Data[2]));
	if (TempData & 0x800000)
	{
		TempData |= 0xFF000000;
	}
	return TempData;

}

float HP20X_ReadTemperature(void)
{

	HP20X_I2C_WriteCmd(HP20X_WR_CONVERT_CMD | HP20X_CONVERT_OSR1024);//adc convert

	HAL_Delay(25);
	HP20X_I2C_WriteCmd(HP20X_READ_T);

	return (float) HP20X_I2C_ReadData();

}

float HP20X_ReadPressure(void)
{

	HP20X_I2C_WriteCmd(HP20X_WR_CONVERT_CMD | HP20X_CONVERT_OSR1024);//adc convert

	HAL_Delay(25);
	HP20X_I2C_WriteCmd(HP20X_READ_P);

	return (float) HP20X_I2C_ReadData();

}

float HP20X_ReadAltitude(void)
{

	//    HP20X_I2C_WriteCmd(HP20X_WR_CONVERT_CMD|HP20X_CONVERT_OSR1024);	//adc convert

	HP20X_I2C_WriteCmd(HP20X_READ_A);

	return (float) HP20X_I2C_ReadData();

}

void HP20X_Compensate(void)
{
	HP20X_I2C_WriteReg(REG_PARA, OK_HP20X_DEV);
}


void HP20X_SoftReset(void)
{
	HP20X_I2C_WriteCmd(HP20X_SOFT_RST);
	HAL_Delay(25);
}
