/*
 * Heizpatrone_PID.c
 *
 * Created: 26.06.2016 17:47:31
 *  Author: Chris
 */ 





static uint16_t adc_val;
static uint32_t r_ntc;

static float temp_sens;


#define TEMP_PID_INTERVAL	10		// only in this interval the PID is active, otherwise just MIN_HEATER_POWER / FULL_HEATER_POWER

#define MIN_HEATER_POWER	0
#define FULL_HEATER_POWER	255	

static float temp_setpoint = 60;	// target temperature


#define K_P		7500
#define K_I		0
#define K_D		0

static pidData_t	hotend_pid;

static volatile uint8_t timerflag_100ms = 0;	// 100ms flag, set in timer interrupt



static void set_pwm(uint8_t val)
{
	// ... set pwm value
}

static PID_STATE_T pid_mode = PID_OFF;

int main(void)
{
	pid_Init(K_P, K_I, K_D, &hotend_pid);
	

    while(1)
    {
		if (timerflag_100ms)
		{			
			timerflag_100ms = 0;
		
			// get temperature
			adc_val = adc_read_multi(NTC_ADC_CHANNEL);
			temp_sens = analog2temp(adc_val, 0);
			
			// perform PID calculation
			int16_t output;
			output = pid_Controller(temp_setpoint, temp_sens, &hotend_pid);	// PID uses int16_t, so maybe we can eliminate the use of float
			
						
			// set PWM value
			if (output < 0)		// we cannot cool, so just turn the heater off
			{
				pid_Reset_Integrator(&hotend_pid);	// reset integrator, since it doesn't make sense to sum up negative values cause we cannot cool
				set_pwm(0);
			}
			else
			{
				if (output > 255)	// 8 bit PWM --> max 255
				{
					output = 255;
				}
				set_pwm(output);
			}
			
		}		
		

    }
}







