+ signed char b;
+
+ /* Use correct brightness value, then constrain it */
+ if (mode != MODE_PARTY && color != COLOR_WHITE)
+ b = cbright;
+ else
+ b = bright;
+ if (b > BRIGHT_MAX)
+ b = BRIGHT_MAX;
+ else if (b < BRIGHT_MIN)
+ b = BRIGHT_MIN;
+
+ rgb_set(led_get((red).value, b), led_get((grn).value, b),
+ led_get((blu).value, b), led_get((wht).value, b));
+}
+
+void start_fade()
+{
+ /* RGB PWM values are 8 bits. Color values are 12 bits. See led_get()
+ * for the conversion of color values and brightness to RGB values.
+ */
+ int newr, newg, newb, neww;
+
+ /* Select the destination color and fade-to time depending upon mode. */
+ fade_steps = STD_FADE;
+ if (mode == MODE_PARTY) {
+ color = lfsr_get() % COLOR_COUNT;
+ fade_steps = PARTY_MIN + (lfsr_get() % PARTY_RANGE);
+ } else if (mode == MODE_CYCLE) {
+ if (++color == COLOR_COUNT)
+ color = 0;
+ }
+
+ /* Retrieve the destination color */
+ newr = colors[color][LED_RED] << 4;
+ newg = colors[color][LED_GRN] << 4;
+ newb = colors[color][LED_BLU] << 4;
+ neww = colors[color][LED_WHT] << 4;
+
+ /* Compute increment per fade step, and remainder, for each led */
+ red.increment = (newr - red.value) / fade_steps;
+ red.remainder = newr - (red.value + red.increment * fade_steps);
+ grn.increment = (newg - grn.value) / fade_steps;
+ grn.remainder = newg - (grn.value + grn.increment * fade_steps);
+ blu.increment = (newb - blu.value) / fade_steps;
+ blu.remainder = newb - (blu.value + blu.increment * fade_steps);
+ wht.increment = (neww - wht.value) / fade_steps;
+ wht.remainder = neww - (wht.value + wht.increment * fade_steps);
+
+ /* Start the fade timer */
+ tmr_stop(TMR_CANDLE);
+ tmr_stop(TMR_INCOLOR);
+ tmr_startPeriodic(TMR_FADE, 1); /* 32.768 msec */
+}
+
+void turnOn()
+{
+ dbgpin_high();
+ on = 1;
+ rgb_on();
+ start_fade();
+ btn_pben();
+}
+
+/* Event on to off, either by switch or auto-off timer */
+void turnOff()
+{
+ tmr_stop(TMR_CFG);
+ tmr_stop(TMR_CANDLE);
+ tmr_stop(TMR_INCOLOR);
+ tmr_stop(TMR_FADE);
+ rgb_off();
+ red.value = grn.value = blu.value = wht.value = 0;
+ on = 0;
+ dbgpin_low();
+ SLEEP();
+}
+
+void pb_clicked()
+{
+ if (on) {
+ if (mode == MODE_SOLID) {
+ if (++color == COLOR_COUNT) {
+ color = 0;
+ if (++mode == MODE_COUNT)
+ mode = 0;
+ }
+ } else if (++mode == MODE_COUNT) {
+ mode = 0;
+ color = 0;
+ }
+ tmr_start(TMR_CFG, CFG_DELAY);
+ start_fade();
+ }