unsigned int step,Alpha,adc_count=0;
float P_pv_old=0,V_pv_old=0,I_pv_old=0,P_pv,V_pv,I_pv;
void InitTimer0(){
OPTION_REG = 0x88;
TMR0 = 206;
INTCON = 0xA0;
}
void Interrupt()
{
if (TMR0IF_bit)
{
TMR0IF_bit = 0;
TMR0 =206;
[COLOR="#FF0000"]TimeToReadTheADC = 1;[/COLOR]
}
}
void main()
{
ADC_Init();
InitTimer0();
TRISA=0xFF;
TRISC=0;
PORTC=0;
ADCON1 = 0b11000010; //0x82; // AN0->AN4 selected as analog input
PWM1_Init(10000);
PWM1_Start();
Alpha = 0;
PWM1_Set_Duty(Alpha);
step=1;
while(1)
{
if(TimeToReadTheADC) // [COLOR="#FF0000"]<- check if it's time to read the ADC[/COLOR]
{
TimeToReadTheADC = 0; // [COLOR="#FF0000"]<- reset the flag for next time
[/COLOR]
V_pv = (ADC_Read(0)*5.0/1024)*6.0; // [COLOR="#FF0000"]<- moved from ISR[/COLOR]
I_pv = ((ADC_Read(1)*5.0/1024)-2.5)/0.185;
P_pv = V_pv*I_pv;
if(P_pv > P_pv_old)
{
if (V_pv > V_pv_old)
{
Alpha = Alpha-step;
}
if (V_pv < V_pv_old)
{
Alpha = Alpha+step;
}
}
if(P_pv < P_pv_old)
{
if (V_pv > V_pv_old)
{
Alpha = Alpha+step;
}
if (V_pv < V_pv_old)
{
Alpha = Alpha-step;
}
}
PWM1_Set_Duty(Alpha);
P_pv_old = P_pv;
V_pv_old = V_pv;
I_pv_old = I_pv;
}
}
}