#ifndef USER_CONSTANTS_H
#define USER_CONSTANTS_H

// numbers
#define SQRT3OVER2		  0.8660254038f 
#define SQRT1OVER3 		  0.5773502692f 
#define SQRT2           1.4142135624f
#define PI				      3.1415926536f 
#define HALFPI		      1.5707963268f
#define TWOPI			      6.2831853072f    
#define THREE_HALVES    1.5f
#define TWO_THIRDS      0.6666666666f
#define ONE_HALF        0.5f
#define ONE_THIRD       0.3333333333f
#define ONE_FOURTH      0.25f
#define ONE_FIFTH       0.2f
#define ONE_SIXTH       0.1666666667f
#define ONE_SEVENTH     0.1428571429f
#define ONE_EIGHTH      0.125f
#define ONE_NINTH       0.1111111111f
#define ONE_TENTH       0.1f

#define RAD2RPM         (60.0f/TWOPI)    // rad/s to rpm 
#define RPM2RAD         (TWOPI/60.0f)	   // rpm to mechanical rad/s
#define HZ2RPM          60.0f            // Hz to rpm
#define RPM2HZ          (1.0f/60.0f)     // rpm to Hz

//States
#define START      		4
#define COMMISSIONING	3 
#define READY      		2
#define WAKE_UP    		1
#define ERROR 	   		0
#define TRAPEZOIDAL   2
#define SINUSOIDAL    1
#define RAMP         	0


#define CRT_PROT 		  15.0f
#define CRT_MAX 		  13.0f
				
#define TIM1_cycle		 7200
#define FAPB1			    (float)72e6		                    // TIM1 clock freq (Hz)
#define fs 				    (FAPB1/(2.0f*(float)TIM1_cycle))
#define Ts 				    (1.0f/(float)fs)
#define DEADTIME       1e-6f                            // 1us di deadtime impostato su Cube 

#define current_scale   0.01567f
#define voltage_scale   0.0160f
#define COEFF_DAC_SPI   2047
#define ZERO_OFFSET     2048                   			// 13-bit Encoder , ndiv  = 2048 
#define ENC_FAC		      TWOPI/(4.0f*ZERO_OFFSET)  	// rad/counter , discretizzazione angolo DeltaTheta = 0.000766 rad 

// Motor parameters IM De Lorenzo DL100W 
// Motore connesso a Triangolo ma i parametri sono del modello equivalente a Stella 
// Nei controlli si fa sempre riferimento al modello equivalente a stella ed ai valori di picco (isd,isq,vsd,vsq etc... sono tutti valori di picco) 
#define Jmotor      (0.002f)                   // kg*m^2, senza considerare il motore DC trascinato
#define Jeq         (0.0052f)       					 // considera motore DC trascinato
#define RS          (0.34f)        	           // ohm - Stator Resistance 
#define RR          (0.22f)                    // ohm - Rotor Resistance
#define LM          (0.0105f)                  // H
//#define LM          (0.0088f)                // H - paramtro indicato nel progetto sensorless FOC
#define INV_LM      (1.0f/LM)                  // H^-1 
#define L_LINKAGE_S (0.0023f)                  // H
#define L_LINKAGE_R (0.0023f)                  // H
#define LS          (1.0f*LM+L_LINKAGE_S)      // H
#define LR          (1.0f*LM+L_LINKAGE_R)      // H
#define SIGMA       (1.0f - (LM*LM)/(LS*LR))   // 
#define SIGMALS     (1.0f*SIGMA*LS)            // H
#define TAU_EL      (1.0f*SIGMALS/RS)          // costante di tempo del sistema  
#define INV_TAU_EL  (1.0f/TAU_EL)              // poli del sistema : s1,2 = RS/SIGMALS + j|w|  
#define TAUR        (1.0f*LR/RR)               // costante di tempo del rotore
//#define TAUR        (0.0477f)	               // s, è il valore che c'era già nello script 
#define INV_TAUR		(1.0f/TAUR)	               // s^-1
#define Kr          (1.0f*LM/LR)               // non usare R lettera maiuscola perchè serve per il watchdog IWDG->KR= 0xAAAA;
#define INV_KR      (1.0f/Kr) 
#define PP				  (2.0f)                     // Pole Pairs ( motore a 4 poli ) 
#define INV_PP      (1.0f/PP)

