Leftover Lighting
Another small break in uploading (what is it with 2026?), but after our house turned into a building site for a few weeks, filming/editing etc became a bit difficult!
But now I'm back with a look at the ArtCraft suite of apps (specifically FilmCraft) and as well using some leftover LED strip and diffuser housing becomes maybe a WOPR computer or a Cylon (or both).
Rather than a traditional ESP32 and WLED code for the WS2812, I've gone with a CH32V003.
And the code (below) is modified from the ch32fun github repository./* ============================== CH32V003J4M6 WOPR SOLAR LIGHT ============================== Target Device : CH32V003J4M6 (SOP-8) Framework : ch32v003fun (https://github.com/cnlohr/ch32fun) Datasheet : https://www.wch-ic.com/downloads/CH32V003DS0_PDF.html Ref Manual : https://www.wch-ic.com/downloads/CH32V003RM_PDF.html What started as a simple solar light with leftover building items has transformed into some mad WOPR implementation. A WS2812 strip blinks and fades randomly to simulate the famous computer from the 1983 movie WarGames, periodically pausing for a classic Battlestar Galactica Cylon red eye scan. Pin Assignments (SOP-8): - Pin 3 (PA2) : Floating ADC entropy seed (later: solar voltage divider) - Pin 5 (PC4) : LED strip Data Out (shared with PC1/PC2 on the SOP-8!) ============================================================================= */ // cnlohr's single-header WS2812B driver pulls its implementation here // Source: https://github.com/cnlohr/ch32fun/blob/master/extralibs/ws2812b_simple.h #define WS2812BSIMPLE_IMPLEMENTATION #include "ch32fun.h" // Core CH32V003 register definitions & startup glue #include "ws2812b_simple.h" // Cycle-accurate bit-banged NeoPixel driver from ch32fun #include <string.h> #define NUM_LEDS 17 // weird number but it matches the diffuser length #define LED_PORT GPIOC // Port C holds our data pin #define LED_PIN 4 // PC4 -> physical Pin 5 on the 8-pin CH32V003J4M6 #define TICK_MS 25 // Heartbeat of the whole show: 25 ms per tick (40 ticks/sec) #define FADE_STEPS 5 // e.g. 5 steps x 25 ms = 125 ms smooth cross-fade // WOPR panel density and timing knobs #define DARK_CHANCE_PCT 75 // 75% chance an LED goes dark (keeps ~5-6 lit so it breathes) #define LIT_MIN_TICKS 10 // shortest lit blip #define LIT_MAX_TICKS 100 // longest lit hold #define DARK_MIN_TICKS 10 // shortest dark pause #define DARK_MAX_TICKS 100 // longest dark pause // Periodic full-strip WOPR blackout tuning (40 ticks = 1.0 s) // Simulates those ominous moments when "Joshua" stops to think... #define BLACKOUT_MIN_WAIT 480 // 480 x 25 ms = 12 s (~5 blackouts/min at most) #define BLACKOUT_MAX_WAIT 2400 // (~1 blackout/min at least) #define BLACKOUT_MIN_DUR 20 // 20 x 25 ms = 0.5 s quick power dip #define BLACKOUT_MAX_DUR 100 // 100 x 25 ms = 2.5 s dramatic pause // Periodic Cylon eye sequence tuning (40 ticks = 1.0 s, 2400 ticks = 1 min) // "By your command..." - https://en.wikipedia.org/wiki/Cylons #define CYLON_MIN_WAIT 4800 // 4800 x 25 ms = 120 s (2 minutes minimum between scans) #define CYLON_MAX_WAIT 12000 // 12000 x 25 ms = 300 s (5 minutes maximum between scans) #define CYLON_BLACKOUT_TICKS 120 // 120 x 25 ms = 3.0 s pitch-black before the "eye" wakes #define CYLON_STEP_TICKS 2 // 2 x 25 ms = 50 ms per pixel (~1.6 s per round-trip sweep) #define CYLON_PASSES 5 // 5 full back-and-forth sweeps before returning to WOPR // Brightness ceiling (0-255). 64 is fine inside a diffuser, keeping peak current under ~150 mA #define MAX_BRIGHT 64 // Top-level state machine modes typedef enum { MODE_WOPR = 0, // Normal asynchronous WarGames console blinkenlights MODE_BLACKOUT, // Brief random full-panel dark pause MODE_CYLON_PAUSE, // 3-second dramatic blackout building up to Cylon mode MODE_CYLON_SCAN // Red eye sweeping back and forth with a fading tail } display_mode_t; // Every single one of the 17 LEDs gets its own private state struct (11 bytes each). // Total RAM for all 17 LEDs = 187 bytes out of the CH32V003's 2,048 bytes of SRAM! typedef struct { uint8_t cur_r, cur_g, cur_b; // What is actually glowing on the LED right now uint8_t start_r, start_g, start_b; // Where the color started when a fade began uint8_t target_r, target_g, target_b; // Where the color is heading uint8_t fade_rem; // 25 ms steps left in current fade (0 = steady/snapped) uint8_t hold_ticks; // 25 ms ticks left to hold steady before picking again } led_state_t; led_state_t leds[NUM_LEDS]; // Our 17 independent pixel state machines uint8_t led_buffer[NUM_LEDS * 3]; // Raw GRB byte array clocked out to the WS2812B strip // 1960s Mainframe / WOPR console color palette (scaled by MAX_BRIGHT) // Pure random RGB looks like a party store; but warm tungsten, amber, red, and // occasional phosphor green looks straight off the movie set. const uint8_t palette[][3] = { {MAX_BRIGHT, MAX_BRIGHT / 3, 0}, // Warm Tungsten Amber {MAX_BRIGHT, MAX_BRIGHT / 2, MAX_BRIGHT / 12}, // Incandescent Panel Glow (hint of blue warms the yellow) {MAX_BRIGHT, MAX_BRIGHT / 5, 0}, // Deep Neon Orange {MAX_BRIGHT, 0, 0}, // Alert / DEFCON Red {MAX_BRIGHT * 3 / 4, 0, 0}, // Dim Status Red {0, MAX_BRIGHT * 3 / 4, MAX_BRIGHT / 8} // Phosphor Indicator Green }; #define PALETTE_SIZE (sizeof(palette) / sizeof(palette[0])) // Handy macro so we can add/remove colors freely // ----------------------------------------------------------------------------- // Xoshiro128** PRNG Engine // Fast, rock-solid 32-bit pseudo-random generator by Blackman & Vigna. // Reference: https://prng.di.unimi.it/xoshiro128starstar.c // ----------------------------------------------------------------------------- static uint32_t xos_s[4] = { 0x29012026, 0x10141400, 0xDEADBEEF, 0xCAFEBABE }; // Default seed (stirred at boot!) // Classic 32-bit bitwise rotate-left; GCC compiles this down to a neat RISC-V shift/or pair static inline uint32_t rotl(const uint32_t x, int k) { return (x << k) | (x >> (32 - k)); } // Cranks the 128-bit state forward and spits out a fresh 32-bit random word uint32_t xos_next(void) { const uint32_t result = rotl(xos_s[1] * 5, 7) * 9; // Scrambler function (the "**" in Xoshiro128**) const uint32_t t = xos_s[1] << 9; // Save shifted word 1 before mixing xos_s[2] ^= xos_s[0]; // Linear engine state transitions... xos_s[3] ^= xos_s[1]; xos_s[1] ^= xos_s[2]; xos_s[0] ^= xos_s[3]; xos_s[2] ^= t; // Fold saved shift back in xos_s[3] = rotl(xos_s[3], 11); // Final bit rotation return result; } // The old function, it returns a random integer from `small` up to `big` uint16_t gimmerand(uint16_t small, uint16_t big) { if (small >= big) return small; // Guard against swapped or equal bounds uint32_t result = xos_next(); // Grab 32 fresh random bits uint16_t range = big - small + 1; // +1 makes the upper bound inclusive return small + (uint16_t)(result % range); // Map into [small .. big] } // ----------------------------------------------------------------------------- // Hardware Entropy Seeding via Floating ADC Pin // Unlike the Padauk PFS154, the CH32V003 has a 10-bit ADC Reading an // unconnected pin picks up thermal and ambient EMI noise so every power-up // starts a genuinely different lightshow instead of repeating the same pattern. // ----------------------------------------------------------------------------- void seed_rng_from_adc(void) { RCC->APB2PCENR |= RCC_APB2Periph_GPIOA | RCC_APB2Periph_ADC1; // Wake up GPIOA and ADC1 peripheral clocks RCC->CFGR0 &= ~(0x1F << 11); // Clear existing ADC clock prescaler bits RCC->CFGR0 |= RCC_ADCPRE_DIV8; // Run ADC clock at 48 MHz / 8 = 6 MHz (well within 14 MHz max) // Set PA2 (ADC Channel A0, Pin 3 on SOP-8) to floating analog input (CNF=00, MODE=00) GPIOA->CFGLR &= ~(0xF << (2 * 4)); ADC1->CTLR2 = ADC_ADON | ADC_EXTSEL | ADC_EXTTRIG; // Power on ADC1 and arm software-triggered conversion ADC1->RSQR1 = 0; // Only 1 channel in our conversion sequence ADC1->RSQR3 = 0; // Select Channel 0 (PA2) ADC1->SAMPTR2 = 0x07; // Max sample window (241.5 cycles) so the floating pin soaks up plenty of noise ADC1->CTLR2 |= ADC_RSTCAL; // Reset internal ADC calibration registers... while (ADC1->CTLR2 & ADC_RSTCAL); // ...and wait until reset finishes ADC1->CTLR2 |= ADC_CAL; // Run self-calibration... while (ADC1->CTLR2 & ADC_CAL); // ...and wait until calibration completes // Take 16 readings and XOR the noisy lowest bits across all four Xoshiro state words for (uint8_t i = 0; i < 16; i++) { ADC1->CTLR2 |= ADC_SWSTART; // Kick off a single conversion while (!(ADC1->STATR & ADC_EOC)); // Spin until End-Of-Conversion flag pops up uint16_t sample = ADC1->RDATAR; // Grab the 10-bit result (clears EOC automatically) xos_s[i & 0x03] ^= ((uint32_t)(sample & 0x03) << (i * 2)) ^ (sample << 7); // Stir noise into xos_s[0..3] } // Shut down ADC1 completely so it doesn't run down battery ADC1->CTLR2 &= ~ADC_ADON; RCC->APB2PCENR &= ~RCC_APB2Periph_ADC1; // Xoshiro128** must never have an all-zero state; restore fallback seed if that ever happened if ((xos_s[0] | xos_s[1] | xos_s[2] | xos_s[3]) == 0) { xos_s[0] = 0x29012026; xos_s[1] = 0x10141400; xos_s[2] = 0xDEADBEEF; xos_s[3] = 0xCAFEBABE; } // Repeat the generator 8 times to thoroughly diffuse the newly mixed seed bits for (uint8_t i = 0; i < 8; i++) { xos_next(); } } // ----------------------------------------------------------------------------- // Picks the next state for a single LED: // 1. Decides whether it goes dark (68%) or lights up in a console color (32%) // 2. Picks a random hold duration // 3. Flips a 50/50 coin between a crisp relay-style snap or a 125 ms fade // Returns 1 if it snapped immediately (meaning the strip needs an update now), // or 0 if it's starting a multi-step fade. // ----------------------------------------------------------------------------- uint8_t start_led_transition(uint8_t idx) { uint8_t roll = (uint8_t)gimmerand(0, 99); // Roll 0..99 percentile dice if (roll < DARK_CHANCE_PCT) { // Heading to dark leds[idx].target_r = 0; leds[idx].target_g = 0; leds[idx].target_b = 0; leds[idx].hold_ticks = (uint8_t)gimmerand(DARK_MIN_TICKS, DARK_MAX_TICKS); } else { // Heading to a random color from our 1960s mainframe palette uint8_t c = (uint8_t)gimmerand(0, PALETTE_SIZE - 1); leds[idx].target_r = palette[c][0]; leds[idx].target_g = palette[c][1]; leds[idx].target_b = palette[c][2]; leds[idx].hold_ticks = (uint8_t)gimmerand(LIT_MIN_TICKS, LIT_MAX_TICKS); } // 50/50 coin flip: 1 = smooth 125 ms filament fade, 0 = instant mechanical click if (gimmerand(0, 1)) { leds[idx].start_r = leds[idx].cur_r; // Snapshot where we're fading FROM leds[idx].start_g = leds[idx].cur_g; leds[idx].start_b = leds[idx].cur_b; leds[idx].fade_rem = FADE_STEPS; // Arm the 5-step countdown return 0; // First fade step happens on the next 25 ms tick } else { leds[idx].cur_r = leds[idx].target_r; // Jump straight to the destination color leds[idx].cur_g = leds[idx].target_g; leds[idx].cur_b = leds[idx].target_b; leds[idx].fade_rem = 0; // No fade needed return 1; // Tell main loop the strip buffer changed } } // Packs our RGB structs into WS2812B's GRB byte order and sends it out to PC4 void push_leds(void) { for (int i = 0; i < NUM_LEDS; i++) { led_buffer[i * 3 + 0] = leds[i].cur_g; // Green goes first on WS2812B! led_buffer[i * 3 + 1] = leds[i].cur_r; // Red second led_buffer[i * 3 + 2] = leds[i].cur_b; // Blue third } WS2812BSimpleSend(LED_PORT, LED_PIN, led_buffer, sizeof(led_buffer)); } // Blanks the entire strip immediately (used for blackouts and Cylon build-up) void clear_strip_now(void) { memset(led_buffer, 0, sizeof(led_buffer)); WS2812BSimpleSend(LED_PORT, LED_PIN, led_buffer, sizeof(led_buffer)); } // Resets all 17 pixels from dark into staggered random WOPR states void init_wopr_leds(void) { for (uint8_t i = 0; i < NUM_LEDS; i++) { leds[i].cur_r = 0; leds[i].cur_g = 0; leds[i].cur_b = 0; start_led_transition(i); // Some will snap on right away, others will fade up } push_leds(); } // ============================================================================= // Main Loop // ============================================================================= int main(void) { SystemInit(); // Bring the CH32V003 up to 48 MHz (required for FUNCONF_SYSTICK_USE_HCLK 1 in funconfig.h) seed_rng_from_adc(); // Harvest boot-time analog noise before enabling Port C RCC->APB2PCENR |= RCC_APB2Periph_GPIOC; // Turn on the clock for Port C (our data pin) init_wopr_leds(); // Light up the initial WOPR panel state display_mode_t mode = MODE_WOPR; // Start in normal WarGames computer mode uint16_t blackout_timer = gimmerand(BLACKOUT_MIN_WAIT, BLACKOUT_MAX_WAIT); // Schedule first brief blackout uint16_t cylon_timer = gimmerand(CYLON_MIN_WAIT, CYLON_MAX_WAIT); // Schedule first Cylon scan // State variables for the Cylon red-eye sweep uint8_t cylon_step_tick = 0; // Sub-timer pacing the eye movement (every 50 ms) int8_t cylon_pos = 0; // Signed index (0 .. NUM_LEDS-1) so bouncing math is safe int8_t cylon_dir = 1; // +1 sweeping right, -1 sweeping left uint8_t cylon_passes = 0; // Counts completed round trips while (1) { Delay_Ms(TICK_MS); // Pace the whole engine to an exact 25 ms heartbeat // --------------------------------------------------------------------- // State 1: Brief WOPR Blackout // --------------------------------------------------------------------- if (mode == MODE_BLACKOUT) { if (--blackout_timer == 0) { mode = MODE_WOPR; // Back to work, Joshua blackout_timer = gimmerand(BLACKOUT_MIN_WAIT, BLACKOUT_MAX_WAIT); init_wopr_leds(); // Wake up into a fresh random configuration } continue; } // --------------------------------------------------------------------- // State 2: 3-Second Suspense Pause Before Cylon Eye Wakes Up // --------------------------------------------------------------------- if (mode == MODE_CYLON_PAUSE) { if (--cylon_timer == 0) { mode = MODE_CYLON_SCAN; cylon_step_tick = 1; // Trigger the very first LED on the next loop pass cylon_pos = 0; // Start at the left end of the diffuser cylon_dir = 1; // Sweep rightward cylon_passes = 0; memset(led_buffer, 0, sizeof(led_buffer)); // Ensure a clean black canvas } continue; } // --------------------------------------------------------------------- // State 3: Cylon Red Eye Scan with Phosphor Decay Trail // --------------------------------------------------------------------- if (mode == MODE_CYLON_SCAN) { if (--cylon_step_tick == 0) { cylon_step_tick = CYLON_STEP_TICKS; // Reload 50 ms step timer // Decay every pixel's red channel by half (>> 1) to leave a glowing tail for (uint8_t i = 0; i < NUM_LEDS; i++) { led_buffer[i * 3 + 0] = 0; // No green led_buffer[i * 3 + 1] = led_buffer[i * 3 + 1] >> 1; // Halve previous red brightness led_buffer[i * 3 + 2] = 0; // No blue } // Stamp the bright red Cylon eye at its current spot and update strip led_buffer[cylon_pos * 3 + 1] = MAX_BRIGHT; WS2812BSimpleSend(LED_PORT, LED_PIN, led_buffer, sizeof(led_buffer)); // Move the eye one pixel and bounce cleanly off both ends cylon_pos += cylon_dir; if (cylon_pos >= (NUM_LEDS - 1)) { cylon_pos = NUM_LEDS - 1; cylon_dir = -1; // Hit right end -> head back left } else if (cylon_pos <= 0) { cylon_pos = 0; cylon_dir = 1; // Returned to left end -> one full round trip complete! cylon_passes++; if (cylon_passes >= CYLON_PASSES) { // Done scanning: return to normal WOPR blinkenlights mode = MODE_WOPR; cylon_timer = gimmerand(CYLON_MIN_WAIT, CYLON_MAX_WAIT); blackout_timer = gimmerand(BLACKOUT_MIN_WAIT, BLACKOUT_MAX_WAIT); init_wopr_leds(); } } } continue; } // --------------------------------------------------------------------- // State 4: Normal Asynchronous WOPR Console Operation // --------------------------------------------------------------------- // Check Cylon trigger first (every 2 to 5 minutes) if (--cylon_timer == 0) { mode = MODE_CYLON_PAUSE; cylon_timer = CYLON_BLACKOUT_TICKS; // 3.0 s blackout before the red eye appears clear_strip_now(); continue; } // Check regular random WOPR blackout trigger if (--blackout_timer == 0) { mode = MODE_BLACKOUT; blackout_timer = gimmerand(BLACKOUT_MIN_DUR, BLACKOUT_MAX_DUR); clear_strip_now(); continue; } // Tick all 17 independent LEDs; only talk to the WS2812B if something moved uint8_t moved = 0; for (uint8_t i = 0; i < NUM_LEDS; i++) { if (leds[i].fade_rem > 0) { // Mid-fade: step linearly from start_r/g/b toward target_r/g/b leds[i].fade_rem--; uint8_t step = FADE_STEPS - leds[i].fade_rem; // Counts 1, 2, 3, 4, 5 leds[i].cur_r = leds[i].start_r + ((int16_t)(leds[i].target_r - leds[i].start_r) * step) / FADE_STEPS; leds[i].cur_g = leds[i].start_g + ((int16_t)(leds[i].target_g - leds[i].start_g) * step) / FADE_STEPS; leds[i].cur_b = leds[i].start_b + ((int16_t)(leds[i].target_b - leds[i].start_b) * step) / FADE_STEPS; moved = 1; // Strip needs refreshing on this tick } else { // Holding steady: count down until it's time to pick a new state if (leds[i].hold_ticks > 0) { leds[i].hold_ticks--; } if (leds[i].hold_ticks == 0) { moved |= start_led_transition(i); // Returns 1 if snapped, 0 if starting a fade } } } // Send out the 51-byte GRB frame when at least one pixel actually changed if (moved) { push_leds(); } } }
This was a (ch32)fun project and hopefully a fun video for you.


