#include <12F683.h>
#device adc=8
#FUSES WDT,NOMCLR,PUT,INTRC_IO,PROTECT
#use delay(clock=8000000)
#use fast_io(a)
//GPIO
#byte GP = 0x05
//0b00011110
//#bit DAT = GP.0 //tambien se usa como Tx para debug
//#bit CLK = GP.1
#bit CX0 = GP.2
//#bit VPP = GP.3
#define ADC 3 //GP4/AN3
#bit TRIAC = GP.5
//#use rs232(baud=2400, xmit=PIN_A0)
//Constantes
#define RES_ADC 255 //resolucion del adc
#define LIMINF 5 //limite inferior de velocidad
#define LIMSUP 250 //limite superior de velocidad
//Variables
short flagCX0 = FALSE; //flag de cruce por cero
int Velocidad = LIMINF; //velocidad actual del motor
long VelocidadCCP = 0; //cuando tiene que saltar la interrupcion CCP
long Semiciclo = 0; //duracion del semiciclo
//Rutinas
void CalcularVelocidad(void);
#int_EXT
void INT_EXT_isr(void){
TRIAC = FALSE; //empieza semiciclo, apagar triac
Semiciclo = get_timer1(); //establece la duracion del semciclo
set_timer1(0); //restablece timer
flagCX0 = TRUE; //flag para leer ADC y calcular velocidad
}
#int_CCP1
void CCP1_isr(void){
TRIAC = TRUE; //encender triac, estamos en la intensidad deseada
}
void main() {
setup_adc_ports(sAN3|VSS_VDD);
setup_adc(ADC_CLOCK_INTERNAL);
setup_timer_0(RTCC_INTERNAL);
setup_timer_1(T1_INTERNAL|T1_DIV_BY_1);
setup_timer_2(T2_DISABLED,0,1);
setup_wdt(WDT_18MS);
setup_ccp1(CCP_COMPARE_INT);
setup_comparator(NC_NC);
setup_vref(FALSE);
enable_interrupts(INT_EXT);
enable_interrupts(INT_CCP1);
enable_interrupts(GLOBAL);
setup_oscillator(OSC_8MHZ);
set_tris_a(0b00011110);
set_adc_channel(ADC);
ext_int_edge(0,L_TO_H); //configura INT para que solo se active a la subida
TRIAC = FALSE; //pwm apagado
do{
if(flagCX0 == TRUE){
flagCX0 = FALSE;
CalcularVelocidad();
}
}while(TRUE);
}
void CalcularVelocidad(void){
long Step = 0;
restart_wdt(); //reinicio el watchdog
Velocidad = read_adc(); //leo adc
if(Velocidad < LIMINF) //comprueba que la velocidad nunca sea inferior al limite
Velocidad = LIMINF;
if(Velocidad > LIMSUP) //comprueba que la velocidad nunca sea superior al limite
Velocidad = LIMSUP;
Step = Semiciclo / RES_ADC;
VelocidadCCP = Semiciclo - (Step * Velocidad);
CCP_1 = VelocidadCCP;
}