#include <16F88.h>
#FUSES WDT                    // No Watch Dog Timer
//#FUSES INTRC_IO                 // >>> Oscilador interno, no CLKOUT
#FUSES HS
#FUSES PUT                      // Power Up Timer
#FUSES NOMCLR                   // Master Clear pin used for I/O
#FUSES BROWNOUT                 // Reset when brownout detected
#FUSES PROTECT                // Code not protected from reading
#FUSES NOCPD                    // No EE protection
#device ADC=8
#byte PortA=0x05
#byte PortB=0x06
#use delay(int=4000000,WDT) // Especifica al compilador que hace uso del OSC interno
//------------ Pines del LCD ---------------------//
#define LCD_E     PIN_B0
#define LCD_CK    PIN_B1   
#define LCD_DAT   PIN_B2
//--------------------------------------------------//
Float CicloMin=0.1,CicloMax=0.4,CicloSeteado=0.5,TMax=1000,TMin=143,T=33,Frecuencia=0;
int8 ValorCiclo=0,ValorPeriodo=0;
int16 THi=0,TLow=0;
#include <flex_lcd_3pins.c>

void CalcularAjusteCiclo()
{
set_adc_channel(3);
delay_us(20);
ValorCiclo=read_adc();
CicloSeteado=CicloMin+((ValorCiclo/255.0)*CicloMax);
}
void CalcularAjustePeriodo()
{
set_adc_channel(4);
delay_us(20);
ValorPeriodo=read_adc();
T=TMax-((ValorPeriodo/255.0)*TMax)+Tmin;
T=T-T*0.1;
}
void CalculaTiempos()
{
THi=CicloSeteado*T;
TLow=T-THi;
Frecuencia=1000000/(T);
}
void GenerarPulsos()
{
#asm
bsf PortB,3
#endasm
//output_high(PIN_B3);
delay_us(THi);
#asm
bcf PortB,3
#endasm
///output_low(PIN_B3);
delay_us(TLow);
}
#int_TIMER1
void  TIMER1_isr(void)//Función de interrupción por desbordamiento TMR1  
{
//GenerarPulsos();
CalcularAjustePeriodo();
CalcularAjusteCiclo();
CalculaTiempos();  
lcd_gotoxy(6,1);
printf(lcd_putc,"%f",Frecuencia);
printf(lcd_putc,"Hz   ");
lcd_gotoxy(13,2);
printf(lcd_putc,"%f",CicloSeteado);
//printf(lcd_putc,"%%");
set_timer1(0x0BDC);
restart_wdt();
}
void main()
{
   setup_adc_ports(sAN3|sAN4|VSS_VDD);
   setup_adc(ADC_CLOCK_INTERNAL);
   setup_wdt(WDT_2304MS);
   setup_timer_1 ( T1_INTERNAL | T1_DIV_BY_8 ); //Para poder generar 200ms
   set_timer1(0x0BDC);
   enable_interrupts(INT_TIMER1);
   enable_interrupts(GLOBAL);
   //disable_interrupts(GLOBAL);
   setup_comparator(NC_NC_NC_NC);   // Todo digital
   set_tris_a(0xFF);
   set_tris_b(0xF0);
   CalcularAjustePeriodo();
   CalcularAjusteCiclo();
   CalculaTiempos();
   delay_ms(500);
   lcd_init();              // inicializamos el LCD
   lcd_setcursor_vb(1,1);  //cursor visible,papadeo
   lcd_gotoxy(1,1);
   printf(lcd_putc,"Frec:");
   lcd_gotoxy(1,2);
   printf(lcd_putc,"Duty Cicle:");
   while(TRUE){
   GenerarPulsos();
   }
}
