#include #include #pragma config FOSC = INTRCIO // INTOSC: I/O function on GP4/5 #pragma config WDTE = OFF // Watchdog Timer #pragma config PWRTE = OFF // Power-Up Timer #pragma config MCLRE = ON // MCLR external control #pragma config BOREN = OFF // Brown-out Detect #pragma config CP = OFF // Program memory code Protection #pragma config CPD = OFF // Data memory code protection #define PWM_STEPS 16 #define STATIC_REPEATS 4 #define LED_NUM 3 // Timeout to start dimming // Each 1K is ~7.5 seconds #define MAX_CYCLES 10000 // Timeout for dim step #define DIM_COUNT 200 struct tLED { char brightness; char pinBinary; } LED[LED_NUM]; void initLEDs() { char j; for (j = 0; j < LED_NUM; j++) { LED[j].brightness = 0; } LED[0].pinBinary = 4; // GP2 LED[1].pinBinary = 16; // GP4 LED[2].pinBinary = 32; // GP5 } void initRegisters() { ANSEL = 0; // All pins Digital TRISIO = 0; // All pins output CMCON = 7; // Comparator off ADCON0 = 0; //A/D conversion off GPIO = 0; // Outputs LOW } void main() { char j; unsigned char r, pwmStep, pattern; unsigned char randResult; unsigned int cycleCount = 0; char highPWM = PWM_STEPS; initRegisters(); initLEDs(); while (1) { randResult = rand(); for (j = 0; j < LED_NUM; j++) { switch (randResult & 3) { case 1: if (LED[j].brightness < highPWM) LED[j].brightness++; break; case 2: if (LED[j].brightness > 0) LED[j].brightness--; break; } // switch randResult >>= 2; } // for for (r = 0; r < STATIC_REPEATS; r++) for (pwmStep = 0; pwmStep < PWM_STEPS; pwmStep++) { pattern = 0; for (j = 0; j < LED_NUM; j++) if (LED[j].brightness > pwmStep) pattern |= LED[j].pinBinary; GPIO = pattern; } // for cycleCount++; // Are we in the dimming phase? if (highPWM < PWM_STEPS) { if (cycleCount == DIM_COUNT) { cycleCount = 0; highPWM--; if (!highPWM) break; } } else if (cycleCount == MAX_CYCLES) { // Switch to dimming mode highPWM--; cycleCount = 0; } } // while asm("sleep"); } // main