/*
 * Temp_Sensor.c
 *
 *  Created on: 5. 5. 2022
 *      Author: Jano
 */

//includes
#include <stdio.h>
#include "main.h"
#include "stm32l4xx.h"
#include "Temp_Sensor.h"

extern TIM_HandleTypeDef htim3;
extern SPI_HandleTypeDef hspi1;


//variables
uint8_t GetTemp[2];
uint8_t temp_compare;
float temp_measure;


//initialize temperature
void Temp_INIT(){
	HAL_GPIO_WritePin(HEATER_SSR_GPIO_Port, HEATER_SSR_Pin, 0);
	HAL_GPIO_WritePin(TEMP_CS_GPIO_Port, TEMP_CS_Pin, 1);

}

void Temp_START(){
	HAL_TIM_Base_Start_IT(&htim3);
}

//set temperature
void Temp_SET (uint8_t set_temp){

	temp_compare = set_temp;
}

//get temperature from sensor
float Temp_GET(){

	HAL_GPIO_WritePin(TEMP_CS_GPIO_Port, TEMP_CS_Pin, 0);
	HAL_SPI_Receive(&hspi1, GetTemp, 1, 50);
	HAL_GPIO_WritePin(TEMP_CS_GPIO_Port, TEMP_CS_Pin, 1);

	uint16_t OutTempBit = (((GetTemp[0])+(GetTemp[1] << 8)) >> 3);
	float OutTemp = (float)OutTempBit*0.25;;

	return OutTemp;
}

//keep temperature on set level
void Temp_KEEP(){

		temp_measure = Temp_GET();

		//temp++
		if (temp_measure < temp_compare){
			HAL_GPIO_WritePin(HEATER_SSR_GPIO_Port, HEATER_SSR_Pin, 1);
			}

		//temp--, temp ok
		if (temp_measure >= temp_compare){
			HAL_GPIO_WritePin(HEATER_SSR_GPIO_Port, HEATER_SSR_Pin, 0);
			}
}

//stop temperature keeping
void Temp_STOP(){

	HAL_GPIO_WritePin(HEATER_SSR_GPIO_Port, HEATER_SSR_Pin, 0);
	HAL_TIM_Base_Stop_IT(&htim3);
}