#define VS_NOM      (24.0f)                    // Rated Voltage Delta Connection [V rms - linea], Tensione nominale motore equivalente a stella V,lineaY  --> NB: La tensione nominale dei motori è sempre quella di linea (concatenata) sia per motori a triangolo che a stella, infatti Vlinea,Y = Vlinea,Delta
#define VS_PH_NOM   (SQRT1OVER3*VS_NOM)        // Rated Voltage di Fase [V rms]   V,faseY = V,lineaY / sqrt(3) 
#define VS_PH_PK    (SQRT2*VS_PH_NOM)          // Rated Voltage di Fase [V picco] V,fase,picco = sqrt(2) * V,fase,rms
#define IS_NOM      (5.5f)                     // Rated Current [A rms] --> NB: nell'equivalente stella Ilinea = Ifase 
#define IS_NOM_PK   (SQRT2*IS_NOM)             // Rated Current [A picco]
#define IS_NO_LOAD  (4.4f)                     // No Load Current [A rms]
//#define IS_NO_LOAD  (3.5f)                     // No Load Current [A rms], nel file Excel sulle prove del motore risulta 3.5 Arms
#define ISD         (SQRT2*IS_NO_LOAD)         // Corrente magnetizzante Im è circa quella a vuoto, a volte conviene usare IS_NOM_PK
//#define ISD         (IS_NOM_PK)          			 // Conviene usare una corrente magnetizzante pari alla rated current per far fronte agli attriti
#define ISQ         (sqrtf(IS_NOM_PK*IS_NOM_PK - ISD*ISD))         
#define FS_NOM      (50.0f)                    // Nominal Frequency [Hz]
#define WS_NOM      (TWOPI*FS_NOM)             // Nominal Electrical Speed [rad/s]
#define N_RATED     (1425.0f)                  // Nominal Speed [rpm], a volte posto trovato pari a 1450 
#define W_RATED     (N_RATED*RPM2RAD)          // Nominal Speed [rad/s]
#define P_RATED     (100.0f)                   // Nominal Power [W] (mechanical)
#define T_RATED     (P_RATED/W_RATED)          // Nominal Torque [Nm] = 0.67 Nm 
#define T_MAX       (2.0f)                     // Overload Torque [Nm], Torque limit in uscita dallo speed loop 
#define COSPHI      (0.7f)                     // Power Factor []
#define EFFICIENCY  (0.6248f)                  // Efficiency []
#define P_ELT       (P_RATED/EFFICIENCY)       // Nominal Electrical Power [W], assorbita dal motore (dunque fornita dall'inverter) per poter fornire P_RATED meccanica
#define S_ELT       (P_ELT/COSPHI)             // Nominal Apparent Power [VA], assorbita dal motore (dunque fornita dall'inverter)

#define V0          (RS*IS_NOM_PK)             // Phase DC Voltage [V picco] - 2.645 Vpk
//#define V0          (2.0f)                     // Phase DC Voltage [V picco] impostato nei laboratori , 2 o 1.5 Vpk
#define LAMBDAS_NOM ((VS_PH_PK-V0)/WS_NOM)     // Flusso nominale Statore [Vs] (phase-picco) - 0.0540 considerando caduta resistiva V0 
//#define LAMBDAS_NOM (VS_PH_PK/WS_NOM)          // Flusso nominale Statore [Vs] (phase-picco) -  0.0624 senza considerare caduta resistiva V0 --- valore utilizzato nel lab 
#define LAMBDASQ    (SIGMALS*ISQ)
#define LAMBDASD    (sqrtf(LAMBDAS_NOM*LAMBDAS_NOM - LAMBDASQ*LAMBDASQ))
#define LAMBDAR_NOM ((LAMBDASD - SIGMALS*ISD)/Kr)     // Vs - LambdaR,nominale --- 0.0296 considerando caduta resistiva, 0.0405 senza considerare caduta resistiva V0 , valori ottenuti considerando Isd = sqrt(2)*I_no_load
//#define LAMBDAR_NOM  (0.067f)                       // Vs - LambdaR,nominale --- nel file del laboratorio 
#define KT          (THREE_HALVES*PP*Kr*LAMBDAR_NOM)  // T = (3/2*PP*Kr*LambdaR,nom)*isq = KT*isq
#define INV_KT      (1.0f/KT)                 			  // isq = INV_KT * T


