├── .cargo └── config ├── .circleci └── config.yml ├── .github └── FUNDING.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── build.rs ├── build.sh ├── doc └── SH1106.pdf ├── examples ├── graphics.rs ├── graphics_128x32.rs ├── image.rs ├── image_spi.rs ├── pixelsquare.rs ├── rotation.rs ├── rust.png ├── rust.raw └── text.rs ├── memory.x ├── readme_banner.jpg ├── release.toml ├── rustfmt.nightly.toml └── src ├── builder.rs ├── command.rs ├── displayrotation.rs ├── displaysize.rs ├── interface ├── i2c.rs ├── mod.rs └── spi.rs ├── lib.rs ├── mode ├── displaymode.rs ├── graphics.rs ├── mod.rs └── raw.rs ├── prelude.rs ├── properties.rs └── test_helpers.rs /.cargo/config: -------------------------------------------------------------------------------- 1 | [target.'cfg(all(target_arch = "arm", target_os = "none"))'] 2 | runner = "probe-run --chip STM32F103C8" 3 | rustflags = [ 4 | "-C", "link-arg=-Tlink.x", 5 | ] 6 | 7 | [build] 8 | target = "thumbv7m-none-eabi" 9 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | target_steps: &target_steps 2 | docker: 3 | - image: cimg/rust:1.72.0 4 | steps: 5 | - checkout 6 | - restore_cache: 7 | key: v2-sh1106-{{ .Environment.CIRCLE_JOB }}-{{ checksum "Cargo.toml" }} 8 | - run: rustup default ${RUST_VERSION:-stable} 9 | - run: rustup component add rustfmt 10 | - run: | 11 | SYSROOT=$(rustc --print sysroot) 12 | 13 | if [[ ! "$SYSROOT" =~ "$TARGET" ]]; then 14 | rustup target add $TARGET 15 | else 16 | echo "Target $TARGET is already installed" 17 | fi 18 | - run: ./build.sh 19 | - save_cache: 20 | key: v2-sh1106-{{ .Environment.CIRCLE_JOB }}-{{ checksum "Cargo.toml" }} 21 | paths: 22 | - ./target 23 | - /home/ubuntu/.cargo 24 | 25 | version: 2 26 | jobs: 27 | target-arm-unknown-linux-eabi: 28 | environment: 29 | - TARGET: "arm-unknown-linux-gnueabi" 30 | - DISABLE_EXAMPLES: 1 31 | <<: *target_steps 32 | 33 | target-armv7-unknown-linux-gnueabihf: 34 | environment: 35 | - TARGET: "armv7-unknown-linux-gnueabihf" 36 | - DISABLE_EXAMPLES: 1 37 | <<: *target_steps 38 | 39 | target-x86_64-unknown-linux-gnu: 40 | environment: 41 | - TARGET: "x86_64-unknown-linux-gnu" 42 | - DISABLE_EXAMPLES: 1 43 | <<: *target_steps 44 | 45 | target-x86_64-unknown-linux-musl: 46 | environment: 47 | - TARGET: "x86_64-unknown-linux-musl" 48 | - DISABLE_EXAMPLES: 1 49 | <<: *target_steps 50 | 51 | target-thumbv6m-none-eabi: 52 | environment: 53 | - TARGET: "thumbv6m-none-eabi" 54 | # Disable example builds as they target thumbv7 and up 55 | - DISABLE_EXAMPLES: 1 56 | <<: *target_steps 57 | 58 | target-thumbv7em-none-eabi: 59 | environment: 60 | - TARGET: "thumbv7em-none-eabi" 61 | <<: *target_steps 62 | 63 | target-thumbv7em-none-eabihf: 64 | environment: 65 | - TARGET: "thumbv7em-none-eabihf" 66 | <<: *target_steps 67 | 68 | target-thumbv7m-none-eabi: 69 | environment: 70 | - TARGET: "thumbv7m-none-eabi" 71 | <<: *target_steps 72 | 73 | build_jobs: &build_jobs 74 | jobs: 75 | # Raspberry Pi 1 76 | - target-arm-unknown-linux-eabi 77 | 78 | # Raspberry Pi 2, 3, etc 79 | - target-armv7-unknown-linux-gnueabihf 80 | 81 | # Linux 82 | - target-x86_64-unknown-linux-gnu 83 | - target-x86_64-unknown-linux-musl 84 | 85 | # Bare metal 86 | - target-thumbv6m-none-eabi 87 | - target-thumbv7em-none-eabi 88 | - target-thumbv7em-none-eabihf 89 | - target-thumbv7m-none-eabi 90 | 91 | workflows: 92 | version: 2 93 | build_all: 94 | <<: *build_jobs 95 | # # Build every day 96 | # nightly: 97 | # <<: *build_jobs 98 | # triggers: 99 | # - schedule: 100 | # cron: '0 0 * * *' 101 | # filters: 102 | # branches: 103 | # only: 104 | # - master 105 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: jamwaffles 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: jamwaffles 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /target/ 3 | **/*.rs.bk 4 | Cargo.lock 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | [`sh1106`](https://crates.io/crates/sh1106) is a Rust driver for the SH1106 OLED display. It 4 | supports [embedded-graphics](https://crates.io/crates/embedded-graphics) or raw pixel drawing modes 5 | and works with the [embedded-hal](crates.io/crates/embedded-hal) traits for maximum portability. 6 | 7 | 8 | 9 | ## [Unreleased] - ReleaseDate 10 | 11 | ## [0.5.0] - 2023-08-30 12 | 13 | ### Changed 14 | 15 | - **(breaking)** [#34](https://github.com/jamwaffles/sh1106/pull/34) Upgrade to `embedded-graphics` 16 | 0.8 and `embedded-graphics-core` to 0.4. 17 | 18 | ## [0.4.0] - 2021-07-11 19 | 20 | ### Changed 21 | 22 | - **(breaking)** [#25](https://github.com/jamwaffles/sh1106/pull/25) Upgrade to `embedded-graphics` 23 | 0.7. 24 | 25 | ## [0.3.4] - 2020-12-28 26 | 27 | ### Fixed 28 | 29 | - [#23](https://github.com/jamwaffles/sh1106/pull/23) Fixed command bytes for `PreChargePeriod` and 30 | `VcomhDeselect`. 31 | 32 | ## [0.3.3] - 2020-06-09 33 | 34 | ### Added 35 | 36 | - [#22](https://github.com/jamwaffles/sh1106/pull/22) Add `DisplaySize::Display128x64NoOffset` 37 | variant for 128x64 displays that don't use a 132x64 buffer internally. 38 | 39 | ## [0.3.2] - 2020-04-30 40 | 41 | ### Added 42 | 43 | - [#20](https://github.com/jamwaffles/sh1106/pull/20) Add `set_contrast` method to set the display 44 | contrast/brightness. 45 | 46 | ## [0.3.1] - 2020-03-21 47 | 48 | ### Fixed 49 | 50 | - Fix docs.rs build config 51 | 52 | ## [0.3.0] - 2020-03-20 53 | 54 | ### Added 55 | 56 | - Migrate from Travis to CircleCI 57 | 58 | ### Changed 59 | 60 | - **(breaking)** [#18](https://github.com/jamwaffles/sh1106/pull/18) Upgrade to embedded-graphics 61 | 0.6.0 62 | 63 | ## [0.3.0-alpha.4] 64 | 65 | ### Fixed 66 | 67 | - Pin `embedded-graphics` dependency versio to `0.6.0-alpha.2` 68 | 69 | ## 0.3.0-alpha.3 70 | 71 | ### Added 72 | 73 | - Added the `NoOutputPin` dummy pin type for SPI cases when no Chip Select pin is required. Use it 74 | like this: 75 | 76 | ```rust 77 | let spi = Spi::spi1( 78 | // ... 79 | ); 80 | 81 | let mut disp: GraphicsMode<_> = sh1106::Builder::new() 82 | .connect_spi(spi, dc, sh1106::NoOutputPin::new()) 83 | .into(); 84 | ``` 85 | 86 | ## 0.3.0-alpha.2 87 | 88 | Upgrade to new embedded-graphics `0.6.0-alpha.2` release. Please see the 89 | [embedded-graphics changelog](https://github.com/jamwaffles/embedded-graphics/blob/c0ed1700635f307a4c5114fec1769147878fd584/CHANGELOG.md) 90 | for more information. 91 | 92 | ### Changed 93 | 94 | - **(breaking)** #11 Upgraded to [embedded-graphics](https://crates.io/crates/embedded-graphics) 95 | 0.6.0-alpha.2 96 | 97 | ## 0.3.0-alpha.1 98 | 99 | Upgrade to new embedded-graphics `0.6.0-alpha.1` release. Please see the 100 | [embedded-graphics changelog](https://github.com/jamwaffles/embedded-graphics/blob/embedded-graphics-v0.6.0-alpha.1/CHANGELOG.md) 101 | for more information. 102 | 103 | ### Changed 104 | 105 | - **(breaking)** #9 Upgraded to [embedded-graphics](https://crates.io/crates/embedded-graphics) 106 | 0.6.0-alpha.1 107 | 108 | 109 | [unreleased]: https://github.com/jamwaffles/sh1106/compare/v0.5.0...HEAD 110 | 111 | [0.5.0]: https://github.com/jamwaffles/sh1106/compare/v0.4.0...v0.5.0 112 | [0.4.0]: https://github.com/jamwaffles/sh1106/compare/v0.3.4...v0.4.0 113 | [0.3.4]: https://github.com/jamwaffles/sh1106/compare/v0.3.3...v0.3.4 114 | [0.3.3]: https://github.com/jamwaffles/sh1106/compare/v0.3.2...v0.3.3 115 | [0.3.2]: https://github.com/jamwaffles/sh1106/compare/v0.3.1...v0.3.2 116 | [0.3.1]: https://github.com/jamwaffles/sh1106/compare/v0.3.0...v0.3.1 117 | [0.3.0]: https://github.com/jamwaffles/sh1106/compare/v0.3.0-alpha.4...v0.3.0 118 | [0.3.0-alpha.4]: https://github.com/jamwaffles/sh1106/compare/v0.3.0-alpha.3...v0.3.0-alpha.4 119 | [0.3.0-alpha.3]: https://github.com/jamwaffles/sh1106/compare/v0.3.0-alpha.2...v0.3.0-alpha.3 120 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["James Waples "] 3 | categories = ["embedded", "no-std"] 4 | description = "I2C/SPI driver for the SH1106 OLED display controller" 5 | documentation = "https://docs.rs/sh1106" 6 | exclude = [".travis.yml", ".gitignore"] 7 | keywords = ["no-std", "sh1106", "oled", "embedded", "embedded-hal-driver"] 8 | license = "MIT OR Apache-2.0" 9 | name = "sh1106" 10 | readme = "README.md" 11 | repository = "https://github.com/jamwaffles/sh1106" 12 | version = "0.5.0" 13 | edition = "2018" 14 | 15 | [package.metadata.docs.rs] 16 | targets = [ "thumbv7m-none-eabi", "thumbv7em-none-eabihf" ] 17 | 18 | [badges] 19 | circle-ci = { repository = "jamwaffles/sh1106", branch = "master" } 20 | 21 | [dependencies] 22 | embedded-hal = "0.2.3" 23 | embedded-graphics-core = { version = "0.4.0", optional = true } 24 | 25 | [dev-dependencies] 26 | cortex-m = "0.7.3" 27 | cortex-m-rt = "0.6.10" 28 | embedded-graphics = "0.8.0" 29 | heapless = "0.7.10" 30 | panic-semihosting = "0.5.2" 31 | cortex-m-rtic = "0.5.9" 32 | 33 | [dev-dependencies.stm32f1xx-hal] 34 | version = "0.7.0" 35 | features = [ "rt", "stm32f103" ] 36 | 37 | [features] 38 | default = ["graphics"] 39 | graphics = ["embedded-graphics-core"] 40 | 41 | [profile.dev] 42 | codegen-units = 1 43 | incremental = false 44 | 45 | [profile.release] 46 | codegen-units = 1 47 | debug = true 48 | lto = true 49 | -------------------------------------------------------------------------------- /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) 2018 James Waples 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 | # SH1106 driver 2 | 3 | [![Build Status](https://circleci.com/gh/jamwaffles/sh1106/tree/master.svg?style=shield)](https://circleci.com/gh/jamwaffles/sh1106/tree/master) 4 | [![Crates.io](https://img.shields.io/crates/v/sh1106.svg)](https://crates.io/crates/sh1106) 5 | [![Docs.rs](https://docs.rs/sh1106/badge.svg)](https://docs.rs/sh1106) 6 | 7 | [![SH1106 display module showing the Rust logo](readme_banner.jpg?raw=true)](examples/image.rs) 8 | 9 | I2C driver for the SH1106 OLED display written in 100% Rust 10 | 11 | ## [Documentation](https://docs.rs/sh1106) 12 | 13 | ## [Examples] 14 | 15 | This crate uses [`probe-run`](https://crates.io/crates/probe-run) to run the examples. Once set up, 16 | it should be as simple as `cargo run --example --release`. `--release` will be 17 | required for some examples to reduce FLASH usage. 18 | 19 | From [`examples/text.rs`](examples/text.rs): 20 | 21 | ```rust 22 | #![no_std] 23 | #![no_main] 24 | 25 | use cortex_m_rt::{entry, exception, ExceptionFrame}; 26 | use embedded_graphics::{ 27 | fonts::{Font6x8, Text}, 28 | pixelcolor::BinaryColor, 29 | prelude::*, 30 | style::TextStyle, 31 | }; 32 | use panic_semihosting as _; 33 | use sh1106::{prelude::*, Builder}; 34 | use stm32f1xx_hal::{ 35 | i2c::{BlockingI2c, DutyCycle, Mode}, 36 | prelude::*, 37 | stm32, 38 | }; 39 | 40 | #[entry] 41 | fn main() -> ! { 42 | let dp = stm32::Peripherals::take().unwrap(); 43 | 44 | let mut flash = dp.FLASH.constrain(); 45 | let mut rcc = dp.RCC.constrain(); 46 | 47 | let clocks = rcc.cfgr.freeze(&mut flash.acr); 48 | 49 | let mut afio = dp.AFIO.constrain(&mut rcc.apb2); 50 | 51 | let mut gpiob = dp.GPIOB.split(&mut rcc.apb2); 52 | 53 | let scl = gpiob.pb8.into_alternate_open_drain(&mut gpiob.crh); 54 | let sda = gpiob.pb9.into_alternate_open_drain(&mut gpiob.crh); 55 | 56 | let i2c = BlockingI2c::i2c1( 57 | dp.I2C1, 58 | (scl, sda), 59 | &mut afio.mapr, 60 | Mode::Fast { 61 | frequency: 100.khz().into(), 62 | duty_cycle: DutyCycle::Ratio2to1, 63 | }, 64 | clocks, 65 | &mut rcc.apb1, 66 | 1000, 67 | 10, 68 | 1000, 69 | 1000, 70 | ); 71 | 72 | let mut disp: GraphicsMode<_> = Builder::new().connect_i2c(i2c).into(); 73 | 74 | disp.init().unwrap(); 75 | disp.flush().unwrap(); 76 | 77 | Text::new("Hello world!", Point::zero()) 78 | .into_styled(TextStyle::new(Font6x8, BinaryColor::On)) 79 | .draw(&mut display) 80 | .unwrap(); 81 | 82 | Text::new("Hello Rust!", Point::new(0, 16)) 83 | .into_styled(TextStyle::new(Font6x8, BinaryColor::On)) 84 | .draw(&mut display) 85 | .unwrap(); 86 | 87 | disp.flush().unwrap(); 88 | 89 | loop {} 90 | } 91 | 92 | #[exception] 93 | fn HardFault(ef: &ExceptionFrame) -> ! { 94 | panic!("{:#?}", ef); 95 | } 96 | ``` 97 | 98 | ## License 99 | 100 | Licensed under either of 101 | 102 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or 103 | http://www.apache.org/licenses/LICENSE-2.0) 104 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 105 | 106 | at your option. 107 | 108 | ### Contribution 109 | 110 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the 111 | work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any 112 | additional terms or conditions. 113 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | use std::{env, fs::File, io::Write, path::PathBuf}; 2 | 3 | pub fn main() { 4 | // Put the linker script somewhere the linker can find it 5 | let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); 6 | File::create(out.join("memory.x")) 7 | .unwrap() 8 | .write_all(include_bytes!("memory.x")) 9 | .unwrap(); 10 | println!("cargo:rustc-link-search={}", out.display()); 11 | 12 | println!("cargo:rerun-if-changed=build.rs"); 13 | println!("cargo:rerun-if-changed=memory.x"); 14 | } 15 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -e 4 | 5 | cargo build --target $TARGET --all-features --release 6 | 7 | if [ -z $DISABLE_EXAMPLES ]; then 8 | cargo build --target $TARGET --all-features --examples 9 | fi 10 | 11 | cargo test --lib --target x86_64-unknown-linux-gnu 12 | cargo test --doc --target x86_64-unknown-linux-gnu 13 | -------------------------------------------------------------------------------- /doc/SH1106.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-embedded-community/sh1106/798759149e6ec6efac1c21802215d7c441cfbbea/doc/SH1106.pdf -------------------------------------------------------------------------------- /examples/graphics.rs: -------------------------------------------------------------------------------- 1 | //! Draw a square, circle and triangle on the screen using the `embedded_graphics` crate. 2 | //! 3 | //! This example is for the STM32F103 "Blue Pill" board using I2C1. 4 | //! 5 | //! Wiring connections are as follows for a CRIUS-branded display: 6 | //! 7 | //! ``` 8 | //! Display -> Blue Pill 9 | //! (black) GND -> GND 10 | //! (red) +5V -> VCC 11 | //! (yellow) SDA -> PB9 12 | //! (green) SCL -> PB8 13 | //! ``` 14 | //! 15 | //! Run on a Blue Pill with `cargo run --example graphics`. 16 | 17 | #![no_std] 18 | #![no_main] 19 | 20 | use cortex_m_rt::{entry, exception, ExceptionFrame}; 21 | use embedded_graphics::{ 22 | pixelcolor::BinaryColor, 23 | prelude::*, 24 | primitives::{Circle, Line, PrimitiveStyle, Rectangle}, 25 | }; 26 | use panic_semihosting as _; 27 | use sh1106::{prelude::*, Builder}; 28 | use stm32f1xx_hal::{ 29 | i2c::{BlockingI2c, DutyCycle, Mode}, 30 | prelude::*, 31 | stm32, 32 | }; 33 | 34 | #[entry] 35 | fn main() -> ! { 36 | let dp = stm32::Peripherals::take().unwrap(); 37 | 38 | let mut flash = dp.FLASH.constrain(); 39 | let mut rcc = dp.RCC.constrain(); 40 | 41 | let clocks = rcc.cfgr.freeze(&mut flash.acr); 42 | 43 | let mut afio = dp.AFIO.constrain(&mut rcc.apb2); 44 | 45 | let mut gpiob = dp.GPIOB.split(&mut rcc.apb2); 46 | 47 | let scl = gpiob.pb8.into_alternate_open_drain(&mut gpiob.crh); 48 | let sda = gpiob.pb9.into_alternate_open_drain(&mut gpiob.crh); 49 | 50 | let i2c = BlockingI2c::i2c1( 51 | dp.I2C1, 52 | (scl, sda), 53 | &mut afio.mapr, 54 | Mode::Fast { 55 | frequency: 100.khz().into(), 56 | duty_cycle: DutyCycle::Ratio2to1, 57 | }, 58 | clocks, 59 | &mut rcc.apb1, 60 | 1000, 61 | 10, 62 | 1000, 63 | 1000, 64 | ); 65 | 66 | let mut display: GraphicsMode<_> = Builder::new().connect_i2c(i2c).into(); 67 | 68 | display.init().unwrap(); 69 | display.flush().unwrap(); 70 | 71 | Line::new(Point::new(8, 16 + 16), Point::new(8 + 16, 16 + 16)) 72 | .into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1)) 73 | .draw(&mut display) 74 | .unwrap(); 75 | 76 | Line::new(Point::new(8, 16 + 16), Point::new(8 + 8, 16)) 77 | .into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1)) 78 | .draw(&mut display) 79 | .unwrap(); 80 | 81 | Line::new(Point::new(8 + 16, 16 + 16), Point::new(8 + 8, 16)) 82 | .into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1)) 83 | .draw(&mut display) 84 | .unwrap(); 85 | 86 | Rectangle::with_corners(Point::new(48, 16), Point::new(48 + 16, 16 + 16)) 87 | .into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1)) 88 | .draw(&mut display) 89 | .unwrap(); 90 | 91 | Circle::new(Point::new(88, 16), 16) 92 | .into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1)) 93 | .draw(&mut display) 94 | .unwrap(); 95 | 96 | display.flush().unwrap(); 97 | 98 | loop {} 99 | } 100 | 101 | #[exception] 102 | fn HardFault(ef: &ExceptionFrame) -> ! { 103 | panic!("{:#?}", ef); 104 | } 105 | -------------------------------------------------------------------------------- /examples/graphics_128x32.rs: -------------------------------------------------------------------------------- 1 | //! Draw a square, circle and triangle on a 128x32px display. 2 | //! 3 | //! This example is for the STM32F103 "Blue Pill" board using I2C1. 4 | //! 5 | //! Run on a Blue Pill with `cargo run --example graphics_128x32`. 6 | 7 | #![no_std] 8 | #![no_main] 9 | 10 | use cortex_m_rt::{entry, exception, ExceptionFrame}; 11 | use embedded_graphics::{ 12 | pixelcolor::BinaryColor, 13 | prelude::*, 14 | primitives::{Circle, Line, PrimitiveStyle, Rectangle}, 15 | }; 16 | use panic_semihosting as _; 17 | use sh1106::{prelude::*, Builder}; 18 | use stm32f1xx_hal::{ 19 | i2c::{BlockingI2c, DutyCycle, Mode}, 20 | prelude::*, 21 | stm32, 22 | }; 23 | 24 | #[entry] 25 | fn main() -> ! { 26 | let dp = stm32::Peripherals::take().unwrap(); 27 | 28 | let mut flash = dp.FLASH.constrain(); 29 | let mut rcc = dp.RCC.constrain(); 30 | 31 | let clocks = rcc.cfgr.freeze(&mut flash.acr); 32 | 33 | let mut afio = dp.AFIO.constrain(&mut rcc.apb2); 34 | 35 | let mut gpiob = dp.GPIOB.split(&mut rcc.apb2); 36 | 37 | let scl = gpiob.pb8.into_alternate_open_drain(&mut gpiob.crh); 38 | let sda = gpiob.pb9.into_alternate_open_drain(&mut gpiob.crh); 39 | 40 | let i2c = BlockingI2c::i2c1( 41 | dp.I2C1, 42 | (scl, sda), 43 | &mut afio.mapr, 44 | Mode::Fast { 45 | frequency: 100.khz().into(), 46 | duty_cycle: DutyCycle::Ratio2to1, 47 | }, 48 | clocks, 49 | &mut rcc.apb1, 50 | 1000, 51 | 10, 52 | 1000, 53 | 1000, 54 | ); 55 | 56 | let mut display: GraphicsMode<_> = Builder::new() 57 | .with_size(DisplaySize::Display128x32) 58 | .connect_i2c(i2c) 59 | .into(); 60 | display.init().unwrap(); 61 | display.flush().unwrap(); 62 | 63 | let yoffset = 8; 64 | 65 | Line::new( 66 | Point::new(8, 16 + yoffset), 67 | Point::new(8 + 16, 16 + yoffset), 68 | ) 69 | .into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1)) 70 | .draw(&mut display) 71 | .unwrap(); 72 | 73 | Line::new(Point::new(8, 16 + yoffset), Point::new(8 + 8, yoffset)) 74 | .into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1)) 75 | .draw(&mut display) 76 | .unwrap(); 77 | 78 | Line::new(Point::new(8 + 16, 16 + yoffset), Point::new(8 + 8, yoffset)) 79 | .into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1)) 80 | .draw(&mut display) 81 | .unwrap(); 82 | 83 | Rectangle::with_corners(Point::new(48, yoffset), Point::new(48 + 16, 16 + yoffset)) 84 | .into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1)) 85 | .draw(&mut display) 86 | .unwrap(); 87 | 88 | Circle::new(Point::new(88, yoffset), 16) 89 | .into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1)) 90 | .draw(&mut display) 91 | .unwrap(); 92 | 93 | display.flush().unwrap(); 94 | 95 | loop {} 96 | } 97 | 98 | #[exception] 99 | fn HardFault(ef: &ExceptionFrame) -> ! { 100 | panic!("{:#?}", ef); 101 | } 102 | -------------------------------------------------------------------------------- /examples/image.rs: -------------------------------------------------------------------------------- 1 | //! Draw a 1 bit per pixel black and white image. On a 128x64 sh1106 display over I2C. 2 | //! 3 | //! Image was created with ImageMagick: 4 | //! 5 | //! ```bash 6 | //! convert rust.png -depth 1 gray:rust.raw 7 | //! ``` 8 | //! 9 | //! This example is for the STM32F103 "Blue Pill" board using I2C1. 10 | //! 11 | //! Wiring connections are as follows for a CRIUS-branded display: 12 | //! 13 | //! ``` 14 | //! Display -> Blue Pill 15 | //! (black) GND -> GND 16 | //! (red) +5V -> VCC 17 | //! (yellow) SDA -> PB9 18 | //! (green) SCL -> PB8 19 | //! ``` 20 | //! 21 | //! Run on a Blue Pill with `cargo run --example image`. 22 | 23 | #![no_std] 24 | #![no_main] 25 | 26 | use cortex_m_rt::{entry, exception, ExceptionFrame}; 27 | use embedded_graphics::{ 28 | image::{Image, ImageRawLE}, 29 | pixelcolor::BinaryColor, 30 | prelude::*, 31 | }; 32 | use panic_semihosting as _; 33 | use sh1106::{prelude::*, Builder}; 34 | use stm32f1xx_hal::{ 35 | i2c::{BlockingI2c, DutyCycle, Mode}, 36 | prelude::*, 37 | stm32, 38 | }; 39 | 40 | #[entry] 41 | fn main() -> ! { 42 | let dp = stm32::Peripherals::take().unwrap(); 43 | 44 | let mut flash = dp.FLASH.constrain(); 45 | let mut rcc = dp.RCC.constrain(); 46 | 47 | let clocks = rcc.cfgr.freeze(&mut flash.acr); 48 | 49 | let mut afio = dp.AFIO.constrain(&mut rcc.apb2); 50 | 51 | let mut gpiob = dp.GPIOB.split(&mut rcc.apb2); 52 | 53 | let scl = gpiob.pb8.into_alternate_open_drain(&mut gpiob.crh); 54 | let sda = gpiob.pb9.into_alternate_open_drain(&mut gpiob.crh); 55 | 56 | let i2c = BlockingI2c::i2c1( 57 | dp.I2C1, 58 | (scl, sda), 59 | &mut afio.mapr, 60 | Mode::Fast { 61 | frequency: 100.khz().into(), 62 | duty_cycle: DutyCycle::Ratio2to1, 63 | }, 64 | clocks, 65 | &mut rcc.apb1, 66 | 1000, 67 | 10, 68 | 1000, 69 | 1000, 70 | ); 71 | 72 | let mut display: GraphicsMode<_> = Builder::new().connect_i2c(i2c).into(); 73 | 74 | display.init().unwrap(); 75 | display.flush().unwrap(); 76 | 77 | let im: ImageRawLE = ImageRawLE::new(include_bytes!("./rust.raw"), 64); 78 | 79 | Image::new(&im, Point::new(32, 0)) 80 | .draw(&mut display) 81 | .unwrap(); 82 | 83 | display.flush().unwrap(); 84 | 85 | loop {} 86 | } 87 | 88 | #[exception] 89 | fn HardFault(ef: &ExceptionFrame) -> ! { 90 | panic!("{:#?}", ef); 91 | } 92 | -------------------------------------------------------------------------------- /examples/image_spi.rs: -------------------------------------------------------------------------------- 1 | //! Draw a 1 bit per pixel black and white image. On a 128x64 sh1106 display over SPI. 2 | //! 3 | //! Image was created with ImageMagick: 4 | //! 5 | //! ```bash 6 | //! convert rust.png -depth 1 gray:rust.raw 7 | //! ``` 8 | //! 9 | //! This example is for the STM32F103 "Blue Pill" board using SPI. 10 | //! 11 | //! Wiring connections are as follows: 12 | //! 13 | //! ``` 14 | //! Display -> Blue Pill 15 | //! GND -> GND 16 | //! VCC -> 3.3V or 5V (check your module's input voltage) 17 | //! SCK -> PA5 18 | //! MOSI -> PA7 19 | //! DC -> PA2 20 | //! CS -> PA1 (optional, connect to ground on module if unused) 21 | //! ``` 22 | //! 23 | //! Run on a Blue Pill with `cargo run --example image`. 24 | 25 | #![no_std] 26 | #![no_main] 27 | 28 | use cortex_m_rt::{entry, exception, ExceptionFrame}; 29 | use embedded_graphics::{ 30 | image::{Image, ImageRawLE}, 31 | pixelcolor::BinaryColor, 32 | prelude::*, 33 | }; 34 | use embedded_hal::spi; 35 | use panic_semihosting as _; 36 | use sh1106::{prelude::*, Builder}; 37 | use stm32f1xx_hal::{prelude::*, spi::Spi, stm32}; 38 | 39 | #[entry] 40 | fn main() -> ! { 41 | let dp = stm32::Peripherals::take().unwrap(); 42 | 43 | let mut flash = dp.FLASH.constrain(); 44 | let mut rcc = dp.RCC.constrain(); 45 | 46 | let clocks = rcc.cfgr.freeze(&mut flash.acr); 47 | 48 | let mut afio = dp.AFIO.constrain(&mut rcc.apb2); 49 | 50 | let mut gpioa = dp.GPIOA.split(&mut rcc.apb2); 51 | 52 | let sck = gpioa.pa5.into_alternate_push_pull(&mut gpioa.crl); 53 | let miso = gpioa.pa6.into_floating_input(&mut gpioa.crl); 54 | let mosi = gpioa.pa7.into_alternate_push_pull(&mut gpioa.crl); 55 | let dc = gpioa.pa2.into_push_pull_output(&mut gpioa.crl); 56 | let cs = gpioa.pa1.into_push_pull_output(&mut gpioa.crl); 57 | 58 | let spi = Spi::spi1( 59 | dp.SPI1, 60 | (sck, miso, mosi), 61 | &mut afio.mapr, 62 | spi::MODE_0, 63 | 400.khz(), 64 | clocks, 65 | &mut rcc.apb2, 66 | ); 67 | 68 | let mut display: GraphicsMode<_> = Builder::new().connect_spi(spi, dc, cs).into(); 69 | 70 | // If you aren't using the Chip Select pin, use this instead: 71 | // let mut display: GraphicsMode<_> = Builder::new() 72 | // .connect_spi(spi, dc, sh1106::builder::NoOutputPin::new()) 73 | // .into(); 74 | 75 | display.init().unwrap(); 76 | display.flush().unwrap(); 77 | 78 | let im: ImageRawLE = ImageRawLE::new(include_bytes!("./rust.raw"), 64); 79 | 80 | Image::new(&im, Point::new(32, 0)) 81 | .draw(&mut display) 82 | .unwrap(); 83 | 84 | display.flush().unwrap(); 85 | 86 | loop {} 87 | } 88 | 89 | #[exception] 90 | fn HardFault(ef: &ExceptionFrame) -> ! { 91 | panic!("{:#?}", ef); 92 | } 93 | -------------------------------------------------------------------------------- /examples/pixelsquare.rs: -------------------------------------------------------------------------------- 1 | //! Draw a 1 bit per pixel black and white image. On a 128x64 SSD1306 display over I2C. 2 | //! 3 | //! Image was created with ImageMagick: 4 | //! 5 | //! ```bash 6 | //! convert rust.png -depth 1 gray:rust.raw 7 | //! ``` 8 | //! 9 | //! This example is for the STM32F103 "Blue Pill" board using I2C1. 10 | //! 11 | //! Wiring connections are as follows for a CRIUS-branded display: 12 | //! 13 | //! ``` 14 | //! Display -> Blue Pill 15 | //! (black) GND -> GND 16 | //! (red) +5V -> VCC 17 | //! (yellow) SDA -> PB9 18 | //! (green) SCL -> PB8 19 | //! ``` 20 | //! 21 | //! Run on a Blue Pill with `cargo run --example pixelsquare`. 22 | 23 | #![no_std] 24 | #![no_main] 25 | 26 | use cortex_m_rt::{entry, exception, ExceptionFrame}; 27 | use panic_semihosting as _; 28 | use sh1106::{prelude::*, Builder}; 29 | use stm32f1xx_hal::{ 30 | i2c::{BlockingI2c, DutyCycle, Mode}, 31 | prelude::*, 32 | stm32, 33 | }; 34 | 35 | #[entry] 36 | fn main() -> ! { 37 | let dp = stm32::Peripherals::take().unwrap(); 38 | 39 | let mut flash = dp.FLASH.constrain(); 40 | let mut rcc = dp.RCC.constrain(); 41 | 42 | let clocks = rcc.cfgr.freeze(&mut flash.acr); 43 | 44 | let mut afio = dp.AFIO.constrain(&mut rcc.apb2); 45 | 46 | let mut gpiob = dp.GPIOB.split(&mut rcc.apb2); 47 | 48 | let scl = gpiob.pb8.into_alternate_open_drain(&mut gpiob.crh); 49 | let sda = gpiob.pb9.into_alternate_open_drain(&mut gpiob.crh); 50 | 51 | let i2c = BlockingI2c::i2c1( 52 | dp.I2C1, 53 | (scl, sda), 54 | &mut afio.mapr, 55 | Mode::Fast { 56 | frequency: 100.khz().into(), 57 | duty_cycle: DutyCycle::Ratio2to1, 58 | }, 59 | clocks, 60 | &mut rcc.apb1, 61 | 1000, 62 | 10, 63 | 1000, 64 | 1000, 65 | ); 66 | 67 | let mut display: GraphicsMode<_> = Builder::new().connect_i2c(i2c).into(); 68 | 69 | display.init().unwrap(); 70 | display.flush().unwrap(); 71 | 72 | // Top side 73 | display.set_pixel(0, 0, 1); 74 | display.set_pixel(1, 0, 1); 75 | display.set_pixel(2, 0, 1); 76 | display.set_pixel(3, 0, 1); 77 | 78 | // Right side 79 | display.set_pixel(3, 0, 1); 80 | display.set_pixel(3, 1, 1); 81 | display.set_pixel(3, 2, 1); 82 | display.set_pixel(3, 3, 1); 83 | 84 | // Bottom side 85 | display.set_pixel(0, 3, 1); 86 | display.set_pixel(1, 3, 1); 87 | display.set_pixel(2, 3, 1); 88 | display.set_pixel(3, 3, 1); 89 | 90 | // Left side 91 | display.set_pixel(0, 0, 1); 92 | display.set_pixel(0, 1, 1); 93 | display.set_pixel(0, 2, 1); 94 | display.set_pixel(0, 3, 1); 95 | 96 | display.flush().unwrap(); 97 | 98 | loop {} 99 | } 100 | 101 | #[exception] 102 | fn HardFault(ef: &ExceptionFrame) -> ! { 103 | panic!("{:#?}", ef); 104 | } 105 | -------------------------------------------------------------------------------- /examples/rotation.rs: -------------------------------------------------------------------------------- 1 | //! Draw the Rust logo centered on a 90 degree rotated 128x64px display 2 | //! 3 | //! Image was created with ImageMagick: 4 | //! 5 | //! ```bash 6 | //! convert rust.png -depth 1 gray:rust.raw 7 | //! ``` 8 | //! 9 | //! This example is for the STM32F103 "Blue Pill" board using I2C1. 10 | //! 11 | //! Wiring connections are as follows for a CRIUS-branded display: 12 | //! 13 | //! ``` 14 | //! Display -> Blue Pill 15 | //! (black) GND -> GND 16 | //! (red) +5V -> VCC 17 | //! (yellow) SDA -> PB9 18 | //! (green) SCL -> PB8 19 | //! ``` 20 | //! 21 | //! Run on a Blue Pill with `cargo run --example rotation`. 22 | 23 | #![no_std] 24 | #![no_main] 25 | 26 | use cortex_m_rt::{entry, exception, ExceptionFrame}; 27 | use embedded_graphics::{ 28 | image::{Image, ImageRawLE}, 29 | pixelcolor::BinaryColor, 30 | prelude::*, 31 | }; 32 | use panic_semihosting as _; 33 | use sh1106::{prelude::*, Builder}; 34 | use stm32f1xx_hal::{ 35 | i2c::{BlockingI2c, DutyCycle, Mode}, 36 | prelude::*, 37 | stm32, 38 | }; 39 | 40 | #[entry] 41 | fn main() -> ! { 42 | let dp = stm32::Peripherals::take().unwrap(); 43 | 44 | let mut flash = dp.FLASH.constrain(); 45 | let mut rcc = dp.RCC.constrain(); 46 | 47 | let clocks = rcc.cfgr.freeze(&mut flash.acr); 48 | 49 | let mut afio = dp.AFIO.constrain(&mut rcc.apb2); 50 | 51 | let mut gpiob = dp.GPIOB.split(&mut rcc.apb2); 52 | 53 | let scl = gpiob.pb8.into_alternate_open_drain(&mut gpiob.crh); 54 | let sda = gpiob.pb9.into_alternate_open_drain(&mut gpiob.crh); 55 | 56 | let i2c = BlockingI2c::i2c1( 57 | dp.I2C1, 58 | (scl, sda), 59 | &mut afio.mapr, 60 | Mode::Fast { 61 | frequency: 100.khz().into(), 62 | duty_cycle: DutyCycle::Ratio2to1, 63 | }, 64 | clocks, 65 | &mut rcc.apb1, 66 | 1000, 67 | 10, 68 | 1000, 69 | 1000, 70 | ); 71 | 72 | let mut display: GraphicsMode<_> = Builder::new() 73 | // Set initial rotation at 90 degrees clockwise 74 | .with_rotation(DisplayRotation::Rotate90) 75 | .connect_i2c(i2c) 76 | .into(); 77 | 78 | display.init().unwrap(); 79 | display.flush().unwrap(); 80 | 81 | // Contrived example to test builder and instance methods. Sets rotation to 270 degress 82 | // or 90 degress counterclockwise 83 | display.set_rotation(DisplayRotation::Rotate270).unwrap(); 84 | 85 | let (w, h) = display.get_dimensions(); 86 | 87 | let im: ImageRawLE = ImageRawLE::new(include_bytes!("./rust.raw"), 64); 88 | 89 | Image::new( 90 | &im, 91 | Point::new(w as i32 / 2 - 64 / 2, h as i32 / 2 - 64 / 2), 92 | ) 93 | .draw(&mut display) 94 | .unwrap(); 95 | 96 | display.flush().unwrap(); 97 | 98 | loop {} 99 | } 100 | 101 | #[exception] 102 | fn HardFault(ef: &ExceptionFrame) -> ! { 103 | panic!("{:#?}", ef); 104 | } 105 | -------------------------------------------------------------------------------- /examples/rust.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-embedded-community/sh1106/798759149e6ec6efac1c21802215d7c441cfbbea/examples/rust.png -------------------------------------------------------------------------------- /examples/rust.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-embedded-community/sh1106/798759149e6ec6efac1c21802215d7c441cfbbea/examples/rust.raw -------------------------------------------------------------------------------- /examples/text.rs: -------------------------------------------------------------------------------- 1 | //! Print "Hello world!" with "Hello rust!" underneath. Uses the `embedded_graphics` crate to draw 2 | //! the text with a 6x8 pixel font. 3 | //! 4 | //! This example is for the STM32F103 "Blue Pill" board using I2C1. 5 | //! 6 | //! Wiring connections are as follows for a CRIUS-branded display: 7 | //! 8 | //! ``` 9 | //! Display -> Blue Pill 10 | //! (black) GND -> GND 11 | //! (red) +5V -> VCC 12 | //! (yellow) SDA -> PB9 13 | //! (green) SCL -> PB8 14 | //! ``` 15 | //! 16 | //! Run on a Blue Pill with `cargo run --example text`. 17 | 18 | #![no_std] 19 | #![no_main] 20 | 21 | use cortex_m_rt::{entry, exception, ExceptionFrame}; 22 | use embedded_graphics::{ 23 | mono_font::{ascii::FONT_6X10, MonoTextStyleBuilder}, 24 | pixelcolor::BinaryColor, 25 | prelude::*, 26 | text::{Baseline, Text}, 27 | }; 28 | use panic_semihosting as _; 29 | use sh1106::{prelude::*, Builder}; 30 | use stm32f1xx_hal::{ 31 | i2c::{BlockingI2c, DutyCycle, Mode}, 32 | prelude::*, 33 | stm32, 34 | }; 35 | 36 | #[entry] 37 | fn main() -> ! { 38 | let dp = stm32::Peripherals::take().unwrap(); 39 | 40 | let mut flash = dp.FLASH.constrain(); 41 | let mut rcc = dp.RCC.constrain(); 42 | 43 | let clocks = rcc.cfgr.freeze(&mut flash.acr); 44 | 45 | let mut afio = dp.AFIO.constrain(&mut rcc.apb2); 46 | 47 | let mut gpiob = dp.GPIOB.split(&mut rcc.apb2); 48 | 49 | let scl = gpiob.pb8.into_alternate_open_drain(&mut gpiob.crh); 50 | let sda = gpiob.pb9.into_alternate_open_drain(&mut gpiob.crh); 51 | 52 | let i2c = BlockingI2c::i2c1( 53 | dp.I2C1, 54 | (scl, sda), 55 | &mut afio.mapr, 56 | Mode::Fast { 57 | frequency: 100.khz().into(), 58 | duty_cycle: DutyCycle::Ratio2to1, 59 | }, 60 | clocks, 61 | &mut rcc.apb1, 62 | 1000, 63 | 10, 64 | 1000, 65 | 1000, 66 | ); 67 | 68 | let mut display: GraphicsMode<_> = Builder::new().connect_i2c(i2c).into(); 69 | 70 | display.init().unwrap(); 71 | display.flush().unwrap(); 72 | 73 | let text_style = MonoTextStyleBuilder::new() 74 | .font(&FONT_6X10) 75 | .text_color(BinaryColor::On) 76 | .build(); 77 | 78 | Text::with_baseline("Hello world!", Point::zero(), text_style, Baseline::Top) 79 | .draw(&mut display) 80 | .unwrap(); 81 | 82 | Text::with_baseline("Hello Rust!", Point::new(0, 16), text_style, Baseline::Top) 83 | .draw(&mut display) 84 | .unwrap(); 85 | 86 | display.flush().unwrap(); 87 | 88 | loop {} 89 | } 90 | 91 | #[exception] 92 | fn HardFault(ef: &ExceptionFrame) -> ! { 93 | panic!("{:#?}", ef); 94 | } 95 | -------------------------------------------------------------------------------- /memory.x: -------------------------------------------------------------------------------- 1 | /* Linker script for the STM32F103C8T6 */ 2 | MEMORY 3 | { 4 | FLASH : ORIGIN = 0x08000000, LENGTH = 128K 5 | RAM : ORIGIN = 0x20000000, LENGTH = 20K 6 | } -------------------------------------------------------------------------------- /readme_banner.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-embedded-community/sh1106/798759149e6ec6efac1c21802215d7c441cfbbea/readme_banner.jpg -------------------------------------------------------------------------------- /release.toml: -------------------------------------------------------------------------------- 1 | pre-release-replacements = [ 2 | { file = "CHANGELOG.md", search = "[Uu]nreleased", replace = "{{version}}" }, 3 | { file = "CHANGELOG.md", search = "\\.\\.\\.HEAD", replace = "...{{tag_name}}" }, 4 | { file = "CHANGELOG.md", search = "ReleaseDate", replace = "{{date}}" }, 5 | { file = "CHANGELOG.md", search = "", replace = "\n\n## [Unreleased] - ReleaseDate" }, 6 | { file = "CHANGELOG.md", search = "", replace = "\n[unreleased]: https://github.com/jamwaffles/sh1106/compare/{{tag_name}}...HEAD" }, 7 | ] 8 | pre-release-commit-message = "Release {{crate_name}} {{version}}" 9 | tag-message = "Release {{crate_name}} {{version}}" 10 | -------------------------------------------------------------------------------- /rustfmt.nightly.toml: -------------------------------------------------------------------------------- 1 | # Run with `cargo +nightly fmt -- --config-path ./rustfmt.nightly.toml` 2 | # This config only works in nightly. It can be used to clean up doc comments without having to do it 3 | # manually. 4 | 5 | format_code_in_doc_comments = true 6 | merge_imports = true 7 | -------------------------------------------------------------------------------- /src/builder.rs: -------------------------------------------------------------------------------- 1 | //! Interface factory 2 | //! 3 | //! This is the easiest way to create a driver instance. You can set various parameters of the 4 | //! driver and give it an interface to use. The builder will return a 5 | //! [`mode::RawMode`](../mode/raw/struct.RawMode.html) object which you should coerce to a richer 6 | //! display mode, like [mode::Graphics](../mode/graphics/struct.GraphicsMode.html) for drawing 7 | //! primitives and text. 8 | //! 9 | //! # Examples 10 | //! 11 | //! Connect over SPI with default rotation (0 deg) and size (128x64): 12 | //! 13 | //! ```rust,no_run 14 | //! use sh1106::{mode::GraphicsMode, Builder}; 15 | //! let spi = /* SPI interface from your HAL of choice */ 16 | //! # sh1106::test_helpers::SpiStub; 17 | //! let dc = /* GPIO data/command select pin */ 18 | //! # sh1106::test_helpers::PinStub; 19 | //! 20 | //! // This example does not use a Chip Select pin 21 | //! let cs = sh1106::builder::NoOutputPin::new(); 22 | //! 23 | //! Builder::new().connect_spi(spi, dc, cs); 24 | //! ``` 25 | //! 26 | //! Connect over I2C, changing lots of options 27 | //! 28 | //! ```rust,no_run 29 | //! use sh1106::{displayrotation::DisplayRotation, displaysize::DisplaySize, Builder}; 30 | //! 31 | //! let i2c = /* I2C interface from your HAL of choice */ 32 | //! # sh1106::test_helpers::I2cStub; 33 | //! 34 | //! Builder::new() 35 | //! .with_rotation(DisplayRotation::Rotate180) 36 | //! .with_i2c_addr(0x3D) 37 | //! .with_size(DisplaySize::Display128x32) 38 | //! .connect_i2c(i2c); 39 | //! ``` 40 | //! 41 | //! The above examples will produce a [RawMode](../mode/raw/struct.RawMode.html) instance 42 | //! by default. You need to coerce them into a mode by specifying a type on assignment. For 43 | //! example, to use [`GraphicsMode` mode](../mode/graphics/struct.GraphicsMode.html): 44 | //! 45 | //! ```rust,no_run 46 | //! use sh1106::{mode::GraphicsMode, Builder}; 47 | //! let spi = /* SPI interface from your HAL of choice */ 48 | //! # sh1106::test_helpers::SpiStub; 49 | //! let dc = /* GPIO data/command select pin */ 50 | //! # sh1106::test_helpers::PinStub; 51 | //! 52 | //! // This example does not use a Chip Select pin 53 | //! let cs = sh1106::builder::NoOutputPin::new(); 54 | //! 55 | //! let display: GraphicsMode<_> = Builder::new().connect_spi(spi, dc, cs).into(); 56 | //! ``` 57 | 58 | use core::marker::PhantomData; 59 | use hal::{self, digital::v2::OutputPin}; 60 | 61 | use crate::{ 62 | displayrotation::DisplayRotation, 63 | displaysize::DisplaySize, 64 | interface::{I2cInterface, SpiInterface}, 65 | mode::{displaymode::DisplayMode, raw::RawMode}, 66 | properties::DisplayProperties, 67 | }; 68 | 69 | /// Builder struct. Driver options and interface are set using its methods. 70 | /// 71 | /// See the [module level documentation](crate::builder) for more details. 72 | #[derive(Clone, Copy)] 73 | pub struct Builder { 74 | display_size: DisplaySize, 75 | rotation: DisplayRotation, 76 | i2c_addr: u8, 77 | } 78 | 79 | impl Default for Builder { 80 | fn default() -> Self { 81 | Self::new() 82 | } 83 | } 84 | 85 | impl Builder { 86 | /// Create new builder with a default size of 128 x 64 pixels and no rotation. 87 | pub fn new() -> Builder { 88 | Builder { 89 | display_size: DisplaySize::Display128x64, 90 | rotation: DisplayRotation::Rotate0, 91 | i2c_addr: 0x3c, 92 | } 93 | } 94 | } 95 | 96 | impl Builder { 97 | /// Set the size of the display. Supported sizes are defined by [DisplaySize]. 98 | pub fn with_size(self, display_size: DisplaySize) -> Self { 99 | Self { 100 | display_size, 101 | ..self 102 | } 103 | } 104 | 105 | /// Set the I2C address to use. Defaults to 0x3C which is the most common address. 106 | /// The other address specified in the datasheet is 0x3D. Ignored when using SPI interface. 107 | pub fn with_i2c_addr(self, i2c_addr: u8) -> Self { 108 | Self { i2c_addr, ..self } 109 | } 110 | 111 | /// Set the rotation of the display to one of four values. Defaults to no rotation. 112 | pub fn with_rotation(self, rotation: DisplayRotation) -> Self { 113 | Self { rotation, ..self } 114 | } 115 | 116 | /// Finish the builder and use I2C to communicate with the display 117 | pub fn connect_i2c(self, i2c: I2C) -> DisplayMode>> 118 | where 119 | I2C: hal::blocking::i2c::Write, 120 | { 121 | let properties = DisplayProperties::new( 122 | I2cInterface::new(i2c, self.i2c_addr), 123 | self.display_size, 124 | self.rotation, 125 | ); 126 | DisplayMode::>>::new(properties) 127 | } 128 | 129 | /// Finish the builder and use SPI to communicate with the display 130 | /// 131 | /// If the Chip Select (CS) pin is not required, [`NoOutputPin`] can be used as a dummy argument 132 | /// 133 | /// [`NoOutputPin`]: ./struct.NoOutputPin.html 134 | pub fn connect_spi( 135 | self, 136 | spi: SPI, 137 | dc: DC, 138 | cs: CS, 139 | ) -> DisplayMode>> 140 | where 141 | SPI: hal::blocking::spi::Transfer 142 | + hal::blocking::spi::Write, 143 | DC: OutputPin, 144 | CS: OutputPin, 145 | { 146 | let properties = DisplayProperties::new( 147 | SpiInterface::new(spi, dc, cs), 148 | self.display_size, 149 | self.rotation, 150 | ); 151 | DisplayMode::>>::new(properties) 152 | } 153 | } 154 | 155 | /// Represents an unused output pin. 156 | #[derive(Clone, Copy)] 157 | pub struct NoOutputPin { 158 | _m: PhantomData, 159 | } 160 | 161 | impl NoOutputPin { 162 | /// Create a new instance of `NoOutputPin` 163 | pub fn new() -> Self { 164 | Self { _m: PhantomData } 165 | } 166 | } 167 | 168 | impl OutputPin for NoOutputPin { 169 | type Error = PinE; 170 | fn set_low(&mut self) -> Result<(), PinE> { 171 | Ok(()) 172 | } 173 | fn set_high(&mut self) -> Result<(), PinE> { 174 | Ok(()) 175 | } 176 | } 177 | 178 | #[cfg(test)] 179 | mod tests { 180 | use super::NoOutputPin; 181 | use embedded_hal::digital::v2::OutputPin; 182 | 183 | enum SomeError {} 184 | 185 | struct SomeDriver> { 186 | #[allow(dead_code)] 187 | p: P, 188 | } 189 | 190 | #[test] 191 | fn test_output_pin() { 192 | let p = NoOutputPin::new(); 193 | let _d = SomeDriver { p }; 194 | 195 | assert!(true); 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /src/command.rs: -------------------------------------------------------------------------------- 1 | use super::interface::DisplayInterface; 2 | 3 | /// sh1106 Commands 4 | 5 | /// Commands 6 | #[derive(Debug)] 7 | #[allow(dead_code)] 8 | pub enum Command { 9 | /// Set contrast. Higher number is higher contrast. Default = 0x7F 10 | Contrast(u8), 11 | /// Turn entire display on. If set, all pixels will 12 | /// be set to on, if not, the value in memory will be used. 13 | AllOn(bool), 14 | /// Invert display. 15 | Invert(bool), 16 | /// Turn display on or off. 17 | DisplayOn(bool), 18 | /// Set column address lower 4 bits 19 | ColumnAddressLow(u8), 20 | /// Set column address higher 4 bits 21 | ColumnAddressHigh(u8), 22 | /// Set page address 23 | PageAddress(Page), 24 | /// Set display start line from 0-63 25 | StartLine(u8), 26 | /// Reverse columns from 127-0 27 | SegmentRemap(bool), 28 | /// Set multipex ratio from 15-63 (MUX-1) 29 | Multiplex(u8), 30 | /// Scan from COM[n-1] to COM0 (where N is mux ratio) 31 | ReverseComDir(bool), 32 | /// Set vertical shift 33 | DisplayOffset(u8), 34 | /// Setup com hardware configuration 35 | /// First value indicates sequential (false) or alternative (true) 36 | /// pin configuration. 37 | ComPinConfig(bool), 38 | /// Set up display clock. 39 | /// First value is oscillator frequency, increasing with higher value 40 | /// Second value is divide ratio - 1 41 | DisplayClockDiv(u8, u8), 42 | /// Set up phase 1 and 2 of precharge period. each value is from 0-63 43 | PreChargePeriod(u8, u8), 44 | /// Set Vcomh Deselect level 45 | VcomhDeselect(VcomhLevel), 46 | /// NOOP 47 | Noop, 48 | /// Enable charge pump 49 | ChargePump(bool), 50 | } 51 | 52 | impl Command { 53 | /// Send command to sh1106 54 | pub fn send(self, iface: &mut DI) -> Result<(), DI::Error> 55 | where 56 | DI: DisplayInterface, 57 | { 58 | // Transform command into a fixed size array of 7 u8 and the real length for sending 59 | let (data, len) = match self { 60 | Command::Contrast(val) => ([0x81, val, 0, 0, 0, 0, 0], 2), 61 | Command::AllOn(on) => ([0xA4 | (on as u8), 0, 0, 0, 0, 0, 0], 1), 62 | Command::Invert(inv) => ([0xA6 | (inv as u8), 0, 0, 0, 0, 0, 0], 1), 63 | Command::DisplayOn(on) => ([0xAE | (on as u8), 0, 0, 0, 0, 0, 0], 1), 64 | Command::ColumnAddressLow(addr) => ([0xF & addr, 0, 0, 0, 0, 0, 0], 1), 65 | Command::ColumnAddressHigh(addr) => ([0x10 | (0xF & addr), 0, 0, 0, 0, 0, 0], 1), 66 | Command::PageAddress(page) => ([0xB0 | (page as u8), 0, 0, 0, 0, 0, 0], 1), 67 | Command::StartLine(line) => ([0x40 | (0x3F & line), 0, 0, 0, 0, 0, 0], 1), 68 | Command::SegmentRemap(remap) => ([0xA0 | (remap as u8), 0, 0, 0, 0, 0, 0], 1), 69 | Command::Multiplex(ratio) => ([0xA8, ratio, 0, 0, 0, 0, 0], 2), 70 | Command::ReverseComDir(rev) => ([0xC0 | ((rev as u8) << 3), 0, 0, 0, 0, 0, 0], 1), 71 | Command::DisplayOffset(offset) => ([0xD3, offset, 0, 0, 0, 0, 0], 2), 72 | Command::ComPinConfig(alt) => ([0xDA, 0x02 | ((alt as u8) << 4), 0, 0, 0, 0, 0], 2), 73 | Command::DisplayClockDiv(fosc, div) => { 74 | ([0xD5, ((0xF & fosc) << 4) | (0xF & div), 0, 0, 0, 0, 0], 2) 75 | } 76 | Command::PreChargePeriod(phase1, phase2) => ( 77 | [0xD9, ((0xF & phase2) << 4) | (0xF & phase1), 0, 0, 0, 0, 0], 78 | 2, 79 | ), 80 | Command::VcomhDeselect(level) => ([0xDB, (level as u8) << 4, 0, 0, 0, 0, 0], 2), 81 | Command::Noop => ([0xE3, 0, 0, 0, 0, 0, 0], 1), 82 | Command::ChargePump(en) => ([0xAD, 0x8A | (en as u8), 0, 0, 0, 0, 0], 2), 83 | }; 84 | 85 | // Send command over the interface 86 | iface.send_commands(&data[0..len]) 87 | } 88 | } 89 | 90 | /// Display page 91 | #[derive(Debug, Clone, Copy)] 92 | pub enum Page { 93 | /// Page 0 94 | Page0 = 0, 95 | /// Page 1 96 | Page1 = 1, 97 | /// Page 2 98 | Page2 = 2, 99 | /// Page 3 100 | Page3 = 3, 101 | /// Page 4 102 | Page4 = 4, 103 | /// Page 5 104 | Page5 = 5, 105 | /// Page 6 106 | Page6 = 6, 107 | /// Page 7 108 | Page7 = 7, 109 | } 110 | 111 | impl From for Page { 112 | fn from(val: u8) -> Page { 113 | match val / 8 { 114 | 0 => Page::Page0, 115 | 1 => Page::Page1, 116 | 2 => Page::Page2, 117 | 3 => Page::Page3, 118 | 4 => Page::Page4, 119 | 5 => Page::Page5, 120 | 6 => Page::Page6, 121 | 7 => Page::Page7, 122 | _ => panic!("Page too high"), 123 | } 124 | } 125 | } 126 | 127 | /// Frame interval 128 | #[derive(Debug, Clone, Copy)] 129 | #[allow(dead_code)] 130 | pub enum NFrames { 131 | /// 2 Frames 132 | F2 = 0b111, 133 | /// 3 Frames 134 | F3 = 0b100, 135 | /// 4 Frames 136 | F4 = 0b101, 137 | /// 5 Frames 138 | F5 = 0b000, 139 | /// 25 Frames 140 | F25 = 0b110, 141 | /// 64 Frames 142 | F64 = 0b001, 143 | /// 128 Frames 144 | F128 = 0b010, 145 | /// 256 Frames 146 | F256 = 0b011, 147 | } 148 | 149 | /// Vcomh Deselect level 150 | #[derive(Debug, Clone, Copy)] 151 | #[allow(dead_code)] 152 | pub enum VcomhLevel { 153 | /// 0.65 * Vcc 154 | V065 = 0b001, 155 | /// 0.77 * Vcc 156 | V077 = 0b010, 157 | /// 0.83 * Vcc 158 | V083 = 0b011, 159 | /// Auto 160 | Auto = 0b100, 161 | } 162 | -------------------------------------------------------------------------------- /src/displayrotation.rs: -------------------------------------------------------------------------------- 1 | //! Display rotation 2 | 3 | /// Display rotation 4 | #[derive(Clone, Copy)] 5 | pub enum DisplayRotation { 6 | /// No rotation, normal display 7 | Rotate0, 8 | /// Rotate by 90 degress clockwise 9 | Rotate90, 10 | /// Rotate by 180 degress clockwise 11 | Rotate180, 12 | /// Rotate 270 degress clockwise 13 | Rotate270, 14 | } 15 | -------------------------------------------------------------------------------- /src/displaysize.rs: -------------------------------------------------------------------------------- 1 | //! Display size 2 | 3 | /// Display size enumeration 4 | #[derive(Clone, Copy)] 5 | pub enum DisplaySize { 6 | /// 128 by 64 pixels 7 | Display128x64, 8 | /// 128 by 64 pixels without 2px X offset 9 | Display128x64NoOffset, 10 | /// 128 by 32 pixels 11 | Display128x32, 12 | /// 132 by 64 pixels 13 | Display132x64, 14 | } 15 | 16 | impl DisplaySize { 17 | /// Get integral dimensions from DisplaySize 18 | pub fn dimensions(self) -> (u8, u8) { 19 | match self { 20 | DisplaySize::Display128x64 => (128, 64), 21 | DisplaySize::Display128x64NoOffset => (128, 64), 22 | DisplaySize::Display128x32 => (128, 32), 23 | DisplaySize::Display132x64 => (132, 64), 24 | } 25 | } 26 | 27 | /// Get the panel column offset from DisplaySize 28 | pub fn column_offset(self) -> u8 { 29 | match self { 30 | DisplaySize::Display128x64 => 2, 31 | DisplaySize::Display128x64NoOffset => 0, 32 | DisplaySize::Display128x32 => 2, 33 | DisplaySize::Display132x64 => 0, 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/interface/i2c.rs: -------------------------------------------------------------------------------- 1 | //! SH1106 I2C Interface 2 | 3 | use hal; 4 | 5 | use super::DisplayInterface; 6 | use crate::{command::Page, Error}; 7 | 8 | /// SH1106 I2C communication interface 9 | pub struct I2cInterface { 10 | i2c: I2C, 11 | addr: u8, 12 | } 13 | 14 | impl I2cInterface 15 | where 16 | I2C: hal::blocking::i2c::Write, 17 | { 18 | /// Create new sh1106 I2C interface 19 | pub fn new(i2c: I2C, addr: u8) -> Self { 20 | Self { i2c, addr } 21 | } 22 | } 23 | 24 | impl DisplayInterface for I2cInterface 25 | where 26 | I2C: hal::blocking::i2c::Write, 27 | { 28 | type Error = Error; 29 | 30 | fn init(&mut self) -> Result<(), Self::Error> { 31 | Ok(()) 32 | } 33 | 34 | fn send_commands(&mut self, cmds: &[u8]) -> Result<(), Self::Error> { 35 | // Copy over given commands to new aray to prefix with command identifier 36 | let mut writebuf: [u8; 8] = [0; 8]; 37 | writebuf[1..=cmds.len()].copy_from_slice(&cmds); 38 | 39 | self.i2c 40 | .write(self.addr, &writebuf[..=cmds.len()]) 41 | .map_err(Error::Comm) 42 | } 43 | 44 | fn send_data(&mut self, buf: &[u8]) -> Result<(), Self::Error> { 45 | // Display is always 128px wide 46 | const CHUNKLEN: usize = 128; 47 | 48 | const BUFLEN: usize = CHUNKLEN + 1; 49 | 50 | // Noop if the data buffer is empty 51 | if buf.is_empty() { 52 | return Ok(()); 53 | } 54 | 55 | let mut page = Page::Page0 as u8; 56 | 57 | // Display width plus 4 start bytes 58 | let mut writebuf: [u8; BUFLEN] = [0; BUFLEN]; 59 | 60 | writebuf[0] = 0x40; // Following bytes are data bytes 61 | 62 | for chunk in buf.chunks(CHUNKLEN) { 63 | // Copy over all data from buffer, leaving the data command byte intact 64 | writebuf[1..BUFLEN].copy_from_slice(&chunk); 65 | 66 | self.i2c 67 | .write( 68 | self.addr, 69 | &[ 70 | 0x00, // Command 71 | page, // Page address 72 | 0x02, // Lower column address 73 | 0x10, // Upper column address (always zero, base is 10h) 74 | ], 75 | ) 76 | .map_err(Error::Comm)?; 77 | 78 | self.i2c.write(self.addr, &writebuf).map_err(Error::Comm)?; 79 | 80 | page += 1; 81 | } 82 | 83 | Ok(()) 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/interface/mod.rs: -------------------------------------------------------------------------------- 1 | //! sh1106 Communication Interface (I2C/SPI) 2 | //! 3 | //! These are the two supported interfaces for communicating with the display. They're used by the 4 | //! [builder](../builder/index.html) methods 5 | //! [connect_i2c](../builder/struct.Builder.html#method.connect_i2c) and 6 | //! [connect_spi](../builder/struct.Builder.html#method.connect_spi). 7 | //! 8 | //! The types that these interfaces define are quite lengthy, so it is recommended that you create 9 | //! a type alias. Here's an example for the I2C1 on an STM32F103xx: 10 | //! 11 | //! ```rust 12 | //! # use stm32f1xx_hal::gpio::gpiob::{PB8, PB9}; 13 | //! # use stm32f1xx_hal::gpio::{Alternate, OpenDrain}; 14 | //! # use stm32f1xx_hal::i2c::I2c; 15 | //! # use stm32f1xx_hal::prelude::*; 16 | //! # use stm32f1xx_hal::pac::I2C1; 17 | //! # use sh1106::{interface::I2cInterface, mode::GraphicsMode, Builder}; 18 | //! type OledDisplay = GraphicsMode< 19 | //! I2cInterface>, PB9>)>>, 20 | //! >; 21 | //! ``` 22 | //! 23 | //! Here's one for SPI1 on an STM32F103xx: 24 | //! 25 | //! ```rust 26 | //! # use stm32f1xx_hal::gpio::gpioa::{PA5, PA6, PA7}; 27 | //! # use stm32f1xx_hal::gpio::gpiob::PB1; 28 | //! # use stm32f1xx_hal::gpio::{Alternate, Floating, Input, Output, PushPull}; 29 | //! # use stm32f1xx_hal::spi; 30 | //! # use stm32f1xx_hal::spi::Spi; 31 | //! # use stm32f1xx_hal::pac::SPI1; 32 | //! # use sh1106::{interface::SpiInterface, mode::GraphicsMode}; 33 | //! pub type OledDisplay = GraphicsMode< 34 | //! SpiInterface< 35 | //! Spi< 36 | //! SPI1, 37 | //! spi::Spi1NoRemap, 38 | //! ( 39 | //! PA5>, 40 | //! PA6>, 41 | //! PA7>, 42 | //! ), 43 | //! u8 44 | //! >, 45 | //! PB1>, 46 | //! sh1106::builder::NoOutputPin, 47 | //! >, 48 | //! >; 49 | //! ``` 50 | 51 | pub mod i2c; 52 | pub mod spi; 53 | 54 | /// A method of communicating with sh1106 55 | pub trait DisplayInterface { 56 | /// Interface error type 57 | type Error; 58 | 59 | /// Initialize device. 60 | fn init(&mut self) -> Result<(), Self::Error>; 61 | /// Send a batch of up to 8 commands to display. 62 | fn send_commands(&mut self, cmd: &[u8]) -> Result<(), Self::Error>; 63 | /// Send data to display. 64 | fn send_data(&mut self, buf: &[u8]) -> Result<(), Self::Error>; 65 | } 66 | 67 | pub use self::{i2c::I2cInterface, spi::SpiInterface}; 68 | -------------------------------------------------------------------------------- /src/interface/spi.rs: -------------------------------------------------------------------------------- 1 | //! sh1106 SPI interface 2 | 3 | use hal::{self, digital::v2::OutputPin}; 4 | 5 | use super::DisplayInterface; 6 | use crate::Error; 7 | 8 | /// SPI display interface. 9 | /// 10 | /// This combines the SPI peripheral and a data/command pin 11 | pub struct SpiInterface { 12 | spi: SPI, 13 | dc: DC, 14 | cs: CS, 15 | } 16 | 17 | impl SpiInterface 18 | where 19 | SPI: hal::blocking::spi::Write, 20 | DC: OutputPin, 21 | CS: OutputPin, 22 | { 23 | /// Create new SPI interface for communciation with sh1106 24 | pub fn new(spi: SPI, dc: DC, cs: CS) -> Self { 25 | Self { spi, dc, cs } 26 | } 27 | } 28 | 29 | impl DisplayInterface for SpiInterface 30 | where 31 | SPI: hal::blocking::spi::Write, 32 | DC: OutputPin, 33 | CS: OutputPin, 34 | { 35 | type Error = Error; 36 | 37 | fn init(&mut self) -> Result<(), Self::Error> { 38 | self.cs.set_high().map_err(Error::Pin) 39 | } 40 | 41 | fn send_commands(&mut self, cmds: &[u8]) -> Result<(), Self::Error> { 42 | self.cs.set_low().map_err(Error::Pin)?; 43 | self.dc.set_low().map_err(Error::Pin)?; 44 | 45 | self.spi.write(&cmds).map_err(Error::Comm)?; 46 | 47 | self.dc.set_high().map_err(Error::Pin)?; 48 | self.cs.set_high().map_err(Error::Pin) 49 | } 50 | 51 | fn send_data(&mut self, buf: &[u8]) -> Result<(), Self::Error> { 52 | self.cs.set_low().map_err(Error::Pin)?; 53 | 54 | // 1 = data, 0 = command 55 | self.dc.set_high().map_err(Error::Pin)?; 56 | 57 | self.spi.write(&buf).map_err(Error::Comm)?; 58 | 59 | self.cs.set_high().map_err(Error::Pin) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! sh1106 OLED display driver 2 | //! 3 | //! The driver must be initialised by passing an I2C or SPI interface peripheral to the 4 | //! [`Builder`](builder/struct.Builder.html), 5 | //! which will in turn create a driver instance in a particular mode. By default, the builder 6 | //! returns a `mode::RawMode` instance which isn't very useful by itself. You can coerce the driver 7 | //! into a more useful mode by calling `into()` and defining the type you want to coerce to. For 8 | //! example, to initialise the display with an I2C interface and 9 | //! [`mode::GraphicsMode`](mode/graphics/struct.GraphicsMode.html), you would do something like 10 | //! this: 11 | //! 12 | //! ```rust,no_run 13 | //! use sh1106::{prelude::*, Builder}; 14 | //! # let i2c = sh1106::test_helpers::I2cStub; 15 | //! 16 | //! let mut display: GraphicsMode<_> = Builder::new().connect_i2c(i2c).into(); 17 | //! 18 | //! display.init().unwrap(); 19 | //! display.flush().unwrap(); 20 | //! 21 | //! display.set_pixel(10, 20, 1); 22 | //! 23 | //! display.flush().unwrap(); 24 | //! ``` 25 | //! 26 | //! See the [example](https://github.com/jamwaffles/sh1106/blob/master/examples/graphics_i2c.rs) 27 | //! for more usage. The [entire `embedded_graphics` featureset](https://github.com/jamwaffles/embedded-graphics#features) 28 | //! is supported by this driver. 29 | //! 30 | //! It's possible to customise the driver to suit your display/application. Take a look at the 31 | //! [Builder] for available options. 32 | //! 33 | //! # Examples 34 | //! 35 | //! Examples can be found in 36 | //! [the examples/ folder](https://github.com/jamwaffles/sh1106/blob/master/examples) 37 | //! 38 | //! ## Draw some text to the display 39 | //! 40 | //! Uses [mode::GraphicsMode] and [embedded_graphics](../embedded_graphics/index.html). 41 | //! 42 | //! ```rust,no_run 43 | //! use embedded_graphics::{ 44 | //! mono_font::{ascii::FONT_6X10, MonoTextStyleBuilder}, 45 | //! pixelcolor::BinaryColor, 46 | //! prelude::*, 47 | //! text::{Baseline, Text}, 48 | //! }; 49 | //! use sh1106::{prelude::*, Builder}; 50 | //! # let i2c = sh1106::test_helpers::I2cStub; 51 | //! 52 | //! let mut display: GraphicsMode<_> = Builder::new().connect_i2c(i2c).into(); 53 | //! 54 | //! display.init().unwrap(); 55 | //! display.flush().unwrap(); 56 | //! 57 | //! let text_style = MonoTextStyleBuilder::new() 58 | //! .font(&FONT_6X10) 59 | //! .text_color(BinaryColor::On) 60 | //! .build(); 61 | //! 62 | //! Text::with_baseline("Hello world!", Point::zero(), text_style, Baseline::Top) 63 | //! .draw(&mut display) 64 | //! .unwrap(); 65 | //! 66 | //! Text::with_baseline("Hello Rust!", Point::new(0, 16), text_style, Baseline::Top) 67 | //! .draw(&mut display) 68 | //! .unwrap(); 69 | //! 70 | //! display.flush().unwrap(); 71 | //! ``` 72 | 73 | #![no_std] 74 | #![deny(missing_docs)] 75 | #![deny(missing_copy_implementations)] 76 | #![deny(trivial_casts)] 77 | #![deny(trivial_numeric_casts)] 78 | #![deny(unsafe_code)] 79 | #![deny(unstable_features)] 80 | #![deny(unused_import_braces)] 81 | #![deny(unused_qualifications)] 82 | 83 | /// Errors in this crate 84 | #[derive(Debug)] 85 | pub enum Error { 86 | /// Communication error 87 | Comm(CommE), 88 | /// Pin setting error 89 | Pin(PinE), 90 | } 91 | 92 | extern crate embedded_hal as hal; 93 | 94 | pub mod builder; 95 | mod command; 96 | pub mod displayrotation; 97 | pub mod displaysize; 98 | pub mod interface; 99 | pub mod mode; 100 | pub mod prelude; 101 | pub mod properties; 102 | #[doc(hidden)] 103 | pub mod test_helpers; 104 | 105 | pub use crate::builder::{Builder, NoOutputPin}; 106 | -------------------------------------------------------------------------------- /src/mode/displaymode.rs: -------------------------------------------------------------------------------- 1 | //! Abstraction of different operating modes for the sh1106 2 | 3 | use crate::{interface::DisplayInterface, properties::DisplayProperties}; 4 | 5 | /// Display mode abstraction 6 | pub struct DisplayMode(pub MODE); 7 | 8 | /// Trait with core functionality for display mode switching 9 | pub trait DisplayModeTrait { 10 | /// Allocate all required data and initialise display for mode 11 | fn new(properties: DisplayProperties) -> Self; 12 | 13 | /// Release resources for reuse with different mode 14 | fn release(self) -> DisplayProperties; 15 | } 16 | 17 | impl DisplayMode { 18 | /// Setup display to run in requested mode 19 | pub fn new(properties: DisplayProperties) -> Self 20 | where 21 | DI: DisplayInterface, 22 | MODE: DisplayModeTrait, 23 | { 24 | DisplayMode(MODE::new(properties)) 25 | } 26 | 27 | /// Change into any mode implementing DisplayModeTrait 28 | // TODO: Figure out how to stay as generic DisplayMode but act as particular mode 29 | pub fn into>(self) -> NMODE 30 | where 31 | DI: DisplayInterface, 32 | MODE: DisplayModeTrait, 33 | { 34 | let properties = self.0.release(); 35 | NMODE::new(properties) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/mode/graphics.rs: -------------------------------------------------------------------------------- 1 | //! Buffered display module for use with the [embedded-graphics] crate 2 | //! 3 | //! ```rust,no_run 4 | //! use embedded_graphics::{ 5 | //! pixelcolor::BinaryColor, 6 | //! prelude::*, 7 | //! primitives::{Circle, Line, PrimitiveStyle, Rectangle}, 8 | //! }; 9 | //! use sh1106::{prelude::*, Builder}; 10 | //! # let i2c = sh1106::test_helpers::I2cStub; 11 | //! 12 | //! let mut display: GraphicsMode<_> = Builder::new().connect_i2c(i2c).into(); 13 | //! 14 | //! display.init().unwrap(); 15 | //! display.flush().unwrap(); 16 | //! 17 | //! Line::new(Point::new(8, 16 + 16), Point::new(8 + 16, 16 + 16)) 18 | //! .into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1)) 19 | //! .draw(&mut display) 20 | //! .unwrap(); 21 | //! 22 | //! Line::new(Point::new(8, 16 + 16), Point::new(8 + 8, 16)) 23 | //! .into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1)) 24 | //! .draw(&mut display) 25 | //! .unwrap(); 26 | //! 27 | //! Line::new(Point::new(8 + 16, 16 + 16), Point::new(8 + 8, 16)) 28 | //! .into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1)) 29 | //! .draw(&mut display) 30 | //! .unwrap(); 31 | //! 32 | //! Rectangle::with_corners(Point::new(48, 16), Point::new(48 + 16, 16 + 16)) 33 | //! .into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1)) 34 | //! .draw(&mut display) 35 | //! .unwrap(); 36 | //! 37 | //! Circle::new(Point::new(88, 16), 16) 38 | //! .into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1)) 39 | //! .draw(&mut display) 40 | //! .unwrap(); 41 | //! 42 | //! display.flush().unwrap(); 43 | //! ``` 44 | 45 | use hal::{blocking::delay::DelayMs, digital::v2::OutputPin}; 46 | 47 | use crate::{ 48 | displayrotation::DisplayRotation, interface::DisplayInterface, 49 | mode::displaymode::DisplayModeTrait, properties::DisplayProperties, Error, 50 | }; 51 | 52 | const BUFFER_SIZE: usize = 132 * 64 / 8; 53 | 54 | /// Graphics mode handler 55 | pub struct GraphicsMode 56 | where 57 | DI: DisplayInterface, 58 | { 59 | properties: DisplayProperties, 60 | buffer: [u8; BUFFER_SIZE], 61 | } 62 | 63 | impl DisplayModeTrait for GraphicsMode 64 | where 65 | DI: DisplayInterface, 66 | { 67 | /// Create new GraphicsMode instance 68 | fn new(properties: DisplayProperties) -> Self { 69 | GraphicsMode { 70 | properties, 71 | buffer: [0; BUFFER_SIZE], 72 | } 73 | } 74 | 75 | /// Release all resources used by GraphicsMode 76 | fn release(self) -> DisplayProperties { 77 | self.properties 78 | } 79 | } 80 | 81 | impl GraphicsMode 82 | where 83 | DI: DisplayInterface, 84 | { 85 | /// Clear the display buffer. You need to call `display.flush()` for any effect on the screen 86 | pub fn clear(&mut self) { 87 | self.buffer = [0; BUFFER_SIZE]; 88 | } 89 | 90 | /// Reset display 91 | pub fn reset( 92 | &mut self, 93 | rst: &mut RST, 94 | delay: &mut DELAY, 95 | ) -> Result<(), Error<(), PinE>> 96 | where 97 | RST: OutputPin, 98 | DELAY: DelayMs, 99 | { 100 | rst.set_high().map_err(Error::Pin)?; 101 | delay.delay_ms(1); 102 | rst.set_low().map_err(Error::Pin)?; 103 | delay.delay_ms(10); 104 | rst.set_high().map_err(Error::Pin) 105 | } 106 | 107 | /// Write out data to display 108 | pub fn flush(&mut self) -> Result<(), DI::Error> { 109 | let display_size = self.properties.get_size(); 110 | 111 | // Ensure the display buffer is at the origin of the display before we send the full frame 112 | // to prevent accidental offsets 113 | let (display_width, display_height) = display_size.dimensions(); 114 | let column_offset = display_size.column_offset(); 115 | self.properties.set_draw_area( 116 | (column_offset, 0), 117 | (display_width + column_offset, display_height), 118 | )?; 119 | 120 | let length = (display_width as usize) * (display_height as usize) / 8; 121 | 122 | self.properties.draw(&self.buffer[..length]) 123 | } 124 | 125 | /// Turn a pixel on or off. A non-zero `value` is treated as on, `0` as off. If the X and Y 126 | /// coordinates are out of the bounds of the display, this method call is a noop. 127 | pub fn set_pixel(&mut self, x: u32, y: u32, value: u8) { 128 | let (display_width, _) = self.properties.get_size().dimensions(); 129 | let display_rotation = self.properties.get_rotation(); 130 | 131 | let idx = match display_rotation { 132 | DisplayRotation::Rotate0 | DisplayRotation::Rotate180 => { 133 | if x >= display_width as u32 { 134 | return; 135 | } 136 | ((y as usize) / 8 * display_width as usize) + (x as usize) 137 | } 138 | 139 | DisplayRotation::Rotate90 | DisplayRotation::Rotate270 => { 140 | if y >= display_width as u32 { 141 | return; 142 | } 143 | ((x as usize) / 8 * display_width as usize) + (y as usize) 144 | } 145 | }; 146 | 147 | if idx >= self.buffer.len() { 148 | return; 149 | } 150 | 151 | let (byte, bit) = match display_rotation { 152 | DisplayRotation::Rotate0 | DisplayRotation::Rotate180 => { 153 | let byte = 154 | &mut self.buffer[((y as usize) / 8 * display_width as usize) + (x as usize)]; 155 | let bit = 1 << (y % 8); 156 | 157 | (byte, bit) 158 | } 159 | DisplayRotation::Rotate90 | DisplayRotation::Rotate270 => { 160 | let byte = 161 | &mut self.buffer[((x as usize) / 8 * display_width as usize) + (y as usize)]; 162 | let bit = 1 << (x % 8); 163 | 164 | (byte, bit) 165 | } 166 | }; 167 | 168 | if value == 0 { 169 | *byte &= !bit; 170 | } else { 171 | *byte |= bit; 172 | } 173 | } 174 | 175 | /// Display is set up in column mode, i.e. a byte walks down a column of 8 pixels from 176 | /// column 0 on the left, to column _n_ on the right 177 | pub fn init(&mut self) -> Result<(), DI::Error> { 178 | self.properties.init_column_mode() 179 | } 180 | 181 | /// Get display dimensions, taking into account the current rotation of the display 182 | pub fn get_dimensions(&self) -> (u8, u8) { 183 | self.properties.get_dimensions() 184 | } 185 | 186 | /// Set the display rotation 187 | pub fn set_rotation(&mut self, rot: DisplayRotation) -> Result<(), DI::Error> { 188 | self.properties.set_rotation(rot) 189 | } 190 | 191 | /// Set the display contrast 192 | pub fn set_contrast(&mut self, contrast: u8) -> Result<(), DI::Error> { 193 | self.properties.set_contrast(contrast) 194 | } 195 | } 196 | 197 | #[cfg(feature = "graphics")] 198 | use embedded_graphics_core::{ 199 | draw_target::DrawTarget, 200 | geometry::Size, 201 | geometry::{Dimensions, OriginDimensions}, 202 | pixelcolor::BinaryColor, 203 | Pixel, 204 | }; 205 | 206 | #[cfg(feature = "graphics")] 207 | impl DrawTarget for GraphicsMode 208 | where 209 | DI: DisplayInterface, 210 | { 211 | type Color = BinaryColor; 212 | type Error = core::convert::Infallible; 213 | 214 | fn draw_iter(&mut self, pixels: I) -> Result<(), Self::Error> 215 | where 216 | I: IntoIterator>, 217 | { 218 | let bb = self.bounding_box(); 219 | 220 | pixels 221 | .into_iter() 222 | .filter(|Pixel(pos, _color)| bb.contains(*pos)) 223 | .for_each(|Pixel(pos, color)| { 224 | self.set_pixel(pos.x as u32, pos.y as u32, color.is_on().into()) 225 | }); 226 | 227 | Ok(()) 228 | } 229 | } 230 | 231 | #[cfg(feature = "graphics")] 232 | impl OriginDimensions for GraphicsMode 233 | where 234 | DI: DisplayInterface, 235 | { 236 | fn size(&self) -> Size { 237 | let (w, h) = self.get_dimensions(); 238 | 239 | Size::new(w.into(), h.into()) 240 | } 241 | } 242 | -------------------------------------------------------------------------------- /src/mode/mod.rs: -------------------------------------------------------------------------------- 1 | //! Operating modes for the sh1106 2 | //! 3 | //! This driver can be used in different modes. A mode defines how the driver will behave, and what 4 | //! methods it exposes. Look at the modes below for more information on what they expose. 5 | 6 | pub mod displaymode; 7 | pub mod graphics; 8 | pub mod raw; 9 | 10 | pub use self::{graphics::GraphicsMode, raw::RawMode}; 11 | -------------------------------------------------------------------------------- /src/mode/raw.rs: -------------------------------------------------------------------------------- 1 | //! Raw mode for coercion into richer driver types 2 | //! 3 | //! A display driver instance without high level functionality used as a return type from the 4 | //! builder. Used as a source to coerce the driver into richer modes like 5 | //! [`GraphicsMode`](../graphics/index.html). 6 | 7 | use crate::{ 8 | interface::DisplayInterface, mode::displaymode::DisplayModeTrait, properties::DisplayProperties, 9 | }; 10 | 11 | /// Raw display mode 12 | pub struct RawMode 13 | where 14 | DI: DisplayInterface, 15 | { 16 | properties: DisplayProperties, 17 | } 18 | 19 | impl DisplayModeTrait for RawMode 20 | where 21 | DI: DisplayInterface, 22 | { 23 | /// Create new RawMode instance 24 | fn new(properties: DisplayProperties) -> Self { 25 | RawMode { properties } 26 | } 27 | 28 | /// Release all resources used by RawMode 29 | fn release(self) -> DisplayProperties { 30 | self.properties 31 | } 32 | } 33 | 34 | impl RawMode { 35 | /// Create a new raw display mode 36 | pub fn new(properties: DisplayProperties) -> Self { 37 | RawMode { properties } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/prelude.rs: -------------------------------------------------------------------------------- 1 | //! Crate prelude 2 | 3 | pub use super::{ 4 | displayrotation::DisplayRotation, 5 | displaysize::DisplaySize, 6 | interface::{I2cInterface, SpiInterface}, 7 | mode::GraphicsMode, 8 | }; 9 | -------------------------------------------------------------------------------- /src/properties.rs: -------------------------------------------------------------------------------- 1 | //! Container to store and set display properties 2 | 3 | use crate::{ 4 | command::{Command, VcomhLevel}, 5 | displayrotation::DisplayRotation, 6 | displaysize::DisplaySize, 7 | interface::DisplayInterface, 8 | }; 9 | 10 | /// Display properties struct 11 | pub struct DisplayProperties { 12 | iface: DI, 13 | display_size: DisplaySize, 14 | display_rotation: DisplayRotation, 15 | draw_area_start: (u8, u8), 16 | draw_area_end: (u8, u8), 17 | draw_column: u8, 18 | draw_row: u8, 19 | } 20 | 21 | impl DisplayProperties 22 | where 23 | DI: DisplayInterface, 24 | { 25 | /// Create new DisplayProperties instance 26 | pub fn new( 27 | iface: DI, 28 | display_size: DisplaySize, 29 | display_rotation: DisplayRotation, 30 | ) -> DisplayProperties { 31 | DisplayProperties { 32 | iface, 33 | display_size, 34 | display_rotation, 35 | draw_area_start: (0, 0), 36 | draw_area_end: (0, 0), 37 | draw_column: 0, 38 | draw_row: 0, 39 | } 40 | } 41 | 42 | /// Initialise the display in column mode (i.e. a byte walks down a column of 8 pixels) with 43 | /// column 0 on the left and column _(display_width - 1)_ on the right. 44 | pub fn init_column_mode(&mut self) -> Result<(), DI::Error> { 45 | self.iface.init()?; 46 | // TODO: Break up into nice bits so display modes can pick whathever they need 47 | let (_, display_height) = self.display_size.dimensions(); 48 | let display_rotation = self.display_rotation; 49 | 50 | Command::DisplayOn(false).send(&mut self.iface)?; 51 | Command::DisplayClockDiv(0x8, 0x0).send(&mut self.iface)?; 52 | Command::Multiplex(display_height - 1).send(&mut self.iface)?; 53 | Command::DisplayOffset(0).send(&mut self.iface)?; 54 | Command::StartLine(0).send(&mut self.iface)?; 55 | // TODO: Ability to turn charge pump on/off 56 | // Display must be off when performing this command 57 | Command::ChargePump(true).send(&mut self.iface)?; 58 | 59 | self.set_rotation(display_rotation)?; 60 | 61 | match self.display_size { 62 | DisplaySize::Display128x32 => Command::ComPinConfig(false).send(&mut self.iface), 63 | DisplaySize::Display128x64 64 | | DisplaySize::Display128x64NoOffset 65 | | DisplaySize::Display132x64 => Command::ComPinConfig(true).send(&mut self.iface), 66 | }?; 67 | 68 | Command::Contrast(0x80).send(&mut self.iface)?; 69 | Command::PreChargePeriod(0x1, 0xF).send(&mut self.iface)?; 70 | Command::VcomhDeselect(VcomhLevel::Auto).send(&mut self.iface)?; 71 | Command::AllOn(false).send(&mut self.iface)?; 72 | Command::Invert(false).send(&mut self.iface)?; 73 | Command::DisplayOn(true).send(&mut self.iface)?; 74 | 75 | Ok(()) 76 | } 77 | 78 | /// Set the position in the framebuffer of the display where any sent data should be 79 | /// drawn. This method can be used for changing the affected area on the screen as well 80 | /// as (re-)setting the start point of the next `draw` call. 81 | pub fn set_draw_area(&mut self, start: (u8, u8), end: (u8, u8)) -> Result<(), DI::Error> { 82 | self.draw_area_start = start; 83 | self.draw_area_end = end; 84 | self.draw_column = start.0; 85 | self.draw_row = start.1; 86 | 87 | self.send_draw_address() 88 | } 89 | 90 | /// Send the data to the display for drawing at the current position in the framebuffer 91 | /// and advance the position accordingly. Cf. `set_draw_area` to modify the affected area by 92 | /// this method. 93 | pub fn draw(&mut self, mut buffer: &[u8]) -> Result<(), DI::Error> { 94 | while !buffer.is_empty() { 95 | let count = self.draw_area_end.0 - self.draw_column; 96 | self.iface.send_data(&buffer[..count as usize])?; 97 | self.draw_column += count; 98 | 99 | if self.draw_column >= self.draw_area_end.0 { 100 | self.draw_column = self.draw_area_start.0; 101 | 102 | self.draw_row += 8; 103 | if self.draw_row >= self.draw_area_end.1 { 104 | self.draw_row = self.draw_area_start.1; 105 | } 106 | 107 | self.send_draw_address()?; 108 | } 109 | 110 | buffer = &buffer[count as usize..]; 111 | } 112 | 113 | Ok(()) 114 | } 115 | 116 | fn send_draw_address(&mut self) -> Result<(), DI::Error> { 117 | Command::PageAddress(self.draw_row.into()).send(&mut self.iface)?; 118 | Command::ColumnAddressLow(0xF & self.draw_column).send(&mut self.iface)?; 119 | Command::ColumnAddressHigh(0xF & (self.draw_column >> 4)).send(&mut self.iface) 120 | } 121 | 122 | /// Get the configured display size 123 | pub fn get_size(&self) -> DisplaySize { 124 | self.display_size 125 | } 126 | 127 | /// Get display dimensions, taking into account the current rotation of the display 128 | pub fn get_dimensions(&self) -> (u8, u8) { 129 | let (w, h) = self.display_size.dimensions(); 130 | 131 | match self.display_rotation { 132 | DisplayRotation::Rotate0 | DisplayRotation::Rotate180 => (w, h), 133 | DisplayRotation::Rotate90 | DisplayRotation::Rotate270 => (h, w), 134 | } 135 | } 136 | 137 | /// Get the display rotation 138 | pub fn get_rotation(&self) -> DisplayRotation { 139 | self.display_rotation 140 | } 141 | 142 | /// Set the display rotation 143 | pub fn set_rotation(&mut self, display_rotation: DisplayRotation) -> Result<(), DI::Error> { 144 | self.display_rotation = display_rotation; 145 | 146 | match display_rotation { 147 | DisplayRotation::Rotate0 => { 148 | Command::SegmentRemap(true).send(&mut self.iface)?; 149 | Command::ReverseComDir(true).send(&mut self.iface) 150 | } 151 | DisplayRotation::Rotate90 => { 152 | Command::SegmentRemap(false).send(&mut self.iface)?; 153 | Command::ReverseComDir(true).send(&mut self.iface) 154 | } 155 | DisplayRotation::Rotate180 => { 156 | Command::SegmentRemap(false).send(&mut self.iface)?; 157 | Command::ReverseComDir(false).send(&mut self.iface) 158 | } 159 | DisplayRotation::Rotate270 => { 160 | Command::SegmentRemap(true).send(&mut self.iface)?; 161 | Command::ReverseComDir(false).send(&mut self.iface) 162 | } 163 | } 164 | } 165 | 166 | /// Set the display contrast 167 | pub fn set_contrast(&mut self, contrast: u8) -> Result<(), DI::Error> { 168 | Command::Contrast(contrast).send(&mut self.iface) 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /src/test_helpers.rs: -------------------------------------------------------------------------------- 1 | //! Helpers for use in examples and tests 2 | 3 | use embedded_hal::{ 4 | blocking::{ 5 | i2c, 6 | spi::{self, Transfer}, 7 | }, 8 | digital::v2::OutputPin, 9 | }; 10 | 11 | #[allow(dead_code)] 12 | #[derive(Debug, Clone, Copy)] 13 | pub struct SpiStub; 14 | 15 | impl spi::Write for SpiStub { 16 | type Error = (); 17 | 18 | fn write(&mut self, _buf: &[u8]) -> Result<(), ()> { 19 | Ok(()) 20 | } 21 | } 22 | 23 | impl Transfer for SpiStub { 24 | type Error = (); 25 | 26 | fn transfer<'a>(&mut self, buf: &'a mut [u8]) -> Result<&'a [u8], ()> { 27 | Ok(buf) 28 | } 29 | } 30 | 31 | #[allow(dead_code)] 32 | #[derive(Debug, Clone, Copy)] 33 | pub struct PinStub; 34 | 35 | impl OutputPin for PinStub { 36 | type Error = (); 37 | 38 | fn set_high(&mut self) -> Result<(), ()> { 39 | Ok(()) 40 | } 41 | 42 | fn set_low(&mut self) -> Result<(), ()> { 43 | Ok(()) 44 | } 45 | } 46 | 47 | #[allow(dead_code)] 48 | #[derive(Debug, Clone, Copy)] 49 | pub struct I2cStub; 50 | 51 | impl i2c::Write for I2cStub { 52 | type Error = (); 53 | 54 | fn write(&mut self, _addr: u8, _buf: &[u8]) -> Result<(), ()> { 55 | Ok(()) 56 | } 57 | } 58 | --------------------------------------------------------------------------------