ws281x/
ws281x.rs

1use rand::Rng;
2use raspberrypi_utils::LedString;
3use raspberrypi_utils::urgb_u32;
4
5// Reference: https://github.com/raspberrypi/utils/blob/master/piolib/examples/ws2812.c
6
7fn main() {
8    println!("WS281x");
9    let mut leds = LedString::new(18, None, true).expect("Failed to initialize WS2812 LED strip");
10
11    let num_pixels = 14_u32;
12
13    let dir = 1; // 1 or -1
14    let mut t = 0;
15    for _ in 0..100 {
16        pattern_snakes(&mut leds, num_pixels, t);
17        std::thread::sleep(std::time::Duration::from_millis(10));
18        t += dir;
19    }
20
21    t = 0;
22    for _ in 0..100 {
23        pattern_random(&mut leds, num_pixels, t);
24        std::thread::sleep(std::time::Duration::from_millis(10));
25        t += dir;
26    }
27
28    t = 0;
29    for _ in 0..100 {
30        pattern_sparkle(&mut leds, num_pixels, t);
31        std::thread::sleep(std::time::Duration::from_millis(10));
32        t += dir;
33    }
34
35    t = 0;
36    for _ in 0..100 {
37        pattern_greys(&mut leds, num_pixels, t);
38        std::thread::sleep(std::time::Duration::from_millis(10));
39        t += dir;
40    }
41}
42
43fn pattern_snakes(leds: &mut LedString, len: u32, t: u32) {
44    for i in 0..len {
45        let x = (i + (t >> 1)) % 64;
46        if x < 10 {
47            leds.put_pixel(urgb_u32(0xff, 0, 0));
48        } else if x >= 15 && x < 25 {
49            leds.put_pixel(urgb_u32(0, 0xff, 0));
50        } else if x >= 30 && x < 40 {
51            leds.put_pixel(urgb_u32(0, 0, 0xff));
52        } else {
53            leds.put_pixel(0);
54        }
55    }
56}
57
58fn pattern_random(leds: &mut LedString, len: u32, t: u32) {
59    if t % 8 != 0 {
60        return;
61    }
62
63    let mut rng = rand::rng();
64
65    for _ in 0..len {
66        leds.put_pixel(rng.random::<u32>());
67    }
68}
69
70fn pattern_sparkle(leds: &mut LedString, len: u32, t: u32) {
71    if t % 8 != 0 {
72        return;
73    }
74
75    let mut rng = rand::rng();
76
77    for _ in 0..len {
78        leds.put_pixel(if rng.random::<u32>() % 16 != 0 { 0 } else { 0xffffffff });
79    }
80}
81
82fn pattern_greys(leds: &mut LedString, len: u32, mut t: u32) {
83    let max: u32 = 100; // let's not draw too much current!
84    t %= max;
85    for _ in 0..len {
86        leds.put_pixel(t * 0x10101);
87
88        if {
89            t += 1;
90            t >= max
91        } {
92            t = 0;
93        }
94    }
95}