From e94d9dcac90b4b0622f573656f32883807381145 Mon Sep 17 00:00:00 2001 From: Adam Greig Date: Sun, 15 Aug 2021 11:00:01 +0100 Subject: Initial commit. Import `registers.rs` from stm32ral. --- .gitignore | 2 + Cargo.toml | 12 ++ LICENSE-APACHE | 201 ++++++++++++++++++ LICENSE-MIT | 25 +++ README.md | 44 ++++ src/lib.rs | 628 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 912 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 README.md create mode 100644 src/lib.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..96ef6c0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..b53758a --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "ral-registers" +version = "0.1.0" +authors = ["Adam Greig "] +edition = "2018" +description = "MMIO registers abstraction with a macro API" +repository = "https://github.com/adamgreig/ral-registers" +license = "MIT OR Apache-2.0" +keywords = ["mmio", "embedded"] +categories = ["embedded", "no-std"] + +[dependencies] diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..e70a821 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2018-2021 Adam Greig + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..abdd137 --- /dev/null +++ b/README.md @@ -0,0 +1,44 @@ +# ral-registers + +[![Version](https://img.shields.io/crates/v/ral-registers.svg)](https://crates.io/crates/ral-registers) +[![Documentation](https://docs.rs/ral-registers/badge.svg)](https://docs.rs/ral-registers) +![CI](https://github.com/adamgreig/ral-registers/workflows/CI/badge.svg) +![License](https://img.shields.io/crates/l/ral-registers.svg) + +This crate contains an MMIO abstraction that uses macros to read, modify, +and write fields in registers. + +For example, several fields on a register can be updated (without changing the +other fields) using: + +```rust +// Modify some fields on GPIOA.MODER without changing others. +modify_reg!(gpio, GPIOA, MODER, MODER1: Input, MODER2: Output, MODER3: Input); + +// Check a condition on a field. +while read_reg!(gpio, GPIOA, IDR, IDR3 == High) {} + +// Read and write the entire register word value. +let port = read_reg!(gpio, GPIOA, IDR); +write_reg!(gpio, GPIOA, port); +``` + +This crate contains register code originally written in +[stm32ral](https://github.com/adamgreig/stm32ral), extracted +for easier use in other projects. + +## Licence + +Licensed under either of + +* Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) +* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +## Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..c1eca44 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,628 @@ +// Copyright 2018 Adam Greig +// See LICENSE-APACHE and LICENSE-MIT for license details. + +//! This crate contains an MMIO abstraction that uses macros to read, +//! modify, and write fields in registers. +//! +//! See the [README](https://github.com/adamgreig/ral-registers/blob/master/README.md) +//! for further details. + +#![no_std] + +use core::cell::UnsafeCell; + +/// A read-write register of type T. +/// +/// Contains one value of type T and provides volatile read/write functions to it. +/// +/// # Safety +/// This register should be used where reads and writes to this peripheral register do not +/// lead to memory unsafety. For example, it is a poor choice for a DMA target, but less +/// worrisome for a GPIO output data register. +/// +/// Access to this register must be synchronised; if multiple threads (or the main thread and an +/// interrupt service routine) are accessing it simultaneously you may encounter data races. +pub struct RWRegister { + register: UnsafeCell, +} + +impl RWRegister { + /// Reads the value of the register. + #[inline(always)] + pub fn read(&self) -> T { + unsafe { ::core::ptr::read_volatile(self.register.get()) } + } + + /// Writes a new value to the register. + #[inline(always)] + pub fn write(&self, val: T) { + unsafe { ::core::ptr::write_volatile(self.register.get(), val) } + } +} + +/// A read-write register of type T, where read/write access is unsafe. +/// +/// Contains one value of type T and provides volatile read/write functions to it. +/// +/// # Safety +/// This register should be used where reads and writes to this peripheral may invoke +/// undefined behaviour or memory unsafety. For example, any registers you write a memory +/// address into. +/// +/// Access to this register must be synchronised; if multiple threads (or the main thread and an +/// interrupt service routine) are accessing it simultaneously you may encounter data races. +pub struct UnsafeRWRegister { + register: UnsafeCell, +} + +impl UnsafeRWRegister { + /// Reads the value of the register. + /// + /// # Safety + /// Refer to [UnsafeRWRegister]'s Safety section. + #[inline(always)] + pub unsafe fn read(&self) -> T { + ::core::ptr::read_volatile(self.register.get()) + } + + /// Writes a new value to the register. + /// + /// # Safety + /// Refer to [UnsafeRWRegister]'s Safety section. + #[inline(always)] + pub unsafe fn write(&self, val: T) { + ::core::ptr::write_volatile(self.register.get(), val) + } +} + +/// A read-only register of type T. +/// +/// Contains one value of type T and provides a volatile read function to it. +/// +/// # Safety +/// This register should be used where reads and writes to this peripheral register do not +/// lead to memory unsafety. +/// +/// Access to this register must be synchronised; if multiple threads (or the main thread and an +/// interrupt service routine) are accessing it simultaneously you may encounter data races. +pub struct RORegister { + register: UnsafeCell, +} + +impl RORegister { + /// Reads the value of the register. + #[inline(always)] + pub fn read(&self) -> T { + unsafe { ::core::ptr::read_volatile(self.register.get()) } + } +} + +/// A read-only register of type T, where read access is unsafe. +/// +/// Contains one value of type T and provides a volatile read function to it. +/// +/// # Safety +/// This register should be used where reads to this peripheral may invoke +/// undefined behaviour or memory unsafety. +/// +/// Access to this register must be synchronised; if multiple threads (or the main thread and an +/// interrupt service routine) are accessing it simultaneously you may encounter data races. +pub struct UnsafeRORegister { + register: UnsafeCell, +} + +impl UnsafeRORegister { + /// Reads the value of the register. + /// + /// # Safety + /// Refer to [UnsafeRWRegister]'s Safety section. + #[inline(always)] + pub unsafe fn read(&self) -> T { + ::core::ptr::read_volatile(self.register.get()) + } +} + +/// A write-only register of type T. +/// +/// Contains one value of type T and provides a volatile write function to it. +/// +/// # Safety +/// This register should be used where writes to this peripheral register do not lead to memory +/// unsafety. +/// +/// Access to this register must be synchronised; if multiple threads (or the main thread and an +/// interrupt service routine) are accessing it simultaneously you may encounter data races. +pub struct WORegister { + register: UnsafeCell, +} + +impl WORegister { + /// Writes a new value to the register. + #[inline(always)] + pub fn write(&self, val: T) { + unsafe { ::core::ptr::write_volatile(self.register.get(), val) } + } +} + +/// A write-only register of type T, where write access is unsafe. +/// +/// Contains one value of type T and provides a volatile write function to it. +/// +/// # Safety +/// This register should be used where reads and writes to this peripheral may invoke +/// undefined behaviour or memory unsafety. +/// +/// Access to this register must be synchronised; if multiple threads (or the main thread and an +/// interrupt service routine) are accessing it simultaneously you may encounter data races. +pub struct UnsafeWORegister { + register: UnsafeCell, +} + +impl UnsafeWORegister { + /// Writes a new value to the register. + /// + /// # Safety + /// Refer to [UnsafeRWRegister]'s Safety section. + #[inline(always)] + pub unsafe fn write(&self, val: T) { + ::core::ptr::write_volatile(self.register.get(), val) + } +} + +/// Write to a RWRegister or UnsafeRWRegister. +/// +/// # Examples +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// // Safely acquire the peripheral instance (will panic if already acquired) +/// let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// +/// // Write some value to the register. +/// write_reg!(stm32ral::gpio, gpioa, ODR, 1<<3); +/// +/// // Write values to specific fields. Unspecified fields are written to 0. +/// write_reg!(stm32ral::gpio, gpioa, MODER, MODER3: Output, MODER4: Analog); +/// +/// // Unsafe access without requiring you to first `take()` the instance +/// unsafe { write_reg!(stm32ral::gpio, GPIOA, MODER, MODER3: Output, MODER4: Analog) }; +/// # } +/// ``` +/// +/// # Usage +/// Like `modify_reg!`, this macro can be used in two ways, either with a single value to write to +/// the whole register, or with multiple fields each with their own value. +/// +/// In both cases, the first arguments are: +/// * the path to the peripheral module: `stm32ral::gpio`, +/// * a reference to the instance of that peripheral: 'gpioa' (anything which dereferences to +/// `RegisterBlock`, such as `Instance`, `&Instance`, `&RegisterBlock`, or +/// `*const RegisterBlock`), +/// * the register you wish you access: `MODER` (a field on the `RegisterBlock`). +/// +/// In the single-value usage, the final argument is just the value to write: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// // Turn on PA3 (and turn everything else off). +/// write_reg!(stm32ral::gpio, gpioa, ODR, 1<<3); +/// # } +/// ``` +/// +/// Otherwise, the remaining arguments are each `Field: Value` pairs: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// // Set PA3 to Output, PA4 to Analog, and everything else to 0 (which is Input). +/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// write_reg!(stm32ral::gpio, gpioa, MODER, MODER3: 0b01, MODER4: 0b11); +/// # } +/// ``` +/// For fields with annotated values, you can also specify a named value: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// // As above, but with named values. +/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// write_reg!(stm32ral::gpio, gpioa, MODER, MODER3: Output, MODER4: Analog); +/// # } +/// ``` +/// +/// This macro expands to calling `(*$instance).$register.write(value)`, +/// where in the second usage, the value is computed as the bitwise OR of +/// each field value, which are masked and shifted appropriately for the given field. +/// The named values are brought into scope by `use $peripheral::$register::$field::*` for +/// each field. The same constants could just be specified manually: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// // As above, but being explicit about named values. +/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// write_reg!(stm32ral::gpio, gpioa, MODER, MODER3: stm32ral::gpio::MODER::MODER3::RW::Output, +/// MODER4: stm32ral::gpio::MODER::MODER4::RW::Analog); +/// # } +/// ``` +/// +/// The fully expanded form is equivalent to: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// // As above, but expanded. +/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// (*gpioa).MODER.write( +/// ((stm32ral::gpio::MODER::MODER3::RW::Output << stm32ral::gpio::MODER::MODER3::offset) +/// & stm32ral::gpio::MODER::MODER3::mask) +/// | +/// ((stm32ral::gpio::MODER::MODER4::RW::Analog << stm32ral::gpio::MODER::MODER4::offset) +/// & stm32ral::gpio::MODER::MODER4::mask) +/// ); +/// # } +/// ``` +/// +/// # Safety +/// This macro will require an unsafe function or block when used with an UnsafeRWRegister, +/// but not if used with RWRegister. +/// +/// When run in an unsafe context, peripheral instances are directly accessible without requiring +/// having called `take()` beforehand: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// unsafe { write_reg!(stm32ral::gpio, GPIOA, MODER, MODER3: Output, MODER4: Analog) }; +/// # } +/// ``` +/// This works because `GPIOA` is a `*const RegisterBlock` in the `stm32ral::gpio` module; +/// and the macro brings such constants into scope and then dereferences the provided reference. +#[macro_export] +macro_rules! write_reg { + ( $periph:path, $instance:expr, $reg:ident, $( $field:ident : $value:expr ),+ ) => {{ + #[allow(unused_imports)] + use $periph::{*}; + #[allow(unused_imports)] + (*$instance).$reg.write( + $({ use $periph::{$reg::$field::{mask, offset, W::*, RW::*}}; ($value << offset) & mask }) | * + ); + }}; + ( $periph:path, $instance:expr, $reg:ident, $value:expr ) => {{ + #[allow(unused_imports)] + use $periph::{*}; + (*$instance).$reg.write($value); + }}; +} + +/// Modify a RWRegister or UnsafeRWRegister. +/// +/// # Examples +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// // Safely acquire the peripheral instance (will panic if already acquired) +/// let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// +/// // Update the register to ensure bit 3 is set. +/// modify_reg!(stm32ral::gpio, gpioa, ODR, |reg| reg | (1<<3)); +/// +/// // Write values to specific fields. Unspecified fields are left unchanged. +/// modify_reg!(stm32ral::gpio, gpioa, MODER, MODER3: Output, MODER4: Analog); +/// +/// // Unsafe access without requiring you to first `take()` the instance +/// unsafe { modify_reg!(stm32ral::gpio, GPIOA, MODER, MODER3: Output, MODER4: Analog) }; +/// # } +/// ``` +/// +/// # Usage +/// Like `write_reg!`, this macro can be used in two ways, either with a modification of the entire +/// register, or by specifying which fields to change and what value to change them to. +/// +/// In both cases, the first arguments are: +/// * the path to the peripheral module: `stm32ral::gpio`, +/// * a reference to the instance of that peripheral: 'gpioa' (anything which dereferences to +/// `RegisterBlock`, such as `Instance`, `&Instance`, `&RegisterBlock`, or +/// `*const RegisterBlock`), +/// * the register you wish you access: `MODER` (a field on the `RegisterBlock`). +/// +/// In the whole-register usage, the final argument is a closure that accepts the current value +/// of the register and returns the new value to write: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// // Turn on PA3 without affecting anything else. +/// modify_reg!(stm32ral::gpio, gpioa, ODR, |reg| reg | (1<<3)); +/// # } +/// ``` +/// +/// Otherwise, the remaining arguments are `Field: Value` pairs: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// // Set PA3 to Output, PA4 to Analog, and leave everything else unchanged. +/// modify_reg!(stm32ral::gpio, gpioa, MODER, MODER3: 0b01, MODER4: 0b11); +/// # } +/// ``` +/// +/// For fields with annotated values, you can also specify a named value: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// // As above, but with named values. +/// modify_reg!(stm32ral::gpio, gpioa, MODER, MODER3: Output, MODER4: Analog); +/// # } +/// ``` +/// +/// This macro expands to calling `(*instance).register.write(value)`. +/// When called with a closure, `(*instance).register.read()` is called, the result +/// passed in to the closure, and the return value of the closure is used for `value`. +/// When called with `Field: Value` arguments, the current value is read and then masked +/// according to the specified fields, and then ORd with the OR of each field value, +/// each masked and shifted appropriately for the field. The named values are brought into scope +/// by `use peripheral::register::field::*` for each field. The same constants could just be +/// specified manually: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// // As above, but being explicit about named values. +/// modify_reg!(stm32ral::gpio, gpioa, MODER, MODER3: stm32ral::gpio::MODER::MODER3::RW::Output, +/// MODER4: stm32ral::gpio::MODER::MODER4::RW::Analog); +/// # } +/// ``` +/// +/// The fully expanded form is equivalent to: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// // As above, but expanded. +/// (*gpioa).MODER.write( +/// ( +/// // First read the current value... +/// (*gpioa).MODER.read() +/// // Then AND it with an appropriate mask... +/// & +/// !( stm32ral::gpio::MODER::MODER3::mask | stm32ral::gpio::MODER::MODER4::mask ) +/// ) +/// // Then OR with each field value. +/// | +/// ((stm32ral::gpio::MODER::MODER3::RW::Output << stm32ral::gpio::MODER::MODER3::offset) +/// & stm32ral::gpio::MODER::MODER3::mask) +/// | +/// ((stm32ral::gpio::MODER::MODER4::RW::Analog << stm32ral::gpio::MODER::MODER3::offset) +/// & stm32ral::gpio::MODER::MODER3::mask) +/// ); +/// # } +/// ``` +/// +/// # Safety +/// This macro will require an unsafe function or block when used with an UnsafeRWRegister, +/// but not if used with RWRegister. +/// +/// When run in an unsafe context, peripheral instances are directly accessible without requiring +/// having called `take()` beforehand: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// unsafe { modify_reg!(stm32ral::gpio, GPIOA, MODER, MODER3: Output, MODER4: Analog) }; +/// # } +/// ``` +/// This works because `GPIOA` is a `*const RegisterBlock` in the `stm32ral::gpio` module; +/// and the macro brings such constants into scope and then dereferences the provided reference. +#[macro_export] +macro_rules! modify_reg { + ( $periph:path, $instance:expr, $reg:ident, $( $field:ident : $value:expr ),+ ) => {{ + #[allow(unused_imports)] + use $periph::{*}; + #[allow(unused_imports)] + (*$instance).$reg.write( + ((*$instance).$reg.read() & !( $({ use $periph::{$reg::$field::mask}; mask }) | * )) + | $({ use $periph::{$reg::$field::{mask, offset, W::*, RW::*}}; ($value << offset) & mask }) | *); + }}; + ( $periph:path, $instance:expr, $reg:ident, $fn:expr ) => {{ + #[allow(unused_imports)] + use $periph::{*}; + (*$instance).$reg.write($fn((*$instance).$reg.read())); + }}; +} + +/// Read the value from a RORegister, RWRegister, UnsafeRORegister, or UnsafeRWRegister. +/// +/// # Examples +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// // Safely acquire the peripheral instance (will panic if already acquired) +/// let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// +/// // Read the whole register. +/// let val = read_reg!(stm32ral::gpio, gpioa, IDR); +/// +/// // Read one field from the register. +/// let val = read_reg!(stm32ral::gpio, gpioa, IDR, IDR2); +/// +/// // Read multiple fields from the register. +/// let (val1, val2, val3) = read_reg!(stm32ral::gpio, gpioa, IDR, IDR0, IDR1, IDR2); +/// +/// // Check if one field is equal to a specific value, with the field's named values in scope. +/// while read_reg!(stm32ral::gpio, gpioa, IDR, IDR2 == High) {} +/// +/// // Unsafe access without requiring you to first `take()` the instance +/// let val = unsafe { read_reg!(stm32ral::gpio, GPIOA, IDR) }; +/// # } +/// ``` +/// +/// # Usage +/// Like `write_reg!`, this macro can be used multiple ways, either reading the entire register or +/// reading a one or more fields from it and potentially performing a comparison with one field. +/// +/// In all cases, the first arguments are: +/// * the path to the peripheral module: `stm32ral::gpio`, +/// * a reference to the instance of that peripheral: 'gpioa' (anything which dereferences to +/// `RegisterBlock`, such as `Instance`, `&Instance`, `&RegisterBlock`, or +/// `*const RegisterBlock`), +/// * the register you wish to access: `IDR` (a field on the `RegisterBlock`). +/// +/// In the whole-register usage, the macro simply returns the register's value: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// // Read the entire value of GPIOA.IDR into `val`. +/// let val = read_reg!(stm32ral::gpio, gpioa, IDR); +/// # } +/// ``` +/// +/// For reading individual fields, the macro masks and shifts appropriately: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// // Read just the value of the field GPIOA.IDR2 into `val`. +/// let val = read_reg!(stm32ral::gpio, gpioa, IDR, IDR2); +/// +/// // As above, but expanded for exposition: +/// let val = ((*gpioa).IDR.read() & stm32ral::gpio::IDR::IDR2::mask) +/// >> stm32ral::gpio::IDR::IDR2::offset; +/// +/// // Read multiple fields +/// let (val1, val2) = read_reg!(stm32ral::gpio, gpioa, IDR, IDR2, IDR3); +/// +/// // As above, but expanded for exposition: +/// let (val1, val2) = { let val = (*gpioa).IDR.read(); +/// ((val & stm32ral::gpio::IDR::IDR2::mask) >> stm32ral::gpio::IDR::IDR2::offset, +/// (val & stm32ral::gpio::IDR::IDR3::mask) >> stm32ral::gpio::IDR::IDR3::offset, +/// )}; +/// # } +/// ``` +/// +/// For comparing a single field, the macro masks and shifts and then performs the comparison: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// # let rcc = stm32ral::rcc::RCC::take().unwrap(); +/// // Loop while PA2 is High. +/// while read_reg!(stm32ral::gpio, gpioa, IDR, IDR2 == High) {} +/// +/// // Only proceed if the clock is not the HSI. +/// if read_reg!(stm32ral::rcc, rcc, CFGR, SWS != HSI) { } +/// +/// // Equivalent expansion: +/// if (((*rcc).CFGR.read() & stm32ral::rcc::CFGR::SWS::mask) +/// >> stm32ral::rcc::CFGR::SWS::offset) != stm32ral::rcc::CFGR::SWS::R::HSI { } +/// # } +/// ``` +/// +/// # Safety +/// This macro will require an unsafe function or block when used with an UnsafeRWRegister or +/// UnsafeRORegister, but not if used with RWRegister, or RORegister. +/// +/// When run in an unsafe context, peripheral instances are directly accessible without requiring +/// having called `take()` beforehand: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// let val = unsafe { read_reg!(stm32ral::gpio, GPIOA, MODER) }; +/// # } +/// ``` +/// This works because `GPIOA` is a `*const RegisterBlock` in the `stm32ral::gpio` module; +/// and the macro brings such constants into scope and then dereferences the provided reference. +#[macro_export] +macro_rules! read_reg { + ( $periph:path, $instance:expr, $reg:ident, $( $field:ident ),+ ) => {{ + #[allow(unused_imports)] + use $periph::{*}; + let val = ((*$instance).$reg.read()); + ( $({ + #[allow(unused_imports)] + use $periph::{$reg::$field::{mask, offset, R::*, RW::*}}; + (val & mask) >> offset + }) , *) + }}; + ( $periph:path, $instance:expr, $reg:ident, $field:ident $($cmp:tt)* ) => {{ + #[allow(unused_imports)] + use $periph::{*}; + #[allow(unused_imports)] + use $periph::{$reg::$field::{mask, offset, R::*, RW::*}}; + (((*$instance).$reg.read() & mask) >> offset) $($cmp)* + }}; + ( $periph:path, $instance:expr, $reg:ident ) => {{ + #[allow(unused_imports)] + use $periph::{*}; + ((*$instance).$reg.read()) + }}; +} + +/// Reset a RWRegister, UnsafeRWRegister, WORegister, or UnsafeWORegister to its reset value. +/// +/// # Examples +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// // Safely acquire the peripheral instance (will panic if already acquired) +/// let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// +/// // Reset PA14 and PA15 to their reset state +/// reset_reg!(stm32ral::gpio, gpioa, GPIOA, MODER, MODER14, MODER15); +/// +/// // Reset the entire GPIOA.MODER to its reset state +/// reset_reg!(stm32ral::gpio, gpioa, GPIOA, MODER); +/// # } +/// ``` +/// +/// # Usage +/// Like `write_reg!`, this macro can be used in two ways, either resetting the entire register +/// or just resetting specific fields within in. The register or fields are written with their +/// reset values. +/// +/// In both cases, the first arguments are: +/// * the path to the peripheral module: `stm32ral::gpio`, +/// * a reference to the instance of that peripheral: 'gpioa' (anything which dereferences to +/// `RegisterBlock`, such as `Instance`, `&Instance`, `&RegisterBlock`, or +/// `*const RegisterBlock`), +/// * the module for the instance of that peripheral: `GPIOA`, +/// * the register you wish to access: `MODER` (a field on the `RegisterBlock`). +/// +/// In the whole-register usage, that's it: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// // Reset the entire GPIOA.MODER +/// reset_reg!(stm32ral::gpio, gpioa, GPIOA, MODER); +/// # } +/// ``` +/// +/// Otherwise, the remaining arguments are each field names: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap(); +/// // Reset the JTAG pins +/// reset_reg!(stm32ral::gpio, gpioa, GPIOA, MODER, MODER13, MODER14, MODER15); +/// reset_reg!(stm32ral::gpio, gpioa, GPIOB, MODER, MODER3, MODER4); +/// # } +/// ``` +/// +/// The second form is only available to RWRegister and UnsafeRWRegister, since `.read()` is +/// not available for WORegister and UnsafeWORegister. +/// +/// This macro expands to calling `(*$instance).$register.write(value)`, where +/// `value` is either the register's reset value, or the current read value of the register +/// masked appropriately and combined with the reset value for each field. +/// +/// # Safety +/// This macro will require an unsafe function or block when used with an UnsafeRWRegister or +/// UnsafeRORegister, but not if used with RWRegister or RORegister. +/// +/// When run in an unsafe context, peripheral instances are directly accessible without requiring +/// having called `take()` beforehand: +/// ```rust,no_run +/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() { +/// unsafe { reset_reg!(stm32ral::gpio, GPIOA, GPIOA, MODER) }; +/// # } +/// ``` +/// This works because `GPIOA` is a `*const RegisterBlock` in the `stm32ral::gpio` module; +/// and the macro brings such constants into scope and then dereferences the provided reference. +/// +/// Note that the second argument is a `*const` and the third is a path; despite both being written +/// `GPIOA` they are not the same thing. +#[macro_export] +macro_rules! reset_reg { + ( $periph:path, $instance:expr, $instancemod:path, $reg:ident, $( $field:ident ),+ ) => {{ + #[allow(unused_imports)] + use $periph::{*}; + use $periph::{$instancemod::{reset}}; + #[allow(unused_imports)] + (*$instance).$reg.write({ + let resetmask: u32 = $({ use $periph::{$reg::$field::mask}; mask }) | *; + ((*$instance).$reg.read() & !resetmask) | (reset.$reg & resetmask) + }); + }}; + ( $periph:path, $instance:expr, $instancemod:path, $reg:ident ) => {{ + #[allow(unused_imports)] + use $periph::{*}; + use $periph::{$instancemod::{reset}}; + (*$instance).$reg.write(reset.$reg); + }}; +} -- cgit v1.2.3