/*
 * max6675.c
 *
 *  Created on: 16 янв. 2022 г.
 *      Author: mcfly
 */
#include "max6675.h"

//Read the temperature. -1.0: SPI error; -2.0: Sensor is not connected
float MAX6675_GetTemp() {
	uint8_t buf[2] = {0};		//Buffer
	uint16_t reg;				//temp data var
	float res;

	MAX6675_CS_ON();
	if (HAL_SPI_Receive(MAX6675_SPI, buf, 2, 50) == HAL_OK) {		//Read 2 bytes from SPI
		if (buf[1] & 0b00000100) {									//Check the thermocouple "connected" bit
			res = -2.0f;											//-2.0 for disconnected sensor
		} else {
			reg = (buf[1] >> 3) | ((uint16_t)(buf[0] << 5));		//combine the rest of the data
			res = reg * 0.25;										//convert to Celsius
		}
	} else {
		res = -1.0f;												//-1.0 for SPI receive error
	}
	MAX6675_CS_OFF();
	return res;
}