#define BLANKTIME		1750                       // Ignore Reference Speed during start-up BLANKTIME for 1750*200us = 0.35s > 5*TAUR  : si fornisce solo DC current isd* per completare eccitazione motore (ottenere flusso rotore nominale lambdaR,nom)
#define T_BLANKTIME (1.0f*BLANKTIME*Ts)        // 0.35s 

// Mechanical loss Nm = Tmec_a0 + Tmec_a2 * w^2
#define P0          (16.8f)                    // ventilation loss at nmax (W)
#define N_MAX       (1500)                     // maximum operating speed (rpm)
#define BM          (0.0f)			               // damping constant (Nm/(rad/sec))
#define TF          (0.00000001f)              // friction loss (Nm)
#define TV          (P0/(N_MAX*RPM2RAD)^3)     // ventilation loss coefficient (W/(rad/s)^3 = Nm/(rad/s)^2)


/*
// Inverter's parameters of Transistors and Diodes
// Modello inverter a 2 ( Von, Rd --- mdl = 1 ) o 5 parametri ( Von1, Rd1, Iknee, Von2, Rd2 --- mdl = 2 )
#define vON1_TR     0.0f                      // vON IGBT, low current range (V)
//#define Rd1_TR      1e-3f                     // Rd  IGBT, low current range (Ohm)
#define Rd1_TR      0.0014f                   // Rds ON MOSFET, low current range (Ohm)
#define Iknee_TR    3.0f                      // IGBT low current upper limit (A) 
#define vON2_TR     1.5f                      // vON IGBT, high current range (V)
#define Rd2_TR      0.0714f                   // Rd  IGBT, high current range (Ohm)  
#define TR_mdl      1.0f                      // IGBT model (2 or 5 parameters) ---> Imposta 1 o 2, cambia il calcolo del Voltage Drop
#define vON1_D      0.0f                      // vON diode, low current range (V)             
#define Rd1_D       1e-3f                     // Rd  diode, low current range (Ohm)
#define Iknee_D     3.0f                      // diode low current upper limit (A)   
#define vON2_D      0.0f                      // vON diode, high current range (V)
#define Rd2_D       0.0f                      // Rd  diode, high current range (Ohm)    
#define D_mdl       1.0f                      // diode model (2 or 5 parameters) ---> Imposta 1 o 2, cambia il calcolo del Voltage Drop
*/

// Inverter's parameters of Transistors and Diodes - DA DEFINIRE la resistenza di on dei diodi ma già cosi va bene 
// Modello inverter a 2 ( Von, Rd --- mdl = 1 ) o 5 parametri ( Von1, Rd1, Iknee, Von2, Rd2 --- mdl = 2 )
#define vON1_TR     0.0f                      // vON IGBT, low current range (V)
#define Rd1_TR      0.0014f                     // Rds ON MOSFET, low current range (Ohm)
#define Iknee_TR    0.0f                      // IGBT low current upper limit (A) 
#define vON2_TR     0.0f                      // vON IGBT, high current range (V)
#define Rd2_TR      0.0f                   // Rd  IGBT, high current range (Ohm)  
#define TR_mdl      1.0f                      // IGBT model (2 or 5 parameters) ---> Imposta 1 o 2, cambia il calcolo del Voltage Drop
#define vON1_D      0.0f                      // vON diode, low current range (V)             
#define Rd1_D       1e-3f                    // Rd  diode, low current range (Ohm)
#define Iknee_D     0.0f                      // diode low current upper limit (A)   
#define vON2_D      0.0f                      // vON diode, high current range (V)
#define Rd2_D       0.0f                      // Rd  diode, high current range (Ohm)    
#define D_mdl       1.0f                      // diode model (2 or 5 parameters) ---> Imposta 1 o 2, cambia il calcolo del Voltage Drop




/*
// Motor parameters SPM s140-2B353
#define SPM
#define PP 4.0f					 		//	pole pairs
#define RS 0.25f						//	stator resistance 
#define LS 0.0002650f				//	stator inductance 
#define KE 0.0569f					//	V/(rad/s) mechanical
#define KT (3.0f/2.0f*KE)			
*/

#endif
