Skip to main content

ws2812_rp235x/
lib.rs

1#![no_std]
2//! これはWS2812のRP235x用ドライバです。
3//! WS2812とは、マイコン内蔵RGBLEDでNeoPixel LEDとも呼ばれます。
4//!
5//! このクレートはws2812-pioを大いに参考にしています。
6
7use cortex_m::prelude::_embedded_hal_timer_CountDown;
8use rp235x_hal::{
9    fugit::{ExtU32, HertzU32},
10    gpio::AnyPin,
11    pio::{Buffers, PIOBuilder, PinDir, ShiftDirection},
12    pio::{PIO, PIOExt, StateMachineIndex, Tx, UninitStateMachine},
13    timer::{CountDown, TimerDevice},
14};
15use smart_leds_trait::{RGB8, SmartLedsWrite};
16
17pub struct Ws2812Direct<P, SM, I>
18where
19    I: AnyPin<Function = P::PinFunction>,
20    P: PIOExt,
21    SM: StateMachineIndex,
22{
23    tx: Tx<(P, SM)>,
24    _pin: I,
25}
26
27impl<P, SM, I> Ws2812Direct<P, SM, I>
28where
29    I: AnyPin<Function = P::PinFunction>,
30    P: PIOExt,
31    SM: StateMachineIndex,
32{
33    pub fn new(
34        pin: I,
35        pio: &mut PIO<P>,
36        sm: UninitStateMachine<(P, SM)>,
37        clock_freq: HertzU32,
38    ) -> Self {
39        const T1: u8 = 2; // start bit
40        const T2: u8 = 5; // data bit
41        const T3: u8 = 3; // stop bit
42        const CYCLES_PER_BIT: u32 = (T1 + T2 + T3) as u32;
43        const FREQ: HertzU32 = HertzU32::kHz(800);
44
45        // PIOに入れるプログラム
46        let program = pio_proc::pio_asm!(
47            ".side_set 1",
48            ".define public T1 2",
49            ".define public T2 5",
50            ".define public T3 3",
51            ".wrap_target",
52            "bitloop:",
53            "    out x, 1           side 0 [T3 - 1]",
54            "    jmp !x do_zero     side 1 [T1 - 1]",
55            "    jmp bitloop        side 1 [T2 - 1]",
56            "do_zero:",
57            "    nop                side 0 [T2 - 1]",
58            ".wrap",
59        );
60
61        let installed = pio.install(&program.program).unwrap();
62
63        // 周波数の計算
64        let bit_freq = FREQ * CYCLES_PER_BIT;
65        let mut int = clock_freq / bit_freq;
66        let rem = clock_freq - (int * bit_freq);
67        let frac = (rem * 256) / bit_freq;
68        assert!(
69            (1..=65536).contains(&int) && (int != 65536 || frac == 0),
70            "(System Clock / {}) must be within [1.0, 65536.0].",
71            bit_freq.to_kHz()
72        );
73        if int == 65536 {
74            int = 0;
75        }
76        let int = int as u16;
77        let frac = frac as u8;
78
79        let pin = pin.into();
80        let (mut sm, _, tx) = PIOBuilder::from_installed_program(installed)
81            .buffers(Buffers::OnlyTx)
82            .side_set_pin_base(pin.id().num)
83            .out_shift_direction(ShiftDirection::Left)
84            .autopull(true)
85            .pull_threshold(24)
86            .clock_divisor_fixed_point(int, frac)
87            .build(sm);
88        sm.set_pindirs([(pin.id().num, PinDir::Output)]);
89        sm.start();
90
91        Self {
92            tx,
93            _pin: I::from(pin),
94        }
95    }
96}
97
98impl<P, SM, I> SmartLedsWrite for Ws2812Direct<P, SM, I>
99where
100    I: AnyPin<Function = P::PinFunction>,
101    P: PIOExt,
102    SM: StateMachineIndex,
103{
104    type Color = RGB8;
105    type Error = ();
106    fn write<T, C>(&mut self, iterator: T) -> Result<(), ()>
107    where
108        T: IntoIterator<Item = C>,
109        C: Into<Self::Color>,
110    {
111        for item in iterator {
112            let color: Self::Color = item.into();
113            let (r, g, b) = (color.r as u32, color.g as u32, color.b as u32);
114            let word: u32 = g << 24 | r << 16 | b << 8;
115
116            while !self.tx.write(word) {
117                cortex_m::asm::nop();
118            }
119        }
120        Ok(())
121    }
122}
123
124pub struct Ws2812<'timer, D, P, SM, I>
125where
126    D: TimerDevice,
127    I: AnyPin<Function = P::PinFunction>,
128    P: PIOExt,
129    SM: StateMachineIndex,
130{
131    cd: CountDown<'timer, D>,
132    driver: Ws2812Direct<P, SM, I>,
133}
134
135impl<'timer, D, P, SM, I> Ws2812<'timer, D, P, SM, I>
136where
137    D: TimerDevice,
138    I: AnyPin<Function = P::PinFunction>,
139    P: PIOExt,
140    SM: StateMachineIndex,
141{
142    /// Creates a new instance of this driver.
143    pub fn new(
144        pin: I,
145        pio: &mut PIO<P>,
146        sm: UninitStateMachine<(P, SM)>,
147        clock_freq: HertzU32,
148        cd: CountDown<'timer, D>,
149    ) -> Ws2812<'timer, D, P, SM, I> {
150        let driver = Ws2812Direct::new(pin, pio, sm, clock_freq);
151        Self { driver, cd }
152    }
153}
154
155impl<'timer, D, P, SM, I> SmartLedsWrite for Ws2812<'timer, D, P, SM, I>
156where
157    D: TimerDevice,
158    I: AnyPin<Function = P::PinFunction>,
159    P: PIOExt,
160    SM: StateMachineIndex,
161{
162    type Color = RGB8;
163    type Error = ();
164    fn write<T, J>(&mut self, iterator: T) -> Result<(), ()>
165    where
166        T: IntoIterator<Item = J>,
167        J: Into<Self::Color>,
168    {
169        self.driver.tx.clear_stalled_flag();
170        while !self.driver.tx.is_empty() && !self.driver.tx.has_stalled() {}
171
172        self.cd.start(70_u32.micros());
173        let _ = nb::block!(self.cd.wait());
174
175        SmartLedsWrite::write(&mut self.driver, iterator)
176    }
177}