// main.c #include __CONFIG(INTIO & WDTDIS & MCLRDIS & BORDIS & UNPROTECT & PWRTEN); void Update(void); void main(void) { // Load Factory Calibration Value Into OSCCAL #asm call 0x3FF bsf _STATUS,5 movwf _OSCCAL #endasm TRISIO = 0b11001111; // RA4,RA5 are outputs GPIO = 0x00; //Clear GPIO (all LEDs off) VRCON = 0x00; //Turn Off Voltage Reference Peripheral CMCON = 0x07; //Turn Off Comparator Peripheral TMR0 = 0x00; //Clear Timer0 OPTION = 0b10000010; //Set Timer0 Prescaler To Fast Flash LED's ANSEL = 0b01010001; // set A/D rate TOSC/16 (4us) and set AN0 as analog input ADCON0 = 0b00000001; // configure Vdd ref, MSB in ADRESH, AN0, A/D enabled GODONE = 1; T0IE = 1; //Timer0 Overflow Interrupt Enabled T0IF = 0; //Clear Timer0 Overflow Interrupt Flag GIE = 1; //Enable All Interrupts for (;;); } void interrupt Isr(void) { if (T0IE & T0IF) //If A Timer0 Interrupt, Then { Update(); T0IF = 0; //Clear Timer0 Interrupt Flag } return; } static unsigned char State = 2; // 0 = red, 1 = yellow, 2 = green // start in green state void ReadAD(void) { unsigned char reading; if (GODONE == 1) return; // not finished reading = ADRESH; GODONE = 1; // read again // 255 = 5V -> 15V battery level // 8V battery level -> 136 // 8.2V battery level -> 140 // 8.4V battery level -> 142 if (reading <= 136) State = 0; else if (reading <= 142) State = 1; else State = 2; } static unsigned char WhichLed = 0; // LED to light next static unsigned char Phase = 0; void Update(void) { unsigned char output = 0; // no LEDs on ReadAD(); switch (WhichLed) { case 0: // red if (State < 2) output = 0b00010000; // RA4 = 1, RA5 = 0 break; case 1: // green if (State > 0) output = 0b00100000; // RA5 = 1, RA4 = 0 break; } if ((State == 0) && (Phase & 128)) output = 0; // flash red GPIO = output; WhichLed ^= 1; Phase++; }