/*
 * myapp.h
 *
 *  Created on: 20. 4. 2022
 *      Author: cosi
 */

#ifndef INC_MYAPP_H_
#define INC_MYAPP_H_

#define ADCsmpNum 4 //pocet prevodu jednoho ADC
#define CurADCConst (13.33f*1.65f/2048.0f) //konstanta pro prepocet hodnoty z ADC na proud
#define VL1ADCConst (325.27f/4096.0f) //konstanta pro prepocet hodnoty z ADC na fazove napeti
#define VdcADCConst (400.0f*3.3f/1.757f/2048.0f) //konstanta pro prepocet hodnoty z ADC na napeti meziobvodu
#define TIM1ARR 6399//ARR časovače TIM1

#define ADC2Current(DATA) ((float)DATA * CurADCConst)
#define ADC2Vdc(DATA) ((float)DATA * VdcADCConst)
#define ADC2VL1(DATA) ((float)DATA * VL1ADCConst)
#define ADC2Vpot(DATA) ((float)DATA * (1.0f/(1u<<12)))
#define ADC2Th(DATA) ((float)(DATA-2048) * (1.0f/50.0f))

#define dutylimit(DUTY) ( (DUTY) > 1.0f ? 1.0f : (DUTY) < 0.0f ? 0.0f : (DUTY) )

#define writeGPIOB7(STATE) ((STATE)) ? SET_BIT(GPIOB->ODR,GPIO_ODR_7) : CLEAR_BIT(GPIOB->ODR,GPIO_ODR_7);
#define writeGPIOC6(STATE) ((STATE)) ? SET_BIT(GPIOC->ODR,GPIO_ODR_6) : CLEAR_BIT(GPIOC->ODR,GPIO_ODR_6);
#define writeGPIOC10(STATE) ((STATE)) ? SET_BIT(GPIOC->ODR,GPIO_ODR_10) : CLEAR_BIT(GPIOC->ODR,GPIO_ODR_10);
#define writeGPIOC11(STATE) ((STATE)) ? SET_BIT(GPIOC->ODR,GPIO_ODR_11) : CLEAR_BIT(GPIOC->ODR,GPIO_ODR_11);

#define readOverCurrent() (GPIOC->IDR & GPIO_IDR_12 ? 0 : 1)
#define readOverTemp() (GPIOC->IDR & GPIO_IDR_9 ? 0 : 1)

#define readGPIOB8() (GPIOB->IDR & GPIO_IDR_8 ? 1 : 0)
#define readGPIOB5() (GPIOB->IDR & GPIO_IDR_5 ? 1 : 0)
#define readGPIOB4() (GPIOB->IDR & GPIO_IDR_4 ? 1 : 0)
#define readGPIOB9() (GPIOB->IDR & GPIO_IDR_9 ? 1 : 0)

#define PFCSTOP() (LL_TIM_CC_DisableChannel(TIM3,LL_TIM_CHANNEL_CH3))
#define RBSTOP() (LL_TIM_CC_DisableChannel(TIM16,LL_TIM_CHANNEL_CH1))
#define IRAMYSTOP() (LL_TIM_CC_DisableChannel(TIM1,LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N))
#define IRAMYSTART() (LL_TIM_CC_EnableChannel(TIM1,LL_TIM_CHANNEL_CH1|LL_TIM_CHANNEL_CH1N|LL_TIM_CHANNEL_CH2|LL_TIM_CHANNEL_CH2N|LL_TIM_CHANNEL_CH3|LL_TIM_CHANNEL_CH3N))

#define IRAMYCheck(STATE) (STATE ? IRAMYSTART() : IRAMYSTOP())
#define PFCCheck(STATE) (STATE ? 0 : PFCSTOP())
#define RBCheck(STATE) (STATE ? 0 : RBSTOP())

//unie pro ulozeni dat z ADC
typedef union{
	uint32_t uwData[ADCsmpNum];
	uint16_t usData[ADCsmpNum*2];
	uint8_t ubData[ADCsmpNum*4];
	struct {
		int16_t Iph1;
		int16_t Iph3;
		uint16_t Vpot;
		int16_t Vd;
		uint16_t Vref;
		uint16_t VL1;
		uint16_t Th_MCU;
		uint16_t Th_H;
	}RawADC;
}rawADCData_typedef;

//Externi promenne
extern rawADCData_typedef rawADCData;

//Prototypy funkci
void MyInit(void);
void MyUpdate(void);
void MyUpdate1kHz(void);
void MyUpdate100Hz(void);

#endif /* INC_MYAPP_H_ */
