#include <main.h>
#include <def_877a.h>
#include <lcddu.c>
/*
int1 a=0;
int Vout,Vref; //cac so dieu nhan len 1023
int m1=1434,m2=-411,e0=1857,e1=-3544,e2=1691;// m1=1.402,m2=-0.4021,e0=1.816,e1=-3.465,e2=1.653;
int er=0,last_er1=0,last_er2=0;
int Vc=0,Vc1=0,Vc2=0;
int value_duty,Vadc;
unsigned char str[20];
unsigned char count=0;
int Vc=0;*/
int1 a;
float Vref,Vout;
//float m1=1.136,m2=-0.1364,e0=0.3862,e1=-0.7274,e2=0.3433;
//float m1=1.083,m2=-0.08291,e0=0.3862,e1=-0.724,e2=0.3406; //thong so cho bo dieu khien PID chu ky trich mau Tm=50us
//float m1=1.007,m2=-0.006874,e0=0.3862,e1=-0.7173,e2=0.3371; //thong so cho bo dieu khien PID chu ky trich mau Tm=0.1ms
float er=0,last_er1=0,last_er2=0;
float Vc=0,Vc1=0,Vc2=0; //tin hieu ra tu bo dieu khien u(k),U(k-1),U(k-2)
unsigned int value_duty,Vadc;
unsigned char str[20];
unsigned char count=0;
//#define Vref 3.3
#define Vref 3.0
//ham tao PID
void PID_isr(void)
{
Vadc= read_adc(); //doc dien ap ra tu bo adc
Vout =(float)(0.6* Vadc *5/1023); // chuyen ve gia tri dien ap thuc
er= Vref -Vout;
Vc= m1 *Vc1 +m2 *Vc2 + e0 *er +e1 *last_er1 + e2*last_er2; // tin hieu ra tu bo PID dua vao PWM de dieu che do ron g xung
// duty=Vc/Vm;
value_duty=(int) (Vc*248) ; // value_duty=4*(PR2 +1)*(duty =Vc)
if(value_duty >=248) value_duty=248; //chong truong hop bao hoa
if(value_duty <=0) value_duty=1;
set_pwm1_duty(value_duty);
Vc2=Vc1; //Vc2 la trang thai truoc cua Vc1
Vc1=Vc; //Vc1 la trang thai truoc cua Vc
last_er2=last_er1;
last_er1=er;
}
/*
#INT_TIMER1
void ngat_timer1()
{
// TMR1IF=0;
setup_timer_1(T1_DISABLED);
// set_timer1(49911);
// set_timer1(65473) ; // Tdk=100us
set_timer1(65505); // Tdk=50us
// disable_interrupts(GLOBAL);
count ++; //dem so lan ngat timer1
PID_isr(); //tao chu ky dieu khien 50us
a=1;
enable_interrupts(GLOBAL);
}
*/
#INT_TIMER1
void ngat_timer0(void)
{
setup_timer_1(T1_DISABLED);
count++;
a=1;
PID_isr();
set_timer1(30000);
setup_timer_1(T1_INTERNAL|T1_DIV_BY_8);
}
void main()
{
set_tris_a(0x01);
LCD_Init();
setup_timer_1(T1_INTERNAL |T1_DIV_BY_8);
//set_timer1(49911); //cu 25 ms thi ngat 1 lan
set_timer1(30000); // Tdk =50us
// set_timer1(65473) ; // Tdk=100us
setup_ccp1(CCP_PWM);
set_pwm1_duty(0);
setup_timer_2(T2_DIV_BY_4,61,1); //Tpmw=25us
setup_adc(ADC_CLOCK_DIV_8);
setup_adc_ports(AN0);
set_adc_channel(0);
delay_us(10);
enable_interrupts(INT_TIMER1);
enable_interrupts(GLOBAL);
while(1)
{
if(a)
{
if(count >=10)
{ a=0;
count=0;
LCD_Gotoxy(0,1);
sprintf(str,"gia tri dien ap chuan :%2f",Vref);
LCD_Puts(str);
delay_ms(10);
LCD_Gotoxy(0,1);
sprintf(str,"gia tri dien ap :%2f",Vout);
LCD_Puts(str);
}
}
}
}