├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples └── basic.rs └── src ├── example_generated.rs ├── lib.rs └── mock_hal.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | 5 | /cruft 6 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "keypad" 3 | version = "0.2.2" 4 | authors = ["e-matteson "] 5 | license = "MIT OR Apache-2.0" 6 | categories = ["embedded", "hardware-support", "no-std"] 7 | keywords = ["embedded-hal-driver", "keyboard"] 8 | description = "Platform-agnostic driver for keypad matrix circuits" 9 | homepage = "https://github.com/e-matteson/keypad" 10 | repository = "https://github.com/e-matteson/keypad" 11 | documentation = "https://docs.rs/keypad" 12 | readme = "README.md" 13 | edition = "2021" 14 | rust-version = "1.56" 15 | 16 | [package.metadata.docs.rs] 17 | features = ["example_generated"] 18 | rustdoc-args = ["--cfg", "docs_rs_workaround"] 19 | 20 | [dependencies.embedded-hal] 21 | features = ["unproven"] 22 | version = "0.2.7" 23 | 24 | [features] 25 | example_generated = [] 26 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2022 e-matteson 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 | [![Latest version](https://img.shields.io/crates/v/keypad.svg)](https://crates.io/crates/keypad) 2 | [![Documentation](https://docs.rs/keypad/badge.svg)](https://docs.rs/keypad) 3 | 4 | # keypad 5 | 6 | **Platform-agnostic driver for keypad matrix circuits** 7 | 8 | This driver lets you read the state of any key in a keypad matrix as if it 9 | was connected to a single input pin. It supports keypads of any size, and any 10 | embedded platform that implements the Rust 11 | [embedded-hal](https://crates.io/crates/embedded-hal) traits. 12 | 13 | ### Motivation 14 | 15 | The simplest way to read keypresses with a microcontroller is to connect 16 | each key to one input pin. However, that won't work if you have more keys 17 | than available pins. One solution is to use a keypad matrix circuit that 18 | lets you read from N*M keys using only N+M pins. 19 | 20 | ![matrix](https://raw.githubusercontent.com/e-matteson/keypad/58d087473246cdbf232b2831f9fc18c0a7a29fc7/matrix_schem.png) 21 | 22 | In this circuit, each row is an input pin with a pullup resistor, and each 23 | column is an open-drain output pin. You read the state of a particular key by 24 | driving its column pin low and reading its row pin. 25 | 26 | A downside of this approach is that it increases code complexity. Instead of 27 | reading a single input pin to check if a key is pressed, you need to 28 | actively scan the matrix by driving a column low, reading a row, and setting 29 | the column high/floating again. 30 | 31 | The purpose of this driver is to use the `embedded-hal` traits to hide that 32 | complexity. It does this by giving you a set of virtual `KeyInput` pins, each 33 | of which represent one key in your keypad matrix. Because they implement the 34 | `InputPin` trait, you can treat each one like a single input pin, without 35 | worrying about the matrix-scanning that happens under the hood. 36 | 37 | This approach was inspired by the 38 | [shift-register-driver](https://github.com/JoshMcguigan/shift-register-driver) 39 | crate, which uses virtual output pins to control a shift register. 40 | 41 | ### Limitations 42 | 43 | - Reading the key state is not reentrant. 44 | 45 | - This is not optimized for scanning through the entire keypad as quickly as 46 | possible. That's a tradeoff that comes from treating each key 47 | as an independent input. 48 | 49 | 50 | ### Example 51 | 52 | This example uses mock types that implement the `embeddded-hal` traits 53 | without using any real hardware. It will compile and run on your host 54 | computer, but it won't do anything interesting because there are no real 55 | buttons to press. 56 | 57 | For an example that runs on an actual microcontroller, see 58 | [keypad-bluepill-example](https://github.com/e-matteson/keypad-bluepill-example). 59 | 60 | ```rust 61 | use core::convert::Infallible; 62 | use embedded_hal::digital::v2::InputPin; 63 | use keypad::mock_hal::{self, GpioExt, Input, OpenDrain, Output, PullUp, GPIOA}; 64 | use keypad::{keypad_new, keypad_struct}; 65 | 66 | // Define the struct that represents your keypad matrix circuit, 67 | // picking the row and column pin numbers. 68 | keypad_struct! { 69 | pub struct ExampleKeypad { 70 | rows: ( 71 | mock_hal::gpioa::PA0>, 72 | mock_hal::gpioa::PA1>, 73 | mock_hal::gpioa::PA2>, 74 | mock_hal::gpioa::PA3>, 75 | ), 76 | columns: ( 77 | mock_hal::gpioa::PA4>, 78 | mock_hal::gpioa::PA5>, 79 | mock_hal::gpioa::PA6>, 80 | mock_hal::gpioa::PA7>, 81 | mock_hal::gpioa::PA8>, 82 | ), 83 | } 84 | } 85 | 86 | fn main() { 87 | // Get access to (mock) general-purpose input/output pins. 88 | let pins = GPIOA::split(); 89 | 90 | // Create an instance of the keypad struct you defined above. 91 | let keypad = keypad_new!(ExampleKeypad { 92 | rows: ( 93 | pins.pa0.into_pull_up_input(), 94 | pins.pa1.into_pull_up_input(), 95 | pins.pa2.into_pull_up_input(), 96 | pins.pa3.into_pull_up_input(), 97 | ), 98 | columns: ( 99 | pins.pa4.into_open_drain_output(), 100 | pins.pa5.into_open_drain_output(), 101 | pins.pa6.into_open_drain_output(), 102 | pins.pa7.into_open_drain_output(), 103 | pins.pa8.into_open_drain_output(), 104 | ), 105 | }); 106 | 107 | // Create a 2d array of virtual `KeypadInput` pins, each representing 1 key 108 | // in the matrix. They implement the `InputPin` trait and can (mostly) be 109 | // used just like any other embedded-hal input pins. 110 | let keys = keypad.decompose(); 111 | 112 | let first_key = &keys[0][0]; 113 | println!("Is first key pressed? {:?}\n", first_key.is_low()); 114 | 115 | // Print a table of which keys are pressed. 116 | for (row_index, row) in keys.iter().enumerate() { 117 | print!("row {}: ", row_index); 118 | for key in row.iter() { 119 | let is_pressed = if key.is_low().unwrap() { 1 } else { 0 }; 120 | print!(" {} ", is_pressed); 121 | } 122 | println!(); 123 | } 124 | 125 | // Give up ownership of the row and column pins. 126 | let ((_r0, _r1, _r2, _r3), (_c0, _c1, _c2, _c3, _c4)) = keypad.release(); 127 | } 128 | ``` 129 | 130 | 131 | 132 | ### License 133 | 134 | Licensed under either of 135 | 136 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or 137 | http://www.apache.org/licenses/LICENSE-2.0) 138 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 139 | 140 | at your option. 141 | -------------------------------------------------------------------------------- /examples/basic.rs: -------------------------------------------------------------------------------- 1 | //! An example of how to use the macros in the `keypad` driver crate. 2 | //! 3 | //! This uses mock types that implement the `embeddded-hal` traits without using 4 | //! any real hardware. It will compile and run on your host computer, but it 5 | //! won't do anything interesting because there are no real buttons to press. 6 | 7 | use core::convert::Infallible; 8 | use embedded_hal::digital::v2::InputPin; 9 | use keypad::mock_hal::{self, GpioExt, Input, OpenDrain, Output, PullUp, GPIOA}; 10 | use keypad::{keypad_new, keypad_struct}; 11 | 12 | // Define the struct that represents your keypad matrix. Give the specific pins 13 | // that will be used for the rows and columns of your matrix - each pin number 14 | // has a unique type. Rows must be input pins, and columns must be output 15 | // pins. You can select the modes (PullUp/Floating/OpenDrain/PushPull) to suit 16 | // your circuit. 17 | keypad_struct! { 18 | pub struct ExampleKeypad { 19 | rows: ( 20 | mock_hal::gpioa::PA0>, 21 | mock_hal::gpioa::PA1>, 22 | mock_hal::gpioa::PA2>, 23 | mock_hal::gpioa::PA3>, 24 | ), 25 | columns: ( 26 | mock_hal::gpioa::PA4>, 27 | mock_hal::gpioa::PA5>, 28 | mock_hal::gpioa::PA6>, 29 | mock_hal::gpioa::PA7>, 30 | mock_hal::gpioa::PA8>, 31 | ), 32 | } 33 | } 34 | 35 | fn main() { 36 | // Get access to (mock) general-purpose input/output pins. 37 | let pins = GPIOA::split(); 38 | 39 | // Create an instance of the keypad struct you defined above. 40 | let keypad = keypad_new!(ExampleKeypad { 41 | rows: ( 42 | pins.pa0.into_pull_up_input(), 43 | pins.pa1.into_pull_up_input(), 44 | pins.pa2.into_pull_up_input(), 45 | pins.pa3.into_pull_up_input(), 46 | ), 47 | columns: ( 48 | pins.pa4.into_open_drain_output(), 49 | pins.pa5.into_open_drain_output(), 50 | pins.pa6.into_open_drain_output(), 51 | pins.pa7.into_open_drain_output(), 52 | pins.pa8.into_open_drain_output(), 53 | ), 54 | }); 55 | 56 | // Create a 2d array of virtual `KeypadInput` pins, each representing 1 key in the 57 | // matrix. They implement the `InputPin` trait and can (mostly) be used 58 | // just like any other embedded-hal input pins. 59 | let keys = keypad.decompose(); 60 | 61 | let first_key = &keys[0][0]; 62 | println!("Is first key pressed? {:?}\n", first_key.is_low()); 63 | 64 | // Print a table of which keys are pressed. This is a boring example because 65 | // we have no way to press the mock keys and they'll always stay unpressed. 66 | 67 | for (row_index, row) in keys.iter().enumerate() { 68 | print!("row {}: ", row_index); 69 | for key in row.iter() { 70 | let is_pressed = if key.is_low().unwrap() { 1 } else { 0 }; 71 | print!(" {} ", is_pressed); 72 | } 73 | println!(); 74 | } 75 | 76 | // Give up ownership of the row and column pins. 77 | let ((_r0, _r1, _r2, _r3), (_c0, _c1, _c2, _c3, _c4)) = keypad.release(); 78 | } 79 | -------------------------------------------------------------------------------- /src/example_generated.rs: -------------------------------------------------------------------------------- 1 | //! An example of a struct generated by the `keypad_struct!()` macro. 2 | 3 | use crate::mock_hal::{self, Input, OpenDrain, Output, PullUp}; 4 | use core::convert::Infallible; 5 | 6 | keypad_struct! { 7 | #[doc= "Example output of `keypad_struct!()`- for documentation purposes only! \n\nYou shouldn't try to use `ExampleKeypad` outside of this crate.\n\nThis struct is the result of this macro invocation:\n```\nuse mock_hal::{self, Input, OpenDrain, Output, PullUp};\nuse core::convert::Infallible;\n\nkeypad_struct!{\n pub struct ExampleKeypad {\n rows: (\n mock_hal::gpioa::PA0>,\n mock_hal::gpioa::PA1>,\n mock_hal::gpioa::PA2>,\n mock_hal::gpioa::PA3>,\n ),\n columns: (\n mock_hal::gpioa::PA4>,\n mock_hal::gpioa::PA5>,\n mock_hal::gpioa::PA6>,\n mock_hal::gpioa::PA7>,\n mock_hal::gpioa::PA8>,\n ),\n }\n}\n```"] 8 | pub struct ExampleKeypad { 9 | rows: ( 10 | mock_hal::gpioa::PA0>, 11 | mock_hal::gpioa::PA1>, 12 | mock_hal::gpioa::PA2>, 13 | mock_hal::gpioa::PA3>, 14 | ), 15 | columns: ( 16 | mock_hal::gpioa::PA4>, 17 | mock_hal::gpioa::PA5>, 18 | mock_hal::gpioa::PA6>, 19 | mock_hal::gpioa::PA7>, 20 | mock_hal::gpioa::PA8>, 21 | ), 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! **Platform-agnostic driver for keypad matrix circuits** 2 | //! 3 | //! This driver lets you read the state of any key in a keypad matrix as if it 4 | //! was connected to a single input pin. It supports keypads of any size, and any 5 | //! embedded platform that implements the Rust 6 | //! [embedded-hal](https://crates.io/crates/embedded-hal) traits. 7 | //! 8 | //! ## Motivation 9 | //! 10 | //! The simplest way to read keypresses with a microcontroller is to connect 11 | //! each key to one input pin. However, that won't work if you have more keys 12 | //! than available pins. One solution is to use a keypad matrix circuit that 13 | //! lets you read from N*M keys using only N+M pins. 14 | //! 15 | //! ![matrix](https://raw.githubusercontent.com/e-matteson/keypad/58d087473246cdbf232b2831f9fc18c0a7a29fc7/matrix_schem.png) 16 | //! 17 | //! In this circuit, each row is an input pin with a pullup resistor, and each 18 | //! column is an open-drain output pin. You read the state of a particular key by 19 | //! driving its column pin low and reading its row pin. 20 | //! 21 | //! A downside of this approach is that it increases code complexity. Instead of 22 | //! reading a single input pin to check if a key is pressed, you need to 23 | //! actively scan the matrix by driving a column low, reading a row, and setting 24 | //! the column high/floating again. 25 | //! 26 | //! The purpose of this driver is to use the `embedded-hal` traits to hide that 27 | //! complexity. It does this by giving you a set of virtual `KeyInput` pins, each 28 | //! of which represent one key in your keypad matrix. Because they implement the 29 | //! `InputPin` trait, you can treat each one like a single input pin, without 30 | //! worrying about the matrix-scanning that happens under the hood. 31 | //! 32 | //! This approach was inspired by the 33 | //! [shift-register-driver](https://github.com/JoshMcguigan/shift-register-driver) 34 | //! crate, which uses virtual output pins to control a shift register. 35 | //! 36 | //! ## Limitations 37 | //! 38 | //! - Reading the key state is not reentrant. 39 | //! 40 | //! - This is not optimized for scanning through the entire keypad as quickly as 41 | //! possible. That's a tradeoff that comes from treating each key 42 | //! as an independent input. 43 | //! 44 | //! 45 | //! ## Example 46 | //! 47 | //! This example uses mock types that implement the `embeddded-hal` traits 48 | //! without using any real hardware. It will compile and run on your host 49 | //! computer, but it won't do anything interesting because there are no real 50 | //! buttons to press. 51 | //! 52 | //! For an example that runs on an actual microcontroller, see 53 | //! [keypad-bluepill-example](https://github.com/e-matteson/keypad-bluepill-example). 54 | //! 55 | //! ``` 56 | //! # #![cfg_attr(docs_rs_workaround, feature(macro_vis_matcher))] 57 | //! #[macro_use] 58 | //! extern crate keypad; 59 | //! 60 | //! use core::convert::Infallible; 61 | //! use keypad::embedded_hal::digital::v2::InputPin; 62 | //! use keypad::mock_hal::{self, GpioExt, Input, OpenDrain, Output, PullUp, GPIOA}; 63 | //! 64 | //! // Define the struct that represents your keypad matrix circuit, 65 | //! // picking the row and column pin numbers. 66 | //! keypad_struct!{ 67 | //! pub struct ExampleKeypad{ 68 | //! rows: ( 69 | //! mock_hal::gpioa::PA0>, 70 | //! mock_hal::gpioa::PA1>, 71 | //! mock_hal::gpioa::PA2>, 72 | //! mock_hal::gpioa::PA3>, 73 | //! ), 74 | //! columns: ( 75 | //! mock_hal::gpioa::PA4>, 76 | //! mock_hal::gpioa::PA5>, 77 | //! mock_hal::gpioa::PA6>, 78 | //! mock_hal::gpioa::PA7>, 79 | //! mock_hal::gpioa::PA8>, 80 | //! ), 81 | //! } 82 | //! } 83 | //! 84 | //! fn main() { 85 | //! let pins = GPIOA::split(); 86 | //! 87 | //! // Create an instance of the keypad struct you defined above. 88 | //! let keypad = keypad_new!(ExampleKeypad { 89 | //! rows: ( 90 | //! pins.pa0.into_pull_up_input(), 91 | //! pins.pa1.into_pull_up_input(), 92 | //! pins.pa2.into_pull_up_input(), 93 | //! pins.pa3.into_pull_up_input(), 94 | //! ), 95 | //! columns: ( 96 | //! pins.pa4.into_open_drain_output(), 97 | //! pins.pa5.into_open_drain_output(), 98 | //! pins.pa6.into_open_drain_output(), 99 | //! pins.pa7.into_open_drain_output(), 100 | //! pins.pa8.into_open_drain_output(), 101 | //! ), 102 | //! }); 103 | //! 104 | //! // Create a 2d array of virtual `KeypadInput` pins, each 105 | //! // representing 1 key in the matrix. They implement the 106 | //! // `InputPin` trait and can be used like other embedded-hal 107 | //! // input pins. 108 | //! let keys = keypad.decompose(); 109 | //! 110 | //! let first_key = &keys[0][0]; 111 | //! println!("Is first key pressed? {}\n", first_key.is_low().unwrap()); 112 | //! 113 | //! // Print a table showing whether each key is pressed. 114 | //! 115 | //! for (row_index, row) in keys.iter().enumerate() { 116 | //! print!("row {}: ", row_index); 117 | //! for key in row.iter() { 118 | //! let is_pressed = if key.is_low().unwrap() { 1 } else { 0 }; 119 | //! print!(" {} ", is_pressed); 120 | //! } 121 | //! println!(); 122 | //! } 123 | //! 124 | //! // Give up ownership of the row and column pins. 125 | //! let ((_r0, _r1, _r2, _r3), (_c0, _c1, _c2, _c3, _c4)) = keypad.release(); 126 | //! } 127 | //! ``` 128 | //! 129 | #![no_std] 130 | #![warn(missing_docs)] 131 | // Workaround needed as long as docs.rs is using rustc <1.30 132 | #![cfg_attr(docs_rs_workaround, feature(macro_vis_matcher))] 133 | 134 | /// Re-export, so the macros and the user can import the InputPin and OutputPin 135 | /// traits from here without requiring `extern crate embedded_hal` downstream. 136 | pub extern crate embedded_hal; 137 | 138 | // Re-export libcore using an alias so that the macros can work without 139 | // requiring `extern crate core` downstream. 140 | #[doc(hidden)] 141 | pub extern crate core as _core; 142 | 143 | pub mod mock_hal; 144 | 145 | use core::cell::RefCell; 146 | use embedded_hal::digital::v2::{InputPin, OutputPin}; 147 | 148 | /// A virtual `embedded-hal` input pin representing one key of the keypad. 149 | /// 150 | /// A `KeypadInput` stores references to one row and one column pin. When you 151 | /// read from it with `.is_low()` or `.is_high()`, it secretly sets the column 152 | /// pin low, reads from the row pin, and then sets the column pin high again. 153 | /// The column pin is actually stored inside a `RefCell` in the keypad struct, 154 | /// so that multiple `KeypadInput`s can mutate the column pin's state as needed, 155 | /// even though they only have a shared/immutable reference to it. 156 | /// 157 | /// This has several implications. 158 | /// 159 | /// 1) Reading from `KeypadInput`s is not reentrant. If we were in the middle 160 | /// of reading a `KeypadInput` and entered an interrupt service routine that 161 | /// read any `KeypadInput` of the same keypad, we might read an incorrect value 162 | /// or cause a `panic`. 163 | /// 164 | /// 2) Reading from a `KeypadInput` is slower than reading from a real input 165 | /// pin, because it needs to change the output pin state twice for every read. 166 | pub struct KeypadInput<'a, E> { 167 | row: &'a dyn InputPin, 168 | col: &'a RefCell>, 169 | } 170 | 171 | impl<'a, E> KeypadInput<'a, E> { 172 | /// Create a new `KeypadInput`. For use in macros. 173 | pub fn new( 174 | row: &'a dyn InputPin, 175 | col: &'a RefCell>, 176 | ) -> Self { 177 | Self { row, col } 178 | } 179 | } 180 | 181 | impl<'a, E> InputPin for KeypadInput<'a, E> { 182 | type Error = E; 183 | /// Read the state of the key at this row and column. Not reentrant. 184 | fn is_high(&self) -> Result { 185 | Ok(!self.is_low()?) 186 | } 187 | 188 | /// Read the state of the key at this row and column. Not reentrant. 189 | fn is_low(&self) -> Result { 190 | self.col.borrow_mut().set_low()?; 191 | let out = self.row.is_low()?; 192 | self.col.borrow_mut().set_high()?; 193 | Ok(out) 194 | } 195 | } 196 | 197 | /// Define a new struct representing your keypad matrix circuit. 198 | /// 199 | /// Every pin has a unique type, depending on its pin number and its current 200 | /// mode. This struct is where you specify which pin types will be used in the 201 | /// rows and columns of the keypad matrix. All the row pins must implement the 202 | /// `InputPin` trait, and the column pins must implement the `OutputPin` trait. 203 | /// The associated `Error` type of the `InputPin` and `OutputPin` traits must be 204 | /// the same for every row and column pin, and you must specify it after your 205 | /// struct name with `` 206 | /// 207 | /// You can specify the visibility of the struct (eg. `pub`) as usual, and add 208 | /// doc comments using the `#[doc="..."]` attribute. 209 | /// 210 | /// Don't access or modify the struct's fields directly. Instead, use 211 | /// the methods implemented by this macro, documented here: 212 | /// [`example_generated::ExampleKeypad`](./example_generated/struct.ExampleKeypad.html) 213 | /// 214 | /// # Example 215 | /// 216 | /// ``` 217 | /// # #![cfg_attr(docs_rs_workaround, feature(macro_vis_matcher))] 218 | /// #[macro_use] 219 | /// extern crate keypad; 220 | /// 221 | /// use keypad::mock_hal::{self, Input, OpenDrain, Output, PullUp}; 222 | /// use core::convert::Infallible; 223 | /// 224 | /// keypad_struct! { 225 | /// #[doc="My super-special keypad."] 226 | /// pub struct ExampleKeypad { 227 | /// rows: ( 228 | /// mock_hal::gpioa::PA0>, 229 | /// mock_hal::gpioa::PA1>, 230 | /// mock_hal::gpioa::PA2>, 231 | /// mock_hal::gpioa::PA3>, 232 | /// ), 233 | /// columns: ( 234 | /// mock_hal::gpioa::PA4>, 235 | /// mock_hal::gpioa::PA5>, 236 | /// mock_hal::gpioa::PA6>, 237 | /// mock_hal::gpioa::PA7>, 238 | /// mock_hal::gpioa::PA8>, 239 | /// ), 240 | /// } 241 | /// } 242 | /// 243 | /// # fn main() { 244 | /// # } 245 | /// ``` 246 | /// 247 | /// # Safety 248 | /// 249 | /// This macro uses `unsafe` to create an array with uninitialized memory, which 250 | /// is then immediately initialized in a loop. This is fine as long as there is 251 | /// not a bug in how the macro calculates the dimensions of the array. 252 | 253 | // There are two reasons why this big, scary macro is necessary: 254 | // 255 | // 1) Every single pin has a unique type, and we don't know which pins will be used. We know that 256 | // they all implement a certain trait, but that doesn't help much because it doesn't tell us the 257 | // size of the type, so we can't directly stick it into the struct. If we could use dynamic 258 | // allocation, we could just store pins on the heap as boxed trait objects. But this crate needs 259 | // to work on embedded platforms without an allocator! So, we use this macro to generate a 260 | // struct containing the exact, concrete pin types the user provides. 261 | // 262 | // 2) We don't know how many pins there will be, because the keypad could have any number of rows 263 | // and columns. That makes it hard to implement `decompose()`, which needs to iterate over the 264 | // row and column pins. We can't store pins in arrays because they all have unique types, but we 265 | // can store them in tuples instead. The problem is that you can't actually iterate over a tuple, 266 | // and even indexing into arbitrary fields of a tuple using a macro is stupidly hard. The best 267 | // approach I could come up with was to repeatedly destructure the tuple with different patterns, 268 | // like this: 269 | // 270 | // let tuple = (0, 1, 2); 271 | // let array = [ 272 | // { 273 | // let (ref x, ..) = tuple; 274 | // x 275 | // }, 276 | // { 277 | // let (_, ref x, ..) = tuple; 278 | // x 279 | // }, 280 | // { 281 | // let (_, _, ref x, ..) = tuple; 282 | // x 283 | // }, 284 | // ]; 285 | // for reference in array.into_iter() { 286 | // // ... 287 | // } 288 | // 289 | // So that's how the `keypad_struct!()` macro iterates over tuples of pins. It counts the length of 290 | // the tuple (also tricky!), creates patterns with increasing numbers of underscores, and uses them 291 | // to build up a temporary array of references that it can iterate over. Luckily this code only 292 | // needs to be run once, in `decompose()`, and not every time we read from a pin. 293 | // 294 | // I can't think of any simpler design that still has a convenient API and allows the keypad struct 295 | // to own the row and column pins. If they weren't owned, the crate would be less convenient to use 296 | // but could provide a generic Keypad struct like this: 297 | // 298 | // pub struct Keypad<'a, E, const R: usize, const C: usize> { 299 | // rows: [&'a dyn InputPin; R], 300 | // columns: [&'a RefCell>; C], 301 | // } 302 | // 303 | #[macro_export] 304 | macro_rules! keypad_struct { 305 | ( 306 | $(#[$attributes:meta])* $visibility:vis struct $struct_name:ident { 307 | rows: ( $($row_type:ty),* $(,)* ), 308 | columns: ( $($col_type:ty),* $(,)* ), 309 | } 310 | ) => { 311 | compile_error!("You must specify the associated `Error` type of the row and column pins'\ 312 | `InputPin` and `OutputPin` traits.\n\ 313 | Example: `struct MyStruct { ... }`"); 314 | }; 315 | ( 316 | $(#[$attributes:meta])* $visibility:vis struct $struct_name:ident { 317 | rows: ( $($row_type:ty),* $(,)* ), 318 | columns: ( $($col_type:ty),* $(,)* ), 319 | } 320 | ) => { 321 | $(#[$attributes])* $visibility struct $struct_name { 322 | /// The input pins used for reading each row. 323 | rows: ($($row_type),* ,), 324 | /// The output pins used for scanning through each column. They're 325 | /// wrapped in RefCells so that we can change their state even if we 326 | /// only have shared/immutable reference to them. This lets us 327 | /// actively scan the matrix when reading the state of a virtual 328 | /// `KeypadInput` pin. 329 | columns: ($($crate::_core::cell::RefCell<$col_type>),* ,), 330 | } 331 | 332 | impl $struct_name { 333 | /// Get a 2d array of embedded-hal input pins, each representing one 334 | /// key in the keypad matrix. 335 | #[allow(dead_code)] 336 | $visibility fn decompose<'a>(&'a self) -> 337 | keypad_struct!( 338 | @array2d_type 339 | $crate::KeypadInput<'a, $error_type>, 340 | ($($row_type),*) 341 | ($($crate::_core::cell::RefCell<$col_type>),*) 342 | ) 343 | { 344 | 345 | let rows: [ 346 | &dyn $crate::embedded_hal::digital::v2::InputPin; 347 | keypad_struct!(@count $($row_type)*) 348 | ] 349 | = keypad_struct!(@tuple self.rows, ($($row_type),*)); 350 | 351 | let columns: [ 352 | &$crate::_core::cell::RefCell>; 353 | keypad_struct!(@count $($col_type)*) 354 | ] 355 | = keypad_struct!(@tuple self.columns, ($($col_type),*)); 356 | 357 | // Create an uninitialized 2d array of MaybeUninit. 358 | let mut out: keypad_struct!( 359 | @array2d_type 360 | $crate::_core::mem::MaybeUninit<$crate::KeypadInput<'a, $error_type>>, 361 | ($($row_type),*) 362 | ($($crate::_core::cell::RefCell<$col_type>),*) 363 | ) = unsafe { 364 | $crate::_core::mem::MaybeUninit::uninit().assume_init() 365 | }; 366 | 367 | // Initialize each element with a KeypadInput struct 368 | for r in 0..rows.len() { 369 | for c in 0..columns.len() { 370 | out[r][c].write($crate::KeypadInput::new(rows[r], columns[c])); 371 | } 372 | } 373 | // All elements are initialized. Transmute the array to the initialized type. 374 | unsafe { $crate::_core::mem::transmute::<_, _>(out) } 375 | } 376 | 377 | /// Give back ownership of the row and column pins. 378 | /// 379 | /// This consumes the keypad struct. All references to its virtual 380 | /// `KeypadInput` pins must have gone out of scope before you try to 381 | /// call `.release()`, or it will fail to compile. 382 | /// 383 | /// The column pins will be returned inside of `RefCell`s (because 384 | /// macros are hard). You can use `.into_inner()` to extract 385 | /// each column pin from its `RefCell`. 386 | #[allow(dead_code)] 387 | $visibility fn release(self) ->(($($row_type),* ,), ($($crate::_core::cell::RefCell<$col_type>),* ,)) { 388 | (self.rows, self.columns) 389 | } 390 | } 391 | }; 392 | (@array2d_type $element_type:ty, ($($row:ty),*) ($($col:ty),*) ) => { 393 | [keypad_struct!(@array1d_type $element_type, ($($col),*)) ; keypad_struct!(@count $($row)*)] 394 | }; 395 | (@array1d_type $element_type:ty, ($($col:ty),*)) => { 396 | [$element_type ; keypad_struct!(@count $($col)*)] 397 | }; 398 | (@count $($token_trees:tt)*) => { 399 | 0usize $(+ keypad_struct!(@replace $token_trees 1usize))* 400 | }; 401 | (@replace $_t:tt $sub:expr) => { 402 | $sub 403 | }; 404 | (@underscore $unused:tt) => { 405 | _ 406 | }; 407 | (@destructure_ref $tuple:expr, ($($repeat_n:ty),*)) => { 408 | { 409 | let ( 410 | $(keypad_struct!(@underscore $repeat_n),)* 411 | ref nth, ..) = $tuple; 412 | nth 413 | } 414 | }; 415 | (@tuple_helper $tuple:expr, ($head:ty), ($($result:expr),* $(,)*)) => { 416 | [ 417 | keypad_struct!(@destructure_ref $tuple, ()), 418 | $($result),* 419 | ] 420 | }; 421 | (@tuple_helper $tuple:expr, ($head:ty $(,$repeats:ty)* $(,)*), ($($result:expr),* $(,)*)) => { 422 | keypad_struct!( 423 | @tuple_helper $tuple, ($($repeats),*), 424 | ( 425 | keypad_struct!(@destructure_ref $tuple, ($($repeats),*)), 426 | $($result),* 427 | ) 428 | ) 429 | }; 430 | (@tuple $tuple:expr, ($($repeats:ty),*)) => { 431 | keypad_struct!(@tuple_helper $tuple, ($($repeats),*) , ()) 432 | }; 433 | } 434 | 435 | /// Create an instance of the struct you defined with the `keypad_struct!()` macro.. 436 | /// 437 | /// The pin numbers and modes will need to match the ones you specified with `keypad_struct!()`. 438 | /// 439 | /// ``` 440 | /// # #![cfg_attr(docs_rs_workaround, feature(macro_vis_matcher))] 441 | /// # #[macro_use] 442 | /// # extern crate keypad; 443 | /// # use core::convert::Infallible; 444 | /// # use keypad::mock_hal::{self, Input, OpenDrain, Output, PullUp}; 445 | /// # use keypad::mock_hal::{GpioExt, GPIOA}; 446 | /// # keypad_struct!{ 447 | /// # pub struct ExampleKeypad{ 448 | /// # rows: ( 449 | /// # mock_hal::gpioa::PA0>, 450 | /// # mock_hal::gpioa::PA1>, 451 | /// # mock_hal::gpioa::PA2>, 452 | /// # mock_hal::gpioa::PA3>, 453 | /// # ), 454 | /// # columns: ( 455 | /// # mock_hal::gpioa::PA4>, 456 | /// # mock_hal::gpioa::PA5>, 457 | /// # mock_hal::gpioa::PA6>, 458 | /// # mock_hal::gpioa::PA7>, 459 | /// # mock_hal::gpioa::PA8>, 460 | /// # ), 461 | /// # } 462 | /// # } 463 | /// # fn main() { 464 | /// let pins = GPIOA::split(); 465 | /// 466 | /// let keypad = keypad_new!(ExampleKeypad { 467 | /// rows: ( 468 | /// pins.pa0.into_pull_up_input(), 469 | /// pins.pa1.into_pull_up_input(), 470 | /// pins.pa2.into_pull_up_input(), 471 | /// pins.pa3.into_pull_up_input(), 472 | /// ), 473 | /// columns: ( 474 | /// pins.pa4.into_open_drain_output(), 475 | /// pins.pa5.into_open_drain_output(), 476 | /// pins.pa6.into_open_drain_output(), 477 | /// pins.pa7.into_open_drain_output(), 478 | /// pins.pa8.into_open_drain_output(), 479 | /// ), 480 | /// }); 481 | /// # } 482 | /// ``` 483 | #[macro_export] 484 | macro_rules! keypad_new { 485 | ( $struct_name:ident { 486 | rows: ( $($row_val:expr),* $(,)* ), 487 | columns: ( $($col_val:expr),* $(,)* ), 488 | }) => { 489 | $struct_name { 490 | rows: ($($row_val),* ,), 491 | columns: ($($crate::_core::cell::RefCell::new($col_val)),* ,), 492 | } 493 | }; 494 | } 495 | 496 | #[cfg(feature = "example_generated")] 497 | pub mod example_generated; 498 | -------------------------------------------------------------------------------- /src/mock_hal.rs: -------------------------------------------------------------------------------- 1 | //! Mock types that implement the `embeddded-hal` traits without using 2 | //! any real hardware. 3 | //! 4 | //! They're used for writing example code that will run on non-embedded targets. 5 | //! 6 | //! Based on the [stm32f103xx_hal](https://github.com/japaric/stm32f103xx-hal) 7 | //! implementation by Jorge Aparicio. 8 | 9 | use core::marker::PhantomData; 10 | 11 | /// The internal state of a mock input or output pin. 12 | #[derive(Debug)] 13 | enum State { 14 | High, 15 | Low, 16 | Float, 17 | } 18 | 19 | /// Input mode marker 20 | #[derive(Debug)] 21 | pub struct Input { 22 | _mode: PhantomData, 23 | } 24 | 25 | /// Floating input marker 26 | #[derive(Debug)] 27 | pub struct Floating; 28 | 29 | /// Pulled up input marker 30 | #[derive(Debug)] 31 | pub struct PullUp; 32 | 33 | /// Output mode marker 34 | #[derive(Debug)] 35 | pub struct Output { 36 | _mode: PhantomData, 37 | } 38 | 39 | /// Push/pull output marker 40 | #[derive(Debug)] 41 | pub struct PushPull; 42 | 43 | /// Open drain output marker 44 | #[derive(Debug)] 45 | pub struct OpenDrain; 46 | 47 | /// Extension trait to split a mock GPIO peripheral into independent pins 48 | pub trait GpioExt { 49 | /// The type to split the GPIO into 50 | type Parts; 51 | 52 | /// Split the GPIO block into independent pins and registers 53 | fn split() -> Self::Parts; 54 | } 55 | 56 | /// Create a whole module around the given mock GPIO port struct. Define structs 57 | /// for its pins and impl useful things. 58 | macro_rules! gpio { 59 | ($PORT:ident, $port:ident, [$( ($Pin:ident, $pin:ident, $default_mode:ty) ),+ $(,)* ]) => { 60 | /// A module containing a mock port of GPIO pins. 61 | pub mod $port { 62 | use super::{State, Input,Output, Floating, PushPull, OpenDrain, GpioExt, PullUp, $PORT}; 63 | use core::marker::PhantomData; 64 | use embedded_hal::digital::v2::{InputPin, OutputPin}; 65 | 66 | /// The pins of a mock GPIO port 67 | #[derive(Debug)] 68 | pub struct Parts { 69 | $( 70 | #[allow(missing_docs)] 71 | pub $pin: $Pin<$default_mode>, 72 | )+ 73 | } 74 | 75 | impl GpioExt for $PORT { 76 | type Parts = Parts; 77 | 78 | fn split() -> Parts { 79 | Self::Parts { 80 | $( 81 | $pin: $Pin::default(), 82 | )+ 83 | } 84 | } 85 | } 86 | 87 | $( 88 | /// A mock GPIO pin in a particular mode. 89 | #[derive(Debug)] 90 | pub struct $Pin { 91 | state: State, 92 | _mode: PhantomData, 93 | } 94 | 95 | 96 | impl Default for $Pin> { 97 | fn default() -> Self { 98 | Self { 99 | state: State::Float, 100 | _mode: PhantomData, 101 | } 102 | } 103 | } 104 | 105 | impl Default for $Pin> { 106 | fn default() -> Self { 107 | Self { 108 | state: State::High, 109 | _mode: PhantomData, 110 | } 111 | } 112 | } 113 | 114 | impl Default for $Pin> { 115 | fn default() -> Self { 116 | Self { 117 | // TODO is default state actually low? 118 | state: State::Low, 119 | _mode: PhantomData, 120 | } 121 | } 122 | } 123 | 124 | impl Default for $Pin> { 125 | fn default() -> Self { 126 | Self { 127 | state: State::Float, 128 | _mode: PhantomData, 129 | } 130 | } 131 | } 132 | 133 | impl $Pin { 134 | /// Change the mode of this mock pin to an output with low and high states. 135 | pub fn into_push_pull_output(self) -> $Pin> { 136 | $Pin::default() 137 | } 138 | 139 | /// Change the mode of this mock pin to an output with low and floating states. 140 | pub fn into_open_drain_output(self) -> $Pin> { 141 | $Pin::default() 142 | } 143 | 144 | /// Change the mode of this mock pin to a floating input. 145 | pub fn into_floating_input(self) -> $Pin> { 146 | $Pin::default() 147 | } 148 | 149 | /// Change the mode of this mock pin to an input with a pullup resistor. 150 | pub fn into_pull_up_input(self) -> $Pin> { 151 | $Pin::default() 152 | } 153 | } 154 | 155 | impl OutputPin for $Pin> { 156 | type Error = core::convert::Infallible; 157 | /// Drive the mock pin high. 158 | fn set_high(&mut self) -> Result<(), Self::Error> { 159 | Ok(self.state = State::High) 160 | } 161 | /// Drive the mock pin low. 162 | fn set_low(&mut self) -> Result<(), Self::Error> { 163 | Ok(self.state = State::Low) 164 | } 165 | } 166 | 167 | impl OutputPin for $Pin> { 168 | type Error = core::convert::Infallible; 169 | /// Leave the mock pin floating. 170 | fn set_high(&mut self) -> Result<(), Self::Error> { 171 | Ok(self.state = State::Float) 172 | } 173 | 174 | /// Drive the mock pin low. 175 | fn set_low(&mut self) -> Result<(), Self::Error> { 176 | Ok(self.state = State::Low) 177 | } 178 | } 179 | 180 | impl InputPin for $Pin> { 181 | type Error = core::convert::Infallible; 182 | /// Is the mock input pin high? Panic if it's floating. 183 | fn is_high(&self) -> Result { 184 | Ok(!self.is_low()?) 185 | } 186 | /// Is the mock input pin low? Panic if it's floating. 187 | fn is_low(&self) -> Result { 188 | match self.state { 189 | State::Low => Ok(true), 190 | State::High => Ok(false), 191 | State::Float => { 192 | panic!("Tried to read a floating input, value is non-deterministic!") 193 | } 194 | } 195 | } 196 | } 197 | )+ 198 | } 199 | }; 200 | } 201 | 202 | /// A struct representing a mock port of GPIO pins. 203 | #[derive(Debug)] 204 | pub struct GPIOA; 205 | 206 | gpio!( GPIOA, gpioa, [ 207 | (PA0, pa0, Input), 208 | (PA1, pa1, Input), 209 | (PA2, pa2, Input), 210 | (PA3, pa3, Input), 211 | (PA4, pa4, Input), 212 | (PA5, pa5, Input), 213 | (PA6, pa6, Input), 214 | (PA7, pa7, Input), 215 | (PA8, pa8, Input), 216 | (PA9, pa9, Input), 217 | (PA10, pa10, Input), 218 | (PA11, pa11, Input), 219 | (PA12, pa12, Input), 220 | (PA13, pa13, Input), 221 | (PA14, pa14, Input), 222 | (PA15, pa15, Input), 223 | ]); 224 | --------------------------------------------------------------------------------