unsigned int adc_val;
unsigned long volts_m;
void main() {
TRISD = 0; // PORTD all output to LED
TRISC = 0; // PORTC all output to LED
ADCON1 = 0x88; // configure Vref, and analog channels
TRISA = 0xFF; // designate PORTA as input
for (;;) {
adc_val = ADC_read(1); // get ADC value for U from channel 1
volts_m = (long)adc_val*5000/1023; // Convert ADC value to millivolts
// 0 LED, Target voltage = 0.0v, Range 0.0 - 0.35v
if (volts_m >= 0 && volts_m <= 350) {
PORTD = 0b00000000;
PORTC = 0b00000000;
}
// 1 LED, Target voltage = 0.5v, Range 0.35 - 0.7v
if (volts_m > 350 && volts_m <= 700) {
PORTD = 0b00000100;
PORTC = 0b00000000;
}
// 2 LEDs, Target voltage = 1.0v, Range 0.7 - 1.3v
if (volts_m > 700 && volts_m <= 1300) {
PORTD = 0b00001100;
PORTC = 0b00000000;
}
// 3 LEDs, Target voltage = 1.5v, Range 1.3 - 1.7v
if (volts_m > 1300 && volts_m <= 1700) {
PORTD = 0b00001100;
PORTC = 0b00010000;
}
// 4 LEDs, Target voltage = 2.0, Range 1.7 - 2.3v
if (volts_m > 1700 && volts_m <= 2300) {
PORTD = 0b00001100;
PORTC = 0b00110000;
}
// 5 LEDs, Target voltage = 2.5, Range 2.3 - 2.7v
if (volts_m > 2300 && volts_m <= 2700) {
PORTD = 0b00001100;
PORTC = 0b01110000;
}
// 6 LEDs, Target voltage = 3.0, Range 2.7 - 3.3v
if (volts_m > 2700 && volts_m <= 3300) {
PORTD = 0b00001100;
PORTC = 0b11110000;
}
// 7 LEDs, Target voltage = 3.5, Range 3.3 - 3.7v
if (volts_m > 3300 && volts_m <= 3700) {
PORTD = 0b00011100;
PORTC = 0b11110000;
}
// 8 LEDs, Target voltage = 4.0, Range 3.7 - 4.3v
if (volts_m > 3700 && volts_m <= 4300) {
PORTD = 0b00111100;
PORTC = 0b11110000;
}
// 9 LEDs, Target voltage = 4.5, Range 4.3 - 4.7v
if (volts_m > 4300 && volts_m <= 4700) {
PORTD = 0b01111100;
PORTC = 0b11110000;
}
// Flash LEDs, Target voltage = 5.0, Range 4.7 - 5.0v
if (volts_m > 4700 && volts_m <= 5000) {
do {
PORTD = 0b00000000;
PORTC = 0b00000000;
delay_ms(300);
PORTD = 0b01111100;
PORTC = 0b11110000;
delay_ms(300);
}
while (volts_m > 4700 && volts_m <= 5000);
}
}
}