├── .cargo └── config.toml ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── notes.org ├── src ├── hosted.rs ├── lib.rs └── prerendered.rs └── stm32f0_ws2812_spi_rainbow.gif /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [target.thumbv6m-none-eabi] 2 | runner = 'arm-none-eabi-gdb' 3 | rustflags = [ 4 | "-C", "link-arg=-Tlink.x", 5 | ] 6 | 7 | [build] 8 | target = "thumbv6m-none-eabi" 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | - nightly 5 | cache: cargo 6 | matrix: 7 | allow_failures: 8 | - rust: nightly 9 | fast_finish: true 10 | script: 11 | - rustup target add thumbv6m-none-eabi 12 | - cargo build --examples --release 13 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## [Unreleased] 8 | 9 | ## [0.5.1] - 2025-06-01 10 | ### Added 11 | - Add a `reset_single_transaction` feature for the `prerendered` version, which uses a single SPI transaction for a `write` call. Can be useful if using a DMA-approach or you're experiencing glitches due to the SPI peripheral turning high between the data and the reset. 12 | 13 | ### Changed 14 | - Using the `mosi_idle_high` feature with the `prerendered` version now sends out the first reset together with the data, thus requiring a larger data buffer (but avoids potentially long dead-time between the first reset and the data being sent). 15 | 16 | ## [0.5.0] - 2024-07-29 17 | ### Added 18 | - Add a `hosted` variant intended for SBCs where the whole data transmission needs to be done in a single call 19 | 20 | ### Changed 21 | - Increased reset time from ~50μs to ~300μs, to deal with more/newer variants 22 | - Add error checking (especially for the length) in the `prerendered` variant 23 | - Update to `embedded_hal 1.0.0` 24 | 25 | ## [0.4.0] - 2020-12-02 26 | ### Added 27 | - SK812w support for the `prerendered` variant 28 | 29 | ### Changed 30 | - Modify `FullDuplex` FIFO handling to be more resilient 31 | - Switch `prerendered` to use the same bit patterns as the normal variant 32 | 33 | This removes the ability to use custom frequencies, but makes the whole code a 34 | *lot* simpler & more like the normal variant. 35 | 36 | ## [0.3.0] - 2020-02-09 37 | ### Added 38 | - SK6812w support 39 | 40 | ### Changed 41 | - Switched to a more efficient pattern generation, with 4 spi bits per ws2812 42 | bit instead of 3 43 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ws2812-spi" 3 | version = "0.5.1" 4 | authors = ["David Sawatzke "] 5 | edition = "2021" 6 | categories = [ 7 | "embedded", 8 | "no-std", 9 | "hardware-support"] 10 | keywords = ["smart-leds", "ws2812"] 11 | description = "SPI-based driver for ws2812 leds" 12 | documentation = "https://docs.rs/crate/ws2812-spi" 13 | license = "MIT OR Apache-2.0" 14 | readme = "README.md" 15 | repository = "https://github.com/smart-leds-rs/ws2812-spi-rs" 16 | 17 | [dependencies] 18 | smart-leds-trait = "0.3.0" 19 | embedded-hal = "1.0.0" 20 | 21 | [features] 22 | mosi_idle_high = [] 23 | # Send the reset command in one single transaction 24 | reset_single_transaction = [] 25 | std = [] 26 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 David Sawatzke 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Ws2812 driver for embedded-hal spi traits 2 | 3 | For usage with the [smart-leds](https://github.com/smart-leds-rs/smart-leds) 4 | crate. 5 | 6 | An embedded-hal driver for ws2812 leds using spi as the timing provider. 7 | 8 | ![rainbow on stm32f0](./stm32f0_ws2812_spi_rainbow.gif) 9 | 10 | It provides three variants: 11 | - The normal usage 12 | 13 | Your spi peripheral has to run betwee 2MHz and 3.8MHz & the SPI data is created on-the-fly. 14 | This means that your core has to be reasonably fast (48 MHz should suffice). 15 | - Prerendered 16 | 17 | If your core is too slow (for example, the AVR family), you 18 | may want to use this. It creates all the data beforehand & then sends it. This 19 | means that you have to provide a data array that's large enough for all the 20 | spi data. 21 | - Hosted 22 | 23 | Intended for device like the Raspberry Pi or other Linux SBCs. Similarly to 24 | prerendered it creates all the data beforehand, but sends it using a single 25 | call. 26 | 27 | ## It doesn't work!!! 28 | - Do you use the normal variant? Does your spi run at the right frequency? 29 | 30 | Your CPU might be too slow, but this can also depend on the HAL implementation 31 | & your Iterator chain. Using the `prerendered` variant might help. For many 32 | SPI peripherals, the clock generations is way less sophisticated than e.g. 33 | the UART peripheral. You should verify it runs at an acceptable frequency, by 34 | either studying the datasheet & the hal code or using a logic analyzer. An 35 | fx2 based one, commonly available under $10 works great for this. 36 | 37 | - If the first led is always on, no matter what data you put in, your spi is 38 | probably not setting the mosi line to low on idle (You can check with a multimeter). 39 | It may also be a timing issue with the first bit being sent, this is the case 40 | on the stm32f030 with 2MHz. 41 | 42 | You could try using the `mosi_idle_high` and `reset_single_transaction` features, they might help. 43 | 44 | If this does not help you can try different `embedded_hal::spi::Mode` parameters. For example on 45 | stm32f411 (as used for example on the Black Pill board) you have to set `phase` to 46 | `Phase::CaptureOnSecondTransition`. 47 | 48 | - Is your device fast enough? Is your iterator fast enough? Taking too long may 49 | completely screw up the timings for the normal version. Try the prerendered variant. 50 | 51 | - Is everything white? This may stem from an spi peripheral that's too slow or 52 | one that takes too much time in-between bytes. 53 | 54 | - Is your first LED the wrong brightness/color while the rest of your LED's do what you expect? 55 | This is due to low voltage of data line, or too much of a voltage difference between Vin and Din 56 | voltages, making some "high" bits read as "low" bits to the chip. Due to the chips circuitry, these 57 | voltages are regulated as they are passed on to the next LED in the line, which is why the other LED's 58 | perform as expected. (For more on exactly what is going on here, see [Hackaday | Cheating at 5V WS2812 Control to Use 3.3V Data](https://hackaday.com/2017/01/20/cheating-at-5v-ws2812-control-to-use-a-3-3v-data-line/)) 59 | 60 | - Are you using the `--release` compiler flag? 61 | 62 | The timing of each byte passed over SPI is very sensitive, and running code compiled 63 | without full optimizations can throw off your timing. Always use either `--release` 64 | flag with your `cargo `, or alternatively set `[profile.dev] opt-level = "3"` 65 | To ensure timing matches what your programmed. A dead giveaway of this is when all 66 | pixels go full brightness for every color. 67 | 68 | - Does it mostly work, but sometimes some of the LEDs get randomly colored? 69 | 70 | As the sending process needs to be without gaps, interrupts and other parallel tasks might lead to intermittent issues. Either disable interrupts during the sending process or ensure that the internal buffer of your HAL (if it exists) is large enough. 71 | 72 | When opening an issue about wrong/strange data, it would help if you include 73 | your code (of course) and a capture of MOSI & SCK from an oscilloscope/a logic 74 | analyzer. 75 | 76 | ## License 77 | 78 | Licensed under either of 79 | 80 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 81 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 82 | 83 | at your option. 84 | 85 | ## Contribution 86 | 87 | Unless you explicitly state otherwise, any contribution intentionally submitted 88 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 89 | dual licensed as above, without any additional terms or conditions. 90 | -------------------------------------------------------------------------------- /notes.org: -------------------------------------------------------------------------------- 1 | * Timings 2 | https://cpldcpu.wordpress.com/2014/01/14/light_ws2812-library-v2-0-part-i-understanding-the-ws2812/ 3 | https://wp.josh.com/2014/05/13/ws2812-neopixels-are-not-so-finicky-once-you-get-to-know-them/ 4 | 5 | | bit | high | 6 | |-----+-----------------| 7 | | 0 | <500ns ^ 100ns> | 8 | | 1 | >625ns ! <6000 | 9 | 10 | 11 | The total time should be at least 1000ns at most 5000ns 12 | 13 | The reset time should be >280 us 14 | (https://blog.particle.io/2017/05/11/heads-up-ws2812b-neopixels-are-about-to-change/) 15 | 16 | Try to do things in between low boundaries 17 | -------------------------------------------------------------------------------- /src/hosted.rs: -------------------------------------------------------------------------------- 1 | //! # Use WS2812 LEDs via SPI on Linux hosts 2 | //! 3 | //! This dynamically allocates an output buffer and writes out the data in a single call. 4 | //! Much better suited for linux or similar environments, but may not always work 5 | //! 6 | //! Intendded for use with rppal or linux-embedded-hal 7 | 8 | use embedded_hal as hal; 9 | 10 | use hal::spi::{Mode, Phase, Polarity, SpiBus}; 11 | 12 | use core::marker::PhantomData; 13 | 14 | use smart_leds_trait::{SmartLedsWrite, RGB8, RGBW}; 15 | 16 | use std::vec; 17 | use std::vec::Vec; 18 | 19 | /// SPI mode that can be used for this crate 20 | /// 21 | /// Provided for convenience 22 | /// Doesn't really matter 23 | pub const MODE: Mode = Mode { 24 | polarity: Polarity::IdleLow, 25 | phase: Phase::CaptureOnFirstTransition, 26 | }; 27 | 28 | pub mod devices { 29 | pub struct Ws2812; 30 | pub struct Sk6812w; 31 | } 32 | 33 | pub struct Ws2812 { 34 | spi: SPI, 35 | data: Vec, 36 | device: PhantomData, 37 | } 38 | 39 | impl Ws2812 40 | where 41 | SPI: SpiBus, 42 | { 43 | /// Use ws2812 devices via spi 44 | /// 45 | /// The SPI bus should run within 2 MHz to 3.8 MHz 46 | /// 47 | /// You may need to look at the datasheet and your own hal to verify this. 48 | /// 49 | pub fn new(spi: SPI) -> Self { 50 | let data = vec![0; 140]; 51 | 52 | Self { 53 | spi, 54 | data, 55 | device: PhantomData {}, 56 | } 57 | } 58 | } 59 | 60 | impl Ws2812 61 | where 62 | SPI: SpiBus, 63 | { 64 | /// Use sk6812w devices via spi 65 | /// 66 | /// The SPI bus should run within 2.3 MHz to 3.8 MHz at least. 67 | /// 68 | /// You may need to look at the datasheet and your own hal to verify this. 69 | /// 70 | // The spi frequencies are just the limits, the available timing data isn't 71 | // complete 72 | pub fn new_sk6812w(spi: SPI) -> Self { 73 | let data = vec![0; 140]; 74 | 75 | Self { 76 | spi, 77 | data, 78 | device: PhantomData {}, 79 | } 80 | } 81 | } 82 | 83 | impl Ws2812 84 | where 85 | SPI: SpiBus, 86 | { 87 | /// Write a single byte for ws2812 devices 88 | fn write_byte(&mut self, mut data: u8) { 89 | // Send two bits in one spi byte. High time first, then the low time 90 | // The maximum for T0H is 500ns, the minimum for one bit 1063 ns. 91 | // These result in the upper and lower spi frequency limits 92 | let patterns = [0b1000_1000, 0b1000_1110, 0b11101000, 0b11101110]; 93 | for _ in 0..4 { 94 | let bits = (data & 0b1100_0000) >> 6; 95 | self.data.push(patterns[bits as usize]); 96 | data <<= 2; 97 | } 98 | } 99 | 100 | fn send_data(&mut self) -> Result<(), E> { 101 | self.data.extend_from_slice(&[0; 140]); 102 | self.spi.write(&self.data)?; 103 | self.data.truncate(140); 104 | Ok(()) 105 | } 106 | } 107 | 108 | impl SmartLedsWrite for Ws2812 109 | where 110 | SPI: SpiBus, 111 | { 112 | type Error = E; 113 | type Color = RGB8; 114 | /// Write all the items of an iterator to a ws2812 strip 115 | fn write(&mut self, iterator: T) -> Result<(), E> 116 | where 117 | T: IntoIterator, 118 | I: Into, 119 | { 120 | for item in iterator { 121 | let item = item.into(); 122 | self.write_byte(item.g); 123 | self.write_byte(item.r); 124 | self.write_byte(item.b); 125 | } 126 | self.send_data() 127 | } 128 | } 129 | 130 | impl SmartLedsWrite for Ws2812 131 | where 132 | SPI: SpiBus, 133 | { 134 | type Error = E; 135 | type Color = RGBW; 136 | /// Write all the items of an iterator to a ws2812 strip 137 | fn write(&mut self, iterator: T) -> Result<(), E> 138 | where 139 | T: IntoIterator, 140 | I: Into, 141 | { 142 | for item in iterator { 143 | let item = item.into(); 144 | self.write_byte(item.g); 145 | self.write_byte(item.r); 146 | self.write_byte(item.b); 147 | self.write_byte(item.a.0); 148 | } 149 | self.send_data() 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! # Use ws2812 leds via spi 2 | //! 3 | //! - For usage with `smart-leds` 4 | //! - Implements the `SmartLedsWrite` trait 5 | //! 6 | //! Needs a type implementing the `spi::SpiBus` trait. 7 | //! 8 | //! The spi peripheral should run at 2MHz to 3.8 MHz 9 | 10 | // Timings for ws2812 from https://cpldcpu.files.wordpress.com/2014/01/ws2812_timing_table.png 11 | // Timings for sk6812 from https://cpldcpu.wordpress.com/2016/03/09/the-sk6812-another-intelligent-rgb-led/ 12 | 13 | #![cfg_attr(not(feature = "std"), no_std)] 14 | 15 | use embedded_hal as hal; 16 | 17 | #[cfg(feature = "std")] 18 | pub mod hosted; 19 | pub mod prerendered; 20 | 21 | use hal::spi::{Mode, Phase, Polarity, SpiBus}; 22 | 23 | use core::marker::PhantomData; 24 | use core::slice::from_ref; 25 | 26 | use smart_leds_trait::{SmartLedsWrite, RGB8, RGBW}; 27 | 28 | /// SPI mode that can be used for this crate 29 | /// 30 | /// Provided for convenience 31 | /// Doesn't really matter 32 | pub const MODE: Mode = Mode { 33 | polarity: Polarity::IdleLow, 34 | phase: Phase::CaptureOnFirstTransition, 35 | }; 36 | 37 | pub mod devices { 38 | pub struct Ws2812; 39 | pub struct Sk6812w; 40 | } 41 | 42 | pub struct Ws2812 { 43 | spi: SPI, 44 | device: PhantomData, 45 | } 46 | 47 | impl Ws2812 48 | where 49 | SPI: SpiBus, 50 | { 51 | /// Use ws2812 devices via spi 52 | /// 53 | /// The SPI bus should run within 2 MHz to 3.8 MHz 54 | /// 55 | /// You may need to look at the datasheet and your own hal to verify this. 56 | /// 57 | /// Please ensure that the mcu is pretty fast, otherwise weird timing 58 | /// issues will occur 59 | pub fn new(spi: SPI) -> Self { 60 | Self { 61 | spi, 62 | device: PhantomData {}, 63 | } 64 | } 65 | } 66 | 67 | impl Ws2812 68 | where 69 | SPI: SpiBus, 70 | { 71 | /// Use sk6812w devices via spi 72 | /// 73 | /// The SPI bus should run within 2.3 MHz to 3.8 MHz at least. 74 | /// 75 | /// You may need to look at the datasheet and your own hal to verify this. 76 | /// 77 | /// Please ensure that the mcu is pretty fast, otherwise weird timing 78 | /// issues will occur 79 | // The spi frequencies are just the limits, the available timing data isn't 80 | // complete 81 | pub fn new_sk6812w(spi: SPI) -> Self { 82 | Self { 83 | spi, 84 | device: PhantomData {}, 85 | } 86 | } 87 | } 88 | 89 | impl Ws2812 90 | where 91 | SPI: SpiBus, 92 | { 93 | /// Write a single byte for ws2812 devices 94 | fn write_byte(&mut self, mut data: u8) -> Result<(), E> { 95 | // Send two bits in one spi byte. High time first, then the low time 96 | // The maximum for T0H is 500ns, the minimum for one bit 1063 ns. 97 | // These result in the upper and lower spi frequency limits 98 | let patterns = [0b1000_1000, 0b1000_1110, 0b11101000, 0b11101110]; 99 | for _ in 0..4 { 100 | let bits = (data & 0b1100_0000) >> 6; 101 | self.spi.write(from_ref(&patterns[bits as usize]))?; 102 | data <<= 2; 103 | } 104 | Ok(()) 105 | } 106 | 107 | fn reset(&mut self) -> Result<(), E> { 108 | // Should be > 300μs, so for an SPI Freq. of 3.8MHz, we have to send at least 1140 low bits or 140 low bytes 109 | for _ in 0..140 { 110 | self.spi.write(from_ref(&0))?; 111 | } 112 | Ok(()) 113 | } 114 | } 115 | 116 | impl SmartLedsWrite for Ws2812 117 | where 118 | SPI: SpiBus, 119 | { 120 | type Error = E; 121 | type Color = RGB8; 122 | /// Write all the items of an iterator to a ws2812 strip 123 | fn write(&mut self, iterator: T) -> Result<(), E> 124 | where 125 | T: IntoIterator, 126 | I: Into, 127 | { 128 | if cfg!(feature = "mosi_idle_high") { 129 | self.reset()?; 130 | } 131 | 132 | for item in iterator { 133 | let item = item.into(); 134 | self.write_byte(item.g)?; 135 | self.write_byte(item.r)?; 136 | self.write_byte(item.b)?; 137 | } 138 | self.reset()?; 139 | Ok(()) 140 | } 141 | } 142 | 143 | impl SmartLedsWrite for Ws2812 144 | where 145 | SPI: SpiBus, 146 | { 147 | type Error = E; 148 | type Color = RGBW; 149 | /// Write all the items of an iterator to a ws2812 strip 150 | fn write(&mut self, iterator: T) -> Result<(), E> 151 | where 152 | T: IntoIterator, 153 | I: Into, 154 | { 155 | if cfg!(feature = "mosi_idle_high") { 156 | self.reset()?; 157 | } 158 | 159 | for item in iterator { 160 | let item = item.into(); 161 | self.write_byte(item.g)?; 162 | self.write_byte(item.r)?; 163 | self.write_byte(item.b)?; 164 | self.write_byte(item.a.0)?; 165 | } 166 | self.reset()?; 167 | Ok(()) 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /src/prerendered.rs: -------------------------------------------------------------------------------- 1 | //! This prerenders the data, so that no calculations have to be performed while sending the data. 2 | //! 3 | //! This approach minimizes timing issues, at the cost of much higher ram usage. 4 | //! It also increases the needed time. 5 | 6 | use embedded_hal as hal; 7 | 8 | use hal::spi::{Mode, Phase, Polarity, SpiBus}; 9 | 10 | use core::marker::PhantomData; 11 | 12 | use smart_leds_trait::{SmartLedsWrite, RGB8, RGBW}; 13 | 14 | const RESET_DATA_LEN: usize = 140; 15 | 16 | /// SPI mode that can be used for this crate 17 | /// 18 | /// Provided for convenience 19 | /// Doesn't really matter 20 | pub const MODE: Mode = Mode { 21 | polarity: Polarity::IdleLow, 22 | phase: Phase::CaptureOnFirstTransition, 23 | }; 24 | 25 | #[derive(Debug)] 26 | pub enum Error { 27 | OutOfBounds, 28 | Spi(E), 29 | } 30 | 31 | pub mod devices { 32 | pub struct Ws2812; 33 | pub struct Sk6812w; 34 | } 35 | 36 | pub struct Ws2812<'a, SPI, DEVICE = devices::Ws2812> { 37 | spi: SPI, 38 | data: &'a mut [u8], 39 | index: usize, 40 | device: PhantomData, 41 | } 42 | 43 | impl<'a, SPI, E> Ws2812<'a, SPI> 44 | where 45 | SPI: SpiBus, 46 | { 47 | /// Use WS2812 devices via SPI 48 | /// 49 | /// The SPI bus should run within 2 MHz to 3.8 MHz 50 | /// 51 | /// You may need to look at the datasheet and your own HAL to verify this. 52 | /// 53 | /// You need to provide a buffer `data`, whose length is at least 12 * the 54 | /// length of the led strip 55 | /// - + 140 bytes if using the `reset_single_transaction` feature 56 | /// - + 140 bytes if using the `mosi_idle_high` feature 57 | /// - + 280 bytes if using the `mosi_idle_high` and `reset_single_transaction` features 58 | /// 59 | /// Please ensure that the MCU is pretty fast, otherwise weird timing 60 | /// issues will occur 61 | pub fn new(spi: SPI, data: &'a mut [u8]) -> Self { 62 | Self { 63 | spi, 64 | data, 65 | index: 0, 66 | device: PhantomData {}, 67 | } 68 | } 69 | } 70 | 71 | impl<'a, SPI, E> Ws2812<'a, SPI, devices::Sk6812w> 72 | where 73 | SPI: SpiBus, 74 | { 75 | /// Use SK6812W devices via SPI 76 | /// 77 | /// The SPI bus should run within 2.3 MHz to 3.8 MHz at least. 78 | /// 79 | /// You may need to look at the datasheet and your own HAL to verify this. 80 | /// 81 | /// You need to provide a buffer `data`, whose length is at least 16 * the 82 | /// length of the led strip 83 | /// - + 140 bytes if using the `reset_single_transaction` feature 84 | /// - + 140 bytes if using the `mosi_idle_high` feature 85 | /// - + 280 bytes if using the `mosi_idle_high` and `reset_single_transaction` features 86 | /// 87 | /// Please ensure that the MCU is pretty fast, otherwise weird timing 88 | /// issues will occur 89 | // The SPI frequencies are just the limits, the available timing data isn't 90 | // complete 91 | pub fn new_sk6812w(spi: SPI, data: &'a mut [u8]) -> Self { 92 | Self { 93 | spi, 94 | data, 95 | index: 0, 96 | device: PhantomData {}, 97 | } 98 | } 99 | } 100 | 101 | impl<'a, SPI, D, E> Ws2812<'a, SPI, D> 102 | where 103 | SPI: SpiBus, 104 | { 105 | /// Write a single byte for WS2812-like devices 106 | fn write_byte(&mut self, mut data: u8) -> Result<(), Error> { 107 | // Send two bits in one spi byte. High time first, then the low time 108 | // The maximum for T0H is 500ns, the minimum for one bit 1063 ns. 109 | // These result in the upper and lower spi frequency limits 110 | let patterns = [0b1000_1000, 0b1000_1110, 0b11101000, 0b11101110]; 111 | 112 | if self.index > self.data.len() - 4 { 113 | return Err(Error::OutOfBounds); 114 | } 115 | for _ in 0..4 { 116 | let bits = (data & 0b1100_0000) >> 6; 117 | self.data[self.index] = patterns[bits as usize]; 118 | self.index += 1; 119 | data <<= 2; 120 | } 121 | Ok(()) 122 | } 123 | 124 | /// Add a reset sequence (140 zeroes) to the data buffer 125 | // Is always used for `mosi_idle_high`, as otherwise the time required to fill the buffer can lead to idle cycles on the SPI bus 126 | fn write_reset(&mut self) -> Result<(), Error> { 127 | if self.index + RESET_DATA_LEN > self.data.len() { 128 | return Err(Error::OutOfBounds); 129 | } 130 | for _ in 0..RESET_DATA_LEN { 131 | self.data[self.index] = 0; 132 | self.index += 1; 133 | } 134 | Ok(()) 135 | } 136 | 137 | /// Send a reset sequence (140 zeroes) on the bus 138 | fn send_reset(&mut self) -> Result<(), Error> { 139 | for _ in 0..RESET_DATA_LEN { 140 | self.spi.write(&[0]).map_err(Error::Spi)?; 141 | } 142 | 143 | Ok(()) 144 | } 145 | 146 | fn send_data(&mut self) -> Result<(), E> { 147 | self.spi.write(&self.data[..self.index]) 148 | } 149 | } 150 | 151 | impl<'a, SPI, E> SmartLedsWrite for Ws2812<'a, SPI> 152 | where 153 | SPI: SpiBus, 154 | { 155 | type Error = Error; 156 | type Color = RGB8; 157 | /// Write all the items of an iterator to a WS2812 strip 158 | fn write(&mut self, iterator: T) -> Result<(), Error> 159 | where 160 | T: IntoIterator, 161 | I: Into, 162 | { 163 | self.index = 0; 164 | 165 | if cfg!(feature = "mosi_idle_high") { 166 | self.write_reset()?; 167 | } 168 | 169 | for item in iterator { 170 | let item = item.into(); 171 | self.write_byte(item.g)?; 172 | self.write_byte(item.r)?; 173 | self.write_byte(item.b)?; 174 | } 175 | 176 | if cfg!(feature = "reset_single_transaction") { 177 | self.write_reset()?; 178 | } 179 | 180 | self.send_data().map_err(Error::Spi)?; 181 | 182 | if !cfg!(feature = "reset_single_transaction") { 183 | self.send_reset()?; 184 | } 185 | Ok(()) 186 | } 187 | } 188 | 189 | impl<'a, SPI, E> SmartLedsWrite for Ws2812<'a, SPI, devices::Sk6812w> 190 | where 191 | SPI: SpiBus, 192 | { 193 | type Error = Error; 194 | type Color = RGBW; 195 | /// Write all the items of an iterator to a SK6812W strip 196 | fn write(&mut self, iterator: T) -> Result<(), Error> 197 | where 198 | T: IntoIterator, 199 | I: Into, 200 | { 201 | self.index = 0; 202 | 203 | if cfg!(feature = "mosi_idle_high") { 204 | self.write_reset()?; 205 | } 206 | 207 | for item in iterator { 208 | let item = item.into(); 209 | self.write_byte(item.g)?; 210 | self.write_byte(item.r)?; 211 | self.write_byte(item.b)?; 212 | self.write_byte(item.a.0)?; 213 | } 214 | 215 | if cfg!(feature = "reset_single_transaction") { 216 | self.write_reset()?; 217 | } 218 | 219 | self.send_data().map_err(Error::Spi)?; 220 | 221 | if !cfg!(feature = "reset_single_transaction") { 222 | self.send_reset()?; 223 | } 224 | Ok(()) 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /stm32f0_ws2812_spi_rainbow.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smart-leds-rs/ws2812-spi-rs/ef6a7f09d18af1268397756d32ee44fd1a31ae7b/stm32f0_ws2812_spi_rainbow.gif --------------------------------------------------------------------------------