#include <16f1827.h>
#use delay (internal = 32MHz)
#use RS232(BAUD=9600, XMIT=PIN_B2, RCV=PIN_B1, stream=com,errors)
#define NIVEL_0 PIN_B6
#define NIVEL_1 PIN_B7
#define NIVEL_2 PIN_B3
#define NIVEL_3 PIN_B5
#define NIVEL_4 PIN_B4
#BYTE TRISA = 0x85
#define LDR PIN_A0
void main(){
int nivel_luz;
int luz_ant;
int porc;
int checksum;
int trama[23]={0x7E, 0x00, 0x13, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFE, 0x00, 0x00, 0x01, 0x20, 0x83, 0x08, 0x00, 0x48};
setup_adc_ports(LDR|VSS_VDD); //Canal 0 analogico
setup_adc(ADC_CLOCK_INTERNAL);
nivel_luz = read_adc();
luz_ant = nivel_luz;
while(TRUE){
set_adc_channel(0); //Habilitacion canal0
delay_us(20);
nivel_luz = read_adc();
delay_us(20);
// RANGOS:
// VREF = 3 V
// LUZ MÁXIMA: 0.60 V -> (0.60*255)/3 = 51
// LUZ MÍNIMA: 1.23 V -> (1.23*255)/3 = 104
if(nivel_luz < 50){ // V < 0.58V
output_low (NIVEL_0);
output_low (NIVEL_1);
output_low (NIVEL_2);
output_low (NIVEL_3);
output_low (NIVEL_4);
delay_ms(20);
porc = 0x00;
checksum = 0x48;
}
else if(nivel_luz > 51 && nivel_luz < 65){ // 0.6V < V < 0.76V
output_high (NIVEL_0);
output_low (NIVEL_1);
output_low (NIVEL_2);
output_low (NIVEL_3);
output_low (NIVEL_4);
delay_ms(20);
porc = 0x14;
checksum = 0x34;
}
else if(nivel_luz > 64 && nivel_luz < 80){ // 0.75V < V < 0.94V
output_high (NIVEL_0);
output_high (NIVEL_1);
output_low (NIVEL_2);
output_low (NIVEL_3);
output_low (NIVEL_4);
delay_ms(20);
porc = 0x28;
checksum = 0x20;
}
else if(nivel_luz > 79 && nivel_luz < 95){ // 0.92V < V < 1.11V
output_high (NIVEL_0);
output_high (NIVEL_1);
output_high (NIVEL_2);
output_low (NIVEL_3);
output_low (NIVEL_4);
delay_ms(20);
porc = 0x3C;
checksum = 0x0C;
}
else if(nivel_luz > 94 && nivel_luz < 105){ // 1.10V < V < 1.23V
output_high (NIVEL_0);
output_high (NIVEL_1);
output_high (NIVEL_2);
output_high (NIVEL_3);
output_low (NIVEL_4);
delay_ms(20);
porc = 0x50;
checksum = 0xF8;
}
else if(nivel_luz > 104){ // 1.22V < V
output_high (NIVEL_0);
output_high (NIVEL_1);
output_high (NIVEL_2);
output_high (NIVEL_3);
output_high (NIVEL_4);
delay_ms(20);
porc = 0x64;
checksum = 0xE4;
}
if(luz_ant-5 < nivel_luz < luz_ant+5){delay_ms(50);}
else{
trama[21] = porc;
trama[22] = checksum;
for(int pos=0;pos<=22;pos++){
delay_ms(500);
}
luz_ant = nivel_luz;
}
}
}