Sunteți pe pagina 1din 4

unsigned short kp, RPMi1, RPMi2, RPMi3, RPMi4, ANencd;

unsigned int RPMi=500;



unsigned short cnd;

unsigned short cnt;

unsigned short x;

unsigned short e=0;

unsigned int AN;

float errora=0;

float derror=0;

float u=0;

float up=0;

float ud=0;
float ui=0;
long int contador=0;
int delay=0;
//unsigned short kp = 2;
//unsigned short kd = 3;
float error=0;
float ierror=0;
char txte[14];
char txtu[14];
char txt[7];
unsigned int Pencd;
unsigned long int fencd;
float RPMr;
float RPMm = 1600; // valor maximo de las revoluciones por minuto
float RPM;
float duty1; // recibe un valor decimal
unsigned short duty; // lo convierte en entero
// LCD module connections
sbit LCD_RS at RD1_bit;
sbit LCD_EN at RD3_bit;
sbit LCD_D4 at RD4_bit;
sbit LCD_D5 at RD5_bit;
sbit LCD_D6 at RD6_bit;
sbit LCD_D7 at RD7_bit;
sbit LCD_RS_Direction at TRISD1_bit;
sbit LCD_EN_Direction at TRISD3_bit;
sbit LCD_D4_Direction at TRISD4_bit;
sbit LCD_D5_Direction at TRISD5_bit;
sbit LCD_D6_Direction at TRISD6_bit;
sbit LCD_D7_Direction at TRISD7_bit;
// End LCD module connections
interrupt(){
if(INTCON.INTF==1){ // int por RB0
contador++;
INTCON.INTF=0;
}
if(PIR1.TMR1IF==1){
T1CON.TMR1ON=0;
TMR1H=0x0B; //100ms
TMR1L=0xDB;
T1CON.TMR1ON=1;
fencd=contador/10; // frecuencia del encoder en kHz
RPMr = 1.5*contador; // RPM reales segun encoder
contador=0;
AN=ADC_Read(0);
RPMi=(AN*RPMm)/1023;
errora=error;
error= RPMi+1*RPMr; // calcula el error cada 10ms(tiempo de muestreo)
derror=(error+1*errora)/0.1;
ierror=ierror+0.05*(error+errora);
up=0.2*error;
ud=0.02*derror;
ui=1*ierror;
if(ui>=255) ui=255;
u=up+ud+ui;
if(u>=0){
PORTB.F1=1;
PORTB.F2=0;
}
else{
PORTB.F1=0;
PORTB.F2=1;
u=u;
}
if(u>=255) u=255;
PWM1_Start(); // enciende el PWM
duty=u;
PWM1_Set_Duty(duty); // establece el duty
PIR1.TMR1IF=0;
}
}
Port_init() { // inicializa puertos

TRISC.F2=0; // Port C salida
PORTC.F2=0; // PWM es inicialmente cero
TRISA.F0=1; // Entrada ADC para la realimentacin
PORTB=0;
TRISB=1;
ADCON1 = 142; // Configure AN0 pin as analog
PORTD=0x00;
TRISD=0b00000101;
}
Inte_init(){
INTCON.GIE=1;
INTCON.PEIE=1;
OPTION_REG=0X87;
TMR1H=0x0B; //100ms
TMR1L=0xDB;
T1CON=0b00100001;
INTCON.INTE=1; //habilita la int por RB0
PIE1.TMR1IE=1;
}
void main() {
cnt = 0; // Reset counter
cnd = 1;
Port_init();
Lcd_Init(); // Initialize Lcd
Lcd_Cmd(_LCD_CLEAR); // Clear display
Lcd_Cmd(_LCD_CURSOR_OFF); // Cursor off
PWM1_Init(5000); // inicializa el PWM y establece una frecuencia de 5kHz
ADC_Init();
Inte_init();
error=0;
while(1) {
Lcd_out(1, 1, "RPMref= ");
IntToStr(RPMi, txt);
Lcd_Out_Cp(txt); // introduce el valor de RPM en el uC
Delay_ms(10);
Lcd_Out(2, 1, "RPMreal= ");
FloatToStr(RPMr, txte);
Lcd_Out_Cp(txte); // imprime los millares // Muestra las RPM en el LCD
Lcd_Out_Cp(" ");
}
}

S-ar putea să vă placă și