1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#![no_std]
use core::marker::PhantomData;
use embedded_hal as hal;
use hal::serial::Write;
use nb::block;
use smart_leds_trait::{SmartLedsWrite, RGB8, RGBW};
pub mod device {
pub struct Ws2812;
pub struct Sk6812w;
pub trait Ws2812Like {
type Color: super::EncodeColor;
}
impl Ws2812Like for Ws2812 {
type Color = super::RGB8;
}
impl Ws2812Like for Sk6812w {
type Color = super::RGBW<u8>;
}
}
pub trait EncodeColor {
type Bytes: IntoIterator<Item = u8>;
fn encode(self) -> Self::Bytes;
}
impl EncodeColor for RGB8 {
type Bytes = [u8; 3];
fn encode(self) -> Self::Bytes {
[self.g, self.r, self.b]
}
}
impl EncodeColor for RGBW<u8> {
type Bytes = [u8; 4];
fn encode(self) -> Self::Bytes {
[self.g, self.r, self.b, self.a.0]
}
}
pub struct Ws2812<UART, DEV = device::Ws2812> {
uart: UART,
_device: PhantomData<DEV>,
}
impl<UART, DEV> Ws2812<UART, DEV>
where
UART: Write<u8>,
{
pub fn new(uart: UART) -> Self {
Self {
uart,
_device: PhantomData,
}
}
fn send_byte(&mut self, mut byte: u8) -> Result<(), <UART as Write<u8>>::Error> {
for _ in 0..4 {
let bits = 0b_0001_0000
| if (byte & 0b_10_00_0000) != 0 {
0b_0000_0011
} else {
0
}
| if (byte & 0b_01_00_0000) != 0 {
0b_0110_0000
} else {
0
};
block!(self.uart.write(!bits))?;
byte <<= 2;
}
Ok(())
}
}
impl<UART, DEV> SmartLedsWrite for Ws2812<UART, DEV>
where
UART: Write<u8>,
DEV: device::Ws2812Like,
{
type Error = <UART as Write<u8>>::Error;
type Color = DEV::Color;
fn write<T, I>(&mut self, iterator: T) -> Result<(), Self::Error>
where
T: Iterator<Item = I>,
I: Into<Self::Color>,
{
for item in iterator {
let color = item.into();
for byte in color.encode() {
self.send_byte(byte)?;
}
}
Ok(())
}
}