diff --git a/.github/ci/book.sh b/.github/ci/book.sh new file mode 100755 index 000000000..285cdc8fa --- /dev/null +++ b/.github/ci/book.sh @@ -0,0 +1,17 @@ +#!/bin/bash +## on push branch=main + +set -euxo pipefail + +make -C docs + +export KUBECONFIG=/ci/secrets/kubeconfig.yml +POD=$(kubectl -n embassy get po -l app=website -o jsonpath={.items[0].metadata.name}) + +mkdir -p build +mv docs/book build/book +tar -C build -cf book.tar book +kubectl exec $POD -- mkdir -p /usr/share/nginx/html +kubectl cp book.tar $POD:/usr/share/nginx/html/ +kubectl exec $POD -- find /usr/share/nginx/html +kubectl exec $POD -- tar -C /usr/share/nginx/html -xvf /usr/share/nginx/html/book.tar diff --git a/.github/ci/build-xtensa.sh b/.github/ci/build-xtensa.sh new file mode 100755 index 000000000..a13391c82 --- /dev/null +++ b/.github/ci/build-xtensa.sh @@ -0,0 +1,37 @@ +#!/bin/bash +## on push branch~=gh-readonly-queue/main/.* +## on pull_request + +set -euo pipefail + +export RUSTUP_HOME=/ci/cache/rustup +export CARGO_HOME=/ci/cache/cargo +export CARGO_TARGET_DIR=/ci/cache/target + +# needed for "dumb HTTP" transport support +# used when pointing stm32-metapac to a CI-built one. +export CARGO_NET_GIT_FETCH_WITH_CLI=true + +cargo install espup +/ci/cache/cargo/bin/espup install + +# Restore lockfiles +if [ -f /ci/cache/lockfiles.tar ]; then + echo Restoring lockfiles... + tar xf /ci/cache/lockfiles.tar +fi + +hashtime restore /ci/cache/filetime.json || true +hashtime save /ci/cache/filetime.json + +mkdir .cargo +cat > .cargo/config.toml<< EOF +[unstable] +build-std = ["alloc", "core"] +EOF + +./ci-xtensa.sh + +# Save lockfiles +echo Saving lockfiles... +find . -type f -name Cargo.lock -exec tar -cf /ci/cache/lockfiles.tar '{}' \+ diff --git a/.github/ci/build.sh b/.github/ci/build.sh index 77d2b3cab..68a7c0c34 100755 --- a/.github/ci/build.sh +++ b/.github/ci/build.sh @@ -7,7 +7,7 @@ set -euo pipefail export RUSTUP_HOME=/ci/cache/rustup export CARGO_HOME=/ci/cache/cargo export CARGO_TARGET_DIR=/ci/cache/target -if [ -f /ci/secrets/teleprobe-token.txt ]; then +if [ -f /ci/secrets/teleprobe-token.txt ]; then echo Got teleprobe token! export TELEPROBE_HOST=https://teleprobe.embassy.dev export TELEPROBE_TOKEN=$(cat /ci/secrets/teleprobe-token.txt) diff --git a/.github/ci/doc.sh b/.github/ci/doc.sh index 7112d8aaa..47babe8f5 100755 --- a/.github/ci/doc.sh +++ b/.github/ci/doc.sh @@ -38,6 +38,7 @@ docserver-builder -i ./embassy-usb -o webroot/crates/embassy-usb/git.zup docserver-builder -i ./embassy-usb-dfu -o webroot/crates/embassy-usb-dfu/git.zup docserver-builder -i ./embassy-usb-driver -o webroot/crates/embassy-usb-driver/git.zup docserver-builder -i ./embassy-usb-logger -o webroot/crates/embassy-usb-logger/git.zup +docserver-builder -i ./embassy-usb-synopsys-otg -o webroot/crates/embassy-usb-synopsys-otg/git.zup docserver-builder -i ./embassy-net -o webroot/crates/embassy-net/git.zup docserver-builder -i ./embassy-net-driver -o webroot/crates/embassy-net-driver/git.zup diff --git a/.github/ci/test-nightly.sh b/.github/ci/test-nightly.sh index d6e5dc574..a03b55e8d 100755 --- a/.github/ci/test-nightly.sh +++ b/.github/ci/test-nightly.sh @@ -9,5 +9,9 @@ export CARGO_HOME=/ci/cache/cargo export CARGO_TARGET_DIR=/ci/cache/target mv rust-toolchain-nightly.toml rust-toolchain.toml +cargo test --manifest-path ./embassy-executor/Cargo.toml +cargo test --manifest-path ./embassy-executor/Cargo.toml --features nightly + MIRIFLAGS=-Zmiri-ignore-leaks cargo miri test --manifest-path ./embassy-executor/Cargo.toml MIRIFLAGS=-Zmiri-ignore-leaks cargo miri test --manifest-path ./embassy-executor/Cargo.toml --features nightly +MIRIFLAGS=-Zmiri-ignore-leaks cargo miri test --manifest-path ./embassy-sync/Cargo.toml diff --git a/.github/ci/test.sh b/.github/ci/test.sh index 8a58939f6..0fe088bfe 100755 --- a/.github/ci/test.sh +++ b/.github/ci/test.sh @@ -8,9 +8,15 @@ export RUSTUP_HOME=/ci/cache/rustup export CARGO_HOME=/ci/cache/cargo export CARGO_TARGET_DIR=/ci/cache/target -cargo test --manifest-path ./embassy-sync/Cargo.toml -cargo test --manifest-path ./embassy-embedded-hal/Cargo.toml -cargo test --manifest-path ./embassy-hal-internal/Cargo.toml +# needed for "dumb HTTP" transport support +# used when pointing stm32-metapac to a CI-built one. +export CARGO_NET_GIT_FETCH_WITH_CLI=true + +cargo test --manifest-path ./embassy-executor/Cargo.toml +cargo test --manifest-path ./embassy-futures/Cargo.toml +cargo test --manifest-path ./embassy-sync/Cargo.toml +cargo test --manifest-path ./embassy-embedded-hal/Cargo.toml +cargo test --manifest-path ./embassy-hal-internal/Cargo.toml cargo test --manifest-path ./embassy-time/Cargo.toml --features generic-queue,mock-driver cargo test --manifest-path ./embassy-time-driver/Cargo.toml @@ -20,7 +26,8 @@ cargo test --manifest-path ./embassy-boot/Cargo.toml --features ed25519-salty cargo test --manifest-path ./embassy-nrf/Cargo.toml --no-default-features --features nrf52840,time-driver-rtc1,gpiote -cargo test --manifest-path ./embassy-rp/Cargo.toml --no-default-features --features time-driver +cargo test --manifest-path ./embassy-rp/Cargo.toml --no-default-features --features time-driver,rp2040,_test +cargo test --manifest-path ./embassy-rp/Cargo.toml --no-default-features --features time-driver,rp235xa,_test cargo test --manifest-path ./embassy-stm32/Cargo.toml --no-default-features --features stm32f429vg,exti,time-driver-any,exti cargo test --manifest-path ./embassy-stm32/Cargo.toml --no-default-features --features stm32f732ze,exti,time-driver-any,exti diff --git a/.gitignore b/.gitignore index 1c221e876..a0b5d6a70 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ Cargo.lock third_party /Cargo.toml out/ +.zed diff --git a/.vscode/settings.json b/.vscode/settings.json index 46d26562c..48d0957e6 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,5 +1,4 @@ { - "editor.formatOnSave": true, "[toml]": { "editor.formatOnSave": false }, @@ -10,21 +9,25 @@ "rust-analyzer.check.noDefaultFeatures": true, "rust-analyzer.cargo.noDefaultFeatures": true, "rust-analyzer.showUnlinkedFileNotification": false, - // uncomment the target of your chip. + // Uncomment the target of your chip. //"rust-analyzer.cargo.target": "thumbv6m-none-eabi", //"rust-analyzer.cargo.target": "thumbv7m-none-eabi", "rust-analyzer.cargo.target": "thumbv7em-none-eabi", + //"rust-analyzer.cargo.target": "thumbv7em-none-eabihf", //"rust-analyzer.cargo.target": "thumbv8m.main-none-eabihf", "rust-analyzer.cargo.features": [ - "stm32f103c8", + // Comment out these features when working on the examples. Most example crates do not have any cargo features. + "stm32f446re", "time-driver-any", "unstable-pac", "exti", + "rt", ], "rust-analyzer.linkedProjects": [ - // Uncomment ONE line for the chip you want to work on. - // This makes rust-analyzer work on the example crate and all its dependencies. "embassy-stm32/Cargo.toml", + // To work on the examples, comment the line above and all of the cargo.features lines, + // then uncomment ONE line below to select the chip you want to work on. + // This makes rust-analyzer work on the example crate and all its dependencies. // "examples/nrf52840-rtic/Cargo.toml", // "examples/nrf5340/Cargo.toml", // "examples/nrf-rtos-trace/Cargo.toml", diff --git a/LICENSE-CC-BY-SA b/LICENSE-CC-BY-SA new file mode 100644 index 000000000..a73481c4b --- /dev/null +++ b/LICENSE-CC-BY-SA @@ -0,0 +1,428 @@ +Attribution-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-ShareAlike 4.0 International Public +License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-ShareAlike 4.0 International Public License ("Public +License"). To the extent this Public License may be interpreted as a +contract, You are granted the Licensed Rights in consideration of Your +acceptance of these terms and conditions, and the Licensor grants You +such rights in consideration of benefits the Licensor receives from +making the Licensed Material available under these terms and +conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + l. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + m. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + + including for purposes of Section 3(b); and + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. + diff --git a/NOTICE.md b/NOTICE.md index 868bec08f..a50b39494 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -12,5 +12,5 @@ listed source code repository logs. This program and the accompanying materials are made available under the terms of the Apache Software License 2.0 which is available at -https://www.apache.org/licenses/LICENSE-2.0, or the MIT license which is +https://www.apache.org/licenses/LICENSE-2.0, or the MIT license which is available at https://opensource.org/licenses/MIT diff --git a/README.md b/README.md index 24347a43f..8952b0358 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,12 @@ Embassy is the next-generation framework for embedded applications. Write safe, correct and energy-efficient embedded code faster, using the Rust programming language, its async facilities, and the Embassy libraries. -## Documentation - API reference - Website - Chat +## Documentation - API reference - Website - Chat ## Rust + async ❤️ embedded The Rust programming language is blazingly fast and memory-efficient, with no runtime, garbage collector or OS. It catches a wide variety of bugs at compile time, thanks to its full memory- and thread-safety, and expressive type system. -Rust's async/await allows for unprecedently easy and efficient multitasking in embedded systems. Tasks get transformed at compile time into state machines that get run cooperatively. It requires no dynamic memory allocation, and runs on a single stack, so no per-task stack size tuning is required. It obsoletes the need for a traditional RTOS with kernel context switching, and is faster and smaller than one! +Rust's async/await allows for unprecedentedly easy and efficient multitasking in embedded systems. Tasks get transformed at compile time into state machines that get run cooperatively. It requires no dynamic memory allocation, and runs on a single stack, so no per-task stack size tuning is required. It obsoletes the need for a traditional RTOS with kernel context switching, and is faster and smaller than one! ## Batteries included @@ -18,6 +18,7 @@ Rust's async/await allows - esp-rs, for the Espressif Systems ESP32 series of chips. - Embassy HAL support for Espressif chips is being developed in the [esp-rs/esp-hal](https://github.com/esp-rs/esp-hal) repository. - Async WiFi, Bluetooth and ESP-NOW is being developed in the [esp-rs/esp-wifi](https://github.com/esp-rs/esp-wifi) repository. + - ch32-hal, for the WCH 32-bit RISC-V(CH32V) series of chips. - **Time that Just Works** - No more messing with hardware timers. embassy_time provides Instant, Duration and Timer types that are globally available and never overflow. @@ -89,7 +90,7 @@ async fn main(spawner: Spawner) { ## Examples -Examples are found in the `examples/` folder seperated by the chip manufacturer they are designed to run on. For example: +Examples are found in the `examples/` folder separated by the chip manufacturer they are designed to run on. For example: * `examples/nrf52840` run on the `nrf52840-dk` board (PCA10056) but should be easily adaptable to other nRF52 chips and boards. * `examples/nrf5340` run on the `nrf5340-dk` board (PCA10095). @@ -99,12 +100,7 @@ Examples are found in the `examples/` folder seperated by the chip manufacturer ### Running examples -- Install `probe-rs`. - -```bash -cargo install probe-rs --features cli -``` - +- Install `probe-rs` following the instructions at . - Change directory to the sample's base directory. For example: ```bash @@ -130,8 +126,8 @@ For more help getting started, see [Getting Started][1] and [Running the Example ## Developing Embassy with Rust Analyzer based editors The [Rust Analyzer](https://rust-analyzer.github.io/) is used by [Visual Studio Code](https://code.visualstudio.com/) -and others. Given the multiple targets that Embassy serves, there is no Cargo workspace file. Instead, the Rust Analyzer -must be told of the target project to work with. In the case of Visual Studio Code, +and others. Given the multiple targets that Embassy serves, there is no Cargo workspace file. Instead, the Rust Analyzer +must be told of the target project to work with. In the case of Visual Studio Code, please refer to the `.vscode/settings.json` file's `rust-analyzer.linkedProjects`setting. ## Minimum supported Rust version (MSRV) diff --git a/ci-nightly.sh b/ci-nightly.sh index 46b19c5b7..bdb364f53 100755 --- a/ci-nightly.sh +++ b/ci-nightly.sh @@ -30,4 +30,3 @@ cargo batch \ cargo build --release --manifest-path embassy-executor/Cargo.toml --target avr-unknown-gnu-atmega328 -Z build-std=core,alloc --features nightly,arch-avr,avr-device/atmega328p cargo build --release --manifest-path embassy-executor/Cargo.toml --target avr-unknown-gnu-atmega328 -Z build-std=core,alloc --features nightly,arch-avr,integrated-timers,avr-device/atmega328p - diff --git a/ci-xtensa.sh b/ci-xtensa.sh new file mode 100755 index 000000000..32d362def --- /dev/null +++ b/ci-xtensa.sh @@ -0,0 +1,39 @@ +#!/bin/bash + +set -eo pipefail + +export RUSTFLAGS=-Dwarnings +export DEFMT_LOG=trace,embassy_hal_internal=debug,embassy_net_esp_hosted=debug,cyw43=info,cyw43_pio=info,smoltcp=info +export RUSTUP_TOOLCHAIN=esp +if [[ -z "${CARGO_TARGET_DIR}" ]]; then + export CARGO_TARGET_DIR=target_ci +fi + +cargo batch \ + --- build --release --manifest-path embassy-executor/Cargo.toml --target xtensa-esp32-none-elf \ + --- build --release --manifest-path embassy-executor/Cargo.toml --target xtensa-esp32-none-elf --features log \ + --- build --release --manifest-path embassy-executor/Cargo.toml --target xtensa-esp32-none-elf --features defmt \ + --- build --release --manifest-path embassy-executor/Cargo.toml --target xtensa-esp32s2-none-elf --features defmt \ + --- build --release --manifest-path embassy-executor/Cargo.toml --target xtensa-esp32-none-elf --features defmt,arch-spin,executor-thread,integrated-timers \ + --- build --release --manifest-path embassy-executor/Cargo.toml --target xtensa-esp32s2-none-elf --features defmt,arch-spin,executor-thread,integrated-timers \ + --- build --release --manifest-path embassy-executor/Cargo.toml --target xtensa-esp32s3-none-elf --features defmt,arch-spin,executor-thread,integrated-timers \ + --- build --release --manifest-path embassy-executor/Cargo.toml --target xtensa-esp32-none-elf --features arch-spin \ + --- build --release --manifest-path embassy-executor/Cargo.toml --target xtensa-esp32-none-elf --features arch-spin,integrated-timers \ + --- build --release --manifest-path embassy-executor/Cargo.toml --target xtensa-esp32-none-elf --features arch-spin,rtos-trace \ + --- build --release --manifest-path embassy-executor/Cargo.toml --target xtensa-esp32-none-elf --features arch-spin,integrated-timers,rtos-trace \ + --- build --release --manifest-path embassy-executor/Cargo.toml --target xtensa-esp32-none-elf --features arch-spin,executor-thread \ + --- build --release --manifest-path embassy-executor/Cargo.toml --target xtensa-esp32-none-elf --features arch-spin,executor-thread,integrated-timers \ + --- build --release --manifest-path embassy-sync/Cargo.toml --target xtensa-esp32s2-none-elf --features defmt \ + --- build --release --manifest-path embassy-time/Cargo.toml --target xtensa-esp32s2-none-elf --features defmt,defmt-timestamp-uptime,generic-queue-8,mock-driver \ + --- build --release --manifest-path embassy-net/Cargo.toml --target xtensa-esp32-none-elf --features defmt,tcp,udp,dns,proto-ipv4,medium-ethernet,packet-trace \ + --- build --release --manifest-path embassy-net/Cargo.toml --target xtensa-esp32-none-elf --features defmt,tcp,udp,dns,proto-ipv4,multicast,medium-ethernet \ + --- build --release --manifest-path embassy-net/Cargo.toml --target xtensa-esp32-none-elf --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet \ + --- build --release --manifest-path embassy-net/Cargo.toml --target xtensa-esp32-none-elf --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet,dhcpv4-hostname \ + --- build --release --manifest-path embassy-net/Cargo.toml --target xtensa-esp32-none-elf --features defmt,tcp,udp,dns,proto-ipv6,medium-ethernet \ + --- build --release --manifest-path embassy-net/Cargo.toml --target xtensa-esp32-none-elf --features defmt,tcp,udp,dns,proto-ipv6,medium-ieee802154 \ + --- build --release --manifest-path embassy-net/Cargo.toml --target xtensa-esp32-none-elf --features defmt,tcp,udp,dns,proto-ipv6,medium-ethernet,medium-ieee802154 \ + --- build --release --manifest-path embassy-net/Cargo.toml --target xtensa-esp32-none-elf --features defmt,tcp,udp,dns,proto-ipv6,medium-ethernet \ + --- build --release --manifest-path embassy-net/Cargo.toml --target xtensa-esp32-none-elf --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ethernet \ + --- build --release --manifest-path embassy-net/Cargo.toml --target xtensa-esp32-none-elf --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ip \ + --- build --release --manifest-path embassy-net/Cargo.toml --target xtensa-esp32-none-elf --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ip,medium-ethernet \ + --- build --release --manifest-path embassy-net/Cargo.toml --target xtensa-esp32-none-elf --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ip,medium-ethernet,medium-ieee802154 \ \ No newline at end of file diff --git a/ci.sh b/ci.sh index 6a5e6e3f5..9f7a7a037 100755 --- a/ci.sh +++ b/ci.sh @@ -2,6 +2,14 @@ set -eo pipefail +if ! command -v cargo-batch &> /dev/null; then + echo "cargo-batch could not be found. Install it with the following command:" + echo "" + echo " cargo install --git https://github.com/embassy-rs/cargo-batch cargo --bin cargo-batch --locked" + echo "" + exit 1 +fi + export RUSTFLAGS=-Dwarnings export DEFMT_LOG=trace,embassy_hal_internal=debug,embassy_net_esp_hosted=debug,cyw43=info,cyw43_pio=info,smoltcp=info if [[ -z "${CARGO_TARGET_DIR}" ]]; then @@ -15,7 +23,8 @@ if [ $TARGET = "x86_64-unknown-linux-gnu" ]; then BUILD_EXTRA="--- build --release --manifest-path examples/std/Cargo.toml --target $TARGET --out-dir out/examples/std" fi -cargo batch \ +# CI intentionally does not use -eabihf on thumbv7em to minimize dep compile time. +cargo batch \ --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi \ --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features log \ --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features defmt \ @@ -23,6 +32,8 @@ cargo batch \ --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv6m-none-eabi --features defmt,arch-cortex-m,executor-thread,executor-interrupt,integrated-timers \ --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features arch-cortex-m \ --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features arch-cortex-m,integrated-timers \ + --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features arch-cortex-m,rtos-trace \ + --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features arch-cortex-m,integrated-timers,rtos-trace \ --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features arch-cortex-m,executor-thread \ --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features arch-cortex-m,executor-thread,integrated-timers \ --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features arch-cortex-m,executor-interrupt \ @@ -36,7 +47,7 @@ cargo batch \ --- build --release --manifest-path embassy-sync/Cargo.toml --target thumbv6m-none-eabi --features defmt \ --- build --release --manifest-path embassy-time/Cargo.toml --target thumbv6m-none-eabi --features defmt,defmt-timestamp-uptime,generic-queue-8,mock-driver \ --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,medium-ethernet,packet-trace \ - --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,igmp,medium-ethernet \ + --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,multicast,medium-ethernet \ --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet \ --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet,dhcpv4-hostname \ --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv6,medium-ethernet \ @@ -47,6 +58,7 @@ cargo batch \ --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ip \ --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ip,medium-ethernet \ --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ip,medium-ethernet,medium-ieee802154 \ + --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv6m-none-eabi --features nrf51,gpiote,time,time-driver-rtc1 \ --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nrf52805,gpiote,time,time-driver-rtc1 \ --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nrf52810,gpiote,time,time-driver-rtc1 \ --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nrf52811,gpiote,time,time-driver-rtc1 \ @@ -70,10 +82,13 @@ cargo batch \ --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv6m-none-eabi --features nrf51,defmt,time,time-driver-rtc1 \ --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv6m-none-eabi --features nrf51,defmt,time \ --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv6m-none-eabi --features nrf51,time \ - --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features time-driver,defmt \ - --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features time-driver,log \ - --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features time-driver,intrinsics \ - --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features time-driver,qspi-as-gpio \ + --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features time-driver,defmt,rp2040 \ + --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features time-driver,log,rp2040 \ + --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features time-driver,intrinsics,rp2040 \ + --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features time-driver,qspi-as-gpio,rp2040 \ + --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv8m.main-none-eabihf --features time-driver,defmt,rp235xa \ + --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv8m.main-none-eabihf --features time-driver,log,rp235xa \ + --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv8m.main-none-eabihf --features time-driver,rp235xa,binary-info \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,time \ @@ -84,6 +99,16 @@ cargo batch \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32f038f6,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32f030c6,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32f058t8,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32f030r8,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32f031k6,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32f030rc,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32f070f6,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32f078vb,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32f042g4,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32f072c8,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f401ve,defmt,exti,time-driver-any \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f405zg,defmt,exti,time-driver-any \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f407zg,defmt,exti,time-driver-any \ @@ -110,6 +135,12 @@ cargo batch \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h755zi-cm7,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h725re,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h7b3ai,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h7b3ai,defmt,exti,time-driver-tim1,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h7r3z8,defmt,exti,time-driver-tim1,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h7r7a8,defmt,exti,time-driver-tim1,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h7s3a8,defmt,exti,time-driver-tim1,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h7s7z8,defmt,exti,time-driver-tim1,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l431cb,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l476vg,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l422cb,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wb15cc,defmt,exti,time-driver-any,time \ @@ -118,9 +149,9 @@ cargo batch \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32l051k8,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32l073cz,defmt,exti,time-driver-any,low-power,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32l151cb-a,defmt,exti,time-driver-any,time \ - --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f303c8,defmt,exti,time-driver-any,time \ - --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f398ve,defmt,exti,time-driver-any,time \ - --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f378cc,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f303c8,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f398ve,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f378cc,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32g0c1ve,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f217zg,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,time-driver-any,low-power,time \ @@ -130,51 +161,81 @@ cargo batch \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f107vc,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f103re,defmt,exti,time-driver-any,time \ --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f100c4,defmt,exti,time-driver-any,time \ - --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32h503rb,defmt,exti,time-driver-any,time \ - --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32h562ag,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32h503rb,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32h523cc,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32h562ag,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32wba50ke,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32wba55ug,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32u5f9zj,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32u5g9nj,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wb35ce,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32u031r8,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32u073mb,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32u083rc,defmt,exti,time-driver-any,time \ + --- build --release --manifest-path embassy-nxp/Cargo.toml --target thumbv8m.main-none-eabihf \ --- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features ''\ --- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'log' \ --- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'defmt' \ --- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'log,firmware-logs' \ --- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'defmt,firmware-logs' \ - --- build --release --manifest-path cyw43-pio/Cargo.toml --target thumbv6m-none-eabi --features '' \ - --- build --release --manifest-path cyw43-pio/Cargo.toml --target thumbv6m-none-eabi --features 'overclock' \ + --- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'log,firmware-logs,bluetooth' \ + --- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'defmt,firmware-logs,bluetooth' \ + --- build --release --manifest-path cyw43-pio/Cargo.toml --target thumbv6m-none-eabi --features 'embassy-rp/rp2040' \ + --- build --release --manifest-path cyw43-pio/Cargo.toml --target thumbv6m-none-eabi --features 'embassy-rp/rp2040,overclock' \ --- build --release --manifest-path embassy-boot-nrf/Cargo.toml --target thumbv7em-none-eabi --features embassy-nrf/nrf52840 \ --- build --release --manifest-path embassy-boot-nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9160-ns \ - --- build --release --manifest-path embassy-boot-rp/Cargo.toml --target thumbv6m-none-eabi \ - --- build --release --manifest-path embassy-boot-stm32/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32wl55jc-cm4 \ - --- build --release --manifest-path docs/modules/ROOT/examples/basic/Cargo.toml --target thumbv7em-none-eabi \ - --- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-pac/Cargo.toml --target thumbv7em-none-eabi \ - --- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-hal/Cargo.toml --target thumbv7em-none-eabi \ - --- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-irq/Cargo.toml --target thumbv7em-none-eabi \ - --- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-async/Cargo.toml --target thumbv7em-none-eabi \ + --- build --release --manifest-path embassy-boot-nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9120-ns \ + --- build --release --manifest-path embassy-boot-nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9151-ns \ + --- build --release --manifest-path embassy-boot-nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9161-ns \ + --- build --release --manifest-path embassy-boot-rp/Cargo.toml --target thumbv6m-none-eabi --features embassy-rp/rp2040 \ + --- build --release --manifest-path embassy-boot-stm32/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32l496zg \ + --- build --release --manifest-path docs/examples/basic/Cargo.toml --target thumbv7em-none-eabi \ + --- build --release --manifest-path docs/examples/layer-by-layer/blinky-pac/Cargo.toml --target thumbv7em-none-eabi \ + --- build --release --manifest-path docs/examples/layer-by-layer/blinky-hal/Cargo.toml --target thumbv7em-none-eabi \ + --- build --release --manifest-path docs/examples/layer-by-layer/blinky-irq/Cargo.toml --target thumbv7em-none-eabi \ + --- build --release --manifest-path docs/examples/layer-by-layer/blinky-async/Cargo.toml --target thumbv7em-none-eabi \ + --- build --release --manifest-path examples/nrf52810/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/nrf52810 \ --- build --release --manifest-path examples/nrf52840/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/nrf52840 \ --- build --release --manifest-path examples/nrf5340/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/nrf5340 \ --- build --release --manifest-path examples/nrf9160/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/nrf9160 \ + --- build --release --manifest-path examples/nrf9151/s/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/nrf9151/s \ + --- build --release --manifest-path examples/nrf9151/ns/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/nrf9151/ns \ --- build --release --manifest-path examples/nrf51/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/nrf51 \ --- build --release --manifest-path examples/rp/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/rp \ + --- build --release --manifest-path examples/rp23/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/rp23 \ --- build --release --manifest-path examples/stm32f0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32f0 \ --- build --release --manifest-path examples/stm32f1/Cargo.toml --target thumbv7m-none-eabi --out-dir out/examples/stm32f1 \ --- build --release --manifest-path examples/stm32f2/Cargo.toml --target thumbv7m-none-eabi --out-dir out/examples/stm32f2 \ - --- build --release --manifest-path examples/stm32f3/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32f3 \ - --- build --release --manifest-path examples/stm32f334/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32f334 \ + --- build --release --manifest-path examples/stm32f3/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32f3 \ + --- build --release --manifest-path examples/stm32f334/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32f334 \ --- build --release --manifest-path examples/stm32f4/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32f4 \ - --- build --release --manifest-path examples/stm32f7/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32f7 \ + --- build --release --manifest-path examples/stm32f469/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32f469 \ + --- build --release --manifest-path examples/stm32f7/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32f7 \ --- build --release --manifest-path examples/stm32c0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32c0 \ --- build --release --manifest-path examples/stm32g0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32g0 \ --- build --release --manifest-path examples/stm32g4/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32g4 \ - --- build --release --manifest-path examples/stm32h5/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32h5 \ + --- build --release --manifest-path examples/stm32h5/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/stm32h5 \ --- build --release --manifest-path examples/stm32h7/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32h7 \ + --- build --release --manifest-path examples/stm32h7b0/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32h7b0 \ + --- build --release --manifest-path examples/stm32h735/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32h735 \ + --- build --release --manifest-path examples/stm32h755cm4/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32h755cm4 \ + --- build --release --manifest-path examples/stm32h755cm7/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32h755cm7 \ + --- build --release --manifest-path examples/stm32h7rs/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32h7rs \ --- build --release --manifest-path examples/stm32l0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32l0 \ --- build --release --manifest-path examples/stm32l1/Cargo.toml --target thumbv7m-none-eabi --out-dir out/examples/stm32l1 \ --- build --release --manifest-path examples/stm32l4/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32l4 \ --- build --release --manifest-path examples/stm32l5/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/stm32l5 \ + --- build --release --manifest-path examples/stm32u0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32u0 \ --- build --release --manifest-path examples/stm32u5/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/stm32u5 \ - --- build --release --manifest-path examples/stm32wb/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32wb \ + --- build --release --manifest-path examples/stm32wb/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32wb \ --- build --release --manifest-path examples/stm32wba/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/stm32wba \ - --- build --release --manifest-path examples/stm32wl/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32wl \ - --- build --release --manifest-path examples/boot/application/nrf/Cargo.toml --target thumbv7em-none-eabi --features embassy-nrf/nrf52840,skip-include --out-dir out/examples/boot/nrf52840 \ + --- build --release --manifest-path examples/stm32wl/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32wl \ + --- build --release --manifest-path examples/lpc55s69/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/lpc55s69 \ + --- build --release --manifest-path examples/boot/application/nrf/Cargo.toml --target thumbv7em-none-eabi --features embassy-nrf/nrf52840,skip-include --out-dir out/examples/boot/nrf52840 \ --- build --release --manifest-path examples/boot/application/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9160-ns,skip-include --out-dir out/examples/boot/nrf9160 \ + --- build --release --manifest-path examples/boot/application/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9120-ns,skip-include --out-dir out/examples/boot/nrf9120 \ + --- build --release --manifest-path examples/boot/application/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9151-ns,skip-include --out-dir out/examples/boot/nrf9151 \ + --- build --release --manifest-path examples/boot/application/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9161-ns,skip-include --out-dir out/examples/boot/nrf9161 \ --- build --release --manifest-path examples/boot/application/rp/Cargo.toml --target thumbv6m-none-eabi --features skip-include --out-dir out/examples/boot/rp \ --- build --release --manifest-path examples/boot/application/stm32f3/Cargo.toml --target thumbv7em-none-eabi --features skip-include --out-dir out/examples/boot/stm32f3 \ --- build --release --manifest-path examples/boot/application/stm32f7/Cargo.toml --target thumbv7em-none-eabi --features skip-include --out-dir out/examples/boot/stm32f7 \ @@ -182,13 +243,17 @@ cargo batch \ --- build --release --manifest-path examples/boot/application/stm32l0/Cargo.toml --target thumbv6m-none-eabi --features skip-include --out-dir out/examples/boot/stm32l0 \ --- build --release --manifest-path examples/boot/application/stm32l1/Cargo.toml --target thumbv7m-none-eabi --features skip-include --out-dir out/examples/boot/stm32l1 \ --- build --release --manifest-path examples/boot/application/stm32l4/Cargo.toml --target thumbv7em-none-eabi --features skip-include --out-dir out/examples/boot/stm32l4 \ - --- build --release --manifest-path examples/boot/application/stm32wl/Cargo.toml --target thumbv7em-none-eabihf --features skip-include --out-dir out/examples/boot/stm32wl \ - --- build --release --manifest-path examples/boot/application/stm32wb-dfu/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/boot/stm32wb-dfu \ + --- build --release --manifest-path examples/boot/application/stm32wl/Cargo.toml --target thumbv7em-none-eabi --features skip-include --out-dir out/examples/boot/stm32wl \ + --- build --release --manifest-path examples/boot/application/stm32wb-dfu/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/boot/stm32wb-dfu \ --- build --release --manifest-path examples/boot/bootloader/nrf/Cargo.toml --target thumbv7em-none-eabi --features embassy-nrf/nrf52840 \ --- build --release --manifest-path examples/boot/bootloader/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9160-ns \ + --- build --release --manifest-path examples/boot/bootloader/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9120-ns \ + --- build --release --manifest-path examples/boot/bootloader/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9151-ns \ + --- build --release --manifest-path examples/boot/bootloader/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9161-ns \ --- build --release --manifest-path examples/boot/bootloader/rp/Cargo.toml --target thumbv6m-none-eabi \ - --- build --release --manifest-path examples/boot/bootloader/stm32/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32wl55jc-cm4 \ - --- build --release --manifest-path examples/boot/bootloader/stm32wb-dfu/Cargo.toml --target thumbv7em-none-eabihf \ + --- build --release --manifest-path examples/boot/bootloader/stm32/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32l496zg \ + --- build --release --manifest-path examples/boot/bootloader/stm32wb-dfu/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32wb55rg \ + --- build --release --manifest-path examples/boot/bootloader/stm32-dual-bank/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32h743zi \ --- build --release --manifest-path examples/wasm/Cargo.toml --target wasm32-unknown-unknown --out-dir out/examples/wasm \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f103c8 --out-dir out/tests/stm32f103c8 \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f429zi --out-dir out/tests/stm32f429zi \ @@ -200,10 +265,10 @@ cargo batch \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h753zi --out-dir out/tests/stm32h753zi \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h7a3zi --out-dir out/tests/stm32h7a3zi \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wb55rg --out-dir out/tests/stm32wb55rg \ - --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h563zi --out-dir out/tests/stm32h563zi \ - --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32u585ai --out-dir out/tests/stm32u585ai \ - --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32u5a5zj --out-dir out/tests/stm32u5a5zj \ - --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wba52cg --out-dir out/tests/stm32wba52cg \ + --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32h563zi --out-dir out/tests/stm32h563zi \ + --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32u585ai --out-dir out/tests/stm32u585ai \ + --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32u5a5zj --out-dir out/tests/stm32u5a5zj \ + --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32wba52cg --out-dir out/tests/stm32wba52cg \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32l073rz --out-dir out/tests/stm32l073rz \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32l152re --out-dir out/tests/stm32l152re \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l4a6zg --out-dir out/tests/stm32l4a6zg \ @@ -214,15 +279,24 @@ cargo batch \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f303ze --out-dir out/tests/stm32f303ze \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l496zg --out-dir out/tests/stm32l496zg \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wl55jc --out-dir out/tests/stm32wl55jc \ + --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h7s3l8 --out-dir out/tests/stm32h7s3l8 \ + --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32f091rc --out-dir out/tests/stm32f091rc \ + --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32h503rb --out-dir out/tests/stm32h503rb \ + --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32u083rc --out-dir out/tests/stm32u083rc \ --- build --release --manifest-path tests/rp/Cargo.toml --target thumbv6m-none-eabi --out-dir out/tests/rpi-pico \ - --- build --release --manifest-path tests/nrf52840/Cargo.toml --target thumbv7em-none-eabi --out-dir out/tests/nrf52840-dk \ - --- build --release --manifest-path tests/nrf51422/Cargo.toml --target thumbv6m-none-eabi --out-dir out/tests/nrf51-dk \ + --- build --release --manifest-path tests/nrf/Cargo.toml --target thumbv6m-none-eabi --features nrf51422 --out-dir out/tests/nrf51422-dk \ + --- build --release --manifest-path tests/nrf/Cargo.toml --target thumbv7em-none-eabi --features nrf52832 --out-dir out/tests/nrf52832-dk \ + --- build --release --manifest-path tests/nrf/Cargo.toml --target thumbv7em-none-eabi --features nrf52833 --out-dir out/tests/nrf52833-dk \ + --- build --release --manifest-path tests/nrf/Cargo.toml --target thumbv7em-none-eabi --features nrf52840 --out-dir out/tests/nrf52840-dk \ + --- build --release --manifest-path tests/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features nrf5340 --out-dir out/tests/nrf5340-dk \ + --- build --release --manifest-path tests/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features nrf9160 --out-dir out/tests/nrf9160-dk \ --- build --release --manifest-path tests/riscv32/Cargo.toml --target riscv32imac-unknown-none-elf \ $BUILD_EXTRA -# failed, a wire must've come loose, will check asap. -rm out/tests/rpi-pico/i2c +# temporarily disabled, these boards are dead. +rm -rf out/tests/stm32f103c8 +rm -rf out/tests/nrf52840-dk rm out/tests/stm32wb55rg/wpan_mac rm out/tests/stm32wb55rg/wpan_ble diff --git a/cyw43-firmware/43439A0.bin b/cyw43-firmware/43439A0.bin old mode 100755 new mode 100644 index 017375277..a05482fe9 Binary files a/cyw43-firmware/43439A0.bin and b/cyw43-firmware/43439A0.bin differ diff --git a/cyw43-firmware/43439A0_btfw.bin b/cyw43-firmware/43439A0_btfw.bin new file mode 100644 index 000000000..290ce8ef0 Binary files /dev/null and b/cyw43-firmware/43439A0_btfw.bin differ diff --git a/cyw43-firmware/43439A0_clm.bin b/cyw43-firmware/43439A0_clm.bin old mode 100755 new mode 100644 index 1fedd753a..dc4ee0252 Binary files a/cyw43-firmware/43439A0_clm.bin and b/cyw43-firmware/43439A0_clm.bin differ diff --git a/cyw43-firmware/README.md b/cyw43-firmware/README.md index db3d9c9cf..10a6b5d02 100644 --- a/cyw43-firmware/README.md +++ b/cyw43-firmware/README.md @@ -1,9 +1,14 @@ -# WiFi firmware +# WiFi + Bluetooth firmware blobs -Firmware obtained from https://github.com/Infineon/wifi-host-driver/tree/master/WiFi_Host_Driver/resources/firmware/COMPONENT_43439 +Firmware obtained from https://github.com/georgerobotics/cyw43-driver/tree/main/firmware Licensed under the [Infineon Permissive Binary License](./LICENSE-permissive-binary-license-1.0.txt) ## Changelog -* 2023-07-28: synced with `ad3bad0` - Update 43439 fw from 7.95.55 ot 7.95.62 +* 2023-08-21: synced with `a1dc885` - Update 43439 fw + clm to come from `wb43439A0_7_95_49_00_combined.h` + add Bluetooth firmware +* 2023-07-28: synced with `ad3bad0` - Update 43439 fw from 7.95.55 to 7.95.62 + +## Notes + +If you update these files, please update the lengths in the `tests/rp/src/bin/cyw43_perf.rs` test (which relies on these files running from RAM). diff --git a/cyw43-pio/CHANGELOG.md b/cyw43-pio/CHANGELOG.md new file mode 100644 index 000000000..913f3515a --- /dev/null +++ b/cyw43-pio/CHANGELOG.md @@ -0,0 +1,17 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## Unreleased + +## 0.2.0 - 2024-08-05 + +- Update to cyw43 0.2.0 +- Update to embassy-rp 0.2.0 + +## 0.1.0 - 2024-01-11 + +- First release diff --git a/cyw43-pio/Cargo.toml b/cyw43-pio/Cargo.toml index 157046b18..4e21c255f 100644 --- a/cyw43-pio/Cargo.toml +++ b/cyw43-pio/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "cyw43-pio" -version = "0.1.0" +version = "0.2.0" edition = "2021" description = "RP2040 PIO SPI implementation for cyw43" keywords = ["embedded", "cyw43", "embassy-net", "embedded-hal-async", "wifi"] @@ -15,8 +15,8 @@ documentation = "https://docs.embassy.dev/cyw43-pio" overclock = [] [dependencies] -cyw43 = { version = "0.1.0", path = "../cyw43" } -embassy-rp = { version = "0.1.0", path = "../embassy-rp" } +cyw43 = { version = "0.2.0", path = "../cyw43" } +embassy-rp = { version = "0.2.0", path = "../embassy-rp" } pio-proc = "0.2" pio = "0.2.1" fixed = "1.23.1" @@ -26,3 +26,4 @@ defmt = { version = "0.3", optional = true } src_base = "https://github.com/embassy-rs/embassy/blob/cyw43-pio-v$VERSION/cyw43-pio/src/" src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/cyw43-pio/src/" target = "thumbv6m-none-eabi" +features = ["embassy-rp/rp2040"] diff --git a/cyw43-pio/src/lib.rs b/cyw43-pio/src/lib.rs index 8c217b995..40cf63a17 100644 --- a/cyw43-pio/src/lib.rs +++ b/cyw43-pio/src/lib.rs @@ -181,7 +181,10 @@ where let read_bits = read.len() * 32 + 32 - 1; #[cfg(feature = "defmt")] - defmt::trace!("write={} read={}", write_bits, read_bits); + defmt::trace!("cmd_read write={} read={}", write_bits, read_bits); + + #[cfg(feature = "defmt")] + defmt::trace!("cmd_read cmd = {:02x} len = {}", cmd, read.len()); unsafe { instr::set_y(&mut self.sm, read_bits as u32); @@ -201,6 +204,10 @@ where .rx() .dma_pull(self.dma.reborrow(), slice::from_mut(&mut status)) .await; + + #[cfg(feature = "defmt")] + defmt::trace!("cmd_read cmd = {:02x} len = {} read = {:08x}", cmd, read.len(), read); + status } } diff --git a/cyw43/CHANGELOG.md b/cyw43/CHANGELOG.md new file mode 100644 index 000000000..1859f7317 --- /dev/null +++ b/cyw43/CHANGELOG.md @@ -0,0 +1,23 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## Unreleased + +## 0.2.0 - 2024-08-05 + +- Update to new versions of embassy-{time,sync} +- Add more fields to the BssInfo packet struct #2461 +- Extend the Scan API #2282 +- Reuse buf to reduce stack usage #2580 +- Add MAC address getter to cyw43 controller #2818 +- Add function to join WPA2 network with precomputed PSK. #2885 +- Add function to close soft AP. #3042 +- Fixing missing re-export #3211 + +## 0.1.0 - 2024-01-11 + +- First release diff --git a/cyw43/Cargo.toml b/cyw43/Cargo.toml index f279739e4..751e59a69 100644 --- a/cyw43/Cargo.toml +++ b/cyw43/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "cyw43" -version = "0.1.0" +version = "0.2.0" edition = "2021" description = "Rust driver for the CYW43439 WiFi chip, used in the Raspberry Pi Pico W." keywords = ["embedded", "cyw43", "embassy-net", "embedded-hal-async", "wifi"] @@ -10,17 +10,18 @@ repository = "https://github.com/embassy-rs/embassy" documentation = "https://docs.embassy.dev/cyw43" [features] -defmt = ["dep:defmt", "heapless/defmt-03", "embassy-time/defmt"] +defmt = ["dep:defmt", "heapless/defmt-03", "embassy-time/defmt", "bt-hci?/defmt", "embedded-io-async?/defmt-03"] log = ["dep:log"] +bluetooth = ["dep:bt-hci", "dep:embedded-io-async"] # Fetch console logs from the WiFi firmware and forward them to `log` or `defmt`. firmware-logs = [] [dependencies] -embassy-time = { version = "0.3.0", path = "../embassy-time"} -embassy-sync = { version = "0.5.0", path = "../embassy-sync"} +embassy-time = { version = "0.3.2", path = "../embassy-time"} +embassy-sync = { version = "0.6.0", path = "../embassy-sync"} embassy-futures = { version = "0.1.0", path = "../embassy-futures"} -embassy-net-driver-channel = { version = "0.2.0", path = "../embassy-net-driver-channel"} +embassy-net-driver-channel = { version = "0.3.0", path = "../embassy-net-driver-channel"} defmt = { version = "0.3", optional = true } log = { version = "0.4.17", optional = true } @@ -31,9 +32,12 @@ futures = { version = "0.3.17", default-features = false, features = ["async-awa embedded-hal-1 = { package = "embedded-hal", version = "1.0" } num_enum = { version = "0.5.7", default-features = false } - heapless = "0.8.0" +# Bluetooth deps +embedded-io-async = { version = "0.6.0", optional = true } +bt-hci = { version = "0.1.0", optional = true } + [package.metadata.embassy_docs] src_base = "https://github.com/embassy-rs/embassy/blob/cyw43-v$VERSION/cyw43/src/" src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/cyw43/src/" diff --git a/cyw43/README.md b/cyw43/README.md index dabdf0471..5b4a5d789 100644 --- a/cyw43/README.md +++ b/cyw43/README.md @@ -23,7 +23,7 @@ TODO: ## Running the examples -- `cargo install probe-rs --features cli` +- Install `probe-rs` following the instructions at . - `cd examples/rp` ### Example 1: Scan the wifi stations - `cargo run --release --bin wifi_scan` diff --git a/cyw43/src/bluetooth.rs b/cyw43/src/bluetooth.rs new file mode 100644 index 000000000..f617a8c7e --- /dev/null +++ b/cyw43/src/bluetooth.rs @@ -0,0 +1,508 @@ +use core::cell::RefCell; +use core::future::Future; +use core::mem::MaybeUninit; + +use bt_hci::transport::WithIndicator; +use bt_hci::{ControllerToHostPacket, FromHciBytes, HostToControllerPacket, PacketKind, WriteHci}; +use embassy_futures::yield_now; +use embassy_sync::blocking_mutex::raw::NoopRawMutex; +use embassy_sync::zerocopy_channel; +use embassy_time::{Duration, Timer}; +use embedded_hal_1::digital::OutputPin; + +use crate::bus::Bus; +pub use crate::bus::SpiBusCyw43; +use crate::consts::*; +use crate::util::round_up; +use crate::{util, CHIP}; + +pub(crate) struct BtState { + rx: [BtPacketBuf; 4], + tx: [BtPacketBuf; 4], + inner: MaybeUninit>, +} + +impl BtState { + pub const fn new() -> Self { + Self { + rx: [const { BtPacketBuf::new() }; 4], + tx: [const { BtPacketBuf::new() }; 4], + inner: MaybeUninit::uninit(), + } + } +} + +struct BtStateInnre<'d> { + rx: zerocopy_channel::Channel<'d, NoopRawMutex, BtPacketBuf>, + tx: zerocopy_channel::Channel<'d, NoopRawMutex, BtPacketBuf>, +} + +/// Bluetooth driver. +pub struct BtDriver<'d> { + rx: RefCell>, + tx: RefCell>, +} + +pub(crate) struct BtRunner<'d> { + pub(crate) tx_chan: zerocopy_channel::Receiver<'d, NoopRawMutex, BtPacketBuf>, + rx_chan: zerocopy_channel::Sender<'d, NoopRawMutex, BtPacketBuf>, + + // Bluetooth circular buffers + addr: u32, + h2b_write_pointer: u32, + b2h_read_pointer: u32, +} + +const BT_HCI_MTU: usize = 1024; + +/// Represents a packet of size MTU. +pub(crate) struct BtPacketBuf { + pub(crate) len: usize, + pub(crate) buf: [u8; BT_HCI_MTU], +} + +impl BtPacketBuf { + /// Create a new packet buffer. + pub const fn new() -> Self { + Self { + len: 0, + buf: [0; BT_HCI_MTU], + } + } +} + +pub(crate) fn new<'d>(state: &'d mut BtState) -> (BtRunner<'d>, BtDriver<'d>) { + // safety: this is a self-referential struct, however: + // - it can't move while the `'d` borrow is active. + // - when the borrow ends, the dangling references inside the MaybeUninit will never be used again. + let state_uninit: *mut MaybeUninit> = + (&mut state.inner as *mut MaybeUninit>).cast(); + let state = unsafe { &mut *state_uninit }.write(BtStateInnre { + rx: zerocopy_channel::Channel::new(&mut state.rx[..]), + tx: zerocopy_channel::Channel::new(&mut state.tx[..]), + }); + + let (rx_sender, rx_receiver) = state.rx.split(); + let (tx_sender, tx_receiver) = state.tx.split(); + + ( + BtRunner { + tx_chan: tx_receiver, + rx_chan: rx_sender, + + addr: 0, + h2b_write_pointer: 0, + b2h_read_pointer: 0, + }, + BtDriver { + rx: RefCell::new(rx_receiver), + tx: RefCell::new(tx_sender), + }, + ) +} + +pub(crate) struct CybtFwCb<'a> { + pub p_next_line_start: &'a [u8], +} + +pub(crate) struct HexFileData<'a> { + pub addr_mode: i32, + pub hi_addr: u16, + pub dest_addr: u32, + pub p_ds: &'a mut [u8], +} + +pub(crate) fn read_firmware_patch_line(p_btfw_cb: &mut CybtFwCb, hfd: &mut HexFileData) -> u32 { + let mut abs_base_addr32 = 0; + + loop { + let num_bytes = p_btfw_cb.p_next_line_start[0]; + p_btfw_cb.p_next_line_start = &p_btfw_cb.p_next_line_start[1..]; + + let addr = (p_btfw_cb.p_next_line_start[0] as u16) << 8 | p_btfw_cb.p_next_line_start[1] as u16; + p_btfw_cb.p_next_line_start = &p_btfw_cb.p_next_line_start[2..]; + + let line_type = p_btfw_cb.p_next_line_start[0]; + p_btfw_cb.p_next_line_start = &p_btfw_cb.p_next_line_start[1..]; + + if num_bytes == 0 { + break; + } + + hfd.p_ds[..num_bytes as usize].copy_from_slice(&p_btfw_cb.p_next_line_start[..num_bytes as usize]); + p_btfw_cb.p_next_line_start = &p_btfw_cb.p_next_line_start[num_bytes as usize..]; + + match line_type { + BTFW_HEX_LINE_TYPE_EXTENDED_ADDRESS => { + hfd.hi_addr = (hfd.p_ds[0] as u16) << 8 | hfd.p_ds[1] as u16; + hfd.addr_mode = BTFW_ADDR_MODE_EXTENDED; + } + BTFW_HEX_LINE_TYPE_EXTENDED_SEGMENT_ADDRESS => { + hfd.hi_addr = (hfd.p_ds[0] as u16) << 8 | hfd.p_ds[1] as u16; + hfd.addr_mode = BTFW_ADDR_MODE_SEGMENT; + } + BTFW_HEX_LINE_TYPE_ABSOLUTE_32BIT_ADDRESS => { + abs_base_addr32 = (hfd.p_ds[0] as u32) << 24 + | (hfd.p_ds[1] as u32) << 16 + | (hfd.p_ds[2] as u32) << 8 + | hfd.p_ds[3] as u32; + hfd.addr_mode = BTFW_ADDR_MODE_LINEAR32; + } + BTFW_HEX_LINE_TYPE_DATA => { + hfd.dest_addr = addr as u32; + match hfd.addr_mode { + BTFW_ADDR_MODE_EXTENDED => hfd.dest_addr += (hfd.hi_addr as u32) << 16, + BTFW_ADDR_MODE_SEGMENT => hfd.dest_addr += (hfd.hi_addr as u32) << 4, + BTFW_ADDR_MODE_LINEAR32 => hfd.dest_addr += abs_base_addr32, + _ => {} + } + return num_bytes as u32; + } + _ => {} + } + } + 0 +} + +impl<'a> BtRunner<'a> { + pub(crate) async fn init_bluetooth(&mut self, bus: &mut Bus, firmware: &[u8]) { + trace!("init_bluetooth"); + bus.bp_write32(CHIP.bluetooth_base_address + BT2WLAN_PWRUP_ADDR, BT2WLAN_PWRUP_WAKE) + .await; + Timer::after(Duration::from_millis(2)).await; + self.upload_bluetooth_firmware(bus, firmware).await; + self.wait_bt_ready(bus).await; + self.init_bt_buffers(bus).await; + self.wait_bt_awake(bus).await; + self.bt_set_host_ready(bus).await; + self.bt_toggle_intr(bus).await; + } + + pub(crate) async fn upload_bluetooth_firmware( + &mut self, + bus: &mut Bus, + firmware: &[u8], + ) { + // read version + let version_length = firmware[0]; + let _version = &firmware[1..=version_length as usize]; + // skip version + 1 extra byte as per cybt_shared_bus_driver.c + let firmware = &firmware[version_length as usize + 2..]; + // buffers + let mut data_buffer: [u8; 0x100] = [0; 0x100]; + let mut aligned_data_buffer: [u8; 0x100] = [0; 0x100]; + // structs + let mut btfw_cb = CybtFwCb { + p_next_line_start: firmware, + }; + let mut hfd = HexFileData { + addr_mode: BTFW_ADDR_MODE_EXTENDED, + hi_addr: 0, + dest_addr: 0, + p_ds: &mut data_buffer, + }; + loop { + let num_fw_bytes = read_firmware_patch_line(&mut btfw_cb, &mut hfd); + if num_fw_bytes == 0 { + break; + } + let fw_bytes = &hfd.p_ds[0..num_fw_bytes as usize]; + let mut dest_start_addr = hfd.dest_addr + CHIP.bluetooth_base_address; + let mut aligned_data_buffer_index: usize = 0; + // pad start + if !util::is_aligned(dest_start_addr, 4) { + let num_pad_bytes = dest_start_addr % 4; + let padded_dest_start_addr = util::round_down(dest_start_addr, 4); + let memory_value = bus.bp_read32(padded_dest_start_addr).await; + let memory_value_bytes = memory_value.to_le_bytes(); + // Copy the previous memory value's bytes to the start + for i in 0..num_pad_bytes as usize { + aligned_data_buffer[aligned_data_buffer_index] = memory_value_bytes[i]; + aligned_data_buffer_index += 1; + } + // Copy the firmware bytes after the padding bytes + for i in 0..num_fw_bytes as usize { + aligned_data_buffer[aligned_data_buffer_index] = fw_bytes[i]; + aligned_data_buffer_index += 1; + } + dest_start_addr = padded_dest_start_addr; + } else { + // Directly copy fw_bytes into aligned_data_buffer if no start padding is required + for i in 0..num_fw_bytes as usize { + aligned_data_buffer[aligned_data_buffer_index] = fw_bytes[i]; + aligned_data_buffer_index += 1; + } + } + // pad end + let mut dest_end_addr = dest_start_addr + aligned_data_buffer_index as u32; + if !util::is_aligned(dest_end_addr, 4) { + let offset = dest_end_addr % 4; + let num_pad_bytes_end = 4 - offset; + let padded_dest_end_addr = util::round_down(dest_end_addr, 4); + let memory_value = bus.bp_read32(padded_dest_end_addr).await; + let memory_value_bytes = memory_value.to_le_bytes(); + // Append the necessary memory bytes to pad the end of aligned_data_buffer + for i in offset..4 { + aligned_data_buffer[aligned_data_buffer_index] = memory_value_bytes[i as usize]; + aligned_data_buffer_index += 1; + } + dest_end_addr += num_pad_bytes_end; + } else { + // pad end alignment not needed + } + let buffer_to_write = &aligned_data_buffer[0..aligned_data_buffer_index as usize]; + assert!(dest_start_addr % 4 == 0); + assert!(dest_end_addr % 4 == 0); + assert!(aligned_data_buffer_index % 4 == 0); + bus.bp_write(dest_start_addr, buffer_to_write).await; + } + } + + pub(crate) async fn wait_bt_ready(&mut self, bus: &mut Bus) { + trace!("wait_bt_ready"); + let mut success = false; + for _ in 0..300 { + let val = bus.bp_read32(BT_CTRL_REG_ADDR).await; + trace!("BT_CTRL_REG_ADDR = {:08x}", val); + if val & BTSDIO_REG_FW_RDY_BITMASK != 0 { + success = true; + break; + } + Timer::after(Duration::from_millis(1)).await; + } + assert!(success == true); + } + + pub(crate) async fn wait_bt_awake(&mut self, bus: &mut Bus) { + trace!("wait_bt_awake"); + let mut success = false; + for _ in 0..300 { + let val = bus.bp_read32(BT_CTRL_REG_ADDR).await; + trace!("BT_CTRL_REG_ADDR = {:08x}", val); + if val & BTSDIO_REG_BT_AWAKE_BITMASK != 0 { + success = true; + break; + } + Timer::after(Duration::from_millis(1)).await; + } + assert!(success == true); + } + + pub(crate) async fn bt_set_host_ready(&mut self, bus: &mut Bus) { + trace!("bt_set_host_ready"); + let old_val = bus.bp_read32(HOST_CTRL_REG_ADDR).await; + // TODO: do we need to swap endianness on this read? + let new_val = old_val | BTSDIO_REG_SW_RDY_BITMASK; + bus.bp_write32(HOST_CTRL_REG_ADDR, new_val).await; + } + + // TODO: use this + #[allow(dead_code)] + pub(crate) async fn bt_set_awake(&mut self, bus: &mut Bus, awake: bool) { + trace!("bt_set_awake"); + let old_val = bus.bp_read32(HOST_CTRL_REG_ADDR).await; + // TODO: do we need to swap endianness on this read? + let new_val = if awake { + old_val | BTSDIO_REG_WAKE_BT_BITMASK + } else { + old_val & !BTSDIO_REG_WAKE_BT_BITMASK + }; + bus.bp_write32(HOST_CTRL_REG_ADDR, new_val).await; + } + + pub(crate) async fn bt_toggle_intr(&mut self, bus: &mut Bus) { + trace!("bt_toggle_intr"); + let old_val = bus.bp_read32(HOST_CTRL_REG_ADDR).await; + // TODO: do we need to swap endianness on this read? + let new_val = old_val ^ BTSDIO_REG_DATA_VALID_BITMASK; + bus.bp_write32(HOST_CTRL_REG_ADDR, new_val).await; + } + + // TODO: use this + #[allow(dead_code)] + pub(crate) async fn bt_set_intr(&mut self, bus: &mut Bus) { + trace!("bt_set_intr"); + let old_val = bus.bp_read32(HOST_CTRL_REG_ADDR).await; + let new_val = old_val | BTSDIO_REG_DATA_VALID_BITMASK; + bus.bp_write32(HOST_CTRL_REG_ADDR, new_val).await; + } + + pub(crate) async fn init_bt_buffers(&mut self, bus: &mut Bus) { + trace!("init_bt_buffers"); + self.addr = bus.bp_read32(WLAN_RAM_BASE_REG_ADDR).await; + assert!(self.addr != 0); + trace!("wlan_ram_base_addr = {:08x}", self.addr); + bus.bp_write32(self.addr + BTSDIO_OFFSET_HOST2BT_IN, 0).await; + bus.bp_write32(self.addr + BTSDIO_OFFSET_HOST2BT_OUT, 0).await; + bus.bp_write32(self.addr + BTSDIO_OFFSET_BT2HOST_IN, 0).await; + bus.bp_write32(self.addr + BTSDIO_OFFSET_BT2HOST_OUT, 0).await; + } + + async fn bt_bus_request(&mut self, bus: &mut Bus) { + // TODO: CYW43_THREAD_ENTER mutex? + self.bt_set_awake(bus, true).await; + self.wait_bt_awake(bus).await; + } + + pub(crate) async fn hci_write(&mut self, bus: &mut Bus) { + self.bt_bus_request(bus).await; + + // NOTE(unwrap): we only call this when we do have a packet in the queue. + let buf = self.tx_chan.try_receive().unwrap(); + debug!("HCI tx: {:02x}", crate::fmt::Bytes(&buf.buf[..buf.len])); + + let len = buf.len as u32 - 1; // len doesn't include hci type byte + let rounded_len = round_up(len, 4); + let total_len = 4 + rounded_len; + + let read_pointer = bus.bp_read32(self.addr + BTSDIO_OFFSET_HOST2BT_OUT).await; + let available = read_pointer.wrapping_sub(self.h2b_write_pointer + 4) % BTSDIO_FWBUF_SIZE; + if available < total_len { + warn!( + "bluetooth tx queue full, retrying. len {} available {}", + total_len, available + ); + yield_now().await; + return; + } + + // Build header + let mut header = [0u8; 4]; + header[0] = len as u8; + header[1] = (len >> 8) as u8; + header[2] = (len >> 16) as u8; + header[3] = buf.buf[0]; // HCI type byte + + // Write header + let addr = self.addr + BTSDIO_OFFSET_HOST_WRITE_BUF + self.h2b_write_pointer; + bus.bp_write(addr, &header).await; + self.h2b_write_pointer = (self.h2b_write_pointer + 4) % BTSDIO_FWBUF_SIZE; + + // Write payload. + let payload = &buf.buf[1..][..rounded_len as usize]; + if self.h2b_write_pointer as usize + payload.len() > BTSDIO_FWBUF_SIZE as usize { + // wraparound + let n = BTSDIO_FWBUF_SIZE - self.h2b_write_pointer; + let addr = self.addr + BTSDIO_OFFSET_HOST_WRITE_BUF + self.h2b_write_pointer; + bus.bp_write(addr, &payload[..n as usize]).await; + let addr = self.addr + BTSDIO_OFFSET_HOST_WRITE_BUF; + bus.bp_write(addr, &payload[n as usize..]).await; + } else { + // no wraparound + let addr = self.addr + BTSDIO_OFFSET_HOST_WRITE_BUF + self.h2b_write_pointer; + bus.bp_write(addr, payload).await; + } + self.h2b_write_pointer = (self.h2b_write_pointer + payload.len() as u32) % BTSDIO_FWBUF_SIZE; + + // Update pointer. + bus.bp_write32(self.addr + BTSDIO_OFFSET_HOST2BT_IN, self.h2b_write_pointer) + .await; + + self.bt_toggle_intr(bus).await; + + self.tx_chan.receive_done(); + } + + async fn bt_has_work(&mut self, bus: &mut Bus) -> bool { + let int_status = bus.bp_read32(CHIP.sdiod_core_base_address + SDIO_INT_STATUS).await; + if int_status & I_HMB_FC_CHANGE != 0 { + bus.bp_write32( + CHIP.sdiod_core_base_address + SDIO_INT_STATUS, + int_status & I_HMB_FC_CHANGE, + ) + .await; + return true; + } + return false; + } + + pub(crate) async fn handle_irq(&mut self, bus: &mut Bus) { + if self.bt_has_work(bus).await { + loop { + // Check if we have data. + let write_pointer = bus.bp_read32(self.addr + BTSDIO_OFFSET_BT2HOST_IN).await; + let available = write_pointer.wrapping_sub(self.b2h_read_pointer) % BTSDIO_FWBUF_SIZE; + if available == 0 { + break; + } + + // read header + let mut header = [0u8; 4]; + let addr = self.addr + BTSDIO_OFFSET_HOST_READ_BUF + self.b2h_read_pointer; + bus.bp_read(addr, &mut header).await; + + // calc length + let len = header[0] as u32 | ((header[1]) as u32) << 8 | ((header[2]) as u32) << 16; + let rounded_len = round_up(len, 4); + if available < 4 + rounded_len { + warn!("ringbuf data not enough for a full packet?"); + break; + } + self.b2h_read_pointer = (self.b2h_read_pointer + 4) % BTSDIO_FWBUF_SIZE; + + // Obtain a buf from the channel. + let buf = self.rx_chan.send().await; + + buf.buf[0] = header[3]; // hci packet type + let payload = &mut buf.buf[1..][..rounded_len as usize]; + if self.b2h_read_pointer as usize + payload.len() > BTSDIO_FWBUF_SIZE as usize { + // wraparound + let n = BTSDIO_FWBUF_SIZE - self.b2h_read_pointer; + let addr = self.addr + BTSDIO_OFFSET_HOST_READ_BUF + self.b2h_read_pointer; + bus.bp_read(addr, &mut payload[..n as usize]).await; + let addr = self.addr + BTSDIO_OFFSET_HOST_READ_BUF; + bus.bp_read(addr, &mut payload[n as usize..]).await; + } else { + // no wraparound + let addr = self.addr + BTSDIO_OFFSET_HOST_READ_BUF + self.b2h_read_pointer; + bus.bp_read(addr, payload).await; + } + self.b2h_read_pointer = (self.b2h_read_pointer + payload.len() as u32) % BTSDIO_FWBUF_SIZE; + bus.bp_write32(self.addr + BTSDIO_OFFSET_BT2HOST_OUT, self.b2h_read_pointer) + .await; + + buf.len = 1 + len as usize; + debug!("HCI rx: {:02x}", crate::fmt::Bytes(&buf.buf[..buf.len])); + + self.rx_chan.send_done(); + + self.bt_toggle_intr(bus).await; + } + } + } +} + +impl<'d> embedded_io_async::ErrorType for BtDriver<'d> { + type Error = core::convert::Infallible; +} + +impl<'d> bt_hci::transport::Transport for BtDriver<'d> { + fn read<'a>(&self, rx: &'a mut [u8]) -> impl Future, Self::Error>> { + async { + let ch = &mut *self.rx.borrow_mut(); + let buf = ch.receive().await; + let n = buf.len; + assert!(n < rx.len()); + rx[..n].copy_from_slice(&buf.buf[..n]); + ch.receive_done(); + + let kind = PacketKind::from_hci_bytes_complete(&rx[..1]).unwrap(); + let (res, _) = ControllerToHostPacket::from_hci_bytes_with_kind(kind, &rx[1..n]).unwrap(); + Ok(res) + } + } + + /// Write a complete HCI packet from the tx buffer + fn write(&self, val: &T) -> impl Future> { + async { + let ch = &mut *self.tx.borrow_mut(); + let buf = ch.send().await; + let buf_len = buf.buf.len(); + let mut slice = &mut buf.buf[..]; + WithIndicator::new(val).write_hci(&mut slice).unwrap(); + buf.len = buf_len - slice.len(); + ch.send_done(); + Ok(()) + } + } +} diff --git a/cyw43/src/bus.rs b/cyw43/src/bus.rs index 014109038..8a53484d5 100644 --- a/cyw43/src/bus.rs +++ b/cyw43/src/bus.rs @@ -4,7 +4,7 @@ use embedded_hal_1::digital::OutputPin; use futures::FutureExt; use crate::consts::*; -use crate::slice8_mut; +use crate::util::slice8_mut; /// Custom Spi Trait that _only_ supports the bus operation of the cyw43 /// Implementors are expected to hold the CS pin low during an operation. @@ -48,44 +48,91 @@ where } } - pub async fn init(&mut self) { + pub async fn init(&mut self, bluetooth_enabled: bool) { // Reset + trace!("WL_REG off/on"); self.pwr.set_low().unwrap(); Timer::after_millis(20).await; self.pwr.set_high().unwrap(); Timer::after_millis(250).await; + trace!("read REG_BUS_TEST_RO"); while self - .read32_swapped(REG_BUS_TEST_RO) + .read32_swapped(FUNC_BUS, REG_BUS_TEST_RO) .inspect(|v| trace!("{:#x}", v)) .await != FEEDBEAD {} - self.write32_swapped(REG_BUS_TEST_RW, TEST_PATTERN).await; - let val = self.read32_swapped(REG_BUS_TEST_RW).await; + trace!("write REG_BUS_TEST_RW"); + self.write32_swapped(FUNC_BUS, REG_BUS_TEST_RW, TEST_PATTERN).await; + let val = self.read32_swapped(FUNC_BUS, REG_BUS_TEST_RW).await; trace!("{:#x}", val); assert_eq!(val, TEST_PATTERN); - let val = self.read32_swapped(REG_BUS_CTRL).await; + trace!("read REG_BUS_CTRL"); + let val = self.read32_swapped(FUNC_BUS, REG_BUS_CTRL).await; trace!("{:#010b}", (val & 0xff)); // 32-bit word length, little endian (which is the default endianess). + // TODO: C library is uint32_t val = WORD_LENGTH_32 | HIGH_SPEED_MODE| ENDIAN_BIG | INTERRUPT_POLARITY_HIGH | WAKE_UP | 0x4 << (8 * SPI_RESPONSE_DELAY) | INTR_WITH_STATUS << (8 * SPI_STATUS_ENABLE); + trace!("write REG_BUS_CTRL"); self.write32_swapped( + FUNC_BUS, REG_BUS_CTRL, - WORD_LENGTH_32 | HIGH_SPEED | INTERRUPT_HIGH | WAKE_UP | STATUS_ENABLE | INTERRUPT_WITH_STATUS, + WORD_LENGTH_32 + | HIGH_SPEED + | INTERRUPT_POLARITY_HIGH + | WAKE_UP + | 0x4 << (8 * REG_BUS_RESPONSE_DELAY) + | STATUS_ENABLE << (8 * REG_BUS_STATUS_ENABLE) + | INTR_WITH_STATUS << (8 * REG_BUS_STATUS_ENABLE), ) .await; + trace!("read REG_BUS_CTRL"); let val = self.read8(FUNC_BUS, REG_BUS_CTRL).await; trace!("{:#b}", val); + // TODO: C doesn't do this? i doubt it messes anything up + trace!("read REG_BUS_TEST_RO"); let val = self.read32(FUNC_BUS, REG_BUS_TEST_RO).await; trace!("{:#x}", val); assert_eq!(val, FEEDBEAD); + + // TODO: C doesn't do this? i doubt it messes anything up + trace!("read REG_BUS_TEST_RW"); let val = self.read32(FUNC_BUS, REG_BUS_TEST_RW).await; trace!("{:#x}", val); assert_eq!(val, TEST_PATTERN); + + trace!("write SPI_RESP_DELAY_F1 CYW43_BACKPLANE_READ_PAD_LEN_BYTES"); + self.write8(FUNC_BUS, SPI_RESP_DELAY_F1, WHD_BUS_SPI_BACKPLANE_READ_PADD_SIZE) + .await; + + // TODO: Make sure error interrupt bits are clear? + // cyw43_write_reg_u8(self, BUS_FUNCTION, SPI_INTERRUPT_REGISTER, DATA_UNAVAILABLE | COMMAND_ERROR | DATA_ERROR | F1_OVERFLOW) != 0) + trace!("Make sure error interrupt bits are clear"); + self.write8( + FUNC_BUS, + REG_BUS_INTERRUPT, + (IRQ_DATA_UNAVAILABLE | IRQ_COMMAND_ERROR | IRQ_DATA_ERROR | IRQ_F1_OVERFLOW) as u8, + ) + .await; + + // Enable a selection of interrupts + // TODO: why not all of these F2_F3_FIFO_RD_UNDERFLOW | F2_F3_FIFO_WR_OVERFLOW | COMMAND_ERROR | DATA_ERROR | F2_PACKET_AVAILABLE | F1_OVERFLOW | F1_INTR + trace!("enable a selection of interrupts"); + let mut val = IRQ_F2_F3_FIFO_RD_UNDERFLOW + | IRQ_F2_F3_FIFO_WR_OVERFLOW + | IRQ_COMMAND_ERROR + | IRQ_DATA_ERROR + | IRQ_F2_PACKET_AVAILABLE + | IRQ_F1_OVERFLOW; + if bluetooth_enabled { + val = val | IRQ_F1_INTR; + } + self.write16(FUNC_BUS, REG_BUS_INTERRUPT_ENABLE, val).await; } pub async fn wlan_read(&mut self, buf: &mut [u32], len_in_u8: u32) { @@ -107,6 +154,8 @@ where #[allow(unused)] pub async fn bp_read(&mut self, mut addr: u32, mut data: &mut [u8]) { + trace!("bp_read addr = {:08x}", addr); + // It seems the HW force-aligns the addr // to 2 if data.len() >= 2 // to 4 if data.len() >= 4 @@ -140,6 +189,8 @@ where } pub async fn bp_write(&mut self, mut addr: u32, mut data: &[u8]) { + trace!("bp_write addr = {:08x}", addr); + // It seems the HW force-aligns the addr // to 2 if data.len() >= 2 // to 4 if data.len() >= 4 @@ -196,23 +247,32 @@ where } async fn backplane_readn(&mut self, addr: u32, len: u32) -> u32 { + trace!("backplane_readn addr = {:08x} len = {}", addr, len); + self.backplane_set_window(addr).await; let mut bus_addr = addr & BACKPLANE_ADDRESS_MASK; if len == 4 { - bus_addr |= BACKPLANE_ADDRESS_32BIT_FLAG + bus_addr |= BACKPLANE_ADDRESS_32BIT_FLAG; } - self.readn(FUNC_BACKPLANE, bus_addr, len).await + + let val = self.readn(FUNC_BACKPLANE, bus_addr, len).await; + + trace!("backplane_readn addr = {:08x} len = {} val = {:08x}", addr, len, val); + + return val; } async fn backplane_writen(&mut self, addr: u32, val: u32, len: u32) { + trace!("backplane_writen addr = {:08x} len = {} val = {:08x}", addr, len, val); + self.backplane_set_window(addr).await; let mut bus_addr = addr & BACKPLANE_ADDRESS_MASK; if len == 4 { - bus_addr |= BACKPLANE_ADDRESS_32BIT_FLAG + bus_addr |= BACKPLANE_ADDRESS_32BIT_FLAG; } - self.writen(FUNC_BACKPLANE, bus_addr, val, len).await + self.writen(FUNC_BACKPLANE, bus_addr, val, len).await; } async fn backplane_set_window(&mut self, addr: u32) { @@ -293,8 +353,8 @@ where self.status = self.spi.cmd_write(&[cmd, val]).await; } - async fn read32_swapped(&mut self, addr: u32) -> u32 { - let cmd = cmd_word(READ, INC_ADDR, FUNC_BUS, addr, 4); + async fn read32_swapped(&mut self, func: u32, addr: u32) -> u32 { + let cmd = cmd_word(READ, INC_ADDR, func, addr, 4); let cmd = swap16(cmd); let mut buf = [0; 1]; @@ -303,8 +363,8 @@ where swap16(buf[0]) } - async fn write32_swapped(&mut self, addr: u32, val: u32) { - let cmd = cmd_word(WRITE, INC_ADDR, FUNC_BUS, addr, 4); + async fn write32_swapped(&mut self, func: u32, addr: u32, val: u32) { + let cmd = cmd_word(WRITE, INC_ADDR, func, addr, 4); let buf = [swap16(cmd), swap16(val)]; self.status = self.spi.cmd_write(&buf).await; diff --git a/cyw43/src/consts.rs b/cyw43/src/consts.rs index 4e2836f3b..c3f0dbfd8 100644 --- a/cyw43/src/consts.rs +++ b/cyw43/src/consts.rs @@ -5,19 +5,33 @@ pub(crate) const FUNC_BACKPLANE: u32 = 1; pub(crate) const FUNC_WLAN: u32 = 2; pub(crate) const FUNC_BT: u32 = 3; +// Register addresses pub(crate) const REG_BUS_CTRL: u32 = 0x0; +pub(crate) const REG_BUS_RESPONSE_DELAY: u32 = 0x1; +pub(crate) const REG_BUS_STATUS_ENABLE: u32 = 0x2; pub(crate) const REG_BUS_INTERRUPT: u32 = 0x04; // 16 bits - Interrupt status pub(crate) const REG_BUS_INTERRUPT_ENABLE: u32 = 0x06; // 16 bits - Interrupt mask pub(crate) const REG_BUS_STATUS: u32 = 0x8; pub(crate) const REG_BUS_TEST_RO: u32 = 0x14; pub(crate) const REG_BUS_TEST_RW: u32 = 0x18; pub(crate) const REG_BUS_RESP_DELAY: u32 = 0x1c; + +// SPI_BUS_CONTROL Bits pub(crate) const WORD_LENGTH_32: u32 = 0x1; +pub(crate) const ENDIAN_BIG: u32 = 0x2; +pub(crate) const CLOCK_PHASE: u32 = 0x4; +pub(crate) const CLOCK_POLARITY: u32 = 0x8; pub(crate) const HIGH_SPEED: u32 = 0x10; -pub(crate) const INTERRUPT_HIGH: u32 = 1 << 5; -pub(crate) const WAKE_UP: u32 = 1 << 7; -pub(crate) const STATUS_ENABLE: u32 = 1 << 16; -pub(crate) const INTERRUPT_WITH_STATUS: u32 = 1 << 17; +pub(crate) const INTERRUPT_POLARITY_HIGH: u32 = 0x20; +pub(crate) const WAKE_UP: u32 = 0x80; + +// SPI_STATUS_ENABLE bits +pub(crate) const STATUS_ENABLE: u32 = 0x01; +pub(crate) const INTR_WITH_STATUS: u32 = 0x02; +pub(crate) const RESP_DELAY_ALL: u32 = 0x04; +pub(crate) const DWORD_PKT_LEN_EN: u32 = 0x08; +pub(crate) const CMD_ERR_CHK_EN: u32 = 0x20; +pub(crate) const DATA_ERR_CHK_EN: u32 = 0x40; // SPI_STATUS_REGISTER bits pub(crate) const STATUS_DATA_NOT_AVAILABLE: u32 = 0x00000001; @@ -51,6 +65,13 @@ pub(crate) const REG_BACKPLANE_READ_FRAME_BC_HIGH: u32 = 0x1001C; pub(crate) const REG_BACKPLANE_WAKEUP_CTRL: u32 = 0x1001E; pub(crate) const REG_BACKPLANE_SLEEP_CSR: u32 = 0x1001F; +pub(crate) const I_HMB_SW_MASK: u32 = 0x000000f0; +pub(crate) const I_HMB_FC_CHANGE: u32 = 1 << 5; +pub(crate) const SDIO_INT_STATUS: u32 = 0x20; +pub(crate) const SDIO_INT_HOST_MASK: u32 = 0x24; + +pub(crate) const SPI_F2_WATERMARK: u8 = 0x20; + pub(crate) const BACKPLANE_WINDOW_SIZE: usize = 0x8000; pub(crate) const BACKPLANE_ADDRESS_MASK: u32 = 0x7FFF; pub(crate) const BACKPLANE_ADDRESS_32BIT_FLAG: u32 = 0x08000; @@ -92,17 +113,6 @@ pub(crate) const IRQ_F1_INTR: u16 = 0x2000; pub(crate) const IRQ_F2_INTR: u16 = 0x4000; pub(crate) const IRQ_F3_INTR: u16 = 0x8000; -pub(crate) const IOCTL_CMD_UP: u32 = 2; -pub(crate) const IOCTL_CMD_DOWN: u32 = 3; -pub(crate) const IOCTL_CMD_SET_SSID: u32 = 26; -pub(crate) const IOCTL_CMD_SET_CHANNEL: u32 = 30; -pub(crate) const IOCTL_CMD_DISASSOC: u32 = 52; -pub(crate) const IOCTL_CMD_ANTDIV: u32 = 64; -pub(crate) const IOCTL_CMD_SET_AP: u32 = 118; -pub(crate) const IOCTL_CMD_SET_VAR: u32 = 263; -pub(crate) const IOCTL_CMD_GET_VAR: u32 = 262; -pub(crate) const IOCTL_CMD_SET_PASSPHRASE: u32 = 268; - pub(crate) const CHANNEL_TYPE_CONTROL: u8 = 0; pub(crate) const CHANNEL_TYPE_EVENT: u8 = 1; pub(crate) const CHANNEL_TYPE_DATA: u8 = 2; @@ -119,6 +129,44 @@ pub(crate) const WPA2_SECURITY: u32 = 0x00400000; pub(crate) const MIN_PSK_LEN: usize = 8; pub(crate) const MAX_PSK_LEN: usize = 64; +// Bluetooth firmware extraction constants. +pub(crate) const BTFW_ADDR_MODE_UNKNOWN: i32 = 0; +pub(crate) const BTFW_ADDR_MODE_EXTENDED: i32 = 1; +pub(crate) const BTFW_ADDR_MODE_SEGMENT: i32 = 2; +pub(crate) const BTFW_ADDR_MODE_LINEAR32: i32 = 3; + +pub(crate) const BTFW_HEX_LINE_TYPE_DATA: u8 = 0; +pub(crate) const BTFW_HEX_LINE_TYPE_END_OF_DATA: u8 = 1; +pub(crate) const BTFW_HEX_LINE_TYPE_EXTENDED_SEGMENT_ADDRESS: u8 = 2; +pub(crate) const BTFW_HEX_LINE_TYPE_EXTENDED_ADDRESS: u8 = 4; +pub(crate) const BTFW_HEX_LINE_TYPE_ABSOLUTE_32BIT_ADDRESS: u8 = 5; + +// Bluetooth constants. +pub(crate) const SPI_RESP_DELAY_F1: u32 = 0x001d; +pub(crate) const WHD_BUS_SPI_BACKPLANE_READ_PADD_SIZE: u8 = 4; + +pub(crate) const BT2WLAN_PWRUP_WAKE: u32 = 3; +pub(crate) const BT2WLAN_PWRUP_ADDR: u32 = 0x640894; + +pub(crate) const BT_CTRL_REG_ADDR: u32 = 0x18000c7c; +pub(crate) const HOST_CTRL_REG_ADDR: u32 = 0x18000d6c; +pub(crate) const WLAN_RAM_BASE_REG_ADDR: u32 = 0x18000d68; + +pub(crate) const BTSDIO_REG_DATA_VALID_BITMASK: u32 = 1 << 1; +pub(crate) const BTSDIO_REG_BT_AWAKE_BITMASK: u32 = 1 << 8; +pub(crate) const BTSDIO_REG_WAKE_BT_BITMASK: u32 = 1 << 17; +pub(crate) const BTSDIO_REG_SW_RDY_BITMASK: u32 = 1 << 24; +pub(crate) const BTSDIO_REG_FW_RDY_BITMASK: u32 = 1 << 24; + +pub(crate) const BTSDIO_FWBUF_SIZE: u32 = 0x1000; +pub(crate) const BTSDIO_OFFSET_HOST_WRITE_BUF: u32 = 0; +pub(crate) const BTSDIO_OFFSET_HOST_READ_BUF: u32 = BTSDIO_FWBUF_SIZE; + +pub(crate) const BTSDIO_OFFSET_HOST2BT_IN: u32 = 0x00002000; +pub(crate) const BTSDIO_OFFSET_HOST2BT_OUT: u32 = 0x00002004; +pub(crate) const BTSDIO_OFFSET_BT2HOST_IN: u32 = 0x00002008; +pub(crate) const BTSDIO_OFFSET_BT2HOST_OUT: u32 = 0x0000200C; + // Security type (authentication and encryption types are combined using bit mask) #[allow(non_camel_case_types)] #[derive(Copy, Clone, PartialEq)] @@ -317,3 +365,306 @@ impl core::fmt::Display for FormatInterrupt { core::fmt::Debug::fmt(self, f) } } + +#[derive(Copy, Clone, Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[repr(u32)] +pub(crate) enum Ioctl { + GetMagic = 0, + GetVersion = 1, + Up = 2, + Down = 3, + GetLoop = 4, + SetLoop = 5, + Dump = 6, + GetMsglevel = 7, + SetMsglevel = 8, + GetPromisc = 9, + SetPromisc = 10, + GetRate = 12, + GetInstance = 14, + GetInfra = 19, + SetInfra = 20, + GetAuth = 21, + SetAuth = 22, + GetBssid = 23, + SetBssid = 24, + GetSsid = 25, + SetSsid = 26, + Restart = 27, + GetChannel = 29, + SetChannel = 30, + GetSrl = 31, + SetSrl = 32, + GetLrl = 33, + SetLrl = 34, + GetPlcphdr = 35, + SetPlcphdr = 36, + GetRadio = 37, + SetRadio = 38, + GetPhytype = 39, + DumpRate = 40, + SetRateParams = 41, + GetKey = 44, + SetKey = 45, + GetRegulatory = 46, + SetRegulatory = 47, + GetPassiveScan = 48, + SetPassiveScan = 49, + Scan = 50, + ScanResults = 51, + Disassoc = 52, + Reassoc = 53, + GetRoamTrigger = 54, + SetRoamTrigger = 55, + GetRoamDelta = 56, + SetRoamDelta = 57, + GetRoamScanPeriod = 58, + SetRoamScanPeriod = 59, + Evm = 60, + GetTxant = 61, + SetTxant = 62, + GetAntdiv = 63, + SetAntdiv = 64, + GetClosed = 67, + SetClosed = 68, + GetMaclist = 69, + SetMaclist = 70, + GetRateset = 71, + SetRateset = 72, + Longtrain = 74, + GetBcnprd = 75, + SetBcnprd = 76, + GetDtimprd = 77, + SetDtimprd = 78, + GetSrom = 79, + SetSrom = 80, + GetWepRestrict = 81, + SetWepRestrict = 82, + GetCountry = 83, + SetCountry = 84, + GetPm = 85, + SetPm = 86, + GetWake = 87, + SetWake = 88, + GetForcelink = 90, + SetForcelink = 91, + FreqAccuracy = 92, + CarrierSuppress = 93, + GetPhyreg = 94, + SetPhyreg = 95, + GetRadioreg = 96, + SetRadioreg = 97, + GetRevinfo = 98, + GetUcantdiv = 99, + SetUcantdiv = 100, + RReg = 101, + WReg = 102, + GetMacmode = 105, + SetMacmode = 106, + GetMonitor = 107, + SetMonitor = 108, + GetGmode = 109, + SetGmode = 110, + GetLegacyErp = 111, + SetLegacyErp = 112, + GetRxAnt = 113, + GetCurrRateset = 114, + GetScansuppress = 115, + SetScansuppress = 116, + GetAp = 117, + SetAp = 118, + GetEapRestrict = 119, + SetEapRestrict = 120, + ScbAuthorize = 121, + ScbDeauthorize = 122, + GetWdslist = 123, + SetWdslist = 124, + GetAtim = 125, + SetAtim = 126, + GetRssi = 127, + GetPhyantdiv = 128, + SetPhyantdiv = 129, + ApRxOnly = 130, + GetTxPathPwr = 131, + SetTxPathPwr = 132, + GetWsec = 133, + SetWsec = 134, + GetPhyNoise = 135, + GetBssInfo = 136, + GetPktcnts = 137, + GetLazywds = 138, + SetLazywds = 139, + GetBandlist = 140, + GetBand = 141, + SetBand = 142, + ScbDeauthenticate = 143, + GetShortslot = 144, + GetShortslotOverride = 145, + SetShortslotOverride = 146, + GetShortslotRestrict = 147, + SetShortslotRestrict = 148, + GetGmodeProtection = 149, + GetGmodeProtectionOverride = 150, + SetGmodeProtectionOverride = 151, + Upgrade = 152, + GetIgnoreBcns = 155, + SetIgnoreBcns = 156, + GetScbTimeout = 157, + SetScbTimeout = 158, + GetAssoclist = 159, + GetClk = 160, + SetClk = 161, + GetUp = 162, + Out = 163, + GetWpaAuth = 164, + SetWpaAuth = 165, + GetUcflags = 166, + SetUcflags = 167, + GetPwridx = 168, + SetPwridx = 169, + GetTssi = 170, + GetSupRatesetOverride = 171, + SetSupRatesetOverride = 172, + GetProtectionControl = 178, + SetProtectionControl = 179, + GetPhylist = 180, + EncryptStrength = 181, + DecryptStatus = 182, + GetKeySeq = 183, + GetScanChannelTime = 184, + SetScanChannelTime = 185, + GetScanUnassocTime = 186, + SetScanUnassocTime = 187, + GetScanHomeTime = 188, + SetScanHomeTime = 189, + GetScanNprobes = 190, + SetScanNprobes = 191, + GetPrbRespTimeout = 192, + SetPrbRespTimeout = 193, + GetAtten = 194, + SetAtten = 195, + GetShmem = 196, + SetShmem = 197, + SetWsecTest = 200, + ScbDeauthenticateForReason = 201, + TkipCountermeasures = 202, + GetPiomode = 203, + SetPiomode = 204, + SetAssocPrefer = 205, + GetAssocPrefer = 206, + SetRoamPrefer = 207, + GetRoamPrefer = 208, + SetLed = 209, + GetLed = 210, + GetInterferenceMode = 211, + SetInterferenceMode = 212, + GetChannelQa = 213, + StartChannelQa = 214, + GetChannelSel = 215, + StartChannelSel = 216, + GetValidChannels = 217, + GetFakefrag = 218, + SetFakefrag = 219, + GetPwroutPercentage = 220, + SetPwroutPercentage = 221, + SetBadFramePreempt = 222, + GetBadFramePreempt = 223, + SetLeapList = 224, + GetLeapList = 225, + GetCwmin = 226, + SetCwmin = 227, + GetCwmax = 228, + SetCwmax = 229, + GetWet = 230, + SetWet = 231, + GetPub = 232, + GetKeyPrimary = 235, + SetKeyPrimary = 236, + GetAciArgs = 238, + SetAciArgs = 239, + UnsetCallback = 240, + SetCallback = 241, + GetRadar = 242, + SetRadar = 243, + SetSpectManagment = 244, + GetSpectManagment = 245, + WdsGetRemoteHwaddr = 246, + WdsGetWpaSup = 247, + SetCsScanTimer = 248, + GetCsScanTimer = 249, + MeasureRequest = 250, + Init = 251, + SendQuiet = 252, + Keepalive = 253, + SendPwrConstraint = 254, + UpgradeStatus = 255, + CurrentPwr = 256, + GetScanPassiveTime = 257, + SetScanPassiveTime = 258, + LegacyLinkBehavior = 259, + GetChannelsInCountry = 260, + GetCountryList = 261, + GetVar = 262, + SetVar = 263, + NvramGet = 264, + NvramSet = 265, + NvramDump = 266, + Reboot = 267, + SetWsecPmk = 268, + GetAuthMode = 269, + SetAuthMode = 270, + GetWakeentry = 271, + SetWakeentry = 272, + NdconfigItem = 273, + Nvotpw = 274, + Otpw = 275, + IovBlockGet = 276, + IovModulesGet = 277, + SoftReset = 278, + GetAllowMode = 279, + SetAllowMode = 280, + GetDesiredBssid = 281, + SetDesiredBssid = 282, + DisassocMyap = 283, + GetNbands = 284, + GetBandstates = 285, + GetWlcBssInfo = 286, + GetAssocInfo = 287, + GetOidPhy = 288, + SetOidPhy = 289, + SetAssocTime = 290, + GetDesiredSsid = 291, + GetChanspec = 292, + GetAssocState = 293, + SetPhyState = 294, + GetScanPending = 295, + GetScanreqPending = 296, + GetPrevRoamReason = 297, + SetPrevRoamReason = 298, + GetBandstatesPi = 299, + GetPhyState = 300, + GetBssWpaRsn = 301, + GetBssWpa2Rsn = 302, + GetBssBcnTs = 303, + GetIntDisassoc = 304, + SetNumPeers = 305, + GetNumBss = 306, + GetWsecPmk = 318, + GetRandomBytes = 319, +} + +pub(crate) const WSEC_TKIP: u32 = 0x02; +pub(crate) const WSEC_AES: u32 = 0x04; + +pub(crate) const AUTH_OPEN: u32 = 0x00; +pub(crate) const AUTH_SAE: u32 = 0x03; + +pub(crate) const MFP_NONE: u32 = 0; +pub(crate) const MFP_CAPABLE: u32 = 1; +pub(crate) const MFP_REQUIRED: u32 = 2; + +pub(crate) const WPA_AUTH_DISABLED: u32 = 0x0000; +pub(crate) const WPA_AUTH_WPA_PSK: u32 = 0x0004; +pub(crate) const WPA_AUTH_WPA2_PSK: u32 = 0x0080; +pub(crate) const WPA_AUTH_WPA3_SAE_PSK: u32 = 0x40000; diff --git a/cyw43/src/control.rs b/cyw43/src/control.rs index 135b8c245..071ba88e4 100644 --- a/cyw43/src/control.rs +++ b/cyw43/src/control.rs @@ -35,16 +35,19 @@ pub struct Control<'a> { ioctl_state: &'a IoctlState, } -#[derive(Copy, Clone)] +#[derive(Copy, Clone, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum ScanType { Active, Passive, } -#[derive(Clone)] +/// Scan options. +#[derive(Clone, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] pub struct ScanOptions { + /// SSID to scan for. pub ssid: Option>, /// If set to `None`, all APs will be returned. If set to `Some`, only APs /// with the specified BSSID will be returned. @@ -72,6 +75,79 @@ impl Default for ScanOptions { } } +/// Authentication type, used in [`JoinOptions::auth`]. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum JoinAuth { + /// Open network + Open, + /// WPA only + Wpa, + /// WPA2 only + Wpa2, + /// WPA3 only + Wpa3, + /// WPA2 + WPA3 + Wpa2Wpa3, +} + +/// Options for [`Control::join`]. +#[derive(Clone, Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub struct JoinOptions<'a> { + /// Authentication type. Default `Wpa2Wpa3`. + pub auth: JoinAuth, + /// Enable TKIP encryption. Default false. + pub cipher_tkip: bool, + /// Enable AES encryption. Default true. + pub cipher_aes: bool, + /// Passphrase. Default empty. + pub passphrase: &'a [u8], + /// If false, `passphrase` is the human-readable passphrase string. + /// If true, `passphrase` is the result of applying the PBKDF2 hash to the + /// passphrase string. This makes it possible to avoid storing unhashed passwords. + /// + /// This is not compatible with WPA3. + /// Default false. + pub passphrase_is_prehashed: bool, +} + +impl<'a> JoinOptions<'a> { + /// Create a new `JoinOptions` for joining open networks. + pub fn new_open() -> Self { + Self { + auth: JoinAuth::Open, + cipher_tkip: false, + cipher_aes: false, + passphrase: &[], + passphrase_is_prehashed: false, + } + } + + /// Create a new `JoinOptions` for joining encrypted networks. + /// + /// Defaults to supporting WPA2+WPA3 with AES only, you may edit + /// the returned options to change this. + pub fn new(passphrase: &'a [u8]) -> Self { + let mut this = Self::default(); + this.passphrase = passphrase; + this + } +} + +impl<'a> Default for JoinOptions<'a> { + fn default() -> Self { + Self { + auth: JoinAuth::Wpa2Wpa3, + cipher_tkip: false, + cipher_aes: true, + passphrase: &[], + passphrase_is_prehashed: false, + } + } +} + impl<'a> Control<'a> { pub(crate) fn new(state_ch: ch::StateRunner<'a>, event_sub: &'a Events, ioctl_state: &'a IoctlState) -> Self { Self { @@ -81,8 +157,7 @@ impl<'a> Control<'a> { } } - /// Initialize WiFi controller. - pub async fn init(&mut self, clm: &[u8]) { + async fn load_clm(&mut self, clm: &[u8]) { const CHUNK_SIZE: usize = 1024; debug!("Downloading CLM..."); @@ -108,12 +183,17 @@ impl<'a> Control<'a> { buf[0..8].copy_from_slice(b"clmload\x00"); buf[8..20].copy_from_slice(&header.to_bytes()); buf[20..][..chunk.len()].copy_from_slice(&chunk); - self.ioctl(IoctlType::Set, IOCTL_CMD_SET_VAR, 0, &mut buf[..8 + 12 + chunk.len()]) + self.ioctl(IoctlType::Set, Ioctl::SetVar, 0, &mut buf[..8 + 12 + chunk.len()]) .await; } // check clmload ok assert_eq!(self.get_iovar_u32("clmload_status").await, 0); + } + + /// Initialize WiFi controller. + pub async fn init(&mut self, clm: &[u8]) { + self.load_clm(&clm).await; debug!("Configuring misc stuff..."); @@ -124,8 +204,7 @@ impl<'a> Control<'a> { self.set_iovar_u32("apsta", 1).await; // read MAC addr. - let mut mac_addr = [0; 6]; - assert_eq!(self.get_iovar("cur_etheraddr", &mut mac_addr).await, 6); + let mac_addr = self.address().await; debug!("mac addr: {:02x}", Bytes(&mac_addr)); let country = countries::WORLD_WIDE_XX; @@ -140,7 +219,7 @@ impl<'a> Control<'a> { Timer::after_millis(100).await; // Set antenna to chip antenna - self.ioctl_set_u32(IOCTL_CMD_ANTDIV, 0, 0).await; + self.ioctl_set_u32(Ioctl::SetAntdiv, 0, 0).await; self.set_iovar_u32("bus:txglom", 0).await; Timer::after_millis(100).await; @@ -178,24 +257,24 @@ impl<'a> Control<'a> { Timer::after_millis(100).await; - self.ioctl_set_u32(110, 0, 1).await; // SET_GMODE = auto - self.ioctl_set_u32(142, 0, 0).await; // SET_BAND = any + self.ioctl_set_u32(Ioctl::SetGmode, 0, 1).await; // SET_GMODE = auto + self.ioctl_set_u32(Ioctl::SetBand, 0, 0).await; // SET_BAND = any Timer::after_millis(100).await; self.state_ch.set_hardware_address(HardwareAddress::Ethernet(mac_addr)); - debug!("INIT DONE"); + debug!("cyw43 control init done"); } /// Set the WiFi interface up. async fn up(&mut self) { - self.ioctl(IoctlType::Set, IOCTL_CMD_UP, 0, &mut []).await; + self.ioctl(IoctlType::Set, Ioctl::Up, 0, &mut []).await; } /// Set the interface down. async fn down(&mut self) { - self.ioctl(IoctlType::Set, IOCTL_CMD_DOWN, 0, &mut []).await; + self.ioctl(IoctlType::Set, Ioctl::Down, 0, &mut []).await; } /// Set power management mode. @@ -208,50 +287,74 @@ impl<'a> Control<'a> { self.set_iovar_u32("bcn_li_dtim", mode.dtim_period() as u32).await; self.set_iovar_u32("assoc_listen", mode.assoc() as u32).await; } - self.ioctl_set_u32(86, 0, mode_num).await; + self.ioctl_set_u32(Ioctl::SetPm, 0, mode_num).await; } /// Join an unprotected network with the provided ssid. - pub async fn join_open(&mut self, ssid: &str) -> Result<(), Error> { + pub async fn join(&mut self, ssid: &str, options: JoinOptions<'_>) -> Result<(), Error> { self.set_iovar_u32("ampdu_ba_wsize", 8).await; - self.ioctl_set_u32(134, 0, 0).await; // wsec = open - self.set_iovar_u32x2("bsscfg:sup_wpa", 0, 0).await; - self.ioctl_set_u32(20, 0, 1).await; // set_infra = 1 - self.ioctl_set_u32(22, 0, 0).await; // set_auth = open (0) + if options.auth == JoinAuth::Open { + self.ioctl_set_u32(Ioctl::SetWsec, 0, 0).await; + self.set_iovar_u32x2("bsscfg:sup_wpa", 0, 0).await; + self.ioctl_set_u32(Ioctl::SetInfra, 0, 1).await; + self.ioctl_set_u32(Ioctl::SetAuth, 0, 0).await; + self.ioctl_set_u32(Ioctl::SetWpaAuth, 0, WPA_AUTH_DISABLED).await; + } else { + let mut wsec = 0; + if options.cipher_aes { + wsec |= WSEC_AES; + } + if options.cipher_tkip { + wsec |= WSEC_TKIP; + } + self.ioctl_set_u32(Ioctl::SetWsec, 0, wsec).await; - let mut i = SsidInfo { - len: ssid.len() as _, - ssid: [0; 32], - }; - i.ssid[..ssid.len()].copy_from_slice(ssid.as_bytes()); + self.set_iovar_u32x2("bsscfg:sup_wpa", 0, 1).await; + self.set_iovar_u32x2("bsscfg:sup_wpa2_eapver", 0, 0xFFFF_FFFF).await; + self.set_iovar_u32x2("bsscfg:sup_wpa_tmo", 0, 2500).await; - self.wait_for_join(i).await - } + Timer::after_millis(100).await; - /// Join an protected network with the provided ssid and passphrase. - pub async fn join_wpa2(&mut self, ssid: &str, passphrase: &str) -> Result<(), Error> { - self.set_iovar_u32("ampdu_ba_wsize", 8).await; + let (wpa12, wpa3, auth, mfp, wpa_auth) = match options.auth { + JoinAuth::Open => unreachable!(), + JoinAuth::Wpa => (true, false, AUTH_OPEN, MFP_NONE, WPA_AUTH_WPA_PSK), + JoinAuth::Wpa2 => (true, false, AUTH_OPEN, MFP_CAPABLE, WPA_AUTH_WPA2_PSK), + JoinAuth::Wpa3 => (false, true, AUTH_SAE, MFP_REQUIRED, WPA_AUTH_WPA3_SAE_PSK), + JoinAuth::Wpa2Wpa3 => (true, true, AUTH_SAE, MFP_CAPABLE, WPA_AUTH_WPA3_SAE_PSK), + }; - self.ioctl_set_u32(134, 0, 4).await; // wsec = wpa2 - self.set_iovar_u32x2("bsscfg:sup_wpa", 0, 1).await; - self.set_iovar_u32x2("bsscfg:sup_wpa2_eapver", 0, 0xFFFF_FFFF).await; - self.set_iovar_u32x2("bsscfg:sup_wpa_tmo", 0, 2500).await; + if wpa12 { + let mut flags = 0; + if !options.passphrase_is_prehashed { + flags |= 1; + } + let mut pfi = PassphraseInfo { + len: options.passphrase.len() as _, + flags, + passphrase: [0; 64], + }; + pfi.passphrase[..options.passphrase.len()].copy_from_slice(options.passphrase); + Timer::after_millis(3).await; + self.ioctl(IoctlType::Set, Ioctl::SetWsecPmk, 0, &mut pfi.to_bytes()) + .await; + } - Timer::after_millis(100).await; + if wpa3 { + let mut pfi = SaePassphraseInfo { + len: options.passphrase.len() as _, + passphrase: [0; 128], + }; + pfi.passphrase[..options.passphrase.len()].copy_from_slice(options.passphrase); + Timer::after_millis(3).await; + self.set_iovar("sae_password", &pfi.to_bytes()).await; + } - let mut pfi = PassphraseInfo { - len: passphrase.len() as _, - flags: 1, - passphrase: [0; 64], - }; - pfi.passphrase[..passphrase.len()].copy_from_slice(passphrase.as_bytes()); - self.ioctl(IoctlType::Set, IOCTL_CMD_SET_PASSPHRASE, 0, &mut pfi.to_bytes()) - .await; // WLC_SET_WSEC_PMK - - self.ioctl_set_u32(20, 0, 1).await; // set_infra = 1 - self.ioctl_set_u32(22, 0, 0).await; // set_auth = 0 (open) - self.ioctl_set_u32(165, 0, 0x80).await; // set_wpa_auth + self.ioctl_set_u32(Ioctl::SetInfra, 0, 1).await; + self.ioctl_set_u32(Ioctl::SetAuth, 0, auth).await; + self.set_iovar_u32("mfp", mfp).await; + self.ioctl_set_u32(Ioctl::SetWpaAuth, 0, wpa_auth).await; + } let mut i = SsidInfo { len: ssid.len() as _, @@ -268,9 +371,7 @@ impl<'a> Control<'a> { // the actual join operation starts here // we make sure to enable events before so we don't miss any - // set_ssid - self.ioctl(IoctlType::Set, IOCTL_CMD_SET_SSID, 0, &mut i.to_bytes()) - .await; + self.ioctl(IoctlType::Set, Ioctl::SetSsid, 0, &mut i.to_bytes()).await; // to complete the join, we wait for a SET_SSID event // we also save the AUTH status for the user, it may be interesting @@ -331,7 +432,7 @@ impl<'a> Control<'a> { self.up().await; // Turn on AP mode - self.ioctl_set_u32(IOCTL_CMD_SET_AP, 0, 1).await; + self.ioctl_set_u32(Ioctl::SetAp, 0, 1).await; // Set SSID let mut i = SsidInfoWithIndex { @@ -345,7 +446,7 @@ impl<'a> Control<'a> { self.set_iovar("bsscfg:ssid", &i.to_bytes()).await; // Set channel number - self.ioctl_set_u32(IOCTL_CMD_SET_CHANNEL, 0, channel as u32).await; + self.ioctl_set_u32(Ioctl::SetChannel, 0, channel as u32).await; // Set security self.set_iovar_u32x2("bsscfg:wsec", 0, (security as u32) & 0xFF).await; @@ -362,7 +463,7 @@ impl<'a> Control<'a> { passphrase: [0; 64], }; pfi.passphrase[..passphrase.as_bytes().len()].copy_from_slice(passphrase.as_bytes()); - self.ioctl(IoctlType::Set, IOCTL_CMD_SET_PASSPHRASE, 0, &mut pfi.to_bytes()) + self.ioctl(IoctlType::Set, Ioctl::SetWsecPmk, 0, &mut pfi.to_bytes()) .await; } @@ -373,6 +474,24 @@ impl<'a> Control<'a> { self.set_iovar_u32x2("bss", 0, 1).await; // bss = BSS_UP } + /// Closes access point. + pub async fn close_ap(&mut self) { + // Stop AP + self.set_iovar_u32x2("bss", 0, 0).await; // bss = BSS_DOWN + + // Turn off AP mode + self.ioctl_set_u32(Ioctl::SetAp, 0, 0).await; + + // Temporarily set wifi down + self.down().await; + + // Turn on APSTA mode + self.set_iovar_u32("apsta", 1).await; + + // Set wifi up again + self.up().await; + } + /// Add specified address to the list of hardware addresses the device /// listens on. The address must be a Group address (I/G bit set). Up /// to 10 addresses are supported by the firmware. Returns the number of @@ -440,11 +559,11 @@ impl<'a> Control<'a> { } async fn set_iovar(&mut self, name: &str, val: &[u8]) { - self.set_iovar_v::<64>(name, val).await + self.set_iovar_v::<196>(name, val).await } async fn set_iovar_v(&mut self, name: &str, val: &[u8]) { - debug!("set {} = {:02x}", name, Bytes(val)); + debug!("iovar set {} = {:02x}", name, Bytes(val)); let mut buf = [0; BUFSIZE]; buf[..name.len()].copy_from_slice(name.as_bytes()); @@ -452,13 +571,13 @@ impl<'a> Control<'a> { buf[name.len() + 1..][..val.len()].copy_from_slice(val); let total_len = name.len() + 1 + val.len(); - self.ioctl(IoctlType::Set, IOCTL_CMD_SET_VAR, 0, &mut buf[..total_len]) + self.ioctl_inner(IoctlType::Set, Ioctl::SetVar, 0, &mut buf[..total_len]) .await; } // TODO this is not really working, it always returns all zeros. async fn get_iovar(&mut self, name: &str, res: &mut [u8]) -> usize { - debug!("get {}", name); + debug!("iovar get {}", name); let mut buf = [0; 64]; buf[..name.len()].copy_from_slice(name.as_bytes()); @@ -466,7 +585,7 @@ impl<'a> Control<'a> { let total_len = max(name.len() + 1, res.len()); let res_len = self - .ioctl(IoctlType::Get, IOCTL_CMD_GET_VAR, 0, &mut buf[..total_len]) + .ioctl_inner(IoctlType::Get, Ioctl::GetVar, 0, &mut buf[..total_len]) .await; let out_len = min(res.len(), res_len); @@ -474,12 +593,20 @@ impl<'a> Control<'a> { out_len } - async fn ioctl_set_u32(&mut self, cmd: u32, iface: u32, val: u32) { + async fn ioctl_set_u32(&mut self, cmd: Ioctl, iface: u32, val: u32) { let mut buf = val.to_le_bytes(); self.ioctl(IoctlType::Set, cmd, iface, &mut buf).await; } - async fn ioctl(&mut self, kind: IoctlType, cmd: u32, iface: u32, buf: &mut [u8]) -> usize { + async fn ioctl(&mut self, kind: IoctlType, cmd: Ioctl, iface: u32, buf: &mut [u8]) -> usize { + if kind == IoctlType::Set { + debug!("ioctl set {:?} iface {} = {:02x}", cmd, iface, Bytes(buf)); + } + let n = self.ioctl_inner(kind, cmd, iface, buf).await; + n + } + + async fn ioctl_inner(&mut self, kind: IoctlType, cmd: Ioctl, iface: u32, buf: &mut [u8]) -> usize { struct CancelOnDrop<'a>(&'a IoctlState); impl CancelOnDrop<'_> { @@ -571,9 +698,16 @@ impl<'a> Control<'a> { } /// Leave the wifi, with which we are currently associated. pub async fn leave(&mut self) { - self.ioctl(IoctlType::Set, IOCTL_CMD_DISASSOC, 0, &mut []).await; + self.ioctl(IoctlType::Set, Ioctl::Disassoc, 0, &mut []).await; info!("Disassociated") } + + /// Gets the MAC address of the device + pub async fn address(&mut self) -> [u8; 6] { + let mut mac_addr = [0; 6]; + assert_eq!(self.get_iovar("cur_etheraddr", &mut mac_addr).await, 6); + mac_addr + } } /// WiFi network scanner. diff --git a/cyw43/src/fmt.rs b/cyw43/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/cyw43/src/fmt.rs +++ b/cyw43/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/cyw43/src/ioctl.rs b/cyw43/src/ioctl.rs index 61524c274..f8b2d9aba 100644 --- a/cyw43/src/ioctl.rs +++ b/cyw43/src/ioctl.rs @@ -4,9 +4,10 @@ use core::task::{Poll, Waker}; use embassy_sync::waitqueue::WakerRegistration; +use crate::consts::Ioctl; use crate::fmt::Bytes; -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq, Eq)] pub enum IoctlType { Get = 0, Set = 2, @@ -16,7 +17,7 @@ pub enum IoctlType { pub struct PendingIoctl { pub buf: *mut [u8], pub kind: IoctlType, - pub cmd: u32, + pub cmd: Ioctl, pub iface: u32, } @@ -101,7 +102,7 @@ impl IoctlState { self.state.set(IoctlStateInner::Done { resp_len: 0 }); } - pub async fn do_ioctl(&self, kind: IoctlType, cmd: u32, iface: u32, buf: &mut [u8]) -> usize { + pub async fn do_ioctl(&self, kind: IoctlType, cmd: Ioctl, iface: u32, buf: &mut [u8]) -> usize { self.state .set(IoctlStateInner::Pending(PendingIoctl { buf, kind, cmd, iface })); self.wake_runner(); diff --git a/cyw43/src/lib.rs b/cyw43/src/lib.rs index 19b0cb194..3cd0e4988 100644 --- a/cyw43/src/lib.rs +++ b/cyw43/src/lib.rs @@ -8,18 +8,19 @@ // This mod MUST go first, so that the others see its macros. pub(crate) mod fmt; +#[cfg(feature = "bluetooth")] +/// Bluetooth module. +pub mod bluetooth; mod bus; mod consts; +mod control; mod countries; mod events; mod ioctl; -mod structs; - -mod control; mod nvram; mod runner; - -use core::slice; +mod structs; +mod util; use embassy_net_driver_channel as ch; use embedded_hal_1::digital::OutputPin; @@ -28,7 +29,9 @@ use ioctl::IoctlState; use crate::bus::Bus; pub use crate::bus::SpiBusCyw43; -pub use crate::control::{AddMulticastAddressError, Control, Error as ControlError, Scanner}; +pub use crate::control::{ + AddMulticastAddressError, Control, Error as ControlError, JoinAuth, JoinOptions, ScanOptions, Scanner, +}; pub use crate::runner::Runner; pub use crate::structs::BssInfo; @@ -56,6 +59,7 @@ impl Core { struct Chip { arm_core_base_address: u32, socsram_base_address: u32, + bluetooth_base_address: u32, socsram_wrapper_base_address: u32, sdiod_core_base_address: u32, pmu_base_address: u32, @@ -83,6 +87,7 @@ const WRAPPER_REGISTER_OFFSET: u32 = 0x100000; const CHIP: Chip = Chip { arm_core_base_address: 0x18003000 + WRAPPER_REGISTER_OFFSET, socsram_base_address: 0x18004000, + bluetooth_base_address: 0x19000000, socsram_wrapper_base_address: 0x18004000 + WRAPPER_REGISTER_OFFSET, sdiod_core_base_address: 0x18002000, pmu_base_address: 0x18000000, @@ -107,6 +112,12 @@ const CHIP: Chip = Chip { /// Driver state. pub struct State { ioctl_state: IoctlState, + net: NetState, + #[cfg(feature = "bluetooth")] + bt: bluetooth::BtState, +} + +struct NetState { ch: ch::State, events: Events, } @@ -116,8 +127,12 @@ impl State { pub fn new() -> Self { Self { ioctl_state: IoctlState::new(), - ch: ch::State::new(), - events: Events::new(), + net: NetState { + ch: ch::State::new(), + events: Events::new(), + }, + #[cfg(feature = "bluetooth")] + bt: bluetooth::BtState::new(), } } } @@ -225,21 +240,60 @@ where PWR: OutputPin, SPI: SpiBusCyw43, { - let (ch_runner, device) = ch::new(&mut state.ch, ch::driver::HardwareAddress::Ethernet([0; 6])); + let (ch_runner, device) = ch::new(&mut state.net.ch, ch::driver::HardwareAddress::Ethernet([0; 6])); let state_ch = ch_runner.state_runner(); - let mut runner = Runner::new(ch_runner, Bus::new(pwr, spi), &state.ioctl_state, &state.events); + let mut runner = Runner::new( + ch_runner, + Bus::new(pwr, spi), + &state.ioctl_state, + &state.net.events, + #[cfg(feature = "bluetooth")] + None, + ); - runner.init(firmware).await; + runner.init(firmware, None).await; + let control = Control::new(state_ch, &state.net.events, &state.ioctl_state); - ( - device, - Control::new(state_ch, &state.events, &state.ioctl_state), - runner, - ) + (device, control, runner) } -fn slice8_mut(x: &mut [u32]) -> &mut [u8] { - let len = x.len() * 4; - unsafe { slice::from_raw_parts_mut(x.as_mut_ptr() as _, len) } +/// Create a new instance of the CYW43 driver. +/// +/// Returns a handle to the network device, control handle and a runner for driving the low level +/// stack. +#[cfg(feature = "bluetooth")] +pub async fn new_with_bluetooth<'a, PWR, SPI>( + state: &'a mut State, + pwr: PWR, + spi: SPI, + wifi_firmware: &[u8], + bluetooth_firmware: &[u8], +) -> ( + NetDriver<'a>, + bluetooth::BtDriver<'a>, + Control<'a>, + Runner<'a, PWR, SPI>, +) +where + PWR: OutputPin, + SPI: SpiBusCyw43, +{ + let (ch_runner, device) = ch::new(&mut state.net.ch, ch::driver::HardwareAddress::Ethernet([0; 6])); + let state_ch = ch_runner.state_runner(); + + let (bt_runner, bt_driver) = bluetooth::new(&mut state.bt); + let mut runner = Runner::new( + ch_runner, + Bus::new(pwr, spi), + &state.ioctl_state, + &state.net.events, + #[cfg(feature = "bluetooth")] + Some(bt_runner), + ); + + runner.init(wifi_firmware, Some(bluetooth_firmware)).await; + let control = Control::new(state_ch, &state.net.events, &state.ioctl_state); + + (device, bt_driver, control, runner) } diff --git a/cyw43/src/runner.rs b/cyw43/src/runner.rs index b2a9e3e80..77910b281 100644 --- a/cyw43/src/runner.rs +++ b/cyw43/src/runner.rs @@ -1,6 +1,5 @@ -use embassy_futures::select::{select3, Either3}; +use embassy_futures::select::{select4, Either4}; use embassy_net_driver_channel as ch; -use embassy_sync::pubsub::PubSubBehavior; use embassy_time::{block_for, Duration, Timer}; use embedded_hal_1::digital::OutputPin; @@ -12,7 +11,8 @@ use crate::fmt::Bytes; use crate::ioctl::{IoctlState, IoctlType, PendingIoctl}; use crate::nvram::NVRAM; use crate::structs::*; -use crate::{events, slice8_mut, Core, CHIP, MTU}; +use crate::util::slice8_mut; +use crate::{events, Core, CHIP, MTU}; #[cfg(feature = "firmware-logs")] struct LogState { @@ -37,7 +37,7 @@ impl Default for LogState { /// Driver communicating with the WiFi chip. pub struct Runner<'a, PWR, SPI> { ch: ch::Runner<'a, MTU>, - bus: Bus, + pub(crate) bus: Bus, ioctl_state: &'a IoctlState, ioctl_id: u16, @@ -48,6 +48,9 @@ pub struct Runner<'a, PWR, SPI> { #[cfg(feature = "firmware-logs")] log: LogState, + + #[cfg(feature = "bluetooth")] + pub(crate) bt: Option>, } impl<'a, PWR, SPI> Runner<'a, PWR, SPI> @@ -60,6 +63,7 @@ where bus: Bus, ioctl_state: &'a IoctlState, events: &'a Events, + #[cfg(feature = "bluetooth")] bt: Option>, ) -> Self { Self { ch, @@ -71,33 +75,52 @@ where events, #[cfg(feature = "firmware-logs")] log: LogState::default(), + #[cfg(feature = "bluetooth")] + bt, } } - pub(crate) async fn init(&mut self, firmware: &[u8]) { - self.bus.init().await; + pub(crate) async fn init(&mut self, wifi_fw: &[u8], bt_fw: Option<&[u8]>) { + self.bus.init(bt_fw.is_some()).await; // Init ALP (Active Low Power) clock + debug!("init alp"); self.bus .write8(FUNC_BACKPLANE, REG_BACKPLANE_CHIP_CLOCK_CSR, BACKPLANE_ALP_AVAIL_REQ) .await; + + debug!("set f2 watermark"); + self.bus + .write8(FUNC_BACKPLANE, REG_BACKPLANE_FUNCTION2_WATERMARK, 0x10) + .await; + let watermark = self.bus.read8(FUNC_BACKPLANE, REG_BACKPLANE_FUNCTION2_WATERMARK).await; + debug!("watermark = {:02x}", watermark); + assert!(watermark == 0x10); + debug!("waiting for clock..."); while self.bus.read8(FUNC_BACKPLANE, REG_BACKPLANE_CHIP_CLOCK_CSR).await & BACKPLANE_ALP_AVAIL == 0 {} debug!("clock ok"); + // clear request for ALP + debug!("clear request for ALP"); + self.bus.write8(FUNC_BACKPLANE, REG_BACKPLANE_CHIP_CLOCK_CSR, 0).await; + let chip_id = self.bus.bp_read16(0x1800_0000).await; debug!("chip ID: {}", chip_id); // Upload firmware. self.core_disable(Core::WLAN).await; + self.core_disable(Core::SOCSRAM).await; // TODO: is this needed if we reset right after? self.core_reset(Core::SOCSRAM).await; + + // this is 4343x specific stuff: Disable remap for SRAM_3 self.bus.bp_write32(CHIP.socsram_base_address + 0x10, 3).await; self.bus.bp_write32(CHIP.socsram_base_address + 0x44, 0).await; let ram_addr = CHIP.atcm_ram_base_address; debug!("loading fw"); - self.bus.bp_write(ram_addr, firmware).await; + self.bus.bp_write(ram_addr, wifi_fw).await; debug!("loading nvram"); // Round up to 4 bytes. @@ -117,10 +140,23 @@ where self.core_reset(Core::WLAN).await; assert!(self.core_is_up(Core::WLAN).await); + // wait until HT clock is available; takes about 29ms + debug!("wait for HT clock"); while self.bus.read8(FUNC_BACKPLANE, REG_BACKPLANE_CHIP_CLOCK_CSR).await & 0x80 == 0 {} // "Set up the interrupt mask and enable interrupts" - // self.bus.bp_write32(CHIP.sdiod_core_base_address + 0x24, 0xF0).await; + debug!("setup interrupt mask"); + self.bus + .bp_write32(CHIP.sdiod_core_base_address + SDIO_INT_HOST_MASK, I_HMB_SW_MASK) + .await; + + // Set up the interrupt mask and enable interrupts + if bt_fw.is_some() { + debug!("bluetooth setup interrupt mask"); + self.bus + .bp_write32(CHIP.sdiod_core_base_address + SDIO_INT_HOST_MASK, I_HMB_FC_CHANGE) + .await; + } self.bus .write16(FUNC_BUS, REG_BUS_INTERRUPT_ENABLE, IRQ_F2_PACKET_AVAILABLE) @@ -129,11 +165,11 @@ where // "Lower F2 Watermark to avoid DMA Hang in F2 when SD Clock is stopped." // Sounds scary... self.bus - .write8(FUNC_BACKPLANE, REG_BACKPLANE_FUNCTION2_WATERMARK, 32) + .write8(FUNC_BACKPLANE, REG_BACKPLANE_FUNCTION2_WATERMARK, SPI_F2_WATERMARK) .await; - // wait for wifi startup - debug!("waiting for wifi init..."); + // wait for F2 to be ready + debug!("waiting for F2 to be ready..."); while self.bus.read32(FUNC_BUS, REG_BUS_STATUS).await & STATUS_F2_RX_READY == 0 {} // Some random configs related to sleep. @@ -154,19 +190,27 @@ where */ // clear pulls + debug!("clear pad pulls"); self.bus.write8(FUNC_BACKPLANE, REG_BACKPLANE_PULL_UP, 0).await; let _ = self.bus.read8(FUNC_BACKPLANE, REG_BACKPLANE_PULL_UP).await; // start HT clock - //self.bus.write8(FUNC_BACKPLANE, REG_BACKPLANE_CHIP_CLOCK_CSR, 0x10).await; - //debug!("waiting for HT clock..."); - //while self.bus.read8(FUNC_BACKPLANE, REG_BACKPLANE_CHIP_CLOCK_CSR).await & 0x80 == 0 {} - //debug!("clock ok"); + self.bus + .write8(FUNC_BACKPLANE, REG_BACKPLANE_CHIP_CLOCK_CSR, 0x10) + .await; // SBSDIO_HT_AVAIL_REQ + debug!("waiting for HT clock..."); + while self.bus.read8(FUNC_BACKPLANE, REG_BACKPLANE_CHIP_CLOCK_CSR).await & 0x80 == 0 {} + debug!("clock ok"); #[cfg(feature = "firmware-logs")] self.log_init().await; - debug!("wifi init done"); + #[cfg(feature = "bluetooth")] + if let Some(bt_fw) = bt_fw { + self.bt.as_mut().unwrap().init_bluetooth(&mut self.bus, bt_fw).await; + } + + debug!("cyw43 runner init done"); } #[cfg(feature = "firmware-logs")] @@ -223,7 +267,7 @@ where } } - /// Run the + /// Run the CYW43 event handling loop. pub async fn run(mut self) -> ! { let mut buf = [0; 512]; loop { @@ -232,23 +276,38 @@ where if self.has_credit() { let ioctl = self.ioctl_state.wait_pending(); - let tx = self.ch.tx_buf(); + let wifi_tx = self.ch.tx_buf(); + #[cfg(feature = "bluetooth")] + let bt_tx = async { + match &mut self.bt { + Some(bt) => bt.tx_chan.receive().await, + None => core::future::pending().await, + } + }; + #[cfg(not(feature = "bluetooth"))] + let bt_tx = core::future::pending::<()>(); + + // interrupts aren't working yet for bluetooth. Do busy-polling instead. + // Note for this to work `ev` has to go last in the `select()`. It prefers + // first futures if they're ready, so other select branches don't get starved.` + #[cfg(feature = "bluetooth")] + let ev = core::future::ready(()); + #[cfg(not(feature = "bluetooth"))] let ev = self.bus.wait_for_event(); - match select3(ioctl, tx, ev).await { - Either3::First(PendingIoctl { + match select4(ioctl, wifi_tx, bt_tx, ev).await { + Either4::First(PendingIoctl { buf: iobuf, kind, cmd, iface, }) => { - self.send_ioctl(kind, cmd, iface, unsafe { &*iobuf }).await; + self.send_ioctl(kind, cmd, iface, unsafe { &*iobuf }, &mut buf).await; self.check_status(&mut buf).await; } - Either3::Second(packet) => { + Either4::Second(packet) => { trace!("tx pkt {:02x}", Bytes(&packet[..packet.len().min(48)])); - let mut buf = [0; 512]; let buf8 = slice8_mut(&mut buf); // There MUST be 2 bytes of padding between the SDPCM and BDC headers. @@ -300,8 +359,19 @@ where self.ch.tx_done(); self.check_status(&mut buf).await; } - Either3::Third(()) => { + Either4::Third(_) => { + #[cfg(feature = "bluetooth")] + self.bt.as_mut().unwrap().hci_write(&mut self.bus).await; + } + Either4::Fourth(()) => { self.handle_irq(&mut buf).await; + + // If we do busy-polling, make sure to yield. + // `handle_irq` will only do a 32bit read if there's no work to do, which is really fast. + // Depending on optimization level, it is possible that the 32-bit read finishes on + // first poll, so it never yields and we starve all other tasks. + #[cfg(feature = "bluetooth")] + embassy_futures::yield_now().await; } } } else { @@ -316,17 +386,24 @@ where async fn handle_irq(&mut self, buf: &mut [u32; 512]) { // Receive stuff let irq = self.bus.read16(FUNC_BUS, REG_BUS_INTERRUPT).await; - trace!("irq{}", FormatInterrupt(irq)); + if irq != 0 { + trace!("irq{}", FormatInterrupt(irq)); + } if irq & IRQ_F2_PACKET_AVAILABLE != 0 { self.check_status(buf).await; } if irq & IRQ_DATA_UNAVAILABLE != 0 { - // TODO what should we do here? - warn!("IRQ DATA_UNAVAILABLE, clearing..."); + // this seems to be ignorable with no ill effects. + trace!("IRQ DATA_UNAVAILABLE, clearing..."); self.bus.write16(FUNC_BUS, REG_BUS_INTERRUPT, 1).await; } + + #[cfg(feature = "bluetooth")] + if let Some(bt) = &mut self.bt { + bt.handle_irq(&mut self.bus).await; + } } /// Handle F2 events while status register is set @@ -439,13 +516,16 @@ where // publish() is a deadlock risk in the current design as awaiting here prevents ioctls // The `Runner` always yields when accessing the device, so consumers always have a chance to receive the event // (if they are actively awaiting the queue) - self.events.queue.publish_immediate(events::Message::new( - Status { - event_type: evt_type, - status, - }, - event_payload, - )); + self.events + .queue + .immediate_publisher() + .publish_immediate(events::Message::new( + Status { + event_type: evt_type, + status, + }, + event_payload, + )); } } CHANNEL_TYPE_DATA => { @@ -480,9 +560,8 @@ where self.sdpcm_seq != self.sdpcm_seq_max && self.sdpcm_seq_max.wrapping_sub(self.sdpcm_seq) & 0x80 == 0 } - async fn send_ioctl(&mut self, kind: IoctlType, cmd: u32, iface: u32, data: &[u8]) { - let mut buf = [0; 512]; - let buf8 = slice8_mut(&mut buf); + async fn send_ioctl(&mut self, kind: IoctlType, cmd: Ioctl, iface: u32, data: &[u8], buf: &mut [u32; 512]) { + let buf8 = slice8_mut(buf); let total_len = SdpcmHeader::SIZE + CdcHeader::SIZE + data.len(); @@ -503,7 +582,7 @@ where }; let cdc_header = CdcHeader { - cmd: cmd, + cmd: cmd as u32, len: data.len() as _, flags: kind as u16 | (iface as u16) << 12, id: self.ioctl_id, diff --git a/cyw43/src/structs.rs b/cyw43/src/structs.rs index ae7ef6038..81ae6a98d 100644 --- a/cyw43/src/structs.rs +++ b/cyw43/src/structs.rs @@ -394,6 +394,15 @@ pub struct PassphraseInfo { } impl_bytes!(PassphraseInfo); +#[derive(Clone, Copy)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[repr(C)] +pub struct SaePassphraseInfo { + pub len: u16, + pub passphrase: [u8; 128], +} +impl_bytes!(SaePassphraseInfo); + #[derive(Clone, Copy)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[repr(C)] diff --git a/cyw43/src/util.rs b/cyw43/src/util.rs new file mode 100644 index 000000000..a4adbd4ed --- /dev/null +++ b/cyw43/src/util.rs @@ -0,0 +1,20 @@ +#![allow(unused)] + +use core::slice; + +pub(crate) fn slice8_mut(x: &mut [u32]) -> &mut [u8] { + let len = x.len() * 4; + unsafe { slice::from_raw_parts_mut(x.as_mut_ptr() as _, len) } +} + +pub(crate) fn is_aligned(a: u32, x: u32) -> bool { + (a & (x - 1)) == 0 +} + +pub(crate) fn round_down(x: u32, a: u32) -> u32 { + x & !(a - 1) +} + +pub(crate) fn round_up(x: u32, a: u32) -> u32 { + ((x + a - 1) / a) * a +} diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 000000000..834802d3b --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,8 @@ +all: + asciidoctor -d book -D book/ index.adoc + cp -r images book + +clean: + rm -rf book + +.PHONY: all clean diff --git a/docs/README.md b/docs/README.md index 0bf3a6c89..d766a86d9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,4 +1,29 @@ # embassy docs -The documentation hosted at [https://embassy.dev/book](https://embassy.dev/book). Building the documentation requires -cloning the [embassy-book](https://github.com/embassy-rs/embassy-book) repository and following the instructions. +The documentation hosted at [https://embassy.dev/book](https://embassy.dev/book). Building the documentation requires the [asciidoctor](https://asciidoctor.org/) tool, and can built running `make` in this folder: + +``` +make +``` + +Then open the generated file `thebook/index.html`. + +## License + +The Embassy Docs (this folder) is distributed under the following licenses: + +* The code samples and free-standing Cargo projects contained within these docs are licensed under the terms of both the [MIT License] and the [Apache License v2.0]. +* The written prose contained within these docs are licensed under the terms of the Creative Commons [CC-BY-SA v4.0] license. + +Copies of the licenses used by this project may also be found here: + +* [MIT License Hosted] +* [Apache License v2.0 Hosted] +* [CC-BY-SA v4.0 Hosted] + +[MIT License]: ./../LICENSE-MIT +[Apache License v2.0]: ./../LICENSE-APACHE +[CC-BY-SA v4.0]: ./../LICENSE-CC-BY-SA +[MIT License Hosted]: https://opensource.org/licenses/MIT +[Apache License v2.0 Hosted]: http://www.apache.org/licenses/LICENSE-2.0 +[CC-BY-SA v4.0 Hosted]: https://creativecommons.org/licenses/by-sa/4.0/legalcode diff --git a/docs/antora.yml b/docs/antora.yml deleted file mode 100644 index 9a00fa820..000000000 --- a/docs/antora.yml +++ /dev/null @@ -1,5 +0,0 @@ -name: ROOT -title: Embassy -version: dev -nav: - - modules/ROOT/nav.adoc diff --git a/docs/modules/ROOT/examples/basic/.cargo/config.toml b/docs/examples/basic/.cargo/config.toml similarity index 100% rename from docs/modules/ROOT/examples/basic/.cargo/config.toml rename to docs/examples/basic/.cargo/config.toml diff --git a/docs/examples/basic/Cargo.toml b/docs/examples/basic/Cargo.toml new file mode 100644 index 000000000..5d391adf3 --- /dev/null +++ b/docs/examples/basic/Cargo.toml @@ -0,0 +1,18 @@ +[package] +authors = ["Dario Nieuwenhuis "] +edition = "2018" +name = "embassy-basic-example" +version = "0.1.0" +license = "MIT OR Apache-2.0" + +[dependencies] +embassy-executor = { version = "0.6.0", path = "../../../embassy-executor", features = ["defmt", "integrated-timers", "arch-cortex-m", "executor-thread"] } +embassy-time = { version = "0.3.2", path = "../../../embassy-time", features = ["defmt"] } +embassy-nrf = { version = "0.2.0", path = "../../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote"] } + +defmt = "0.3" +defmt-rtt = "0.3" + +cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] } +cortex-m-rt = "0.7.0" +panic-probe = { version = "0.3", features = ["print-defmt"] } diff --git a/docs/modules/ROOT/examples/basic/build.rs b/docs/examples/basic/build.rs similarity index 100% rename from docs/modules/ROOT/examples/basic/build.rs rename to docs/examples/basic/build.rs diff --git a/docs/modules/ROOT/examples/basic/memory.x b/docs/examples/basic/memory.x similarity index 100% rename from docs/modules/ROOT/examples/basic/memory.x rename to docs/examples/basic/memory.x diff --git a/docs/modules/ROOT/examples/basic/src/main.rs b/docs/examples/basic/src/main.rs similarity index 100% rename from docs/modules/ROOT/examples/basic/src/main.rs rename to docs/examples/basic/src/main.rs diff --git a/docs/examples/examples b/docs/examples/examples new file mode 120000 index 000000000..d15735c1d --- /dev/null +++ b/docs/examples/examples @@ -0,0 +1 @@ +../../examples \ No newline at end of file diff --git a/docs/modules/ROOT/examples/layer-by-layer/.cargo/config.toml b/docs/examples/layer-by-layer/.cargo/config.toml similarity index 100% rename from docs/modules/ROOT/examples/layer-by-layer/.cargo/config.toml rename to docs/examples/layer-by-layer/.cargo/config.toml diff --git a/docs/modules/ROOT/examples/layer-by-layer/Cargo.toml b/docs/examples/layer-by-layer/Cargo.toml similarity index 69% rename from docs/modules/ROOT/examples/layer-by-layer/Cargo.toml rename to docs/examples/layer-by-layer/Cargo.toml index 943249a17..0f233eae5 100644 --- a/docs/modules/ROOT/examples/layer-by-layer/Cargo.toml +++ b/docs/examples/layer-by-layer/Cargo.toml @@ -8,8 +8,8 @@ members = [ ] [patch.crates-io] -embassy-executor = { path = "../../../../../embassy-executor" } -embassy-stm32 = { path = "../../../../../embassy-stm32" } +embassy-executor = { path = "../../../embassy-executor" } +embassy-stm32 = { path = "../../../embassy-stm32" } [profile.release] codegen-units = 1 diff --git a/docs/modules/ROOT/examples/layer-by-layer/blinky-async/Cargo.toml b/docs/examples/layer-by-layer/blinky-async/Cargo.toml similarity index 85% rename from docs/modules/ROOT/examples/layer-by-layer/blinky-async/Cargo.toml rename to docs/examples/layer-by-layer/blinky-async/Cargo.toml index 64f7e8403..7f8d8af3e 100644 --- a/docs/modules/ROOT/examples/layer-by-layer/blinky-async/Cargo.toml +++ b/docs/examples/layer-by-layer/blinky-async/Cargo.toml @@ -8,7 +8,7 @@ license = "MIT OR Apache-2.0" cortex-m = "0.7" cortex-m-rt = "0.7" embassy-stm32 = { version = "0.1.0", features = ["stm32l475vg", "memory-x", "exti"] } -embassy-executor = { version = "0.5.0", features = ["arch-cortex-m", "executor-thread"] } +embassy-executor = { version = "0.6.0", features = ["arch-cortex-m", "executor-thread"] } defmt = "0.3.0" defmt-rtt = "0.3.0" diff --git a/docs/modules/ROOT/examples/layer-by-layer/blinky-async/src/main.rs b/docs/examples/layer-by-layer/blinky-async/src/main.rs similarity index 100% rename from docs/modules/ROOT/examples/layer-by-layer/blinky-async/src/main.rs rename to docs/examples/layer-by-layer/blinky-async/src/main.rs diff --git a/docs/modules/ROOT/examples/layer-by-layer/blinky-hal/Cargo.toml b/docs/examples/layer-by-layer/blinky-hal/Cargo.toml similarity index 100% rename from docs/modules/ROOT/examples/layer-by-layer/blinky-hal/Cargo.toml rename to docs/examples/layer-by-layer/blinky-hal/Cargo.toml diff --git a/docs/modules/ROOT/examples/layer-by-layer/blinky-hal/src/main.rs b/docs/examples/layer-by-layer/blinky-hal/src/main.rs similarity index 100% rename from docs/modules/ROOT/examples/layer-by-layer/blinky-hal/src/main.rs rename to docs/examples/layer-by-layer/blinky-hal/src/main.rs diff --git a/docs/modules/ROOT/examples/layer-by-layer/blinky-irq/Cargo.toml b/docs/examples/layer-by-layer/blinky-irq/Cargo.toml similarity index 100% rename from docs/modules/ROOT/examples/layer-by-layer/blinky-irq/Cargo.toml rename to docs/examples/layer-by-layer/blinky-irq/Cargo.toml diff --git a/docs/modules/ROOT/examples/layer-by-layer/blinky-irq/src/main.rs b/docs/examples/layer-by-layer/blinky-irq/src/main.rs similarity index 100% rename from docs/modules/ROOT/examples/layer-by-layer/blinky-irq/src/main.rs rename to docs/examples/layer-by-layer/blinky-irq/src/main.rs diff --git a/docs/modules/ROOT/examples/layer-by-layer/blinky-pac/Cargo.toml b/docs/examples/layer-by-layer/blinky-pac/Cargo.toml similarity index 100% rename from docs/modules/ROOT/examples/layer-by-layer/blinky-pac/Cargo.toml rename to docs/examples/layer-by-layer/blinky-pac/Cargo.toml diff --git a/docs/modules/ROOT/examples/layer-by-layer/blinky-pac/src/main.rs b/docs/examples/layer-by-layer/blinky-pac/src/main.rs similarity index 100% rename from docs/modules/ROOT/examples/layer-by-layer/blinky-pac/src/main.rs rename to docs/examples/layer-by-layer/blinky-pac/src/main.rs diff --git a/docs/modules/ROOT/images/bootloader_flash.png b/docs/images/bootloader_flash.png similarity index 100% rename from docs/modules/ROOT/images/bootloader_flash.png rename to docs/images/bootloader_flash.png diff --git a/docs/modules/ROOT/images/embassy_executor.drawio b/docs/images/embassy_executor.drawio similarity index 100% rename from docs/modules/ROOT/images/embassy_executor.drawio rename to docs/images/embassy_executor.drawio diff --git a/docs/modules/ROOT/images/embassy_executor.png b/docs/images/embassy_executor.png similarity index 100% rename from docs/modules/ROOT/images/embassy_executor.png rename to docs/images/embassy_executor.png diff --git a/docs/modules/ROOT/images/embassy_irq.drawio b/docs/images/embassy_irq.drawio similarity index 100% rename from docs/modules/ROOT/images/embassy_irq.drawio rename to docs/images/embassy_irq.drawio diff --git a/docs/modules/ROOT/images/embassy_irq.png b/docs/images/embassy_irq.png similarity index 100% rename from docs/modules/ROOT/images/embassy_irq.png rename to docs/images/embassy_irq.png diff --git a/docs/index.adoc b/docs/index.adoc new file mode 100644 index 000000000..9c6150196 --- /dev/null +++ b/docs/index.adoc @@ -0,0 +1,16 @@ +:description: Embassy Book +:sectanchors: +:doctype: book +:toc: +:toc-placement: left +:toclevels: 2 +:imagesdir: images + +# Embassy Book + +Welcome to the Embassy Book. The Embassy Book is for everyone who wants to use Embassy and understand how Embassy works. + +include::pages/overview.adoc[leveloffset = 1] +include::pages/beginners.adoc[leveloffset = 1] +include::pages/system.adoc[leveloffset = 1] +include::pages/faq.adoc[leveloffset = 1] diff --git a/docs/modules/ROOT/examples/basic/Cargo.toml b/docs/modules/ROOT/examples/basic/Cargo.toml deleted file mode 100644 index 2c282145d..000000000 --- a/docs/modules/ROOT/examples/basic/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -authors = ["Dario Nieuwenhuis "] -edition = "2018" -name = "embassy-basic-example" -version = "0.1.0" -license = "MIT OR Apache-2.0" - -[dependencies] -embassy-executor = { version = "0.5.0", path = "../../../../../embassy-executor", features = ["defmt", "integrated-timers", "arch-cortex-m", "executor-thread"] } -embassy-time = { version = "0.3.0", path = "../../../../../embassy-time", features = ["defmt"] } -embassy-nrf = { version = "0.1.0", path = "../../../../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote"] } - -defmt = "0.3" -defmt-rtt = "0.3" - -cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] } -cortex-m-rt = "0.7.0" -panic-probe = { version = "0.3", features = ["print-defmt"] } diff --git a/docs/modules/ROOT/examples/examples b/docs/modules/ROOT/examples/examples deleted file mode 120000 index 1929330b0..000000000 --- a/docs/modules/ROOT/examples/examples +++ /dev/null @@ -1 +0,0 @@ -../../../../examples \ No newline at end of file diff --git a/docs/modules/ROOT/nav.adoc b/docs/modules/ROOT/nav.adoc deleted file mode 100644 index 44b0eddb9..000000000 --- a/docs/modules/ROOT/nav.adoc +++ /dev/null @@ -1,19 +0,0 @@ -* xref:getting_started.adoc[Getting started] -** xref:basic_application.adoc[Basic application] -** xref:project_structure.adoc[Project Structure] -** xref:new_project.adoc[Starting a new Embassy project] -** xref:best_practices.adoc[Best Practices] -* xref:runtime.adoc[Executor] -* xref::time_keeping.adoc[Time-keeping] -* xref:sharing_peripherals.adoc[Sharing peripherals] -* xref:hal.adoc[HAL] -** xref:layer_by_layer.adoc[Anatomy of an async HAL] -** xref:nrf.adoc[nRF] -** xref:stm32.adoc[STM32] -* xref:bootloader.adoc[Bootloader] - -* xref:examples.adoc[Examples] -* xref:developer.adoc[Developer Docs] -** xref:developer_stm32.adoc[Developer Docs: STM32] -* xref:embassy_in_the_wild.adoc[Embassy in the wild] -* xref:faq.adoc[Frequently Asked Questions] diff --git a/docs/modules/ROOT/pages/embassy_in_the_wild.adoc b/docs/modules/ROOT/pages/embassy_in_the_wild.adoc deleted file mode 100644 index a1c31bfc7..000000000 --- a/docs/modules/ROOT/pages/embassy_in_the_wild.adoc +++ /dev/null @@ -1,9 +0,0 @@ -= Embassy in the wild! - -Here are known examples of real-world projects which make use of Embassy. Feel free to link:https://github.com/embassy-rs/embassy/blob/main/docs/modules/ROOT/pages/embassy_in_the_wild.adoc[add more]! - -* link:https://github.com/cbruiz/printhor/[Printhor: The highly reliable but not necessarily functional 3D printer firmware] -** Targets some STM32 MCUs -* link:https://github.com/card-io-ecg/card-io-fw[Card/IO firmware] - firmware for an open source ECG device -** Targets the ESP32-S3 or ESP32-C6 MCU -* The link:https://github.com/lora-rs/lora-rs[lora-rs] project includes link:https://github.com/lora-rs/lora-rs/tree/main/examples/stm32l0/src/bin[various standalone examples] for NRF52840, RP2040, STM32L0 and STM32WL diff --git a/docs/modules/ROOT/pages/faq.adoc b/docs/modules/ROOT/pages/faq.adoc deleted file mode 100644 index 05ff7c598..000000000 --- a/docs/modules/ROOT/pages/faq.adoc +++ /dev/null @@ -1,201 +0,0 @@ -= Frequently Asked Questions - -These are a list of unsorted, commonly asked questions and answers. - -Please feel free to add items to link:https://github.com/embassy-rs/embassy/edit/main/docs/modules/ROOT/pages/faq.adoc[this page], especially if someone in the chat answered a question for you! - -== How to deploy to RP2040 without a debugging probe. - -Install link:https://github.com/JoNil/elf2uf2-rs[elf2uf2-rs] for converting the generated elf binary into a uf2 file. - -Configure the runner to use this tool, add this to `.cargo/config.toml`: -[source,toml] ----- -[target.'cfg(all(target_arch = "arm", target_os = "none"))'] -runner = "elf2uf2-rs --deploy --serial --verbose" ----- - -The command-line parameters `--deploy` will detect your device and upload the binary, `--serial` starts a serial connection. See the documentation for more info. - -== Missing main macro - -If you see an error like this: - -[source,rust] ----- -#[embassy_executor::main] -| ^^^^ could not find `main` in `embassy_executor` ----- - -You are likely missing some features of the `embassy-executor` crate. - -For Cortex-M targets, consider making sure that ALL of the following features are active in your `Cargo.toml` for the `embassy-executor` crate: - -* `arch-cortex-m` -* `executor-thread` -* `nightly` - -For ESP32, consider using the executors and `#[main]` macro provided by your appropriate link:https://crates.io/crates/esp-hal-common[HAL crate]. - -== Why is my binary so big? - -The first step to managing your binary size is to set up your link:https://doc.rust-lang.org/cargo/reference/profiles.html[profiles]. - -[source,toml] ----- -[profile.release] -lto = true -opt-level = "s" -incremental = false -codegen-units = 1 -# note: debug = true is okay - debuginfo isn't flashed to the device! -debug = true ----- - -All of these flags are elaborated on in the Rust Book page linked above. - -=== My binary is still big... filled with `std::fmt` stuff! - -This means your code is sufficiently complex that `panic!` invocation's formatting requirements could not be optimized out, despite your usage of `panic-halt` or `panic-reset`. - -You can remedy this by adding the following to your `.cargo/config.toml`: - -[source,toml] ----- -[unstable] -build-std = ["core"] -build-std-features = ["panic_immediate_abort"] ----- - -This replaces all panics with a `UDF` (undefined) instruction. - -Depending on your chipset, this will exhibit different behavior. - -Refer to the spec for your chipset, but for `thumbv6m`, it results in a hardfault. Which can be configured like so: - -[source,rust] ----- -#[exception] -unsafe fn HardFault(_frame: &ExceptionFrame) -> ! { - SCB::sys_reset() // <- you could do something other than reset -} ----- - -Refer to cortex-m's link:https://docs.rs/cortex-m-rt/latest/cortex_m_rt/attr.exception.html[exception handling] for more info. - -== `embassy-time` throws linker errors - -If you see linker error like this: - -[source,text] ----- - = note: rust-lld: error: undefined symbol: _embassy_time_now - >>> referenced by driver.rs:127 (src/driver.rs:127) - >>> embassy_time-846f66f1620ad42c.embassy_time.4f6a638abb75dd4c-cgu.0.rcgu.o:(embassy_time::driver::now::hefb1f99d6e069842) in archive Devel/Embedded/pogodyna/target/thumbv7em-none-eabihf/debug/deps/libembassy_time-846f66f1620ad42c.rlib - - rust-lld: error: undefined symbol: _embassy_time_allocate_alarm - >>> referenced by driver.rs:134 (src/driver.rs:134) - >>> embassy_time-846f66f1620ad42c.embassy_time.4f6a638abb75dd4c-cgu.0.rcgu.o:(embassy_time::driver::allocate_alarm::hf5145b6bd46706b2) in archive Devel/Embedded/pogodyna/target/thumbv7em-none-eabihf/debug/deps/libembassy_time-846f66f1620ad42c.rlib - - rust-lld: error: undefined symbol: _embassy_time_set_alarm_callback - >>> referenced by driver.rs:139 (src/driver.rs:139) - >>> embassy_time-846f66f1620ad42c.embassy_time.4f6a638abb75dd4c-cgu.0.rcgu.o:(embassy_time::driver::set_alarm_callback::h24f92388d96eafd2) in archive Devel/Embedded/pogodyna/target/thumbv7em-none-eabihf/debug/deps/libembassy_time-846f66f1620ad42c.rlib - - rust-lld: error: undefined symbol: _embassy_time_set_alarm - >>> referenced by driver.rs:144 (src/driver.rs:144) - >>> embassy_time-846f66f1620ad42c.embassy_time.4f6a638abb75dd4c-cgu.0.rcgu.o:(embassy_time::driver::set_alarm::h530a5b1f444a6d5b) in archive Devel/Embedded/pogodyna/target/thumbv7em-none-eabihf/debug/deps/libembassy_time-846f66f1620ad42c.rlib ----- - -You probably need to enable a time driver for your HAL (not in `embassy-time`!). For example with `embassy-stm32`, you might need to enable `time-driver-any`: - -[source,toml] ----- -[dependencies.embassy-stm32] -version = "0.1.0" -features = [ - # ... - "time-driver-any", # Add this line! - # ... -] ----- - -== Error: `Only one package in the dependency graph may specify the same links value.` - -You have multiple versions of the same crate in your dependency tree. This means that some of your -embassy crates are coming from crates.io, and some from git, each of them pulling in a different set -of dependencies. - -To resolve this issue, make sure to only use a single source for all your embassy crates! To do this, -you should patch your dependencies to use git sources using `[patch.crates.io]` and maybe `[patch.'https://github.com/embassy-rs/embassy.git']`. - -Example: - -[source,toml] ----- -[patch.crates-io] -embassy-time = { git = "https://github.com/embassy-rs/embassy.git", rev = "e5fdd35" } ----- - -Note that the git revision should match any other embassy patches or git dependencies that you are using! - -== How can I optimize the speed of my embassy-stm32 program? - -* Make sure RCC is set up to go as fast as possible -* Make sure link:https://docs.rs/cortex-m/latest/cortex_m/peripheral/struct.SCB.html[flash cache] is enabled -* build with `--release` -* Set the following keys for the release profile in your `Cargo.toml`: - ** `opt-level = "s"` - ** `lto = "fat"` -* Set the following keys in the `[unstable]` section of your `.cargo/config.toml` - ** `build-std = ["core"]` - ** `build-std-features = ["panic_immediate_abort"]` -* Enable feature `embassy-time/generic-queue`, disable feature `embassy-executor/integrated-timers` -* When using `InterruptExecutor`: - ** disable `executor-thread` - ** make `main`` spawn everything, then enable link:https://docs.rs/cortex-m/latest/cortex_m/peripheral/struct.SCB.html#method.set_sleeponexit[SCB.SLEEPONEXIT] and `loop { cortex_m::asm::wfi() }` - ** *Note:* If you need 2 priority levels, using 2 interrupt executors is better than 1 thread executor + 1 interrupt executor. - -== How do I set up the task arenas on stable? - -When you aren't using the `nightly` feature of `embassy-executor`, the executor uses a bump allocator, which may require configuration. - -Something like this error will occur at **compile time** if the task arena is *too large* for the target's RAM: - -[source,plain] ----- -rust-lld: error: section '.bss' will not fit in region 'RAM': overflowed by _ bytes -rust-lld: error: section '.uninit' will not fit in region 'RAM': overflowed by _ bytes ----- - -And this message will appear at **runtime** if the task arena is *too small* for the tasks running: - -[source,plain] ----- -ERROR panicked at 'embassy-executor: task arena is full. You must increase the arena size, see the documentation for details: https://docs.embassy.dev/embassy-executor/' ----- - -NOTE: If all tasks are spawned at startup, this panic will occur immediately. - -Check out link:https://docs.embassy.dev/embassy-executor/git/cortex-m/index.html#task-arena[Task Arena Documentation] for more details. - -== Can I use manual ISRs alongside Embassy? - -Yes! This can be useful if you need to respond to an event as fast as possible, and the latency caused by the usual “ISR, wake, return from ISR, context switch to woken task” flow is too much for your application. Simply define a `#[interrupt] fn INTERRUPT_NAME() {}` handler as you would link:https://docs.rust-embedded.org/book/start/interrupts.html[in any other embedded rust project]. - -== How can I measure resource usage (CPU, RAM, etc.)? - -=== For CPU Usage: - -There are a couple techniques that have been documented, generally you want to measure how long you are spending in the idle or low priority loop. - -We need to document specifically how to do this in embassy, but link:https://blog.japaric.io/cpu-monitor/[this older post] describes the general process. - -If you end up doing this, please update this section with more specific examples! - -=== For Static Memory Usage - -Tools like `cargo size` and `cargo nm` can tell you the size of any globals or other static usage. Specifically you will want to see the size of the `.data` and `.bss` sections, which together make up the total global/static memory usage. - -=== For Max Stack Usage - -Check out link:https://github.com/Dirbaio/cargo-call-stack/[`cargo-call-stack`] for statically calculating worst-case stack usage. There are some caveats and inaccuracies possible with this, but this is a good way to get the general idea. See link:https://github.com/dirbaio/cargo-call-stack#known-limitations[the README] for more details. diff --git a/docs/modules/ROOT/pages/basic_application.adoc b/docs/pages/basic_application.adoc similarity index 80% rename from docs/modules/ROOT/pages/basic_application.adoc rename to docs/pages/basic_application.adoc index 95792d5a0..5c4e3e8b3 100644 --- a/docs/modules/ROOT/pages/basic_application.adoc +++ b/docs/pages/basic_application.adoc @@ -1,10 +1,10 @@ = A basic Embassy application -So you've got one of the xref:examples.adoc[examples] running, but what now? Let's go through a simple Embassy application for the nRF52 DK to understand it better. +So you've got one of the examples running, but what now? Let's go through a simple Embassy application for the nRF52 DK to understand it better. == Main -The full example can be found link:https://github.com/embassy-rs/embassy/tree/master/docs/modules/ROOT/examples/basic[here]. +The full example can be found link:https://github.com/embassy-rs/embassy/tree/main/docs/examples/basic[here]. NOTE: If you’re using VS Code and rust-analyzer to view and edit the examples, you may need to make some changes to `.vscode/settings.json` to tell it which project we’re working on. Follow the instructions commented in that file to get rust-analyzer working correctly. @@ -14,16 +14,7 @@ The first thing you’ll notice are two attributes at the top of the file. These [source,rust] ---- -include::example$basic/src/main.rs[lines="1..2"] ----- - -=== Rust Nightly - -The next declaration is a Rust Unstable feature, which means that Embassy requires Rust Nightly: - -[source,rust] ----- -include::example$basic/src/main.rs[lines="3"] +include::../examples/basic/src/main.rs[lines="1..2"] ---- === Dealing with errors @@ -32,7 +23,7 @@ Then, what follows are some declarations on how to deal with panics and faults. [source,rust] ---- -include::example$basic/src/main.rs[lines="10"] +include::../examples/basic/src/main.rs[lines="8"] ---- === Task declaration @@ -41,7 +32,7 @@ After a bit of import declaration, the tasks run by the application should be de [source,rust] ---- -include::example$basic/src/main.rs[lines="12..20"] +include::../examples/basic/src/main.rs[lines="10..18"] ---- An embassy task must be declared `async`, and may NOT take generic arguments. In this case, we are handed the LED that should be blinked and the interval of the blinking. @@ -56,7 +47,7 @@ We then initialize the HAL with a default config, which gives us a `Peripherals` [source,rust] ---- -include::example$basic/src/main.rs[lines="22..-1"] +include::../examples/basic/src/main.rs[lines="20..-1"] ---- What happens when the `blinker` task has been spawned and main returns? Well, the main entry point is actually just like any other task, except that you can only have one and it takes some specific type arguments. The magic lies within the `#[embassy_executor::main]` macro. The macro does the following: @@ -73,7 +64,7 @@ The project definition needs to contain the embassy dependencies: [source,toml] ---- -include::example$basic/Cargo.toml[lines="9..11"] +include::../examples/basic/Cargo.toml[lines="9..11"] ---- Depending on your microcontroller, you may need to replace `embassy-nrf` with something else (`embassy-stm32` for STM32. Remember to update feature flags as well). diff --git a/docs/pages/beginners.adoc b/docs/pages/beginners.adoc new file mode 100644 index 000000000..48c9f4541 --- /dev/null +++ b/docs/pages/beginners.adoc @@ -0,0 +1,11 @@ += For beginners + +The articles in this section are primarily aimed at users new to Embassy, +showing how to get started, how to structure your project and other best practices. + +include::getting_started.adoc[leveloffset = 2] +include::basic_application.adoc[leveloffset = 2] +include::project_structure.adoc[leveloffset = 2] +include::new_project.adoc[leveloffset = 2] +include::best_practices.adoc[leveloffset = 2] +include::layer_by_layer.adoc[leveloffset = 2] diff --git a/docs/modules/ROOT/pages/best_practices.adoc b/docs/pages/best_practices.adoc similarity index 83% rename from docs/modules/ROOT/pages/best_practices.adoc rename to docs/pages/best_practices.adoc index 1e02f9ba9..bfcedec06 100644 --- a/docs/modules/ROOT/pages/best_practices.adoc +++ b/docs/pages/best_practices.adoc @@ -3,8 +3,10 @@ Over time, a couple of best practices have emerged. The following list should serve as a guideline for developers writing embedded software in _Rust_, especially in the context of the _Embassy_ framework. == Passing Buffers by Reference -It may be tempting to pass arrays or wrappers, like link:https://docs.rs/heapless/latest/heapless/[`heapless::Vec`], to a function or return one just like you would with a `std::Vec`. However, in most embedded applications you don't want to spend ressources on an allocator and end up placing buffers on the stack. -This, however, can easily blow up your stack if you are not careful. +It may be tempting to pass arrays or wrappers, like link:https://docs.rs/heapless/latest/heapless/[`heapless::Vec`], +to a function or return one just like you would with a `std::Vec`. However, in most embedded applications you don't +want to spend resources on an allocator and end up placing buffers on the stack. This, however, can easily blow up +your stack if you are not careful. Consider the following example: [,rust] diff --git a/docs/modules/ROOT/pages/bootloader.adoc b/docs/pages/bootloader.adoc similarity index 97% rename from docs/modules/ROOT/pages/bootloader.adoc rename to docs/pages/bootloader.adoc index 3b0cdb182..53f85d995 100644 --- a/docs/modules/ROOT/pages/bootloader.adoc +++ b/docs/pages/bootloader.adoc @@ -19,6 +19,8 @@ The bootloader supports In general, the bootloader works on any platform that implements the `embedded-storage` traits for its internal flash, but may require custom initialization code to work. +STM32L0x1 devices require the `flash-erase-zero` feature to be enabled. + == Design image::bootloader_flash.png[Bootloader flash layout] @@ -86,8 +88,7 @@ Then, to sign your firmware given a declaration of `FIRMWARE_DIR` and a firmware [source, bash] ---- -shasum -a 512 -b $FIRMWARE_DIR/myfirmware > $SECRETS_DIR/message.txt -cat $SECRETS_DIR/message.txt | dd ibs=128 count=1 | xxd -p -r > $SECRETS_DIR/message.txt +shasum -a 512 -b $FIRMWARE_DIR/myfirmware | head -c128 | xxd -p -r > $SECRETS_DIR/message.txt signify -S -s $SECRETS_DIR/key.sec -m $SECRETS_DIR/message.txt -x $SECRETS_DIR/message.txt.sig cp $FIRMWARE_DIR/myfirmware $FIRMWARE_DIR/myfirmware+signed tail -n1 $SECRETS_DIR/message.txt.sig | base64 -d -i - | dd ibs=10 skip=1 >> $FIRMWARE_DIR/myfirmware+signed diff --git a/docs/modules/ROOT/pages/developer.adoc b/docs/pages/developer.adoc similarity index 100% rename from docs/modules/ROOT/pages/developer.adoc rename to docs/pages/developer.adoc diff --git a/docs/modules/ROOT/pages/developer_stm32.adoc b/docs/pages/developer_stm32.adoc similarity index 100% rename from docs/modules/ROOT/pages/developer_stm32.adoc rename to docs/pages/developer_stm32.adoc diff --git a/docs/pages/embassy_in_the_wild.adoc b/docs/pages/embassy_in_the_wild.adoc new file mode 100644 index 000000000..620794c31 --- /dev/null +++ b/docs/pages/embassy_in_the_wild.adoc @@ -0,0 +1,26 @@ += Embassy in the wild! + +Here are known examples of real-world projects which make use of Embassy. Feel free to link:https://github.com/embassy-rs/embassy/blob/main/docs/pages/embassy_in_the_wild.adoc[add more]! + +* link:https://github.com/1-rafael-1/simple-robot[A simple tracked robot based on Raspberry Pi Pico 2] +** A hobbyist project building a tracked robot with basic autonomous and manual drive mode. +* link:https://github.com/1-rafael-1/pi-pico-alarmclock-rust[A Raspberry Pi Pico W Alarmclock] +** A hobbyist project building an alarm clock around a Pi Pico W complete with code, components list and enclosure design files. +* link:https://github.com/haobogu/rmk/[RMK: A feature-rich Rust keyboard firmware] +** RMK has built-in layer support, wireless(BLE) support, real-time key editing support using vial, and more! +** Targets STM32, RP2040, nRF52 and ESP32 MCUs +* link:https://github.com/cbruiz/printhor/[Printhor: The highly reliable but not necessarily functional 3D printer firmware] +** Targets some STM32 MCUs +* link:https://github.com/card-io-ecg/card-io-fw[Card/IO firmware] - firmware for an open source ECG device +** Targets the ESP32-S3 or ESP32-C6 MCU +* The link:https://github.com/lora-rs/lora-rs[lora-rs] project includes link:https://github.com/lora-rs/lora-rs/tree/main/examples/stm32l0/src/bin[various standalone examples] for NRF52840, RP2040, STM32L0 and STM32WL +* link:https://github.com/matoushybl/air-force-one[Air force one: A simple air quality monitoring system] +** Targets nRF52 and uses nrf-softdevice + +* link:https://github.com/schmettow/ylab-edge-go[YLab Edge Go] and link:https://github.com/schmettow/ylab-edge-pro[YLab Edge Pro] projects develop +firmware (RP2040, STM32) for capturing physiological data in behavioural science research. Included so far are: +** biopotentials (analog ports) +** motion capture (6-axis accelerometers) +** air quality (CO2, Temp, Humidity) +** comes with an app for capturing and visualizing data [link:https://github.com/schmettow/ystudio-zero[Ystudio]] + diff --git a/docs/modules/ROOT/pages/examples.adoc b/docs/pages/examples.adoc similarity index 74% rename from docs/modules/ROOT/pages/examples.adoc rename to docs/pages/examples.adoc index c852f5205..82381a2c5 100644 --- a/docs/modules/ROOT/pages/examples.adoc +++ b/docs/pages/examples.adoc @@ -7,5 +7,5 @@ Main loop example [source,rust] ---- -include::example$examples/std/src/bin/tick.rs[] +include::../examples/examples/std/src/bin/tick.rs[] ---- diff --git a/docs/pages/faq.adoc b/docs/pages/faq.adoc new file mode 100644 index 000000000..d4f49bfc1 --- /dev/null +++ b/docs/pages/faq.adoc @@ -0,0 +1,387 @@ += Frequently Asked Questions + +These are a list of unsorted, commonly asked questions and answers. + +Please feel free to add items to link:https://github.com/embassy-rs/embassy/edit/main/docs/pages/faq.adoc[this page], especially if someone in the chat answered a question for you! + +== How to deploy to RP2040 without a debugging probe. + +Install link:https://github.com/JoNil/elf2uf2-rs[elf2uf2-rs] for converting the generated elf binary into a uf2 file. + +Configure the runner to use this tool, add this to `.cargo/config.toml`: +[source,toml] +---- +[target.'cfg(all(target_arch = "arm", target_os = "none"))'] +runner = "elf2uf2-rs --deploy --serial --verbose" +---- + +The command-line parameters `--deploy` will detect your device and upload the binary, `--serial` starts a serial connection. See the documentation for more info. + +== Missing main macro + +If you see an error like this: + +[source,rust] +---- +#[embassy_executor::main] +| ^^^^ could not find `main` in `embassy_executor` +---- + +You are likely missing some features of the `embassy-executor` crate. + +For Cortex-M targets, check whether ALL of the following features are enabled in your `Cargo.toml` for the `embassy-executor` crate: + +* `arch-cortex-m` +* `executor-thread` + +For ESP32, consider using the executors and `#[main]` macro provided by your appropriate link:https://crates.io/crates/esp-hal-common[HAL crate]. + +== Why is my binary so big? + +The first step to managing your binary size is to set up your link:https://doc.rust-lang.org/cargo/reference/profiles.html[profiles]. + +[source,toml] +---- +[profile.release] +lto = true +opt-level = "s" +incremental = false +codegen-units = 1 +# note: debug = true is okay - debuginfo isn't flashed to the device! +debug = true +---- + +All of these flags are elaborated on in the Rust Book page linked above. + +=== My binary is still big... filled with `std::fmt` stuff! + +This means your code is sufficiently complex that `panic!` invocation's formatting requirements could not be optimized out, despite your usage of `panic-halt` or `panic-reset`. + +You can remedy this by adding the following to your `.cargo/config.toml`: + +[source,toml] +---- +[unstable] +build-std = ["core"] +build-std-features = ["panic_immediate_abort"] +---- + +This replaces all panics with a `UDF` (undefined) instruction. + +Depending on your chipset, this will exhibit different behavior. + +Refer to the spec for your chipset, but for `thumbv6m`, it results in a hardfault. Which can be configured like so: + +[source,rust] +---- +#[exception] +unsafe fn HardFault(_frame: &ExceptionFrame) -> ! { + SCB::sys_reset() // <- you could do something other than reset +} +---- + +Refer to cortex-m's link:https://docs.rs/cortex-m-rt/latest/cortex_m_rt/attr.exception.html[exception handling] for more info. + +== `embassy-time` throws linker errors + +If you see linker error like this: + +[source,text] +---- + = note: rust-lld: error: undefined symbol: _embassy_time_now + >>> referenced by driver.rs:127 (src/driver.rs:127) + >>> embassy_time-846f66f1620ad42c.embassy_time.4f6a638abb75dd4c-cgu.0.rcgu.o:(embassy_time::driver::now::hefb1f99d6e069842) in archive Devel/Embedded/pogodyna/target/thumbv7em-none-eabihf/debug/deps/libembassy_time-846f66f1620ad42c.rlib + + rust-lld: error: undefined symbol: _embassy_time_allocate_alarm + >>> referenced by driver.rs:134 (src/driver.rs:134) + >>> embassy_time-846f66f1620ad42c.embassy_time.4f6a638abb75dd4c-cgu.0.rcgu.o:(embassy_time::driver::allocate_alarm::hf5145b6bd46706b2) in archive Devel/Embedded/pogodyna/target/thumbv7em-none-eabihf/debug/deps/libembassy_time-846f66f1620ad42c.rlib + + rust-lld: error: undefined symbol: _embassy_time_set_alarm_callback + >>> referenced by driver.rs:139 (src/driver.rs:139) + >>> embassy_time-846f66f1620ad42c.embassy_time.4f6a638abb75dd4c-cgu.0.rcgu.o:(embassy_time::driver::set_alarm_callback::h24f92388d96eafd2) in archive Devel/Embedded/pogodyna/target/thumbv7em-none-eabihf/debug/deps/libembassy_time-846f66f1620ad42c.rlib + + rust-lld: error: undefined symbol: _embassy_time_set_alarm + >>> referenced by driver.rs:144 (src/driver.rs:144) + >>> embassy_time-846f66f1620ad42c.embassy_time.4f6a638abb75dd4c-cgu.0.rcgu.o:(embassy_time::driver::set_alarm::h530a5b1f444a6d5b) in archive Devel/Embedded/pogodyna/target/thumbv7em-none-eabihf/debug/deps/libembassy_time-846f66f1620ad42c.rlib +---- + +You probably need to enable a time driver for your HAL (not in `embassy-time`!). For example with `embassy-stm32`, you might need to enable `time-driver-any`: + +[source,toml] +---- +[dependencies.embassy-stm32] +version = "0.1.0" +features = [ + # ... + "time-driver-any", # Add this line! + # ... +] +---- + +If you are in the early project setup phase and not using anything from the HAL, make sure the HAL is explicitly used to prevent the linker removing it as dead code by adding this line to your source: + +[source,rust] +---- +use embassy_stm32 as _; +---- + +== Error: `Only one package in the dependency graph may specify the same links value.` + +You have multiple versions of the same crate in your dependency tree. This means that some of your +embassy crates are coming from crates.io, and some from git, each of them pulling in a different set +of dependencies. + +To resolve this issue, make sure to only use a single source for all your embassy crates! +To do this, you should patch your dependencies to use git sources using `[patch.crates.io]` +and maybe `[patch.'https://github.com/embassy-rs/embassy.git']`. + +Example: + +[source,toml] +---- +[patch.crates-io] +embassy-time-queue-driver = { git = "https://github.com/embassy-rs/embassy.git", rev = "e5fdd35" } +embassy-time-driver = { git = "https://github.com/embassy-rs/embassy.git", rev = "e5fdd35" } +# embassy-time = { git = "https://github.com/embassy-rs/embassy.git", rev = "e5fdd35" } +---- + +Note that the git revision should match any other embassy patches or git dependencies that you are using! + +== How can I optimize the speed of my embassy-stm32 program? + +* Make sure RCC is set up to go as fast as possible +* Make sure link:https://docs.rs/cortex-m/latest/cortex_m/peripheral/struct.SCB.html[flash cache] is enabled +* build with `--release` +* Set the following keys for the release profile in your `Cargo.toml`: + ** `opt-level = "s"` + ** `lto = "fat"` +* Set the following keys in the `[unstable]` section of your `.cargo/config.toml` + ** `build-std = ["core"]` + ** `build-std-features = ["panic_immediate_abort"]` +* Enable feature `embassy-time/generic-queue`, disable feature `embassy-executor/integrated-timers` +* When using `InterruptExecutor`: + ** disable `executor-thread` + ** make `main`` spawn everything, then enable link:https://docs.rs/cortex-m/latest/cortex_m/peripheral/struct.SCB.html#method.set_sleeponexit[SCB.SLEEPONEXIT] and `loop { cortex_m::asm::wfi() }` + ** *Note:* If you need 2 priority levels, using 2 interrupt executors is better than 1 thread executor + 1 interrupt executor. + +== How do I set up the task arenas on stable? + +When you aren't using the `nightly` feature of `embassy-executor`, the executor uses a bump allocator, which may require configuration. + +Something like this error will occur at **compile time** if the task arena is *too large* for the target's RAM: + +[source,plain] +---- +rust-lld: error: section '.bss' will not fit in region 'RAM': overflowed by _ bytes +rust-lld: error: section '.uninit' will not fit in region 'RAM': overflowed by _ bytes +---- + +And this message will appear at **runtime** if the task arena is *too small* for the tasks running: + +[source,plain] +---- +ERROR panicked at 'embassy-executor: task arena is full. You must increase the arena size, see the documentation for details: https://docs.embassy.dev/embassy-executor/' +---- + +NOTE: If all tasks are spawned at startup, this panic will occur immediately. + +Check out link:https://docs.embassy.dev/embassy-executor/git/cortex-m/index.html#task-arena[Task Arena Documentation] for more details. + +== Can I use manual ISRs alongside Embassy? + +Yes! This can be useful if you need to respond to an event as fast as possible, and the latency caused by the usual “ISR, wake, return from ISR, context switch to woken task” flow is too much for your application. Simply define a `#[interrupt] fn INTERRUPT_NAME() {}` handler as you would link:https://docs.rust-embedded.org/book/start/interrupts.html[in any other embedded rust project]. + +== How can I measure resource usage (CPU, RAM, etc.)? + +=== For CPU Usage: + +There are a couple techniques that have been documented, generally you want to measure how long you are spending in the idle or low priority loop. + +We need to document specifically how to do this in embassy, but link:https://blog.japaric.io/cpu-monitor/[this older post] describes the general process. + +If you end up doing this, please update this section with more specific examples! + +=== For Static Memory Usage + +Tools like `cargo size` and `cargo nm` can tell you the size of any globals or other static usage. Specifically you will want to see the size of the `.data` and `.bss` sections, which together make up the total global/static memory usage. + +=== For Max Stack Usage + +Check out link:https://github.com/Dirbaio/cargo-call-stack/[`cargo-call-stack`] for statically calculating worst-case stack usage. There are some caveats and inaccuracies possible with this, but this is a good way to get the general idea. See link:https://github.com/dirbaio/cargo-call-stack#known-limitations[the README] for more details. + +== The memory definition for my STM chip seems wrong, how do I define a `memory.x` file? + +It could happen that your project compiles, flashes but fails to run. The following situation can be true for your setup: + +The `memory.x` is generated automatically when enabling the `memory-x` feature on the `embassy-stm32` crate in the `Cargo.toml` file. +This, in turn, uses `stm32-metapac` to generate the `memory.x` file for you. Unfortunately, more often than not this memory definition is not correct. + +You can override this by adding your own `memory.x` file. Such a file could look like this: +``` +MEMORY +{ + FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 1024K + RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 320K +} + +_stack_start = ORIGIN(RAM) + LENGTH(RAM); +``` + +Please refer to the STM32 documentation for the specific values suitable for your board and setup. The STM32 Cube examples often contain a linker script `.ld` file. +Look for the `MEMORY` section and try to determine the FLASH and RAM sizes and section start. + +If you find a case where the memory.x is wrong, please report it on [this Github issue](https://github.com/embassy-rs/stm32-data/issues/301) so other users are not caught by surprise. + +== The USB examples are not working on my board, is there anything else I need to configure? + +If you are trying out the USB examples and your device doesn not connect, the most common issues are listed below. + +=== Incorrect RCC config + +Check your board and crystal/oscillator, in particular make sure that `HSE` is set to the correct value, e.g. `8_000_000` Hertz if your board does indeed run on a 8 MHz oscillator. + +=== VBUS detection on STM32 platform + +The USB specification requires that all USB devices monitor the bus for detection of plugging/unplugging actions. The devices must pull-up the D+ or D- lane as soon as the host supplies VBUS. + +See the docs, for example at link:https://docs.embassy.dev/embassy-stm32/git/stm32f401vc/usb/struct.Config.html[`usb/struct.Config.html`] for information on how to enable/disable `vbus_detection`. + +When the device is powered only from the USB bus that simultaneously serves as the data connection, this is optional. (If there's no power in VBUS the device would be off anyway, so it's safe to always assume there's power in VBUS, i.e. the USB cable is always plugged in). If your device doesn't have the required connections in place to allow VBUS sensing (see below), then this option needs to be set to `false` to work. + +When the device is powered from another power source and therefore can stay powered through USB cable plug/unplug events, then this must be implemented and `vbus_detection` MUST be set to `true`. + +If your board is powered from the USB and you are unsure whether it supports `vbus_detection`, consult the schematics of your board to see if VBUS is connected to PA9 for USB Full Speed or PB13 for USB High Speed, vice versa, possibly with a voltage divider. When designing your own hardware, see ST application note AN4879 (in particular section 2.6) and the reference manual of your specific chip for more details. + +== Known issues (details and/or mitigations) + +These are issues that are commonly reported. Help wanted fixing them, or improving the UX when possible! + +=== STM32H5 and STM32H7 power issues + +STM32 chips with built-in power management (SMPS and LDO) settings often cause user problems when the configuration does not match how the board was designed. + +Settings from the examples, or even from other working boards, may not work on YOUR board, because they are wired differently. + +Additionally, some PWR settings require a full device reboot (and enough time to discharge any power capacitors!), making this hard to troubleshoot. Also, some +"wrong" power settings will ALMOST work, meaning it will sometimes work on some boots, or for a while, but crash unexpectedly. + +There is not a fix for this yet, as it is board/hardware dependant. See link:https://github.com/embassy-rs/embassy/issues/2806[this tracking issue] for more details + +=== STM32 BDMA only working out of some RAM regions + +The STM32 BDMA controller included in some STM32H7 chips has to be configured to use only certain regions of RAM, +otherwise the transfer will fail. + +If you see errors that look like this: + +[source,plain] +---- +DMA: error on BDMA@1234ABCD channel 4 +---- + +You need to set up your linker script to define a special region for this area and copy data to that region before using with BDMA. + +General steps: + +1. Find out which memory region BDMA has access to. You can get this information from the bus matrix and the memory mapping table in the STM32 datasheet. +2. Add the memory region to `memory.x`, you can modify the generated one from https://github.com/embassy-rs/stm32-data-generated/tree/main/data/chips. +3. You might need to modify `build.rs` to make cargo pick up the modified `memory.x`. +4. In your code, access the defined memory region using `#[link_section = ".xxx"]` +5. Copy data to that region before using BDMA. + +See link:https://github.com/embassy-rs/embassy/blob/main/examples/stm32h7/src/bin/spi_bdma.rs[SMT32H7 SPI BDMA example] for more details. + +== How do I switch to the `main` branch? + +Sometimes to test new changes or fixes, you'll want to switch your project to using a version from GitHub. + +You can add a section to your `Cargo.toml` file like this, you'll need to patch ALL embassy crates to the same revision: + +Using `patch` will replace all direct AND indirect dependencies. + +See the link:https://embassy.dev/book/#_starting_a_new_project[new project docs] for more details on this approach. + +[source,toml] +---- +[patch.crates-io] +# make sure to get the latest git rev from github, you can see the latest one here: +# https://github.com/embassy-rs/embassy/commits/main/ +embassy-embedded-hal = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" } +embassy-executor = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" } +embassy-rp = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" } +embassy-sync = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" } +embassy-time = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" } +embassy-usb = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" } +embassy-usb-driver = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" } +---- + +== How do I add support for a new microcontroller to embassy? + +This is particularly for cortex-m, and potentially risc-v, where there is already support for basics like interrupt handling, or even already embassy-executor support for your architecture. + +This is a *much harder path* than just using Embassy on an already supported chip. If you are a beginner, consider using embassy on an existing, well supported chip for a while, before you decide to write drivers from scratch. It's also worth reading the existing source of supported Embassy HALs, to get a feel for how drivers are implemented for various chips. You should already be comfortable reading and writing unsafe code, and understanding the responsibilities of writing safe abstractions for users of your HAL. + +This is not the only possible approach, but if you are looking for where to start, this is a reasonable way to tackle the task: + +1. First, drop by the Matrix room or search around to see if someone has already started writing drivers, either in Embassy or otherwise in Rust. You might not have to start from scratch! +2. Make sure the target is supported in probe-rs, it likely is, and if not, there is likely a cmsis-pack you can use to add support so that flashing and debugging is possible. You will definitely appreciate being able to debug with SWD or JTAG when writing drivers! +3. See if there is an SVD (or SVDs, if it's a family) available, if it is, run it through chiptool to create a PAC for low level register access. If not, there are other ways (like scraping the PDF datasheets or existing C header files), but these are more work than starting from the SVD file to define peripheral memory locations necessary for writing drivers. +4. Either make a fork of embassy repo, and add your target there, or make a repo that just contains the PAC and an empty HAL. It doesn't necessarily have to live in the embassy repo at first. +5. Get a hello world binary working on your chip, either with minimal HAL or just PAC access, use delays and blink a light or send some raw data on some interface, make sure it works and you can flash, debug with defmt + RTT, write a proper linker script, etc. +6. Get basic timer operations and timer interrupts working, upgrade your blinking application to use hardware timers and interrupts, and ensure they are accurate (with a logic analyzer or oscilloscope, if possible). +7. Implement the embassy-time driver API with your timer and timer interrupt code, so that you can use embassy-time operations in your drivers and applications. +8. Then start implementing whatever peripherals you need, like GPIOs, UART, SPI, I2C, etc. This is the largest part of the work, and will likely continue for a while! Don't feel like you need 100% coverage of all peripherals at first, this is likely to be an ongoing process over time. +9. Start implementing the embedded-hal, embedded-io, and embedded-hal-async traits on top of your HAL drivers, once you start having more features completed. This will allow users to use standard external device drivers (e.g. sensors, actuators, displays, etc.) with your HAL. +10. Discuss upstreaming the PAC/HAL for embassy support, or make sure your drivers are added to the awesome-embedded-rust list so that people can find it. + +== Multiple Tasks, or one task with multiple futures? + +Some examples end like this in main: + +[source,rust] +---- +// Run everything concurrently. +// If we had made everything `'static` above instead, we could do this using separate tasks instead. +join(usb_fut, join(echo_fut, log_fut)).await; +---- + +There are two main ways to handle concurrency in Embassy: + +1. Spawn multiple tasks, e.g. with `#[embassy_executor::task]` +2. Manage multiple futures inside ONE task using `join()` or `select()` (as shown above) + +In general, either of these approaches will work. The main differences of these approaches are: + +When using **separate tasks**, each task needs its own RAM allocation, so there's a little overhead for each task, so one task that does three things will likely be a little bit smaller than three tasks that do one thing (not a lot, probably a couple dozen bytes). In contrast, with **multiple futures in one task**, you don't need multiple task allocations, and it will generally be easier to share data, or use borrowed resources, inside of a single task. +An example showcasing some methods for sharing things between tasks link:https://github.com/embassy-rs/embassy/blob/main/examples/rp/src/bin/sharing.rs[can be found here]. + +But when it comes to "waking" tasks, for example when a data transfer is complete or a button is pressed, it's faster to wake a dedicated task, because that task does not need to check which future is actually ready. `join` and `select` must check ALL of the futures they are managing to see which one (or which ones) are ready to do more work. This is because all Rust executors (like Embassy or Tokio) only have the ability to wake tasks, not specific futures. This means you will use slightly less CPU time juggling futures when using dedicated tasks. + +Practically, there's not a LOT of difference either way - so go with what makes it easier for you and your code first, but there will be some details that are slightly different in each case. + +== splitting peripherals resources between tasks + +There are two ways to split resources between tasks, either manually assigned or by a convenient macro. See link:https://github.com/embassy-rs/embassy/blob/main/examples/rp/src/bin/assign_resources.rs[this example] + +== My code/driver works in debug mode, but not release mode (or with LTO) + +Issues like these while implementing drivers often fall into one of the following general causes, which are a good list of common errors to check for: + +1. Some kind of race condition - the faster code means you miss an interrupt or something +2. Some kind of UB, if you have unsafe code, or something like DMA with fences missing +3. Some kind of hardware errata, or some hardware misconfiguration like wrong clock speeds +4. Some issue with an interrupt handler, either enabling, disabling, or re-enabling of interrupts when necessary +5. Some kind of async issue, like not registering wakers fully before checking flags, or not registering or pending wakers at the right time + +== How can I prevent the thread-mode executor from going to sleep? == + +In some cases you might want to prevent the thread-mode executor from going to sleep, for example when doing so would result in current spikes that reduce analog performance. +As a workaround, you can spawn a task that yields in a loop, preventing the executor from going to sleep. Note that this may increase power consumption. + +[source,rust] +---- +#[embassy_executor::task] +async fn idle() { + loop { embassy_futures::yield_now().await; } +} +---- diff --git a/docs/modules/ROOT/pages/getting_started.adoc b/docs/pages/getting_started.adoc similarity index 61% rename from docs/modules/ROOT/pages/getting_started.adoc rename to docs/pages/getting_started.adoc index 24bde1c1f..017409018 100644 --- a/docs/modules/ROOT/pages/getting_started.adoc +++ b/docs/pages/getting_started.adoc @@ -3,7 +3,7 @@ So you want to try Embassy, great! To get started, there are a few tools you need to install: * link:https://rustup.rs/[rustup] - the Rust toolchain is needed to compile Rust code. -* link:https://crates.io/crates/probe-rs[probe-rs] - to flash the firmware on your device. If you already have other tools like `OpenOCD` setup, you can use that as well. +* link:https://probe.rs/[probe-rs] - to flash the firmware on your device. If you already have other tools like `OpenOCD` setup, you can use that as well. If you don't have any supported board, don't worry: you can also run embassy on your PC using the `std` examples. @@ -82,19 +82,19 @@ If everything worked correctly, you should see a blinking LED on your board, and └─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:27 ---- -NOTE: How does the `cargo run` command know how to connect to our board and program it? In each `examples` folder, there’s a `.cargo/config.toml` file which tells cargo to use link:https://probe.rs/[probe-rs] as the runner for ARM binaries in that folder. probe-rs handles communication with the debug probe and MCU. In order for this to work, probe-rs needs to know which chip it’s programming, so you’ll have to edit this file if you want to run examples on other chips. +NOTE: How does the `+cargo run+` command know how to connect to our board and program it? In each `examples` folder, there’s a `.cargo/config.toml` file which tells cargo to use link:https://probe.rs/[probe-rs] as the runner for ARM binaries in that folder. probe-rs handles communication with the debug probe and MCU. In order for this to work, probe-rs needs to know which chip it’s programming, so you’ll have to edit this file if you want to run examples on other chips. === It didn’t work! -If you hare having issues when running `cargo run --release`, please check the following: +If you hare having issues when running `+cargo run --release+`, please check the following: -* You are specifying the correct `--chip` on the command line, OR -* You have set `.cargo/config.toml`'s run line to the correct chip, AND -* You have changed `examples/Cargo.toml`'s HAL (e.g. embassy-stm32) dependency's feature to use the correct chip (replace the existing stm32xxxx feature) +* You are specifying the correct `+--chip+` on the command line, OR +* You have set `+.cargo/config.toml+`’s run line to the correct chip, AND +* You have changed `+examples/Cargo.toml+`’s HAL (e.g. embassy-stm32) dependency's feature to use the correct chip (replace the existing stm32xxxx feature) At this point the project should run. If you do not see a blinky LED for blinky, for example, be sure to check the code is toggling your board's LED pin. -If you are trying to run an example with `cargo run --release` and you see the following output: +If you are trying to run an example with `+cargo run --release+` and you see the following output: [source] ---- 0.000000 INFO Hello World! @@ -115,12 +115,32 @@ To get rid of the frame-index error add the following to your `Cargo.toml`: debug = 2 ---- -If you’re still having problems, check the link:https://embassy.dev/book/dev/faq.html[FAQ], or ask for help in the link:https://matrix.to/#/#embassy-rs:matrix.org[Embassy Chat Room]. +If you’re getting an extremely long error message containing something like the following: + +[source] +---- +error[E0463]: can't find crate for `std` + | + = note: the `thumbv6m-none-eabi` target may not support the standard library + = note: `std` is required by `stable_deref_trait` because it does not declare `#![no_std]` +---- + +Make sure that you didn’t accidentally run `+cargo add probe-rs+` (which adds it as a dependency) instead of link:https://probe.rs/docs/getting-started/installation/[correctly installing probe-rs]. + +If you’re using a raspberry pi pico-w, make sure you’re running `+cargo run --bin wifi_blinky --release+` rather than the regular blinky. The pico-w’s on-board LED is connected to the WiFi chip, which needs to be initialized before the LED can be blinked. + +If you’re using an rp2040 debug probe (e.g. the pico probe) and are having issues after running `probe-rs info`, unplug and reconnect the probe, letting it power cycle. Running `probe-rs info` is link:https://github.com/probe-rs/probe-rs/issues/1849[known to put the pico probe into an unusable state]. + +:embassy-dev-faq-link-with-hash: https://embassy.dev/book/#_frequently_asked_questions +:embassy-matrix-channel: https://matrix.to/#/#embassy-rs:matrix.org + +If you’re still having problems, check the {embassy-dev-faq-link-with-hash}[FAQ], or ask for help in the {embassy-matrix-channel}[Embassy Chat Room]. == What's next? Congratulations, you have your first Embassy application running! Here are some suggestions for where to go from here: -* Read more about the xref:runtime.adoc[executor]. -* Read more about the xref:hal.adoc[HAL]. -* Start xref:basic_application.adoc[writing your application]. +* Read more about the xref:_embassy_executor[executor]. +* Read more about the xref:_hardware_abstraction_layer_hal[HAL]. +* Start xref:_a_basic_embassy_application[writing your application]. +* Learn how to xref:_starting_a_new_project[start a new embassy project by adapting an example]. diff --git a/docs/modules/ROOT/pages/hal.adoc b/docs/pages/hal.adoc similarity index 83% rename from docs/modules/ROOT/pages/hal.adoc rename to docs/pages/hal.adoc index b1382e8e5..14b85e1f1 100644 --- a/docs/modules/ROOT/pages/hal.adoc +++ b/docs/pages/hal.adoc @@ -10,3 +10,5 @@ These HALs implement async/await functionality for most peripherals while also i async traits in `embedded-hal` and `embedded-hal-async`. You can also use these HALs with another executor. For the ESP32 series, there is an link:https://github.com/esp-rs/esp-hal[esp-hal] which you can use. + +For the WCH 32-bit RISC-V series, there is an link:https://github.com/ch32-rs/ch32-hal[ch32-hal], which you can use. diff --git a/docs/modules/ROOT/pages/layer_by_layer.adoc b/docs/pages/layer_by_layer.adoc similarity index 88% rename from docs/modules/ROOT/pages/layer_by_layer.adoc rename to docs/pages/layer_by_layer.adoc index 1d7bdc89b..7852d27b7 100644 --- a/docs/modules/ROOT/pages/layer_by_layer.adoc +++ b/docs/pages/layer_by_layer.adoc @@ -16,7 +16,7 @@ The blinky app using PAC is shown below: [source,rust] ---- -include::example$layer-by-layer/blinky-pac/src/main.rs[] +include::../examples/layer-by-layer/blinky-pac/src/main.rs[] ---- As you can see, a lot of code is needed to enable the peripheral clocks and to configure the input pins and the output pins of the application. @@ -35,7 +35,7 @@ The HAL example is shown below: [source,rust] ---- -include::example$layer-by-layer/blinky-hal/src/main.rs[] +include::../examples/layer-by-layer/blinky-hal/src/main.rs[] ---- As you can see, the application becomes a lot simpler, even without using any async code. The `Input` and `Output` types hide all the details of accessing the GPIO registers and allow you to use a much simpler API for querying the state of the button and toggling the LED output. @@ -52,7 +52,7 @@ Given Embassy focus on async Rust (which we'll come back to after this example), [source,rust] ---- -include::example$layer-by-layer/blinky-irq/src/main.rs[lines="1..57"] +include::../examples/layer-by-layer/blinky-irq/src/main.rs[lines="1..57"] ---- The simple application is now more complex again, primarily because of the need to keep the button and LED states in the global scope where it is accessible by the main application loop, as well as the interrupt handler. @@ -63,11 +63,11 @@ Luckily, there is an elegant solution to this problem when using Embassy. == Async version -It's time to use the Embassy capabilities to its fullest. At the core, Embassy has an async excecutor, or a runtime for async tasks if you will. The executor polls a set of tasks (defined at compile time), and whenever a task `blocks`, the executor will run another task, or put the microcontroller to sleep. +It's time to use the Embassy capabilities to its fullest. At the core, Embassy has an async executor, or a runtime for async tasks if you will. The executor polls a set of tasks (defined at compile time), and whenever a task `blocks`, the executor will run another task, or put the microcontroller to sleep. [source,rust] ---- -include::example$layer-by-layer/blinky-async/src/main.rs[] +include::../examples/layer-by-layer/blinky-async/src/main.rs[] ---- The async version looks very similar to the HAL version, apart from a few minor details: @@ -76,7 +76,7 @@ The async version looks very similar to the HAL version, apart from a few minor * The peripheral initialization is done by the main macro, and is handed to the main task. * Before checking the button state, the application is awaiting a transition in the pin state (low -> high or high -> low). -When `button.await_for_any_edge().await` is called, the executor will pause the main task and put the microcontroller in sleep mode, unless there are other tasks that can run. Internally, the Embassy HAL has configured the interrupt handler for the button (in `ExtiButton`), so that whenever an interrupt is raised, the task awaiting the button will be woken up. +When `button.await_for_any_edge().await` is called, the executor will pause the main task and put the microcontroller in sleep mode, unless there are other tasks that can run. Internally, the Embassy HAL has configured the interrupt handler for the button (in `ExtiInput`), so that whenever an interrupt is raised, the task awaiting the button will be woken up. The minimal overhead of the executor and the ability to run multiple tasks "concurrently" combined with the enormous simplification of the application, makes `async` a great fit for embedded. diff --git a/docs/modules/ROOT/pages/new_project.adoc b/docs/pages/new_project.adoc similarity index 82% rename from docs/modules/ROOT/pages/new_project.adoc rename to docs/pages/new_project.adoc index ce139ed8d..38cea044b 100644 --- a/docs/modules/ROOT/pages/new_project.adoc +++ b/docs/pages/new_project.adoc @@ -1,6 +1,18 @@ -= Starting a new Embassy project += Starting a new project -Once you’ve successfully xref:getting_started.adoc[run some example projects], the next step is to make a standalone Embassy project. The easiest way to do this is to adapt an example for a similar chip to the one you’re targeting. +Once you’ve successfully xref:#_getting_started[run some example projects], the next step is to make a standalone Embassy project. + +== Tools for generating Embassy projects + +=== CLI +- link:https://github.com/adinack/cargo-embassy[cargo-embassy] (STM32 and NRF) + +=== cargo-generate +- link:https://github.com/lulf/embassy-template[embassy-template] (STM32, NRF, and RP) +- link:https://github.com/bentwire/embassy-rp2040-template[embassy-rp2040-template] (RP) + + +== Starting a project from scratch As an example, let’s create a new embassy project from scratch for a STM32G474. The same instructions are applicable for any supported chip with some minor changes. @@ -24,7 +36,7 @@ stm32g474-example Looking in link:https://github.com/embassy-rs/embassy/tree/main/examples[the Embassy examples], we can see there’s a `stm32g4` folder. Find `src/blinky.rs` and copy its contents into our `src/main.rs`. -== .cargo/config.toml +=== The .cargo/config.toml Currently, we’d need to provide cargo with a target triple every time we run `cargo build` or `cargo run`. Let’s spare ourselves that work by copying `.cargo/config.toml` from `examples/stm32g4` into our project. @@ -55,22 +67,34 @@ and copying `STM32G474RETx` into `.cargo/config.toml` as so: runner = "probe-rs run --chip STM32G474RETx" ---- -== Cargo.toml +=== Cargo.toml Now that cargo knows what target to compile for (and probe-rs knows what chip to run it on), we’re ready to add some dependencies. Looking in `examples/stm32g4/Cargo.toml`, we can see that the examples require a number of embassy crates. For blinky, we’ll only need three of them: `embassy-stm32`, `embassy-executor` and `embassy-time`. -At the time of writing, the latest version of embassy isn‘t available on crates.io, so we need to install it straight from the git repository. The recommended way of doing so is as follows: + +At the time of writing, embassy is already published to crates.io. Therefore, dependencies can easily added via Cargo.toml. + +[source,toml] +---- +[dependencies] +embassy-stm32 = { version = "0.1.0", features = ["defmt", "time-driver-any", "stm32g474re", "memory-x", "unstable-pac", "exti"] } +embassy-executor = { version = "0.6.1", features = ["nightly", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +---- + +Prior, embassy needed to be installed straight from the git repository. Installing from git is still useful, if you want to checkout a specic revision of an embassy crate which is not yet published. +The recommended way of doing so is as follows: * Copy the required `embassy-*` lines from the example `Cargo.toml` * Make any necessary changes to `features`, e.g. requiring the `stm32g474re` feature of `embassy-stm32` * Remove the `path = ""` keys in the `embassy-*` entries * Create a `[patch.crates-io]` section, with entries for each embassy crate we need. These should all contain identical values: a link to the git repository, and a reference to the commit we’re checking out. Assuming you want the latest commit, you can find it by running `git ls-remote https://github.com/embassy-rs/embassy.git HEAD` -NOTE: When using this method, it’s necessary that the `version` keys in `[dependencies]` match up with the versions defined in each crate’s `Cargo.toml` in the specificed `rev` under `[patch.crates.io]`. This means that when updating, you have to a pick a new revision, change everything in `[patch.crates.io]` to match it, and then correct any versions under `[dependencies]` which have changed. Hopefully this will no longer be necessary once embassy is released on crates.io! +NOTE: When using this method, it’s necessary that the `version` keys in `[dependencies]` match up with the versions defined in each crate’s `Cargo.toml` in the specificed `rev` under `[patch.crates.io]`. This means that when updating, you have to a pick a new revision, change everything in `[patch.crates.io]` to match it, and then correct any versions under `[dependencies]` which have changed. -At the time of writing, this method produces the following results: +An example Cargo.toml file might look as follows: [source,toml] ---- @@ -106,7 +130,7 @@ Finally, copy the `[profile.release]` section from the example `Cargo.toml` into debug = 2 ---- -== rust-toolchain.toml +=== rust-toolchain.toml Before we can build our project, we need to add an additional file to tell cargo to use the nightly toolchain. Copy the `rust-toolchain.toml` from the embassy repo to ours, and trim the list of targets down to only the target triple relevent for our project — in this case, `thumbv7em-none-eabi`: @@ -131,7 +155,7 @@ components = [ "rust-src", "rustfmt", "llvm-tools", "miri" ] targets = ["thumbv7em-none-eabi"] ---- -== build.rs +=== build.rs In order to produce a working binary for our target, cargo requires a custom build script. Copy `build.rs` from the example to our project: @@ -147,7 +171,7 @@ stm32g474-example └── main.rs ---- -== Building and running +=== Building and running At this point, we‘re finally ready to build and run our project! Connect your board via a debug probe and run: @@ -166,13 +190,13 @@ should result in a blinking LED (if there’s one attached to the pin in `src/ma Erasing sectors ✔ [00:00:00] [#########################################################] 18.00 KiB/18.00 KiB @ 54.09 KiB/s (eta 0s ) Programming pages ✔ [00:00:00] [#########################################################] 17.00 KiB/17.00 KiB @ 35.91 KiB/s (eta 0s ) Finished in 0.817s 0.000000 TRACE BDCR configured: 00008200 -└─ embassy_stm32::rcc::bd::{impl#3}::init::{closure#4} @ /home/you/.cargo/git/checkouts/embassy-9312dcb0ed774b29/7703f47/embassy-stm32/src/fmt.rs:117 +└─ embassy_stm32::rcc::bd::{impl#3}::init::{closure#4} @ /home/you/.cargo/git/checkouts/embassy-9312dcb0ed774b29/7703f47/embassy-stm32/src/fmt.rs:117 0.000000 DEBUG rcc: Clocks { sys: Hertz(16000000), pclk1: Hertz(16000000), pclk1_tim: Hertz(16000000), pclk2: Hertz(16000000), pclk2_tim: Hertz(16000000), hclk1: Hertz(16000000), hclk2: Hertz(16000000), pll1_p: None, adc: None, adc34: None, rtc: Some(Hertz(32000)) } -└─ embassy_stm32::rcc::set_freqs @ /home/you/.cargo/git/checkouts/embassy-9312dcb0ed774b29/7703f47/embassy-stm32/src/fmt.rs:130 +└─ embassy_stm32::rcc::set_freqs @ /home/you/.cargo/git/checkouts/embassy-9312dcb0ed774b29/7703f47/embassy-stm32/src/fmt.rs:130 0.000000 INFO Hello World! -└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:14 +└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:14 0.000091 INFO high -└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:19 +└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:19 0.300201 INFO low -└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:23 ----- \ No newline at end of file +└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:23 +---- diff --git a/docs/modules/ROOT/pages/nrf.adoc b/docs/pages/nrf.adoc similarity index 67% rename from docs/modules/ROOT/pages/nrf.adoc rename to docs/pages/nrf.adoc index 1706087ae..de052b63f 100644 --- a/docs/modules/ROOT/pages/nrf.adoc +++ b/docs/pages/nrf.adoc @@ -1,6 +1,6 @@ = Embassy nRF HAL -The link:https://github.com/embassy-rs/embassy/tree/master/embassy-nrf[Embassy nRF HAL] is based on the PACs (Peripheral Access Crate) from link:https://github.com/nrf-rs/[nrf-rs]. +The link:https://github.com/embassy-rs/embassy/tree/main/embassy-nrf[Embassy nRF HAL] is based on the PACs (Peripheral Access Crate) from link:https://github.com/nrf-rs/[nrf-rs]. == Timer driver diff --git a/docs/modules/ROOT/pages/index.adoc b/docs/pages/overview.adoc similarity index 84% rename from docs/modules/ROOT/pages/index.adoc rename to docs/pages/overview.adoc index e17adbbd7..8f97d937f 100644 --- a/docs/modules/ROOT/pages/index.adoc +++ b/docs/pages/overview.adoc @@ -1,4 +1,4 @@ -= Embassy += Introduction Embassy is a project to make async/await a first-class option for embedded development. @@ -30,6 +30,7 @@ The Embassy project maintains HALs for select hardware, but you can still use HA * link:https://docs.embassy.dev/embassy-nrf/[embassy-nrf], for the Nordic Semiconductor nRF52, nRF53, nRF91 series. * link:https://docs.embassy.dev/embassy-rp/[embassy-rp], for the Raspberry Pi RP2040 microcontroller. * link:https://github.com/esp-rs[esp-rs], for the Espressif Systems ESP32 series of chips. +* link:https://github.com/ch32-rs/ch32-hal[ch32-hal], for the WCH 32-bit RISC-V(CH32V) series of chips. NOTE: A common question is if one can use the Embassy HALs standalone. Yes, it is possible! There are no dependency on the executor within the HALs. You can even use them without async, as they implement both the link:https://github.com/rust-embedded/embedded-hal[Embedded HAL] blocking and async traits. @@ -47,14 +48,28 @@ link:https://github.com/lora-rs/lora-rs[lora-rs] supports LoRa networking on a w link:https://docs.embassy.dev/embassy-usb/[embassy-usb] implements a device-side USB stack. Implementations for common classes such as USB serial (CDC ACM) and USB HID are available, and a rich builder API allows building your own. === Bootloader and DFU -link:https://github.com/embassy-rs/embassy/tree/master/embassy-boot[embassy-boot] is a lightweight bootloader supporting firmware application upgrades in a power-fail-safe way, with trial boots and rollbacks. +link:https://github.com/embassy-rs/embassy/tree/main/embassy-boot[embassy-boot] is a lightweight bootloader supporting firmware application upgrades in a power-fail-safe way, with trial boots and rollbacks. == What is DMA? -For most I/O in embedded devices, the peripheral doesn't directly support the transmission of multiple bits at once, with CAN being a notable exception. Instead, the MCU must write each byte, one at a time, and then wait until the peripheral is ready to send the next. For high I/O rates, this can pose a problem if the MCU must devote an increasing portion of its time handling each byte. The solution to this problem is to use the Direct Memory Access controller. +For most I/O in embedded devices, the peripheral doesn't directly support the transmission of multiple bytes at once, with CAN being a notable exception. Instead, the MCU must write each byte, one at a time, and then wait until the peripheral is ready to send the next. For high I/O rates, this can pose a problem if the MCU must devote an increasing portion of its time handling each byte. The solution to this problem is to use the Direct Memory Access controller. The Direct Memory Access controller (DMA) is a controller that is present in MCUs that Embassy supports, including stm32 and nrf. The DMA allows the MCU to set up a transfer, either send or receive, and then wait for the transfer to complete. With DMA, once started, no MCU intervention is required until the transfer is complete, meaning that the MCU can perform other computation, or set up other I/O while the transfer is in progress. For high I/O rates, DMA can cut the time that the MCU spends handling I/O by over half. However, because DMA is more complex to set-up, it is less widely used in the embedded community. Embassy aims to change that by making DMA the first choice rather than the last. Using Embassy, there's no additional tuning required once I/O rates increase because your application is already set-up to handle them. +== Examples + +Embassy provides examples for all HALs supported. You can find them in the `examples/` folder. + + +Main loop example + +[source,rust] +---- +include::../examples/examples/std/src/bin/tick.rs[] +---- + +include::embassy_in_the_wild.adoc[leveloffset = 2] + == Resources For more reading material on async Rust and Embassy: @@ -62,3 +77,7 @@ For more reading material on async Rust and Embassy: * link:https://tweedegolf.nl/en/blog/65/async-rust-vs-rtos-showdown[Comparsion of FreeRTOS and Embassy] * link:https://dev.to/apollolabsbin/series/20707[Tutorials] * link:https://blog.drogue.io/firmware-updates-part-1/[Firmware Updates with Embassy] + +Videos: + +* link:https://www.youtube.com/watch?v=wni5h5vIPhU[From Zero to Async in Embedded Rust] diff --git a/docs/modules/ROOT/pages/project_structure.adoc b/docs/pages/project_structure.adoc similarity index 78% rename from docs/modules/ROOT/pages/project_structure.adoc rename to docs/pages/project_structure.adoc index 61ffd05a6..722ec8d9d 100644 --- a/docs/modules/ROOT/pages/project_structure.adoc +++ b/docs/pages/project_structure.adoc @@ -18,6 +18,7 @@ my-project |- rust-toolchain.toml ---- +[discrete] == .cargo/config.toml This directory/file describes what platform you're on, and configures link:https://github.com/probe-rs/probe-rs[probe-rs] to deploy to your device. @@ -36,16 +37,27 @@ target = "thumbv6m-none-eabi" # <-change for your platform DEFMT_LOG = "trace" # <- can change to info, warn, or error ---- +[discrete] == build.rs -This is the build script for your project. It links defmt (what is defmt?) and the `memory.x` file if needed. This file is pretty specific for each chipset, just copy and paste from the corresponding link:https://github.com/embassy-rs/embassy/tree/main/examples[example]. +This is the build script for your project. It links defmt (what is link:https://defmt.ferrous-systems.com[defmt]?) and the `memory.x` file if needed. This file is pretty specific for each chipset, just copy and paste from the corresponding link:https://github.com/embassy-rs/embassy/tree/main/examples[example]. +[discrete] == Cargo.toml This is your manifest file, where you can configure all of the embassy components to use the features you need. -TODO: someone should exhaustively describe every feature for every component! +[discrete] +=== Features +[discrete] +==== Time +- tick-hz-x: Configures the tick rate of `embassy-time`. Higher tick rate means higher precision, and higher CPU wakes. +- defmt-timestamp-uptime: defmt log entries will display the uptime in seconds. + +...more to come + +[discrete] == memory.x This file outlines the flash/ram usage of your program. It is especially useful when using link:https://github.com/embassy-rs/nrf-softdevice[nrf-softdevice] on an nRF5x. @@ -63,6 +75,7 @@ MEMORY } ---- +[discrete] == rust-toolchain.toml This file configures the rust version and configuration to use. diff --git a/docs/modules/ROOT/pages/runtime.adoc b/docs/pages/runtime.adoc similarity index 100% rename from docs/modules/ROOT/pages/runtime.adoc rename to docs/pages/runtime.adoc diff --git a/docs/modules/ROOT/pages/sharing_peripherals.adoc b/docs/pages/sharing_peripherals.adoc similarity index 88% rename from docs/modules/ROOT/pages/sharing_peripherals.adoc rename to docs/pages/sharing_peripherals.adoc index fcba0e27b..dfb8c1ffe 100644 --- a/docs/modules/ROOT/pages/sharing_peripherals.adoc +++ b/docs/pages/sharing_peripherals.adoc @@ -8,6 +8,7 @@ The following examples shows different ways to use the on-board LED on a Raspber Using mutual exclusion is the simplest way to share a peripheral. +TIP: Dependencies needed to run this example link:#_the_cargo_toml[can be found here]. [,rust] ---- use defmt::*; @@ -77,6 +78,7 @@ To indicate that the pin will be set to an Output. The `AnyPin` could have been A channel is another way to ensure exclusive access to a resource. Using a channel is great in the cases where the access can happen at a later point in time, allowing you to enqueue operations and do other things. +TIP: Dependencies needed to run this example link:#_the_cargo_toml[can be found here]. [,rust] ---- use defmt::*; @@ -123,4 +125,10 @@ async fn toggle_led(control: Sender<'static, ThreadModeRawMutex, LedState, 64>, ---- This example replaces the Mutex with a Channel, and uses another task (the main loop) to drive the LED. The advantage of this approach is that only a single task references the peripheral, separating concerns. However, using a Mutex has a lower overhead and might be necessary if you need to ensure -that the operation is ecompleted before continuing to do other work in your task. +that the operation is completed before continuing to do other work in your task. + +An example showcasing more methods for sharing link:https://github.com/embassy-rs/embassy/blob/main/examples/rp/src/bin/sharing.rs[can be found here]. + +== Sharing an I2C or SPI bus between multiple devices + +An example of how to deal with multiple devices sharing a common I2C or SPI bus link:https://github.com/embassy-rs/embassy/blob/main/examples/rp/src/bin/shared_bus.rs[can be found here]. diff --git a/docs/modules/ROOT/pages/stm32.adoc b/docs/pages/stm32.adoc similarity index 90% rename from docs/modules/ROOT/pages/stm32.adoc rename to docs/pages/stm32.adoc index 7bfc0592b..df139a420 100644 --- a/docs/modules/ROOT/pages/stm32.adoc +++ b/docs/pages/stm32.adoc @@ -1,6 +1,6 @@ = Embassy STM32 HAL -The link:https://github.com/embassy-rs/embassy/tree/master/embassy-stm32[Embassy STM32 HAL] is based on the `stm32-metapac` project. +The link:https://github.com/embassy-rs/embassy/tree/main/embassy-stm32[Embassy STM32 HAL] is based on the `stm32-metapac` project. == The infinite variant problem diff --git a/docs/pages/system.adoc b/docs/pages/system.adoc new file mode 100644 index 000000000..985f92b18 --- /dev/null +++ b/docs/pages/system.adoc @@ -0,0 +1,13 @@ += System description + +This section describes different parts of Embassy in more detail. + +include::runtime.adoc[leveloffset = 2] +include::bootloader.adoc[leveloffset = 2] +include::time_keeping.adoc[leveloffset = 2] +include::hal.adoc[leveloffset = 2] +include::nrf.adoc[leveloffset = 2] +include::stm32.adoc[leveloffset = 2] +include::sharing_peripherals.adoc[leveloffset = 2] +include::developer.adoc[leveloffset = 2] +include::developer_stm32.adoc[leveloffset = 2] diff --git a/docs/modules/ROOT/pages/time_keeping.adoc b/docs/pages/time_keeping.adoc similarity index 92% rename from docs/modules/ROOT/pages/time_keeping.adoc rename to docs/pages/time_keeping.adoc index 5068216ed..11ddb2b2b 100644 --- a/docs/modules/ROOT/pages/time_keeping.adoc +++ b/docs/pages/time_keeping.adoc @@ -16,6 +16,7 @@ The `embassy::time::Timer` type provides two timing methods. An example of a delay is provided as follows: +TIP: Dependencies needed to run this example link:#_the_cargo_toml[can be found here]. [,rust] ---- use embassy::executor::{task, Executor}; @@ -40,6 +41,7 @@ that expect a generic delay implementation to be provided. An example of how this can be used: +TIP: Dependencies needed to run this example link:#_the_cargo_toml[can be found here]. [,rust] ---- use embassy::executor::{task, Executor}; diff --git a/embassy-boot-nrf/Cargo.toml b/embassy-boot-nrf/Cargo.toml index c056dc66a..27407ae92 100644 --- a/embassy-boot-nrf/Cargo.toml +++ b/embassy-boot-nrf/Cargo.toml @@ -1,7 +1,7 @@ [package] edition = "2021" name = "embassy-boot-nrf" -version = "0.2.0" +version = "0.3.0" description = "Bootloader lib for nRF chips" license = "MIT OR Apache-2.0" repository = "https://github.com/embassy-rs/embassy" @@ -22,10 +22,11 @@ target = "thumbv7em-none-eabi" [dependencies] defmt = { version = "0.3", optional = true } +log = { version = "0.4.17", optional = true } -embassy-sync = { version = "0.5.0", path = "../embassy-sync" } -embassy-nrf = { version = "0.1.0", path = "../embassy-nrf", default-features = false } -embassy-boot = { version = "0.2.0", path = "../embassy-boot" } +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } +embassy-nrf = { version = "0.2.0", path = "../embassy-nrf", default-features = false } +embassy-boot = { version = "0.3.0", path = "../embassy-boot" } cortex-m = { version = "0.7.6" } cortex-m-rt = { version = "0.7" } embedded-storage = "0.3.1" diff --git a/embassy-boot-nrf/README.md b/embassy-boot-nrf/README.md index 9dc5b0eb9..f0d87e18c 100644 --- a/embassy-boot-nrf/README.md +++ b/embassy-boot-nrf/README.md @@ -2,7 +2,7 @@ An [Embassy](https://embassy.dev) project. -An adaptation of `embassy-boot` for nRF. +An adaptation of `embassy-boot` for nRF. ## Features diff --git a/embassy-boot-nrf/src/fmt.rs b/embassy-boot-nrf/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-boot-nrf/src/fmt.rs +++ b/embassy-boot-nrf/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-boot-nrf/src/lib.rs b/embassy-boot-nrf/src/lib.rs index 5b20a93c6..e5bc870b5 100644 --- a/embassy-boot-nrf/src/lib.rs +++ b/embassy-boot-nrf/src/lib.rs @@ -4,8 +4,8 @@ mod fmt; pub use embassy_boot::{ - AlignedBuffer, BlockingFirmwareState, BlockingFirmwareUpdater, BootLoaderConfig, FirmwareState, FirmwareUpdater, - FirmwareUpdaterConfig, + AlignedBuffer, BlockingFirmwareState, BlockingFirmwareUpdater, BootError, BootLoaderConfig, FirmwareState, + FirmwareUpdater, FirmwareUpdaterConfig, }; use embassy_nrf::nvmc::PAGE_SIZE; use embassy_nrf::peripherals::WDT; @@ -16,14 +16,27 @@ use embedded_storage::nor_flash::{ErrorType, NorFlash, ReadNorFlash}; pub struct BootLoader; impl BootLoader { - /// Inspect the bootloader state and perform actions required before booting, such as swapping firmware. + /// Inspect the bootloader state and perform actions required before booting, such as swapping firmware pub fn prepare( config: BootLoaderConfig, ) -> Self { + if let Ok(loader) = Self::try_prepare::(config) { + loader + } else { + // Use explicit panic instead of .expect() to ensure this gets routed via defmt/etc. + // properly + panic!("Boot prepare error") + } + } + + /// Inspect the bootloader state and perform actions required before booting, such as swapping firmware + pub fn try_prepare( + config: BootLoaderConfig, + ) -> Result { let mut aligned_buf = AlignedBuffer([0; BUFFER_SIZE]); let mut boot = embassy_boot::BootLoader::new(config); - boot.prepare_boot(&mut aligned_buf.0).expect("Boot prepare error"); - Self + let _state = boot.prepare_boot(aligned_buf.as_mut())?; + Ok(Self) } /// Boots the application without softdevice mechanisms. diff --git a/embassy-boot-rp/Cargo.toml b/embassy-boot-rp/Cargo.toml index 305bc5995..bf5f34abe 100644 --- a/embassy-boot-rp/Cargo.toml +++ b/embassy-boot-rp/Cargo.toml @@ -1,7 +1,7 @@ [package] edition = "2021" name = "embassy-boot-rp" -version = "0.2.0" +version = "0.3.0" description = "Bootloader lib for RP2040 chips" license = "MIT OR Apache-2.0" repository = "https://github.com/embassy-rs/embassy" @@ -16,18 +16,18 @@ categories = [ src_base = "https://github.com/embassy-rs/embassy/blob/embassy-boot-rp-v$VERSION/src/" src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/embassy-boot-rp/src/" target = "thumbv6m-none-eabi" +features = ["embassy-rp/rp2040"] [lib] [dependencies] defmt = { version = "0.3", optional = true } -defmt-rtt = { version = "0.4", optional = true } log = { version = "0.4", optional = true } -embassy-sync = { version = "0.5.0", path = "../embassy-sync" } -embassy-rp = { version = "0.1.0", path = "../embassy-rp", default-features = false } -embassy-boot = { version = "0.2.0", path = "../embassy-boot" } -embassy-time = { version = "0.3.0", path = "../embassy-time" } +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } +embassy-rp = { version = "0.2.0", path = "../embassy-rp", default-features = false } +embassy-boot = { version = "0.3.0", path = "../embassy-boot" } +embassy-time = { version = "0.3.2", path = "../embassy-time" } cortex-m = { version = "0.7.6" } cortex-m-rt = { version = "0.7" } @@ -46,7 +46,6 @@ log = [ "embassy-boot/log", "embassy-rp/log", ] -debug = ["defmt-rtt"] [profile.dev] debug = 2 diff --git a/embassy-boot-rp/build.rs b/embassy-boot-rp/build.rs index 2cbc7ef5e..bfaee3503 100644 --- a/embassy-boot-rp/build.rs +++ b/embassy-boot-rp/build.rs @@ -5,4 +5,5 @@ fn main() { if target.starts_with("thumbv6m-") { println!("cargo:rustc-cfg=armv6m"); } + println!("cargo:rustc-check-cfg=cfg(armv6m)"); } diff --git a/embassy-boot-rp/src/fmt.rs b/embassy-boot-rp/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-boot-rp/src/fmt.rs +++ b/embassy-boot-rp/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-boot-rp/src/lib.rs b/embassy-boot-rp/src/lib.rs index 07a5b3f4d..3e1731f5e 100644 --- a/embassy-boot-rp/src/lib.rs +++ b/embassy-boot-rp/src/lib.rs @@ -4,8 +4,8 @@ mod fmt; pub use embassy_boot::{ - AlignedBuffer, BlockingFirmwareState, BlockingFirmwareUpdater, BootLoaderConfig, FirmwareState, FirmwareUpdater, - FirmwareUpdaterConfig, State, + AlignedBuffer, BlockingFirmwareState, BlockingFirmwareUpdater, BootError, BootLoaderConfig, FirmwareState, + FirmwareUpdater, FirmwareUpdaterConfig, State, }; use embassy_rp::flash::{Blocking, Flash, ERASE_SIZE}; use embassy_rp::peripherals::{FLASH, WATCHDOG}; @@ -21,10 +21,23 @@ impl BootLoader { pub fn prepare( config: BootLoaderConfig, ) -> Self { + if let Ok(loader) = Self::try_prepare::(config) { + loader + } else { + // Use explicit panic instead of .expect() to ensure this gets routed via defmt/etc. + // properly + panic!("Boot prepare error") + } + } + + /// Inspect the bootloader state and perform actions required before booting, such as swapping firmware + pub fn try_prepare( + config: BootLoaderConfig, + ) -> Result { let mut aligned_buf = AlignedBuffer([0; BUFFER_SIZE]); let mut boot = embassy_boot::BootLoader::new(config); - boot.prepare_boot(aligned_buf.as_mut()).expect("Boot prepare error"); - Self + let _state = boot.prepare_boot(aligned_buf.as_mut())?; + Ok(Self) } /// Boots the application. diff --git a/embassy-boot-stm32/Cargo.toml b/embassy-boot-stm32/Cargo.toml index 6f8fbe355..e4ef9a612 100644 --- a/embassy-boot-stm32/Cargo.toml +++ b/embassy-boot-stm32/Cargo.toml @@ -13,7 +13,7 @@ categories = [ ] [package.metadata.embassy_docs] -src_base = "https://github.com/embassy-rs/embassy/blob/embassy-boot-nrf-v$VERSION/embassy-boot-stm32/src/" +src_base = "https://github.com/embassy-rs/embassy/blob/embassy-boot-stm32-v$VERSION/embassy-boot-stm32/src/" src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/embassy-boot-stm32/src/" features = ["embassy-stm32/stm32f429zi"] target = "thumbv7em-none-eabi" @@ -22,12 +22,11 @@ target = "thumbv7em-none-eabi" [dependencies] defmt = { version = "0.3", optional = true } -defmt-rtt = { version = "0.4", optional = true } log = { version = "0.4", optional = true } -embassy-sync = { version = "0.5.0", path = "../embassy-sync" } +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } embassy-stm32 = { version = "0.1.0", path = "../embassy-stm32", default-features = false } -embassy-boot = { version = "0.2.0", path = "../embassy-boot" } +embassy-boot = { version = "0.3.0", path = "../embassy-boot" } cortex-m = { version = "0.7.6" } cortex-m-rt = { version = "0.7" } embedded-storage = "0.3.1" @@ -37,7 +36,6 @@ cfg-if = "1.0.0" [features] defmt = ["dep:defmt", "embassy-boot/defmt", "embassy-stm32/defmt"] log = ["dep:log", "embassy-boot/log", "embassy-stm32/log"] -debug = ["defmt-rtt"] [profile.dev] debug = 2 diff --git a/embassy-boot-stm32/build.rs b/embassy-boot-stm32/build.rs index 2cbc7ef5e..bfaee3503 100644 --- a/embassy-boot-stm32/build.rs +++ b/embassy-boot-stm32/build.rs @@ -5,4 +5,5 @@ fn main() { if target.starts_with("thumbv6m-") { println!("cargo:rustc-cfg=armv6m"); } + println!("cargo:rustc-check-cfg=cfg(armv6m)"); } diff --git a/embassy-boot-stm32/src/fmt.rs b/embassy-boot-stm32/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-boot-stm32/src/fmt.rs +++ b/embassy-boot-stm32/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-boot-stm32/src/lib.rs b/embassy-boot-stm32/src/lib.rs index 4b4091ac9..387cc0ce5 100644 --- a/embassy-boot-stm32/src/lib.rs +++ b/embassy-boot-stm32/src/lib.rs @@ -4,8 +4,8 @@ mod fmt; pub use embassy_boot::{ - AlignedBuffer, BlockingFirmwareState, BlockingFirmwareUpdater, BootLoaderConfig, FirmwareState, FirmwareUpdater, - FirmwareUpdaterConfig, State, + AlignedBuffer, BlockingFirmwareState, BlockingFirmwareUpdater, BootError, BootLoaderConfig, FirmwareState, + FirmwareUpdater, FirmwareUpdaterConfig, State, }; use embedded_storage::nor_flash::NorFlash; @@ -20,10 +20,23 @@ impl BootLoader { pub fn prepare( config: BootLoaderConfig, ) -> Self { + if let Ok(loader) = Self::try_prepare::(config) { + loader + } else { + // Use explicit panic instead of .expect() to ensure this gets routed via defmt/etc. + // properly + panic!("Boot prepare error") + } + } + + /// Inspect the bootloader state and perform actions required before booting, such as swapping firmware + pub fn try_prepare( + config: BootLoaderConfig, + ) -> Result { let mut aligned_buf = AlignedBuffer([0; BUFFER_SIZE]); let mut boot = embassy_boot::BootLoader::new(config); - let state = boot.prepare_boot(aligned_buf.as_mut()).expect("Boot prepare error"); - Self { state } + let state = boot.prepare_boot(aligned_buf.as_mut())?; + Ok(Self { state }) } /// Boots the application. diff --git a/embassy-boot/Cargo.toml b/embassy-boot/Cargo.toml index 242caa229..79ba6456a 100644 --- a/embassy-boot/Cargo.toml +++ b/embassy-boot/Cargo.toml @@ -1,7 +1,7 @@ [package] edition = "2021" name = "embassy-boot" -version = "0.2.0" +version = "0.3.0" description = "A lightweight bootloader supporting firmware updates in a power-fail-safe way, with trial boots and rollbacks." license = "MIT OR Apache-2.0" repository = "https://github.com/embassy-rs/embassy" @@ -27,9 +27,9 @@ features = ["defmt"] defmt = { version = "0.3", optional = true } digest = "0.10" log = { version = "0.4", optional = true } -ed25519-dalek = { version = "2", default_features = false, features = ["digest"], optional = true } -embassy-embedded-hal = { version = "0.1.0", path = "../embassy-embedded-hal" } -embassy-sync = { version = "0.5.0", path = "../embassy-sync" } +ed25519-dalek = { version = "2", default-features = false, features = ["digest"], optional = true } +embassy-embedded-hal = { version = "0.2.0", path = "../embassy-embedded-hal" } +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } embedded-storage = "0.3.1" embedded-storage-async = { version = "0.4.1" } salty = { version = "0.3", optional = true } @@ -42,11 +42,12 @@ rand = "0.8" futures = { version = "0.3", features = ["executor"] } sha1 = "0.10.5" critical-section = { version = "1.1.1", features = ["std"] } -ed25519-dalek = { version = "2", default_features = false, features = ["std", "rand_core", "digest"] } +ed25519-dalek = { version = "2", default-features = false, features = ["std", "rand_core", "digest"] } [features] ed25519-dalek = ["dep:ed25519-dalek", "_verify"] ed25519-salty = ["dep:salty", "_verify"] +flash-erase-zero = [] #Internal features _verify = [] diff --git a/embassy-boot/README.md b/embassy-boot/README.md index 3c2d45e96..c893c83e1 100644 --- a/embassy-boot/README.md +++ b/embassy-boot/README.md @@ -15,7 +15,7 @@ The bootloader divides the storage into 4 main partitions, configurable when cre * BOOTLOADER - Where the bootloader is placed. The bootloader itself consumes about 8kB of flash, but if you need to debug it and have space available, increasing this to 24kB will allow you to run the bootloader with probe-rs. * ACTIVE - Where the main application is placed. The bootloader will attempt to load the application at the start of this partition. The minimum size required for this partition is the size of your application. * DFU - Where the application-to-be-swapped is placed. This partition is written to by the application. This partition must be at least 1 page bigger than the ACTIVE partition. -* BOOTLOADER STATE - Where the bootloader stores the current state describing if the active and dfu partitions need to be swapped. +* BOOTLOADER STATE - Where the bootloader stores the current state describing if the active and dfu partitions need to be swapped. For any partition, the following preconditions are required: @@ -24,7 +24,7 @@ For any partition, the following preconditions are required: The linker scripts for the application and bootloader look similar, but the FLASH region must point to the BOOTLOADER partition for the bootloader, and the ACTIVE partition for the application. -For more details on the bootloader, see [the documentation](https://embassy.dev/book/dev/bootloader.html). +For more details on the bootloader, see [the documentation](https://embassy.dev/book/#_bootloader). ## Hardware support diff --git a/embassy-boot/src/boot_loader.rs b/embassy-boot/src/boot_loader.rs index e568001bc..5bffdc5ea 100644 --- a/embassy-boot/src/boot_loader.rs +++ b/embassy-boot/src/boot_loader.rs @@ -5,7 +5,7 @@ use embassy_sync::blocking_mutex::raw::NoopRawMutex; use embassy_sync::blocking_mutex::Mutex; use embedded_storage::nor_flash::{NorFlash, NorFlashError, NorFlashErrorKind}; -use crate::{State, BOOT_MAGIC, DFU_DETACH_MAGIC, STATE_ERASE_VALUE, SWAP_MAGIC}; +use crate::{State, DFU_DETACH_MAGIC, REVERT_MAGIC, STATE_ERASE_VALUE, SWAP_MAGIC}; /// Errors returned by bootloader #[derive(PartialEq, Eq, Debug)] @@ -49,16 +49,51 @@ pub struct BootLoaderConfig { pub state: STATE, } -impl<'a, FLASH: NorFlash> +impl<'a, ACTIVE: NorFlash, DFU: NorFlash, STATE: NorFlash> BootLoaderConfig< - BlockingPartition<'a, NoopRawMutex, FLASH>, - BlockingPartition<'a, NoopRawMutex, FLASH>, - BlockingPartition<'a, NoopRawMutex, FLASH>, + BlockingPartition<'a, NoopRawMutex, ACTIVE>, + BlockingPartition<'a, NoopRawMutex, DFU>, + BlockingPartition<'a, NoopRawMutex, STATE>, > { - /// Create a bootloader config from the flash and address symbols defined in the linkerfile + /// Constructs a `BootLoaderConfig` instance from flash memory and address symbols defined in the linker file. + /// + /// This method initializes `BlockingPartition` instances for the active, DFU (Device Firmware Update), + /// and state partitions, leveraging start and end addresses specified by the linker. These partitions + /// are critical for managing firmware updates, application state, and boot operations within the bootloader. + /// + /// # Parameters + /// - `active_flash`: A reference to a mutex-protected `RefCell` for the active partition's flash interface. + /// - `dfu_flash`: A reference to a mutex-protected `RefCell` for the DFU partition's flash interface. + /// - `state_flash`: A reference to a mutex-protected `RefCell` for the state partition's flash interface. + /// + /// # Safety + /// The method contains `unsafe` blocks for dereferencing raw pointers that represent the start and end addresses + /// of the bootloader's partitions in flash memory. It is crucial that these addresses are accurately defined + /// in the memory.x file to prevent undefined behavior. + /// + /// The caller must ensure that the memory regions defined by these symbols are valid and that the flash memory + /// interfaces provided are compatible with these regions. + /// + /// # Returns + /// A `BootLoaderConfig` instance with `BlockingPartition` instances for the active, DFU, and state partitions. + /// + /// # Example + /// ```ignore + /// // Assume `active_flash`, `dfu_flash`, and `state_flash` all share the same flash memory interface. + /// let layout = Flash::new_blocking(p.FLASH).into_blocking_regions(); + /// let flash = Mutex::new(RefCell::new(layout.bank1_region)); + /// + /// let config = BootLoaderConfig::from_linkerfile_blocking(&flash, &flash, &flash); + /// // `config` can now be used to create a `BootLoader` instance for managing boot operations. + /// ``` + /// Working examples can be found in the bootloader examples folder. // #[cfg(target_os = "none")] - pub fn from_linkerfile_blocking(flash: &'a Mutex>) -> Self { + pub fn from_linkerfile_blocking( + active_flash: &'a Mutex>, + dfu_flash: &'a Mutex>, + state_flash: &'a Mutex>, + ) -> Self { extern "C" { static __bootloader_state_start: u32; static __bootloader_state_end: u32; @@ -73,21 +108,21 @@ impl<'a, FLASH: NorFlash> let end = &__bootloader_active_end as *const u32 as u32; trace!("ACTIVE: 0x{:x} - 0x{:x}", start, end); - BlockingPartition::new(flash, start, end - start) + BlockingPartition::new(active_flash, start, end - start) }; let dfu = unsafe { let start = &__bootloader_dfu_start as *const u32 as u32; let end = &__bootloader_dfu_end as *const u32 as u32; trace!("DFU: 0x{:x} - 0x{:x}", start, end); - BlockingPartition::new(flash, start, end - start) + BlockingPartition::new(dfu_flash, start, end - start) }; let state = unsafe { let start = &__bootloader_state_start as *const u32 as u32; let end = &__bootloader_state_end as *const u32 as u32; trace!("STATE: 0x{:x} - 0x{:x}", start, end); - BlockingPartition::new(flash, start, end - start) + BlockingPartition::new(state_flash, start, end - start) }; Self { active, dfu, state } @@ -148,29 +183,29 @@ impl BootLoader BootLoader Result { + const { + core::assert!(Self::PAGE_SIZE % ACTIVE::WRITE_SIZE as u32 == 0); + core::assert!(Self::PAGE_SIZE % ACTIVE::ERASE_SIZE as u32 == 0); + core::assert!(Self::PAGE_SIZE % DFU::WRITE_SIZE as u32 == 0); + core::assert!(Self::PAGE_SIZE % DFU::ERASE_SIZE as u32 == 0); + } + // Ensure we have enough progress pages to store copy progress assert_eq!(0, Self::PAGE_SIZE % aligned_buf.len() as u32); - assert_eq!(0, Self::PAGE_SIZE % ACTIVE::WRITE_SIZE as u32); - assert_eq!(0, Self::PAGE_SIZE % ACTIVE::ERASE_SIZE as u32); - assert_eq!(0, Self::PAGE_SIZE % DFU::WRITE_SIZE as u32); - assert_eq!(0, Self::PAGE_SIZE % DFU::ERASE_SIZE as u32); assert!(aligned_buf.len() >= STATE::WRITE_SIZE); assert_eq!(0, aligned_buf.len() % ACTIVE::WRITE_SIZE); assert_eq!(0, aligned_buf.len() % DFU::WRITE_SIZE); @@ -238,7 +276,7 @@ impl BootLoader BootLoader { dfu: DFU, state: FirmwareState<'d, STATE>, + last_erased_dfu_sector_index: Option, } #[cfg(target_os = "none")] -impl<'a, FLASH: NorFlash> - FirmwareUpdaterConfig, Partition<'a, NoopRawMutex, FLASH>> +impl<'a, DFU: NorFlash, STATE: NorFlash> + FirmwareUpdaterConfig, Partition<'a, NoopRawMutex, STATE>> { /// Create a firmware updater config from the flash and address symbols defined in the linkerfile - pub fn from_linkerfile(flash: &'a embassy_sync::mutex::Mutex) -> Self { + pub fn from_linkerfile( + dfu_flash: &'a embassy_sync::mutex::Mutex, + state_flash: &'a embassy_sync::mutex::Mutex, + ) -> Self { extern "C" { static __bootloader_state_start: u32; static __bootloader_state_end: u32; @@ -33,14 +37,14 @@ impl<'a, FLASH: NorFlash> let end = &__bootloader_dfu_end as *const u32 as u32; trace!("DFU: 0x{:x} - 0x{:x}", start, end); - Partition::new(flash, start, end - start) + Partition::new(dfu_flash, start, end - start) }; let state = unsafe { let start = &__bootloader_state_start as *const u32 as u32; let end = &__bootloader_state_end as *const u32 as u32; trace!("STATE: 0x{:x} - 0x{:x}", start, end); - Partition::new(flash, start, end - start) + Partition::new(state_flash, start, end - start) }; Self { dfu, state } @@ -53,6 +57,7 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> FirmwareUpdater<'d, DFU, STATE> { Self { dfu: config.dfu, state: FirmwareState::new(config.state, aligned), + last_erased_dfu_sector_index: None, } } @@ -69,7 +74,7 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> FirmwareUpdater<'d, DFU, STATE> { /// proceed with updating the firmware as it must be signed with a /// corresponding private key (otherwise it could be malicious firmware). /// - /// Mark to trigger firmware swap on next boot if verify suceeds. + /// Mark to trigger firmware swap on next boot if verify succeeds. /// /// If the "ed25519-salty" feature is set (or another similar feature) then the signature is expected to have /// been generated from a SHA-512 digest of the firmware bytes. @@ -102,7 +107,8 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> FirmwareUpdater<'d, DFU, STATE> { let mut message = [0; 64]; self.hash::(_update_len, &mut chunk_buf, &mut message).await?; - public_key.verify(&message, &signature).map_err(into_signature_error)? + public_key.verify(&message, &signature).map_err(into_signature_error)?; + return self.state.mark_updated().await; } #[cfg(feature = "ed25519-salty")] { @@ -129,10 +135,13 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> FirmwareUpdater<'d, DFU, STATE> { message, r.is_ok() ); - r.map_err(into_signature_error)? + r.map_err(into_signature_error)?; + return self.state.mark_updated().await; + } + #[cfg(not(any(feature = "ed25519-dalek", feature = "ed25519-salty")))] + { + Err(FirmwareUpdaterError::Signature(signature::Error::new())) } - - self.state.mark_updated().await } /// Verify the update in DFU with any digest. @@ -169,21 +178,68 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> FirmwareUpdater<'d, DFU, STATE> { self.state.mark_booted().await } - /// Write data to a flash page. + /// Writes firmware data to the device. /// - /// The buffer must follow alignment requirements of the target flash and a multiple of page size big. + /// This function writes the given data to the firmware area starting at the specified offset. + /// It handles sector erasures and data writes while verifying the device is in a proper state + /// for firmware updates. The function ensures that only unerased sectors are erased before + /// writing and efficiently handles the writing process across sector boundaries and in + /// various configurations (data size, sector size, etc.). /// - /// # Safety + /// # Arguments /// - /// Failing to meet alignment and size requirements may result in a panic. + /// * `offset` - The starting offset within the firmware area where data writing should begin. + /// * `data` - A slice of bytes representing the firmware data to be written. It must be a + /// multiple of NorFlash WRITE_SIZE. + /// + /// # Returns + /// + /// A `Result<(), FirmwareUpdaterError>` indicating the success or failure of the write operation. + /// + /// # Errors + /// + /// This function will return an error if: + /// + /// - The device is not in a proper state to receive firmware updates (e.g., not booted). + /// - There is a failure erasing a sector before writing. + /// - There is a failure writing data to the device. pub async fn write_firmware(&mut self, offset: usize, data: &[u8]) -> Result<(), FirmwareUpdaterError> { - assert!(data.len() >= DFU::ERASE_SIZE); - + // Make sure we are running a booted firmware to avoid reverting to a bad state. self.state.verify_booted().await?; - self.dfu.erase(offset as u32, (offset + data.len()) as u32).await?; + // Initialize variables to keep track of the remaining data and the current offset. + let mut remaining_data = data; + let mut offset = offset; - self.dfu.write(offset as u32, data).await?; + // Continue writing as long as there is data left to write. + while !remaining_data.is_empty() { + // Compute the current sector and its boundaries. + let current_sector = offset / DFU::ERASE_SIZE; + let sector_start = current_sector * DFU::ERASE_SIZE; + let sector_end = sector_start + DFU::ERASE_SIZE; + // Determine if the current sector needs to be erased before writing. + let need_erase = self + .last_erased_dfu_sector_index + .map_or(true, |last_erased_sector| current_sector != last_erased_sector); + + // If the sector needs to be erased, erase it and update the last erased sector index. + if need_erase { + self.dfu.erase(sector_start as u32, sector_end as u32).await?; + self.last_erased_dfu_sector_index = Some(current_sector); + } + + // Calculate the size of the data chunk that can be written in the current iteration. + let write_size = core::cmp::min(remaining_data.len(), sector_end - offset); + // Split the data to get the current chunk to be written and the remaining data. + let (data_chunk, rest) = remaining_data.split_at(write_size); + + // Write the current data chunk. + self.dfu.write(offset as u32, data_chunk).await?; + + // Update the offset and remaining data for the next iteration. + remaining_data = rest; + offset += write_size; + } Ok(()) } @@ -233,7 +289,8 @@ impl<'d, STATE: NorFlash> FirmwareState<'d, STATE> { // Make sure we are running a booted firmware to avoid reverting to a bad state. async fn verify_booted(&mut self) -> Result<(), FirmwareUpdaterError> { - if self.get_state().await? == State::Boot { + let state = self.get_state().await?; + if state == State::Boot || state == State::DfuDetach || state == State::Revert { Ok(()) } else { Err(FirmwareUpdaterError::BadState) @@ -247,12 +304,7 @@ impl<'d, STATE: NorFlash> FirmwareState<'d, STATE> { /// `mark_booted`. pub async fn get_state(&mut self) -> Result { self.state.read(0, &mut self.aligned).await?; - - if !self.aligned.iter().any(|&b| b != SWAP_MAGIC) { - Ok(State::Swap) - } else { - Ok(State::Boot) - } + Ok(State::from(&self.aligned[..STATE::WRITE_SIZE])) } /// Mark to trigger firmware swap on next boot. @@ -273,16 +325,25 @@ impl<'d, STATE: NorFlash> FirmwareState<'d, STATE> { async fn set_magic(&mut self, magic: u8) -> Result<(), FirmwareUpdaterError> { self.state.read(0, &mut self.aligned).await?; - if self.aligned.iter().any(|&b| b != magic) { + if self.aligned[..STATE::WRITE_SIZE].iter().any(|&b| b != magic) { // Read progress validity - self.state.read(STATE::WRITE_SIZE as u32, &mut self.aligned).await?; + if STATE::READ_SIZE <= 2 * STATE::WRITE_SIZE { + self.state.read(STATE::WRITE_SIZE as u32, &mut self.aligned).await?; + } else { + self.aligned.rotate_left(STATE::WRITE_SIZE); + } - if self.aligned.iter().any(|&b| b != STATE_ERASE_VALUE) { + if self.aligned[..STATE::WRITE_SIZE] + .iter() + .any(|&b| b != STATE_ERASE_VALUE) + { // The current progress validity marker is invalid } else { // Invalidate progress self.aligned.fill(!STATE_ERASE_VALUE); - self.state.write(STATE::WRITE_SIZE as u32, &self.aligned).await?; + self.state + .write(STATE::WRITE_SIZE as u32, &self.aligned[..STATE::WRITE_SIZE]) + .await?; } // Clear magic and progress @@ -290,7 +351,7 @@ impl<'d, STATE: NorFlash> FirmwareState<'d, STATE> { // Set magic self.aligned.fill(magic); - self.state.write(0, &self.aligned).await?; + self.state.write(0, &self.aligned[..STATE::WRITE_SIZE]).await?; } Ok(()) } @@ -326,4 +387,76 @@ mod tests { assert_eq!(Sha1::digest(update).as_slice(), hash); } + + #[test] + fn can_verify_sha1_sector_bigger_than_chunk() { + let flash = Mutex::::new(MemFlash::<131072, 4096, 8>::default()); + let state = Partition::new(&flash, 0, 4096); + let dfu = Partition::new(&flash, 65536, 65536); + let mut aligned = [0; 8]; + + let update = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66]; + let mut to_write = [0; 4096]; + to_write[..7].copy_from_slice(update.as_slice()); + + let mut updater = FirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }, &mut aligned); + let mut offset = 0; + for chunk in to_write.chunks(1024) { + block_on(updater.write_firmware(offset, chunk)).unwrap(); + offset += chunk.len(); + } + let mut chunk_buf = [0; 2]; + let mut hash = [0; 20]; + block_on(updater.hash::(update.len() as u32, &mut chunk_buf, &mut hash)).unwrap(); + + assert_eq!(Sha1::digest(update).as_slice(), hash); + } + + #[test] + fn can_verify_sha1_sector_smaller_than_chunk() { + let flash = Mutex::::new(MemFlash::<131072, 1024, 8>::default()); + let state = Partition::new(&flash, 0, 4096); + let dfu = Partition::new(&flash, 65536, 65536); + let mut aligned = [0; 8]; + + let update = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66]; + let mut to_write = [0; 4096]; + to_write[..7].copy_from_slice(update.as_slice()); + + let mut updater = FirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }, &mut aligned); + let mut offset = 0; + for chunk in to_write.chunks(2048) { + block_on(updater.write_firmware(offset, chunk)).unwrap(); + offset += chunk.len(); + } + let mut chunk_buf = [0; 2]; + let mut hash = [0; 20]; + block_on(updater.hash::(update.len() as u32, &mut chunk_buf, &mut hash)).unwrap(); + + assert_eq!(Sha1::digest(update).as_slice(), hash); + } + + #[test] + fn can_verify_sha1_cross_sector_boundary() { + let flash = Mutex::::new(MemFlash::<131072, 1024, 8>::default()); + let state = Partition::new(&flash, 0, 4096); + let dfu = Partition::new(&flash, 65536, 65536); + let mut aligned = [0; 8]; + + let update = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66]; + let mut to_write = [0; 4096]; + to_write[..7].copy_from_slice(update.as_slice()); + + let mut updater = FirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }, &mut aligned); + let mut offset = 0; + for chunk in to_write.chunks(896) { + block_on(updater.write_firmware(offset, chunk)).unwrap(); + offset += chunk.len(); + } + let mut chunk_buf = [0; 2]; + let mut hash = [0; 20]; + block_on(updater.hash::(update.len() as u32, &mut chunk_buf, &mut hash)).unwrap(); + + assert_eq!(Sha1::digest(update).as_slice(), hash); + } } diff --git a/embassy-boot/src/firmware_updater/blocking.rs b/embassy-boot/src/firmware_updater/blocking.rs index f1368540d..08062b0d0 100644 --- a/embassy-boot/src/firmware_updater/blocking.rs +++ b/embassy-boot/src/firmware_updater/blocking.rs @@ -13,15 +13,47 @@ use crate::{FirmwareUpdaterError, State, BOOT_MAGIC, DFU_DETACH_MAGIC, STATE_ERA pub struct BlockingFirmwareUpdater<'d, DFU: NorFlash, STATE: NorFlash> { dfu: DFU, state: BlockingFirmwareState<'d, STATE>, + last_erased_dfu_sector_index: Option, } #[cfg(target_os = "none")] -impl<'a, FLASH: NorFlash> - FirmwareUpdaterConfig, BlockingPartition<'a, NoopRawMutex, FLASH>> +impl<'a, DFU: NorFlash, STATE: NorFlash> + FirmwareUpdaterConfig, BlockingPartition<'a, NoopRawMutex, STATE>> { - /// Create a firmware updater config from the flash and address symbols defined in the linkerfile + /// Constructs a `FirmwareUpdaterConfig` instance from flash memory and address symbols defined in the linker file. + /// + /// This method initializes `BlockingPartition` instances for the DFU (Device Firmware Update), and state + /// partitions, leveraging start and end addresses specified by the linker. These partitions are critical + /// for managing firmware updates, application state, and boot operations within the bootloader. + /// + /// # Parameters + /// - `dfu_flash`: A reference to a mutex-protected `RefCell` for the DFU partition's flash interface. + /// - `state_flash`: A reference to a mutex-protected `RefCell` for the state partition's flash interface. + /// + /// # Safety + /// The method contains `unsafe` blocks for dereferencing raw pointers that represent the start and end addresses + /// of the bootloader's partitions in flash memory. It is crucial that these addresses are accurately defined + /// in the memory.x file to prevent undefined behavior. + /// + /// The caller must ensure that the memory regions defined by these symbols are valid and that the flash memory + /// interfaces provided are compatible with these regions. + /// + /// # Returns + /// A `FirmwareUpdaterConfig` instance with `BlockingPartition` instances for the DFU, and state partitions. + /// + /// # Example + /// ```ignore + /// // Assume `dfu_flash`, and `state_flash` share the same flash memory interface. + /// let layout = Flash::new_blocking(p.FLASH).into_blocking_regions(); + /// let flash = Mutex::new(RefCell::new(layout.bank1_region)); + /// + /// let config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash, &flash); + /// // `config` can now be used to create a `FirmwareUpdater` instance for managing boot operations. + /// ``` + /// Working examples can be found in the bootloader examples folder. pub fn from_linkerfile_blocking( - flash: &'a embassy_sync::blocking_mutex::Mutex>, + dfu_flash: &'a embassy_sync::blocking_mutex::Mutex>, + state_flash: &'a embassy_sync::blocking_mutex::Mutex>, ) -> Self { extern "C" { static __bootloader_state_start: u32; @@ -35,14 +67,14 @@ impl<'a, FLASH: NorFlash> let end = &__bootloader_dfu_end as *const u32 as u32; trace!("DFU: 0x{:x} - 0x{:x}", start, end); - BlockingPartition::new(flash, start, end - start) + BlockingPartition::new(dfu_flash, start, end - start) }; let state = unsafe { let start = &__bootloader_state_start as *const u32 as u32; let end = &__bootloader_state_end as *const u32 as u32; trace!("STATE: 0x{:x} - 0x{:x}", start, end); - BlockingPartition::new(flash, start, end - start) + BlockingPartition::new(state_flash, start, end - start) }; Self { dfu, state } @@ -60,6 +92,7 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<'d, DFU, STATE> Self { dfu: config.dfu, state: BlockingFirmwareState::new(config.state, aligned), + last_erased_dfu_sector_index: None, } } @@ -76,7 +109,7 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<'d, DFU, STATE> /// proceed with updating the firmware as it must be signed with a /// corresponding private key (otherwise it could be malicious firmware). /// - /// Mark to trigger firmware swap on next boot if verify suceeds. + /// Mark to trigger firmware swap on next boot if verify succeeds. /// /// If the "ed25519-salty" feature is set (or another similar feature) then the signature is expected to have /// been generated from a SHA-512 digest of the firmware bytes. @@ -109,7 +142,8 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<'d, DFU, STATE> let mut chunk_buf = [0; 2]; self.hash::(_update_len, &mut chunk_buf, &mut message)?; - public_key.verify(&message, &signature).map_err(into_signature_error)? + public_key.verify(&message, &signature).map_err(into_signature_error)?; + return self.state.mark_updated(); } #[cfg(feature = "ed25519-salty")] { @@ -136,10 +170,13 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<'d, DFU, STATE> message, r.is_ok() ); - r.map_err(into_signature_error)? + r.map_err(into_signature_error)?; + return self.state.mark_updated(); + } + #[cfg(not(any(feature = "ed25519-dalek", feature = "ed25519-salty")))] + { + Err(FirmwareUpdaterError::Signature(signature::Error::new())) } - - self.state.mark_updated() } /// Verify the update in DFU with any digest. @@ -176,20 +213,68 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<'d, DFU, STATE> self.state.mark_booted() } - /// Write data to a flash page. + /// Writes firmware data to the device. /// - /// The buffer must follow alignment requirements of the target flash and a multiple of page size big. + /// This function writes the given data to the firmware area starting at the specified offset. + /// It handles sector erasures and data writes while verifying the device is in a proper state + /// for firmware updates. The function ensures that only unerased sectors are erased before + /// writing and efficiently handles the writing process across sector boundaries and in + /// various configurations (data size, sector size, etc.). /// - /// # Safety + /// # Arguments /// - /// Failing to meet alignment and size requirements may result in a panic. + /// * `offset` - The starting offset within the firmware area where data writing should begin. + /// * `data` - A slice of bytes representing the firmware data to be written. It must be a + /// multiple of NorFlash WRITE_SIZE. + /// + /// # Returns + /// + /// A `Result<(), FirmwareUpdaterError>` indicating the success or failure of the write operation. + /// + /// # Errors + /// + /// This function will return an error if: + /// + /// - The device is not in a proper state to receive firmware updates (e.g., not booted). + /// - There is a failure erasing a sector before writing. + /// - There is a failure writing data to the device. pub fn write_firmware(&mut self, offset: usize, data: &[u8]) -> Result<(), FirmwareUpdaterError> { - assert!(data.len() >= DFU::ERASE_SIZE); + // Make sure we are running a booted firmware to avoid reverting to a bad state. self.state.verify_booted()?; - self.dfu.erase(offset as u32, (offset + data.len()) as u32)?; + // Initialize variables to keep track of the remaining data and the current offset. + let mut remaining_data = data; + let mut offset = offset; - self.dfu.write(offset as u32, data)?; + // Continue writing as long as there is data left to write. + while !remaining_data.is_empty() { + // Compute the current sector and its boundaries. + let current_sector = offset / DFU::ERASE_SIZE; + let sector_start = current_sector * DFU::ERASE_SIZE; + let sector_end = sector_start + DFU::ERASE_SIZE; + // Determine if the current sector needs to be erased before writing. + let need_erase = self + .last_erased_dfu_sector_index + .map_or(true, |last_erased_sector| current_sector != last_erased_sector); + + // If the sector needs to be erased, erase it and update the last erased sector index. + if need_erase { + self.dfu.erase(sector_start as u32, sector_end as u32)?; + self.last_erased_dfu_sector_index = Some(current_sector); + } + + // Calculate the size of the data chunk that can be written in the current iteration. + let write_size = core::cmp::min(remaining_data.len(), sector_end - offset); + // Split the data to get the current chunk to be written and the remaining data. + let (data_chunk, rest) = remaining_data.split_at(write_size); + + // Write the current data chunk. + self.dfu.write(offset as u32, data_chunk)?; + + // Update the offset and remaining data for the next iteration. + remaining_data = rest; + offset += write_size; + } Ok(()) } @@ -239,7 +324,8 @@ impl<'d, STATE: NorFlash> BlockingFirmwareState<'d, STATE> { // Make sure we are running a booted firmware to avoid reverting to a bad state. fn verify_booted(&mut self) -> Result<(), FirmwareUpdaterError> { - if self.get_state()? == State::Boot || self.get_state()? == State::DfuDetach { + let state = self.get_state()?; + if state == State::Boot || state == State::DfuDetach || state == State::Revert { Ok(()) } else { Err(FirmwareUpdaterError::BadState) @@ -253,14 +339,7 @@ impl<'d, STATE: NorFlash> BlockingFirmwareState<'d, STATE> { /// `mark_booted`. pub fn get_state(&mut self) -> Result { self.state.read(0, &mut self.aligned)?; - - if !self.aligned.iter().any(|&b| b != SWAP_MAGIC) { - Ok(State::Swap) - } else if !self.aligned.iter().any(|&b| b != DFU_DETACH_MAGIC) { - Ok(State::DfuDetach) - } else { - Ok(State::Boot) - } + Ok(State::from(&self.aligned)) } /// Mark to trigger firmware swap on next boot. @@ -337,4 +416,82 @@ mod tests { assert_eq!(Sha1::digest(update).as_slice(), hash); } + + #[test] + fn can_verify_sha1_sector_bigger_than_chunk() { + let flash = Mutex::::new(RefCell::new(MemFlash::<131072, 4096, 8>::default())); + let state = BlockingPartition::new(&flash, 0, 4096); + let dfu = BlockingPartition::new(&flash, 65536, 65536); + let mut aligned = [0; 8]; + + let update = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66]; + let mut to_write = [0; 4096]; + to_write[..7].copy_from_slice(update.as_slice()); + + let mut updater = BlockingFirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }, &mut aligned); + let mut offset = 0; + for chunk in to_write.chunks(1024) { + updater.write_firmware(offset, chunk).unwrap(); + offset += chunk.len(); + } + let mut chunk_buf = [0; 2]; + let mut hash = [0; 20]; + updater + .hash::(update.len() as u32, &mut chunk_buf, &mut hash) + .unwrap(); + + assert_eq!(Sha1::digest(update).as_slice(), hash); + } + + #[test] + fn can_verify_sha1_sector_smaller_than_chunk() { + let flash = Mutex::::new(RefCell::new(MemFlash::<131072, 1024, 8>::default())); + let state = BlockingPartition::new(&flash, 0, 4096); + let dfu = BlockingPartition::new(&flash, 65536, 65536); + let mut aligned = [0; 8]; + + let update = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66]; + let mut to_write = [0; 4096]; + to_write[..7].copy_from_slice(update.as_slice()); + + let mut updater = BlockingFirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }, &mut aligned); + let mut offset = 0; + for chunk in to_write.chunks(2048) { + updater.write_firmware(offset, chunk).unwrap(); + offset += chunk.len(); + } + let mut chunk_buf = [0; 2]; + let mut hash = [0; 20]; + updater + .hash::(update.len() as u32, &mut chunk_buf, &mut hash) + .unwrap(); + + assert_eq!(Sha1::digest(update).as_slice(), hash); + } + + #[test] + fn can_verify_sha1_cross_sector_boundary() { + let flash = Mutex::::new(RefCell::new(MemFlash::<131072, 1024, 8>::default())); + let state = BlockingPartition::new(&flash, 0, 4096); + let dfu = BlockingPartition::new(&flash, 65536, 65536); + let mut aligned = [0; 8]; + + let update = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66]; + let mut to_write = [0; 4096]; + to_write[..7].copy_from_slice(update.as_slice()); + + let mut updater = BlockingFirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }, &mut aligned); + let mut offset = 0; + for chunk in to_write.chunks(896) { + updater.write_firmware(offset, chunk).unwrap(); + offset += chunk.len(); + } + let mut chunk_buf = [0; 2]; + let mut hash = [0; 20]; + updater + .hash::(update.len() as u32, &mut chunk_buf, &mut hash) + .unwrap(); + + assert_eq!(Sha1::digest(update).as_slice(), hash); + } } diff --git a/embassy-boot/src/fmt.rs b/embassy-boot/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-boot/src/fmt.rs +++ b/embassy-boot/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-boot/src/lib.rs b/embassy-boot/src/lib.rs index b4f03e01e..e2c4cf771 100644 --- a/embassy-boot/src/lib.rs +++ b/embassy-boot/src/lib.rs @@ -14,13 +14,18 @@ mod test_flash; // The expected value of the flash after an erase // TODO: Use the value provided by NorFlash when available +#[cfg(not(feature = "flash-erase-zero"))] pub(crate) const STATE_ERASE_VALUE: u8 = 0xFF; +#[cfg(feature = "flash-erase-zero")] +pub(crate) const STATE_ERASE_VALUE: u8 = 0x00; + pub use boot_loader::{BootError, BootLoader, BootLoaderConfig}; pub use firmware_updater::{ BlockingFirmwareState, BlockingFirmwareUpdater, FirmwareState, FirmwareUpdater, FirmwareUpdaterConfig, FirmwareUpdaterError, }; +pub(crate) const REVERT_MAGIC: u8 = 0xC0; pub(crate) const BOOT_MAGIC: u8 = 0xD0; pub(crate) const SWAP_MAGIC: u8 = 0xF0; pub(crate) const DFU_DETACH_MAGIC: u8 = 0xE0; @@ -33,10 +38,30 @@ pub enum State { Boot, /// Bootloader has swapped the active partition with the dfu partition and will attempt boot. Swap, + /// Bootloader has reverted the active partition with the dfu partition and will attempt boot. + Revert, /// Application has received a request to reboot into DFU mode to apply an update. DfuDetach, } +impl From for State +where + T: AsRef<[u8]>, +{ + fn from(magic: T) -> State { + let magic = magic.as_ref(); + if !magic.iter().any(|&b| b != SWAP_MAGIC) { + State::Swap + } else if !magic.iter().any(|&b| b != REVERT_MAGIC) { + State::Revert + } else if !magic.iter().any(|&b| b != DFU_DETACH_MAGIC) { + State::DfuDetach + } else { + State::Boot + } + } +} + /// Buffer aligned to 32 byte boundary, largest known alignment requirement for embassy-boot. #[repr(align(32))] pub struct AlignedBuffer(pub [u8; N]); @@ -153,6 +178,9 @@ mod tests { // Running again should cause a revert assert_eq!(State::Swap, bootloader.prepare_boot(&mut page).unwrap()); + // Next time we know it was reverted + assert_eq!(State::Revert, bootloader.prepare_boot(&mut page).unwrap()); + let mut read_buf = [0; FIRMWARE_SIZE]; flash.active().read(0, &mut read_buf).unwrap(); assert_eq!(ORIGINAL, read_buf); diff --git a/embassy-boot/src/test_flash/asynch.rs b/embassy-boot/src/test_flash/asynch.rs index 3ac9e71ab..c67f2495c 100644 --- a/embassy-boot/src/test_flash/asynch.rs +++ b/embassy-boot/src/test_flash/asynch.rs @@ -43,7 +43,7 @@ where } fn create_partition(mutex: &Mutex) -> Partition { - Partition::new(mutex, 0, mutex.try_lock().unwrap().capacity() as u32) + Partition::new(mutex, 0, unwrap!(mutex.try_lock()).capacity() as u32) } } diff --git a/embassy-embedded-hal/CHANGELOG.md b/embassy-embedded-hal/CHANGELOG.md new file mode 100644 index 000000000..f8e272160 --- /dev/null +++ b/embassy-embedded-hal/CHANGELOG.md @@ -0,0 +1,21 @@ +# Changelog for embassy-embedded-hal + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## Unreleased + +## 0.2.0 - 2024-08-05 + +- Add Clone derive to flash Partition in embassy-embedded-hal +- Add support for all word sizes to async shared spi +- Add Copy and 'static constraint to Word type in SPI structs +- Improve flexibility by introducing SPI word size as a generic parameter +- Allow changing Spi/I2cDeviceWithConfig's config at runtime +- Impl `MultiwriteNorFlash` for `BlockingAsync` + +## 0.1.0 - 2024-01-10 + +- First release diff --git a/embassy-embedded-hal/Cargo.toml b/embassy-embedded-hal/Cargo.toml index e89179740..345dc3420 100644 --- a/embassy-embedded-hal/Cargo.toml +++ b/embassy-embedded-hal/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "embassy-embedded-hal" -version = "0.1.0" +version = "0.2.0" edition = "2021" license = "MIT OR Apache-2.0" description = "Collection of utilities to use `embedded-hal` and `embedded-storage` traits with Embassy." @@ -28,8 +28,8 @@ default = ["time"] [dependencies] embassy-futures = { version = "0.1.0", path = "../embassy-futures" } -embassy-sync = { version = "0.5.0", path = "../embassy-sync" } -embassy-time = { version = "0.3.0", path = "../embassy-time", optional = true } +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } +embassy-time = { version = "0.3.2", path = "../embassy-time", optional = true } embedded-hal-02 = { package = "embedded-hal", version = "0.2.6", features = [ "unproven", ] } diff --git a/embassy-embedded-hal/src/adapter/blocking_async.rs b/embassy-embedded-hal/src/adapter/blocking_async.rs index ae0d0a7f9..bafc31583 100644 --- a/embassy-embedded-hal/src/adapter/blocking_async.rs +++ b/embassy-embedded-hal/src/adapter/blocking_async.rs @@ -104,8 +104,10 @@ where } /// NOR flash wrapper -use embedded_storage::nor_flash::{ErrorType, NorFlash, ReadNorFlash}; -use embedded_storage_async::nor_flash::{NorFlash as AsyncNorFlash, ReadNorFlash as AsyncReadNorFlash}; +use embedded_storage::nor_flash::{ErrorType, MultiwriteNorFlash, NorFlash, ReadNorFlash}; +use embedded_storage_async::nor_flash::{ + MultiwriteNorFlash as AsyncMultiwriteNorFlash, NorFlash as AsyncNorFlash, ReadNorFlash as AsyncReadNorFlash, +}; impl ErrorType for BlockingAsync where @@ -143,3 +145,5 @@ where self.wrapped.capacity() } } + +impl AsyncMultiwriteNorFlash for BlockingAsync where T: MultiwriteNorFlash {} diff --git a/embassy-embedded-hal/src/flash/partition/asynch.rs b/embassy-embedded-hal/src/flash/partition/asynch.rs index 5920436dd..1b0c91232 100644 --- a/embassy-embedded-hal/src/flash/partition/asynch.rs +++ b/embassy-embedded-hal/src/flash/partition/asynch.rs @@ -18,6 +18,16 @@ pub struct Partition<'a, M: RawMutex, T: NorFlash> { size: u32, } +impl<'a, M: RawMutex, T: NorFlash> Clone for Partition<'a, M, T> { + fn clone(&self) -> Self { + Self { + flash: self.flash, + offset: self.offset, + size: self.size, + } + } +} + impl<'a, M: RawMutex, T: NorFlash> Partition<'a, M, T> { /// Create a new partition pub const fn new(flash: &'a Mutex, offset: u32, size: u32) -> Self { diff --git a/embassy-embedded-hal/src/flash/partition/blocking.rs b/embassy-embedded-hal/src/flash/partition/blocking.rs index 2ddbe3de0..a68df7812 100644 --- a/embassy-embedded-hal/src/flash/partition/blocking.rs +++ b/embassy-embedded-hal/src/flash/partition/blocking.rs @@ -19,6 +19,16 @@ pub struct BlockingPartition<'a, M: RawMutex, T: NorFlash> { size: u32, } +impl<'a, M: RawMutex, T: NorFlash> Clone for BlockingPartition<'a, M, T> { + fn clone(&self) -> Self { + Self { + flash: self.flash, + offset: self.offset, + size: self.size, + } + } +} + impl<'a, M: RawMutex, T: NorFlash> BlockingPartition<'a, M, T> { /// Create a new partition pub const fn new(flash: &'a Mutex>, offset: u32, size: u32) -> Self { diff --git a/embassy-embedded-hal/src/shared_bus/asynch/i2c.rs b/embassy-embedded-hal/src/shared_bus/asynch/i2c.rs index 779c04263..71ce09def 100644 --- a/embassy-embedded-hal/src/shared_bus/asynch/i2c.rs +++ b/embassy-embedded-hal/src/shared_bus/asynch/i2c.rs @@ -106,6 +106,11 @@ impl<'a, M: RawMutex, BUS: SetConfig> I2cDeviceWithConfig<'a, M, BUS> { pub fn new(bus: &'a Mutex, config: BUS::Config) -> Self { Self { bus, config } } + + /// Change the device's config at runtime + pub fn set_config(&mut self, config: BUS::Config) { + self.config = config; + } } impl<'a, M, BUS> i2c::ErrorType for I2cDeviceWithConfig<'a, M, BUS> diff --git a/embassy-embedded-hal/src/shared_bus/asynch/spi.rs b/embassy-embedded-hal/src/shared_bus/asynch/spi.rs index 62b2c92a0..30d4ecc36 100644 --- a/embassy-embedded-hal/src/shared_bus/asynch/spi.rs +++ b/embassy-embedded-hal/src/shared_bus/asynch/spi.rs @@ -55,13 +55,14 @@ where type Error = SpiDeviceError; } -impl spi::SpiDevice for SpiDevice<'_, M, BUS, CS> +impl spi::SpiDevice for SpiDevice<'_, M, BUS, CS> where M: RawMutex, - BUS: spi::SpiBus, + BUS: spi::SpiBus, CS: OutputPin, + Word: Copy + 'static, { - async fn transaction(&mut self, operations: &mut [spi::Operation<'_, u8>]) -> Result<(), Self::Error> { + async fn transaction(&mut self, operations: &mut [spi::Operation<'_, Word>]) -> Result<(), Self::Error> { if cfg!(not(feature = "time")) && operations.iter().any(|op| matches!(op, Operation::DelayNs(_))) { return Err(SpiDeviceError::DelayNotSupported); } @@ -122,6 +123,11 @@ impl<'a, M: RawMutex, BUS: SetConfig, CS> SpiDeviceWithConfig<'a, M, BUS, CS> { pub fn new(bus: &'a Mutex, cs: CS, config: BUS::Config) -> Self { Self { bus, cs, config } } + + /// Change the device's config at runtime + pub fn set_config(&mut self, config: BUS::Config) { + self.config = config; + } } impl<'a, M, BUS, CS> spi::ErrorType for SpiDeviceWithConfig<'a, M, BUS, CS> @@ -133,13 +139,14 @@ where type Error = SpiDeviceError; } -impl spi::SpiDevice for SpiDeviceWithConfig<'_, M, BUS, CS> +impl spi::SpiDevice for SpiDeviceWithConfig<'_, M, BUS, CS> where M: RawMutex, - BUS: spi::SpiBus + SetConfig, + BUS: spi::SpiBus + SetConfig, CS: OutputPin, + Word: Copy + 'static, { - async fn transaction(&mut self, operations: &mut [spi::Operation<'_, u8>]) -> Result<(), Self::Error> { + async fn transaction(&mut self, operations: &mut [spi::Operation<'_, Word>]) -> Result<(), Self::Error> { if cfg!(not(feature = "time")) && operations.iter().any(|op| matches!(op, Operation::DelayNs(_))) { return Err(SpiDeviceError::DelayNotSupported); } diff --git a/embassy-embedded-hal/src/shared_bus/blocking/i2c.rs b/embassy-embedded-hal/src/shared_bus/blocking/i2c.rs index 233c9e1fd..627767c8a 100644 --- a/embassy-embedded-hal/src/shared_bus/blocking/i2c.rs +++ b/embassy-embedded-hal/src/shared_bus/blocking/i2c.rs @@ -67,9 +67,11 @@ where } fn transaction<'a>(&mut self, address: u8, operations: &mut [Operation<'a>]) -> Result<(), Self::Error> { - let _ = address; - let _ = operations; - todo!() + self.bus.lock(|bus| { + bus.borrow_mut() + .transaction(address, operations) + .map_err(I2cDeviceError::I2c) + }) } } @@ -130,6 +132,11 @@ impl<'a, M: RawMutex, BUS: SetConfig> I2cDeviceWithConfig<'a, M, BUS> { pub fn new(bus: &'a Mutex>, config: BUS::Config) -> Self { Self { bus, config } } + + /// Change the device's config at runtime + pub fn set_config(&mut self, config: BUS::Config) { + self.config = config; + } } impl<'a, M, BUS> ErrorType for I2cDeviceWithConfig<'a, M, BUS> @@ -171,8 +178,10 @@ where } fn transaction<'a>(&mut self, address: u8, operations: &mut [Operation<'a>]) -> Result<(), Self::Error> { - let _ = address; - let _ = operations; - todo!() + self.bus.lock(|bus| { + let mut bus = bus.borrow_mut(); + bus.set_config(&self.config).map_err(|_| I2cDeviceError::Config)?; + bus.transaction(address, operations).map_err(I2cDeviceError::I2c) + }) } } diff --git a/embassy-embedded-hal/src/shared_bus/blocking/spi.rs b/embassy-embedded-hal/src/shared_bus/blocking/spi.rs index 59b65bfbd..eb9c0c4f4 100644 --- a/embassy-embedded-hal/src/shared_bus/blocking/spi.rs +++ b/embassy-embedded-hal/src/shared_bus/blocking/spi.rs @@ -48,13 +48,14 @@ where type Error = SpiDeviceError; } -impl embedded_hal_1::spi::SpiDevice for SpiDevice<'_, M, BUS, CS> +impl embedded_hal_1::spi::SpiDevice for SpiDevice<'_, M, BUS, CS> where M: RawMutex, - BUS: SpiBus, + BUS: SpiBus, CS: OutputPin, + Word: Copy + 'static, { - fn transaction(&mut self, operations: &mut [Operation<'_, u8>]) -> Result<(), Self::Error> { + fn transaction(&mut self, operations: &mut [embedded_hal_1::spi::Operation<'_, Word>]) -> Result<(), Self::Error> { if cfg!(not(feature = "time")) && operations.iter().any(|op| matches!(op, Operation::DelayNs(_))) { return Err(SpiDeviceError::DelayNotSupported); } @@ -90,47 +91,6 @@ where } } -impl<'d, M, BUS, CS, BusErr, CsErr> embedded_hal_02::blocking::spi::Transfer for SpiDevice<'_, M, BUS, CS> -where - M: RawMutex, - BUS: embedded_hal_02::blocking::spi::Transfer, - CS: OutputPin, -{ - type Error = SpiDeviceError; - fn transfer<'w>(&mut self, words: &'w mut [u8]) -> Result<&'w [u8], Self::Error> { - self.bus.lock(|bus| { - let mut bus = bus.borrow_mut(); - self.cs.set_low().map_err(SpiDeviceError::Cs)?; - let op_res = bus.transfer(words); - let cs_res = self.cs.set_high(); - let op_res = op_res.map_err(SpiDeviceError::Spi)?; - cs_res.map_err(SpiDeviceError::Cs)?; - Ok(op_res) - }) - } -} - -impl<'d, M, BUS, CS, BusErr, CsErr> embedded_hal_02::blocking::spi::Write for SpiDevice<'_, M, BUS, CS> -where - M: RawMutex, - BUS: embedded_hal_02::blocking::spi::Write, - CS: OutputPin, -{ - type Error = SpiDeviceError; - - fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> { - self.bus.lock(|bus| { - let mut bus = bus.borrow_mut(); - self.cs.set_low().map_err(SpiDeviceError::Cs)?; - let op_res = bus.write(words); - let cs_res = self.cs.set_high(); - let op_res = op_res.map_err(SpiDeviceError::Spi)?; - cs_res.map_err(SpiDeviceError::Cs)?; - Ok(op_res) - }) - } -} - /// SPI device on a shared bus, with its own configuration. /// /// This is like [`SpiDevice`], with an additional bus configuration that's applied @@ -147,6 +107,11 @@ impl<'a, M: RawMutex, BUS: SetConfig, CS> SpiDeviceWithConfig<'a, M, BUS, CS> { pub fn new(bus: &'a Mutex>, cs: CS, config: BUS::Config) -> Self { Self { bus, cs, config } } + + /// Change the device's config at runtime + pub fn set_config(&mut self, config: BUS::Config) { + self.config = config; + } } impl<'a, M, BUS, CS> spi::ErrorType for SpiDeviceWithConfig<'a, M, BUS, CS> @@ -158,13 +123,14 @@ where type Error = SpiDeviceError; } -impl embedded_hal_1::spi::SpiDevice for SpiDeviceWithConfig<'_, M, BUS, CS> +impl embedded_hal_1::spi::SpiDevice for SpiDeviceWithConfig<'_, M, BUS, CS> where M: RawMutex, - BUS: SpiBus + SetConfig, + BUS: SpiBus + SetConfig, CS: OutputPin, + Word: Copy + 'static, { - fn transaction(&mut self, operations: &mut [Operation<'_, u8>]) -> Result<(), Self::Error> { + fn transaction(&mut self, operations: &mut [embedded_hal_1::spi::Operation<'_, Word>]) -> Result<(), Self::Error> { if cfg!(not(feature = "time")) && operations.iter().any(|op| matches!(op, Operation::DelayNs(_))) { return Err(SpiDeviceError::DelayNotSupported); } diff --git a/embassy-executor-macros/Cargo.toml b/embassy-executor-macros/Cargo.toml index 2953e7ccc..5a38f2f06 100644 --- a/embassy-executor-macros/Cargo.toml +++ b/embassy-executor-macros/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "embassy-executor-macros" -version = "0.4.1" +version = "0.6.2" edition = "2021" license = "MIT OR Apache-2.0" description = "macros for creating the entry point and tasks for embassy-executor" @@ -13,7 +13,7 @@ categories = [ ] [dependencies] -syn = { version = "2.0.15", features = ["full", "extra-traits"] } +syn = { version = "2.0.15", features = ["full", "visit"] } quote = "1.0.9" darling = "0.20.1" proc-macro2 = "1.0.29" diff --git a/embassy-executor-macros/src/lib.rs b/embassy-executor-macros/src/lib.rs index 5461fe04c..5f2182f10 100644 --- a/embassy-executor-macros/src/lib.rs +++ b/embassy-executor-macros/src/lib.rs @@ -1,28 +1,11 @@ #![doc = include_str!("../README.md")] extern crate proc_macro; -use darling::ast::NestedMeta; use proc_macro::TokenStream; mod macros; mod util; use macros::*; -use syn::parse::{Parse, ParseBuffer}; -use syn::punctuated::Punctuated; -use syn::Token; - -struct Args { - meta: Vec, -} - -impl Parse for Args { - fn parse(input: &ParseBuffer) -> syn::Result { - let meta = Punctuated::::parse_terminated(input)?; - Ok(Args { - meta: meta.into_iter().collect(), - }) - } -} /// Declares an async task that can be run by `embassy-executor`. The optional `pool_size` parameter can be used to specify how /// many concurrent tasks can be spawned (default is 1) for the function. @@ -56,17 +39,12 @@ impl Parse for Args { /// ``` #[proc_macro_attribute] pub fn task(args: TokenStream, item: TokenStream) -> TokenStream { - let args = syn::parse_macro_input!(args as Args); - let f = syn::parse_macro_input!(item as syn::ItemFn); - - task::run(&args.meta, f).unwrap_or_else(|x| x).into() + task::run(args.into(), item.into()).into() } #[proc_macro_attribute] pub fn main_avr(args: TokenStream, item: TokenStream) -> TokenStream { - let args = syn::parse_macro_input!(args as Args); - let f = syn::parse_macro_input!(item as syn::ItemFn); - main::run(&args.meta, f, main::avr()).unwrap_or_else(|x| x).into() + main::run(args.into(), item.into(), &main::ARCH_AVR).into() } /// Creates a new `executor` instance and declares an application entry point for Cortex-M spawning the corresponding function body as an async task. @@ -89,9 +67,32 @@ pub fn main_avr(args: TokenStream, item: TokenStream) -> TokenStream { /// ``` #[proc_macro_attribute] pub fn main_cortex_m(args: TokenStream, item: TokenStream) -> TokenStream { - let args = syn::parse_macro_input!(args as Args); - let f = syn::parse_macro_input!(item as syn::ItemFn); - main::run(&args.meta, f, main::cortex_m()).unwrap_or_else(|x| x).into() + main::run(args.into(), item.into(), &main::ARCH_CORTEX_M).into() +} + +/// Creates a new `executor` instance and declares an architecture agnostic application entry point spawning +/// the corresponding function body as an async task. +/// +/// The following restrictions apply: +/// +/// * The function must accept exactly 1 parameter, an `embassy_executor::Spawner` handle that it can use to spawn additional tasks. +/// * The function must be declared `async`. +/// * The function must not use generics. +/// * Only a single `main` task may be declared. +/// +/// A user-defined entry macro must provided via the `entry` argument +/// +/// ## Examples +/// Spawning a task: +/// ``` rust +/// #[embassy_executor::main(entry = "qingke_rt::entry")] +/// async fn main(_s: embassy_executor::Spawner) { +/// // Function body +/// } +/// ``` +#[proc_macro_attribute] +pub fn main_spin(args: TokenStream, item: TokenStream) -> TokenStream { + main::run(args.into(), item.into(), &main::ARCH_SPIN).into() } /// Creates a new `executor` instance and declares an application entry point for RISC-V spawning the corresponding function body as an async task. @@ -124,11 +125,7 @@ pub fn main_cortex_m(args: TokenStream, item: TokenStream) -> TokenStream { /// ``` #[proc_macro_attribute] pub fn main_riscv(args: TokenStream, item: TokenStream) -> TokenStream { - let args = syn::parse_macro_input!(args as Args); - let f = syn::parse_macro_input!(item as syn::ItemFn); - main::run(&args.meta, f, main::riscv(&args.meta)) - .unwrap_or_else(|x| x) - .into() + main::run(args.into(), item.into(), &main::ARCH_RISCV).into() } /// Creates a new `executor` instance and declares an application entry point for STD spawning the corresponding function body as an async task. @@ -151,9 +148,7 @@ pub fn main_riscv(args: TokenStream, item: TokenStream) -> TokenStream { /// ``` #[proc_macro_attribute] pub fn main_std(args: TokenStream, item: TokenStream) -> TokenStream { - let args = syn::parse_macro_input!(args as Args); - let f = syn::parse_macro_input!(item as syn::ItemFn); - main::run(&args.meta, f, main::std()).unwrap_or_else(|x| x).into() + main::run(args.into(), item.into(), &main::ARCH_STD).into() } /// Creates a new `executor` instance and declares an application entry point for WASM spawning the corresponding function body as an async task. @@ -176,7 +171,5 @@ pub fn main_std(args: TokenStream, item: TokenStream) -> TokenStream { /// ``` #[proc_macro_attribute] pub fn main_wasm(args: TokenStream, item: TokenStream) -> TokenStream { - let args = syn::parse_macro_input!(args as Args); - let f = syn::parse_macro_input!(item as syn::ItemFn); - main::run(&args.meta, f, main::wasm()).unwrap_or_else(|x| x).into() + main::run(args.into(), item.into(), &main::ARCH_WASM).into() } diff --git a/embassy-executor-macros/src/macros/main.rs b/embassy-executor-macros/src/macros/main.rs index 088e64d1c..14b1d9de2 100644 --- a/embassy-executor-macros/src/macros/main.rs +++ b/embassy-executor-macros/src/macros/main.rs @@ -1,125 +1,107 @@ +use std::str::FromStr; + use darling::export::NestedMeta; use darling::FromMeta; use proc_macro2::TokenStream; use quote::quote; -use syn::{Expr, ReturnType, Type}; +use syn::{ReturnType, Type}; -use crate::util::ctxt::Ctxt; +use crate::util::*; -#[derive(Debug, FromMeta)] +enum Flavor { + Standard, + Wasm, +} + +pub(crate) struct Arch { + default_entry: Option<&'static str>, + flavor: Flavor, +} + +pub static ARCH_AVR: Arch = Arch { + default_entry: Some("avr_device::entry"), + flavor: Flavor::Standard, +}; + +pub static ARCH_RISCV: Arch = Arch { + default_entry: Some("riscv_rt::entry"), + flavor: Flavor::Standard, +}; + +pub static ARCH_CORTEX_M: Arch = Arch { + default_entry: Some("cortex_m_rt::entry"), + flavor: Flavor::Standard, +}; + +pub static ARCH_SPIN: Arch = Arch { + default_entry: None, + flavor: Flavor::Standard, +}; + +pub static ARCH_STD: Arch = Arch { + default_entry: None, + flavor: Flavor::Standard, +}; + +pub static ARCH_WASM: Arch = Arch { + default_entry: Some("wasm_bindgen::prelude::wasm_bindgen(start)"), + flavor: Flavor::Wasm, +}; + +#[derive(Debug, FromMeta, Default)] struct Args { #[darling(default)] entry: Option, } -pub fn avr() -> TokenStream { - quote! { - #[avr_device::entry] - fn main() -> ! { - let mut executor = ::embassy_executor::Executor::new(); - let executor = unsafe { __make_static(&mut executor) }; +pub fn run(args: TokenStream, item: TokenStream, arch: &Arch) -> TokenStream { + let mut errors = TokenStream::new(); - executor.run(|spawner| { - spawner.must_spawn(__embassy_main(spawner)); - }) - } - } -} - -pub fn riscv(args: &[NestedMeta]) -> TokenStream { - let maybe_entry = match Args::from_list(args) { - Ok(args) => args.entry, - Err(e) => return e.write_errors(), + // If any of the steps for this macro fail, we still want to expand to an item that is as close + // to the expected output as possible. This helps out IDEs such that completions and other + // related features keep working. + let f: ItemFn = match syn::parse2(item.clone()) { + Ok(x) => x, + Err(e) => return token_stream_with_error(item, e), }; - let entry = maybe_entry.unwrap_or("riscv_rt::entry".into()); - let entry = match Expr::from_string(&entry) { - Ok(expr) => expr, - Err(e) => return e.write_errors(), + let args = match NestedMeta::parse_meta_list(args) { + Ok(x) => x, + Err(e) => return token_stream_with_error(item, e), }; - quote! { - #[#entry] - fn main() -> ! { - let mut executor = ::embassy_executor::Executor::new(); - let executor = unsafe { __make_static(&mut executor) }; - executor.run(|spawner| { - spawner.must_spawn(__embassy_main(spawner)); - }) + let args = match Args::from_list(&args) { + Ok(x) => x, + Err(e) => { + errors.extend(e.write_errors()); + Args::default() } - } -} - -pub fn cortex_m() -> TokenStream { - quote! { - #[cortex_m_rt::entry] - fn main() -> ! { - let mut executor = ::embassy_executor::Executor::new(); - let executor = unsafe { __make_static(&mut executor) }; - executor.run(|spawner| { - spawner.must_spawn(__embassy_main(spawner)); - }) - } - } -} - -pub fn wasm() -> TokenStream { - quote! { - #[wasm_bindgen::prelude::wasm_bindgen(start)] - pub fn main() -> Result<(), wasm_bindgen::JsValue> { - let executor = ::std::boxed::Box::leak(::std::boxed::Box::new(::embassy_executor::Executor::new())); - - executor.start(|spawner| { - spawner.spawn(__embassy_main(spawner)).unwrap(); - }); - - Ok(()) - } - } -} - -pub fn std() -> TokenStream { - quote! { - fn main() -> ! { - let mut executor = ::embassy_executor::Executor::new(); - let executor = unsafe { __make_static(&mut executor) }; - - executor.run(|spawner| { - spawner.must_spawn(__embassy_main(spawner)); - }) - } - } -} - -pub fn run(args: &[NestedMeta], f: syn::ItemFn, main: TokenStream) -> Result { - #[allow(unused_variables)] - let args = Args::from_list(args).map_err(|e| e.write_errors())?; + }; let fargs = f.sig.inputs.clone(); - let ctxt = Ctxt::new(); - if f.sig.asyncness.is_none() { - ctxt.error_spanned_by(&f.sig, "main function must be async"); + error(&mut errors, &f.sig, "main function must be async"); } if !f.sig.generics.params.is_empty() { - ctxt.error_spanned_by(&f.sig, "main function must not be generic"); + error(&mut errors, &f.sig, "main function must not be generic"); } if !f.sig.generics.where_clause.is_none() { - ctxt.error_spanned_by(&f.sig, "main function must not have `where` clauses"); + error(&mut errors, &f.sig, "main function must not have `where` clauses"); } if !f.sig.abi.is_none() { - ctxt.error_spanned_by(&f.sig, "main function must not have an ABI qualifier"); + error(&mut errors, &f.sig, "main function must not have an ABI qualifier"); } if !f.sig.variadic.is_none() { - ctxt.error_spanned_by(&f.sig, "main function must not be variadic"); + error(&mut errors, &f.sig, "main function must not be variadic"); } match &f.sig.output { ReturnType::Default => {} ReturnType::Type(_, ty) => match &**ty { Type::Tuple(tuple) if tuple.elems.is_empty() => {} Type::Never(_) => {} - _ => ctxt.error_spanned_by( + _ => error( + &mut errors, &f.sig, "main function must either not return a value, return `()` or return `!`", ), @@ -127,26 +109,69 @@ pub fn run(args: &[NestedMeta], f: syn::ItemFn, main: TokenStream) -> Result TokenStream::new(), + Some(x) => match TokenStream::from_str(x) { + Ok(x) => quote!(#[#x]), + Err(e) => { + error(&mut errors, &f.sig, e); + TokenStream::new() + } + }, + }; - let f_body = f.block; + let f_body = f.body; let out = &f.sig.output; + let (main_ret, mut main_body) = match arch.flavor { + Flavor::Standard => ( + quote!(!), + quote! { + unsafe fn __make_static(t: &mut T) -> &'static mut T { + ::core::mem::transmute(t) + } + + let mut executor = ::embassy_executor::Executor::new(); + let executor = unsafe { __make_static(&mut executor) }; + executor.run(|spawner| { + spawner.must_spawn(__embassy_main(spawner)); + }) + }, + ), + Flavor::Wasm => ( + quote!(Result<(), wasm_bindgen::JsValue>), + quote! { + let executor = ::std::boxed::Box::leak(::std::boxed::Box::new(::embassy_executor::Executor::new())); + + executor.start(|spawner| { + spawner.must_spawn(__embassy_main(spawner)); + }); + + Ok(()) + }, + ), + }; + + if !errors.is_empty() { + main_body = quote! {loop{}}; + } + let result = quote! { #[::embassy_executor::task()] async fn __embassy_main(#fargs) #out { #f_body } - unsafe fn __make_static(t: &mut T) -> &'static mut T { - ::core::mem::transmute(t) + #entry + fn main() -> #main_ret { + #main_body } - #main + #errors }; - Ok(result) + result } diff --git a/embassy-executor-macros/src/macros/task.rs b/embassy-executor-macros/src/macros/task.rs index 1efb2788b..e8134c6a9 100644 --- a/embassy-executor-macros/src/macros/task.rs +++ b/embassy-executor-macros/src/macros/task.rs @@ -1,48 +1,78 @@ +use std::str::FromStr; + use darling::export::NestedMeta; use darling::FromMeta; use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; -use syn::{parse_quote, Expr, ExprLit, ItemFn, Lit, LitInt, ReturnType, Type}; +use syn::visit::{self, Visit}; +use syn::{Expr, ExprLit, Lit, LitInt, ReturnType, Type}; -use crate::util::ctxt::Ctxt; +use crate::util::*; -#[derive(Debug, FromMeta)] +#[derive(Debug, FromMeta, Default)] struct Args { #[darling(default)] pool_size: Option, + /// Use this to override the `embassy_executor` crate path. Defaults to `::embassy_executor`. + #[darling(default)] + embassy_executor: Option, } -pub fn run(args: &[NestedMeta], f: syn::ItemFn) -> Result { - let args = Args::from_list(args).map_err(|e| e.write_errors())?; +pub fn run(args: TokenStream, item: TokenStream) -> TokenStream { + let mut errors = TokenStream::new(); + + // If any of the steps for this macro fail, we still want to expand to an item that is as close + // to the expected output as possible. This helps out IDEs such that completions and other + // related features keep working. + let f: ItemFn = match syn::parse2(item.clone()) { + Ok(x) => x, + Err(e) => return token_stream_with_error(item, e), + }; + + let args = match NestedMeta::parse_meta_list(args) { + Ok(x) => x, + Err(e) => return token_stream_with_error(item, e), + }; + + let args = match Args::from_list(&args) { + Ok(x) => x, + Err(e) => { + errors.extend(e.write_errors()); + Args::default() + } + }; let pool_size = args.pool_size.unwrap_or(Expr::Lit(ExprLit { attrs: vec![], lit: Lit::Int(LitInt::new("1", Span::call_site())), })); - let ctxt = Ctxt::new(); + let embassy_executor = args + .embassy_executor + .unwrap_or(Expr::Verbatim(TokenStream::from_str("::embassy_executor").unwrap())); if f.sig.asyncness.is_none() { - ctxt.error_spanned_by(&f.sig, "task functions must be async"); + error(&mut errors, &f.sig, "task functions must be async"); } if !f.sig.generics.params.is_empty() { - ctxt.error_spanned_by(&f.sig, "task functions must not be generic"); + error(&mut errors, &f.sig, "task functions must not be generic"); } if !f.sig.generics.where_clause.is_none() { - ctxt.error_spanned_by(&f.sig, "task functions must not have `where` clauses"); + error(&mut errors, &f.sig, "task functions must not have `where` clauses"); } if !f.sig.abi.is_none() { - ctxt.error_spanned_by(&f.sig, "task functions must not have an ABI qualifier"); + error(&mut errors, &f.sig, "task functions must not have an ABI qualifier"); } if !f.sig.variadic.is_none() { - ctxt.error_spanned_by(&f.sig, "task functions must not be variadic"); + error(&mut errors, &f.sig, "task functions must not be variadic"); } match &f.sig.output { ReturnType::Default => {} ReturnType::Type(_, ty) => match &**ty { Type::Tuple(tuple) if tuple.elems.is_empty() => {} Type::Never(_) => {} - _ => ctxt.error_spanned_by( + _ => error( + &mut errors, &f.sig, "task functions must either not return a value, return `()` or return `!`", ), @@ -55,26 +85,31 @@ pub fn run(args: &[NestedMeta], f: syn::ItemFn) -> Result { - ctxt.error_spanned_by(arg, "task functions must not have receiver arguments"); + error(&mut errors, arg, "task functions must not have `self` arguments"); } - syn::FnArg::Typed(t) => match t.pat.as_mut() { - syn::Pat::Ident(id) => { - id.mutability = None; - args.push((id.clone(), t.attrs.clone())); + syn::FnArg::Typed(t) => { + check_arg_ty(&mut errors, &t.ty); + match t.pat.as_mut() { + syn::Pat::Ident(id) => { + id.mutability = None; + args.push((id.clone(), t.attrs.clone())); + } + _ => { + error( + &mut errors, + arg, + "pattern matching in task arguments is not yet supported", + ); + } } - _ => { - ctxt.error_spanned_by(arg, "pattern matching in task arguments is not yet supported"); - } - }, + } } } - ctxt.check()?; - let task_ident = f.sig.ident.clone(); let task_inner_ident = format_ident!("__{}_task", task_ident); - let mut task_inner = f; + let mut task_inner = f.clone(); let visibility = task_inner.vis.clone(); task_inner.vis = syn::Visibility::Inherited; task_inner.sig.ident = task_inner_ident.clone(); @@ -91,24 +126,43 @@ pub fn run(args: &[NestedMeta], f: syn::ItemFn) -> Result ::embassy_executor::SpawnToken { - type Fut = impl ::core::future::Future + 'static; - const POOL_SIZE: usize = #pool_size; - static POOL: ::embassy_executor::raw::TaskPool = ::embassy_executor::raw::TaskPool::new(); - unsafe { POOL._spawn_async_fn(move || #task_inner_ident(#(#full_args,)*)) } + let mut task_outer_body = quote! { + trait _EmbassyInternalTaskTrait { + type Fut: ::core::future::Future + 'static; + fn construct(#fargs) -> Self::Fut; } + + impl _EmbassyInternalTaskTrait for () { + type Fut = impl core::future::Future + 'static; + fn construct(#fargs) -> Self::Fut { + #task_inner_ident(#(#full_args,)*) + } + } + + const POOL_SIZE: usize = #pool_size; + static POOL: #embassy_executor::raw::TaskPool<<() as _EmbassyInternalTaskTrait>::Fut, POOL_SIZE> = #embassy_executor::raw::TaskPool::new(); + unsafe { POOL._spawn_async_fn(move || <() as _EmbassyInternalTaskTrait>::construct(#(#full_args,)*)) } }; #[cfg(not(feature = "nightly"))] - let mut task_outer: ItemFn = parse_quote! { - #visibility fn #task_ident(#fargs) -> ::embassy_executor::SpawnToken { - const POOL_SIZE: usize = #pool_size; - static POOL: ::embassy_executor::_export::TaskPoolRef = ::embassy_executor::_export::TaskPoolRef::new(); - unsafe { POOL.get::<_, POOL_SIZE>()._spawn_async_fn(move || #task_inner_ident(#(#full_args,)*)) } - } + let mut task_outer_body = quote! { + const POOL_SIZE: usize = #pool_size; + static POOL: #embassy_executor::_export::TaskPoolRef = #embassy_executor::_export::TaskPoolRef::new(); + unsafe { POOL.get::<_, POOL_SIZE>()._spawn_async_fn(move || #task_inner_ident(#(#full_args,)*)) } }; - task_outer.attrs.append(&mut task_inner.attrs.clone()); + let task_outer_attrs = task_inner.attrs.clone(); + + if !errors.is_empty() { + task_outer_body = quote! { + #![allow(unused_variables, unreachable_code)] + let _x: #embassy_executor::SpawnToken<()> = ::core::todo!(); + _x + }; + } + + // Copy the generics + where clause to avoid more spurious errors. + let generics = &f.sig.generics; + let where_clause = &f.sig.generics.where_clause; let result = quote! { // This is the user's task function, renamed. @@ -118,8 +172,49 @@ pub fn run(args: &[NestedMeta], f: syn::ItemFn) -> Result #embassy_executor::SpawnToken #where_clause{ + #task_outer_body + } + + #errors }; - Ok(result) + result +} + +fn check_arg_ty(errors: &mut TokenStream, ty: &Type) { + struct Visitor<'a> { + errors: &'a mut TokenStream, + } + + impl<'a, 'ast> Visit<'ast> for Visitor<'a> { + fn visit_type_reference(&mut self, i: &'ast syn::TypeReference) { + // only check for elided lifetime here. If not elided, it's checked by `visit_lifetime`. + if i.lifetime.is_none() { + error( + self.errors, + i.and_token, + "Arguments for tasks must live forever. Try using the `'static` lifetime.", + ) + } + visit::visit_type_reference(self, i); + } + + fn visit_lifetime(&mut self, i: &'ast syn::Lifetime) { + if i.ident.to_string() != "static" { + error( + self.errors, + i, + "Arguments for tasks must live forever. Try using the `'static` lifetime.", + ) + } + } + + fn visit_type_impl_trait(&mut self, i: &'ast syn::TypeImplTrait) { + error(self.errors, i, "`impl Trait` is not allowed in task arguments. It is syntax sugar for generics, and tasks can't be generic."); + } + } + + Visit::visit_type(&mut Visitor { errors }, ty); } diff --git a/embassy-executor-macros/src/util.rs b/embassy-executor-macros/src/util.rs new file mode 100644 index 000000000..ebd032a62 --- /dev/null +++ b/embassy-executor-macros/src/util.rs @@ -0,0 +1,74 @@ +use std::fmt::Display; + +use proc_macro2::{TokenStream, TokenTree}; +use quote::{ToTokens, TokenStreamExt}; +use syn::parse::{Parse, ParseStream}; +use syn::{braced, bracketed, token, AttrStyle, Attribute, Signature, Token, Visibility}; + +pub fn token_stream_with_error(mut tokens: TokenStream, error: syn::Error) -> TokenStream { + tokens.extend(error.into_compile_error()); + tokens +} + +pub fn error(s: &mut TokenStream, obj: A, msg: T) { + s.extend(syn::Error::new_spanned(obj.into_token_stream(), msg).into_compile_error()) +} + +/// Function signature and body. +/// +/// Same as `syn`'s `ItemFn` except we keep the body as a TokenStream instead of +/// parsing it. This makes the macro not error if there's a syntax error in the body, +/// which helps IDE autocomplete work better. +#[derive(Debug, Clone)] +pub struct ItemFn { + pub attrs: Vec, + pub vis: Visibility, + pub sig: Signature, + pub brace_token: token::Brace, + pub body: TokenStream, +} + +impl Parse for ItemFn { + fn parse(input: ParseStream) -> syn::Result { + let mut attrs = input.call(Attribute::parse_outer)?; + let vis: Visibility = input.parse()?; + let sig: Signature = input.parse()?; + + let content; + let brace_token = braced!(content in input); + while content.peek(Token![#]) && content.peek2(Token![!]) { + let content2; + attrs.push(Attribute { + pound_token: content.parse()?, + style: AttrStyle::Inner(content.parse()?), + bracket_token: bracketed!(content2 in content), + meta: content2.parse()?, + }); + } + + let mut body = Vec::new(); + while !content.is_empty() { + body.push(content.parse::()?); + } + let body = body.into_iter().collect(); + + Ok(ItemFn { + attrs, + vis, + sig, + brace_token, + body, + }) + } +} + +impl ToTokens for ItemFn { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append_all(self.attrs.iter().filter(|a| matches!(a.style, AttrStyle::Outer))); + self.vis.to_tokens(tokens); + self.sig.to_tokens(tokens); + self.brace_token.surround(tokens, |tokens| { + tokens.append_all(self.body.clone()); + }); + } +} diff --git a/embassy-executor-macros/src/util/ctxt.rs b/embassy-executor-macros/src/util/ctxt.rs deleted file mode 100644 index 74c872c3c..000000000 --- a/embassy-executor-macros/src/util/ctxt.rs +++ /dev/null @@ -1,73 +0,0 @@ -// nifty utility borrowed from serde :) -// https://github.com/serde-rs/serde/blob/master/serde_derive/src/internals/ctxt.rs - -use std::cell::RefCell; -use std::fmt::Display; -use std::thread; - -use proc_macro2::TokenStream; -use quote::{quote, ToTokens}; -use syn; - -/// A type to collect errors together and format them. -/// -/// Dropping this object will cause a panic. It must be consumed using `check`. -/// -/// References can be shared since this type uses run-time exclusive mut checking. -#[derive(Default)] -pub struct Ctxt { - // The contents will be set to `None` during checking. This is so that checking can be - // enforced. - errors: RefCell>>, -} - -impl Ctxt { - /// Create a new context object. - /// - /// This object contains no errors, but will still trigger a panic if it is not `check`ed. - pub fn new() -> Self { - Ctxt { - errors: RefCell::new(Some(Vec::new())), - } - } - - /// Add an error to the context object with a tokenenizable object. - /// - /// The object is used for spanning in error messages. - pub fn error_spanned_by(&self, obj: A, msg: T) { - self.errors - .borrow_mut() - .as_mut() - .unwrap() - // Curb monomorphization from generating too many identical methods. - .push(syn::Error::new_spanned(obj.into_token_stream(), msg)); - } - - /// Add one of Syn's parse errors. - #[allow(unused)] - pub fn syn_error(&self, err: syn::Error) { - self.errors.borrow_mut().as_mut().unwrap().push(err); - } - - /// Consume this object, producing a formatted error string if there are errors. - pub fn check(self) -> Result<(), TokenStream> { - let errors = self.errors.borrow_mut().take().unwrap(); - match errors.len() { - 0 => Ok(()), - _ => Err(to_compile_errors(errors)), - } - } -} - -fn to_compile_errors(errors: Vec) -> proc_macro2::TokenStream { - let compile_errors = errors.iter().map(syn::Error::to_compile_error); - quote!(#(#compile_errors)*) -} - -impl Drop for Ctxt { - fn drop(&mut self) { - if !thread::panicking() && self.errors.borrow().is_some() { - panic!("forgot to check for errors"); - } - } -} diff --git a/embassy-executor-macros/src/util/mod.rs b/embassy-executor-macros/src/util/mod.rs deleted file mode 100644 index 28702809e..000000000 --- a/embassy-executor-macros/src/util/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod ctxt; diff --git a/embassy-executor/CHANGELOG.md b/embassy-executor/CHANGELOG.md index 77c64fd8e..b342ccc32 100644 --- a/embassy-executor/CHANGELOG.md +++ b/embassy-executor/CHANGELOG.md @@ -7,6 +7,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased +## 0.6.2 - 2024-11-06 + +- The `nightly` feature no longer requires `nightly-2024-09-06` or newer. + +## 0.6.1 - 2024-10-21 + +- Soundness fix: Deny using `impl Trait` in task arguments. This was previously accidentally allowed when not using the `nightly` feature, + and could cause out of bounds memory accesses if spawning the same task mulitple times with different underlying types + for the `impl Trait`. Affected versions are 0.4.x, 0.5.0 and 0.6.0, which have been yanked. +- Add an architecture-agnostic executor that spins waiting for tasks to run, enabled with the `arch-spin` feature. +- Update for breaking change in the nightly waker_getters API. The `nightly` feature now requires `nightly-2024-09-06` or newer. +- Improve macro error messages. + +## 0.6.0 - 2024-08-05 + +- Add collapse_debuginfo to fmt.rs macros. +- initial support for AVR +- use nightly waker_getters APIs + +## 0.5.1 - 2024-10-21 + +- Soundness fix: Deny using `impl Trait` in task arguments. This was previously accidentally allowed when not using the `nightly` feature, + and could cause out of bounds memory accesses if spawning the same task mulitple times with different underlying types + for the `impl Trait`. Affected versions are 0.4.x, 0.5.0 and 0.6.0, which have been yanked. + ## 0.5.0 - 2024-01-11 - Updated to `embassy-time-driver 0.1`, `embassy-time-queue-driver 0.1`, compatible with `embassy-time v0.3` and higher. diff --git a/embassy-executor/Cargo.toml b/embassy-executor/Cargo.toml index 409df0d75..7141fe0f9 100644 --- a/embassy-executor/Cargo.toml +++ b/embassy-executor/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "embassy-executor" -version = "0.5.0" +version = "0.6.2" edition = "2021" license = "MIT OR Apache-2.0" description = "async/await executor designed for embedded usage" @@ -33,15 +33,14 @@ defmt = { version = "0.3", optional = true } log = { version = "0.4.14", optional = true } rtos-trace = { version = "0.1.2", optional = true } -embassy-executor-macros = { version = "0.4.0", path = "../embassy-executor-macros" } +embassy-executor-macros = { version = "0.6.2", path = "../embassy-executor-macros" } embassy-time-driver = { version = "0.1.0", path = "../embassy-time-driver", optional = true } embassy-time-queue-driver = { version = "0.1.0", path = "../embassy-time-queue-driver", optional = true } critical-section = "1.1" document-features = "0.2.7" -# needed for riscv and avr -# remove when https://github.com/rust-lang/rust/pull/114499 lands on stable (on 1.76) +# needed for AVR portable-atomic = { version = "1.5", optional = true } # arch-cortex-m dependencies @@ -56,7 +55,7 @@ avr-device = { version = "0.5.3", optional = true } [dev-dependencies] critical-section = { version = "1.1", features = ["std"] } - +trybuild = "1.0" [features] @@ -78,11 +77,13 @@ arch-std = ["_arch", "critical-section/std"] ## Cortex-M arch-cortex-m = ["_arch", "dep:cortex-m"] ## RISC-V 32 -arch-riscv32 = ["_arch", "dep:portable-atomic"] +arch-riscv32 = ["_arch"] ## WASM -arch-wasm = ["_arch", "dep:wasm-bindgen", "dep:js-sys"] +arch-wasm = ["_arch", "dep:wasm-bindgen", "dep:js-sys", "critical-section/std"] ## AVR arch-avr = ["_arch", "dep:portable-atomic", "dep:avr-device"] +## spin (architecture agnostic; never sleeps) +arch-spin = ["_arch"] #! ### Executor diff --git a/embassy-executor/build.rs b/embassy-executor/build.rs index 07f31e3fb..8a41d7503 100644 --- a/embassy-executor/build.rs +++ b/embassy-executor/build.rs @@ -3,6 +3,9 @@ use std::fmt::Write; use std::path::PathBuf; use std::{env, fs}; +#[path = "./build_common.rs"] +mod common; + static CONFIGS: &[(&str, usize)] = &[ // BEGIN AUTOGENERATED CONFIG FEATURES // Generated by gen_config.py. DO NOT EDIT. @@ -91,30 +94,6 @@ fn main() { let out_file = out_dir.join("config.rs").to_string_lossy().to_string(); fs::write(out_file, data).unwrap(); - // cortex-m targets - let target = env::var("TARGET").unwrap(); - - if target.starts_with("thumbv6m-") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv6m"); - } else if target.starts_with("thumbv7m-") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv7m"); - } else if target.starts_with("thumbv7em-") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv7m"); - println!("cargo:rustc-cfg=armv7em"); // (not currently used) - } else if target.starts_with("thumbv8m.base") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv8m"); - println!("cargo:rustc-cfg=armv8m_base"); - } else if target.starts_with("thumbv8m.main") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv8m"); - println!("cargo:rustc-cfg=armv8m_main"); - } - - if target.ends_with("-eabihf") { - println!("cargo:rustc-cfg=has_fpu"); - } + let mut rustc_cfgs = common::CfgSet::new(); + common::set_target_cfgs(&mut rustc_cfgs); } diff --git a/embassy-executor/build_common.rs b/embassy-executor/build_common.rs new file mode 100644 index 000000000..b15a8369f --- /dev/null +++ b/embassy-executor/build_common.rs @@ -0,0 +1,126 @@ +// NOTE: this file is copy-pasted between several Embassy crates, because there is no +// straightforward way to share this code: +// - it cannot be placed into the root of the repo and linked from each build.rs using `#[path = +// "../build_common.rs"]`, because `cargo publish` requires that all files published with a crate +// reside in the crate's directory, +// - it cannot be symlinked from `embassy-xxx/build_common.rs` to `../build_common.rs`, because +// symlinks don't work on Windows. + +use std::collections::HashSet; +use std::env; + +/// Helper for emitting cargo instruction for enabling configs (`cargo:rustc-cfg=X`) and declaring +/// them (`cargo:rust-check-cfg=cfg(X)`). +#[derive(Debug)] +pub struct CfgSet { + enabled: HashSet, + declared: HashSet, +} + +impl CfgSet { + pub fn new() -> Self { + Self { + enabled: HashSet::new(), + declared: HashSet::new(), + } + } + + /// Enable a config, which can then be used in `#[cfg(...)]` for conditional compilation. + /// + /// All configs that can potentially be enabled should be unconditionally declared using + /// [`Self::declare()`]. + pub fn enable(&mut self, cfg: impl AsRef) { + if self.enabled.insert(cfg.as_ref().to_owned()) { + println!("cargo:rustc-cfg={}", cfg.as_ref()); + } + } + + pub fn enable_all(&mut self, cfgs: &[impl AsRef]) { + for cfg in cfgs.iter() { + self.enable(cfg.as_ref()); + } + } + + /// Declare a valid config for conditional compilation, without enabling it. + /// + /// This enables rustc to check that the configs in `#[cfg(...)]` attributes are valid. + pub fn declare(&mut self, cfg: impl AsRef) { + if self.declared.insert(cfg.as_ref().to_owned()) { + println!("cargo:rustc-check-cfg=cfg({})", cfg.as_ref()); + } + } + + pub fn declare_all(&mut self, cfgs: &[impl AsRef]) { + for cfg in cfgs.iter() { + self.declare(cfg.as_ref()); + } + } + + pub fn set(&mut self, cfg: impl Into, enable: bool) { + let cfg = cfg.into(); + if enable { + self.enable(cfg.clone()); + } + self.declare(cfg); + } +} + +/// Sets configs that describe the target platform. +pub fn set_target_cfgs(cfgs: &mut CfgSet) { + let target = env::var("TARGET").unwrap(); + + if target.starts_with("thumbv6m-") { + cfgs.enable_all(&["cortex_m", "armv6m"]); + } else if target.starts_with("thumbv7m-") { + cfgs.enable_all(&["cortex_m", "armv7m"]); + } else if target.starts_with("thumbv7em-") { + cfgs.enable_all(&["cortex_m", "armv7m", "armv7em"]); + } else if target.starts_with("thumbv8m.base") { + cfgs.enable_all(&["cortex_m", "armv8m", "armv8m_base"]); + } else if target.starts_with("thumbv8m.main") { + cfgs.enable_all(&["cortex_m", "armv8m", "armv8m_main"]); + } + cfgs.declare_all(&[ + "cortex_m", + "armv6m", + "armv7m", + "armv7em", + "armv8m", + "armv8m_base", + "armv8m_main", + ]); + + cfgs.set("has_fpu", target.ends_with("-eabihf")); +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub struct CompilerDate { + year: u16, + month: u8, + day: u8, +} + +impl CompilerDate { + fn parse(date: &str) -> Option { + let mut parts = date.split('-'); + let year = parts.next()?.parse().ok()?; + let month = parts.next()?.parse().ok()?; + let day = parts.next()?.parse().ok()?; + Some(Self { year, month, day }) + } +} + +impl PartialEq<&str> for CompilerDate { + fn eq(&self, other: &&str) -> bool { + let Some(other) = Self::parse(other) else { + return false; + }; + self.eq(&other) + } +} + +impl PartialOrd<&str> for CompilerDate { + fn partial_cmp(&self, other: &&str) -> Option { + Self::parse(other).map(|other| self.cmp(&other)) + } +} diff --git a/embassy-executor/src/arch/riscv32.rs b/embassy-executor/src/arch/riscv32.rs index c56f502d3..01e63a9fd 100644 --- a/embassy-executor/src/arch/riscv32.rs +++ b/embassy-executor/src/arch/riscv32.rs @@ -6,9 +6,9 @@ pub use thread::*; #[cfg(feature = "executor-thread")] mod thread { use core::marker::PhantomData; + use core::sync::atomic::{AtomicBool, Ordering}; pub use embassy_executor_macros::main_riscv as main; - use portable_atomic::{AtomicBool, Ordering}; use crate::{raw, Spawner}; diff --git a/embassy-executor/src/arch/spin.rs b/embassy-executor/src/arch/spin.rs new file mode 100644 index 000000000..340023620 --- /dev/null +++ b/embassy-executor/src/arch/spin.rs @@ -0,0 +1,58 @@ +#[cfg(feature = "executor-interrupt")] +compile_error!("`executor-interrupt` is not supported with `arch-spin`."); + +#[cfg(feature = "executor-thread")] +pub use thread::*; +#[cfg(feature = "executor-thread")] +mod thread { + use core::marker::PhantomData; + + pub use embassy_executor_macros::main_spin as main; + + use crate::{raw, Spawner}; + + #[export_name = "__pender"] + fn __pender(_context: *mut ()) {} + + /// Spin Executor + pub struct Executor { + inner: raw::Executor, + not_send: PhantomData<*mut ()>, + } + + impl Executor { + /// Create a new Executor. + pub fn new() -> Self { + Self { + inner: raw::Executor::new(core::ptr::null_mut()), + not_send: PhantomData, + } + } + + /// Run the executor. + /// + /// The `init` closure is called with a [`Spawner`] that spawns tasks on + /// this executor. Use it to spawn the initial task(s). After `init` returns, + /// the executor starts running the tasks. + /// + /// To spawn more tasks later, you may keep copies of the [`Spawner`] (it is `Copy`), + /// for example by passing it as an argument to the initial tasks. + /// + /// This function requires `&'static mut self`. This means you have to store the + /// Executor instance in a place where it'll live forever and grants you mutable + /// access. There's a few ways to do this: + /// + /// - a [StaticCell](https://docs.rs/static_cell/latest/static_cell/) (safe) + /// - a `static mut` (unsafe) + /// - a local variable in a function you know never returns (like `fn main() -> !`), upgrading its lifetime with `transmute`. (unsafe) + /// + /// This function never returns. + pub fn run(&'static mut self, init: impl FnOnce(Spawner)) -> ! { + init(self.inner.spawner()); + + loop { + unsafe { self.inner.poll() }; + } + } + } +} diff --git a/embassy-executor/src/fmt.rs b/embassy-executor/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-executor/src/fmt.rs +++ b/embassy-executor/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-executor/src/lib.rs b/embassy-executor/src/lib.rs index 6a2e493a2..d816539ac 100644 --- a/embassy-executor/src/lib.rs +++ b/embassy-executor/src/lib.rs @@ -23,7 +23,14 @@ macro_rules! check_at_most_one { check_at_most_one!(@amo [$($f)*] [$($f)*] []); }; } -check_at_most_one!("arch-avr", "arch-cortex-m", "arch-riscv32", "arch-std", "arch-wasm",); +check_at_most_one!( + "arch-avr", + "arch-cortex-m", + "arch-riscv32", + "arch-std", + "arch-wasm", + "arch-spin", +); #[cfg(feature = "_arch")] #[cfg_attr(feature = "arch-avr", path = "arch/avr.rs")] @@ -31,6 +38,7 @@ check_at_most_one!("arch-avr", "arch-cortex-m", "arch-riscv32", "arch-std", "arc #[cfg_attr(feature = "arch-riscv32", path = "arch/riscv32.rs")] #[cfg_attr(feature = "arch-std", path = "arch/std.rs")] #[cfg_attr(feature = "arch-wasm", path = "arch/wasm.rs")] +#[cfg_attr(feature = "arch-spin", path = "arch/spin.rs")] mod arch; #[cfg(feature = "_arch")] diff --git a/embassy-executor/src/raw/mod.rs b/embassy-executor/src/raw/mod.rs index 3f00be4a8..d9ea5c005 100644 --- a/embassy-executor/src/raw/mod.rs +++ b/embassy-executor/src/raw/mod.rs @@ -30,7 +30,7 @@ use core::ptr::NonNull; use core::task::{Context, Poll}; #[cfg(feature = "integrated-timers")] -use embassy_time_driver::{self, AlarmHandle}; +use embassy_time_driver::AlarmHandle; #[cfg(feature = "rtos-trace")] use rtos_trace::trace; @@ -581,6 +581,15 @@ impl embassy_time_queue_driver::TimerQueue for TimerQueue { #[cfg(feature = "integrated-timers")] embassy_time_queue_driver::timer_queue_impl!(static TIMER_QUEUE: TimerQueue = TimerQueue); +#[cfg(all(feature = "rtos-trace", feature = "integrated-timers"))] +const fn gcd(a: u64, b: u64) -> u64 { + if b == 0 { + a + } else { + gcd(b, a % b) + } +} + #[cfg(feature = "rtos-trace")] impl rtos_trace::RtosTraceOSCallbacks for Executor { fn task_list() { @@ -588,7 +597,8 @@ impl rtos_trace::RtosTraceOSCallbacks for Executor { } #[cfg(feature = "integrated-timers")] fn time() -> u64 { - Instant::now().as_micros() + const GCD_1M: u64 = gcd(embassy_time_driver::TICK_HZ, 1_000_000); + embassy_time_driver::now() * (1_000_000 / GCD_1M) / (embassy_time_driver::TICK_HZ / GCD_1M) } #[cfg(not(feature = "integrated-timers"))] fn time() -> u64 { diff --git a/embassy-executor/src/raw/waker.rs b/embassy-executor/src/raw/waker.rs index 522853e34..9c70f995a 100644 --- a/embassy-executor/src/raw/waker.rs +++ b/embassy-executor/src/raw/waker.rs @@ -1,4 +1,3 @@ -use core::mem; use core::task::{RawWaker, RawWakerVTable, Waker}; use super::{wake_task, TaskHeader, TaskRef}; @@ -33,20 +32,22 @@ pub(crate) unsafe fn from_task(p: TaskRef) -> Waker { /// /// Panics if the waker is not created by the Embassy executor. pub fn task_from_waker(waker: &Waker) -> TaskRef { + struct WakerHack { + data: *const (), + vtable: &'static RawWakerVTable, + } + // safety: OK because WakerHack has the same layout as Waker. // This is not really guaranteed because the structs are `repr(Rust)`, it is // indeed the case in the current implementation. // TODO use waker_getters when stable. https://github.com/rust-lang/rust/issues/96992 - let hack: &WakerHack = unsafe { mem::transmute(waker) }; - if hack.vtable != &VTABLE { + let hack: &WakerHack = unsafe { core::mem::transmute(waker) }; + + // make sure to compare vtable addresses. Doing `==` on the references + // will compare the contents, which is slower. + if hack.vtable as *const _ != &VTABLE as *const _ { panic!("Found waker not created by the Embassy executor. `embassy_time::Timer` only works with the Embassy executor.") } - // safety: our wakers are always created with `TaskRef::as_ptr` unsafe { TaskRef::from_ptr(hack.data as *const TaskHeader) } } - -struct WakerHack { - data: *const (), - vtable: &'static RawWakerVTable, -} diff --git a/embassy-executor/tests/test.rs b/embassy-executor/tests/test.rs index 2c2441dd5..348cc7dc4 100644 --- a/embassy-executor/tests/test.rs +++ b/embassy-executor/tests/test.rs @@ -1,4 +1,4 @@ -#![cfg_attr(feature = "nightly", feature(type_alias_impl_trait))] +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] use std::boxed::Box; use std::future::poll_fn; diff --git a/embassy-executor/tests/ui.rs b/embassy-executor/tests/ui.rs new file mode 100644 index 000000000..be4679485 --- /dev/null +++ b/embassy-executor/tests/ui.rs @@ -0,0 +1,23 @@ +#[cfg(not(miri))] +#[test] +fn ui() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/ui/abi.rs"); + t.compile_fail("tests/ui/bad_return.rs"); + t.compile_fail("tests/ui/generics.rs"); + t.compile_fail("tests/ui/impl_trait_nested.rs"); + t.compile_fail("tests/ui/impl_trait.rs"); + t.compile_fail("tests/ui/impl_trait_static.rs"); + t.compile_fail("tests/ui/nonstatic_ref_anon_nested.rs"); + t.compile_fail("tests/ui/nonstatic_ref_anon.rs"); + t.compile_fail("tests/ui/nonstatic_ref_elided.rs"); + t.compile_fail("tests/ui/nonstatic_ref_generic.rs"); + t.compile_fail("tests/ui/nonstatic_struct_anon.rs"); + #[cfg(not(feature = "nightly"))] // we can't catch this case with the macro, so the output changes on nightly. + t.compile_fail("tests/ui/nonstatic_struct_elided.rs"); + t.compile_fail("tests/ui/nonstatic_struct_generic.rs"); + t.compile_fail("tests/ui/not_async.rs"); + t.compile_fail("tests/ui/self_ref.rs"); + t.compile_fail("tests/ui/self.rs"); + t.compile_fail("tests/ui/where_clause.rs"); +} diff --git a/embassy-executor/tests/ui/abi.rs b/embassy-executor/tests/ui/abi.rs new file mode 100644 index 000000000..fd52f7e41 --- /dev/null +++ b/embassy-executor/tests/ui/abi.rs @@ -0,0 +1,8 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +struct Foo<'a>(&'a ()); + +#[embassy_executor::task] +async extern "C" fn task() {} + +fn main() {} diff --git a/embassy-executor/tests/ui/abi.stderr b/embassy-executor/tests/ui/abi.stderr new file mode 100644 index 000000000..e264e371a --- /dev/null +++ b/embassy-executor/tests/ui/abi.stderr @@ -0,0 +1,5 @@ +error: task functions must not have an ABI qualifier + --> tests/ui/abi.rs:6:1 + | +6 | async extern "C" fn task() {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/embassy-executor/tests/ui/bad_return.rs b/embassy-executor/tests/ui/bad_return.rs new file mode 100644 index 000000000..f09a5205b --- /dev/null +++ b/embassy-executor/tests/ui/bad_return.rs @@ -0,0 +1,10 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +struct Foo<'a>(&'a ()); + +#[embassy_executor::task] +async fn task() -> u32 { + 5 +} + +fn main() {} diff --git a/embassy-executor/tests/ui/bad_return.stderr b/embassy-executor/tests/ui/bad_return.stderr new file mode 100644 index 000000000..e9d94dff8 --- /dev/null +++ b/embassy-executor/tests/ui/bad_return.stderr @@ -0,0 +1,5 @@ +error: task functions must either not return a value, return `()` or return `!` + --> tests/ui/bad_return.rs:6:1 + | +6 | async fn task() -> u32 { + | ^^^^^^^^^^^^^^^^^^^^^^ diff --git a/embassy-executor/tests/ui/generics.rs b/embassy-executor/tests/ui/generics.rs new file mode 100644 index 000000000..b83123bb1 --- /dev/null +++ b/embassy-executor/tests/ui/generics.rs @@ -0,0 +1,8 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +struct Foo<'a>(&'a ()); + +#[embassy_executor::task] +async fn task(_t: T) {} + +fn main() {} diff --git a/embassy-executor/tests/ui/generics.stderr b/embassy-executor/tests/ui/generics.stderr new file mode 100644 index 000000000..197719a7b --- /dev/null +++ b/embassy-executor/tests/ui/generics.stderr @@ -0,0 +1,5 @@ +error: task functions must not be generic + --> tests/ui/generics.rs:6:1 + | +6 | async fn task(_t: T) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/embassy-executor/tests/ui/impl_trait.rs b/embassy-executor/tests/ui/impl_trait.rs new file mode 100644 index 000000000..a21402aa0 --- /dev/null +++ b/embassy-executor/tests/ui/impl_trait.rs @@ -0,0 +1,6 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +#[embassy_executor::task] +async fn foo(_x: impl Sized) {} + +fn main() {} diff --git a/embassy-executor/tests/ui/impl_trait.stderr b/embassy-executor/tests/ui/impl_trait.stderr new file mode 100644 index 000000000..099b1828f --- /dev/null +++ b/embassy-executor/tests/ui/impl_trait.stderr @@ -0,0 +1,5 @@ +error: `impl Trait` is not allowed in task arguments. It is syntax sugar for generics, and tasks can't be generic. + --> tests/ui/impl_trait.rs:4:18 + | +4 | async fn foo(_x: impl Sized) {} + | ^^^^^^^^^^ diff --git a/embassy-executor/tests/ui/impl_trait_nested.rs b/embassy-executor/tests/ui/impl_trait_nested.rs new file mode 100644 index 000000000..07442b8fa --- /dev/null +++ b/embassy-executor/tests/ui/impl_trait_nested.rs @@ -0,0 +1,8 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +struct Foo(T); + +#[embassy_executor::task] +async fn foo(_x: Foo) {} + +fn main() {} diff --git a/embassy-executor/tests/ui/impl_trait_nested.stderr b/embassy-executor/tests/ui/impl_trait_nested.stderr new file mode 100644 index 000000000..39592f958 --- /dev/null +++ b/embassy-executor/tests/ui/impl_trait_nested.stderr @@ -0,0 +1,5 @@ +error: `impl Trait` is not allowed in task arguments. It is syntax sugar for generics, and tasks can't be generic. + --> tests/ui/impl_trait_nested.rs:6:22 + | +6 | async fn foo(_x: Foo) {} + | ^^^^^^^^^^^^^^^^^^^^ diff --git a/embassy-executor/tests/ui/impl_trait_static.rs b/embassy-executor/tests/ui/impl_trait_static.rs new file mode 100644 index 000000000..272470f98 --- /dev/null +++ b/embassy-executor/tests/ui/impl_trait_static.rs @@ -0,0 +1,6 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +#[embassy_executor::task] +async fn foo(_x: impl Sized + 'static) {} + +fn main() {} diff --git a/embassy-executor/tests/ui/impl_trait_static.stderr b/embassy-executor/tests/ui/impl_trait_static.stderr new file mode 100644 index 000000000..0032a20c9 --- /dev/null +++ b/embassy-executor/tests/ui/impl_trait_static.stderr @@ -0,0 +1,5 @@ +error: `impl Trait` is not allowed in task arguments. It is syntax sugar for generics, and tasks can't be generic. + --> tests/ui/impl_trait_static.rs:4:18 + | +4 | async fn foo(_x: impl Sized + 'static) {} + | ^^^^^^^^^^^^^^^^^^^^ diff --git a/embassy-executor/tests/ui/nonstatic_ref_anon.rs b/embassy-executor/tests/ui/nonstatic_ref_anon.rs new file mode 100644 index 000000000..417c360a1 --- /dev/null +++ b/embassy-executor/tests/ui/nonstatic_ref_anon.rs @@ -0,0 +1,6 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +#[embassy_executor::task] +async fn foo(_x: &'_ u32) {} + +fn main() {} diff --git a/embassy-executor/tests/ui/nonstatic_ref_anon.stderr b/embassy-executor/tests/ui/nonstatic_ref_anon.stderr new file mode 100644 index 000000000..0544de843 --- /dev/null +++ b/embassy-executor/tests/ui/nonstatic_ref_anon.stderr @@ -0,0 +1,5 @@ +error: Arguments for tasks must live forever. Try using the `'static` lifetime. + --> tests/ui/nonstatic_ref_anon.rs:4:19 + | +4 | async fn foo(_x: &'_ u32) {} + | ^^ diff --git a/embassy-executor/tests/ui/nonstatic_ref_anon_nested.rs b/embassy-executor/tests/ui/nonstatic_ref_anon_nested.rs new file mode 100644 index 000000000..175ebccc1 --- /dev/null +++ b/embassy-executor/tests/ui/nonstatic_ref_anon_nested.rs @@ -0,0 +1,6 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +#[embassy_executor::task] +async fn foo(_x: &'static &'_ u32) {} + +fn main() {} diff --git a/embassy-executor/tests/ui/nonstatic_ref_anon_nested.stderr b/embassy-executor/tests/ui/nonstatic_ref_anon_nested.stderr new file mode 100644 index 000000000..79f262e6b --- /dev/null +++ b/embassy-executor/tests/ui/nonstatic_ref_anon_nested.stderr @@ -0,0 +1,5 @@ +error: Arguments for tasks must live forever. Try using the `'static` lifetime. + --> tests/ui/nonstatic_ref_anon_nested.rs:4:28 + | +4 | async fn foo(_x: &'static &'_ u32) {} + | ^^ diff --git a/embassy-executor/tests/ui/nonstatic_ref_elided.rs b/embassy-executor/tests/ui/nonstatic_ref_elided.rs new file mode 100644 index 000000000..cf49ad709 --- /dev/null +++ b/embassy-executor/tests/ui/nonstatic_ref_elided.rs @@ -0,0 +1,6 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +#[embassy_executor::task] +async fn foo(_x: &u32) {} + +fn main() {} diff --git a/embassy-executor/tests/ui/nonstatic_ref_elided.stderr b/embassy-executor/tests/ui/nonstatic_ref_elided.stderr new file mode 100644 index 000000000..7e2b9eb7c --- /dev/null +++ b/embassy-executor/tests/ui/nonstatic_ref_elided.stderr @@ -0,0 +1,5 @@ +error: Arguments for tasks must live forever. Try using the `'static` lifetime. + --> tests/ui/nonstatic_ref_elided.rs:4:18 + | +4 | async fn foo(_x: &u32) {} + | ^ diff --git a/embassy-executor/tests/ui/nonstatic_ref_generic.rs b/embassy-executor/tests/ui/nonstatic_ref_generic.rs new file mode 100644 index 000000000..3f8a26cf8 --- /dev/null +++ b/embassy-executor/tests/ui/nonstatic_ref_generic.rs @@ -0,0 +1,6 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +#[embassy_executor::task] +async fn foo<'a>(_x: &'a u32) {} + +fn main() {} diff --git a/embassy-executor/tests/ui/nonstatic_ref_generic.stderr b/embassy-executor/tests/ui/nonstatic_ref_generic.stderr new file mode 100644 index 000000000..af8491ad7 --- /dev/null +++ b/embassy-executor/tests/ui/nonstatic_ref_generic.stderr @@ -0,0 +1,11 @@ +error: task functions must not be generic + --> tests/ui/nonstatic_ref_generic.rs:4:1 + | +4 | async fn foo<'a>(_x: &'a u32) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: Arguments for tasks must live forever. Try using the `'static` lifetime. + --> tests/ui/nonstatic_ref_generic.rs:4:23 + | +4 | async fn foo<'a>(_x: &'a u32) {} + | ^^ diff --git a/embassy-executor/tests/ui/nonstatic_struct_anon.rs b/embassy-executor/tests/ui/nonstatic_struct_anon.rs new file mode 100644 index 000000000..ba95d1459 --- /dev/null +++ b/embassy-executor/tests/ui/nonstatic_struct_anon.rs @@ -0,0 +1,8 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +struct Foo<'a>(&'a ()); + +#[embassy_executor::task] +async fn task(_x: Foo<'_>) {} + +fn main() {} diff --git a/embassy-executor/tests/ui/nonstatic_struct_anon.stderr b/embassy-executor/tests/ui/nonstatic_struct_anon.stderr new file mode 100644 index 000000000..5df2a6e06 --- /dev/null +++ b/embassy-executor/tests/ui/nonstatic_struct_anon.stderr @@ -0,0 +1,5 @@ +error: Arguments for tasks must live forever. Try using the `'static` lifetime. + --> tests/ui/nonstatic_struct_anon.rs:6:23 + | +6 | async fn task(_x: Foo<'_>) {} + | ^^ diff --git a/embassy-executor/tests/ui/nonstatic_struct_elided.rs b/embassy-executor/tests/ui/nonstatic_struct_elided.rs new file mode 100644 index 000000000..4cfe2966a --- /dev/null +++ b/embassy-executor/tests/ui/nonstatic_struct_elided.rs @@ -0,0 +1,8 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +struct Foo<'a>(&'a ()); + +#[embassy_executor::task] +async fn task(_x: Foo) {} + +fn main() {} diff --git a/embassy-executor/tests/ui/nonstatic_struct_elided.stderr b/embassy-executor/tests/ui/nonstatic_struct_elided.stderr new file mode 100644 index 000000000..099ef8b4e --- /dev/null +++ b/embassy-executor/tests/ui/nonstatic_struct_elided.stderr @@ -0,0 +1,10 @@ +error[E0726]: implicit elided lifetime not allowed here + --> tests/ui/nonstatic_struct_elided.rs:6:19 + | +6 | async fn task(_x: Foo) {} + | ^^^ expected lifetime parameter + | +help: indicate the anonymous lifetime + | +6 | async fn task(_x: Foo<'_>) {} + | ++++ diff --git a/embassy-executor/tests/ui/nonstatic_struct_generic.rs b/embassy-executor/tests/ui/nonstatic_struct_generic.rs new file mode 100644 index 000000000..ec3d908f6 --- /dev/null +++ b/embassy-executor/tests/ui/nonstatic_struct_generic.rs @@ -0,0 +1,8 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +struct Foo<'a>(&'a ()); + +#[embassy_executor::task] +async fn task<'a>(_x: Foo<'a>) {} + +fn main() {} diff --git a/embassy-executor/tests/ui/nonstatic_struct_generic.stderr b/embassy-executor/tests/ui/nonstatic_struct_generic.stderr new file mode 100644 index 000000000..61d5231bc --- /dev/null +++ b/embassy-executor/tests/ui/nonstatic_struct_generic.stderr @@ -0,0 +1,11 @@ +error: task functions must not be generic + --> tests/ui/nonstatic_struct_generic.rs:6:1 + | +6 | async fn task<'a>(_x: Foo<'a>) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: Arguments for tasks must live forever. Try using the `'static` lifetime. + --> tests/ui/nonstatic_struct_generic.rs:6:27 + | +6 | async fn task<'a>(_x: Foo<'a>) {} + | ^^ diff --git a/embassy-executor/tests/ui/not_async.rs b/embassy-executor/tests/ui/not_async.rs new file mode 100644 index 000000000..f3f7e9bd2 --- /dev/null +++ b/embassy-executor/tests/ui/not_async.rs @@ -0,0 +1,8 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +struct Foo<'a>(&'a ()); + +#[embassy_executor::task] +fn task() {} + +fn main() {} diff --git a/embassy-executor/tests/ui/not_async.stderr b/embassy-executor/tests/ui/not_async.stderr new file mode 100644 index 000000000..27f040d9c --- /dev/null +++ b/embassy-executor/tests/ui/not_async.stderr @@ -0,0 +1,5 @@ +error: task functions must be async + --> tests/ui/not_async.rs:6:1 + | +6 | fn task() {} + | ^^^^^^^^^ diff --git a/embassy-executor/tests/ui/self.rs b/embassy-executor/tests/ui/self.rs new file mode 100644 index 000000000..f83a962d1 --- /dev/null +++ b/embassy-executor/tests/ui/self.rs @@ -0,0 +1,8 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +struct Foo<'a>(&'a ()); + +#[embassy_executor::task] +async fn task(self) {} + +fn main() {} diff --git a/embassy-executor/tests/ui/self.stderr b/embassy-executor/tests/ui/self.stderr new file mode 100644 index 000000000..aaf031573 --- /dev/null +++ b/embassy-executor/tests/ui/self.stderr @@ -0,0 +1,13 @@ +error: task functions must not have `self` arguments + --> tests/ui/self.rs:6:15 + | +6 | async fn task(self) {} + | ^^^^ + +error: `self` parameter is only allowed in associated functions + --> tests/ui/self.rs:6:15 + | +6 | async fn task(self) {} + | ^^^^ not semantically valid as function parameter + | + = note: associated functions are those in `impl` or `trait` definitions diff --git a/embassy-executor/tests/ui/self_ref.rs b/embassy-executor/tests/ui/self_ref.rs new file mode 100644 index 000000000..5e49bba5e --- /dev/null +++ b/embassy-executor/tests/ui/self_ref.rs @@ -0,0 +1,8 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +struct Foo<'a>(&'a ()); + +#[embassy_executor::task] +async fn task(&mut self) {} + +fn main() {} diff --git a/embassy-executor/tests/ui/self_ref.stderr b/embassy-executor/tests/ui/self_ref.stderr new file mode 100644 index 000000000..dd2052977 --- /dev/null +++ b/embassy-executor/tests/ui/self_ref.stderr @@ -0,0 +1,13 @@ +error: task functions must not have `self` arguments + --> tests/ui/self_ref.rs:6:15 + | +6 | async fn task(&mut self) {} + | ^^^^^^^^^ + +error: `self` parameter is only allowed in associated functions + --> tests/ui/self_ref.rs:6:15 + | +6 | async fn task(&mut self) {} + | ^^^^^^^^^ not semantically valid as function parameter + | + = note: associated functions are those in `impl` or `trait` definitions diff --git a/embassy-executor/tests/ui/where_clause.rs b/embassy-executor/tests/ui/where_clause.rs new file mode 100644 index 000000000..848d78149 --- /dev/null +++ b/embassy-executor/tests/ui/where_clause.rs @@ -0,0 +1,12 @@ +#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))] + +struct Foo<'a>(&'a ()); + +#[embassy_executor::task] +async fn task() +where + (): Sized, +{ +} + +fn main() {} diff --git a/embassy-executor/tests/ui/where_clause.stderr b/embassy-executor/tests/ui/where_clause.stderr new file mode 100644 index 000000000..eba45af40 --- /dev/null +++ b/embassy-executor/tests/ui/where_clause.stderr @@ -0,0 +1,7 @@ +error: task functions must not have `where` clauses + --> tests/ui/where_clause.rs:6:1 + | +6 | / async fn task() +7 | | where +8 | | (): Sized, + | |______________^ diff --git a/embassy-futures/src/fmt.rs b/embassy-futures/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-futures/src/fmt.rs +++ b/embassy-futures/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-futures/src/select.rs b/embassy-futures/src/select.rs index 97a81a86d..bb175253b 100644 --- a/embassy-futures/src/select.rs +++ b/embassy-futures/src/select.rs @@ -188,6 +188,169 @@ where // ==================================================================== +/// Result for [`select5`]. +#[derive(Debug, Clone)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Either5 { + /// First future finished first. + First(A), + /// Second future finished first. + Second(B), + /// Third future finished first. + Third(C), + /// Fourth future finished first. + Fourth(D), + /// Fifth future finished first. + Fifth(E), +} + +/// Same as [`select`], but with more futures. +pub fn select5(a: A, b: B, c: C, d: D, e: E) -> Select5 +where + A: Future, + B: Future, + C: Future, + D: Future, + E: Future, +{ + Select5 { a, b, c, d, e } +} + +/// Future for the [`select5`] function. +#[derive(Debug)] +#[must_use = "futures do nothing unless you `.await` or poll them"] +pub struct Select5 { + a: A, + b: B, + c: C, + d: D, + e: E, +} + +impl Future for Select5 +where + A: Future, + B: Future, + C: Future, + D: Future, + E: Future, +{ + type Output = Either5; + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let this = unsafe { self.get_unchecked_mut() }; + let a = unsafe { Pin::new_unchecked(&mut this.a) }; + let b = unsafe { Pin::new_unchecked(&mut this.b) }; + let c = unsafe { Pin::new_unchecked(&mut this.c) }; + let d = unsafe { Pin::new_unchecked(&mut this.d) }; + let e = unsafe { Pin::new_unchecked(&mut this.e) }; + if let Poll::Ready(x) = a.poll(cx) { + return Poll::Ready(Either5::First(x)); + } + if let Poll::Ready(x) = b.poll(cx) { + return Poll::Ready(Either5::Second(x)); + } + if let Poll::Ready(x) = c.poll(cx) { + return Poll::Ready(Either5::Third(x)); + } + if let Poll::Ready(x) = d.poll(cx) { + return Poll::Ready(Either5::Fourth(x)); + } + if let Poll::Ready(x) = e.poll(cx) { + return Poll::Ready(Either5::Fifth(x)); + } + Poll::Pending + } +} + +// ==================================================================== + +/// Result for [`select6`]. +#[derive(Debug, Clone)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Either6 { + /// First future finished first. + First(A), + /// Second future finished first. + Second(B), + /// Third future finished first. + Third(C), + /// Fourth future finished first. + Fourth(D), + /// Fifth future finished first. + Fifth(E), + /// Sixth future finished first. + Sixth(F), +} + +/// Same as [`select`], but with more futures. +pub fn select6(a: A, b: B, c: C, d: D, e: E, f: F) -> Select6 +where + A: Future, + B: Future, + C: Future, + D: Future, + E: Future, + F: Future, +{ + Select6 { a, b, c, d, e, f } +} + +/// Future for the [`select6`] function. +#[derive(Debug)] +#[must_use = "futures do nothing unless you `.await` or poll them"] +pub struct Select6 { + a: A, + b: B, + c: C, + d: D, + e: E, + f: F, +} + +impl Future for Select6 +where + A: Future, + B: Future, + C: Future, + D: Future, + E: Future, + F: Future, +{ + type Output = Either6; + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let this = unsafe { self.get_unchecked_mut() }; + let a = unsafe { Pin::new_unchecked(&mut this.a) }; + let b = unsafe { Pin::new_unchecked(&mut this.b) }; + let c = unsafe { Pin::new_unchecked(&mut this.c) }; + let d = unsafe { Pin::new_unchecked(&mut this.d) }; + let e = unsafe { Pin::new_unchecked(&mut this.e) }; + let f = unsafe { Pin::new_unchecked(&mut this.f) }; + if let Poll::Ready(x) = a.poll(cx) { + return Poll::Ready(Either6::First(x)); + } + if let Poll::Ready(x) = b.poll(cx) { + return Poll::Ready(Either6::Second(x)); + } + if let Poll::Ready(x) = c.poll(cx) { + return Poll::Ready(Either6::Third(x)); + } + if let Poll::Ready(x) = d.poll(cx) { + return Poll::Ready(Either6::Fourth(x)); + } + if let Poll::Ready(x) = e.poll(cx) { + return Poll::Ready(Either6::Fifth(x)); + } + if let Poll::Ready(x) = f.poll(cx) { + return Poll::Ready(Either6::Sixth(x)); + } + Poll::Pending + } +} + +// ==================================================================== + /// Future for the [`select_array`] function. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] @@ -237,7 +400,7 @@ impl Future for SelectArray { #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct SelectSlice<'a, Fut> { - inner: &'a mut [Fut], + inner: Pin<&'a mut [Fut]>, } /// Creates a new future which will select over a slice of futures. @@ -247,31 +410,26 @@ pub struct SelectSlice<'a, Fut> { /// future that was ready. /// /// If the slice is empty, the resulting future will be Pending forever. -pub fn select_slice<'a, Fut: Future>(slice: &'a mut [Fut]) -> SelectSlice<'a, Fut> { +pub fn select_slice<'a, Fut: Future>(slice: Pin<&'a mut [Fut]>) -> SelectSlice<'a, Fut> { SelectSlice { inner: slice } } impl<'a, Fut: Future> Future for SelectSlice<'a, Fut> { type Output = (Fut::Output, usize); - fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - // Safety: Since `self` is pinned, `inner` cannot move. Since `inner` cannot move, - // its elements also cannot move. Therefore it is safe to access `inner` and pin - // references to the contained futures. - let item = unsafe { - self.get_unchecked_mut() - .inner - .iter_mut() - .enumerate() - .find_map(|(i, f)| match Pin::new_unchecked(f).poll(cx) { - Poll::Pending => None, - Poll::Ready(e) => Some((i, e)), - }) - }; - - match item { - Some((idx, res)) => Poll::Ready((res, idx)), - None => Poll::Pending, + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + // Safety: refer to + // https://users.rust-lang.org/t/working-with-pinned-slices-are-there-any-structurally-pinning-vec-like-collection-types/50634/2 + #[inline(always)] + fn pin_iter(slice: Pin<&mut [T]>) -> impl Iterator> { + unsafe { slice.get_unchecked_mut().iter_mut().map(|v| Pin::new_unchecked(v)) } } + for (i, fut) in pin_iter(self.inner.as_mut()).enumerate() { + if let Poll::Ready(res) = fut.poll(cx) { + return Poll::Ready((res, i)); + } + } + + Poll::Pending } } diff --git a/embassy-futures/src/yield_now.rs b/embassy-futures/src/yield_now.rs index bb3c67d17..4d4e535f2 100644 --- a/embassy-futures/src/yield_now.rs +++ b/embassy-futures/src/yield_now.rs @@ -9,10 +9,16 @@ use core::task::{Context, Poll}; /// hold, while still allowing other tasks to run concurrently (not monopolizing /// the executor thread). /// -/// ```rust,no_run +/// ```rust +/// # use embassy_futures::{block_on, yield_now}; +/// # async fn test_fn() { +/// # let mut iter_count: u32 = 0; +/// # let mut some_condition = || { iter_count += 1; iter_count > 10 }; /// while !some_condition() { /// yield_now().await; /// } +/// # } +/// # block_on(test_fn()); /// ``` /// /// The downside is this will spin in a busy loop, using 100% of the CPU, while diff --git a/embassy-hal-internal/Cargo.toml b/embassy-hal-internal/Cargo.toml index c5013f365..d5ca95ac2 100644 --- a/embassy-hal-internal/Cargo.toml +++ b/embassy-hal-internal/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "embassy-hal-internal" -version = "0.1.0" +version = "0.2.0" edition = "2021" license = "MIT OR Apache-2.0" description = "Internal implementation details for Embassy HALs. DO NOT USE DIRECTLY." diff --git a/embassy-hal-internal/build.rs b/embassy-hal-internal/build.rs index 6fe82b44f..ecd2c0c9f 100644 --- a/embassy-hal-internal/build.rs +++ b/embassy-hal-internal/build.rs @@ -1,29 +1,7 @@ -use std::env; +#[path = "./build_common.rs"] +mod common; fn main() { - let target = env::var("TARGET").unwrap(); - - if target.starts_with("thumbv6m-") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv6m"); - } else if target.starts_with("thumbv7m-") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv7m"); - } else if target.starts_with("thumbv7em-") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv7m"); - println!("cargo:rustc-cfg=armv7em"); // (not currently used) - } else if target.starts_with("thumbv8m.base") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv8m"); - println!("cargo:rustc-cfg=armv8m_base"); - } else if target.starts_with("thumbv8m.main") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv8m"); - println!("cargo:rustc-cfg=armv8m_main"); - } - - if target.ends_with("-eabihf") { - println!("cargo:rustc-cfg=has_fpu"); - } + let mut cfgs = common::CfgSet::new(); + common::set_target_cfgs(&mut cfgs); } diff --git a/embassy-hal-internal/build_common.rs b/embassy-hal-internal/build_common.rs new file mode 100644 index 000000000..4f24e6d37 --- /dev/null +++ b/embassy-hal-internal/build_common.rs @@ -0,0 +1,94 @@ +// NOTE: this file is copy-pasted between several Embassy crates, because there is no +// straightforward way to share this code: +// - it cannot be placed into the root of the repo and linked from each build.rs using `#[path = +// "../build_common.rs"]`, because `cargo publish` requires that all files published with a crate +// reside in the crate's directory, +// - it cannot be symlinked from `embassy-xxx/build_common.rs` to `../build_common.rs`, because +// symlinks don't work on Windows. + +use std::collections::HashSet; +use std::env; + +/// Helper for emitting cargo instruction for enabling configs (`cargo:rustc-cfg=X`) and declaring +/// them (`cargo:rust-check-cfg=cfg(X)`). +#[derive(Debug)] +pub struct CfgSet { + enabled: HashSet, + declared: HashSet, +} + +impl CfgSet { + pub fn new() -> Self { + Self { + enabled: HashSet::new(), + declared: HashSet::new(), + } + } + + /// Enable a config, which can then be used in `#[cfg(...)]` for conditional compilation. + /// + /// All configs that can potentially be enabled should be unconditionally declared using + /// [`Self::declare()`]. + pub fn enable(&mut self, cfg: impl AsRef) { + if self.enabled.insert(cfg.as_ref().to_owned()) { + println!("cargo:rustc-cfg={}", cfg.as_ref()); + } + } + + pub fn enable_all(&mut self, cfgs: &[impl AsRef]) { + for cfg in cfgs.iter() { + self.enable(cfg.as_ref()); + } + } + + /// Declare a valid config for conditional compilation, without enabling it. + /// + /// This enables rustc to check that the configs in `#[cfg(...)]` attributes are valid. + pub fn declare(&mut self, cfg: impl AsRef) { + if self.declared.insert(cfg.as_ref().to_owned()) { + println!("cargo:rustc-check-cfg=cfg({})", cfg.as_ref()); + } + } + + pub fn declare_all(&mut self, cfgs: &[impl AsRef]) { + for cfg in cfgs.iter() { + self.declare(cfg.as_ref()); + } + } + + pub fn set(&mut self, cfg: impl Into, enable: bool) { + let cfg = cfg.into(); + if enable { + self.enable(cfg.clone()); + } + self.declare(cfg); + } +} + +/// Sets configs that describe the target platform. +pub fn set_target_cfgs(cfgs: &mut CfgSet) { + let target = env::var("TARGET").unwrap(); + + if target.starts_with("thumbv6m-") { + cfgs.enable_all(&["cortex_m", "armv6m"]); + } else if target.starts_with("thumbv7m-") { + cfgs.enable_all(&["cortex_m", "armv7m"]); + } else if target.starts_with("thumbv7em-") { + cfgs.enable_all(&["cortex_m", "armv7m", "armv7em"]); + } else if target.starts_with("thumbv8m.base") { + cfgs.enable_all(&["cortex_m", "armv8m", "armv8m_base"]); + } else if target.starts_with("thumbv8m.main") { + cfgs.enable_all(&["cortex_m", "armv8m", "armv8m_main"]); + } + cfgs.declare_all(&[ + "cortex_m", + "armv6m", + "armv7m", + "armv7em", + "armv8m", + "armv8m_base", + "armv8m_main", + ]); + + cfgs.set("has_fpu", target.ends_with("-eabihf")); +} diff --git a/embassy-hal-internal/src/atomic_ring_buffer.rs b/embassy-hal-internal/src/atomic_ring_buffer.rs index b4f2cec28..00b7a1249 100644 --- a/embassy-hal-internal/src/atomic_ring_buffer.rs +++ b/embassy-hal-internal/src/atomic_ring_buffer.rs @@ -1,6 +1,6 @@ //! Atomic reusable ringbuffer. -use core::slice; use core::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; +use core::{ptr, slice}; /// Atomic reusable ringbuffer /// @@ -73,6 +73,7 @@ impl RingBuffer { pub unsafe fn deinit(&self) { // Ordering: it's OK to use `Relaxed` because this is not called // concurrently with other methods. + self.buf.store(ptr::null_mut(), Ordering::Relaxed); self.len.store(0, Ordering::Relaxed); self.start.store(0, Ordering::Relaxed); self.end.store(0, Ordering::Relaxed); @@ -82,20 +83,51 @@ impl RingBuffer { /// /// # Safety /// - /// Only one reader can exist at a time. + /// - Only one reader can exist at a time. + /// - Ringbuffer must be initialized. pub unsafe fn reader(&self) -> Reader<'_> { Reader(self) } + /// Try creating a reader, fails if not initialized. + /// + /// # Safety + /// + /// Only one reader can exist at a time. + pub unsafe fn try_reader(&self) -> Option> { + if self.buf.load(Ordering::Relaxed).is_null() { + return None; + } + Some(Reader(self)) + } + /// Create a writer. /// /// # Safety /// - /// Only one writer can exist at a time. + /// - Only one writer can exist at a time. + /// - Ringbuffer must be initialized. pub unsafe fn writer(&self) -> Writer<'_> { Writer(self) } + /// Try creating a writer, fails if not initialized. + /// + /// # Safety + /// + /// Only one writer can exist at a time. + pub unsafe fn try_writer(&self) -> Option> { + if self.buf.load(Ordering::Relaxed).is_null() { + return None; + } + Some(Writer(self)) + } + + /// Return if buffer is available. + pub fn is_available(&self) -> bool { + !self.buf.load(Ordering::Relaxed).is_null() && self.len.load(Ordering::Relaxed) != 0 + } + /// Return length of buffer. pub fn len(&self) -> usize { self.len.load(Ordering::Relaxed) @@ -451,8 +483,12 @@ mod tests { #[test] fn zero_len() { + let mut b = [0; 0]; + let rb = RingBuffer::new(); unsafe { + rb.init(b.as_mut_ptr(), b.len()); + assert_eq!(rb.is_empty(), true); assert_eq!(rb.is_full(), true); diff --git a/embassy-hal-internal/src/fmt.rs b/embassy-hal-internal/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-hal-internal/src/fmt.rs +++ b/embassy-hal-internal/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-hal-internal/src/interrupt.rs b/embassy-hal-internal/src/interrupt.rs index 19dabcf6f..5e64dce9d 100644 --- a/embassy-hal-internal/src/interrupt.rs +++ b/embassy-hal-internal/src/interrupt.rs @@ -30,14 +30,12 @@ macro_rules! interrupt_mod { pub mod typelevel { use super::InterruptExt; - mod sealed { - pub trait Interrupt {} - } + trait SealedInterrupt {} /// Type-level interrupt. /// /// This trait is implemented for all typelevel interrupt types in this module. - pub trait Interrupt: sealed::Interrupt { + pub trait Interrupt: SealedInterrupt { /// Interrupt enum variant. /// @@ -105,7 +103,7 @@ macro_rules! interrupt_mod { #[doc=stringify!($irqs)] #[doc=" typelevel interrupt."] pub enum $irqs {} - impl sealed::Interrupt for $irqs{} + impl SealedInterrupt for $irqs{} impl Interrupt for $irqs { const IRQ: super::Interrupt = super::Interrupt::$irqs; } diff --git a/embassy-hal-internal/src/peripheral.rs b/embassy-hal-internal/src/peripheral.rs index 16d49edfb..0b0f13338 100644 --- a/embassy-hal-internal/src/peripheral.rs +++ b/embassy-hal-internal/src/peripheral.rs @@ -86,13 +86,6 @@ impl<'a, T> Deref for PeripheralRef<'a, T> { } } -impl<'a, T> DerefMut for PeripheralRef<'a, T> { - #[inline] - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.inner - } -} - /// Trait for any type that can be used as a peripheral of type `P`. /// /// This is used in driver constructors, to allow passing either owned peripherals (e.g. `TWISPI0`), @@ -170,6 +163,15 @@ where #[inline] unsafe fn clone_unchecked(&self) -> Self::P { - self.deref().clone_unchecked() + T::Target::clone_unchecked(self) + } +} + +impl<'b, T: Peripheral> Peripheral for PeripheralRef<'_, T> { + type P = T::P; + + #[inline] + unsafe fn clone_unchecked(&self) -> Self::P { + T::clone_unchecked(self) } } diff --git a/embassy-net-adin1110/Cargo.toml b/embassy-net-adin1110/Cargo.toml index 97579a467..0b2a6744d 100644 --- a/embassy-net-adin1110/Cargo.toml +++ b/embassy-net-adin1110/Cargo.toml @@ -16,8 +16,8 @@ log = { version = "0.4", default-features = false, optional = true } embedded-hal-1 = { package = "embedded-hal", version = "1.0" } embedded-hal-async = { version = "1.0" } embedded-hal-bus = { version = "0.1", features = ["async"] } -embassy-net-driver-channel = { version = "0.2.0", path = "../embassy-net-driver-channel" } -embassy-time = { version = "0.3.0", path = "../embassy-time" } +embassy-net-driver-channel = { version = "0.3.0", path = "../embassy-net-driver-channel" } +embassy-time = { version = "0.3.2", path = "../embassy-time" } embassy-futures = { version = "0.1.0", path = "../embassy-futures" } bitfield = "0.14.0" @@ -29,7 +29,6 @@ critical-section = { version = "1.1.2", features = ["std"] } futures-test = "0.3.28" [features] -default = [ ] defmt = [ "dep:defmt", "embedded-hal-1/defmt-03" ] log = ["dep:log"] diff --git a/embassy-net-adin1110/README.md b/embassy-net-adin1110/README.md index 39a38960d..0514274b4 100644 --- a/embassy-net-adin1110/README.md +++ b/embassy-net-adin1110/README.md @@ -21,7 +21,7 @@ APL can be used in [`intrinsic safety applications/explosion hazardous areas`](h ## Supported SPI modes -`ADIN1110` supports two SPI modes. `Generic` and [`OPEN Alliance 10BASE-T1x MAC-PHY serial interface`](https://opensig.org/download/document/OPEN_Alliance_10BASET1x_MAC-PHY_Serial_Interface_V1.1.pdf) +`ADIN1110` supports two SPI modes. `Generic` and [`OPEN Alliance 10BASE-T1x MAC-PHY serial interface`](https://opensig.org/wp-content/uploads/2023/12/OPEN_Alliance_10BASET1x_MAC-PHY_Serial_Interface_V1.1.pdf) Both modes support with and without additional CRC. Currently only `Generic` SPI with or without CRC is supported. diff --git a/embassy-net-adin1110/src/crc8.rs b/embassy-net-adin1110/src/crc8.rs index 7d20a7401..321983e64 100644 --- a/embassy-net-adin1110/src/crc8.rs +++ b/embassy-net-adin1110/src/crc8.rs @@ -16,7 +16,7 @@ const CRC8X_TABLE: [u8; 256] = [ 0xcb, 0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3, ]; -/// Calculate the crc of a pease of data. +/// Calculate the crc of a piece of data. pub fn crc8(data: &[u8]) -> u8 { data.iter().fold(0, |crc, &byte| CRC8X_TABLE[usize::from(byte ^ crc)]) } diff --git a/embassy-net-adin1110/src/fmt.rs b/embassy-net-adin1110/src/fmt.rs index 12737c690..8ca61bc39 100644 --- a/embassy-net-adin1110/src/fmt.rs +++ b/embassy-net-adin1110/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,6 +90,7 @@ macro_rules! todo { }; } +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { { @@ -94,6 +102,7 @@ macro_rules! unreachable { }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -105,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -113,11 +123,12 @@ macro_rules! trace { #[cfg(feature = "defmt")] ::defmt::trace!($s $(, $x)*); #[cfg(not(any(feature = "log", feature="defmt")))] - let _ignored = ($( & $x ),*); + let _ = ($( & $x ),*); } }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -126,11 +137,12 @@ macro_rules! debug { #[cfg(feature = "defmt")] ::defmt::debug!($s $(, $x)*); #[cfg(not(any(feature = "log", feature="defmt")))] - let _ignored = ($( & $x ),*); + let _ = ($( & $x ),*); } }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -139,11 +151,12 @@ macro_rules! info { #[cfg(feature = "defmt")] ::defmt::info!($s $(, $x)*); #[cfg(not(any(feature = "log", feature="defmt")))] - let _ignored = ($( & $x ),*); + let _ = ($( & $x ),*); } }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -152,11 +165,12 @@ macro_rules! warn { #[cfg(feature = "defmt")] ::defmt::warn!($s $(, $x)*); #[cfg(not(any(feature = "log", feature="defmt")))] - let _ignored = ($( & $x ),*); + let _ = ($( & $x ),*); } }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -165,12 +179,13 @@ macro_rules! error { #[cfg(feature = "defmt")] ::defmt::error!($s $(, $x)*); #[cfg(not(any(feature = "log", feature="defmt")))] - let _ignored = ($( & $x ),*); + let _ = ($( & $x ),*); } }; } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -178,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -226,7 +242,7 @@ impl Try for Result { } } -pub struct Bytes<'a>(pub &'a [u8]); +pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { diff --git a/embassy-net-adin1110/src/lib.rs b/embassy-net-adin1110/src/lib.rs index d98e98422..7f1c772e2 100644 --- a/embassy-net-adin1110/src/lib.rs +++ b/embassy-net-adin1110/src/lib.rs @@ -1,6 +1,6 @@ +#![cfg_attr(not(test), no_std)] #![deny(clippy::pedantic)] #![allow(async_fn_in_trait)] -#![cfg_attr(not(any(test, feature = "std")), no_std)] #![allow(clippy::module_name_repetitions)] #![allow(clippy::missing_errors_doc)] #![allow(clippy::missing_panics_doc)] diff --git a/embassy-net-driver-channel/CHANGELOG.md b/embassy-net-driver-channel/CHANGELOG.md index b04d0a86b..d7af7e55d 100644 --- a/embassy-net-driver-channel/CHANGELOG.md +++ b/embassy-net-driver-channel/CHANGELOG.md @@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + +## 0.3.0 - 2024-08-05 + +- Add collapse_debuginfo to fmt.rs macros. +- Update embassy-sync version + ## 0.2.0 - 2023-10-18 - Update `embassy-net-driver` to v0.2 diff --git a/embassy-net-driver-channel/Cargo.toml b/embassy-net-driver-channel/Cargo.toml index c1ad11482..abce9315b 100644 --- a/embassy-net-driver-channel/Cargo.toml +++ b/embassy-net-driver-channel/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "embassy-net-driver-channel" -version = "0.2.0" +version = "0.3.0" edition = "2021" license = "MIT OR Apache-2.0" description = "High-level channel-based driver for the `embassy-net` async TCP/IP network stack." @@ -25,6 +25,6 @@ features = ["defmt"] defmt = { version = "0.3", optional = true } log = { version = "0.4.14", optional = true } -embassy-sync = { version = "0.5.0", path = "../embassy-sync" } +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } embassy-futures = { version = "0.1.0", path = "../embassy-futures" } embassy-net-driver = { version = "0.2.0", path = "../embassy-net-driver" } diff --git a/embassy-net-driver-channel/src/fmt.rs b/embassy-net-driver-channel/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-net-driver-channel/src/fmt.rs +++ b/embassy-net-driver-channel/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-net-driver-channel/src/lib.rs b/embassy-net-driver-channel/src/lib.rs index 7ad4d449e..6390502a8 100644 --- a/embassy-net-driver-channel/src/lib.rs +++ b/embassy-net-driver-channel/src/lib.rs @@ -326,8 +326,14 @@ pub struct Device<'d, const MTU: usize> { } impl<'d, const MTU: usize> embassy_net_driver::Driver for Device<'d, MTU> { - type RxToken<'a> = RxToken<'a, MTU> where Self: 'a ; - type TxToken<'a> = TxToken<'a, MTU> where Self: 'a ; + type RxToken<'a> + = RxToken<'a, MTU> + where + Self: 'a; + type TxToken<'a> + = TxToken<'a, MTU> + where + Self: 'a; fn receive(&mut self, cx: &mut Context) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> { if self.rx.poll_receive(cx).is_ready() && self.tx.poll_send(cx).is_ready() { diff --git a/embassy-net-driver/src/lib.rs b/embassy-net-driver/src/lib.rs index 87f9f6ed1..4c847718d 100644 --- a/embassy-net-driver/src/lib.rs +++ b/embassy-net-driver/src/lib.rs @@ -83,10 +83,12 @@ pub trait Driver { } impl Driver for &mut T { - type RxToken<'a> = T::RxToken<'a> + type RxToken<'a> + = T::RxToken<'a> where Self: 'a; - type TxToken<'a> = T::TxToken<'a> + type TxToken<'a> + = T::TxToken<'a> where Self: 'a; diff --git a/embassy-net-enc28j60/Cargo.toml b/embassy-net-enc28j60/Cargo.toml index 23bd3da7e..cafced4b2 100644 --- a/embassy-net-enc28j60/Cargo.toml +++ b/embassy-net-enc28j60/Cargo.toml @@ -13,7 +13,7 @@ documentation = "https://docs.embassy.dev/embassy-net-enc28j60" embedded-hal = { version = "1.0" } embedded-hal-async = { version = "1.0" } embassy-net-driver = { version = "0.2.0", path = "../embassy-net-driver" } -embassy-time = { version = "0.3.0", path = "../embassy-time" } +embassy-time = { version = "0.3.2", path = "../embassy-time" } embassy-futures = { version = "0.1.0", path = "../embassy-futures" } defmt = { version = "0.3", optional = true } diff --git a/embassy-net-enc28j60/src/fmt.rs b/embassy-net-enc28j60/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-net-enc28j60/src/fmt.rs +++ b/embassy-net-enc28j60/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-net-enc28j60/src/lib.rs b/embassy-net-enc28j60/src/lib.rs index f18134927..c1f32719a 100644 --- a/embassy-net-enc28j60/src/lib.rs +++ b/embassy-net-enc28j60/src/lib.rs @@ -17,7 +17,6 @@ mod phy; mod traits; use core::cmp; -use core::convert::TryInto; use embassy_net_driver::{Capabilities, HardwareAddress, LinkState}; use embassy_time::Duration; @@ -636,17 +635,19 @@ where S: SpiDevice, O: OutputPin, { - type RxToken<'a> = RxToken<'a> + type RxToken<'a> + = RxToken<'a> where Self: 'a; - type TxToken<'a> = TxToken<'a, S, O> + type TxToken<'a> + = TxToken<'a, S, O> where Self: 'a; fn receive(&mut self, cx: &mut core::task::Context) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> { - let rx_buf = unsafe { &mut RX_BUF }; - let tx_buf = unsafe { &mut TX_BUF }; + let rx_buf = unsafe { &mut *core::ptr::addr_of_mut!(RX_BUF) }; + let tx_buf = unsafe { &mut *core::ptr::addr_of_mut!(TX_BUF) }; if let Some(n) = self.receive(rx_buf) { Some((RxToken { buf: &mut rx_buf[..n] }, TxToken { buf: tx_buf, eth: self })) } else { @@ -656,7 +657,7 @@ where } fn transmit(&mut self, _cx: &mut core::task::Context) -> Option> { - let tx_buf = unsafe { &mut TX_BUF }; + let tx_buf = unsafe { &mut *core::ptr::addr_of_mut!(TX_BUF) }; Some(TxToken { buf: tx_buf, eth: self }) } diff --git a/embassy-net-esp-hosted/Cargo.toml b/embassy-net-esp-hosted/Cargo.toml index dda65dbf9..915eba7a0 100644 --- a/embassy-net-esp-hosted/Cargo.toml +++ b/embassy-net-esp-hosted/Cargo.toml @@ -9,14 +9,18 @@ license = "MIT OR Apache-2.0" repository = "https://github.com/embassy-rs/embassy" documentation = "https://docs.embassy.dev/embassy-net-esp-hosted" +[features] +defmt = [ "dep:defmt", "heapless/defmt-03" ] +log = [ "dep:log" ] + [dependencies] defmt = { version = "0.3", optional = true } log = { version = "0.4.14", optional = true } -embassy-time = { version = "0.3.0", path = "../embassy-time" } -embassy-sync = { version = "0.5.0", path = "../embassy-sync"} +embassy-time = { version = "0.3.2", path = "../embassy-time" } +embassy-sync = { version = "0.6.0", path = "../embassy-sync"} embassy-futures = { version = "0.1.0", path = "../embassy-futures"} -embassy-net-driver-channel = { version = "0.2.0", path = "../embassy-net-driver-channel"} +embassy-net-driver-channel = { version = "0.3.0", path = "../embassy-net-driver-channel"} embedded-hal = { version = "1.0" } embedded-hal-async = { version = "1.0" } diff --git a/embassy-net-esp-hosted/src/control.rs b/embassy-net-esp-hosted/src/control.rs index c8cea8503..b1838a425 100644 --- a/embassy-net-esp-hosted/src/control.rs +++ b/embassy-net-esp-hosted/src/control.rs @@ -120,7 +120,7 @@ impl<'a> Control<'a> { pwd: unwrap!(String::try_from(password)), bssid: String::new(), listen_interval: 3, - is_wpa3_supported: false, + is_wpa3_supported: true, }; ioctl!(self, ReqConnectAp, RespConnectAp, req, resp); self.state_ch.set_link_state(LinkState::Up); diff --git a/embassy-net-esp-hosted/src/fmt.rs b/embassy-net-esp-hosted/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-net-esp-hosted/src/fmt.rs +++ b/embassy-net-esp-hosted/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-net-esp-hosted/src/lib.rs b/embassy-net-esp-hosted/src/lib.rs index c78578bf1..f05e2a70a 100644 --- a/embassy-net-esp-hosted/src/lib.rs +++ b/embassy-net-esp-hosted/src/lib.rs @@ -137,7 +137,7 @@ where let (ch_runner, device) = ch::new(&mut state.ch, ch::driver::HardwareAddress::Ethernet([0; 6])); let state_ch = ch_runner.state_runner(); - let mut runner = Runner { + let runner = Runner { ch: ch_runner, state_ch, shared: &state.shared, @@ -148,7 +148,6 @@ where spi, heartbeat_deadline: Instant::now() + HEARTBEAT_MAX_GAP, }; - runner.init().await; (device, Control::new(state_ch, &state.shared), runner) } @@ -174,8 +173,6 @@ where IN: InputPin + Wait, OUT: OutputPin, { - async fn init(&mut self) {} - /// Run the packet processing. pub async fn run(mut self) -> ! { debug!("resetting..."); diff --git a/embassy-net-esp-hosted/src/proto.rs b/embassy-net-esp-hosted/src/proto.rs index 034d5bf84..089ded677 100644 --- a/embassy-net-esp-hosted/src/proto.rs +++ b/embassy-net-esp-hosted/src/proto.rs @@ -1,3 +1,5 @@ +#![allow(unused)] + use heapless::{String, Vec}; /// internal supporting structures for CtrlMsg diff --git a/embassy-net-nrf91/Cargo.toml b/embassy-net-nrf91/Cargo.toml new file mode 100644 index 000000000..98356c1ba --- /dev/null +++ b/embassy-net-nrf91/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "embassy-net-nrf91" +version = "0.1.0" +edition = "2021" +description = "embassy-net driver for Nordic nRF91-series cellular modems" +keywords = ["embedded", "nrf91", "embassy-net", "cellular"] +categories = ["embedded", "hardware-support", "no-std", "network-programming", "asynchronous"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/embassy-rs/embassy" +documentation = "https://docs.embassy.dev/embassy-net-nrf91" + +[features] +defmt = [ "dep:defmt", "heapless/defmt-03" ] +log = [ "dep:log" ] + +[dependencies] +defmt = { version = "0.3", optional = true } +log = { version = "0.4.14", optional = true } + +nrf-pac = { git = "https://github.com/embassy-rs/nrf-pac", rev = "875a29629cc1c87aae00cfea647a956b3807d8be" } +cortex-m = "0.7.7" + +embassy-time = { version = "0.3.1", path = "../embassy-time" } +embassy-sync = { version = "0.6.0", path = "../embassy-sync"} +embassy-futures = { version = "0.1.0", path = "../embassy-futures"} +embassy-net-driver-channel = { version = "0.3.0", path = "../embassy-net-driver-channel"} + +heapless = "0.8" +embedded-io = "0.6.1" +at-commands = "0.5.4" + +[package.metadata.embassy_docs] +src_base = "https://github.com/embassy-rs/embassy/blob/embassy-net-nrf91-v$VERSION/embassy-net-nrf91/src/" +src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/embassy-net-nrf91/src/" +target = "thumbv7em-none-eabi" +features = ["defmt"] + +[package.metadata.docs.rs] +features = ["defmt"] diff --git a/embassy-net-nrf91/README.md b/embassy-net-nrf91/README.md new file mode 100644 index 000000000..30da71787 --- /dev/null +++ b/embassy-net-nrf91/README.md @@ -0,0 +1,9 @@ +# nRF91 `embassy-net` integration + +[`embassy-net`](https://crates.io/crates/embassy-net) driver for Nordic nRF91-series cellular modems. + +See the [`examples`](https://github.com/embassy-rs/embassy/tree/main/examples/nrf9160) directory for usage examples with the nRF9160. + +## Interoperability + +This crate can run on any executor. diff --git a/embassy-net-nrf91/src/context.rs b/embassy-net-nrf91/src/context.rs new file mode 100644 index 000000000..2dda615c1 --- /dev/null +++ b/embassy-net-nrf91/src/context.rs @@ -0,0 +1,362 @@ +//! Helper utility to configure a specific modem context. +use core::net::IpAddr; +use core::str::FromStr; + +use at_commands::builder::CommandBuilder; +use at_commands::parser::CommandParser; +use embassy_time::{Duration, Timer}; +use heapless::Vec; + +/// Provides a higher level API for controlling a given context. +pub struct Control<'a> { + control: crate::Control<'a>, + cid: u8, +} + +/// Configuration for a given context +pub struct Config<'a> { + /// Desired APN address. + pub apn: &'a [u8], + /// Desired authentication protocol. + pub auth_prot: AuthProt, + /// Credentials. + pub auth: Option<(&'a [u8], &'a [u8])>, + /// SIM pin + pub pin: Option<&'a [u8]>, +} + +/// Authentication protocol. +#[derive(Clone, Copy, PartialEq, Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[repr(u8)] +pub enum AuthProt { + /// No authentication. + None = 0, + /// PAP authentication. + Pap = 1, + /// CHAP authentication. + Chap = 2, +} + +/// Error returned by control. +#[derive(Clone, Copy, PartialEq, Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Error { + /// Not enough space for command. + BufferTooSmall, + /// Error parsing response from modem. + AtParseError, + /// Error parsing IP addresses. + AddrParseError, +} + +impl From for Error { + fn from(_: at_commands::parser::ParseError) -> Self { + Self::AtParseError + } +} + +/// Status of a given context. +#[derive(PartialEq, Debug)] +pub struct Status { + /// Attached to APN or not. + pub attached: bool, + /// IP if assigned. + pub ip: Option, + /// Gateway if assigned. + pub gateway: Option, + /// DNS servers if assigned. + pub dns: Vec, +} + +#[cfg(feature = "defmt")] +impl defmt::Format for Status { + fn format(&self, f: defmt::Formatter<'_>) { + defmt::write!(f, "attached: {}", self.attached); + if let Some(ip) = &self.ip { + defmt::write!(f, ", ip: {}", defmt::Debug2Format(&ip)); + } + } +} + +impl<'a> Control<'a> { + /// Create a new instance of a control handle for a given context. + /// + /// Will wait for the modem to be initialized if not. + pub async fn new(control: crate::Control<'a>, cid: u8) -> Self { + control.wait_init().await; + Self { control, cid } + } + + /// Perform a raw AT command + pub async fn at_command(&self, req: &[u8], resp: &mut [u8]) -> usize { + self.control.at_command(req, resp).await + } + + /// Configures the modem with the provided config. + /// + /// NOTE: This will disconnect the modem from any current APN and should not + /// be called if the configuration has not been changed. + /// + /// After configuring, invoke [`enable()`] to activate the configuration. + pub async fn configure(&self, config: &Config<'_>) -> Result<(), Error> { + let mut cmd: [u8; 256] = [0; 256]; + let mut buf: [u8; 256] = [0; 256]; + + let op = CommandBuilder::create_set(&mut cmd, true) + .named("+CFUN") + .with_int_parameter(0) + .finish() + .map_err(|_| Error::BufferTooSmall)?; + let n = self.control.at_command(op, &mut buf).await; + CommandParser::parse(&buf[..n]).expect_identifier(b"OK").finish()?; + + let op = CommandBuilder::create_set(&mut cmd, true) + .named("+CGDCONT") + .with_int_parameter(self.cid) + .with_string_parameter("IP") + .with_string_parameter(config.apn) + .finish() + .map_err(|_| Error::BufferTooSmall)?; + let n = self.control.at_command(op, &mut buf).await; + // info!("RES1: {}", unsafe { core::str::from_utf8_unchecked(&buf[..n]) }); + CommandParser::parse(&buf[..n]).expect_identifier(b"OK").finish()?; + + let mut op = CommandBuilder::create_set(&mut cmd, true) + .named("+CGAUTH") + .with_int_parameter(self.cid) + .with_int_parameter(config.auth_prot as u8); + if let Some((username, password)) = config.auth { + op = op.with_string_parameter(username).with_string_parameter(password); + } + let op = op.finish().map_err(|_| Error::BufferTooSmall)?; + + let n = self.control.at_command(op, &mut buf).await; + // info!("RES2: {}", unsafe { core::str::from_utf8_unchecked(&buf[..n]) }); + CommandParser::parse(&buf[..n]).expect_identifier(b"OK").finish()?; + + if let Some(pin) = config.pin { + let op = CommandBuilder::create_set(&mut cmd, true) + .named("+CPIN") + .with_string_parameter(pin) + .finish() + .map_err(|_| Error::BufferTooSmall)?; + let _ = self.control.at_command(op, &mut buf).await; + // Ignore ERROR which means no pin required + } + + Ok(()) + } + + /// Attach to the PDN + pub async fn attach(&self) -> Result<(), Error> { + let mut cmd: [u8; 256] = [0; 256]; + let mut buf: [u8; 256] = [0; 256]; + let op = CommandBuilder::create_set(&mut cmd, true) + .named("+CGATT") + .with_int_parameter(1) + .finish() + .map_err(|_| Error::BufferTooSmall)?; + let n = self.control.at_command(op, &mut buf).await; + CommandParser::parse(&buf[..n]).expect_identifier(b"OK").finish()?; + Ok(()) + } + + /// Read current connectivity status for modem. + pub async fn detach(&self) -> Result<(), Error> { + let mut cmd: [u8; 256] = [0; 256]; + let mut buf: [u8; 256] = [0; 256]; + let op = CommandBuilder::create_set(&mut cmd, true) + .named("+CGATT") + .with_int_parameter(0) + .finish() + .map_err(|_| Error::BufferTooSmall)?; + let n = self.control.at_command(op, &mut buf).await; + CommandParser::parse(&buf[..n]).expect_identifier(b"OK").finish()?; + Ok(()) + } + + async fn attached(&self) -> Result { + let mut cmd: [u8; 256] = [0; 256]; + let mut buf: [u8; 256] = [0; 256]; + + let op = CommandBuilder::create_query(&mut cmd, true) + .named("+CGATT") + .finish() + .map_err(|_| Error::BufferTooSmall)?; + let n = self.control.at_command(op, &mut buf).await; + let (res,) = CommandParser::parse(&buf[..n]) + .expect_identifier(b"+CGATT: ") + .expect_int_parameter() + .expect_identifier(b"\r\nOK") + .finish()?; + Ok(res == 1) + } + + /// Read current connectivity status for modem. + pub async fn status(&self) -> Result { + let mut cmd: [u8; 256] = [0; 256]; + let mut buf: [u8; 256] = [0; 256]; + + let op = CommandBuilder::create_query(&mut cmd, true) + .named("+CGATT") + .finish() + .map_err(|_| Error::BufferTooSmall)?; + let n = self.control.at_command(op, &mut buf).await; + let (res,) = CommandParser::parse(&buf[..n]) + .expect_identifier(b"+CGATT: ") + .expect_int_parameter() + .expect_identifier(b"\r\nOK") + .finish()?; + let attached = res == 1; + if !attached { + return Ok(Status { + attached, + ip: None, + gateway: None, + dns: Vec::new(), + }); + } + + let op = CommandBuilder::create_set(&mut cmd, true) + .named("+CGPADDR") + .with_int_parameter(self.cid) + .finish() + .map_err(|_| Error::BufferTooSmall)?; + let n = self.control.at_command(op, &mut buf).await; + let (_, ip1, _ip2) = CommandParser::parse(&buf[..n]) + .expect_identifier(b"+CGPADDR: ") + .expect_int_parameter() + .expect_optional_string_parameter() + .expect_optional_string_parameter() + .expect_identifier(b"\r\nOK") + .finish()?; + + let ip = if let Some(ip) = ip1 { + let ip = IpAddr::from_str(ip).map_err(|_| Error::AddrParseError)?; + Some(ip) + } else { + None + }; + + let op = CommandBuilder::create_set(&mut cmd, true) + .named("+CGCONTRDP") + .with_int_parameter(self.cid) + .finish() + .map_err(|_| Error::BufferTooSmall)?; + let n = self.control.at_command(op, &mut buf).await; + let (_cid, _bid, _apn, _mask, gateway, dns1, dns2, _, _, _, _, _mtu) = CommandParser::parse(&buf[..n]) + .expect_identifier(b"+CGCONTRDP: ") + .expect_int_parameter() + .expect_optional_int_parameter() + .expect_optional_string_parameter() + .expect_optional_string_parameter() + .expect_optional_string_parameter() + .expect_optional_string_parameter() + .expect_optional_string_parameter() + .expect_optional_int_parameter() + .expect_optional_int_parameter() + .expect_optional_int_parameter() + .expect_optional_int_parameter() + .expect_optional_int_parameter() + .expect_identifier(b"\r\nOK") + .finish()?; + + let gateway = if let Some(ip) = gateway { + if ip.is_empty() { + None + } else { + Some(IpAddr::from_str(ip).map_err(|_| Error::AddrParseError)?) + } + } else { + None + }; + + let mut dns = Vec::new(); + if let Some(ip) = dns1 { + dns.push(IpAddr::from_str(ip).map_err(|_| Error::AddrParseError)?) + .unwrap(); + } + + if let Some(ip) = dns2 { + dns.push(IpAddr::from_str(ip).map_err(|_| Error::AddrParseError)?) + .unwrap(); + } + + Ok(Status { + attached, + ip, + gateway, + dns, + }) + } + + async fn wait_attached(&self) -> Result { + while !self.attached().await? { + Timer::after(Duration::from_secs(1)).await; + } + let status = self.status().await?; + Ok(status) + } + + /// Disable modem + pub async fn disable(&self) -> Result<(), Error> { + let mut cmd: [u8; 256] = [0; 256]; + let mut buf: [u8; 256] = [0; 256]; + + let op = CommandBuilder::create_set(&mut cmd, true) + .named("+CFUN") + .with_int_parameter(0) + .finish() + .map_err(|_| Error::BufferTooSmall)?; + let n = self.control.at_command(op, &mut buf).await; + CommandParser::parse(&buf[..n]).expect_identifier(b"OK").finish()?; + + Ok(()) + } + + /// Enable modem + pub async fn enable(&self) -> Result<(), Error> { + let mut cmd: [u8; 256] = [0; 256]; + let mut buf: [u8; 256] = [0; 256]; + + let op = CommandBuilder::create_set(&mut cmd, true) + .named("+CFUN") + .with_int_parameter(1) + .finish() + .map_err(|_| Error::BufferTooSmall)?; + let n = self.control.at_command(op, &mut buf).await; + CommandParser::parse(&buf[..n]).expect_identifier(b"OK").finish()?; + + // Make modem survive PDN detaches + let op = CommandBuilder::create_set(&mut cmd, true) + .named("%XPDNCFG") + .with_int_parameter(1) + .finish() + .map_err(|_| Error::BufferTooSmall)?; + let n = self.control.at_command(op, &mut buf).await; + CommandParser::parse(&buf[..n]).expect_identifier(b"OK").finish()?; + Ok(()) + } + + /// Run a control loop for this context, ensuring that reaattach is handled. + pub async fn run(&self, reattach: F) -> Result<(), Error> { + self.enable().await?; + let status = self.wait_attached().await?; + let mut fd = self.control.open_raw_socket().await; + reattach(&status); + + loop { + if !self.attached().await? { + trace!("detached"); + + self.control.close_raw_socket(fd).await; + let status = self.wait_attached().await?; + trace!("attached"); + fd = self.control.open_raw_socket().await; + reattach(&status); + } + Timer::after(Duration::from_secs(10)).await; + } + } +} diff --git a/embassy-net-nrf91/src/fmt.rs b/embassy-net-nrf91/src/fmt.rs new file mode 100644 index 000000000..35b929fde --- /dev/null +++ b/embassy-net-nrf91/src/fmt.rs @@ -0,0 +1,274 @@ +#![macro_use] +#![allow(unused)] + +use core::fmt::{Debug, Display, LowerHex}; + +#[cfg(all(feature = "defmt", feature = "log"))] +compile_error!("You may not enable both `defmt` and `log` features."); + +#[collapse_debuginfo(yes)] +macro_rules! assert { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::assert!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::assert!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! assert_eq { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::assert_eq!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::assert_eq!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! assert_ne { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::assert_ne!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::assert_ne!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! debug_assert { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::debug_assert!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::debug_assert!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! debug_assert_eq { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::debug_assert_eq!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::debug_assert_eq!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! debug_assert_ne { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::debug_assert_ne!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::debug_assert_ne!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! todo { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::todo!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::todo!($($x)*); + } + }; +} + +#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] +macro_rules! unreachable { + ($($x:tt)*) => { + ::core::unreachable!($($x)*) + }; +} + +#[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] +macro_rules! unreachable { + ($($x:tt)*) => { + ::defmt::unreachable!($($x)*) + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! panic { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::panic!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::panic!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! trace { + ($s:literal $(, $x:expr)* $(,)?) => { + { + #[cfg(feature = "log")] + ::log::trace!($s $(, $x)*); + #[cfg(feature = "defmt")] + ::defmt::trace!($s $(, $x)*); + #[cfg(not(any(feature = "log", feature="defmt")))] + let _ = ($( & $x ),*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! debug { + ($s:literal $(, $x:expr)* $(,)?) => { + { + #[cfg(feature = "log")] + ::log::debug!($s $(, $x)*); + #[cfg(feature = "defmt")] + ::defmt::debug!($s $(, $x)*); + #[cfg(not(any(feature = "log", feature="defmt")))] + let _ = ($( & $x ),*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! info { + ($s:literal $(, $x:expr)* $(,)?) => { + { + #[cfg(feature = "log")] + ::log::info!($s $(, $x)*); + #[cfg(feature = "defmt")] + ::defmt::info!($s $(, $x)*); + #[cfg(not(any(feature = "log", feature="defmt")))] + let _ = ($( & $x ),*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! warn { + ($s:literal $(, $x:expr)* $(,)?) => { + { + #[cfg(feature = "log")] + ::log::warn!($s $(, $x)*); + #[cfg(feature = "defmt")] + ::defmt::warn!($s $(, $x)*); + #[cfg(not(any(feature = "log", feature="defmt")))] + let _ = ($( & $x ),*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! error { + ($s:literal $(, $x:expr)* $(,)?) => { + { + #[cfg(feature = "log")] + ::log::error!($s $(, $x)*); + #[cfg(feature = "defmt")] + ::defmt::error!($s $(, $x)*); + #[cfg(not(any(feature = "log", feature="defmt")))] + let _ = ($( & $x ),*); + } + }; +} + +#[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] +macro_rules! unwrap { + ($($x:tt)*) => { + ::defmt::unwrap!($($x)*) + }; +} + +#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] +macro_rules! unwrap { + ($arg:expr) => { + match $crate::fmt::Try::into_result($arg) { + ::core::result::Result::Ok(t) => t, + ::core::result::Result::Err(e) => { + ::core::panic!("unwrap of `{}` failed: {:?}", ::core::stringify!($arg), e); + } + } + }; + ($arg:expr, $($msg:expr),+ $(,)? ) => { + match $crate::fmt::Try::into_result($arg) { + ::core::result::Result::Ok(t) => t, + ::core::result::Result::Err(e) => { + ::core::panic!("unwrap of `{}` failed: {}: {:?}", ::core::stringify!($arg), ::core::format_args!($($msg,)*), e); + } + } + } +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub struct NoneError; + +pub trait Try { + type Ok; + type Error; + fn into_result(self) -> Result; +} + +impl Try for Option { + type Ok = T; + type Error = NoneError; + + #[inline] + fn into_result(self) -> Result { + self.ok_or(NoneError) + } +} + +impl Try for Result { + type Ok = T; + type Error = E; + + #[inline] + fn into_result(self) -> Self { + self + } +} + +pub(crate) struct Bytes<'a>(pub &'a [u8]); + +impl<'a> Debug for Bytes<'a> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{:#02x?}", self.0) + } +} + +impl<'a> Display for Bytes<'a> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{:#02x?}", self.0) + } +} + +impl<'a> LowerHex for Bytes<'a> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{:#02x?}", self.0) + } +} + +#[cfg(feature = "defmt")] +impl<'a> defmt::Format for Bytes<'a> { + fn format(&self, fmt: defmt::Formatter) { + defmt::write!(fmt, "{:02x}", self.0) + } +} diff --git a/embassy-net-nrf91/src/lib.rs b/embassy-net-nrf91/src/lib.rs new file mode 100644 index 000000000..80d08f7f5 --- /dev/null +++ b/embassy-net-nrf91/src/lib.rs @@ -0,0 +1,1042 @@ +#![no_std] +#![doc = include_str!("../README.md")] +#![warn(missing_docs)] +#![deny(unused_must_use)] + +// must be first +mod fmt; + +pub mod context; + +use core::cell::RefCell; +use core::future::poll_fn; +use core::marker::PhantomData; +use core::mem::{self, MaybeUninit}; +use core::ptr::{self, addr_of, addr_of_mut, copy_nonoverlapping}; +use core::slice; +use core::sync::atomic::{compiler_fence, fence, Ordering}; +use core::task::{Poll, Waker}; + +use cortex_m::peripheral::NVIC; +use embassy_sync::blocking_mutex::raw::NoopRawMutex; +use embassy_sync::pipe; +use embassy_sync::waitqueue::{AtomicWaker, WakerRegistration}; +use heapless::Vec; +use {embassy_net_driver_channel as ch, nrf_pac as pac}; + +const RX_SIZE: usize = 8 * 1024; +const TRACE_SIZE: usize = 16 * 1024; +const TRACE_BUF: usize = 1024; +const MTU: usize = 1500; + +/// Network driver. +/// +/// This is the type you have to pass to `embassy-net` when creating the network stack. +pub type NetDriver<'a> = ch::Device<'a, MTU>; + +static WAKER: AtomicWaker = AtomicWaker::new(); + +/// Call this function on IPC IRQ +pub fn on_ipc_irq() { + trace!("irq"); + + pac::IPC_NS.inten().write(|_| ()); + WAKER.wake(); +} + +struct Allocator<'a> { + start: *mut u8, + end: *mut u8, + _phantom: PhantomData<&'a mut u8>, +} + +impl<'a> Allocator<'a> { + fn alloc_bytes(&mut self, size: usize) -> &'a mut [MaybeUninit] { + // safety: both pointers come from the same allocation. + let available_size = unsafe { self.end.offset_from(self.start) } as usize; + if size > available_size { + panic!("out of memory") + } + + // safety: we've checked above this doesn't go out of bounds. + let p = self.start; + self.start = unsafe { p.add(size) }; + + // safety: we've checked the pointer is in-bounds. + unsafe { slice::from_raw_parts_mut(p as *mut _, size) } + } + + fn alloc(&mut self) -> &'a mut MaybeUninit { + let align = mem::align_of::(); + let size = mem::size_of::(); + + let align_size = match (self.start as usize) % align { + 0 => 0, + n => align - n, + }; + + // safety: both pointers come from the same allocation. + let available_size = unsafe { self.end.offset_from(self.start) } as usize; + if align_size + size > available_size { + panic!("out of memory") + } + + // safety: we've checked above this doesn't go out of bounds. + let p = unsafe { self.start.add(align_size) }; + self.start = unsafe { p.add(size) }; + + // safety: we've checked the pointer is aligned and in-bounds. + unsafe { &mut *(p as *mut _) } + } +} + +/// Create a new nRF91 embassy-net driver. +pub async fn new<'a>( + state: &'a mut State, + shmem: &'a mut [MaybeUninit], +) -> (NetDriver<'a>, Control<'a>, Runner<'a>) { + let (n, c, r, _) = new_internal(state, shmem, None).await; + (n, c, r) +} + +/// Create a new nRF91 embassy-net driver with trace. +pub async fn new_with_trace<'a>( + state: &'a mut State, + shmem: &'a mut [MaybeUninit], + trace_buffer: &'a mut TraceBuffer, +) -> (NetDriver<'a>, Control<'a>, Runner<'a>, TraceReader<'a>) { + let (n, c, r, t) = new_internal(state, shmem, Some(trace_buffer)).await; + (n, c, r, t.unwrap()) +} + +/// Create a new nRF91 embassy-net driver. +async fn new_internal<'a>( + state: &'a mut State, + shmem: &'a mut [MaybeUninit], + trace_buffer: Option<&'a mut TraceBuffer>, +) -> (NetDriver<'a>, Control<'a>, Runner<'a>, Option>) { + let shmem_len = shmem.len(); + let shmem_ptr = shmem.as_mut_ptr() as *mut u8; + + const SPU_REGION_SIZE: usize = 8192; // 8kb + assert!(shmem_len != 0); + assert!( + shmem_len % SPU_REGION_SIZE == 0, + "shmem length must be a multiple of 8kb" + ); + assert!( + (shmem_ptr as usize) % SPU_REGION_SIZE == 0, + "shmem length must be a multiple of 8kb" + ); + assert!( + (shmem_ptr as usize + shmem_len) < 0x2002_0000, + "shmem must be in the lower 128kb of RAM" + ); + + let spu = pac::SPU_S; + debug!("Setting IPC RAM as nonsecure..."); + let region_start = (shmem_ptr as usize - 0x2000_0000) / SPU_REGION_SIZE; + let region_end = region_start + shmem_len / SPU_REGION_SIZE; + for i in region_start..region_end { + spu.ramregion(i).perm().write(|w| { + w.set_execute(true); + w.set_write(true); + w.set_read(true); + w.set_secattr(false); + w.set_lock(false); + }) + } + + spu.periphid(42).perm().write(|w| w.set_secattr(false)); + + let mut alloc = Allocator { + start: shmem_ptr, + end: unsafe { shmem_ptr.add(shmem_len) }, + _phantom: PhantomData, + }; + + let ipc = pac::IPC_NS; + let power = pac::POWER_S; + + let cb: &mut ControlBlock = alloc.alloc().write(unsafe { mem::zeroed() }); + let rx = alloc.alloc_bytes(RX_SIZE); + let trace = alloc.alloc_bytes(TRACE_SIZE); + + cb.version = 0x00010000; + cb.rx_base = rx.as_mut_ptr() as _; + cb.rx_size = RX_SIZE; + cb.control_list_ptr = &mut cb.lists[0]; + cb.data_list_ptr = &mut cb.lists[1]; + cb.modem_info_ptr = &mut cb.modem_info; + cb.trace_ptr = &mut cb.trace; + cb.lists[0].len = LIST_LEN; + cb.lists[1].len = LIST_LEN; + cb.trace.base = trace.as_mut_ptr() as _; + cb.trace.size = TRACE_SIZE; + + ipc.gpmem(0).write_value(cb as *mut _ as u32); + ipc.gpmem(1).write_value(0); + + // connect task/event i to channel i + for i in 0..8 { + ipc.send_cnf(i).write(|w| w.0 = 1 << i); + ipc.receive_cnf(i).write(|w| w.0 = 1 << i); + } + + compiler_fence(Ordering::SeqCst); + + // POWER.LTEMODEM.STARTN = 0 + // The reg is missing in the PAC?? + let startn = unsafe { (power.as_ptr() as *mut u32).add(0x610 / 4) }; + unsafe { startn.write_volatile(0) } + + unsafe { NVIC::unmask(pac::Interrupt::IPC) }; + + let state_inner = &*state.inner.write(RefCell::new(StateInner { + init: false, + init_waker: WakerRegistration::new(), + cb, + requests: [const { None }; REQ_COUNT], + next_req_serial: 0x12345678, + + rx_control_list: ptr::null_mut(), + rx_data_list: ptr::null_mut(), + rx_seq_no: 0, + rx_check: PointerChecker { + start: rx.as_mut_ptr() as *mut u8, + end: (rx.as_mut_ptr() as *mut u8).wrapping_add(RX_SIZE), + }, + + tx_seq_no: 0, + tx_buf_used: [false; TX_BUF_COUNT], + + trace_chans: Vec::new(), + trace_check: PointerChecker { + start: trace.as_mut_ptr() as *mut u8, + end: (trace.as_mut_ptr() as *mut u8).wrapping_add(TRACE_SIZE), + }, + })); + + let control = Control { state: state_inner }; + + let (ch_runner, device) = ch::new(&mut state.ch, ch::driver::HardwareAddress::Ip); + let state_ch = ch_runner.state_runner(); + state_ch.set_link_state(ch::driver::LinkState::Up); + + let (trace_reader, trace_writer) = if let Some(trace) = trace_buffer { + let (r, w) = trace.trace.split(); + (Some(r), Some(w)) + } else { + (None, None) + }; + + let runner = Runner { + ch: ch_runner, + state: state_inner, + trace_writer, + }; + + (device, control, runner, trace_reader) +} + +/// State holding modem traces. +pub struct TraceBuffer { + trace: pipe::Pipe, +} + +/// Represents writer half of the trace buffer. +pub type TraceWriter<'a> = pipe::Writer<'a, NoopRawMutex, TRACE_BUF>; + +/// Represents the reader half of the trace buffer. +pub type TraceReader<'a> = pipe::Reader<'a, NoopRawMutex, TRACE_BUF>; + +impl TraceBuffer { + /// Create a new TraceBuffer. + pub const fn new() -> Self { + Self { + trace: pipe::Pipe::new(), + } + } +} + +/// Shared state for the driver. +pub struct State { + ch: ch::State, + inner: MaybeUninit>, +} + +impl State { + /// Create a new State. + pub const fn new() -> Self { + Self { + ch: ch::State::new(), + inner: MaybeUninit::uninit(), + } + } +} + +const TX_BUF_COUNT: usize = 4; +const TX_BUF_SIZE: usize = 1500; + +struct TraceChannelInfo { + ptr: *mut TraceChannel, + start: *mut u8, + end: *mut u8, +} + +const REQ_COUNT: usize = 4; + +struct PendingRequest { + req_serial: u32, + resp_msg: *mut Message, + waker: Waker, +} + +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +struct NoFreeBufs; + +struct StateInner { + init: bool, + init_waker: WakerRegistration, + + cb: *mut ControlBlock, + requests: [Option; REQ_COUNT], + next_req_serial: u32, + + rx_control_list: *mut List, + rx_data_list: *mut List, + rx_seq_no: u16, + rx_check: PointerChecker, + + tx_seq_no: u16, + tx_buf_used: [bool; TX_BUF_COUNT], + + trace_chans: Vec, + trace_check: PointerChecker, +} + +impl StateInner { + fn poll(&mut self, trace_writer: &mut Option>, ch: &mut ch::Runner) { + trace!("poll!"); + let ipc = pac::IPC_NS; + + if ipc.events_receive(0).read() != 0 { + ipc.events_receive(0).write_value(0); + trace!("ipc 0"); + } + + if ipc.events_receive(2).read() != 0 { + ipc.events_receive(2).write_value(0); + trace!("ipc 2"); + + if !self.init { + let desc = unsafe { addr_of!((*self.cb).modem_info).read_volatile() }; + assert_eq!(desc.version, 1); + + self.rx_check.check_mut(desc.control_list_ptr); + self.rx_check.check_mut(desc.data_list_ptr); + + self.rx_control_list = desc.control_list_ptr; + self.rx_data_list = desc.data_list_ptr; + let rx_control_len = unsafe { addr_of!((*self.rx_control_list).len).read_volatile() }; + let rx_data_len = unsafe { addr_of!((*self.rx_data_list).len).read_volatile() }; + assert_eq!(rx_control_len, LIST_LEN); + assert_eq!(rx_data_len, LIST_LEN); + self.init = true; + + debug!("IPC initialized OK!"); + self.init_waker.wake(); + } + } + + if ipc.events_receive(4).read() != 0 { + ipc.events_receive(4).write_value(0); + trace!("ipc 4"); + + loop { + let list = unsafe { &mut *self.rx_control_list }; + let control_work = self.process(list, true, ch); + let list = unsafe { &mut *self.rx_data_list }; + let data_work = self.process(list, false, ch); + if !control_work && !data_work { + break; + } + } + } + + if ipc.events_receive(6).read() != 0 { + ipc.events_receive(6).write_value(0); + trace!("ipc 6"); + } + + if ipc.events_receive(7).read() != 0 { + ipc.events_receive(7).write_value(0); + trace!("ipc 7: trace"); + + let msg = unsafe { addr_of!((*self.cb).trace.rx_state).read_volatile() }; + if msg != 0 { + trace!("trace msg {}", msg); + match msg { + 0 => unreachable!(), + 1 => { + let ctx = unsafe { addr_of!((*self.cb).trace.rx_ptr).read_volatile() } as *mut TraceContext; + debug!("trace init: {:?}", ctx); + self.trace_check.check(ctx); + let chans = unsafe { addr_of!((*ctx).chans).read_volatile() }; + for chan_ptr in chans { + let chan = self.trace_check.check_read(chan_ptr); + self.trace_check.check(chan.start); + self.trace_check.check(chan.end); + assert!(chan.start < chan.end); + self.trace_chans + .push(TraceChannelInfo { + ptr: chan_ptr, + start: chan.start, + end: chan.end, + }) + .map_err(|_| ()) + .unwrap() + } + } + 2 => { + for chan_info in &self.trace_chans { + let read_ptr = unsafe { addr_of!((*chan_info.ptr).read_ptr).read_volatile() }; + let write_ptr = unsafe { addr_of!((*chan_info.ptr).write_ptr).read_volatile() }; + assert!(read_ptr >= chan_info.start && read_ptr <= chan_info.end); + assert!(write_ptr >= chan_info.start && write_ptr <= chan_info.end); + if read_ptr != write_ptr { + let id = unsafe { addr_of!((*chan_info.ptr).id).read_volatile() }; + fence(Ordering::SeqCst); // synchronize volatile accesses with the slice access. + if read_ptr < write_ptr { + Self::handle_trace(trace_writer, id, unsafe { + slice::from_raw_parts(read_ptr, write_ptr.offset_from(read_ptr) as _) + }); + } else { + Self::handle_trace(trace_writer, id, unsafe { + slice::from_raw_parts(read_ptr, chan_info.end.offset_from(read_ptr) as _) + }); + Self::handle_trace(trace_writer, id, unsafe { + slice::from_raw_parts( + chan_info.start, + write_ptr.offset_from(chan_info.start) as _, + ) + }); + } + fence(Ordering::SeqCst); // synchronize volatile accesses with the slice access. + unsafe { addr_of_mut!((*chan_info.ptr).read_ptr).write_volatile(write_ptr) }; + } + } + } + _ => warn!("unknown trace msg {}", msg), + } + unsafe { addr_of_mut!((*self.cb).trace.rx_state).write_volatile(0) }; + } + } + + ipc.intenset().write(|w| { + w.set_receive0(true); + w.set_receive2(true); + w.set_receive4(true); + w.set_receive6(true); + w.set_receive7(true); + }); + } + + fn handle_trace(writer: &mut Option>, id: u8, data: &[u8]) { + if let Some(writer) = writer { + trace!("trace: {} {}", id, data.len()); + let mut header = [0u8; 5]; + header[0] = 0xEF; + header[1] = 0xBE; + header[2..4].copy_from_slice(&(data.len() as u16).to_le_bytes()); + header[4] = id; + writer.try_write(&header).ok(); + writer.try_write(data).ok(); + } + } + + fn process(&mut self, list: *mut List, is_control: bool, ch: &mut ch::Runner) -> bool { + let mut did_work = false; + for i in 0..LIST_LEN { + let item_ptr = unsafe { addr_of_mut!((*list).items[i]) }; + let preamble = unsafe { addr_of!((*item_ptr).state).read_volatile() }; + if preamble & 0xFF == 0x01 && preamble >> 16 == self.rx_seq_no as u32 { + let msg_ptr = unsafe { addr_of!((*item_ptr).message).read_volatile() }; + let msg = self.rx_check.check_read(msg_ptr); + + debug!("rx seq {} msg: {:?}", preamble >> 16, msg); + + if is_control { + self.handle_control(&msg); + } else { + self.handle_data(&msg, ch); + } + + unsafe { addr_of_mut!((*item_ptr).state).write_volatile(0x03) }; + self.rx_seq_no = self.rx_seq_no.wrapping_add(1); + + did_work = true; + } + } + did_work + } + + fn find_free_message(&mut self, ch: usize) -> Option { + for i in 0..LIST_LEN { + let preamble = unsafe { addr_of!((*self.cb).lists[ch].items[i].state).read_volatile() }; + if matches!(preamble & 0xFF, 0 | 3) { + trace!("using tx msg idx {}", i); + return Some(i); + } + } + return None; + } + + fn find_free_tx_buf(&mut self) -> Option { + for i in 0..TX_BUF_COUNT { + if !self.tx_buf_used[i] { + trace!("using tx buf idx {}", i); + return Some(i); + } + } + return None; + } + + fn send_message(&mut self, msg: &mut Message, data: &[u8]) -> Result<(), NoFreeBufs> { + if data.is_empty() { + msg.data = ptr::null_mut(); + msg.data_len = 0; + } else { + assert!(data.len() <= TX_BUF_SIZE); + let buf_idx = self.find_free_tx_buf().ok_or(NoFreeBufs)?; + let buf = unsafe { addr_of_mut!((*self.cb).tx_bufs[buf_idx]) } as *mut u8; + unsafe { copy_nonoverlapping(data.as_ptr(), buf, data.len()) } + msg.data = buf; + msg.data_len = data.len(); + self.tx_buf_used[buf_idx] = true; + + fence(Ordering::SeqCst); // synchronize copy_nonoverlapping (non-volatile) with volatile writes below. + } + + // TODO free data buf if send_message_raw fails. + self.send_message_raw(msg) + } + + fn send_message_raw(&mut self, msg: &Message) -> Result<(), NoFreeBufs> { + let (ch, ipc_ch) = match msg.channel { + 1 => (0, 1), // control + 2 => (1, 3), // data + _ => unreachable!(), + }; + + // allocate a msg. + let idx = self.find_free_message(ch).ok_or(NoFreeBufs)?; + + debug!("tx seq {} msg: {:?}", self.tx_seq_no, msg); + + let msg_slot = unsafe { addr_of_mut!((*self.cb).msgs[ch][idx]) }; + unsafe { msg_slot.write_volatile(*msg) } + let list_item = unsafe { addr_of_mut!((*self.cb).lists[ch].items[idx]) }; + unsafe { addr_of_mut!((*list_item).message).write_volatile(msg_slot) } + unsafe { addr_of_mut!((*list_item).state).write_volatile((self.tx_seq_no as u32) << 16 | 0x01) } + self.tx_seq_no = self.tx_seq_no.wrapping_add(1); + + let ipc = pac::IPC_NS; + ipc.tasks_send(ipc_ch).write_value(1); + Ok(()) + } + + fn handle_control(&mut self, msg: &Message) { + match msg.id >> 16 { + 1 => debug!("control msg: modem ready"), + 2 => self.handle_control_free(msg.data), + _ => warn!("unknown control message id {:08x}", msg.id), + } + } + + fn handle_control_free(&mut self, ptr: *mut u8) { + let base = unsafe { addr_of!((*self.cb).tx_bufs) } as usize; + let ptr = ptr as usize; + + if ptr < base { + warn!("control free bad pointer {:08x}", ptr); + return; + } + + let diff = ptr - base; + let idx = diff / TX_BUF_SIZE; + + if idx >= TX_BUF_COUNT || idx * TX_BUF_SIZE != diff { + warn!("control free bad pointer {:08x}", ptr); + return; + } + + trace!("control free pointer {:08x} idx {}", ptr, idx); + if !self.tx_buf_used[idx] { + warn!( + "control free pointer {:08x} idx {}: buffer was already free??", + ptr, idx + ); + } + self.tx_buf_used[idx] = false; + } + + fn handle_data(&mut self, msg: &Message, ch: &mut ch::Runner) { + if !msg.data.is_null() { + self.rx_check.check_length(msg.data, msg.data_len); + } + + let freed = match msg.id & 0xFFFF { + // AT + 3 => { + match msg.id >> 16 { + // AT request ack + 2 => false, + // AT response + 3 => self.handle_resp(msg), + // AT notification + 4 => false, + x => { + warn!("received unknown AT kind {}", x); + false + } + } + } + // IP + 4 => { + match msg.id >> 28 { + // IP response + 8 => self.handle_resp(msg), + // IP notification + 9 => match (msg.id >> 16) & 0xFFF { + // IP receive notification + 1 => { + if let Some(buf) = ch.try_rx_buf() { + let mut len = msg.data_len; + if len > buf.len() { + warn!("truncating rx'd packet from {} to {} bytes", len, buf.len()); + len = buf.len(); + } + fence(Ordering::SeqCst); // synchronize volatile accesses with the nonvolatile copy_nonoverlapping. + unsafe { ptr::copy_nonoverlapping(msg.data, buf.as_mut_ptr(), len) } + fence(Ordering::SeqCst); // synchronize volatile accesses with the nonvolatile copy_nonoverlapping. + ch.rx_done(len); + } + false + } + _ => false, + }, + x => { + warn!("received unknown IP kind {}", x); + false + } + } + } + x => { + warn!("received unknown kind {}", x); + false + } + }; + + if !freed { + self.send_free(msg); + } + } + + fn handle_resp(&mut self, msg: &Message) -> bool { + let req_serial = u32::from_le_bytes(msg.param[0..4].try_into().unwrap()); + if req_serial == 0 { + return false; + } + + for optr in &mut self.requests { + if let Some(r) = optr { + if r.req_serial == req_serial { + let r = optr.take().unwrap(); + unsafe { r.resp_msg.write(*msg) } + r.waker.wake(); + *optr = None; + return true; + } + } + } + + warn!( + "resp with id {} serial {} doesn't match any pending req", + msg.id, req_serial + ); + false + } + + fn send_free(&mut self, msg: &Message) { + if msg.data.is_null() { + return; + } + + let mut free_msg: Message = unsafe { mem::zeroed() }; + free_msg.channel = 1; // control + free_msg.id = 0x20001; // free + free_msg.data = msg.data; + free_msg.data_len = msg.data_len; + + unwrap!(self.send_message_raw(&free_msg)); + } +} + +struct PointerChecker { + start: *mut u8, + end: *mut u8, +} + +impl PointerChecker { + // check the pointer is in bounds in the arena, panic otherwise. + fn check_length(&self, ptr: *const u8, len: usize) { + assert!(ptr as usize >= self.start as usize); + let end_ptr = (ptr as usize).checked_add(len).unwrap(); + assert!(end_ptr <= self.end as usize); + } + + // check the pointer is in bounds in the arena, panic otherwise. + fn check(&self, ptr: *const T) { + assert!(ptr.is_aligned()); + self.check_length(ptr as *const u8, mem::size_of::()); + } + + // check the pointer is in bounds in the arena, panic otherwise. + fn check_read(&self, ptr: *const T) -> T { + self.check(ptr); + unsafe { ptr.read_volatile() } + } + + // check the pointer is in bounds in the arena, panic otherwise. + fn check_mut(&self, ptr: *mut T) { + self.check(ptr as *const T) + } +} + +/// Control handle for the driver. +/// +/// You can use this object to control the modem at runtime, such as running AT commands. +pub struct Control<'a> { + state: &'a RefCell, +} + +impl<'a> Control<'a> { + /// Wait for modem IPC to be initialized. + pub async fn wait_init(&self) { + poll_fn(|cx| { + let mut state = self.state.borrow_mut(); + if state.init { + return Poll::Ready(()); + } + state.init_waker.register(cx.waker()); + Poll::Pending + }) + .await + } + + async fn request(&self, msg: &mut Message, req_data: &[u8], resp_data: &mut [u8]) -> usize { + // get waker + let waker = poll_fn(|cx| Poll::Ready(cx.waker().clone())).await; + + // Send request + let mut state = self.state.borrow_mut(); + let mut req_serial = state.next_req_serial; + if msg.id & 0xFFFF == 3 { + // AT response seems to keep only the lower 8 bits. Others do keep the full 32 bits..?? + req_serial &= 0xFF; + } + + // increment next_req_serial, skip zero because we use it as an "ignore" value. + // We have to skip when the *lowest byte* is zero because AT responses. + state.next_req_serial = state.next_req_serial.wrapping_add(1); + if state.next_req_serial & 0xFF == 0 { + state.next_req_serial = state.next_req_serial.wrapping_add(1); + } + + msg.param[0..4].copy_from_slice(&req_serial.to_le_bytes()); + unwrap!(state.send_message(msg, req_data)); + + // Setup the pending request state. + let (req_slot_idx, req_slot) = state + .requests + .iter_mut() + .enumerate() + .find(|(_, x)| x.is_none()) + .unwrap(); + msg.id = 0; // zero out id, so when it becomes nonzero we know the req is done. + let msg_ptr: *mut Message = msg; + *req_slot = Some(PendingRequest { + req_serial, + resp_msg: msg_ptr, + waker, + }); + + drop(state); // don't borrow state across awaits. + + // On cancel, unregister the request slot. + let _drop = OnDrop::new(|| { + // Remove request slot. + let mut state = self.state.borrow_mut(); + let slot = &mut state.requests[req_slot_idx]; + if let Some(s) = slot { + if s.req_serial == req_serial { + *slot = None; + } + } + + // If cancelation raced with actually receiving the response, + // we own the data, so we have to free it. + let msg = unsafe { &mut *msg_ptr }; + if msg.id != 0 { + state.send_free(msg); + } + }); + // Wait for response. + poll_fn(|_| { + // we have to use the raw pointer and not the original reference `msg` + // because that'd invalidate the raw ptr that's still stored in `req_slot`. + if unsafe { (*msg_ptr).id } != 0 { + Poll::Ready(()) + } else { + Poll::Pending + } + }) + .await; + _drop.defuse(); + + if msg.data.is_null() { + // no response data. + return 0; + } + + // Copy response data out, if any. + // Pointer was validated in StateInner::handle_data(). + let mut len = msg.data_len; + if len > resp_data.len() { + warn!("truncating response data from {} to {}", len, resp_data.len()); + len = resp_data.len(); + } + fence(Ordering::SeqCst); // synchronize volatile accesses with the nonvolatile copy_nonoverlapping. + unsafe { ptr::copy_nonoverlapping(msg.data, resp_data.as_mut_ptr(), len) } + fence(Ordering::SeqCst); // synchronize volatile accesses with the nonvolatile copy_nonoverlapping. + self.state.borrow_mut().send_free(msg); + len + } + + /// Run an AT command. + /// + /// The response is written in `resp` and its length returned. + pub async fn at_command(&self, req: &[u8], resp: &mut [u8]) -> usize { + let mut msg: Message = unsafe { mem::zeroed() }; + msg.channel = 2; // data + msg.id = 0x0001_0003; // AT command + msg.param_len = 4; + + self.request(&mut msg, req, resp).await + } + + /// Open the raw socket used for sending/receiving IP packets. + /// + /// This must be done after `AT+CFUN=1` (?) + async fn open_raw_socket(&self) -> u32 { + let mut msg: Message = unsafe { mem::zeroed() }; + msg.channel = 2; // data + msg.id = 0x7001_0004; // open socket + msg.param_len = 20; + + let param = [ + 0xFF, 0xFF, 0xFF, 0xFF, // req_serial + 0xFF, 0xFF, 0xFF, 0xFF, // ??? + 0x05, 0x00, 0x00, 0x00, // family + 0x03, 0x00, 0x00, 0x00, // type + 0x00, 0x00, 0x00, 0x00, // protocol + ]; + msg.param[..param.len()].copy_from_slice(¶m); + + self.request(&mut msg, &[], &mut []).await; + + assert_eq!(msg.id, 0x80010004); + assert!(msg.param_len >= 12); + let status = u32::from_le_bytes(msg.param[8..12].try_into().unwrap()); + assert_eq!(status, 0); + assert_eq!(msg.param_len, 16); + let fd = u32::from_le_bytes(msg.param[12..16].try_into().unwrap()); + trace!("got FD: {}", fd); + fd + } + + async fn close_raw_socket(&self, fd: u32) { + let mut msg: Message = unsafe { mem::zeroed() }; + msg.channel = 2; // data + msg.id = 0x7009_0004; // close socket + msg.param_len = 8; + msg.param[4..8].copy_from_slice(&fd.to_le_bytes()); + + self.request(&mut msg, &[], &mut []).await; + + assert_eq!(msg.id, 0x80090004); + assert!(msg.param_len >= 12); + let status = u32::from_le_bytes(msg.param[8..12].try_into().unwrap()); + assert_eq!(status, 0); + } +} + +/// Background runner for the driver. +pub struct Runner<'a> { + ch: ch::Runner<'a, MTU>, + state: &'a RefCell, + trace_writer: Option>, +} + +impl<'a> Runner<'a> { + /// Run the driver operation in the background. + /// + /// You must run this in a background task, concurrently with all network operations. + pub async fn run(mut self) -> ! { + poll_fn(|cx| { + WAKER.register(cx.waker()); + + let mut state = self.state.borrow_mut(); + state.poll(&mut self.trace_writer, &mut self.ch); + + if let Poll::Ready(buf) = self.ch.poll_tx_buf(cx) { + let fd = 128u32; // TODO unhardcode + let mut msg: Message = unsafe { mem::zeroed() }; + msg.channel = 2; // data + msg.id = 0x7006_0004; // IP send + msg.param_len = 12; + msg.param[4..8].copy_from_slice(&fd.to_le_bytes()); + if let Err(e) = state.send_message(&mut msg, buf) { + warn!("tx failed: {:?}", e); + } + self.ch.tx_done(); + } + + Poll::Pending + }) + .await + } +} + +const LIST_LEN: usize = 16; + +#[repr(C)] +struct ControlBlock { + version: u32, + rx_base: *mut u8, + rx_size: usize, + control_list_ptr: *mut List, + data_list_ptr: *mut List, + modem_info_ptr: *mut ModemInfo, + trace_ptr: *mut Trace, + unk: u32, + + modem_info: ModemInfo, + trace: Trace, + + // 0 = control, 1 = data + lists: [List; 2], + msgs: [[Message; LIST_LEN]; 2], + + tx_bufs: [[u8; TX_BUF_SIZE]; TX_BUF_COUNT], +} + +#[repr(C)] +struct ModemInfo { + version: u32, + control_list_ptr: *mut List, + data_list_ptr: *mut List, + padding: [u32; 5], +} + +#[repr(C)] +struct Trace { + size: usize, + base: *mut u8, + tx_state: u32, + tx_ptr: *mut u8, + rx_state: u32, + rx_ptr: *mut u8, + unk1: u32, + unk2: u32, +} + +const TRACE_CHANNEL_COUNT: usize = 3; + +#[repr(C)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +struct TraceContext { + unk1: u32, + unk2: u32, + len: u32, + chans: [*mut TraceChannel; TRACE_CHANNEL_COUNT], +} + +#[repr(C)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +struct TraceChannel { + id: u8, + unk1: u8, + unk2: u8, + unk3: u8, + write_ptr: *mut u8, + read_ptr: *mut u8, + start: *mut u8, + end: *mut u8, +} + +#[repr(C)] +struct List { + len: usize, + items: [ListItem; LIST_LEN], +} + +#[repr(C)] +struct ListItem { + /// top 16 bits: seqno + /// bottom 8 bits: + /// 0x01: sent + /// 0x02: held + /// 0x03: freed + state: u32, + message: *mut Message, +} + +#[repr(C)] +#[derive(defmt::Format, Clone, Copy)] +struct Message { + id: u32, + + /// 1 = control, 2 = data + channel: u8, + unk1: u8, + unk2: u8, + unk3: u8, + + data: *mut u8, + data_len: usize, + param_len: usize, + param: [u8; 44], +} + +struct OnDrop { + f: MaybeUninit, +} + +impl OnDrop { + pub fn new(f: F) -> Self { + Self { f: MaybeUninit::new(f) } + } + + pub fn defuse(self) { + mem::forget(self) + } +} + +impl Drop for OnDrop { + fn drop(&mut self) { + unsafe { self.f.as_ptr().read()() } + } +} diff --git a/embassy-net-ppp/Cargo.toml b/embassy-net-ppp/Cargo.toml index c4bea202f..d2f43ef45 100644 --- a/embassy-net-ppp/Cargo.toml +++ b/embassy-net-ppp/Cargo.toml @@ -18,10 +18,10 @@ defmt = { version = "0.3", optional = true } log = { version = "0.4.14", optional = true } embedded-io-async = { version = "0.6.1" } -embassy-net-driver-channel = { version = "0.2.0", path = "../embassy-net-driver-channel" } +embassy-net-driver-channel = { version = "0.3.0", path = "../embassy-net-driver-channel" } embassy-futures = { version = "0.1.0", path = "../embassy-futures" } -ppproto = { version = "0.1.2"} -embassy-sync = { version = "0.5.0", path = "../embassy-sync" } +ppproto = { version = "0.2.0"} +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } [package.metadata.embassy_docs] src_base = "https://github.com/embassy-rs/embassy/blob/embassy-net-ppp-v$VERSION/embassy-net-ppp/src/" diff --git a/embassy-net-ppp/src/fmt.rs b/embassy-net-ppp/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-net-ppp/src/fmt.rs +++ b/embassy-net-ppp/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-net-tuntap/src/lib.rs b/embassy-net-tuntap/src/lib.rs index de30934eb..2ff23f462 100644 --- a/embassy-net-tuntap/src/lib.rs +++ b/embassy-net-tuntap/src/lib.rs @@ -6,7 +6,7 @@ use std::os::unix::io::{AsRawFd, RawFd}; use std::task::Context; use async_io::Async; -use embassy_net_driver::{self, Capabilities, Driver, HardwareAddress, LinkState}; +use embassy_net_driver::{Capabilities, Driver, HardwareAddress, LinkState}; use log::*; /// Get the MTU of the given interface. @@ -152,8 +152,14 @@ impl TunTapDevice { } impl Driver for TunTapDevice { - type RxToken<'a> = RxToken where Self: 'a; - type TxToken<'a> = TxToken<'a> where Self: 'a; + type RxToken<'a> + = RxToken + where + Self: 'a; + type TxToken<'a> + = TxToken<'a> + where + Self: 'a; fn receive(&mut self, cx: &mut Context) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> { let mut buf = vec![0; self.device.get_ref().mtu]; diff --git a/embassy-net-wiznet/Cargo.toml b/embassy-net-wiznet/Cargo.toml index f87bf2bd0..e7fb3f455 100644 --- a/embassy-net-wiznet/Cargo.toml +++ b/embassy-net-wiznet/Cargo.toml @@ -12,8 +12,8 @@ documentation = "https://docs.embassy.dev/embassy-net-wiznet" [dependencies] embedded-hal = { version = "1.0" } embedded-hal-async = { version = "1.0" } -embassy-net-driver-channel = { version = "0.2.0", path = "../embassy-net-driver-channel" } -embassy-time = { version = "0.3.0", path = "../embassy-time" } +embassy-net-driver-channel = { version = "0.3.0", path = "../embassy-net-driver-channel" } +embassy-time = { version = "0.3.2", path = "../embassy-time" } embassy-futures = { version = "0.1.0", path = "../embassy-futures" } defmt = { version = "0.3", optional = true } diff --git a/embassy-net-wiznet/src/chip/mod.rs b/embassy-net-wiznet/src/chip/mod.rs index b987c2b36..2e7a9ed6c 100644 --- a/embassy-net-wiznet/src/chip/mod.rs +++ b/embassy-net-wiznet/src/chip/mod.rs @@ -2,49 +2,47 @@ mod w5500; pub use w5500::W5500; mod w5100s; +use embedded_hal_async::spi::SpiDevice; pub use w5100s::W5100S; -pub(crate) mod sealed { - use embedded_hal_async::spi::SpiDevice; +pub(crate) trait SealedChip { + type Address; - pub trait Chip { - type Address; + /// The version of the chip as reported by the VERSIONR register. + /// This is used to verify that the chip is supported by the driver, + /// and that SPI communication is working. + const CHIP_VERSION: u8; - const COMMON_MODE: Self::Address; - const COMMON_MAC: Self::Address; - const COMMON_SOCKET_INTR: Self::Address; - const COMMON_PHY_CFG: Self::Address; - const SOCKET_MODE: Self::Address; - const SOCKET_COMMAND: Self::Address; - const SOCKET_RXBUF_SIZE: Self::Address; - const SOCKET_TXBUF_SIZE: Self::Address; - const SOCKET_TX_FREE_SIZE: Self::Address; - const SOCKET_TX_DATA_WRITE_PTR: Self::Address; - const SOCKET_RECVD_SIZE: Self::Address; - const SOCKET_RX_DATA_READ_PTR: Self::Address; - const SOCKET_INTR_MASK: Self::Address; - const SOCKET_INTR: Self::Address; + const COMMON_MODE: Self::Address; + const COMMON_MAC: Self::Address; + const COMMON_SOCKET_INTR: Self::Address; + const COMMON_PHY_CFG: Self::Address; + const COMMON_VERSION: Self::Address; - const SOCKET_MODE_VALUE: u8; + const SOCKET_MODE: Self::Address; + const SOCKET_COMMAND: Self::Address; + const SOCKET_RXBUF_SIZE: Self::Address; + const SOCKET_TXBUF_SIZE: Self::Address; + const SOCKET_TX_FREE_SIZE: Self::Address; + const SOCKET_TX_DATA_WRITE_PTR: Self::Address; + const SOCKET_RECVD_SIZE: Self::Address; + const SOCKET_RX_DATA_READ_PTR: Self::Address; + const SOCKET_INTR_MASK: Self::Address; + const SOCKET_INTR: Self::Address; - const BUF_SIZE: u16; - const AUTO_WRAP: bool; + const SOCKET_MODE_VALUE: u8; - fn rx_addr(addr: u16) -> Self::Address; - fn tx_addr(addr: u16) -> Self::Address; + const BUF_SIZE: u16; + const AUTO_WRAP: bool; - async fn bus_read( - spi: &mut SPI, - address: Self::Address, - data: &mut [u8], - ) -> Result<(), SPI::Error>; - async fn bus_write( - spi: &mut SPI, - address: Self::Address, - data: &[u8], - ) -> Result<(), SPI::Error>; - } + fn rx_addr(addr: u16) -> Self::Address; + fn tx_addr(addr: u16) -> Self::Address; + + async fn bus_read(spi: &mut SPI, address: Self::Address, data: &mut [u8]) + -> Result<(), SPI::Error>; + async fn bus_write(spi: &mut SPI, address: Self::Address, data: &[u8]) -> Result<(), SPI::Error>; } /// Trait for Wiznet chips. -pub trait Chip: sealed::Chip {} +#[allow(private_bounds)] +pub trait Chip: SealedChip {} diff --git a/embassy-net-wiznet/src/chip/w5100s.rs b/embassy-net-wiznet/src/chip/w5100s.rs index 7d328bce5..4c4b7ab16 100644 --- a/embassy-net-wiznet/src/chip/w5100s.rs +++ b/embassy-net-wiznet/src/chip/w5100s.rs @@ -8,13 +8,16 @@ const RX_BASE: u16 = 0x6000; pub enum W5100S {} impl super::Chip for W5100S {} -impl super::sealed::Chip for W5100S { +impl super::SealedChip for W5100S { type Address = u16; + const CHIP_VERSION: u8 = 0x51; + const COMMON_MODE: Self::Address = 0x00; const COMMON_MAC: Self::Address = 0x09; const COMMON_SOCKET_INTR: Self::Address = 0x16; const COMMON_PHY_CFG: Self::Address = 0x3c; + const COMMON_VERSION: Self::Address = 0x80; const SOCKET_MODE: Self::Address = SOCKET_BASE + 0x00; const SOCKET_COMMAND: Self::Address = SOCKET_BASE + 0x01; diff --git a/embassy-net-wiznet/src/chip/w5500.rs b/embassy-net-wiznet/src/chip/w5500.rs index 16236126d..5cfcb94e4 100644 --- a/embassy-net-wiznet/src/chip/w5500.rs +++ b/embassy-net-wiznet/src/chip/w5500.rs @@ -12,13 +12,16 @@ pub enum RegisterBlock { pub enum W5500 {} impl super::Chip for W5500 {} -impl super::sealed::Chip for W5500 { +impl super::SealedChip for W5500 { type Address = (RegisterBlock, u16); + const CHIP_VERSION: u8 = 0x04; + const COMMON_MODE: Self::Address = (RegisterBlock::Common, 0x00); const COMMON_MAC: Self::Address = (RegisterBlock::Common, 0x09); const COMMON_SOCKET_INTR: Self::Address = (RegisterBlock::Common, 0x18); const COMMON_PHY_CFG: Self::Address = (RegisterBlock::Common, 0x2E); + const COMMON_VERSION: Self::Address = (RegisterBlock::Common, 0x39); const SOCKET_MODE: Self::Address = (RegisterBlock::Socket0, 0x00); const SOCKET_COMMAND: Self::Address = (RegisterBlock::Socket0, 0x01); diff --git a/embassy-net-wiznet/src/device.rs b/embassy-net-wiznet/src/device.rs index 43f9512a3..d2b6bb0c3 100644 --- a/embassy-net-wiznet/src/device.rs +++ b/embassy-net-wiznet/src/device.rs @@ -24,9 +24,57 @@ pub(crate) struct WiznetDevice { _phantom: PhantomData, } +/// Error type when initializing a new Wiznet device +pub enum InitError { + /// Error occurred when sending or receiving SPI data + SpiError(SE), + /// The chip returned a version that isn't expected or supported + InvalidChipVersion { + /// The version that is supported + expected: u8, + /// The version that was returned by the chip + actual: u8, + }, +} + +impl From for InitError { + fn from(e: SE) -> Self { + InitError::SpiError(e) + } +} + +impl core::fmt::Debug for InitError +where + SE: core::fmt::Debug, +{ + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + InitError::SpiError(e) => write!(f, "SpiError({:?})", e), + InitError::InvalidChipVersion { expected, actual } => { + write!(f, "InvalidChipVersion {{ expected: {}, actual: {} }}", expected, actual) + } + } + } +} + +#[cfg(feature = "defmt")] +impl defmt::Format for InitError +where + SE: defmt::Format, +{ + fn format(&self, f: defmt::Formatter) { + match self { + InitError::SpiError(e) => defmt::write!(f, "SpiError({})", e), + InitError::InvalidChipVersion { expected, actual } => { + defmt::write!(f, "InvalidChipVersion {{ expected: {}, actual: {} }}", expected, actual) + } + } + } +} + impl WiznetDevice { /// Create and initialize the driver - pub async fn new(spi: SPI, mac_addr: [u8; 6]) -> Result { + pub async fn new(spi: SPI, mac_addr: [u8; 6]) -> Result> { let mut this = Self { spi, _phantom: PhantomData, @@ -35,6 +83,18 @@ impl WiznetDevice { // Reset device this.bus_write(C::COMMON_MODE, &[0x80]).await?; + // Check the version of the chip + let mut version = [0]; + this.bus_read(C::COMMON_VERSION, &mut version).await?; + if version[0] != C::CHIP_VERSION { + #[cfg(feature = "defmt")] + defmt::error!("invalid chip version: {} (expected {})", version[0], C::CHIP_VERSION); + return Err(InitError::InvalidChipVersion { + actual: version[0], + expected: C::CHIP_VERSION, + }); + } + // Enable interrupt pin this.bus_write(C::COMMON_SOCKET_INTR, &[0x01]).await?; // Enable receive interrupt diff --git a/embassy-net-wiznet/src/lib.rs b/embassy-net-wiznet/src/lib.rs index da70d22bd..3fbd4c741 100644 --- a/embassy-net-wiznet/src/lib.rs +++ b/embassy-net-wiznet/src/lib.rs @@ -15,14 +15,25 @@ use embedded_hal_async::digital::Wait; use embedded_hal_async::spi::SpiDevice; use crate::chip::Chip; +pub use crate::device::InitError; use crate::device::WiznetDevice; +// If you change this update the docs of State const MTU: usize = 1514; /// Type alias for the embassy-net driver. pub type Device<'d> = embassy_net_driver_channel::Device<'d, MTU>; /// Internal state for the embassy-net integration. +/// +/// The two generic arguments `N_RX` and `N_TX` set the size of the receive and +/// send packet queue. With a the ethernet MTU of _1514_ this takes up `N_RX + +/// NTX * 1514` bytes. While setting these both to 1 is the minimum this might +/// hurt performance as a packet can not be received while processing another. +/// +/// # Warning +/// On devices with a small amount of ram (think ~64k) watch out with the size +/// of there parameters. They will quickly use too much RAM. pub struct State { ch_state: ch::State, } @@ -95,7 +106,7 @@ pub async fn new<'a, const N_RX: usize, const N_TX: usize, C: Chip, SPI: SpiDevi spi_dev: SPI, int: INT, mut reset: RST, -) -> (Device<'a>, Runner<'a, C, SPI, INT, RST>) { +) -> Result<(Device<'a>, Runner<'a, C, SPI, INT, RST>), InitError> { // Reset the chip. reset.set_low().ok(); // Ensure the reset is registered. @@ -106,10 +117,11 @@ pub async fn new<'a, const N_RX: usize, const N_TX: usize, C: Chip, SPI: SpiDevi // Slowest is w5100s which is 100ms, so let's just wait that. Timer::after_millis(100).await; - let mac = WiznetDevice::new(spi_dev, mac_addr).await.unwrap(); + let mac = WiznetDevice::new(spi_dev, mac_addr).await?; let (runner, device) = ch::new(&mut state.ch_state, ch::driver::HardwareAddress::Ethernet(mac_addr)); - ( + + Ok(( device, Runner { ch: runner, @@ -117,5 +129,5 @@ pub async fn new<'a, const N_RX: usize, const N_TX: usize, C: Chip, SPI: SpiDevi int, _reset: reset, }, - ) + )) } diff --git a/embassy-net/Cargo.toml b/embassy-net/Cargo.toml index 44bd2e8f3..1090892e0 100644 --- a/embassy-net/Cargo.toml +++ b/embassy-net/Cargo.toml @@ -16,18 +16,18 @@ categories = [ [package.metadata.embassy_docs] src_base = "https://github.com/embassy-rs/embassy/blob/embassy-net-v$VERSION/embassy-net/src/" src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/embassy-net/src/" -features = ["defmt", "tcp", "udp", "dns", "dhcpv4", "proto-ipv6", "medium-ethernet", "medium-ip", "medium-ieee802154", "igmp"] +features = ["defmt", "tcp", "udp", "raw", "dns", "dhcpv4", "proto-ipv6", "medium-ethernet", "medium-ip", "medium-ieee802154", "multicast", "dhcpv4-hostname"] target = "thumbv7em-none-eabi" [package.metadata.docs.rs] -features = ["defmt", "tcp", "udp", "dns", "dhcpv4", "proto-ipv6", "medium-ethernet", "medium-ip", "medium-ieee802154", "igmp"] +features = ["defmt", "tcp", "udp", "raw", "dns", "dhcpv4", "proto-ipv6", "medium-ethernet", "medium-ip", "medium-ieee802154", "multicast", "dhcpv4-hostname"] [features] default = [] std = [] ## Enable defmt -defmt = ["dep:defmt", "smoltcp/defmt", "embassy-net-driver/defmt", "heapless/defmt-03"] +defmt = ["dep:defmt", "smoltcp/defmt", "embassy-net-driver/defmt", "heapless/defmt-03", "defmt?/ip_in_core"] ## Trace all raw received and transmitted packets using defmt or log. packet-trace = [] @@ -38,10 +38,14 @@ packet-trace = [] ## Enable UDP support udp = ["smoltcp/socket-udp"] +## Enable Raw support +raw = ["smoltcp/socket-raw"] ## Enable TCP support tcp = ["smoltcp/socket-tcp"] ## Enable DNS support dns = ["smoltcp/socket-dns", "smoltcp/proto-dns"] +## Enable mDNS support +mdns = ["dns", "smoltcp/socket-mdns"] ## Enable DHCPv4 support dhcpv4 = ["proto-ipv4", "medium-ethernet", "smoltcp/socket-dhcpv4"] ## Enable DHCPv4 support with hostname @@ -56,30 +60,25 @@ medium-ethernet = ["smoltcp/medium-ethernet"] medium-ip = ["smoltcp/medium-ip"] ## Enable the IEEE 802.15.4 medium medium-ieee802154 = ["smoltcp/medium-ieee802154"] -## Enable IGMP support -igmp = ["smoltcp/proto-igmp"] +## Enable multicast support (for both ipv4 and/or ipv6 if enabled) +multicast = ["smoltcp/multicast"] [dependencies] -defmt = { version = "0.3", optional = true } +defmt = { version = "0.3.8", optional = true } log = { version = "0.4.14", optional = true } -smoltcp = { version = "0.11.0", default-features = false, features = [ +smoltcp = { git="https://github.com/smoltcp-rs/smoltcp", rev="fe0b4d102253465850cd1cf39cd33d4721a4a8d5", default-features = false, features = [ "socket", "async", ] } embassy-net-driver = { version = "0.2.0", path = "../embassy-net-driver" } -embassy-time = { version = "0.3.0", path = "../embassy-time" } -embassy-sync = { version = "0.5.0", path = "../embassy-sync" } +embassy-time = { version = "0.3.2", path = "../embassy-time" } +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } embedded-io-async = { version = "0.6.1" } managed = { version = "0.8.0", default-features = false, features = [ "map" ] } heapless = { version = "0.8", default-features = false } -as-slice = "0.2.1" -generic-array = { version = "0.14.4", default-features = false } -stable_deref_trait = { version = "1.2.0", default-features = false } -futures = { version = "0.3.17", default-features = false, features = [ "async-await" ] } -atomic-pool = "1.0" -embedded-nal-async = { version = "0.7.1" } +embedded-nal-async = "0.8.0" document-features = "0.2.7" diff --git a/embassy-net/README.md b/embassy-net/README.md index 94aa6f550..1722ffc7b 100644 --- a/embassy-net/README.md +++ b/embassy-net/README.md @@ -10,11 +10,12 @@ memory management designed to work well for embedded systems, aiming for a more - IPv4, IPv6 - Ethernet and bare-IP mediums. -- TCP, UDP, DNS, DHCPv4, IGMPv4 +- TCP, UDP, DNS, DHCPv4 - TCP sockets implement the `embedded-io` async traits. +- Multicast -See the [`smoltcp`](https://github.com/smoltcp-rs/smoltcp) README for a detailed list of implemented and -unimplemented features of the network protocols. +See the [`smoltcp`](https://github.com/smoltcp-rs/smoltcp) README for a detailed list of implemented and +unimplemented features of the network protocols. ## Hardware support @@ -37,7 +38,7 @@ To add `embassy-net` support for new hardware (i.e. a new Ethernet or WiFi chip, an Ethernet/WiFi MCU peripheral), you have to implement the [`embassy-net-driver`](https://crates.io/crates/embassy-net-driver) traits. -Alternatively, [`embassy-net-driver-channel`](https://crates.io/crates/embassy-net-driver-channel) provides a higer-level API +Alternatively, [`embassy-net-driver-channel`](https://crates.io/crates/embassy-net-driver-channel) provides a higher-level API to construct a driver that processes packets in its own background task and communicates with the `embassy-net` task via packet queues for RX and TX. diff --git a/embassy-net/src/dns.rs b/embassy-net/src/dns.rs index a1151d5e4..dbe73776c 100644 --- a/embassy-net/src/dns.rs +++ b/embassy-net/src/dns.rs @@ -9,7 +9,7 @@ pub use smoltcp::socket::dns::{DnsQuery, Socket}; pub(crate) use smoltcp::socket::dns::{GetQueryResultError, StartQueryError}; pub use smoltcp::wire::{DnsQueryType, IpAddress}; -use crate::{Driver, Stack}; +use crate::Stack; /// Errors returned by DnsSocket. #[derive(Debug, PartialEq, Eq, Clone, Copy)] @@ -44,21 +44,15 @@ impl From for Error { /// This exists only for compatibility with crates that use `embedded-nal-async`. /// Prefer using [`Stack::dns_query`](crate::Stack::dns_query) directly if you're /// not using `embedded-nal-async`. -pub struct DnsSocket<'a, D> -where - D: Driver + 'static, -{ - stack: &'a Stack, +pub struct DnsSocket<'a> { + stack: Stack<'a>, } -impl<'a, D> DnsSocket<'a, D> -where - D: Driver + 'static, -{ +impl<'a> DnsSocket<'a> { /// Create a new DNS socket using the provided stack. /// /// NOTE: If using DHCP, make sure it has reconfigured the stack to ensure the DNS servers are updated. - pub fn new(stack: &'a Stack) -> Self { + pub fn new(stack: Stack<'a>) -> Self { Self { stack } } @@ -72,40 +66,55 @@ where } } -impl<'a, D> embedded_nal_async::Dns for DnsSocket<'a, D> -where - D: Driver + 'static, -{ +impl<'a> embedded_nal_async::Dns for DnsSocket<'a> { type Error = Error; async fn get_host_by_name( &self, host: &str, addr_type: embedded_nal_async::AddrType, - ) -> Result { - use embedded_nal_async::{AddrType, IpAddr}; - let qtype = match addr_type { - AddrType::IPv6 => DnsQueryType::Aaaa, - _ => DnsQueryType::A, + ) -> Result { + use core::net::IpAddr; + + use embedded_nal_async::AddrType; + + let (qtype, secondary_qtype) = match addr_type { + AddrType::IPv4 => (DnsQueryType::A, None), + AddrType::IPv6 => (DnsQueryType::Aaaa, None), + AddrType::Either => { + #[cfg(not(feature = "proto-ipv6"))] + let v6_first = false; + #[cfg(feature = "proto-ipv6")] + let v6_first = self.stack.config_v6().is_some(); + match v6_first { + true => (DnsQueryType::Aaaa, Some(DnsQueryType::A)), + false => (DnsQueryType::A, Some(DnsQueryType::Aaaa)), + } + } }; - let addrs = self.query(host, qtype).await?; + let mut addrs = self.query(host, qtype).await?; + if addrs.is_empty() { + if let Some(qtype) = secondary_qtype { + addrs = self.query(host, qtype).await? + } + } if let Some(first) = addrs.get(0) { Ok(match first { #[cfg(feature = "proto-ipv4")] - IpAddress::Ipv4(addr) => IpAddr::V4(addr.0.into()), + IpAddress::Ipv4(addr) => IpAddr::V4(*addr), #[cfg(feature = "proto-ipv6")] - IpAddress::Ipv6(addr) => IpAddr::V6(addr.0.into()), + IpAddress::Ipv6(addr) => IpAddr::V6(*addr), }) } else { Err(Error::Failed) } } - async fn get_host_by_address( - &self, - _addr: embedded_nal_async::IpAddr, - _result: &mut [u8], - ) -> Result { + async fn get_host_by_address(&self, _addr: core::net::IpAddr, _result: &mut [u8]) -> Result { todo!() } } + +fn _assert_covariant<'a, 'b: 'a>(x: DnsSocket<'b>) -> DnsSocket<'a> { + x +} diff --git a/embassy-net/src/device.rs b/embassy-net/src/driver_util.rs similarity index 89% rename from embassy-net/src/device.rs rename to embassy-net/src/driver_util.rs index 3b1d3c47c..536f4c3d9 100644 --- a/embassy-net/src/device.rs +++ b/embassy-net/src/driver_util.rs @@ -18,8 +18,14 @@ impl<'d, 'c, T> phy::Device for DriverAdapter<'d, 'c, T> where T: Driver, { - type RxToken<'a> = RxTokenAdapter> where Self: 'a; - type TxToken<'a> = TxTokenAdapter> where Self: 'a; + type RxToken<'a> + = RxTokenAdapter> + where + Self: 'a; + type TxToken<'a> + = TxTokenAdapter> + where + Self: 'a; fn receive(&mut self, _timestamp: Instant) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> { self.inner @@ -74,11 +80,11 @@ where { fn consume(self, f: F) -> R where - F: FnOnce(&mut [u8]) -> R, + F: FnOnce(&[u8]) -> R, { self.0.consume(|buf| { #[cfg(feature = "packet-trace")] - trace!("rx: {:?}", buf); + trace!("embassy device rx: {:02x}", buf); f(buf) }) } @@ -99,7 +105,7 @@ where self.0.consume(len, |buf| { let r = f(buf); #[cfg(feature = "packet-trace")] - trace!("tx: {:?}", buf); + trace!("embassy device tx: {:02x}", buf); r }) } diff --git a/embassy-net/src/fmt.rs b/embassy-net/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-net/src/fmt.rs +++ b/embassy-net/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-net/src/lib.rs b/embassy-net/src/lib.rs index 1c0cf1a12..ec7f10fdd 100644 --- a/embassy-net/src/lib.rs +++ b/embassy-net/src/lib.rs @@ -12,9 +12,11 @@ compile_error!("You must enable at least one of the following features: proto-ip // This mod MUST go first, so that the others see its macros. pub(crate) mod fmt; -mod device; #[cfg(feature = "dns")] pub mod dns; +mod driver_util; +#[cfg(feature = "raw")] +pub mod raw; #[cfg(feature = "tcp")] pub mod tcp; mod time; @@ -23,19 +25,22 @@ pub mod udp; use core::cell::RefCell; use core::future::{poll_fn, Future}; +use core::mem::MaybeUninit; +use core::pin::pin; use core::task::{Context, Poll}; pub use embassy_net_driver as driver; use embassy_net_driver::{Driver, LinkState}; use embassy_sync::waitqueue::WakerRegistration; use embassy_time::{Instant, Timer}; -use futures::pin_mut; -#[allow(unused_imports)] use heapless::Vec; -#[cfg(feature = "igmp")] +#[cfg(feature = "dns")] +pub use smoltcp::config::DNS_MAX_SERVER_COUNT; +#[cfg(feature = "multicast")] pub use smoltcp::iface::MulticastError; -#[allow(unused_imports)] -use smoltcp::iface::{Interface, SocketHandle, SocketSet, SocketStorage}; +#[cfg(any(feature = "dns", feature = "dhcpv4"))] +use smoltcp::iface::SocketHandle; +use smoltcp::iface::{Interface, SocketSet, SocketStorage}; use smoltcp::phy::Medium; #[cfg(feature = "dhcpv4")] use smoltcp::socket::dhcpv4::{self, RetryConfig}; @@ -53,7 +58,7 @@ pub use smoltcp::wire::{Ipv4Address, Ipv4Cidr}; #[cfg(feature = "proto-ipv6")] pub use smoltcp::wire::{Ipv6Address, Ipv6Cidr}; -use crate::device::DriverAdapter; +use crate::driver_util::DriverAdapter; use crate::time::{instant_from_smoltcp, instant_to_smoltcp}; const LOCAL_PORT_MIN: u16 = 1025; @@ -65,33 +70,33 @@ const MAX_HOSTNAME_LEN: usize = 32; /// Memory resources needed for a network stack. pub struct StackResources { - sockets: [SocketStorage<'static>; SOCK], + sockets: MaybeUninit<[SocketStorage<'static>; SOCK]>, + inner: MaybeUninit>, #[cfg(feature = "dns")] - queries: [Option; MAX_QUERIES], + queries: MaybeUninit<[Option; MAX_QUERIES]>, #[cfg(feature = "dhcpv4-hostname")] - hostname: core::cell::UnsafeCell, + hostname: HostnameResources, } #[cfg(feature = "dhcpv4-hostname")] struct HostnameResources { - option: smoltcp::wire::DhcpOption<'static>, - data: [u8; MAX_HOSTNAME_LEN], + option: MaybeUninit>, + data: MaybeUninit<[u8; MAX_HOSTNAME_LEN]>, } impl StackResources { /// Create a new set of stack resources. pub const fn new() -> Self { - #[cfg(feature = "dns")] - const INIT: Option = None; Self { - sockets: [SocketStorage::EMPTY; SOCK], + sockets: MaybeUninit::uninit(), + inner: MaybeUninit::uninit(), #[cfg(feature = "dns")] - queries: [INIT; MAX_QUERIES], + queries: MaybeUninit::uninit(), #[cfg(feature = "dhcpv4-hostname")] - hostname: core::cell::UnsafeCell::new(HostnameResources { - option: smoltcp::wire::DhcpOption { kind: 0, data: &[] }, - data: [0; MAX_HOSTNAME_LEN], - }), + hostname: HostnameResources { + option: MaybeUninit::uninit(), + data: MaybeUninit::uninit(), + }, } } } @@ -235,16 +240,32 @@ pub enum ConfigV6 { Static(StaticConfigV6), } -/// A network stack. +/// Network stack runner. /// -/// This is the main entry point for the network stack. -pub struct Stack { - pub(crate) socket: RefCell, - inner: RefCell>, +/// You must call [`Runner::run()`] in a background task for the network stack to work. +pub struct Runner<'d, D: Driver> { + driver: D, + stack: Stack<'d>, } -struct Inner { - device: D, +/// Network stack handle +/// +/// Use this to create sockets. It's `Copy`, so you can pass +/// it by value instead of by reference. +#[derive(Copy, Clone)] +pub struct Stack<'d> { + inner: &'d RefCell, +} + +pub(crate) struct Inner { + pub(crate) sockets: SocketSet<'static>, // Lifetime type-erased. + pub(crate) iface: Interface, + /// Waker used for triggering polls. + pub(crate) waker: WakerRegistration, + /// Waker used for waiting for link up or config up. + state_waker: WakerRegistration, + hardware_address: HardwareAddress, + next_local_port: u16, link_up: bool, #[cfg(feature = "proto-ipv4")] static_v4: Option, @@ -252,20 +273,88 @@ struct Inner { static_v6: Option, #[cfg(feature = "dhcpv4")] dhcp_socket: Option, - config_waker: WakerRegistration, #[cfg(feature = "dns")] dns_socket: SocketHandle, #[cfg(feature = "dns")] dns_waker: WakerRegistration, #[cfg(feature = "dhcpv4-hostname")] - hostname: &'static mut core::cell::UnsafeCell, + hostname: *mut HostnameResources, } -pub(crate) struct SocketStack { - pub(crate) sockets: SocketSet<'static>, - pub(crate) iface: Interface, - pub(crate) waker: WakerRegistration, - next_local_port: u16, +fn _assert_covariant<'a, 'b: 'a>(x: Stack<'b>) -> Stack<'a> { + x +} + +/// Create a new network stack. +pub fn new<'d, D: Driver, const SOCK: usize>( + mut driver: D, + config: Config, + resources: &'d mut StackResources, + random_seed: u64, +) -> (Stack<'d>, Runner<'d, D>) { + let (hardware_address, medium) = to_smoltcp_hardware_address(driver.hardware_address()); + let mut iface_cfg = smoltcp::iface::Config::new(hardware_address); + iface_cfg.random_seed = random_seed; + + let iface = Interface::new( + iface_cfg, + &mut DriverAdapter { + inner: &mut driver, + cx: None, + medium, + }, + instant_to_smoltcp(Instant::now()), + ); + + unsafe fn transmute_slice(x: &mut [T]) -> &'static mut [T] { + core::mem::transmute(x) + } + + let sockets = resources.sockets.write([SocketStorage::EMPTY; SOCK]); + #[allow(unused_mut)] + let mut sockets: SocketSet<'static> = SocketSet::new(unsafe { transmute_slice(sockets) }); + + let next_local_port = (random_seed % (LOCAL_PORT_MAX - LOCAL_PORT_MIN) as u64) as u16 + LOCAL_PORT_MIN; + + #[cfg(feature = "dns")] + let dns_socket = sockets.add(dns::Socket::new( + &[], + managed::ManagedSlice::Borrowed(unsafe { + transmute_slice(resources.queries.write([const { None }; MAX_QUERIES])) + }), + )); + + let mut inner = Inner { + sockets, + iface, + waker: WakerRegistration::new(), + state_waker: WakerRegistration::new(), + next_local_port, + hardware_address, + link_up: false, + #[cfg(feature = "proto-ipv4")] + static_v4: None, + #[cfg(feature = "proto-ipv6")] + static_v6: None, + #[cfg(feature = "dhcpv4")] + dhcp_socket: None, + #[cfg(feature = "dns")] + dns_socket, + #[cfg(feature = "dns")] + dns_waker: WakerRegistration::new(), + #[cfg(feature = "dhcpv4-hostname")] + hostname: &mut resources.hostname, + }; + + #[cfg(feature = "proto-ipv4")] + inner.set_config_v4(config.ipv4); + #[cfg(feature = "proto-ipv6")] + inner.set_config_v6(config.ipv6); + inner.apply_static_config(); + + let inner = &*resources.inner.write(RefCell::new(inner)); + let stack = Stack { inner }; + (stack, Runner { driver, stack }) } fn to_smoltcp_hardware_address(addr: driver::HardwareAddress) -> (HardwareAddress, Medium) { @@ -288,92 +377,26 @@ fn to_smoltcp_hardware_address(addr: driver::HardwareAddress) -> (HardwareAddres } } -impl Stack { - /// Create a new network stack. - pub fn new( - mut device: D, - config: Config, - resources: &'static mut StackResources, - random_seed: u64, - ) -> Self { - let (hardware_addr, medium) = to_smoltcp_hardware_address(device.hardware_address()); - let mut iface_cfg = smoltcp::iface::Config::new(hardware_addr); - iface_cfg.random_seed = random_seed; - - let iface = Interface::new( - iface_cfg, - &mut DriverAdapter { - inner: &mut device, - cx: None, - medium, - }, - instant_to_smoltcp(Instant::now()), - ); - - let sockets = SocketSet::new(&mut resources.sockets[..]); - - let next_local_port = (random_seed % (LOCAL_PORT_MAX - LOCAL_PORT_MIN) as u64) as u16 + LOCAL_PORT_MIN; - - #[cfg_attr(feature = "medium-ieee802154", allow(unused_mut))] - let mut socket = SocketStack { - sockets, - iface, - waker: WakerRegistration::new(), - next_local_port, - }; - - let mut inner = Inner { - device, - link_up: false, - #[cfg(feature = "proto-ipv4")] - static_v4: None, - #[cfg(feature = "proto-ipv6")] - static_v6: None, - #[cfg(feature = "dhcpv4")] - dhcp_socket: None, - config_waker: WakerRegistration::new(), - #[cfg(feature = "dns")] - dns_socket: socket.sockets.add(dns::Socket::new( - &[], - managed::ManagedSlice::Borrowed(&mut resources.queries), - )), - #[cfg(feature = "dns")] - dns_waker: WakerRegistration::new(), - #[cfg(feature = "dhcpv4-hostname")] - hostname: &mut resources.hostname, - }; - - #[cfg(feature = "proto-ipv4")] - inner.set_config_v4(&mut socket, config.ipv4); - #[cfg(feature = "proto-ipv6")] - inner.set_config_v6(&mut socket, config.ipv6); - inner.apply_static_config(&mut socket); - - Self { - socket: RefCell::new(socket), - inner: RefCell::new(inner), - } +impl<'d> Stack<'d> { + fn with(&self, f: impl FnOnce(&Inner) -> R) -> R { + f(&self.inner.borrow()) } - fn with(&self, f: impl FnOnce(&SocketStack, &Inner) -> R) -> R { - f(&*self.socket.borrow(), &*self.inner.borrow()) - } - - fn with_mut(&self, f: impl FnOnce(&mut SocketStack, &mut Inner) -> R) -> R { - f(&mut *self.socket.borrow_mut(), &mut *self.inner.borrow_mut()) + fn with_mut(&self, f: impl FnOnce(&mut Inner) -> R) -> R { + f(&mut self.inner.borrow_mut()) } /// Get the hardware address of the network interface. pub fn hardware_address(&self) -> HardwareAddress { - self.with(|_s, i| to_smoltcp_hardware_address(i.device.hardware_address()).0) + self.with(|i| i.hardware_address) } - /// Get whether the link is up. + /// Check whether the link is up. pub fn is_link_up(&self) -> bool { - self.with(|_s, i| i.link_up) + self.with(|i| i.link_up) } - /// Get whether the network stack has a valid IP configuration. + /// Check whether the network stack has a valid IP configuration. /// This is true if the network stack has a static IP configuration or if DHCP has completed pub fn is_config_up(&self) -> bool { let v4_up; @@ -400,10 +423,20 @@ impl Stack { v4_up || v6_up } + /// Wait for the network device to obtain a link signal. + pub async fn wait_link_up(&self) { + self.wait(|| self.is_link_up()).await + } + + /// Wait for the network device to lose link signal. + pub async fn wait_link_down(&self) { + self.wait(|| !self.is_link_up()).await + } + /// Wait for the network stack to obtain a valid IP configuration. /// /// ## Notes: - /// - Ensure [`Stack::run`] has been called before using this function. + /// - Ensure [`Runner::run`] has been started before using this function. /// /// - This function may never return (e.g. if no configuration is obtained through DHCP). /// The caller is supposed to handle a timeout for this case. @@ -411,44 +444,49 @@ impl Stack { /// ## Example /// ```ignore /// let config = embassy_net::Config::dhcpv4(Default::default()); - ///// Init network stack - /// static RESOURCES: StaticCell = StaticCell::new(); - /// static STACK: StaticCell = StaticCell::new(); - /// let stack = &*STACK.init(embassy_net::Stack::new( - /// device, + /// // Init network stack + /// // NOTE: DHCP and DNS need one socket slot if enabled. This is why we're + /// // provisioning space for 3 sockets here: one for DHCP, one for DNS, and one for your code (e.g. TCP). + /// // If you use more sockets you must increase this. If you don't enable DHCP or DNS you can decrease it. + /// static RESOURCES: StaticCell> = StaticCell::new(); + /// let (stack, runner) = embassy_net::new( + /// driver, /// config, /// RESOURCES.init(embassy_net::StackResources::new()), /// seed - /// )); - /// // Launch network task that runs `stack.run().await` - /// spawner.spawn(net_task(stack)).unwrap(); + /// ); + /// // Launch network task that runs `runner.run().await` + /// spawner.spawn(net_task(runner)).unwrap(); /// // Wait for DHCP config /// stack.wait_config_up().await; /// // use the network stack /// // ... /// ``` pub async fn wait_config_up(&self) { - // If the config is up already, we can return immediately. - if self.is_config_up() { - return; - } + self.wait(|| self.is_config_up()).await + } - poll_fn(|cx| { - if self.is_config_up() { + /// Wait for the network stack to lose a valid IP configuration. + pub async fn wait_config_down(&self) { + self.wait(|| !self.is_config_up()).await + } + + fn wait<'a>(&'a self, mut predicate: impl FnMut() -> bool + 'a) -> impl Future + 'a { + poll_fn(move |cx| { + if predicate() { Poll::Ready(()) } else { // If the config is not up, we register a waker that is woken up // when a config is applied (static or DHCP). trace!("Waiting for config up"); - self.with_mut(|_, i| { - i.config_waker.register(cx.waker()); + self.with_mut(|i| { + i.state_waker.register(cx.waker()); }); Poll::Pending } }) - .await; } /// Get the current IPv4 configuration. @@ -457,45 +495,33 @@ impl Stack { /// acquire an IP address, or Some if it has. #[cfg(feature = "proto-ipv4")] pub fn config_v4(&self) -> Option { - self.with(|_, i| i.static_v4.clone()) + self.with(|i| i.static_v4.clone()) } /// Get the current IPv6 configuration. #[cfg(feature = "proto-ipv6")] pub fn config_v6(&self) -> Option { - self.with(|_, i| i.static_v6.clone()) + self.with(|i| i.static_v6.clone()) } /// Set the IPv4 configuration. #[cfg(feature = "proto-ipv4")] pub fn set_config_v4(&self, config: ConfigV4) { - self.with_mut(|s, i| { - i.set_config_v4(s, config); - i.apply_static_config(s); + self.with_mut(|i| { + i.set_config_v4(config); + i.apply_static_config(); }) } /// Set the IPv6 configuration. #[cfg(feature = "proto-ipv6")] pub fn set_config_v6(&self, config: ConfigV6) { - self.with_mut(|s, i| { - i.set_config_v6(s, config); - i.apply_static_config(s); + self.with_mut(|i| { + i.set_config_v6(config); + i.apply_static_config(); }) } - /// Run the network stack. - /// - /// You must call this in a background task, to process network events. - pub async fn run(&self) -> ! { - poll_fn(|cx| { - self.with_mut(|s, i| i.poll(cx, s)); - Poll::<()>::Pending - }) - .await; - unreachable!() - } - /// Make a query for a given name and return the corresponding IP addresses. #[cfg(feature = "dns")] pub async fn dns_query( @@ -521,11 +547,11 @@ impl Stack { } let query = poll_fn(|cx| { - self.with_mut(|s, i| { - let socket = s.sockets.get_mut::(i.dns_socket); - match socket.start_query(s.iface.context(), name, qtype) { + self.with_mut(|i| { + let socket = i.sockets.get_mut::(i.dns_socket); + match socket.start_query(i.iface.context(), name, qtype) { Ok(handle) => { - s.waker.wake(); + i.waker.wake(); Poll::Ready(Ok(handle)) } Err(dns::StartQueryError::NoFreeSlot) => { @@ -562,17 +588,17 @@ impl Stack { } let drop = OnDrop::new(|| { - self.with_mut(|s, i| { - let socket = s.sockets.get_mut::(i.dns_socket); + self.with_mut(|i| { + let socket = i.sockets.get_mut::(i.dns_socket); socket.cancel_query(query); - s.waker.wake(); + i.waker.wake(); i.dns_waker.wake(); }) }); let res = poll_fn(|cx| { - self.with_mut(|s, i| { - let socket = s.sockets.get_mut::(i.dns_socket); + self.with_mut(|i| { + let socket = i.sockets.get_mut::(i.dns_socket); match socket.get_query_result(query) { Ok(addrs) => { i.dns_waker.wake(); @@ -597,104 +623,34 @@ impl Stack { } } -#[cfg(feature = "igmp")] -impl Stack { +#[cfg(feature = "multicast")] +impl<'d> Stack<'d> { /// Join a multicast group. - pub async fn join_multicast_group(&self, addr: T) -> Result - where - T: Into, - { - let addr = addr.into(); - - poll_fn(move |cx| self.poll_join_multicast_group(addr, cx)).await - } - - /// Join a multicast group. - /// - /// When the send queue is full, this method will return `Poll::Pending` - /// and register the current task to be notified when the queue has space available. - pub fn poll_join_multicast_group(&self, addr: T, cx: &mut Context<'_>) -> Poll> - where - T: Into, - { - let addr = addr.into(); - - self.with_mut(|s, i| { - let (_hardware_addr, medium) = to_smoltcp_hardware_address(i.device.hardware_address()); - let mut smoldev = DriverAdapter { - cx: Some(cx), - inner: &mut i.device, - medium, - }; - - match s - .iface - .join_multicast_group(&mut smoldev, addr, instant_to_smoltcp(Instant::now())) - { - Ok(announce_sent) => Poll::Ready(Ok(announce_sent)), - Err(MulticastError::Exhausted) => Poll::Pending, - Err(other) => Poll::Ready(Err(other)), - } - }) + pub fn join_multicast_group(&self, addr: impl Into) -> Result<(), MulticastError> { + self.with_mut(|i| i.iface.join_multicast_group(addr)) } /// Leave a multicast group. - pub async fn leave_multicast_group(&self, addr: T) -> Result - where - T: Into, - { - let addr = addr.into(); - - poll_fn(move |cx| self.poll_leave_multicast_group(addr, cx)).await - } - - /// Leave a multicast group. - /// - /// When the send queue is full, this method will return `Poll::Pending` - /// and register the current task to be notified when the queue has space available. - pub fn poll_leave_multicast_group(&self, addr: T, cx: &mut Context<'_>) -> Poll> - where - T: Into, - { - let addr = addr.into(); - - self.with_mut(|s, i| { - let (_hardware_addr, medium) = to_smoltcp_hardware_address(i.device.hardware_address()); - let mut smoldev = DriverAdapter { - cx: Some(cx), - inner: &mut i.device, - medium, - }; - - match s - .iface - .leave_multicast_group(&mut smoldev, addr, instant_to_smoltcp(Instant::now())) - { - Ok(leave_sent) => Poll::Ready(Ok(leave_sent)), - Err(MulticastError::Exhausted) => Poll::Pending, - Err(other) => Poll::Ready(Err(other)), - } - }) + pub fn leave_multicast_group(&self, addr: impl Into) -> Result<(), MulticastError> { + self.with_mut(|i| i.iface.leave_multicast_group(addr)) } /// Get whether the network stack has joined the given multicast group. - pub fn has_multicast_group>(&self, addr: T) -> bool { - self.socket.borrow().iface.has_multicast_group(addr) + pub fn has_multicast_group(&self, addr: impl Into) -> bool { + self.with(|i| i.iface.has_multicast_group(addr)) } } -impl SocketStack { - #[allow(clippy::absurd_extreme_comparisons, dead_code)] +impl Inner { + #[allow(clippy::absurd_extreme_comparisons)] pub fn get_local_port(&mut self) -> u16 { let res = self.next_local_port; self.next_local_port = if res >= LOCAL_PORT_MAX { LOCAL_PORT_MIN } else { res + 1 }; res } -} -impl Inner { #[cfg(feature = "proto-ipv4")] - pub fn set_config_v4(&mut self, _s: &mut SocketStack, config: ConfigV4) { + pub fn set_config_v4(&mut self, config: ConfigV4) { // Handle static config. self.static_v4 = match config.clone() { ConfigV4::None => None, @@ -710,12 +666,12 @@ impl Inner { // Create the socket if it doesn't exist. if self.dhcp_socket.is_none() { let socket = smoltcp::socket::dhcpv4::Socket::new(); - let handle = _s.sockets.add(socket); + let handle = self.sockets.add(socket); self.dhcp_socket = Some(handle); } // Configure it - let socket = _s.sockets.get_mut::(unwrap!(self.dhcp_socket)); + let socket = self.sockets.get_mut::(unwrap!(self.dhcp_socket)); socket.set_ignore_naks(c.ignore_naks); socket.set_max_lease_duration(c.max_lease_duration.map(crate::time::duration_to_smoltcp)); socket.set_ports(c.server_port, c.client_port); @@ -724,19 +680,20 @@ impl Inner { socket.set_outgoing_options(&[]); #[cfg(feature = "dhcpv4-hostname")] if let Some(h) = c.hostname { - // safety: we just did set_outgoing_options([]) so we know the socket is no longer holding a reference. - let hostname = unsafe { &mut *self.hostname.get() }; + // safety: + // - we just did set_outgoing_options([]) so we know the socket is no longer holding a reference. + // - we know this pointer lives for as long as the stack exists, because `new()` borrows + // the resources for `'d`. Therefore it's OK to pass a reference to this to smoltcp. + let hostname = unsafe { &mut *self.hostname }; // create data - // safety: we know the buffer lives forever, new borrows the StackResources for 'static. - // also we won't modify it until next call to this function. - hostname.data[..h.len()].copy_from_slice(h.as_bytes()); - let data: &[u8] = &hostname.data[..h.len()]; - let data: &'static [u8] = unsafe { core::mem::transmute(data) }; + let data = hostname.data.write([0; MAX_HOSTNAME_LEN]); + data[..h.len()].copy_from_slice(h.as_bytes()); + let data: &[u8] = &data[..h.len()]; // set the option. - hostname.option = smoltcp::wire::DhcpOption { data, kind: 12 }; - socket.set_outgoing_options(core::slice::from_ref(&hostname.option)); + let option = hostname.option.write(smoltcp::wire::DhcpOption { data, kind: 12 }); + socket.set_outgoing_options(core::slice::from_ref(option)); } socket.reset(); @@ -744,7 +701,7 @@ impl Inner { _ => { // Remove DHCP socket if any. if let Some(socket) = self.dhcp_socket { - _s.sockets.remove(socket); + self.sockets.remove(socket); self.dhcp_socket = None; } } @@ -752,14 +709,14 @@ impl Inner { } #[cfg(feature = "proto-ipv6")] - pub fn set_config_v6(&mut self, _s: &mut SocketStack, config: ConfigV6) { + pub fn set_config_v6(&mut self, config: ConfigV6) { self.static_v6 = match config { ConfigV6::None => None, ConfigV6::Static(c) => Some(c), }; } - fn apply_static_config(&mut self, s: &mut SocketStack) { + fn apply_static_config(&mut self) { let mut addrs = Vec::new(); #[cfg(feature = "dns")] let mut dns_servers: Vec<_, 6> = Vec::new(); @@ -775,7 +732,7 @@ impl Inner { debug!(" Default gateway: {:?}", config.gateway); unwrap!(addrs.push(IpCidr::Ipv4(config.address)).ok()); - gateway_v4 = config.gateway.into(); + gateway_v4 = config.gateway; #[cfg(feature = "dns")] for s in &config.dns_servers { debug!(" DNS server: {:?}", s); @@ -803,35 +760,43 @@ impl Inner { } // Apply addresses - s.iface.update_ip_addrs(|a| *a = addrs); + self.iface.update_ip_addrs(|a| *a = addrs); // Apply gateways #[cfg(feature = "proto-ipv4")] if let Some(gateway) = gateway_v4 { - unwrap!(s.iface.routes_mut().add_default_ipv4_route(gateway)); + unwrap!(self.iface.routes_mut().add_default_ipv4_route(gateway)); } else { - s.iface.routes_mut().remove_default_ipv4_route(); + self.iface.routes_mut().remove_default_ipv4_route(); } #[cfg(feature = "proto-ipv6")] if let Some(gateway) = gateway_v6 { - unwrap!(s.iface.routes_mut().add_default_ipv6_route(gateway)); + unwrap!(self.iface.routes_mut().add_default_ipv6_route(gateway)); } else { - s.iface.routes_mut().remove_default_ipv6_route(); + self.iface.routes_mut().remove_default_ipv6_route(); } // Apply DNS servers #[cfg(feature = "dns")] - s.sockets - .get_mut::(self.dns_socket) - .update_servers(&dns_servers[..]); + if !dns_servers.is_empty() { + let count = if dns_servers.len() > DNS_MAX_SERVER_COUNT { + warn!("Number of DNS servers exceeds DNS_MAX_SERVER_COUNT, truncating list."); + DNS_MAX_SERVER_COUNT + } else { + dns_servers.len() + }; + self.sockets + .get_mut::(self.dns_socket) + .update_servers(&dns_servers[..count]); + } - self.config_waker.wake(); + self.state_waker.wake(); } - fn poll(&mut self, cx: &mut Context<'_>, s: &mut SocketStack) { - s.waker.register(cx.waker()); + fn poll(&mut self, cx: &mut Context<'_>, driver: &mut D) { + self.waker.register(cx.waker()); - let (_hardware_addr, medium) = to_smoltcp_hardware_address(self.device.hardware_address()); + let (_hardware_addr, medium) = to_smoltcp_hardware_address(driver.hardware_address()); #[cfg(any(feature = "medium-ethernet", feature = "medium-ieee802154"))] { @@ -844,43 +809,41 @@ impl Inner { _ => false, }; if do_set { - s.iface.set_hardware_addr(_hardware_addr); + self.iface.set_hardware_addr(_hardware_addr); } } let timestamp = instant_to_smoltcp(Instant::now()); let mut smoldev = DriverAdapter { cx: Some(cx), - inner: &mut self.device, + inner: driver, medium, }; - s.iface.poll(timestamp, &mut smoldev, &mut s.sockets); + self.iface.poll(timestamp, &mut smoldev, &mut self.sockets); // Update link up let old_link_up = self.link_up; - self.link_up = self.device.link_state(cx) == LinkState::Up; + self.link_up = driver.link_state(cx) == LinkState::Up; // Print when changed if old_link_up != self.link_up { info!("link_up = {:?}", self.link_up); + self.state_waker.wake(); } - #[allow(unused_mut)] - let mut apply_config = false; - #[cfg(feature = "dhcpv4")] if let Some(dhcp_handle) = self.dhcp_socket { - let socket = s.sockets.get_mut::(dhcp_handle); + let socket = self.sockets.get_mut::(dhcp_handle); - if self.link_up { + let configure = if self.link_up { if old_link_up != self.link_up { socket.reset(); } match socket.poll() { - None => {} + None => false, Some(dhcpv4::Event::Deconfigured) => { self.static_v4 = None; - apply_config = true; + true } Some(dhcpv4::Event::Configured(config)) => { self.static_v4 = Some(StaticConfigV4 { @@ -888,26 +851,40 @@ impl Inner { gateway: config.router, dns_servers: config.dns_servers, }); - apply_config = true; + true } } } else if old_link_up { socket.reset(); self.static_v4 = None; - apply_config = true; + true + } else { + false + }; + if configure { + self.apply_static_config() } } - if apply_config { - self.apply_static_config(s); - } - - if let Some(poll_at) = s.iface.poll_at(timestamp, &mut s.sockets) { - let t = Timer::at(instant_from_smoltcp(poll_at)); - pin_mut!(t); + if let Some(poll_at) = self.iface.poll_at(timestamp, &mut self.sockets) { + let t = pin!(Timer::at(instant_from_smoltcp(poll_at))); if t.poll(cx).is_ready() { cx.waker().wake_by_ref(); } } } } + +impl<'d, D: Driver> Runner<'d, D> { + /// Run the network stack. + /// + /// You must call this in a background task, to process network events. + pub async fn run(&mut self) -> ! { + poll_fn(|cx| { + self.stack.with_mut(|i| i.poll(cx, &mut self.driver)); + Poll::<()>::Pending + }) + .await; + unreachable!() + } +} diff --git a/embassy-net/src/raw.rs b/embassy-net/src/raw.rs new file mode 100644 index 000000000..a88bcc458 --- /dev/null +++ b/embassy-net/src/raw.rs @@ -0,0 +1,191 @@ +//! Raw sockets. + +use core::future::poll_fn; +use core::mem; +use core::task::{Context, Poll}; + +use embassy_net_driver::Driver; +use smoltcp::iface::{Interface, SocketHandle}; +use smoltcp::socket::raw; +pub use smoltcp::socket::raw::PacketMetadata; +pub use smoltcp::wire::{IpProtocol, IpVersion}; + +use crate::Stack; + +/// Error returned by [`RawSocket::recv`] and [`RawSocket::send`]. +#[derive(PartialEq, Eq, Clone, Copy, Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum RecvError { + /// Provided buffer was smaller than the received packet. + Truncated, +} + +/// An Raw socket. +pub struct RawSocket<'a> { + stack: Stack<'a>, + handle: SocketHandle, +} + +impl<'a> RawSocket<'a> { + /// Create a new Raw socket using the provided stack and buffers. + pub fn new( + stack: Stack<'a>, + ip_version: IpVersion, + ip_protocol: IpProtocol, + rx_meta: &'a mut [PacketMetadata], + rx_buffer: &'a mut [u8], + tx_meta: &'a mut [PacketMetadata], + tx_buffer: &'a mut [u8], + ) -> Self { + let handle = stack.with_mut(|i| { + let rx_meta: &'static mut [PacketMetadata] = unsafe { mem::transmute(rx_meta) }; + let rx_buffer: &'static mut [u8] = unsafe { mem::transmute(rx_buffer) }; + let tx_meta: &'static mut [PacketMetadata] = unsafe { mem::transmute(tx_meta) }; + let tx_buffer: &'static mut [u8] = unsafe { mem::transmute(tx_buffer) }; + i.sockets.add(raw::Socket::new( + ip_version, + ip_protocol, + raw::PacketBuffer::new(rx_meta, rx_buffer), + raw::PacketBuffer::new(tx_meta, tx_buffer), + )) + }); + + Self { stack, handle } + } + + fn with_mut(&self, f: impl FnOnce(&mut raw::Socket, &mut Interface) -> R) -> R { + self.stack.with_mut(|i| { + let socket = i.sockets.get_mut::(self.handle); + let res = f(socket, &mut i.iface); + i.waker.wake(); + res + }) + } + + /// Wait until the socket becomes readable. + /// + /// A socket is readable when a packet has been received, or when there are queued packets in + /// the buffer. + pub async fn wait_recv_ready(&self) { + poll_fn(move |cx| self.poll_recv_ready(cx)).await + } + + /// Receive a datagram. + /// + /// This method will wait until a datagram is received. + pub async fn recv(&self, buf: &mut [u8]) -> Result { + poll_fn(move |cx| self.poll_recv(buf, cx)).await + } + + /// Wait until a datagram can be read. + /// + /// When no datagram is readable, this method will return `Poll::Pending` and + /// register the current task to be notified when a datagram is received. + /// + /// When a datagram is received, this method will return `Poll::Ready`. + pub fn poll_recv_ready(&self, cx: &mut Context<'_>) -> Poll<()> { + self.with_mut(|s, _| { + if s.can_recv() { + Poll::Ready(()) + } else { + // socket buffer is empty wait until at least one byte has arrived + s.register_recv_waker(cx.waker()); + Poll::Pending + } + }) + } + + /// Receive a datagram. + /// + /// When no datagram is available, this method will return `Poll::Pending` and + /// register the current task to be notified when a datagram is received. + pub fn poll_recv(&self, buf: &mut [u8], cx: &mut Context<'_>) -> Poll> { + self.with_mut(|s, _| match s.recv_slice(buf) { + Ok(n) => Poll::Ready(Ok(n)), + // No data ready + Err(raw::RecvError::Truncated) => Poll::Ready(Err(RecvError::Truncated)), + Err(raw::RecvError::Exhausted) => { + s.register_recv_waker(cx.waker()); + Poll::Pending + } + }) + } + + /// Wait until the socket becomes writable. + /// + /// A socket becomes writable when there is space in the buffer, from initial memory or after + /// dispatching datagrams on a full buffer. + pub async fn wait_send_ready(&self) { + poll_fn(move |cx| self.poll_send_ready(cx)).await + } + + /// Wait until a datagram can be sent. + /// + /// When no datagram can be sent (i.e. the buffer is full), this method will return + /// `Poll::Pending` and register the current task to be notified when + /// space is freed in the buffer after a datagram has been dispatched. + /// + /// When a datagram can be sent, this method will return `Poll::Ready`. + pub fn poll_send_ready(&self, cx: &mut Context<'_>) -> Poll<()> { + self.with_mut(|s, _| { + if s.can_send() { + Poll::Ready(()) + } else { + // socket buffer is full wait until a datagram has been dispatched + s.register_send_waker(cx.waker()); + Poll::Pending + } + }) + } + + /// Send a datagram. + /// + /// This method will wait until the datagram has been sent.` + pub async fn send(&self, buf: &[u8]) { + poll_fn(move |cx| self.poll_send(buf, cx)).await + } + + /// Send a datagram. + /// + /// When the datagram has been sent, this method will return `Poll::Ready(Ok())`. + /// + /// When the socket's send buffer is full, this method will return `Poll::Pending` + /// and register the current task to be notified when the buffer has space available. + pub fn poll_send(&self, buf: &[u8], cx: &mut Context<'_>) -> Poll<()> { + self.with_mut(|s, _| match s.send_slice(buf) { + // Entire datagram has been sent + Ok(()) => Poll::Ready(()), + Err(raw::SendError::BufferFull) => { + s.register_send_waker(cx.waker()); + Poll::Pending + } + }) + } + + /// Flush the socket. + /// + /// This method will wait until the socket is flushed. + pub async fn flush(&mut self) { + poll_fn(move |cx| { + self.with_mut(|s, _| { + if s.send_queue() == 0 { + Poll::Ready(()) + } else { + s.register_send_waker(cx.waker()); + Poll::Pending + } + }) + }) + .await + } +} + +impl Drop for RawSocket<'_> { + fn drop(&mut self) { + self.stack.with_mut(|i| i.sockets.remove(self.handle)); + } +} + +fn _assert_covariant<'a, 'b: 'a>(x: RawSocket<'b>) -> RawSocket<'a> { + x +} diff --git a/embassy-net/src/tcp.rs b/embassy-net/src/tcp.rs index 72b0677b4..32d374064 100644 --- a/embassy-net/src/tcp.rs +++ b/embassy-net/src/tcp.rs @@ -8,12 +8,10 @@ //! Incoming connections when no socket is listening are rejected. To accept many incoming //! connections, create many sockets and put them all into listening mode. -use core::cell::RefCell; use core::future::poll_fn; use core::mem; -use core::task::Poll; +use core::task::{Context, Poll}; -use embassy_net_driver::Driver; use embassy_time::Duration; use smoltcp::iface::{Interface, SocketHandle}; use smoltcp::socket::tcp; @@ -21,7 +19,7 @@ pub use smoltcp::socket::tcp::State; use smoltcp::wire::{IpEndpoint, IpListenEndpoint}; use crate::time::duration_to_smoltcp; -use crate::{SocketStack, Stack}; +use crate::Stack; /// Error returned by TcpSocket read/write functions. #[derive(PartialEq, Eq, Clone, Copy, Debug)] @@ -75,10 +73,29 @@ pub struct TcpWriter<'a> { } impl<'a> TcpReader<'a> { + /// Wait until the socket becomes readable. + /// + /// A socket becomes readable when the receive half of the full-duplex connection is open + /// (see [`may_recv()`](TcpSocket::may_recv)), and there is some pending data in the receive buffer. + /// + /// This is the equivalent of [read](#method.read), without buffering any data. + pub async fn wait_read_ready(&self) { + poll_fn(move |cx| self.io.poll_read_ready(cx)).await + } + /// Read data from the socket. /// /// Returns how many bytes were read, or an error. If no data is available, it waits /// until there is at least one byte available. + /// + /// # Note + /// A return value of Ok(0) means that we have read all data and the remote + /// side has closed our receive half of the socket. The remote can no longer + /// send bytes. + /// + /// The send half of the socket is still open. If you want to reconnect using + /// the socket you split this reader off the send half needs to be closed using + /// [`abort()`](TcpSocket::abort). pub async fn read(&mut self, buf: &mut [u8]) -> Result { self.io.read(buf).await } @@ -98,9 +115,26 @@ impl<'a> TcpReader<'a> { pub fn recv_capacity(&self) -> usize { self.io.recv_capacity() } + + /// Return the amount of octets queued in the receive buffer. This value can be larger than + /// the slice read by the next `recv` or `peek` call because it includes all queued octets, + /// and not only the octets that may be returned as a contiguous slice. + pub fn recv_queue(&self) -> usize { + self.io.recv_queue() + } } impl<'a> TcpWriter<'a> { + /// Wait until the socket becomes writable. + /// + /// A socket becomes writable when the transmit half of the full-duplex connection is open + /// (see [`may_send()`](TcpSocket::may_send)), and the transmit buffer is not full. + /// + /// This is the equivalent of [write](#method.write), without sending any data. + pub async fn wait_write_ready(&self) { + poll_fn(move |cx| self.io.poll_write_ready(cx)).await + } + /// Write data to the socket. /// /// Returns how many bytes were written, or an error. If the socket is not ready to @@ -132,24 +166,27 @@ impl<'a> TcpWriter<'a> { pub fn send_capacity(&self) -> usize { self.io.send_capacity() } + + /// Return the amount of octets queued in the transmit buffer. + pub fn send_queue(&self) -> usize { + self.io.send_queue() + } } impl<'a> TcpSocket<'a> { /// Create a new TCP socket on the given stack, with the given buffers. - pub fn new(stack: &'a Stack, rx_buffer: &'a mut [u8], tx_buffer: &'a mut [u8]) -> Self { - let s = &mut *stack.socket.borrow_mut(); - let rx_buffer: &'static mut [u8] = unsafe { mem::transmute(rx_buffer) }; - let tx_buffer: &'static mut [u8] = unsafe { mem::transmute(tx_buffer) }; - let handle = s.sockets.add(tcp::Socket::new( - tcp::SocketBuffer::new(rx_buffer), - tcp::SocketBuffer::new(tx_buffer), - )); + pub fn new(stack: Stack<'a>, rx_buffer: &'a mut [u8], tx_buffer: &'a mut [u8]) -> Self { + let handle = stack.with_mut(|i| { + let rx_buffer: &'static mut [u8] = unsafe { mem::transmute(rx_buffer) }; + let tx_buffer: &'static mut [u8] = unsafe { mem::transmute(tx_buffer) }; + i.sockets.add(tcp::Socket::new( + tcp::SocketBuffer::new(rx_buffer), + tcp::SocketBuffer::new(tx_buffer), + )) + }); Self { - io: TcpIo { - stack: &stack.socket, - handle, - }, + io: TcpIo { stack, handle }, } } @@ -163,6 +200,18 @@ impl<'a> TcpSocket<'a> { self.io.send_capacity() } + /// Return the amount of octets queued in the transmit buffer. + pub fn send_queue(&self) -> usize { + self.io.send_queue() + } + + /// Return the amount of octets queued in the receive buffer. This value can be larger than + /// the slice read by the next `recv` or `peek` call because it includes all queued octets, + /// and not only the octets that may be returned as a contiguous slice. + pub fn recv_queue(&self) -> usize { + self.io.recv_queue() + } + /// Call `f` with the largest contiguous slice of octets in the transmit buffer, /// and enqueue the amount of elements returned by `f`. /// @@ -195,7 +244,7 @@ impl<'a> TcpSocket<'a> { where T: Into, { - let local_port = self.io.stack.borrow_mut().get_local_port(); + let local_port = self.io.stack.with_mut(|i| i.get_local_port()); match { self.io @@ -245,14 +294,37 @@ impl<'a> TcpSocket<'a> { .await } + /// Wait until the socket becomes readable. + /// + /// A socket becomes readable when the receive half of the full-duplex connection is open + /// (see [may_recv](#method.may_recv)), and there is some pending data in the receive buffer. + /// + /// This is the equivalent of [read](#method.read), without buffering any data. + pub async fn wait_read_ready(&self) { + poll_fn(move |cx| self.io.poll_read_ready(cx)).await + } + /// Read data from the socket. /// /// Returns how many bytes were read, or an error. If no data is available, it waits /// until there is at least one byte available. + /// + /// A return value of Ok(0) means that the socket was closed and is longer + /// able to receive any data. pub async fn read(&mut self, buf: &mut [u8]) -> Result { self.io.read(buf).await } + /// Wait until the socket becomes writable. + /// + /// A socket becomes writable when the transmit half of the full-duplex connection is open + /// (see [may_send](#method.may_send)), and the transmit buffer is not full. + /// + /// This is the equivalent of [write](#method.write), without sending any data. + pub async fn wait_write_ready(&self) { + poll_fn(move |cx| self.io.poll_write_ready(cx)).await + } + /// Write data to the socket. /// /// Returns how many bytes were written, or an error. If the socket is not ready to @@ -273,6 +345,10 @@ impl<'a> TcpSocket<'a> { /// /// If the timeout is set, the socket will be closed if no data is received for the /// specified duration. + /// + /// # Note: + /// Set a keep alive interval ([`set_keep_alive`] to prevent timeouts when + /// the remote could still respond. pub fn set_timeout(&mut self, duration: Option) { self.io .with_mut(|s, _| s.set_timeout(duration.map(duration_to_smoltcp))) @@ -284,6 +360,9 @@ impl<'a> TcpSocket<'a> { /// the specified duration of inactivity. /// /// If not set, the socket will not send keep-alive packets. + /// + /// By setting a [`timeout`](Self::timeout) larger then the keep alive you + /// can detect a remote endpoint that no longer answers. pub fn set_keep_alive(&mut self, interval: Option) { self.io .with_mut(|s, _| s.set_keep_alive(interval.map(duration_to_smoltcp))) @@ -337,12 +416,26 @@ impl<'a> TcpSocket<'a> { self.io.with_mut(|s, _| s.abort()) } - /// Get whether the socket is ready to send data, i.e. whether there is space in the send buffer. + /// Return whether the transmit half of the full-duplex connection is open. + /// + /// This function returns true if it's possible to send data and have it arrive + /// to the remote endpoint. However, it does not make any guarantees about the state + /// of the transmit buffer, and even if it returns true, [write](#method.write) may + /// not be able to enqueue any octets. + /// + /// In terms of the TCP state machine, the socket must be in the `ESTABLISHED` or + /// `CLOSE-WAIT` state. pub fn may_send(&self) -> bool { self.io.with(|s, _| s.may_send()) } - /// return whether the recieve half of the full-duplex connection is open. + /// Check whether the transmit half of the full-duplex connection is open + /// (see [may_send](#method.may_send)), and the transmit buffer is not full. + pub fn can_send(&self) -> bool { + self.io.with(|s, _| s.can_send()) + } + + /// return whether the receive half of the full-duplex connection is open. /// This function returns true if it’s possible to receive data from the remote endpoint. /// It will return true while there is data in the receive buffer, and if there isn’t, /// as long as the remote endpoint has not closed the connection. @@ -358,31 +451,54 @@ impl<'a> TcpSocket<'a> { impl<'a> Drop for TcpSocket<'a> { fn drop(&mut self) { - self.io.stack.borrow_mut().sockets.remove(self.io.handle); + self.io.stack.with_mut(|i| i.sockets.remove(self.io.handle)); } } +fn _assert_covariant<'a, 'b: 'a>(x: TcpSocket<'b>) -> TcpSocket<'a> { + x +} +fn _assert_covariant_reader<'a, 'b: 'a>(x: TcpReader<'b>) -> TcpReader<'a> { + x +} +fn _assert_covariant_writer<'a, 'b: 'a>(x: TcpWriter<'b>) -> TcpWriter<'a> { + x +} + // ======================= #[derive(Copy, Clone)] struct TcpIo<'a> { - stack: &'a RefCell, + stack: Stack<'a>, handle: SocketHandle, } impl<'d> TcpIo<'d> { fn with(&self, f: impl FnOnce(&tcp::Socket, &Interface) -> R) -> R { - let s = &*self.stack.borrow(); - let socket = s.sockets.get::(self.handle); - f(socket, &s.iface) + self.stack.with(|i| { + let socket = i.sockets.get::(self.handle); + f(socket, &i.iface) + }) } - fn with_mut(&mut self, f: impl FnOnce(&mut tcp::Socket, &mut Interface) -> R) -> R { - let s = &mut *self.stack.borrow_mut(); - let socket = s.sockets.get_mut::(self.handle); - let res = f(socket, &mut s.iface); - s.waker.wake(); - res + fn with_mut(&self, f: impl FnOnce(&mut tcp::Socket, &mut Interface) -> R) -> R { + self.stack.with_mut(|i| { + let socket = i.sockets.get_mut::(self.handle); + let res = f(socket, &mut i.iface); + i.waker.wake(); + res + }) + } + + fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<()> { + self.with_mut(|s, _| { + if s.can_recv() { + Poll::Ready(()) + } else { + s.register_recv_waker(cx.waker()); + Poll::Pending + } + }) } async fn read(&mut self, buf: &mut [u8]) -> Result { @@ -413,6 +529,17 @@ impl<'d> TcpIo<'d> { .await } + fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<()> { + self.with_mut(|s, _| { + if s.can_send() { + Poll::Ready(()) + } else { + s.register_send_waker(cx.waker()); + Poll::Pending + } + }) + } + async fn write(&mut self, buf: &[u8]) -> Result { poll_fn(move |cx| { self.with_mut(|s, _| match s.send_slice(buf) { @@ -471,7 +598,7 @@ impl<'d> TcpIo<'d> { s.register_recv_waker(cx.waker()); Poll::Pending } else { - // if we can't receive because the recieve half of the duplex connection is closed then return an error + // if we can't receive because the receive half of the duplex connection is closed then return an error Poll::Ready(Err(Error::ConnectionReset)) } } else { @@ -491,10 +618,16 @@ impl<'d> TcpIo<'d> { async fn flush(&mut self) -> Result<(), Error> { poll_fn(move |cx| { self.with_mut(|s, _| { - let waiting_close = s.state() == tcp::State::Closed && s.remote_endpoint().is_some(); + let data_pending = (s.send_queue() > 0) && s.state() != tcp::State::Closed; + let fin_pending = matches!( + s.state(), + tcp::State::FinWait1 | tcp::State::Closing | tcp::State::LastAck + ); + let rst_pending = s.state() == tcp::State::Closed && s.remote_endpoint().is_some(); + // If there are outstanding send operations, register for wake up and wait // smoltcp issues wake-ups when octets are dequeued from the send buffer - if s.send_queue() > 0 || waiting_close { + if data_pending || fin_pending || rst_pending { s.register_send_waker(cx.waker()); Poll::Pending // No outstanding sends, socket is flushed @@ -513,6 +646,14 @@ impl<'d> TcpIo<'d> { fn send_capacity(&self) -> usize { self.with(|s, _| s.send_capacity()) } + + fn send_queue(&self) -> usize { + self.with(|s, _| s.send_queue()) + } + + fn recv_queue(&self) -> usize { + self.with(|s, _| s.recv_queue()) + } } mod embedded_io_impls { @@ -549,7 +690,7 @@ mod embedded_io_impls { impl<'d> embedded_io_async::ReadReady for TcpSocket<'d> { fn read_ready(&mut self) -> Result { - Ok(self.io.with(|s, _| s.may_recv())) + Ok(self.io.with(|s, _| s.can_recv() || !s.may_recv())) } } @@ -565,7 +706,7 @@ mod embedded_io_impls { impl<'d> embedded_io_async::WriteReady for TcpSocket<'d> { fn write_ready(&mut self) -> Result { - Ok(self.io.with(|s, _| s.may_send())) + Ok(self.io.with(|s, _| s.can_send())) } } @@ -581,7 +722,7 @@ mod embedded_io_impls { impl<'d> embedded_io_async::ReadReady for TcpReader<'d> { fn read_ready(&mut self) -> Result { - Ok(self.io.with(|s, _| s.may_recv())) + Ok(self.io.with(|s, _| s.can_recv() || !s.may_recv())) } } @@ -601,7 +742,7 @@ mod embedded_io_impls { impl<'d> embedded_io_async::WriteReady for TcpWriter<'d> { fn write_ready(&mut self) -> Result { - Ok(self.io.with(|s, _| s.may_send())) + Ok(self.io.with(|s, _| s.can_send())) } } } @@ -610,49 +751,62 @@ mod embedded_io_impls { pub mod client { use core::cell::{Cell, UnsafeCell}; use core::mem::MaybeUninit; + use core::net::IpAddr; use core::ptr::NonNull; - use embedded_nal_async::IpAddr; - use super::*; /// TCP client connection pool compatible with `embedded-nal-async` traits. /// /// The pool is capable of managing up to N concurrent connections with tx and rx buffers according to TX_SZ and RX_SZ. - pub struct TcpClient<'d, D: Driver, const N: usize, const TX_SZ: usize = 1024, const RX_SZ: usize = 1024> { - stack: &'d Stack, + pub struct TcpClient<'d, const N: usize, const TX_SZ: usize = 1024, const RX_SZ: usize = 1024> { + stack: Stack<'d>, state: &'d TcpClientState, + socket_timeout: Option, } - impl<'d, D: Driver, const N: usize, const TX_SZ: usize, const RX_SZ: usize> TcpClient<'d, D, N, TX_SZ, RX_SZ> { + impl<'d, const N: usize, const TX_SZ: usize, const RX_SZ: usize> TcpClient<'d, N, TX_SZ, RX_SZ> { /// Create a new `TcpClient`. - pub fn new(stack: &'d Stack, state: &'d TcpClientState) -> Self { - Self { stack, state } + pub fn new(stack: Stack<'d>, state: &'d TcpClientState) -> Self { + Self { + stack, + state, + socket_timeout: None, + } + } + + /// Set the timeout for each socket created by this `TcpClient`. + /// + /// If the timeout is set, the socket will be closed if no data is received for the + /// specified duration. + pub fn set_timeout(&mut self, timeout: Option) { + self.socket_timeout = timeout; } } - impl<'d, D: Driver, const N: usize, const TX_SZ: usize, const RX_SZ: usize> embedded_nal_async::TcpConnect - for TcpClient<'d, D, N, TX_SZ, RX_SZ> + impl<'d, const N: usize, const TX_SZ: usize, const RX_SZ: usize> embedded_nal_async::TcpConnect + for TcpClient<'d, N, TX_SZ, RX_SZ> { type Error = Error; - type Connection<'m> = TcpConnection<'m, N, TX_SZ, RX_SZ> where Self: 'm; + type Connection<'m> + = TcpConnection<'m, N, TX_SZ, RX_SZ> + where + Self: 'm; - async fn connect<'a>( - &'a self, - remote: embedded_nal_async::SocketAddr, - ) -> Result, Self::Error> { + async fn connect<'a>(&'a self, remote: core::net::SocketAddr) -> Result, Self::Error> { let addr: crate::IpAddress = match remote.ip() { #[cfg(feature = "proto-ipv4")] - IpAddr::V4(addr) => crate::IpAddress::Ipv4(crate::Ipv4Address::from_bytes(&addr.octets())), + IpAddr::V4(addr) => crate::IpAddress::Ipv4(addr), #[cfg(not(feature = "proto-ipv4"))] IpAddr::V4(_) => panic!("ipv4 support not enabled"), #[cfg(feature = "proto-ipv6")] - IpAddr::V6(addr) => crate::IpAddress::Ipv6(crate::Ipv6Address::from_bytes(&addr.octets())), + IpAddr::V6(addr) => crate::IpAddress::Ipv6(addr), #[cfg(not(feature = "proto-ipv6"))] IpAddr::V6(_) => panic!("ipv6 support not enabled"), }; let remote_endpoint = (addr, remote.port()); - let mut socket = TcpConnection::new(&self.stack, self.state)?; + let mut socket = TcpConnection::new(self.stack, self.state)?; + socket.socket.set_timeout(self.socket_timeout); socket .socket .connect(remote_endpoint) @@ -670,7 +824,7 @@ pub mod client { } impl<'d, const N: usize, const TX_SZ: usize, const RX_SZ: usize> TcpConnection<'d, N, TX_SZ, RX_SZ> { - fn new(stack: &'d Stack, state: &'d TcpClientState) -> Result { + fn new(stack: Stack<'d>, state: &'d TcpClientState) -> Result { let mut bufs = state.pool.alloc().ok_or(Error::ConnectionReset)?; Ok(Self { socket: unsafe { TcpSocket::new(stack, &mut bufs.as_mut().1, &mut bufs.as_mut().0) }, diff --git a/embassy-net/src/udp.rs b/embassy-net/src/udp.rs index a22cd8827..76602edc2 100644 --- a/embassy-net/src/udp.rs +++ b/embassy-net/src/udp.rs @@ -1,17 +1,15 @@ //! UDP sockets. -use core::cell::RefCell; use core::future::poll_fn; use core::mem; use core::task::{Context, Poll}; -use embassy_net_driver::Driver; use smoltcp::iface::{Interface, SocketHandle}; use smoltcp::socket::udp; -pub use smoltcp::socket::udp::PacketMetadata; -use smoltcp::wire::{IpEndpoint, IpListenEndpoint}; +pub use smoltcp::socket::udp::{PacketMetadata, UdpMetadata}; +use smoltcp::wire::IpListenEndpoint; -use crate::{SocketStack, Stack}; +use crate::Stack; /// Error returned by [`UdpSocket::bind`]. #[derive(PartialEq, Eq, Clone, Copy, Debug)] @@ -43,34 +41,31 @@ pub enum RecvError { /// An UDP socket. pub struct UdpSocket<'a> { - stack: &'a RefCell, + stack: Stack<'a>, handle: SocketHandle, } impl<'a> UdpSocket<'a> { /// Create a new UDP socket using the provided stack and buffers. - pub fn new( - stack: &'a Stack, + pub fn new( + stack: Stack<'a>, rx_meta: &'a mut [PacketMetadata], rx_buffer: &'a mut [u8], tx_meta: &'a mut [PacketMetadata], tx_buffer: &'a mut [u8], ) -> Self { - let s = &mut *stack.socket.borrow_mut(); + let handle = stack.with_mut(|i| { + let rx_meta: &'static mut [PacketMetadata] = unsafe { mem::transmute(rx_meta) }; + let rx_buffer: &'static mut [u8] = unsafe { mem::transmute(rx_buffer) }; + let tx_meta: &'static mut [PacketMetadata] = unsafe { mem::transmute(tx_meta) }; + let tx_buffer: &'static mut [u8] = unsafe { mem::transmute(tx_buffer) }; + i.sockets.add(udp::Socket::new( + udp::PacketBuffer::new(rx_meta, rx_buffer), + udp::PacketBuffer::new(tx_meta, tx_buffer), + )) + }); - let rx_meta: &'static mut [PacketMetadata] = unsafe { mem::transmute(rx_meta) }; - let rx_buffer: &'static mut [u8] = unsafe { mem::transmute(rx_buffer) }; - let tx_meta: &'static mut [PacketMetadata] = unsafe { mem::transmute(tx_meta) }; - let tx_buffer: &'static mut [u8] = unsafe { mem::transmute(tx_buffer) }; - let handle = s.sockets.add(udp::Socket::new( - udp::PacketBuffer::new(rx_meta, rx_buffer), - udp::PacketBuffer::new(tx_meta, tx_buffer), - )); - - Self { - stack: &stack.socket, - handle, - } + Self { stack, handle } } /// Bind the socket to a local endpoint. @@ -82,7 +77,7 @@ impl<'a> UdpSocket<'a> { if endpoint.port == 0 { // If user didn't specify port allocate a dynamic port. - endpoint.port = self.stack.borrow_mut().get_local_port(); + endpoint.port = self.stack.with_mut(|i| i.get_local_port()); } match self.with_mut(|s, _| s.bind(endpoint)) { @@ -93,17 +88,45 @@ impl<'a> UdpSocket<'a> { } fn with(&self, f: impl FnOnce(&udp::Socket, &Interface) -> R) -> R { - let s = &*self.stack.borrow(); - let socket = s.sockets.get::(self.handle); - f(socket, &s.iface) + self.stack.with(|i| { + let socket = i.sockets.get::(self.handle); + f(socket, &i.iface) + }) } fn with_mut(&self, f: impl FnOnce(&mut udp::Socket, &mut Interface) -> R) -> R { - let s = &mut *self.stack.borrow_mut(); - let socket = s.sockets.get_mut::(self.handle); - let res = f(socket, &mut s.iface); - s.waker.wake(); - res + self.stack.with_mut(|i| { + let socket = i.sockets.get_mut::(self.handle); + let res = f(socket, &mut i.iface); + i.waker.wake(); + res + }) + } + + /// Wait until the socket becomes readable. + /// + /// A socket is readable when a packet has been received, or when there are queued packets in + /// the buffer. + pub async fn wait_recv_ready(&self) { + poll_fn(move |cx| self.poll_recv_ready(cx)).await + } + + /// Wait until a datagram can be read. + /// + /// When no datagram is readable, this method will return `Poll::Pending` and + /// register the current task to be notified when a datagram is received. + /// + /// When a datagram is received, this method will return `Poll::Ready`. + pub fn poll_recv_ready(&self, cx: &mut Context<'_>) -> Poll<()> { + self.with_mut(|s, _| { + if s.can_recv() { + Poll::Ready(()) + } else { + // socket buffer is empty wait until at least one byte has arrived + s.register_recv_waker(cx.waker()); + Poll::Pending + } + }) } /// Receive a datagram. @@ -111,7 +134,7 @@ impl<'a> UdpSocket<'a> { /// This method will wait until a datagram is received. /// /// Returns the number of bytes received and the remote endpoint. - pub async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, IpEndpoint), RecvError> { + pub async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, UdpMetadata), RecvError> { poll_fn(move |cx| self.poll_recv_from(buf, cx)).await } @@ -122,9 +145,13 @@ impl<'a> UdpSocket<'a> { /// /// When a datagram is received, this method will return `Poll::Ready` with the /// number of bytes received and the remote endpoint. - pub fn poll_recv_from(&self, buf: &mut [u8], cx: &mut Context<'_>) -> Poll> { + pub fn poll_recv_from( + &self, + buf: &mut [u8], + cx: &mut Context<'_>, + ) -> Poll> { self.with_mut(|s, _| match s.recv_slice(buf) { - Ok((n, meta)) => Poll::Ready(Ok((n, meta.endpoint))), + Ok((n, meta)) => Poll::Ready(Ok((n, meta))), // No data ready Err(udp::RecvError::Truncated) => Poll::Ready(Err(RecvError::Truncated)), Err(udp::RecvError::Exhausted) => { @@ -134,6 +161,62 @@ impl<'a> UdpSocket<'a> { }) } + /// Receive a datagram with a zero-copy function. + /// + /// When no datagram is available, this method will return `Poll::Pending` and + /// register the current task to be notified when a datagram is received. + /// + /// When a datagram is received, this method will call the provided function + /// with the number of bytes received and the remote endpoint and return + /// `Poll::Ready` with the function's returned value. + pub async fn recv_from_with(&mut self, f: F) -> R + where + F: FnOnce(&[u8], UdpMetadata) -> R, + { + let mut f = Some(f); + poll_fn(move |cx| { + self.with_mut(|s, _| { + match s.recv() { + Ok((buffer, endpoint)) => Poll::Ready(unwrap!(f.take())(buffer, endpoint)), + Err(udp::RecvError::Truncated) => unreachable!(), + Err(udp::RecvError::Exhausted) => { + // socket buffer is empty wait until at least one byte has arrived + s.register_recv_waker(cx.waker()); + Poll::Pending + } + } + }) + }) + .await + } + + /// Wait until the socket becomes writable. + /// + /// A socket becomes writable when there is space in the buffer, from initial memory or after + /// dispatching datagrams on a full buffer. + pub async fn wait_send_ready(&self) { + poll_fn(move |cx| self.poll_send_ready(cx)).await + } + + /// Wait until a datagram can be sent. + /// + /// When no datagram can be sent (i.e. the buffer is full), this method will return + /// `Poll::Pending` and register the current task to be notified when + /// space is freed in the buffer after a datagram has been dispatched. + /// + /// When a datagram can be sent, this method will return `Poll::Ready`. + pub fn poll_send_ready(&self, cx: &mut Context<'_>) -> Poll<()> { + self.with_mut(|s, _| { + if s.can_send() { + Poll::Ready(()) + } else { + // socket buffer is full wait until a datagram has been dispatched + s.register_send_waker(cx.waker()); + Poll::Pending + } + }) + } + /// Send a datagram to the specified remote endpoint. /// /// This method will wait until the datagram has been sent. @@ -141,9 +224,9 @@ impl<'a> UdpSocket<'a> { /// When the remote endpoint is not reachable, this method will return `Err(SendError::NoRoute)` pub async fn send_to(&self, buf: &[u8], remote_endpoint: T) -> Result<(), SendError> where - T: Into, + T: Into, { - let remote_endpoint: IpEndpoint = remote_endpoint.into(); + let remote_endpoint: UdpMetadata = remote_endpoint.into(); poll_fn(move |cx| self.poll_send_to(buf, remote_endpoint, cx)).await } @@ -157,7 +240,7 @@ impl<'a> UdpSocket<'a> { /// When the remote endpoint is not reachable, this method will return `Poll::Ready(Err(Error::NoRoute))`. pub fn poll_send_to(&self, buf: &[u8], remote_endpoint: T, cx: &mut Context<'_>) -> Poll> where - T: Into, + T: Into, { self.with_mut(|s, _| match s.send_slice(buf, remote_endpoint) { // Entire datagram has been sent @@ -177,6 +260,57 @@ impl<'a> UdpSocket<'a> { }) } + /// Send a datagram to the specified remote endpoint with a zero-copy function. + /// + /// This method will wait until the buffer can fit the requested size before + /// calling the function to fill its contents. + /// + /// When the remote endpoint is not reachable, this method will return `Err(SendError::NoRoute)` + pub async fn send_to_with(&mut self, size: usize, remote_endpoint: T, f: F) -> Result + where + T: Into + Copy, + F: FnOnce(&mut [u8]) -> R, + { + let mut f = Some(f); + poll_fn(move |cx| { + self.with_mut(|s, _| { + match s.send(size, remote_endpoint) { + Ok(buffer) => Poll::Ready(Ok(unwrap!(f.take())(buffer))), + Err(udp::SendError::BufferFull) => { + s.register_send_waker(cx.waker()); + Poll::Pending + } + Err(udp::SendError::Unaddressable) => { + // If no sender/outgoing port is specified, there is not really "no route" + if s.endpoint().port == 0 { + Poll::Ready(Err(SendError::SocketNotBound)) + } else { + Poll::Ready(Err(SendError::NoRoute)) + } + } + } + }) + }) + .await + } + + /// Flush the socket. + /// + /// This method will wait until the socket is flushed. + pub async fn flush(&mut self) { + poll_fn(move |cx| { + self.with_mut(|s, _| { + if s.send_queue() == 0 { + Poll::Ready(()) + } else { + s.register_send_waker(cx.waker()); + Poll::Pending + } + }) + }) + .await + } + /// Returns the local endpoint of the socket. pub fn endpoint(&self) -> IpListenEndpoint { self.with(|s, _| s.endpoint()) @@ -231,6 +365,10 @@ impl<'a> UdpSocket<'a> { impl Drop for UdpSocket<'_> { fn drop(&mut self) { - self.stack.borrow_mut().sockets.remove(self.handle); + self.stack.with_mut(|i| i.sockets.remove(self.handle)); } } + +fn _assert_covariant<'a, 'b: 'a>(x: UdpSocket<'b>) -> UdpSocket<'a> { + x +} diff --git a/embassy-nrf/CHANGELOG.md b/embassy-nrf/CHANGELOG.md new file mode 100644 index 000000000..f8d6ab753 --- /dev/null +++ b/embassy-nrf/CHANGELOG.md @@ -0,0 +1,53 @@ +# Changelog for embassy-nrf + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## Unreleased + +## 0.2.0 - 2024-08-05 + +- Support for NRF chips: + - nrf51 + - nrf9151 +- Support for new peripherals: + - EGU + - radio - low-level support for IEEE 802.15.4 and BLE via radio peripheral +- Peripheral changes: + - gpio: Drop GPIO Pin generics (API break) + - pdm: Fix gain register value derivation + - pwm: + - Expose `duty` method + - Expose `pwm::PWM_CLK_HZ` and add `is_enabled` method + - Allow specifying OutputDrive for PWM channels + - Fix infinite loop + - spim: + - Reduce trace-level messages ("Copying SPIM tx buffer..") + - Support configuring bit order for bus + - Allow specifying OutputDrive for SPI pins + - Add bounds checks for EasyDMA buffer size + - Implement chunked DMA transfers + - uart: + - Add support for rx- or tx-only BufferedUart + - Implement splitting Rx/Tx + - Add support for handling RX errors +- Miscellaneous changes: + - Add `collapse_debuginfo` to fmt.rs macros. + - Drop `sealed` mod + - nrf52840: Add dcdc voltage parameter to configure REG0 regulator + +## 0.1.0 - 2024-01-12 + +- First release with support for following NRF chips: + - nrf52805 + - nrf52810 + - nrf52811 + - nrf52820 + - nrf52832 + - nrf52833 + - nrf52840 + - nrf5340 + - nrf9160 + diff --git a/embassy-nrf/Cargo.toml b/embassy-nrf/Cargo.toml index a682e1227..24a3db91d 100644 --- a/embassy-nrf/Cargo.toml +++ b/embassy-nrf/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "embassy-nrf" -version = "0.1.0" +version = "0.2.0" edition = "2021" license = "MIT OR Apache-2.0" description = "Embassy Hardware Abstraction Layer (HAL) for nRF series microcontrollers" @@ -28,19 +28,7 @@ rustdoc-args = ["--cfg", "docsrs"] [features] default = ["rt"] ## Cortex-M runtime (enabled by default) -rt = [ - "nrf51-pac?/rt", - "nrf52805-pac?/rt", - "nrf52810-pac?/rt", - "nrf52811-pac?/rt", - "nrf52820-pac?/rt", - "nrf52832-pac?/rt", - "nrf52833-pac?/rt", - "nrf52840-pac?/rt", - "nrf5340-app-pac?/rt", - "nrf5340-net-pac?/rt", - "nrf9160-pac?/rt", -] +rt = ["nrf-pac/rt"] ## Enable features requiring `embassy-time` time = ["dep:embassy-time"] @@ -74,21 +62,21 @@ qspi-multiwrite-flash = [] #! ### Chip selection features ## nRF51 -nrf51 = ["nrf51-pac", "_nrf51"] +nrf51 = ["nrf-pac/nrf51", "_nrf51"] ## nRF52805 -nrf52805 = ["nrf52805-pac", "_nrf52"] +nrf52805 = ["nrf-pac/nrf52805", "_nrf52"] ## nRF52810 -nrf52810 = ["nrf52810-pac", "_nrf52"] +nrf52810 = ["nrf-pac/nrf52810", "_nrf52"] ## nRF52811 -nrf52811 = ["nrf52811-pac", "_nrf52"] +nrf52811 = ["nrf-pac/nrf52811", "_nrf52"] ## nRF52820 -nrf52820 = ["nrf52820-pac", "_nrf52"] +nrf52820 = ["nrf-pac/nrf52820", "_nrf52"] ## nRF52832 -nrf52832 = ["nrf52832-pac", "_nrf52", "_nrf52832_anomaly_109"] +nrf52832 = ["nrf-pac/nrf52832", "_nrf52", "_nrf52832_anomaly_109"] ## nRF52833 -nrf52833 = ["nrf52833-pac", "_nrf52", "_gpio-p1"] +nrf52833 = ["nrf-pac/nrf52833", "_nrf52", "_gpio-p1"] ## nRF52840 -nrf52840 = ["nrf52840-pac", "_nrf52", "_gpio-p1"] +nrf52840 = ["nrf-pac/nrf52840", "_nrf52", "_gpio-p1"] ## nRF5340 application core in Secure mode nrf5340-app-s = ["_nrf5340-app", "_s"] ## nRF5340 application core in Non-Secure mode @@ -96,19 +84,30 @@ nrf5340-app-ns = ["_nrf5340-app", "_ns"] ## nRF5340 network core nrf5340-net = ["_nrf5340-net"] ## nRF9160 in Secure mode -nrf9160-s = ["_nrf9160", "_s"] +nrf9160-s = ["_nrf9160", "_s", "_nrf91"] ## nRF9160 in Non-Secure mode -nrf9160-ns = ["_nrf9160", "_ns"] +nrf9160-ns = ["_nrf9160", "_ns", "_nrf91"] +## The nRF9120 is the internal part number for the nRF9161 and nRF9151. +## nRF9120 in Secure mode +nrf9120-s = ["_nrf9120", "_s", "_nrf91"] +nrf9151-s = ["nrf9120-s"] +nrf9161-s = ["nrf9120-s"] +## nRF9120 in Non-Secure mode +nrf9120-ns = ["_nrf9120", "_ns", "_nrf91"] +nrf9151-ns = ["nrf9120-ns"] +nrf9161-ns = ["nrf9120-ns"] # Features starting with `_` are for internal use only. They're not intended # to be enabled by other crates, and are not covered by semver guarantees. -_nrf5340-app = ["_nrf5340", "nrf5340-app-pac"] -_nrf5340-net = ["_nrf5340", "nrf5340-net-pac"] +_nrf5340-app = ["_nrf5340", "nrf-pac/nrf5340-app"] +_nrf5340-net = ["_nrf5340", "nrf-pac/nrf5340-net"] _nrf5340 = ["_gpio-p1", "_dppi"] -_nrf9160 = ["nrf9160-pac", "_dppi"] +_nrf9160 = ["nrf-pac/nrf9160", "_dppi"] +_nrf9120 = ["nrf-pac/nrf9120", "_dppi"] _nrf52 = ["_ppi"] _nrf51 = ["_ppi"] +_nrf91 = [] _time-driver = ["dep:embassy-time-driver", "embassy-time-driver?/tick-hz-32_768"] @@ -125,10 +124,10 @@ _nrf52832_anomaly_109 = [] [dependencies] embassy-time-driver = { version = "0.1", path = "../embassy-time-driver", optional = true } -embassy-time = { version = "0.3.0", path = "../embassy-time", optional = true } -embassy-sync = { version = "0.5.0", path = "../embassy-sync" } -embassy-hal-internal = {version = "0.1.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-3"] } -embassy-embedded-hal = {version = "0.1.0", path = "../embassy-embedded-hal" } +embassy-time = { version = "0.3.2", path = "../embassy-time", optional = true } +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } +embassy-hal-internal = {version = "0.2.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-3"] } +embassy-embedded-hal = {version = "0.2.0", path = "../embassy-embedded-hal" } embassy-usb-driver = {version = "0.1.0", path = "../embassy-usb-driver" } embedded-hal-02 = { package = "embedded-hal", version = "0.2.6", features = ["unproven"] } @@ -137,7 +136,10 @@ embedded-hal-async = { version = "1.0" } embedded-io = { version = "0.6.0" } embedded-io-async = { version = "0.6.1" } +nrf-pac = { git = "https://github.com/embassy-rs/nrf-pac", rev = "875a29629cc1c87aae00cfea647a956b3807d8be" } + defmt = { version = "0.3", optional = true } +bitflags = "2.4.2" log = { version = "0.4.14", optional = true } cortex-m-rt = ">=0.6.15,<0.8" cortex-m = "0.7.6" @@ -145,18 +147,6 @@ critical-section = "1.1" rand_core = "0.6.3" fixed = "1.10.0" embedded-storage = "0.3.1" -embedded-storage-async = "0.4.0" +embedded-storage-async = "0.4.1" cfg-if = "1.0.0" document-features = "0.2.7" - -nrf51-pac = { version = "0.12.0", optional = true } -nrf52805-pac = { version = "0.12.0", optional = true } -nrf52810-pac = { version = "0.12.0", optional = true } -nrf52811-pac = { version = "0.12.0", optional = true } -nrf52820-pac = { version = "0.12.0", optional = true } -nrf52832-pac = { version = "0.12.0", optional = true } -nrf52833-pac = { version = "0.12.0", optional = true } -nrf52840-pac = { version = "0.12.0", optional = true } -nrf5340-app-pac = { version = "0.12.0", optional = true } -nrf5340-net-pac = { version = "0.12.0", optional = true } -nrf9160-pac = { version = "0.12.0", optional = true } diff --git a/embassy-nrf/src/buffered_uarte.rs b/embassy-nrf/src/buffered_uarte.rs index 2c620798d..b55e70a36 100644 --- a/embassy-nrf/src/buffered_uarte.rs +++ b/embassy-nrf/src/buffered_uarte.rs @@ -17,35 +17,28 @@ use core::task::Poll; use embassy_hal_internal::atomic_ring_buffer::RingBuffer; use embassy_hal_internal::{into_ref, PeripheralRef}; -use embassy_sync::waitqueue::AtomicWaker; +use pac::uarte::vals; // Re-export SVD variants to allow user to directly set values -pub use pac::uarte0::{baudrate::BAUDRATE_A as Baudrate, config::PARITY_A as Parity}; +pub use pac::uarte::vals::{Baudrate, ConfigParity as Parity}; -use crate::gpio::sealed::Pin; -use crate::gpio::{self, AnyPin, Pin as GpioPin, PselBits}; +use crate::gpio::{AnyPin, Pin as GpioPin}; use crate::interrupt::typelevel::Interrupt; use crate::ppi::{ self, AnyConfigurableChannel, AnyGroup, Channel, ConfigurableChannel, Event, Group, Ppi, PpiGroup, Task, }; use crate::timer::{Instance as TimerInstance, Timer}; -use crate::uarte::{apply_workaround_for_enable_anomaly, Config, Instance as UarteInstance}; -use crate::{interrupt, pac, Peripheral}; +use crate::uarte::{configure, configure_rx_pins, configure_tx_pins, drop_tx_rx, Config, Instance as UarteInstance}; +use crate::{interrupt, pac, Peripheral, EASY_DMA_SIZE}; -mod sealed { - use super::*; +pub(crate) struct State { + tx_buf: RingBuffer, + tx_count: AtomicUsize, - pub struct State { - pub tx_waker: AtomicWaker, - pub tx_buf: RingBuffer, - pub tx_count: AtomicUsize, - - pub rx_waker: AtomicWaker, - pub rx_buf: RingBuffer, - pub rx_started: AtomicBool, - pub rx_started_count: AtomicU8, - pub rx_ended_count: AtomicU8, - pub rx_ppi_ch: AtomicU8, - } + rx_buf: RingBuffer, + rx_started: AtomicBool, + rx_started_count: AtomicU8, + rx_ended_count: AtomicU8, + rx_ppi_ch: AtomicU8, } /// UART error. @@ -56,16 +49,12 @@ pub enum Error { // No errors for now } -pub(crate) use sealed::State; - impl State { pub(crate) const fn new() -> Self { Self { - tx_waker: AtomicWaker::new(), tx_buf: RingBuffer::new(), tx_count: AtomicUsize::new(0), - rx_waker: AtomicWaker::new(), rx_buf: RingBuffer::new(), rx_started: AtomicBool::new(false), rx_started_count: AtomicU8::new(0), @@ -84,128 +73,132 @@ impl interrupt::typelevel::Handler for Interrupt unsafe fn on_interrupt() { //trace!("irq: start"); let r = U::regs(); + let ss = U::state(); let s = U::buffered_state(); - let buf_len = s.rx_buf.len(); - let half_len = buf_len / 2; - let mut tx = unsafe { s.tx_buf.reader() }; - let mut rx = unsafe { s.rx_buf.writer() }; + if let Some(mut rx) = unsafe { s.rx_buf.try_writer() } { + let buf_len = s.rx_buf.len(); + let half_len = buf_len / 2; - if r.events_error.read().bits() != 0 { - r.events_error.reset(); - let errs = r.errorsrc.read(); - r.errorsrc.write(|w| unsafe { w.bits(errs.bits()) }); + if r.events_error().read() != 0 { + r.events_error().write_value(0); + let errs = r.errorsrc().read(); + r.errorsrc().write_value(errs); - if errs.overrun().bit() { - panic!("BufferedUarte overrun"); + if errs.overrun() { + panic!("BufferedUarte overrun"); + } } - } - // Received some bytes, wake task. - if r.inten.read().rxdrdy().bit_is_set() && r.events_rxdrdy.read().bits() != 0 { - r.intenclr.write(|w| w.rxdrdy().clear()); - r.events_rxdrdy.reset(); - s.rx_waker.wake(); - } + // Received some bytes, wake task. + if r.inten().read().rxdrdy() && r.events_rxdrdy().read() != 0 { + r.intenclr().write(|w| w.set_rxdrdy(true)); + r.events_rxdrdy().write_value(0); + ss.rx_waker.wake(); + } - if r.events_endrx.read().bits() != 0 { - //trace!(" irq_rx: endrx"); - r.events_endrx.reset(); + if r.events_endrx().read() != 0 { + //trace!(" irq_rx: endrx"); + r.events_endrx().write_value(0); - let val = s.rx_ended_count.load(Ordering::Relaxed); - s.rx_ended_count.store(val.wrapping_add(1), Ordering::Relaxed); - } + let val = s.rx_ended_count.load(Ordering::Relaxed); + s.rx_ended_count.store(val.wrapping_add(1), Ordering::Relaxed); + } - if r.events_rxstarted.read().bits() != 0 || !s.rx_started.load(Ordering::Relaxed) { - //trace!(" irq_rx: rxstarted"); - let (ptr, len) = rx.push_buf(); - if len >= half_len { - r.events_rxstarted.reset(); + if r.events_rxstarted().read() != 0 || !s.rx_started.load(Ordering::Relaxed) { + //trace!(" irq_rx: rxstarted"); + let (ptr, len) = rx.push_buf(); + if len >= half_len { + r.events_rxstarted().write_value(0); - //trace!(" irq_rx: starting second {:?}", half_len); + //trace!(" irq_rx: starting second {:?}", half_len); - // Set up the DMA read - r.rxd.ptr.write(|w| unsafe { w.ptr().bits(ptr as u32) }); - r.rxd.maxcnt.write(|w| unsafe { w.maxcnt().bits(half_len as _) }); + // Set up the DMA read + r.rxd().ptr().write_value(ptr as u32); + r.rxd().maxcnt().write(|w| w.set_maxcnt(half_len as _)); - let chn = s.rx_ppi_ch.load(Ordering::Relaxed); + let chn = s.rx_ppi_ch.load(Ordering::Relaxed); - // Enable endrx -> startrx PPI channel. - // From this point on, if endrx happens, startrx is automatically fired. - ppi::regs().chenset.write(|w| unsafe { w.bits(1 << chn) }); + // Enable endrx -> startrx PPI channel. + // From this point on, if endrx happens, startrx is automatically fired. + ppi::regs().chenset().write(|w| w.0 = 1 << chn); - // It is possible that endrx happened BEFORE enabling the PPI. In this case - // the PPI channel doesn't trigger, and we'd hang. We have to detect this - // and manually start. + // It is possible that endrx happened BEFORE enabling the PPI. In this case + // the PPI channel doesn't trigger, and we'd hang. We have to detect this + // and manually start. - // check again in case endrx has happened between the last check and now. - if r.events_endrx.read().bits() != 0 { - //trace!(" irq_rx: endrx"); - r.events_endrx.reset(); + // check again in case endrx has happened between the last check and now. + if r.events_endrx().read() != 0 { + //trace!(" irq_rx: endrx"); + r.events_endrx().write_value(0); - let val = s.rx_ended_count.load(Ordering::Relaxed); - s.rx_ended_count.store(val.wrapping_add(1), Ordering::Relaxed); + let val = s.rx_ended_count.load(Ordering::Relaxed); + s.rx_ended_count.store(val.wrapping_add(1), Ordering::Relaxed); + } + + let rx_ended = s.rx_ended_count.load(Ordering::Relaxed); + let rx_started = s.rx_started_count.load(Ordering::Relaxed); + + // If we started the same amount of transfers as ended, the last rxend has + // already occured. + let rxend_happened = rx_started == rx_ended; + + // Check if the PPI channel is still enabled. The PPI channel disables itself + // when it fires, so if it's still enabled it hasn't fired. + let ppi_ch_enabled = ppi::regs().chen().read().ch(chn as _); + + // if rxend happened, and the ppi channel hasn't fired yet, the rxend got missed. + // this condition also naturally matches if `!started`, needed to kickstart the DMA. + if rxend_happened && ppi_ch_enabled { + //trace!("manually starting."); + + // disable the ppi ch, it's of no use anymore. + ppi::regs().chenclr().write(|w| w.set_ch(chn as _, true)); + + // manually start + r.tasks_startrx().write_value(1); + } + + rx.push_done(half_len); + + s.rx_started_count.store(rx_started.wrapping_add(1), Ordering::Relaxed); + s.rx_started.store(true, Ordering::Relaxed); + } else { + //trace!(" irq_rx: rxstarted no buf"); + r.intenclr().write(|w| w.set_rxstarted(true)); } - - let rx_ended = s.rx_ended_count.load(Ordering::Relaxed); - let rx_started = s.rx_started_count.load(Ordering::Relaxed); - - // If we started the same amount of transfers as ended, the last rxend has - // already occured. - let rxend_happened = rx_started == rx_ended; - - // Check if the PPI channel is still enabled. The PPI channel disables itself - // when it fires, so if it's still enabled it hasn't fired. - let ppi_ch_enabled = ppi::regs().chen.read().bits() & (1 << chn) != 0; - - // if rxend happened, and the ppi channel hasn't fired yet, the rxend got missed. - // this condition also naturally matches if `!started`, needed to kickstart the DMA. - if rxend_happened && ppi_ch_enabled { - //trace!("manually starting."); - - // disable the ppi ch, it's of no use anymore. - ppi::regs().chenclr.write(|w| unsafe { w.bits(1 << chn) }); - - // manually start - r.tasks_startrx.write(|w| unsafe { w.bits(1) }); - } - - rx.push_done(half_len); - - s.rx_started_count.store(rx_started.wrapping_add(1), Ordering::Relaxed); - s.rx_started.store(true, Ordering::Relaxed); - } else { - //trace!(" irq_rx: rxstarted no buf"); - r.intenclr.write(|w| w.rxstarted().clear()); } } // ============================= - // TX end - if r.events_endtx.read().bits() != 0 { - r.events_endtx.reset(); + if let Some(mut tx) = unsafe { s.tx_buf.try_reader() } { + // TX end + if r.events_endtx().read() != 0 { + r.events_endtx().write_value(0); - let n = s.tx_count.load(Ordering::Relaxed); - //trace!(" irq_tx: endtx {:?}", n); - tx.pop_done(n); - s.tx_waker.wake(); - s.tx_count.store(0, Ordering::Relaxed); - } + let n = s.tx_count.load(Ordering::Relaxed); + //trace!(" irq_tx: endtx {:?}", n); + tx.pop_done(n); + ss.tx_waker.wake(); + s.tx_count.store(0, Ordering::Relaxed); + } - // If not TXing, start. - if s.tx_count.load(Ordering::Relaxed) == 0 { - let (ptr, len) = tx.pop_buf(); - if len != 0 { - //trace!(" irq_tx: starting {:?}", len); - s.tx_count.store(len, Ordering::Relaxed); + // If not TXing, start. + if s.tx_count.load(Ordering::Relaxed) == 0 { + let (ptr, len) = tx.pop_buf(); + let len = len.min(EASY_DMA_SIZE); + if len != 0 { + //trace!(" irq_tx: starting {:?}", len); + s.tx_count.store(len, Ordering::Relaxed); - // Set up the DMA write - r.txd.ptr.write(|w| unsafe { w.ptr().bits(ptr as u32) }); - r.txd.maxcnt.write(|w| unsafe { w.maxcnt().bits(len as _) }); + // Set up the DMA write + r.txd().ptr().write_value(ptr as u32); + r.txd().maxcnt().write(|w| w.set_maxcnt(len as _)); - // Start UARTE Transmit transaction - r.tasks_starttx.write(|w| unsafe { w.bits(1) }); + // Start UARTE Transmit transaction + r.tasks_starttx().write_value(1); + } } } @@ -215,11 +208,8 @@ impl interrupt::typelevel::Handler for Interrupt /// Buffered UARTE driver. pub struct BufferedUarte<'d, U: UarteInstance, T: TimerInstance> { - _peri: PeripheralRef<'d, U>, - timer: Timer<'d, T>, - _ppi_ch1: Ppi<'d, AnyConfigurableChannel, 1, 1>, - _ppi_ch2: Ppi<'d, AnyConfigurableChannel, 1, 2>, - _ppi_group: PpiGroup<'d, AnyGroup>, + tx: BufferedUarteTx<'d, U>, + rx: BufferedUarteRx<'d, U, T>, } impl<'d, U: UarteInstance, T: TimerInstance> Unpin for BufferedUarte<'d, U, T> {} @@ -230,6 +220,7 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> { /// # Panics /// /// Panics if `rx_buffer.len()` is odd. + #[allow(clippy::too_many_arguments)] pub fn new( uarte: impl Peripheral

+ 'd, timer: impl Peripheral

+ 'd, @@ -243,7 +234,7 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> { rx_buffer: &'d mut [u8], tx_buffer: &'d mut [u8], ) -> Self { - into_ref!(rxd, txd, ppi_ch1, ppi_ch2, ppi_group); + into_ref!(uarte, timer, rxd, txd, ppi_ch1, ppi_ch2, ppi_group); Self::new_inner( uarte, timer, @@ -265,6 +256,7 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> { /// # Panics /// /// Panics if `rx_buffer.len()` is odd. + #[allow(clippy::too_many_arguments)] pub fn new_with_rtscts( uarte: impl Peripheral

+ 'd, timer: impl Peripheral

+ 'd, @@ -280,7 +272,7 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> { rx_buffer: &'d mut [u8], tx_buffer: &'d mut [u8], ) -> Self { - into_ref!(rxd, txd, cts, rts, ppi_ch1, ppi_ch2, ppi_group); + into_ref!(uarte, timer, rxd, txd, cts, rts, ppi_ch1, ppi_ch2, ppi_group); Self::new_inner( uarte, timer, @@ -297,9 +289,10 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> { ) } + #[allow(clippy::too_many_arguments)] fn new_inner( - peri: impl Peripheral

+ 'd, - timer: impl Peripheral

+ 'd, + peri: PeripheralRef<'d, U>, + timer: PeripheralRef<'d, T>, ppi_ch1: PeripheralRef<'d, AnyConfigurableChannel>, ppi_ch2: PeripheralRef<'d, AnyConfigurableChannel>, ppi_group: PeripheralRef<'d, AnyGroup>, @@ -311,143 +304,165 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> { rx_buffer: &'d mut [u8], tx_buffer: &'d mut [u8], ) -> Self { - into_ref!(peri, timer); + configure(U::regs(), config, cts.is_some()); - assert!(rx_buffer.len() % 2 == 0); - - let r = U::regs(); - - let hwfc = cts.is_some(); - - rxd.conf().write(|w| w.input().connect().drive().h0h1()); - r.psel.rxd.write(|w| unsafe { w.bits(rxd.psel_bits()) }); - - txd.set_high(); - txd.conf().write(|w| w.dir().output().drive().h0h1()); - r.psel.txd.write(|w| unsafe { w.bits(txd.psel_bits()) }); - - if let Some(pin) = &cts { - pin.conf().write(|w| w.input().connect().drive().h0h1()); - } - r.psel.cts.write(|w| unsafe { w.bits(cts.psel_bits()) }); - - if let Some(pin) = &rts { - pin.set_high(); - pin.conf().write(|w| w.dir().output().drive().h0h1()); - } - r.psel.rts.write(|w| unsafe { w.bits(rts.psel_bits()) }); - - // Initialize state - let s = U::buffered_state(); - s.tx_count.store(0, Ordering::Relaxed); - s.rx_started_count.store(0, Ordering::Relaxed); - s.rx_ended_count.store(0, Ordering::Relaxed); - s.rx_started.store(false, Ordering::Relaxed); - let len = tx_buffer.len(); - unsafe { s.tx_buf.init(tx_buffer.as_mut_ptr(), len) }; - let len = rx_buffer.len(); - unsafe { s.rx_buf.init(rx_buffer.as_mut_ptr(), len) }; - - // Configure - r.config.write(|w| { - w.hwfc().bit(hwfc); - w.parity().variant(config.parity); - w - }); - r.baudrate.write(|w| w.baudrate().variant(config.baudrate)); - - // clear errors - let errors = r.errorsrc.read().bits(); - r.errorsrc.write(|w| unsafe { w.bits(errors) }); - - r.events_rxstarted.reset(); - r.events_txstarted.reset(); - r.events_error.reset(); - r.events_endrx.reset(); - r.events_endtx.reset(); - - // Enable interrupts - r.intenclr.write(|w| unsafe { w.bits(!0) }); - r.intenset.write(|w| { - w.endtx().set(); - w.rxstarted().set(); - w.error().set(); - w.endrx().set(); - w - }); - - // Enable UARTE instance - apply_workaround_for_enable_anomaly(&r); - r.enable.write(|w| w.enable().enabled()); - - // Configure byte counter. - let timer = Timer::new_counter(timer); - timer.cc(1).write(rx_buffer.len() as u32 * 2); - timer.cc(1).short_compare_clear(); - timer.clear(); - timer.start(); - - let mut ppi_ch1 = Ppi::new_one_to_one(ppi_ch1, Event::from_reg(&r.events_rxdrdy), timer.task_count()); - ppi_ch1.enable(); - - s.rx_ppi_ch.store(ppi_ch2.number() as u8, Ordering::Relaxed); - let mut ppi_group = PpiGroup::new(ppi_group); - let mut ppi_ch2 = Ppi::new_one_to_two( - ppi_ch2, - Event::from_reg(&r.events_endrx), - Task::from_reg(&r.tasks_startrx), - ppi_group.task_disable_all(), - ); - ppi_ch2.disable(); - ppi_group.add_channel(&ppi_ch2); + let tx = BufferedUarteTx::new_innerer(unsafe { peri.clone_unchecked() }, txd, cts, tx_buffer); + let rx = BufferedUarteRx::new_innerer(peri, timer, ppi_ch1, ppi_ch2, ppi_group, rxd, rts, rx_buffer); + U::regs().enable().write(|w| w.set_enable(vals::Enable::ENABLED)); U::Interrupt::pend(); unsafe { U::Interrupt::enable() }; - Self { - _peri: peri, - timer, - _ppi_ch1: ppi_ch1, - _ppi_ch2: ppi_ch2, - _ppi_group: ppi_group, - } - } + U::state().tx_rx_refcount.store(2, Ordering::Relaxed); - fn pend_irq() { - U::Interrupt::pend() + Self { tx, rx } } /// Adjust the baud rate to the provided value. pub fn set_baudrate(&mut self, baudrate: Baudrate) { let r = U::regs(); - r.baudrate.write(|w| w.baudrate().variant(baudrate)); + r.baudrate().write(|w| w.set_baudrate(baudrate)); } /// Split the UART in reader and writer parts. /// /// This allows reading and writing concurrently from independent tasks. - pub fn split<'u>(&'u mut self) -> (BufferedUarteRx<'u, 'd, U, T>, BufferedUarteTx<'u, 'd, U, T>) { - (BufferedUarteRx { inner: self }, BufferedUarteTx { inner: self }) + pub fn split(self) -> (BufferedUarteRx<'d, U, T>, BufferedUarteTx<'d, U>) { + (self.rx, self.tx) } - async fn inner_read(&self, buf: &mut [u8]) -> Result { - let data = self.inner_fill_buf().await?; - let n = data.len().min(buf.len()); - buf[..n].copy_from_slice(&data[..n]); - self.inner_consume(n); - Ok(n) + /// Split the UART in reader and writer parts, by reference. + /// + /// The returned halves borrow from `self`, so you can drop them and go back to using + /// the "un-split" `self`. This allows temporarily splitting the UART. + pub fn split_by_ref(&mut self) -> (&mut BufferedUarteRx<'d, U, T>, &mut BufferedUarteTx<'d, U>) { + (&mut self.rx, &mut self.tx) } - async fn inner_write<'a>(&'a self, buf: &'a [u8]) -> Result { + /// Pull some bytes from this source into the specified buffer, returning how many bytes were read. + pub async fn read(&mut self, buf: &mut [u8]) -> Result { + self.rx.read(buf).await + } + + /// Return the contents of the internal buffer, filling it with more data from the inner reader if it is empty. + pub async fn fill_buf(&mut self) -> Result<&[u8], Error> { + self.rx.fill_buf().await + } + + /// Tell this buffer that `amt` bytes have been consumed from the buffer, so they should no longer be returned in calls to `fill_buf`. + pub fn consume(&mut self, amt: usize) { + self.rx.consume(amt) + } + + /// Write a buffer into this writer, returning how many bytes were written. + pub async fn write(&mut self, buf: &[u8]) -> Result { + self.tx.write(buf).await + } + + /// Try writing a buffer without waiting, returning how many bytes were written. + pub fn try_write(&mut self, buf: &[u8]) -> Result { + self.tx.try_write(buf) + } + + /// Flush this output stream, ensuring that all intermediately buffered contents reach their destination. + pub async fn flush(&mut self) -> Result<(), Error> { + self.tx.flush().await + } +} + +/// Reader part of the buffered UARTE driver. +pub struct BufferedUarteTx<'d, U: UarteInstance> { + _peri: PeripheralRef<'d, U>, +} + +impl<'d, U: UarteInstance> BufferedUarteTx<'d, U> { + /// Create a new BufferedUarteTx without hardware flow control. + pub fn new( + uarte: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + txd: impl Peripheral

+ 'd, + config: Config, + tx_buffer: &'d mut [u8], + ) -> Self { + into_ref!(uarte, txd); + Self::new_inner(uarte, txd.map_into(), None, config, tx_buffer) + } + + /// Create a new BufferedUarte with hardware flow control (RTS/CTS) + /// + /// # Panics + /// + /// Panics if `rx_buffer.len()` is odd. + pub fn new_with_cts( + uarte: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + txd: impl Peripheral

+ 'd, + cts: impl Peripheral

+ 'd, + config: Config, + tx_buffer: &'d mut [u8], + ) -> Self { + into_ref!(uarte, txd, cts); + Self::new_inner(uarte, txd.map_into(), Some(cts.map_into()), config, tx_buffer) + } + + fn new_inner( + peri: PeripheralRef<'d, U>, + txd: PeripheralRef<'d, AnyPin>, + cts: Option>, + config: Config, + tx_buffer: &'d mut [u8], + ) -> Self { + configure(U::regs(), config, cts.is_some()); + + let this = Self::new_innerer(peri, txd, cts, tx_buffer); + + U::regs().enable().write(|w| w.set_enable(vals::Enable::ENABLED)); + U::Interrupt::pend(); + unsafe { U::Interrupt::enable() }; + + U::state().tx_rx_refcount.store(1, Ordering::Relaxed); + + this + } + + fn new_innerer( + peri: PeripheralRef<'d, U>, + txd: PeripheralRef<'d, AnyPin>, + cts: Option>, + tx_buffer: &'d mut [u8], + ) -> Self { + let r = U::regs(); + + configure_tx_pins(r, txd, cts); + + // Initialize state + let s = U::buffered_state(); + s.tx_count.store(0, Ordering::Relaxed); + let len = tx_buffer.len(); + unsafe { s.tx_buf.init(tx_buffer.as_mut_ptr(), len) }; + + r.events_txstarted().write_value(0); + + // Enable interrupts + r.intenset().write(|w| { + w.set_endtx(true); + }); + + Self { _peri: peri } + } + + /// Write a buffer into this writer, returning how many bytes were written. + pub async fn write(&mut self, buf: &[u8]) -> Result { poll_fn(move |cx| { //trace!("poll_write: {:?}", buf.len()); + let ss = U::state(); let s = U::buffered_state(); let mut tx = unsafe { s.tx_buf.writer() }; let tx_buf = tx.push_slice(); if tx_buf.is_empty() { //trace!("poll_write: pending"); - s.tx_waker.register(cx.waker()); + ss.tx_waker.register(cx.waker()); return Poll::Pending; } @@ -458,20 +473,45 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> { //trace!("poll_write: queued {:?}", n); compiler_fence(Ordering::SeqCst); - Self::pend_irq(); + U::Interrupt::pend(); Poll::Ready(Ok(n)) }) .await } - async fn inner_flush<'a>(&'a self) -> Result<(), Error> { + /// Try writing a buffer without waiting, returning how many bytes were written. + pub fn try_write(&mut self, buf: &[u8]) -> Result { + //trace!("poll_write: {:?}", buf.len()); + let s = U::buffered_state(); + let mut tx = unsafe { s.tx_buf.writer() }; + + let tx_buf = tx.push_slice(); + if tx_buf.is_empty() { + return Ok(0); + } + + let n = min(tx_buf.len(), buf.len()); + tx_buf[..n].copy_from_slice(&buf[..n]); + tx.push_done(n); + + //trace!("poll_write: queued {:?}", n); + + compiler_fence(Ordering::SeqCst); + U::Interrupt::pend(); + + Ok(n) + } + + /// Flush this output stream, ensuring that all intermediately buffered contents reach their destination. + pub async fn flush(&mut self) -> Result<(), Error> { poll_fn(move |cx| { //trace!("poll_flush"); + let ss = U::state(); let s = U::buffered_state(); if !s.tx_buf.is_empty() { //trace!("poll_flush: pending"); - s.tx_waker.register(cx.waker()); + ss.tx_waker.register(cx.waker()); return Poll::Pending; } @@ -479,18 +519,220 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> { }) .await } +} - async fn inner_fill_buf<'a>(&'a self) -> Result<&'a [u8], Error> { +impl<'a, U: UarteInstance> Drop for BufferedUarteTx<'a, U> { + fn drop(&mut self) { + let r = U::regs(); + + r.intenclr().write(|w| { + w.set_txdrdy(true); + w.set_txstarted(true); + w.set_txstopped(true); + }); + r.events_txstopped().write_value(0); + r.tasks_stoptx().write_value(1); + while r.events_txstopped().read() == 0 {} + + let s = U::buffered_state(); + unsafe { s.tx_buf.deinit() } + + let s = U::state(); + drop_tx_rx(r, s); + } +} + +/// Reader part of the buffered UARTE driver. +pub struct BufferedUarteRx<'d, U: UarteInstance, T: TimerInstance> { + _peri: PeripheralRef<'d, U>, + timer: Timer<'d, T>, + _ppi_ch1: Ppi<'d, AnyConfigurableChannel, 1, 1>, + _ppi_ch2: Ppi<'d, AnyConfigurableChannel, 1, 2>, + _ppi_group: PpiGroup<'d, AnyGroup>, +} + +impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarteRx<'d, U, T> { + /// Create a new BufferedUarte without hardware flow control. + /// + /// # Panics + /// + /// Panics if `rx_buffer.len()` is odd. + #[allow(clippy::too_many_arguments)] + pub fn new( + uarte: impl Peripheral

+ 'd, + timer: impl Peripheral

+ 'd, + ppi_ch1: impl Peripheral

+ 'd, + ppi_ch2: impl Peripheral

+ 'd, + ppi_group: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + rxd: impl Peripheral

+ 'd, + config: Config, + rx_buffer: &'d mut [u8], + ) -> Self { + into_ref!(uarte, timer, rxd, ppi_ch1, ppi_ch2, ppi_group); + Self::new_inner( + uarte, + timer, + ppi_ch1.map_into(), + ppi_ch2.map_into(), + ppi_group.map_into(), + rxd.map_into(), + None, + config, + rx_buffer, + ) + } + + /// Create a new BufferedUarte with hardware flow control (RTS/CTS) + /// + /// # Panics + /// + /// Panics if `rx_buffer.len()` is odd. + #[allow(clippy::too_many_arguments)] + pub fn new_with_rts( + uarte: impl Peripheral

+ 'd, + timer: impl Peripheral

+ 'd, + ppi_ch1: impl Peripheral

+ 'd, + ppi_ch2: impl Peripheral

+ 'd, + ppi_group: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + rxd: impl Peripheral

+ 'd, + rts: impl Peripheral

+ 'd, + config: Config, + rx_buffer: &'d mut [u8], + ) -> Self { + into_ref!(uarte, timer, rxd, rts, ppi_ch1, ppi_ch2, ppi_group); + Self::new_inner( + uarte, + timer, + ppi_ch1.map_into(), + ppi_ch2.map_into(), + ppi_group.map_into(), + rxd.map_into(), + Some(rts.map_into()), + config, + rx_buffer, + ) + } + + #[allow(clippy::too_many_arguments)] + fn new_inner( + peri: PeripheralRef<'d, U>, + timer: PeripheralRef<'d, T>, + ppi_ch1: PeripheralRef<'d, AnyConfigurableChannel>, + ppi_ch2: PeripheralRef<'d, AnyConfigurableChannel>, + ppi_group: PeripheralRef<'d, AnyGroup>, + rxd: PeripheralRef<'d, AnyPin>, + rts: Option>, + config: Config, + rx_buffer: &'d mut [u8], + ) -> Self { + configure(U::regs(), config, rts.is_some()); + + let this = Self::new_innerer(peri, timer, ppi_ch1, ppi_ch2, ppi_group, rxd, rts, rx_buffer); + + U::regs().enable().write(|w| w.set_enable(vals::Enable::ENABLED)); + U::Interrupt::pend(); + unsafe { U::Interrupt::enable() }; + + U::state().tx_rx_refcount.store(1, Ordering::Relaxed); + + this + } + + #[allow(clippy::too_many_arguments)] + fn new_innerer( + peri: PeripheralRef<'d, U>, + timer: PeripheralRef<'d, T>, + ppi_ch1: PeripheralRef<'d, AnyConfigurableChannel>, + ppi_ch2: PeripheralRef<'d, AnyConfigurableChannel>, + ppi_group: PeripheralRef<'d, AnyGroup>, + rxd: PeripheralRef<'d, AnyPin>, + rts: Option>, + rx_buffer: &'d mut [u8], + ) -> Self { + assert!(rx_buffer.len() % 2 == 0); + + let r = U::regs(); + + configure_rx_pins(r, rxd, rts); + + // Initialize state + let s = U::buffered_state(); + s.rx_started_count.store(0, Ordering::Relaxed); + s.rx_ended_count.store(0, Ordering::Relaxed); + s.rx_started.store(false, Ordering::Relaxed); + let rx_len = rx_buffer.len().min(EASY_DMA_SIZE * 2); + unsafe { s.rx_buf.init(rx_buffer.as_mut_ptr(), rx_len) }; + + // clear errors + let errors = r.errorsrc().read(); + r.errorsrc().write_value(errors); + + r.events_rxstarted().write_value(0); + r.events_error().write_value(0); + r.events_endrx().write_value(0); + + // Enable interrupts + r.intenset().write(|w| { + w.set_endtx(true); + w.set_rxstarted(true); + w.set_error(true); + w.set_endrx(true); + }); + + // Configure byte counter. + let timer = Timer::new_counter(timer); + timer.cc(1).write(rx_len as u32 * 2); + timer.cc(1).short_compare_clear(); + timer.clear(); + timer.start(); + + let mut ppi_ch1 = Ppi::new_one_to_one(ppi_ch1, Event::from_reg(r.events_rxdrdy()), timer.task_count()); + ppi_ch1.enable(); + + s.rx_ppi_ch.store(ppi_ch2.number() as u8, Ordering::Relaxed); + let mut ppi_group = PpiGroup::new(ppi_group); + let mut ppi_ch2 = Ppi::new_one_to_two( + ppi_ch2, + Event::from_reg(r.events_endrx()), + Task::from_reg(r.tasks_startrx()), + ppi_group.task_disable_all(), + ); + ppi_ch2.disable(); + ppi_group.add_channel(&ppi_ch2); + + Self { + _peri: peri, + timer, + _ppi_ch1: ppi_ch1, + _ppi_ch2: ppi_ch2, + _ppi_group: ppi_group, + } + } + + /// Pull some bytes from this source into the specified buffer, returning how many bytes were read. + pub async fn read(&mut self, buf: &mut [u8]) -> Result { + let data = self.fill_buf().await?; + let n = data.len().min(buf.len()); + buf[..n].copy_from_slice(&data[..n]); + self.consume(n); + Ok(n) + } + + /// Return the contents of the internal buffer, filling it with more data from the inner reader if it is empty. + pub async fn fill_buf(&mut self) -> Result<&[u8], Error> { poll_fn(move |cx| { compiler_fence(Ordering::SeqCst); //trace!("poll_read"); let r = U::regs(); let s = U::buffered_state(); + let ss = U::state(); // Read the RXDRDY counter. - T::regs().tasks_capture[0].write(|w| unsafe { w.bits(1) }); - let mut end = T::regs().cc[0].read().bits() as usize; + T::regs().tasks_capture(0).write_value(1); + let mut end = T::regs().cc(0).read() as usize; //trace!(" rxdrdy count = {:?}", end); // We've set a compare channel that resets the counter to 0 when it reaches `len*2`. @@ -510,8 +752,8 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> { let len = s.rx_buf.len(); if start == end { //trace!(" empty"); - s.rx_waker.register(cx.waker()); - r.intenset.write(|w| w.rxdrdy().set_bit()); + ss.rx_waker.register(cx.waker()); + r.intenset().write(|w| w.set_rxdrdy(true)); return Poll::Pending; } @@ -532,7 +774,8 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> { .await } - fn inner_consume(&self, amt: usize) { + /// Tell this buffer that `amt` bytes have been consumed from the buffer, so they should no longer be returned in calls to `fill_buf`. + pub fn consume(&mut self, amt: usize) { if amt == 0 { return; } @@ -540,71 +783,38 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> { let s = U::buffered_state(); let mut rx = unsafe { s.rx_buf.reader() }; rx.pop_done(amt); - U::regs().intenset.write(|w| w.rxstarted().set()); + U::regs().intenset().write(|w| w.set_rxstarted(true)); } - /// Pull some bytes from this source into the specified buffer, returning how many bytes were read. - pub async fn read(&mut self, buf: &mut [u8]) -> Result { - self.inner_read(buf).await - } - - /// Return the contents of the internal buffer, filling it with more data from the inner reader if it is empty. - pub async fn fill_buf(&mut self) -> Result<&[u8], Error> { - self.inner_fill_buf().await - } - - /// Tell this buffer that `amt` bytes have been consumed from the buffer, so they should no longer be returned in calls to `fill_buf`. - pub fn consume(&mut self, amt: usize) { - self.inner_consume(amt) - } - - /// Write a buffer into this writer, returning how many bytes were written. - pub async fn write(&mut self, buf: &[u8]) -> Result { - self.inner_write(buf).await - } - - /// Flush this output stream, ensuring that all intermediately buffered contents reach their destination. - pub async fn flush(&mut self) -> Result<(), Error> { - self.inner_flush().await + /// we are ready to read if there is data in the buffer + fn read_ready() -> Result { + let state = U::buffered_state(); + Ok(!state.rx_buf.is_empty()) } } -/// Reader part of the buffered UARTE driver. -pub struct BufferedUarteTx<'u, 'd, U: UarteInstance, T: TimerInstance> { - inner: &'u BufferedUarte<'d, U, T>, -} +impl<'a, U: UarteInstance, T: TimerInstance> Drop for BufferedUarteRx<'a, U, T> { + fn drop(&mut self) { + self._ppi_group.disable_all(); -impl<'u, 'd, U: UarteInstance, T: TimerInstance> BufferedUarteTx<'u, 'd, U, T> { - /// Write a buffer into this writer, returning how many bytes were written. - pub async fn write(&mut self, buf: &[u8]) -> Result { - self.inner.inner_write(buf).await - } + let r = U::regs(); - /// Flush this output stream, ensuring that all intermediately buffered contents reach their destination. - pub async fn flush(&mut self) -> Result<(), Error> { - self.inner.inner_flush().await - } -} + self.timer.stop(); -/// Writer part of the buffered UARTE driver. -pub struct BufferedUarteRx<'u, 'd, U: UarteInstance, T: TimerInstance> { - inner: &'u BufferedUarte<'d, U, T>, -} + r.intenclr().write(|w| { + w.set_rxdrdy(true); + w.set_rxstarted(true); + w.set_rxto(true); + }); + r.events_rxto().write_value(0); + r.tasks_stoprx().write_value(1); + while r.events_rxto().read() == 0 {} -impl<'u, 'd, U: UarteInstance, T: TimerInstance> BufferedUarteRx<'u, 'd, U, T> { - /// Pull some bytes from this source into the specified buffer, returning how many bytes were read. - pub async fn read(&mut self, buf: &mut [u8]) -> Result { - self.inner.inner_read(buf).await - } + let s = U::buffered_state(); + unsafe { s.rx_buf.deinit() } - /// Return the contents of the internal buffer, filling it with more data from the inner reader if it is empty. - pub async fn fill_buf(&mut self) -> Result<&[u8], Error> { - self.inner.inner_fill_buf().await - } - - /// Tell this buffer that `amt` bytes have been consumed from the buffer, so they should no longer be returned in calls to `fill_buf`. - pub fn consume(&mut self, amt: usize) { - self.inner.inner_consume(amt) + let s = U::state(); + drop_tx_rx(r, s); } } @@ -621,95 +831,75 @@ mod _embedded_io { type Error = Error; } - impl<'u, 'd, U: UarteInstance, T: TimerInstance> embedded_io_async::ErrorType for BufferedUarteRx<'u, 'd, U, T> { + impl<'d, U: UarteInstance, T: TimerInstance> embedded_io_async::ErrorType for BufferedUarteRx<'d, U, T> { type Error = Error; } - impl<'u, 'd, U: UarteInstance, T: TimerInstance> embedded_io_async::ErrorType for BufferedUarteTx<'u, 'd, U, T> { + impl<'d, U: UarteInstance> embedded_io_async::ErrorType for BufferedUarteTx<'d, U> { type Error = Error; } impl<'d, U: UarteInstance, T: TimerInstance> embedded_io_async::Read for BufferedUarte<'d, U, T> { async fn read(&mut self, buf: &mut [u8]) -> Result { - self.inner_read(buf).await + self.read(buf).await } } - impl<'u, 'd: 'u, U: UarteInstance, T: TimerInstance> embedded_io_async::Read for BufferedUarteRx<'u, 'd, U, T> { + impl<'d: 'd, U: UarteInstance, T: TimerInstance> embedded_io_async::Read for BufferedUarteRx<'d, U, T> { async fn read(&mut self, buf: &mut [u8]) -> Result { - self.inner.inner_read(buf).await + self.read(buf).await + } + } + + impl<'d, U: UarteInstance, T: TimerInstance + 'd> embedded_io_async::ReadReady for BufferedUarte<'d, U, T> { + fn read_ready(&mut self) -> Result { + BufferedUarteRx::<'d, U, T>::read_ready() + } + } + + impl<'d, U: UarteInstance, T: TimerInstance + 'd> embedded_io_async::ReadReady for BufferedUarteRx<'d, U, T> { + fn read_ready(&mut self) -> Result { + Self::read_ready() } } impl<'d, U: UarteInstance, T: TimerInstance> embedded_io_async::BufRead for BufferedUarte<'d, U, T> { async fn fill_buf(&mut self) -> Result<&[u8], Self::Error> { - self.inner_fill_buf().await + self.fill_buf().await } fn consume(&mut self, amt: usize) { - self.inner_consume(amt) + self.consume(amt) } } - impl<'u, 'd: 'u, U: UarteInstance, T: TimerInstance> embedded_io_async::BufRead for BufferedUarteRx<'u, 'd, U, T> { + impl<'d: 'd, U: UarteInstance, T: TimerInstance> embedded_io_async::BufRead for BufferedUarteRx<'d, U, T> { async fn fill_buf(&mut self) -> Result<&[u8], Self::Error> { - self.inner.inner_fill_buf().await + self.fill_buf().await } fn consume(&mut self, amt: usize) { - self.inner.inner_consume(amt) + self.consume(amt) } } impl<'d, U: UarteInstance, T: TimerInstance> embedded_io_async::Write for BufferedUarte<'d, U, T> { async fn write(&mut self, buf: &[u8]) -> Result { - self.inner_write(buf).await + self.write(buf).await } async fn flush(&mut self) -> Result<(), Self::Error> { - self.inner_flush().await + self.flush().await } } - impl<'u, 'd: 'u, U: UarteInstance, T: TimerInstance> embedded_io_async::Write for BufferedUarteTx<'u, 'd, U, T> { + impl<'d: 'd, U: UarteInstance> embedded_io_async::Write for BufferedUarteTx<'d, U> { async fn write(&mut self, buf: &[u8]) -> Result { - self.inner.inner_write(buf).await + self.write(buf).await } async fn flush(&mut self) -> Result<(), Self::Error> { - self.inner.inner_flush().await - } - } -} - -impl<'a, U: UarteInstance, T: TimerInstance> Drop for BufferedUarte<'a, U, T> { - fn drop(&mut self) { - self._ppi_group.disable_all(); - - let r = U::regs(); - - self.timer.stop(); - - r.inten.reset(); - r.events_rxto.reset(); - r.tasks_stoprx.write(|w| unsafe { w.bits(1) }); - r.events_txstopped.reset(); - r.tasks_stoptx.write(|w| unsafe { w.bits(1) }); - - while r.events_txstopped.read().bits() == 0 {} - while r.events_rxto.read().bits() == 0 {} - - r.enable.write(|w| w.enable().disabled()); - - gpio::deconfigure_pin(r.psel.rxd.read().bits()); - gpio::deconfigure_pin(r.psel.txd.read().bits()); - gpio::deconfigure_pin(r.psel.rts.read().bits()); - gpio::deconfigure_pin(r.psel.cts.read().bits()); - - let s = U::buffered_state(); - unsafe { - s.rx_buf.deinit(); - s.tx_buf.deinit(); + self.flush().await } } } diff --git a/embassy-nrf/src/chips/nrf51.rs b/embassy-nrf/src/chips/nrf51.rs index 016352fb8..95fa926c3 100644 --- a/embassy-nrf/src/chips/nrf51.rs +++ b/embassy-nrf/src/chips/nrf51.rs @@ -1,4 +1,4 @@ -pub use nrf51_pac as pac; +pub use nrf_pac as pac; /// The maximum buffer size that the EasyDMA can send/recv in one operation. pub const EASY_DMA_SIZE: usize = (1 << 14) - 1; @@ -99,6 +99,9 @@ embassy_hal_internal::peripherals! { // TEMP TEMP, + + // Radio + RADIO, } impl_timer!(TIMER0, TIMER0, TIMER0); @@ -140,6 +143,8 @@ impl_pin!(P0_29, 0, 29); impl_pin!(P0_30, 0, 30); impl_pin!(P0_31, 0, 31); +impl_radio!(RADIO, RADIO, RADIO); + embassy_hal_internal::interrupt_mod!( POWER_CLOCK, RADIO, diff --git a/embassy-nrf/src/chips/nrf52805.rs b/embassy-nrf/src/chips/nrf52805.rs index 624d6613d..fc8db856c 100644 --- a/embassy-nrf/src/chips/nrf52805.rs +++ b/embassy-nrf/src/chips/nrf52805.rs @@ -1,4 +1,4 @@ -pub use nrf52805_pac as pac; +pub use nrf_pac as pac; /// The maximum buffer size that the EasyDMA can send/recv in one operation. pub const EASY_DMA_SIZE: usize = (1 << 14) - 1; @@ -129,6 +129,13 @@ embassy_hal_internal::peripherals! { // QDEC QDEC, + + // Radio + RADIO, + + // EGU + EGU0, + EGU1, } impl_uarte!(UARTE0, UARTE0, UARTE0_UART0); @@ -209,6 +216,11 @@ impl_ppi_channel!(PPI_CH31, 31 => static); impl_saadc_input!(P0_04, ANALOG_INPUT2); impl_saadc_input!(P0_05, ANALOG_INPUT3); +impl_radio!(RADIO, RADIO, RADIO); + +impl_egu!(EGU0, EGU0, SWI0_EGU0); +impl_egu!(EGU1, EGU1, SWI1_EGU1); + embassy_hal_internal::interrupt_mod!( POWER_CLOCK, RADIO, diff --git a/embassy-nrf/src/chips/nrf52810.rs b/embassy-nrf/src/chips/nrf52810.rs index 002feab3b..11a8b4dde 100644 --- a/embassy-nrf/src/chips/nrf52810.rs +++ b/embassy-nrf/src/chips/nrf52810.rs @@ -1,4 +1,4 @@ -pub use nrf52810_pac as pac; +pub use nrf_pac as pac; /// The maximum buffer size that the EasyDMA can send/recv in one operation. pub const EASY_DMA_SIZE: usize = (1 << 10) - 1; @@ -135,6 +135,13 @@ embassy_hal_internal::peripherals! { // PDM PDM, + + // Radio + RADIO, + + // EGU + EGU0, + EGU1, } impl_uarte!(UARTE0, UARTE0, UARTE0_UART0); @@ -235,6 +242,11 @@ impl_saadc_input!(P0_29, ANALOG_INPUT5); impl_saadc_input!(P0_30, ANALOG_INPUT6); impl_saadc_input!(P0_31, ANALOG_INPUT7); +impl_radio!(RADIO, RADIO, RADIO); + +impl_egu!(EGU0, EGU0, SWI0_EGU0); +impl_egu!(EGU1, EGU1, SWI1_EGU1); + embassy_hal_internal::interrupt_mod!( POWER_CLOCK, RADIO, diff --git a/embassy-nrf/src/chips/nrf52811.rs b/embassy-nrf/src/chips/nrf52811.rs index 5952907f8..077a36e31 100644 --- a/embassy-nrf/src/chips/nrf52811.rs +++ b/embassy-nrf/src/chips/nrf52811.rs @@ -1,4 +1,4 @@ -pub use nrf52811_pac as pac; +pub use nrf_pac as pac; /// The maximum buffer size that the EasyDMA can send/recv in one operation. pub const EASY_DMA_SIZE: usize = (1 << 14) - 1; @@ -135,6 +135,13 @@ embassy_hal_internal::peripherals! { // PDM PDM, + + // Radio + RADIO, + + // EGU + EGU0, + EGU1, } impl_uarte!(UARTE0, UARTE0, UARTE0_UART0); @@ -237,6 +244,11 @@ impl_saadc_input!(P0_29, ANALOG_INPUT5); impl_saadc_input!(P0_30, ANALOG_INPUT6); impl_saadc_input!(P0_31, ANALOG_INPUT7); +impl_radio!(RADIO, RADIO, RADIO); + +impl_egu!(EGU0, EGU0, SWI0_EGU0); +impl_egu!(EGU1, EGU1, SWI1_EGU1); + embassy_hal_internal::interrupt_mod!( POWER_CLOCK, RADIO, diff --git a/embassy-nrf/src/chips/nrf52820.rs b/embassy-nrf/src/chips/nrf52820.rs index c2f792cb9..6ee16706d 100644 --- a/embassy-nrf/src/chips/nrf52820.rs +++ b/embassy-nrf/src/chips/nrf52820.rs @@ -1,4 +1,4 @@ -pub use nrf52820_pac as pac; +pub use nrf_pac as pac; /// The maximum buffer size that the EasyDMA can send/recv in one operation. pub const EASY_DMA_SIZE: usize = (1 << 15) - 1; @@ -130,6 +130,17 @@ embassy_hal_internal::peripherals! { // QDEC QDEC, + + // Radio + RADIO, + + // EGU + EGU0, + EGU1, + EGU2, + EGU3, + EGU4, + EGU5, } impl_usb!(USBD, USBD, USBD); @@ -224,6 +235,15 @@ impl_ppi_channel!(PPI_CH29, 29 => static); impl_ppi_channel!(PPI_CH30, 30 => static); impl_ppi_channel!(PPI_CH31, 31 => static); +impl_radio!(RADIO, RADIO, RADIO); + +impl_egu!(EGU0, EGU0, SWI0_EGU0); +impl_egu!(EGU1, EGU1, SWI1_EGU1); +impl_egu!(EGU2, EGU2, SWI2_EGU2); +impl_egu!(EGU3, EGU3, SWI3_EGU3); +impl_egu!(EGU4, EGU4, SWI4_EGU4); +impl_egu!(EGU5, EGU5, SWI5_EGU5); + embassy_hal_internal::interrupt_mod!( POWER_CLOCK, RADIO, diff --git a/embassy-nrf/src/chips/nrf52832.rs b/embassy-nrf/src/chips/nrf52832.rs index 65d52364d..4a7a29229 100644 --- a/embassy-nrf/src/chips/nrf52832.rs +++ b/embassy-nrf/src/chips/nrf52832.rs @@ -1,4 +1,4 @@ -pub use nrf52832_pac as pac; +pub use nrf_pac as pac; /// The maximum buffer size that the EasyDMA can send/recv in one operation. pub const EASY_DMA_SIZE: usize = (1 << 8) - 1; @@ -150,6 +150,17 @@ embassy_hal_internal::peripherals! { // PDM PDM, + + // Radio + RADIO, + + // EGU + EGU0, + EGU1, + EGU2, + EGU3, + EGU4, + EGU5, } impl_uarte!(UARTE0, UARTE0, UARTE0_UART0); @@ -264,6 +275,15 @@ impl_saadc_input!(P0_31, ANALOG_INPUT7); impl_i2s!(I2S, I2S, I2S); +impl_radio!(RADIO, RADIO, RADIO); + +impl_egu!(EGU0, EGU0, SWI0_EGU0); +impl_egu!(EGU1, EGU1, SWI1_EGU1); +impl_egu!(EGU2, EGU2, SWI2_EGU2); +impl_egu!(EGU3, EGU3, SWI3_EGU3); +impl_egu!(EGU4, EGU4, SWI4_EGU4); +impl_egu!(EGU5, EGU5, SWI5_EGU5); + embassy_hal_internal::interrupt_mod!( POWER_CLOCK, RADIO, diff --git a/embassy-nrf/src/chips/nrf52833.rs b/embassy-nrf/src/chips/nrf52833.rs index 7c9b66d69..6d70b763f 100644 --- a/embassy-nrf/src/chips/nrf52833.rs +++ b/embassy-nrf/src/chips/nrf52833.rs @@ -1,4 +1,4 @@ -pub use nrf52833_pac as pac; +pub use nrf_pac as pac; /// The maximum buffer size that the EasyDMA can send/recv in one operation. pub const EASY_DMA_SIZE: usize = (1 << 16) - 1; @@ -170,6 +170,17 @@ embassy_hal_internal::peripherals! { // I2S I2S, + + // Radio + RADIO, + + // EGU + EGU0, + EGU1, + EGU2, + EGU3, + EGU4, + EGU5, } impl_usb!(USBD, USBD, USBD); @@ -306,6 +317,15 @@ impl_saadc_input!(P0_31, ANALOG_INPUT7); impl_i2s!(I2S, I2S, I2S); +impl_radio!(RADIO, RADIO, RADIO); + +impl_egu!(EGU0, EGU0, SWI0_EGU0); +impl_egu!(EGU1, EGU1, SWI1_EGU1); +impl_egu!(EGU2, EGU2, SWI2_EGU2); +impl_egu!(EGU3, EGU3, SWI3_EGU3); +impl_egu!(EGU4, EGU4, SWI4_EGU4); +impl_egu!(EGU5, EGU5, SWI5_EGU5); + embassy_hal_internal::interrupt_mod!( POWER_CLOCK, RADIO, diff --git a/embassy-nrf/src/chips/nrf52840.rs b/embassy-nrf/src/chips/nrf52840.rs index 51c55cd4d..b6afbf213 100644 --- a/embassy-nrf/src/chips/nrf52840.rs +++ b/embassy-nrf/src/chips/nrf52840.rs @@ -1,4 +1,4 @@ -pub use nrf52840_pac as pac; +pub use nrf_pac as pac; /// The maximum buffer size that the EasyDMA can send/recv in one operation. pub const EASY_DMA_SIZE: usize = (1 << 16) - 1; @@ -173,6 +173,17 @@ embassy_hal_internal::peripherals! { // I2S I2S, + + // Radio + RADIO, + + // EGU + EGU0, + EGU1, + EGU2, + EGU3, + EGU4, + EGU5, } impl_usb!(USBD, USBD, USBD); @@ -311,6 +322,15 @@ impl_saadc_input!(P0_31, ANALOG_INPUT7); impl_i2s!(I2S, I2S, I2S); +impl_radio!(RADIO, RADIO, RADIO); + +impl_egu!(EGU0, EGU0, SWI0_EGU0); +impl_egu!(EGU1, EGU1, SWI1_EGU1); +impl_egu!(EGU2, EGU2, SWI2_EGU2); +impl_egu!(EGU3, EGU3, SWI3_EGU3); +impl_egu!(EGU4, EGU4, SWI4_EGU4); +impl_egu!(EGU5, EGU5, SWI5_EGU5); + embassy_hal_internal::interrupt_mod!( POWER_CLOCK, RADIO, diff --git a/embassy-nrf/src/chips/nrf5340_app.rs b/embassy-nrf/src/chips/nrf5340_app.rs index 62c74bb6f..d7846b094 100644 --- a/embassy-nrf/src/chips/nrf5340_app.rs +++ b/embassy-nrf/src/chips/nrf5340_app.rs @@ -5,16 +5,17 @@ pub mod pac { // The nRF5340 has a secure and non-secure (NS) mode. // To avoid cfg spam, we remove _ns or _s suffixes here. - pub use nrf5340_app_pac::NVIC_PRIO_BITS; + #[cfg(feature="rt")] + pub use nrf_pac::NVIC_PRIO_BITS; + pub use nrf_pac::{common, shared}; #[cfg(feature="rt")] #[doc(no_inline)] - pub use nrf5340_app_pac::interrupt; + pub use nrf_pac::interrupt; #[doc(no_inline)] - pub use nrf5340_app_pac::{ + pub use nrf_pac::{ Interrupt, - Peripherals, cache_s as cache, cachedata_s as cachedata, @@ -26,11 +27,11 @@ pub mod pac { ctrlap_ns as ctrlap, dcnf_ns as dcnf, dppic_ns as dppic, - egu0_ns as egu0, + egu_ns as egu, ficr_s as ficr, fpu_ns as fpu, - gpiote0_s as gpiote, - i2s0_ns as i2s0, + gpiote_s as gpiote, + i2s_ns as i2s, ipc_ns as ipc, kmu_ns as kmu, lpcomp_ns as lpcomp, @@ -38,36 +39,36 @@ pub mod pac { nfct_ns as nfct, nvmc_ns as nvmc, oscillators_ns as oscillators, - p0_ns as p0, - pdm0_ns as pdm, + gpio_ns as gpio, + pdm_ns as pdm, power_ns as power, - pwm0_ns as pwm0, - qdec0_ns as qdec, + pwm_ns as pwm, + qdec_ns as qdec, qspi_ns as qspi, regulators_ns as regulators, reset_ns as reset, - rtc0_ns as rtc0, + rtc_ns as rtc, saadc_ns as saadc, - spim0_ns as spim0, - spis0_ns as spis0, + spim_ns as spim, + spis_ns as spis, spu_s as spu, tad_s as tad, - timer0_ns as timer0, - twim0_ns as twim0, - twis0_ns as twis0, - uarte0_ns as uarte0, + timer_ns as timer, + twim_ns as twim, + twis_ns as twis, + uarte_ns as uarte, uicr_s as uicr, usbd_ns as usbd, usbregulator_ns as usbregulator, vmc_ns as vmc, - wdt0_ns as wdt0, + wdt_ns as wdt, }; /// Non-Secure mode (NS) peripherals pub mod ns { #[cfg(feature = "nrf5340-app-ns")] #[doc(no_inline)] - pub use nrf5340_app_pac::{ + pub use nrf_pac::{ CLOCK_NS as CLOCK, COMP_NS as COMP, CTRLAP_NS as CTRLAP, @@ -141,7 +142,7 @@ pub mod pac { pub mod s { #[cfg(feature = "nrf5340-app-s")] #[doc(no_inline)] - pub use nrf5340_app_pac::{ + pub use nrf_pac::{ CACHEDATA_S as CACHEDATA, CACHEINFO_S as CACHEINFO, CACHE_S as CACHE, @@ -251,6 +252,7 @@ embassy_hal_internal::peripherals! { SERIAL1, SERIAL2, SERIAL3, + SPIM4, // SAADC SAADC, @@ -380,6 +382,14 @@ embassy_hal_internal::peripherals! { P1_13, P1_14, P1_15, + + // EGU + EGU0, + EGU1, + EGU2, + EGU3, + EGU4, + EGU5, } impl_usb!(USBD, USBD, USBD); @@ -393,6 +403,7 @@ impl_spim!(SERIAL0, SPIM0, SERIAL0); impl_spim!(SERIAL1, SPIM1, SERIAL1); impl_spim!(SERIAL2, SPIM2, SERIAL2); impl_spim!(SERIAL3, SPIM3, SERIAL3); +impl_spim!(SPIM4, SPIM4, SPIM4); impl_spis!(SERIAL0, SPIS0, SERIAL0); impl_spis!(SERIAL1, SPIS1, SERIAL1); @@ -519,6 +530,13 @@ impl_saadc_input!(P0_18, ANALOG_INPUT5); impl_saadc_input!(P0_19, ANALOG_INPUT6); impl_saadc_input!(P0_20, ANALOG_INPUT7); +impl_egu!(EGU0, EGU0, EGU0); +impl_egu!(EGU1, EGU1, EGU1); +impl_egu!(EGU2, EGU2, EGU2); +impl_egu!(EGU3, EGU3, EGU3); +impl_egu!(EGU4, EGU4, EGU4); +impl_egu!(EGU5, EGU5, EGU5); + embassy_hal_internal::interrupt_mod!( FPU, CACHE, diff --git a/embassy-nrf/src/chips/nrf5340_net.rs b/embassy-nrf/src/chips/nrf5340_net.rs index a7cf82872..00ff5fea6 100644 --- a/embassy-nrf/src/chips/nrf5340_net.rs +++ b/embassy-nrf/src/chips/nrf5340_net.rs @@ -5,16 +5,17 @@ pub mod pac { // The nRF5340 has a secure and non-secure (NS) mode. // To avoid cfg spam, we remove _ns or _s suffixes here. - pub use nrf5340_net_pac::NVIC_PRIO_BITS; + #[cfg(feature="rt")] + pub use nrf_pac::NVIC_PRIO_BITS; + pub use nrf_pac::{common, shared}; #[cfg(feature="rt")] #[doc(no_inline)] - pub use nrf5340_net_pac::interrupt; + pub use nrf_pac::interrupt; #[doc(no_inline)] - pub use nrf5340_net_pac::{ + pub use nrf_pac::{ Interrupt, - Peripherals, aar_ns as aar, acl_ns as acl, @@ -26,25 +27,25 @@ pub mod pac { dcnf_ns as dcnf, dppic_ns as dppic, ecb_ns as ecb, - egu0_ns as egu0, + egu_ns as egu, ficr_ns as ficr, gpiote_ns as gpiote, ipc_ns as ipc, nvmc_ns as nvmc, - p0_ns as p0, + gpio_ns as gpio, power_ns as power, radio_ns as radio, reset_ns as reset, rng_ns as rng, - rtc0_ns as rtc0, - spim0_ns as spim0, - spis0_ns as spis0, - swi0_ns as swi0, + rtc_ns as rtc, + spim_ns as spim, + spis_ns as spis, + swi_ns as swi, temp_ns as temp, - timer0_ns as timer0, - twim0_ns as twim0, - twis0_ns as twis0, - uarte0_ns as uarte0, + timer_ns as timer, + twim_ns as twim, + twis_ns as twis, + uarte_ns as uarte, uicr_ns as uicr, vmc_ns as vmc, vreqctrl_ns as vreqctrl, @@ -54,25 +55,17 @@ pub mod pac { ACL_NS as ACL, APPMUTEX_NS as APPMUTEX, APPMUTEX_S as APPMUTEX_S, - CBP as CBP, CCM_NS as CCM, CLOCK_NS as CLOCK, - CPUID as CPUID, CTI_NS as CTI, CTRLAP_NS as CTRLAP, - DCB as DCB, DCNF_NS as DCNF, DPPIC_NS as DPPIC, - DWT as DWT, ECB_NS as ECB, EGU0_NS as EGU0, FICR_NS as FICR, - FPB as FPB, GPIOTE_NS as GPIOTE, IPC_NS as IPC, - ITM as ITM, - MPU as MPU, - NVIC as NVIC, NVMC_NS as NVMC, P0_NS as P0, P1_NS as P1, @@ -82,19 +75,16 @@ pub mod pac { RNG_NS as RNG, RTC0_NS as RTC0, RTC1_NS as RTC1, - SCB as SCB, SPIM0_NS as SPIM0, SPIS0_NS as SPIS0, SWI0_NS as SWI0, SWI1_NS as SWI1, SWI2_NS as SWI2, SWI3_NS as SWI3, - SYST as SYST, TEMP_NS as TEMP, TIMER0_NS as TIMER0, TIMER1_NS as TIMER1, TIMER2_NS as TIMER2, - TPIU as TPIU, TWIM0_NS as TWIM0, TWIS0_NS as TWIS0, UARTE0_NS as UARTE0, @@ -248,6 +238,12 @@ embassy_hal_internal::peripherals! { P1_13, P1_14, P1_15, + + // Radio + RADIO, + + // EGU + EGU0, } impl_uarte!(SERIAL0, UARTE0, SERIAL0); @@ -345,6 +341,10 @@ impl_ppi_channel!(PPI_CH29, 29 => configurable); impl_ppi_channel!(PPI_CH30, 30 => configurable); impl_ppi_channel!(PPI_CH31, 31 => configurable); +impl_radio!(RADIO, RADIO, RADIO); + +impl_egu!(EGU0, EGU0, EGU0); + embassy_hal_internal::interrupt_mod!( CLOCK_POWER, RADIO, diff --git a/embassy-nrf/src/chips/nrf9120.rs b/embassy-nrf/src/chips/nrf9120.rs new file mode 100644 index 000000000..b89570dcd --- /dev/null +++ b/embassy-nrf/src/chips/nrf9120.rs @@ -0,0 +1,432 @@ +/// Peripheral Access Crate +#[allow(unused_imports)] +#[rustfmt::skip] +pub mod pac { + // The nRF9120 has a secure and non-secure (NS) mode. + // To avoid cfg spam, we remove _ns or _s suffixes here. + + #[cfg(feature="rt")] + pub use nrf_pac::NVIC_PRIO_BITS; + pub use nrf_pac::{common, shared}; + + #[cfg(feature="rt")] + #[doc(no_inline)] + pub use nrf_pac::interrupt; + + #[doc(no_inline)] + pub use nrf_pac::{ + Interrupt, + + cc_host_rgf_s as cc_host_rgf, + clock_ns as clock, + cryptocell_s as cryptocell, + ctrl_ap_peri_s as ctrl_ap_peri, + dppic_ns as dppic, + egu_ns as egu, + ficr_s as ficr, + fpu_ns as fpu, + gpiote_s as gpiote, + i2s_ns as i2s, + ipc_ns as ipc, + kmu_ns as kmu, + nvmc_ns as nvmc, + gpio_ns as gpio, + pdm_ns as pdm, + power_ns as power, + pwm_ns as pwm, + regulators_ns as regulators, + rtc_ns as rtc, + saadc_ns as saadc, + spim_ns as spim, + spis_ns as spis, + spu_s as spu, + tad_s as tad, + timer_ns as timer, + twim_ns as twim, + twis_ns as twis, + uarte_ns as uarte, + uicr_s as uicr, + vmc_ns as vmc, + wdt_ns as wdt, + }; + + /// Non-Secure mode (NS) peripherals + pub mod ns { + #[doc(no_inline)] + pub use nrf_pac::{ + CLOCK_NS as CLOCK, + DPPIC_NS as DPPIC, + EGU0_NS as EGU0, + EGU1_NS as EGU1, + EGU2_NS as EGU2, + EGU3_NS as EGU3, + EGU4_NS as EGU4, + EGU5_NS as EGU5, + FPU_NS as FPU, + GPIOTE1_NS as GPIOTE1, + I2S_NS as I2S, + IPC_NS as IPC, + KMU_NS as KMU, + NVMC_NS as NVMC, + P0_NS as P0, + PDM_NS as PDM, + POWER_NS as POWER, + PWM0_NS as PWM0, + PWM1_NS as PWM1, + PWM2_NS as PWM2, + PWM3_NS as PWM3, + REGULATORS_NS as REGULATORS, + RTC0_NS as RTC0, + RTC1_NS as RTC1, + SAADC_NS as SAADC, + SPIM0_NS as SPIM0, + SPIM1_NS as SPIM1, + SPIM2_NS as SPIM2, + SPIM3_NS as SPIM3, + SPIS0_NS as SPIS0, + SPIS1_NS as SPIS1, + SPIS2_NS as SPIS2, + SPIS3_NS as SPIS3, + TIMER0_NS as TIMER0, + TIMER1_NS as TIMER1, + TIMER2_NS as TIMER2, + TWIM0_NS as TWIM0, + TWIM1_NS as TWIM1, + TWIM2_NS as TWIM2, + TWIM3_NS as TWIM3, + TWIS0_NS as TWIS0, + TWIS1_NS as TWIS1, + TWIS2_NS as TWIS2, + TWIS3_NS as TWIS3, + UARTE0_NS as UARTE0, + UARTE1_NS as UARTE1, + UARTE2_NS as UARTE2, + UARTE3_NS as UARTE3, + VMC_NS as VMC, + WDT_NS as WDT, + }; + } + + /// Secure mode (S) peripherals + pub mod s { + #[doc(no_inline)] + pub use nrf_pac::{ + CC_HOST_RGF_S as CC_HOST_RGF, + CLOCK_S as CLOCK, + CRYPTOCELL_S as CRYPTOCELL, + CTRL_AP_PERI_S as CTRL_AP_PERI, + DPPIC_S as DPPIC, + EGU0_S as EGU0, + EGU1_S as EGU1, + EGU2_S as EGU2, + EGU3_S as EGU3, + EGU4_S as EGU4, + EGU5_S as EGU5, + FICR_S as FICR, + FPU_NS as FPU, + GPIOTE0_S as GPIOTE0, + I2S_S as I2S, + IPC_S as IPC, + KMU_S as KMU, + NVMC_S as NVMC, + P0_S as P0, + PDM_S as PDM, + POWER_S as POWER, + PWM0_S as PWM0, + PWM1_S as PWM1, + PWM2_S as PWM2, + PWM3_S as PWM3, + REGULATORS_S as REGULATORS, + RTC0_S as RTC0, + RTC1_S as RTC1, + SAADC_S as SAADC, + SPIM0_S as SPIM0, + SPIM1_S as SPIM1, + SPIM2_S as SPIM2, + SPIM3_S as SPIM3, + SPIS0_S as SPIS0, + SPIS1_S as SPIS1, + SPIS2_S as SPIS2, + SPIS3_S as SPIS3, + SPU_S as SPU, + TAD_S as TAD, + TIMER0_S as TIMER0, + TIMER1_S as TIMER1, + TIMER2_S as TIMER2, + TWIM0_S as TWIM0, + TWIM1_S as TWIM1, + TWIM2_S as TWIM2, + TWIM3_S as TWIM3, + TWIS0_S as TWIS0, + TWIS1_S as TWIS1, + TWIS2_S as TWIS2, + TWIS3_S as TWIS3, + UARTE0_S as UARTE0, + UARTE1_S as UARTE1, + UARTE2_S as UARTE2, + UARTE3_S as UARTE3, + UICR_S as UICR, + VMC_S as VMC, + WDT_S as WDT, + }; + } + + #[cfg(feature = "_ns")] + pub use ns::*; + #[cfg(feature = "_s")] + pub use s::*; +} + +/// The maximum buffer size that the EasyDMA can send/recv in one operation. +pub const EASY_DMA_SIZE: usize = (1 << 13) - 1; +pub const FORCE_COPY_BUFFER_SIZE: usize = 1024; + +pub const FLASH_SIZE: usize = 1024 * 1024; + +embassy_hal_internal::peripherals! { + // RTC + RTC0, + RTC1, + + // WDT + WDT, + + // NVMC + NVMC, + + // UARTE, TWI & SPI + SERIAL0, + SERIAL1, + SERIAL2, + SERIAL3, + + // SAADC + SAADC, + + // PWM + PWM0, + PWM1, + PWM2, + PWM3, + + // TIMER + TIMER0, + TIMER1, + TIMER2, + + // GPIOTE + GPIOTE_CH0, + GPIOTE_CH1, + GPIOTE_CH2, + GPIOTE_CH3, + GPIOTE_CH4, + GPIOTE_CH5, + GPIOTE_CH6, + GPIOTE_CH7, + + // PPI + PPI_CH0, + PPI_CH1, + PPI_CH2, + PPI_CH3, + PPI_CH4, + PPI_CH5, + PPI_CH6, + PPI_CH7, + PPI_CH8, + PPI_CH9, + PPI_CH10, + PPI_CH11, + PPI_CH12, + PPI_CH13, + PPI_CH14, + PPI_CH15, + + PPI_GROUP0, + PPI_GROUP1, + PPI_GROUP2, + PPI_GROUP3, + PPI_GROUP4, + PPI_GROUP5, + + // GPIO port 0 + P0_00, + P0_01, + P0_02, + P0_03, + P0_04, + P0_05, + P0_06, + P0_07, + P0_08, + P0_09, + P0_10, + P0_11, + P0_12, + P0_13, + P0_14, + P0_15, + P0_16, + P0_17, + P0_18, + P0_19, + P0_20, + P0_21, + P0_22, + P0_23, + P0_24, + P0_25, + P0_26, + P0_27, + P0_28, + P0_29, + P0_30, + P0_31, + + // PDM + PDM, + + // EGU + EGU0, + EGU1, + EGU2, + EGU3, + EGU4, + EGU5, +} + +impl_uarte!(SERIAL0, UARTE0, SPIM0_SPIS0_TWIM0_TWIS0_UARTE0); +impl_uarte!(SERIAL1, UARTE1, SPIM1_SPIS1_TWIM1_TWIS1_UARTE1); +impl_uarte!(SERIAL2, UARTE2, SPIM2_SPIS2_TWIM2_TWIS2_UARTE2); +impl_uarte!(SERIAL3, UARTE3, SPIM3_SPIS3_TWIM3_TWIS3_UARTE3); + +impl_spim!(SERIAL0, SPIM0, SPIM0_SPIS0_TWIM0_TWIS0_UARTE0); +impl_spim!(SERIAL1, SPIM1, SPIM1_SPIS1_TWIM1_TWIS1_UARTE1); +impl_spim!(SERIAL2, SPIM2, SPIM2_SPIS2_TWIM2_TWIS2_UARTE2); +impl_spim!(SERIAL3, SPIM3, SPIM3_SPIS3_TWIM3_TWIS3_UARTE3); + +impl_spis!(SERIAL0, SPIS0, SPIM0_SPIS0_TWIM0_TWIS0_UARTE0); +impl_spis!(SERIAL1, SPIS1, SPIM1_SPIS1_TWIM1_TWIS1_UARTE1); +impl_spis!(SERIAL2, SPIS2, SPIM2_SPIS2_TWIM2_TWIS2_UARTE2); +impl_spis!(SERIAL3, SPIS3, SPIM3_SPIS3_TWIM3_TWIS3_UARTE3); + +impl_twim!(SERIAL0, TWIM0, SPIM0_SPIS0_TWIM0_TWIS0_UARTE0); +impl_twim!(SERIAL1, TWIM1, SPIM1_SPIS1_TWIM1_TWIS1_UARTE1); +impl_twim!(SERIAL2, TWIM2, SPIM2_SPIS2_TWIM2_TWIS2_UARTE2); +impl_twim!(SERIAL3, TWIM3, SPIM3_SPIS3_TWIM3_TWIS3_UARTE3); + +impl_twis!(SERIAL0, TWIS0, SPIM0_SPIS0_TWIM0_TWIS0_UARTE0); +impl_twis!(SERIAL1, TWIS1, SPIM1_SPIS1_TWIM1_TWIS1_UARTE1); +impl_twis!(SERIAL2, TWIS2, SPIM2_SPIS2_TWIM2_TWIS2_UARTE2); +impl_twis!(SERIAL3, TWIS3, SPIM3_SPIS3_TWIM3_TWIS3_UARTE3); + +impl_pwm!(PWM0, PWM0, PWM0); +impl_pwm!(PWM1, PWM1, PWM1); +impl_pwm!(PWM2, PWM2, PWM2); +impl_pwm!(PWM3, PWM3, PWM3); + +impl_pdm!(PDM, PDM, PDM); + +impl_timer!(TIMER0, TIMER0, TIMER0); +impl_timer!(TIMER1, TIMER1, TIMER1); +impl_timer!(TIMER2, TIMER2, TIMER2); + +impl_pin!(P0_00, 0, 0); +impl_pin!(P0_01, 0, 1); +impl_pin!(P0_02, 0, 2); +impl_pin!(P0_03, 0, 3); +impl_pin!(P0_04, 0, 4); +impl_pin!(P0_05, 0, 5); +impl_pin!(P0_06, 0, 6); +impl_pin!(P0_07, 0, 7); +impl_pin!(P0_08, 0, 8); +impl_pin!(P0_09, 0, 9); +impl_pin!(P0_10, 0, 10); +impl_pin!(P0_11, 0, 11); +impl_pin!(P0_12, 0, 12); +impl_pin!(P0_13, 0, 13); +impl_pin!(P0_14, 0, 14); +impl_pin!(P0_15, 0, 15); +impl_pin!(P0_16, 0, 16); +impl_pin!(P0_17, 0, 17); +impl_pin!(P0_18, 0, 18); +impl_pin!(P0_19, 0, 19); +impl_pin!(P0_20, 0, 20); +impl_pin!(P0_21, 0, 21); +impl_pin!(P0_22, 0, 22); +impl_pin!(P0_23, 0, 23); +impl_pin!(P0_24, 0, 24); +impl_pin!(P0_25, 0, 25); +impl_pin!(P0_26, 0, 26); +impl_pin!(P0_27, 0, 27); +impl_pin!(P0_28, 0, 28); +impl_pin!(P0_29, 0, 29); +impl_pin!(P0_30, 0, 30); +impl_pin!(P0_31, 0, 31); + +impl_ppi_channel!(PPI_CH0, 0 => configurable); +impl_ppi_channel!(PPI_CH1, 1 => configurable); +impl_ppi_channel!(PPI_CH2, 2 => configurable); +impl_ppi_channel!(PPI_CH3, 3 => configurable); +impl_ppi_channel!(PPI_CH4, 4 => configurable); +impl_ppi_channel!(PPI_CH5, 5 => configurable); +impl_ppi_channel!(PPI_CH6, 6 => configurable); +impl_ppi_channel!(PPI_CH7, 7 => configurable); +impl_ppi_channel!(PPI_CH8, 8 => configurable); +impl_ppi_channel!(PPI_CH9, 9 => configurable); +impl_ppi_channel!(PPI_CH10, 10 => configurable); +impl_ppi_channel!(PPI_CH11, 11 => configurable); +impl_ppi_channel!(PPI_CH12, 12 => configurable); +impl_ppi_channel!(PPI_CH13, 13 => configurable); +impl_ppi_channel!(PPI_CH14, 14 => configurable); +impl_ppi_channel!(PPI_CH15, 15 => configurable); + +impl_saadc_input!(P0_13, ANALOG_INPUT0); +impl_saadc_input!(P0_14, ANALOG_INPUT1); +impl_saadc_input!(P0_15, ANALOG_INPUT2); +impl_saadc_input!(P0_16, ANALOG_INPUT3); +impl_saadc_input!(P0_17, ANALOG_INPUT4); +impl_saadc_input!(P0_18, ANALOG_INPUT5); +impl_saadc_input!(P0_19, ANALOG_INPUT6); +impl_saadc_input!(P0_20, ANALOG_INPUT7); + +impl_egu!(EGU0, EGU0, EGU0); +impl_egu!(EGU1, EGU1, EGU1); +impl_egu!(EGU2, EGU2, EGU2); +impl_egu!(EGU3, EGU3, EGU3); +impl_egu!(EGU4, EGU4, EGU4); +impl_egu!(EGU5, EGU5, EGU5); + +embassy_hal_internal::interrupt_mod!( + SPU, + CLOCK_POWER, + SPIM0_SPIS0_TWIM0_TWIS0_UARTE0, + SPIM1_SPIS1_TWIM1_TWIS1_UARTE1, + SPIM2_SPIS2_TWIM2_TWIS2_UARTE2, + SPIM3_SPIS3_TWIM3_TWIS3_UARTE3, + GPIOTE0, + SAADC, + TIMER0, + TIMER1, + TIMER2, + RTC0, + RTC1, + WDT, + EGU0, + EGU1, + EGU2, + EGU3, + EGU4, + EGU5, + PWM0, + PWM1, + PWM2, + PDM, + PWM3, + I2S, + IPC, + FPU, + GPIOTE1, + KMU, + CRYPTOCELL, +); diff --git a/embassy-nrf/src/chips/nrf9160.rs b/embassy-nrf/src/chips/nrf9160.rs index 8b1356ef8..dba3d1ef5 100644 --- a/embassy-nrf/src/chips/nrf9160.rs +++ b/embassy-nrf/src/chips/nrf9160.rs @@ -5,14 +5,16 @@ pub mod pac { // The nRF9160 has a secure and non-secure (NS) mode. // To avoid cfg spam, we remove _ns or _s suffixes here. - pub use nrf9160_pac::NVIC_PRIO_BITS; + #[cfg(feature="rt")] + pub use nrf_pac::NVIC_PRIO_BITS; + pub use nrf_pac::{common, shared}; #[cfg(feature="rt")] #[doc(no_inline)] - pub use nrf9160_pac::interrupt; + pub use nrf_pac::interrupt; #[doc(no_inline)] - pub use nrf9160_pac::{ + pub use nrf_pac::{ Interrupt, cc_host_rgf_s as cc_host_rgf, @@ -20,29 +22,29 @@ pub mod pac { cryptocell_s as cryptocell, ctrl_ap_peri_s as ctrl_ap_peri, dppic_ns as dppic, - egu0_ns as egu0, + egu_ns as egu, ficr_s as ficr, fpu_ns as fpu, - gpiote0_s as gpiote, + gpiote_s as gpiote, i2s_ns as i2s, ipc_ns as ipc, kmu_ns as kmu, nvmc_ns as nvmc, - p0_ns as p0, + gpio_ns as gpio, pdm_ns as pdm, power_ns as power, - pwm0_ns as pwm0, + pwm_ns as pwm, regulators_ns as regulators, - rtc0_ns as rtc0, + rtc_ns as rtc, saadc_ns as saadc, - spim0_ns as spim0, - spis0_ns as spis0, + spim_ns as spim, + spis_ns as spis, spu_s as spu, tad_s as tad, - timer0_ns as timer0, - twim0_ns as twim0, - twis0_ns as twis0, - uarte0_ns as uarte0, + timer_ns as timer, + twim_ns as twim, + twis_ns as twis, + uarte_ns as uarte, uicr_s as uicr, vmc_ns as vmc, wdt_ns as wdt, @@ -51,7 +53,7 @@ pub mod pac { /// Non-Secure mode (NS) peripherals pub mod ns { #[doc(no_inline)] - pub use nrf9160_pac::{ + pub use nrf_pac::{ CLOCK_NS as CLOCK, DPPIC_NS as DPPIC, EGU0_NS as EGU0, @@ -108,7 +110,7 @@ pub mod pac { /// Secure mode (S) peripherals pub mod s { #[doc(no_inline)] - pub use nrf9160_pac::{ + pub use nrf_pac::{ CC_HOST_RGF_S as CC_HOST_RGF, CLOCK_S as CLOCK, CRYPTOCELL_S as CRYPTOCELL, @@ -283,6 +285,14 @@ embassy_hal_internal::peripherals! { // PDM PDM, + + // EGU + EGU0, + EGU1, + EGU2, + EGU3, + EGU4, + EGU5, } impl_uarte!(SERIAL0, UARTE0, UARTE0_SPIM0_SPIS0_TWIM0_TWIS0); @@ -380,6 +390,13 @@ impl_saadc_input!(P0_18, ANALOG_INPUT5); impl_saadc_input!(P0_19, ANALOG_INPUT6); impl_saadc_input!(P0_20, ANALOG_INPUT7); +impl_egu!(EGU0, EGU0, EGU0); +impl_egu!(EGU1, EGU1, EGU1); +impl_egu!(EGU2, EGU2, EGU2); +impl_egu!(EGU3, EGU3, EGU3); +impl_egu!(EGU4, EGU4, EGU4); +impl_egu!(EGU5, EGU5, EGU5); + embassy_hal_internal::interrupt_mod!( SPU, CLOCK_POWER, diff --git a/embassy-nrf/src/egu.rs b/embassy-nrf/src/egu.rs new file mode 100644 index 000000000..7f9abdac4 --- /dev/null +++ b/embassy-nrf/src/egu.rs @@ -0,0 +1,115 @@ +//! EGU driver. +//! +//! The event generator driver provides a higher level API for task triggering +//! and events to use with PPI. + +#![macro_use] + +use core::marker::PhantomData; + +use embassy_hal_internal::into_ref; + +use crate::ppi::{Event, Task}; +use crate::{interrupt, pac, Peripheral, PeripheralRef}; + +/// An instance of the EGU. +pub struct Egu<'d, T: Instance> { + _p: PeripheralRef<'d, T>, +} + +impl<'d, T: Instance> Egu<'d, T> { + /// Create a new EGU instance. + pub fn new(_p: impl Peripheral

+ 'd) -> Self { + into_ref!(_p); + Self { _p } + } + + /// Get a handle to a trigger for the EGU. + pub fn trigger(&mut self, number: TriggerNumber) -> Trigger<'d, T> { + Trigger { + number, + _p: PhantomData, + } + } +} + +pub(crate) trait SealedInstance { + fn regs() -> pac::egu::Egu; +} + +/// Basic Egu instance. +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static + Send { + /// Interrupt for this peripheral. + type Interrupt: interrupt::typelevel::Interrupt; +} + +macro_rules! impl_egu { + ($type:ident, $pac_type:ident, $irq:ident) => { + impl crate::egu::SealedInstance for peripherals::$type { + fn regs() -> pac::egu::Egu { + pac::$pac_type + } + } + impl crate::egu::Instance for peripherals::$type { + type Interrupt = crate::interrupt::typelevel::$irq; + } + }; +} + +/// Represents a trigger within the EGU. +pub struct Trigger<'d, T: Instance> { + number: TriggerNumber, + _p: PhantomData<&'d T>, +} + +impl<'d, T: Instance> Trigger<'d, T> { + /// Get task for this trigger to use with PPI. + pub fn task(&self) -> Task<'d> { + let nr = self.number as usize; + let regs = T::regs(); + Task::from_reg(regs.tasks_trigger(nr)) + } + + /// Get event for this trigger to use with PPI. + pub fn event(&self) -> Event<'d> { + let nr = self.number as usize; + let regs = T::regs(); + Event::from_reg(regs.events_triggered(nr)) + } + + /// Enable interrupts for this trigger + pub fn enable_interrupt(&mut self) { + let regs = T::regs(); + regs.intenset().modify(|w| w.set_triggered(self.number as usize, true)); + } + + /// Enable interrupts for this trigger + pub fn disable_interrupt(&mut self) { + let regs = T::regs(); + regs.intenset().modify(|w| w.set_triggered(self.number as usize, false)); + } +} + +/// Represents a trigger within an EGU. +#[allow(missing_docs)] +#[derive(Clone, Copy, PartialEq)] +#[repr(u8)] +pub enum TriggerNumber { + Trigger0 = 0, + Trigger1 = 1, + Trigger2 = 2, + Trigger3 = 3, + Trigger4 = 4, + Trigger5 = 5, + Trigger6 = 6, + Trigger7 = 7, + Trigger8 = 8, + Trigger9 = 9, + Trigger10 = 10, + Trigger11 = 11, + Trigger12 = 12, + Trigger13 = 13, + Trigger14 = 14, + Trigger15 = 15, +} diff --git a/embassy-nrf/src/fmt.rs b/embassy-nrf/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-nrf/src/fmt.rs +++ b/embassy-nrf/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-nrf/src/gpio.rs b/embassy-nrf/src/gpio.rs index b2f987109..35b0f2e7b 100644 --- a/embassy-nrf/src/gpio.rs +++ b/embassy-nrf/src/gpio.rs @@ -7,15 +7,11 @@ use core::hint::unreachable_unchecked; use cfg_if::cfg_if; use embassy_hal_internal::{impl_peripheral, into_ref, PeripheralRef}; -use self::sealed::Pin as _; -#[cfg(feature = "nrf51")] +use crate::pac::common::{Reg, RW}; use crate::pac::gpio; -#[cfg(feature = "nrf51")] -use crate::pac::gpio::pin_cnf::{DRIVE_A, PULL_A}; -#[cfg(not(feature = "nrf51"))] -use crate::pac::p0 as gpio; -#[cfg(not(feature = "nrf51"))] -use crate::pac::p0::pin_cnf::{DRIVE_A, PULL_A}; +use crate::pac::gpio::vals; +#[cfg(not(feature = "_nrf51"))] +use crate::pac::shared::{regs::Psel, vals::Connect}; use crate::{pac, Peripheral}; /// A GPIO port with up to 32 pins. @@ -104,7 +100,7 @@ impl From for bool { } /// Drive strength settings for an output pin. -// These numbers match DRIVE_A exactly so hopefully the compiler will unify them. +// These numbers match vals::Drive exactly so hopefully the compiler will unify them. #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[repr(u8)] @@ -189,24 +185,24 @@ impl<'d> Output<'d> { } } -fn convert_drive(drive: OutputDrive) -> DRIVE_A { +pub(crate) fn convert_drive(drive: OutputDrive) -> vals::Drive { match drive { - OutputDrive::Standard => DRIVE_A::S0S1, - OutputDrive::HighDrive0Standard1 => DRIVE_A::H0S1, - OutputDrive::Standard0HighDrive1 => DRIVE_A::S0H1, - OutputDrive::HighDrive => DRIVE_A::H0H1, - OutputDrive::Disconnect0Standard1 => DRIVE_A::D0S1, - OutputDrive::Disconnect0HighDrive1 => DRIVE_A::D0H1, - OutputDrive::Standard0Disconnect1 => DRIVE_A::S0D1, - OutputDrive::HighDrive0Disconnect1 => DRIVE_A::H0D1, + OutputDrive::Standard => vals::Drive::S0S1, + OutputDrive::HighDrive0Standard1 => vals::Drive::H0S1, + OutputDrive::Standard0HighDrive1 => vals::Drive::S0H1, + OutputDrive::HighDrive => vals::Drive::H0H1, + OutputDrive::Disconnect0Standard1 => vals::Drive::D0S1, + OutputDrive::Disconnect0HighDrive1 => vals::Drive::D0H1, + OutputDrive::Standard0Disconnect1 => vals::Drive::S0D1, + OutputDrive::HighDrive0Disconnect1 => vals::Drive::H0D1, } } -fn convert_pull(pull: Pull) -> PULL_A { +fn convert_pull(pull: Pull) -> vals::Pull { match pull { - Pull::None => PULL_A::DISABLED, - Pull::Up => PULL_A::PULLUP, - Pull::Down => PULL_A::PULLDOWN, + Pull::None => vals::Pull::DISABLED, + Pull::Up => vals::Pull::PULLUP, + Pull::Down => vals::Pull::PULLDOWN, } } @@ -235,12 +231,11 @@ impl<'d> Flex<'d> { #[inline] pub fn set_as_input(&mut self, pull: Pull) { self.pin.conf().write(|w| { - w.dir().input(); - w.input().connect(); - w.pull().variant(convert_pull(pull)); - w.drive().s0s1(); - w.sense().disabled(); - w + w.set_dir(vals::Dir::INPUT); + w.set_input(vals::Input::CONNECT); + w.set_pull(convert_pull(pull)); + w.set_drive(vals::Drive::S0S1); + w.set_sense(vals::Sense::DISABLED); }); } @@ -251,12 +246,11 @@ impl<'d> Flex<'d> { #[inline] pub fn set_as_output(&mut self, drive: OutputDrive) { self.pin.conf().write(|w| { - w.dir().output(); - w.input().disconnect(); - w.pull().disabled(); - w.drive().variant(convert_drive(drive)); - w.sense().disabled(); - w + w.set_dir(vals::Dir::OUTPUT); + w.set_input(vals::Input::DISCONNECT); + w.set_pull(vals::Pull::DISABLED); + w.set_drive(convert_drive(drive)); + w.set_sense(vals::Sense::DISABLED); }); } @@ -272,31 +266,30 @@ impl<'d> Flex<'d> { #[inline] pub fn set_as_input_output(&mut self, pull: Pull, drive: OutputDrive) { self.pin.conf().write(|w| { - w.dir().output(); - w.input().connect(); - w.pull().variant(convert_pull(pull)); - w.drive().variant(convert_drive(drive)); - w.sense().disabled(); - w + w.set_dir(vals::Dir::OUTPUT); + w.set_input(vals::Input::CONNECT); + w.set_pull(convert_pull(pull)); + w.set_drive(convert_drive(drive)); + w.set_sense(vals::Sense::DISABLED); }); } /// Put the pin into disconnected mode. #[inline] pub fn set_as_disconnected(&mut self) { - self.pin.conf().reset(); + self.pin.conf().write(|_| ()); } /// Get whether the pin input level is high. #[inline] pub fn is_high(&self) -> bool { - !self.is_low() + self.pin.block().in_().read().pin(self.pin.pin() as _) } /// Get whether the pin input level is low. #[inline] pub fn is_low(&self) -> bool { - self.pin.block().in_.read().bits() & (1 << self.pin.pin()) == 0 + !self.is_high() } /// Get the pin input level. @@ -339,13 +332,13 @@ impl<'d> Flex<'d> { /// Get whether the output level is set to high. #[inline] pub fn is_set_high(&self) -> bool { - !self.is_set_low() + self.pin.block().out().read().pin(self.pin.pin() as _) } /// Get whether the output level is set to low. #[inline] pub fn is_set_low(&self) -> bool { - self.pin.block().out.read().bits() & (1 << self.pin.pin()) == 0 + !self.is_set_high() } /// Get the current output level. @@ -357,63 +350,58 @@ impl<'d> Flex<'d> { impl<'d> Drop for Flex<'d> { fn drop(&mut self) { - self.pin.conf().reset(); + self.pin.conf().write(|_| ()) } } -pub(crate) mod sealed { - use super::*; +pub(crate) trait SealedPin { + fn pin_port(&self) -> u8; - pub trait Pin { - fn pin_port(&self) -> u8; - - #[inline] - fn _pin(&self) -> u8 { - cfg_if! { - if #[cfg(feature = "_gpio-p1")] { - self.pin_port() % 32 - } else { - self.pin_port() - } + #[inline] + fn _pin(&self) -> u8 { + cfg_if! { + if #[cfg(feature = "_gpio-p1")] { + self.pin_port() % 32 + } else { + self.pin_port() } } + } - #[inline] - fn block(&self) -> &gpio::RegisterBlock { - unsafe { - match self.pin_port() / 32 { - #[cfg(feature = "nrf51")] - 0 => &*pac::GPIO::ptr(), - #[cfg(not(feature = "nrf51"))] - 0 => &*pac::P0::ptr(), - #[cfg(feature = "_gpio-p1")] - 1 => &*pac::P1::ptr(), - _ => unreachable_unchecked(), - } - } + #[inline] + fn block(&self) -> gpio::Gpio { + match self.pin_port() / 32 { + #[cfg(feature = "_nrf51")] + 0 => pac::GPIO, + #[cfg(not(feature = "_nrf51"))] + 0 => pac::P0, + #[cfg(feature = "_gpio-p1")] + 1 => pac::P1, + _ => unsafe { unreachable_unchecked() }, } + } - #[inline] - fn conf(&self) -> &gpio::PIN_CNF { - &self.block().pin_cnf[self._pin() as usize] - } + #[inline] + fn conf(&self) -> Reg { + self.block().pin_cnf(self._pin() as usize) + } - /// Set the output as high. - #[inline] - fn set_high(&self) { - unsafe { self.block().outset.write(|w| w.bits(1u32 << self._pin())) } - } + /// Set the output as high. + #[inline] + fn set_high(&self) { + self.block().outset().write(|w| w.set_pin(self._pin() as _, true)) + } - /// Set the output as low. - #[inline] - fn set_low(&self) { - unsafe { self.block().outclr.write(|w| w.bits(1u32 << self._pin())) } - } + /// Set the output as low. + #[inline] + fn set_low(&self) { + self.block().outclr().write(|w| w.set_pin(self._pin() as _, true)) } } /// Interface for a Pin that can be configured by an [Input] or [Output] driver, or converted to an [AnyPin]. -pub trait Pin: Peripheral

+ Into + sealed::Pin + Sized + 'static { +#[allow(private_bounds)] +pub trait Pin: Peripheral

+ Into + SealedPin + Sized + 'static { /// Number of the pin within the port (0..31) #[inline] fn pin(&self) -> u8 { @@ -433,8 +421,9 @@ pub trait Pin: Peripheral

+ Into + sealed::Pin + Sized + 'stat /// Peripheral port register value #[inline] - fn psel_bits(&self) -> u32 { - self.pin_port() as u32 + #[cfg(not(feature = "_nrf51"))] + fn psel_bits(&self) -> pac::shared::regs::Psel { + pac::shared::regs::Psel(self.pin_port() as u32) } /// Convert from concrete pin type PX_XX to type erased `AnyPin`. @@ -464,7 +453,7 @@ impl AnyPin { impl_peripheral!(AnyPin); impl Pin for AnyPin {} -impl sealed::Pin for AnyPin { +impl SealedPin for AnyPin { #[inline] fn pin_port(&self) -> u8 { self.pin_port @@ -473,26 +462,32 @@ impl sealed::Pin for AnyPin { // ==================== +#[cfg(not(feature = "_nrf51"))] pub(crate) trait PselBits { - fn psel_bits(&self) -> u32; + fn psel_bits(&self) -> pac::shared::regs::Psel; } +#[cfg(not(feature = "_nrf51"))] impl<'a, P: Pin> PselBits for Option> { #[inline] - fn psel_bits(&self) -> u32 { + fn psel_bits(&self) -> pac::shared::regs::Psel { match self { Some(pin) => pin.psel_bits(), - None => 1u32 << 31, + None => DISCONNECTED, } } } +#[cfg(not(feature = "_nrf51"))] +pub(crate) const DISCONNECTED: Psel = Psel(1 << 31); + +#[cfg(not(feature = "_nrf51"))] #[allow(dead_code)] -pub(crate) fn deconfigure_pin(psel_bits: u32) { - if psel_bits & 0x8000_0000 != 0 { +pub(crate) fn deconfigure_pin(psel: Psel) { + if psel.connect() == Connect::DISCONNECTED { return; } - unsafe { AnyPin::steal(psel_bits as _).conf().reset() } + unsafe { AnyPin::steal(psel.0 as _).conf().write(|_| ()) } } // ==================== @@ -500,7 +495,7 @@ pub(crate) fn deconfigure_pin(psel_bits: u32) { macro_rules! impl_pin { ($type:ident, $port_num:expr, $pin_num:expr) => { impl crate::gpio::Pin for peripherals::$type {} - impl crate::gpio::sealed::Pin for peripherals::$type { + impl crate::gpio::SealedPin for peripherals::$type { #[inline] fn pin_port(&self) -> u8 { $port_num * 32 + $pin_num @@ -536,11 +531,13 @@ mod eh02 { type Error = Infallible; fn set_high(&mut self) -> Result<(), Self::Error> { - Ok(self.set_high()) + self.set_high(); + Ok(()) } fn set_low(&mut self) -> Result<(), Self::Error> { - Ok(self.set_low()) + self.set_low(); + Ok(()) } } @@ -582,11 +579,13 @@ mod eh02 { type Error = Infallible; fn set_high(&mut self) -> Result<(), Self::Error> { - Ok(self.set_high()) + self.set_high(); + Ok(()) } fn set_low(&mut self) -> Result<(), Self::Error> { - Ok(self.set_low()) + self.set_low(); + Ok(()) } } @@ -630,11 +629,13 @@ impl<'d> embedded_hal_1::digital::ErrorType for Output<'d> { impl<'d> embedded_hal_1::digital::OutputPin for Output<'d> { fn set_high(&mut self) -> Result<(), Self::Error> { - Ok(self.set_high()) + self.set_high(); + Ok(()) } fn set_low(&mut self) -> Result<(), Self::Error> { - Ok(self.set_low()) + self.set_low(); + Ok(()) } } @@ -667,11 +668,13 @@ impl<'d> embedded_hal_1::digital::InputPin for Flex<'d> { impl<'d> embedded_hal_1::digital::OutputPin for Flex<'d> { fn set_high(&mut self) -> Result<(), Self::Error> { - Ok(self.set_high()) + self.set_high(); + Ok(()) } fn set_low(&mut self) -> Result<(), Self::Error> { - Ok(self.set_low()) + self.set_low(); + Ok(()) } } diff --git a/embassy-nrf/src/gpiote.rs b/embassy-nrf/src/gpiote.rs index a459446a2..87bb405f4 100644 --- a/embassy-nrf/src/gpiote.rs +++ b/embassy-nrf/src/gpiote.rs @@ -7,18 +7,25 @@ use core::task::{Context, Poll}; use embassy_hal_internal::{impl_peripheral, into_ref, Peripheral, PeripheralRef}; use embassy_sync::waitqueue::AtomicWaker; -use crate::gpio::sealed::Pin as _; -use crate::gpio::{AnyPin, Flex, Input, Output, Pin as GpioPin}; +use crate::gpio::{AnyPin, Flex, Input, Output, Pin as GpioPin, SealedPin as _}; use crate::interrupt::InterruptExt; +#[cfg(not(feature = "_nrf51"))] +use crate::pac::gpio::vals::Detectmode; +use crate::pac::gpio::vals::Sense; +use crate::pac::gpiote::vals::{Mode, Outinit, Polarity}; use crate::ppi::{Event, Task}; use crate::{interrupt, pac, peripherals}; +#[cfg(feature = "_nrf51")] +/// Amount of GPIOTE channels in the chip. +const CHANNEL_COUNT: usize = 4; +#[cfg(not(feature = "_nrf51"))] /// Amount of GPIOTE channels in the chip. const CHANNEL_COUNT: usize = 8; -#[cfg(any(feature = "nrf52833", feature = "nrf52840"))] +#[cfg(any(feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340"))] const PIN_COUNT: usize = 48; -#[cfg(not(any(feature = "nrf52833", feature = "nrf52840")))] +#[cfg(not(any(feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340")))] const PIN_COUNT: usize = 32; #[allow(clippy::declare_interior_mutable_const)] @@ -48,37 +55,41 @@ pub enum OutputChannelPolarity { Toggle, } -fn regs() -> &'static pac::gpiote::RegisterBlock { +fn regs() -> pac::gpiote::Gpiote { cfg_if::cfg_if! { - if #[cfg(any(feature="nrf5340-app-s", feature="nrf9160-s"))] { - unsafe { &*pac::GPIOTE0::ptr() } - } else if #[cfg(any(feature="nrf5340-app-ns", feature="nrf9160-ns"))] { - unsafe { &*pac::GPIOTE1::ptr() } + if #[cfg(any(feature="nrf5340-app-s", feature="nrf9160-s", feature="nrf9120-s"))] { + pac::GPIOTE0 + } else if #[cfg(any(feature="nrf5340-app-ns", feature="nrf9160-ns", feature="nrf9120-ns"))] { + pac::GPIOTE1 } else { - unsafe { &*pac::GPIOTE::ptr() } + pac::GPIOTE } } } pub(crate) fn init(irq_prio: crate::interrupt::Priority) { - #[cfg(any(feature = "nrf52833", feature = "nrf52840"))] - let ports = unsafe { &[&*pac::P0::ptr(), &*pac::P1::ptr()] }; - #[cfg(not(any(feature = "nrf52833", feature = "nrf52840")))] - let ports = unsafe { &[&*pac::P0::ptr()] }; + // no latched GPIO detect in nrf51. + #[cfg(not(feature = "_nrf51"))] + { + #[cfg(any(feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340"))] + let ports = &[pac::P0, pac::P1]; + #[cfg(not(any(feature = "_nrf51", feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340")))] + let ports = &[pac::P0]; - for &p in ports { - // Enable latched detection - p.detectmode.write(|w| w.detectmode().ldetect()); - // Clear latch - p.latch.write(|w| unsafe { w.bits(0xFFFFFFFF) }) + for &p in ports { + // Enable latched detection + p.detectmode().write(|w| w.set_detectmode(Detectmode::LDETECT)); + // Clear latch + p.latch().write(|w| w.0 = 0xFFFFFFFF) + } } // Enable interrupts - #[cfg(any(feature = "nrf5340-app-s", feature = "nrf9160-s"))] + #[cfg(any(feature = "nrf5340-app-s", feature = "nrf9160-s", feature = "nrf9120-s"))] let irq = interrupt::GPIOTE0; - #[cfg(any(feature = "nrf5340-app-ns", feature = "nrf9160-ns"))] + #[cfg(any(feature = "nrf5340-app-ns", feature = "nrf9160-ns", feature = "nrf9120-ns"))] let irq = interrupt::GPIOTE1; - #[cfg(any(feature = "_nrf52", feature = "nrf5340-net"))] + #[cfg(any(feature = "_nrf51", feature = "_nrf52", feature = "nrf5340-net"))] let irq = interrupt::GPIOTE; irq.unpend(); @@ -86,24 +97,24 @@ pub(crate) fn init(irq_prio: crate::interrupt::Priority) { unsafe { irq.enable() }; let g = regs(); - g.intenset.write(|w| w.port().set()); + g.intenset().write(|w| w.set_port(true)); } -#[cfg(any(feature = "nrf5340-app-s", feature = "nrf9160-s"))] +#[cfg(any(feature = "nrf5340-app-s", feature = "nrf9160-s", feature = "nrf9120-s"))] #[cfg(feature = "rt")] #[interrupt] fn GPIOTE0() { unsafe { handle_gpiote_interrupt() }; } -#[cfg(any(feature = "nrf5340-app-ns", feature = "nrf9160-ns"))] +#[cfg(any(feature = "nrf5340-app-ns", feature = "nrf9160-ns", feature = "nrf9120-ns"))] #[cfg(feature = "rt")] #[interrupt] fn GPIOTE1() { unsafe { handle_gpiote_interrupt() }; } -#[cfg(any(feature = "_nrf52", feature = "nrf5340-net"))] +#[cfg(any(feature = "_nrf51", feature = "_nrf52", feature = "nrf5340-net"))] #[cfg(feature = "rt")] #[interrupt] fn GPIOTE() { @@ -114,33 +125,55 @@ unsafe fn handle_gpiote_interrupt() { let g = regs(); for i in 0..CHANNEL_COUNT { - if g.events_in[i].read().bits() != 0 { - g.intenclr.write(|w| w.bits(1 << i)); + if g.events_in(i).read() != 0 { + g.intenclr().write(|w| w.0 = 1 << i); CHANNEL_WAKERS[i].wake(); } } - if g.events_port.read().bits() != 0 { - g.events_port.write(|w| w); + if g.events_port().read() != 0 { + g.events_port().write_value(0); - #[cfg(any(feature = "nrf52833", feature = "nrf52840"))] - let ports = &[&*pac::P0::ptr(), &*pac::P1::ptr()]; - #[cfg(not(any(feature = "nrf52833", feature = "nrf52840")))] - let ports = &[&*pac::P0::ptr()]; + #[cfg(any(feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340"))] + let ports = &[pac::P0, pac::P1]; + #[cfg(not(any(feature = "_nrf51", feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340")))] + let ports = &[pac::P0]; + #[cfg(feature = "_nrf51")] + let ports = &[pac::GPIO]; + #[cfg(feature = "_nrf51")] for (port, &p) in ports.iter().enumerate() { - let bits = p.latch.read().bits(); + let inp = p.in_().read(); + for pin in 0..32 { + let fired = match p.pin_cnf(pin as usize).read().sense() { + Sense::HIGH => inp.pin(pin), + Sense::LOW => !inp.pin(pin), + _ => false, + }; + + if fired { + PORT_WAKERS[port * 32 + pin as usize].wake(); + p.pin_cnf(pin as usize).modify(|w| w.set_sense(Sense::DISABLED)); + } + } + } + + #[cfg(not(feature = "_nrf51"))] + for (port, &p) in ports.iter().enumerate() { + let bits = p.latch().read().0; for pin in BitIter(bits) { - p.pin_cnf[pin as usize].modify(|_, w| w.sense().disabled()); + p.pin_cnf(pin as usize).modify(|w| w.set_sense(Sense::DISABLED)); PORT_WAKERS[port * 32 + pin as usize].wake(); } - p.latch.write(|w| w.bits(bits)); + p.latch().write(|w| w.0 = bits); } } } +#[cfg(not(feature = "_nrf51"))] struct BitIter(u32); +#[cfg(not(feature = "_nrf51"))] impl Iterator for BitIter { type Item = u32; @@ -165,8 +198,8 @@ impl<'d> Drop for InputChannel<'d> { fn drop(&mut self) { let g = regs(); let num = self.ch.number(); - g.config[num].write(|w| w.mode().disabled()); - g.intenclr.write(|w| unsafe { w.bits(1 << num) }); + g.config(num).write(|w| w.set_mode(Mode::DISABLED)); + g.intenclr().write(|w| w.0 = 1 << num); } } @@ -178,22 +211,23 @@ impl<'d> InputChannel<'d> { let g = regs(); let num = ch.number(); - g.config[num].write(|w| { + g.config(num).write(|w| { + w.set_mode(Mode::EVENT); match polarity { - InputChannelPolarity::HiToLo => w.mode().event().polarity().hi_to_lo(), - InputChannelPolarity::LoToHi => w.mode().event().polarity().lo_to_hi(), - InputChannelPolarity::None => w.mode().event().polarity().none(), - InputChannelPolarity::Toggle => w.mode().event().polarity().toggle(), + InputChannelPolarity::HiToLo => w.set_polarity(Polarity::HI_TO_LO), + InputChannelPolarity::LoToHi => w.set_polarity(Polarity::LO_TO_HI), + InputChannelPolarity::None => w.set_polarity(Polarity::NONE), + InputChannelPolarity::Toggle => w.set_polarity(Polarity::TOGGLE), }; - #[cfg(any(feature = "nrf52833", feature = "nrf52840"))] - w.port().bit(match pin.pin.pin.port() { + #[cfg(any(feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340"))] + w.set_port(match pin.pin.pin.port() { crate::gpio::Port::Port0 => false, crate::gpio::Port::Port1 => true, }); - unsafe { w.psel().bits(pin.pin.pin.pin()) } + w.set_psel(pin.pin.pin.pin()); }); - g.events_in[num].reset(); + g.events_in(num).write_value(0); InputChannel { ch: ch.map_into(), pin } } @@ -204,13 +238,13 @@ impl<'d> InputChannel<'d> { let num = self.ch.number(); // Enable interrupt - g.events_in[num].reset(); - g.intenset.write(|w| unsafe { w.bits(1 << num) }); + g.events_in(num).write_value(0); + g.intenset().write(|w| w.0 = 1 << num); poll_fn(|cx| { CHANNEL_WAKERS[num].register(cx.waker()); - if g.events_in[num].read().bits() != 0 { + if g.events_in(num).read() != 0 { Poll::Ready(()) } else { Poll::Pending @@ -222,7 +256,7 @@ impl<'d> InputChannel<'d> { /// Returns the IN event, for use with PPI. pub fn event_in(&self) -> Event<'d> { let g = regs(); - Event::from_reg(&g.events_in[self.ch.number()]) + Event::from_reg(g.events_in(self.ch.number())) } } @@ -236,8 +270,8 @@ impl<'d> Drop for OutputChannel<'d> { fn drop(&mut self) { let g = regs(); let num = self.ch.number(); - g.config[num].write(|w| w.mode().disabled()); - g.intenclr.write(|w| unsafe { w.bits(1 << num) }); + g.config(num).write(|w| w.set_mode(Mode::DISABLED)); + g.intenclr().write(|w| w.0 = 1 << num); } } @@ -248,23 +282,23 @@ impl<'d> OutputChannel<'d> { let g = regs(); let num = ch.number(); - g.config[num].write(|w| { - w.mode().task(); + g.config(num).write(|w| { + w.set_mode(Mode::TASK); match pin.is_set_high() { - true => w.outinit().high(), - false => w.outinit().low(), + true => w.set_outinit(Outinit::HIGH), + false => w.set_outinit(Outinit::LOW), }; match polarity { - OutputChannelPolarity::Set => w.polarity().lo_to_hi(), - OutputChannelPolarity::Clear => w.polarity().hi_to_lo(), - OutputChannelPolarity::Toggle => w.polarity().toggle(), + OutputChannelPolarity::Set => w.set_polarity(Polarity::HI_TO_LO), + OutputChannelPolarity::Clear => w.set_polarity(Polarity::LO_TO_HI), + OutputChannelPolarity::Toggle => w.set_polarity(Polarity::TOGGLE), }; - #[cfg(any(feature = "nrf52833", feature = "nrf52840"))] - w.port().bit(match pin.pin.pin.port() { + #[cfg(any(feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340"))] + w.set_port(match pin.pin.pin.port() { crate::gpio::Port::Port0 => false, crate::gpio::Port::Port1 => true, }); - unsafe { w.psel().bits(pin.pin.pin.pin()) } + w.set_psel(pin.pin.pin.pin()); }); OutputChannel { @@ -276,41 +310,41 @@ impl<'d> OutputChannel<'d> { /// Triggers the OUT task (does the action as configured with task_out_polarity, defaults to Toggle). pub fn out(&self) { let g = regs(); - g.tasks_out[self.ch.number()].write(|w| unsafe { w.bits(1) }); + g.tasks_out(self.ch.number()).write_value(1); } /// Triggers the SET task (set associated pin high). - #[cfg(not(feature = "nrf51"))] + #[cfg(not(feature = "_nrf51"))] pub fn set(&self) { let g = regs(); - g.tasks_set[self.ch.number()].write(|w| unsafe { w.bits(1) }); + g.tasks_set(self.ch.number()).write_value(1); } /// Triggers the CLEAR task (set associated pin low). - #[cfg(not(feature = "nrf51"))] + #[cfg(not(feature = "_nrf51"))] pub fn clear(&self) { let g = regs(); - g.tasks_clr[self.ch.number()].write(|w| unsafe { w.bits(1) }); + g.tasks_clr(self.ch.number()).write_value(1); } /// Returns the OUT task, for use with PPI. pub fn task_out(&self) -> Task<'d> { let g = regs(); - Task::from_reg(&g.tasks_out[self.ch.number()]) + Task::from_reg(g.tasks_out(self.ch.number())) } /// Returns the CLR task, for use with PPI. - #[cfg(not(feature = "nrf51"))] + #[cfg(not(feature = "_nrf51"))] pub fn task_clr(&self) -> Task<'d> { let g = regs(); - Task::from_reg(&g.tasks_clr[self.ch.number()]) + Task::from_reg(g.tasks_clr(self.ch.number())) } /// Returns the SET task, for use with PPI. - #[cfg(not(feature = "nrf51"))] + #[cfg(not(feature = "_nrf51"))] pub fn task_set(&self) -> Task<'d> { let g = regs(); - Task::from_reg(&g.tasks_set[self.ch.number()]) + Task::from_reg(g.tasks_set(self.ch.number())) } } @@ -333,7 +367,7 @@ impl<'a> Unpin for PortInputFuture<'a> {} impl<'a> Drop for PortInputFuture<'a> { fn drop(&mut self) { - self.pin.conf().modify(|_, w| w.sense().disabled()); + self.pin.conf().modify(|w| w.set_sense(Sense::DISABLED)); } } @@ -343,7 +377,7 @@ impl<'a> Future for PortInputFuture<'a> { fn poll(self: core::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { PORT_WAKERS[self.pin.pin_port() as usize].register(cx.waker()); - if self.pin.conf().read().sense().is_disabled() { + if self.pin.conf().read().sense() == Sense::DISABLED { Poll::Ready(()) } else { Poll::Pending @@ -381,13 +415,13 @@ impl<'d> Input<'d> { impl<'d> Flex<'d> { /// Wait until the pin is high. If it is already high, return immediately. pub async fn wait_for_high(&mut self) { - self.pin.conf().modify(|_, w| w.sense().high()); + self.pin.conf().modify(|w| w.set_sense(Sense::HIGH)); PortInputFuture::new(&mut self.pin).await } /// Wait until the pin is low. If it is already low, return immediately. pub async fn wait_for_low(&mut self) { - self.pin.conf().modify(|_, w| w.sense().low()); + self.pin.conf().modify(|w| w.set_sense(Sense::LOW)); PortInputFuture::new(&mut self.pin).await } @@ -406,9 +440,9 @@ impl<'d> Flex<'d> { /// Wait for the pin to undergo any transition, i.e low to high OR high to low. pub async fn wait_for_any_edge(&mut self) { if self.is_high() { - self.pin.conf().modify(|_, w| w.sense().low()); + self.pin.conf().modify(|w| w.set_sense(Sense::LOW)); } else { - self.pin.conf().modify(|_, w| w.sense().high()); + self.pin.conf().modify(|w| w.set_sense(Sense::HIGH)); } PortInputFuture::new(&mut self.pin).await } @@ -416,14 +450,13 @@ impl<'d> Flex<'d> { // ======================= -mod sealed { - pub trait Channel {} -} +trait SealedChannel {} /// GPIOTE channel trait. /// /// Implemented by all GPIOTE channels. -pub trait Channel: sealed::Channel + Into + Sized + 'static { +#[allow(private_bounds)] +pub trait Channel: SealedChannel + Into + Sized + 'static { /// Get the channel number. fn number(&self) -> usize; @@ -448,7 +481,7 @@ pub struct AnyChannel { number: u8, } impl_peripheral!(AnyChannel); -impl sealed::Channel for AnyChannel {} +impl SealedChannel for AnyChannel {} impl Channel for AnyChannel { fn number(&self) -> usize { self.number as usize @@ -457,7 +490,7 @@ impl Channel for AnyChannel { macro_rules! impl_channel { ($type:ident, $number:expr) => { - impl sealed::Channel for peripherals::$type {} + impl SealedChannel for peripherals::$type {} impl Channel for peripherals::$type { fn number(&self) -> usize { $number as usize @@ -476,9 +509,13 @@ impl_channel!(GPIOTE_CH0, 0); impl_channel!(GPIOTE_CH1, 1); impl_channel!(GPIOTE_CH2, 2); impl_channel!(GPIOTE_CH3, 3); +#[cfg(not(feature = "_nrf51"))] impl_channel!(GPIOTE_CH4, 4); +#[cfg(not(feature = "_nrf51"))] impl_channel!(GPIOTE_CH5, 5); +#[cfg(not(feature = "_nrf51"))] impl_channel!(GPIOTE_CH6, 6); +#[cfg(not(feature = "_nrf51"))] impl_channel!(GPIOTE_CH7, 7); // ==================== diff --git a/embassy-nrf/src/i2s.rs b/embassy-nrf/src/i2s.rs index 907acdf4c..384a1637b 100644 --- a/embassy-nrf/src/i2s.rs +++ b/embassy-nrf/src/i2s.rs @@ -6,17 +6,18 @@ use core::future::poll_fn; use core::marker::PhantomData; use core::mem::size_of; use core::ops::{Deref, DerefMut}; -use core::sync::atomic::{compiler_fence, Ordering}; +use core::sync::atomic::{compiler_fence, AtomicBool, Ordering}; use core::task::Poll; use embassy_hal_internal::drop::OnDrop; use embassy_hal_internal::{into_ref, PeripheralRef}; +use embassy_sync::waitqueue::AtomicWaker; -use crate::gpio::{AnyPin, Pin as GpioPin}; +use crate::gpio::{AnyPin, Pin as GpioPin, PselBits}; use crate::interrupt::typelevel::Interrupt; -use crate::pac::i2s::RegisterBlock; -use crate::util::{slice_in_ram_or, slice_ptr_parts}; -use crate::{interrupt, Peripheral, EASY_DMA_SIZE}; +use crate::pac::i2s::vals; +use crate::util::slice_in_ram_or; +use crate::{interrupt, pac, Peripheral, EASY_DMA_SIZE}; /// Type alias for `MultiBuffering` with 2 buffers. pub type DoubleBuffering = MultiBuffering; @@ -116,9 +117,20 @@ pub enum MckFreq { } impl MckFreq { - const REGISTER_VALUES: &'static [u32] = &[ - 0x20000000, 0x18000000, 0x16000000, 0x11000000, 0x10000000, 0x0C000000, 0x0B000000, 0x08800000, 0x08400000, - 0x08000000, 0x06000000, 0x04100000, 0x020C0000, + const REGISTER_VALUES: &'static [vals::Mckfreq] = &[ + vals::Mckfreq::_32MDIV8, + vals::Mckfreq::_32MDIV10, + vals::Mckfreq::_32MDIV11, + vals::Mckfreq::_32MDIV15, + vals::Mckfreq::_32MDIV16, + vals::Mckfreq::_32MDIV21, + vals::Mckfreq::_32MDIV23, + vals::Mckfreq::_32MDIV30, + vals::Mckfreq::_32MDIV31, + vals::Mckfreq::_32MDIV32, + vals::Mckfreq::_32MDIV42, + vals::Mckfreq::_32MDIV63, + vals::Mckfreq::_32MDIV125, ]; const FREQUENCIES: &'static [u32] = &[ @@ -127,7 +139,7 @@ impl MckFreq { ]; /// Return the value that needs to be written to the register. - pub fn to_register_value(&self) -> u32 { + pub fn to_register_value(&self) -> vals::Mckfreq { Self::REGISTER_VALUES[usize::from(*self)] } @@ -173,8 +185,8 @@ impl Ratio { const RATIOS: &'static [u32] = &[32, 48, 64, 96, 128, 192, 256, 384, 512]; /// Return the value that needs to be written to the register. - pub fn to_register_value(&self) -> u8 { - usize::from(*self) as u8 + pub fn to_register_value(&self) -> vals::Ratio { + vals::Ratio::from_bits(*self as u8) } /// Return the divisor for this ratio @@ -303,9 +315,9 @@ pub enum SampleWidth { _24bit, } -impl From for u8 { +impl From for vals::Swidth { fn from(variant: SampleWidth) -> Self { - variant as _ + vals::Swidth::from_bits(variant as u8) } } @@ -318,11 +330,11 @@ pub enum Align { Right, } -impl From for bool { +impl From for vals::Align { fn from(variant: Align) -> Self { match variant { - Align::Left => false, - Align::Right => true, + Align::Left => vals::Align::LEFT, + Align::Right => vals::Align::RIGHT, } } } @@ -336,11 +348,11 @@ pub enum Format { Aligned, } -impl From for bool { +impl From for vals::Format { fn from(variant: Format) -> Self { match variant { - Format::I2S => false, - Format::Aligned => true, + Format::I2S => vals::Format::I2S, + Format::Aligned => vals::Format::ALIGNED, } } } @@ -356,9 +368,9 @@ pub enum Channels { MonoRight, } -impl From for u8 { +impl From for vals::Channels { fn from(variant: Channels) -> Self { - variant as _ + vals::Channels::from_bits(variant as u8) } } @@ -505,61 +517,32 @@ impl<'d, T: Instance> I2S<'d, T> { } fn apply_config(&self) { - let c = &T::regs().config; + let c = T::regs().config(); match &self.master_clock { Some(MasterClock { freq, ratio }) => { - c.mode.write(|w| w.mode().master()); - c.mcken.write(|w| w.mcken().enabled()); - c.mckfreq - .write(|w| unsafe { w.mckfreq().bits(freq.to_register_value()) }); - c.ratio.write(|w| unsafe { w.ratio().bits(ratio.to_register_value()) }); + c.mode().write(|w| w.set_mode(vals::Mode::MASTER)); + c.mcken().write(|w| w.set_mcken(true)); + c.mckfreq().write(|w| w.set_mckfreq(freq.to_register_value())); + c.ratio().write(|w| w.set_ratio(ratio.to_register_value())); } None => { - c.mode.write(|w| w.mode().slave()); + c.mode().write(|w| w.set_mode(vals::Mode::SLAVE)); } }; - c.swidth - .write(|w| unsafe { w.swidth().bits(self.config.sample_width.into()) }); - c.align.write(|w| w.align().bit(self.config.align.into())); - c.format.write(|w| w.format().bit(self.config.format.into())); - c.channels - .write(|w| unsafe { w.channels().bits(self.config.channels.into()) }); + c.swidth().write(|w| w.set_swidth(self.config.sample_width.into())); + c.align().write(|w| w.set_align(self.config.align.into())); + c.format().write(|w| w.set_format(self.config.format.into())); + c.channels().write(|w| w.set_channels(self.config.channels.into())); } fn select_pins(&self) { - let psel = &T::regs().psel; - - if let Some(mck) = &self.mck { - psel.mck.write(|w| { - unsafe { w.bits(mck.psel_bits()) }; - w.connect().connected() - }); - } - - psel.sck.write(|w| { - unsafe { w.bits(self.sck.psel_bits()) }; - w.connect().connected() - }); - - psel.lrck.write(|w| { - unsafe { w.bits(self.lrck.psel_bits()) }; - w.connect().connected() - }); - - if let Some(sdin) = &self.sdin { - psel.sdin.write(|w| { - unsafe { w.bits(sdin.psel_bits()) }; - w.connect().connected() - }); - } - - if let Some(sdout) = &self.sdout { - psel.sdout.write(|w| { - unsafe { w.bits(sdout.psel_bits()) }; - w.connect().connected() - }); - } + let psel = T::regs().psel(); + psel.mck().write_value(self.mck.psel_bits()); + psel.sck().write_value(self.sck.psel_bits()); + psel.lrck().write_value(self.lrck.psel_bits()); + psel.sdin().write_value(self.sdin.psel_bits()); + psel.sdout().write_value(self.sdout.psel_bits()); } fn setup_interrupt(&self) { @@ -887,7 +870,7 @@ impl<'d, T: Instance, S: Sample, const NB: usize, const NS: usize> FullDuplexStr } /// Helper encapsulating common I2S device operations. -struct Device(&'static RegisterBlock, PhantomData); +struct Device(pac::i2s::I2s, PhantomData); impl Device { fn new() -> Self { @@ -897,139 +880,138 @@ impl Device { #[inline(always)] pub fn enable(&self) { trace!("ENABLED"); - self.0.enable.write(|w| w.enable().enabled()); + self.0.enable().write(|w| w.set_enable(true)); } #[inline(always)] pub fn disable(&self) { trace!("DISABLED"); - self.0.enable.write(|w| w.enable().disabled()); + self.0.enable().write(|w| w.set_enable(false)); } #[inline(always)] fn enable_tx(&self) { trace!("TX ENABLED"); - self.0.config.txen.write(|w| w.txen().enabled()); + self.0.config().txen().write(|w| w.set_txen(true)); } #[inline(always)] fn disable_tx(&self) { trace!("TX DISABLED"); - self.0.config.txen.write(|w| w.txen().disabled()); + self.0.config().txen().write(|w| w.set_txen(false)); } #[inline(always)] fn enable_rx(&self) { trace!("RX ENABLED"); - self.0.config.rxen.write(|w| w.rxen().enabled()); + self.0.config().rxen().write(|w| w.set_rxen(true)); } #[inline(always)] fn disable_rx(&self) { trace!("RX DISABLED"); - self.0.config.rxen.write(|w| w.rxen().disabled()); + self.0.config().rxen().write(|w| w.set_rxen(false)); } #[inline(always)] fn start(&self) { trace!("START"); - self.0.tasks_start.write(|w| unsafe { w.bits(1) }); + self.0.tasks_start().write_value(1); } #[inline(always)] fn stop(&self) { - self.0.tasks_stop.write(|w| unsafe { w.bits(1) }); + self.0.tasks_stop().write_value(1); } #[inline(always)] fn is_stopped(&self) -> bool { - self.0.events_stopped.read().bits() != 0 + self.0.events_stopped().read() != 0 } #[inline(always)] fn reset_stopped_event(&self) { trace!("STOPPED EVENT: Reset"); - self.0.events_stopped.reset(); + self.0.events_stopped().write_value(0); } #[inline(always)] fn disable_stopped_interrupt(&self) { trace!("STOPPED INTERRUPT: Disabled"); - self.0.intenclr.write(|w| w.stopped().clear()); + self.0.intenclr().write(|w| w.set_stopped(true)); } #[inline(always)] fn enable_stopped_interrupt(&self) { trace!("STOPPED INTERRUPT: Enabled"); - self.0.intenset.write(|w| w.stopped().set()); + self.0.intenset().write(|w| w.set_stopped(true)); } #[inline(always)] fn reset_tx_ptr_event(&self) { trace!("TX PTR EVENT: Reset"); - self.0.events_txptrupd.reset(); + self.0.events_txptrupd().write_value(0); } #[inline(always)] fn reset_rx_ptr_event(&self) { trace!("RX PTR EVENT: Reset"); - self.0.events_rxptrupd.reset(); + self.0.events_rxptrupd().write_value(0); } #[inline(always)] fn disable_tx_ptr_interrupt(&self) { trace!("TX PTR INTERRUPT: Disabled"); - self.0.intenclr.write(|w| w.txptrupd().clear()); + self.0.intenclr().write(|w| w.set_txptrupd(true)); } #[inline(always)] fn disable_rx_ptr_interrupt(&self) { trace!("RX PTR INTERRUPT: Disabled"); - self.0.intenclr.write(|w| w.rxptrupd().clear()); + self.0.intenclr().write(|w| w.set_rxptrupd(true)); } #[inline(always)] fn enable_tx_ptr_interrupt(&self) { trace!("TX PTR INTERRUPT: Enabled"); - self.0.intenset.write(|w| w.txptrupd().set()); + self.0.intenset().write(|w| w.set_txptrupd(true)); } #[inline(always)] fn enable_rx_ptr_interrupt(&self) { trace!("RX PTR INTERRUPT: Enabled"); - self.0.intenset.write(|w| w.rxptrupd().set()); + self.0.intenset().write(|w| w.set_rxptrupd(true)); } #[inline(always)] fn is_tx_ptr_updated(&self) -> bool { - self.0.events_txptrupd.read().bits() != 0 + self.0.events_txptrupd().read() != 0 } #[inline(always)] fn is_rx_ptr_updated(&self) -> bool { - self.0.events_rxptrupd.read().bits() != 0 + self.0.events_rxptrupd().read() != 0 } #[inline] fn update_tx(&self, buffer_ptr: *const [S]) -> Result<(), Error> { let (ptr, maxcnt) = Self::validated_dma_parts(buffer_ptr)?; - self.0.rxtxd.maxcnt.write(|w| unsafe { w.bits(maxcnt) }); - self.0.txd.ptr.write(|w| unsafe { w.ptr().bits(ptr) }); + self.0.rxtxd().maxcnt().write(|w| w.0 = maxcnt); + self.0.txd().ptr().write_value(ptr); Ok(()) } #[inline] fn update_rx(&self, buffer_ptr: *const [S]) -> Result<(), Error> { let (ptr, maxcnt) = Self::validated_dma_parts(buffer_ptr)?; - self.0.rxtxd.maxcnt.write(|w| unsafe { w.bits(maxcnt) }); - self.0.rxd.ptr.write(|w| unsafe { w.ptr().bits(ptr) }); + self.0.rxtxd().maxcnt().write(|w| w.0 = maxcnt); + self.0.rxd().ptr().write_value(ptr); Ok(()) } fn validated_dma_parts(buffer_ptr: *const [S]) -> Result<(u32, u32), Error> { - let (ptr, len) = slice_ptr_parts(buffer_ptr); - let ptr = ptr as u32; - let bytes_len = len * size_of::(); + let ptr = buffer_ptr as *const S as u32; + let bytes_len = buffer_ptr.len() * size_of::(); let maxcnt = (bytes_len / size_of::()) as u32; trace!("PTR={}, MAXCNT={}", ptr, maxcnt); @@ -1140,50 +1122,45 @@ impl MultiBuffering { } } -pub(crate) mod sealed { - use core::sync::atomic::AtomicBool; +/// Peripheral static state +pub(crate) struct State { + started: AtomicBool, + rx_waker: AtomicWaker, + tx_waker: AtomicWaker, + stop_waker: AtomicWaker, +} - use embassy_sync::waitqueue::AtomicWaker; - - /// Peripheral static state - pub struct State { - pub started: AtomicBool, - pub rx_waker: AtomicWaker, - pub tx_waker: AtomicWaker, - pub stop_waker: AtomicWaker, - } - - impl State { - pub const fn new() -> Self { - Self { - started: AtomicBool::new(false), - rx_waker: AtomicWaker::new(), - tx_waker: AtomicWaker::new(), - stop_waker: AtomicWaker::new(), - } +impl State { + pub(crate) const fn new() -> Self { + Self { + started: AtomicBool::new(false), + rx_waker: AtomicWaker::new(), + tx_waker: AtomicWaker::new(), + stop_waker: AtomicWaker::new(), } } - - pub trait Instance { - fn regs() -> &'static crate::pac::i2s::RegisterBlock; - fn state() -> &'static State; - } +} + +pub(crate) trait SealedInstance { + fn regs() -> pac::i2s::I2s; + fn state() -> &'static State; } /// I2S peripheral instance. -pub trait Instance: Peripheral

+ sealed::Instance + 'static + Send { +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static + Send { /// Interrupt for this peripheral. type Interrupt: interrupt::typelevel::Interrupt; } macro_rules! impl_i2s { ($type:ident, $pac_type:ident, $irq:ident) => { - impl crate::i2s::sealed::Instance for peripherals::$type { - fn regs() -> &'static crate::pac::i2s::RegisterBlock { - unsafe { &*pac::$pac_type::ptr() } + impl crate::i2s::SealedInstance for peripherals::$type { + fn regs() -> pac::i2s::I2s { + pac::$pac_type } - fn state() -> &'static crate::i2s::sealed::State { - static STATE: crate::i2s::sealed::State = crate::i2s::sealed::State::new(); + fn state() -> &'static crate::i2s::State { + static STATE: crate::i2s::State = crate::i2s::State::new(); &STATE } } diff --git a/embassy-nrf/src/lib.rs b/embassy-nrf/src/lib.rs index 358a7cc27..430b6fae7 100644 --- a/embassy-nrf/src/lib.rs +++ b/embassy-nrf/src/lib.rs @@ -11,7 +11,7 @@ #![doc = document_features::document_features!(feature_label = r#"{feature}"#)] #[cfg(not(any( - feature = "nrf51", + feature = "_nrf51", feature = "nrf52805", feature = "nrf52810", feature = "nrf52811", @@ -24,8 +24,36 @@ feature = "nrf5340-net", feature = "nrf9160-s", feature = "nrf9160-ns", + feature = "nrf9120-s", + feature = "nrf9120-ns", + feature = "nrf9151-s", + feature = "nrf9151-ns", + feature = "nrf9161-s", + feature = "nrf9161-ns", )))] -compile_error!("No chip feature activated. You must activate exactly one of the following features: nrf52810, nrf52811, nrf52832, nrf52833, nrf52840"); +compile_error!( + "No chip feature activated. You must activate exactly one of the following features: + nrf51, + nrf52805, + nrf52810, + nrf52811, + nrf52820, + nrf52832, + nrf52833, + nrf52840, + nrf5340-app-s, + nrf5340-app-ns, + nrf5340-net, + nrf9160-s, + nrf9160-ns, + nrf9120-s, + nrf9120-ns, + nrf9151-s, + nrf9151-ns, + nrf9161-s, + nrf9161-ns, + " +); #[cfg(all(feature = "reset-pin-as-gpio", not(feature = "_nrf52")))] compile_error!("feature `reset-pin-as-gpio` is only valid for nRF52 series chips."); @@ -40,11 +68,18 @@ pub(crate) mod util; #[cfg(feature = "_time-driver")] mod time_driver; -#[cfg(not(feature = "nrf51"))] +#[cfg(not(feature = "_nrf51"))] pub mod buffered_uarte; pub mod gpio; #[cfg(feature = "gpiote")] pub mod gpiote; + +// TODO: tested on other chips +#[cfg(not(any(feature = "_nrf91", feature = "_nrf5340-app")))] +pub mod radio; + +#[cfg(not(feature = "_nrf51"))] +pub mod egu; #[cfg(any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840"))] pub mod i2s; pub mod nvmc; @@ -55,37 +90,37 @@ pub mod nvmc; feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340-app", - feature = "_nrf9160" + feature = "_nrf91", ))] pub mod pdm; pub mod ppi; #[cfg(not(any( - feature = "nrf51", + feature = "_nrf51", feature = "nrf52805", feature = "nrf52820", feature = "_nrf5340-net" )))] pub mod pwm; -#[cfg(not(any(feature = "nrf51", feature = "_nrf9160", feature = "_nrf5340-net")))] +#[cfg(not(any(feature = "_nrf51", feature = "_nrf91", feature = "_nrf5340-net")))] pub mod qdec; #[cfg(any(feature = "nrf52840", feature = "_nrf5340-app"))] pub mod qspi; -#[cfg(not(any(feature = "_nrf5340-app", feature = "_nrf9160")))] +#[cfg(not(any(feature = "_nrf5340-app", feature = "_nrf91")))] pub mod rng; -#[cfg(not(any(feature = "nrf51", feature = "nrf52820", feature = "_nrf5340-net")))] +#[cfg(not(any(feature = "_nrf51", feature = "nrf52820", feature = "_nrf5340-net")))] pub mod saadc; -#[cfg(not(feature = "nrf51"))] +#[cfg(not(feature = "_nrf51"))] pub mod spim; -#[cfg(not(feature = "nrf51"))] +#[cfg(not(feature = "_nrf51"))] pub mod spis; -#[cfg(not(any(feature = "_nrf5340", feature = "_nrf9160")))] +#[cfg(not(any(feature = "_nrf5340", feature = "_nrf91")))] pub mod temp; pub mod timer; -#[cfg(not(feature = "nrf51"))] +#[cfg(not(feature = "_nrf51"))] pub mod twim; -#[cfg(not(feature = "nrf51"))] +#[cfg(not(feature = "_nrf51"))] pub mod twis; -#[cfg(not(feature = "nrf51"))] +#[cfg(not(feature = "_nrf51"))] pub mod uarte; #[cfg(any( feature = "_nrf5340-app", @@ -98,7 +133,7 @@ pub mod usb; pub mod wdt; // This mod MUST go last, so that it sees all the `impl_foo!` macros -#[cfg_attr(feature = "nrf51", path = "chips/nrf51.rs")] +#[cfg_attr(feature = "_nrf51", path = "chips/nrf51.rs")] #[cfg_attr(feature = "nrf52805", path = "chips/nrf52805.rs")] #[cfg_attr(feature = "nrf52810", path = "chips/nrf52810.rs")] #[cfg_attr(feature = "nrf52811", path = "chips/nrf52811.rs")] @@ -109,6 +144,7 @@ pub mod wdt; #[cfg_attr(feature = "_nrf5340-app", path = "chips/nrf5340_app.rs")] #[cfg_attr(feature = "_nrf5340-net", path = "chips/nrf5340_net.rs")] #[cfg_attr(feature = "_nrf9160", path = "chips/nrf9160.rs")] +#[cfg_attr(feature = "_nrf9120", path = "chips/nrf9120.rs")] mod chip; /// Macro to bind interrupts to handlers. @@ -141,25 +177,43 @@ mod chip; // developer note: this macro can't be in `embassy-hal-internal` due to the use of `$crate`. #[macro_export] macro_rules! bind_interrupts { - ($vis:vis struct $name:ident { $($irq:ident => $($handler:ty),*;)* }) => { - #[derive(Copy, Clone)] - $vis struct $name; - - $( - #[allow(non_snake_case)] - #[no_mangle] - unsafe extern "C" fn $irq() { - $( - <$handler as $crate::interrupt::typelevel::Handler<$crate::interrupt::typelevel::$irq>>::on_interrupt(); - )* - } + ($vis:vis struct $name:ident { + $( + $(#[cfg($cond_irq:meta)])? + $irq:ident => $( + $(#[cfg($cond_handler:meta)])? + $handler:ty + ),*; + )* + }) => { + #[derive(Copy, Clone)] + $vis struct $name; + $( + #[allow(non_snake_case)] + #[no_mangle] + $(#[cfg($cond_irq)])? + unsafe extern "C" fn $irq() { $( + $(#[cfg($cond_handler)])? + <$handler as $crate::interrupt::typelevel::Handler<$crate::interrupt::typelevel::$irq>>::on_interrupt(); + + )* + } + + $(#[cfg($cond_irq)])? + $crate::bind_interrupts!(@inner + $( + $(#[cfg($cond_handler)])? unsafe impl $crate::interrupt::typelevel::Binding<$crate::interrupt::typelevel::$irq, $handler> for $name {} )* - )* - }; + ); + )* + }; + (@inner $($t:tt)*) => { + $($t)* } +} // Reexports @@ -171,6 +225,7 @@ pub use chip::{peripherals, Peripherals, EASY_DMA_SIZE}; pub use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef}; pub use crate::chip::interrupt; +#[cfg(feature = "rt")] pub use crate::pac::NVIC_PRIO_BITS; pub mod config { @@ -189,15 +244,15 @@ pub mod config { /// Internal RC oscillator InternalRC, /// Synthesized from the high frequency clock source. - #[cfg(not(any(feature = "_nrf5340", feature = "_nrf9160")))] + #[cfg(not(any(feature = "_nrf5340", feature = "_nrf91")))] Synthesized, /// External source from xtal. ExternalXtal, /// External source from xtal with low swing applied. - #[cfg(not(any(feature = "_nrf5340", feature = "_nrf9160")))] + #[cfg(not(any(feature = "_nrf5340", feature = "_nrf91")))] ExternalLowSwing, /// External source from xtal with full swing applied. - #[cfg(not(any(feature = "_nrf5340", feature = "_nrf9160")))] + #[cfg(not(any(feature = "_nrf5340", feature = "_nrf91")))] ExternalFullSwing, } @@ -215,15 +270,36 @@ pub mod config { } /// Settings for enabling the built in DCDC converters. - #[cfg(not(any(feature = "_nrf5340", feature = "_nrf9160")))] + #[cfg(not(any(feature = "_nrf5340", feature = "_nrf91")))] pub struct DcdcConfig { /// Config for the first stage DCDC (VDDH -> VDD), if disabled LDO will be used. #[cfg(feature = "nrf52840")] pub reg0: bool, + /// Configure the voltage of the first stage DCDC. It is stored in non-volatile memory (UICR.REGOUT0 register); pass None to not touch it. + #[cfg(feature = "nrf52840")] + pub reg0_voltage: Option, /// Config for the second stage DCDC (VDD -> DEC4), if disabled LDO will be used. pub reg1: bool, } + /// Output voltage setting for REG0 regulator stage. + #[cfg(feature = "nrf52840")] + pub enum Reg0Voltage { + /// 1.8 V + _1V8 = 0, + /// 2.1 V + _2V1 = 1, + /// 2.4 V + _2V4 = 2, + /// 2.7 V + _2V7 = 3, + /// 3.0 V + _3V0 = 4, + /// 3.3 V + _3v3 = 5, + //ERASED = 7, means 1.8V + } + /// Settings for enabling the built in DCDC converters. #[cfg(feature = "_nrf5340-app")] pub struct DcdcConfig { @@ -236,7 +312,7 @@ pub mod config { } /// Settings for enabling the built in DCDC converter. - #[cfg(feature = "_nrf9160")] + #[cfg(feature = "_nrf91")] pub struct DcdcConfig { /// Config for the main rail, if disabled LDO will be used. pub regmain: bool, @@ -270,10 +346,12 @@ pub mod config { // xtals if they know they have them. hfclk_source: HfclkSource::Internal, lfclk_source: LfclkSource::InternalRC, - #[cfg(not(any(feature = "_nrf5340", feature = "_nrf9160")))] + #[cfg(not(any(feature = "_nrf5340", feature = "_nrf91")))] dcdc: DcdcConfig { #[cfg(feature = "nrf52840")] reg0: false, + #[cfg(feature = "nrf52840")] + reg0_voltage: None, reg1: false, }, #[cfg(feature = "_nrf5340-app")] @@ -282,7 +360,7 @@ pub mod config { regmain: false, regradio: false, }, - #[cfg(feature = "_nrf9160")] + #[cfg(feature = "_nrf91")] dcdc: DcdcConfig { regmain: false }, #[cfg(feature = "gpiote")] gpiote_interrupt_priority: crate::interrupt::Priority::P0, @@ -299,7 +377,7 @@ pub mod config { } } -#[cfg(feature = "_nrf9160")] +#[cfg(feature = "_nrf91")] #[allow(unused)] mod consts { pub const UICR_APPROTECT: *mut u32 = 0x00FF8000 as *mut u32; @@ -332,11 +410,12 @@ mod consts { pub const UICR_PSELRESET2: *mut u32 = 0x10001204 as *mut u32; pub const UICR_NFCPINS: *mut u32 = 0x1000120C as *mut u32; pub const UICR_APPROTECT: *mut u32 = 0x10001208 as *mut u32; + pub const UICR_REGOUT0: *mut u32 = 0x10001304 as *mut u32; pub const APPROTECT_ENABLED: u32 = 0x0000_0000; pub const APPROTECT_DISABLED: u32 = 0x0000_005a; } -#[cfg(not(feature = "nrf51"))] +#[cfg(not(feature = "_nrf51"))] #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] enum WriteResult { @@ -348,12 +427,12 @@ enum WriteResult { Failed, } -#[cfg(not(feature = "nrf51"))] +#[cfg(not(feature = "_nrf51"))] unsafe fn uicr_write(address: *mut u32, value: u32) -> WriteResult { uicr_write_masked(address, value, 0xFFFF_FFFF) } -#[cfg(not(feature = "nrf51"))] +#[cfg(not(feature = "_nrf51"))] unsafe fn uicr_write_masked(address: *mut u32, value: u32, mask: u32) -> WriteResult { let curr_val = address.read_volatile(); if curr_val & mask == value & mask { @@ -365,13 +444,13 @@ unsafe fn uicr_write_masked(address: *mut u32, value: u32, mask: u32) -> WriteRe return WriteResult::Failed; } - let nvmc = &*pac::NVMC::ptr(); - nvmc.config.write(|w| w.wen().wen()); - while nvmc.ready.read().ready().is_busy() {} + let nvmc = pac::NVMC; + nvmc.config().write(|w| w.set_wen(pac::nvmc::vals::Wen::WEN)); + while !nvmc.ready().read().ready() {} address.write_volatile(value | !mask); - while nvmc.ready.read().ready().is_busy() {} - nvmc.config.reset(); - while nvmc.ready.read().ready().is_busy() {} + while !nvmc.ready().read().ready() {} + nvmc.config().write(|_| {}); + while !nvmc.ready().read().ready() {} WriteResult::Written } @@ -390,7 +469,7 @@ pub fn init(config: config::Config) -> Peripherals { let mut needs_reset = false; // Setup debug protection. - #[cfg(not(feature = "nrf51"))] + #[cfg(not(feature = "_nrf51"))] match config.debug { config::Debug::Allowed => { #[cfg(feature = "_nrf52")] @@ -417,17 +496,17 @@ pub fn init(config: config::Config) -> Peripherals { #[cfg(feature = "_nrf5340")] unsafe { - let p = &*pac::CTRLAP::ptr(); + let p = pac::CTRLAP; let res = uicr_write(consts::UICR_APPROTECT, consts::APPROTECT_DISABLED); needs_reset |= res == WriteResult::Written; - p.approtect.disable.write(|w| w.bits(consts::APPROTECT_DISABLED)); + p.approtect().disable().write_value(consts::APPROTECT_DISABLED); #[cfg(feature = "_nrf5340-app")] { let res = uicr_write(consts::UICR_SECUREAPPROTECT, consts::APPROTECT_DISABLED); needs_reset |= res == WriteResult::Written; - p.secureapprotect.disable.write(|w| w.bits(consts::APPROTECT_DISABLED)); + p.secureapprotect().disable().write_value(consts::APPROTECT_DISABLED); } } @@ -437,7 +516,7 @@ pub fn init(config: config::Config) -> Peripherals { // UICR.APPROTECT = Enabled let res = uicr_write(consts::UICR_APPROTECT, consts::APPROTECT_ENABLED); needs_reset |= res == WriteResult::Written; - #[cfg(any(feature = "_nrf5340-app", feature = "_nrf9160"))] + #[cfg(any(feature = "_nrf5340-app", feature = "_nrf91"))] { let res = uicr_write(consts::UICR_SECUREAPPROTECT, consts::APPROTECT_ENABLED); needs_reset |= res == WriteResult::Written; @@ -488,89 +567,98 @@ pub fn init(config: config::Config) -> Peripherals { } } + #[cfg(feature = "nrf52840")] + unsafe { + if let Some(value) = config.dcdc.reg0_voltage { + let value = value as u32; + let res = uicr_write_masked(consts::UICR_REGOUT0, value, 0b00000000_00000000_00000000_00000111); + needs_reset |= res == WriteResult::Written; + if res == WriteResult::Failed { + warn!( + "Failed to set regulator voltage, as UICR is already programmed to some other setting, and can't be changed without erasing it.\n\ + To fix this, erase UICR manually, for example using `probe-rs erase` or `nrfjprog --eraseuicr`." + ); + } + } + } + if needs_reset { cortex_m::peripheral::SCB::sys_reset(); } - let r = unsafe { &*pac::CLOCK::ptr() }; + let r = pac::CLOCK; // Start HFCLK. match config.hfclk_source { config::HfclkSource::Internal => {} config::HfclkSource::ExternalXtal => { // Datasheet says this is likely to take 0.36ms - r.events_hfclkstarted.write(|w| unsafe { w.bits(0) }); - r.tasks_hfclkstart.write(|w| unsafe { w.bits(1) }); - while r.events_hfclkstarted.read().bits() == 0 {} + r.events_hfclkstarted().write_value(0); + r.tasks_hfclkstart().write_value(1); + while r.events_hfclkstarted().read() == 0 {} } } // Configure LFCLK. - #[cfg(not(any(feature = "nrf51", feature = "_nrf5340", feature = "_nrf9160")))] + #[cfg(not(any(feature = "_nrf51", feature = "_nrf5340", feature = "_nrf91")))] match config.lfclk_source { - config::LfclkSource::InternalRC => r.lfclksrc.write(|w| w.src().rc()), - config::LfclkSource::Synthesized => r.lfclksrc.write(|w| w.src().synth()), - - config::LfclkSource::ExternalXtal => r.lfclksrc.write(|w| w.src().xtal()), - - config::LfclkSource::ExternalLowSwing => r.lfclksrc.write(|w| { - w.src().xtal(); - w.external().enabled(); - w.bypass().disabled(); - w + config::LfclkSource::InternalRC => r.lfclksrc().write(|w| w.set_src(pac::clock::vals::Lfclksrc::RC)), + config::LfclkSource::Synthesized => r.lfclksrc().write(|w| w.set_src(pac::clock::vals::Lfclksrc::SYNTH)), + config::LfclkSource::ExternalXtal => r.lfclksrc().write(|w| w.set_src(pac::clock::vals::Lfclksrc::XTAL)), + config::LfclkSource::ExternalLowSwing => r.lfclksrc().write(|w| { + w.set_src(pac::clock::vals::Lfclksrc::XTAL); + w.set_external(true); + w.set_bypass(false); }), - config::LfclkSource::ExternalFullSwing => r.lfclksrc.write(|w| { - w.src().xtal(); - w.external().enabled(); - w.bypass().enabled(); - w + config::LfclkSource::ExternalFullSwing => r.lfclksrc().write(|w| { + w.set_src(pac::clock::vals::Lfclksrc::XTAL); + w.set_external(true); + w.set_bypass(true); }), } - #[cfg(feature = "_nrf9160")] + #[cfg(feature = "_nrf91")] match config.lfclk_source { - config::LfclkSource::InternalRC => r.lfclksrc.write(|w| w.src().lfrc()), - config::LfclkSource::ExternalXtal => r.lfclksrc.write(|w| w.src().lfxo()), + config::LfclkSource::InternalRC => r.lfclksrc().write(|w| w.set_src(pac::clock::vals::Lfclksrc::LFRC)), + config::LfclkSource::ExternalXtal => r.lfclksrc().write(|w| w.set_src(pac::clock::vals::Lfclksrc::LFXO)), } // Start LFCLK. // Datasheet says this could take 100us from synth source // 600us from rc source, 0.25s from an external source. - r.events_lfclkstarted.write(|w| unsafe { w.bits(0) }); - r.tasks_lfclkstart.write(|w| unsafe { w.bits(1) }); - while r.events_lfclkstarted.read().bits() == 0 {} + r.events_lfclkstarted().write_value(0); + r.tasks_lfclkstart().write_value(1); + while r.events_lfclkstarted().read() == 0 {} - #[cfg(not(any(feature = "_nrf5340", feature = "_nrf9160")))] + #[cfg(not(any(feature = "_nrf5340", feature = "_nrf91")))] { // Setup DCDCs. - let pwr = unsafe { &*pac::POWER::ptr() }; #[cfg(feature = "nrf52840")] if config.dcdc.reg0 { - pwr.dcdcen0.write(|w| w.dcdcen().set_bit()); + pac::POWER.dcdcen0().write(|w| w.set_dcdcen(true)); } if config.dcdc.reg1 { - pwr.dcdcen.write(|w| w.dcdcen().set_bit()); + pac::POWER.dcdcen().write(|w| w.set_dcdcen(true)); } } - #[cfg(feature = "_nrf9160")] + #[cfg(feature = "_nrf91")] { // Setup DCDC. - let reg = unsafe { &*pac::REGULATORS::ptr() }; if config.dcdc.regmain { - reg.dcdcen.write(|w| w.dcdcen().set_bit()); + pac::REGULATORS.dcdcen().write(|w| w.set_dcdcen(true)); } } #[cfg(feature = "_nrf5340-app")] { // Setup DCDC. - let reg = unsafe { &*pac::REGULATORS::ptr() }; + let reg = pac::REGULATORS; if config.dcdc.regh { - reg.vregh.dcdcen.write(|w| w.dcdcen().set_bit()); + reg.vregh().dcdcen().write(|w| w.set_dcdcen(true)); } if config.dcdc.regmain { - reg.vregmain.dcdcen.write(|w| w.dcdcen().set_bit()); + reg.vregmain().dcdcen().write(|w| w.set_dcdcen(true)); } if config.dcdc.regradio { - reg.vregradio.dcdcen.write(|w| w.dcdcen().set_bit()); + reg.vregradio().dcdcen().write(|w| w.set_dcdcen(true)); } } @@ -583,10 +671,11 @@ pub fn init(config: config::Config) -> Peripherals { time_driver::init(config.time_interrupt_priority); // Disable UARTE (enabled by default for some reason) - #[cfg(feature = "_nrf9160")] - unsafe { - (*pac::UARTE0::ptr()).enable.write(|w| w.enable().disabled()); - (*pac::UARTE1::ptr()).enable.write(|w| w.enable().disabled()); + #[cfg(feature = "_nrf91")] + { + use pac::uarte::vals::Enable; + pac::UARTE0.enable().write(|w| w.set_enable(Enable::DISABLED)); + pac::UARTE1.enable().write(|w| w.set_enable(Enable::DISABLED)); } peripherals diff --git a/embassy-nrf/src/nvmc.rs b/embassy-nrf/src/nvmc.rs index de840b886..6973b4847 100644 --- a/embassy-nrf/src/nvmc.rs +++ b/embassy-nrf/src/nvmc.rs @@ -7,6 +7,7 @@ use embedded_storage::nor_flash::{ ErrorType, MultiwriteNorFlash, NorFlash, NorFlashError, NorFlashErrorKind, ReadNorFlash, }; +use crate::pac::nvmc::vals; use crate::peripherals::NVMC; use crate::{pac, Peripheral}; @@ -51,32 +52,32 @@ impl<'d> Nvmc<'d> { Self { _p } } - fn regs() -> &'static pac::nvmc::RegisterBlock { - unsafe { &*pac::NVMC::ptr() } + fn regs() -> pac::nvmc::Nvmc { + pac::NVMC } fn wait_ready(&mut self) { let p = Self::regs(); - while p.ready.read().ready().is_busy() {} + while !p.ready().read().ready() {} } - #[cfg(not(any(feature = "_nrf9160", feature = "_nrf5340")))] + #[cfg(not(any(feature = "_nrf91", feature = "_nrf5340")))] fn wait_ready_write(&mut self) { self.wait_ready(); } - #[cfg(any(feature = "_nrf9160", feature = "_nrf5340"))] + #[cfg(any(feature = "_nrf91", feature = "_nrf5340"))] fn wait_ready_write(&mut self) { let p = Self::regs(); - while p.readynext.read().readynext().is_busy() {} + while !p.readynext().read().readynext() {} } - #[cfg(not(any(feature = "_nrf9160", feature = "_nrf5340")))] + #[cfg(not(any(feature = "_nrf91", feature = "_nrf5340")))] fn erase_page(&mut self, page_addr: u32) { - Self::regs().erasepage().write(|w| unsafe { w.bits(page_addr) }); + Self::regs().erasepage().write_value(page_addr); } - #[cfg(any(feature = "_nrf9160", feature = "_nrf5340"))] + #[cfg(any(feature = "_nrf91", feature = "_nrf5340"))] fn erase_page(&mut self, page_addr: u32) { let first_page_word = page_addr as *mut u32; unsafe { @@ -86,23 +87,23 @@ impl<'d> Nvmc<'d> { fn enable_erase(&self) { #[cfg(not(feature = "_ns"))] - Self::regs().config.write(|w| w.wen().een()); + Self::regs().config().write(|w| w.set_wen(vals::Wen::EEN)); #[cfg(feature = "_ns")] - Self::regs().configns.write(|w| w.wen().een()); + Self::regs().configns().write(|w| w.set_wen(vals::ConfignsWen::EEN)); } fn enable_read(&self) { #[cfg(not(feature = "_ns"))] - Self::regs().config.write(|w| w.wen().ren()); + Self::regs().config().write(|w| w.set_wen(vals::Wen::REN)); #[cfg(feature = "_ns")] - Self::regs().configns.write(|w| w.wen().ren()); + Self::regs().configns().write(|w| w.set_wen(vals::ConfignsWen::REN)); } fn enable_write(&self) { #[cfg(not(feature = "_ns"))] - Self::regs().config.write(|w| w.wen().wen()); + Self::regs().config().write(|w| w.set_wen(vals::Wen::WEN)); #[cfg(feature = "_ns")] - Self::regs().configns.write(|w| w.wen().wen()); + Self::regs().configns().write(|w| w.set_wen(vals::ConfignsWen::WEN)); } } @@ -160,7 +161,7 @@ impl<'d> NorFlash for Nvmc<'d> { if offset as usize + bytes.len() > FLASH_SIZE { return Err(Error::OutOfBounds); } - if offset as usize % 4 != 0 || bytes.len() as usize % 4 != 0 { + if offset as usize % 4 != 0 || bytes.len() % 4 != 0 { return Err(Error::Unaligned); } diff --git a/embassy-nrf/src/pdm.rs b/embassy-nrf/src/pdm.rs index 356ed97a5..75ad33e28 100644 --- a/embassy-nrf/src/pdm.rs +++ b/embassy-nrf/src/pdm.rs @@ -1,4 +1,4 @@ -//! Pulse Density Modulation (PDM) mirophone driver. +//! Pulse Density Modulation (PDM) microphone driver #![macro_use] @@ -9,24 +9,25 @@ use core::task::Poll; use embassy_hal_internal::drop::OnDrop; use embassy_hal_internal::{into_ref, PeripheralRef}; +use embassy_sync::waitqueue::AtomicWaker; use fixed::types::I7F1; use crate::chip::EASY_DMA_SIZE; -use crate::gpio::sealed::Pin; -use crate::gpio::{AnyPin, Pin as GpioPin}; +use crate::gpio::{AnyPin, Pin as GpioPin, SealedPin, DISCONNECTED}; use crate::interrupt::typelevel::Interrupt; -use crate::pac::pdm::mode::{EDGE_A, OPERATION_A}; -pub use crate::pac::pdm::pdmclkctrl::FREQ_A as Frequency; +use crate::pac::gpio::vals as gpiovals; +use crate::pac::pdm::vals; +pub use crate::pac::pdm::vals::Freq as Frequency; #[cfg(any( feature = "nrf52840", feature = "nrf52833", feature = "_nrf5340-app", - feature = "_nrf9160", + feature = "_nrf91", ))] -pub use crate::pac::pdm::ratio::RATIO_A as Ratio; -use crate::{interrupt, Peripheral}; +pub use crate::pac::pdm::vals::Ratio; +use crate::{interrupt, pac, Peripheral}; -/// Interrupt handler. +/// Interrupt handler pub struct InterruptHandler { _phantom: PhantomData, } @@ -35,16 +36,16 @@ impl interrupt::typelevel::Handler for InterruptHandl unsafe fn on_interrupt() { let r = T::regs(); - if r.events_end.read().bits() != 0 { - r.intenclr.write(|w| w.end().clear()); + if r.events_end().read() != 0 { + r.intenclr().write(|w| w.set_end(true)); } - if r.events_started.read().bits() != 0 { - r.intenclr.write(|w| w.started().clear()); + if r.events_started().read() != 0 { + r.intenclr().write(|w| w.set_started(true)); } - if r.events_stopped.read().bits() != 0 { - r.intenclr.write(|w| w.stopped().clear()); + if r.events_stopped().read() != 0 { + r.intenclr().write(|w| w.set_stopped(true)); } T::state().waker.wake(); @@ -56,12 +57,12 @@ pub struct Pdm<'d, T: Instance> { _peri: PeripheralRef<'d, T>, } -/// PDM error. +/// PDM error #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[non_exhaustive] pub enum Error { - /// Buffer is too long. + /// Buffer is too long BufferTooLong, /// Buffer is empty BufferZeroLength, @@ -75,13 +76,13 @@ static DUMMY_BUFFER: [i16; 1] = [0; 1]; /// The state of a continuously running sampler. While it reflects /// the progress of a sampler, it also signals what should be done -/// next. For example, if the sampler has stopped then the Pdm implementation -/// can then tear down its infrastructure. +/// next. For example, if the sampler has stopped then the PDM implementation +/// can then tear down its infrastructure #[derive(PartialEq)] pub enum SamplerState { - /// The sampler processed the samples and is ready for more. + /// The sampler processed the samples and is ready for more Sampled, - /// The sampler is done processing samples. + /// The sampler is done processing samples Stopped, } @@ -125,51 +126,47 @@ impl<'d, T: Instance> Pdm<'d, T> { let r = T::regs(); // setup gpio pins - din.conf().write(|w| w.input().set_bit()); - r.psel.din.write(|w| unsafe { w.bits(din.psel_bits()) }); + din.conf().write(|w| w.set_input(gpiovals::Input::CONNECT)); + r.psel().din().write_value(din.psel_bits()); clk.set_low(); - clk.conf().write(|w| w.dir().output()); - r.psel.clk.write(|w| unsafe { w.bits(clk.psel_bits()) }); + clk.conf().write(|w| w.set_dir(gpiovals::Dir::OUTPUT)); + r.psel().clk().write_value(clk.psel_bits()); // configure - r.pdmclkctrl.write(|w| w.freq().variant(config.frequency)); + r.pdmclkctrl().write(|w| w.set_freq(config.frequency)); #[cfg(any( feature = "nrf52840", feature = "nrf52833", feature = "_nrf5340-app", - feature = "_nrf9160", + feature = "_nrf91", ))] - r.ratio.write(|w| w.ratio().variant(config.ratio)); - r.mode.write(|w| { - w.operation().variant(config.operation_mode.into()); - w.edge().variant(config.edge.into()); - w + r.ratio().write(|w| w.set_ratio(config.ratio)); + r.mode().write(|w| { + w.set_operation(config.operation_mode.into()); + w.set_edge(config.edge.into()); }); Self::_set_gain(r, config.gain_left, config.gain_right); // Disable all events interrupts - r.intenclr.write(|w| unsafe { w.bits(0x003F_FFFF) }); + r.intenclr().write(|w| w.0 = 0x003F_FFFF); // IRQ T::Interrupt::unpend(); unsafe { T::Interrupt::enable() }; - r.enable.write(|w| w.enable().set_bit()); + r.enable().write(|w| w.set_enable(true)); Self { _peri: pdm } } - fn _set_gain(r: &crate::pac::pdm::RegisterBlock, gain_left: I7F1, gain_right: I7F1) { - let gain_to_bits = |gain: I7F1| -> u8 { - let gain = gain.saturating_add(I7F1::from_bits(0x28)).to_bits().clamp(0, 0x50); - unsafe { core::mem::transmute(gain) } + fn _set_gain(r: pac::pdm::Pdm, gain_left: I7F1, gain_right: I7F1) { + let gain_to_bits = |gain: I7F1| -> vals::Gain { + let gain: i8 = gain.saturating_add(I7F1::from_bits(0x28)).to_bits().clamp(0, 0x50); + vals::Gain::from_bits(gain as u8) }; - let gain_left = gain_to_bits(gain_left); - let gain_right = gain_to_bits(gain_right); - - r.gainl.write(|w| unsafe { w.gainl().bits(gain_left) }); - r.gainr.write(|w| unsafe { w.gainr().bits(gain_right) }); + r.gainl().write(|w| w.set_gainl(gain_to_bits(gain_left))); + r.gainr().write(|w| w.set_gainr(gain_to_bits(gain_right))); } /// Adjust the gain of the PDM microphone on the fly @@ -177,32 +174,28 @@ impl<'d, T: Instance> Pdm<'d, T> { Self::_set_gain(T::regs(), gain_left, gain_right) } - /// Start sampling microphon data into a dummy buffer - /// Usefull to start the microphon and keep it active between recording samples + /// Start sampling microphone data into a dummy buffer. + /// Useful to start the microphone and keep it active between recording samples. pub async fn start(&mut self) { let r = T::regs(); - // start dummy sampling because microphon needs some setup time - r.sample - .ptr - .write(|w| unsafe { w.sampleptr().bits(DUMMY_BUFFER.as_ptr() as u32) }); - r.sample - .maxcnt - .write(|w| unsafe { w.buffsize().bits(DUMMY_BUFFER.len() as _) }); + // start dummy sampling because microphone needs some setup time + r.sample().ptr().write_value(DUMMY_BUFFER.as_ptr() as u32); + r.sample().maxcnt().write(|w| w.set_buffsize(DUMMY_BUFFER.len() as _)); - r.tasks_start.write(|w| unsafe { w.bits(1) }); + r.tasks_start().write_value(1); } - /// Stop sampling microphon data inta a dummy buffer + /// Stop sampling microphone data inta a dummy buffer pub async fn stop(&mut self) { let r = T::regs(); - r.tasks_stop.write(|w| unsafe { w.bits(1) }); - r.events_started.reset(); + r.tasks_stop().write_value(1); + r.events_started().write_value(0); } - /// Sample data into the given buffer. + /// Sample data into the given buffer pub async fn sample(&mut self, buffer: &mut [i16]) -> Result<(), Error> { - if buffer.len() == 0 { + if buffer.is_empty() { return Err(Error::BufferZeroLength); } if buffer.len() > EASY_DMA_SIZE { @@ -211,41 +204,33 @@ impl<'d, T: Instance> Pdm<'d, T> { let r = T::regs(); - if r.events_started.read().bits() == 0 { + if r.events_started().read() == 0 { return Err(Error::NotRunning); } let drop = OnDrop::new(move || { - r.intenclr.write(|w| w.end().clear()); - r.events_stopped.reset(); + r.intenclr().write(|w| w.set_end(true)); + r.events_stopped().write_value(0); // reset to dummy buffer - r.sample - .ptr - .write(|w| unsafe { w.sampleptr().bits(DUMMY_BUFFER.as_ptr() as u32) }); - r.sample - .maxcnt - .write(|w| unsafe { w.buffsize().bits(DUMMY_BUFFER.len() as _) }); + r.sample().ptr().write_value(DUMMY_BUFFER.as_ptr() as u32); + r.sample().maxcnt().write(|w| w.set_buffsize(DUMMY_BUFFER.len() as _)); - while r.events_stopped.read().bits() == 0 {} + while r.events_stopped().read() == 0 {} }); // setup user buffer let ptr = buffer.as_ptr(); let len = buffer.len(); - r.sample.ptr.write(|w| unsafe { w.sampleptr().bits(ptr as u32) }); - r.sample.maxcnt.write(|w| unsafe { w.buffsize().bits(len as _) }); + r.sample().ptr().write_value(ptr as u32); + r.sample().maxcnt().write(|w| w.set_buffsize(len as _)); // wait till the current sample is finished and the user buffer sample is started Self::wait_for_sample().await; // reset the buffer back to the dummy buffer - r.sample - .ptr - .write(|w| unsafe { w.sampleptr().bits(DUMMY_BUFFER.as_ptr() as u32) }); - r.sample - .maxcnt - .write(|w| unsafe { w.buffsize().bits(DUMMY_BUFFER.len() as _) }); + r.sample().ptr().write_value(DUMMY_BUFFER.as_ptr() as u32); + r.sample().maxcnt().write(|w| w.set_buffsize(DUMMY_BUFFER.len() as _)); // wait till the user buffer is sampled Self::wait_for_sample().await; @@ -258,14 +243,14 @@ impl<'d, T: Instance> Pdm<'d, T> { async fn wait_for_sample() { let r = T::regs(); - r.events_end.reset(); - r.intenset.write(|w| w.end().set()); + r.events_end().write_value(0); + r.intenset().write(|w| w.set_end(true)); compiler_fence(Ordering::SeqCst); poll_fn(|cx| { T::state().waker.register(cx.waker()); - if r.events_end.read().bits() != 0 { + if r.events_end().read() != 0 { return Poll::Ready(()); } Poll::Pending @@ -296,77 +281,72 @@ impl<'d, T: Instance> Pdm<'d, T> { { let r = T::regs(); - if r.events_started.read().bits() != 0 { + if r.events_started().read() != 0 { return Err(Error::AlreadyRunning); } - r.sample - .ptr - .write(|w| unsafe { w.sampleptr().bits(bufs[0].as_mut_ptr() as u32) }); - r.sample.maxcnt.write(|w| unsafe { w.buffsize().bits(N as _) }); + r.sample().ptr().write_value(bufs[0].as_mut_ptr() as u32); + r.sample().maxcnt().write(|w| w.set_buffsize(N as _)); // Reset and enable the events - r.events_end.reset(); - r.events_started.reset(); - r.events_stopped.reset(); - r.intenset.write(|w| { - w.end().set(); - w.started().set(); - w.stopped().set(); - w + r.events_end().write_value(0); + r.events_started().write_value(0); + r.events_stopped().write_value(0); + r.intenset().write(|w| { + w.set_end(true); + w.set_started(true); + w.set_stopped(true); }); // Don't reorder the start event before the previous writes. Hopefully self - // wouldn't happen anyway. + // wouldn't happen anyway compiler_fence(Ordering::SeqCst); - r.tasks_start.write(|w| unsafe { w.bits(1) }); + r.tasks_start().write_value(1); let mut current_buffer = 0; let mut done = false; let drop = OnDrop::new(|| { - r.tasks_stop.write(|w| unsafe { w.bits(1) }); - // N.B. It would be better if this were async, but Drop only support sync code. - while r.events_stopped.read().bits() != 0 {} + r.tasks_stop().write_value(1); + // N.B. It would be better if this were async, but Drop only support sync code + while r.events_stopped().read() != 0 {} }); - // Wait for events and complete when the sampler indicates it has had enough. + // Wait for events and complete when the sampler indicates it has had enough poll_fn(|cx| { let r = T::regs(); T::state().waker.register(cx.waker()); - if r.events_end.read().bits() != 0 { + if r.events_end().read() != 0 { compiler_fence(Ordering::SeqCst); - r.events_end.reset(); - r.intenset.write(|w| w.end().set()); + r.events_end().write_value(0); + r.intenset().write(|w| w.set_end(true)); if !done { - // Discard the last buffer after the user requested a stop. + // Discard the last buffer after the user requested a stop if sampler(&bufs[current_buffer]) == SamplerState::Sampled { let next_buffer = 1 - current_buffer; current_buffer = next_buffer; } else { - r.tasks_stop.write(|w| unsafe { w.bits(1) }); + r.tasks_stop().write_value(1); done = true; }; }; } - if r.events_started.read().bits() != 0 { - r.events_started.reset(); - r.intenset.write(|w| w.started().set()); + if r.events_started().read() != 0 { + r.events_started().write_value(0); + r.intenset().write(|w| w.set_started(true)); let next_buffer = 1 - current_buffer; - r.sample - .ptr - .write(|w| unsafe { w.sampleptr().bits(bufs[next_buffer].as_mut_ptr() as u32) }); + r.sample().ptr().write_value(bufs[next_buffer].as_mut_ptr() as u32); } - if r.events_stopped.read().bits() != 0 { + if r.events_stopped().read() != 0 { return Poll::Ready(()); } @@ -510,7 +490,7 @@ pub struct Config { feature = "nrf52840", feature = "nrf52833", feature = "_nrf5340-app", - feature = "_nrf9160", + feature = "_nrf91", ))] pub ratio: Ratio, /// Gain left in dB @@ -529,7 +509,7 @@ impl Default for Config { feature = "nrf52840", feature = "nrf52833", feature = "_nrf5340-app", - feature = "_nrf9160", + feature = "_nrf91", ))] ratio: Ratio::RATIO80, gain_left: I7F1::ZERO, @@ -538,7 +518,7 @@ impl Default for Config { } } -/// PDM operation mode. +/// PDM operation mode #[derive(PartialEq)] pub enum OperationMode { /// Mono (1 channel) @@ -547,11 +527,11 @@ pub enum OperationMode { Stereo, } -impl From for OPERATION_A { +impl From for vals::Operation { fn from(mode: OperationMode) -> Self { match mode { - OperationMode::Mono => OPERATION_A::MONO, - OperationMode::Stereo => OPERATION_A::STEREO, + OperationMode::Mono => vals::Operation::MONO, + OperationMode::Stereo => vals::Operation::STEREO, } } } @@ -565,11 +545,11 @@ pub enum Edge { LeftFalling, } -impl From for EDGE_A { +impl From for vals::Edge { fn from(edge: Edge) -> Self { match edge { - Edge::LeftRising => EDGE_A::LEFT_RISING, - Edge::LeftFalling => EDGE_A::LEFT_FALLING, + Edge::LeftRising => vals::Edge::LEFT_RISING, + Edge::LeftFalling => vals::Edge::LEFT_FALLING, } } } @@ -578,51 +558,48 @@ impl<'d, T: Instance> Drop for Pdm<'d, T> { fn drop(&mut self) { let r = T::regs(); - r.tasks_stop.write(|w| unsafe { w.bits(1) }); + r.tasks_stop().write_value(1); - r.enable.write(|w| w.enable().disabled()); + r.enable().write(|w| w.set_enable(false)); - r.psel.din.reset(); - r.psel.clk.reset(); + r.psel().din().write_value(DISCONNECTED); + r.psel().clk().write_value(DISCONNECTED); } } -pub(crate) mod sealed { - use embassy_sync::waitqueue::AtomicWaker; +/// Peripheral static state +pub(crate) struct State { + waker: AtomicWaker, +} - /// Peripheral static state - pub struct State { - pub waker: AtomicWaker, - } - - impl State { - pub const fn new() -> Self { - Self { - waker: AtomicWaker::new(), - } +impl State { + pub(crate) const fn new() -> Self { + Self { + waker: AtomicWaker::new(), } } - - pub trait Instance { - fn regs() -> &'static crate::pac::pdm::RegisterBlock; - fn state() -> &'static State; - } } -/// PDM peripheral instance. -pub trait Instance: Peripheral

+ sealed::Instance + 'static + Send { - /// Interrupt for this peripheral. +pub(crate) trait SealedInstance { + fn regs() -> crate::pac::pdm::Pdm; + fn state() -> &'static State; +} + +/// PDM peripheral instance +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static + Send { + /// Interrupt for this peripheral type Interrupt: interrupt::typelevel::Interrupt; } macro_rules! impl_pdm { ($type:ident, $pac_type:ident, $irq:ident) => { - impl crate::pdm::sealed::Instance for peripherals::$type { - fn regs() -> &'static crate::pac::pdm::RegisterBlock { - unsafe { &*pac::$pac_type::ptr() } + impl crate::pdm::SealedInstance for peripherals::$type { + fn regs() -> crate::pac::pdm::Pdm { + pac::$pac_type } - fn state() -> &'static crate::pdm::sealed::State { - static STATE: crate::pdm::sealed::State = crate::pdm::sealed::State::new(); + fn state() -> &'static crate::pdm::State { + static STATE: crate::pdm::State = crate::pdm::State::new(); &STATE } } diff --git a/embassy-nrf/src/ppi/dppi.rs b/embassy-nrf/src/ppi/dppi.rs index 0bc7f821e..3c7b96df7 100644 --- a/embassy-nrf/src/ppi/dppi.rs +++ b/embassy-nrf/src/ppi/dppi.rs @@ -6,8 +6,8 @@ use crate::{pac, Peripheral}; const DPPI_ENABLE_BIT: u32 = 0x8000_0000; const DPPI_CHANNEL_MASK: u32 = 0x0000_00FF; -pub(crate) fn regs() -> &'static pac::dppic::RegisterBlock { - unsafe { &*pac::DPPIC::ptr() } +pub(crate) fn regs() -> pac::dppic::Dppic { + pac::DPPIC } impl<'d, C: ConfigurableChannel> Ppi<'d, C, 1, 1> { @@ -57,13 +57,13 @@ impl<'d, C: Channel, const EVENT_COUNT: usize, const TASK_COUNT: usize> Ppi<'d, /// Enables the channel. pub fn enable(&mut self) { let n = self.ch.number(); - regs().chenset.write(|w| unsafe { w.bits(1 << n) }); + regs().chenset().write(|w| w.0 = 1 << n); } /// Disables the channel. pub fn disable(&mut self) { let n = self.ch.number(); - regs().chenclr.write(|w| unsafe { w.bits(1 << n) }); + regs().chenclr().write(|w| w.0 = 1 << n); } } diff --git a/embassy-nrf/src/ppi/mod.rs b/embassy-nrf/src/ppi/mod.rs index f5764b8b7..325e4ce00 100644 --- a/embassy-nrf/src/ppi/mod.rs +++ b/embassy-nrf/src/ppi/mod.rs @@ -20,6 +20,7 @@ use core::ptr::NonNull; use embassy_hal_internal::{impl_peripheral, into_ref, PeripheralRef}; +use crate::pac::common::{Reg, RW, W}; use crate::{peripherals, Peripheral}; #[cfg_attr(feature = "_dppi", path = "dppi.rs")] @@ -50,7 +51,7 @@ impl<'d, G: Group> PpiGroup<'d, G> { let r = regs(); let n = g.number(); - r.chg[n].write(|w| unsafe { w.bits(0) }); + r.chg(n).write(|_| ()); Self { g } } @@ -65,7 +66,7 @@ impl<'d, G: Group> PpiGroup<'d, G> { let r = regs(); let ng = self.g.number(); let nc = ch.ch.number(); - r.chg[ng].modify(|r, w| unsafe { w.bits(r.bits() | 1 << nc) }); + r.chg(ng).modify(|w| w.set_ch(nc, true)); } /// Remove a PPI channel from this group. @@ -78,19 +79,19 @@ impl<'d, G: Group> PpiGroup<'d, G> { let r = regs(); let ng = self.g.number(); let nc = ch.ch.number(); - r.chg[ng].modify(|r, w| unsafe { w.bits(r.bits() & !(1 << nc)) }); + r.chg(ng).modify(|w| w.set_ch(nc, false)); } /// Enable all the channels in this group. pub fn enable_all(&mut self) { let n = self.g.number(); - regs().tasks_chg[n].en.write(|w| unsafe { w.bits(1) }); + regs().tasks_chg(n).en().write_value(1); } /// Disable all the channels in this group. pub fn disable_all(&mut self) { let n = self.g.number(); - regs().tasks_chg[n].dis.write(|w| unsafe { w.bits(1) }); + regs().tasks_chg(n).dis().write_value(1); } /// Get a reference to the "enable all" task. @@ -98,7 +99,7 @@ impl<'d, G: Group> PpiGroup<'d, G> { /// When triggered, it will enable all the channels in this group. pub fn task_enable_all(&self) -> Task<'d> { let n = self.g.number(); - Task::from_reg(®s().tasks_chg[n].en) + Task::from_reg(regs().tasks_chg(n).en()) } /// Get a reference to the "disable all" task. @@ -106,7 +107,7 @@ impl<'d, G: Group> PpiGroup<'d, G> { /// When triggered, it will disable all the channels in this group. pub fn task_disable_all(&self) -> Task<'d> { let n = self.g.number(); - Task::from_reg(®s().tasks_chg[n].dis) + Task::from_reg(regs().tasks_chg(n).dis()) } } @@ -114,7 +115,7 @@ impl<'d, G: Group> Drop for PpiGroup<'d, G> { fn drop(&mut self) { let r = regs(); let n = self.g.number(); - r.chg[n].write(|w| unsafe { w.bits(0) }); + r.chg(n).write(|_| ()); } } @@ -143,11 +144,8 @@ impl<'d> Task<'d> { unsafe { self.0.as_ptr().write_volatile(1) }; } - pub(crate) fn from_reg(reg: &T) -> Self { - Self( - unsafe { NonNull::new_unchecked(reg as *const _ as *mut _) }, - PhantomData, - ) + pub(crate) fn from_reg(reg: Reg) -> Self { + Self(unsafe { NonNull::new_unchecked(reg.as_ptr()) }, PhantomData) } /// Address of subscription register for this task. @@ -178,11 +176,8 @@ impl<'d> Event<'d> { Self(ptr, PhantomData) } - pub(crate) fn from_reg(reg: &'d T) -> Self { - Self( - unsafe { NonNull::new_unchecked(reg as *const _ as *mut _) }, - PhantomData, - ) + pub(crate) fn from_reg(reg: Reg) -> Self { + Self(unsafe { NonNull::new_unchecked(reg.as_ptr()) }, PhantomData) } /// Describes whether this Event is currently in a triggered state. @@ -210,13 +205,12 @@ unsafe impl Send for Event<'_> {} // ====================== // traits -pub(crate) mod sealed { - pub trait Channel {} - pub trait Group {} -} +pub(crate) trait SealedChannel {} +pub(crate) trait SealedGroup {} /// Interface for PPI channels. -pub trait Channel: sealed::Channel + Peripheral

+ Sized + 'static { +#[allow(private_bounds)] +pub trait Channel: SealedChannel + Peripheral

+ Sized + 'static { /// Returns the number of the channel fn number(&self) -> usize; } @@ -234,7 +228,8 @@ pub trait StaticChannel: Channel + Into { } /// Interface for a group of PPI channels. -pub trait Group: sealed::Group + Peripheral

+ Into + Sized + 'static { +#[allow(private_bounds)] +pub trait Group: SealedGroup + Peripheral

+ Into + Sized + 'static { /// Returns the number of the group. fn number(&self) -> usize; /// Convert into a type erased group. @@ -254,7 +249,7 @@ pub struct AnyStaticChannel { pub(crate) number: u8, } impl_peripheral!(AnyStaticChannel); -impl sealed::Channel for AnyStaticChannel {} +impl SealedChannel for AnyStaticChannel {} impl Channel for AnyStaticChannel { fn number(&self) -> usize { self.number as usize @@ -272,7 +267,7 @@ pub struct AnyConfigurableChannel { pub(crate) number: u8, } impl_peripheral!(AnyConfigurableChannel); -impl sealed::Channel for AnyConfigurableChannel {} +impl SealedChannel for AnyConfigurableChannel {} impl Channel for AnyConfigurableChannel { fn number(&self) -> usize { self.number as usize @@ -284,10 +279,10 @@ impl ConfigurableChannel for AnyConfigurableChannel { } } -#[cfg(not(feature = "nrf51"))] +#[cfg(not(feature = "_nrf51"))] macro_rules! impl_ppi_channel { ($type:ident, $number:expr) => { - impl crate::ppi::sealed::Channel for peripherals::$type {} + impl crate::ppi::SealedChannel for peripherals::$type {} impl crate::ppi::Channel for peripherals::$type { fn number(&self) -> usize { $number @@ -338,7 +333,7 @@ pub struct AnyGroup { number: u8, } impl_peripheral!(AnyGroup); -impl sealed::Group for AnyGroup {} +impl SealedGroup for AnyGroup {} impl Group for AnyGroup { fn number(&self) -> usize { self.number as usize @@ -347,7 +342,7 @@ impl Group for AnyGroup { macro_rules! impl_group { ($type:ident, $number:expr) => { - impl sealed::Group for peripherals::$type {} + impl SealedGroup for peripherals::$type {} impl Group for peripherals::$type { fn number(&self) -> usize { $number @@ -366,7 +361,7 @@ impl_group!(PPI_GROUP0, 0); impl_group!(PPI_GROUP1, 1); impl_group!(PPI_GROUP2, 2); impl_group!(PPI_GROUP3, 3); -#[cfg(not(feature = "nrf51"))] +#[cfg(not(feature = "_nrf51"))] impl_group!(PPI_GROUP4, 4); -#[cfg(not(feature = "nrf51"))] +#[cfg(not(feature = "_nrf51"))] impl_group!(PPI_GROUP5, 5); diff --git a/embassy-nrf/src/ppi/ppi.rs b/embassy-nrf/src/ppi/ppi.rs index 8ff52ece3..a1beb9dcd 100644 --- a/embassy-nrf/src/ppi/ppi.rs +++ b/embassy-nrf/src/ppi/ppi.rs @@ -14,11 +14,11 @@ impl<'d> Event<'d> { } } -pub(crate) fn regs() -> &'static pac::ppi::RegisterBlock { - unsafe { &*pac::PPI::ptr() } +pub(crate) fn regs() -> pac::ppi::Ppi { + pac::PPI } -#[cfg(not(feature = "nrf51"))] // Not for nrf51 because of the fork task +#[cfg(not(feature = "_nrf51"))] // Not for nrf51 because of the fork task impl<'d, C: super::StaticChannel> Ppi<'d, C, 0, 1> { /// Configure PPI channel to trigger `task`. pub fn new_zero_to_one(ch: impl Peripheral

+ 'd, task: Task) -> Self { @@ -26,7 +26,7 @@ impl<'d, C: super::StaticChannel> Ppi<'d, C, 0, 1> { let r = regs(); let n = ch.number(); - r.fork[n].tep.write(|w| unsafe { w.bits(task.reg_val()) }); + r.fork(n).tep().write_value(task.reg_val()); Self { ch } } @@ -39,14 +39,14 @@ impl<'d, C: ConfigurableChannel> Ppi<'d, C, 1, 1> { let r = regs(); let n = ch.number(); - r.ch[n].eep.write(|w| unsafe { w.bits(event.reg_val()) }); - r.ch[n].tep.write(|w| unsafe { w.bits(task.reg_val()) }); + r.ch(n).eep().write_value(event.reg_val()); + r.ch(n).tep().write_value(task.reg_val()); Self { ch } } } -#[cfg(not(feature = "nrf51"))] // Not for nrf51 because of the fork task +#[cfg(not(feature = "_nrf51"))] // Not for nrf51 because of the fork task impl<'d, C: ConfigurableChannel> Ppi<'d, C, 1, 2> { /// Configure PPI channel to trigger both `task1` and `task2` on `event`. pub fn new_one_to_two(ch: impl Peripheral

+ 'd, event: Event<'d>, task1: Task<'d>, task2: Task<'d>) -> Self { @@ -54,9 +54,9 @@ impl<'d, C: ConfigurableChannel> Ppi<'d, C, 1, 2> { let r = regs(); let n = ch.number(); - r.ch[n].eep.write(|w| unsafe { w.bits(event.reg_val()) }); - r.ch[n].tep.write(|w| unsafe { w.bits(task1.reg_val()) }); - r.fork[n].tep.write(|w| unsafe { w.bits(task2.reg_val()) }); + r.ch(n).eep().write_value(event.reg_val()); + r.ch(n).tep().write_value(task1.reg_val()); + r.fork(n).tep().write_value(task2.reg_val()); Self { ch } } @@ -66,13 +66,13 @@ impl<'d, C: Channel, const EVENT_COUNT: usize, const TASK_COUNT: usize> Ppi<'d, /// Enables the channel. pub fn enable(&mut self) { let n = self.ch.number(); - regs().chenset.write(|w| unsafe { w.bits(1 << n) }); + regs().chenset().write(|w| w.set_ch(n, true)); } /// Disables the channel. pub fn disable(&mut self) { let n = self.ch.number(); - regs().chenclr.write(|w| unsafe { w.bits(1 << n) }); + regs().chenclr().write(|w| w.set_ch(n, true)); } } @@ -82,9 +82,9 @@ impl<'d, C: Channel, const EVENT_COUNT: usize, const TASK_COUNT: usize> Drop for let r = regs(); let n = self.ch.number(); - r.ch[n].eep.write(|w| unsafe { w.bits(0) }); - r.ch[n].tep.write(|w| unsafe { w.bits(0) }); - #[cfg(not(feature = "nrf51"))] - r.fork[n].tep.write(|w| unsafe { w.bits(0) }); + r.ch(n).eep().write_value(0); + r.ch(n).tep().write_value(0); + #[cfg(not(feature = "_nrf51"))] + r.fork(n).tep().write_value(0); } } diff --git a/embassy-nrf/src/pwm.rs b/embassy-nrf/src/pwm.rs index e0583b770..7f1f568f4 100644 --- a/embassy-nrf/src/pwm.rs +++ b/embassy-nrf/src/pwm.rs @@ -6,8 +6,9 @@ use core::sync::atomic::{compiler_fence, Ordering}; use embassy_hal_internal::{into_ref, PeripheralRef}; -use crate::gpio::sealed::Pin as _; -use crate::gpio::{AnyPin, Pin as GpioPin, PselBits}; +use crate::gpio::{convert_drive, AnyPin, OutputDrive, Pin as GpioPin, PselBits, SealedPin as _, DISCONNECTED}; +use crate::pac::gpio::vals as gpiovals; +use crate::pac::pwm::vals; use crate::ppi::{Event, Task}; use crate::util::slice_in_ram_or; use crate::{interrupt, pac, Peripheral}; @@ -129,48 +130,65 @@ impl<'d, T: Instance> SequencePwm<'d, T> { if let Some(pin) = &ch0 { pin.set_low(); - pin.conf().write(|w| w.dir().output()); + pin.conf().write(|w| { + w.set_dir(gpiovals::Dir::OUTPUT); + w.set_input(gpiovals::Input::DISCONNECT); + w.set_drive(convert_drive(config.ch0_drive)); + }); } if let Some(pin) = &ch1 { pin.set_low(); - pin.conf().write(|w| w.dir().output()); + pin.conf().write(|w| { + w.set_dir(gpiovals::Dir::OUTPUT); + w.set_input(gpiovals::Input::DISCONNECT); + w.set_drive(convert_drive(config.ch1_drive)); + }); } if let Some(pin) = &ch2 { pin.set_low(); - pin.conf().write(|w| w.dir().output()); + pin.conf().write(|w| { + w.set_dir(gpiovals::Dir::OUTPUT); + w.set_input(gpiovals::Input::DISCONNECT); + w.set_drive(convert_drive(config.ch2_drive)); + }); } if let Some(pin) = &ch3 { pin.set_low(); - pin.conf().write(|w| w.dir().output()); + pin.conf().write(|w| { + w.set_dir(gpiovals::Dir::OUTPUT); + w.set_input(gpiovals::Input::DISCONNECT); + w.set_drive(convert_drive(config.ch3_drive)); + }); } - r.psel.out[0].write(|w| unsafe { w.bits(ch0.psel_bits()) }); - r.psel.out[1].write(|w| unsafe { w.bits(ch1.psel_bits()) }); - r.psel.out[2].write(|w| unsafe { w.bits(ch2.psel_bits()) }); - r.psel.out[3].write(|w| unsafe { w.bits(ch3.psel_bits()) }); + r.psel().out(0).write_value(ch0.psel_bits()); + r.psel().out(1).write_value(ch1.psel_bits()); + r.psel().out(2).write_value(ch2.psel_bits()); + r.psel().out(3).write_value(ch3.psel_bits()); // Disable all interrupts - r.intenclr.write(|w| unsafe { w.bits(0xFFFF_FFFF) }); - r.shorts.reset(); - r.events_stopped.reset(); - r.events_loopsdone.reset(); - r.events_seqend[0].reset(); - r.events_seqend[1].reset(); - r.events_pwmperiodend.reset(); - r.events_seqstarted[0].reset(); - r.events_seqstarted[1].reset(); + r.intenclr().write(|w| w.0 = 0xFFFF_FFFF); + r.shorts().write(|_| ()); + r.events_stopped().write_value(0); + r.events_loopsdone().write_value(0); + r.events_seqend(0).write_value(0); + r.events_seqend(1).write_value(0); + r.events_pwmperiodend().write_value(0); + r.events_seqstarted(0).write_value(0); + r.events_seqstarted(1).write_value(0); - r.decoder.write(|w| { - w.load().bits(config.sequence_load as u8); - w.mode().refresh_count() + r.decoder().write(|w| { + w.set_load(vals::Load::from_bits(config.sequence_load as u8)); + w.set_mode(vals::Mode::REFRESH_COUNT); }); - r.mode.write(|w| match config.counter_mode { - CounterMode::UpAndDown => w.updown().up_and_down(), - CounterMode::Up => w.updown().up(), + r.mode().write(|w| match config.counter_mode { + CounterMode::UpAndDown => w.set_updown(vals::Updown::UP_AND_DOWN), + CounterMode::Up => w.set_updown(vals::Updown::UP), }); - r.prescaler.write(|w| w.prescaler().bits(config.prescaler as u8)); - r.countertop.write(|w| unsafe { w.countertop().bits(config.max_duty) }); + r.prescaler() + .write(|w| w.set_prescaler(vals::Prescaler::from_bits(config.prescaler as u8))); + r.countertop().write(|w| w.set_countertop(config.max_duty)); Ok(Self { _peri: _pwm, @@ -186,7 +204,7 @@ impl<'d, T: Instance> SequencePwm<'d, T> { pub fn event_stopped(&self) -> Event<'d> { let r = T::regs(); - Event::from_reg(&r.events_stopped) + Event::from_reg(r.events_stopped()) } /// Returns reference to `LoopsDone` event endpoint for PPI. @@ -194,7 +212,7 @@ impl<'d, T: Instance> SequencePwm<'d, T> { pub fn event_loops_done(&self) -> Event<'d> { let r = T::regs(); - Event::from_reg(&r.events_loopsdone) + Event::from_reg(r.events_loopsdone()) } /// Returns reference to `PwmPeriodEnd` event endpoint for PPI. @@ -202,7 +220,7 @@ impl<'d, T: Instance> SequencePwm<'d, T> { pub fn event_pwm_period_end(&self) -> Event<'d> { let r = T::regs(); - Event::from_reg(&r.events_pwmperiodend) + Event::from_reg(r.events_pwmperiodend()) } /// Returns reference to `Seq0 End` event endpoint for PPI. @@ -210,7 +228,7 @@ impl<'d, T: Instance> SequencePwm<'d, T> { pub fn event_seq_end(&self) -> Event<'d> { let r = T::regs(); - Event::from_reg(&r.events_seqend[0]) + Event::from_reg(r.events_seqend(0)) } /// Returns reference to `Seq1 End` event endpoint for PPI. @@ -218,7 +236,7 @@ impl<'d, T: Instance> SequencePwm<'d, T> { pub fn event_seq1_end(&self) -> Event<'d> { let r = T::regs(); - Event::from_reg(&r.events_seqend[1]) + Event::from_reg(r.events_seqend(1)) } /// Returns reference to `Seq0 Started` event endpoint for PPI. @@ -226,7 +244,7 @@ impl<'d, T: Instance> SequencePwm<'d, T> { pub fn event_seq0_started(&self) -> Event<'d> { let r = T::regs(); - Event::from_reg(&r.events_seqstarted[0]) + Event::from_reg(r.events_seqstarted(0)) } /// Returns reference to `Seq1 Started` event endpoint for PPI. @@ -234,7 +252,7 @@ impl<'d, T: Instance> SequencePwm<'d, T> { pub fn event_seq1_started(&self) -> Event<'d> { let r = T::regs(); - Event::from_reg(&r.events_seqstarted[1]) + Event::from_reg(r.events_seqstarted(1)) } /// Returns reference to `Seq0 Start` task endpoint for PPI. @@ -245,7 +263,7 @@ impl<'d, T: Instance> SequencePwm<'d, T> { pub unsafe fn task_start_seq0(&self) -> Task<'d> { let r = T::regs(); - Task::from_reg(&r.tasks_seqstart[0]) + Task::from_reg(r.tasks_seqstart(0)) } /// Returns reference to `Seq1 Started` task endpoint for PPI. @@ -256,7 +274,7 @@ impl<'d, T: Instance> SequencePwm<'d, T> { pub unsafe fn task_start_seq1(&self) -> Task<'d> { let r = T::regs(); - Task::from_reg(&r.tasks_seqstart[1]) + Task::from_reg(r.tasks_seqstart(1)) } /// Returns reference to `NextStep` task endpoint for PPI. @@ -267,7 +285,7 @@ impl<'d, T: Instance> SequencePwm<'d, T> { pub unsafe fn task_next_step(&self) -> Task<'d> { let r = T::regs(); - Task::from_reg(&r.tasks_nextstep) + Task::from_reg(r.tasks_nextstep()) } /// Returns reference to `Stop` task endpoint for PPI. @@ -278,7 +296,7 @@ impl<'d, T: Instance> SequencePwm<'d, T> { pub unsafe fn task_stop(&self) -> Task<'d> { let r = T::regs(); - Task::from_reg(&r.tasks_stop) + Task::from_reg(r.tasks_stop()) } } @@ -288,23 +306,23 @@ impl<'a, T: Instance> Drop for SequencePwm<'a, T> { if let Some(pin) = &self.ch0 { pin.set_low(); - pin.conf().reset(); - r.psel.out[0].reset(); + pin.conf().write(|_| ()); + r.psel().out(0).write_value(DISCONNECTED); } if let Some(pin) = &self.ch1 { pin.set_low(); - pin.conf().reset(); - r.psel.out[1].reset(); + pin.conf().write(|_| ()); + r.psel().out(1).write_value(DISCONNECTED); } if let Some(pin) = &self.ch2 { pin.set_low(); - pin.conf().reset(); - r.psel.out[2].reset(); + pin.conf().write(|_| ()); + r.psel().out(2).write_value(DISCONNECTED); } if let Some(pin) = &self.ch3 { pin.set_low(); - pin.conf().reset(); - r.psel.out[3].reset(); + pin.conf().write(|_| ()); + r.psel().out(3).write_value(DISCONNECTED); } } } @@ -320,6 +338,14 @@ pub struct Config { pub prescaler: Prescaler, /// How a sequence is read from RAM and is spread to the compare register pub sequence_load: SequenceLoad, + /// Drive strength for the channel 0 line. + pub ch0_drive: OutputDrive, + /// Drive strength for the channel 1 line. + pub ch1_drive: OutputDrive, + /// Drive strength for the channel 2 line. + pub ch2_drive: OutputDrive, + /// Drive strength for the channel 3 line. + pub ch3_drive: OutputDrive, } impl Default for Config { @@ -329,6 +355,10 @@ impl Default for Config { max_duty: 1000, prescaler: Prescaler::Div16, sequence_load: SequenceLoad::Common, + ch0_drive: OutputDrive::Standard, + ch1_drive: OutputDrive::Standard, + ch2_drive: OutputDrive::Standard, + ch3_drive: OutputDrive::Standard, } } } @@ -369,7 +399,7 @@ impl<'s> Sequence<'s> { } /// A single sequence that can be started and stopped. -/// Takes at one sequence along with its configuration. +/// Takes one sequence along with its configuration. #[non_exhaustive] pub struct SingleSequencer<'d, 's, T: Instance> { sequencer: Sequencer<'d, 's, T>, @@ -444,25 +474,21 @@ impl<'d, 's, T: Instance> Sequencer<'d, 's, T> { return Err(Error::SequenceTimesAtLeastOne); } - let _ = self.stop(); + self.stop(); let r = T::regs(); - r.seq0.refresh.write(|w| unsafe { w.bits(sequence0.config.refresh) }); - r.seq0.enddelay.write(|w| unsafe { w.bits(sequence0.config.end_delay) }); - r.seq0.ptr.write(|w| unsafe { w.bits(sequence0.words.as_ptr() as u32) }); - r.seq0.cnt.write(|w| unsafe { w.bits(sequence0.words.len() as u32) }); + r.seq(0).refresh().write(|w| w.0 = sequence0.config.refresh); + r.seq(0).enddelay().write(|w| w.0 = sequence0.config.end_delay); + r.seq(0).ptr().write_value(sequence0.words.as_ptr() as u32); + r.seq(0).cnt().write(|w| w.0 = sequence0.words.len() as u32); - r.seq1.refresh.write(|w| unsafe { w.bits(alt_sequence.config.refresh) }); - r.seq1 - .enddelay - .write(|w| unsafe { w.bits(alt_sequence.config.end_delay) }); - r.seq1 - .ptr - .write(|w| unsafe { w.bits(alt_sequence.words.as_ptr() as u32) }); - r.seq1.cnt.write(|w| unsafe { w.bits(alt_sequence.words.len() as u32) }); + r.seq(1).refresh().write(|w| w.0 = alt_sequence.config.refresh); + r.seq(1).enddelay().write(|w| w.0 = alt_sequence.config.end_delay); + r.seq(1).ptr().write_value(alt_sequence.words.as_ptr() as u32); + r.seq(1).cnt().write(|w| w.0 = alt_sequence.words.len() as u32); - r.enable.write(|w| w.enable().enabled()); + r.enable().write(|w| w.set_enable(true)); // defensive before seqstart compiler_fence(Ordering::SeqCst); @@ -471,18 +497,17 @@ impl<'d, 's, T: Instance> Sequencer<'d, 's, T> { match times { // just the one time, no loop count - SequenceMode::Loop(n) => { - r.loop_.write(|w| unsafe { w.cnt().bits(n) }); + SequenceMode::Loop(_) => { + r.loop_().write(|w| w.set_cnt(vals::LoopCnt::DISABLED)); } // to play infinitely, repeat the sequence one time, then have loops done self trigger seq0 again SequenceMode::Infinite => { - r.loop_.write(|w| unsafe { w.cnt().bits(0x1) }); - r.shorts.write(|w| w.loopsdone_seqstart0().enabled()); + r.loop_().write(|w| w.set_cnt(vals::LoopCnt::from_bits(1))); + r.shorts().write(|w| w.set_loopsdone_seqstart0(true)); } } - // tasks_seqstart() doesn't exist in all svds so write its bit instead - r.tasks_seqstart[seqstart_index].write(|w| unsafe { w.bits(0x01) }); + r.tasks_seqstart(seqstart_index).write_value(1); Ok(()) } @@ -494,20 +519,18 @@ impl<'d, 's, T: Instance> Sequencer<'d, 's, T> { pub fn stop(&self) { let r = T::regs(); - r.shorts.reset(); + r.shorts().write(|_| ()); compiler_fence(Ordering::SeqCst); - // tasks_stop() doesn't exist in all svds so write its bit instead - r.tasks_stop.write(|w| unsafe { w.bits(0x01) }); - - r.enable.write(|w| w.enable().disabled()); + r.tasks_stop().write_value(1); + r.enable().write(|w| w.set_enable(false)); } } impl<'d, 's, T: Instance> Drop for Sequencer<'d, 's, T> { fn drop(&mut self) { - let _ = self.stop(); + self.stop(); } } @@ -657,29 +680,18 @@ impl<'d, T: Instance> SimplePwm<'d, T> { let r = T::regs(); - if let Some(pin) = &ch0 { - pin.set_low(); - pin.conf().write(|w| w.dir().output()); - } - if let Some(pin) = &ch1 { - pin.set_low(); - pin.conf().write(|w| w.dir().output()); - } - if let Some(pin) = &ch2 { - pin.set_low(); - pin.conf().write(|w| w.dir().output()); - } - if let Some(pin) = &ch3 { - pin.set_low(); - pin.conf().write(|w| w.dir().output()); - } + for (i, ch) in [&ch0, &ch1, &ch2, &ch3].into_iter().enumerate() { + if let Some(pin) = ch { + pin.set_low(); - // if NoPin provided writes disconnected (top bit 1) 0x80000000 else - // writes pin number ex 13 (0x0D) which is connected (top bit 0) - r.psel.out[0].write(|w| unsafe { w.bits(ch0.psel_bits()) }); - r.psel.out[1].write(|w| unsafe { w.bits(ch1.psel_bits()) }); - r.psel.out[2].write(|w| unsafe { w.bits(ch2.psel_bits()) }); - r.psel.out[3].write(|w| unsafe { w.bits(ch3.psel_bits()) }); + pin.conf().write(|w| { + w.set_dir(gpiovals::Dir::OUTPUT); + w.set_input(gpiovals::Input::DISCONNECT); + w.set_drive(gpiovals::Drive::S0S1); + }); + } + r.psel().out(i).write_value(ch.psel_bits()); + } let pwm = Self { _peri: _pwm, @@ -691,26 +703,25 @@ impl<'d, T: Instance> SimplePwm<'d, T> { }; // Disable all interrupts - r.intenclr.write(|w| unsafe { w.bits(0xFFFF_FFFF) }); - r.shorts.reset(); + r.intenclr().write(|w| w.0 = 0xFFFF_FFFF); + r.shorts().write(|_| ()); // Enable - r.enable.write(|w| w.enable().enabled()); + r.enable().write(|w| w.set_enable(true)); - r.seq0.ptr.write(|w| unsafe { w.bits((&pwm.duty).as_ptr() as u32) }); + r.seq(0).ptr().write_value((pwm.duty).as_ptr() as u32); + r.seq(0).cnt().write(|w| w.0 = 4); + r.seq(0).refresh().write(|w| w.0 = 0); + r.seq(0).enddelay().write(|w| w.0 = 0); - r.seq0.cnt.write(|w| unsafe { w.bits(4) }); - r.seq0.refresh.write(|w| unsafe { w.bits(0) }); - r.seq0.enddelay.write(|w| unsafe { w.bits(0) }); - - r.decoder.write(|w| { - w.load().individual(); - w.mode().refresh_count() + r.decoder().write(|w| { + w.set_load(vals::Load::INDIVIDUAL); + w.set_mode(vals::Mode::REFRESH_COUNT); }); - r.mode.write(|w| w.updown().up()); - r.prescaler.write(|w| w.prescaler().div_16()); - r.countertop.write(|w| unsafe { w.countertop().bits(1000) }); - r.loop_.write(|w| w.cnt().disabled()); + r.mode().write(|w| w.set_updown(vals::Updown::UP)); + r.prescaler().write(|w| w.set_prescaler(vals::Prescaler::DIV_16)); + r.countertop().write(|w| w.set_countertop(1000)); + r.loop_().write(|w| w.set_cnt(vals::LoopCnt::DISABLED)); pwm } @@ -719,21 +730,21 @@ impl<'d, T: Instance> SimplePwm<'d, T> { #[inline(always)] pub fn is_enabled(&self) -> bool { let r = T::regs(); - r.enable.read().enable().bit_is_set() + r.enable().read().enable() } /// Enables the PWM generator. #[inline(always)] pub fn enable(&self) { let r = T::regs(); - r.enable.write(|w| w.enable().enabled()); + r.enable().write(|w| w.set_enable(true)); } /// Disables the PWM generator. Does NOT clear the last duty cycle from the pin. #[inline(always)] pub fn disable(&self) { let r = T::regs(); - r.enable.write(|w| w.enable().disabled()); + r.enable().write(|w| w.set_enable(false)); } /// Returns the current duty of the channel @@ -748,33 +759,35 @@ impl<'d, T: Instance> SimplePwm<'d, T> { self.duty[channel] = duty & 0x7FFF; // reload ptr in case self was moved - r.seq0.ptr.write(|w| unsafe { w.bits((&self.duty).as_ptr() as u32) }); + r.seq(0).ptr().write_value((self.duty).as_ptr() as u32); // defensive before seqstart compiler_fence(Ordering::SeqCst); - r.events_seqend[0].reset(); + r.events_seqend(0).write_value(0); // tasks_seqstart() doesn't exist in all svds so write its bit instead - r.tasks_seqstart[0].write(|w| unsafe { w.bits(1) }); + r.tasks_seqstart(0).write_value(1); // defensive wait until waveform is loaded after seqstart so set_duty // can't be called again while dma is still reading if self.is_enabled() { - while r.events_seqend[0].read().bits() == 0 {} + while r.events_seqend(0).read() == 0 {} } } /// Sets the PWM clock prescaler. #[inline(always)] pub fn set_prescaler(&self, div: Prescaler) { - T::regs().prescaler.write(|w| w.prescaler().bits(div as u8)); + T::regs() + .prescaler() + .write(|w| w.set_prescaler(vals::Prescaler::from_bits(div as u8))); } /// Gets the PWM clock prescaler. #[inline(always)] pub fn prescaler(&self) -> Prescaler { - match T::regs().prescaler.read().prescaler().bits() { + match T::regs().prescaler().read().prescaler().to_bits() { 0 => Prescaler::Div1, 1 => Prescaler::Div2, 2 => Prescaler::Div4, @@ -790,15 +803,13 @@ impl<'d, T: Instance> SimplePwm<'d, T> { /// Sets the maximum duty cycle value. #[inline(always)] pub fn set_max_duty(&self, duty: u16) { - T::regs() - .countertop - .write(|w| unsafe { w.countertop().bits(duty.min(32767u16)) }); + T::regs().countertop().write(|w| w.set_countertop(duty.min(32767u16))); } /// Returns the maximum duty cycle value. #[inline(always)] pub fn max_duty(&self) -> u16 { - T::regs().countertop.read().countertop().bits() + T::regs().countertop().read().countertop() } /// Sets the PWM output frequency. @@ -816,6 +827,38 @@ impl<'d, T: Instance> SimplePwm<'d, T> { let max_duty = self.max_duty() as u32; clk / max_duty } + + /// Sets the PWM-Channel0 output drive strength + #[inline(always)] + pub fn set_ch0_drive(&self, drive: OutputDrive) { + if let Some(pin) = &self.ch0 { + pin.conf().modify(|w| w.set_drive(convert_drive(drive))); + } + } + + /// Sets the PWM-Channel1 output drive strength + #[inline(always)] + pub fn set_ch1_drive(&self, drive: OutputDrive) { + if let Some(pin) = &self.ch1 { + pin.conf().modify(|w| w.set_drive(convert_drive(drive))); + } + } + + /// Sets the PWM-Channel2 output drive strength + #[inline(always)] + pub fn set_ch2_drive(&self, drive: OutputDrive) { + if let Some(pin) = &self.ch2 { + pin.conf().modify(|w| w.set_drive(convert_drive(drive))); + } + } + + /// Sets the PWM-Channel3 output drive strength + #[inline(always)] + pub fn set_ch3_drive(&self, drive: OutputDrive) { + if let Some(pin) = &self.ch3 { + pin.conf().modify(|w| w.set_drive(convert_drive(drive))); + } + } } impl<'a, T: Instance> Drop for SimplePwm<'a, T> { @@ -826,46 +869,43 @@ impl<'a, T: Instance> Drop for SimplePwm<'a, T> { if let Some(pin) = &self.ch0 { pin.set_low(); - pin.conf().reset(); - r.psel.out[0].reset(); + pin.conf().write(|_| ()); + r.psel().out(0).write_value(DISCONNECTED); } if let Some(pin) = &self.ch1 { pin.set_low(); - pin.conf().reset(); - r.psel.out[1].reset(); + pin.conf().write(|_| ()); + r.psel().out(1).write_value(DISCONNECTED); } if let Some(pin) = &self.ch2 { pin.set_low(); - pin.conf().reset(); - r.psel.out[2].reset(); + pin.conf().write(|_| ()); + r.psel().out(2).write_value(DISCONNECTED); } if let Some(pin) = &self.ch3 { pin.set_low(); - pin.conf().reset(); - r.psel.out[3].reset(); + pin.conf().write(|_| ()); + r.psel().out(3).write_value(DISCONNECTED); } } } -pub(crate) mod sealed { - use super::*; - - pub trait Instance { - fn regs() -> &'static pac::pwm0::RegisterBlock; - } +pub(crate) trait SealedInstance { + fn regs() -> pac::pwm::Pwm; } /// PWM peripheral instance. -pub trait Instance: Peripheral

+ sealed::Instance + 'static { +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static { /// Interrupt for this peripheral. type Interrupt: interrupt::typelevel::Interrupt; } macro_rules! impl_pwm { ($type:ident, $pac_type:ident, $irq:ident) => { - impl crate::pwm::sealed::Instance for peripherals::$type { - fn regs() -> &'static pac::pwm0::RegisterBlock { - unsafe { &*pac::$pac_type::ptr() } + impl crate::pwm::SealedInstance for peripherals::$type { + fn regs() -> pac::pwm::Pwm { + pac::$pac_type } } impl crate::pwm::Instance for peripherals::$type { diff --git a/embassy-nrf/src/qdec.rs b/embassy-nrf/src/qdec.rs index 2aa50a2ba..efd2a134c 100644 --- a/embassy-nrf/src/qdec.rs +++ b/embassy-nrf/src/qdec.rs @@ -7,11 +7,13 @@ use core::marker::PhantomData; use core::task::Poll; use embassy_hal_internal::{into_ref, PeripheralRef}; +use embassy_sync::waitqueue::AtomicWaker; -use crate::gpio::sealed::Pin as _; -use crate::gpio::{AnyPin, Pin as GpioPin}; +use crate::gpio::{AnyPin, Pin as GpioPin, SealedPin as _}; use crate::interrupt::typelevel::Interrupt; -use crate::{interrupt, Peripheral}; +use crate::pac::gpio::vals as gpiovals; +use crate::pac::qdec::vals; +use crate::{interrupt, pac, Peripheral}; /// Quadrature decoder driver. pub struct Qdec<'d, T: Instance> { @@ -52,7 +54,7 @@ pub struct InterruptHandler { impl interrupt::typelevel::Handler for InterruptHandler { unsafe fn on_interrupt() { - T::regs().intenclr.write(|w| w.reportrdy().clear()); + T::regs().intenclr().write(|w| w.set_reportrdy(true)); T::state().waker.wake(); } } @@ -93,54 +95,59 @@ impl<'d, T: Instance> Qdec<'d, T> { let r = T::regs(); // Select pins. - a.conf().write(|w| w.input().connect().pull().pullup()); - b.conf().write(|w| w.input().connect().pull().pullup()); - r.psel.a.write(|w| unsafe { w.bits(a.psel_bits()) }); - r.psel.b.write(|w| unsafe { w.bits(b.psel_bits()) }); + a.conf().write(|w| { + w.set_input(gpiovals::Input::CONNECT); + w.set_pull(gpiovals::Pull::PULLUP); + }); + b.conf().write(|w| { + w.set_input(gpiovals::Input::CONNECT); + w.set_pull(gpiovals::Pull::PULLUP); + }); + r.psel().a().write_value(a.psel_bits()); + r.psel().b().write_value(b.psel_bits()); if let Some(led_pin) = &led { - led_pin.conf().write(|w| w.dir().output()); - r.psel.led.write(|w| unsafe { w.bits(led_pin.psel_bits()) }); + led_pin.conf().write(|w| w.set_dir(gpiovals::Dir::OUTPUT)); + r.psel().led().write_value(led_pin.psel_bits()); } // Enables/disable input debounce filters - r.dbfen.write(|w| match config.debounce { - true => w.dbfen().enabled(), - false => w.dbfen().disabled(), + r.dbfen().write(|w| match config.debounce { + true => w.set_dbfen(true), + false => w.set_dbfen(false), }); // Set LED output pin polarity - r.ledpol.write(|w| match config.led_polarity { - LedPolarity::ActiveHigh => w.ledpol().active_high(), - LedPolarity::ActiveLow => w.ledpol().active_low(), + r.ledpol().write(|w| match config.led_polarity { + LedPolarity::ActiveHigh => w.set_ledpol(vals::Ledpol::ACTIVE_HIGH), + LedPolarity::ActiveLow => w.set_ledpol(vals::Ledpol::ACTIVE_LOW), }); // Set time period the LED is switched ON prior to sampling (0..511 us). - r.ledpre - .write(|w| unsafe { w.ledpre().bits(config.led_pre_usecs.min(511)) }); + r.ledpre().write(|w| w.set_ledpre(config.led_pre_usecs.min(511))); // Set sample period - r.sampleper.write(|w| match config.period { - SamplePeriod::_128us => w.sampleper()._128us(), - SamplePeriod::_256us => w.sampleper()._256us(), - SamplePeriod::_512us => w.sampleper()._512us(), - SamplePeriod::_1024us => w.sampleper()._1024us(), - SamplePeriod::_2048us => w.sampleper()._2048us(), - SamplePeriod::_4096us => w.sampleper()._4096us(), - SamplePeriod::_8192us => w.sampleper()._8192us(), - SamplePeriod::_16384us => w.sampleper()._16384us(), - SamplePeriod::_32ms => w.sampleper()._32ms(), - SamplePeriod::_65ms => w.sampleper()._65ms(), - SamplePeriod::_131ms => w.sampleper()._131ms(), + r.sampleper().write(|w| match config.period { + SamplePeriod::_128us => w.set_sampleper(vals::Sampleper::_128US), + SamplePeriod::_256us => w.set_sampleper(vals::Sampleper::_256US), + SamplePeriod::_512us => w.set_sampleper(vals::Sampleper::_512US), + SamplePeriod::_1024us => w.set_sampleper(vals::Sampleper::_1024US), + SamplePeriod::_2048us => w.set_sampleper(vals::Sampleper::_2048US), + SamplePeriod::_4096us => w.set_sampleper(vals::Sampleper::_4096US), + SamplePeriod::_8192us => w.set_sampleper(vals::Sampleper::_8192US), + SamplePeriod::_16384us => w.set_sampleper(vals::Sampleper::_16384US), + SamplePeriod::_32ms => w.set_sampleper(vals::Sampleper::_32MS), + SamplePeriod::_65ms => w.set_sampleper(vals::Sampleper::_65MS), + SamplePeriod::_131ms => w.set_sampleper(vals::Sampleper::_131MS), }); T::Interrupt::unpend(); unsafe { T::Interrupt::enable() }; // Enable peripheral - r.enable.write(|w| w.enable().set_bit()); + r.enable().write(|w| w.set_enable(true)); // Start sampling - unsafe { r.tasks_start.write(|w| w.bits(1)) }; + r.tasks_start().write_value(1); Self { _p: p } } @@ -169,21 +176,20 @@ impl<'d, T: Instance> Qdec<'d, T> { /// ``` pub async fn read(&mut self) -> i16 { let t = T::regs(); - t.intenset.write(|w| w.reportrdy().set()); - unsafe { t.tasks_readclracc.write(|w| w.bits(1)) }; + t.intenset().write(|w| w.set_reportrdy(true)); + t.tasks_readclracc().write_value(1); - let value = poll_fn(|cx| { + poll_fn(|cx| { T::state().waker.register(cx.waker()); - if t.events_reportrdy.read().bits() == 0 { - return Poll::Pending; + if t.events_reportrdy().read() == 0 { + Poll::Pending } else { - t.events_reportrdy.reset(); - let acc = t.accread.read().bits(); + t.events_reportrdy().write_value(0); + let acc = t.accread().read(); Poll::Ready(acc as i16) } }) - .await; - value + .await } } @@ -246,42 +252,39 @@ pub enum LedPolarity { ActiveLow, } -pub(crate) mod sealed { - use embassy_sync::waitqueue::AtomicWaker; +/// Peripheral static state +pub(crate) struct State { + waker: AtomicWaker, +} - /// Peripheral static state - pub struct State { - pub waker: AtomicWaker, - } - - impl State { - pub const fn new() -> Self { - Self { - waker: AtomicWaker::new(), - } +impl State { + pub(crate) const fn new() -> Self { + Self { + waker: AtomicWaker::new(), } } - - pub trait Instance { - fn regs() -> &'static crate::pac::qdec::RegisterBlock; - fn state() -> &'static State; - } +} + +pub(crate) trait SealedInstance { + fn regs() -> pac::qdec::Qdec; + fn state() -> &'static State; } /// qdec peripheral instance. -pub trait Instance: Peripheral

+ sealed::Instance + 'static + Send { +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static + Send { /// Interrupt for this peripheral. type Interrupt: interrupt::typelevel::Interrupt; } macro_rules! impl_qdec { ($type:ident, $pac_type:ident, $irq:ident) => { - impl crate::qdec::sealed::Instance for peripherals::$type { - fn regs() -> &'static crate::pac::qdec::RegisterBlock { - unsafe { &*pac::$pac_type::ptr() } + impl crate::qdec::SealedInstance for peripherals::$type { + fn regs() -> pac::qdec::Qdec { + pac::$pac_type } - fn state() -> &'static crate::qdec::sealed::State { - static STATE: crate::qdec::sealed::State = crate::qdec::sealed::State::new(); + fn state() -> &'static crate::qdec::State { + static STATE: crate::qdec::State = crate::qdec::State::new(); &STATE } } diff --git a/embassy-nrf/src/qspi.rs b/embassy-nrf/src/qspi.rs index 8eec09c96..de9c268c1 100755 --- a/embassy-nrf/src/qspi.rs +++ b/embassy-nrf/src/qspi.rs @@ -9,15 +9,17 @@ use core::task::Poll; use embassy_hal_internal::drop::OnDrop; use embassy_hal_internal::{into_ref, PeripheralRef}; +use embassy_sync::waitqueue::AtomicWaker; use embedded_storage::nor_flash::{ErrorType, NorFlash, NorFlashError, NorFlashErrorKind, ReadNorFlash}; use crate::gpio::{self, Pin as GpioPin}; use crate::interrupt::typelevel::Interrupt; -pub use crate::pac::qspi::ifconfig0::{ - ADDRMODE_A as AddressMode, PPSIZE_A as WritePageSize, READOC_A as ReadOpcode, WRITEOC_A as WriteOpcode, +use crate::pac::gpio::vals as gpiovals; +use crate::pac::qspi::vals; +pub use crate::pac::qspi::vals::{ + Addrmode as AddressMode, Ppsize as WritePageSize, Readoc as ReadOpcode, Spimode as SpiMode, Writeoc as WriteOpcode, }; -pub use crate::pac::qspi::ifconfig1::SPIMODE_A as SpiMode; -use crate::{interrupt, Peripheral}; +use crate::{interrupt, pac, Peripheral}; /// Deep power-down config. pub struct DeepPowerDownConfig { @@ -128,9 +130,9 @@ impl interrupt::typelevel::Handler for InterruptHandl let r = T::regs(); let s = T::state(); - if r.events_ready.read().bits() != 0 { + if r.events_ready().read() != 0 { s.waker.wake(); - r.intenclr.write(|w| w.ready().clear()); + r.intenclr().write(|w| w.set_ready(true)); } } } @@ -163,13 +165,12 @@ impl<'d, T: Instance> Qspi<'d, T> { ($pin:ident) => { $pin.set_high(); $pin.conf().write(|w| { - w.dir().output(); - w.drive().h0h1(); - #[cfg(feature = "_nrf5340-s")] - w.mcusel().peripheral(); - w + w.set_dir(gpiovals::Dir::OUTPUT); + w.set_drive(gpiovals::Drive::H0H1); + #[cfg(all(feature = "_nrf5340", feature = "_s"))] + w.set_mcusel(gpiovals::Mcusel::PERIPHERAL); }); - r.psel.$pin.write(|w| unsafe { w.bits($pin.psel_bits()) }); + r.psel().$pin().write_value($pin.psel_bits()); }; } @@ -180,46 +181,39 @@ impl<'d, T: Instance> Qspi<'d, T> { config_pin!(io2); config_pin!(io3); - r.ifconfig0.write(|w| { - w.addrmode().variant(config.address_mode); - w.dpmenable().bit(config.deep_power_down.is_some()); - w.ppsize().variant(config.write_page_size); - w.readoc().variant(config.read_opcode); - w.writeoc().variant(config.write_opcode); - w + r.ifconfig0().write(|w| { + w.set_addrmode(config.address_mode); + w.set_dpmenable(config.deep_power_down.is_some()); + w.set_ppsize(config.write_page_size); + w.set_readoc(config.read_opcode); + w.set_writeoc(config.write_opcode); }); if let Some(dpd) = &config.deep_power_down { - r.dpmdur.write(|w| unsafe { - w.enter().bits(dpd.enter_time); - w.exit().bits(dpd.exit_time); - w + r.dpmdur().write(|w| { + w.set_enter(dpd.enter_time); + w.set_exit(dpd.exit_time); }) } - r.ifconfig1.write(|w| unsafe { - w.sckdelay().bits(config.sck_delay); - w.dpmen().exit(); - w.spimode().variant(config.spi_mode); - w.sckfreq().bits(config.frequency as u8); - w + r.ifconfig1().write(|w| { + w.set_sckdelay(config.sck_delay); + w.set_dpmen(false); + w.set_spimode(config.spi_mode); + w.set_sckfreq(config.frequency as u8); }); - r.iftiming.write(|w| unsafe { - w.rxdelay().bits(config.rx_delay & 0b111); - w + r.iftiming().write(|w| { + w.set_rxdelay(config.rx_delay & 0b111); }); - r.xipoffset.write(|w| unsafe { - w.xipoffset().bits(config.xip_offset); - w - }); + r.xipoffset().write_value(config.xip_offset); T::Interrupt::unpend(); unsafe { T::Interrupt::enable() }; // Enable it - r.enable.write(|w| w.enable().enabled()); + r.enable().write(|w| w.set_enable(true)); let res = Self { _peri: qspi, @@ -227,10 +221,10 @@ impl<'d, T: Instance> Qspi<'d, T> { capacity: config.capacity, }; - r.events_ready.reset(); - r.intenset.write(|w| w.ready().set()); + r.events_ready().write_value(0); + r.intenset().write(|w| w.set_ready(true)); - r.tasks_activate.write(|w| w.tasks_activate().bit(true)); + r.tasks_activate().write_value(1); Self::blocking_wait_ready(); @@ -283,22 +277,21 @@ impl<'d, T: Instance> Qspi<'d, T> { } let r = T::regs(); - r.cinstrdat0.write(|w| unsafe { w.bits(dat0) }); - r.cinstrdat1.write(|w| unsafe { w.bits(dat1) }); + r.cinstrdat0().write(|w| w.0 = dat0); + r.cinstrdat1().write(|w| w.0 = dat1); - r.events_ready.reset(); - r.intenset.write(|w| w.ready().set()); + r.events_ready().write_value(0); + r.intenset().write(|w| w.set_ready(true)); - r.cinstrconf.write(|w| { - let w = unsafe { w.opcode().bits(opcode) }; - let w = unsafe { w.length().bits(len + 1) }; - let w = w.lio2().bit(true); - let w = w.lio3().bit(true); - let w = w.wipwait().bit(true); - let w = w.wren().bit(true); - let w = w.lfen().bit(false); - let w = w.lfstop().bit(false); - w + r.cinstrconf().write(|w| { + w.set_opcode(opcode); + w.set_length(vals::Length::from_bits(len + 1)); + w.set_lio2(true); + w.set_lio3(true); + w.set_wipwait(true); + w.set_wren(true); + w.set_lfen(false); + w.set_lfstop(false); }); Ok(()) } @@ -306,8 +299,8 @@ impl<'d, T: Instance> Qspi<'d, T> { fn custom_instruction_finish(&mut self, resp: &mut [u8]) -> Result<(), Error> { let r = T::regs(); - let dat0 = r.cinstrdat0.read().bits(); - let dat1 = r.cinstrdat1.read().bits(); + let dat0 = r.cinstrdat0().read().0; + let dat1 = r.cinstrdat1().read().0; for i in 0..4 { if i < resp.len() { resp[i] = (dat0 >> (i * 8)) as u8; @@ -326,7 +319,7 @@ impl<'d, T: Instance> Qspi<'d, T> { let r = T::regs(); let s = T::state(); s.waker.register(cx.waker()); - if r.events_ready.read().bits() != 0 { + if r.events_ready().read() != 0 { return Poll::Ready(()); } Poll::Pending @@ -337,7 +330,7 @@ impl<'d, T: Instance> Qspi<'d, T> { fn blocking_wait_ready() { loop { let r = T::regs(); - if r.events_ready.read().bits() != 0 { + if r.events_ready().read() != 0 { break; } } @@ -351,13 +344,13 @@ impl<'d, T: Instance> Qspi<'d, T> { let r = T::regs(); - r.read.src.write(|w| unsafe { w.src().bits(address) }); - r.read.dst.write(|w| unsafe { w.dst().bits(data.as_ptr() as u32) }); - r.read.cnt.write(|w| unsafe { w.cnt().bits(data.len() as u32) }); + r.read().src().write_value(address); + r.read().dst().write_value(data.as_ptr() as u32); + r.read().cnt().write(|w| w.set_cnt(data.len() as u32)); - r.events_ready.reset(); - r.intenset.write(|w| w.ready().set()); - r.tasks_readstart.write(|w| w.tasks_readstart().bit(true)); + r.events_ready().write_value(0); + r.intenset().write(|w| w.set_ready(true)); + r.tasks_readstart().write_value(1); Ok(()) } @@ -369,13 +362,13 @@ impl<'d, T: Instance> Qspi<'d, T> { assert_eq!(address % 4, 0); let r = T::regs(); - r.write.src.write(|w| unsafe { w.src().bits(data.as_ptr() as u32) }); - r.write.dst.write(|w| unsafe { w.dst().bits(address) }); - r.write.cnt.write(|w| unsafe { w.cnt().bits(data.len() as u32) }); + r.write().src().write_value(data.as_ptr() as u32); + r.write().dst().write_value(address); + r.write().cnt().write(|w| w.set_cnt(data.len() as u32)); - r.events_ready.reset(); - r.intenset.write(|w| w.ready().set()); - r.tasks_writestart.write(|w| w.tasks_writestart().bit(true)); + r.events_ready().write_value(0); + r.intenset().write(|w| w.set_ready(true)); + r.tasks_writestart().write_value(1); Ok(()) } @@ -385,12 +378,12 @@ impl<'d, T: Instance> Qspi<'d, T> { assert_eq!(address % 4096, 0); let r = T::regs(); - r.erase.ptr.write(|w| unsafe { w.ptr().bits(address) }); - r.erase.len.write(|w| w.len()._4kb()); + r.erase().ptr().write_value(address); + r.erase().len().write(|w| w.set_len(vals::Len::_4KB)); - r.events_ready.reset(); - r.intenset.write(|w| w.ready().set()); - r.tasks_erasestart.write(|w| w.tasks_erasestart().bit(true)); + r.events_ready().write_value(0); + r.intenset().write(|w| w.set_ready(true)); + r.tasks_erasestart().write_value(1); Ok(()) } @@ -402,7 +395,7 @@ impl<'d, T: Instance> Qspi<'d, T> { /// a raw bus, not with flash memory. pub async fn read_raw(&mut self, address: u32, data: &mut [u8]) -> Result<(), Error> { // Avoid blocking_wait_ready() blocking forever on zero-length buffers. - if data.len() == 0 { + if data.is_empty() { return Ok(()); } @@ -423,7 +416,7 @@ impl<'d, T: Instance> Qspi<'d, T> { /// a raw bus, not with flash memory. pub async fn write_raw(&mut self, address: u32, data: &[u8]) -> Result<(), Error> { // Avoid blocking_wait_ready() blocking forever on zero-length buffers. - if data.len() == 0 { + if data.is_empty() { return Ok(()); } @@ -444,7 +437,7 @@ impl<'d, T: Instance> Qspi<'d, T> { /// a raw bus, not with flash memory. pub fn blocking_read_raw(&mut self, address: u32, data: &mut [u8]) -> Result<(), Error> { // Avoid blocking_wait_ready() blocking forever on zero-length buffers. - if data.len() == 0 { + if data.is_empty() { return Ok(()); } @@ -460,7 +453,7 @@ impl<'d, T: Instance> Qspi<'d, T> { /// a raw bus, not with flash memory. pub fn blocking_write_raw(&mut self, address: u32, data: &[u8]) -> Result<(), Error> { // Avoid blocking_wait_ready() blocking forever on zero-length buffers. - if data.len() == 0 { + if data.is_empty() { return Ok(()); } @@ -537,12 +530,12 @@ impl<'d, T: Instance> Drop for Qspi<'d, T> { if self.dpm_enabled { trace!("qspi: doing deep powerdown..."); - r.ifconfig1.modify(|_, w| w.dpmen().enter()); + r.ifconfig1().modify(|w| w.set_dpmen(true)); // Wait for DPM enter. // Unfortunately we must spin. There's no way to do this interrupt-driven. // The READY event does NOT fire on DPM enter (but it does fire on DPM exit :shrug:) - while r.status.read().dpm().is_disabled() {} + while !r.status().read().dpm() {} // Wait MORE for DPM enter. // I have absolutely no idea why, but the wait above is not enough :'( @@ -551,23 +544,23 @@ impl<'d, T: Instance> Drop for Qspi<'d, T> { } // it seems events_ready is not generated in response to deactivate. nrfx doesn't wait for it. - r.tasks_deactivate.write(|w| w.tasks_deactivate().set_bit()); + r.tasks_deactivate().write_value(1); // Workaround https://infocenter.nordicsemi.com/topic/errata_nRF52840_Rev1/ERR/nRF52840/Rev1/latest/anomaly_840_122.html?cp=4_0_1_2_1_7 // Note that the doc has 2 register writes, but the first one is really the write to tasks_deactivate, // so we only do the second one here. unsafe { ptr::write_volatile(0x40029054 as *mut u32, 1) } - r.enable.write(|w| w.enable().disabled()); + r.enable().write(|w| w.set_enable(false)); // Note: we do NOT deconfigure CSN here. If DPM is in use and we disconnect CSN, // leaving it floating, the flash chip might read it as zero which would cause it to // spuriously exit DPM. - gpio::deconfigure_pin(r.psel.sck.read().bits()); - gpio::deconfigure_pin(r.psel.io0.read().bits()); - gpio::deconfigure_pin(r.psel.io1.read().bits()); - gpio::deconfigure_pin(r.psel.io2.read().bits()); - gpio::deconfigure_pin(r.psel.io3.read().bits()); + gpio::deconfigure_pin(r.psel().sck().read()); + gpio::deconfigure_pin(r.psel().io0().read()); + gpio::deconfigure_pin(r.psel().io1().read()); + gpio::deconfigure_pin(r.psel().io2().read()); + gpio::deconfigure_pin(r.psel().io3().read()); trace!("qspi: dropped"); } @@ -652,42 +645,39 @@ mod _eh1 { impl<'d, T: Instance> embedded_storage_async::nor_flash::MultiwriteNorFlash for Qspi<'d, T> {} } -pub(crate) mod sealed { - use embassy_sync::waitqueue::AtomicWaker; +/// Peripheral static state +pub(crate) struct State { + waker: AtomicWaker, +} - /// Peripheral static state - pub struct State { - pub waker: AtomicWaker, - } - - impl State { - pub const fn new() -> Self { - Self { - waker: AtomicWaker::new(), - } +impl State { + pub(crate) const fn new() -> Self { + Self { + waker: AtomicWaker::new(), } } - - pub trait Instance { - fn regs() -> &'static crate::pac::qspi::RegisterBlock; - fn state() -> &'static State; - } +} + +pub(crate) trait SealedInstance { + fn regs() -> pac::qspi::Qspi; + fn state() -> &'static State; } /// QSPI peripheral instance. -pub trait Instance: Peripheral

+ sealed::Instance + 'static + Send { +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static + Send { /// Interrupt for this peripheral. type Interrupt: interrupt::typelevel::Interrupt; } macro_rules! impl_qspi { ($type:ident, $pac_type:ident, $irq:ident) => { - impl crate::qspi::sealed::Instance for peripherals::$type { - fn regs() -> &'static crate::pac::qspi::RegisterBlock { - unsafe { &*pac::$pac_type::ptr() } + impl crate::qspi::SealedInstance for peripherals::$type { + fn regs() -> pac::qspi::Qspi { + pac::$pac_type } - fn state() -> &'static crate::qspi::sealed::State { - static STATE: crate::qspi::sealed::State = crate::qspi::sealed::State::new(); + fn state() -> &'static crate::qspi::State { + static STATE: crate::qspi::State = crate::qspi::State::new(); &STATE } } diff --git a/embassy-nrf/src/radio/ble.rs b/embassy-nrf/src/radio/ble.rs new file mode 100644 index 000000000..682ca1c79 --- /dev/null +++ b/embassy-nrf/src/radio/ble.rs @@ -0,0 +1,396 @@ +//! Radio driver implementation focused on Bluetooth Low-Energy transmission. + +use core::future::poll_fn; +use core::sync::atomic::{compiler_fence, Ordering}; +use core::task::Poll; + +use embassy_hal_internal::drop::OnDrop; +use embassy_hal_internal::{into_ref, PeripheralRef}; +pub use pac::radio::vals::Mode; +#[cfg(not(feature = "_nrf51"))] +use pac::radio::vals::Plen as PreambleLength; + +use crate::interrupt::typelevel::Interrupt; +use crate::pac::radio::vals; +use crate::radio::*; +pub use crate::radio::{Error, TxPower}; +use crate::util::slice_in_ram_or; + +/// Radio driver. +pub struct Radio<'d, T: Instance> { + _p: PeripheralRef<'d, T>, +} + +impl<'d, T: Instance> Radio<'d, T> { + /// Create a new radio driver. + pub fn new( + radio: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + ) -> Self { + into_ref!(radio); + + let r = T::regs(); + + r.pcnf1().write(|w| { + // It is 0 bytes long in a standard BLE packet + w.set_statlen(0); + // MaxLen configures the maximum packet payload plus add-on size in + // number of bytes that can be transmitted or received by the RADIO. This feature can be used to ensure + // that the RADIO does not overwrite, or read beyond, the RAM assigned to the packet payload. This means + // that if the packet payload length defined by PCNF1.STATLEN and the LENGTH field in the packet specifies a + // packet larger than MAXLEN, the payload will be truncated at MAXLEN + // + // To simplify the implementation, It is setted as the maximum value + // and the length of the packet is controlled only by the LENGTH field in the packet + w.set_maxlen(255); + // Configure the length of the address field in the packet + // The prefix after the address fields is always appended, so is always 1 byte less than the size of the address + // The base address is truncated from the least significant byte if the BALEN is less than 4 + // + // BLE address is always 4 bytes long + w.set_balen(3); // 3 bytes base address (+ 1 prefix); + // Configure the endianess + // For BLE is always little endian (LSB first) + w.set_endian(vals::Endian::LITTLE); + // Data whitening is used to avoid long sequences of zeros or + // ones, e.g., 0b0000000 or 0b1111111, in the data bit stream. + // The whitener and de-whitener are defined the same way, + // using a 7-bit linear feedback shift register with the + // polynomial x7 + x4 + 1. + // + // In BLE Whitening shall be applied on the PDU and CRC of all + // Link Layer packets and is performed after the CRC generation + // in the transmitter. No other parts of the packets are whitened. + // De-whitening is performed before the CRC checking in the receiver + // Before whitening or de-whitening, the shift register should be + // initialized based on the channel index. + w.set_whiteen(true); + }); + + // Configure CRC + r.crccnf().write(|w| { + // In BLE the CRC shall be calculated on the PDU of all Link Layer + // packets (even if the packet is encrypted). + // It skips the address field + w.set_skipaddr(vals::Skipaddr::SKIP); + // In BLE 24-bit CRC = 3 bytes + w.set_len(vals::Len::THREE); + }); + + // Ch map between 2400 MHZ .. 2500 MHz + // All modes use this range + #[cfg(not(feature = "_nrf51"))] + r.frequency().write(|w| w.set_map(vals::Map::DEFAULT)); + + // Configure shortcuts to simplify and speed up sending and receiving packets. + r.shorts().write(|w| { + // start transmission/recv immediately after ramp-up + // disable radio when transmission/recv is done + w.set_ready_start(true); + w.set_end_disable(true); + }); + + // Enable NVIC interrupt + T::Interrupt::unpend(); + unsafe { T::Interrupt::enable() }; + + Self { _p: radio } + } + + fn state(&self) -> RadioState { + super::state(T::regs()) + } + + /// Set the radio mode + /// + /// The radio must be disabled before calling this function + pub fn set_mode(&mut self, mode: Mode) { + assert!(self.state() == RadioState::DISABLED); + + let r = T::regs(); + r.mode().write(|w| w.set_mode(mode)); + + #[cfg(not(feature = "_nrf51"))] + r.pcnf0().write(|w| { + w.set_plen(match mode { + Mode::BLE_1MBIT => PreambleLength::_8BIT, + Mode::BLE_2MBIT => PreambleLength::_16BIT, + #[cfg(any( + feature = "nrf52811", + feature = "nrf52820", + feature = "nrf52833", + feature = "nrf52840", + feature = "_nrf5340-net" + ))] + Mode::BLE_LR125KBIT | Mode::BLE_LR500KBIT => PreambleLength::LONG_RANGE, + _ => unimplemented!(), + }) + }); + } + + /// Set the header size changing the S1's len field + /// + /// The radio must be disabled before calling this function + pub fn set_header_expansion(&mut self, use_s1_field: bool) { + assert!(self.state() == RadioState::DISABLED); + + let r = T::regs(); + + // s1 len in bits + let s1len: u8 = match use_s1_field { + false => 0, + true => 8, + }; + + r.pcnf0().write(|w| { + // Configure S0 to 1 byte length, this will represent the Data/Adv header flags + w.set_s0len(true); + // Configure the length (in bits) field to 1 byte length, this will represent the length of the payload + // and also be used to know how many bytes to read/write from/to the buffer + w.set_lflen(0); + // Configure the lengh (in bits) of bits in the S1 field. It could be used to represent the CTEInfo for data packages in BLE. + w.set_s1len(s1len); + }); + } + + /// Set initial data whitening value + /// Data whitening is used to avoid long sequences of zeros or ones, e.g., 0b0000000 or 0b1111111, in the data bit stream + /// On BLE the initial value is the channel index | 0x40 + /// + /// The radio must be disabled before calling this function + pub fn set_whitening_init(&mut self, whitening_init: u8) { + assert!(self.state() == RadioState::DISABLED); + + let r = T::regs(); + + r.datawhiteiv().write(|w| w.set_datawhiteiv(whitening_init)); + } + + /// Set the central frequency to be used + /// It should be in the range 2400..2500 + /// + /// [The radio must be disabled before calling this function](https://devzone.nordicsemi.com/f/nordic-q-a/15829/radio-frequency-change) + pub fn set_frequency(&mut self, frequency: u32) { + assert!(self.state() == RadioState::DISABLED); + assert!((2400..=2500).contains(&frequency)); + + let r = T::regs(); + + r.frequency().write(|w| w.set_frequency((frequency - 2400) as u8)); + } + + /// Set the acess address + /// This address is always constants for advertising + /// And a random value generate on each connection + /// It is used to filter the packages + /// + /// The radio must be disabled before calling this function + pub fn set_access_address(&mut self, access_address: u32) { + assert!(self.state() == RadioState::DISABLED); + + let r = T::regs(); + + // Configure logical address + // The byte ordering on air is always least significant byte first for the address + // So for the address 0xAA_BB_CC_DD, the address on air will be DD CC BB AA + // The package order is BASE, PREFIX so BASE=0xBB_CC_DD and PREFIX=0xAA + r.prefix0().write(|w| w.set_ap0((access_address >> 24) as u8)); + + // The base address is truncated from the least significant byte (because the BALEN is less than 4) + // So it shifts the address to the right + r.base0().write_value(access_address << 8); + + // Don't match tx address + r.txaddress().write(|w| w.set_txaddress(0)); + + // Match on logical address + // This config only filter the packets by the address, + // so only packages send to the previous address + // will finish the reception (TODO: check the explanation) + r.rxaddresses().write(|w| { + w.set_addr0(true); + w.set_addr1(true); + w.set_addr2(true); + w.set_addr3(true); + w.set_addr4(true); + }); + } + + /// Set the CRC polynomial + /// It only uses the 24 least significant bits + /// + /// The radio must be disabled before calling this function + pub fn set_crc_poly(&mut self, crc_poly: u32) { + assert!(self.state() == RadioState::DISABLED); + + let r = T::regs(); + + r.crcpoly().write(|w| { + // Configure the CRC polynomial + // Each term in the CRC polynomial is mapped to a bit in this + // register which index corresponds to the term's exponent. + // The least significant term/bit is hard-wired internally to + // 1, and bit number 0 of the register content is ignored by + // the hardware. The following example is for an 8 bit CRC + // polynomial: x8 + x7 + x3 + x2 + 1 = 1 1000 1101 . + w.set_crcpoly(crc_poly & 0xFFFFFF) + }); + } + + /// Set the CRC init value + /// It only uses the 24 least significant bits + /// The CRC initial value varies depending of the PDU type + /// + /// The radio must be disabled before calling this function + pub fn set_crc_init(&mut self, crc_init: u32) { + assert!(self.state() == RadioState::DISABLED); + + let r = T::regs(); + + r.crcinit().write(|w| w.set_crcinit(crc_init & 0xFFFFFF)); + } + + /// Set the radio tx power + /// + /// The radio must be disabled before calling this function + pub fn set_tx_power(&mut self, tx_power: TxPower) { + assert!(self.state() == RadioState::DISABLED); + + let r = T::regs(); + + r.txpower().write(|w| w.set_txpower(tx_power)); + } + + /// Set buffer to read/write + /// + /// This method is unsound. You should guarantee that the buffer will live + /// for the life time of the transmission or if the buffer will be modified. + /// Also if the buffer is smaller than the packet length, the radio will + /// read/write memory out of the buffer bounds. + fn set_buffer(&mut self, buffer: &[u8]) -> Result<(), Error> { + slice_in_ram_or(buffer, Error::BufferNotInRAM)?; + + let r = T::regs(); + + // Here it consider that the length of the packet is + // correctly set in the buffer, otherwise it will send + // unowned regions of memory + let ptr = buffer.as_ptr(); + + // Configure the payload + r.packetptr().write_value(ptr as u32); + + Ok(()) + } + + /// Send packet + /// If the length byte in the package is greater than the buffer length + /// the radio will read memory out of the buffer bounds + pub async fn transmit(&mut self, buffer: &[u8]) -> Result<(), Error> { + self.set_buffer(buffer)?; + + let r = T::regs(); + self.trigger_and_wait_end(move || { + // Initialize the transmission + // trace!("txen"); + + r.tasks_txen().write_value(1); + }) + .await; + + Ok(()) + } + + /// Receive packet + /// If the length byte in the received package is greater than the buffer length + /// the radio will write memory out of the buffer bounds + pub async fn receive(&mut self, buffer: &mut [u8]) -> Result<(), Error> { + self.set_buffer(buffer)?; + + let r = T::regs(); + self.trigger_and_wait_end(move || { + // Initialize the transmission + // trace!("rxen"); + r.tasks_rxen().write_value(1); + }) + .await; + + Ok(()) + } + + async fn trigger_and_wait_end(&mut self, trigger: impl FnOnce()) { + let r = T::regs(); + let s = T::state(); + + // If the Future is dropped before the end of the transmission + // it disable the interrupt and stop the transmission + // to keep the state consistent + let drop = OnDrop::new(|| { + trace!("radio drop: stopping"); + + r.intenclr().write(|w| w.set_end(true)); + + r.tasks_stop().write_value(1); + + r.events_end().write_value(0); + + trace!("radio drop: stopped"); + }); + + // trace!("radio:enable interrupt"); + // Clear some remnant side-effects (TODO: check if this is necessary) + r.events_end().write_value(0); + + // Enable interrupt + r.intenset().write(|w| w.set_end(true)); + + compiler_fence(Ordering::SeqCst); + + // Trigger the transmission + trigger(); + + // On poll check if interrupt happen + poll_fn(|cx| { + s.event_waker.register(cx.waker()); + if r.events_end().read() == 1 { + // trace!("radio:end"); + return core::task::Poll::Ready(()); + } + Poll::Pending + }) + .await; + + compiler_fence(Ordering::SeqCst); + r.events_end().write_value(0); // ACK + + // Everthing ends fine, so it disable the drop + drop.defuse(); + } + + /// Disable the radio + fn disable(&mut self) { + let r = T::regs(); + + compiler_fence(Ordering::SeqCst); + // If it is already disabled, do nothing + if self.state() != RadioState::DISABLED { + trace!("radio:disable"); + // Trigger the disable task + r.tasks_disable().write_value(1); + + // Wait until the radio is disabled + while r.events_disabled().read() == 0 {} + + compiler_fence(Ordering::SeqCst); + + // Acknowledge it + r.events_disabled().write_value(0); + } + } +} + +impl<'d, T: Instance> Drop for Radio<'d, T> { + fn drop(&mut self) { + self.disable(); + } +} diff --git a/embassy-nrf/src/radio/ieee802154.rs b/embassy-nrf/src/radio/ieee802154.rs new file mode 100644 index 000000000..083842f4a --- /dev/null +++ b/embassy-nrf/src/radio/ieee802154.rs @@ -0,0 +1,539 @@ +//! IEEE 802.15.4 radio driver + +use core::sync::atomic::{compiler_fence, Ordering}; +use core::task::Poll; + +use embassy_hal_internal::drop::OnDrop; +use embassy_hal_internal::{into_ref, PeripheralRef}; + +use super::{state, Error, Instance, InterruptHandler, RadioState, TxPower}; +use crate::interrupt::typelevel::Interrupt; +use crate::interrupt::{self}; +use crate::pac::radio::vals; +use crate::Peripheral; + +/// Default (IEEE compliant) Start of Frame Delimiter +pub const DEFAULT_SFD: u8 = 0xA7; + +// TODO expose the other variants in `pac::CCAMODE_A` +/// Clear Channel Assessment method +pub enum Cca { + /// Carrier sense + CarrierSense, + /// Energy Detection / Energy Above Threshold + EnergyDetection { + /// Energy measurements above this value mean that the channel is assumed to be busy. + /// Note the measurement range is 0..0xFF - where 0 means that the received power was + /// less than 10 dB above the selected receiver sensitivity. This value is not given in dBm, + /// but can be converted. See the nrf52840 Product Specification Section 6.20.12.4 + /// for details. + ed_threshold: u8, + }, +} + +/// IEEE 802.15.4 radio driver. +pub struct Radio<'d, T: Instance> { + _p: PeripheralRef<'d, T>, + needs_enable: bool, +} + +impl<'d, T: Instance> Radio<'d, T> { + /// Create a new IEEE 802.15.4 radio driver. + pub fn new( + radio: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + ) -> Self { + into_ref!(radio); + + let r = T::regs(); + + // Disable and enable to reset peripheral + r.power().write(|w| w.set_power(false)); + r.power().write(|w| w.set_power(true)); + + // Enable 802.15.4 mode + r.mode().write(|w| w.set_mode(vals::Mode::IEEE802154_250KBIT)); + // Configure CRC skip address + r.crccnf().write(|w| { + w.set_len(vals::Len::TWO); + w.set_skipaddr(vals::Skipaddr::IEEE802154); + }); + // Configure CRC polynomial and init + r.crcpoly().write(|w| w.set_crcpoly(0x0001_1021)); + r.crcinit().write(|w| w.set_crcinit(0)); + r.pcnf0().write(|w| { + // 8-bit on air length + w.set_lflen(8); + // Zero bytes S0 field length + w.set_s0len(false); + // Zero bytes S1 field length + w.set_s1len(0); + // Do not include S1 field in RAM if S1 length > 0 + w.set_s1incl(vals::S1incl::AUTOMATIC); + // Zero code Indicator length + w.set_cilen(0); + // 32-bit zero preamble + w.set_plen(vals::Plen::_32BIT_ZERO); + // Include CRC in length + w.set_crcinc(vals::Crcinc::INCLUDE); + }); + r.pcnf1().write(|w| { + // Maximum packet length + w.set_maxlen(Packet::MAX_PSDU_LEN); + // Zero static length + w.set_statlen(0); + // Zero base address length + w.set_balen(0); + // Little-endian + w.set_endian(vals::Endian::LITTLE); + // Disable packet whitening + w.set_whiteen(false); + }); + + // Enable NVIC interrupt + T::Interrupt::unpend(); + unsafe { T::Interrupt::enable() }; + + let mut radio = Self { + _p: radio, + needs_enable: false, + }; + + radio.set_sfd(DEFAULT_SFD); + radio.set_transmission_power(0); + radio.set_channel(11); + radio.set_cca(Cca::CarrierSense); + + radio + } + + /// Changes the radio channel + pub fn set_channel(&mut self, channel: u8) { + let r = T::regs(); + if channel < 11 || channel > 26 { + panic!("Bad 802.15.4 channel"); + } + let frequency_offset = (channel - 10) * 5; + self.needs_enable = true; + r.frequency().write(|w| { + w.set_frequency(frequency_offset); + w.set_map(vals::Map::DEFAULT); + }); + } + + /// Changes the Clear Channel Assessment method + pub fn set_cca(&mut self, cca: Cca) { + let r = T::regs(); + self.needs_enable = true; + match cca { + Cca::CarrierSense => r.ccactrl().write(|w| w.set_ccamode(vals::Ccamode::CARRIER_MODE)), + Cca::EnergyDetection { ed_threshold } => { + // "[ED] is enabled by first configuring the field CCAMODE=EdMode in CCACTRL + // and writing the CCAEDTHRES field to a chosen value." + r.ccactrl().write(|w| { + w.set_ccamode(vals::Ccamode::ED_MODE); + w.set_ccaedthres(ed_threshold); + }); + } + } + } + + /// Changes the Start of Frame Delimiter (SFD) + pub fn set_sfd(&mut self, sfd: u8) { + let r = T::regs(); + r.sfd().write(|w| w.set_sfd(sfd)); + } + + /// Clear interrupts + pub fn clear_all_interrupts(&mut self) { + let r = T::regs(); + r.intenclr().write(|w| w.0 = 0xffff_ffff); + } + + /// Changes the radio transmission power + pub fn set_transmission_power(&mut self, power: i8) { + let r = T::regs(); + self.needs_enable = true; + + let tx_power: TxPower = match power { + #[cfg(not(any(feature = "nrf52811", feature = "_nrf5340-net")))] + 8 => TxPower::POS8_DBM, + #[cfg(not(any(feature = "nrf52811", feature = "_nrf5340-net")))] + 7 => TxPower::POS7_DBM, + #[cfg(not(any(feature = "nrf52811", feature = "_nrf5340-net")))] + 6 => TxPower::POS6_DBM, + #[cfg(not(any(feature = "nrf52811", feature = "_nrf5340-net")))] + 5 => TxPower::POS5_DBM, + #[cfg(not(feature = "_nrf5340-net"))] + 4 => TxPower::POS4_DBM, + #[cfg(not(feature = "_nrf5340-net"))] + 3 => TxPower::POS3_DBM, + #[cfg(not(any(feature = "nrf52811", feature = "_nrf5340-net")))] + 2 => TxPower::POS2_DBM, + 0 => TxPower::_0_DBM, + #[cfg(feature = "_nrf5340-net")] + -1 => TxPower::NEG1_DBM, + #[cfg(feature = "_nrf5340-net")] + -2 => TxPower::NEG2_DBM, + #[cfg(feature = "_nrf5340-net")] + -3 => TxPower::NEG3_DBM, + -4 => TxPower::NEG4_DBM, + #[cfg(feature = "_nrf5340-net")] + -5 => TxPower::NEG5_DBM, + #[cfg(feature = "_nrf5340-net")] + -6 => TxPower::NEG6_DBM, + #[cfg(feature = "_nrf5340-net")] + -7 => TxPower::NEG7_DBM, + -8 => TxPower::NEG8_DBM, + -12 => TxPower::NEG12_DBM, + -16 => TxPower::NEG16_DBM, + -20 => TxPower::NEG20_DBM, + -30 => TxPower::NEG30_DBM, + -40 => TxPower::NEG40_DBM, + _ => panic!("Invalid transmission power value"), + }; + + r.txpower().write(|w| w.set_txpower(tx_power)); + } + + /// Waits until the radio state matches the given `state` + fn wait_for_radio_state(&self, state: RadioState) { + while self.state() != state {} + } + + /// Get the current radio state + fn state(&self) -> RadioState { + state(T::regs()) + } + + /// Moves the radio from any state to the DISABLED state + fn disable(&mut self) { + let r = T::regs(); + // See figure 110 in nRF52840-PS + loop { + match self.state() { + RadioState::DISABLED => return, + // idle or ramping up + RadioState::RX_RU | RadioState::RX_IDLE | RadioState::TX_RU | RadioState::TX_IDLE => { + r.tasks_disable().write_value(1); + self.wait_for_radio_state(RadioState::DISABLED); + return; + } + // ramping down + RadioState::RX_DISABLE | RadioState::TX_DISABLE => { + self.wait_for_radio_state(RadioState::DISABLED); + return; + } + // cancel ongoing transfer or ongoing CCA + RadioState::RX => { + r.tasks_ccastop().write_value(1); + r.tasks_stop().write_value(1); + self.wait_for_radio_state(RadioState::RX_IDLE); + } + RadioState::TX => { + r.tasks_stop().write_value(1); + self.wait_for_radio_state(RadioState::TX_IDLE); + } + _ => unreachable!(), + } + } + } + + fn set_buffer(&mut self, buffer: &[u8]) { + let r = T::regs(); + r.packetptr().write_value(buffer.as_ptr() as u32); + } + + /// Moves the radio to the RXIDLE state + fn receive_prepare(&mut self) { + // clear related events + T::regs().events_ccabusy().write_value(0); + T::regs().events_phyend().write_value(0); + // NOTE to avoid errata 204 (see rev1 v1.4) we do TX_IDLE -> DISABLED -> RXIDLE + let disable = match self.state() { + RadioState::DISABLED => false, + RadioState::RX_IDLE => self.needs_enable, + _ => true, + }; + if disable { + self.disable(); + } + self.needs_enable = false; + } + + /// Prepare radio for receiving a packet + fn receive_start(&mut self, packet: &mut Packet) { + // NOTE we do NOT check the address of `packet` because the mutable reference ensures it's + // allocated in RAM + let r = T::regs(); + + self.receive_prepare(); + + // Configure shortcuts + // + // The radio goes through following states when receiving a 802.15.4 packet + // + // enable RX → ramp up RX → RX idle → Receive → end (PHYEND) + r.shorts().write(|w| w.set_rxready_start(true)); + + // set up RX buffer + self.set_buffer(packet.buffer.as_mut()); + + // start transfer + dma_start_fence(); + + match self.state() { + // Re-start receiver + RadioState::RX_IDLE => r.tasks_start().write_value(1), + // Enable receiver + _ => r.tasks_rxen().write_value(1), + } + } + + /// Cancel receiving packet + fn receive_cancel() { + let r = T::regs(); + r.shorts().write(|_| {}); + r.tasks_stop().write_value(1); + loop { + match state(r) { + RadioState::DISABLED | RadioState::RX_IDLE => break, + _ => (), + } + } + // DMA transfer may have been in progress so synchronize with its memory operations + dma_end_fence(); + } + + /// Receives one radio packet and copies its contents into the given `packet` buffer + /// + /// This methods returns the `Ok` variant if the CRC included the packet was successfully + /// validated by the hardware; otherwise it returns the `Err` variant. In either case, `packet` + /// will be updated with the received packet's data + pub async fn receive(&mut self, packet: &mut Packet) -> Result<(), Error> { + let s = T::state(); + let r = T::regs(); + + // Start the read + self.receive_start(packet); + + let dropper = OnDrop::new(|| Self::receive_cancel()); + + self.clear_all_interrupts(); + // wait until we have received something + core::future::poll_fn(|cx| { + s.event_waker.register(cx.waker()); + + if r.events_phyend().read() != 0 { + r.events_phyend().write_value(0); + trace!("RX done poll"); + return Poll::Ready(()); + } else { + r.intenset().write(|w| w.set_phyend(true)); + }; + + Poll::Pending + }) + .await; + + dma_end_fence(); + dropper.defuse(); + + let crc = r.rxcrc().read().rxcrc() as u16; + if r.crcstatus().read().crcstatus() == vals::Crcstatus::CRCOK { + Ok(()) + } else { + Err(Error::CrcFailed(crc)) + } + } + + /// Tries to send the given `packet` + /// + /// This method performs Clear Channel Assessment (CCA) first and sends the `packet` only if the + /// channel is observed to be *clear* (no transmission is currently ongoing), otherwise no + /// packet is transmitted and the `Err` variant is returned + /// + /// NOTE this method will *not* modify the `packet` argument. The mutable reference is used to + /// ensure the `packet` buffer is allocated in RAM, which is required by the RADIO peripheral + // NOTE we do NOT check the address of `packet` because the mutable reference ensures it's + // allocated in RAM + pub async fn try_send(&mut self, packet: &mut Packet) -> Result<(), Error> { + let s = T::state(); + let r = T::regs(); + + // enable radio to perform cca + self.receive_prepare(); + + /// transmit result + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum TransmitResult { + /// Success + Success, + /// Clear channel assessment reported channel in use + ChannelInUse, + } + + // Configure shortcuts + // + // The radio goes through following states when sending a 802.15.4 packet + // + // enable RX → ramp up RX → clear channel assessment (CCA) → CCA result + // CCA idle → enable TX → start TX → TX → end (PHYEND) → disabled + // + // CCA might end up in the event CCABUSY in which there will be no transmission + r.shorts().write(|w| { + w.set_rxready_ccastart(true); + w.set_ccaidle_txen(true); + w.set_txready_start(true); + w.set_ccabusy_disable(true); + w.set_phyend_disable(true); + }); + + // Set transmission buffer + self.set_buffer(packet.buffer.as_mut()); + + // the DMA transfer will start at some point after the following write operation so + // we place the compiler fence here + dma_start_fence(); + // start CCA. In case the channel is clear, the data at packetptr will be sent automatically + + match self.state() { + // Re-start receiver + RadioState::RX_IDLE => r.tasks_ccastart().write_value(1), + // Enable receiver + _ => r.tasks_rxen().write_value(1), + } + + self.clear_all_interrupts(); + let result = core::future::poll_fn(|cx| { + s.event_waker.register(cx.waker()); + + if r.events_phyend().read() != 0 { + r.events_phyend().write_value(0); + r.events_ccabusy().write_value(0); + trace!("TX done poll"); + return Poll::Ready(TransmitResult::Success); + } else if r.events_ccabusy().read() != 0 { + r.events_ccabusy().write_value(0); + trace!("TX no CCA"); + return Poll::Ready(TransmitResult::ChannelInUse); + } + + r.intenset().write(|w| { + w.set_phyend(true); + w.set_ccabusy(true); + }); + + Poll::Pending + }) + .await; + + match result { + TransmitResult::Success => Ok(()), + TransmitResult::ChannelInUse => Err(Error::ChannelInUse), + } + } +} + +/// An IEEE 802.15.4 packet +/// +/// This `Packet` is a PHY layer packet. It's made up of the physical header (PHR) and the PSDU +/// (PHY service data unit). The PSDU of this `Packet` will always include the MAC level CRC, AKA +/// the FCS (Frame Control Sequence) -- the CRC is fully computed in hardware and automatically +/// appended on transmission and verified on reception. +/// +/// The API lets users modify the usable part (not the CRC) of the PSDU via the `deref` and +/// `copy_from_slice` methods. These methods will automatically update the PHR. +/// +/// See figure 119 in the Product Specification of the nRF52840 for more details +pub struct Packet { + buffer: [u8; Self::SIZE], +} + +// See figure 124 in nRF52840-PS +impl Packet { + // for indexing purposes + const PHY_HDR: usize = 0; + const DATA: core::ops::RangeFrom = 1..; + + /// Maximum amount of usable payload (CRC excluded) a single packet can contain, in bytes + pub const CAPACITY: u8 = 125; + const CRC: u8 = 2; // size of the CRC, which is *never* copied to / from RAM + const MAX_PSDU_LEN: u8 = Self::CAPACITY + Self::CRC; + const SIZE: usize = 1 /* PHR */ + Self::MAX_PSDU_LEN as usize; + + /// Returns an empty packet (length = 0) + pub fn new() -> Self { + let mut packet = Self { + buffer: [0; Self::SIZE], + }; + packet.set_len(0); + packet + } + + /// Fills the packet payload with given `src` data + /// + /// # Panics + /// + /// This function panics if `src` is larger than `Self::CAPACITY` + pub fn copy_from_slice(&mut self, src: &[u8]) { + assert!(src.len() <= Self::CAPACITY as usize); + let len = src.len() as u8; + self.buffer[Self::DATA][..len as usize].copy_from_slice(&src[..len.into()]); + self.set_len(len); + } + + /// Returns the size of this packet's payload + pub fn len(&self) -> u8 { + self.buffer[Self::PHY_HDR] - Self::CRC + } + + /// Changes the size of the packet's payload + /// + /// # Panics + /// + /// This function panics if `len` is larger than `Self::CAPACITY` + pub fn set_len(&mut self, len: u8) { + assert!(len <= Self::CAPACITY); + self.buffer[Self::PHY_HDR] = len + Self::CRC; + } + + /// Returns the LQI (Link Quality Indicator) of the received packet + /// + /// Note that the LQI is stored in the `Packet`'s internal buffer by the hardware so the value + /// returned by this method is only valid after a `Radio.recv` operation. Operations that + /// modify the `Packet`, like `copy_from_slice` or `set_len`+`deref_mut`, will overwrite the + /// stored LQI value. + /// + /// Also note that the hardware will *not* compute a LQI for packets smaller than 3 bytes so + /// this method will return an invalid value for those packets. + pub fn lqi(&self) -> u8 { + self.buffer[1 /* PHY_HDR */ + self.len() as usize /* data */] + } +} + +impl core::ops::Deref for Packet { + type Target = [u8]; + + fn deref(&self) -> &[u8] { + &self.buffer[Self::DATA][..self.len() as usize] + } +} + +impl core::ops::DerefMut for Packet { + fn deref_mut(&mut self) -> &mut [u8] { + let len = self.len(); + &mut self.buffer[Self::DATA][..len as usize] + } +} + +/// NOTE must be followed by a volatile write operation +fn dma_start_fence() { + compiler_fence(Ordering::Release); +} + +/// NOTE must be preceded by a volatile read operation +fn dma_end_fence() { + compiler_fence(Ordering::Acquire); +} diff --git a/embassy-nrf/src/radio/mod.rs b/embassy-nrf/src/radio/mod.rs new file mode 100644 index 000000000..251f37d3d --- /dev/null +++ b/embassy-nrf/src/radio/mod.rs @@ -0,0 +1,105 @@ +//! Integrated 2.4 GHz Radio +//! +//! The 2.4 GHz radio transceiver is compatible with multiple radio standards +//! such as 1Mbps, 2Mbps and Long Range Bluetooth Low Energy. + +#![macro_use] + +/// Bluetooth Low Energy Radio driver. +pub mod ble; +#[cfg(any( + feature = "nrf52811", + feature = "nrf52820", + feature = "nrf52833", + feature = "nrf52840", + feature = "_nrf5340-net" +))] +/// IEEE 802.15.4 +pub mod ieee802154; + +use core::marker::PhantomData; + +use embassy_sync::waitqueue::AtomicWaker; +use pac::radio::vals::State as RadioState; +pub use pac::radio::vals::Txpower as TxPower; + +use crate::{interrupt, pac, Peripheral}; + +/// RADIO error. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub enum Error { + /// Buffer was too long. + BufferTooLong, + /// Buffer was too short. + BufferTooShort, + /// The buffer is not in data RAM. It's most likely in flash, and nRF's DMA cannot access flash. + BufferNotInRAM, + /// Clear channel assessment reported channel in use + ChannelInUse, + /// CRC check failed + CrcFailed(u16), +} + +/// Interrupt handler +pub struct InterruptHandler { + _phantom: PhantomData, +} + +impl interrupt::typelevel::Handler for InterruptHandler { + unsafe fn on_interrupt() { + let r = T::regs(); + let s = T::state(); + // clear all interrupts + r.intenclr().write(|w| w.0 = 0xffff_ffff); + s.event_waker.wake(); + } +} + +pub(crate) struct State { + /// end packet transmission or reception + event_waker: AtomicWaker, +} +impl State { + pub(crate) const fn new() -> Self { + Self { + event_waker: AtomicWaker::new(), + } + } +} + +pub(crate) trait SealedInstance { + fn regs() -> crate::pac::radio::Radio; + fn state() -> &'static State; +} + +macro_rules! impl_radio { + ($type:ident, $pac_type:ident, $irq:ident) => { + impl crate::radio::SealedInstance for peripherals::$type { + fn regs() -> crate::pac::radio::Radio { + pac::$pac_type + } + + fn state() -> &'static crate::radio::State { + static STATE: crate::radio::State = crate::radio::State::new(); + &STATE + } + } + impl crate::radio::Instance for peripherals::$type { + type Interrupt = crate::interrupt::typelevel::$irq; + } + }; +} + +/// Radio peripheral instance. +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static + Send { + /// Interrupt for this peripheral. + type Interrupt: interrupt::typelevel::Interrupt; +} + +/// Get the state of the radio +pub(crate) fn state(radio: pac::radio::Radio) -> RadioState { + radio.state().read().state() +} diff --git a/embassy-nrf/src/rng.rs b/embassy-nrf/src/rng.rs index 40b73231b..7a98ab2fb 100644 --- a/embassy-nrf/src/rng.rs +++ b/embassy-nrf/src/rng.rs @@ -2,16 +2,19 @@ #![macro_use] +use core::cell::{RefCell, RefMut}; use core::future::poll_fn; use core::marker::PhantomData; use core::ptr; use core::task::Poll; +use critical_section::{CriticalSection, Mutex}; use embassy_hal_internal::drop::OnDrop; use embassy_hal_internal::{into_ref, PeripheralRef}; +use embassy_sync::waitqueue::WakerRegistration; use crate::interrupt::typelevel::Interrupt; -use crate::{interrupt, Peripheral}; +use crate::{interrupt, pac, Peripheral}; /// Interrupt handler. pub struct InterruptHandler { @@ -23,7 +26,7 @@ impl interrupt::typelevel::Handler for InterruptHandl let r = T::regs(); // Clear the event. - r.events_valrdy.reset(); + r.events_valrdy().write_value(0); // Mutate the slice within a critical section, // so that the future isn't dropped in between us loading the pointer and actually dereferencing it. @@ -37,7 +40,7 @@ impl interrupt::typelevel::Handler for InterruptHandl // The safety contract of `Rng::new` means that the future can't have been dropped // without calling its destructor. unsafe { - *state.ptr = r.value.read().value().bits(); + *state.ptr = r.value().read().value(); state.ptr = state.ptr.add(1); } @@ -81,19 +84,19 @@ impl<'d, T: Instance> Rng<'d, T> { } fn stop(&self) { - T::regs().tasks_stop.write(|w| unsafe { w.bits(1) }) + T::regs().tasks_stop().write_value(1) } fn start(&self) { - T::regs().tasks_start.write(|w| unsafe { w.bits(1) }) + T::regs().tasks_start().write_value(1) } fn enable_irq(&self) { - T::regs().intenset.write(|w| w.valrdy().set()); + T::regs().intenset().write(|w| w.set_valrdy(true)); } fn disable_irq(&self) { - T::regs().intenclr.write(|w| w.valrdy().clear()); + T::regs().intenclr().write(|w| w.set_valrdy(true)); } /// Enable or disable the RNG's bias correction. @@ -103,12 +106,12 @@ impl<'d, T: Instance> Rng<'d, T> { /// /// Defaults to disabled. pub fn set_bias_correction(&self, enable: bool) { - T::regs().config.write(|w| w.dercen().bit(enable)) + T::regs().config().write(|w| w.set_dercen(enable)) } /// Fill the buffer with random bytes. pub async fn fill_bytes(&mut self, dest: &mut [u8]) { - if dest.len() == 0 { + if dest.is_empty() { return; // Nothing to fill } @@ -159,9 +162,9 @@ impl<'d, T: Instance> Rng<'d, T> { for byte in dest.iter_mut() { let regs = T::regs(); - while regs.events_valrdy.read().bits() == 0 {} - regs.events_valrdy.reset(); - *byte = regs.value.read().value().bits(); + while regs.events_valrdy().read() == 0 {} + regs.events_valrdy().write_value(0); + *byte = regs.value().read().value(); } self.stop(); @@ -205,73 +208,61 @@ impl<'d, T: Instance> rand_core::RngCore for Rng<'d, T> { impl<'d, T: Instance> rand_core::CryptoRng for Rng<'d, T> {} -pub(crate) mod sealed { - use core::cell::{Ref, RefCell, RefMut}; +/// Peripheral static state +pub(crate) struct State { + inner: Mutex>, +} - use critical_section::{CriticalSection, Mutex}; - use embassy_sync::waitqueue::WakerRegistration; +struct InnerState { + ptr: *mut u8, + end: *mut u8, + waker: WakerRegistration, +} - use super::*; +unsafe impl Send for InnerState {} - /// Peripheral static state - pub struct State { - inner: Mutex>, - } - - pub struct InnerState { - pub ptr: *mut u8, - pub end: *mut u8, - pub waker: WakerRegistration, - } - - unsafe impl Send for InnerState {} - - impl State { - pub const fn new() -> Self { - Self { - inner: Mutex::new(RefCell::new(InnerState::new())), - } - } - - pub fn borrow<'cs>(&'cs self, cs: CriticalSection<'cs>) -> Ref<'cs, InnerState> { - self.inner.borrow(cs).borrow() - } - - pub fn borrow_mut<'cs>(&'cs self, cs: CriticalSection<'cs>) -> RefMut<'cs, InnerState> { - self.inner.borrow(cs).borrow_mut() +impl State { + pub(crate) const fn new() -> Self { + Self { + inner: Mutex::new(RefCell::new(InnerState::new())), } } - impl InnerState { - pub const fn new() -> Self { - Self { - ptr: ptr::null_mut(), - end: ptr::null_mut(), - waker: WakerRegistration::new(), - } - } - } - - pub trait Instance { - fn regs() -> &'static crate::pac::rng::RegisterBlock; - fn state() -> &'static State; + fn borrow_mut<'cs>(&'cs self, cs: CriticalSection<'cs>) -> RefMut<'cs, InnerState> { + self.inner.borrow(cs).borrow_mut() } } +impl InnerState { + const fn new() -> Self { + Self { + ptr: ptr::null_mut(), + end: ptr::null_mut(), + waker: WakerRegistration::new(), + } + } +} + +pub(crate) trait SealedInstance { + fn regs() -> pac::rng::Rng; + fn state() -> &'static State; +} + /// RNG peripheral instance. -pub trait Instance: Peripheral

+ sealed::Instance + 'static + Send { +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static + Send { /// Interrupt for this peripheral. type Interrupt: interrupt::typelevel::Interrupt; } macro_rules! impl_rng { ($type:ident, $pac_type:ident, $irq:ident) => { - impl crate::rng::sealed::Instance for peripherals::$type { - fn regs() -> &'static crate::pac::rng::RegisterBlock { - unsafe { &*pac::$pac_type::ptr() } + impl crate::rng::SealedInstance for peripherals::$type { + fn regs() -> crate::pac::rng::Rng { + pac::$pac_type } - fn state() -> &'static crate::rng::sealed::State { - static STATE: crate::rng::sealed::State = crate::rng::sealed::State::new(); + fn state() -> &'static crate::rng::State { + static STATE: crate::rng::State = crate::rng::State::new(); &STATE } } diff --git a/embassy-nrf/src/saadc.rs b/embassy-nrf/src/saadc.rs index 7733280bd..ec283363c 100644 --- a/embassy-nrf/src/saadc.rs +++ b/embassy-nrf/src/saadc.rs @@ -9,15 +9,10 @@ use core::task::Poll; use embassy_hal_internal::drop::OnDrop; use embassy_hal_internal::{impl_peripheral, into_ref, PeripheralRef}; use embassy_sync::waitqueue::AtomicWaker; -use pac::{saadc, SAADC}; -use saadc::ch::config::{GAIN_A, REFSEL_A, RESP_A, TACQ_A}; -// We treat the positive and negative channels with the same enum values to keep our type tidy and given they are the same -pub(crate) use saadc::ch::pselp::PSELP_A as InputChannel; -use saadc::oversample::OVERSAMPLE_A; -use saadc::resolution::VAL_A; +pub(crate) use vals::Psel as InputChannel; -use self::sealed::Input as _; use crate::interrupt::InterruptExt; +use crate::pac::saadc::vals; use crate::ppi::{ConfigurableChannel, Event, Ppi, Task}; use crate::timer::{Frequency, Instance as TimerInstance, Timer}; use crate::{interrupt, pac, peripherals, Peripheral}; @@ -35,20 +30,20 @@ pub struct InterruptHandler { impl interrupt::typelevel::Handler for InterruptHandler { unsafe fn on_interrupt() { - let r = unsafe { &*SAADC::ptr() }; + let r = pac::SAADC; - if r.events_calibratedone.read().bits() != 0 { - r.intenclr.write(|w| w.calibratedone().clear()); + if r.events_calibratedone().read() != 0 { + r.intenclr().write(|w| w.set_calibratedone(true)); WAKER.wake(); } - if r.events_end.read().bits() != 0 { - r.intenclr.write(|w| w.end().clear()); + if r.events_end().read() != 0 { + r.intenclr().write(|w| w.set_end(true)); WAKER.wake(); } - if r.events_started.read().bits() != 0 { - r.intenclr.write(|w| w.started().clear()); + if r.events_started().read() != 0 { + r.intenclr().write(|w| w.set_started(true)); WAKER.wake(); } } @@ -79,7 +74,8 @@ impl Default for Config { /// Used to configure an individual SAADC peripheral channel. /// -/// See the `Default` impl for suitable default values. +/// Construct using the `single_ended` or `differential` methods. These provide sensible defaults +/// for the public fields, which can be overridden if required. #[non_exhaustive] pub struct ChannelConfig<'d> { /// Reference voltage of the SAADC input. @@ -167,44 +163,36 @@ impl<'d, const N: usize> Saadc<'d, N> { ) -> Self { into_ref!(saadc); - let r = unsafe { &*SAADC::ptr() }; + let r = pac::SAADC; let Config { resolution, oversample } = config; // Configure channels - r.enable.write(|w| w.enable().enabled()); - r.resolution.write(|w| w.val().variant(resolution.into())); - r.oversample.write(|w| w.oversample().variant(oversample.into())); + r.enable().write(|w| w.set_enable(true)); + r.resolution().write(|w| w.set_val(resolution.into())); + r.oversample().write(|w| w.set_oversample(oversample.into())); for (i, cc) in channel_configs.iter().enumerate() { - r.ch[i].pselp.write(|w| w.pselp().variant(cc.p_channel.channel())); + r.ch(i).pselp().write(|w| w.set_pselp(cc.p_channel.channel())); if let Some(n_channel) = &cc.n_channel { - r.ch[i] - .pseln - .write(|w| unsafe { w.pseln().bits(n_channel.channel() as u8) }); + r.ch(i).pseln().write(|w| w.set_pseln(n_channel.channel())); } - r.ch[i].config.write(|w| { - w.refsel().variant(cc.reference.into()); - w.gain().variant(cc.gain.into()); - w.tacq().variant(cc.time.into()); - if cc.n_channel.is_none() { - w.mode().se(); - } else { - w.mode().diff(); - } - w.resp().variant(cc.resistor.into()); - w.resn().bypass(); - if !matches!(oversample, Oversample::BYPASS) { - w.burst().enabled(); - } else { - w.burst().disabled(); - } - w + r.ch(i).config().write(|w| { + w.set_refsel(cc.reference.into()); + w.set_gain(cc.gain.into()); + w.set_tacq(cc.time.into()); + w.set_mode(match cc.n_channel { + None => vals::ConfigMode::SE, + Some(_) => vals::ConfigMode::DIFF, + }); + w.set_resp(cc.resistor.into()); + w.set_resn(vals::Resn::BYPASS); + w.set_burst(!matches!(oversample, Oversample::BYPASS)); }); } // Disable all events interrupts - r.intenclr.write(|w| unsafe { w.bits(0x003F_FFFF) }); + r.intenclr().write(|w| w.0 = 0x003F_FFFF); interrupt::SAADC.unpend(); unsafe { interrupt::SAADC.enable() }; @@ -212,8 +200,8 @@ impl<'d, const N: usize> Saadc<'d, N> { Self { _p: saadc } } - fn regs() -> &'static saadc::RegisterBlock { - unsafe { &*SAADC::ptr() } + fn regs() -> pac::saadc::Saadc { + pac::SAADC } /// Perform SAADC calibration. Completes when done. @@ -221,13 +209,13 @@ impl<'d, const N: usize> Saadc<'d, N> { let r = Self::regs(); // Reset and enable the end event - r.events_calibratedone.reset(); - r.intenset.write(|w| w.calibratedone().set()); + r.events_calibratedone().write_value(0); + r.intenset().write(|w| w.set_calibratedone(true)); // Order is important compiler_fence(Ordering::SeqCst); - r.tasks_calibrateoffset.write(|w| unsafe { w.bits(1) }); + r.tasks_calibrateoffset().write_value(1); // Wait for 'calibratedone' event. poll_fn(|cx| { @@ -235,8 +223,8 @@ impl<'d, const N: usize> Saadc<'d, N> { WAKER.register(cx.waker()); - if r.events_calibratedone.read().bits() != 0 { - r.events_calibratedone.reset(); + if r.events_calibratedone().read() != 0 { + r.events_calibratedone().write_value(0); return Poll::Ready(()); } @@ -256,19 +244,19 @@ impl<'d, const N: usize> Saadc<'d, N> { let r = Self::regs(); // Set up the DMA - r.result.ptr.write(|w| unsafe { w.ptr().bits(buf.as_mut_ptr() as u32) }); - r.result.maxcnt.write(|w| unsafe { w.maxcnt().bits(N as _) }); + r.result().ptr().write_value(buf.as_mut_ptr() as u32); + r.result().maxcnt().write(|w| w.set_maxcnt(N as _)); // Reset and enable the end event - r.events_end.reset(); - r.intenset.write(|w| w.end().set()); + r.events_end().write_value(0); + r.intenset().write(|w| w.set_end(true)); // Don't reorder the ADC start event before the previous writes. Hopefully self // wouldn't happen anyway. compiler_fence(Ordering::SeqCst); - r.tasks_start.write(|w| unsafe { w.bits(1) }); - r.tasks_sample.write(|w| unsafe { w.bits(1) }); + r.tasks_start().write_value(1); + r.tasks_sample().write_value(1); // Wait for 'end' event. poll_fn(|cx| { @@ -276,8 +264,8 @@ impl<'d, const N: usize> Saadc<'d, N> { WAKER.register(cx.waker()); - if r.events_end.read().bits() != 0 { - r.events_end.reset(); + if r.events_end().read() != 0 { + r.events_end().write_value(0); return Poll::Ready(()); } @@ -471,8 +459,11 @@ impl<'d, const N: usize> Saadc<'d, N> { // We want the task start to effectively short with the last one ending so // we don't miss any samples. It'd be great for the SAADC to offer a SHORTS // register instead, but it doesn't, so we must use PPI. - let mut start_ppi = - Ppi::new_one_to_one(ppi_ch1, Event::from_reg(&r.events_end), Task::from_reg(&r.tasks_start)); + let mut start_ppi = Ppi::new_one_to_one( + ppi_ch1, + Event::from_reg(r.events_end()), + Task::from_reg(r.tasks_start()), + ); start_ppi.enable(); let timer = Timer::new(timer); @@ -482,7 +473,7 @@ impl<'d, const N: usize> Saadc<'d, N> { let timer_cc = timer.cc(0); - let mut sample_ppi = Ppi::new_one_to_one(ppi_ch2, timer_cc.event_compare(), Task::from_reg(&r.tasks_sample)); + let mut sample_ppi = Ppi::new_one_to_one(ppi_ch2, timer_cc.event_compare(), Task::from_reg(r.tasks_sample())); timer.start(); @@ -515,43 +506,37 @@ impl<'d, const N: usize> Saadc<'d, N> { // Establish mode and sample rate match sample_rate_divisor { Some(sr) => { - r.samplerate.write(|w| unsafe { - w.cc().bits(sr); - w.mode().timers(); - w + r.samplerate().write(|w| { + w.set_cc(sr); + w.set_mode(vals::SamplerateMode::TIMERS); }); - r.tasks_sample.write(|w| unsafe { w.bits(1) }); // Need to kick-start the internal timer + r.tasks_sample().write_value(1); // Need to kick-start the internal timer } - None => r.samplerate.write(|w| unsafe { - w.cc().bits(0); - w.mode().task(); - w + None => r.samplerate().write(|w| { + w.set_cc(0); + w.set_mode(vals::SamplerateMode::TASK); }), } // Set up the initial DMA - r.result - .ptr - .write(|w| unsafe { w.ptr().bits(bufs[0].as_mut_ptr() as u32) }); - r.result.maxcnt.write(|w| unsafe { w.maxcnt().bits((N0 * N) as _) }); + r.result().ptr().write_value(bufs[0].as_mut_ptr() as u32); + r.result().maxcnt().write(|w| w.set_maxcnt((N0 * N) as _)); // Reset and enable the events - r.events_end.reset(); - r.events_started.reset(); - r.intenset.write(|w| { - w.end().set(); - w.started().set(); - w + r.events_end().write_value(0); + r.events_started().write_value(0); + r.intenset().write(|w| { + w.set_end(true); + w.set_started(true); }); // Don't reorder the ADC start event before the previous writes. Hopefully self // wouldn't happen anyway. compiler_fence(Ordering::SeqCst); - r.tasks_start.write(|w| unsafe { w.bits(1) }); + r.tasks_start().write_value(1); let mut inited = false; - let mut current_buffer = 0; // Wait for events and complete when the sampler indicates it has had enough. @@ -560,11 +545,11 @@ impl<'d, const N: usize> Saadc<'d, N> { WAKER.register(cx.waker()); - if r.events_end.read().bits() != 0 { + if r.events_end().read() != 0 { compiler_fence(Ordering::SeqCst); - r.events_end.reset(); - r.intenset.write(|w| w.end().set()); + r.events_end().write_value(0); + r.intenset().write(|w| w.set_end(true)); match callback(&bufs[current_buffer]) { CallbackResult::Continue => { @@ -577,9 +562,9 @@ impl<'d, const N: usize> Saadc<'d, N> { } } - if r.events_started.read().bits() != 0 { - r.events_started.reset(); - r.intenset.write(|w| w.started().set()); + if r.events_started().read() != 0 { + r.events_started().write_value(0); + r.intenset().write(|w| w.set_started(true)); if !inited { init(); @@ -587,9 +572,7 @@ impl<'d, const N: usize> Saadc<'d, N> { } let next_buffer = 1 - current_buffer; - r.result - .ptr - .write(|w| unsafe { w.ptr().bits(bufs[next_buffer].as_mut_ptr() as u32) }); + r.result().ptr().write_value(bufs[next_buffer].as_mut_ptr() as u32); } Poll::Pending @@ -607,11 +590,11 @@ impl<'d, const N: usize> Saadc<'d, N> { compiler_fence(Ordering::SeqCst); - r.events_stopped.reset(); - r.tasks_stop.write(|w| unsafe { w.bits(1) }); + r.events_stopped().write_value(0); + r.tasks_stop().write_value(1); - while r.events_stopped.read().bits() == 0 {} - r.events_stopped.reset(); + while r.events_stopped().read() == 0 {} + r.events_stopped().write_value(0); } } @@ -651,17 +634,17 @@ impl<'d, const N: usize> Drop for Saadc<'d, N> { } } -impl From for GAIN_A { +impl From for vals::Gain { fn from(gain: Gain) -> Self { match gain { - Gain::GAIN1_6 => GAIN_A::GAIN1_6, - Gain::GAIN1_5 => GAIN_A::GAIN1_5, - Gain::GAIN1_4 => GAIN_A::GAIN1_4, - Gain::GAIN1_3 => GAIN_A::GAIN1_3, - Gain::GAIN1_2 => GAIN_A::GAIN1_2, - Gain::GAIN1 => GAIN_A::GAIN1, - Gain::GAIN2 => GAIN_A::GAIN2, - Gain::GAIN4 => GAIN_A::GAIN4, + Gain::GAIN1_6 => vals::Gain::GAIN1_6, + Gain::GAIN1_5 => vals::Gain::GAIN1_5, + Gain::GAIN1_4 => vals::Gain::GAIN1_4, + Gain::GAIN1_3 => vals::Gain::GAIN1_3, + Gain::GAIN1_2 => vals::Gain::GAIN1_2, + Gain::GAIN1 => vals::Gain::GAIN1, + Gain::GAIN2 => vals::Gain::GAIN2, + Gain::GAIN4 => vals::Gain::GAIN4, } } } @@ -688,11 +671,11 @@ pub enum Gain { GAIN4 = 7, } -impl From for REFSEL_A { +impl From for vals::Refsel { fn from(reference: Reference) -> Self { match reference { - Reference::INTERNAL => REFSEL_A::INTERNAL, - Reference::VDD1_4 => REFSEL_A::VDD1_4, + Reference::INTERNAL => vals::Refsel::INTERNAL, + Reference::VDD1_4 => vals::Refsel::VDD1_4, } } } @@ -707,13 +690,13 @@ pub enum Reference { VDD1_4 = 1, } -impl From for RESP_A { +impl From for vals::Resp { fn from(resistor: Resistor) -> Self { match resistor { - Resistor::BYPASS => RESP_A::BYPASS, - Resistor::PULLDOWN => RESP_A::PULLDOWN, - Resistor::PULLUP => RESP_A::PULLUP, - Resistor::VDD1_2 => RESP_A::VDD1_2, + Resistor::BYPASS => vals::Resp::BYPASS, + Resistor::PULLDOWN => vals::Resp::PULLDOWN, + Resistor::PULLUP => vals::Resp::PULLUP, + Resistor::VDD1_2 => vals::Resp::VDD1_2, } } } @@ -732,15 +715,15 @@ pub enum Resistor { VDD1_2 = 3, } -impl From

+ Sized + 'static { +#[allow(private_bounds)] +pub trait Input: SealedInput + Into + Peripheral

+ Sized + 'static { /// Convert this SAADC input to a type-erased `AnyInput`. /// /// This allows using several inputs in situations that might require @@ -859,7 +839,7 @@ pub struct AnyInput { impl_peripheral!(AnyInput); -impl sealed::Input for AnyInput { +impl SealedInput for AnyInput { fn channel(&self) -> InputChannel { self.channel } @@ -872,7 +852,7 @@ macro_rules! impl_saadc_input { impl_saadc_input!(@local, crate::peripherals::$pin, $ch); }; (@local, $pin:ty, $ch:ident) => { - impl crate::saadc::sealed::Input for $pin { + impl crate::saadc::SealedInput for $pin { fn channel(&self) -> crate::saadc::InputChannel { crate::saadc::InputChannel::$ch } @@ -892,10 +872,10 @@ macro_rules! impl_saadc_input { pub struct VddInput; impl_peripheral!(VddInput); -#[cfg(not(feature = "_nrf9160"))] +#[cfg(not(feature = "_nrf91"))] impl_saadc_input!(@local, VddInput, VDD); -#[cfg(feature = "_nrf9160")] -impl_saadc_input!(@local, VddInput, VDDGPIO); +#[cfg(feature = "_nrf91")] +impl_saadc_input!(@local, VddInput, VDD_GPIO); /// A dummy `Input` pin implementation for SAADC peripheral sampling from the /// VDDH / 5 voltage. diff --git a/embassy-nrf/src/spim.rs b/embassy-nrf/src/spim.rs index 6b6f79188..ffaee2dc5 100644 --- a/embassy-nrf/src/spim.rs +++ b/embassy-nrf/src/spim.rs @@ -4,20 +4,23 @@ use core::future::poll_fn; use core::marker::PhantomData; +#[cfg(feature = "_nrf52832_anomaly_109")] +use core::sync::atomic::AtomicU8; use core::sync::atomic::{compiler_fence, Ordering}; use core::task::Poll; use embassy_embedded_hal::SetConfig; use embassy_hal_internal::{into_ref, PeripheralRef}; +use embassy_sync::waitqueue::AtomicWaker; pub use embedded_hal_02::spi::{Mode, Phase, Polarity, MODE_0, MODE_1, MODE_2, MODE_3}; -pub use pac::spim0::config::ORDER_A as BitOrder; -pub use pac::spim0::frequency::FREQUENCY_A as Frequency; +pub use pac::spim::vals::{Frequency, Order as BitOrder}; -use crate::chip::FORCE_COPY_BUFFER_SIZE; -use crate::gpio::sealed::Pin as _; -use crate::gpio::{self, AnyPin, Pin as GpioPin, PselBits}; +use crate::chip::{EASY_DMA_SIZE, FORCE_COPY_BUFFER_SIZE}; +use crate::gpio::{self, convert_drive, AnyPin, OutputDrive, Pin as GpioPin, PselBits, SealedPin as _}; use crate::interrupt::typelevel::Interrupt; -use crate::util::{slice_in_ram_or, slice_ptr_parts, slice_ptr_parts_mut}; +use crate::pac::gpio::vals as gpiovals; +use crate::pac::spim::vals; +use crate::util::slice_in_ram_or; use crate::{interrupt, pac, Peripheral}; /// SPIM error @@ -25,16 +28,13 @@ use crate::{interrupt, pac, Peripheral}; #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[non_exhaustive] pub enum Error { - /// TX buffer was too long. - TxBufferTooLong, - /// RX buffer was too long. - RxBufferTooLong, /// EasyDMA can only read from data memory, read only buffers in flash will fail. BufferNotInRAM, } /// SPIM configuration. #[non_exhaustive] +#[derive(Clone)] pub struct Config { /// Frequency pub frequency: Frequency, @@ -50,6 +50,12 @@ pub struct Config { /// When doing bidirectional transfers, if the TX buffer is shorter than the RX buffer, /// this byte will be transmitted in the MOSI line for the left-over bytes. pub orc: u8, + + /// Drive strength for the SCK line. + pub sck_drive: OutputDrive, + + /// Drive strength for the MOSI line. + pub mosi_drive: OutputDrive, } impl Default for Config { @@ -59,6 +65,8 @@ impl Default for Config { mode: MODE_0, bit_order: BitOrder::MSB_FIRST, orc: 0x00, + sck_drive: OutputDrive::HighDrive, + mosi_drive: OutputDrive::HighDrive, } } } @@ -74,14 +82,18 @@ impl interrupt::typelevel::Handler for InterruptHandl let s = T::state(); #[cfg(feature = "_nrf52832_anomaly_109")] - if r.events_started.read().bits() != 0 { - s.waker.wake(); - r.intenclr.write(|w| w.started().clear()); + { + // Ideally we should call this only during the first chunk transfer, + // but so far calling this every time doesn't seem to be causing any issues. + if r.events_started().read() != 0 { + s.waker.wake(); + r.intenclr().write(|w| w.set_started(true)); + } } - if r.events_end.read().bits() != 0 { + if r.events_end().read() != 0 { s.waker.wake(); - r.intenclr.write(|w| w.end().clear()); + r.intenclr().write(|w| w.set_end(true)); } } } @@ -159,13 +171,19 @@ impl<'d, T: Instance> Spim<'d, T> { // Configure pins if let Some(sck) = &sck { - sck.conf().write(|w| w.dir().output().drive().h0h1()); + sck.conf().write(|w| { + w.set_dir(gpiovals::Dir::OUTPUT); + w.set_drive(convert_drive(config.sck_drive)) + }); } if let Some(mosi) = &mosi { - mosi.conf().write(|w| w.dir().output().drive().h0h1()); + mosi.conf().write(|w| { + w.set_dir(gpiovals::Dir::OUTPUT); + w.set_drive(convert_drive(config.mosi_drive)) + }); } if let Some(miso) = &miso { - miso.conf().write(|w| w.input().connect().drive().h0h1()); + miso.conf().write(|w| w.set_input(gpiovals::Input::CONNECT)); } match config.mode.polarity { @@ -188,12 +206,12 @@ impl<'d, T: Instance> Spim<'d, T> { } // Select pins. - r.psel.sck.write(|w| unsafe { w.bits(sck.psel_bits()) }); - r.psel.mosi.write(|w| unsafe { w.bits(mosi.psel_bits()) }); - r.psel.miso.write(|w| unsafe { w.bits(miso.psel_bits()) }); + r.psel().sck().write_value(sck.psel_bits()); + r.psel().mosi().write_value(mosi.psel_bits()); + r.psel().miso().write_value(miso.psel_bits()); // Enable SPIM instance. - r.enable.write(|w| w.enable().enabled()); + r.enable().write(|w| w.set_enable(vals::Enable::ENABLED)); let mut spim = Self { _p: spim }; @@ -201,7 +219,7 @@ impl<'d, T: Instance> Spim<'d, T> { Self::set_config(&mut spim, &config).unwrap(); // Disable all events interrupts - r.intenclr.write(|w| unsafe { w.bits(0xFFFF_FFFF) }); + r.intenclr().write(|w| w.0 = 0xFFFF_FFFF); T::Interrupt::unpend(); unsafe { T::Interrupt::enable() }; @@ -209,64 +227,85 @@ impl<'d, T: Instance> Spim<'d, T> { spim } - fn prepare(&mut self, rx: *mut [u8], tx: *const [u8]) -> Result<(), Error> { - slice_in_ram_or(tx, Error::BufferNotInRAM)?; - // NOTE: RAM slice check for rx is not necessary, as a mutable - // slice can only be built from data located in RAM. - + fn prepare_dma_transfer(&mut self, rx: *mut [u8], tx: *const [u8], offset: usize, length: usize) { compiler_fence(Ordering::SeqCst); let r = T::regs(); - // Set up the DMA write. - let (ptr, tx_len) = slice_ptr_parts(tx); - r.txd.ptr.write(|w| unsafe { w.ptr().bits(ptr as _) }); - r.txd.maxcnt.write(|w| unsafe { w.maxcnt().bits(tx_len as _) }); + fn xfer_params(ptr: u32, total: usize, offset: usize, length: usize) -> (u32, usize) { + if total > offset { + (ptr.wrapping_add(offset as _), core::cmp::min(total - offset, length)) + } else { + (ptr, 0) + } + } // Set up the DMA read. - let (ptr, rx_len) = slice_ptr_parts_mut(rx); - r.rxd.ptr.write(|w| unsafe { w.ptr().bits(ptr as _) }); - r.rxd.maxcnt.write(|w| unsafe { w.maxcnt().bits(rx_len as _) }); + let (rx_ptr, rx_len) = xfer_params(rx as *mut u8 as _, rx.len() as _, offset, length); + r.rxd().ptr().write_value(rx_ptr); + r.rxd().maxcnt().write(|w| w.set_maxcnt(rx_len as _)); + + // Set up the DMA write. + let (tx_ptr, tx_len) = xfer_params(tx as *const u8 as _, tx.len() as _, offset, length); + r.txd().ptr().write_value(tx_ptr); + r.txd().maxcnt().write(|w| w.set_maxcnt(tx_len as _)); + + /* + trace!("XFER: offset: {}, length: {}", offset, length); + trace!("RX(len: {}, ptr: {=u32:02x})", rx_len, rx_ptr as u32); + trace!("TX(len: {}, ptr: {=u32:02x})", tx_len, tx_ptr as u32); + */ #[cfg(feature = "_nrf52832_anomaly_109")] - { + if offset == 0 { let s = T::state(); - r.events_started.reset(); + r.events_started().write_value(0); // Set rx/tx buffer lengths to 0... - r.txd.maxcnt.reset(); - r.rxd.maxcnt.reset(); + r.txd().maxcnt().write(|_| ()); + r.rxd().maxcnt().write(|_| ()); // ...and keep track of original buffer lengths... s.tx.store(tx_len as _, Ordering::Relaxed); s.rx.store(rx_len as _, Ordering::Relaxed); // ...signalling the start of the fake transfer. - r.intenset.write(|w| w.started().bit(true)); + r.intenset().write(|w| w.set_started(true)); } // Reset and enable the event - r.events_end.reset(); - r.intenset.write(|w| w.end().set()); + r.events_end().write_value(0); + r.intenset().write(|w| w.set_end(true)); // Start SPI transaction. - r.tasks_start.write(|w| unsafe { w.bits(1) }); + r.tasks_start().write_value(1); + } - Ok(()) + fn blocking_inner_from_ram_chunk(&mut self, rx: *mut [u8], tx: *const [u8], offset: usize, length: usize) { + self.prepare_dma_transfer(rx, tx, offset, length); + + #[cfg(feature = "_nrf52832_anomaly_109")] + if offset == 0 { + while self.nrf52832_dma_workaround_status().is_pending() {} + } + + // Wait for 'end' event. + while T::regs().events_end().read() == 0 {} + + compiler_fence(Ordering::SeqCst); } fn blocking_inner_from_ram(&mut self, rx: *mut [u8], tx: *const [u8]) -> Result<(), Error> { - self.prepare(rx, tx)?; - - #[cfg(feature = "_nrf52832_anomaly_109")] - while let Poll::Pending = self.nrf52832_dma_workaround_status() {} - - // Wait for 'end' event. - while T::regs().events_end.read().bits() == 0 {} - - compiler_fence(Ordering::SeqCst); + slice_in_ram_or(tx, Error::BufferNotInRAM)?; + // NOTE: RAM slice check for rx is not necessary, as a mutable + // slice can only be built from data located in RAM. + let xfer_len = core::cmp::max(rx.len(), tx.len()); + for offset in (0..xfer_len).step_by(EASY_DMA_SIZE) { + let length = core::cmp::min(xfer_len - offset, EASY_DMA_SIZE); + self.blocking_inner_from_ram_chunk(rx, tx, offset, length); + } Ok(()) } @@ -274,32 +313,33 @@ impl<'d, T: Instance> Spim<'d, T> { match self.blocking_inner_from_ram(rx, tx) { Ok(_) => Ok(()), Err(Error::BufferNotInRAM) => { - trace!("Copying SPIM tx buffer into RAM for DMA"); + // trace!("Copying SPIM tx buffer into RAM for DMA"); let tx_ram_buf = &mut [0; FORCE_COPY_BUFFER_SIZE][..tx.len()]; tx_ram_buf.copy_from_slice(tx); self.blocking_inner_from_ram(rx, tx_ram_buf) } - Err(error) => Err(error), } } - async fn async_inner_from_ram(&mut self, rx: *mut [u8], tx: *const [u8]) -> Result<(), Error> { - self.prepare(rx, tx)?; + async fn async_inner_from_ram_chunk(&mut self, rx: *mut [u8], tx: *const [u8], offset: usize, length: usize) { + self.prepare_dma_transfer(rx, tx, offset, length); #[cfg(feature = "_nrf52832_anomaly_109")] - poll_fn(|cx| { - let s = T::state(); + if offset == 0 { + poll_fn(|cx| { + let s = T::state(); - s.waker.register(cx.waker()); + s.waker.register(cx.waker()); - self.nrf52832_dma_workaround_status() - }) - .await; + self.nrf52832_dma_workaround_status() + }) + .await; + } // Wait for 'end' event. poll_fn(|cx| { T::state().waker.register(cx.waker()); - if T::regs().events_end.read().bits() != 0 { + if T::regs().events_end().read() != 0 { return Poll::Ready(()); } @@ -308,7 +348,18 @@ impl<'d, T: Instance> Spim<'d, T> { .await; compiler_fence(Ordering::SeqCst); + } + async fn async_inner_from_ram(&mut self, rx: *mut [u8], tx: *const [u8]) -> Result<(), Error> { + slice_in_ram_or(tx, Error::BufferNotInRAM)?; + // NOTE: RAM slice check for rx is not necessary, as a mutable + // slice can only be built from data located in RAM. + + let xfer_len = core::cmp::max(rx.len(), tx.len()); + for offset in (0..xfer_len).step_by(EASY_DMA_SIZE) { + let length = core::cmp::min(xfer_len - offset, EASY_DMA_SIZE); + self.async_inner_from_ram_chunk(rx, tx, offset, length).await; + } Ok(()) } @@ -316,12 +367,11 @@ impl<'d, T: Instance> Spim<'d, T> { match self.async_inner_from_ram(rx, tx).await { Ok(_) => Ok(()), Err(Error::BufferNotInRAM) => { - trace!("Copying SPIM tx buffer into RAM for DMA"); + // trace!("Copying SPIM tx buffer into RAM for DMA"); let tx_ram_buf = &mut [0; FORCE_COPY_BUFFER_SIZE][..tx.len()]; tx_ram_buf.copy_from_slice(tx); self.async_inner_from_ram(rx, tx_ram_buf).await } - Err(error) => Err(error), } } @@ -393,24 +443,20 @@ impl<'d, T: Instance> Spim<'d, T> { #[cfg(feature = "_nrf52832_anomaly_109")] fn nrf52832_dma_workaround_status(&mut self) -> Poll<()> { let r = T::regs(); - if r.events_started.read().bits() != 0 { + if r.events_started().read() != 0 { let s = T::state(); // Handle the first "fake" transmission - r.events_started.reset(); - r.events_end.reset(); + r.events_started().write_value(0); + r.events_end().write_value(0); // Update DMA registers with correct rx/tx buffer sizes - r.rxd - .maxcnt - .write(|w| unsafe { w.maxcnt().bits(s.rx.load(Ordering::Relaxed)) }); - r.txd - .maxcnt - .write(|w| unsafe { w.maxcnt().bits(s.tx.load(Ordering::Relaxed)) }); + r.rxd().maxcnt().write(|w| w.set_maxcnt(s.rx.load(Ordering::Relaxed))); + r.txd().maxcnt().write(|w| w.set_maxcnt(s.tx.load(Ordering::Relaxed))); - r.intenset.write(|w| w.end().set()); + r.intenset().write(|w| w.set_end(true)); // ... and start actual, hopefully glitch-free transmission - r.tasks_start.write(|w| unsafe { w.bits(1) }); + r.tasks_start().write_value(1); return Poll::Ready(()); } Poll::Pending @@ -425,11 +471,11 @@ impl<'d, T: Instance> Drop for Spim<'d, T> { // disable! let r = T::regs(); - r.enable.write(|w| w.enable().disabled()); + r.enable().write(|w| w.set_enable(vals::Enable::DISABLED)); - gpio::deconfigure_pin(r.psel.sck.read().bits()); - gpio::deconfigure_pin(r.psel.miso.read().bits()); - gpio::deconfigure_pin(r.psel.mosi.read().bits()); + gpio::deconfigure_pin(r.psel().sck().read()); + gpio::deconfigure_pin(r.psel().miso().read()); + gpio::deconfigure_pin(r.psel().mosi().read()); // Disable all events interrupts T::Interrupt::disable(); @@ -438,54 +484,46 @@ impl<'d, T: Instance> Drop for Spim<'d, T> { } } -pub(crate) mod sealed { +pub(crate) struct State { + waker: AtomicWaker, #[cfg(feature = "_nrf52832_anomaly_109")] - use core::sync::atomic::AtomicU8; + rx: AtomicU8, + #[cfg(feature = "_nrf52832_anomaly_109")] + tx: AtomicU8, +} - use embassy_sync::waitqueue::AtomicWaker; - - use super::*; - - pub struct State { - pub waker: AtomicWaker, - #[cfg(feature = "_nrf52832_anomaly_109")] - pub rx: AtomicU8, - #[cfg(feature = "_nrf52832_anomaly_109")] - pub tx: AtomicU8, - } - - impl State { - pub const fn new() -> Self { - Self { - waker: AtomicWaker::new(), - #[cfg(feature = "_nrf52832_anomaly_109")] - rx: AtomicU8::new(0), - #[cfg(feature = "_nrf52832_anomaly_109")] - tx: AtomicU8::new(0), - } +impl State { + pub(crate) const fn new() -> Self { + Self { + waker: AtomicWaker::new(), + #[cfg(feature = "_nrf52832_anomaly_109")] + rx: AtomicU8::new(0), + #[cfg(feature = "_nrf52832_anomaly_109")] + tx: AtomicU8::new(0), } } - - pub trait Instance { - fn regs() -> &'static pac::spim0::RegisterBlock; - fn state() -> &'static State; - } +} + +pub(crate) trait SealedInstance { + fn regs() -> pac::spim::Spim; + fn state() -> &'static State; } /// SPIM peripheral instance -pub trait Instance: Peripheral

+ sealed::Instance + 'static { +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static { /// Interrupt for this peripheral. type Interrupt: interrupt::typelevel::Interrupt; } macro_rules! impl_spim { ($type:ident, $pac_type:ident, $irq:ident) => { - impl crate::spim::sealed::Instance for peripherals::$type { - fn regs() -> &'static pac::spim0::RegisterBlock { - unsafe { &*pac::$pac_type::ptr() } + impl crate::spim::SealedInstance for peripherals::$type { + fn regs() -> pac::spim::Spim { + pac::$pac_type } - fn state() -> &'static crate::spim::sealed::State { - static STATE: crate::spim::sealed::State = crate::spim::sealed::State::new(); + fn state() -> &'static crate::spim::State { + static STATE: crate::spim::State = crate::spim::State::new(); &STATE } } @@ -520,8 +558,6 @@ mod eh02 { impl embedded_hal_1::spi::Error for Error { fn kind(&self) -> embedded_hal_1::spi::ErrorKind { match *self { - Self::TxBufferTooLong => embedded_hal_1::spi::ErrorKind::Other, - Self::RxBufferTooLong => embedded_hal_1::spi::ErrorKind::Other, Self::BufferNotInRAM => embedded_hal_1::spi::ErrorKind::Other, } } @@ -582,40 +618,35 @@ impl<'d, T: Instance> SetConfig for Spim<'d, T> { let r = T::regs(); // Configure mode. let mode = config.mode; - r.config.write(|w| { + r.config().write(|w| { + w.set_order(config.bit_order); match mode { MODE_0 => { - w.order().variant(config.bit_order); - w.cpol().active_high(); - w.cpha().leading(); + w.set_cpol(vals::Cpol::ACTIVE_HIGH); + w.set_cpha(vals::Cpha::LEADING); } MODE_1 => { - w.order().variant(config.bit_order); - w.cpol().active_high(); - w.cpha().trailing(); + w.set_cpol(vals::Cpol::ACTIVE_HIGH); + w.set_cpha(vals::Cpha::TRAILING); } MODE_2 => { - w.order().variant(config.bit_order); - w.cpol().active_low(); - w.cpha().leading(); + w.set_cpol(vals::Cpol::ACTIVE_LOW); + w.set_cpha(vals::Cpha::LEADING); } MODE_3 => { - w.order().variant(config.bit_order); - w.cpol().active_low(); - w.cpha().trailing(); + w.set_cpol(vals::Cpol::ACTIVE_LOW); + w.set_cpha(vals::Cpha::TRAILING); } } - - w }); // Configure frequency. let frequency = config.frequency; - r.frequency.write(|w| w.frequency().variant(frequency)); + r.frequency().write(|w| w.set_frequency(frequency)); // Set over-read character let orc = config.orc; - r.orc.write(|w| unsafe { w.orc().bits(orc) }); + r.orc().write(|w| w.set_orc(orc)); Ok(()) } diff --git a/embassy-nrf/src/spis.rs b/embassy-nrf/src/spis.rs index 60f4c9865..a363e5909 100644 --- a/embassy-nrf/src/spis.rs +++ b/embassy-nrf/src/spis.rs @@ -8,14 +8,16 @@ use core::task::Poll; use embassy_embedded_hal::SetConfig; use embassy_hal_internal::{into_ref, PeripheralRef}; +use embassy_sync::waitqueue::AtomicWaker; pub use embedded_hal_02::spi::{Mode, Phase, Polarity, MODE_0, MODE_1, MODE_2, MODE_3}; -pub use pac::spis0::config::ORDER_A as BitOrder; +pub use pac::spis::vals::Order as BitOrder; -use crate::chip::FORCE_COPY_BUFFER_SIZE; -use crate::gpio::sealed::Pin as _; -use crate::gpio::{self, AnyPin, Pin as GpioPin}; +use crate::chip::{EASY_DMA_SIZE, FORCE_COPY_BUFFER_SIZE}; +use crate::gpio::{self, convert_drive, AnyPin, OutputDrive, Pin as GpioPin, SealedPin as _}; use crate::interrupt::typelevel::Interrupt; -use crate::util::{slice_in_ram_or, slice_ptr_parts, slice_ptr_parts_mut}; +use crate::pac::gpio::vals as gpiovals; +use crate::pac::spis::vals; +use crate::util::slice_in_ram_or; use crate::{interrupt, pac, Peripheral}; /// SPIS error @@ -54,6 +56,9 @@ pub struct Config { /// Automatically make the firmware side acquire the semaphore on transfer end. pub auto_acquire: bool, + + /// Drive strength for the MISO line. + pub miso_drive: OutputDrive, } impl Default for Config { @@ -64,6 +69,7 @@ impl Default for Config { orc: 0x00, def: 0x00, auto_acquire: true, + miso_drive: OutputDrive::HighDrive, } } } @@ -78,14 +84,14 @@ impl interrupt::typelevel::Handler for InterruptHandl let r = T::regs(); let s = T::state(); - if r.events_end.read().bits() != 0 { + if r.events_end().read() != 0 { s.waker.wake(); - r.intenclr.write(|w| w.end().clear()); + r.intenclr().write(|w| w.set_end(true)); } - if r.events_acquired.read().bits() != 0 { + if r.events_acquired().read() != 0 { s.waker.wake(); - r.intenclr.write(|w| w.acquired().clear()); + r.intenclr().write(|w| w.set_acquired(true)); } } } @@ -184,23 +190,26 @@ impl<'d, T: Instance> Spis<'d, T> { let r = T::regs(); // Configure pins. - cs.conf().write(|w| w.input().connect().drive().h0h1()); - r.psel.csn.write(|w| unsafe { w.bits(cs.psel_bits()) }); + cs.conf().write(|w| w.set_input(gpiovals::Input::CONNECT)); + r.psel().csn().write_value(cs.psel_bits()); if let Some(sck) = &sck { - sck.conf().write(|w| w.input().connect().drive().h0h1()); - r.psel.sck.write(|w| unsafe { w.bits(sck.psel_bits()) }); + sck.conf().write(|w| w.set_input(gpiovals::Input::CONNECT)); + r.psel().sck().write_value(sck.psel_bits()); } if let Some(mosi) = &mosi { - mosi.conf().write(|w| w.input().connect().drive().h0h1()); - r.psel.mosi.write(|w| unsafe { w.bits(mosi.psel_bits()) }); + mosi.conf().write(|w| w.set_input(gpiovals::Input::CONNECT)); + r.psel().mosi().write_value(mosi.psel_bits()); } if let Some(miso) = &miso { - miso.conf().write(|w| w.dir().output().drive().h0h1()); - r.psel.miso.write(|w| unsafe { w.bits(miso.psel_bits()) }); + miso.conf().write(|w| { + w.set_dir(gpiovals::Dir::OUTPUT); + w.set_drive(convert_drive(config.miso_drive)) + }); + r.psel().miso().write_value(miso.psel_bits()); } // Enable SPIS instance. - r.enable.write(|w| w.enable().enabled()); + r.enable().write(|w| w.set_enable(vals::Enable::ENABLED)); let mut spis = Self { _p: spis }; @@ -208,7 +217,7 @@ impl<'d, T: Instance> Spis<'d, T> { Self::set_config(&mut spis, &config).unwrap(); // Disable all events interrupts. - r.intenclr.write(|w| unsafe { w.bits(0xFFFF_FFFF) }); + r.intenclr().write(|w| w.0 = 0xFFFF_FFFF); T::Interrupt::unpend(); unsafe { T::Interrupt::enable() }; @@ -226,20 +235,24 @@ impl<'d, T: Instance> Spis<'d, T> { let r = T::regs(); // Set up the DMA write. - let (ptr, len) = slice_ptr_parts(tx); - r.txd.ptr.write(|w| unsafe { w.ptr().bits(ptr as _) }); - r.txd.maxcnt.write(|w| unsafe { w.maxcnt().bits(len as _) }); + if tx.len() > EASY_DMA_SIZE { + return Err(Error::TxBufferTooLong); + } + r.txd().ptr().write_value(tx as *const u8 as _); + r.txd().maxcnt().write(|w| w.set_maxcnt(tx.len() as _)); // Set up the DMA read. - let (ptr, len) = slice_ptr_parts_mut(rx); - r.rxd.ptr.write(|w| unsafe { w.ptr().bits(ptr as _) }); - r.rxd.maxcnt.write(|w| unsafe { w.maxcnt().bits(len as _) }); + if rx.len() > EASY_DMA_SIZE { + return Err(Error::RxBufferTooLong); + } + r.rxd().ptr().write_value(rx as *mut u8 as _); + r.rxd().maxcnt().write(|w| w.set_maxcnt(rx.len() as _)); // Reset end event. - r.events_end.reset(); + r.events_end().write_value(0); // Release the semaphore. - r.tasks_release.write(|w| unsafe { w.bits(1) }); + r.tasks_release().write_value(1); Ok(()) } @@ -249,20 +262,20 @@ impl<'d, T: Instance> Spis<'d, T> { let r = T::regs(); // Acquire semaphore. - if r.semstat.read().bits() != 1 { - r.events_acquired.reset(); - r.tasks_acquire.write(|w| unsafe { w.bits(1) }); + if r.semstat().read().0 != 1 { + r.events_acquired().write_value(0); + r.tasks_acquire().write_value(1); // Wait until CPU has acquired the semaphore. - while r.semstat.read().bits() != 1 {} + while r.semstat().read().0 != 1 {} } self.prepare(rx, tx)?; // Wait for 'end' event. - while r.events_end.read().bits() == 0 {} + while r.events_end().read() == 0 {} - let n_rx = r.rxd.amount.read().bits() as usize; - let n_tx = r.txd.amount.read().bits() as usize; + let n_rx = r.rxd().amount().read().0 as usize; + let n_tx = r.txd().amount().read().0 as usize; compiler_fence(Ordering::SeqCst); @@ -287,22 +300,25 @@ impl<'d, T: Instance> Spis<'d, T> { let s = T::state(); // Clear status register. - r.status.write(|w| w.overflow().clear().overread().clear()); + r.status().write(|w| { + w.set_overflow(true); + w.set_overread(true); + }); // Acquire semaphore. - if r.semstat.read().bits() != 1 { + if r.semstat().read().0 != 1 { // Reset and enable the acquire event. - r.events_acquired.reset(); - r.intenset.write(|w| w.acquired().set()); + r.events_acquired().write_value(0); + r.intenset().write(|w| w.set_acquired(true)); // Request acquiring the SPIS semaphore. - r.tasks_acquire.write(|w| unsafe { w.bits(1) }); + r.tasks_acquire().write_value(1); // Wait until CPU has acquired the semaphore. poll_fn(|cx| { s.waker.register(cx.waker()); - if r.events_acquired.read().bits() == 1 { - r.events_acquired.reset(); + if r.events_acquired().read() == 1 { + r.events_acquired().write_value(0); return Poll::Ready(()); } Poll::Pending @@ -313,19 +329,19 @@ impl<'d, T: Instance> Spis<'d, T> { self.prepare(rx, tx)?; // Wait for 'end' event. - r.intenset.write(|w| w.end().set()); + r.intenset().write(|w| w.set_end(true)); poll_fn(|cx| { s.waker.register(cx.waker()); - if r.events_end.read().bits() != 0 { - r.events_end.reset(); + if r.events_end().read() != 0 { + r.events_end().write_value(0); return Poll::Ready(()); } Poll::Pending }) .await; - let n_rx = r.rxd.amount.read().bits() as usize; - let n_tx = r.txd.amount.read().bits() as usize; + let n_rx = r.rxd().amount().read().0 as usize; + let n_tx = r.txd().amount().read().0 as usize; compiler_fence(Ordering::SeqCst); @@ -424,12 +440,12 @@ impl<'d, T: Instance> Spis<'d, T> { /// Checks if last transaction overread. pub fn is_overread(&mut self) -> bool { - T::regs().status.read().overread().is_present() + T::regs().status().read().overread() } /// Checks if last transaction overflowed. pub fn is_overflow(&mut self) -> bool { - T::regs().status.read().overflow().is_present() + T::regs().status().read().overflow() } } @@ -439,54 +455,49 @@ impl<'d, T: Instance> Drop for Spis<'d, T> { // Disable let r = T::regs(); - r.enable.write(|w| w.enable().disabled()); + r.enable().write(|w| w.set_enable(vals::Enable::DISABLED)); - gpio::deconfigure_pin(r.psel.sck.read().bits()); - gpio::deconfigure_pin(r.psel.csn.read().bits()); - gpio::deconfigure_pin(r.psel.miso.read().bits()); - gpio::deconfigure_pin(r.psel.mosi.read().bits()); + gpio::deconfigure_pin(r.psel().sck().read()); + gpio::deconfigure_pin(r.psel().csn().read()); + gpio::deconfigure_pin(r.psel().miso().read()); + gpio::deconfigure_pin(r.psel().mosi().read()); trace!("spis drop: done"); } } -pub(crate) mod sealed { - use embassy_sync::waitqueue::AtomicWaker; +pub(crate) struct State { + waker: AtomicWaker, +} - use super::*; - - pub struct State { - pub waker: AtomicWaker, - } - - impl State { - pub const fn new() -> Self { - Self { - waker: AtomicWaker::new(), - } +impl State { + pub(crate) const fn new() -> Self { + Self { + waker: AtomicWaker::new(), } } - - pub trait Instance { - fn regs() -> &'static pac::spis0::RegisterBlock; - fn state() -> &'static State; - } +} + +pub(crate) trait SealedInstance { + fn regs() -> pac::spis::Spis; + fn state() -> &'static State; } /// SPIS peripheral instance -pub trait Instance: Peripheral

+ sealed::Instance + 'static { +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static { /// Interrupt for this peripheral. type Interrupt: interrupt::typelevel::Interrupt; } macro_rules! impl_spis { ($type:ident, $pac_type:ident, $irq:ident) => { - impl crate::spis::sealed::Instance for peripherals::$type { - fn regs() -> &'static pac::spis0::RegisterBlock { - unsafe { &*pac::$pac_type::ptr() } + impl crate::spis::SealedInstance for peripherals::$type { + fn regs() -> pac::spis::Spis { + pac::$pac_type } - fn state() -> &'static crate::spis::sealed::State { - static STATE: crate::spis::sealed::State = crate::spis::sealed::State::new(); + fn state() -> &'static crate::spis::State { + static STATE: crate::spis::State = crate::spis::State::new(); &STATE } } @@ -505,44 +516,39 @@ impl<'d, T: Instance> SetConfig for Spis<'d, T> { let r = T::regs(); // Configure mode. let mode = config.mode; - r.config.write(|w| { + r.config().write(|w| { + w.set_order(config.bit_order); match mode { MODE_0 => { - w.order().variant(config.bit_order); - w.cpol().active_high(); - w.cpha().leading(); + w.set_cpol(vals::Cpol::ACTIVE_HIGH); + w.set_cpha(vals::Cpha::LEADING); } MODE_1 => { - w.order().variant(config.bit_order); - w.cpol().active_high(); - w.cpha().trailing(); + w.set_cpol(vals::Cpol::ACTIVE_HIGH); + w.set_cpha(vals::Cpha::TRAILING); } MODE_2 => { - w.order().variant(config.bit_order); - w.cpol().active_low(); - w.cpha().leading(); + w.set_cpol(vals::Cpol::ACTIVE_LOW); + w.set_cpha(vals::Cpha::LEADING); } MODE_3 => { - w.order().variant(config.bit_order); - w.cpol().active_low(); - w.cpha().trailing(); + w.set_cpol(vals::Cpol::ACTIVE_LOW); + w.set_cpha(vals::Cpha::TRAILING); } } - - w }); // Set over-read character. let orc = config.orc; - r.orc.write(|w| unsafe { w.orc().bits(orc) }); + r.orc().write(|w| w.set_orc(orc)); // Set default character. let def = config.def; - r.def.write(|w| unsafe { w.def().bits(def) }); + r.def().write(|w| w.set_def(def)); // Configure auto-acquire on 'transfer end' event. let auto_acquire = config.auto_acquire; - r.shorts.write(|w| w.end_acquire().bit(auto_acquire)); + r.shorts().write(|w| w.set_end_acquire(auto_acquire)); Ok(()) } diff --git a/embassy-nrf/src/temp.rs b/embassy-nrf/src/temp.rs index 5e2998b10..1488c5c24 100644 --- a/embassy-nrf/src/temp.rs +++ b/embassy-nrf/src/temp.rs @@ -19,8 +19,8 @@ pub struct InterruptHandler { impl interrupt::typelevel::Handler for InterruptHandler { unsafe fn on_interrupt() { - let r = unsafe { &*pac::TEMP::PTR }; - r.intenclr.write(|w| w.datardy().clear()); + let r = pac::TEMP; + r.intenclr().write(|w| w.set_datardy(true)); WAKER.wake(); } } @@ -72,21 +72,21 @@ impl<'d> Temp<'d> { // In case the future is dropped, stop the task and reset events. let on_drop = OnDrop::new(|| { let t = Self::regs(); - t.tasks_stop.write(|w| unsafe { w.bits(1) }); - t.events_datardy.reset(); + t.tasks_stop().write_value(1); + t.events_datardy().write_value(0); }); let t = Self::regs(); - t.intenset.write(|w| w.datardy().set()); - unsafe { t.tasks_start.write(|w| w.bits(1)) }; + t.intenset().write(|w| w.set_datardy(true)); + t.tasks_start().write_value(1); let value = poll_fn(|cx| { WAKER.register(cx.waker()); - if t.events_datardy.read().bits() == 0 { - return Poll::Pending; + if t.events_datardy().read() == 0 { + Poll::Pending } else { - t.events_datardy.reset(); - let raw = t.temp.read().bits(); + t.events_datardy().write_value(0); + let raw = t.temp().read(); Poll::Ready(I30F2::from_bits(raw as i32)) } }) @@ -95,7 +95,7 @@ impl<'d> Temp<'d> { value } - fn regs() -> &'static pac::temp::RegisterBlock { - unsafe { &*pac::TEMP::ptr() } + fn regs() -> pac::temp::Temp { + pac::TEMP } } diff --git a/embassy-nrf/src/time_driver.rs b/embassy-nrf/src/time_driver.rs index 3407c9504..e39c4ed52 100644 --- a/embassy-nrf/src/time_driver.rs +++ b/embassy-nrf/src/time_driver.rs @@ -10,8 +10,8 @@ use embassy_time_driver::{AlarmHandle, Driver}; use crate::interrupt::InterruptExt; use crate::{interrupt, pac}; -fn rtc() -> &'static pac::rtc0::RegisterBlock { - unsafe { &*pac::RTC1::ptr() } +fn rtc() -> pac::rtc::Rtc { + pac::RTC1 } /// Calculate the timestamp from the period count and the tick count. @@ -128,19 +128,18 @@ embassy_time_driver::time_driver_impl!(static DRIVER: RtcDriver = RtcDriver { impl RtcDriver { fn init(&'static self, irq_prio: crate::interrupt::Priority) { let r = rtc(); - r.cc[3].write(|w| unsafe { w.bits(0x800000) }); + r.cc(3).write(|w| w.set_compare(0x800000)); - r.intenset.write(|w| { - let w = w.ovrflw().set(); - let w = w.compare3().set(); - w + r.intenset().write(|w| { + w.set_ovrflw(true); + w.set_compare3(true); }); - r.tasks_clear.write(|w| unsafe { w.bits(1) }); - r.tasks_start.write(|w| unsafe { w.bits(1) }); + r.tasks_clear().write_value(1); + r.tasks_start().write_value(1); // Wait for clear - while r.counter.read().bits() != 0 {} + while r.counter().read().0 != 0 {} interrupt::RTC1.set_priority(irq_prio); unsafe { interrupt::RTC1.enable() }; @@ -148,19 +147,19 @@ impl RtcDriver { fn on_interrupt(&self) { let r = rtc(); - if r.events_ovrflw.read().bits() == 1 { - r.events_ovrflw.write(|w| w); + if r.events_ovrflw().read() == 1 { + r.events_ovrflw().write_value(0); self.next_period(); } - if r.events_compare[3].read().bits() == 1 { - r.events_compare[3].write(|w| w); + if r.events_compare(3).read() == 1 { + r.events_compare(3).write_value(0); self.next_period(); } for n in 0..ALARM_COUNT { - if r.events_compare[n].read().bits() == 1 { - r.events_compare[n].write(|w| w); + if r.events_compare(n).read() == 1 { + r.events_compare(n).write_value(0); critical_section::with(|cs| { self.trigger_alarm(n, cs); }) @@ -181,7 +180,7 @@ impl RtcDriver { if at < t + 0xc00000 { // just enable it. `set_alarm` has already set the correct CC val. - r.intenset.write(|w| unsafe { w.bits(compare_n(n)) }); + r.intenset().write(|w| w.0 = compare_n(n)); } } }) @@ -195,7 +194,7 @@ impl RtcDriver { fn trigger_alarm(&self, n: usize, cs: CriticalSection) { let r = rtc(); - r.intenclr.write(|w| unsafe { w.bits(compare_n(n)) }); + r.intenclr().write(|w| w.0 = compare_n(n)); let alarm = &self.alarms.borrow(cs)[n]; alarm.timestamp.set(u64::MAX); @@ -215,7 +214,7 @@ impl Driver for RtcDriver { // `period` MUST be read before `counter`, see comment at the top for details. let period = self.period.load(Ordering::Relaxed); compiler_fence(Ordering::Acquire); - let counter = rtc().counter.read().bits(); + let counter = rtc().counter().read().0; calc_now(period, counter) } @@ -252,7 +251,7 @@ impl Driver for RtcDriver { if timestamp <= t { // If alarm timestamp has passed the alarm will not fire. // Disarm the alarm and return `false` to indicate that. - r.intenclr.write(|w| unsafe { w.bits(compare_n(n)) }); + r.intenclr().write(|w| w.0 = compare_n(n)); alarm.timestamp.set(u64::MAX); @@ -277,15 +276,15 @@ impl Driver for RtcDriver { // by the Alarm trait contract. What's not allowed is triggering alarms *before* their scheduled time, // and we don't do that here. let safe_timestamp = timestamp.max(t + 3); - r.cc[n].write(|w| unsafe { w.bits(safe_timestamp as u32 & 0xFFFFFF) }); + r.cc(n).write(|w| w.set_compare(safe_timestamp as u32 & 0xFFFFFF)); let diff = timestamp - t; if diff < 0xc00000 { - r.intenset.write(|w| unsafe { w.bits(compare_n(n)) }); + r.intenset().write(|w| w.0 = compare_n(n)); } else { // If it's too far in the future, don't setup the compare channel yet. // It will be setup later by `next_period`. - r.intenclr.write(|w| unsafe { w.bits(compare_n(n)) }); + r.intenclr().write(|w| w.0 = compare_n(n)); } true diff --git a/embassy-nrf/src/timer.rs b/embassy-nrf/src/timer.rs index 3c35baee5..a9aeb40fa 100644 --- a/embassy-nrf/src/timer.rs +++ b/embassy-nrf/src/timer.rs @@ -8,38 +8,32 @@ use embassy_hal_internal::{into_ref, PeripheralRef}; +use crate::pac::timer::vals; use crate::ppi::{Event, Task}; use crate::{pac, Peripheral}; -pub(crate) mod sealed { - - use super::*; - - pub trait Instance { - /// The number of CC registers this instance has. - const CCS: usize; - fn regs() -> &'static pac::timer0::RegisterBlock; - } - pub trait ExtendedInstance {} - - pub trait TimerType {} +pub(crate) trait SealedInstance { + /// The number of CC registers this instance has. + const CCS: usize; + fn regs() -> pac::timer::Timer; } /// Basic Timer instance. -pub trait Instance: Peripheral

+ sealed::Instance + 'static + Send { +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static + Send { /// Interrupt for this peripheral. type Interrupt: crate::interrupt::typelevel::Interrupt; } /// Extended timer instance. -pub trait ExtendedInstance: Instance + sealed::ExtendedInstance {} +pub trait ExtendedInstance: Instance {} macro_rules! impl_timer { ($type:ident, $pac_type:ident, $irq:ident, $ccs:literal) => { - impl crate::timer::sealed::Instance for peripherals::$type { + impl crate::timer::SealedInstance for peripherals::$type { const CCS: usize = $ccs; - fn regs() -> &'static pac::timer0::RegisterBlock { - unsafe { &*(pac::$pac_type::ptr() as *const pac::timer0::RegisterBlock) } + fn regs() -> pac::timer::Timer { + unsafe { pac::timer::Timer::from_ptr(pac::$pac_type.as_ptr()) } } } impl crate::timer::Instance for peripherals::$type { @@ -51,7 +45,6 @@ macro_rules! impl_timer { }; ($type:ident, $pac_type:ident, $irq:ident, extended) => { impl_timer!($type, $pac_type, $irq, 6); - impl crate::timer::sealed::ExtendedInstance for peripherals::$type {} impl crate::timer::ExtendedInstance for peripherals::$type {} }; } @@ -122,19 +115,19 @@ impl<'d, T: Instance> Timer<'d, T> { // since changing BITMODE while running can cause 'unpredictable behaviour' according to the specification. this.stop(); - #[cfg(not(feature = "nrf51"))] - if _is_counter { - regs.mode.write(|w| w.mode().low_power_counter()); - } else { - regs.mode.write(|w| w.mode().timer()); - } - - #[cfg(feature = "nrf51")] - regs.mode.write(|w| w.mode().timer()); + regs.mode().write(|w| { + w.set_mode(match _is_counter { + #[cfg(not(feature = "_nrf51"))] + true => vals::Mode::LOW_POWER_COUNTER, + #[cfg(feature = "_nrf51")] + true => vals::Mode::COUNTER, + false => vals::Mode::TIMER, + }) + }); // Make the counter's max value as high as possible. // TODO: is there a reason someone would want to set this lower? - regs.bitmode.write(|w| w.bitmode()._32bit()); + regs.bitmode().write(|w| w.set_bitmode(vals::Bitmode::_32BIT)); // Initialize the counter at 0. this.clear(); @@ -156,38 +149,38 @@ impl<'d, T: Instance> Timer<'d, T> { /// Starts the timer. pub fn start(&self) { - T::regs().tasks_start.write(|w| unsafe { w.bits(1) }) + T::regs().tasks_start().write_value(1) } /// Stops the timer. pub fn stop(&self) { - T::regs().tasks_stop.write(|w| unsafe { w.bits(1) }) + T::regs().tasks_stop().write_value(1) } /// Reset the timer's counter to 0. pub fn clear(&self) { - T::regs().tasks_clear.write(|w| unsafe { w.bits(1) }) + T::regs().tasks_clear().write_value(1) } /// Returns the START task, for use with PPI. /// /// When triggered, this task starts the timer. pub fn task_start(&self) -> Task<'d> { - Task::from_reg(&T::regs().tasks_start) + Task::from_reg(T::regs().tasks_start()) } /// Returns the STOP task, for use with PPI. /// /// When triggered, this task stops the timer. pub fn task_stop(&self) -> Task<'d> { - Task::from_reg(&T::regs().tasks_stop) + Task::from_reg(T::regs().tasks_stop()) } /// Returns the CLEAR task, for use with PPI. /// /// When triggered, this task resets the timer's counter to 0. pub fn task_clear(&self) -> Task<'d> { - Task::from_reg(&T::regs().tasks_clear) + Task::from_reg(T::regs().tasks_clear()) } /// Returns the COUNT task, for use with PPI. @@ -195,7 +188,7 @@ impl<'d, T: Instance> Timer<'d, T> { /// When triggered, this task increments the timer's counter by 1. /// Only works in counter mode. pub fn task_count(&self) -> Task<'d> { - Task::from_reg(&T::regs().tasks_count) + Task::from_reg(T::regs().tasks_count()) } /// Change the timer's frequency. @@ -206,10 +199,10 @@ impl<'d, T: Instance> Timer<'d, T> { self.stop(); T::regs() - .prescaler + .prescaler() // SAFETY: `frequency` is a variant of `Frequency`, // whose values are all in the range of 0-9 (the valid range of `prescaler`). - .write(|w| unsafe { w.prescaler().bits(frequency as u8) }) + .write(|w| w.set_prescaler(frequency as u8)) } /// Returns this timer's `n`th CC register. @@ -242,28 +235,19 @@ pub struct Cc<'d, T: Instance> { impl<'d, T: Instance> Cc<'d, T> { /// Get the current value stored in the register. pub fn read(&self) -> u32 { - #[cfg(not(feature = "nrf51"))] - return T::regs().cc[self.n].read().cc().bits(); - - #[cfg(feature = "nrf51")] - return T::regs().cc[self.n].read().bits(); + return T::regs().cc(self.n).read(); } /// Set the value stored in the register. /// /// `event_compare` will fire when the timer's counter reaches this value. pub fn write(&self, value: u32) { - // SAFETY: there are no invalid values for the CC register. - #[cfg(not(feature = "nrf51"))] - T::regs().cc[self.n].write(|w| unsafe { w.cc().bits(value) }); - - #[cfg(feature = "nrf51")] - T::regs().cc[self.n].write(|w| unsafe { w.bits(value) }); + T::regs().cc(self.n).write_value(value); } /// Capture the current value of the timer's counter in this register, and return it. pub fn capture(&self) -> u32 { - T::regs().tasks_capture[self.n].write(|w| unsafe { w.bits(1) }); + T::regs().tasks_capture(self.n).write_value(1); self.read() } @@ -271,14 +255,14 @@ impl<'d, T: Instance> Cc<'d, T> { /// /// When triggered, this task will capture the current value of the timer's counter in this register. pub fn task_capture(&self) -> Task<'d> { - Task::from_reg(&T::regs().tasks_capture) + Task::from_reg(T::regs().tasks_capture(self.n)) } /// Returns this CC register's COMPARE event, for use with PPI. /// /// This event will fire when the timer's counter reaches the value in this CC register. pub fn event_compare(&self) -> Event<'d> { - Event::from_reg(&T::regs().events_compare[self.n]) + Event::from_reg(T::regs().events_compare(self.n)) } /// Enable the shortcut between this CC register's COMPARE event and the timer's CLEAR task. @@ -287,16 +271,12 @@ impl<'d, T: Instance> Cc<'d, T> { /// /// So, when the timer's counter reaches the value stored in this register, the timer's counter will be reset to 0. pub fn short_compare_clear(&self) { - T::regs() - .shorts - .modify(|r, w| unsafe { w.bits(r.bits() | (1 << self.n)) }) + T::regs().shorts().modify(|w| w.set_compare_clear(self.n, true)) } /// Disable the shortcut between this CC register's COMPARE event and the timer's CLEAR task. pub fn unshort_compare_clear(&self) { - T::regs() - .shorts - .modify(|r, w| unsafe { w.bits(r.bits() & !(1 << self.n)) }) + T::regs().shorts().modify(|w| w.set_compare_clear(self.n, false)) } /// Enable the shortcut between this CC register's COMPARE event and the timer's STOP task. @@ -305,15 +285,11 @@ impl<'d, T: Instance> Cc<'d, T> { /// /// So, when the timer's counter reaches the value stored in this register, the timer will stop counting up. pub fn short_compare_stop(&self) { - T::regs() - .shorts - .modify(|r, w| unsafe { w.bits(r.bits() | (1 << (8 + self.n))) }) + T::regs().shorts().modify(|w| w.set_compare_stop(self.n, true)) } /// Disable the shortcut between this CC register's COMPARE event and the timer's STOP task. pub fn unshort_compare_stop(&self) { - T::regs() - .shorts - .modify(|r, w| unsafe { w.bits(r.bits() & !(1 << (8 + self.n))) }) + T::regs().shorts().modify(|w| w.set_compare_stop(self.n, false)) } } diff --git a/embassy-nrf/src/twim.rs b/embassy-nrf/src/twim.rs index da8e15d02..ebad39df2 100644 --- a/embassy-nrf/src/twim.rs +++ b/embassy-nrf/src/twim.rs @@ -4,6 +4,7 @@ use core::future::{poll_fn, Future}; use core::marker::PhantomData; +use core::mem::MaybeUninit; use core::sync::atomic::compiler_fence; use core::sync::atomic::Ordering::SeqCst; use core::task::Poll; @@ -13,24 +14,17 @@ use embassy_hal_internal::{into_ref, PeripheralRef}; use embassy_sync::waitqueue::AtomicWaker; #[cfg(feature = "time")] use embassy_time::{Duration, Instant}; +use embedded_hal_1::i2c::Operation; +pub use pac::twim::vals::Frequency; use crate::chip::{EASY_DMA_SIZE, FORCE_COPY_BUFFER_SIZE}; use crate::gpio::Pin as GpioPin; use crate::interrupt::typelevel::Interrupt; -use crate::util::{slice_in_ram, slice_in_ram_or}; +use crate::pac::gpio::vals as gpiovals; +use crate::pac::twim::vals; +use crate::util::slice_in_ram; use crate::{gpio, interrupt, pac, Peripheral}; -/// TWI frequency -#[derive(Clone, Copy)] -pub enum Frequency { - /// 100 kbps - K100 = 26738688, - /// 250 kbps - K250 = 67108864, - /// 400 kbps - K400 = 104857600, -} - /// TWIM config. #[non_exhaustive] pub struct Config { @@ -103,13 +97,17 @@ impl interrupt::typelevel::Handler for InterruptHandl let r = T::regs(); let s = T::state(); - if r.events_stopped.read().bits() != 0 { + if r.events_suspended().read() != 0 { s.end_waker.wake(); - r.intenclr.write(|w| w.stopped().clear()); + r.intenclr().write(|w| w.set_suspended(true)); } - if r.events_error.read().bits() != 0 { + if r.events_stopped().read() != 0 { s.end_waker.wake(); - r.intenclr.write(|w| w.error().clear()); + r.intenclr().write(|w| w.set_stopped(true)); + } + if r.events_error().read() != 0 { + s.end_waker.wake(); + r.intenclr().write(|w| w.set_error(true)); } } } @@ -134,38 +132,34 @@ impl<'d, T: Instance> Twim<'d, T> { // Configure pins sda.conf().write(|w| { - w.dir().input(); - w.input().connect(); - if config.sda_high_drive { - w.drive().h0d1(); - } else { - w.drive().s0d1(); - } + w.set_dir(gpiovals::Dir::OUTPUT); + w.set_input(gpiovals::Input::CONNECT); + w.set_drive(match config.sda_high_drive { + true => gpiovals::Drive::H0D1, + false => gpiovals::Drive::S0D1, + }); if config.sda_pullup { - w.pull().pullup(); + w.set_pull(gpiovals::Pull::PULLUP); } - w }); scl.conf().write(|w| { - w.dir().input(); - w.input().connect(); - if config.scl_high_drive { - w.drive().h0d1(); - } else { - w.drive().s0d1(); + w.set_dir(gpiovals::Dir::OUTPUT); + w.set_input(gpiovals::Input::CONNECT); + w.set_drive(match config.scl_high_drive { + true => gpiovals::Drive::H0D1, + false => gpiovals::Drive::S0D1, + }); + if config.sda_pullup { + w.set_pull(gpiovals::Pull::PULLUP); } - if config.scl_pullup { - w.pull().pullup(); - } - w }); // Select pins. - r.psel.sda.write(|w| unsafe { w.bits(sda.psel_bits()) }); - r.psel.scl.write(|w| unsafe { w.bits(scl.psel_bits()) }); + r.psel().sda().write_value(sda.psel_bits()); + r.psel().scl().write_value(scl.psel_bits()); // Enable TWIM instance. - r.enable.write(|w| w.enable().enabled()); + r.enable().write(|w| w.set_enable(vals::Enable::ENABLED)); let mut twim = Self { _p: twim }; @@ -173,7 +167,7 @@ impl<'d, T: Instance> Twim<'d, T> { Self::set_config(&mut twim, &config).unwrap(); // Disable all events interrupts - r.intenclr.write(|w| unsafe { w.bits(0xFFFF_FFFF) }); + r.intenclr().write(|w| w.0 = 0xFFFF_FFFF); T::Interrupt::unpend(); unsafe { T::Interrupt::enable() }; @@ -182,8 +176,22 @@ impl<'d, T: Instance> Twim<'d, T> { } /// Set TX buffer, checking that it is in RAM and has suitable length. - unsafe fn set_tx_buffer(&mut self, buffer: &[u8]) -> Result<(), Error> { - slice_in_ram_or(buffer, Error::BufferNotInRAM)?; + unsafe fn set_tx_buffer( + &mut self, + buffer: &[u8], + ram_buffer: Option<&mut [MaybeUninit; FORCE_COPY_BUFFER_SIZE]>, + ) -> Result<(), Error> { + let buffer = if slice_in_ram(buffer) { + buffer + } else { + let ram_buffer = ram_buffer.ok_or(Error::BufferNotInRAM)?; + trace!("Copying TWIM tx buffer into RAM for DMA"); + let ram_buffer = &mut ram_buffer[..buffer.len()]; + // Inline implementation of the nightly API MaybeUninit::copy_from_slice(ram_buffer, buffer) + let uninit_src: &[MaybeUninit] = unsafe { core::mem::transmute(buffer) }; + ram_buffer.copy_from_slice(uninit_src); + unsafe { &*(ram_buffer as *const [MaybeUninit] as *const [u8]) } + }; if buffer.len() > EASY_DMA_SIZE { return Err(Error::TxBufferTooLong); @@ -191,22 +199,18 @@ impl<'d, T: Instance> Twim<'d, T> { let r = T::regs(); - r.txd.ptr.write(|w| - // We're giving the register a pointer to the stack. Since we're - // waiting for the I2C transaction to end before this stack pointer - // becomes invalid, there's nothing wrong here. - // - // The PTR field is a full 32 bits wide and accepts the full range - // of values. - w.ptr().bits(buffer.as_ptr() as u32)); - r.txd.maxcnt.write(|w| + // We're giving the register a pointer to the stack. Since we're + // waiting for the I2C transaction to end before this stack pointer + // becomes invalid, there's nothing wrong here. + r.txd().ptr().write_value(buffer.as_ptr() as u32); + r.txd().maxcnt().write(|w| // We're giving it the length of the buffer, so no danger of // accessing invalid memory. We have verified that the length of the // buffer fits in an `u8`, so the cast to `u8` is also fine. // // The MAXCNT field is 8 bits wide and accepts the full range of // values. - w.maxcnt().bits(buffer.len() as _)); + w.set_maxcnt(buffer.len() as _)); Ok(()) } @@ -222,15 +226,11 @@ impl<'d, T: Instance> Twim<'d, T> { let r = T::regs(); - r.rxd.ptr.write(|w| - // We're giving the register a pointer to the stack. Since we're - // waiting for the I2C transaction to end before this stack pointer - // becomes invalid, there's nothing wrong here. - // - // The PTR field is a full 32 bits wide and accepts the full range - // of values. - w.ptr().bits(buffer.as_mut_ptr() as u32)); - r.rxd.maxcnt.write(|w| + // We're giving the register a pointer to the stack. Since we're + // waiting for the I2C transaction to end before this stack pointer + // becomes invalid, there's nothing wrong here. + r.rxd().ptr().write_value(buffer.as_mut_ptr() as u32); + r.rxd().maxcnt().write(|w| // We're giving it the length of the buffer, so no danger of // accessing invalid memory. We have verified that the length of the // buffer fits in an `u8`, so the cast to the type of maxcnt @@ -240,29 +240,32 @@ impl<'d, T: Instance> Twim<'d, T> { // type than a u8, so we use a `_` cast rather than a `u8` cast. // The MAXCNT field is thus at least 8 bits wide and accepts the // full range of values that fit in a `u8`. - w.maxcnt().bits(buffer.len() as _)); + w.set_maxcnt(buffer.len() as _)); Ok(()) } fn clear_errorsrc(&mut self) { let r = T::regs(); - r.errorsrc - .write(|w| w.anack().bit(true).dnack().bit(true).overrun().bit(true)); + r.errorsrc().write(|w| { + w.set_anack(true); + w.set_dnack(true); + w.set_overrun(true); + }); } /// Get Error instance, if any occurred. fn check_errorsrc(&self) -> Result<(), Error> { let r = T::regs(); - let err = r.errorsrc.read(); - if err.anack().is_received() { + let err = r.errorsrc().read(); + if err.anack() { return Err(Error::AddressNack); } - if err.dnack().is_received() { + if err.dnack() { return Err(Error::DataNack); } - if err.overrun().is_received() { + if err.overrun() { return Err(Error::Overrun); } Ok(()) @@ -270,7 +273,7 @@ impl<'d, T: Instance> Twim<'d, T> { fn check_rx(&self, len: usize) -> Result<(), Error> { let r = T::regs(); - if r.rxd.amount.read().bits() != len as u32 { + if r.rxd().amount().read().0 != len as u32 { Err(Error::Receive) } else { Ok(()) @@ -279,7 +282,7 @@ impl<'d, T: Instance> Twim<'d, T> { fn check_tx(&self, len: usize) -> Result<(), Error> { let r = T::regs(); - if r.txd.amount.read().bits() != len as u32 { + if r.txd().amount().read().0 != len as u32 { Err(Error::Transmit) } else { Ok(()) @@ -290,13 +293,14 @@ impl<'d, T: Instance> Twim<'d, T> { fn blocking_wait(&mut self) { let r = T::regs(); loop { - if r.events_stopped.read().bits() != 0 { - r.events_stopped.reset(); + if r.events_suspended().read() != 0 || r.events_stopped().read() != 0 { + r.events_suspended().write_value(0); + r.events_stopped().write_value(0); break; } - if r.events_error.read().bits() != 0 { - r.events_error.reset(); - r.tasks_stop.write(|w| unsafe { w.bits(1) }); + if r.events_error().read() != 0 { + r.events_error().write_value(0); + r.tasks_stop().write_value(1); } } } @@ -307,16 +311,16 @@ impl<'d, T: Instance> Twim<'d, T> { let r = T::regs(); let deadline = Instant::now() + timeout; loop { - if r.events_stopped.read().bits() != 0 { - r.events_stopped.reset(); + if r.events_suspended().read() != 0 || r.events_stopped().read() != 0 { + r.events_stopped().write_value(0); break; } - if r.events_error.read().bits() != 0 { - r.events_error.reset(); - r.tasks_stop.write(|w| unsafe { w.bits(1) }); + if r.events_error().read() != 0 { + r.events_error().write_value(0); + r.tasks_stop().write_value(1); } if Instant::now() > deadline { - r.tasks_stop.write(|w| unsafe { w.bits(1) }); + r.tasks_stop().write_value(1); return Err(Error::Timeout); } } @@ -331,184 +335,336 @@ impl<'d, T: Instance> Twim<'d, T> { let s = T::state(); s.end_waker.register(cx.waker()); - if r.events_stopped.read().bits() != 0 { - r.events_stopped.reset(); + if r.events_suspended().read() != 0 || r.events_stopped().read() != 0 { + r.events_stopped().write_value(0); return Poll::Ready(()); } // stop if an error occurred - if r.events_error.read().bits() != 0 { - r.events_error.reset(); - r.tasks_stop.write(|w| unsafe { w.bits(1) }); + if r.events_error().read() != 0 { + r.events_error().write_value(0); + r.tasks_stop().write_value(1); } Poll::Pending }) } - fn setup_write_from_ram(&mut self, address: u8, buffer: &[u8], inten: bool) -> Result<(), Error> { - let r = T::regs(); - - compiler_fence(SeqCst); - - r.address.write(|w| unsafe { w.address().bits(address) }); - - // Set up the DMA write. - unsafe { self.set_tx_buffer(buffer)? }; - - // Clear events - r.events_stopped.reset(); - r.events_error.reset(); - r.events_lasttx.reset(); - self.clear_errorsrc(); - - if inten { - r.intenset.write(|w| w.stopped().set().error().set()); - } else { - r.intenclr.write(|w| w.stopped().clear().error().clear()); - } - - // Start write operation. - r.shorts.write(|w| w.lasttx_stop().enabled()); - r.tasks_starttx.write(|w| unsafe { w.bits(1) }); - if buffer.len() == 0 { - // With a zero-length buffer, LASTTX doesn't fire (because there's no last byte!), so do the STOP ourselves. - r.tasks_stop.write(|w| unsafe { w.bits(1) }); - } - Ok(()) - } - - fn setup_read(&mut self, address: u8, buffer: &mut [u8], inten: bool) -> Result<(), Error> { - let r = T::regs(); - - compiler_fence(SeqCst); - - r.address.write(|w| unsafe { w.address().bits(address) }); - - // Set up the DMA read. - unsafe { self.set_rx_buffer(buffer)? }; - - // Clear events - r.events_stopped.reset(); - r.events_error.reset(); - self.clear_errorsrc(); - - if inten { - r.intenset.write(|w| w.stopped().set().error().set()); - } else { - r.intenclr.write(|w| w.stopped().clear().error().clear()); - } - - // Start read operation. - r.shorts.write(|w| w.lastrx_stop().enabled()); - r.tasks_startrx.write(|w| unsafe { w.bits(1) }); - if buffer.len() == 0 { - // With a zero-length buffer, LASTRX doesn't fire (because there's no last byte!), so do the STOP ourselves. - r.tasks_stop.write(|w| unsafe { w.bits(1) }); - } - Ok(()) - } - - fn setup_write_read_from_ram( + fn setup_operations( &mut self, address: u8, - wr_buffer: &[u8], - rd_buffer: &mut [u8], + operations: &mut [Operation<'_>], + tx_ram_buffer: Option<&mut [MaybeUninit; FORCE_COPY_BUFFER_SIZE]>, + last_op: Option<&Operation<'_>>, inten: bool, - ) -> Result<(), Error> { + ) -> Result { let r = T::regs(); compiler_fence(SeqCst); - r.address.write(|w| unsafe { w.address().bits(address) }); + r.address().write(|w| w.set_address(address)); - // Set up DMA buffers. - unsafe { - self.set_tx_buffer(wr_buffer)?; - self.set_rx_buffer(rd_buffer)?; - } - - // Clear events - r.events_stopped.reset(); - r.events_error.reset(); + r.events_suspended().write_value(0); + r.events_stopped().write_value(0); + r.events_error().write_value(0); self.clear_errorsrc(); if inten { - r.intenset.write(|w| w.stopped().set().error().set()); + r.intenset().write(|w| { + w.set_suspended(true); + w.set_stopped(true); + w.set_error(true); + }); } else { - r.intenclr.write(|w| w.stopped().clear().error().clear()); + r.intenclr().write(|w| { + w.set_suspended(true); + w.set_stopped(true); + w.set_error(true); + }); } - // Start write+read operation. - r.shorts.write(|w| { - w.lasttx_startrx().enabled(); - w.lastrx_stop().enabled(); - w - }); - r.tasks_starttx.write(|w| unsafe { w.bits(1) }); - if wr_buffer.len() == 0 && rd_buffer.len() == 0 { - // With a zero-length buffer, LASTRX/LASTTX doesn't fire (because there's no last byte!), so do the STOP ourselves. - // TODO handle when only one of the buffers is zero length - r.tasks_stop.write(|w| unsafe { w.bits(1) }); - } + assert!(!operations.is_empty()); + match operations { + [Operation::Read(_), Operation::Read(_), ..] => { + panic!("Consecutive read operations are not supported!") + } + [Operation::Read(rd_buffer), Operation::Write(wr_buffer), rest @ ..] => { + let stop = rest.is_empty(); + // Set up DMA buffers. + unsafe { + self.set_tx_buffer(wr_buffer, tx_ram_buffer)?; + self.set_rx_buffer(rd_buffer)?; + } + + r.shorts().write(|w| { + w.set_lastrx_starttx(true); + if stop { + w.set_lasttx_stop(true); + } else { + w.set_lasttx_suspend(true); + } + }); + + // Start read+write operation. + r.tasks_startrx().write_value(1); + if last_op.is_some() { + r.tasks_resume().write_value(1); + } + + // TODO: Handle empty write buffer + if rd_buffer.is_empty() { + // With a zero-length buffer, LASTRX doesn't fire (because there's no last byte!), so do the STARTTX ourselves. + r.tasks_starttx().write_value(1); + } + + Ok(2) + } + [Operation::Read(buffer)] => { + // Set up DMA buffers. + unsafe { + self.set_rx_buffer(buffer)?; + } + + r.shorts().write(|w| w.set_lastrx_stop(true)); + + // Start read operation. + r.tasks_startrx().write_value(1); + if last_op.is_some() { + r.tasks_resume().write_value(1); + } + + if buffer.is_empty() { + // With a zero-length buffer, LASTRX doesn't fire (because there's no last byte!), so do the STOP ourselves. + r.tasks_stop().write_value(1); + } + + Ok(1) + } + [Operation::Write(wr_buffer), Operation::Read(rd_buffer)] + if !wr_buffer.is_empty() && !rd_buffer.is_empty() => + { + // Set up DMA buffers. + unsafe { + self.set_tx_buffer(wr_buffer, tx_ram_buffer)?; + self.set_rx_buffer(rd_buffer)?; + } + + // Start write+read operation. + r.shorts().write(|w| { + w.set_lasttx_startrx(true); + w.set_lastrx_stop(true); + }); + + r.tasks_starttx().write_value(1); + if last_op.is_some() { + r.tasks_resume().write_value(1); + } + + Ok(2) + } + [Operation::Write(buffer), rest @ ..] => { + let stop = rest.is_empty(); + + // Set up DMA buffers. + unsafe { + self.set_tx_buffer(buffer, tx_ram_buffer)?; + } + + // Start write operation. + r.shorts().write(|w| { + if stop { + w.set_lasttx_stop(true); + } else { + w.set_lasttx_suspend(true); + } + }); + + r.tasks_starttx().write_value(1); + if last_op.is_some() { + r.tasks_resume().write_value(1); + } + + if buffer.is_empty() { + // With a zero-length buffer, LASTTX doesn't fire (because there's no last byte!), so do the STOP/SUSPEND ourselves. + if stop { + r.tasks_stop().write_value(1); + } else { + r.tasks_suspend().write_value(1); + } + } + + Ok(1) + } + [] => unreachable!(), + } + } + + fn check_operations(&mut self, operations: &[Operation<'_>]) -> Result<(), Error> { + compiler_fence(SeqCst); + self.check_errorsrc()?; + + assert!(operations.len() == 1 || operations.len() == 2); + match operations { + [Operation::Read(rd_buffer), Operation::Write(wr_buffer)] + | [Operation::Write(wr_buffer), Operation::Read(rd_buffer)] => { + self.check_rx(rd_buffer.len())?; + self.check_tx(wr_buffer.len())?; + } + [Operation::Read(buffer)] => { + self.check_rx(buffer.len())?; + } + [Operation::Write(buffer), ..] => { + self.check_tx(buffer.len())?; + } + _ => unreachable!(), + } Ok(()) } - fn setup_write_read( - &mut self, - address: u8, - wr_buffer: &[u8], - rd_buffer: &mut [u8], - inten: bool, - ) -> Result<(), Error> { - match self.setup_write_read_from_ram(address, wr_buffer, rd_buffer, inten) { - Ok(_) => Ok(()), - Err(Error::BufferNotInRAM) => { - trace!("Copying TWIM tx buffer into RAM for DMA"); - let tx_ram_buf = &mut [0; FORCE_COPY_BUFFER_SIZE][..wr_buffer.len()]; - tx_ram_buf.copy_from_slice(wr_buffer); - self.setup_write_read_from_ram(address, &tx_ram_buf, rd_buffer, inten) - } - Err(error) => Err(error), + // =========================================== + + /// Execute the provided operations on the I2C bus. + /// + /// Each buffer must have a length of at most 255 bytes on the nRF52832 + /// and at most 65535 bytes on the nRF52840. + /// + /// Consecutive `Operation::Read`s are not supported due to hardware + /// limitations. + /// + /// An `Operation::Write` following an `Operation::Read` must have a + /// non-empty buffer. + pub fn blocking_transaction(&mut self, address: u8, mut operations: &mut [Operation<'_>]) -> Result<(), Error> { + let mut tx_ram_buffer = [MaybeUninit::uninit(); FORCE_COPY_BUFFER_SIZE]; + let mut last_op = None; + while !operations.is_empty() { + let ops = self.setup_operations(address, operations, Some(&mut tx_ram_buffer), last_op, false)?; + let (in_progress, rest) = operations.split_at_mut(ops); + self.blocking_wait(); + self.check_operations(in_progress)?; + last_op = in_progress.last(); + operations = rest; } + Ok(()) } - fn setup_write(&mut self, address: u8, wr_buffer: &[u8], inten: bool) -> Result<(), Error> { - match self.setup_write_from_ram(address, wr_buffer, inten) { - Ok(_) => Ok(()), - Err(Error::BufferNotInRAM) => { - trace!("Copying TWIM tx buffer into RAM for DMA"); - let tx_ram_buf = &mut [0; FORCE_COPY_BUFFER_SIZE][..wr_buffer.len()]; - tx_ram_buf.copy_from_slice(wr_buffer); - self.setup_write_from_ram(address, &tx_ram_buf, inten) - } - Err(error) => Err(error), + /// Same as [`blocking_transaction`](Twim::blocking_transaction) but will fail instead of copying data into RAM. Consult the module level documentation to learn more. + pub fn blocking_transaction_from_ram( + &mut self, + address: u8, + mut operations: &mut [Operation<'_>], + ) -> Result<(), Error> { + let mut last_op = None; + while !operations.is_empty() { + let ops = self.setup_operations(address, operations, None, last_op, false)?; + let (in_progress, rest) = operations.split_at_mut(ops); + self.blocking_wait(); + self.check_operations(in_progress)?; + last_op = in_progress.last(); + operations = rest; } + Ok(()) } + /// Execute the provided operations on the I2C bus with timeout. + /// + /// See [`blocking_transaction`]. + #[cfg(feature = "time")] + pub fn blocking_transaction_timeout( + &mut self, + address: u8, + mut operations: &mut [Operation<'_>], + timeout: Duration, + ) -> Result<(), Error> { + let mut tx_ram_buffer = [MaybeUninit::uninit(); FORCE_COPY_BUFFER_SIZE]; + let mut last_op = None; + while !operations.is_empty() { + let ops = self.setup_operations(address, operations, Some(&mut tx_ram_buffer), last_op, false)?; + let (in_progress, rest) = operations.split_at_mut(ops); + self.blocking_wait_timeout(timeout)?; + self.check_operations(in_progress)?; + last_op = in_progress.last(); + operations = rest; + } + Ok(()) + } + + /// Same as [`blocking_transaction_timeout`](Twim::blocking_transaction_timeout) but will fail instead of copying data into RAM. Consult the module level documentation to learn more. + #[cfg(feature = "time")] + pub fn blocking_transaction_from_ram_timeout( + &mut self, + address: u8, + mut operations: &mut [Operation<'_>], + timeout: Duration, + ) -> Result<(), Error> { + let mut last_op = None; + while !operations.is_empty() { + let ops = self.setup_operations(address, operations, None, last_op, false)?; + let (in_progress, rest) = operations.split_at_mut(ops); + self.blocking_wait_timeout(timeout)?; + self.check_operations(in_progress)?; + last_op = in_progress.last(); + operations = rest; + } + Ok(()) + } + + /// Execute the provided operations on the I2C bus. + /// + /// Each buffer must have a length of at most 255 bytes on the nRF52832 + /// and at most 65535 bytes on the nRF52840. + /// + /// Consecutive `Operation::Read`s are not supported due to hardware + /// limitations. + /// + /// An `Operation::Write` following an `Operation::Read` must have a + /// non-empty buffer. + pub async fn transaction(&mut self, address: u8, mut operations: &mut [Operation<'_>]) -> Result<(), Error> { + let mut tx_ram_buffer = [MaybeUninit::uninit(); FORCE_COPY_BUFFER_SIZE]; + let mut last_op = None; + while !operations.is_empty() { + let ops = self.setup_operations(address, operations, Some(&mut tx_ram_buffer), last_op, true)?; + let (in_progress, rest) = operations.split_at_mut(ops); + self.async_wait().await; + self.check_operations(in_progress)?; + last_op = in_progress.last(); + operations = rest; + } + Ok(()) + } + + /// Same as [`transaction`](Twim::transaction) but will fail instead of copying data into RAM. Consult the module level documentation to learn more. + pub async fn transaction_from_ram( + &mut self, + address: u8, + mut operations: &mut [Operation<'_>], + ) -> Result<(), Error> { + let mut last_op = None; + while !operations.is_empty() { + let ops = self.setup_operations(address, operations, None, last_op, true)?; + let (in_progress, rest) = operations.split_at_mut(ops); + self.async_wait().await; + self.check_operations(in_progress)?; + last_op = in_progress.last(); + operations = rest; + } + Ok(()) + } + + // =========================================== + /// Write to an I2C slave. /// /// The buffer must have a length of at most 255 bytes on the nRF52832 /// and at most 65535 bytes on the nRF52840. pub fn blocking_write(&mut self, address: u8, buffer: &[u8]) -> Result<(), Error> { - self.setup_write(address, buffer, false)?; - self.blocking_wait(); - compiler_fence(SeqCst); - self.check_errorsrc()?; - self.check_tx(buffer.len())?; - Ok(()) + self.blocking_transaction(address, &mut [Operation::Write(buffer)]) } /// Same as [`blocking_write`](Twim::blocking_write) but will fail instead of copying data into RAM. Consult the module level documentation to learn more. pub fn blocking_write_from_ram(&mut self, address: u8, buffer: &[u8]) -> Result<(), Error> { - self.setup_write_from_ram(address, buffer, false)?; - self.blocking_wait(); - compiler_fence(SeqCst); - self.check_errorsrc()?; - self.check_tx(buffer.len())?; - Ok(()) + self.blocking_transaction_from_ram(address, &mut [Operation::Write(buffer)]) } /// Read from an I2C slave. @@ -516,12 +672,7 @@ impl<'d, T: Instance> Twim<'d, T> { /// The buffer must have a length of at most 255 bytes on the nRF52832 /// and at most 65535 bytes on the nRF52840. pub fn blocking_read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Error> { - self.setup_read(address, buffer, false)?; - self.blocking_wait(); - compiler_fence(SeqCst); - self.check_errorsrc()?; - self.check_rx(buffer.len())?; - Ok(()) + self.blocking_transaction(address, &mut [Operation::Read(buffer)]) } /// Write data to an I2C slave, then read data from the slave without @@ -530,13 +681,7 @@ impl<'d, T: Instance> Twim<'d, T> { /// The buffers must have a length of at most 255 bytes on the nRF52832 /// and at most 65535 bytes on the nRF52840. pub fn blocking_write_read(&mut self, address: u8, wr_buffer: &[u8], rd_buffer: &mut [u8]) -> Result<(), Error> { - self.setup_write_read(address, wr_buffer, rd_buffer, false)?; - self.blocking_wait(); - compiler_fence(SeqCst); - self.check_errorsrc()?; - self.check_tx(wr_buffer.len())?; - self.check_rx(rd_buffer.len())?; - Ok(()) + self.blocking_transaction(address, &mut [Operation::Write(wr_buffer), Operation::Read(rd_buffer)]) } /// Same as [`blocking_write_read`](Twim::blocking_write_read) but will fail instead of copying data into RAM. Consult the module level documentation to learn more. @@ -546,13 +691,7 @@ impl<'d, T: Instance> Twim<'d, T> { wr_buffer: &[u8], rd_buffer: &mut [u8], ) -> Result<(), Error> { - self.setup_write_read_from_ram(address, wr_buffer, rd_buffer, false)?; - self.blocking_wait(); - compiler_fence(SeqCst); - self.check_errorsrc()?; - self.check_tx(wr_buffer.len())?; - self.check_rx(rd_buffer.len())?; - Ok(()) + self.blocking_transaction_from_ram(address, &mut [Operation::Write(wr_buffer), Operation::Read(rd_buffer)]) } // =========================================== @@ -562,12 +701,7 @@ impl<'d, T: Instance> Twim<'d, T> { /// See [`blocking_write`]. #[cfg(feature = "time")] pub fn blocking_write_timeout(&mut self, address: u8, buffer: &[u8], timeout: Duration) -> Result<(), Error> { - self.setup_write(address, buffer, false)?; - self.blocking_wait_timeout(timeout)?; - compiler_fence(SeqCst); - self.check_errorsrc()?; - self.check_tx(buffer.len())?; - Ok(()) + self.blocking_transaction_timeout(address, &mut [Operation::Write(buffer)], timeout) } /// Same as [`blocking_write`](Twim::blocking_write) but will fail instead of copying data into RAM. Consult the module level documentation to learn more. @@ -578,12 +712,7 @@ impl<'d, T: Instance> Twim<'d, T> { buffer: &[u8], timeout: Duration, ) -> Result<(), Error> { - self.setup_write_from_ram(address, buffer, false)?; - self.blocking_wait_timeout(timeout)?; - compiler_fence(SeqCst); - self.check_errorsrc()?; - self.check_tx(buffer.len())?; - Ok(()) + self.blocking_transaction_from_ram_timeout(address, &mut [Operation::Write(buffer)], timeout) } /// Read from an I2C slave. @@ -592,12 +721,7 @@ impl<'d, T: Instance> Twim<'d, T> { /// and at most 65535 bytes on the nRF52840. #[cfg(feature = "time")] pub fn blocking_read_timeout(&mut self, address: u8, buffer: &mut [u8], timeout: Duration) -> Result<(), Error> { - self.setup_read(address, buffer, false)?; - self.blocking_wait_timeout(timeout)?; - compiler_fence(SeqCst); - self.check_errorsrc()?; - self.check_rx(buffer.len())?; - Ok(()) + self.blocking_transaction_timeout(address, &mut [Operation::Read(buffer)], timeout) } /// Write data to an I2C slave, then read data from the slave without @@ -613,13 +737,11 @@ impl<'d, T: Instance> Twim<'d, T> { rd_buffer: &mut [u8], timeout: Duration, ) -> Result<(), Error> { - self.setup_write_read(address, wr_buffer, rd_buffer, false)?; - self.blocking_wait_timeout(timeout)?; - compiler_fence(SeqCst); - self.check_errorsrc()?; - self.check_tx(wr_buffer.len())?; - self.check_rx(rd_buffer.len())?; - Ok(()) + self.blocking_transaction_timeout( + address, + &mut [Operation::Write(wr_buffer), Operation::Read(rd_buffer)], + timeout, + ) } /// Same as [`blocking_write_read`](Twim::blocking_write_read) but will fail instead of copying data into RAM. Consult the module level documentation to learn more. @@ -631,13 +753,11 @@ impl<'d, T: Instance> Twim<'d, T> { rd_buffer: &mut [u8], timeout: Duration, ) -> Result<(), Error> { - self.setup_write_read_from_ram(address, wr_buffer, rd_buffer, false)?; - self.blocking_wait_timeout(timeout)?; - compiler_fence(SeqCst); - self.check_errorsrc()?; - self.check_tx(wr_buffer.len())?; - self.check_rx(rd_buffer.len())?; - Ok(()) + self.blocking_transaction_from_ram_timeout( + address, + &mut [Operation::Write(wr_buffer), Operation::Read(rd_buffer)], + timeout, + ) } // =========================================== @@ -647,12 +767,7 @@ impl<'d, T: Instance> Twim<'d, T> { /// The buffer must have a length of at most 255 bytes on the nRF52832 /// and at most 65535 bytes on the nRF52840. pub async fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Error> { - self.setup_read(address, buffer, true)?; - self.async_wait().await; - compiler_fence(SeqCst); - self.check_errorsrc()?; - self.check_rx(buffer.len())?; - Ok(()) + self.transaction(address, &mut [Operation::Read(buffer)]).await } /// Write to an I2C slave. @@ -660,22 +775,13 @@ impl<'d, T: Instance> Twim<'d, T> { /// The buffer must have a length of at most 255 bytes on the nRF52832 /// and at most 65535 bytes on the nRF52840. pub async fn write(&mut self, address: u8, buffer: &[u8]) -> Result<(), Error> { - self.setup_write(address, buffer, true)?; - self.async_wait().await; - compiler_fence(SeqCst); - self.check_errorsrc()?; - self.check_tx(buffer.len())?; - Ok(()) + self.transaction(address, &mut [Operation::Write(buffer)]).await } /// Same as [`write`](Twim::write) but will fail instead of copying data into RAM. Consult the module level documentation to learn more. pub async fn write_from_ram(&mut self, address: u8, buffer: &[u8]) -> Result<(), Error> { - self.setup_write_from_ram(address, buffer, true)?; - self.async_wait().await; - compiler_fence(SeqCst); - self.check_errorsrc()?; - self.check_tx(buffer.len())?; - Ok(()) + self.transaction_from_ram(address, &mut [Operation::Write(buffer)]) + .await } /// Write data to an I2C slave, then read data from the slave without @@ -684,13 +790,8 @@ impl<'d, T: Instance> Twim<'d, T> { /// The buffers must have a length of at most 255 bytes on the nRF52832 /// and at most 65535 bytes on the nRF52840. pub async fn write_read(&mut self, address: u8, wr_buffer: &[u8], rd_buffer: &mut [u8]) -> Result<(), Error> { - self.setup_write_read(address, wr_buffer, rd_buffer, true)?; - self.async_wait().await; - compiler_fence(SeqCst); - self.check_errorsrc()?; - self.check_tx(wr_buffer.len())?; - self.check_rx(rd_buffer.len())?; - Ok(()) + self.transaction(address, &mut [Operation::Write(wr_buffer), Operation::Read(rd_buffer)]) + .await } /// Same as [`write_read`](Twim::write_read) but will fail instead of copying data into RAM. Consult the module level documentation to learn more. @@ -700,13 +801,8 @@ impl<'d, T: Instance> Twim<'d, T> { wr_buffer: &[u8], rd_buffer: &mut [u8], ) -> Result<(), Error> { - self.setup_write_read_from_ram(address, wr_buffer, rd_buffer, true)?; - self.async_wait().await; - compiler_fence(SeqCst); - self.check_errorsrc()?; - self.check_tx(wr_buffer.len())?; - self.check_rx(rd_buffer.len())?; - Ok(()) + self.transaction_from_ram(address, &mut [Operation::Write(wr_buffer), Operation::Read(rd_buffer)]) + .await } } @@ -718,50 +814,47 @@ impl<'a, T: Instance> Drop for Twim<'a, T> { // disable! let r = T::regs(); - r.enable.write(|w| w.enable().disabled()); + r.enable().write(|w| w.set_enable(vals::Enable::DISABLED)); - gpio::deconfigure_pin(r.psel.sda.read().bits()); - gpio::deconfigure_pin(r.psel.scl.read().bits()); + gpio::deconfigure_pin(r.psel().sda().read()); + gpio::deconfigure_pin(r.psel().scl().read()); trace!("twim drop: done"); } } -pub(crate) mod sealed { - use super::*; +pub(crate) struct State { + end_waker: AtomicWaker, +} - pub struct State { - pub end_waker: AtomicWaker, - } - - impl State { - pub const fn new() -> Self { - Self { - end_waker: AtomicWaker::new(), - } +impl State { + pub(crate) const fn new() -> Self { + Self { + end_waker: AtomicWaker::new(), } } - - pub trait Instance { - fn regs() -> &'static pac::twim0::RegisterBlock; - fn state() -> &'static State; - } +} + +pub(crate) trait SealedInstance { + fn regs() -> pac::twim::Twim; + fn state() -> &'static State; } /// TWIM peripheral instance. -pub trait Instance: Peripheral

+ sealed::Instance + 'static { +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static { /// Interrupt for this peripheral. type Interrupt: interrupt::typelevel::Interrupt; } macro_rules! impl_twim { ($type:ident, $pac_type:ident, $irq:ident) => { - impl crate::twim::sealed::Instance for peripherals::$type { - fn regs() -> &'static pac::twim0::RegisterBlock { - unsafe { &*pac::$pac_type::ptr() } + impl crate::twim::SealedInstance for peripherals::$type { + fn regs() -> pac::twim::Twim { + pac::$pac_type } - fn state() -> &'static crate::twim::sealed::State { - static STATE: crate::twim::sealed::State = crate::twim::sealed::State::new(); + fn state() -> &'static crate::twim::State { + static STATE: crate::twim::State = crate::twim::State::new(); &STATE } } @@ -779,24 +872,15 @@ mod eh02 { impl<'a, T: Instance> embedded_hal_02::blocking::i2c::Write for Twim<'a, T> { type Error = Error; - fn write<'w>(&mut self, addr: u8, bytes: &'w [u8]) -> Result<(), Error> { - if slice_in_ram(bytes) { - self.blocking_write(addr, bytes) - } else { - let buf = &mut [0; FORCE_COPY_BUFFER_SIZE][..]; - for chunk in bytes.chunks(FORCE_COPY_BUFFER_SIZE) { - buf[..chunk.len()].copy_from_slice(chunk); - self.blocking_write(addr, &buf[..chunk.len()])?; - } - Ok(()) - } + fn write(&mut self, addr: u8, bytes: &[u8]) -> Result<(), Error> { + self.blocking_write(addr, bytes) } } impl<'a, T: Instance> embedded_hal_02::blocking::i2c::Read for Twim<'a, T> { type Error = Error; - fn read<'w>(&mut self, addr: u8, bytes: &'w mut [u8]) -> Result<(), Error> { + fn read(&mut self, addr: u8, bytes: &mut [u8]) -> Result<(), Error> { self.blocking_read(addr, bytes) } } @@ -835,47 +919,14 @@ impl<'d, T: Instance> embedded_hal_1::i2c::ErrorType for Twim<'d, T> { } impl<'d, T: Instance> embedded_hal_1::i2c::I2c for Twim<'d, T> { - fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Self::Error> { - self.blocking_read(address, buffer) - } - - fn write(&mut self, address: u8, buffer: &[u8]) -> Result<(), Self::Error> { - self.blocking_write(address, buffer) - } - - fn write_read(&mut self, address: u8, wr_buffer: &[u8], rd_buffer: &mut [u8]) -> Result<(), Self::Error> { - self.blocking_write_read(address, wr_buffer, rd_buffer) - } - - fn transaction<'a>( - &mut self, - _address: u8, - _operations: &mut [embedded_hal_1::i2c::Operation<'a>], - ) -> Result<(), Self::Error> { - todo!(); + fn transaction(&mut self, address: u8, operations: &mut [Operation<'_>]) -> Result<(), Self::Error> { + self.blocking_transaction(address, operations) } } impl<'d, T: Instance> embedded_hal_async::i2c::I2c for Twim<'d, T> { - async fn read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Self::Error> { - self.read(address, read).await - } - - async fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Self::Error> { - self.write(address, write).await - } - async fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Self::Error> { - self.write_read(address, write, read).await - } - - async fn transaction( - &mut self, - address: u8, - operations: &mut [embedded_hal_1::i2c::Operation<'_>], - ) -> Result<(), Self::Error> { - let _ = address; - let _ = operations; - todo!() + async fn transaction(&mut self, address: u8, operations: &mut [Operation<'_>]) -> Result<(), Self::Error> { + self.transaction(address, operations).await } } @@ -884,8 +935,7 @@ impl<'d, T: Instance> SetConfig for Twim<'d, T> { type ConfigError = (); fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> { let r = T::regs(); - r.frequency - .write(|w| unsafe { w.frequency().bits(config.frequency as u32) }); + r.frequency().write(|w| w.set_frequency(config.frequency)); Ok(()) } diff --git a/embassy-nrf/src/twis.rs b/embassy-nrf/src/twis.rs index c6c020557..60de2ed9d 100644 --- a/embassy-nrf/src/twis.rs +++ b/embassy-nrf/src/twis.rs @@ -16,6 +16,8 @@ use embassy_time::{Duration, Instant}; use crate::chip::{EASY_DMA_SIZE, FORCE_COPY_BUFFER_SIZE}; use crate::gpio::Pin as GpioPin; use crate::interrupt::typelevel::Interrupt; +use crate::pac::gpio::vals as gpiovals; +use crate::pac::twis::vals; use crate::util::slice_in_ram_or; use crate::{gpio, interrupt, pac, Peripheral}; @@ -119,17 +121,20 @@ impl interrupt::typelevel::Handler for InterruptHandl let r = T::regs(); let s = T::state(); - if r.events_read.read().bits() != 0 || r.events_write.read().bits() != 0 { + if r.events_read().read() != 0 || r.events_write().read() != 0 { s.waker.wake(); - r.intenclr.modify(|_r, w| w.read().clear().write().clear()); + r.intenclr().write(|w| { + w.set_read(true); + w.set_write(true); + }); } - if r.events_stopped.read().bits() != 0 { + if r.events_stopped().read() != 0 { s.waker.wake(); - r.intenclr.modify(|_r, w| w.stopped().clear()); + r.intenclr().write(|w| w.set_stopped(true)); } - if r.events_error.read().bits() != 0 { + if r.events_error().read() != 0 { s.waker.wake(); - r.intenclr.modify(|_r, w| w.error().clear()); + r.intenclr().write(|w| w.set_error(true)); } } } @@ -154,55 +159,51 @@ impl<'d, T: Instance> Twis<'d, T> { // Configure pins sda.conf().write(|w| { - w.dir().input(); - w.input().connect(); - if config.sda_high_drive { - w.drive().h0d1(); - } else { - w.drive().s0d1(); - } + w.set_dir(gpiovals::Dir::INPUT); + w.set_input(gpiovals::Input::CONNECT); + w.set_drive(match config.sda_high_drive { + true => gpiovals::Drive::H0D1, + false => gpiovals::Drive::S0D1, + }); if config.sda_pullup { - w.pull().pullup(); + w.set_pull(gpiovals::Pull::PULLUP); } - w }); scl.conf().write(|w| { - w.dir().input(); - w.input().connect(); - if config.scl_high_drive { - w.drive().h0d1(); - } else { - w.drive().s0d1(); + w.set_dir(gpiovals::Dir::INPUT); + w.set_input(gpiovals::Input::CONNECT); + w.set_drive(match config.scl_high_drive { + true => gpiovals::Drive::H0D1, + false => gpiovals::Drive::S0D1, + }); + if config.sda_pullup { + w.set_pull(gpiovals::Pull::PULLUP); } - if config.scl_pullup { - w.pull().pullup(); - } - w }); // Select pins. - r.psel.sda.write(|w| unsafe { w.bits(sda.psel_bits()) }); - r.psel.scl.write(|w| unsafe { w.bits(scl.psel_bits()) }); + r.psel().sda().write_value(sda.psel_bits()); + r.psel().scl().write_value(scl.psel_bits()); // Enable TWIS instance. - r.enable.write(|w| w.enable().enabled()); + r.enable().write(|w| w.set_enable(vals::Enable::ENABLED)); // Disable all events interrupts - r.intenclr.write(|w| unsafe { w.bits(0xFFFF_FFFF) }); + r.intenclr().write(|w| w.0 = 0xFFFF_FFFF); // Set address - r.address[0].write(|w| unsafe { w.address().bits(config.address0) }); - r.config.write(|w| w.address0().enabled()); + r.address(0).write(|w| w.set_address(config.address0)); + r.config().write(|w| w.set_address0(true)); if let Some(address1) = config.address1 { - r.address[1].write(|w| unsafe { w.address().bits(address1) }); - r.config.modify(|_r, w| w.address1().enabled()); + r.address(1).write(|w| w.set_address(address1)); + r.config().modify(|w| w.set_address1(true)); } // Set over-read character - r.orc.write(|w| unsafe { w.orc().bits(config.orc) }); + r.orc().write(|w| w.set_orc(config.orc)); // Generate suspend on read event - r.shorts.write(|w| w.read_suspend().enabled()); + r.shorts().write(|w| w.set_read_suspend(true)); T::Interrupt::unpend(); unsafe { T::Interrupt::enable() }; @@ -220,22 +221,18 @@ impl<'d, T: Instance> Twis<'d, T> { let r = T::regs(); - r.txd.ptr.write(|w| - // We're giving the register a pointer to the stack. Since we're - // waiting for the I2C transaction to end before this stack pointer - // becomes invalid, there's nothing wrong here. - // - // The PTR field is a full 32 bits wide and accepts the full range - // of values. - w.ptr().bits(buffer.as_ptr() as u32)); - r.txd.maxcnt.write(|w| + // We're giving the register a pointer to the stack. Since we're + // waiting for the I2C transaction to end before this stack pointer + // becomes invalid, there's nothing wrong here. + r.txd().ptr().write_value(buffer.as_ptr() as u32); + r.txd().maxcnt().write(|w| // We're giving it the length of the buffer, so no danger of // accessing invalid memory. We have verified that the length of the // buffer fits in an `u8`, so the cast to `u8` is also fine. // // The MAXCNT field is 8 bits wide and accepts the full range of // values. - w.maxcnt().bits(buffer.len() as _)); + w.set_maxcnt(buffer.len() as _)); Ok(()) } @@ -251,15 +248,11 @@ impl<'d, T: Instance> Twis<'d, T> { let r = T::regs(); - r.rxd.ptr.write(|w| - // We're giving the register a pointer to the stack. Since we're - // waiting for the I2C transaction to end before this stack pointer - // becomes invalid, there's nothing wrong here. - // - // The PTR field is a full 32 bits wide and accepts the full range - // of values. - w.ptr().bits(buffer.as_mut_ptr() as u32)); - r.rxd.maxcnt.write(|w| + // We're giving the register a pointer to the stack. Since we're + // waiting for the I2C transaction to end before this stack pointer + // becomes invalid, there's nothing wrong here. + r.rxd().ptr().write_value(buffer.as_mut_ptr() as u32); + r.rxd().maxcnt().write(|w| // We're giving it the length of the buffer, so no danger of // accessing invalid memory. We have verified that the length of the // buffer fits in an `u8`, so the cast to the type of maxcnt @@ -269,48 +262,51 @@ impl<'d, T: Instance> Twis<'d, T> { // type than a u8, so we use a `_` cast rather than a `u8` cast. // The MAXCNT field is thus at least 8 bits wide and accepts the // full range of values that fit in a `u8`. - w.maxcnt().bits(buffer.len() as _)); + w.set_maxcnt(buffer.len() as _)); Ok(()) } fn clear_errorsrc(&mut self) { let r = T::regs(); - r.errorsrc - .write(|w| w.overflow().bit(true).overread().bit(true).dnack().bit(true)); + r.errorsrc().write(|w| { + w.set_overflow(true); + w.set_overread(true); + w.set_dnack(true); + }); } /// Returns matched address for latest command. pub fn address_match(&self) -> u8 { let r = T::regs(); - r.address[r.match_.read().bits() as usize].read().address().bits() + r.address(r.match_().read().0 as usize).read().address() } /// Returns the index of the address matched in the latest command. pub fn address_match_index(&self) -> usize { - T::regs().match_.read().bits() as _ + T::regs().match_().read().0 as _ } /// Wait for read, write, stop or error fn blocking_listen_wait(&mut self) -> Result { let r = T::regs(); loop { - if r.events_error.read().bits() != 0 { - r.events_error.reset(); - r.tasks_stop.write(|w| unsafe { w.bits(1) }); - while r.events_stopped.read().bits() == 0 {} + if r.events_error().read() != 0 { + r.events_error().write_value(0); + r.tasks_stop().write_value(1); + while r.events_stopped().read() == 0 {} return Err(Error::Overflow); } - if r.events_stopped.read().bits() != 0 { - r.events_stopped.reset(); + if r.events_stopped().read() != 0 { + r.events_stopped().write_value(0); return Err(Error::Bus); } - if r.events_read.read().bits() != 0 { - r.events_read.reset(); + if r.events_read().read() != 0 { + r.events_read().write_value(0); return Ok(Status::Read); } - if r.events_write.read().bits() != 0 { - r.events_write.reset(); + if r.events_write().read() != 0 { + r.events_write().write_value(0); return Ok(Status::Write); } } @@ -321,22 +317,22 @@ impl<'d, T: Instance> Twis<'d, T> { let r = T::regs(); loop { // stop if an error occurred - if r.events_error.read().bits() != 0 { - r.events_error.reset(); - r.tasks_stop.write(|w| unsafe { w.bits(1) }); + if r.events_error().read() != 0 { + r.events_error().write_value(0); + r.tasks_stop().write_value(1); return Err(Error::Overflow); - } else if r.events_stopped.read().bits() != 0 { - r.events_stopped.reset(); + } else if r.events_stopped().read() != 0 { + r.events_stopped().write_value(0); return match status { Status::Read => Ok(Command::Read), Status::Write => { - let n = r.rxd.amount.read().bits() as usize; + let n = r.rxd().amount().read().0 as usize; Ok(Command::Write(n)) } }; - } else if r.events_read.read().bits() != 0 { - r.events_read.reset(); - let n = r.rxd.amount.read().bits() as usize; + } else if r.events_read().read() != 0 { + r.events_read().write_value(0); + let n = r.rxd().amount().read().0 as usize; return Ok(Command::WriteRead(n)); } } @@ -347,20 +343,20 @@ impl<'d, T: Instance> Twis<'d, T> { let r = T::regs(); loop { // stop if an error occurred - if r.events_error.read().bits() != 0 { - r.events_error.reset(); - r.tasks_stop.write(|w| unsafe { w.bits(1) }); - let errorsrc = r.errorsrc.read(); - if errorsrc.overread().is_detected() { + if r.events_error().read() != 0 { + r.events_error().write_value(0); + r.tasks_stop().write_value(1); + let errorsrc = r.errorsrc().read(); + if errorsrc.overread() { return Err(Error::OverRead); - } else if errorsrc.dnack().is_received() { + } else if errorsrc.dnack() { return Err(Error::DataNack); } else { return Err(Error::Bus); } - } else if r.events_stopped.read().bits() != 0 { - r.events_stopped.reset(); - let n = r.txd.amount.read().bits() as usize; + } else if r.events_stopped().read() != 0 { + r.events_stopped().write_value(0); + let n = r.txd().amount().read().0 as usize; return Ok(n); } } @@ -373,23 +369,23 @@ impl<'d, T: Instance> Twis<'d, T> { let deadline = Instant::now() + timeout; loop { // stop if an error occurred - if r.events_error.read().bits() != 0 { - r.events_error.reset(); - r.tasks_stop.write(|w| unsafe { w.bits(1) }); - let errorsrc = r.errorsrc.read(); - if errorsrc.overread().is_detected() { + if r.events_error().read() != 0 { + r.events_error().write_value(0); + r.tasks_stop().write_value(1); + let errorsrc = r.errorsrc().read(); + if errorsrc.overread() { return Err(Error::OverRead); - } else if errorsrc.dnack().is_received() { + } else if errorsrc.dnack() { return Err(Error::DataNack); } else { return Err(Error::Bus); } - } else if r.events_stopped.read().bits() != 0 { - r.events_stopped.reset(); - let n = r.txd.amount.read().bits() as usize; + } else if r.events_stopped().read() != 0 { + r.events_stopped().write_value(0); + let n = r.txd().amount().read().0 as usize; return Ok(n); } else if Instant::now() > deadline { - r.tasks_stop.write(|w| unsafe { w.bits(1) }); + r.tasks_stop().write_value(1); return Err(Error::Timeout); } } @@ -401,26 +397,26 @@ impl<'d, T: Instance> Twis<'d, T> { let r = T::regs(); let deadline = Instant::now() + timeout; loop { - if r.events_error.read().bits() != 0 { - r.events_error.reset(); - r.tasks_stop.write(|w| unsafe { w.bits(1) }); - while r.events_stopped.read().bits() == 0 {} + if r.events_error().read() != 0 { + r.events_error().write_value(0); + r.tasks_stop().write_value(1); + while r.events_stopped().read() == 0 {} return Err(Error::Overflow); } - if r.events_stopped.read().bits() != 0 { - r.events_stopped.reset(); + if r.events_stopped().read() != 0 { + r.events_stopped().write_value(0); return Err(Error::Bus); } - if r.events_read.read().bits() != 0 { - r.events_read.reset(); + if r.events_read().read() != 0 { + r.events_read().write_value(0); return Ok(Status::Read); } - if r.events_write.read().bits() != 0 { - r.events_write.reset(); + if r.events_write().read() != 0 { + r.events_write().write_value(0); return Ok(Status::Write); } if Instant::now() > deadline { - r.tasks_stop.write(|w| unsafe { w.bits(1) }); + r.tasks_stop().write_value(1); return Err(Error::Timeout); } } @@ -433,25 +429,25 @@ impl<'d, T: Instance> Twis<'d, T> { let deadline = Instant::now() + timeout; loop { // stop if an error occurred - if r.events_error.read().bits() != 0 { - r.events_error.reset(); - r.tasks_stop.write(|w| unsafe { w.bits(1) }); + if r.events_error().read() != 0 { + r.events_error().write_value(0); + r.tasks_stop().write_value(1); return Err(Error::Overflow); - } else if r.events_stopped.read().bits() != 0 { - r.events_stopped.reset(); + } else if r.events_stopped().read() != 0 { + r.events_stopped().write_value(0); return match status { Status::Read => Ok(Command::Read), Status::Write => { - let n = r.rxd.amount.read().bits() as usize; + let n = r.rxd().amount().read().0 as usize; Ok(Command::Write(n)) } }; - } else if r.events_read.read().bits() != 0 { - r.events_read.reset(); - let n = r.rxd.amount.read().bits() as usize; + } else if r.events_read().read() != 0 { + r.events_read().write_value(0); + let n = r.rxd().amount().read().0 as usize; return Ok(Command::WriteRead(n)); } else if Instant::now() > deadline { - r.tasks_stop.write(|w| unsafe { w.bits(1) }); + r.tasks_stop().write_value(1); return Err(Error::Timeout); } } @@ -466,20 +462,20 @@ impl<'d, T: Instance> Twis<'d, T> { s.waker.register(cx.waker()); // stop if an error occurred - if r.events_error.read().bits() != 0 { - r.events_error.reset(); - r.tasks_stop.write(|w| unsafe { w.bits(1) }); - let errorsrc = r.errorsrc.read(); - if errorsrc.overread().is_detected() { + if r.events_error().read() != 0 { + r.events_error().write_value(0); + r.tasks_stop().write_value(1); + let errorsrc = r.errorsrc().read(); + if errorsrc.overread() { return Poll::Ready(Err(Error::OverRead)); - } else if errorsrc.dnack().is_received() { + } else if errorsrc.dnack() { return Poll::Ready(Err(Error::DataNack)); } else { return Poll::Ready(Err(Error::Bus)); } - } else if r.events_stopped.read().bits() != 0 { - r.events_stopped.reset(); - let n = r.txd.amount.read().bits() as usize; + } else if r.events_stopped().read() != 0 { + r.events_stopped().write_value(0); + let n = r.txd().amount().read().0 as usize; return Poll::Ready(Ok(n)); } @@ -496,18 +492,18 @@ impl<'d, T: Instance> Twis<'d, T> { s.waker.register(cx.waker()); // stop if an error occurred - if r.events_error.read().bits() != 0 { - r.events_error.reset(); - r.tasks_stop.write(|w| unsafe { w.bits(1) }); + if r.events_error().read() != 0 { + r.events_error().write_value(0); + r.tasks_stop().write_value(1); return Poll::Ready(Err(Error::Overflow)); - } else if r.events_read.read().bits() != 0 { - r.events_read.reset(); + } else if r.events_read().read() != 0 { + r.events_read().write_value(0); return Poll::Ready(Ok(Status::Read)); - } else if r.events_write.read().bits() != 0 { - r.events_write.reset(); + } else if r.events_write().read() != 0 { + r.events_write().write_value(0); return Poll::Ready(Ok(Status::Write)); - } else if r.events_stopped.read().bits() != 0 { - r.events_stopped.reset(); + } else if r.events_stopped().read() != 0 { + r.events_stopped().write_value(0); return Poll::Ready(Err(Error::Bus)); } Poll::Pending @@ -523,22 +519,22 @@ impl<'d, T: Instance> Twis<'d, T> { s.waker.register(cx.waker()); // stop if an error occurred - if r.events_error.read().bits() != 0 { - r.events_error.reset(); - r.tasks_stop.write(|w| unsafe { w.bits(1) }); + if r.events_error().read() != 0 { + r.events_error().write_value(0); + r.tasks_stop().write_value(1); return Poll::Ready(Err(Error::Overflow)); - } else if r.events_stopped.read().bits() != 0 { - r.events_stopped.reset(); + } else if r.events_stopped().read() != 0 { + r.events_stopped().write_value(0); return match status { Status::Read => Poll::Ready(Ok(Command::Read)), Status::Write => { - let n = r.rxd.amount.read().bits() as usize; + let n = r.rxd().amount().read().0 as usize; Poll::Ready(Ok(Command::Write(n))) } }; - } else if r.events_read.read().bits() != 0 { - r.events_read.reset(); - let n = r.rxd.amount.read().bits() as usize; + } else if r.events_read().read() != 0 { + r.events_read().write_value(0); + let n = r.rxd().amount().read().0 as usize; return Poll::Ready(Ok(Command::WriteRead(n))); } Poll::Pending @@ -554,19 +550,25 @@ impl<'d, T: Instance> Twis<'d, T> { unsafe { self.set_tx_buffer(buffer)? }; // Clear events - r.events_stopped.reset(); - r.events_error.reset(); + r.events_stopped().write_value(0); + r.events_error().write_value(0); self.clear_errorsrc(); if inten { - r.intenset.write(|w| w.stopped().set().error().set()); + r.intenset().write(|w| { + w.set_stopped(true); + w.set_error(true); + }); } else { - r.intenclr.write(|w| w.stopped().clear().error().clear()); + r.intenclr().write(|w| { + w.set_stopped(true); + w.set_error(true); + }); } // Start write operation. - r.tasks_preparetx.write(|w| unsafe { w.bits(1) }); - r.tasks_resume.write(|w| unsafe { w.bits(1) }); + r.tasks_preparetx().write_value(1); + r.tasks_resume().write_value(1); Ok(()) } @@ -577,7 +579,7 @@ impl<'d, T: Instance> Twis<'d, T> { trace!("Copying TWIS tx buffer into RAM for DMA"); let tx_ram_buf = &mut [0; FORCE_COPY_BUFFER_SIZE][..wr_buffer.len()]; tx_ram_buf.copy_from_slice(wr_buffer); - self.setup_respond_from_ram(&tx_ram_buf, inten) + self.setup_respond_from_ram(tx_ram_buf, inten) } Err(error) => Err(error), } @@ -591,22 +593,30 @@ impl<'d, T: Instance> Twis<'d, T> { unsafe { self.set_rx_buffer(buffer)? }; // Clear events - r.events_read.reset(); - r.events_write.reset(); - r.events_stopped.reset(); - r.events_error.reset(); + r.events_read().write_value(0); + r.events_write().write_value(0); + r.events_stopped().write_value(0); + r.events_error().write_value(0); self.clear_errorsrc(); if inten { - r.intenset - .write(|w| w.stopped().set().error().set().read().set().write().set()); + r.intenset().write(|w| { + w.set_stopped(true); + w.set_error(true); + w.set_read(true); + w.set_write(true); + }); } else { - r.intenclr - .write(|w| w.stopped().clear().error().clear().read().clear().write().clear()); + r.intenclr().write(|w| { + w.set_stopped(true); + w.set_error(true); + w.set_read(true); + w.set_write(true); + }); } // Start read operation. - r.tasks_preparerx.write(|w| unsafe { w.bits(1) }); + r.tasks_preparerx().write_value(1); Ok(()) } @@ -616,16 +626,24 @@ impl<'d, T: Instance> Twis<'d, T> { compiler_fence(SeqCst); // Clear events - r.events_read.reset(); - r.events_write.reset(); - r.events_stopped.reset(); - r.events_error.reset(); + r.events_read().write_value(0); + r.events_write().write_value(0); + r.events_stopped().write_value(0); + r.events_error().write_value(0); self.clear_errorsrc(); if inten { - r.intenset.write(|w| w.stopped().set().error().set().read().set()); + r.intenset().write(|w| { + w.set_stopped(true); + w.set_error(true); + w.set_read(true); + }); } else { - r.intenclr.write(|w| w.stopped().clear().error().clear().read().clear()); + r.intenclr().write(|w| { + w.set_stopped(true); + w.set_error(true); + w.set_read(true); + }); } Ok(()) @@ -745,50 +763,47 @@ impl<'a, T: Instance> Drop for Twis<'a, T> { // disable! let r = T::regs(); - r.enable.write(|w| w.enable().disabled()); + r.enable().write(|w| w.set_enable(vals::Enable::DISABLED)); - gpio::deconfigure_pin(r.psel.sda.read().bits()); - gpio::deconfigure_pin(r.psel.scl.read().bits()); + gpio::deconfigure_pin(r.psel().sda().read()); + gpio::deconfigure_pin(r.psel().scl().read()); trace!("twis drop: done"); } } -pub(crate) mod sealed { - use super::*; +pub(crate) struct State { + waker: AtomicWaker, +} - pub struct State { - pub waker: AtomicWaker, - } - - impl State { - pub const fn new() -> Self { - Self { - waker: AtomicWaker::new(), - } +impl State { + pub(crate) const fn new() -> Self { + Self { + waker: AtomicWaker::new(), } } - - pub trait Instance { - fn regs() -> &'static pac::twis0::RegisterBlock; - fn state() -> &'static State; - } +} + +pub(crate) trait SealedInstance { + fn regs() -> pac::twis::Twis; + fn state() -> &'static State; } /// TWIS peripheral instance. -pub trait Instance: Peripheral

+ sealed::Instance + 'static { +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static { /// Interrupt for this peripheral. type Interrupt: interrupt::typelevel::Interrupt; } macro_rules! impl_twis { ($type:ident, $pac_type:ident, $irq:ident) => { - impl crate::twis::sealed::Instance for peripherals::$type { - fn regs() -> &'static pac::twis0::RegisterBlock { - unsafe { &*pac::$pac_type::ptr() } + impl crate::twis::SealedInstance for peripherals::$type { + fn regs() -> pac::twis::Twis { + pac::$pac_type } - fn state() -> &'static crate::twis::sealed::State { - static STATE: crate::twis::sealed::State = crate::twis::sealed::State::new(); + fn state() -> &'static crate::twis::State { + static STATE: crate::twis::State = crate::twis::State::new(); &STATE } } diff --git a/embassy-nrf/src/uarte.rs b/embassy-nrf/src/uarte.rs index 95434e7a7..2a59d029d 100644 --- a/embassy-nrf/src/uarte.rs +++ b/embassy-nrf/src/uarte.rs @@ -15,19 +15,20 @@ use core::future::poll_fn; use core::marker::PhantomData; -use core::sync::atomic::{compiler_fence, Ordering}; +use core::sync::atomic::{compiler_fence, AtomicU8, Ordering}; use core::task::Poll; use embassy_hal_internal::drop::OnDrop; use embassy_hal_internal::{into_ref, PeripheralRef}; -use pac::uarte0::RegisterBlock; +use embassy_sync::waitqueue::AtomicWaker; // Re-export SVD variants to allow user to directly set values. -pub use pac::uarte0::{baudrate::BAUDRATE_A as Baudrate, config::PARITY_A as Parity}; +pub use pac::uarte::vals::{Baudrate, ConfigParity as Parity}; use crate::chip::{EASY_DMA_SIZE, FORCE_COPY_BUFFER_SIZE}; -use crate::gpio::sealed::Pin as _; -use crate::gpio::{self, AnyPin, Pin as GpioPin, PselBits}; +use crate::gpio::{self, AnyPin, Pin as GpioPin, PselBits, SealedPin as _, DISCONNECTED}; use crate::interrupt::typelevel::Interrupt; +use crate::pac::gpio::vals as gpiovals; +use crate::pac::uarte::vals; use crate::ppi::{AnyConfigurableChannel, ConfigurableChannel, Event, Ppi, Task}; use crate::timer::{Frequency, Instance as TimerInstance, Timer}; use crate::util::slice_in_ram_or; @@ -52,6 +53,37 @@ impl Default for Config { } } +bitflags::bitflags! { + /// Error source flags + pub(crate) struct ErrorSource: u32 { + /// Buffer overrun + const OVERRUN = 0x01; + /// Parity error + const PARITY = 0x02; + /// Framing error + const FRAMING = 0x04; + /// Break condition + const BREAK = 0x08; + } +} + +impl ErrorSource { + #[inline] + fn check(self) -> Result<(), Error> { + if self.contains(ErrorSource::OVERRUN) { + Err(Error::Overrun) + } else if self.contains(ErrorSource::PARITY) { + Err(Error::Parity) + } else if self.contains(ErrorSource::FRAMING) { + Err(Error::Framing) + } else if self.contains(ErrorSource::BREAK) { + Err(Error::Break) + } else { + Ok(()) + } + } +} + /// UART error. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -61,6 +93,14 @@ pub enum Error { BufferTooLong, /// The buffer is not in data RAM. It's most likely in flash, and nRF's DMA cannot access flash. BufferNotInRAM, + /// Framing Error + Framing, + /// Parity Error + Parity, + /// Buffer Overrun + Overrun, + /// Break condition + Break, } /// Interrupt handler. @@ -73,13 +113,20 @@ impl interrupt::typelevel::Handler for InterruptHandl let r = T::regs(); let s = T::state(); - if r.events_endrx.read().bits() != 0 { - s.endrx_waker.wake(); - r.intenclr.write(|w| w.endrx().clear()); + let endrx = r.events_endrx().read(); + let error = r.events_error().read(); + if endrx != 0 || error != 0 { + s.rx_waker.wake(); + if endrx != 0 { + r.intenclr().write(|w| w.set_endrx(true)); + } + if error != 0 { + r.intenclr().write(|w| w.set_error(true)); + } } - if r.events_endtx.read().bits() != 0 { - s.endtx_waker.wake(); - r.intenclr.write(|w| w.endtx().clear()); + if r.events_endtx().read() != 0 { + s.tx_waker.wake(); + r.intenclr().write(|w| w.set_endtx(true)); } } } @@ -113,7 +160,7 @@ impl<'d, T: Instance> Uarte<'d, T> { txd: impl Peripheral

+ 'd, config: Config, ) -> Self { - into_ref!(rxd, txd); + into_ref!(uarte, rxd, txd); Self::new_inner(uarte, rxd.map_into(), txd.map_into(), None, None, config) } @@ -127,7 +174,7 @@ impl<'d, T: Instance> Uarte<'d, T> { rts: impl Peripheral

+ 'd, config: Config, ) -> Self { - into_ref!(rxd, txd, cts, rts); + into_ref!(uarte, rxd, txd, cts, rts); Self::new_inner( uarte, rxd.map_into(), @@ -139,44 +186,27 @@ impl<'d, T: Instance> Uarte<'d, T> { } fn new_inner( - uarte: impl Peripheral

+ 'd, + uarte: PeripheralRef<'d, T>, rxd: PeripheralRef<'d, AnyPin>, txd: PeripheralRef<'d, AnyPin>, cts: Option>, rts: Option>, config: Config, ) -> Self { - into_ref!(uarte); - let r = T::regs(); - rxd.conf().write(|w| w.input().connect().drive().h0h1()); - r.psel.rxd.write(|w| unsafe { w.bits(rxd.psel_bits()) }); - - txd.set_high(); - txd.conf().write(|w| w.dir().output().drive().h0h1()); - r.psel.txd.write(|w| unsafe { w.bits(txd.psel_bits()) }); - - if let Some(pin) = &cts { - pin.conf().write(|w| w.input().connect().drive().h0h1()); - } - r.psel.cts.write(|w| unsafe { w.bits(cts.psel_bits()) }); - - if let Some(pin) = &rts { - pin.set_high(); - pin.conf().write(|w| w.dir().output().drive().h0h1()); - } - r.psel.rts.write(|w| unsafe { w.bits(rts.psel_bits()) }); - - T::Interrupt::unpend(); - unsafe { T::Interrupt::enable() }; - let hardware_flow_control = match (rts.is_some(), cts.is_some()) { (false, false) => false, (true, true) => true, _ => panic!("RTS and CTS pins must be either both set or none set."), }; configure(r, config, hardware_flow_control); + configure_rx_pins(r, rxd, rts); + configure_tx_pins(r, txd, cts); + + T::Interrupt::unpend(); + unsafe { T::Interrupt::enable() }; + r.enable().write(|w| w.set_enable(vals::Enable::ENABLED)); let s = T::state(); s.tx_rx_refcount.store(2, Ordering::Relaxed); @@ -196,6 +226,14 @@ impl<'d, T: Instance> Uarte<'d, T> { (self.tx, self.rx) } + /// Split the UART in reader and writer parts, by reference. + /// + /// The returned halves borrow from `self`, so you can drop them and go back to using + /// the "un-split" `self`. This allows temporarily splitting the UART. + pub fn split_by_ref(&mut self) -> (&mut UarteTx<'d, T>, &mut UarteRx<'d, T>) { + (&mut self.tx, &mut self.rx) + } + /// Split the Uarte into the transmitter and receiver with idle support parts. /// /// This is useful to concurrently transmit and receive from independent tasks. @@ -211,7 +249,7 @@ impl<'d, T: Instance> Uarte<'d, T> { /// Return the endtx event for use with PPI pub fn event_endtx(&self) -> Event { let r = T::regs(); - Event::from_reg(&r.events_endtx) + Event::from_reg(r.events_endtx()) } /// Read bytes until the buffer is filled. @@ -245,25 +283,74 @@ impl<'d, T: Instance> Uarte<'d, T> { } } -fn configure(r: &RegisterBlock, config: Config, hardware_flow_control: bool) { - r.config.write(|w| { - w.hwfc().bit(hardware_flow_control); - w.parity().variant(config.parity); - w +pub(crate) fn configure_tx_pins( + r: pac::uarte::Uarte, + txd: PeripheralRef<'_, AnyPin>, + cts: Option>, +) { + txd.set_high(); + txd.conf().write(|w| { + w.set_dir(gpiovals::Dir::OUTPUT); + w.set_input(gpiovals::Input::DISCONNECT); + w.set_drive(gpiovals::Drive::H0H1); }); - r.baudrate.write(|w| w.baudrate().variant(config.baudrate)); + r.psel().txd().write_value(txd.psel_bits()); + + if let Some(pin) = &cts { + pin.conf().write(|w| { + w.set_dir(gpiovals::Dir::INPUT); + w.set_input(gpiovals::Input::CONNECT); + w.set_drive(gpiovals::Drive::H0H1); + }); + } + r.psel().cts().write_value(cts.psel_bits()); +} + +pub(crate) fn configure_rx_pins( + r: pac::uarte::Uarte, + rxd: PeripheralRef<'_, AnyPin>, + rts: Option>, +) { + rxd.conf().write(|w| { + w.set_dir(gpiovals::Dir::INPUT); + w.set_input(gpiovals::Input::CONNECT); + w.set_drive(gpiovals::Drive::H0H1); + }); + r.psel().rxd().write_value(rxd.psel_bits()); + + if let Some(pin) = &rts { + pin.set_high(); + pin.conf().write(|w| { + w.set_dir(gpiovals::Dir::OUTPUT); + w.set_input(gpiovals::Input::DISCONNECT); + w.set_drive(gpiovals::Drive::H0H1); + }); + } + r.psel().rts().write_value(rts.psel_bits()); +} + +pub(crate) fn configure(r: pac::uarte::Uarte, config: Config, hardware_flow_control: bool) { + r.config().write(|w| { + w.set_hwfc(hardware_flow_control); + w.set_parity(config.parity); + }); + r.baudrate().write(|w| w.set_baudrate(config.baudrate)); // Disable all interrupts - r.intenclr.write(|w| unsafe { w.bits(0xFFFF_FFFF) }); + r.intenclr().write(|w| w.0 = 0xFFFF_FFFF); // Reset rxstarted, txstarted. These are used by drop to know whether a transfer was // stopped midway or not. - r.events_rxstarted.reset(); - r.events_txstarted.reset(); + r.events_rxstarted().write_value(0); + r.events_txstarted().write_value(0); - // Enable - apply_workaround_for_enable_anomaly(&r); - r.enable.write(|w| w.enable().enabled()); + // reset all pins + r.psel().txd().write_value(DISCONNECTED); + r.psel().rxd().write_value(DISCONNECTED); + r.psel().cts().write_value(DISCONNECTED); + r.psel().rts().write_value(DISCONNECTED); + + apply_workaround_for_enable_anomaly(r); } impl<'d, T: Instance> UarteTx<'d, T> { @@ -274,7 +361,7 @@ impl<'d, T: Instance> UarteTx<'d, T> { txd: impl Peripheral

+ 'd, config: Config, ) -> Self { - into_ref!(txd); + into_ref!(uarte, txd); Self::new_inner(uarte, txd.map_into(), None, config) } @@ -286,37 +373,24 @@ impl<'d, T: Instance> UarteTx<'d, T> { cts: impl Peripheral

+ 'd, config: Config, ) -> Self { - into_ref!(txd, cts); + into_ref!(uarte, txd, cts); Self::new_inner(uarte, txd.map_into(), Some(cts.map_into()), config) } fn new_inner( - uarte: impl Peripheral

+ 'd, + uarte: PeripheralRef<'d, T>, txd: PeripheralRef<'d, AnyPin>, cts: Option>, config: Config, ) -> Self { - into_ref!(uarte); - let r = T::regs(); - txd.set_high(); - txd.conf().write(|w| w.dir().output().drive().s0s1()); - r.psel.txd.write(|w| unsafe { w.bits(txd.psel_bits()) }); - - if let Some(pin) = &cts { - pin.conf().write(|w| w.input().connect().drive().h0h1()); - } - r.psel.cts.write(|w| unsafe { w.bits(cts.psel_bits()) }); - - r.psel.rxd.write(|w| w.connect().disconnected()); - r.psel.rts.write(|w| w.connect().disconnected()); - - let hardware_flow_control = cts.is_some(); - configure(r, config, hardware_flow_control); + configure(r, config, cts.is_some()); + configure_tx_pins(r, txd, cts); T::Interrupt::unpend(); unsafe { T::Interrupt::enable() }; + r.enable().write(|w| w.set_enable(vals::Enable::ENABLED)); let s = T::state(); s.tx_rx_refcount.store(1, Ordering::Relaxed); @@ -332,7 +406,7 @@ impl<'d, T: Instance> UarteTx<'d, T> { trace!("Copying UARTE tx buffer into RAM for DMA"); let ram_buf = &mut [0; FORCE_COPY_BUFFER_SIZE][..buffer.len()]; ram_buf.copy_from_slice(buffer); - self.write_from_ram(&ram_buf).await + self.write_from_ram(ram_buf).await } Err(error) => Err(error), } @@ -340,7 +414,7 @@ impl<'d, T: Instance> UarteTx<'d, T> { /// Same as [`write`](Self::write) but will fail instead of copying data into RAM. Consult the module level documentation to learn more. pub async fn write_from_ram(&mut self, buffer: &[u8]) -> Result<(), Error> { - if buffer.len() == 0 { + if buffer.is_empty() { return Ok(()); } @@ -358,29 +432,29 @@ impl<'d, T: Instance> UarteTx<'d, T> { let drop = OnDrop::new(move || { trace!("write drop: stopping"); - r.intenclr.write(|w| w.endtx().clear()); - r.events_txstopped.reset(); - r.tasks_stoptx.write(|w| unsafe { w.bits(1) }); + r.intenclr().write(|w| w.set_endtx(true)); + r.events_txstopped().write_value(0); + r.tasks_stoptx().write_value(1); // TX is stopped almost instantly, spinning is fine. - while r.events_endtx.read().bits() == 0 {} + while r.events_endtx().read() == 0 {} trace!("write drop: stopped"); }); - r.txd.ptr.write(|w| unsafe { w.ptr().bits(ptr as u32) }); - r.txd.maxcnt.write(|w| unsafe { w.maxcnt().bits(len as _) }); + r.txd().ptr().write_value(ptr as u32); + r.txd().maxcnt().write(|w| w.set_maxcnt(len as _)); - r.events_endtx.reset(); - r.intenset.write(|w| w.endtx().set()); + r.events_endtx().write_value(0); + r.intenset().write(|w| w.set_endtx(true)); compiler_fence(Ordering::SeqCst); trace!("starttx"); - r.tasks_starttx.write(|w| unsafe { w.bits(1) }); + r.tasks_starttx().write_value(1); poll_fn(|cx| { - s.endtx_waker.register(cx.waker()); - if r.events_endtx.read().bits() != 0 { + s.tx_waker.register(cx.waker()); + if r.events_endtx().read() != 0 { return Poll::Ready(()); } Poll::Pending @@ -388,7 +462,7 @@ impl<'d, T: Instance> UarteTx<'d, T> { .await; compiler_fence(Ordering::SeqCst); - r.events_txstarted.reset(); + r.events_txstarted().write_value(0); drop.defuse(); Ok(()) @@ -402,7 +476,7 @@ impl<'d, T: Instance> UarteTx<'d, T> { trace!("Copying UARTE tx buffer into RAM for DMA"); let ram_buf = &mut [0; FORCE_COPY_BUFFER_SIZE][..buffer.len()]; ram_buf.copy_from_slice(buffer); - self.blocking_write_from_ram(&ram_buf) + self.blocking_write_from_ram(ram_buf) } Err(error) => Err(error), } @@ -410,7 +484,7 @@ impl<'d, T: Instance> UarteTx<'d, T> { /// Same as [`write_from_ram`](Self::write_from_ram) but will fail instead of copying data into RAM. Consult the module level documentation to learn more. pub fn blocking_write_from_ram(&mut self, buffer: &[u8]) -> Result<(), Error> { - if buffer.len() == 0 { + if buffer.is_empty() { return Ok(()); } @@ -424,21 +498,21 @@ impl<'d, T: Instance> UarteTx<'d, T> { let r = T::regs(); - r.txd.ptr.write(|w| unsafe { w.ptr().bits(ptr as u32) }); - r.txd.maxcnt.write(|w| unsafe { w.maxcnt().bits(len as _) }); + r.txd().ptr().write_value(ptr as u32); + r.txd().maxcnt().write(|w| w.set_maxcnt(len as _)); - r.events_endtx.reset(); - r.intenclr.write(|w| w.endtx().clear()); + r.events_endtx().write_value(0); + r.intenclr().write(|w| w.set_endtx(true)); compiler_fence(Ordering::SeqCst); trace!("starttx"); - r.tasks_starttx.write(|w| unsafe { w.bits(1) }); + r.tasks_starttx().write_value(1); - while r.events_endtx.read().bits() == 0 {} + while r.events_endtx().read() == 0 {} compiler_fence(Ordering::SeqCst); - r.events_txstarted.reset(); + r.events_txstarted().write_value(0); Ok(()) } @@ -450,15 +524,15 @@ impl<'a, T: Instance> Drop for UarteTx<'a, T> { let r = T::regs(); - let did_stoptx = r.events_txstarted.read().bits() != 0; + let did_stoptx = r.events_txstarted().read() != 0; trace!("did_stoptx {}", did_stoptx); // Wait for txstopped, if needed. - while did_stoptx && r.events_txstopped.read().bits() == 0 {} + while did_stoptx && r.events_txstopped().read() == 0 {} let s = T::state(); - drop_tx_rx(&r, &s); + drop_tx_rx(r, s); } } @@ -470,7 +544,7 @@ impl<'d, T: Instance> UarteRx<'d, T> { rxd: impl Peripheral

+ 'd, config: Config, ) -> Self { - into_ref!(rxd); + into_ref!(uarte, rxd); Self::new_inner(uarte, rxd.map_into(), None, config) } @@ -482,37 +556,32 @@ impl<'d, T: Instance> UarteRx<'d, T> { rts: impl Peripheral

+ 'd, config: Config, ) -> Self { - into_ref!(rxd, rts); + into_ref!(uarte, rxd, rts); Self::new_inner(uarte, rxd.map_into(), Some(rts.map_into()), config) } + /// Check for errors and clear the error register if an error occured. + fn check_and_clear_errors(&mut self) -> Result<(), Error> { + let r = T::regs(); + let err_bits = r.errorsrc().read(); + r.errorsrc().write_value(err_bits); + ErrorSource::from_bits_truncate(err_bits.0).check() + } + fn new_inner( - uarte: impl Peripheral

+ 'd, + uarte: PeripheralRef<'d, T>, rxd: PeripheralRef<'d, AnyPin>, rts: Option>, config: Config, ) -> Self { - into_ref!(uarte); - let r = T::regs(); - rxd.conf().write(|w| w.input().connect().drive().h0h1()); - r.psel.rxd.write(|w| unsafe { w.bits(rxd.psel_bits()) }); - - if let Some(pin) = &rts { - pin.set_high(); - pin.conf().write(|w| w.dir().output().drive().h0h1()); - } - r.psel.rts.write(|w| unsafe { w.bits(rts.psel_bits()) }); - - r.psel.txd.write(|w| w.connect().disconnected()); - r.psel.cts.write(|w| w.connect().disconnected()); + configure(r, config, rts.is_some()); + configure_rx_pins(r, rxd, rts); T::Interrupt::unpend(); unsafe { T::Interrupt::enable() }; - - let hardware_flow_control = rts.is_some(); - configure(r, config, hardware_flow_control); + r.enable().write(|w| w.set_enable(vals::Enable::ENABLED)); let s = T::state(); s.tx_rx_refcount.store(1, Ordering::Relaxed); @@ -539,8 +608,8 @@ impl<'d, T: Instance> UarteRx<'d, T> { // We want to stop RX if line is idle for 2 bytes worth of time // That is 20 bits (each byte is 1 start bit + 8 data bits + 1 stop bit) // This gives us the amount of 16M ticks for 20 bits. - let baudrate = r.baudrate.read().baudrate().variant().unwrap(); - let timeout = 0x8000_0000 / (baudrate as u32 / 40); + let baudrate = r.baudrate().read().baudrate(); + let timeout = 0x8000_0000 / (baudrate.to_bits() / 40); timer.set_frequency(Frequency::F16MHz); timer.cc(0).write(timeout); @@ -549,7 +618,7 @@ impl<'d, T: Instance> UarteRx<'d, T> { let mut ppi_ch1 = Ppi::new_one_to_two( ppi_ch1.map_into(), - Event::from_reg(&r.events_rxdrdy), + Event::from_reg(r.events_rxdrdy()), timer.task_clear(), timer.task_start(), ); @@ -558,21 +627,21 @@ impl<'d, T: Instance> UarteRx<'d, T> { let mut ppi_ch2 = Ppi::new_one_to_one( ppi_ch2.map_into(), timer.cc(0).event_compare(), - Task::from_reg(&r.tasks_stoprx), + Task::from_reg(r.tasks_stoprx()), ); ppi_ch2.enable(); UarteRxWithIdle { rx: self, timer, - ppi_ch1: ppi_ch1, + ppi_ch1, _ppi_ch2: ppi_ch2, } } /// Read bytes until the buffer is filled. pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> { - if buffer.len() == 0 { + if buffer.is_empty() { return Ok(()); } if buffer.len() > EASY_DMA_SIZE { @@ -588,45 +657,58 @@ impl<'d, T: Instance> UarteRx<'d, T> { let drop = OnDrop::new(move || { trace!("read drop: stopping"); - r.intenclr.write(|w| w.endrx().clear()); - r.events_rxto.reset(); - r.tasks_stoprx.write(|w| unsafe { w.bits(1) }); + r.intenclr().write(|w| { + w.set_endrx(true); + w.set_error(true); + }); + r.events_rxto().write_value(0); + r.events_error().write_value(0); + r.tasks_stoprx().write_value(1); - while r.events_endrx.read().bits() == 0 {} + while r.events_endrx().read() == 0 {} trace!("read drop: stopped"); }); - r.rxd.ptr.write(|w| unsafe { w.ptr().bits(ptr as u32) }); - r.rxd.maxcnt.write(|w| unsafe { w.maxcnt().bits(len as _) }); + r.rxd().ptr().write_value(ptr as u32); + r.rxd().maxcnt().write(|w| w.set_maxcnt(len as _)); - r.events_endrx.reset(); - r.intenset.write(|w| w.endrx().set()); + r.events_endrx().write_value(0); + r.events_error().write_value(0); + r.intenset().write(|w| { + w.set_endrx(true); + w.set_error(true); + }); compiler_fence(Ordering::SeqCst); trace!("startrx"); - r.tasks_startrx.write(|w| unsafe { w.bits(1) }); + r.tasks_startrx().write_value(1); - poll_fn(|cx| { - s.endrx_waker.register(cx.waker()); - if r.events_endrx.read().bits() != 0 { - return Poll::Ready(()); + let result = poll_fn(|cx| { + s.rx_waker.register(cx.waker()); + + if let Err(e) = self.check_and_clear_errors() { + r.tasks_stoprx().write_value(1); + return Poll::Ready(Err(e)); + } + if r.events_endrx().read() != 0 { + return Poll::Ready(Ok(())); } Poll::Pending }) .await; compiler_fence(Ordering::SeqCst); - r.events_rxstarted.reset(); + r.events_rxstarted().write_value(0); drop.defuse(); - Ok(()) + result } /// Read bytes until the buffer is filled. pub fn blocking_read(&mut self, buffer: &mut [u8]) -> Result<(), Error> { - if buffer.len() == 0 { + if buffer.is_empty() { return Ok(()); } if buffer.len() > EASY_DMA_SIZE { @@ -638,23 +720,27 @@ impl<'d, T: Instance> UarteRx<'d, T> { let r = T::regs(); - r.rxd.ptr.write(|w| unsafe { w.ptr().bits(ptr as u32) }); - r.rxd.maxcnt.write(|w| unsafe { w.maxcnt().bits(len as _) }); + r.rxd().ptr().write_value(ptr as u32); + r.rxd().maxcnt().write(|w| w.set_maxcnt(len as _)); - r.events_endrx.reset(); - r.intenclr.write(|w| w.endrx().clear()); + r.events_endrx().write_value(0); + r.events_error().write_value(0); + r.intenclr().write(|w| { + w.set_endrx(true); + w.set_error(true); + }); compiler_fence(Ordering::SeqCst); trace!("startrx"); - r.tasks_startrx.write(|w| unsafe { w.bits(1) }); + r.tasks_startrx().write_value(1); - while r.events_endrx.read().bits() == 0 {} + while r.events_endrx().read() == 0 && r.events_error().read() == 0 {} compiler_fence(Ordering::SeqCst); - r.events_rxstarted.reset(); + r.events_rxstarted().write_value(0); - Ok(()) + self.check_and_clear_errors() } } @@ -664,15 +750,15 @@ impl<'a, T: Instance> Drop for UarteRx<'a, T> { let r = T::regs(); - let did_stoprx = r.events_rxstarted.read().bits() != 0; + let did_stoprx = r.events_rxstarted().read() != 0; trace!("did_stoprx {}", did_stoprx); // Wait for rxto, if needed. - while did_stoprx && r.events_rxto.read().bits() == 0 {} + while did_stoprx && r.events_rxto().read() == 0 {} let s = T::state(); - drop_tx_rx(&r, &s); + drop_tx_rx(r, s); } } @@ -703,7 +789,7 @@ impl<'d, T: Instance, U: TimerInstance> UarteRxWithIdle<'d, T, U> { /// /// Returns the amount of bytes read. pub async fn read_until_idle(&mut self, buffer: &mut [u8]) -> Result { - if buffer.len() == 0 { + if buffer.is_empty() { return Ok(0); } if buffer.len() > EASY_DMA_SIZE { @@ -721,48 +807,62 @@ impl<'d, T: Instance, U: TimerInstance> UarteRxWithIdle<'d, T, U> { let drop = OnDrop::new(|| { self.timer.stop(); - r.intenclr.write(|w| w.endrx().clear()); - r.events_rxto.reset(); - r.tasks_stoprx.write(|w| unsafe { w.bits(1) }); + r.intenclr().write(|w| { + w.set_endrx(true); + w.set_error(true); + }); + r.events_rxto().write_value(0); + r.events_error().write_value(0); + r.tasks_stoprx().write_value(1); - while r.events_endrx.read().bits() == 0 {} + while r.events_endrx().read() == 0 {} }); - r.rxd.ptr.write(|w| unsafe { w.ptr().bits(ptr as u32) }); - r.rxd.maxcnt.write(|w| unsafe { w.maxcnt().bits(len as _) }); + r.rxd().ptr().write_value(ptr as u32); + r.rxd().maxcnt().write(|w| w.set_maxcnt(len as _)); - r.events_endrx.reset(); - r.intenset.write(|w| w.endrx().set()); + r.events_endrx().write_value(0); + r.events_error().write_value(0); + r.intenset().write(|w| { + w.set_endrx(true); + w.set_error(true); + }); compiler_fence(Ordering::SeqCst); - r.tasks_startrx.write(|w| unsafe { w.bits(1) }); + r.tasks_startrx().write_value(1); - poll_fn(|cx| { - s.endrx_waker.register(cx.waker()); - if r.events_endrx.read().bits() != 0 { - return Poll::Ready(()); + let result = poll_fn(|cx| { + s.rx_waker.register(cx.waker()); + + if let Err(e) = self.rx.check_and_clear_errors() { + r.tasks_stoprx().write_value(1); + return Poll::Ready(Err(e)); } + if r.events_endrx().read() != 0 { + return Poll::Ready(Ok(())); + } + Poll::Pending }) .await; compiler_fence(Ordering::SeqCst); - let n = r.rxd.amount.read().amount().bits() as usize; + let n = r.rxd().amount().read().0 as usize; self.timer.stop(); - r.events_rxstarted.reset(); + r.events_rxstarted().write_value(0); drop.defuse(); - Ok(n) + result.map(|_| n) } /// Read bytes until the buffer is filled, or the line becomes idle. /// /// Returns the amount of bytes read. pub fn blocking_read_until_idle(&mut self, buffer: &mut [u8]) -> Result { - if buffer.len() == 0 { + if buffer.is_empty() { return Ok(0); } if buffer.len() > EASY_DMA_SIZE { @@ -776,52 +876,57 @@ impl<'d, T: Instance, U: TimerInstance> UarteRxWithIdle<'d, T, U> { self.ppi_ch1.enable(); - r.rxd.ptr.write(|w| unsafe { w.ptr().bits(ptr as u32) }); - r.rxd.maxcnt.write(|w| unsafe { w.maxcnt().bits(len as _) }); + r.rxd().ptr().write_value(ptr as u32); + r.rxd().maxcnt().write(|w| w.set_maxcnt(len as _)); - r.events_endrx.reset(); - r.intenclr.write(|w| w.endrx().clear()); + r.events_endrx().write_value(0); + r.events_error().write_value(0); + r.intenclr().write(|w| { + w.set_endrx(true); + w.set_error(true); + }); compiler_fence(Ordering::SeqCst); - r.tasks_startrx.write(|w| unsafe { w.bits(1) }); + r.tasks_startrx().write_value(1); - while r.events_endrx.read().bits() == 0 {} + while r.events_endrx().read() == 0 && r.events_error().read() == 0 {} compiler_fence(Ordering::SeqCst); - let n = r.rxd.amount.read().amount().bits() as usize; + let n = r.rxd().amount().read().0 as usize; self.timer.stop(); - r.events_rxstarted.reset(); + r.events_rxstarted().write_value(0); - Ok(n) + self.rx.check_and_clear_errors().map(|_| n) } } #[cfg(not(any(feature = "_nrf9160", feature = "_nrf5340")))] -pub(crate) fn apply_workaround_for_enable_anomaly(_r: &crate::pac::uarte0::RegisterBlock) { +pub(crate) fn apply_workaround_for_enable_anomaly(_r: pac::uarte::Uarte) { // Do nothing } #[cfg(any(feature = "_nrf9160", feature = "_nrf5340"))] -pub(crate) fn apply_workaround_for_enable_anomaly(r: &crate::pac::uarte0::RegisterBlock) { +pub(crate) fn apply_workaround_for_enable_anomaly(r: pac::uarte::Uarte) { // Apply workaround for anomalies: // - nRF9160 - anomaly 23 // - nRF5340 - anomaly 44 - let rxenable_reg: *const u32 = ((r as *const _ as usize) + 0x564) as *const u32; - let txenable_reg: *const u32 = ((r as *const _ as usize) + 0x568) as *const u32; + let rp = r.as_ptr() as *mut u32; + let rxenable_reg = unsafe { rp.add(0x564 / 4) }; + let txenable_reg = unsafe { rp.add(0x568 / 4) }; // NB Safety: This is taken from Nordic's driver - // https://github.com/NordicSemiconductor/nrfx/blob/master/drivers/src/nrfx_uarte.c#L197 if unsafe { core::ptr::read_volatile(txenable_reg) } == 1 { - r.tasks_stoptx.write(|w| unsafe { w.bits(1) }); + r.tasks_stoptx().write_value(1); } // NB Safety: This is taken from Nordic's driver - // https://github.com/NordicSemiconductor/nrfx/blob/master/drivers/src/nrfx_uarte.c#L197 if unsafe { core::ptr::read_volatile(rxenable_reg) } == 1 { - r.enable.write(|w| w.enable().enabled()); - r.tasks_stoprx.write(|w| unsafe { w.bits(1) }); + r.enable().write(|w| w.set_enable(vals::Enable::ENABLED)); + r.tasks_stoprx().write_value(1); let mut workaround_succeded = false; // The UARTE is able to receive up to four bytes after the STOPRX task has been triggered. @@ -842,71 +947,64 @@ pub(crate) fn apply_workaround_for_enable_anomaly(r: &crate::pac::uarte0::Regist panic!("Failed to apply workaround for UART"); } - let errors = r.errorsrc.read().bits(); - // NB Safety: safe to write back the bits we just read to clear them - r.errorsrc.write(|w| unsafe { w.bits(errors) }); - r.enable.write(|w| w.enable().disabled()); + // write back the bits we just read to clear them + let errors = r.errorsrc().read(); + r.errorsrc().write_value(errors); + r.enable().write(|w| w.set_enable(vals::Enable::DISABLED)); } } -pub(crate) fn drop_tx_rx(r: &pac::uarte0::RegisterBlock, s: &sealed::State) { +pub(crate) fn drop_tx_rx(r: pac::uarte::Uarte, s: &State) { if s.tx_rx_refcount.fetch_sub(1, Ordering::Relaxed) == 1 { // Finally we can disable, and we do so for the peripheral // i.e. not just rx concerns. - r.enable.write(|w| w.enable().disabled()); + r.enable().write(|w| w.set_enable(vals::Enable::DISABLED)); - gpio::deconfigure_pin(r.psel.rxd.read().bits()); - gpio::deconfigure_pin(r.psel.txd.read().bits()); - gpio::deconfigure_pin(r.psel.rts.read().bits()); - gpio::deconfigure_pin(r.psel.cts.read().bits()); + gpio::deconfigure_pin(r.psel().rxd().read()); + gpio::deconfigure_pin(r.psel().txd().read()); + gpio::deconfigure_pin(r.psel().rts().read()); + gpio::deconfigure_pin(r.psel().cts().read()); trace!("uarte tx and rx drop: done"); } } -pub(crate) mod sealed { - use core::sync::atomic::AtomicU8; - - use embassy_sync::waitqueue::AtomicWaker; - - use super::*; - - pub struct State { - pub endrx_waker: AtomicWaker, - pub endtx_waker: AtomicWaker, - pub tx_rx_refcount: AtomicU8, - } - impl State { - pub const fn new() -> Self { - Self { - endrx_waker: AtomicWaker::new(), - endtx_waker: AtomicWaker::new(), - tx_rx_refcount: AtomicU8::new(0), - } +pub(crate) struct State { + pub(crate) rx_waker: AtomicWaker, + pub(crate) tx_waker: AtomicWaker, + pub(crate) tx_rx_refcount: AtomicU8, +} +impl State { + pub(crate) const fn new() -> Self { + Self { + rx_waker: AtomicWaker::new(), + tx_waker: AtomicWaker::new(), + tx_rx_refcount: AtomicU8::new(0), } } - - pub trait Instance { - fn regs() -> &'static pac::uarte0::RegisterBlock; - fn state() -> &'static State; - fn buffered_state() -> &'static crate::buffered_uarte::State; - } +} + +pub(crate) trait SealedInstance { + fn regs() -> pac::uarte::Uarte; + fn state() -> &'static State; + fn buffered_state() -> &'static crate::buffered_uarte::State; } /// UARTE peripheral instance. -pub trait Instance: Peripheral

+ sealed::Instance + 'static + Send { +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static + Send { /// Interrupt for this peripheral. type Interrupt: interrupt::typelevel::Interrupt; } macro_rules! impl_uarte { ($type:ident, $pac_type:ident, $irq:ident) => { - impl crate::uarte::sealed::Instance for peripherals::$type { - fn regs() -> &'static pac::uarte0::RegisterBlock { - unsafe { &*pac::$pac_type::ptr() } + impl crate::uarte::SealedInstance for peripherals::$type { + fn regs() -> pac::uarte::Uarte { + pac::$pac_type } - fn state() -> &'static crate::uarte::sealed::State { - static STATE: crate::uarte::sealed::State = crate::uarte::sealed::State::new(); + fn state() -> &'static crate::uarte::State { + static STATE: crate::uarte::State = crate::uarte::State::new(); &STATE } fn buffered_state() -> &'static crate::buffered_uarte::State { diff --git a/embassy-nrf/src/usb/mod.rs b/embassy-nrf/src/usb/mod.rs index e26b49db3..52c9c532b 100644 --- a/embassy-nrf/src/usb/mod.rs +++ b/embassy-nrf/src/usb/mod.rs @@ -15,10 +15,10 @@ use embassy_hal_internal::{into_ref, PeripheralRef}; use embassy_sync::waitqueue::AtomicWaker; use embassy_usb_driver as driver; use embassy_usb_driver::{Direction, EndpointAddress, EndpointError, EndpointInfo, EndpointType, Event, Unsupported}; -use pac::usbd::RegisterBlock; use self::vbus_detect::VbusDetect; use crate::interrupt::typelevel::Interrupt; +use crate::pac::usbd::vals; use crate::util::slice_in_ram; use crate::{interrupt, pac, Peripheral}; @@ -38,19 +38,19 @@ impl interrupt::typelevel::Handler for InterruptHandl unsafe fn on_interrupt() { let regs = T::regs(); - if regs.events_usbreset.read().bits() != 0 { - regs.intenclr.write(|w| w.usbreset().clear()); + if regs.events_usbreset().read() != 0 { + regs.intenclr().write(|w| w.set_usbreset(true)); BUS_WAKER.wake(); EP0_WAKER.wake(); } - if regs.events_ep0setup.read().bits() != 0 { - regs.intenclr.write(|w| w.ep0setup().clear()); + if regs.events_ep0setup().read() != 0 { + regs.intenclr().write(|w| w.set_ep0setup(true)); EP0_WAKER.wake(); } - if regs.events_ep0datadone.read().bits() != 0 { - regs.intenclr.write(|w| w.ep0datadone().clear()); + if regs.events_ep0datadone().read() != 0 { + regs.intenclr().write(|w| w.set_ep0datadone(true)); EP0_WAKER.wake(); } @@ -63,22 +63,22 @@ impl interrupt::typelevel::Handler for InterruptHandl // Therefore, it's fine to clear just the event, and let main thread // check the individual bits in EVENTCAUSE and EPDATASTATUS. It // doesn't cause an infinite irq loop. - if regs.events_usbevent.read().bits() != 0 { - regs.events_usbevent.reset(); + if regs.events_usbevent().read() != 0 { + regs.events_usbevent().write_value(0); BUS_WAKER.wake(); } - if regs.events_epdata.read().bits() != 0 { - regs.events_epdata.reset(); + if regs.events_epdata().read() != 0 { + regs.events_epdata().write_value(0); - let r = regs.epdatastatus.read().bits(); - regs.epdatastatus.write(|w| unsafe { w.bits(r) }); - READY_ENDPOINTS.fetch_or(r, Ordering::AcqRel); + let r = regs.epdatastatus().read(); + regs.epdatastatus().write_value(r); + READY_ENDPOINTS.fetch_or(r.0, Ordering::AcqRel); for i in 1..=7 { - if r & In::mask(i) != 0 { + if r.0 & In::mask(i) != 0 { In::waker(i).wake(); } - if r & Out::mask(i) != 0 { + if r.0 & Out::mask(i) != 0 { Out::waker(i).wake(); } } @@ -181,35 +181,34 @@ impl<'d, T: Instance, V: VbusDetect> driver::Bus for Bus<'d, T, V> { errata::pre_enable(); - regs.enable.write(|w| w.enable().enabled()); + regs.enable().write(|w| w.set_enable(true)); // Wait until the peripheral is ready. - regs.intenset.write(|w| w.usbevent().set_bit()); + regs.intenset().write(|w| w.set_usbevent(true)); poll_fn(|cx| { BUS_WAKER.register(cx.waker()); - if regs.eventcause.read().ready().is_ready() { + if regs.eventcause().read().ready() { Poll::Ready(()) } else { Poll::Pending } }) .await; - regs.eventcause.write(|w| w.ready().clear_bit_by_one()); + regs.eventcause().write(|w| w.set_ready(true)); errata::post_enable(); unsafe { NVIC::unmask(pac::Interrupt::USBD) }; - regs.intenset.write(|w| { - w.usbreset().set_bit(); - w.usbevent().set_bit(); - w.epdata().set_bit(); - w + regs.intenset().write(|w| { + w.set_usbreset(true); + w.set_usbevent(true); + w.set_epdata(true); }); if self.vbus_detect.wait_power_ready().await.is_ok() { // Enable the USB pullup, allowing enumeration. - regs.usbpullup.write(|w| w.connect().enabled()); + regs.usbpullup().write(|w| w.set_connect(true)); trace!("enabled"); } else { trace!("usb power not ready due to usb removal"); @@ -218,7 +217,7 @@ impl<'d, T: Instance, V: VbusDetect> driver::Bus for Bus<'d, T, V> { async fn disable(&mut self) { let regs = T::regs(); - regs.enable.write(|x| x.enable().disabled()); + regs.enable().write(|x| x.set_enable(false)); } async fn poll(&mut self) -> Event { @@ -226,13 +225,13 @@ impl<'d, T: Instance, V: VbusDetect> driver::Bus for Bus<'d, T, V> { BUS_WAKER.register(cx.waker()); let regs = T::regs(); - if regs.events_usbreset.read().bits() != 0 { - regs.events_usbreset.reset(); - regs.intenset.write(|w| w.usbreset().set()); + if regs.events_usbreset().read() != 0 { + regs.events_usbreset().write_value(0); + regs.intenset().write(|w| w.set_usbreset(true)); // Disable all endpoints except EP0 - regs.epinen.write(|w| unsafe { w.bits(0x01) }); - regs.epouten.write(|w| unsafe { w.bits(0x01) }); + regs.epinen().write(|w| w.0 = 0x01); + regs.epouten().write(|w| w.0 = 0x01); READY_ENDPOINTS.store(In::mask(0), Ordering::Release); for i in 1..=7 { In::waker(i).wake(); @@ -242,27 +241,27 @@ impl<'d, T: Instance, V: VbusDetect> driver::Bus for Bus<'d, T, V> { return Poll::Ready(Event::Reset); } - let r = regs.eventcause.read(); + let r = regs.eventcause().read(); - if r.isooutcrc().bit() { - regs.eventcause.write(|w| w.isooutcrc().detected()); + if r.isooutcrc() { + regs.eventcause().write(|w| w.set_isooutcrc(true)); trace!("USB event: isooutcrc"); } - if r.usbwuallowed().bit() { - regs.eventcause.write(|w| w.usbwuallowed().allowed()); + if r.usbwuallowed() { + regs.eventcause().write(|w| w.set_usbwuallowed(true)); trace!("USB event: usbwuallowed"); } - if r.suspend().bit() { - regs.eventcause.write(|w| w.suspend().detected()); - regs.lowpower.write(|w| w.lowpower().low_power()); + if r.suspend() { + regs.eventcause().write(|w| w.set_suspend(true)); + regs.lowpower().write(|w| w.set_lowpower(vals::Lowpower::LOW_POWER)); return Poll::Ready(Event::Suspend); } - if r.resume().bit() { - regs.eventcause.write(|w| w.resume().detected()); + if r.resume() { + regs.eventcause().write(|w| w.set_resume(true)); return Poll::Ready(Event::Resume); } - if r.ready().bit() { - regs.eventcause.write(|w| w.ready().ready()); + if r.ready() { + regs.eventcause().write(|w| w.set_ready(true)); trace!("USB event: ready"); } @@ -284,16 +283,19 @@ impl<'d, T: Instance, V: VbusDetect> driver::Bus for Bus<'d, T, V> { fn endpoint_set_stalled(&mut self, ep_addr: EndpointAddress, stalled: bool) { let regs = T::regs(); - unsafe { - if ep_addr.index() == 0 { - regs.tasks_ep0stall.write(|w| w.tasks_ep0stall().bit(stalled)); - } else { - regs.epstall.write(|w| { - w.ep().bits(ep_addr.index() as u8 & 0b111); - w.io().bit(ep_addr.is_in()); - w.stall().bit(stalled) - }); + if ep_addr.index() == 0 { + if stalled { + regs.tasks_ep0stall().write_value(1); } + } else { + regs.epstall().write(|w| { + w.set_ep(ep_addr.index() as u8 & 0b111); + w.set_io(match ep_addr.direction() { + Direction::In => vals::Io::IN, + Direction::Out => vals::Io::OUT, + }); + w.set_stall(stalled); + }); } } @@ -301,8 +303,8 @@ impl<'d, T: Instance, V: VbusDetect> driver::Bus for Bus<'d, T, V> { let regs = T::regs(); let i = ep_addr.index(); match ep_addr.direction() { - Direction::Out => regs.halted.epout[i].read().getstatus().is_halted(), - Direction::In => regs.halted.epin[i].read().getstatus().is_halted(), + Direction::Out => regs.halted().epout(i).read().getstatus() == vals::Getstatus::HALTED, + Direction::In => regs.halted().epin(i).read().getstatus() == vals::Getstatus::HALTED, } } @@ -317,15 +319,13 @@ impl<'d, T: Instance, V: VbusDetect> driver::Bus for Bus<'d, T, V> { match ep_addr.direction() { Direction::In => { let mut was_enabled = false; - regs.epinen.modify(|r, w| { - let mut bits = r.bits(); - was_enabled = (bits & mask) != 0; + regs.epinen().modify(|w| { + was_enabled = (w.0 & mask) != 0; if enabled { - bits |= mask + w.0 |= mask } else { - bits &= !mask + w.0 &= !mask } - unsafe { w.bits(bits) } }); let ready_mask = In::mask(i); @@ -340,15 +340,8 @@ impl<'d, T: Instance, V: VbusDetect> driver::Bus for Bus<'d, T, V> { In::waker(i).wake(); } Direction::Out => { - regs.epouten.modify(|r, w| { - let mut bits = r.bits(); - if enabled { - bits |= mask - } else { - bits &= !mask - } - unsafe { w.bits(bits) } - }); + regs.epouten() + .modify(|w| if enabled { w.0 |= mask } else { w.0 &= !mask }); let ready_mask = Out::mask(i); if enabled { @@ -356,7 +349,7 @@ impl<'d, T: Instance, V: VbusDetect> driver::Bus for Bus<'d, T, V> { // peripheral will NAK all incoming packets) until we write a zero to the SIZE // register (see figure 203 of the 52840 manual). To avoid that we write a 0 to the // SIZE register - regs.size.epout[i].reset(); + regs.size().epout(i).write(|_| ()); } else { READY_ENDPOINTS.fetch_and(!ready_mask, Ordering::AcqRel); } @@ -370,25 +363,24 @@ impl<'d, T: Instance, V: VbusDetect> driver::Bus for Bus<'d, T, V> { async fn remote_wakeup(&mut self) -> Result<(), Unsupported> { let regs = T::regs(); - if regs.lowpower.read().lowpower().is_low_power() { + if regs.lowpower().read().lowpower() == vals::Lowpower::LOW_POWER { errata::pre_wakeup(); - regs.lowpower.write(|w| w.lowpower().force_normal()); + regs.lowpower().write(|w| w.set_lowpower(vals::Lowpower::FORCE_NORMAL)); poll_fn(|cx| { BUS_WAKER.register(cx.waker()); let regs = T::regs(); - let r = regs.eventcause.read(); + let r = regs.eventcause().read(); - if regs.events_usbreset.read().bits() != 0 { + if regs.events_usbreset().read() != 0 { Poll::Ready(()) - } else if r.resume().bit() { + } else if r.resume() { Poll::Ready(()) - } else if r.usbwuallowed().bit() { - regs.eventcause.write(|w| w.usbwuallowed().allowed()); - - regs.dpdmvalue.write(|w| w.state().resume()); - regs.tasks_dpdmdrive.write(|w| w.tasks_dpdmdrive().set_bit()); + } else if r.usbwuallowed() { + regs.eventcause().write(|w| w.set_usbwuallowed(true)); + regs.dpdmvalue().write(|w| w.set_state(vals::State::RESUME)); + regs.tasks_dpdmdrive().write_value(1); Poll::Ready(()) } else { @@ -413,7 +405,7 @@ pub enum In {} trait EndpointDir { fn waker(i: usize) -> &'static AtomicWaker; fn mask(i: usize) -> u32; - fn is_enabled(regs: &RegisterBlock, i: usize) -> bool; + fn is_enabled(regs: pac::usbd::Usbd, i: usize) -> bool; } impl EndpointDir for In { @@ -428,8 +420,8 @@ impl EndpointDir for In { } #[inline] - fn is_enabled(regs: &RegisterBlock, i: usize) -> bool { - (regs.epinen.read().bits() & (1 << i)) != 0 + fn is_enabled(regs: pac::usbd::Usbd, i: usize) -> bool { + regs.epinen().read().in_(i) } } @@ -445,8 +437,8 @@ impl EndpointDir for Out { } #[inline] - fn is_enabled(regs: &RegisterBlock, i: usize) -> bool { - (regs.epouten.read().bits() & (1 << i)) != 0 + fn is_enabled(regs: pac::usbd::Usbd, i: usize) -> bool { + regs.epouten().read().out(i) } } @@ -471,12 +463,19 @@ impl<'d, T: Instance, Dir: EndpointDir> driver::Endpoint for Endpoint<'d, T, Dir } async fn wait_enabled(&mut self) { + self.wait_enabled_state(true).await + } +} + +#[allow(private_bounds)] +impl<'d, T: Instance, Dir: EndpointDir> Endpoint<'d, T, Dir> { + async fn wait_enabled_state(&mut self, state: bool) { let i = self.info.addr.index(); assert!(i != 0); poll_fn(move |cx| { Dir::waker(i).register(cx.waker()); - if Dir::is_enabled(T::regs(), i) { + if Dir::is_enabled(T::regs(), i) == state { Poll::Ready(()) } else { Poll::Pending @@ -484,6 +483,11 @@ impl<'d, T: Instance, Dir: EndpointDir> driver::Endpoint for Endpoint<'d, T, Dir }) .await } + + /// Wait for the endpoint to be disabled + pub async fn wait_disabled(&mut self) { + self.wait_enabled_state(false).await + } } impl<'d, T: Instance, Dir> Endpoint<'d, T, Dir> { @@ -517,33 +521,23 @@ unsafe fn read_dma(i: usize, buf: &mut [u8]) -> Result buf.len() { return Err(EndpointError::BufferOverflow); } - let epout = [ - ®s.epout0, - ®s.epout1, - ®s.epout2, - ®s.epout3, - ®s.epout4, - ®s.epout5, - ®s.epout6, - ®s.epout7, - ]; - epout[i].ptr.write(|w| w.bits(buf.as_ptr() as u32)); + regs.epout(i).ptr().write_value(buf.as_ptr() as u32); // MAXCNT must match SIZE - epout[i].maxcnt.write(|w| w.bits(size as u32)); + regs.epout(i).maxcnt().write(|w| w.set_maxcnt(size as _)); dma_start(); - regs.events_endepout[i].reset(); - regs.tasks_startepout[i].write(|w| w.tasks_startepout().set_bit()); - while regs.events_endepout[i].read().events_endepout().bit_is_clear() {} - regs.events_endepout[i].reset(); + regs.events_endepout(i).write_value(0); + regs.tasks_startepout(i).write_value(1); + while regs.events_endepout(i).read() == 0 {} + regs.events_endepout(i).write_value(0); dma_end(); - regs.size.epout[i].reset(); + regs.size().epout(i).write(|_| ()); Ok(size) } @@ -562,27 +556,16 @@ unsafe fn write_dma(i: usize, buf: &[u8]) { buf.as_ptr() }; - let epin = [ - ®s.epin0, - ®s.epin1, - ®s.epin2, - ®s.epin3, - ®s.epin4, - ®s.epin5, - ®s.epin6, - ®s.epin7, - ]; - // Set the buffer length so the right number of bytes are transmitted. // Safety: `buf.len()` has been checked to be <= the max buffer length. - epin[i].ptr.write(|w| w.bits(ptr as u32)); - epin[i].maxcnt.write(|w| w.maxcnt().bits(buf.len() as u8)); + regs.epin(i).ptr().write_value(ptr as u32); + regs.epin(i).maxcnt().write(|w| w.set_maxcnt(buf.len() as u8)); - regs.events_endepin[i].reset(); + regs.events_endepin(i).write_value(0); dma_start(); - regs.tasks_startepin[i].write(|w| w.bits(1)); - while regs.events_endepin[i].read().bits() == 0 {} + regs.tasks_startepin(i).write_value(1); + while regs.events_endepin(i).read() == 0 {} dma_end(); } @@ -625,14 +608,14 @@ impl<'d, T: Instance> driver::ControlPipe for ControlPipe<'d, T> { let regs = T::regs(); // Reset shorts - regs.shorts.write(|w| w); + regs.shorts().write(|_| ()); // Wait for SETUP packet - regs.intenset.write(|w| w.ep0setup().set()); + regs.intenset().write(|w| w.set_ep0setup(true)); poll_fn(|cx| { EP0_WAKER.register(cx.waker()); let regs = T::regs(); - if regs.events_ep0setup.read().bits() != 0 { + if regs.events_ep0setup().read() != 0 { Poll::Ready(()) } else { Poll::Pending @@ -640,17 +623,17 @@ impl<'d, T: Instance> driver::ControlPipe for ControlPipe<'d, T> { }) .await; - regs.events_ep0setup.reset(); + regs.events_ep0setup().write_value(0); let mut buf = [0; 8]; - buf[0] = regs.bmrequesttype.read().bits() as u8; - buf[1] = regs.brequest.read().brequest().bits(); - buf[2] = regs.wvaluel.read().wvaluel().bits(); - buf[3] = regs.wvalueh.read().wvalueh().bits(); - buf[4] = regs.windexl.read().windexl().bits(); - buf[5] = regs.windexh.read().windexh().bits(); - buf[6] = regs.wlengthl.read().wlengthl().bits(); - buf[7] = regs.wlengthh.read().wlengthh().bits(); + buf[0] = regs.bmrequesttype().read().0 as u8; + buf[1] = regs.brequest().read().0 as u8; + buf[2] = regs.wvaluel().read().0 as u8; + buf[3] = regs.wvalueh().read().0 as u8; + buf[4] = regs.windexl().read().0 as u8; + buf[5] = regs.windexh().read().0 as u8; + buf[6] = regs.wlengthl().read().0 as u8; + buf[7] = regs.wlengthh().read().0 as u8; buf } @@ -658,26 +641,26 @@ impl<'d, T: Instance> driver::ControlPipe for ControlPipe<'d, T> { async fn data_out(&mut self, buf: &mut [u8], _first: bool, _last: bool) -> Result { let regs = T::regs(); - regs.events_ep0datadone.reset(); + regs.events_ep0datadone().write_value(0); // This starts a RX on EP0. events_ep0datadone notifies when done. - regs.tasks_ep0rcvout.write(|w| w.tasks_ep0rcvout().set_bit()); + regs.tasks_ep0rcvout().write_value(1); // Wait until ready - regs.intenset.write(|w| { - w.usbreset().set(); - w.ep0setup().set(); - w.ep0datadone().set() + regs.intenset().write(|w| { + w.set_usbreset(true); + w.set_ep0setup(true); + w.set_ep0datadone(true); }); poll_fn(|cx| { EP0_WAKER.register(cx.waker()); let regs = T::regs(); - if regs.events_ep0datadone.read().bits() != 0 { + if regs.events_ep0datadone().read() != 0 { Poll::Ready(Ok(())) - } else if regs.events_usbreset.read().bits() != 0 { + } else if regs.events_usbreset().read() != 0 { trace!("aborted control data_out: usb reset"); Poll::Ready(Err(EndpointError::Disabled)) - } else if regs.events_ep0setup.read().bits() != 0 { + } else if regs.events_ep0setup().read() != 0 { trace!("aborted control data_out: received another SETUP"); Poll::Ready(Err(EndpointError::Disabled)) } else { @@ -691,29 +674,29 @@ impl<'d, T: Instance> driver::ControlPipe for ControlPipe<'d, T> { async fn data_in(&mut self, buf: &[u8], _first: bool, last: bool) -> Result<(), EndpointError> { let regs = T::regs(); - regs.events_ep0datadone.reset(); + regs.events_ep0datadone().write_value(0); - regs.shorts.write(|w| w.ep0datadone_ep0status().bit(last)); + regs.shorts().write(|w| w.set_ep0datadone_ep0status(last)); // This starts a TX on EP0. events_ep0datadone notifies when done. unsafe { write_dma::(0, buf) } - regs.intenset.write(|w| { - w.usbreset().set(); - w.ep0setup().set(); - w.ep0datadone().set() + regs.intenset().write(|w| { + w.set_usbreset(true); + w.set_ep0setup(true); + w.set_ep0datadone(true); }); poll_fn(|cx| { cx.waker().wake_by_ref(); EP0_WAKER.register(cx.waker()); let regs = T::regs(); - if regs.events_ep0datadone.read().bits() != 0 { + if regs.events_ep0datadone().read() != 0 { Poll::Ready(Ok(())) - } else if regs.events_usbreset.read().bits() != 0 { + } else if regs.events_usbreset().read() != 0 { trace!("aborted control data_in: usb reset"); Poll::Ready(Err(EndpointError::Disabled)) - } else if regs.events_ep0setup.read().bits() != 0 { + } else if regs.events_ep0setup().read() != 0 { trace!("aborted control data_in: received another SETUP"); Poll::Ready(Err(EndpointError::Disabled)) } else { @@ -725,12 +708,12 @@ impl<'d, T: Instance> driver::ControlPipe for ControlPipe<'d, T> { async fn accept(&mut self) { let regs = T::regs(); - regs.tasks_ep0status.write(|w| w.tasks_ep0status().bit(true)); + regs.tasks_ep0status().write_value(1); } async fn reject(&mut self) { let regs = T::regs(); - regs.tasks_ep0stall.write(|w| w.tasks_ep0stall().bit(true)); + regs.tasks_ep0stall().write_value(1); } async fn accept_set_address(&mut self, _addr: u8) { @@ -793,25 +776,22 @@ impl Allocator { } } -pub(crate) mod sealed { - use super::*; - - pub trait Instance { - fn regs() -> &'static pac::usbd::RegisterBlock; - } +pub(crate) trait SealedInstance { + fn regs() -> pac::usbd::Usbd; } /// USB peripheral instance. -pub trait Instance: Peripheral

+ sealed::Instance + 'static + Send { +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static + Send { /// Interrupt for this peripheral. type Interrupt: interrupt::typelevel::Interrupt; } macro_rules! impl_usb { ($type:ident, $pac_type:ident, $irq:ident) => { - impl crate::usb::sealed::Instance for peripherals::$type { - fn regs() -> &'static pac::usbd::RegisterBlock { - unsafe { &*pac::$pac_type::ptr() } + impl crate::usb::SealedInstance for peripherals::$type { + fn regs() -> pac::usbd::Usbd { + pac::$pac_type } } impl crate::usb::Instance for peripherals::$type { diff --git a/embassy-nrf/src/usb/vbus_detect.rs b/embassy-nrf/src/usb/vbus_detect.rs index a05e5aa52..7f816a5ad 100644 --- a/embassy-nrf/src/usb/vbus_detect.rs +++ b/embassy-nrf/src/usb/vbus_detect.rs @@ -34,9 +34,9 @@ type UsbRegIrq = interrupt::typelevel::POWER_CLOCK; type UsbRegIrq = interrupt::typelevel::USBREGULATOR; #[cfg(not(feature = "_nrf5340"))] -type UsbRegPeri = pac::POWER; +const USB_REG_PERI: pac::power::Power = pac::POWER; #[cfg(feature = "_nrf5340")] -type UsbRegPeri = pac::USBREGULATOR; +const USB_REG_PERI: pac::usbregulator::Usbregulator = pac::USBREGULATOR; /// Interrupt handler. pub struct InterruptHandler { @@ -45,21 +45,21 @@ pub struct InterruptHandler { impl interrupt::typelevel::Handler for InterruptHandler { unsafe fn on_interrupt() { - let regs = unsafe { &*UsbRegPeri::ptr() }; + let regs = USB_REG_PERI; - if regs.events_usbdetected.read().bits() != 0 { - regs.events_usbdetected.reset(); + if regs.events_usbdetected().read() != 0 { + regs.events_usbdetected().write_value(0); BUS_WAKER.wake(); } - if regs.events_usbremoved.read().bits() != 0 { - regs.events_usbremoved.reset(); + if regs.events_usbremoved().read() != 0 { + regs.events_usbremoved().write_value(0); BUS_WAKER.wake(); POWER_WAKER.wake(); } - if regs.events_usbpwrrdy.read().bits() != 0 { - regs.events_usbpwrrdy.reset(); + if regs.events_usbpwrrdy().read() != 0 { + regs.events_usbpwrrdy().write_value(0); POWER_WAKER.wake(); } } @@ -78,13 +78,16 @@ static POWER_WAKER: AtomicWaker = AtomicWaker::new(); impl HardwareVbusDetect { /// Create a new `VbusDetectNative`. pub fn new(_irq: impl interrupt::typelevel::Binding + 'static) -> Self { - let regs = unsafe { &*UsbRegPeri::ptr() }; + let regs = USB_REG_PERI; UsbRegIrq::unpend(); unsafe { UsbRegIrq::enable() }; - regs.intenset - .write(|w| w.usbdetected().set().usbremoved().set().usbpwrrdy().set()); + regs.intenset().write(|w| { + w.set_usbdetected(true); + w.set_usbremoved(true); + w.set_usbpwrrdy(true); + }); Self { _private: () } } @@ -92,16 +95,16 @@ impl HardwareVbusDetect { impl VbusDetect for HardwareVbusDetect { fn is_usb_detected(&self) -> bool { - let regs = unsafe { &*UsbRegPeri::ptr() }; - regs.usbregstatus.read().vbusdetect().is_vbus_present() + let regs = USB_REG_PERI; + regs.usbregstatus().read().vbusdetect() } async fn wait_power_ready(&mut self) -> Result<(), ()> { poll_fn(move |cx| { POWER_WAKER.register(cx.waker()); - let regs = unsafe { &*UsbRegPeri::ptr() }; + let regs = USB_REG_PERI; - if regs.usbregstatus.read().outputrdy().is_ready() { + if regs.usbregstatus().read().outputrdy() { Poll::Ready(Ok(())) } else if !self.is_usb_detected() { Poll::Ready(Err(())) diff --git a/embassy-nrf/src/util.rs b/embassy-nrf/src/util.rs index b408c517b..78f71719f 100644 --- a/embassy-nrf/src/util.rs +++ b/embassy-nrf/src/util.rs @@ -1,30 +1,21 @@ #![allow(dead_code)] -use core::mem; const SRAM_LOWER: usize = 0x2000_0000; const SRAM_UPPER: usize = 0x3000_0000; -// TODO: replace transmutes with core::ptr::metadata once it's stable -pub(crate) fn slice_ptr_parts(slice: *const [T]) -> (*const T, usize) { - unsafe { mem::transmute(slice) } -} - -pub(crate) fn slice_ptr_parts_mut(slice: *mut [T]) -> (*mut T, usize) { - unsafe { mem::transmute(slice) } -} - /// Does this slice reside entirely within RAM? pub(crate) fn slice_in_ram(slice: *const [T]) -> bool { - let (ptr, len) = slice_ptr_parts(slice); - let ptr = ptr as usize; - ptr >= SRAM_LOWER && (ptr + len * core::mem::size_of::()) < SRAM_UPPER + if slice.is_empty() { + return true; + } + + let ptr = slice as *const T as usize; + ptr >= SRAM_LOWER && (ptr + slice.len() * core::mem::size_of::()) < SRAM_UPPER } /// Return an error if slice is not in RAM. Skips check if slice is zero-length. -#[cfg(not(feature = "nrf51"))] pub(crate) fn slice_in_ram_or(slice: *const [T], err: E) -> Result<(), E> { - let (_, len) = slice_ptr_parts(slice); - if len == 0 || slice_in_ram(slice) { + if slice_in_ram(slice) { Ok(()) } else { Err(err) diff --git a/embassy-nrf/src/wdt.rs b/embassy-nrf/src/wdt.rs index 40a674424..dfe6cbec3 100644 --- a/embassy-nrf/src/wdt.rs +++ b/embassy-nrf/src/wdt.rs @@ -3,7 +3,8 @@ //! This HAL implements a basic watchdog timer with 1..=8 handles. //! Once the watchdog has been started, it cannot be stopped. -use crate::pac::WDT; +use crate::pac::wdt::vals; +pub use crate::pac::wdt::vals::{Halt as HaltConfig, Sleep as SleepConfig}; use crate::peripherals; const MIN_TICKS: u32 = 15; @@ -18,29 +19,29 @@ pub struct Config { pub timeout_ticks: u32, /// Should the watchdog continue to count during sleep modes? - pub run_during_sleep: bool, + pub action_during_sleep: SleepConfig, /// Should the watchdog continue to count when the CPU is halted for debug? - pub run_during_debug_halt: bool, + pub action_during_debug_halt: HaltConfig, } impl Config { /// Create a config structure from the current configuration of the WDT /// peripheral. pub fn try_new(_wdt: &peripherals::WDT) -> Option { - let r = unsafe { &*WDT::ptr() }; + let r = crate::pac::WDT; - #[cfg(not(feature = "_nrf9160"))] - let runstatus = r.runstatus.read().runstatus().bit(); - #[cfg(feature = "_nrf9160")] - let runstatus = r.runstatus.read().runstatuswdt().bit(); + #[cfg(not(feature = "_nrf91"))] + let runstatus = r.runstatus().read().runstatus(); + #[cfg(feature = "_nrf91")] + let runstatus = r.runstatus().read().runstatuswdt(); if runstatus { - let config = r.config.read(); + let config = r.config().read(); Some(Self { - timeout_ticks: r.crv.read().bits(), - run_during_sleep: config.sleep().bit(), - run_during_debug_halt: config.halt().bit(), + timeout_ticks: r.crv().read(), + action_during_sleep: config.sleep(), + action_during_debug_halt: config.halt(), }) } else { None @@ -52,8 +53,8 @@ impl Default for Config { fn default() -> Self { Self { timeout_ticks: 32768, // 1 second - run_during_debug_halt: true, - run_during_sleep: true, + action_during_debug_halt: HaltConfig::RUN, + action_during_sleep: SleepConfig::RUN, } } } @@ -78,36 +79,35 @@ impl Watchdog { ) -> Result<(Self, [WatchdogHandle; N]), peripherals::WDT> { assert!(N >= 1 && N <= 8); - let r = unsafe { &*WDT::ptr() }; + let r = crate::pac::WDT; let crv = config.timeout_ticks.max(MIN_TICKS); - let rren = (1u32 << N) - 1; + let rren = crate::pac::wdt::regs::Rren((1u32 << N) - 1); - #[cfg(not(feature = "_nrf9160"))] - let runstatus = r.runstatus.read().runstatus().bit(); - #[cfg(feature = "_nrf9160")] - let runstatus = r.runstatus.read().runstatuswdt().bit(); + #[cfg(not(feature = "_nrf91"))] + let runstatus = r.runstatus().read().runstatus(); + #[cfg(feature = "_nrf91")] + let runstatus = r.runstatus().read().runstatuswdt(); if runstatus { - let curr_config = r.config.read(); - if curr_config.halt().bit() != config.run_during_debug_halt - || curr_config.sleep().bit() != config.run_during_sleep - || r.crv.read().bits() != crv - || r.rren.read().bits() != rren + let curr_config = r.config().read(); + if curr_config.halt() != config.action_during_debug_halt + || curr_config.sleep() != config.action_during_sleep + || r.crv().read() != crv + || r.rren().read() != rren { return Err(wdt); } } else { - r.config.write(|w| { - w.sleep().bit(config.run_during_sleep); - w.halt().bit(config.run_during_debug_halt); - w + r.config().write(|w| { + w.set_sleep(config.action_during_sleep); + w.set_halt(config.action_during_debug_halt); }); - r.intenset.write(|w| w.timeout().set_bit()); + r.intenset().write(|w| w.set_timeout(true)); - r.crv.write(|w| unsafe { w.bits(crv) }); - r.rren.write(|w| unsafe { w.bits(rren) }); - r.tasks_start.write(|w| unsafe { w.bits(1) }); + r.crv().write_value(crv); + r.rren().write_value(rren); + r.tasks_start().write_value(1); } let this = Self { _private: () }; @@ -130,8 +130,7 @@ impl Watchdog { /// interrupt has been enabled. #[inline(always)] pub fn enable_interrupt(&mut self) { - let r = unsafe { &*WDT::ptr() }; - r.intenset.write(|w| w.timeout().set_bit()); + crate::pac::WDT.intenset().write(|w| w.set_timeout(true)); } /// Disable the watchdog interrupt. @@ -139,8 +138,7 @@ impl Watchdog { /// NOTE: This has no effect on the reset caused by the Watchdog. #[inline(always)] pub fn disable_interrupt(&mut self) { - let r = unsafe { &*WDT::ptr() }; - r.intenclr.write(|w| w.timeout().set_bit()); + crate::pac::WDT.intenclr().write(|w| w.set_timeout(true)); } /// Is the watchdog still awaiting pets from any handle? @@ -149,9 +147,9 @@ impl Watchdog { /// handles to prevent a reset this time period. #[inline(always)] pub fn awaiting_pets(&self) -> bool { - let r = unsafe { &*WDT::ptr() }; - let enabled = r.rren.read().bits(); - let status = r.reqstatus.read().bits(); + let r = crate::pac::WDT; + let enabled = r.rren().read().0; + let status = r.reqstatus().read().0; (status & enabled) == 0 } } @@ -170,22 +168,21 @@ impl WatchdogHandle { /// prevent a reset from occurring. #[inline] pub fn pet(&mut self) { - let r = unsafe { &*WDT::ptr() }; - r.rr[self.index as usize].write(|w| w.rr().reload()); + let r = crate::pac::WDT; + r.rr(self.index as usize).write(|w| w.set_rr(vals::Rr::RELOAD)); } /// Has this handle been pet within the current window? pub fn is_pet(&self) -> bool { - let r = unsafe { &*WDT::ptr() }; - let rd = r.reqstatus.read().bits(); - let idx = self.index as usize; - ((rd >> idx) & 0x1) == 0 + let r = crate::pac::WDT; + !r.reqstatus().read().rr(self.index as usize) } /// Steal a watchdog handle by index. /// - /// Safety: watchdog must be initialized, index must be between 0 and N-1 where - /// N is the handle count when initializing. + /// # Safety + /// Watchdog must be initialized and `index` must be between `0` and `N-1` + /// where `N` is the handle count when initializing. pub unsafe fn steal(index: u8) -> Self { Self { index } } diff --git a/embassy-nxp/Cargo.toml b/embassy-nxp/Cargo.toml new file mode 100644 index 000000000..df329be66 --- /dev/null +++ b/embassy-nxp/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "embassy-nxp" +version = "0.1.0" +edition = "2021" + +[dependencies] +cortex-m = "0.7.7" +cortex-m-rt = "0.7.0" +critical-section = "1.1.2" +embassy-hal-internal = {version = "0.2.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-2"] } +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } +lpc55-pac = "0.5.0" +defmt = "0.3.8" + +[features] +default = ["rt"] +rt = ["lpc55-pac/rt"] \ No newline at end of file diff --git a/embassy-nxp/src/gpio.rs b/embassy-nxp/src/gpio.rs new file mode 100644 index 000000000..d5d04ee69 --- /dev/null +++ b/embassy-nxp/src/gpio.rs @@ -0,0 +1,361 @@ +use embassy_hal_internal::impl_peripheral; + +use crate::pac_utils::*; +use crate::{peripherals, Peripheral, PeripheralRef}; + +pub(crate) fn init() { + // Enable clocks for GPIO, PINT, and IOCON + syscon_reg() + .ahbclkctrl0 + .modify(|_, w| w.gpio0().enable().gpio1().enable().mux().enable().iocon().enable()); +} + +/// The GPIO pin level for pins set on "Digital" mode. +#[derive(Debug, Eq, PartialEq, Clone, Copy)] +pub enum Level { + /// Logical low. Corresponds to 0V. + Low, + /// Logical high. Corresponds to VDD. + High, +} + +/// Pull setting for a GPIO input set on "Digital" mode. +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub enum Pull { + /// No pull. + None, + /// Internal pull-up resistor. + Up, + /// Internal pull-down resistor. + Down, +} + +/// The LPC55 boards have two GPIO banks, each with 32 pins. This enum represents the two banks. +#[derive(Debug, Eq, PartialEq, Clone, Copy)] +pub enum Bank { + Bank0 = 0, + Bank1 = 1, +} + +/// GPIO output driver. Internally, this is a specialized [Flex] pin. +pub struct Output<'d> { + pub(crate) pin: Flex<'d>, +} + +impl<'d> Output<'d> { + /// Create GPIO output driver for a [Pin] with the provided [initial output](Level). + #[inline] + pub fn new(pin: impl Peripheral

+ 'd, initial_output: Level) -> Self { + let mut pin = Flex::new(pin); + pin.set_as_output(); + let mut result = Self { pin }; + + match initial_output { + Level::High => result.set_high(), + Level::Low => result.set_low(), + }; + + result + } + + pub fn set_high(&mut self) { + gpio_reg().set[self.pin.pin_bank() as usize].write(|w| unsafe { w.bits(self.pin.bit()) }) + } + + pub fn set_low(&mut self) { + gpio_reg().clr[self.pin.pin_bank() as usize].write(|w| unsafe { w.bits(self.pin.bit()) }) + } + + pub fn toggle(&mut self) { + gpio_reg().not[self.pin.pin_bank() as usize].write(|w| unsafe { w.bits(self.pin.bit()) }) + } + + /// Get the current output level of the pin. Note that the value returned by this function is + /// the voltage level reported by the pin, not the value set by the output driver. + pub fn level(&self) -> Level { + let bits = gpio_reg().pin[self.pin.pin_bank() as usize].read().bits(); + if bits & self.pin.bit() != 0 { + Level::High + } else { + Level::Low + } + } +} + +/// GPIO input driver. Internally, this is a specialized [Flex] pin. +pub struct Input<'d> { + pub(crate) pin: Flex<'d>, +} + +impl<'d> Input<'d> { + /// Create GPIO output driver for a [Pin] with the provided [Pull]. + #[inline] + pub fn new(pin: impl Peripheral

+ 'd, pull: Pull) -> Self { + let mut pin = Flex::new(pin); + pin.set_as_input(); + let mut result = Self { pin }; + result.set_pull(pull); + + result + } + + /// Set the pull configuration for the pin. To disable the pull, use [Pull::None]. + pub fn set_pull(&mut self, pull: Pull) { + match_iocon!(register, iocon_reg(), self.pin.pin_bank(), self.pin.pin_number(), { + register.modify(|_, w| match pull { + Pull::None => w.mode().inactive(), + Pull::Up => w.mode().pull_up(), + Pull::Down => w.mode().pull_down(), + }); + }); + } + + /// Get the current input level of the pin. + pub fn read(&self) -> Level { + let bits = gpio_reg().pin[self.pin.pin_bank() as usize].read().bits(); + if bits & self.pin.bit() != 0 { + Level::High + } else { + Level::Low + } + } +} + +/// A flexible GPIO (digital mode) pin whose mode is not yet determined. Under the hood, this is a +/// reference to a type-erased pin called ["AnyPin"](AnyPin). +pub struct Flex<'d> { + pub(crate) pin: PeripheralRef<'d, AnyPin>, +} + +impl<'d> Flex<'d> { + /// Wrap the pin in a `Flex`. + /// + /// Note: you cannot assume that the pin will be in Digital mode after this call. + #[inline] + pub fn new(pin: impl Peripheral

+ 'd) -> Self { + Self { + pin: pin.into_ref().map_into(), + } + } + + /// Get the bank of this pin. See also [Bank]. + /// + /// # Example + /// + /// ``` + /// use embassy_nxp::gpio::{Bank, Flex}; + /// + /// let p = embassy_nxp::init(Default::default()); + /// let pin = Flex::new(p.PIO1_15); + /// + /// assert_eq!(pin.pin_bank(), Bank::Bank1); + /// ``` + pub fn pin_bank(&self) -> Bank { + self.pin.pin_bank() + } + + /// Get the number of this pin within its bank. See also [Bank]. + /// + /// # Example + /// + /// ``` + /// use embassy_nxp::gpio::Flex; + /// + /// let p = embassy_nxp::init(Default::default()); + /// let pin = Flex::new(p.PIO1_15); + /// + /// assert_eq!(pin.pin_number(), 15 as u8); + /// ``` + pub fn pin_number(&self) -> u8 { + self.pin.pin_number() + } + + /// Get the bit mask for this pin. Useful for setting or clearing bits in a register. Note: + /// PIOx_0 is bit 0, PIOx_1 is bit 1, etc. + /// + /// # Example + /// + /// ``` + /// use embassy_nxp::gpio::Flex; + /// + /// let p = embassy_nxp::init(Default::default()); + /// let pin = Flex::new(p.PIO1_3); + /// + /// assert_eq!(pin.bit(), 0b0000_1000); + /// ``` + pub fn bit(&self) -> u32 { + 1 << self.pin.pin_number() + } + + /// Set the pin to digital mode. This is required for using a pin as a GPIO pin. The default + /// setting for pins is (usually) non-digital. + fn set_as_digital(&mut self) { + match_iocon!(register, iocon_reg(), self.pin_bank(), self.pin_number(), { + register.modify(|_, w| w.digimode().digital()); + }); + } + + /// Set the pin in output mode. This implies setting the pin to digital mode, which this + /// function handles itself. + pub fn set_as_output(&mut self) { + self.set_as_digital(); + gpio_reg().dirset[self.pin.pin_bank() as usize].write(|w| unsafe { w.dirsetp().bits(self.bit()) }) + } + + pub fn set_as_input(&mut self) { + self.set_as_digital(); + gpio_reg().dirclr[self.pin.pin_bank() as usize].write(|w| unsafe { w.dirclrp().bits(self.bit()) }) + } +} + +/// Sealed trait for pins. This trait is sealed and cannot be implemented outside of this crate. +pub(crate) trait SealedPin: Sized { + fn pin_bank(&self) -> Bank; + fn pin_number(&self) -> u8; +} + +/// Interface for a Pin that can be configured by an [Input] or [Output] driver, or converted to an +/// [AnyPin]. By default, this trait is sealed and cannot be implemented outside of the +/// `embassy-nxp` crate due to the [SealedPin] trait. +#[allow(private_bounds)] +pub trait Pin: Peripheral

+ Into + SealedPin + Sized + 'static { + /// Degrade to a generic pin struct + fn degrade(self) -> AnyPin { + AnyPin { + pin_bank: self.pin_bank(), + pin_number: self.pin_number(), + } + } + + /// Returns the pin number within a bank + #[inline] + fn pin(&self) -> u8 { + self.pin_number() + } + + /// Returns the bank of this pin + #[inline] + fn bank(&self) -> Bank { + self.pin_bank() + } +} + +/// Type-erased GPIO pin. +pub struct AnyPin { + pin_bank: Bank, + pin_number: u8, +} + +impl AnyPin { + /// Unsafely create a new type-erased pin. + /// + /// # Safety + /// + /// You must ensure that you’re only using one instance of this type at a time. + pub unsafe fn steal(pin_bank: Bank, pin_number: u8) -> Self { + Self { pin_bank, pin_number } + } +} + +impl_peripheral!(AnyPin); + +impl Pin for AnyPin {} +impl SealedPin for AnyPin { + #[inline] + fn pin_bank(&self) -> Bank { + self.pin_bank + } + + #[inline] + fn pin_number(&self) -> u8 { + self.pin_number + } +} + +macro_rules! impl_pin { + ($name:ident, $bank:expr, $pin_num:expr) => { + impl Pin for peripherals::$name {} + impl SealedPin for peripherals::$name { + #[inline] + fn pin_bank(&self) -> Bank { + $bank + } + + #[inline] + fn pin_number(&self) -> u8 { + $pin_num + } + } + + impl From for crate::gpio::AnyPin { + fn from(val: peripherals::$name) -> Self { + crate::gpio::Pin::degrade(val) + } + } + }; +} + +impl_pin!(PIO0_0, Bank::Bank0, 0); +impl_pin!(PIO0_1, Bank::Bank0, 1); +impl_pin!(PIO0_2, Bank::Bank0, 2); +impl_pin!(PIO0_3, Bank::Bank0, 3); +impl_pin!(PIO0_4, Bank::Bank0, 4); +impl_pin!(PIO0_5, Bank::Bank0, 5); +impl_pin!(PIO0_6, Bank::Bank0, 6); +impl_pin!(PIO0_7, Bank::Bank0, 7); +impl_pin!(PIO0_8, Bank::Bank0, 8); +impl_pin!(PIO0_9, Bank::Bank0, 9); +impl_pin!(PIO0_10, Bank::Bank0, 10); +impl_pin!(PIO0_11, Bank::Bank0, 11); +impl_pin!(PIO0_12, Bank::Bank0, 12); +impl_pin!(PIO0_13, Bank::Bank0, 13); +impl_pin!(PIO0_14, Bank::Bank0, 14); +impl_pin!(PIO0_15, Bank::Bank0, 15); +impl_pin!(PIO0_16, Bank::Bank0, 16); +impl_pin!(PIO0_17, Bank::Bank0, 17); +impl_pin!(PIO0_18, Bank::Bank0, 18); +impl_pin!(PIO0_19, Bank::Bank0, 19); +impl_pin!(PIO0_20, Bank::Bank0, 20); +impl_pin!(PIO0_21, Bank::Bank0, 21); +impl_pin!(PIO0_22, Bank::Bank0, 22); +impl_pin!(PIO0_23, Bank::Bank0, 23); +impl_pin!(PIO0_24, Bank::Bank0, 24); +impl_pin!(PIO0_25, Bank::Bank0, 25); +impl_pin!(PIO0_26, Bank::Bank0, 26); +impl_pin!(PIO0_27, Bank::Bank0, 27); +impl_pin!(PIO0_28, Bank::Bank0, 28); +impl_pin!(PIO0_29, Bank::Bank0, 29); +impl_pin!(PIO0_30, Bank::Bank0, 30); +impl_pin!(PIO0_31, Bank::Bank0, 31); +impl_pin!(PIO1_0, Bank::Bank1, 0); +impl_pin!(PIO1_1, Bank::Bank1, 1); +impl_pin!(PIO1_2, Bank::Bank1, 2); +impl_pin!(PIO1_3, Bank::Bank1, 3); +impl_pin!(PIO1_4, Bank::Bank1, 4); +impl_pin!(PIO1_5, Bank::Bank1, 5); +impl_pin!(PIO1_6, Bank::Bank1, 6); +impl_pin!(PIO1_7, Bank::Bank1, 7); +impl_pin!(PIO1_8, Bank::Bank1, 8); +impl_pin!(PIO1_9, Bank::Bank1, 9); +impl_pin!(PIO1_10, Bank::Bank1, 10); +impl_pin!(PIO1_11, Bank::Bank1, 11); +impl_pin!(PIO1_12, Bank::Bank1, 12); +impl_pin!(PIO1_13, Bank::Bank1, 13); +impl_pin!(PIO1_14, Bank::Bank1, 14); +impl_pin!(PIO1_15, Bank::Bank1, 15); +impl_pin!(PIO1_16, Bank::Bank1, 16); +impl_pin!(PIO1_17, Bank::Bank1, 17); +impl_pin!(PIO1_18, Bank::Bank1, 18); +impl_pin!(PIO1_19, Bank::Bank1, 19); +impl_pin!(PIO1_20, Bank::Bank1, 20); +impl_pin!(PIO1_21, Bank::Bank1, 21); +impl_pin!(PIO1_22, Bank::Bank1, 22); +impl_pin!(PIO1_23, Bank::Bank1, 23); +impl_pin!(PIO1_24, Bank::Bank1, 24); +impl_pin!(PIO1_25, Bank::Bank1, 25); +impl_pin!(PIO1_26, Bank::Bank1, 26); +impl_pin!(PIO1_27, Bank::Bank1, 27); +impl_pin!(PIO1_28, Bank::Bank1, 28); +impl_pin!(PIO1_29, Bank::Bank1, 29); +impl_pin!(PIO1_30, Bank::Bank1, 30); +impl_pin!(PIO1_31, Bank::Bank1, 31); diff --git a/embassy-nxp/src/lib.rs b/embassy-nxp/src/lib.rs new file mode 100644 index 000000000..80fdecb2e --- /dev/null +++ b/embassy-nxp/src/lib.rs @@ -0,0 +1,95 @@ +#![no_std] + +pub mod gpio; +mod pac_utils; +pub mod pint; + +pub use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef}; +pub use lpc55_pac as pac; + +/// Initialize the `embassy-nxp` HAL with the provided configuration. +/// +/// This returns the peripheral singletons that can be used for creating drivers. +/// +/// This should only be called once and at startup, otherwise it panics. +pub fn init(_config: config::Config) -> Peripherals { + gpio::init(); + pint::init(); + + crate::Peripherals::take() +} + +embassy_hal_internal::peripherals! { + // External pins. These are not only GPIOs, they are multi-purpose pins and can be used by other + // peripheral types (e.g. I2C). + PIO0_0, + PIO0_1, + PIO0_2, + PIO0_3, + PIO0_4, + PIO0_5, + PIO0_6, + PIO0_7, + PIO0_8, + PIO0_9, + PIO0_10, + PIO0_11, + PIO0_12, + PIO0_13, + PIO0_14, + PIO0_15, + PIO0_16, + PIO0_17, + PIO0_18, + PIO0_19, + PIO0_20, + PIO0_21, + PIO0_22, + PIO0_23, + PIO0_24, + PIO0_25, + PIO0_26, + PIO0_27, + PIO0_28, + PIO0_29, + PIO0_30, + PIO0_31, + PIO1_0, + PIO1_1, + PIO1_2, + PIO1_3, + PIO1_4, + PIO1_5, + PIO1_6, + PIO1_7, + PIO1_8, + PIO1_9, + PIO1_10, + PIO1_11, + PIO1_12, + PIO1_13, + PIO1_14, + PIO1_15, + PIO1_16, + PIO1_17, + PIO1_18, + PIO1_19, + PIO1_20, + PIO1_21, + PIO1_22, + PIO1_23, + PIO1_24, + PIO1_25, + PIO1_26, + PIO1_27, + PIO1_28, + PIO1_29, + PIO1_30, + PIO1_31, +} + +/// HAL configuration for the NXP board. +pub mod config { + #[derive(Default)] + pub struct Config {} +} diff --git a/embassy-nxp/src/pac_utils.rs b/embassy-nxp/src/pac_utils.rs new file mode 100644 index 000000000..86a807f6c --- /dev/null +++ b/embassy-nxp/src/pac_utils.rs @@ -0,0 +1,323 @@ +/// Get the GPIO register block. This is used to configure all GPIO pins. +/// +/// # Safety +/// Due to the type system of peripherals, access to the settings of a single pin is possible only +/// by a single thread at a time. Read/Write operations on a single registers are NOT atomic. You +/// must ensure that the GPIO registers are not accessed concurrently by multiple threads. +pub(crate) fn gpio_reg() -> &'static lpc55_pac::gpio::RegisterBlock { + unsafe { &*lpc55_pac::GPIO::ptr() } +} + +/// Get the IOCON register block. +/// +/// # Safety +/// Read/Write operations on a single registers are NOT atomic. You must ensure that the GPIO +/// registers are not accessed concurrently by multiple threads. +pub(crate) fn iocon_reg() -> &'static lpc55_pac::iocon::RegisterBlock { + unsafe { &*lpc55_pac::IOCON::ptr() } +} + +/// Get the INPUTMUX register block. +/// +/// # Safety +/// Read/Write operations on a single registers are NOT atomic. You must ensure that the GPIO +/// registers are not accessed concurrently by multiple threads. +pub(crate) fn inputmux_reg() -> &'static lpc55_pac::inputmux::RegisterBlock { + unsafe { &*lpc55_pac::INPUTMUX::ptr() } +} + +/// Get the SYSCON register block. +/// +/// # Safety +/// Read/Write operations on a single registers are NOT atomic. You must ensure that the GPIO +/// registers are not accessed concurrently by multiple threads. +pub(crate) fn syscon_reg() -> &'static lpc55_pac::syscon::RegisterBlock { + unsafe { &*lpc55_pac::SYSCON::ptr() } +} + +/// Get the PINT register block. +/// +/// # Safety +/// Read/Write operations on a single registers are NOT atomic. You must ensure that the GPIO +/// registers are not accessed concurrently by multiple threads. +pub(crate) fn pint_reg() -> &'static lpc55_pac::pint::RegisterBlock { + unsafe { &*lpc55_pac::PINT::ptr() } +} + +/// Match the pin bank and number of a pin to the corresponding IOCON register. +/// +/// # Example +/// ``` +/// use embassy_nxp::gpio::Bank; +/// use embassy_nxp::pac_utils::{iocon_reg, match_iocon}; +/// +/// // Make pin PIO1_6 digital and set it to pull-down mode. +/// match_iocon!(register, iocon_reg(), Bank::Bank1, 6, { +/// register.modify(|_, w| w.mode().pull_down().digimode().digital()); +/// }); +/// ``` +macro_rules! match_iocon { + ($register:ident, $iocon_register:expr, $pin_bank:expr, $pin_number:expr, $action:expr) => { + match ($pin_bank, $pin_number) { + (Bank::Bank0, 0) => { + let $register = &($iocon_register).pio0_0; + $action; + } + (Bank::Bank0, 1) => { + let $register = &($iocon_register).pio0_1; + $action; + } + (Bank::Bank0, 2) => { + let $register = &($iocon_register).pio0_2; + $action; + } + (Bank::Bank0, 3) => { + let $register = &($iocon_register).pio0_3; + $action; + } + (Bank::Bank0, 4) => { + let $register = &($iocon_register).pio0_4; + $action; + } + (Bank::Bank0, 5) => { + let $register = &($iocon_register).pio0_5; + $action; + } + (Bank::Bank0, 6) => { + let $register = &($iocon_register).pio0_6; + $action; + } + (Bank::Bank0, 7) => { + let $register = &($iocon_register).pio0_7; + $action; + } + (Bank::Bank0, 8) => { + let $register = &($iocon_register).pio0_8; + $action; + } + (Bank::Bank0, 9) => { + let $register = &($iocon_register).pio0_9; + $action; + } + (Bank::Bank0, 10) => { + let $register = &($iocon_register).pio0_10; + $action; + } + (Bank::Bank0, 11) => { + let $register = &($iocon_register).pio0_11; + $action; + } + (Bank::Bank0, 12) => { + let $register = &($iocon_register).pio0_12; + $action; + } + (Bank::Bank0, 13) => { + let $register = &($iocon_register).pio0_13; + $action; + } + (Bank::Bank0, 14) => { + let $register = &($iocon_register).pio0_14; + $action; + } + (Bank::Bank0, 15) => { + let $register = &($iocon_register).pio0_15; + $action; + } + (Bank::Bank0, 16) => { + let $register = &($iocon_register).pio0_16; + $action; + } + (Bank::Bank0, 17) => { + let $register = &($iocon_register).pio0_17; + $action; + } + (Bank::Bank0, 18) => { + let $register = &($iocon_register).pio0_18; + $action; + } + (Bank::Bank0, 19) => { + let $register = &($iocon_register).pio0_19; + $action; + } + (Bank::Bank0, 20) => { + let $register = &($iocon_register).pio0_20; + $action; + } + (Bank::Bank0, 21) => { + let $register = &($iocon_register).pio0_21; + $action; + } + (Bank::Bank0, 22) => { + let $register = &($iocon_register).pio0_22; + $action; + } + (Bank::Bank0, 23) => { + let $register = &($iocon_register).pio0_23; + $action; + } + (Bank::Bank0, 24) => { + let $register = &($iocon_register).pio0_24; + $action; + } + (Bank::Bank0, 25) => { + let $register = &($iocon_register).pio0_25; + $action; + } + (Bank::Bank0, 26) => { + let $register = &($iocon_register).pio0_26; + $action; + } + (Bank::Bank0, 27) => { + let $register = &($iocon_register).pio0_27; + $action; + } + (Bank::Bank0, 28) => { + let $register = &($iocon_register).pio0_28; + $action; + } + (Bank::Bank0, 29) => { + let $register = &($iocon_register).pio0_29; + $action; + } + (Bank::Bank0, 30) => { + let $register = &($iocon_register).pio0_30; + $action; + } + (Bank::Bank0, 31) => { + let $register = &($iocon_register).pio0_31; + $action; + } + (Bank::Bank1, 0) => { + let $register = &($iocon_register).pio1_0; + $action; + } + (Bank::Bank1, 1) => { + let $register = &($iocon_register).pio1_1; + $action; + } + (Bank::Bank1, 2) => { + let $register = &($iocon_register).pio1_2; + $action; + } + (Bank::Bank1, 3) => { + let $register = &($iocon_register).pio1_3; + $action; + } + (Bank::Bank1, 4) => { + let $register = &($iocon_register).pio1_4; + $action; + } + (Bank::Bank1, 5) => { + let $register = &($iocon_register).pio1_5; + $action; + } + (Bank::Bank1, 6) => { + let $register = &($iocon_register).pio1_6; + $action; + } + (Bank::Bank1, 7) => { + let $register = &($iocon_register).pio1_7; + $action; + } + (Bank::Bank1, 8) => { + let $register = &($iocon_register).pio1_8; + $action; + } + (Bank::Bank1, 9) => { + let $register = &($iocon_register).pio1_9; + $action; + } + (Bank::Bank1, 10) => { + let $register = &($iocon_register).pio1_10; + $action; + } + (Bank::Bank1, 11) => { + let $register = &($iocon_register).pio1_11; + $action; + } + (Bank::Bank1, 12) => { + let $register = &($iocon_register).pio1_12; + $action; + } + (Bank::Bank1, 13) => { + let $register = &($iocon_register).pio1_13; + $action; + } + (Bank::Bank1, 14) => { + let $register = &($iocon_register).pio1_14; + $action; + } + (Bank::Bank1, 15) => { + let $register = &($iocon_register).pio1_15; + $action; + } + (Bank::Bank1, 16) => { + let $register = &($iocon_register).pio1_16; + $action; + } + (Bank::Bank1, 17) => { + let $register = &($iocon_register).pio1_17; + $action; + } + (Bank::Bank1, 18) => { + let $register = &($iocon_register).pio1_18; + $action; + } + (Bank::Bank1, 19) => { + let $register = &($iocon_register).pio1_19; + $action; + } + (Bank::Bank1, 20) => { + let $register = &($iocon_register).pio1_20; + $action; + } + (Bank::Bank1, 21) => { + let $register = &($iocon_register).pio1_21; + $action; + } + (Bank::Bank1, 22) => { + let $register = &($iocon_register).pio1_22; + $action; + } + (Bank::Bank1, 23) => { + let $register = &($iocon_register).pio1_23; + $action; + } + (Bank::Bank1, 24) => { + let $register = &($iocon_register).pio1_24; + $action; + } + (Bank::Bank1, 25) => { + let $register = &($iocon_register).pio1_25; + $action; + } + (Bank::Bank1, 26) => { + let $register = &($iocon_register).pio1_26; + $action; + } + (Bank::Bank1, 27) => { + let $register = &($iocon_register).pio1_27; + $action; + } + (Bank::Bank1, 28) => { + let $register = &($iocon_register).pio1_28; + $action; + } + (Bank::Bank1, 29) => { + let $register = &($iocon_register).pio1_29; + $action; + } + (Bank::Bank1, 30) => { + let $register = &($iocon_register).pio1_30; + $action; + } + (Bank::Bank1, 31) => { + let $register = &($iocon_register).pio1_31; + $action; + } + _ => unreachable!(), + } + }; +} + +pub(crate) use match_iocon; diff --git a/embassy-nxp/src/pint.rs b/embassy-nxp/src/pint.rs new file mode 100644 index 000000000..3313f91a6 --- /dev/null +++ b/embassy-nxp/src/pint.rs @@ -0,0 +1,440 @@ +//! Pin Interrupt module. +use core::cell::RefCell; +use core::future::Future; +use core::pin::Pin as FuturePin; +use core::task::{Context, Poll}; + +use critical_section::Mutex; +use embassy_hal_internal::{Peripheral, PeripheralRef}; +use embassy_sync::waitqueue::AtomicWaker; + +use crate::gpio::{self, AnyPin, Level, SealedPin}; +use crate::pac::interrupt; +use crate::pac_utils::*; + +struct PinInterrupt { + assigned: bool, + waker: AtomicWaker, + /// If true, the interrupt was triggered due to this PinInterrupt. This is used to determine if + /// an [InputFuture] should return Poll::Ready. + at_fault: bool, +} + +impl PinInterrupt { + pub fn interrupt_active(&self) -> bool { + self.assigned + } + + /// Mark the interrupt as assigned to a pin. + pub fn enable(&mut self) { + self.assigned = true; + self.at_fault = false; + } + + /// Mark the interrupt as available. + pub fn disable(&mut self) { + self.assigned = false; + self.at_fault = false; + } + + /// Returns true if the interrupt was triggered due to this PinInterrupt. + /// + /// If this function returns true, it will also reset the at_fault flag. + pub fn at_fault(&mut self) -> bool { + let val = self.at_fault; + self.at_fault = false; + val + } + + /// Set the at_fault flag to true. + pub fn fault(&mut self) { + self.at_fault = true; + } +} + +const NEW_PIN_INTERRUPT: PinInterrupt = PinInterrupt { + assigned: false, + waker: AtomicWaker::new(), + at_fault: false, +}; +const INTERUPT_COUNT: usize = 8; +static PIN_INTERRUPTS: Mutex> = + Mutex::new(RefCell::new([NEW_PIN_INTERRUPT; INTERUPT_COUNT])); + +fn next_available_interrupt() -> Option { + critical_section::with(|cs| { + for (i, pin_interrupt) in PIN_INTERRUPTS.borrow(cs).borrow().iter().enumerate() { + if !pin_interrupt.interrupt_active() { + return Some(i); + } + } + + None + }) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Edge { + Rising, + Falling, + Both, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum InterruptOn { + Level(Level), + Edge(Edge), +} + +pub(crate) fn init() { + syscon_reg().ahbclkctrl0.modify(|_, w| w.pint().enable()); + + // Enable interrupts + unsafe { + crate::pac::NVIC::unmask(crate::pac::Interrupt::PIN_INT0); + crate::pac::NVIC::unmask(crate::pac::Interrupt::PIN_INT1); + crate::pac::NVIC::unmask(crate::pac::Interrupt::PIN_INT2); + crate::pac::NVIC::unmask(crate::pac::Interrupt::PIN_INT3); + crate::pac::NVIC::unmask(crate::pac::Interrupt::PIN_INT4); + crate::pac::NVIC::unmask(crate::pac::Interrupt::PIN_INT5); + crate::pac::NVIC::unmask(crate::pac::Interrupt::PIN_INT6); + crate::pac::NVIC::unmask(crate::pac::Interrupt::PIN_INT7); + }; +} + +#[must_use = "futures do nothing unless you `.await` or poll them"] +struct InputFuture<'d> { + #[allow(dead_code)] + pin: PeripheralRef<'d, AnyPin>, + interrupt_number: usize, +} + +impl<'d> InputFuture<'d> { + /// Create a new input future. Returns None if all interrupts are in use. + fn new(pin: impl Peripheral

+ 'd, interrupt_on: InterruptOn) -> Option { + let pin = pin.into_ref().map_into(); + let interrupt_number = next_available_interrupt()?; + + // Clear interrupt, just in case + pint_reg() + .rise + .write(|w| unsafe { w.rdet().bits(1 << interrupt_number) }); + pint_reg() + .fall + .write(|w| unsafe { w.fdet().bits(1 << interrupt_number) }); + + // Enable input multiplexing on pin interrupt register 0 for pin (32*bank + pin_number) + inputmux_reg().pintsel[interrupt_number] + .write(|w| unsafe { w.intpin().bits(32 * pin.pin_bank() as u8 + pin.pin_number()) }); + + match interrupt_on { + InterruptOn::Level(level) => { + // Set pin interrupt register to edge sensitive or level sensitive + // 0 = edge sensitive, 1 = level sensitive + pint_reg() + .isel + .modify(|r, w| unsafe { w.bits(r.bits() | (1 << interrupt_number)) }); + + // Enable level interrupt. + // + // Note: Level sensitive interrupts are enabled by the same register as rising edge + // is activated. + + // 0 = no-op, 1 = enable + pint_reg() + .sienr + .write(|w| unsafe { w.setenrl().bits(1 << interrupt_number) }); + + // Set active level + match level { + Level::Low => { + // 0 = no-op, 1 = select LOW + pint_reg() + .cienf + .write(|w| unsafe { w.cenaf().bits(1 << interrupt_number) }); + } + Level::High => { + // 0 = no-op, 1 = select HIGH + pint_reg() + .sienf + .write(|w| unsafe { w.setenaf().bits(1 << interrupt_number) }); + } + } + } + InterruptOn::Edge(edge) => { + // Set pin interrupt register to edge sensitive or level sensitive + // 0 = edge sensitive, 1 = level sensitive + pint_reg() + .isel + .modify(|r, w| unsafe { w.bits(r.bits() & !(1 << interrupt_number)) }); + + // Enable rising/falling edge detection + match edge { + Edge::Rising => { + // 0 = no-op, 1 = enable rising edge + pint_reg() + .sienr + .write(|w| unsafe { w.setenrl().bits(1 << interrupt_number) }); + // 0 = no-op, 1 = disable falling edge + pint_reg() + .cienf + .write(|w| unsafe { w.cenaf().bits(1 << interrupt_number) }); + } + Edge::Falling => { + // 0 = no-op, 1 = enable falling edge + pint_reg() + .sienf + .write(|w| unsafe { w.setenaf().bits(1 << interrupt_number) }); + // 0 = no-op, 1 = disable rising edge + pint_reg() + .cienr + .write(|w| unsafe { w.cenrl().bits(1 << interrupt_number) }); + } + Edge::Both => { + // 0 = no-op, 1 = enable + pint_reg() + .sienr + .write(|w| unsafe { w.setenrl().bits(1 << interrupt_number) }); + pint_reg() + .sienf + .write(|w| unsafe { w.setenaf().bits(1 << interrupt_number) }); + } + } + } + } + + critical_section::with(|cs| { + let mut pin_interrupts = PIN_INTERRUPTS.borrow(cs).borrow_mut(); + let pin_interrupt = &mut pin_interrupts[interrupt_number]; + + pin_interrupt.enable(); + }); + + Some(Self { pin, interrupt_number }) + } + + /// Returns true if the interrupt was triggered for this pin. + fn interrupt_triggered(&self) -> bool { + let interrupt_number = self.interrupt_number; + + // Initially, we determine if the interrupt was triggered by this InputFuture by checking + // the flags of the interrupt_number. However, by the time we get to this point, the + // interrupt may have been triggered again, so we needed to clear the cpu flags immediately. + // As a solution, we mark which [PinInterrupt] is responsible for the interrupt ("at fault") + critical_section::with(|cs| { + let mut pin_interrupts = PIN_INTERRUPTS.borrow(cs).borrow_mut(); + let pin_interrupt = &mut pin_interrupts[interrupt_number]; + + pin_interrupt.at_fault() + }) + } +} + +impl<'d> Drop for InputFuture<'d> { + fn drop(&mut self) { + let interrupt_number = self.interrupt_number; + + // Disable pin interrupt + // 0 = no-op, 1 = disable + pint_reg() + .cienr + .write(|w| unsafe { w.cenrl().bits(1 << interrupt_number) }); + pint_reg() + .cienf + .write(|w| unsafe { w.cenaf().bits(1 << interrupt_number) }); + + critical_section::with(|cs| { + let mut pin_interrupts = PIN_INTERRUPTS.borrow(cs).borrow_mut(); + let pin_interrupt = &mut pin_interrupts[interrupt_number]; + + pin_interrupt.disable(); + }); + } +} + +impl<'d> Future for InputFuture<'d> { + type Output = (); + + fn poll(self: FuturePin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let interrupt_number = self.interrupt_number; + + critical_section::with(|cs| { + let mut pin_interrupts = PIN_INTERRUPTS.borrow(cs).borrow_mut(); + let pin_interrupt = &mut pin_interrupts[interrupt_number]; + + pin_interrupt.waker.register(cx.waker()); + }); + + if self.interrupt_triggered() { + Poll::Ready(()) + } else { + Poll::Pending + } + } +} + +fn handle_interrupt(interrupt_number: usize) { + pint_reg() + .rise + .write(|w| unsafe { w.rdet().bits(1 << interrupt_number) }); + pint_reg() + .fall + .write(|w| unsafe { w.fdet().bits(1 << interrupt_number) }); + + critical_section::with(|cs| { + let mut pin_interrupts = PIN_INTERRUPTS.borrow(cs).borrow_mut(); + let pin_interrupt = &mut pin_interrupts[interrupt_number]; + + pin_interrupt.fault(); + pin_interrupt.waker.wake(); + }); +} + +#[allow(non_snake_case)] +#[interrupt] +fn PIN_INT0() { + handle_interrupt(0); +} + +#[allow(non_snake_case)] +#[interrupt] +fn PIN_INT1() { + handle_interrupt(1); +} + +#[allow(non_snake_case)] +#[interrupt] +fn PIN_INT2() { + handle_interrupt(2); +} + +#[allow(non_snake_case)] +#[interrupt] +fn PIN_INT3() { + handle_interrupt(3); +} + +#[allow(non_snake_case)] +#[interrupt] +fn PIN_INT4() { + handle_interrupt(4); +} + +#[allow(non_snake_case)] +#[interrupt] +fn PIN_INT5() { + handle_interrupt(5); +} + +#[allow(non_snake_case)] +#[interrupt] +fn PIN_INT6() { + handle_interrupt(6); +} + +#[allow(non_snake_case)] +#[interrupt] +fn PIN_INT7() { + handle_interrupt(7); +} + +impl gpio::Flex<'_> { + /// Wait for a falling or rising edge on the pin. You can have at most 8 pins waiting. If you + /// try to wait for more than 8 pins, this function will return `None`. + pub async fn wait_for_any_edge(&mut self) -> Option<()> { + InputFuture::new(&mut self.pin, InterruptOn::Edge(Edge::Both))?.await; + Some(()) + } + + /// Wait for a falling edge on the pin. You can have at most 8 pins waiting. If you try to wait + /// for more than 8 pins, this function will return `None`. + pub async fn wait_for_falling_edge(&mut self) -> Option<()> { + InputFuture::new(&mut self.pin, InterruptOn::Edge(Edge::Falling))?.await; + Some(()) + } + + /// Wait for a rising edge on the pin. You can have at most 8 pins waiting. If you try to wait + /// for more than 8 pins, this function will return `None`. + pub async fn wait_for_rising_edge(&mut self) -> Option<()> { + InputFuture::new(&mut self.pin, InterruptOn::Edge(Edge::Rising))?.await; + Some(()) + } + + /// Wait for a low level on the pin. You can have at most 8 pins waiting. If you try to wait for + /// more than 8 pins, this function will return `None`. + pub async fn wait_for_low(&mut self) -> Option<()> { + InputFuture::new(&mut self.pin, InterruptOn::Level(Level::Low))?.await; + Some(()) + } + + /// Wait for a high level on the pin. You can have at most 8 pins waiting. If you try to wait for + /// more than 8 pins, this function will return `None`. + pub async fn wait_for_high(&mut self) -> Option<()> { + InputFuture::new(&mut self.pin, InterruptOn::Level(Level::High))?.await; + Some(()) + } +} + +impl gpio::Input<'_> { + /// Wait for a falling or rising edge on the pin. You can have at most 8 pins waiting. If you + /// try to wait for more than 8 pins, this function will return `None`. + pub async fn wait_for_any_edge(&mut self) -> Option<()> { + self.pin.wait_for_any_edge().await + } + + /// Wait for a falling edge on the pin. You can have at most 8 pins waiting. If you try to wait + /// for more than 8 pins, this function will return `None`. + pub async fn wait_for_falling_edge(&mut self) -> Option<()> { + self.pin.wait_for_falling_edge().await + } + + /// Wait for a rising edge on the pin. You can have at most 8 pins waiting. If you try to wait + /// for more than 8 pins, this function will return `None`. + pub async fn wait_for_rising_edge(&mut self) -> Option<()> { + self.pin.wait_for_rising_edge().await + } + + /// Wait for a low level on the pin. You can have at most 8 pins waiting. If you try to wait for + /// more than 8 pins, this function will return `None`. + pub async fn wait_for_low(&mut self) -> Option<()> { + self.pin.wait_for_low().await + } + + /// Wait for a high level on the pin. You can have at most 8 pins waiting. If you try to wait for + /// more than 8 pins, this function will return `None`. + pub async fn wait_for_high(&mut self) -> Option<()> { + self.pin.wait_for_high().await + } +} + +impl gpio::Output<'_> { + /// Wait for a falling or rising edge on the pin. You can have at most 8 pins waiting. If you + /// try to wait for more than 8 pins, this function will return `None`. + pub async fn wait_for_any_edge(&mut self) -> Option<()> { + self.pin.wait_for_any_edge().await + } + + /// Wait for a falling edge on the pin. You can have at most 8 pins waiting. If you try to wait + /// for more than 8 pins, this function will return `None`. + pub async fn wait_for_falling_edge(&mut self) -> Option<()> { + self.pin.wait_for_falling_edge().await + } + + /// Wait for a rising edge on the pin. You can have at most 8 pins waiting. If you try to wait + /// for more than 8 pins, this function will return `None`. + pub async fn wait_for_rising_edge(&mut self) -> Option<()> { + self.pin.wait_for_rising_edge().await + } + + /// Wait for a low level on the pin. You can have at most 8 pins waiting. If you try to wait for + /// more than 8 pins, this function will return `None`. + pub async fn wait_for_low(&mut self) -> Option<()> { + self.pin.wait_for_low().await + } + + /// Wait for a high level on the pin. You can have at most 8 pins waiting. If you try to wait for + /// more than 8 pins, this function will return `None`. + pub async fn wait_for_high(&mut self) -> Option<()> { + self.pin.wait_for_high().await + } +} diff --git a/embassy-rp/CHANGELOG.md b/embassy-rp/CHANGELOG.md new file mode 100644 index 000000000..7eef64292 --- /dev/null +++ b/embassy-rp/CHANGELOG.md @@ -0,0 +1,32 @@ +# Changelog for embassy-rp + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## Unreleased + +## 0.2.0 - 2024-08-05 + +- Add read_to_break_with_count +- add option to provide your own boot2 +- Add multichannel ADC +- Add collapse_debuginfo to fmt.rs macros. +- Use raw slices .len() method instead of unsafe hacks. +- Add missing word "pin" in rp pwm documentation +- Add Clone and Copy to Error types +- fix spinlocks staying locked after reset. +- wait until read matches for PSM accesses. +- Remove generics +- fix drop implementation of BufferedUartRx and BufferedUartTx +- implement `embedded_storage_async::nor_flash::MultiwriteNorFlash` +- rp usb: wake ep-wakers after stalling +- rp usb: add stall implementation +- Add parameter for enabling pull-up and pull-down in RP PWM input mode +- rp: remove mod sealed. +- rename pins data type and the macro +- rename pwm channels to pwm slices, including in documentation +- rename the Channel trait to Slice and the PwmPin to PwmChannel +- i2c: Fix race condition that appears on fast repeated transfers. +- Add a basic "read to break" function diff --git a/embassy-rp/Cargo.toml b/embassy-rp/Cargo.toml index 794f1109c..4616116aa 100644 --- a/embassy-rp/Cargo.toml +++ b/embassy-rp/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "embassy-rp" -version = "0.1.0" +version = "0.2.0" edition = "2021" license = "MIT OR Apache-2.0" description = "Embassy Hardware Abstraction Layer (HAL) for the Raspberry Pi RP2040 microcontroller" @@ -14,7 +14,9 @@ src_base = "https://github.com/embassy-rs/embassy/blob/embassy-rp-v$VERSION/emba src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/embassy-rp/src/" features = ["defmt", "unstable-pac", "time-driver"] flavors = [ - { name = "rp2040", target = "thumbv6m-none-eabi" }, + { name = "rp2040", target = "thumbv6m-none-eabi", features = ["rp2040"] }, + { name = "rp235xa", target = "thumbv8m.main-none-eabihf", features = ["rp235xa"] }, + { name = "rp235xb", target = "thumbv8m.main-none-eabihf", features = ["rp235xb"] }, ] [package.metadata.docs.rs] @@ -22,13 +24,13 @@ features = ["defmt", "unstable-pac", "time-driver"] [features] default = [ "rt" ] -## Enable the rt feature of [`rp-pac`](https://docs.rs/crates/rp-pac). This brings in the [`cortex-m-rt`](https://docs.rs/cortex-m-rt) crate, which adds startup code and minimal runtime initialization. +## Enable the rt feature of [`rp-pac`](https://docs.rs/rp-pac). This brings in the [`cortex-m-rt`](https://docs.rs/cortex-m-rt) crate, which adds startup code and minimal runtime initialization. rt = [ "rp-pac/rt" ] ## Enable [defmt support](https://docs.rs/defmt) and enables `defmt` debug-log messages and formatting in embassy drivers. defmt = ["dep:defmt", "embassy-usb-driver/defmt", "embassy-hal-internal/defmt"] -## Configure the critical section crate to use an implementation that is safe for multicore use on rp2040. +## Configure the [`critical-section`](https://docs.rs/critical-section) crate to use an implementation that is safe for multicore use on rp2040. critical-section-impl = ["critical-section/restore-state-u8"] ## Reexport the PAC for the currently enabled chip at `embassy_rp::pac`. @@ -79,33 +81,57 @@ boot2-ram-memcpy = [] boot2-w25q080 = [] ## Use boot2 with support for Winbond W25X10CL SPI flash. boot2-w25x10cl = [] +## Have embassy not provide the boot2 so you can use your own. +## Place your own in the ".boot2" section like: +## ``` +## #[link_section = ".boot2"] +## #[used] +## static BOOT2: [u8; 256] = [0; 256]; // Provide your own with e.g. include_bytes! +## ``` +boot2-none = [] + +## Configure the hal for use with the rp2040 +rp2040 = ["rp-pac/rp2040"] +_rp235x = ["rp-pac/rp235x"] +## Configure the hal for use with the rp235xA +rp235xa = ["_rp235x"] +## Configure the hal for use with the rp235xB +rp235xb = ["_rp235x"] + +# hack around cortex-m peripherals being wrong when running tests. +_test = [] + +## Add a binary-info header block containing picotool-compatible metadata. +## +## Takes up a little flash space, but picotool can then report the name of your +## program and other details. +binary-info = ["rt", "dep:rp-binary-info", "rp-binary-info?/binary-info"] [dependencies] -embassy-sync = { version = "0.5.0", path = "../embassy-sync" } +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } embassy-time-driver = { version = "0.1", path = "../embassy-time-driver", optional = true } -embassy-time = { version = "0.3.0", path = "../embassy-time" } +embassy-time = { version = "0.3.2", path = "../embassy-time" } embassy-futures = { version = "0.1.0", path = "../embassy-futures" } -embassy-hal-internal = {version = "0.1.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-2"] } -embassy-embedded-hal = {version = "0.1.0", path = "../embassy-embedded-hal" } +embassy-hal-internal = {version = "0.2.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-2"] } +embassy-embedded-hal = {version = "0.2.0", path = "../embassy-embedded-hal" } embassy-usb-driver = {version = "0.1.0", path = "../embassy-usb-driver" } atomic-polyfill = "1.0.1" defmt = { version = "0.3", optional = true } log = { version = "0.4.14", optional = true } -nb = "1.0.0" +nb = "1.1.0" cfg-if = "1.0.0" cortex-m-rt = ">=0.6.15,<0.8" cortex-m = "0.7.6" -critical-section = "1.1" -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } +critical-section = "1.2.0" chrono = { version = "0.4", default-features = false, optional = true } embedded-io = { version = "0.6.1" } embedded-io-async = { version = "0.6.1" } embedded-storage = { version = "0.3" } embedded-storage-async = { version = "0.4.1" } rand_core = "0.6.4" -fixed = "1.23.1" +fixed = "1.28.0" -rp-pac = { version = "6" } +rp-pac = { git = "https://github.com/embassy-rs/rp-pac.git", rev = "a7f42d25517f7124ad3b4ed492dec8b0f50a0e6c", feature = ["rt"] } embedded-hal-02 = { package = "embedded-hal", version = "0.2.6", features = ["unproven"] } embedded-hal-1 = { package = "embedded-hal", version = "1.0" } @@ -115,8 +141,11 @@ embedded-hal-nb = { version = "1.0" } pio-proc = {version= "0.2" } pio = {version= "0.2.1" } rp2040-boot2 = "0.3" -document-features = "0.2.7" +document-features = "0.2.10" +sha2-const-stable = "0.1" +rp-binary-info = { version = "0.1.0", optional = true } +smart-leds = "0.4.0" [dev-dependencies] -embassy-executor = { version = "0.5.0", path = "../embassy-executor", features = ["arch-std", "executor-thread"] } +embassy-executor = { version = "0.6.2", path = "../embassy-executor", features = ["arch-std", "executor-thread"] } static_cell = { version = "2" } diff --git a/embassy-rp/LICENSE-APACHE b/embassy-rp/LICENSE-APACHE new file mode 100644 index 000000000..48be1263d --- /dev/null +++ b/embassy-rp/LICENSE-APACHE @@ -0,0 +1,202 @@ + 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 (c) Embassy project contributors +Portions copyright (c) rp-rs organization + +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/embassy-rp/LICENSE-MIT b/embassy-rp/LICENSE-MIT new file mode 100644 index 000000000..f1cfbd5f7 --- /dev/null +++ b/embassy-rp/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright (c) Embassy project contributors +Portions copyright (c) rp-rs organization + +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/embassy-rp/README.md b/embassy-rp/README.md index 8cf7da994..16b189344 100644 --- a/embassy-rp/README.md +++ b/embassy-rp/README.md @@ -23,5 +23,5 @@ The `embassy-rp` HAL implements the traits from [embedded-hal](https://crates.io This crate can run on any executor. -Optionally, some features requiring [`embassy-time`](https://crates.io/crates/embassy-time) can be activated with the `time` feature. If you enable it, +Optionally, some features requiring [`embassy-time`](https://crates.io/crates/embassy-time) can be activated with the `time-driver` feature. If you enable it, you must link an `embassy-time` driver in your project. diff --git a/embassy-rp/build.rs b/embassy-rp/build.rs index f41ccd220..a8d387611 100644 --- a/embassy-rp/build.rs +++ b/embassy-rp/build.rs @@ -1,17 +1,39 @@ use std::env; +use std::ffi::OsStr; use std::fs::File; use std::io::Write; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; fn main() { - // Put the linker script somewhere the linker can find it - let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); - let link_x = include_bytes!("link-rp.x.in"); - let mut f = File::create(out.join("link-rp.x")).unwrap(); - f.write_all(link_x).unwrap(); + if env::var("CARGO_FEATURE_RP2040").is_ok() { + // Put the linker script somewhere the linker can find it + let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); + let link_x = include_bytes!("link-rp.x.in"); + let mut f = File::create(out.join("link-rp.x")).unwrap(); + f.write_all(link_x).unwrap(); - println!("cargo:rustc-link-search={}", out.display()); + println!("cargo:rustc-link-search={}", out.display()); - println!("cargo:rerun-if-changed=build.rs"); - println!("cargo:rerun-if-changed=link-rp.x.in"); + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-changed=link-rp.x.in"); + } + + // code below taken from https://github.com/rust-embedded/cortex-m/blob/master/cortex-m-rt/build.rs + + let mut target = env::var("TARGET").unwrap(); + + // When using a custom target JSON, `$TARGET` contains the path to that JSON file. By + // convention, these files are named after the actual target triple, eg. + // `thumbv7m-customos-elf.json`, so we extract the file stem here to allow custom target specs. + let path = Path::new(&target); + if path.extension() == Some(OsStr::new("json")) { + target = path + .file_stem() + .map_or(target.clone(), |stem| stem.to_str().unwrap().to_string()); + } + + println!("cargo::rustc-check-cfg=cfg(has_fpu)"); + if target.ends_with("-eabihf") { + println!("cargo:rustc-cfg=has_fpu"); + } } diff --git a/embassy-rp/link-rp.x.in b/embassy-rp/link-rp.x.in index af463f963..1839dda68 100644 --- a/embassy-rp/link-rp.x.in +++ b/embassy-rp/link-rp.x.in @@ -5,4 +5,4 @@ SECTIONS { { KEEP(*(.boot2)); } > BOOT2 -} \ No newline at end of file +} diff --git a/embassy-rp/src/adc.rs b/embassy-rp/src/adc.rs index 21360bf66..9582e43c8 100644 --- a/embassy-rp/src/adc.rs +++ b/embassy-rp/src/adc.rs @@ -8,10 +8,10 @@ use core::task::Poll; use embassy_hal_internal::{into_ref, PeripheralRef}; use embassy_sync::waitqueue::AtomicWaker; -use crate::gpio::sealed::Pin as GpioPin; -use crate::gpio::{self, AnyPin, Pull}; +use crate::gpio::{self, AnyPin, Pull, SealedPin as GpioPin}; use crate::interrupt::typelevel::Binding; use crate::interrupt::InterruptExt; +use crate::pac::dma::vals::TreqSel; use crate::peripherals::{ADC, ADC_TEMP_SENSOR}; use crate::{dma, interrupt, pac, peripherals, Peripheral, RegExt}; @@ -19,14 +19,9 @@ static WAKER: AtomicWaker = AtomicWaker::new(); /// ADC config. #[non_exhaustive] +#[derive(Default)] pub struct Config {} -impl Default for Config { - fn default() -> Self { - Self {} - } -} - enum Source<'p> { Pin(PeripheralRef<'p, AnyPin>), TempSensor(PeripheralRef<'p, ADC_TEMP_SENSOR>), @@ -40,6 +35,8 @@ impl<'p> Channel<'p> { pub fn new_pin(pin: impl Peripheral

+ 'p, pull: Pull) -> Self { into_ref!(pin); pin.pad_ctrl().modify(|w| { + #[cfg(feature = "_rp235x")] + w.set_iso(false); // manual says: // // > When using an ADC input shared with a GPIO pin, the pin’s @@ -175,7 +172,7 @@ impl<'d, M: Mode> Adc<'d, M> { while !r.cs().read().ready() {} match r.cs().read().err() { true => Err(Error::ConversionFailed), - false => Ok(r.result().read().result().into()), + false => Ok(r.result().read().result()), } } } @@ -221,22 +218,37 @@ impl<'d> Adc<'d, Async> { Self::wait_for_ready().await; match r.cs().read().err() { true => Err(Error::ConversionFailed), - false => Ok(r.result().read().result().into()), + false => Ok(r.result().read().result()), } } + // Note for refactoring: we don't require the actual Channels here, just the channel numbers. + // The public api is responsible for asserting ownership of the actual Channels. async fn read_many_inner( &mut self, - ch: &mut Channel<'_>, + channels: impl Iterator, buf: &mut [W], fcs_err: bool, div: u16, dma: impl Peripheral

, ) -> Result<(), Error> { + #[cfg(feature = "rp2040")] + let mut rrobin = 0_u8; + #[cfg(feature = "_rp235x")] + let mut rrobin = 0_u16; + for c in channels { + rrobin |= 1 << c; + } + let first_ch = rrobin.trailing_zeros() as u8; + if rrobin.count_ones() == 1 { + rrobin = 0; + } + let r = Self::regs(); // clear previous errors and set channel r.cs().modify(|w| { - w.set_ainsel(ch.channel()); + w.set_ainsel(first_ch); + w.set_rrobin(rrobin); w.set_err_sticky(true); // clear previous errors w.set_start_many(false); }); @@ -272,7 +284,7 @@ impl<'d> Adc<'d, Async> { } let auto_reset = ResetDmaConfig; - let dma = unsafe { dma::read(dma, r.fifo().as_ptr() as *const W, buf as *mut [W], 36) }; + let dma = unsafe { dma::read(dma, r.fifo().as_ptr() as *const W, buf as *mut [W], TreqSel::ADC) }; // start conversions and wait for dma to finish. we can't report errors early // because there's no interrupt to signal them, and inspecting every element // of the fifo is too costly to do here. @@ -289,7 +301,49 @@ impl<'d> Adc<'d, Async> { } } + /// Sample multiple values from multiple channels using DMA. + /// Samples are stored in an interleaved fashion inside the buffer. + /// `div` is the integer part of the clock divider and can be calculated with `floor(48MHz / sample_rate * num_channels - 1)` + /// Any `div` value of less than 96 will have the same effect as setting it to 0 + #[inline] + pub async fn read_many_multichannel( + &mut self, + ch: &mut [Channel<'_>], + buf: &mut [S], + div: u16, + dma: impl Peripheral

, + ) -> Result<(), Error> { + self.read_many_inner(ch.iter().map(|c| c.channel()), buf, false, div, dma) + .await + } + + /// Sample multiple values from multiple channels using DMA, with errors inlined in samples. + /// Samples are stored in an interleaved fashion inside the buffer. + /// `div` is the integer part of the clock divider and can be calculated with `floor(48MHz / sample_rate * num_channels - 1)` + /// Any `div` value of less than 96 will have the same effect as setting it to 0 + #[inline] + pub async fn read_many_multichannel_raw( + &mut self, + ch: &mut [Channel<'_>], + buf: &mut [Sample], + div: u16, + dma: impl Peripheral

, + ) { + // errors are reported in individual samples + let _ = self + .read_many_inner( + ch.iter().map(|c| c.channel()), + unsafe { mem::transmute::<_, &mut [u16]>(buf) }, + true, + div, + dma, + ) + .await; + } + /// Sample multiple values from a channel using DMA. + /// `div` is the integer part of the clock divider and can be calculated with `floor(48MHz / sample_rate - 1)` + /// Any `div` value of less than 96 will have the same effect as setting it to 0 #[inline] pub async fn read_many( &mut self, @@ -298,10 +352,13 @@ impl<'d> Adc<'d, Async> { div: u16, dma: impl Peripheral

, ) -> Result<(), Error> { - self.read_many_inner(ch, buf, false, div, dma).await + self.read_many_inner([ch.channel()].into_iter(), buf, false, div, dma) + .await } - /// Sample multiple values from a channel using DMA with errors inlined in samples. + /// Sample multiple values from a channel using DMA, with errors inlined in samples. + /// `div` is the integer part of the clock divider and can be calculated with `floor(48MHz / sample_rate - 1)` + /// Any `div` value of less than 96 will have the same effect as setting it to 0 #[inline] pub async fn read_many_raw( &mut self, @@ -312,7 +369,13 @@ impl<'d> Adc<'d, Async> { ) { // errors are reported in individual samples let _ = self - .read_many_inner(ch, unsafe { mem::transmute::<_, &mut [u16]>(buf) }, true, div, dma) + .read_many_inner( + [ch.channel()].into_iter(), + unsafe { mem::transmute::<_, &mut [u16]>(buf) }, + true, + div, + dma, + ) .await; } } @@ -339,38 +402,58 @@ impl interrupt::typelevel::Handler for Inter } } -mod sealed { - pub trait AdcSample: crate::dma::Word {} - - pub trait AdcChannel {} -} +trait SealedAdcSample: crate::dma::Word {} +trait SealedAdcChannel {} /// ADC sample. -pub trait AdcSample: sealed::AdcSample {} +#[allow(private_bounds)] +pub trait AdcSample: SealedAdcSample {} -impl sealed::AdcSample for u16 {} +impl SealedAdcSample for u16 {} impl AdcSample for u16 {} -impl sealed::AdcSample for u8 {} +impl SealedAdcSample for u8 {} impl AdcSample for u8 {} /// ADC channel. -pub trait AdcChannel: sealed::AdcChannel {} +#[allow(private_bounds)] +pub trait AdcChannel: SealedAdcChannel {} /// ADC pin. pub trait AdcPin: AdcChannel + gpio::Pin {} macro_rules! impl_pin { ($pin:ident, $channel:expr) => { - impl sealed::AdcChannel for peripherals::$pin {} + impl SealedAdcChannel for peripherals::$pin {} impl AdcChannel for peripherals::$pin {} impl AdcPin for peripherals::$pin {} }; } +#[cfg(any(feature = "rp235xa", feature = "rp2040"))] impl_pin!(PIN_26, 0); +#[cfg(any(feature = "rp235xa", feature = "rp2040"))] impl_pin!(PIN_27, 1); +#[cfg(any(feature = "rp235xa", feature = "rp2040"))] impl_pin!(PIN_28, 2); +#[cfg(any(feature = "rp235xa", feature = "rp2040"))] impl_pin!(PIN_29, 3); -impl sealed::AdcChannel for peripherals::ADC_TEMP_SENSOR {} +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_40, 0); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_41, 1); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_42, 2); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_43, 3); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_44, 4); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_45, 5); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_46, 6); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_47, 7); + +impl SealedAdcChannel for peripherals::ADC_TEMP_SENSOR {} impl AdcChannel for peripherals::ADC_TEMP_SENSOR {} diff --git a/embassy-rp/src/block.rs b/embassy-rp/src/block.rs new file mode 100644 index 000000000..a3e1ad925 --- /dev/null +++ b/embassy-rp/src/block.rs @@ -0,0 +1,1079 @@ +//! Support for the RP235x Boot ROM's "Block" structures +//! +//! Blocks contain pointers, to form Block Loops. +//! +//! The `IMAGE_DEF` Block (here the `ImageDef` type) tells the ROM how to boot a +//! firmware image. The `PARTITION_TABLE` Block (here the `PartitionTable` type) +//! tells the ROM how to divide the flash space up into partitions. + +// Credit: Taken from https://github.com/thejpster/rp-hal-rp2350-public (also licensed Apache 2.0 + MIT). +// Copyright (c) rp-rs organization + +// These all have a 1 byte size + +/// An item ID for encoding a Vector Table address +pub const ITEM_1BS_VECTOR_TABLE: u8 = 0x03; + +/// An item ID for encoding a Rolling Window Delta +pub const ITEM_1BS_ROLLING_WINDOW_DELTA: u8 = 0x05; + +/// An item ID for encoding a Signature +pub const ITEM_1BS_SIGNATURE: u8 = 0x09; + +/// An item ID for encoding a Salt +pub const ITEM_1BS_SALT: u8 = 0x0c; + +/// An item ID for encoding an Image Type +pub const ITEM_1BS_IMAGE_TYPE: u8 = 0x42; + +/// An item ID for encoding the image's Entry Point +pub const ITEM_1BS_ENTRY_POINT: u8 = 0x44; + +/// An item ID for encoding the definition of a Hash +pub const ITEM_2BS_HASH_DEF: u8 = 0x47; + +/// An item ID for encoding a Version +pub const ITEM_1BS_VERSION: u8 = 0x48; + +/// An item ID for encoding a Hash +pub const ITEM_1BS_HASH_VALUE: u8 = 0x4b; + +// These all have a 2-byte size + +/// An item ID for encoding a Load Map +pub const ITEM_2BS_LOAD_MAP: u8 = 0x06; + +/// An item ID for encoding a Partition Table +pub const ITEM_2BS_PARTITION_TABLE: u8 = 0x0a; + +/// An item ID for encoding a placeholder entry that is ignored +/// +/// Allows a Block to not be empty. +pub const ITEM_2BS_IGNORED: u8 = 0xfe; + +/// An item ID for encoding the special last item in a Block +/// +/// It records how long the Block is. +pub const ITEM_2BS_LAST: u8 = 0xff; + +// Options for ITEM_1BS_IMAGE_TYPE + +/// A [`ITEM_1BS_IMAGE_TYPE`] value bitmask to mark an image as invalid +pub const IMAGE_TYPE_INVALID: u16 = 0x0000; + +/// A [`ITEM_1BS_IMAGE_TYPE`] value bitmask to mark an image as an executable +pub const IMAGE_TYPE_EXE: u16 = 0x0001; + +/// A [`ITEM_1BS_IMAGE_TYPE`] value bitmask to mark an image as data +pub const IMAGE_TYPE_DATA: u16 = 0x0002; + +/// A [`ITEM_1BS_IMAGE_TYPE`] value bitmask to mark the CPU security mode as unspecified +pub const IMAGE_TYPE_EXE_TYPE_SECURITY_UNSPECIFIED: u16 = 0x0000; + +/// A [`ITEM_1BS_IMAGE_TYPE`] value bitmask to mark the CPU security mode as Non Secure +pub const IMAGE_TYPE_EXE_TYPE_SECURITY_NS: u16 = 0x0010; + +/// A [`ITEM_1BS_IMAGE_TYPE`] value bitmask to mark the CPU security mode as Non Secure +pub const IMAGE_TYPE_EXE_TYPE_SECURITY_S: u16 = 0x0020; + +/// A [`ITEM_1BS_IMAGE_TYPE`] value bitmask to mark the CPU type as Arm +pub const IMAGE_TYPE_EXE_CPU_ARM: u16 = 0x0000; + +/// A [`ITEM_1BS_IMAGE_TYPE`] value bitmask to mark the CPU type as RISC-V +pub const IMAGE_TYPE_EXE_CPU_RISCV: u16 = 0x0100; + +/// A [`ITEM_1BS_IMAGE_TYPE`] value bitmask to mark the CPU as an RP2040 +pub const IMAGE_TYPE_EXE_CHIP_RP2040: u16 = 0x0000; + +/// A [`ITEM_1BS_IMAGE_TYPE`] value bitmask to mark the CPU as an RP2350 +pub const IMAGE_TYPE_EXE_CHIP_RP2350: u16 = 0x1000; + +/// A [`ITEM_1BS_IMAGE_TYPE`] value bitmask to mark the image as Try Before You Buy. +/// +/// This means the image must be marked as 'Bought' with the ROM before the +/// watchdog times out the trial period, otherwise it is erased and the previous +/// image will be booted. +pub const IMAGE_TYPE_TBYB: u16 = 0x8000; + +/// This is the magic Block Start value. +/// +/// The Pico-SDK calls it `PICOBIN_BLOCK_MARKER_START` +const BLOCK_MARKER_START: u32 = 0xffffded3; + +/// This is the magic Block END value. +/// +/// The Pico-SDK calls it `PICOBIN_BLOCK_MARKER_END` +const BLOCK_MARKER_END: u32 = 0xab123579; + +/// An Image Definition has one item in it - an [`ITEM_1BS_IMAGE_TYPE`] +pub type ImageDef = Block<1>; + +/// A Block as understood by the Boot ROM. +/// +/// This could be an Image Definition, or a Partition Table, or maybe some other +/// kind of block. +/// +/// It contains within the special start and end markers the Boot ROM is looking +/// for. +#[derive(Debug)] +#[repr(C)] +pub struct Block { + marker_start: u32, + items: [u32; N], + length: u32, + offset: *const u32, + marker_end: u32, +} + +unsafe impl Sync for Block {} + +impl Block { + /// Construct a new Binary Block, with the given items. + /// + /// The length, and the Start and End markers are added automatically. The + /// Block Loop pointer initially points to itself. + pub const fn new(items: [u32; N]) -> Block { + Block { + marker_start: BLOCK_MARKER_START, + items, + length: item_last(N as u16), + // offset from this block to next block in loop. By default + // we form a Block Loop with a single Block in it. + offset: core::ptr::null(), + marker_end: BLOCK_MARKER_END, + } + } + + /// Change the Block Loop offset value. + /// + /// This method isn't that useful because you can't evaluate the difference + /// between two pointers in a const context as the addresses aren't assigned + /// until long after the const evaluator has run. + /// + /// If you think you need this method, you might want to set a unique random + /// value here and swap it for the real offset as a post-processing step. + pub const fn with_offset(self, offset: *const u32) -> Block { + Block { offset, ..self } + } +} + +impl Block<0> { + /// Construct an empty block. + pub const fn empty() -> Block<0> { + Block::new([]) + } + + /// Make the block one word larger + pub const fn extend(self, word: u32) -> Block<1> { + Block::new([word]) + } +} + +impl Block<1> { + /// Make the block one word larger + pub const fn extend(self, word: u32) -> Block<2> { + Block::new([self.items[0], word]) + } +} + +impl Block<2> { + /// Make the block one word larger + pub const fn extend(self, word: u32) -> Block<3> { + Block::new([self.items[0], self.items[1], word]) + } +} + +impl ImageDef { + /// Construct a new IMAGE_DEF Block, for an EXE with the given security and + /// architecture. + pub const fn arch_exe(security: Security, architecture: Architecture) -> Self { + Self::new([item_image_type_exe(security, architecture)]) + } + + /// Construct a new IMAGE_DEF Block, for an EXE with the given security. + /// + /// The target architecture is taken from the current build target (i.e. Arm + /// or RISC-V). + pub const fn exe(security: Security) -> Self { + if cfg!(all(target_arch = "riscv32", target_os = "none")) { + Self::arch_exe(security, Architecture::Riscv) + } else { + Self::arch_exe(security, Architecture::Arm) + } + } + + /// Construct a new IMAGE_DEF Block, for a Non-Secure EXE. + /// + /// The target architecture is taken from the current build target (i.e. Arm + /// or RISC-V). + pub const fn non_secure_exe() -> Self { + Self::exe(Security::NonSecure) + } + + /// Construct a new IMAGE_DEF Block, for a Secure EXE. + /// + /// The target architecture is taken from the current build target (i.e. Arm + /// or RISC-V). + pub const fn secure_exe() -> Self { + Self::exe(Security::Secure) + } +} + +/// We make our partition table this fixed size. +pub const PARTITION_TABLE_MAX_ITEMS: usize = 128; + +/// Describes a unpartitioned space +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct UnpartitionedSpace { + permissions_and_location: u32, + permissions_and_flags: u32, +} + +impl UnpartitionedSpace { + /// Create a new unpartitioned space. + /// + /// It defaults to no permissions. + pub const fn new() -> Self { + Self { + permissions_and_location: 0, + permissions_and_flags: 0, + } + } + + /// Create a new unpartition space from run-time values. + /// + /// Get these from the ROM function `get_partition_table_info` with an argument of `PT_INFO`. + pub const fn from_raw(permissions_and_location: u32, permissions_and_flags: u32) -> Self { + Self { + permissions_and_location, + permissions_and_flags, + } + } + + /// Add a permission + pub const fn with_permission(self, permission: Permission) -> Self { + Self { + permissions_and_flags: self.permissions_and_flags | permission as u32, + permissions_and_location: self.permissions_and_location | permission as u32, + } + } + + /// Set a flag + pub const fn with_flag(self, flag: UnpartitionedFlag) -> Self { + Self { + permissions_and_flags: self.permissions_and_flags | flag as u32, + ..self + } + } + + /// Get the partition start and end + /// + /// The offsets are in 4 KiB sectors, inclusive. + pub fn get_first_last_sectors(&self) -> (u16, u16) { + ( + (self.permissions_and_location & 0x0000_1FFF) as u16, + ((self.permissions_and_location >> 13) & 0x0000_1FFF) as u16, + ) + } + + /// Get the partition start and end + /// + /// The offsets are in bytes, inclusive. + pub fn get_first_last_bytes(&self) -> (u32, u32) { + let (first, last) = self.get_first_last_sectors(); + (u32::from(first) * 4096, (u32::from(last) * 4096) + 4095) + } + + /// Check if it has a permission + pub fn has_permission(&self, permission: Permission) -> bool { + let mask = permission as u32; + (self.permissions_and_flags & mask) != 0 + } + + /// Check if the partition has a flag set + pub fn has_flag(&self, flag: UnpartitionedFlag) -> bool { + let mask = flag as u32; + (self.permissions_and_flags & mask) != 0 + } +} + +impl core::fmt::Display for UnpartitionedSpace { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let (first, last) = self.get_first_last_bytes(); + write!( + f, + "{:#010x}..{:#010x} S:{}{} NS:{}{} B:{}{}", + first, + last, + if self.has_permission(Permission::SecureRead) { + 'R' + } else { + '_' + }, + if self.has_permission(Permission::SecureWrite) { + 'W' + } else { + '_' + }, + if self.has_permission(Permission::NonSecureRead) { + 'R' + } else { + '_' + }, + if self.has_permission(Permission::NonSecureWrite) { + 'W' + } else { + '_' + }, + if self.has_permission(Permission::BootRead) { + 'R' + } else { + '_' + }, + if self.has_permission(Permission::BootWrite) { + 'W' + } else { + '_' + } + ) + } +} + +/// Describes a Partition +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Partition { + permissions_and_location: u32, + permissions_and_flags: u32, + id: Option, + extra_families: [u32; 4], + extra_families_len: usize, + name: [u8; 128], +} + +impl Partition { + const FLAGS_HAS_ID: u32 = 0b1; + const FLAGS_LINK_TYPE_A_PARTITION: u32 = 0b01 << 1; + const FLAGS_LINK_TYPE_OWNER: u32 = 0b10 << 1; + const FLAGS_LINK_MASK: u32 = 0b111111 << 1; + const FLAGS_HAS_NAME: u32 = 0b1 << 12; + const FLAGS_HAS_EXTRA_FAMILIES_SHIFT: u8 = 7; + const FLAGS_HAS_EXTRA_FAMILIES_MASK: u32 = 0b11 << Self::FLAGS_HAS_EXTRA_FAMILIES_SHIFT; + + /// Create a new partition, with the given start and end sectors. + /// + /// It defaults to no permissions. + pub const fn new(first_sector: u16, last_sector: u16) -> Self { + // 0x2000 sectors of 4 KiB is 32 MiB, which is the total XIP area + core::assert!(first_sector < 0x2000); + core::assert!(last_sector < 0x2000); + core::assert!(first_sector <= last_sector); + Self { + permissions_and_location: (last_sector as u32) << 13 | first_sector as u32, + permissions_and_flags: 0, + id: None, + extra_families: [0; 4], + extra_families_len: 0, + name: [0; 128], + } + } + + /// Create a new partition from run-time values. + /// + /// Get these from the ROM function `get_partition_table_info` with an argument of `PARTITION_LOCATION_AND_FLAGS`. + pub const fn from_raw(permissions_and_location: u32, permissions_and_flags: u32) -> Self { + Self { + permissions_and_location, + permissions_and_flags, + id: None, + extra_families: [0; 4], + extra_families_len: 0, + name: [0; 128], + } + } + + /// Add a permission + pub const fn with_permission(self, permission: Permission) -> Self { + Self { + permissions_and_location: self.permissions_and_location | permission as u32, + permissions_and_flags: self.permissions_and_flags | permission as u32, + ..self + } + } + + /// Set the name of the partition + pub const fn with_name(self, name: &str) -> Self { + let mut new_name = [0u8; 128]; + let name = name.as_bytes(); + let mut idx = 0; + new_name[0] = name.len() as u8; + while idx < name.len() { + new_name[idx + 1] = name[idx]; + idx += 1; + } + Self { + name: new_name, + permissions_and_flags: self.permissions_and_flags | Self::FLAGS_HAS_NAME, + ..self + } + } + + /// Set the extra families for the partition. + /// + /// You can supply up to four. + pub const fn with_extra_families(self, extra_families: &[u32]) -> Self { + core::assert!(extra_families.len() <= 4); + let mut new_extra_families = [0u32; 4]; + let mut idx = 0; + while idx < extra_families.len() { + new_extra_families[idx] = extra_families[idx]; + idx += 1; + } + Self { + extra_families: new_extra_families, + extra_families_len: extra_families.len(), + permissions_and_flags: (self.permissions_and_flags & !Self::FLAGS_HAS_EXTRA_FAMILIES_MASK) + | (extra_families.len() as u32) << Self::FLAGS_HAS_EXTRA_FAMILIES_SHIFT, + ..self + } + } + + /// Set the ID + pub const fn with_id(self, id: u64) -> Self { + Self { + id: Some(id), + permissions_and_flags: self.permissions_and_flags | Self::FLAGS_HAS_ID, + ..self + } + } + + /// Add a link + pub const fn with_link(self, link: Link) -> Self { + let mut new_flags = self.permissions_and_flags & !Self::FLAGS_LINK_MASK; + match link { + Link::Nothing => {} + Link::ToA { partition_idx } => { + core::assert!(partition_idx < 16); + new_flags |= Self::FLAGS_LINK_TYPE_A_PARTITION; + new_flags |= (partition_idx as u32) << 3; + } + Link::ToOwner { partition_idx } => { + core::assert!(partition_idx < 16); + new_flags |= Self::FLAGS_LINK_TYPE_OWNER; + new_flags |= (partition_idx as u32) << 3; + } + } + Self { + permissions_and_flags: new_flags, + ..self + } + } + + /// Set a flag + pub const fn with_flag(self, flag: PartitionFlag) -> Self { + Self { + permissions_and_flags: self.permissions_and_flags | flag as u32, + ..self + } + } + + /// Get the partition start and end + /// + /// The offsets are in 4 KiB sectors, inclusive. + pub fn get_first_last_sectors(&self) -> (u16, u16) { + ( + (self.permissions_and_location & 0x0000_1FFF) as u16, + ((self.permissions_and_location >> 13) & 0x0000_1FFF) as u16, + ) + } + + /// Get the partition start and end + /// + /// The offsets are in bytes, inclusive. + pub fn get_first_last_bytes(&self) -> (u32, u32) { + let (first, last) = self.get_first_last_sectors(); + (u32::from(first) * 4096, (u32::from(last) * 4096) + 4095) + } + + /// Check if it has a permission + pub fn has_permission(&self, permission: Permission) -> bool { + let mask = permission as u32; + (self.permissions_and_flags & mask) != 0 + } + + /// Get which extra families are allowed in this partition + pub fn get_extra_families(&self) -> &[u32] { + &self.extra_families[0..self.extra_families_len] + } + + /// Get the name of the partition + /// + /// Returns `None` if there's no name, or the name is not valid UTF-8. + pub fn get_name(&self) -> Option<&str> { + let len = self.name[0] as usize; + if len == 0 { + None + } else { + core::str::from_utf8(&self.name[1..=len]).ok() + } + } + + /// Get the ID + pub fn get_id(&self) -> Option { + self.id + } + + /// Check if this partition is linked + pub fn get_link(&self) -> Link { + if (self.permissions_and_flags & Self::FLAGS_LINK_TYPE_A_PARTITION) != 0 { + let partition_idx = ((self.permissions_and_flags >> 3) & 0x0F) as u8; + Link::ToA { partition_idx } + } else if (self.permissions_and_flags & Self::FLAGS_LINK_TYPE_OWNER) != 0 { + let partition_idx = ((self.permissions_and_flags >> 3) & 0x0F) as u8; + Link::ToOwner { partition_idx } + } else { + Link::Nothing + } + } + + /// Check if the partition has a flag set + pub fn has_flag(&self, flag: PartitionFlag) -> bool { + let mask = flag as u32; + (self.permissions_and_flags & mask) != 0 + } +} + +impl core::fmt::Display for Partition { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let (first, last) = self.get_first_last_bytes(); + write!( + f, + "{:#010x}..{:#010x} S:{}{} NS:{}{} B:{}{}", + first, + last, + if self.has_permission(Permission::SecureRead) { + 'R' + } else { + '_' + }, + if self.has_permission(Permission::SecureWrite) { + 'W' + } else { + '_' + }, + if self.has_permission(Permission::NonSecureRead) { + 'R' + } else { + '_' + }, + if self.has_permission(Permission::NonSecureWrite) { + 'W' + } else { + '_' + }, + if self.has_permission(Permission::BootRead) { + 'R' + } else { + '_' + }, + if self.has_permission(Permission::BootWrite) { + 'W' + } else { + '_' + } + ) + } +} + +/// Describes a partition table. +/// +/// Don't store this as a static - make sure you convert it to a block. +#[derive(Clone)] +pub struct PartitionTableBlock { + /// This must look like a block, including the 1 word header and the 3 word footer. + contents: [u32; PARTITION_TABLE_MAX_ITEMS], + /// This value doesn't include the 1 word header or the 3 word footer + num_items: usize, +} + +impl PartitionTableBlock { + /// Create an empty Block, big enough for a partition table. + /// + /// At a minimum you need to call [`Self::add_partition_item`]. + pub const fn new() -> PartitionTableBlock { + let mut contents = [0; PARTITION_TABLE_MAX_ITEMS]; + contents[0] = BLOCK_MARKER_START; + contents[1] = item_last(0); + contents[2] = 0; + contents[3] = BLOCK_MARKER_END; + PartitionTableBlock { contents, num_items: 0 } + } + + /// Add a partition to the partition table + pub const fn add_partition_item(self, unpartitioned: UnpartitionedSpace, partitions: &[Partition]) -> Self { + let mut new_table = PartitionTableBlock::new(); + let mut idx = 0; + // copy over old table, with the header but not the footer + while idx < self.num_items + 1 { + new_table.contents[idx] = self.contents[idx]; + idx += 1; + } + + // 1. add item header space (we fill this in later) + let header_idx = idx; + new_table.contents[idx] = 0; + idx += 1; + + // 2. unpartitioned space flags + // + // (the location of unpartition space is not recorded here - it is + // inferred because the unpartitioned space is where the partitions are + // not) + new_table.contents[idx] = unpartitioned.permissions_and_flags; + idx += 1; + + // 3. partition info + + let mut partition_no = 0; + while partition_no < partitions.len() { + // a. permissions_and_location (4K units) + new_table.contents[idx] = partitions[partition_no].permissions_and_location; + idx += 1; + + // b. permissions_and_flags + new_table.contents[idx] = partitions[partition_no].permissions_and_flags; + idx += 1; + + // c. ID + if let Some(id) = partitions[partition_no].id { + new_table.contents[idx] = id as u32; + new_table.contents[idx + 1] = (id >> 32) as u32; + idx += 2; + } + + // d. Extra Families + let mut extra_families_idx = 0; + while extra_families_idx < partitions[partition_no].extra_families_len { + new_table.contents[idx] = partitions[partition_no].extra_families[extra_families_idx]; + idx += 1; + extra_families_idx += 1; + } + + // e. Name + let mut name_idx = 0; + while name_idx < partitions[partition_no].name[0] as usize { + let name_chunk = [ + partitions[partition_no].name[name_idx], + partitions[partition_no].name[name_idx + 1], + partitions[partition_no].name[name_idx + 2], + partitions[partition_no].name[name_idx + 3], + ]; + new_table.contents[idx] = u32::from_le_bytes(name_chunk); + name_idx += 4; + idx += 1; + } + + partition_no += 1; + } + + let len = idx - header_idx; + new_table.contents[header_idx] = item_generic_2bs(partitions.len() as u8, len as u16, ITEM_2BS_PARTITION_TABLE); + + // 7. New Footer + new_table.contents[idx] = item_last(idx as u16 - 1); + new_table.contents[idx + 1] = 0; + new_table.contents[idx + 2] = BLOCK_MARKER_END; + + // ignore the header + new_table.num_items = idx - 1; + new_table + } + + /// Add a version number to the partition table + pub const fn with_version(self, major: u16, minor: u16) -> Self { + let mut new_table = PartitionTableBlock::new(); + let mut idx = 0; + // copy over old table, with the header but not the footer + while idx < self.num_items + 1 { + new_table.contents[idx] = self.contents[idx]; + idx += 1; + } + + // 1. add item + new_table.contents[idx] = item_generic_2bs(0, 2, ITEM_1BS_VERSION); + idx += 1; + new_table.contents[idx] = (major as u32) << 16 | minor as u32; + idx += 1; + + // 2. New Footer + new_table.contents[idx] = item_last(idx as u16 - 1); + new_table.contents[idx + 1] = 0; + new_table.contents[idx + 2] = BLOCK_MARKER_END; + + // ignore the header + new_table.num_items = idx - 1; + new_table + } + + /// Add a a SHA256 hash of the Block + /// + /// Adds a `HASH_DEF` covering all the previous items in the Block, and a + /// `HASH_VALUE` with a SHA-256 hash of them. + pub const fn with_sha256(self) -> Self { + let mut new_table = PartitionTableBlock::new(); + let mut idx = 0; + // copy over old table, with the header but not the footer + while idx < self.num_items + 1 { + new_table.contents[idx] = self.contents[idx]; + idx += 1; + } + + // 1. HASH_DEF says what is hashed + new_table.contents[idx] = item_generic_2bs(1, 2, ITEM_2BS_HASH_DEF); + idx += 1; + // we're hashing all the previous contents - including this line. + new_table.contents[idx] = (idx + 1) as u32; + idx += 1; + + // calculate hash over prior contents + let input = unsafe { core::slice::from_raw_parts(new_table.contents.as_ptr() as *const u8, idx * 4) }; + let hash: [u8; 32] = sha2_const_stable::Sha256::new().update(input).finalize(); + + // 2. HASH_VALUE contains the hash + new_table.contents[idx] = item_generic_2bs(0, 9, ITEM_1BS_HASH_VALUE); + idx += 1; + + let mut hash_idx = 0; + while hash_idx < hash.len() { + new_table.contents[idx] = u32::from_le_bytes([ + hash[hash_idx], + hash[hash_idx + 1], + hash[hash_idx + 2], + hash[hash_idx + 3], + ]); + idx += 1; + hash_idx += 4; + } + + // 3. New Footer + new_table.contents[idx] = item_last(idx as u16 - 1); + new_table.contents[idx + 1] = 0; + new_table.contents[idx + 2] = BLOCK_MARKER_END; + + // ignore the header + new_table.num_items = idx - 1; + new_table + } +} + +impl Default for PartitionTableBlock { + fn default() -> Self { + Self::new() + } +} + +/// Flags that a Partition can have +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[repr(u32)] +#[allow(missing_docs)] +pub enum PartitionFlag { + NotBootableArm = 1 << 9, + NotBootableRiscv = 1 << 10, + Uf2DownloadAbNonBootableOwnerAffinity = 1 << 11, + Uf2DownloadNoReboot = 1 << 13, + AcceptsDefaultFamilyRp2040 = 1 << 14, + AcceptsDefaultFamilyData = 1 << 16, + AcceptsDefaultFamilyRp2350ArmS = 1 << 17, + AcceptsDefaultFamilyRp2350Riscv = 1 << 18, + AcceptsDefaultFamilyRp2350ArmNs = 1 << 19, +} + +/// Flags that a Partition can have +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[repr(u32)] +#[allow(missing_docs)] +pub enum UnpartitionedFlag { + Uf2DownloadNoReboot = 1 << 13, + AcceptsDefaultFamilyRp2040 = 1 << 14, + AcceptsDefaultFamilyAbsolute = 1 << 15, + AcceptsDefaultFamilyData = 1 << 16, + AcceptsDefaultFamilyRp2350ArmS = 1 << 17, + AcceptsDefaultFamilyRp2350Riscv = 1 << 18, + AcceptsDefaultFamilyRp2350ArmNs = 1 << 19, +} + +/// Kinds of linked partition +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum Link { + /// Not linked to anything + Nothing, + /// This is a B partition - link to our A partition. + ToA { + /// The index of our matching A partition. + partition_idx: u8, + }, + /// Link to the partition that owns this one. + ToOwner { + /// The idx of our owner + partition_idx: u8, + }, +} + +/// Permissions that a Partition can have +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[repr(u32)] +pub enum Permission { + /// Can be read in Secure Mode + /// + /// Corresponds to `PERMISSION_S_R_BITS` in the Pico SDK + SecureRead = 1 << 26, + /// Can be written in Secure Mode + /// + /// Corresponds to `PERMISSION_S_W_BITS` in the Pico SDK + SecureWrite = 1 << 27, + /// Can be read in Non-Secure Mode + /// + /// Corresponds to `PERMISSION_NS_R_BITS` in the Pico SDK + NonSecureRead = 1 << 28, + /// Can be written in Non-Secure Mode + /// + /// Corresponds to `PERMISSION_NS_W_BITS` in the Pico SDK + NonSecureWrite = 1 << 29, + /// Can be read in Non-Secure Bootloader mode + /// + /// Corresponds to `PERMISSION_NSBOOT_R_BITS` in the Pico SDK + BootRead = 1 << 30, + /// Can be written in Non-Secure Bootloader mode + /// + /// Corresponds to `PERMISSION_NSBOOT_W_BITS` in the Pico SDK + BootWrite = 1 << 31, +} + +impl Permission { + /// Is this permission bit set this in this bitmask? + pub const fn is_in(self, mask: u32) -> bool { + (mask & (self as u32)) != 0 + } +} + +/// The supported RP2350 CPU architectures +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum Architecture { + /// Core is in Arm Cortex-M33 mode + Arm, + /// Core is in RISC-V / Hazard3 mode + Riscv, +} + +/// The kinds of Secure Boot we support +#[derive(Debug, Copy, Clone)] +pub enum Security { + /// Security mode not given + Unspecified, + /// Start in Non-Secure mode + NonSecure, + /// Start in Secure mode + Secure, +} + +/// Make an item containing a tag, 1 byte length and two extra bytes. +/// +/// The `command` arg should contain `1BS` +pub const fn item_generic_1bs(value: u16, length: u8, command: u8) -> u32 { + ((value as u32) << 16) | ((length as u32) << 8) | (command as u32) +} + +/// Make an item containing a tag, 2 byte length and one extra byte. +/// +/// The `command` arg should contain `2BS` +pub const fn item_generic_2bs(value: u8, length: u16, command: u8) -> u32 { + ((value as u32) << 24) | ((length as u32) << 8) | (command as u32) +} + +/// Create Image Type item, of type IGNORED. +pub const fn item_ignored() -> u32 { + item_generic_2bs(0, 1, ITEM_2BS_IGNORED) +} + +/// Create Image Type item, of type INVALID. +pub const fn item_image_type_invalid() -> u32 { + let value = IMAGE_TYPE_INVALID; + item_generic_1bs(value, 1, ITEM_1BS_IMAGE_TYPE) +} + +/// Create Image Type item, of type DATA. +pub const fn item_image_type_data() -> u32 { + let value = IMAGE_TYPE_DATA; + item_generic_1bs(value, 1, ITEM_1BS_IMAGE_TYPE) +} + +/// Create Image Type item, of type EXE. +pub const fn item_image_type_exe(security: Security, arch: Architecture) -> u32 { + let mut value = IMAGE_TYPE_EXE | IMAGE_TYPE_EXE_CHIP_RP2350; + + match arch { + Architecture::Arm => { + value |= IMAGE_TYPE_EXE_CPU_ARM; + } + Architecture::Riscv => { + value |= IMAGE_TYPE_EXE_CPU_RISCV; + } + } + + match security { + Security::Unspecified => value |= IMAGE_TYPE_EXE_TYPE_SECURITY_UNSPECIFIED, + Security::NonSecure => value |= IMAGE_TYPE_EXE_TYPE_SECURITY_NS, + Security::Secure => value |= IMAGE_TYPE_EXE_TYPE_SECURITY_S, + } + + item_generic_1bs(value, 1, ITEM_1BS_IMAGE_TYPE) +} + +/// Create a Block Last item. +pub const fn item_last(length: u16) -> u32 { + item_generic_2bs(0, length, ITEM_2BS_LAST) +} + +/// Create a Vector Table item. +/// +/// This is only allowed on Arm systems. +pub const fn item_vector_table(table_ptr: u32) -> [u32; 2] { + [item_generic_1bs(0, 2, ITEM_1BS_VECTOR_TABLE), table_ptr] +} + +/// Create an Entry Point item. +pub const fn item_entry_point(entry_point: u32, initial_sp: u32) -> [u32; 3] { + [item_generic_1bs(0, 3, ITEM_1BS_ENTRY_POINT), entry_point, initial_sp] +} + +/// Create an Rolling Window item. +/// +/// The delta is the number of bytes into the image that 0x10000000 should +/// be mapped. +pub const fn item_rolling_window(delta: u32) -> [u32; 2] { + [item_generic_1bs(0, 3, ITEM_1BS_ROLLING_WINDOW_DELTA), delta] +} + +#[cfg(test)] +mod test { + use super::*; + + /// I used this JSON, with `picotool partition create`: + /// + /// ```json + /// { + /// "version": [1, 0], + /// "unpartitioned": { + /// "families": ["absolute"], + /// "permissions": { + /// "secure": "rw", + /// "nonsecure": "rw", + /// "bootloader": "rw" + /// } + /// }, + /// "partitions": [ + /// { + /// "name": "A", + /// "id": 0, + /// "size": "2044K", + /// "families": ["rp2350-arm-s", "rp2350-riscv"], + /// "permissions": { + /// "secure": "rw", + /// "nonsecure": "rw", + /// "bootloader": "rw" + /// } + /// }, + /// { + /// "name": "B", + /// "id": 1, + /// "size": "2044K", + /// "families": ["rp2350-arm-s", "rp2350-riscv"], + /// "permissions": { + /// "secure": "rw", + /// "nonsecure": "rw", + /// "bootloader": "rw" + /// }, + /// "link": ["a", 0] + /// } + /// ] + /// } + /// ``` + #[test] + fn make_hashed_partition_table() { + let table = PartitionTableBlock::new() + .add_partition_item( + UnpartitionedSpace::new() + .with_permission(Permission::SecureRead) + .with_permission(Permission::SecureWrite) + .with_permission(Permission::NonSecureRead) + .with_permission(Permission::NonSecureWrite) + .with_permission(Permission::BootRead) + .with_permission(Permission::BootWrite) + .with_flag(UnpartitionedFlag::AcceptsDefaultFamilyAbsolute), + &[ + Partition::new(2, 512) + .with_id(0) + .with_flag(PartitionFlag::AcceptsDefaultFamilyRp2350ArmS) + .with_flag(PartitionFlag::AcceptsDefaultFamilyRp2350Riscv) + .with_permission(Permission::SecureRead) + .with_permission(Permission::SecureWrite) + .with_permission(Permission::NonSecureRead) + .with_permission(Permission::NonSecureWrite) + .with_permission(Permission::BootRead) + .with_permission(Permission::BootWrite) + .with_name("A"), + Partition::new(513, 1023) + .with_id(1) + .with_flag(PartitionFlag::AcceptsDefaultFamilyRp2350ArmS) + .with_flag(PartitionFlag::AcceptsDefaultFamilyRp2350Riscv) + .with_link(Link::ToA { partition_idx: 0 }) + .with_permission(Permission::SecureRead) + .with_permission(Permission::SecureWrite) + .with_permission(Permission::NonSecureRead) + .with_permission(Permission::NonSecureWrite) + .with_permission(Permission::BootRead) + .with_permission(Permission::BootWrite) + .with_name("B"), + ], + ) + .with_version(1, 0) + .with_sha256(); + let expected = &[ + 0xffffded3, // start + 0x02000c0a, // Item = PARTITION_TABLE + 0xfc008000, // Unpartitioned Space - permissions_and_flags + 0xfc400002, // Partition 0 - permissions_and_location (512 * 4096, 2 * 4096) + 0xfc061001, // permissions_and_flags HAS_ID | HAS_NAME | ARM-S | RISC-V + 0x00000000, // ID + 0x00000000, // ID + 0x00004101, // Name ("A") + 0xfc7fe201, // Partition 1 - permissions_and_location (1023 * 4096, 513 * 4096) + 0xfc061003, // permissions_and_flags LINKA(0) | HAS_ID | HAS_NAME | ARM-S | RISC-V + 0x00000001, // ID + 0x00000000, // ID + 0x00004201, // Name ("B") + 0x00000248, // Item = Version + 0x00010000, // 0, 1 + 0x01000247, // HASH_DEF with 2 words, and SHA256 hash + 0x00000011, // 17 words hashed + 0x0000094b, // HASH_VALUE with 9 words + 0x1945cdad, // Hash word 0 + 0x6b5f9773, // Hash word 1 + 0xe2bf39bd, // Hash word 2 + 0xb243e599, // Hash word 3 + 0xab2f0e9a, // Hash word 4 + 0x4d5d6d0b, // Hash word 5 + 0xf973050f, // Hash word 6 + 0x5ab6dadb, // Hash word 7 + 0x000019ff, // Last Item + 0x00000000, // Block Loop Next Offset + 0xab123579, // End + ]; + core::assert_eq!( + &table.contents[..29], + expected, + "{:#010x?}\n != \n{:#010x?}", + &table.contents[0..29], + expected, + ); + } +} diff --git a/embassy-rp/src/bootsel.rs b/embassy-rp/src/bootsel.rs index 540255ae3..d24ce7bd8 100644 --- a/embassy-rp/src/bootsel.rs +++ b/embassy-rp/src/bootsel.rs @@ -57,9 +57,9 @@ mod ram_helpers { "str {val}, [{cs_gpio}, $GPIO_CTRL]", // ...then wait for the state to settle... - "1:", // ~4000 cycle delay loop + "2:", // ~4000 cycle delay loop "subs {val}, #8", - "bne 1b", + "bne 2b", // ...we can read the current state of bootsel "ldr {val}, [{cs_gpio}, $GPIO_STATUS]", diff --git a/embassy-rp/src/clocks.rs b/embassy-rp/src/clocks.rs index 19232b801..e82beb0f1 100644 --- a/embassy-rp/src/clocks.rs +++ b/embassy-rp/src/clocks.rs @@ -1,13 +1,17 @@ //! Clock configuration for the RP2040 + +#[cfg(feature = "rp2040")] use core::arch::asm; use core::marker::PhantomData; -use core::sync::atomic::{AtomicU16, AtomicU32, Ordering}; +#[cfg(feature = "rp2040")] +use core::sync::atomic::AtomicU16; +use core::sync::atomic::{AtomicU32, Ordering}; use embassy_hal_internal::{into_ref, PeripheralRef}; use pac::clocks::vals::*; -use crate::gpio::sealed::Pin; -use crate::gpio::AnyPin; +use crate::gpio::{AnyPin, SealedPin}; +#[cfg(feature = "rp2040")] use crate::pac::common::{Reg, RW}; use crate::{pac, reset, Peripheral}; @@ -27,6 +31,7 @@ struct Clocks { // gpin1: AtomicU32, rosc: AtomicU32, peri: AtomicU32, + #[cfg(feature = "rp2040")] rtc: AtomicU16, } @@ -42,6 +47,7 @@ static CLOCKS: Clocks = Clocks { // gpin1: AtomicU32::new(0), rosc: AtomicU32::new(0), peri: AtomicU32::new(0), + #[cfg(feature = "rp2040")] rtc: AtomicU16::new(0), }; @@ -82,6 +88,7 @@ pub struct ClockConfig { /// ADC clock configuration. pub adc_clk: Option, /// RTC clock configuration. + #[cfg(feature = "rp2040")] pub rtc_clk: Option, // gpin0: Option<(u32, Gpin<'static, AnyPin>)>, // gpin1: Option<(u32, Gpin<'static, AnyPin>)>, @@ -102,7 +109,10 @@ impl ClockConfig { sys_pll: Some(PllConfig { refdiv: 1, fbdiv: 125, + #[cfg(feature = "rp2040")] post_div1: 6, + #[cfg(feature = "_rp235x")] + post_div1: 5, post_div2: 2, }), usb_pll: Some(PllConfig { @@ -136,6 +146,7 @@ impl ClockConfig { phase: 0, }), // CLK RTC = PLL USB (48MHz) / 1024 = 46875Hz + #[cfg(feature = "rp2040")] rtc_clk: Some(RtcClkConfig { src: RtcClkSrc::PllUsb, div_int: 1024, @@ -175,6 +186,7 @@ impl ClockConfig { phase: 0, }), // CLK RTC = ROSC (140MHz) / 2986.667969 ≅ 46875Hz + #[cfg(feature = "rp2040")] rtc_clk: Some(RtcClkConfig { src: RtcClkSrc::Rosc, div_int: 2986, @@ -296,9 +308,17 @@ pub struct SysClkConfig { /// SYS clock source. pub src: SysClkSrc, /// SYS clock divider. + #[cfg(feature = "rp2040")] pub div_int: u32, /// SYS clock fraction. + #[cfg(feature = "rp2040")] pub div_frac: u8, + /// SYS clock divider. + #[cfg(feature = "_rp235x")] + pub div_int: u16, + /// SYS clock fraction. + #[cfg(feature = "_rp235x")] + pub div_frac: u16, } /// USB clock source. @@ -359,6 +379,7 @@ pub struct AdcClkConfig { #[repr(u8)] #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg(feature = "rp2040")] pub enum RtcClkSrc { /// PLL USB. PllUsb = ClkRtcCtrlAuxsrc::CLKSRC_PLL_USB as _, @@ -373,6 +394,7 @@ pub enum RtcClkSrc { } /// RTC clock config. +#[cfg(feature = "rp2040")] pub struct RtcClkConfig { /// RTC clock source. pub src: RtcClkSrc, @@ -397,10 +419,9 @@ pub(crate) unsafe fn init(config: ClockConfig) { peris.set_pads_qspi(false); peris.set_pll_sys(false); peris.set_pll_usb(false); - // TODO investigate if usb should be unreset here peris.set_usbctrl(false); peris.set_syscfg(false); - peris.set_rtc(false); + //peris.set_rtc(false); reset::reset(peris); // Disable resus that may be enabled from previous software @@ -410,9 +431,15 @@ pub(crate) unsafe fn init(config: ClockConfig) { // Before we touch PLLs, switch sys and ref cleanly away from their aux sources. c.clk_sys_ctrl().modify(|w| w.set_src(ClkSysCtrlSrc::CLK_REF)); + #[cfg(feature = "rp2040")] while c.clk_sys_selected().read() != 1 {} + #[cfg(feature = "_rp235x")] + while c.clk_sys_selected().read() != pac::clocks::regs::ClkSysSelected(1) {} c.clk_ref_ctrl().modify(|w| w.set_src(ClkRefCtrlSrc::ROSC_CLKSRC_PH)); + #[cfg(feature = "rp2040")] while c.clk_ref_selected().read() != 1 {} + #[cfg(feature = "_rp235x")] + while c.clk_ref_selected().read() != pac::clocks::regs::ClkRefSelected(1) {} // Reset the PLLs let mut peris = reset::Peripherals(0); @@ -480,15 +507,26 @@ pub(crate) unsafe fn init(config: ClockConfig) { w.set_src(ref_src); w.set_auxsrc(ref_aux); }); - while c.clk_ref_selected().read() != 1 << ref_src as u32 {} + #[cfg(feature = "rp2040")] + while c.clk_ref_selected().read() != (1 << ref_src as u32) {} + #[cfg(feature = "_rp235x")] + while c.clk_ref_selected().read() != pac::clocks::regs::ClkRefSelected(1 << ref_src as u32) {} c.clk_ref_div().write(|w| { w.set_int(config.ref_clk.div); }); + // Configure tick generation on the 2040. + #[cfg(feature = "rp2040")] pac::WATCHDOG.tick().write(|w| { w.set_cycles((clk_ref_freq / 1_000_000) as u16); w.set_enable(true); }); + // Configure tick generator on the 2350 + #[cfg(feature = "_rp235x")] + { + pac::TICKS.timer0_cycles().write(|w| w.0 = clk_ref_freq / 1_000_000); + pac::TICKS.timer0_ctrl().write(|w| w.set_enable(true)); + } let (sys_src, sys_aux, clk_sys_freq) = { use {ClkSysCtrlAuxsrc as Aux, ClkSysCtrlSrc as Src}; @@ -501,7 +539,6 @@ pub(crate) unsafe fn init(config: ClockConfig) { // SysClkSrc::Gpin0 => (Src::CLKSRC_CLK_SYS_AUX, Aux::CLKSRC_GPIN0, gpin0_freq), // SysClkSrc::Gpin1 => (Src::CLKSRC_CLK_SYS_AUX, Aux::CLKSRC_GPIN1, gpin1_freq), }; - assert!(config.sys_clk.div_int <= 0x1000000); let div = config.sys_clk.div_int as u64 * 256 + config.sys_clk.div_frac as u64; (src, aux, ((freq as u64 * 256) / div) as u32) }; @@ -509,13 +546,21 @@ pub(crate) unsafe fn init(config: ClockConfig) { CLOCKS.sys.store(clk_sys_freq, Ordering::Relaxed); if sys_src != ClkSysCtrlSrc::CLK_REF { c.clk_sys_ctrl().write(|w| w.set_src(ClkSysCtrlSrc::CLK_REF)); - while c.clk_sys_selected().read() != 1 << ClkSysCtrlSrc::CLK_REF as u32 {} + #[cfg(feature = "rp2040")] + while c.clk_sys_selected().read() != (1 << ClkSysCtrlSrc::CLK_REF as u32) {} + #[cfg(feature = "_rp235x")] + while c.clk_sys_selected().read() != pac::clocks::regs::ClkSysSelected(1 << ClkSysCtrlSrc::CLK_REF as u32) {} } c.clk_sys_ctrl().write(|w| { w.set_auxsrc(sys_aux); w.set_src(sys_src); }); - while c.clk_sys_selected().read() != 1 << sys_src as u32 {} + + #[cfg(feature = "rp2040")] + while c.clk_sys_selected().read() != (1 << sys_src as u32) {} + #[cfg(feature = "_rp235x")] + while c.clk_sys_selected().read() != pac::clocks::regs::ClkSysSelected(1 << sys_src as u32) {} + c.clk_sys_div().write(|w| { w.set_int(config.sys_clk.div_int); w.set_frac(config.sys_clk.div_frac); @@ -593,6 +638,8 @@ pub(crate) unsafe fn init(config: ClockConfig) { CLOCKS.adc.store(0, Ordering::Relaxed); } + // rp2040 specific clocks + #[cfg(feature = "rp2040")] if let Some(conf) = config.rtc_clk { c.clk_rtc_div().write(|w| { w.set_int(conf.div_int); @@ -622,6 +669,13 @@ pub(crate) unsafe fn init(config: ClockConfig) { CLOCKS.rtc.store(0, Ordering::Relaxed); } + // rp235x specific clocks + #[cfg(feature = "_rp235x")] + { + // TODO hstx clock + peris.set_hstx(false); + } + // Peripheral clocks should now all be running reset::unreset_wait(peris); } @@ -710,15 +764,12 @@ pub fn clk_adc_freq() -> u32 { } /// RTC clock frequency. +#[cfg(feature = "rp2040")] pub fn clk_rtc_freq() -> u16 { CLOCKS.rtc.load(Ordering::Relaxed) } fn start_xosc(crystal_hz: u32, delay_multiplier: u32) { - pac::XOSC - .ctrl() - .write(|w| w.set_freq_range(pac::xosc::vals::CtrlFreqRange::_1_15MHZ)); - let startup_delay = (((crystal_hz / 1000) * delay_multiplier) + 128) / 256; pac::XOSC.startup().write(|w| w.set_delay(startup_delay as u16)); pac::XOSC.ctrl().write(|w| { @@ -737,7 +788,7 @@ fn configure_pll(p: pac::pll::Pll, input_freq: u32, config: PllConfig) -> u32 { assert!(config.refdiv >= 1 && config.refdiv <= 63); assert!(ref_freq >= 5_000_000 && ref_freq <= 800_000_000); let vco_freq = ref_freq.saturating_mul(config.fbdiv as u32); - assert!(vco_freq >= 750_000_000 && vco_freq <= 1800_000_000); + assert!(vco_freq >= 750_000_000 && vco_freq <= 1_800_000_000); // Load VCO-related dividers before starting VCO p.cs().write(|w| w.set_refdiv(config.refdiv as _)); @@ -788,17 +839,21 @@ impl_gpinpin!(PIN_20, 20, 0); impl_gpinpin!(PIN_22, 22, 1); /// General purpose clock input driver. -pub struct Gpin<'d, T: Pin> { +pub struct Gpin<'d, T: GpinPin> { gpin: PeripheralRef<'d, AnyPin>, _phantom: PhantomData, } -impl<'d, T: Pin> Gpin<'d, T> { +impl<'d, T: GpinPin> Gpin<'d, T> { /// Create new gpin driver. - pub fn new(gpin: impl Peripheral

+ 'd) -> Gpin<'d, P> { + pub fn new(gpin: impl Peripheral

+ 'd) -> Self { into_ref!(gpin); gpin.gpio().ctrl().write(|w| w.set_funcsel(0x08)); + #[cfg(feature = "_rp235x")] + gpin.pad_ctrl().write(|w| { + w.set_iso(false); + }); Gpin { gpin: gpin.map_into(), @@ -811,8 +866,9 @@ impl<'d, T: Pin> Gpin<'d, T> { // } } -impl<'d, T: Pin> Drop for Gpin<'d, T> { +impl<'d, T: GpinPin> Drop for Gpin<'d, T> { fn drop(&mut self) { + self.gpin.pad_ctrl().write(|_| {}); self.gpin .gpio() .ctrl() @@ -861,6 +917,7 @@ pub enum GpoutSrc { /// ADC. Adc = ClkGpoutCtrlAuxsrc::CLK_ADC as _, /// RTC. + #[cfg(feature = "rp2040")] Rtc = ClkGpoutCtrlAuxsrc::CLK_RTC as _, /// REF. Ref = ClkGpoutCtrlAuxsrc::CLK_REF as _, @@ -872,16 +929,21 @@ pub struct Gpout<'d, T: GpoutPin> { } impl<'d, T: GpoutPin> Gpout<'d, T> { - /// Create new general purpose cloud output. + /// Create new general purpose clock output. pub fn new(gpout: impl Peripheral

+ 'd) -> Self { into_ref!(gpout); gpout.gpio().ctrl().write(|w| w.set_funcsel(0x08)); + #[cfg(feature = "_rp235x")] + gpout.pad_ctrl().write(|w| { + w.set_iso(false); + }); Self { gpout } } /// Set clock divider. + #[cfg(feature = "rp2040")] pub fn set_div(&self, int: u32, frac: u8) { let c = pac::CLOCKS; c.clk_gpout_div(self.gpout.number()).write(|w| { @@ -890,6 +952,16 @@ impl<'d, T: GpoutPin> Gpout<'d, T> { }); } + /// Set clock divider. + #[cfg(feature = "_rp235x")] + pub fn set_div(&self, int: u16, frac: u16) { + let c = pac::CLOCKS; + c.clk_gpout_div(self.gpout.number()).write(|w| { + w.set_int(int); + w.set_frac(frac); + }); + } + /// Set clock source. pub fn set_src(&self, src: GpoutSrc) { let c = pac::CLOCKS; @@ -929,13 +1001,13 @@ impl<'d, T: GpoutPin> Gpout<'d, T> { ClkGpoutCtrlAuxsrc::CLK_SYS => clk_sys_freq(), ClkGpoutCtrlAuxsrc::CLK_USB => clk_usb_freq(), ClkGpoutCtrlAuxsrc::CLK_ADC => clk_adc_freq(), - ClkGpoutCtrlAuxsrc::CLK_RTC => clk_rtc_freq() as _, + //ClkGpoutCtrlAuxsrc::CLK_RTC => clk_rtc_freq() as _, ClkGpoutCtrlAuxsrc::CLK_REF => clk_ref_freq(), _ => unreachable!(), }; let div = c.clk_gpout_div(self.gpout.number()).read(); - let int = if div.int() == 0 { 65536 } else { div.int() } as u64; + let int = if div.int() == 0 { 0xFFFF } else { div.int() } as u64; let frac = div.frac() as u64; ((base as u64 * 256) / (int * 256 + frac)) as u32 @@ -945,6 +1017,7 @@ impl<'d, T: GpoutPin> Gpout<'d, T> { impl<'d, T: GpoutPin> Drop for Gpout<'d, T> { fn drop(&mut self) { self.disable(); + self.gpout.pad_ctrl().write(|_| {}); self.gpout .gpio() .ctrl() @@ -992,7 +1065,7 @@ impl rand_core::RngCore for RoscRng { /// and can only be exited through resets, dormant-wake GPIO interrupts, /// and RTC interrupts. If RTC is clocked from an internal clock source /// it will be stopped and not function as a wakeup source. -#[cfg(target_arch = "arm")] +#[cfg(all(target_arch = "arm", feature = "rp2040"))] pub fn dormant_sleep() { struct Set(Reg, T, F); @@ -1028,7 +1101,7 @@ pub fn dormant_sleep() { let _stop_adc = set(pac::CLOCKS.clk_adc_ctrl(), |w| w.set_enable(false)); let _stop_usb = set(pac::CLOCKS.clk_usb_ctrl(), |w| w.set_enable(false)); let _stop_peri = set(pac::CLOCKS.clk_peri_ctrl(), |w| w.set_enable(false)); - // set up rosc. we could ask the use to tell us which clock source to wake from like + // set up rosc. we could ask the user to tell us which clock source to wake from like // the C SDK does, but that seems rather unfriendly. we *may* disturb rtc by changing // rosc configuration if it's currently the rtc clock source, so we'll configure rosc // to the slowest frequency to minimize that impact. @@ -1112,7 +1185,7 @@ pub fn dormant_sleep() { coma = in (reg) 0x636f6d61, ); } else { - pac::ROSC.dormant().write_value(0x636f6d61); + pac::ROSC.dormant().write_value(rp_pac::rosc::regs::Dormant(0x636f6d61)); } } } diff --git a/embassy-rp/src/dma.rs b/embassy-rp/src/dma.rs index 088a842a1..34abe3e2d 100644 --- a/embassy-rp/src/dma.rs +++ b/embassy-rp/src/dma.rs @@ -15,7 +15,7 @@ use crate::{interrupt, pac, peripherals}; #[cfg(feature = "rt")] #[interrupt] fn DMA_IRQ_0() { - let ints0 = pac::DMA.ints0().read().ints0(); + let ints0 = pac::DMA.ints(0).read(); for channel in 0..CHANNEL_COUNT { let ctrl_trig = pac::DMA.ch(channel).ctrl_trig().read(); if ctrl_trig.ahb_error() { @@ -26,14 +26,14 @@ fn DMA_IRQ_0() { CHANNEL_WAKERS[channel].wake(); } } - pac::DMA.ints0().write(|w| w.set_ints0(ints0)); + pac::DMA.ints(0).write_value(ints0); } pub(crate) unsafe fn init() { interrupt::DMA_IRQ_0.disable(); interrupt::DMA_IRQ_0.set_priority(interrupt::Priority::P3); - pac::DMA.inte0().write(|w| w.set_inte0(0xFFFF)); + pac::DMA.inte(0).write_value(0xFFFF); interrupt::DMA_IRQ_0.enable(); } @@ -45,14 +45,13 @@ pub unsafe fn read<'a, C: Channel, W: Word>( ch: impl Peripheral

+ 'a, from: *const W, to: *mut [W], - dreq: u8, + dreq: vals::TreqSel, ) -> Transfer<'a, C> { - let (to_ptr, len) = crate::dma::slice_ptr_parts(to); copy_inner( ch, from as *const u32, - to_ptr as *mut u32, - len, + to as *mut W as *mut u32, + to.len(), W::size(), false, true, @@ -67,14 +66,13 @@ pub unsafe fn write<'a, C: Channel, W: Word>( ch: impl Peripheral

+ 'a, from: *const [W], to: *mut W, - dreq: u8, + dreq: vals::TreqSel, ) -> Transfer<'a, C> { - let (from_ptr, len) = crate::dma::slice_ptr_parts(from); copy_inner( ch, - from_ptr as *const u32, + from as *const W as *const u32, to as *mut u32, - len, + from.len(), W::size(), true, false, @@ -92,11 +90,11 @@ pub unsafe fn write_repeated<'a, C: Channel, W: Word>( ch: impl Peripheral

+ 'a, to: *mut W, len: usize, - dreq: u8, + dreq: vals::TreqSel, ) -> Transfer<'a, C> { copy_inner( ch, - &mut DUMMY as *const u32, + core::ptr::addr_of_mut!(DUMMY) as *const u32, to as *mut u32, len, W::size(), @@ -114,18 +112,18 @@ pub unsafe fn copy<'a, C: Channel, W: Word>( from: &[W], to: &mut [W], ) -> Transfer<'a, C> { - let (from_ptr, from_len) = crate::dma::slice_ptr_parts(from); - let (to_ptr, to_len) = crate::dma::slice_ptr_parts_mut(to); + let from_len = from.len(); + let to_len = to.len(); assert_eq!(from_len, to_len); copy_inner( ch, - from_ptr as *const u32, - to_ptr as *mut u32, + from.as_ptr() as *const u32, + to.as_mut_ptr() as *mut u32, from_len, W::size(), true, true, - vals::TreqSel::PERMANENT.0, + vals::TreqSel::PERMANENT, ) } @@ -137,7 +135,7 @@ fn copy_inner<'a, C: Channel>( data_size: DataSize, incr_read: bool, incr_write: bool, - dreq: u8, + dreq: vals::TreqSel, ) -> Transfer<'a, C> { into_ref!(ch); @@ -145,14 +143,20 @@ fn copy_inner<'a, C: Channel>( p.read_addr().write_value(from as u32); p.write_addr().write_value(to as u32); - p.trans_count().write_value(len as u32); + #[cfg(feature = "rp2040")] + p.trans_count().write(|w| { + *w = len as u32; + }); + #[cfg(feature = "_rp235x")] + p.trans_count().write(|w| { + w.set_mode(0.into()); + w.set_count(len as u32); + }); compiler_fence(Ordering::SeqCst); p.ctrl_trig().write(|w| { - // TODO: Add all DREQ options to pac vals::TreqSel, and use - // `set_treq:sel` - w.0 = ((dreq as u32) & 0x3f) << 15usize; + w.set_treq_sel(dreq); w.set_data_size(data_size); w.set_incr_read(incr_read); w.set_incr_write(incr_write); @@ -204,18 +208,19 @@ impl<'a, C: Channel> Future for Transfer<'a, C> { } } +#[cfg(feature = "rp2040")] pub(crate) const CHANNEL_COUNT: usize = 12; +#[cfg(feature = "_rp235x")] +pub(crate) const CHANNEL_COUNT: usize = 16; const NEW_AW: AtomicWaker = AtomicWaker::new(); static CHANNEL_WAKERS: [AtomicWaker; CHANNEL_COUNT] = [NEW_AW; CHANNEL_COUNT]; -mod sealed { - pub trait Channel {} - - pub trait Word {} -} +trait SealedChannel {} +trait SealedWord {} /// DMA channel interface. -pub trait Channel: Peripheral

+ sealed::Channel + Into + Sized + 'static { +#[allow(private_bounds)] +pub trait Channel: Peripheral

+ SealedChannel + Into + Sized + 'static { /// Channel number. fn number(&self) -> u8; @@ -231,26 +236,27 @@ pub trait Channel: Peripheral

+ sealed::Channel + Into + S } /// DMA word. -pub trait Word: sealed::Word { +#[allow(private_bounds)] +pub trait Word: SealedWord { /// Word size. fn size() -> vals::DataSize; } -impl sealed::Word for u8 {} +impl SealedWord for u8 {} impl Word for u8 { fn size() -> vals::DataSize { vals::DataSize::SIZE_BYTE } } -impl sealed::Word for u16 {} +impl SealedWord for u16 {} impl Word for u16 { fn size() -> vals::DataSize { vals::DataSize::SIZE_HALFWORD } } -impl sealed::Word for u32 {} +impl SealedWord for u32 {} impl Word for u32 { fn size() -> vals::DataSize { vals::DataSize::SIZE_WORD @@ -264,7 +270,7 @@ pub struct AnyChannel { impl_peripheral!(AnyChannel); -impl sealed::Channel for AnyChannel {} +impl SealedChannel for AnyChannel {} impl Channel for AnyChannel { fn number(&self) -> u8 { self.number @@ -273,7 +279,7 @@ impl Channel for AnyChannel { macro_rules! channel { ($name:ident, $num:expr) => { - impl sealed::Channel for peripherals::$name {} + impl SealedChannel for peripherals::$name {} impl Channel for peripherals::$name { fn number(&self) -> u8 { $num @@ -288,17 +294,6 @@ macro_rules! channel { }; } -// TODO: replace transmutes with core::ptr::metadata once it's stable -#[allow(unused)] -pub(crate) fn slice_ptr_parts(slice: *const [T]) -> (usize, usize) { - unsafe { core::mem::transmute(slice) } -} - -#[allow(unused)] -pub(crate) fn slice_ptr_parts_mut(slice: *mut [T]) -> (usize, usize) { - unsafe { core::mem::transmute(slice) } -} - channel!(DMA_CH0, 0); channel!(DMA_CH1, 1); channel!(DMA_CH2, 2); @@ -311,3 +306,11 @@ channel!(DMA_CH8, 8); channel!(DMA_CH9, 9); channel!(DMA_CH10, 10); channel!(DMA_CH11, 11); +#[cfg(feature = "_rp235x")] +channel!(DMA_CH12, 12); +#[cfg(feature = "_rp235x")] +channel!(DMA_CH13, 13); +#[cfg(feature = "_rp235x")] +channel!(DMA_CH14, 14); +#[cfg(feature = "_rp235x")] +channel!(DMA_CH15, 15); diff --git a/embassy-rp/src/flash.rs b/embassy-rp/src/flash.rs index 2d673cf6c..fbc8b35ec 100644 --- a/embassy-rp/src/flash.rs +++ b/embassy-rp/src/flash.rs @@ -17,9 +17,13 @@ use crate::peripherals::FLASH; /// Flash base address. pub const FLASH_BASE: *const u32 = 0x10000000 as _; +/// Address for xip setup function set up by the 235x bootrom. +#[cfg(feature = "_rp235x")] +pub const BOOTROM_BASE: *const u32 = 0x400e0000 as _; + /// If running from RAM, we might have no boot2. Use bootrom `flash_enter_cmd_xip` instead. // TODO: when run-from-ram is set, completely skip the "pause cores and jumpp to RAM" dance. -pub const USE_BOOT2: bool = !cfg!(feature = "run-from-ram"); +pub const USE_BOOT2: bool = !cfg!(feature = "run-from-ram") | cfg!(feature = "_rp235x"); // **NOTE**: // @@ -97,7 +101,10 @@ impl<'a, 'd, T: Instance, const FLASH_SIZE: usize> Drop for BackgroundRead<'a, ' // Errata RP2040-E8: Perform an uncached read to make sure there's not a transfer in // flight that might effect an address written to start a new transfer. This stalls // until after any transfer is complete, so the address will not change anymore. + #[cfg(feature = "rp2040")] const XIP_NOCACHE_NOALLOC_BASE: *const u32 = 0x13000000 as *const _; + #[cfg(feature = "_rp235x")] + const XIP_NOCACHE_NOALLOC_BASE: *const u32 = 0x14000000 as *const _; unsafe { core::ptr::read_volatile(XIP_NOCACHE_NOALLOC_BASE); } @@ -225,12 +232,14 @@ impl<'d, T: Instance, M: Mode, const FLASH_SIZE: usize> Flash<'d, T, M, FLASH_SI } /// Read SPI flash unique ID + #[cfg(feature = "rp2040")] pub fn blocking_unique_id(&mut self, uid: &mut [u8]) -> Result<(), Error> { unsafe { in_ram(|| ram_helpers::flash_unique_id(uid))? }; Ok(()) } /// Read SPI flash JEDEC ID + #[cfg(feature = "rp2040")] pub fn blocking_jedec_id(&mut self) -> Result { let mut jedec = None; unsafe { @@ -301,8 +310,18 @@ impl<'d, T: Instance, const FLASH_SIZE: usize> Flash<'d, T, Async, FLASH_SIZE> { // Use the XIP AUX bus port, rather than the FIFO register access (e.x. // pac::XIP_CTRL.stream_fifo().as_ptr()) to avoid DMA stalling on // general XIP access. + #[cfg(feature = "rp2040")] const XIP_AUX_BASE: *const u32 = 0x50400000 as *const _; - let transfer = unsafe { crate::dma::read(self.dma.as_mut().unwrap(), XIP_AUX_BASE, data, 37) }; + #[cfg(feature = "_rp235x")] + const XIP_AUX_BASE: *const u32 = 0x50500000 as *const _; + let transfer = unsafe { + crate::dma::read( + self.dma.as_mut().unwrap(), + XIP_AUX_BASE, + data, + pac::dma::vals::TreqSel::XIP_STREAM, + ) + }; Ok(BackgroundRead { flash: PhantomData, @@ -326,9 +345,9 @@ impl<'d, T: Instance, const FLASH_SIZE: usize> Flash<'d, T, Async, FLASH_SIZE> { // If the destination address is already aligned, then we can just DMA directly if (bytes.as_ptr() as u32) % 4 == 0 { // Safety: alignment and size have been checked for compatibility - let mut buf: &mut [u32] = + let buf: &mut [u32] = unsafe { core::slice::from_raw_parts_mut(bytes.as_mut_ptr() as *mut u32, bytes.len() / 4) }; - self.background_read(offset, &mut buf)?.await; + self.background_read(offset, buf)?.await; return Ok(()); } @@ -374,6 +393,11 @@ impl<'d, T: Instance, M: Mode, const FLASH_SIZE: usize> ReadNorFlash for Flash<' impl<'d, T: Instance, M: Mode, const FLASH_SIZE: usize> MultiwriteNorFlash for Flash<'d, T, M, FLASH_SIZE> {} +impl<'d, T: Instance, const FLASH_SIZE: usize> embedded_storage_async::nor_flash::MultiwriteNorFlash + for Flash<'d, T, Async, FLASH_SIZE> +{ +} + impl<'d, T: Instance, M: Mode, const FLASH_SIZE: usize> NorFlash for Flash<'d, T, M, FLASH_SIZE> { const WRITE_SIZE: usize = WRITE_SIZE; @@ -420,8 +444,6 @@ impl<'d, T: Instance, const FLASH_SIZE: usize> embedded_storage_async::nor_flash #[allow(dead_code)] mod ram_helpers { - use core::marker::PhantomData; - use super::*; use crate::rom_data; @@ -502,7 +524,10 @@ mod ram_helpers { pub unsafe fn flash_range_erase(addr: u32, len: u32) { let mut boot2 = [0u32; 256 / 4]; let ptrs = if USE_BOOT2 { + #[cfg(feature = "rp2040")] rom_data::memcpy44(&mut boot2 as *mut _, FLASH_BASE, 256); + #[cfg(feature = "_rp235x")] + core::ptr::copy_nonoverlapping(BOOTROM_BASE as *const u8, boot2.as_mut_ptr() as *mut u8, 256); flash_function_pointers_with_boot2(true, false, &boot2) } else { flash_function_pointers(true, false) @@ -532,7 +557,10 @@ mod ram_helpers { pub unsafe fn flash_range_erase_and_program(addr: u32, data: &[u8]) { let mut boot2 = [0u32; 256 / 4]; let ptrs = if USE_BOOT2 { + #[cfg(feature = "rp2040")] rom_data::memcpy44(&mut boot2 as *mut _, FLASH_BASE, 256); + #[cfg(feature = "_rp235x")] + core::ptr::copy_nonoverlapping(BOOTROM_BASE as *const u8, (boot2).as_mut_ptr() as *mut u8, 256); flash_function_pointers_with_boot2(true, true, &boot2) } else { flash_function_pointers(true, true) @@ -567,7 +595,10 @@ mod ram_helpers { pub unsafe fn flash_range_program(addr: u32, data: &[u8]) { let mut boot2 = [0u32; 256 / 4]; let ptrs = if USE_BOOT2 { + #[cfg(feature = "rp2040")] rom_data::memcpy44(&mut boot2 as *mut _, FLASH_BASE, 256); + #[cfg(feature = "_rp235x")] + core::ptr::copy_nonoverlapping(BOOTROM_BASE as *const u8, boot2.as_mut_ptr() as *mut u8, 256); flash_function_pointers_with_boot2(false, true, &boot2) } else { flash_function_pointers(false, true) @@ -594,16 +625,8 @@ mod ram_helpers { /// addr must be aligned to 4096 #[inline(never)] #[link_section = ".data.ram_func"] + #[cfg(feature = "rp2040")] unsafe fn write_flash_inner(addr: u32, len: u32, data: Option<&[u8]>, ptrs: *const FlashFunctionPointers) { - /* - Should be equivalent to: - rom_data::connect_internal_flash(); - rom_data::flash_exit_xip(); - rom_data::flash_range_erase(addr, len, 1 << 31, 0); // if selected - rom_data::flash_range_program(addr, data as *const _, len); // if selected - rom_data::flash_flush_cache(); - rom_data::flash_enter_cmd_xip(); - */ #[cfg(target_arch = "arm")] core::arch::asm!( "mov r8, r0", @@ -622,18 +645,18 @@ mod ram_helpers { "movs r3, #0", // r3 = 0 "ldr r4, [{ptrs}, #8]", "cmp r4, #0", - "beq 1f", + "beq 2f", "blx r4", // flash_range_erase(addr, len, 1 << 31, 0) - "1:", + "2:", "mov r0, r8", // r0 = addr "mov r1, r9", // r0 = data "mov r2, r10", // r2 = len "ldr r4, [{ptrs}, #12]", "cmp r4, #0", - "beq 1f", + "beq 2f", "blx r4", // flash_range_program(addr, data, len); - "1:", + "2:", "ldr r4, [{ptrs}, #16]", "blx r4", // flash_flush_cache(); @@ -656,6 +679,32 @@ mod ram_helpers { ); } + /// # Safety + /// + /// Nothing must access flash while this is running. + /// Usually this means: + /// - interrupts must be disabled + /// - 2nd core must be running code from RAM or ROM with interrupts disabled + /// - DMA must not access flash memory + /// Length of data must be a multiple of 4096 + /// addr must be aligned to 4096 + #[inline(never)] + #[link_section = ".data.ram_func"] + #[cfg(feature = "_rp235x")] + unsafe fn write_flash_inner(addr: u32, len: u32, data: Option<&[u8]>, ptrs: *const FlashFunctionPointers) { + let data = data.map(|d| d.as_ptr()).unwrap_or(core::ptr::null()); + ((*ptrs).connect_internal_flash)(); + ((*ptrs).flash_exit_xip)(); + if (*ptrs).flash_range_erase.is_some() { + ((*ptrs).flash_range_erase.unwrap())(addr, len as usize, 1 << 31, 0); + } + if (*ptrs).flash_range_program.is_some() { + ((*ptrs).flash_range_program.unwrap())(addr, data as *const _, len as usize); + } + ((*ptrs).flash_flush_cache)(); + ((*ptrs).flash_enter_cmd_xip)(); + } + #[repr(C)] struct FlashCommand { cmd_addr: *const u8, @@ -689,6 +738,7 @@ mod ram_helpers { /// - DMA must not access flash memory /// /// Credit: taken from `rp2040-flash` (also licensed Apache+MIT) + #[cfg(feature = "rp2040")] pub unsafe fn flash_unique_id(out: &mut [u8]) { let mut boot2 = [0u32; 256 / 4]; let ptrs = if USE_BOOT2 { @@ -697,6 +747,7 @@ mod ram_helpers { } else { flash_function_pointers(false, false) }; + // 4B - read unique ID let cmd = [0x4B]; read_flash(&cmd[..], 4, out, &ptrs as *const FlashFunctionPointers); @@ -717,6 +768,7 @@ mod ram_helpers { /// - DMA must not access flash memory /// /// Credit: taken from `rp2040-flash` (also licensed Apache+MIT) + #[cfg(feature = "rp2040")] pub unsafe fn flash_jedec_id() -> u32 { let mut boot2 = [0u32; 256 / 4]; let ptrs = if USE_BOOT2 { @@ -725,6 +777,7 @@ mod ram_helpers { } else { flash_function_pointers(false, false) }; + let mut id = [0u8; 4]; // 9F - read JEDEC ID let cmd = [0x9F]; @@ -732,6 +785,7 @@ mod ram_helpers { u32::from_be_bytes(id) } + #[cfg(feature = "rp2040")] unsafe fn read_flash(cmd_addr: &[u8], dummy_len: u32, out: &mut [u8], ptrs: *const FlashFunctionPointers) { read_flash_inner( FlashCommand { @@ -755,6 +809,7 @@ mod ram_helpers { /// Credit: taken from `rp2040-flash` (also licensed Apache+MIT) #[inline(never)] #[link_section = ".data.ram_func"] + #[cfg(feature = "rp2040")] unsafe fn read_flash_inner(cmd: FlashCommand, ptrs: *const FlashFunctionPointers) { #[cfg(target_arch = "arm")] core::arch::asm!( @@ -799,12 +854,12 @@ mod ram_helpers { "adds r2, 0x60", // &DR "ldr r0, [r3, #0]", // cmd_addr "ldr r1, [r3, #4]", // cmd_addr_len - "10:", + "3:", "ldrb r3, [r0]", "strb r3, [r2]", // DR "adds r0, #1", "subs r1, #1", - "bne 10b", + "bne 3b", // Skip any dummy cycles "mov r3, r10", // cmd @@ -905,22 +960,22 @@ pub(crate) unsafe fn in_ram(operation: impl FnOnce()) -> Result<(), Error> { Ok(()) } -mod sealed { - pub trait Instance {} - pub trait Mode {} -} +trait SealedInstance {} +trait SealedMode {} /// Flash instance. -pub trait Instance: sealed::Instance {} +#[allow(private_bounds)] +pub trait Instance: SealedInstance {} /// Flash mode. -pub trait Mode: sealed::Mode {} +#[allow(private_bounds)] +pub trait Mode: SealedMode {} -impl sealed::Instance for FLASH {} +impl SealedInstance for FLASH {} impl Instance for FLASH {} macro_rules! impl_mode { ($name:ident) => { - impl sealed::Mode for $name {} + impl SealedMode for $name {} impl Mode for $name {} }; } diff --git a/embassy-rp/src/float/mod.rs b/embassy-rp/src/float/mod.rs index 945afff90..3ad6f1c50 100644 --- a/embassy-rp/src/float/mod.rs +++ b/embassy-rp/src/float/mod.rs @@ -89,6 +89,7 @@ pub(crate) trait Float: } /// Returns true if `self` is infinity + #[allow(unused)] fn is_infinity(self) -> bool { (self.repr() & (Self::EXPONENT_MASK | Self::SIGNIFICAND_MASK)) == Self::EXPONENT_MASK } diff --git a/embassy-rp/src/fmt.rs b/embassy-rp/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-rp/src/fmt.rs +++ b/embassy-rp/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-rp/src/gpio.rs b/embassy-rp/src/gpio.rs index 93b29bbf9..cb54375e4 100644 --- a/embassy-rp/src/gpio.rs +++ b/embassy-rp/src/gpio.rs @@ -8,14 +8,18 @@ use core::task::{Context, Poll}; use embassy_hal_internal::{impl_peripheral, into_ref, PeripheralRef}; use embassy_sync::waitqueue::AtomicWaker; -use self::sealed::Pin as _; use crate::interrupt::InterruptExt; use crate::pac::common::{Reg, RW}; use crate::pac::SIO; use crate::{interrupt, pac, peripherals, Peripheral, RegExt}; const NEW_AW: AtomicWaker = AtomicWaker::new(); -const BANK0_PIN_COUNT: usize = 30; + +#[cfg(any(feature = "rp2040", feature = "rp235xa"))] +pub(crate) const BANK0_PIN_COUNT: usize = 30; +#[cfg(feature = "rp235xb")] +pub(crate) const BANK0_PIN_COUNT: usize = 48; + static BANK0_WAKERS: [AtomicWaker; BANK0_PIN_COUNT] = [NEW_AW; BANK0_PIN_COUNT]; #[cfg(feature = "qspi-as-gpio")] const QSPI_PIN_COUNT: usize = 6; @@ -179,6 +183,13 @@ impl<'d> Input<'d> { pub fn dormant_wake(&mut self, cfg: DormantWakeConfig) -> DormantWake<'_> { self.pin.dormant_wake(cfg) } + + /// Set the pin's pad isolation + #[cfg(feature = "_rp235x")] + #[inline] + pub fn set_pad_isolation(&mut self, isolate: bool) { + self.pin.set_pad_isolation(isolate) + } } /// Interrupt trigger levels. @@ -225,8 +236,8 @@ fn irq_handler(bank: pac::io::Io, wakers: &[AtomicWaker; N]) { // The status register is divided into groups of four, one group for // each pin. Each group consists of four trigger levels LEVEL_LOW, // LEVEL_HIGH, EDGE_LOW, and EDGE_HIGH for each pin. - let pin_group = (pin % 8) as usize; - let event = (intsx.read().0 >> pin_group * 4) & 0xf as u32; + let pin_group = pin % 8; + let event = (intsx.read().0 >> (pin_group * 4)) & 0xf; // no more than one event can be awaited per pin at any given time, so // we can just clear all interrupt enables for that pin without having @@ -238,7 +249,7 @@ fn irq_handler(bank: pac::io::Io, wakers: &[AtomicWaker; N]) { w.set_level_high(pin_group, true); w.set_level_low(pin_group, true); }); - wakers[pin as usize].wake(); + wakers[pin].wake(); } } } @@ -414,6 +425,13 @@ impl<'d> Output<'d> { pub fn toggle(&mut self) { self.pin.toggle() } + + /// Set the pin's pad isolation + #[cfg(feature = "_rp235x")] + #[inline] + pub fn set_pad_isolation(&mut self, isolate: bool) { + self.pin.set_pad_isolation(isolate) + } } /// GPIO output open-drain. @@ -540,6 +558,13 @@ impl<'d> OutputOpenDrain<'d> { pub async fn wait_for_any_edge(&mut self) { self.pin.wait_for_any_edge().await; } + + /// Set the pin's pad isolation + #[cfg(feature = "_rp235x")] + #[inline] + pub fn set_pad_isolation(&mut self, isolate: bool) { + self.pin.set_pad_isolation(isolate) + } } /// GPIO flexible pin. @@ -561,11 +586,16 @@ impl<'d> Flex<'d> { into_ref!(pin); pin.pad_ctrl().write(|w| { + #[cfg(feature = "_rp235x")] + w.set_iso(false); w.set_ie(true); }); pin.gpio().ctrl().write(|w| { + #[cfg(feature = "rp2040")] w.set_funcsel(pac::io::vals::Gpio0ctrlFuncsel::SIO_0 as _); + #[cfg(feature = "_rp235x")] + w.set_funcsel(pac::io::vals::Gpio0ctrlFuncsel::SIOB_PROC_0 as _); }); Self { pin: pin.map_into() } @@ -573,7 +603,7 @@ impl<'d> Flex<'d> { #[inline] fn bit(&self) -> u32 { - 1 << self.pin.pin() + 1 << (self.pin.pin() % 32) } /// Set the pin's pull. @@ -761,6 +791,15 @@ impl<'d> Flex<'d> { cfg, } } + + /// Set the pin's pad isolation + #[cfg(feature = "_rp235x")] + #[inline] + pub fn set_pad_isolation(&mut self, isolate: bool) { + self.pin.pad_ctrl().modify(|w| { + w.set_iso(isolate); + }); + } } impl<'d> Drop for Flex<'d> { @@ -802,68 +841,77 @@ impl<'w> Drop for DormantWake<'w> { } } -pub(crate) mod sealed { - use super::*; +pub(crate) trait SealedPin: Sized { + fn pin_bank(&self) -> u8; - pub trait Pin: Sized { - fn pin_bank(&self) -> u8; + #[inline] + fn _pin(&self) -> u8 { + self.pin_bank() & 0x7f + } - #[inline] - fn _pin(&self) -> u8 { - self.pin_bank() & 0x1f + #[inline] + fn _bank(&self) -> Bank { + match self.pin_bank() >> 7 { + #[cfg(feature = "qspi-as-gpio")] + 1 => Bank::Qspi, + _ => Bank::Bank0, } + } - #[inline] - fn _bank(&self) -> Bank { - match self.pin_bank() & 0x20 { - #[cfg(feature = "qspi-as-gpio")] - 1 => Bank::Qspi, - _ => Bank::Bank0, - } + fn io(&self) -> pac::io::Io { + match self._bank() { + Bank::Bank0 => crate::pac::IO_BANK0, + #[cfg(feature = "qspi-as-gpio")] + Bank::Qspi => crate::pac::IO_QSPI, } + } - fn io(&self) -> pac::io::Io { - match self._bank() { - Bank::Bank0 => crate::pac::IO_BANK0, - #[cfg(feature = "qspi-as-gpio")] - Bank::Qspi => crate::pac::IO_QSPI, - } - } + fn gpio(&self) -> pac::io::Gpio { + self.io().gpio(self._pin() as _) + } - fn gpio(&self) -> pac::io::Gpio { - self.io().gpio(self._pin() as _) - } + fn pad_ctrl(&self) -> Reg { + let block = match self._bank() { + Bank::Bank0 => crate::pac::PADS_BANK0, + #[cfg(feature = "qspi-as-gpio")] + Bank::Qspi => crate::pac::PADS_QSPI, + }; + block.gpio(self._pin() as _) + } - fn pad_ctrl(&self) -> Reg { - let block = match self._bank() { - Bank::Bank0 => crate::pac::PADS_BANK0, - #[cfg(feature = "qspi-as-gpio")] - Bank::Qspi => crate::pac::PADS_QSPI, - }; - block.gpio(self._pin() as _) - } - - fn sio_out(&self) -> pac::sio::Gpio { + fn sio_out(&self) -> pac::sio::Gpio { + if cfg!(feature = "rp2040") { SIO.gpio_out(self._bank() as _) + } else { + SIO.gpio_out((self._pin() / 32) as _) } + } - fn sio_oe(&self) -> pac::sio::Gpio { + fn sio_oe(&self) -> pac::sio::Gpio { + if cfg!(feature = "rp2040") { SIO.gpio_oe(self._bank() as _) + } else { + SIO.gpio_oe((self._pin() / 32) as _) } + } - fn sio_in(&self) -> Reg { + fn sio_in(&self) -> Reg { + if cfg!(feature = "rp2040") { SIO.gpio_in(self._bank() as _) + } else { + SIO.gpio_in((self._pin() / 32) as _) } + } - fn int_proc(&self) -> pac::io::Int { - let proc = SIO.cpuid().read(); - self.io().int_proc(proc as _) - } + fn int_proc(&self) -> pac::io::Int { + let proc = SIO.cpuid().read(); + self.io().int_proc(proc as _) } } /// Interface for a Pin that can be configured by an [Input] or [Output] driver, or converted to an [AnyPin]. -pub trait Pin: Peripheral

+ Into + sealed::Pin + Sized + 'static { +#[allow(private_bounds)] +pub trait Pin: Peripheral

+ Into + SealedPin + Sized + 'static { /// Degrade to a generic pin struct fn degrade(self) -> AnyPin { AnyPin { @@ -889,10 +937,21 @@ pub struct AnyPin { pin_bank: u8, } +impl AnyPin { + /// Unsafely create a new type-erased pin. + /// + /// # Safety + /// + /// You must ensure that you’re only using one instance of this type at a time. + pub unsafe fn steal(pin_bank: u8) -> Self { + Self { pin_bank } + } +} + impl_peripheral!(AnyPin); impl Pin for AnyPin {} -impl sealed::Pin for AnyPin { +impl SealedPin for AnyPin { fn pin_bank(&self) -> u8 { self.pin_bank } @@ -903,10 +962,10 @@ impl sealed::Pin for AnyPin { macro_rules! impl_pin { ($name:ident, $bank:expr, $pin_num:expr) => { impl Pin for peripherals::$name {} - impl sealed::Pin for peripherals::$name { + impl SealedPin for peripherals::$name { #[inline] fn pin_bank(&self) -> u8 { - ($bank as u8) * 32 + $pin_num + ($bank as u8) * 128 + $pin_num } } @@ -949,6 +1008,44 @@ impl_pin!(PIN_27, Bank::Bank0, 27); impl_pin!(PIN_28, Bank::Bank0, 28); impl_pin!(PIN_29, Bank::Bank0, 29); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_30, Bank::Bank0, 30); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_31, Bank::Bank0, 31); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_32, Bank::Bank0, 32); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_33, Bank::Bank0, 33); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_34, Bank::Bank0, 34); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_35, Bank::Bank0, 35); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_36, Bank::Bank0, 36); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_37, Bank::Bank0, 37); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_38, Bank::Bank0, 38); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_39, Bank::Bank0, 39); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_40, Bank::Bank0, 40); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_41, Bank::Bank0, 41); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_42, Bank::Bank0, 42); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_43, Bank::Bank0, 43); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_44, Bank::Bank0, 44); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_45, Bank::Bank0, 45); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_46, Bank::Bank0, 46); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_47, Bank::Bank0, 47); + +// TODO rp235x bank1 as gpio support #[cfg(feature = "qspi-as-gpio")] impl_pin!(PIN_QSPI_SCLK, Bank::Qspi, 0); #[cfg(feature = "qspi-as-gpio")] @@ -965,8 +1062,6 @@ impl_pin!(PIN_QSPI_SD3, Bank::Qspi, 5); // ==================== mod eh02 { - use core::convert::Infallible; - use super::*; impl<'d> embedded_hal_02::digital::v2::InputPin for Input<'d> { diff --git a/embassy-rp/src/i2c.rs b/embassy-rp/src/i2c.rs index 74d015792..32778215f 100644 --- a/embassy-rp/src/i2c.rs +++ b/embassy-rp/src/i2c.rs @@ -12,7 +12,7 @@ use crate::interrupt::typelevel::{Binding, Interrupt}; use crate::{interrupt, pac, peripherals, Peripheral}; /// I2C error abort reason -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum AbortReason { /// A bus operation was not acknowledged, e.g. due to the addressed device @@ -28,7 +28,7 @@ pub enum AbortReason { } /// I2C error -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Error { /// I2C abort with error @@ -43,6 +43,18 @@ pub enum Error { AddressReserved(u16), } +/// I2C Config error +#[derive(Debug, PartialEq, Eq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum ConfigError { + /// Max i2c speed is 1MHz + FrequencyTooHigh, + /// The sys clock is too slow to support given frequency + ClockTooSlow, + /// The sys clock is too fast to support given frequency + ClockTooFast, +} + /// I2C config. #[non_exhaustive] #[derive(Copy, Clone)] @@ -300,26 +312,30 @@ impl<'d, T: Instance> I2c<'d, T, Async> { } } - /// Read from address into buffer using DMA. - pub async fn read_async(&mut self, addr: u16, buffer: &mut [u8]) -> Result<(), Error> { - Self::setup(addr)?; + /// Read from address into buffer asynchronously. + pub async fn read_async(&mut self, addr: impl Into, buffer: &mut [u8]) -> Result<(), Error> { + Self::setup(addr.into())?; self.read_async_internal(buffer, true, true).await } - /// Write to address from buffer using DMA. - pub async fn write_async(&mut self, addr: u16, bytes: impl IntoIterator) -> Result<(), Error> { - Self::setup(addr)?; + /// Write to address from buffer asynchronously. + pub async fn write_async( + &mut self, + addr: impl Into, + bytes: impl IntoIterator, + ) -> Result<(), Error> { + Self::setup(addr.into())?; self.write_async_internal(bytes, true).await } - /// Write to address from bytes and read from address into buffer using DMA. + /// Write to address from bytes and read from address into buffer asynchronously. pub async fn write_read_async( &mut self, - addr: u16, + addr: impl Into, bytes: impl IntoIterator, buffer: &mut [u8], ) -> Result<(), Error> { - Self::setup(addr)?; + Self::setup(addr.into())?; self.write_async_internal(bytes, false).await?; self.read_async_internal(buffer, true, true).await } @@ -340,13 +356,15 @@ impl interrupt::typelevel::Handler for InterruptHandl } } -pub(crate) fn set_up_i2c_pin<'d, P, T>(pin: &P) +pub(crate) fn set_up_i2c_pin(pin: &P) where P: core::ops::Deref, T: crate::gpio::Pin, { pin.gpio().ctrl().write(|w| w.set_funcsel(3)); pin.pad_ctrl().write(|w| { + #[cfg(feature = "_rp235x")] + w.set_iso(false); w.set_schmitt(true); w.set_slewfast(false); w.set_ie(true); @@ -365,37 +383,32 @@ impl<'d, T: Instance + 'd, M: Mode> I2c<'d, T, M> { ) -> Self { into_ref!(_peri); - assert!(config.frequency <= 1_000_000); - assert!(config.frequency > 0); - - let p = T::regs(); - let reset = T::reset(); crate::reset::reset(reset); crate::reset::unreset_wait(reset); - p.ic_enable().write(|w| w.set_enable(false)); - - // Select controller mode & speed - p.ic_con().modify(|w| { - // Always use "fast" mode (<= 400 kHz, works fine for standard - // mode too) - w.set_speed(i2c::vals::Speed::FAST); - w.set_master_mode(true); - w.set_ic_slave_disable(true); - w.set_ic_restart_en(true); - w.set_tx_empty_ctrl(true); - }); - - // Set FIFO watermarks to 1 to make things simpler. This is encoded - // by a register value of 0. - p.ic_tx_tl().write(|w| w.set_tx_tl(0)); - p.ic_rx_tl().write(|w| w.set_rx_tl(0)); - // Configure SCL & SDA pins set_up_i2c_pin(&scl); set_up_i2c_pin(&sda); + let mut me = Self { phantom: PhantomData }; + + if let Err(e) = me.set_config_inner(&config) { + panic!("Error configuring i2c: {:?}", e); + } + + me + } + + fn set_config_inner(&mut self, config: &Config) -> Result<(), ConfigError> { + if config.frequency > 1_000_000 { + return Err(ConfigError::FrequencyTooHigh); + } + + let p = T::regs(); + + p.ic_enable().write(|w| w.set_enable(false)); + // Configure baudrate // There are some subtleties to I2C timing which we are completely @@ -408,10 +421,12 @@ impl<'d, T: Instance + 'd, M: Mode> I2c<'d, T, M> { let hcnt = period - lcnt; // and 2/5 (40%) of the period high // Check for out-of-range divisors: - assert!(hcnt <= 0xffff); - assert!(lcnt <= 0xffff); - assert!(hcnt >= 8); - assert!(lcnt >= 8); + if hcnt > 0xffff || lcnt > 0xffff { + return Err(ConfigError::ClockTooFast); + } + if hcnt < 8 || lcnt < 8 { + return Err(ConfigError::ClockTooSlow); + } // Per I2C-bus specification a device in standard or fast mode must // internally provide a hold time of at least 300ns for the SDA @@ -424,14 +439,19 @@ impl<'d, T: Instance + 'd, M: Mode> I2c<'d, T, M> { ((clk_base * 3) / 10_000_000) + 1 } else { // fast mode plus requires a clk_base > 32MHz - assert!(clk_base >= 32_000_000); + if clk_base <= 32_000_000 { + return Err(ConfigError::ClockTooSlow); + } // sda_tx_hold_count = clk_base [cycles/s] * 120ns * (1s / // 1e9ns) Reduce 120/1e9 to 3/25e6 to avoid numbers that don't // fit in uint. Add 1 to avoid division truncation. ((clk_base * 3) / 25_000_000) + 1 }; - assert!(sda_tx_hold_count <= lcnt - 2); + + if sda_tx_hold_count > lcnt - 2 { + return Err(ConfigError::ClockTooSlow); + } p.ic_fs_scl_hcnt().write(|w| w.set_ic_fs_scl_hcnt(hcnt as u16)); p.ic_fs_scl_lcnt().write(|w| w.set_ic_fs_scl_lcnt(lcnt as u16)); @@ -440,10 +460,9 @@ impl<'d, T: Instance + 'd, M: Mode> I2c<'d, T, M> { p.ic_sda_hold() .modify(|w| w.set_ic_sda_tx_hold(sda_tx_hold_count as u16)); - // Enable I2C block p.ic_enable().write(|w| w.set_enable(true)); - Self { phantom: PhantomData } + Ok(()) } fn setup(addr: u16) -> Result<(), Error> { @@ -582,20 +601,20 @@ impl<'d, T: Instance + 'd, M: Mode> I2c<'d, T, M> { // ========================= /// Read from address into buffer blocking caller until done. - pub fn blocking_read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Error> { + pub fn blocking_read(&mut self, address: impl Into, read: &mut [u8]) -> Result<(), Error> { Self::setup(address.into())?; self.read_blocking_internal(read, true, true) // Automatic Stop } /// Write to address from buffer blocking caller until done. - pub fn blocking_write(&mut self, address: u8, write: &[u8]) -> Result<(), Error> { + pub fn blocking_write(&mut self, address: impl Into, write: &[u8]) -> Result<(), Error> { Self::setup(address.into())?; self.write_blocking_internal(write, true) } /// Write to address from bytes and read from address into buffer blocking caller until done. - pub fn blocking_write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error> { + pub fn blocking_write_read(&mut self, address: impl Into, write: &[u8], read: &mut [u8]) -> Result<(), Error> { Self::setup(address.into())?; self.write_blocking_internal(write, false)?; self.read_blocking_internal(read, true, true) @@ -706,25 +725,15 @@ where T: Instance + 'd, { async fn read(&mut self, address: A, read: &mut [u8]) -> Result<(), Self::Error> { - let addr: u16 = address.into(); - - Self::setup(addr)?; - self.read_async_internal(read, false, true).await + self.read_async(address, read).await } async fn write(&mut self, address: A, write: &[u8]) -> Result<(), Self::Error> { - let addr: u16 = address.into(); - - Self::setup(addr)?; - self.write_async_internal(write.iter().copied(), true).await + self.write_async(address, write.iter().copied()).await } async fn write_read(&mut self, address: A, write: &[u8], read: &mut [u8]) -> Result<(), Self::Error> { - let addr: u16 = address.into(); - - Self::setup(addr)?; - self.write_async_internal(write.iter().cloned(), false).await?; - self.read_async_internal(read, true, true).await + self.write_read_async(address, write.iter().copied(), read).await } async fn transaction( @@ -736,7 +745,7 @@ where let addr: u16 = address.into(); - if operations.len() > 0 { + if !operations.is_empty() { Self::setup(addr)?; } let mut iterator = operations.iter_mut(); @@ -749,7 +758,7 @@ where self.read_async_internal(buffer, false, last).await?; } Operation::Write(buffer) => { - self.write_async_internal(buffer.into_iter().cloned(), last).await?; + self.write_async_internal(buffer.iter().cloned(), last).await?; } } } @@ -757,39 +766,35 @@ where } } +impl<'d, T: Instance, M: Mode> embassy_embedded_hal::SetConfig for I2c<'d, T, M> { + type Config = Config; + type ConfigError = ConfigError; + + fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> { + self.set_config_inner(config) + } +} + /// Check if address is reserved. pub fn i2c_reserved_addr(addr: u16) -> bool { ((addr & 0x78) == 0 || (addr & 0x78) == 0x78) && addr != 0 } -mod sealed { - use embassy_sync::waitqueue::AtomicWaker; - - use crate::interrupt; - - pub trait Instance { - const TX_DREQ: u8; - const RX_DREQ: u8; - - type Interrupt: interrupt::typelevel::Interrupt; - - fn regs() -> crate::pac::i2c::I2c; - fn reset() -> crate::pac::resets::regs::Peripherals; - fn waker() -> &'static AtomicWaker; - } - - pub trait Mode {} - - pub trait SdaPin {} - pub trait SclPin {} +pub(crate) trait SealedInstance { + fn regs() -> crate::pac::i2c::I2c; + fn reset() -> crate::pac::resets::regs::Peripherals; + fn waker() -> &'static AtomicWaker; } +trait SealedMode {} + /// Driver mode. -pub trait Mode: sealed::Mode {} +#[allow(private_bounds)] +pub trait Mode: SealedMode {} macro_rules! impl_mode { ($name:ident) => { - impl sealed::Mode for $name {} + impl SealedMode for $name {} impl Mode for $name {} }; } @@ -803,16 +808,15 @@ impl_mode!(Blocking); impl_mode!(Async); /// I2C instance. -pub trait Instance: sealed::Instance {} +#[allow(private_bounds)] +pub trait Instance: SealedInstance { + /// Interrupt for this peripheral. + type Interrupt: interrupt::typelevel::Interrupt; +} macro_rules! impl_instance { - ($type:ident, $irq:ident, $reset:ident, $tx_dreq:expr, $rx_dreq:expr) => { - impl sealed::Instance for peripherals::$type { - const TX_DREQ: u8 = $tx_dreq; - const RX_DREQ: u8 = $rx_dreq; - - type Interrupt = crate::interrupt::typelevel::$irq; - + ($type:ident, $irq:ident, $reset:ident) => { + impl SealedInstance for peripherals::$type { #[inline] fn regs() -> pac::i2c::I2c { pac::$type @@ -832,21 +836,22 @@ macro_rules! impl_instance { &WAKER } } - impl Instance for peripherals::$type {} + impl Instance for peripherals::$type { + type Interrupt = crate::interrupt::typelevel::$irq; + } }; } -impl_instance!(I2C0, I2C0_IRQ, set_i2c0, 32, 33); -impl_instance!(I2C1, I2C1_IRQ, set_i2c1, 34, 35); +impl_instance!(I2C0, I2C0_IRQ, set_i2c0); +impl_instance!(I2C1, I2C1_IRQ, set_i2c1); /// SDA pin. -pub trait SdaPin: sealed::SdaPin + crate::gpio::Pin {} +pub trait SdaPin: crate::gpio::Pin {} /// SCL pin. -pub trait SclPin: sealed::SclPin + crate::gpio::Pin {} +pub trait SclPin: crate::gpio::Pin {} macro_rules! impl_pin { ($pin:ident, $instance:ident, $function:ident) => { - impl sealed::$function for peripherals::$pin {} impl $function for peripherals::$pin {} }; } @@ -881,3 +886,39 @@ impl_pin!(PIN_26, I2C1, SdaPin); impl_pin!(PIN_27, I2C1, SclPin); impl_pin!(PIN_28, I2C0, SdaPin); impl_pin!(PIN_29, I2C0, SclPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_30, I2C1, SdaPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_31, I2C1, SclPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_32, I2C0, SdaPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_33, I2C0, SclPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_34, I2C1, SdaPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_35, I2C1, SclPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_36, I2C0, SdaPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_37, I2C0, SclPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_38, I2C1, SdaPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_39, I2C1, SclPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_40, I2C0, SdaPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_41, I2C0, SclPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_42, I2C1, SdaPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_43, I2C1, SclPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_44, I2C0, SdaPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_45, I2C0, SclPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_46, I2C1, SdaPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_47, I2C1, SclPin); diff --git a/embassy-rp/src/i2c_slave.rs b/embassy-rp/src/i2c_slave.rs index 721b7a1f6..c46a55d2e 100644 --- a/embassy-rp/src/i2c_slave.rs +++ b/embassy-rp/src/i2c_slave.rs @@ -13,7 +13,7 @@ use crate::interrupt::typelevel::{Binding, Interrupt}; use crate::{pac, Peripheral}; /// I2C error -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[non_exhaustive] pub enum Error { @@ -21,6 +21,16 @@ pub enum Error { Abort(AbortReason), /// User passed in a response buffer that was 0 length InvalidResponseBufferLength, + /// The response buffer length was too short to contain the message + /// + /// The length parameter will always be the length of the buffer, and is + /// provided as a convenience for matching alongside `Command::Write`. + PartialWrite(usize), + /// The response buffer length was too short to contain the message + /// + /// The length parameter will always be the length of the buffer, and is + /// provided as a convenience for matching alongside `Command::GeneralCall`. + PartialGeneralCall(usize), } /// Received command @@ -56,17 +66,24 @@ pub enum ReadStatus { pub struct Config { /// Target Address pub addr: u16, + /// Control if the peripheral should ack to and report general calls. + pub general_call: bool, } impl Default for Config { fn default() -> Self { - Self { addr: 0x55 } + Self { + addr: 0x55, + general_call: true, + } } } /// I2CSlave driver. pub struct I2cSlave<'d, T: Instance> { phantom: PhantomData<&'d mut T>, + pending_byte: Option, + config: Config, } impl<'d, T: Instance> I2cSlave<'d, T> { @@ -83,6 +100,25 @@ impl<'d, T: Instance> I2cSlave<'d, T> { assert!(!i2c_reserved_addr(config.addr)); assert!(config.addr != 0); + // Configure SCL & SDA pins + set_up_i2c_pin(&scl); + set_up_i2c_pin(&sda); + + let mut ret = Self { + phantom: PhantomData, + pending_byte: None, + config, + }; + + ret.reset(); + + ret + } + + /// Reset the i2c peripheral. If you cancel a respond_to_read, you may stall the bus. + /// You can recover the bus by calling this function, but doing so will almost certainly cause + /// an i/o error in the master. + pub fn reset(&mut self) { let p = T::regs(); let reset = T::reset(); @@ -91,12 +127,24 @@ impl<'d, T: Instance> I2cSlave<'d, T> { p.ic_enable().write(|w| w.set_enable(false)); - p.ic_sar().write(|w| w.set_ic_sar(config.addr)); + p.ic_sar().write(|w| w.set_ic_sar(self.config.addr)); p.ic_con().modify(|w| { w.set_master_mode(false); w.set_ic_slave_disable(false); w.set_tx_empty_ctrl(true); + w.set_rx_fifo_full_hld_ctrl(true); + + // This typically makes no sense for a slave, but it is used to + // tune spike suppression, according to the datasheet. + w.set_speed(pac::i2c::vals::Speed::FAST); + + // Generate stop interrupts for general calls + // This also causes stop interrupts for other devices on the bus but those will not be + // propagated up to the application. + w.set_stop_det_ifaddressed(!self.config.general_call); }); + p.ic_ack_general_call() + .write(|w| w.set_ack_gen_call(self.config.general_call)); // Set FIFO watermarks to 1 to make things simpler. This is encoded // by a register value of 0. Rx watermark should never change, but Tx watermark will be @@ -104,10 +152,6 @@ impl<'d, T: Instance> I2cSlave<'d, T> { p.ic_tx_tl().write(|w| w.set_tx_tl(0)); p.ic_rx_tl().write(|w| w.set_rx_tl(0)); - // Configure SCL & SDA pins - set_up_i2c_pin(&scl); - set_up_i2c_pin(&sda); - // Clear interrupts p.ic_clr_intr().read(); @@ -118,8 +162,6 @@ impl<'d, T: Instance> I2cSlave<'d, T> { p.ic_intr_mask().write_value(i2c::regs::IcIntrMask(0)); T::Interrupt::unpend(); unsafe { T::Interrupt::enable() }; - - Self { phantom: PhantomData } } /// Calls `f` to check if we are ready or not. @@ -133,8 +175,6 @@ impl<'d, T: Instance> I2cSlave<'d, T> { future::poll_fn(|cx| { let r = f(self); - trace!("intr p: {:013b}", T::regs().ic_raw_intr_stat().read().0); - if r.is_pending() { T::waker().register(cx.waker()); g(self); @@ -146,131 +186,168 @@ impl<'d, T: Instance> I2cSlave<'d, T> { } #[inline(always)] - fn drain_fifo(&mut self, buffer: &mut [u8], offset: usize) -> usize { + fn drain_fifo(&mut self, buffer: &mut [u8], offset: &mut usize) { let p = T::regs(); - let len = p.ic_rxflr().read().rxflr() as usize; - let end = offset + len; - for i in offset..end { - buffer[i] = p.ic_data_cmd().read().dat(); - } - end - } - #[inline(always)] - fn write_to_fifo(&mut self, buffer: &[u8]) { - let p = T::regs(); - for byte in buffer { - p.ic_data_cmd().write(|w| w.set_dat(*byte)); + if let Some(pending) = self.pending_byte.take() { + buffer[*offset] = pending; + *offset += 1; + } + + for b in &mut buffer[*offset..] { + if !p.ic_status().read().rfne() { + break; + } + + let dat = p.ic_data_cmd().read(); + if *offset != 0 && dat.first_data_byte() { + // The RP2040 state machine will keep placing bytes into the + // FIFO, even if they are part of a subsequent write transaction. + // + // Unfortunately merely reading ic_data_cmd will consume that + // byte, the first byte of the next transaction, so we need + // to store it elsewhere + self.pending_byte = Some(dat.dat()); + break; + } + + *b = dat.dat(); + *offset += 1; } } /// Wait asynchronously for commands from an I2C master. - /// `buffer` is provided in case master does a 'write' and is unused for 'read'. + /// `buffer` is provided in case master does a 'write', 'write read', or 'general call' and is unused for 'read'. pub async fn listen(&mut self, buffer: &mut [u8]) -> Result { let p = T::regs(); - p.ic_clr_intr().read(); // set rx fifo watermark to 1 byte p.ic_rx_tl().write(|w| w.set_rx_tl(0)); let mut len = 0; - let ret = self - .wait_on( - |me| { - let stat = p.ic_raw_intr_stat().read(); - if p.ic_rxflr().read().rxflr() > 0 { - len = me.drain_fifo(buffer, len); - // we're recieving data, set rx fifo watermark to 12 bytes to reduce interrupt noise - p.ic_rx_tl().write(|w| w.set_rx_tl(11)); - } + self.wait_on( + |me| { + let stat = p.ic_raw_intr_stat().read(); + trace!("ls:{:013b} len:{}", stat.0, len); - if stat.restart_det() && stat.rd_req() { - Poll::Ready(Ok(Command::WriteRead(len))) - } else if stat.gen_call() && stat.stop_det() && len > 0 { - Poll::Ready(Ok(Command::GeneralCall(len))) - } else if stat.stop_det() { - Poll::Ready(Ok(Command::Write(len))) - } else if stat.rd_req() { - Poll::Ready(Ok(Command::Read)) + if p.ic_rxflr().read().rxflr() > 0 || me.pending_byte.is_some() { + me.drain_fifo(buffer, &mut len); + // we're recieving data, set rx fifo watermark to 12 bytes (3/4 full) to reduce interrupt noise + p.ic_rx_tl().write(|w| w.set_rx_tl(11)); + } + + if buffer.len() == len { + if stat.gen_call() { + return Poll::Ready(Err(Error::PartialGeneralCall(buffer.len()))); } else { - Poll::Pending + return Poll::Ready(Err(Error::PartialWrite(buffer.len()))); } - }, - |_me| { - p.ic_intr_mask().modify(|w| { - w.set_m_stop_det(true); - w.set_m_restart_det(true); - w.set_m_gen_call(true); - w.set_m_rd_req(true); - w.set_m_rx_full(true); - }); - }, - ) - .await; + } + trace!("len:{}, pend:{:?}", len, me.pending_byte); + if me.pending_byte.is_some() { + warn!("pending") + } - p.ic_clr_intr().read(); - - ret + if stat.restart_det() && stat.rd_req() { + p.ic_clr_restart_det().read(); + Poll::Ready(Ok(Command::WriteRead(len))) + } else if stat.gen_call() && stat.stop_det() && len > 0 { + p.ic_clr_gen_call().read(); + p.ic_clr_stop_det().read(); + Poll::Ready(Ok(Command::GeneralCall(len))) + } else if stat.stop_det() && len > 0 { + p.ic_clr_stop_det().read(); + Poll::Ready(Ok(Command::Write(len))) + } else if stat.rd_req() { + p.ic_clr_stop_det().read(); + p.ic_clr_restart_det().read(); + p.ic_clr_gen_call().read(); + Poll::Ready(Ok(Command::Read)) + } else if stat.stop_det() { + // clear stuck stop bit + // This can happen if the SDA/SCL pullups are enabled after calling this func + p.ic_clr_stop_det().read(); + Poll::Pending + } else { + Poll::Pending + } + }, + |_me| { + p.ic_intr_mask().write(|w| { + w.set_m_stop_det(true); + w.set_m_restart_det(true); + w.set_m_gen_call(true); + w.set_m_rd_req(true); + w.set_m_rx_full(true); + }); + }, + ) + .await } /// Respond to an I2C master READ command, asynchronously. pub async fn respond_to_read(&mut self, buffer: &[u8]) -> Result { let p = T::regs(); - if buffer.len() == 0 { + if buffer.is_empty() { return Err(Error::InvalidResponseBufferLength); } let mut chunks = buffer.chunks(FIFO_SIZE as usize); - let ret = self - .wait_on( - |me| { + self.wait_on( + |me| { + let stat = p.ic_raw_intr_stat().read(); + trace!("rs:{:013b}", stat.0); + + if stat.tx_abrt() { if let Err(abort_reason) = me.read_and_clear_abort_reason() { if let Error::Abort(AbortReason::TxNotEmpty(bytes)) = abort_reason { + p.ic_clr_intr().read(); return Poll::Ready(Ok(ReadStatus::LeftoverBytes(bytes))); } else { return Poll::Ready(Err(abort_reason)); } } + } - if let Some(chunk) = chunks.next() { - me.write_to_fifo(chunk); - - Poll::Pending - } else { - let stat = p.ic_raw_intr_stat().read(); - - if stat.rx_done() && stat.stop_det() { - Poll::Ready(Ok(ReadStatus::Done)) - } else if stat.rd_req() { - Poll::Ready(Ok(ReadStatus::NeedMoreBytes)) - } else { - Poll::Pending - } + if let Some(chunk) = chunks.next() { + for byte in chunk { + p.ic_clr_rd_req().read(); + p.ic_data_cmd().write(|w| w.set_dat(*byte)); } - }, - |_me| { - p.ic_intr_mask().modify(|w| { - w.set_m_stop_det(true); - w.set_m_rx_done(true); - w.set_m_tx_empty(true); - w.set_m_tx_abrt(true); - }) - }, - ) - .await; - p.ic_clr_intr().read(); - - ret + Poll::Pending + } else if stat.rx_done() { + p.ic_clr_rx_done().read(); + Poll::Ready(Ok(ReadStatus::Done)) + } else if stat.rd_req() && stat.tx_empty() { + Poll::Ready(Ok(ReadStatus::NeedMoreBytes)) + } else { + Poll::Pending + } + }, + |_me| { + p.ic_intr_mask().write(|w| { + w.set_m_rx_done(true); + w.set_m_tx_empty(true); + w.set_m_tx_abrt(true); + }) + }, + ) + .await } /// Respond to reads with the fill byte until the controller stops asking pub async fn respond_till_stop(&mut self, fill: u8) -> Result<(), Error> { + // Send fill bytes a full fifo at a time, to reduce interrupt noise. + // This does mean we'll almost certainly abort the write, but since these are fill bytes, + // we don't care. + let buff = [fill; FIFO_SIZE as usize]; loop { - match self.respond_to_read(&[fill]).await { + match self.respond_to_read(&buff).await { Ok(ReadStatus::NeedMoreBytes) => (), + Ok(ReadStatus::LeftoverBytes(_)) => break Ok(()), Ok(_) => break Ok(()), Err(e) => break Err(e), } @@ -292,14 +369,7 @@ impl<'d, T: Instance> I2cSlave<'d, T> { #[inline(always)] fn read_and_clear_abort_reason(&mut self) -> Result<(), Error> { let p = T::regs(); - let mut abort_reason = p.ic_tx_abrt_source().read(); - - // Mask off fifo flush count - let tx_flush_cnt = abort_reason.tx_flush_cnt(); - abort_reason.set_tx_flush_cnt(0); - - // Mask off master_dis - abort_reason.set_abrt_master_dis(false); + let abort_reason = p.ic_tx_abrt_source().read(); if abort_reason.0 != 0 { // Note clearing the abort flag also clears the reason, and this @@ -314,8 +384,8 @@ impl<'d, T: Instance> I2cSlave<'d, T> { AbortReason::NoAcknowledge } else if abort_reason.arb_lost() { AbortReason::ArbitrationLoss - } else if abort_reason.abrt_slvflush_txfifo() { - AbortReason::TxNotEmpty(tx_flush_cnt) + } else if abort_reason.tx_flush_cnt() > 0 { + AbortReason::TxNotEmpty(abort_reason.tx_flush_cnt()) } else { AbortReason::Other(abort_reason.0) }; diff --git a/embassy-rp/src/lib.rs b/embassy-rp/src/lib.rs index 46973fdc8..f0893b5a0 100644 --- a/embassy-rp/src/lib.rs +++ b/embassy-rp/src/lib.rs @@ -9,28 +9,42 @@ // This mod MUST go first, so that the others see its macros. pub(crate) mod fmt; +#[cfg(feature = "binary-info")] +pub use rp_binary_info as binary_info; + #[cfg(feature = "critical-section-impl")] mod critical_section_impl; +#[cfg(feature = "rp2040")] mod intrinsics; pub mod adc; +#[cfg(feature = "_rp235x")] +pub mod block; +#[cfg(feature = "rp2040")] pub mod bootsel; pub mod clocks; pub mod dma; pub mod flash; +#[cfg(feature = "rp2040")] mod float; pub mod gpio; pub mod i2c; pub mod i2c_slave; pub mod multicore; +#[cfg(feature = "_rp235x")] +pub mod otp; +pub mod pio_programs; pub mod pwm; mod reset; pub mod rom_data; +#[cfg(feature = "rp2040")] pub mod rtc; pub mod spi; #[cfg(feature = "time-driver")] pub mod time_driver; +#[cfg(feature = "_rp235x")] +pub mod trng; pub mod uart; pub mod usb; pub mod watchdog; @@ -49,6 +63,7 @@ pub(crate) use rp_pac as pac; #[cfg(feature = "rt")] pub use crate::pac::NVIC_PRIO_BITS; +#[cfg(feature = "rp2040")] embassy_hal_internal::interrupt_mod!( TIMER_IRQ_0, TIMER_IRQ_1, @@ -84,6 +99,54 @@ embassy_hal_internal::interrupt_mod!( SWI_IRQ_5, ); +#[cfg(feature = "_rp235x")] +embassy_hal_internal::interrupt_mod!( + TIMER0_IRQ_0, + TIMER0_IRQ_1, + TIMER0_IRQ_2, + TIMER0_IRQ_3, + TIMER1_IRQ_0, + TIMER1_IRQ_1, + TIMER1_IRQ_2, + TIMER1_IRQ_3, + PWM_IRQ_WRAP_0, + PWM_IRQ_WRAP_1, + DMA_IRQ_0, + DMA_IRQ_1, + USBCTRL_IRQ, + PIO0_IRQ_0, + PIO0_IRQ_1, + PIO1_IRQ_0, + PIO1_IRQ_1, + PIO2_IRQ_0, + PIO2_IRQ_1, + IO_IRQ_BANK0, + IO_IRQ_BANK0_NS, + IO_IRQ_QSPI, + IO_IRQ_QSPI_NS, + SIO_IRQ_FIFO, + SIO_IRQ_BELL, + SIO_IRQ_FIFO_NS, + SIO_IRQ_BELL_NS, + CLOCKS_IRQ, + SPI0_IRQ, + SPI1_IRQ, + UART0_IRQ, + UART1_IRQ, + ADC_IRQ_FIFO, + I2C0_IRQ, + I2C1_IRQ, + TRNG_IRQ, + PLL_SYS_IRQ, + PLL_USB_IRQ, + SWI_IRQ_0, + SWI_IRQ_1, + SWI_IRQ_2, + SWI_IRQ_3, + SWI_IRQ_4, + SWI_IRQ_5, +); + /// Macro to bind interrupts to handlers. /// /// This defines the right interrupt handlers, and creates a unit struct (like `struct Irqs;`) @@ -103,26 +166,45 @@ embassy_hal_internal::interrupt_mod!( // developer note: this macro can't be in `embassy-hal-internal` due to the use of `$crate`. #[macro_export] macro_rules! bind_interrupts { - ($vis:vis struct $name:ident { $($irq:ident => $($handler:ty),*;)* }) => { - #[derive(Copy, Clone)] - $vis struct $name; + ($vis:vis struct $name:ident { + $( + $(#[cfg($cond_irq:meta)])? + $irq:ident => $( + $(#[cfg($cond_handler:meta)])? + $handler:ty + ),*; + )* + }) => { + #[derive(Copy, Clone)] + $vis struct $name; $( #[allow(non_snake_case)] #[no_mangle] + $(#[cfg($cond_irq)])? unsafe extern "C" fn $irq() { $( + $(#[cfg($cond_handler)])? <$handler as $crate::interrupt::typelevel::Handler<$crate::interrupt::typelevel::$irq>>::on_interrupt(); + )* } - $( - unsafe impl $crate::interrupt::typelevel::Binding<$crate::interrupt::typelevel::$irq, $handler> for $name {} - )* + $(#[cfg($cond_irq)])? + $crate::bind_interrupts!(@inner + $( + $(#[cfg($cond_handler)])? + unsafe impl $crate::interrupt::typelevel::Binding<$crate::interrupt::typelevel::$irq, $handler> for $name {} + )* + ); )* }; + (@inner $($t:tt)*) => { + $($t)* + } } +#[cfg(feature = "rp2040")] embassy_hal_internal::peripherals! { PIN_0, PIN_1, @@ -183,14 +265,14 @@ embassy_hal_internal::peripherals! { DMA_CH10, DMA_CH11, - PWM_CH0, - PWM_CH1, - PWM_CH2, - PWM_CH3, - PWM_CH4, - PWM_CH5, - PWM_CH6, - PWM_CH7, + PWM_SLICE0, + PWM_SLICE1, + PWM_SLICE2, + PWM_SLICE3, + PWM_SLICE4, + PWM_SLICE5, + PWM_SLICE6, + PWM_SLICE7, USB, @@ -210,6 +292,142 @@ embassy_hal_internal::peripherals! { BOOTSEL, } +#[cfg(feature = "_rp235x")] +embassy_hal_internal::peripherals! { + PIN_0, + PIN_1, + PIN_2, + PIN_3, + PIN_4, + PIN_5, + PIN_6, + PIN_7, + PIN_8, + PIN_9, + PIN_10, + PIN_11, + PIN_12, + PIN_13, + PIN_14, + PIN_15, + PIN_16, + PIN_17, + PIN_18, + PIN_19, + PIN_20, + PIN_21, + PIN_22, + PIN_23, + PIN_24, + PIN_25, + PIN_26, + PIN_27, + PIN_28, + PIN_29, + #[cfg(feature = "rp235xb")] + PIN_30, + #[cfg(feature = "rp235xb")] + PIN_31, + #[cfg(feature = "rp235xb")] + PIN_32, + #[cfg(feature = "rp235xb")] + PIN_33, + #[cfg(feature = "rp235xb")] + PIN_34, + #[cfg(feature = "rp235xb")] + PIN_35, + #[cfg(feature = "rp235xb")] + PIN_36, + #[cfg(feature = "rp235xb")] + PIN_37, + #[cfg(feature = "rp235xb")] + PIN_38, + #[cfg(feature = "rp235xb")] + PIN_39, + #[cfg(feature = "rp235xb")] + PIN_40, + #[cfg(feature = "rp235xb")] + PIN_41, + #[cfg(feature = "rp235xb")] + PIN_42, + #[cfg(feature = "rp235xb")] + PIN_43, + #[cfg(feature = "rp235xb")] + PIN_44, + #[cfg(feature = "rp235xb")] + PIN_45, + #[cfg(feature = "rp235xb")] + PIN_46, + #[cfg(feature = "rp235xb")] + PIN_47, + PIN_QSPI_SCLK, + PIN_QSPI_SS, + PIN_QSPI_SD0, + PIN_QSPI_SD1, + PIN_QSPI_SD2, + PIN_QSPI_SD3, + + UART0, + UART1, + + SPI0, + SPI1, + + I2C0, + I2C1, + + DMA_CH0, + DMA_CH1, + DMA_CH2, + DMA_CH3, + DMA_CH4, + DMA_CH5, + DMA_CH6, + DMA_CH7, + DMA_CH8, + DMA_CH9, + DMA_CH10, + DMA_CH11, + DMA_CH12, + DMA_CH13, + DMA_CH14, + DMA_CH15, + + PWM_SLICE0, + PWM_SLICE1, + PWM_SLICE2, + PWM_SLICE3, + PWM_SLICE4, + PWM_SLICE5, + PWM_SLICE6, + PWM_SLICE7, + PWM_SLICE8, + PWM_SLICE9, + PWM_SLICE10, + PWM_SLICE11, + + USB, + + RTC, + + FLASH, + + ADC, + ADC_TEMP_SENSOR, + + CORE1, + + PIO0, + PIO1, + PIO2, + + WATCHDOG, + BOOTSEL, + + TRNG +} + +#[cfg(all(not(feature = "boot2-none"), feature = "rp2040"))] macro_rules! select_bootloader { ( $( $feature:literal => $loader:ident, )+ default => $default:ident ) => { $( @@ -226,6 +444,7 @@ macro_rules! select_bootloader { } } +#[cfg(all(not(feature = "boot2-none"), feature = "rp2040"))] select_bootloader! { "boot2-at25sf128a" => BOOT_LOADER_AT25SF128A, "boot2-gd25q64cs" => BOOT_LOADER_GD25Q64CS, @@ -238,8 +457,8 @@ select_bootloader! { } /// Installs a stack guard for the CORE0 stack in MPU region 0. -/// Will fail if the MPU is already confgigured. This function requires -/// a `_stack_end` symbol to be defined by the linker script, and expexcts +/// Will fail if the MPU is already configured. This function requires +/// a `_stack_end` symbol to be defined by the linker script, and expects /// `_stack_end` to be located at the lowest address (largest depth) of /// the stack. /// @@ -274,11 +493,12 @@ pub fn install_core0_stack_guard() -> Result<(), ()> { extern "C" { static mut _stack_end: usize; } - unsafe { install_stack_guard(&mut _stack_end as *mut usize) } + unsafe { install_stack_guard(core::ptr::addr_of_mut!(_stack_end)) } } +#[cfg(all(feature = "rp2040", not(feature = "_test")))] #[inline(always)] -fn install_stack_guard(stack_bottom: *mut usize) -> Result<(), ()> { +unsafe fn install_stack_guard(stack_bottom: *mut usize) -> Result<(), ()> { let core = unsafe { cortex_m::Peripherals::steal() }; // Fail if MPU is already configured @@ -304,6 +524,32 @@ fn install_stack_guard(stack_bottom: *mut usize) -> Result<(), ()> { Ok(()) } +#[cfg(all(feature = "_rp235x", not(feature = "_test")))] +#[inline(always)] +unsafe fn install_stack_guard(stack_bottom: *mut usize) -> Result<(), ()> { + let core = unsafe { cortex_m::Peripherals::steal() }; + + // Fail if MPU is already configured + if core.MPU.ctrl.read() != 0 { + return Err(()); + } + + unsafe { + core.MPU.ctrl.write(5); // enable mpu with background default map + core.MPU.rbar.write(stack_bottom as u32 & !0xff); // set address + core.MPU.rlar.write(1); // enable region + } + Ok(()) +} + +// This is to hack around cortex_m defaulting to ARMv7 when building tests, +// so the compile fails when we try to use ARMv8 peripherals. +#[cfg(feature = "_test")] +#[inline(always)] +unsafe fn install_stack_guard(_stack_bottom: *mut usize) -> Result<(), ()> { + Ok(()) +} + /// HAL configuration for RP. pub mod config { use crate::clocks::ClockConfig; @@ -352,11 +598,60 @@ pub fn init(config: config::Config) -> Peripherals { peripherals } +#[cfg(all(feature = "rt", feature = "rp2040"))] +#[cortex_m_rt::pre_init] +unsafe fn pre_init() { + // SIO does not get reset when core0 is reset with either `scb::sys_reset()` or with SWD. + // Since we're using SIO spinlock 31 for the critical-section impl, this causes random + // hangs if we reset in the middle of a CS, because the next boot sees the spinlock + // as locked and waits forever. + // + // See https://github.com/embassy-rs/embassy/issues/1736 + // and https://github.com/rp-rs/rp-hal/issues/292 + // and https://matrix.to/#/!vhKMWjizPZBgKeknOo:matrix.org/$VfOkQgyf1PjmaXZbtycFzrCje1RorAXd8BQFHTl4d5M + // + // According to Raspberry Pi, this is considered Working As Intended, and not an errata, + // even though this behavior is different from every other ARM chip (sys_reset usually resets + // the *system* as its name implies, not just the current core). + // + // To fix this, reset SIO on boot. We must do this in pre_init because it's unsound to do it + // in `embassy_rp::init`, since the user could've acquired a CS by then. pre_init is guaranteed + // to run before any user code. + // + // A similar thing could happen with PROC1. It is unclear whether it's possible for PROC1 + // to stay unreset through a PROC0 reset, so we reset it anyway just in case. + // + // Important info from PSM logic (from Luke Wren in above Matrix thread) + // + // The logic is, each PSM stage is reset if either of the following is true: + // - The previous stage is in reset and FRCE_ON is false + // - FRCE_OFF is true + // + // The PSM order is SIO -> PROC0 -> PROC1. + // So, we have to force-on PROC0 to prevent it from getting reset when resetting SIO. + pac::PSM.frce_on().write_and_wait(|w| { + w.set_proc0(true); + }); + // Then reset SIO and PROC1. + pac::PSM.frce_off().write_and_wait(|w| { + w.set_sio(true); + w.set_proc1(true); + }); + // clear force_off first, force_on second. The other way around would reset PROC0. + pac::PSM.frce_off().write_and_wait(|_| {}); + pac::PSM.frce_on().write_and_wait(|_| {}); +} + /// Extension trait for PAC regs, adding atomic xor/bitset/bitclear writes. +#[allow(unused)] trait RegExt { + #[allow(unused)] fn write_xor(&self, f: impl FnOnce(&mut T) -> R) -> R; fn write_set(&self, f: impl FnOnce(&mut T) -> R) -> R; fn write_clear(&self, f: impl FnOnce(&mut T) -> R) -> R; + fn write_and_wait(&self, f: impl FnOnce(&mut T) -> R) -> R + where + T: PartialEq; } impl RegExt for pac::common::Reg { @@ -389,4 +684,17 @@ impl RegExt for pac::common::Reg(&self, f: impl FnOnce(&mut T) -> R) -> R + where + T: PartialEq, + { + let mut val = Default::default(); + let res = f(&mut val); + unsafe { + self.as_ptr().write_volatile(val); + while self.as_ptr().read_volatile() != val {} + } + res + } } diff --git a/embassy-rp/src/multicore.rs b/embassy-rp/src/multicore.rs index 252f30dc1..ea0a29a36 100644 --- a/embassy-rp/src/multicore.rs +++ b/embassy-rp/src/multicore.rs @@ -58,8 +58,8 @@ const RESUME_TOKEN: u32 = !0xDEADBEEF; static IS_CORE1_INIT: AtomicBool = AtomicBool::new(false); #[inline(always)] -fn core1_setup(stack_bottom: *mut usize) { - if let Err(_) = install_stack_guard(stack_bottom) { +unsafe fn core1_setup(stack_bottom: *mut usize) { + if install_stack_guard(stack_bottom).is_err() { // currently only happens if the MPU was already set up, which // would indicate that the core is already in use from outside // embassy, somehow. trap if so since we can't deal with that. @@ -84,7 +84,7 @@ impl Stack { } } -#[cfg(feature = "rt")] +#[cfg(all(feature = "rt", feature = "rp2040"))] #[interrupt] #[link_section = ".data.ram_func"] unsafe fn SIO_IRQ_PROC1() { @@ -109,6 +109,31 @@ unsafe fn SIO_IRQ_PROC1() { } } +#[cfg(all(feature = "rt", feature = "_rp235x"))] +#[interrupt] +#[link_section = ".data.ram_func"] +unsafe fn SIO_IRQ_FIFO() { + let sio = pac::SIO; + // Clear IRQ + sio.fifo().st().write(|w| w.set_wof(false)); + + while sio.fifo().st().read().vld() { + // Pause CORE1 execution and disable interrupts + if fifo_read_wfe() == PAUSE_TOKEN { + cortex_m::interrupt::disable(); + // Signal to CORE0 that execution is paused + fifo_write(PAUSE_TOKEN); + // Wait for `resume` signal from CORE0 + while fifo_read_wfe() != RESUME_TOKEN { + cortex_m::asm::nop(); + } + cortex_m::interrupt::enable(); + // Signal to CORE0 that execution is resumed + fifo_write(RESUME_TOKEN); + } + } +} + /// Spawn a function on this core pub fn spawn_core1(_core1: CORE1, stack: &'static mut Stack, entry: F) where @@ -123,7 +148,7 @@ where entry: *mut ManuallyDrop, stack_bottom: *mut usize, ) -> ! { - core1_setup(stack_bottom); + unsafe { core1_setup(stack_bottom) }; let entry = unsafe { ManuallyDrop::take(&mut *entry) }; @@ -135,7 +160,21 @@ where IS_CORE1_INIT.store(true, Ordering::Release); // Enable fifo interrupt on CORE1 for `pause` functionality. - unsafe { interrupt::SIO_IRQ_PROC1.enable() }; + #[cfg(feature = "rp2040")] + unsafe { + interrupt::SIO_IRQ_PROC1.enable() + }; + #[cfg(feature = "_rp235x")] + unsafe { + interrupt::SIO_IRQ_FIFO.enable() + }; + + // Enable FPU + #[cfg(all(feature = "_rp235x", has_fpu))] + unsafe { + let p = cortex_m::Peripherals::steal(); + p.SCB.cpacr.modify(|cpacr| cpacr | (3 << 20) | (3 << 22)); + } entry() } diff --git a/embassy-rp/src/otp.rs b/embassy-rp/src/otp.rs new file mode 100644 index 000000000..cdaf5bded --- /dev/null +++ b/embassy-rp/src/otp.rs @@ -0,0 +1,108 @@ +//! Interface to the RP2350's One Time Programmable Memory + +// Credit: taken from `rp-hal` (also licensed Apache+MIT) +// https://github.com/rp-rs/rp-hal/blob/main/rp235x-hal/src/rom_data.rs + +/// The ways in which we can fail to read OTP +#[derive(Debug, Clone)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Error { + /// The user passed an invalid index to a function. + InvalidIndex, + /// The hardware refused to let us read this word, probably due to + /// read lock set earlier in the boot process. + InvalidPermissions, +} + +/// OTP read address, using automatic Error Correction. +/// +/// A 32-bit read returns the ECC-corrected data for two neighbouring rows, or +/// all-ones on permission failure. Only the first 8 KiB is populated. +pub const OTP_DATA_BASE: *const u32 = 0x4013_0000 as *const u32; + +/// OTP read address, without using any automatic Error Correction. +/// +/// A 32-bit read returns 24-bits of raw data from the OTP word. +pub const OTP_DATA_RAW_BASE: *const u32 = 0x4013_4000 as *const u32; + +/// How many pages in OTP (post error-correction) +pub const NUM_PAGES: usize = 64; + +/// How many rows in one page in OTP (post error-correction) +pub const NUM_ROWS_PER_PAGE: usize = 64; + +/// How many rows in OTP (post error-correction) +pub const NUM_ROWS: usize = NUM_PAGES * NUM_ROWS_PER_PAGE; + +/// Read one ECC protected word from the OTP +pub fn read_ecc_word(row: usize) -> Result { + if row >= NUM_ROWS { + return Err(Error::InvalidIndex); + } + // First do a raw read to check permissions + let _ = read_raw_word(row)?; + // One 32-bit read gets us two rows + let offset = row >> 1; + // # Safety + // + // We checked this offset was in range already. + let value = unsafe { OTP_DATA_BASE.add(offset).read() }; + if (row & 1) == 0 { + Ok(value as u16) + } else { + Ok((value >> 16) as u16) + } +} + +/// Read one raw word from the OTP +/// +/// You get the 24-bit raw value in the lower part of the 32-bit result. +pub fn read_raw_word(row: usize) -> Result { + if row >= NUM_ROWS { + return Err(Error::InvalidIndex); + } + // One 32-bit read gets us one row + // # Safety + // + // We checked this offset was in range already. + let value = unsafe { OTP_DATA_RAW_BASE.add(row).read() }; + if value == 0xFFFF_FFFF { + Err(Error::InvalidPermissions) + } else { + Ok(value) + } +} + +/// Get the random 64bit chipid from rows 0x0-0x3. +pub fn get_chipid() -> Result { + let w0 = read_ecc_word(0x000)?.to_be_bytes(); + let w1 = read_ecc_word(0x001)?.to_be_bytes(); + let w2 = read_ecc_word(0x002)?.to_be_bytes(); + let w3 = read_ecc_word(0x003)?.to_be_bytes(); + + Ok(u64::from_be_bytes([ + w3[0], w3[1], w2[0], w2[1], w1[0], w1[1], w0[0], w0[1], + ])) +} + +/// Get the 128bit private random number from rows 0x4-0xb. +/// +/// This ID is not exposed through the USB PICOBOOT GET_INFO command +/// or the ROM get_sys_info() API. However note that the USB PICOBOOT OTP +/// access point can read the entirety of page 0, so this value is not +/// meaningfully private unless the USB PICOBOOT interface is disabled via the +//// DISABLE_BOOTSEL_USB_PICOBOOT_IFC flag in BOOT_FLAGS0 +pub fn get_private_random_number() -> Result { + let w0 = read_ecc_word(0x004)?.to_be_bytes(); + let w1 = read_ecc_word(0x005)?.to_be_bytes(); + let w2 = read_ecc_word(0x006)?.to_be_bytes(); + let w3 = read_ecc_word(0x007)?.to_be_bytes(); + let w4 = read_ecc_word(0x008)?.to_be_bytes(); + let w5 = read_ecc_word(0x009)?.to_be_bytes(); + let w6 = read_ecc_word(0x00a)?.to_be_bytes(); + let w7 = read_ecc_word(0x00b)?.to_be_bytes(); + + Ok(u128::from_be_bytes([ + w7[0], w7[1], w6[0], w6[1], w5[0], w5[1], w4[0], w4[1], w3[0], w3[1], w2[0], w2[1], w1[0], w1[1], w0[0], w0[1], + ])) +} diff --git a/embassy-rp/src/pio/mod.rs b/embassy-rp/src/pio/mod.rs index ca9795024..98f4f8943 100644 --- a/embassy-rp/src/pio/mod.rs +++ b/embassy-rp/src/pio/mod.rs @@ -5,20 +5,16 @@ use core::pin::Pin as FuturePin; use core::sync::atomic::{compiler_fence, Ordering}; use core::task::{Context, Poll}; -use atomic_polyfill::{AtomicU32, AtomicU8}; +use atomic_polyfill::{AtomicU64, AtomicU8}; use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef}; use embassy_sync::waitqueue::AtomicWaker; use fixed::types::extra::U8; use fixed::FixedU32; -use pac::io::vals::Gpio0ctrlFuncsel; -use pac::pio::vals::SmExecctrlStatusSel; use pio::{Program, SideSet, Wrap}; use crate::dma::{Channel, Transfer, Word}; -use crate::gpio::sealed::Pin as SealedPin; -use crate::gpio::{self, AnyPin, Drive, Level, Pull, SlewRate}; +use crate::gpio::{self, AnyPin, Drive, Level, Pull, SealedPin, SlewRate}; use crate::interrupt::typelevel::{Binding, Handler, Interrupt}; -use crate::pac::dma::vals::TreqSel; use crate::relocate::RelocatedProgram; use crate::{pac, peripherals, RegExt}; @@ -268,7 +264,7 @@ impl<'l, PIO: Instance> Pin<'l, PIO> { } /// Set the pin's input sync bypass. - pub fn set_input_sync_bypass<'a>(&mut self, bypass: bool) { + pub fn set_input_sync_bypass(&mut self, bypass: bool) { let mask = 1 << self.pin(); if bypass { PIO::PIO.input_sync_bypass().write_set(|w| *w = mask); @@ -325,6 +321,10 @@ impl<'d, PIO: Instance, const SM: usize> StateMachineRx<'d, PIO, SM> { } /// Pull data from RX FIFO. + /// + /// This function doesn't check if there is data available to be read. + /// If the rx FIFO is empty, an undefined value is returned. If you only + /// want to pull if data is available, use `try_pull` instead. pub fn pull(&mut self) -> u32 { PIO::PIO.rxf(SM).read() } @@ -352,11 +352,14 @@ impl<'d, PIO: Instance, const SM: usize> StateMachineRx<'d, PIO, SM> { let p = ch.regs(); p.write_addr().write_value(data.as_ptr() as u32); p.read_addr().write_value(PIO::PIO.rxf(SM).as_ptr() as u32); - p.trans_count().write_value(data.len() as u32); + #[cfg(feature = "rp2040")] + p.trans_count().write(|w| *w = data.len() as u32); + #[cfg(feature = "_rp235x")] + p.trans_count().write(|w| w.set_count(data.len() as u32)); compiler_fence(Ordering::SeqCst); p.ctrl_trig().write(|w| { // Set RX DREQ for this statemachine - w.set_treq_sel(TreqSel(pio_no * 8 + SM as u8 + 4)); + w.set_treq_sel(crate::pac::dma::vals::TreqSel::from(pio_no * 8 + SM as u8 + 4)); w.set_data_size(W::size()); w.set_chain_to(ch.number()); w.set_incr_read(false); @@ -434,11 +437,14 @@ impl<'d, PIO: Instance, const SM: usize> StateMachineTx<'d, PIO, SM> { let p = ch.regs(); p.read_addr().write_value(data.as_ptr() as u32); p.write_addr().write_value(PIO::PIO.txf(SM).as_ptr() as u32); - p.trans_count().write_value(data.len() as u32); + #[cfg(feature = "rp2040")] + p.trans_count().write(|w| *w = data.len() as u32); + #[cfg(feature = "_rp235x")] + p.trans_count().write(|w| w.set_count(data.len() as u32)); compiler_fence(Ordering::SeqCst); p.ctrl_trig().write(|w| { // Set TX DREQ for this statemachine - w.set_treq_sel(TreqSel(pio_no * 8 + SM as u8)); + w.set_treq_sel(crate::pac::dma::vals::TreqSel::from(pio_no * 8 + SM as u8)); w.set_data_size(W::size()); w.set_chain_to(ch.number()); w.set_incr_read(true); @@ -463,7 +469,7 @@ impl<'d, PIO: Instance, const SM: usize> Drop for StateMachine<'d, PIO, SM> { } } -fn assert_consecutive<'d, PIO: Instance>(pins: &[&Pin<'d, PIO>]) { +fn assert_consecutive(pins: &[&Pin]) { for (p1, p2) in pins.iter().zip(pins.iter().skip(1)) { // purposely does not allow wrap-around because we can't claim pins 30 and 31. assert!(p1.pin() + 1 == p2.pin(), "pins must be consecutive"); @@ -520,6 +526,39 @@ pub struct PinConfig { pub out_base: u8, } +/// Comparison level or IRQ index for the MOV x, STATUS instruction. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[cfg(feature = "_rp235x")] +pub enum StatusN { + /// IRQ flag in this PIO block + This(u8), + /// IRQ flag in the next lower PIO block + Lower(u8), + /// IRQ flag in the next higher PIO block + Higher(u8), +} + +#[cfg(feature = "_rp235x")] +impl Default for StatusN { + fn default() -> Self { + Self::This(0) + } +} + +#[cfg(feature = "_rp235x")] +impl Into for StatusN { + fn into(self) -> crate::pac::pio::vals::ExecctrlStatusN { + let x = match self { + StatusN::This(n) => n, + StatusN::Lower(n) => n + 0x08, + StatusN::Higher(n) => n + 0x10, + }; + + crate::pac::pio::vals::ExecctrlStatusN(x) + } +} + /// PIO config. #[derive(Clone, Copy, Debug)] pub struct Config<'d, PIO: Instance> { @@ -534,7 +573,12 @@ pub struct Config<'d, PIO: Instance> { /// Which source to use for checking status. pub status_sel: StatusSource, /// Status comparison level. + #[cfg(feature = "rp2040")] pub status_n: u8, + // This cfg probably shouldn't be required, but the SVD for the 2040 doesn't have the enum + #[cfg(feature = "_rp235x")] + /// Status comparison level. + pub status_n: StatusN, exec: ExecConfig, origin: Option, /// Configure FIFO allocation. @@ -650,7 +694,7 @@ impl<'d, PIO: Instance + 'd, const SM: usize> StateMachine<'d, PIO, SM> { assert!(config.clock_divider <= 65536, "clkdiv must be <= 65536"); assert!(config.clock_divider >= 1, "clkdiv must be >= 1"); assert!(config.out_en_sel < 32, "out_en_sel must be < 32"); - assert!(config.status_n < 32, "status_n must be < 32"); + //assert!(config.status_n < 32, "status_n must be < 32"); // sm expects 0 for 32, truncation makes that happen assert!(config.shift_in.threshold <= 32, "shift_in.threshold must be <= 32"); assert!(config.shift_out.threshold <= 32, "shift_out.threshold must be <= 32"); @@ -665,11 +709,17 @@ impl<'d, PIO: Instance + 'd, const SM: usize> StateMachine<'d, PIO, SM> { w.set_out_sticky(config.out_sticky); w.set_wrap_top(config.exec.wrap_top); w.set_wrap_bottom(config.exec.wrap_bottom); + #[cfg(feature = "_rp235x")] w.set_status_sel(match config.status_sel { - StatusSource::TxFifoLevel => SmExecctrlStatusSel::TXLEVEL, - StatusSource::RxFifoLevel => SmExecctrlStatusSel::RXLEVEL, + StatusSource::TxFifoLevel => pac::pio::vals::ExecctrlStatusSel::TXLEVEL, + StatusSource::RxFifoLevel => pac::pio::vals::ExecctrlStatusSel::RXLEVEL, }); - w.set_status_n(config.status_n); + #[cfg(feature = "rp2040")] + w.set_status_sel(match config.status_sel { + StatusSource::TxFifoLevel => pac::pio::vals::SmExecctrlStatusSel::TXLEVEL, + StatusSource::RxFifoLevel => pac::pio::vals::SmExecctrlStatusSel::RXLEVEL, + }); + w.set_status_n(config.status_n.into()); }); sm.shiftctrl().write(|w| { w.set_fjoin_rx(config.fifo_join == FifoJoin::RxOnly); @@ -681,6 +731,8 @@ impl<'d, PIO: Instance + 'd, const SM: usize> StateMachine<'d, PIO, SM> { w.set_autopull(config.shift_out.auto_fill); w.set_autopush(config.shift_in.auto_fill); }); + + #[cfg(feature = "rp2040")] sm.pinctrl().write(|w| { w.set_sideset_count(config.pins.sideset_count); w.set_set_count(config.pins.set_count); @@ -690,11 +742,63 @@ impl<'d, PIO: Instance + 'd, const SM: usize> StateMachine<'d, PIO, SM> { w.set_set_base(config.pins.set_base); w.set_out_base(config.pins.out_base); }); + + #[cfg(feature = "_rp235x")] + { + let mut low_ok = true; + let mut high_ok = true; + + let in_pins = config.pins.in_base..config.pins.in_base + config.in_count; + let side_pins = config.pins.sideset_base..config.pins.sideset_base + config.pins.sideset_count; + let set_pins = config.pins.set_base..config.pins.set_base + config.pins.set_count; + let out_pins = config.pins.out_base..config.pins.out_base + config.pins.out_count; + + for pin_range in [in_pins, side_pins, set_pins, out_pins] { + for pin in pin_range { + low_ok &= pin < 32; + high_ok &= pin >= 16; + } + } + + if !low_ok && !high_ok { + panic!( + "All pins must either be <32 or >=16, in:{:?}-{:?}, side:{:?}-{:?}, set:{:?}-{:?}, out:{:?}-{:?}", + config.pins.in_base, + config.pins.in_base + config.in_count - 1, + config.pins.sideset_base, + config.pins.sideset_base + config.pins.sideset_count - 1, + config.pins.set_base, + config.pins.set_base + config.pins.set_count - 1, + config.pins.out_base, + config.pins.out_base + config.pins.out_count - 1, + ) + } + let shift = if low_ok { 0 } else { 16 }; + + sm.pinctrl().write(|w| { + w.set_sideset_count(config.pins.sideset_count); + w.set_set_count(config.pins.set_count); + w.set_out_count(config.pins.out_count); + w.set_in_base(config.pins.in_base.checked_sub(shift).unwrap_or_default()); + w.set_sideset_base(config.pins.sideset_base.checked_sub(shift).unwrap_or_default()); + w.set_set_base(config.pins.set_base.checked_sub(shift).unwrap_or_default()); + w.set_out_base(config.pins.out_base.checked_sub(shift).unwrap_or_default()); + }); + + PIO::PIO.gpiobase().write(|w| w.set_gpiobase(shift == 16)); + } + if let Some(origin) = config.origin { unsafe { instr::exec_jmp(self, origin) } } } + /// Set the clock divider for this state machine. + pub fn set_clock_divider(&mut self, clock_divider: FixedU32) { + let sm = Self::this_sm(); + sm.clkdiv().write(|w| w.0 = clock_divider.to_bits() << 8); + } + #[inline(always)] fn this_sm() -> crate::pac::pio::StateMachine { PIO::PIO.sm(SM) @@ -764,7 +868,7 @@ impl<'d, PIO: Instance + 'd, const SM: usize> StateMachine<'d, PIO, SM> { w.set_set_count(1); }); // SET PINS, (dir) - unsafe { sm.exec_instr(0b111_00000_000_00000 | level as u16) }; + unsafe { sm.exec_instr(0b11100_000_000_00000 | level as u16) }; } }); } @@ -867,9 +971,7 @@ impl<'d, PIO: Instance> Common<'d, PIO> { prog: &Program, ) -> Result, LoadError> { match prog.origin { - Some(origin) => self - .try_load_program_at(prog, origin) - .map_err(|a| LoadError::AddressInUse(a)), + Some(origin) => self.try_load_program_at(prog, origin).map_err(LoadError::AddressInUse), None => { // naively search for free space, allowing wraparound since // PIO does support that. with only 32 instruction slots it @@ -952,6 +1054,18 @@ impl<'d, PIO: Instance> Common<'d, PIO> { pub fn make_pio_pin(&mut self, pin: impl Peripheral

+ 'd) -> Pin<'d, PIO> { into_ref!(pin); pin.gpio().ctrl().write(|w| w.set_funcsel(PIO::FUNCSEL as _)); + pin.pad_ctrl().write(|w| { + #[cfg(feature = "_rp235x")] + w.set_iso(false); + w.set_schmitt(true); + w.set_slewfast(false); + // TODO rp235x errata E9 recommends to not enable IE if we're not + // going to use input. Maybe add an API for the user to enable/disable this? + w.set_ie(true); + w.set_od(false); + w.set_pue(false); + w.set_pde(false); + }); // we can be relaxed about this because we're &mut here and nothing is cached PIO::state().used_pins.fetch_or(1 << pin.pin_bank(), Ordering::Relaxed); Pin { @@ -1133,16 +1247,15 @@ impl<'d, PIO: Instance> Pio<'d, PIO> { // other way. pub struct State { users: AtomicU8, - used_pins: AtomicU32, + used_pins: AtomicU64, } fn on_pio_drop() { let state = PIO::state(); if state.users.fetch_sub(1, Ordering::AcqRel) == 1 { let used_pins = state.used_pins.load(Ordering::Relaxed); - let null = Gpio0ctrlFuncsel::NULL as _; - // we only have 30 pins. don't test the other two since gpio() asserts. - for i in 0..30 { + let null = pac::io::vals::Gpio0ctrlFuncsel::NULL as _; + for i in 0..crate::gpio::BANK0_PIN_COUNT { if used_pins & (1 << i) != 0 { pac::IO_BANK0.gpio(i).ctrl().write(|w| w.set_funcsel(null)); } @@ -1150,62 +1263,61 @@ fn on_pio_drop() { } } -mod sealed { - use super::*; +trait SealedInstance { + const PIO_NO: u8; + const PIO: &'static crate::pac::pio::Pio; + const FUNCSEL: crate::pac::io::vals::Gpio0ctrlFuncsel; - pub trait PioPin {} + #[inline] + fn wakers() -> &'static Wakers { + const NEW_AW: AtomicWaker = AtomicWaker::new(); + static WAKERS: Wakers = Wakers([NEW_AW; 12]); - pub trait Instance { - const PIO_NO: u8; - const PIO: &'static crate::pac::pio::Pio; - const FUNCSEL: crate::pac::io::vals::Gpio0ctrlFuncsel; - type Interrupt: crate::interrupt::typelevel::Interrupt; + &WAKERS + } - #[inline] - fn wakers() -> &'static Wakers { - const NEW_AW: AtomicWaker = AtomicWaker::new(); - static WAKERS: Wakers = Wakers([NEW_AW; 12]); + #[inline] + fn state() -> &'static State { + static STATE: State = State { + users: AtomicU8::new(0), + used_pins: AtomicU64::new(0), + }; - &WAKERS - } - - #[inline] - fn state() -> &'static State { - static STATE: State = State { - users: AtomicU8::new(0), - used_pins: AtomicU32::new(0), - }; - - &STATE - } + &STATE } } /// PIO instance. -pub trait Instance: sealed::Instance + Sized + Unpin {} +#[allow(private_bounds)] +pub trait Instance: SealedInstance + Sized + Unpin { + /// Interrupt for this peripheral. + type Interrupt: crate::interrupt::typelevel::Interrupt; +} macro_rules! impl_pio { ($name:ident, $pio:expr, $pac:ident, $funcsel:ident, $irq:ident) => { - impl sealed::Instance for peripherals::$name { + impl SealedInstance for peripherals::$name { const PIO_NO: u8 = $pio; const PIO: &'static pac::pio::Pio = &pac::$pac; const FUNCSEL: pac::io::vals::Gpio0ctrlFuncsel = pac::io::vals::Gpio0ctrlFuncsel::$funcsel; + } + impl Instance for peripherals::$name { type Interrupt = crate::interrupt::typelevel::$irq; } - impl Instance for peripherals::$name {} }; } impl_pio!(PIO0, 0, PIO0, PIO0_0, PIO0_IRQ_0); impl_pio!(PIO1, 1, PIO1, PIO1_0, PIO1_IRQ_0); +#[cfg(feature = "_rp235x")] +impl_pio!(PIO2, 2, PIO2, PIO2_0, PIO2_IRQ_0); /// PIO pin. -pub trait PioPin: sealed::PioPin + gpio::Pin {} +pub trait PioPin: gpio::Pin {} macro_rules! impl_pio_pin { ($( $pin:ident, )*) => { $( - impl sealed::PioPin for peripherals::$pin {} impl PioPin for peripherals::$pin {} )* }; @@ -1243,3 +1355,25 @@ impl_pio_pin! { PIN_28, PIN_29, } + +#[cfg(feature = "rp235xb")] +impl_pio_pin! { + PIN_30, + PIN_31, + PIN_32, + PIN_33, + PIN_34, + PIN_35, + PIN_36, + PIN_37, + PIN_38, + PIN_39, + PIN_40, + PIN_41, + PIN_42, + PIN_43, + PIN_44, + PIN_45, + PIN_46, + PIN_47, +} diff --git a/embassy-rp/src/pio_programs/hd44780.rs b/embassy-rp/src/pio_programs/hd44780.rs new file mode 100644 index 000000000..9bbf44fc4 --- /dev/null +++ b/embassy-rp/src/pio_programs/hd44780.rs @@ -0,0 +1,203 @@ +//! [HD44780 display driver](https://www.sparkfun.com/datasheets/LCD/HD44780.pdf) + +use crate::dma::{AnyChannel, Channel}; +use crate::pio::{ + Common, Config, Direction, FifoJoin, Instance, Irq, LoadedProgram, PioPin, ShiftConfig, ShiftDirection, + StateMachine, +}; +use crate::{into_ref, Peripheral, PeripheralRef}; + +/// This struct represents a HD44780 program that takes command words ( <0:4>) +pub struct PioHD44780CommandWordProgram<'a, PIO: Instance> { + prg: LoadedProgram<'a, PIO>, +} + +impl<'a, PIO: Instance> PioHD44780CommandWordProgram<'a, PIO> { + /// Load the program into the given pio + pub fn new(common: &mut Common<'a, PIO>) -> Self { + let prg = pio_proc::pio_asm!( + r#" + .side_set 1 opt + .origin 20 + + loop: + out x, 24 + delay: + jmp x--, delay + out pins, 4 side 1 + out null, 4 side 0 + jmp !osre, loop + irq 0 + "#, + ); + + let prg = common.load_program(&prg.program); + + Self { prg } + } +} + +/// This struct represents a HD44780 program that takes command sequences ( , data...) +pub struct PioHD44780CommandSequenceProgram<'a, PIO: Instance> { + prg: LoadedProgram<'a, PIO>, +} + +impl<'a, PIO: Instance> PioHD44780CommandSequenceProgram<'a, PIO> { + /// Load the program into the given pio + pub fn new(common: &mut Common<'a, PIO>) -> Self { + // many side sets are only there to free up a delay bit! + let prg = pio_proc::pio_asm!( + r#" + .origin 27 + .side_set 1 + + .wrap_target + pull side 0 + out x 1 side 0 ; !rs + out y 7 side 0 ; #data - 1 + + ; rs/rw to e: >= 60ns + ; e high time: >= 500ns + ; e low time: >= 500ns + ; read data valid after e falling: ~5ns + ; write data hold after e falling: ~10ns + + loop: + pull side 0 + jmp !x data side 0 + command: + set pins 0b00 side 0 + jmp shift side 0 + data: + set pins 0b01 side 0 + shift: + out pins 4 side 1 [9] + nop side 0 [9] + out pins 4 side 1 [9] + mov osr null side 0 [7] + out pindirs 4 side 0 + set pins 0b10 side 0 + busy: + nop side 1 [9] + jmp pin more side 0 [9] + mov osr ~osr side 1 [9] + nop side 0 [4] + out pindirs 4 side 0 + jmp y-- loop side 0 + .wrap + more: + nop side 1 [9] + jmp busy side 0 [9] + "# + ); + + let prg = common.load_program(&prg.program); + + Self { prg } + } +} + +/// Pio backed HD44780 driver +pub struct PioHD44780<'l, P: Instance, const S: usize> { + dma: PeripheralRef<'l, AnyChannel>, + sm: StateMachine<'l, P, S>, + + buf: [u8; 40], +} + +impl<'l, P: Instance, const S: usize> PioHD44780<'l, P, S> { + /// Configure the given state machine to first init, then write data to, a HD44780 display. + pub async fn new( + common: &mut Common<'l, P>, + mut sm: StateMachine<'l, P, S>, + mut irq: Irq<'l, P, S>, + dma: impl Peripheral

+ 'l, + rs: impl PioPin, + rw: impl PioPin, + e: impl PioPin, + db4: impl PioPin, + db5: impl PioPin, + db6: impl PioPin, + db7: impl PioPin, + word_prg: &PioHD44780CommandWordProgram<'l, P>, + seq_prg: &PioHD44780CommandSequenceProgram<'l, P>, + ) -> PioHD44780<'l, P, S> { + into_ref!(dma); + + let rs = common.make_pio_pin(rs); + let rw = common.make_pio_pin(rw); + let e = common.make_pio_pin(e); + let db4 = common.make_pio_pin(db4); + let db5 = common.make_pio_pin(db5); + let db6 = common.make_pio_pin(db6); + let db7 = common.make_pio_pin(db7); + + sm.set_pin_dirs(Direction::Out, &[&rs, &rw, &e, &db4, &db5, &db6, &db7]); + + let mut cfg = Config::default(); + cfg.use_program(&word_prg.prg, &[&e]); + cfg.clock_divider = 125u8.into(); + cfg.set_out_pins(&[&db4, &db5, &db6, &db7]); + cfg.shift_out = ShiftConfig { + auto_fill: true, + direction: ShiftDirection::Left, + threshold: 32, + }; + cfg.fifo_join = FifoJoin::TxOnly; + sm.set_config(&cfg); + + sm.set_enable(true); + // init to 8 bit thrice + sm.tx().push((50000 << 8) | 0x30); + sm.tx().push((5000 << 8) | 0x30); + sm.tx().push((200 << 8) | 0x30); + // init 4 bit + sm.tx().push((200 << 8) | 0x20); + // set font and lines + sm.tx().push((50 << 8) | 0x20); + sm.tx().push(0b1100_0000); + + irq.wait().await; + sm.set_enable(false); + + let mut cfg = Config::default(); + cfg.use_program(&seq_prg.prg, &[&e]); + cfg.clock_divider = 8u8.into(); // ~64ns/insn + cfg.set_jmp_pin(&db7); + cfg.set_set_pins(&[&rs, &rw]); + cfg.set_out_pins(&[&db4, &db5, &db6, &db7]); + cfg.shift_out.direction = ShiftDirection::Left; + cfg.fifo_join = FifoJoin::TxOnly; + sm.set_config(&cfg); + + sm.set_enable(true); + + // display on and cursor on and blinking, reset display + sm.tx().dma_push(dma.reborrow(), &[0x81u8, 0x0f, 1]).await; + + Self { + dma: dma.map_into(), + sm, + buf: [0x20; 40], + } + } + + /// Write a line to the display + pub async fn add_line(&mut self, s: &[u8]) { + // move cursor to 0:0, prepare 16 characters + self.buf[..3].copy_from_slice(&[0x80, 0x80, 15]); + // move line 2 up + self.buf.copy_within(22..38, 3); + // move cursor to 1:0, prepare 16 characters + self.buf[19..22].copy_from_slice(&[0x80, 0xc0, 15]); + // file line 2 with spaces + self.buf[22..38].fill(0x20); + // copy input line + let len = s.len().min(16); + self.buf[22..22 + len].copy_from_slice(&s[0..len]); + // set cursor to 1:15 + self.buf[38..].copy_from_slice(&[0x80, 0xcf]); + + self.sm.tx().dma_push(self.dma.reborrow(), &self.buf).await; + } +} diff --git a/embassy-rp/src/pio_programs/i2s.rs b/embassy-rp/src/pio_programs/i2s.rs new file mode 100644 index 000000000..e3f1f89d4 --- /dev/null +++ b/embassy-rp/src/pio_programs/i2s.rs @@ -0,0 +1,95 @@ +//! Pio backed I2s output + +use fixed::traits::ToFixed; + +use crate::dma::{AnyChannel, Channel, Transfer}; +use crate::pio::{ + Common, Config, Direction, FifoJoin, Instance, LoadedProgram, PioPin, ShiftConfig, ShiftDirection, StateMachine, +}; +use crate::{into_ref, Peripheral, PeripheralRef}; + +/// This struct represents an i2s output driver program +pub struct PioI2sOutProgram<'a, PIO: Instance> { + prg: LoadedProgram<'a, PIO>, +} + +impl<'a, PIO: Instance> PioI2sOutProgram<'a, PIO> { + /// Load the program into the given pio + pub fn new(common: &mut Common<'a, PIO>) -> Self { + let prg = pio_proc::pio_asm!( + ".side_set 2", + " set x, 14 side 0b01", // side 0bWB - W = Word Clock, B = Bit Clock + "left_data:", + " out pins, 1 side 0b00", + " jmp x-- left_data side 0b01", + " out pins 1 side 0b10", + " set x, 14 side 0b11", + "right_data:", + " out pins 1 side 0b10", + " jmp x-- right_data side 0b11", + " out pins 1 side 0b00", + ); + + let prg = common.load_program(&prg.program); + + Self { prg } + } +} + +/// Pio backed I2s output driver +pub struct PioI2sOut<'a, P: Instance, const S: usize> { + dma: PeripheralRef<'a, AnyChannel>, + sm: StateMachine<'a, P, S>, +} + +impl<'a, P: Instance, const S: usize> PioI2sOut<'a, P, S> { + /// Configure a state machine to output I2s + pub fn new( + common: &mut Common<'a, P>, + mut sm: StateMachine<'a, P, S>, + dma: impl Peripheral

+ 'a, + data_pin: impl PioPin, + bit_clock_pin: impl PioPin, + lr_clock_pin: impl PioPin, + sample_rate: u32, + bit_depth: u32, + channels: u32, + program: &PioI2sOutProgram<'a, P>, + ) -> Self { + into_ref!(dma); + + let data_pin = common.make_pio_pin(data_pin); + let bit_clock_pin = common.make_pio_pin(bit_clock_pin); + let left_right_clock_pin = common.make_pio_pin(lr_clock_pin); + + let cfg = { + let mut cfg = Config::default(); + cfg.use_program(&program.prg, &[&bit_clock_pin, &left_right_clock_pin]); + cfg.set_out_pins(&[&data_pin]); + let clock_frequency = sample_rate * bit_depth * channels; + cfg.clock_divider = (125_000_000. / clock_frequency as f64 / 2.).to_fixed(); + cfg.shift_out = ShiftConfig { + threshold: 32, + direction: ShiftDirection::Left, + auto_fill: true, + }; + // join fifos to have twice the time to start the next dma transfer + cfg.fifo_join = FifoJoin::TxOnly; + cfg + }; + sm.set_config(&cfg); + sm.set_pin_dirs(Direction::Out, &[&data_pin, &left_right_clock_pin, &bit_clock_pin]); + + sm.set_enable(true); + + Self { + dma: dma.map_into(), + sm, + } + } + + /// Return an in-prograss dma transfer future. Awaiting it will guarentee a complete transfer. + pub fn write<'b>(&'b mut self, buff: &'b [u32]) -> Transfer<'b, AnyChannel> { + self.sm.tx().dma_push(self.dma.reborrow(), buff) + } +} diff --git a/embassy-rp/src/pio_programs/mod.rs b/embassy-rp/src/pio_programs/mod.rs new file mode 100644 index 000000000..74537825b --- /dev/null +++ b/embassy-rp/src/pio_programs/mod.rs @@ -0,0 +1,10 @@ +//! Pre-built pio programs for common interfaces + +pub mod hd44780; +pub mod i2s; +pub mod onewire; +pub mod pwm; +pub mod rotary_encoder; +pub mod stepper; +pub mod uart; +pub mod ws2812; diff --git a/embassy-rp/src/pio_programs/onewire.rs b/embassy-rp/src/pio_programs/onewire.rs new file mode 100644 index 000000000..f3bc5fcd7 --- /dev/null +++ b/embassy-rp/src/pio_programs/onewire.rs @@ -0,0 +1,109 @@ +//! OneWire pio driver + +use crate::pio::{self, Common, Config, Instance, LoadedProgram, PioPin, ShiftConfig, ShiftDirection, StateMachine}; + +/// This struct represents an onewire driver program +pub struct PioOneWireProgram<'a, PIO: Instance> { + prg: LoadedProgram<'a, PIO>, +} + +impl<'a, PIO: Instance> PioOneWireProgram<'a, PIO> { + /// Load the program into the given pio + pub fn new(common: &mut Common<'a, PIO>) -> Self { + let prg = pio_proc::pio_asm!( + r#" + .wrap_target + again: + pull block + mov x, osr + jmp !x, read + write: + set pindirs, 1 + set pins, 0 + loop1: + jmp x--,loop1 + set pindirs, 0 [31] + wait 1 pin 0 [31] + pull block + mov x, osr + bytes1: + pull block + set y, 7 + set pindirs, 1 + bit1: + set pins, 0 [1] + out pins,1 [31] + set pins, 1 [20] + jmp y--,bit1 + jmp x--,bytes1 + set pindirs, 0 [31] + jmp again + read: + pull block + mov x, osr + bytes2: + set y, 7 + bit2: + set pindirs, 1 + set pins, 0 [1] + set pindirs, 0 [5] + in pins,1 [10] + jmp y--,bit2 + jmp x--,bytes2 + .wrap + "#, + ); + let prg = common.load_program(&prg.program); + + Self { prg } + } +} + +/// Pio backed OneWire driver +pub struct PioOneWire<'d, PIO: pio::Instance, const SM: usize> { + sm: StateMachine<'d, PIO, SM>, +} + +impl<'d, PIO: pio::Instance, const SM: usize> PioOneWire<'d, PIO, SM> { + /// Create a new instance the driver + pub fn new( + common: &mut Common<'d, PIO>, + mut sm: StateMachine<'d, PIO, SM>, + pin: impl PioPin, + program: &PioOneWireProgram<'d, PIO>, + ) -> Self { + let pin = common.make_pio_pin(pin); + let mut cfg = Config::default(); + cfg.use_program(&program.prg, &[]); + cfg.set_out_pins(&[&pin]); + cfg.set_in_pins(&[&pin]); + cfg.set_set_pins(&[&pin]); + cfg.shift_in = ShiftConfig { + auto_fill: true, + direction: ShiftDirection::Right, + threshold: 8, + }; + cfg.clock_divider = 255_u8.into(); + sm.set_config(&cfg); + sm.set_enable(true); + Self { sm } + } + + /// Write bytes over the wire + pub async fn write_bytes(&mut self, bytes: &[u8]) { + self.sm.tx().wait_push(250).await; + self.sm.tx().wait_push(bytes.len() as u32 - 1).await; + for b in bytes { + self.sm.tx().wait_push(*b as u32).await; + } + } + + /// Read bytes from the wire + pub async fn read_bytes(&mut self, bytes: &mut [u8]) { + self.sm.tx().wait_push(0).await; + self.sm.tx().wait_push(bytes.len() as u32 - 1).await; + for b in bytes.iter_mut() { + *b = (self.sm.rx().wait_pull().await >> 24) as u8; + } + } +} diff --git a/embassy-rp/src/pio_programs/pwm.rs b/embassy-rp/src/pio_programs/pwm.rs new file mode 100644 index 000000000..c6502387a --- /dev/null +++ b/embassy-rp/src/pio_programs/pwm.rs @@ -0,0 +1,121 @@ +//! PIO backed PWM driver + +use core::time::Duration; + +use pio::InstructionOperands; + +use crate::clocks; +use crate::gpio::Level; +use crate::pio::{Common, Config, Direction, Instance, LoadedProgram, Pin, PioPin, StateMachine}; + +/// This converts the duration provided into the number of cycles the PIO needs to run to make it take the same time +fn to_pio_cycles(duration: Duration) -> u32 { + (clocks::clk_sys_freq() / 1_000_000) / 3 * duration.as_micros() as u32 // parentheses are required to prevent overflow +} + +/// This struct represents a PWM program loaded into pio instruction memory. +pub struct PioPwmProgram<'a, PIO: Instance> { + prg: LoadedProgram<'a, PIO>, +} + +impl<'a, PIO: Instance> PioPwmProgram<'a, PIO> { + /// Load the program into the given pio + pub fn new(common: &mut Common<'a, PIO>) -> Self { + let prg = pio_proc::pio_asm!( + ".side_set 1 opt" + "pull noblock side 0" + "mov x, osr" + "mov y, isr" + "countloop:" + "jmp x!=y noset" + "jmp skip side 1" + "noset:" + "nop" + "skip:" + "jmp y-- countloop" + ); + + let prg = common.load_program(&prg.program); + + Self { prg } + } +} + +/// Pio backed PWM output +pub struct PioPwm<'d, T: Instance, const SM: usize> { + sm: StateMachine<'d, T, SM>, + pin: Pin<'d, T>, +} + +impl<'d, T: Instance, const SM: usize> PioPwm<'d, T, SM> { + /// Configure a state machine as a PWM output + pub fn new( + pio: &mut Common<'d, T>, + mut sm: StateMachine<'d, T, SM>, + pin: impl PioPin, + program: &PioPwmProgram<'d, T>, + ) -> Self { + let pin = pio.make_pio_pin(pin); + sm.set_pins(Level::High, &[&pin]); + sm.set_pin_dirs(Direction::Out, &[&pin]); + + let mut cfg = Config::default(); + cfg.use_program(&program.prg, &[&pin]); + + sm.set_config(&cfg); + + Self { sm, pin } + } + + /// Enable's the PIO program, continuing the wave generation from the PIO program. + pub fn start(&mut self) { + self.sm.set_enable(true); + } + + /// Stops the PIO program, ceasing all signals from the PIN that were generated via PIO. + pub fn stop(&mut self) { + self.sm.set_enable(false); + } + + /// Sets the pwm period, which is the length of time for each pio wave until reset. + pub fn set_period(&mut self, duration: Duration) { + let is_enabled = self.sm.is_enabled(); + while !self.sm.tx().empty() {} // Make sure that the queue is empty + self.sm.set_enable(false); + self.sm.tx().push(to_pio_cycles(duration)); + unsafe { + self.sm.exec_instr( + InstructionOperands::PULL { + if_empty: false, + block: false, + } + .encode(), + ); + self.sm.exec_instr( + InstructionOperands::OUT { + destination: ::pio::OutDestination::ISR, + bit_count: 32, + } + .encode(), + ); + }; + if is_enabled { + self.sm.set_enable(true) // Enable if previously enabled + } + } + + /// Set the number of pio cycles to set the wave on high to. + pub fn set_level(&mut self, level: u32) { + self.sm.tx().push(level); + } + + /// Set the pulse width high time + pub fn write(&mut self, duration: Duration) { + self.set_level(to_pio_cycles(duration)); + } + + /// Return the state machine and pin. + pub fn release(self) -> (StateMachine<'d, T, SM>, Pin<'d, T>) { + (self.sm, self.pin) + } +} diff --git a/embassy-rp/src/pio_programs/rotary_encoder.rs b/embassy-rp/src/pio_programs/rotary_encoder.rs new file mode 100644 index 000000000..86423fd31 --- /dev/null +++ b/embassy-rp/src/pio_programs/rotary_encoder.rs @@ -0,0 +1,73 @@ +//! PIO backed quadrature encoder + +use fixed::traits::ToFixed; + +use crate::gpio::Pull; +use crate::pio::{self, Common, Config, FifoJoin, Instance, LoadedProgram, PioPin, ShiftDirection, StateMachine}; + +/// This struct represents an Encoder program loaded into pio instruction memory. +pub struct PioEncoderProgram<'a, PIO: Instance> { + prg: LoadedProgram<'a, PIO>, +} + +impl<'a, PIO: Instance> PioEncoderProgram<'a, PIO> { + /// Load the program into the given pio + pub fn new(common: &mut Common<'a, PIO>) -> Self { + let prg = pio_proc::pio_asm!("wait 1 pin 1", "wait 0 pin 1", "in pins, 2", "push",); + + let prg = common.load_program(&prg.program); + + Self { prg } + } +} + +/// Pio Backed quadrature encoder reader +pub struct PioEncoder<'d, T: Instance, const SM: usize> { + sm: StateMachine<'d, T, SM>, +} + +impl<'d, T: Instance, const SM: usize> PioEncoder<'d, T, SM> { + /// Configure a state machine with the loaded [PioEncoderProgram] + pub fn new( + pio: &mut Common<'d, T>, + mut sm: StateMachine<'d, T, SM>, + pin_a: impl PioPin, + pin_b: impl PioPin, + program: &PioEncoderProgram<'d, T>, + ) -> Self { + let mut pin_a = pio.make_pio_pin(pin_a); + let mut pin_b = pio.make_pio_pin(pin_b); + pin_a.set_pull(Pull::Up); + pin_b.set_pull(Pull::Up); + sm.set_pin_dirs(pio::Direction::In, &[&pin_a, &pin_b]); + + let mut cfg = Config::default(); + cfg.set_in_pins(&[&pin_a, &pin_b]); + cfg.fifo_join = FifoJoin::RxOnly; + cfg.shift_in.direction = ShiftDirection::Left; + cfg.clock_divider = 10_000.to_fixed(); + cfg.use_program(&program.prg, &[]); + sm.set_config(&cfg); + sm.set_enable(true); + Self { sm } + } + + /// Read a single count from the encoder + pub async fn read(&mut self) -> Direction { + loop { + match self.sm.rx().wait_pull().await { + 0 => return Direction::CounterClockwise, + 1 => return Direction::Clockwise, + _ => {} + } + } + } +} + +/// Encoder Count Direction +pub enum Direction { + /// Encoder turned clockwise + Clockwise, + /// Encoder turned counter clockwise + CounterClockwise, +} diff --git a/embassy-rp/src/pio_programs/stepper.rs b/embassy-rp/src/pio_programs/stepper.rs new file mode 100644 index 000000000..0d58c754c --- /dev/null +++ b/embassy-rp/src/pio_programs/stepper.rs @@ -0,0 +1,147 @@ +//! Pio Stepper Driver for 5-wire steppers + +use core::mem::{self, MaybeUninit}; + +use fixed::traits::ToFixed; +use fixed::types::extra::U8; +use fixed::FixedU32; + +use crate::pio::{Common, Config, Direction, Instance, Irq, LoadedProgram, PioPin, StateMachine}; + +/// This struct represents a Stepper driver program loaded into pio instruction memory. +pub struct PioStepperProgram<'a, PIO: Instance> { + prg: LoadedProgram<'a, PIO>, +} + +impl<'a, PIO: Instance> PioStepperProgram<'a, PIO> { + /// Load the program into the given pio + pub fn new(common: &mut Common<'a, PIO>) -> Self { + let prg = pio_proc::pio_asm!( + "pull block", + "mov x, osr", + "pull block", + "mov y, osr", + "jmp !x end", + "loop:", + "jmp !osre step", + "mov osr, y", + "step:", + "out pins, 4 [31]" + "jmp x-- loop", + "end:", + "irq 0 rel" + ); + + let prg = common.load_program(&prg.program); + + Self { prg } + } +} + +/// Pio backed Stepper driver +pub struct PioStepper<'d, T: Instance, const SM: usize> { + irq: Irq<'d, T, SM>, + sm: StateMachine<'d, T, SM>, +} + +impl<'d, T: Instance, const SM: usize> PioStepper<'d, T, SM> { + /// Configure a state machine to drive a stepper + pub fn new( + pio: &mut Common<'d, T>, + mut sm: StateMachine<'d, T, SM>, + irq: Irq<'d, T, SM>, + pin0: impl PioPin, + pin1: impl PioPin, + pin2: impl PioPin, + pin3: impl PioPin, + program: &PioStepperProgram<'d, T>, + ) -> Self { + let pin0 = pio.make_pio_pin(pin0); + let pin1 = pio.make_pio_pin(pin1); + let pin2 = pio.make_pio_pin(pin2); + let pin3 = pio.make_pio_pin(pin3); + sm.set_pin_dirs(Direction::Out, &[&pin0, &pin1, &pin2, &pin3]); + let mut cfg = Config::default(); + cfg.set_out_pins(&[&pin0, &pin1, &pin2, &pin3]); + cfg.clock_divider = (125_000_000 / (100 * 136)).to_fixed(); + cfg.use_program(&program.prg, &[]); + sm.set_config(&cfg); + sm.set_enable(true); + Self { irq, sm } + } + + /// Set pulse frequency + pub fn set_frequency(&mut self, freq: u32) { + let clock_divider: FixedU32 = (125_000_000 / (freq * 136)).to_fixed(); + assert!(clock_divider <= 65536, "clkdiv must be <= 65536"); + assert!(clock_divider >= 1, "clkdiv must be >= 1"); + self.sm.set_clock_divider(clock_divider); + self.sm.clkdiv_restart(); + } + + /// Full step, one phase + pub async fn step(&mut self, steps: i32) { + if steps > 0 { + self.run(steps, 0b1000_0100_0010_0001_1000_0100_0010_0001).await + } else { + self.run(-steps, 0b0001_0010_0100_1000_0001_0010_0100_1000).await + } + } + + /// Full step, two phase + pub async fn step2(&mut self, steps: i32) { + if steps > 0 { + self.run(steps, 0b1001_1100_0110_0011_1001_1100_0110_0011).await + } else { + self.run(-steps, 0b0011_0110_1100_1001_0011_0110_1100_1001).await + } + } + + /// Half step + pub async fn step_half(&mut self, steps: i32) { + if steps > 0 { + self.run(steps, 0b1001_1000_1100_0100_0110_0010_0011_0001).await + } else { + self.run(-steps, 0b0001_0011_0010_0110_0100_1100_1000_1001).await + } + } + + async fn run(&mut self, steps: i32, pattern: u32) { + self.sm.tx().wait_push(steps as u32).await; + self.sm.tx().wait_push(pattern).await; + let drop = OnDrop::new(|| { + self.sm.clear_fifos(); + unsafe { + self.sm.exec_instr( + pio::InstructionOperands::JMP { + address: 0, + condition: pio::JmpCondition::Always, + } + .encode(), + ); + } + }); + self.irq.wait().await; + drop.defuse(); + } +} + +struct OnDrop { + f: MaybeUninit, +} + +impl OnDrop { + pub fn new(f: F) -> Self { + Self { f: MaybeUninit::new(f) } + } + + pub fn defuse(self) { + mem::forget(self) + } +} + +impl Drop for OnDrop { + fn drop(&mut self) { + unsafe { self.f.as_ptr().read()() } + } +} diff --git a/embassy-rp/src/pio_programs/uart.rs b/embassy-rp/src/pio_programs/uart.rs new file mode 100644 index 000000000..c643f1063 --- /dev/null +++ b/embassy-rp/src/pio_programs/uart.rs @@ -0,0 +1,185 @@ +//! Pio backed uart drivers + +use core::convert::Infallible; + +use embedded_io_async::{ErrorType, Read, Write}; +use fixed::traits::ToFixed; + +use crate::clocks::clk_sys_freq; +use crate::gpio::Level; +use crate::pio::{ + Common, Config, Direction as PioDirection, FifoJoin, Instance, LoadedProgram, PioPin, ShiftDirection, StateMachine, +}; + +/// This struct represents a uart tx program loaded into pio instruction memory. +pub struct PioUartTxProgram<'a, PIO: Instance> { + prg: LoadedProgram<'a, PIO>, +} + +impl<'a, PIO: Instance> PioUartTxProgram<'a, PIO> { + /// Load the uart tx program into the given pio + pub fn new(common: &mut Common<'a, PIO>) -> Self { + let prg = pio_proc::pio_asm!( + r#" + .side_set 1 opt + + ; An 8n1 UART transmit program. + ; OUT pin 0 and side-set pin 0 are both mapped to UART TX pin. + + pull side 1 [7] ; Assert stop bit, or stall with line in idle state + set x, 7 side 0 [7] ; Preload bit counter, assert start bit for 8 clocks + bitloop: ; This loop will run 8 times (8n1 UART) + out pins, 1 ; Shift 1 bit from OSR to the first OUT pin + jmp x-- bitloop [6] ; Each loop iteration is 8 cycles. + "# + ); + + let prg = common.load_program(&prg.program); + + Self { prg } + } +} + +/// PIO backed Uart transmitter +pub struct PioUartTx<'a, PIO: Instance, const SM: usize> { + sm_tx: StateMachine<'a, PIO, SM>, +} + +impl<'a, PIO: Instance, const SM: usize> PioUartTx<'a, PIO, SM> { + /// Configure a pio state machine to use the loaded tx program. + pub fn new( + baud: u32, + common: &mut Common<'a, PIO>, + mut sm_tx: StateMachine<'a, PIO, SM>, + tx_pin: impl PioPin, + program: &PioUartTxProgram<'a, PIO>, + ) -> Self { + let tx_pin = common.make_pio_pin(tx_pin); + sm_tx.set_pins(Level::High, &[&tx_pin]); + sm_tx.set_pin_dirs(PioDirection::Out, &[&tx_pin]); + + let mut cfg = Config::default(); + + cfg.set_out_pins(&[&tx_pin]); + cfg.use_program(&program.prg, &[&tx_pin]); + cfg.shift_out.auto_fill = false; + cfg.shift_out.direction = ShiftDirection::Right; + cfg.fifo_join = FifoJoin::TxOnly; + cfg.clock_divider = (clk_sys_freq() / (8 * baud)).to_fixed(); + sm_tx.set_config(&cfg); + sm_tx.set_enable(true); + + Self { sm_tx } + } + + /// Write a single u8 + pub async fn write_u8(&mut self, data: u8) { + self.sm_tx.tx().wait_push(data as u32).await; + } +} + +impl ErrorType for PioUartTx<'_, PIO, SM> { + type Error = Infallible; +} + +impl Write for PioUartTx<'_, PIO, SM> { + async fn write(&mut self, buf: &[u8]) -> Result { + for byte in buf { + self.write_u8(*byte).await; + } + Ok(buf.len()) + } +} + +/// This struct represents a Uart Rx program loaded into pio instruction memory. +pub struct PioUartRxProgram<'a, PIO: Instance> { + prg: LoadedProgram<'a, PIO>, +} + +impl<'a, PIO: Instance> PioUartRxProgram<'a, PIO> { + /// Load the uart rx program into the given pio + pub fn new(common: &mut Common<'a, PIO>) -> Self { + let prg = pio_proc::pio_asm!( + r#" + ; Slightly more fleshed-out 8n1 UART receiver which handles framing errors and + ; break conditions more gracefully. + ; IN pin 0 and JMP pin are both mapped to the GPIO used as UART RX. + + start: + wait 0 pin 0 ; Stall until start bit is asserted + set x, 7 [10] ; Preload bit counter, then delay until halfway through + rx_bitloop: ; the first data bit (12 cycles incl wait, set). + in pins, 1 ; Shift data bit into ISR + jmp x-- rx_bitloop [6] ; Loop 8 times, each loop iteration is 8 cycles + jmp pin good_rx_stop ; Check stop bit (should be high) + + irq 4 rel ; Either a framing error or a break. Set a sticky flag, + wait 1 pin 0 ; and wait for line to return to idle state. + jmp start ; Don't push data if we didn't see good framing. + + good_rx_stop: ; No delay before returning to start; a little slack is + in null 24 + push ; important in case the TX clock is slightly too fast. + "# + ); + + let prg = common.load_program(&prg.program); + + Self { prg } + } +} + +/// PIO backed Uart reciever +pub struct PioUartRx<'a, PIO: Instance, const SM: usize> { + sm_rx: StateMachine<'a, PIO, SM>, +} + +impl<'a, PIO: Instance, const SM: usize> PioUartRx<'a, PIO, SM> { + /// Configure a pio state machine to use the loaded rx program. + pub fn new( + baud: u32, + common: &mut Common<'a, PIO>, + mut sm_rx: StateMachine<'a, PIO, SM>, + rx_pin: impl PioPin, + program: &PioUartRxProgram<'a, PIO>, + ) -> Self { + let mut cfg = Config::default(); + cfg.use_program(&program.prg, &[]); + + let rx_pin = common.make_pio_pin(rx_pin); + sm_rx.set_pins(Level::High, &[&rx_pin]); + cfg.set_in_pins(&[&rx_pin]); + cfg.set_jmp_pin(&rx_pin); + sm_rx.set_pin_dirs(PioDirection::In, &[&rx_pin]); + + cfg.clock_divider = (clk_sys_freq() / (8 * baud)).to_fixed(); + cfg.shift_in.auto_fill = false; + cfg.shift_in.direction = ShiftDirection::Right; + cfg.shift_in.threshold = 32; + cfg.fifo_join = FifoJoin::RxOnly; + sm_rx.set_config(&cfg); + sm_rx.set_enable(true); + + Self { sm_rx } + } + + /// Wait for a single u8 + pub async fn read_u8(&mut self) -> u8 { + self.sm_rx.rx().wait_pull().await as u8 + } +} + +impl ErrorType for PioUartRx<'_, PIO, SM> { + type Error = Infallible; +} + +impl Read for PioUartRx<'_, PIO, SM> { + async fn read(&mut self, buf: &mut [u8]) -> Result { + let mut i = 0; + while i < buf.len() { + buf[i] = self.read_u8().await; + i += 1; + } + Ok(i) + } +} diff --git a/embassy-rp/src/pio_programs/ws2812.rs b/embassy-rp/src/pio_programs/ws2812.rs new file mode 100644 index 000000000..875f0209f --- /dev/null +++ b/embassy-rp/src/pio_programs/ws2812.rs @@ -0,0 +1,118 @@ +//! [ws2812](https://www.sparkfun.com/datasheets/LCD/HD44780.pdf) + +use embassy_time::Timer; +use fixed::types::U24F8; +use smart_leds::RGB8; + +use crate::clocks::clk_sys_freq; +use crate::dma::{AnyChannel, Channel}; +use crate::pio::{ + Common, Config, FifoJoin, Instance, LoadedProgram, PioPin, ShiftConfig, ShiftDirection, StateMachine, +}; +use crate::{into_ref, Peripheral, PeripheralRef}; + +const T1: u8 = 2; // start bit +const T2: u8 = 5; // data bit +const T3: u8 = 3; // stop bit +const CYCLES_PER_BIT: u32 = (T1 + T2 + T3) as u32; + +/// This struct represents a ws2812 program loaded into pio instruction memory. +pub struct PioWs2812Program<'a, PIO: Instance> { + prg: LoadedProgram<'a, PIO>, +} + +impl<'a, PIO: Instance> PioWs2812Program<'a, PIO> { + /// Load the ws2812 program into the given pio + pub fn new(common: &mut Common<'a, PIO>) -> Self { + let side_set = pio::SideSet::new(false, 1, false); + let mut a: pio::Assembler<32> = pio::Assembler::new_with_side_set(side_set); + + let mut wrap_target = a.label(); + let mut wrap_source = a.label(); + let mut do_zero = a.label(); + a.set_with_side_set(pio::SetDestination::PINDIRS, 1, 0); + a.bind(&mut wrap_target); + // Do stop bit + a.out_with_delay_and_side_set(pio::OutDestination::X, 1, T3 - 1, 0); + // Do start bit + a.jmp_with_delay_and_side_set(pio::JmpCondition::XIsZero, &mut do_zero, T1 - 1, 1); + // Do data bit = 1 + a.jmp_with_delay_and_side_set(pio::JmpCondition::Always, &mut wrap_target, T2 - 1, 1); + a.bind(&mut do_zero); + // Do data bit = 0 + a.nop_with_delay_and_side_set(T2 - 1, 0); + a.bind(&mut wrap_source); + + let prg = a.assemble_with_wrap(wrap_source, wrap_target); + let prg = common.load_program(&prg); + + Self { prg } + } +} + +/// Pio backed ws2812 driver +/// Const N is the number of ws2812 leds attached to this pin +pub struct PioWs2812<'d, P: Instance, const S: usize, const N: usize> { + dma: PeripheralRef<'d, AnyChannel>, + sm: StateMachine<'d, P, S>, +} + +impl<'d, P: Instance, const S: usize, const N: usize> PioWs2812<'d, P, S, N> { + /// Configure a pio state machine to use the loaded ws2812 program. + pub fn new( + pio: &mut Common<'d, P>, + mut sm: StateMachine<'d, P, S>, + dma: impl Peripheral

+ 'd, + pin: impl PioPin, + program: &PioWs2812Program<'d, P>, + ) -> Self { + into_ref!(dma); + + // Setup sm0 + let mut cfg = Config::default(); + + // Pin config + let out_pin = pio.make_pio_pin(pin); + cfg.set_out_pins(&[&out_pin]); + cfg.set_set_pins(&[&out_pin]); + + cfg.use_program(&program.prg, &[&out_pin]); + + // Clock config, measured in kHz to avoid overflows + let clock_freq = U24F8::from_num(clk_sys_freq() / 1000); + let ws2812_freq = U24F8::from_num(800); + let bit_freq = ws2812_freq * CYCLES_PER_BIT; + cfg.clock_divider = clock_freq / bit_freq; + + // FIFO config + cfg.fifo_join = FifoJoin::TxOnly; + cfg.shift_out = ShiftConfig { + auto_fill: true, + threshold: 24, + direction: ShiftDirection::Left, + }; + + sm.set_config(&cfg); + sm.set_enable(true); + + Self { + dma: dma.map_into(), + sm, + } + } + + /// Write a buffer of [smart_leds::RGB8] to the ws2812 string + pub async fn write(&mut self, colors: &[RGB8; N]) { + // Precompute the word bytes from the colors + let mut words = [0u32; N]; + for i in 0..N { + let word = (u32::from(colors[i].g) << 24) | (u32::from(colors[i].r) << 16) | (u32::from(colors[i].b) << 8); + words[i] = word; + } + + // DMA transfer + self.sm.tx().dma_push(self.dma.reborrow(), &words).await; + + Timer::after_micros(55).await; + } +} diff --git a/embassy-rp/src/pwm.rs b/embassy-rp/src/pwm.rs index 784a05f92..4fb8ade12 100644 --- a/embassy-rp/src/pwm.rs +++ b/embassy-rp/src/pwm.rs @@ -1,13 +1,14 @@ //! Pulse Width Modulation (PWM) use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef}; +pub use embedded_hal_1::pwm::SetDutyCycle; +use embedded_hal_1::pwm::{Error, ErrorKind, ErrorType}; use fixed::traits::ToFixed; use fixed::FixedU16; use pac::pwm::regs::{ChDiv, Intr}; use pac::pwm::vals::Divmode; -use crate::gpio::sealed::Pin as _; -use crate::gpio::{AnyPin, Pin as GpioPin}; +use crate::gpio::{AnyPin, Pin as GpioPin, Pull, SealedPin as _}; use crate::{pac, peripherals, RegExt}; /// The configuration of a PWM slice. @@ -81,24 +82,62 @@ impl From for Divmode { } } -/// PWM driver. -pub struct Pwm<'d, T: Channel> { - inner: PeripheralRef<'d, T>, - pin_a: Option>, - pin_b: Option>, +/// PWM error. +#[derive(Debug)] +pub enum PwmError { + /// Invalid Duty Cycle. + InvalidDutyCycle, } -impl<'d, T: Channel> Pwm<'d, T> { +impl Error for PwmError { + fn kind(&self) -> ErrorKind { + match self { + PwmError::InvalidDutyCycle => ErrorKind::Other, + } + } +} + +/// PWM driver. +pub struct Pwm<'d> { + pin_a: Option>, + pin_b: Option>, + slice: usize, +} + +impl<'d> ErrorType for Pwm<'d> { + type Error = PwmError; +} + +impl<'d> SetDutyCycle for Pwm<'d> { + fn max_duty_cycle(&self) -> u16 { + pac::PWM.ch(self.slice).top().read().top() + } + + fn set_duty_cycle(&mut self, duty: u16) -> Result<(), Self::Error> { + let max_duty = self.max_duty_cycle(); + if duty > max_duty { + return Err(PwmError::InvalidDutyCycle); + } + + let p = pac::PWM.ch(self.slice); + p.cc().modify(|w| { + w.set_a(duty); + w.set_b(duty); + }); + Ok(()) + } +} + +impl<'d> Pwm<'d> { fn new_inner( - inner: impl Peripheral

+ 'd, + slice: usize, a: Option>, b: Option>, + b_pull: Pull, config: Config, divmode: Divmode, ) -> Self { - into_ref!(inner); - - let p = inner.regs(); + let p = pac::PWM.ch(slice); p.csr().modify(|w| { w.set_divmode(divmode); w.set_en(false); @@ -108,89 +147,131 @@ impl<'d, T: Channel> Pwm<'d, T> { if let Some(pin) = &a { pin.gpio().ctrl().write(|w| w.set_funcsel(4)); + #[cfg(feature = "_rp235x")] + pin.pad_ctrl().modify(|w| { + w.set_iso(false); + }); } if let Some(pin) = &b { pin.gpio().ctrl().write(|w| w.set_funcsel(4)); + pin.pad_ctrl().modify(|w| { + #[cfg(feature = "_rp235x")] + w.set_iso(false); + w.set_pue(b_pull == Pull::Up); + w.set_pde(b_pull == Pull::Down); + }); } Self { - inner, - pin_a: a.into(), - pin_b: b.into(), + // inner: p.into(), + pin_a: a, + pin_b: b, + slice, } } /// Create PWM driver without any configured pins. #[inline] - pub fn new_free(inner: impl Peripheral

+ 'd, config: Config) -> Self { - Self::new_inner(inner, None, None, config, Divmode::DIV) + pub fn new_free(slice: impl Peripheral

+ 'd, config: Config) -> Self { + into_ref!(slice); + Self::new_inner(slice.number(), None, None, Pull::None, config, Divmode::DIV) } - /// Create PWM driver with a single 'a' as output. + /// Create PWM driver with a single 'a' pin as output. #[inline] - pub fn new_output_a( - inner: impl Peripheral

+ 'd, - a: impl Peripheral

> + 'd, + pub fn new_output_a( + slice: impl Peripheral

+ 'd, + a: impl Peripheral

> + 'd, config: Config, ) -> Self { - into_ref!(a); - Self::new_inner(inner, Some(a.map_into()), None, config, Divmode::DIV) + into_ref!(slice, a); + Self::new_inner( + slice.number(), + Some(a.map_into()), + None, + Pull::None, + config, + Divmode::DIV, + ) } /// Create PWM driver with a single 'b' pin as output. #[inline] - pub fn new_output_b( - inner: impl Peripheral

+ 'd, - b: impl Peripheral

> + 'd, + pub fn new_output_b( + slice: impl Peripheral

+ 'd, + b: impl Peripheral

> + 'd, config: Config, ) -> Self { - into_ref!(b); - Self::new_inner(inner, None, Some(b.map_into()), config, Divmode::DIV) + into_ref!(slice, b); + Self::new_inner( + slice.number(), + None, + Some(b.map_into()), + Pull::None, + config, + Divmode::DIV, + ) } /// Create PWM driver with a 'a' and 'b' pins as output. #[inline] - pub fn new_output_ab( - inner: impl Peripheral

+ 'd, - a: impl Peripheral

> + 'd, - b: impl Peripheral

> + 'd, + pub fn new_output_ab( + slice: impl Peripheral

+ 'd, + a: impl Peripheral

> + 'd, + b: impl Peripheral

> + 'd, config: Config, ) -> Self { - into_ref!(a, b); - Self::new_inner(inner, Some(a.map_into()), Some(b.map_into()), config, Divmode::DIV) + into_ref!(slice, a, b); + Self::new_inner( + slice.number(), + Some(a.map_into()), + Some(b.map_into()), + Pull::None, + config, + Divmode::DIV, + ) } /// Create PWM driver with a single 'b' as input pin. #[inline] - pub fn new_input( - inner: impl Peripheral

+ 'd, - b: impl Peripheral

> + 'd, + pub fn new_input( + slice: impl Peripheral

+ 'd, + b: impl Peripheral

> + 'd, + b_pull: Pull, mode: InputMode, config: Config, ) -> Self { - into_ref!(b); - Self::new_inner(inner, None, Some(b.map_into()), config, mode.into()) + into_ref!(slice, b); + Self::new_inner(slice.number(), None, Some(b.map_into()), b_pull, config, mode.into()) } /// Create PWM driver with a 'a' and 'b' pins in the desired input mode. #[inline] - pub fn new_output_input( - inner: impl Peripheral

+ 'd, - a: impl Peripheral

> + 'd, - b: impl Peripheral

> + 'd, + pub fn new_output_input( + slice: impl Peripheral

+ 'd, + a: impl Peripheral

> + 'd, + b: impl Peripheral

> + 'd, + b_pull: Pull, mode: InputMode, config: Config, ) -> Self { - into_ref!(a, b); - Self::new_inner(inner, Some(a.map_into()), Some(b.map_into()), config, mode.into()) + into_ref!(slice, a, b); + Self::new_inner( + slice.number(), + Some(a.map_into()), + Some(b.map_into()), + b_pull, + config, + mode.into(), + ) } /// Set the PWM config. pub fn set_config(&mut self, config: &Config) { - Self::configure(self.inner.regs(), config); + Self::configure(pac::PWM.ch(self.slice), config); } fn configure(p: pac::pwm::Channel, config: &Config) { - if config.divider > FixedU16::::from_bits(0xFF_F) { + if config.divider > FixedU16::::from_bits(0xFFF) { panic!("Requested divider is too large"); } @@ -208,22 +289,22 @@ impl<'d, T: Channel> Pwm<'d, T> { }); } - /// Advances a slice’s output phase by one count while it is running + /// Advances a slice's output phase by one count while it is running /// by inserting a pulse into the clock enable. The counter /// will not count faster than once per cycle. #[inline] pub fn phase_advance(&mut self) { - let p = self.inner.regs(); + let p = pac::PWM.ch(self.slice); p.csr().write_set(|w| w.set_ph_adv(true)); while p.csr().read().ph_adv() {} } - /// Retards a slice’s output phase by one count while it is running + /// Retards a slice's output phase by one count while it is running /// by deleting a pulse from the clock enable. The counter will not - /// count backward when clock enable is permenantly low. + /// count backward when clock enable is permanently low. #[inline] pub fn phase_retard(&mut self) { - let p = self.inner.regs(); + let p = pac::PWM.ch(self.slice); p.csr().write_set(|w| w.set_ph_ret(true)); while p.csr().read().ph_ret() {} } @@ -231,13 +312,13 @@ impl<'d, T: Channel> Pwm<'d, T> { /// Read PWM counter. #[inline] pub fn counter(&self) -> u16 { - self.inner.regs().ctr().read().ctr() + pac::PWM.ch(self.slice).ctr().read().ctr() } /// Write PWM counter. #[inline] pub fn set_counter(&self, ctr: u16) { - self.inner.regs().ctr().write(|w| w.set_ctr(ctr)) + pac::PWM.ch(self.slice).ctr().write(|w| w.set_ctr(ctr)) } /// Wait for channel interrupt. @@ -261,22 +342,135 @@ impl<'d, T: Channel> Pwm<'d, T> { #[inline] fn bit(&self) -> u32 { - 1 << self.inner.number() as usize + 1 << self.slice as usize + } + + /// Splits the PWM driver into separate `PwmOutput` instances for channels A and B. + #[inline] + pub fn split(mut self) -> (Option>, Option>) { + ( + self.pin_a + .take() + .map(|pin| PwmOutput::new(PwmChannelPin::A(pin), self.slice.clone(), true)), + self.pin_b + .take() + .map(|pin| PwmOutput::new(PwmChannelPin::B(pin), self.slice.clone(), true)), + ) + } + /// Splits the PWM driver by reference to allow for separate duty cycle control + /// of each channel (A and B) without taking ownership of the PWM instance. + #[inline] + pub fn split_by_ref(&mut self) -> (Option>, Option>) { + ( + self.pin_a + .as_mut() + .map(|pin| PwmOutput::new(PwmChannelPin::A(pin.reborrow()), self.slice.clone(), false)), + self.pin_b + .as_mut() + .map(|pin| PwmOutput::new(PwmChannelPin::B(pin.reborrow()), self.slice.clone(), false)), + ) } } -/// Batch representation of PWM channels. +enum PwmChannelPin<'d> { + A(PeripheralRef<'d, AnyPin>), + B(PeripheralRef<'d, AnyPin>), +} + +/// Single channel of Pwm driver. +pub struct PwmOutput<'d> { + //pin that can be ether ChannelAPin or ChannelBPin + channel_pin: PwmChannelPin<'d>, + slice: usize, + is_owned: bool, +} + +impl<'d> PwmOutput<'d> { + fn new(channel_pin: PwmChannelPin<'d>, slice: usize, is_owned: bool) -> Self { + Self { + channel_pin, + slice, + is_owned, + } + } +} + +impl<'d> Drop for PwmOutput<'d> { + fn drop(&mut self) { + if self.is_owned { + let p = pac::PWM.ch(self.slice); + match &self.channel_pin { + PwmChannelPin::A(pin) => { + p.cc().modify(|w| { + w.set_a(0); + }); + + pin.gpio().ctrl().write(|w| w.set_funcsel(31)); + //Enable pin PULL-DOWN + pin.pad_ctrl().modify(|w| { + w.set_pde(true); + }); + } + PwmChannelPin::B(pin) => { + p.cc().modify(|w| { + w.set_b(0); + }); + pin.gpio().ctrl().write(|w| w.set_funcsel(31)); + //Enable pin PULL-DOWN + pin.pad_ctrl().modify(|w| { + w.set_pde(true); + }); + } + } + } + } +} + +impl<'d> ErrorType for PwmOutput<'d> { + type Error = PwmError; +} + +impl<'d> SetDutyCycle for PwmOutput<'d> { + fn max_duty_cycle(&self) -> u16 { + pac::PWM.ch(self.slice).top().read().top() + } + + fn set_duty_cycle(&mut self, duty: u16) -> Result<(), Self::Error> { + let max_duty = self.max_duty_cycle(); + if duty > max_duty { + return Err(PwmError::InvalidDutyCycle); + } + + let p = pac::PWM.ch(self.slice); + match self.channel_pin { + PwmChannelPin::A(_) => { + p.cc().modify(|w| { + w.set_a(duty); + }); + } + PwmChannelPin::B(_) => { + p.cc().modify(|w| { + w.set_b(duty); + }); + } + } + + Ok(()) + } +} + +/// Batch representation of PWM slices. pub struct PwmBatch(u32); impl PwmBatch { #[inline] - /// Enable a PWM channel in this batch. - pub fn enable(&mut self, pwm: &Pwm<'_, impl Channel>) { + /// Enable a PWM slice in this batch. + pub fn enable(&mut self, pwm: &Pwm<'_>) { self.0 |= pwm.bit(); } #[inline] - /// Enable channels in this batch in a PWM. + /// Enable slices in this batch in a PWM. pub fn set_enabled(enabled: bool, batch: impl FnOnce(&mut PwmBatch)) { let mut en = PwmBatch(0); batch(&mut en); @@ -288,9 +482,9 @@ impl PwmBatch { } } -impl<'d, T: Channel> Drop for Pwm<'d, T> { +impl<'d> Drop for Pwm<'d> { fn drop(&mut self) { - self.inner.regs().csr().write_clear(|w| w.set_en(false)); + pac::PWM.ch(self.slice).csr().write_clear(|w| w.set_en(false)); if let Some(pin) = &self.pin_a { pin.gpio().ctrl().write(|w| w.set_funcsel(31)); } @@ -300,45 +494,48 @@ impl<'d, T: Channel> Drop for Pwm<'d, T> { } } -mod sealed { - pub trait Channel {} +trait SealedSlice {} + +/// PWM Slice. +#[allow(private_bounds)] +pub trait Slice: Peripheral

+ SealedSlice + Sized + 'static { + /// Slice number. + fn number(&self) -> usize; } -/// PWM Channel. -pub trait Channel: Peripheral

+ sealed::Channel + Sized + 'static { - /// Channel number. - fn number(&self) -> u8; - - /// Channel register block. - fn regs(&self) -> pac::pwm::Channel { - pac::PWM.ch(self.number() as _) - } -} - -macro_rules! channel { +macro_rules! slice { ($name:ident, $num:expr) => { - impl sealed::Channel for peripherals::$name {} - impl Channel for peripherals::$name { - fn number(&self) -> u8 { + impl SealedSlice for peripherals::$name {} + impl Slice for peripherals::$name { + fn number(&self) -> usize { $num } } }; } -channel!(PWM_CH0, 0); -channel!(PWM_CH1, 1); -channel!(PWM_CH2, 2); -channel!(PWM_CH3, 3); -channel!(PWM_CH4, 4); -channel!(PWM_CH5, 5); -channel!(PWM_CH6, 6); -channel!(PWM_CH7, 7); +slice!(PWM_SLICE0, 0); +slice!(PWM_SLICE1, 1); +slice!(PWM_SLICE2, 2); +slice!(PWM_SLICE3, 3); +slice!(PWM_SLICE4, 4); +slice!(PWM_SLICE5, 5); +slice!(PWM_SLICE6, 6); +slice!(PWM_SLICE7, 7); -/// PWM Pin A. -pub trait PwmPinA: GpioPin {} -/// PWM Pin B. -pub trait PwmPinB: GpioPin {} +#[cfg(feature = "_rp235x")] +slice!(PWM_SLICE8, 8); +#[cfg(feature = "_rp235x")] +slice!(PWM_SLICE9, 9); +#[cfg(feature = "_rp235x")] +slice!(PWM_SLICE10, 10); +#[cfg(feature = "_rp235x")] +slice!(PWM_SLICE11, 11); + +/// PWM Channel A. +pub trait ChannelAPin: GpioPin {} +/// PWM Channel B. +pub trait ChannelBPin: GpioPin {} macro_rules! impl_pin { ($pin:ident, $channel:ident, $kind:ident) => { @@ -346,33 +543,69 @@ macro_rules! impl_pin { }; } -impl_pin!(PIN_0, PWM_CH0, PwmPinA); -impl_pin!(PIN_1, PWM_CH0, PwmPinB); -impl_pin!(PIN_2, PWM_CH1, PwmPinA); -impl_pin!(PIN_3, PWM_CH1, PwmPinB); -impl_pin!(PIN_4, PWM_CH2, PwmPinA); -impl_pin!(PIN_5, PWM_CH2, PwmPinB); -impl_pin!(PIN_6, PWM_CH3, PwmPinA); -impl_pin!(PIN_7, PWM_CH3, PwmPinB); -impl_pin!(PIN_8, PWM_CH4, PwmPinA); -impl_pin!(PIN_9, PWM_CH4, PwmPinB); -impl_pin!(PIN_10, PWM_CH5, PwmPinA); -impl_pin!(PIN_11, PWM_CH5, PwmPinB); -impl_pin!(PIN_12, PWM_CH6, PwmPinA); -impl_pin!(PIN_13, PWM_CH6, PwmPinB); -impl_pin!(PIN_14, PWM_CH7, PwmPinA); -impl_pin!(PIN_15, PWM_CH7, PwmPinB); -impl_pin!(PIN_16, PWM_CH0, PwmPinA); -impl_pin!(PIN_17, PWM_CH0, PwmPinB); -impl_pin!(PIN_18, PWM_CH1, PwmPinA); -impl_pin!(PIN_19, PWM_CH1, PwmPinB); -impl_pin!(PIN_20, PWM_CH2, PwmPinA); -impl_pin!(PIN_21, PWM_CH2, PwmPinB); -impl_pin!(PIN_22, PWM_CH3, PwmPinA); -impl_pin!(PIN_23, PWM_CH3, PwmPinB); -impl_pin!(PIN_24, PWM_CH4, PwmPinA); -impl_pin!(PIN_25, PWM_CH4, PwmPinB); -impl_pin!(PIN_26, PWM_CH5, PwmPinA); -impl_pin!(PIN_27, PWM_CH5, PwmPinB); -impl_pin!(PIN_28, PWM_CH6, PwmPinA); -impl_pin!(PIN_29, PWM_CH6, PwmPinB); +impl_pin!(PIN_0, PWM_SLICE0, ChannelAPin); +impl_pin!(PIN_1, PWM_SLICE0, ChannelBPin); +impl_pin!(PIN_2, PWM_SLICE1, ChannelAPin); +impl_pin!(PIN_3, PWM_SLICE1, ChannelBPin); +impl_pin!(PIN_4, PWM_SLICE2, ChannelAPin); +impl_pin!(PIN_5, PWM_SLICE2, ChannelBPin); +impl_pin!(PIN_6, PWM_SLICE3, ChannelAPin); +impl_pin!(PIN_7, PWM_SLICE3, ChannelBPin); +impl_pin!(PIN_8, PWM_SLICE4, ChannelAPin); +impl_pin!(PIN_9, PWM_SLICE4, ChannelBPin); +impl_pin!(PIN_10, PWM_SLICE5, ChannelAPin); +impl_pin!(PIN_11, PWM_SLICE5, ChannelBPin); +impl_pin!(PIN_12, PWM_SLICE6, ChannelAPin); +impl_pin!(PIN_13, PWM_SLICE6, ChannelBPin); +impl_pin!(PIN_14, PWM_SLICE7, ChannelAPin); +impl_pin!(PIN_15, PWM_SLICE7, ChannelBPin); +impl_pin!(PIN_16, PWM_SLICE0, ChannelAPin); +impl_pin!(PIN_17, PWM_SLICE0, ChannelBPin); +impl_pin!(PIN_18, PWM_SLICE1, ChannelAPin); +impl_pin!(PIN_19, PWM_SLICE1, ChannelBPin); +impl_pin!(PIN_20, PWM_SLICE2, ChannelAPin); +impl_pin!(PIN_21, PWM_SLICE2, ChannelBPin); +impl_pin!(PIN_22, PWM_SLICE3, ChannelAPin); +impl_pin!(PIN_23, PWM_SLICE3, ChannelBPin); +impl_pin!(PIN_24, PWM_SLICE4, ChannelAPin); +impl_pin!(PIN_25, PWM_SLICE4, ChannelBPin); +impl_pin!(PIN_26, PWM_SLICE5, ChannelAPin); +impl_pin!(PIN_27, PWM_SLICE5, ChannelBPin); +impl_pin!(PIN_28, PWM_SLICE6, ChannelAPin); +impl_pin!(PIN_29, PWM_SLICE6, ChannelBPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_30, PWM_SLICE7, ChannelAPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_31, PWM_SLICE7, ChannelBPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_32, PWM_SLICE8, ChannelAPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_33, PWM_SLICE8, ChannelBPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_34, PWM_SLICE9, ChannelAPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_35, PWM_SLICE9, ChannelBPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_36, PWM_SLICE10, ChannelAPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_37, PWM_SLICE10, ChannelBPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_38, PWM_SLICE11, ChannelAPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_39, PWM_SLICE11, ChannelBPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_40, PWM_SLICE8, ChannelAPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_41, PWM_SLICE8, ChannelBPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_42, PWM_SLICE9, ChannelAPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_43, PWM_SLICE9, ChannelBPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_44, PWM_SLICE10, ChannelAPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_45, PWM_SLICE10, ChannelBPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_46, PWM_SLICE11, ChannelAPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_47, PWM_SLICE11, ChannelBPin); diff --git a/embassy-rp/src/relocate.rs b/embassy-rp/src/relocate.rs index b35b4ed72..34487819f 100644 --- a/embassy-rp/src/relocate.rs +++ b/embassy-rp/src/relocate.rs @@ -1,5 +1,3 @@ -use core::iter::Iterator; - use pio::{Program, SideSet, Wrap}; pub struct CodeIterator<'a, I> @@ -22,15 +20,15 @@ where { type Item = u16; fn next(&mut self) -> Option { - self.iter.next().and_then(|&instr| { - Some(if instr & 0b1110_0000_0000_0000 == 0 { + self.iter.next().map(|&instr| { + if instr & 0b1110_0000_0000_0000 == 0 { // this is a JMP instruction -> add offset to address let address = (instr & 0b1_1111) as u8; let address = address.wrapping_add(self.offset) % 32; instr & (!0b11111) | address as u16 } else { instr - }) + } }) } } diff --git a/embassy-rp/src/reset.rs b/embassy-rp/src/reset.rs index 70512fa14..4b9e42483 100644 --- a/embassy-rp/src/reset.rs +++ b/embassy-rp/src/reset.rs @@ -2,7 +2,7 @@ pub use pac::resets::regs::Peripherals; use crate::pac; -pub const ALL_PERIPHERALS: Peripherals = Peripherals(0x01ffffff); +pub const ALL_PERIPHERALS: Peripherals = Peripherals(0x01ff_ffff); pub(crate) fn reset(peris: Peripherals) { pac::RESETS.reset().write_value(peris); diff --git a/embassy-rp/src/rom_data/mod.rs b/embassy-rp/src/rom_data/mod.rs new file mode 100644 index 000000000..e5fcf8e3c --- /dev/null +++ b/embassy-rp/src/rom_data/mod.rs @@ -0,0 +1,33 @@ +#![cfg_attr( + feature = "rp2040", + doc = r" +//! Functions and data from the RPI Bootrom. +//! +//! From the [RP2040 datasheet](https://datasheets.raspberrypi.org/rp2040/rp2040-datasheet.pdf), Section 2.8.2.1: +//! +//! > The Bootrom contains a number of public functions that provide useful +//! > RP2040 functionality that might be needed in the absence of any other code +//! > on the device, as well as highly optimized versions of certain key +//! > functionality that would otherwise have to take up space in most user +//! > binaries. +" +)] +#![cfg_attr( + feature = "_rp235x", + doc = r" +//! Functions and data from the RPI Bootrom. +//! +//! From [Section 5.4](https://rptl.io/rp2350-datasheet#section_bootrom) of the +//! RP2350 datasheet: +//! +//! > Whilst some ROM space is dedicated to the implementation of the boot +//! > sequence and USB/UART boot interfaces, the bootrom also contains public +//! > functions that provide useful RP2350 functionality that may be useful for +//! > any code or runtime running on the device +" +)] + +#[cfg_attr(feature = "rp2040", path = "rp2040.rs")] +#[cfg_attr(feature = "_rp235x", path = "rp235x.rs")] +mod inner; +pub use inner::*; diff --git a/embassy-rp/src/rom_data.rs b/embassy-rp/src/rom_data/rp2040.rs similarity index 99% rename from embassy-rp/src/rom_data.rs rename to embassy-rp/src/rom_data/rp2040.rs index baebe5b6c..5a74eddd6 100644 --- a/embassy-rp/src/rom_data.rs +++ b/embassy-rp/src/rom_data/rp2040.rs @@ -189,7 +189,7 @@ macro_rules! rom_functions { declare_rom_function! { $(#[$outer])* fn $name( $($argname: $ty),* ) -> $ret { - $crate::rom_data::rom_table_lookup($crate::rom_data::FUNC_TABLE, *$c) + $crate::rom_data::inner::rom_table_lookup($crate::rom_data::inner::FUNC_TABLE, *$c) } } @@ -205,7 +205,7 @@ macro_rules! rom_functions { declare_rom_function! { $(#[$outer])* unsafe fn $name( $($argname: $ty),* ) -> $ret { - $crate::rom_data::rom_table_lookup($crate::rom_data::FUNC_TABLE, *$c) + $crate::rom_data::inner::rom_table_lookup($crate::rom_data::inner::FUNC_TABLE, *$c) } } diff --git a/embassy-rp/src/rom_data/rp235x.rs b/embassy-rp/src/rom_data/rp235x.rs new file mode 100644 index 000000000..b16fee8f7 --- /dev/null +++ b/embassy-rp/src/rom_data/rp235x.rs @@ -0,0 +1,752 @@ +//! Functions and data from the RPI Bootrom. +//! +//! From [Section 5.4](https://rptl.io/rp2350-datasheet#section_bootrom) of the +//! RP2350 datasheet: +//! +//! > Whilst some ROM space is dedicated to the implementation of the boot +//! > sequence and USB/UART boot interfaces, the bootrom also contains public +//! > functions that provide useful RP2350 functionality that may be useful for +//! > any code or runtime running on the device + +// Credit: taken from `rp-hal` (also licensed Apache+MIT) +// https://github.com/rp-rs/rp-hal/blob/main/rp235x-hal/src/rom_data.rs + +/// A bootrom function table code. +pub type RomFnTableCode = [u8; 2]; + +/// This function searches for the tag which matches the mask. +type RomTableLookupFn = unsafe extern "C" fn(code: u32, mask: u32) -> usize; + +/// Pointer to the value lookup function supplied by the ROM. +/// +/// This address is described at `5.5.1. Locating the API Functions` +#[cfg(all(target_arch = "arm", target_os = "none"))] +const ROM_TABLE_LOOKUP_A2: *const u16 = 0x0000_0016 as _; + +/// Pointer to the value lookup function supplied by the ROM. +/// +/// This address is described at `5.5.1. Locating the API Functions` +#[cfg(all(target_arch = "arm", target_os = "none"))] +const ROM_TABLE_LOOKUP_A1: *const u32 = 0x0000_0018 as _; + +/// Pointer to the data lookup function supplied by the ROM. +/// +/// On Arm, the same function is used to look up code and data. +#[cfg(all(target_arch = "arm", target_os = "none"))] +const ROM_DATA_LOOKUP_A2: *const u16 = ROM_TABLE_LOOKUP_A2; + +/// Pointer to the data lookup function supplied by the ROM. +/// +/// On Arm, the same function is used to look up code and data. +#[cfg(all(target_arch = "arm", target_os = "none"))] +const ROM_DATA_LOOKUP_A1: *const u32 = ROM_TABLE_LOOKUP_A1; + +/// Pointer to the value lookup function supplied by the ROM. +/// +/// This address is described at `5.5.1. Locating the API Functions` +#[cfg(not(all(target_arch = "arm", target_os = "none")))] +const ROM_TABLE_LOOKUP_A2: *const u16 = 0x0000_7DFA as _; + +/// Pointer to the value lookup function supplied by the ROM. +/// +/// This address is described at `5.5.1. Locating the API Functions` +#[cfg(not(all(target_arch = "arm", target_os = "none")))] +const ROM_TABLE_LOOKUP_A1: *const u32 = 0x0000_7DF8 as _; + +/// Pointer to the data lookup function supplied by the ROM. +/// +/// On RISC-V, a different function is used to look up data. +#[cfg(not(all(target_arch = "arm", target_os = "none")))] +const ROM_DATA_LOOKUP_A2: *const u16 = 0x0000_7DF8 as _; + +/// Pointer to the data lookup function supplied by the ROM. +/// +/// On RISC-V, a different function is used to look up data. +#[cfg(not(all(target_arch = "arm", target_os = "none")))] +const ROM_DATA_LOOKUP_A1: *const u32 = 0x0000_7DF4 as _; + +/// Address of the version number of the ROM. +const VERSION_NUMBER: *const u8 = 0x0000_0013 as _; + +#[allow(unused)] +mod rt_flags { + pub const FUNC_RISCV: u32 = 0x0001; + pub const FUNC_RISCV_FAR: u32 = 0x0003; + pub const FUNC_ARM_SEC: u32 = 0x0004; + // reserved for 32-bit pointer: 0x0008 + pub const FUNC_ARM_NONSEC: u32 = 0x0010; + // reserved for 32-bit pointer: 0x0020 + pub const DATA: u32 = 0x0040; + // reserved for 32-bit pointer: 0x0080 + #[cfg(all(target_arch = "arm", target_os = "none"))] + pub const FUNC_ARM_SEC_RISCV: u32 = FUNC_ARM_SEC; + #[cfg(not(all(target_arch = "arm", target_os = "none")))] + pub const FUNC_ARM_SEC_RISCV: u32 = FUNC_RISCV; +} + +/// Retrieve rom content from a table using a code. +pub fn rom_table_lookup(tag: RomFnTableCode, mask: u32) -> usize { + let tag = u16::from_le_bytes(tag) as u32; + unsafe { + let lookup_func = if rom_version_number() == 1 { + ROM_TABLE_LOOKUP_A1.read() as usize + } else { + ROM_TABLE_LOOKUP_A2.read() as usize + }; + let lookup_func: RomTableLookupFn = core::mem::transmute(lookup_func); + lookup_func(tag, mask) + } +} + +/// Retrieve rom data content from a table using a code. +pub fn rom_data_lookup(tag: RomFnTableCode, mask: u32) -> usize { + let tag = u16::from_le_bytes(tag) as u32; + unsafe { + let lookup_func = if rom_version_number() == 1 { + ROM_DATA_LOOKUP_A1.read() as usize + } else { + ROM_DATA_LOOKUP_A2.read() as usize + }; + let lookup_func: RomTableLookupFn = core::mem::transmute(lookup_func); + lookup_func(tag, mask) + } +} + +macro_rules! declare_rom_function { + ( + $(#[$outer:meta])* + fn $name:ident( $($argname:ident: $ty:ty),* ) -> $ret:ty + $lookup:block + ) => { + #[doc = r"Additional access for the `"] + #[doc = stringify!($name)] + #[doc = r"` ROM function."] + pub mod $name { + /// Retrieve a function pointer. + #[cfg(not(feature = "rom-func-cache"))] + pub fn ptr() -> extern "C" fn( $($argname: $ty),* ) -> $ret { + let p: usize = $lookup; + unsafe { + let func : extern "C" fn( $($argname: $ty),* ) -> $ret = core::mem::transmute(p); + func + } + } + + /// Retrieve a function pointer. + #[cfg(feature = "rom-func-cache")] + pub fn ptr() -> extern "C" fn( $($argname: $ty),* ) -> $ret { + use core::sync::atomic::{AtomicU16, Ordering}; + + // All pointers in the ROM fit in 16 bits, so we don't need a + // full width word to store the cached value. + static CACHED_PTR: AtomicU16 = AtomicU16::new(0); + // This is safe because the lookup will always resolve + // to the same value. So even if an interrupt or another + // core starts at the same time, it just repeats some + // work and eventually writes back the correct value. + let p: usize = match CACHED_PTR.load(Ordering::Relaxed) { + 0 => { + let raw: usize = $lookup; + CACHED_PTR.store(raw as u16, Ordering::Relaxed); + raw + }, + val => val as usize, + }; + unsafe { + let func : extern "C" fn( $($argname: $ty),* ) -> $ret = core::mem::transmute(p); + func + } + } + } + + $(#[$outer])* + pub extern "C" fn $name( $($argname: $ty),* ) -> $ret { + $name::ptr()($($argname),*) + } + }; + + ( + $(#[$outer:meta])* + unsafe fn $name:ident( $($argname:ident: $ty:ty),* ) -> $ret:ty + $lookup:block + ) => { + #[doc = r"Additional access for the `"] + #[doc = stringify!($name)] + #[doc = r"` ROM function."] + pub mod $name { + /// Retrieve a function pointer. + #[cfg(not(feature = "rom-func-cache"))] + pub fn ptr() -> unsafe extern "C" fn( $($argname: $ty),* ) -> $ret { + let p: usize = $lookup; + unsafe { + let func : unsafe extern "C" fn( $($argname: $ty),* ) -> $ret = core::mem::transmute(p); + func + } + } + + /// Retrieve a function pointer. + #[cfg(feature = "rom-func-cache")] + pub fn ptr() -> unsafe extern "C" fn( $($argname: $ty),* ) -> $ret { + use core::sync::atomic::{AtomicU16, Ordering}; + + // All pointers in the ROM fit in 16 bits, so we don't need a + // full width word to store the cached value. + static CACHED_PTR: AtomicU16 = AtomicU16::new(0); + // This is safe because the lookup will always resolve + // to the same value. So even if an interrupt or another + // core starts at the same time, it just repeats some + // work and eventually writes back the correct value. + let p: usize = match CACHED_PTR.load(Ordering::Relaxed) { + 0 => { + let raw: usize = $lookup; + CACHED_PTR.store(raw as u16, Ordering::Relaxed); + raw + }, + val => val as usize, + }; + unsafe { + let func : unsafe extern "C" fn( $($argname: $ty),* ) -> $ret = core::mem::transmute(p); + func + } + } + } + + $(#[$outer])* + /// # Safety + /// + /// This is a low-level C function. It may be difficult to call safely from + /// Rust. If in doubt, check the rp235x datasheet for details and do your own + /// safety evaluation. + pub unsafe extern "C" fn $name( $($argname: $ty),* ) -> $ret { + $name::ptr()($($argname),*) + } + }; +} + +// **************** 5.5.7 Low-level Flash Commands **************** + +declare_rom_function! { + /// Restore all QSPI pad controls to their default state, and connect the + /// QMI peripheral to the QSPI pads. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn connect_internal_flash() -> () { + crate::rom_data::rom_table_lookup(*b"IF", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Initialise the QMI for serial operations (direct mode) + /// + /// Also initialise a basic XIP mode, where the QMI will perform 03h serial + /// read commands at low speed (CLKDIV=12) in response to XIP reads. + /// + /// Then, issue a sequence to the QSPI device on chip select 0, designed to + /// return it from continuous read mode ("XIP mode") and/or QPI mode to a + /// state where it will accept serial commands. This is necessary after + /// system reset to restore the QSPI device to a known state, because + /// resetting RP2350 does not reset attached QSPI devices. It is also + /// necessary when user code, having already performed some + /// continuous-read-mode or QPI-mode accesses, wishes to return the QSPI + /// device to a state where it will accept the serial erase and programming + /// commands issued by the bootrom’s flash access functions. + /// + /// If a GPIO for the secondary chip select is configured via FLASH_DEVINFO, + /// then the XIP exit sequence is also issued to chip select 1. + /// + /// The QSPI device should be accessible for XIP reads after calling this + /// function; the name flash_exit_xip refers to returning the QSPI device + /// from its XIP state to a serial command state. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn flash_exit_xip() -> () { + crate::rom_data::rom_table_lookup(*b"EX", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Erase count bytes, starting at addr (offset from start of flash). + /// + /// Optionally, pass a block erase command e.g. D8h block erase, and the + /// size of the block erased by this command — this function will use the + /// larger block erase where possible, for much higher erase speed. addr + /// must be aligned to a 4096-byte sector, and count must be a multiple of + /// 4096 bytes. + /// + /// This is a low-level flash API, and no validation of the arguments is + /// performed. See flash_op() for a higher-level API which checks alignment, + /// flash bounds and partition permissions, and can transparently apply a + /// runtime-to-storage address translation. + /// + /// The QSPI device must be in a serial command state before calling this + /// API, which can be achieved by calling connect_internal_flash() followed + /// by flash_exit_xip(). After the erase, the flash cache should be flushed + /// via flash_flush_cache() to ensure the modified flash data is visible to + /// cached XIP accesses. + /// + /// Finally, the original XIP mode should be restored by copying the saved + /// XIP setup function from bootram into SRAM, and executing it: the bootrom + /// provides a default function which restores the flash mode/clkdiv + /// discovered during flash scanning, and user programs can override this + /// with their own XIP setup function. + /// + /// For the duration of the erase operation, QMI is in direct mode (Section + /// 12.14.5) and attempting to access XIP from DMA, the debugger or the + /// other core will return a bus fault. XIP becomes accessible again once + /// the function returns. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn flash_range_erase(addr: u32, count: usize, block_size: u32, block_cmd: u8) -> () { + crate::rom_data::rom_table_lookup(*b"RE", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Program data to a range of flash storage addresses starting at addr + /// (offset from the start of flash) and count bytes in size. + /// + /// `addr` must be aligned to a 256-byte boundary, and count must be a + /// multiple of 256. + /// + /// This is a low-level flash API, and no validation of the arguments is + /// performed. See flash_op() for a higher-level API which checks alignment, + /// flash bounds and partition permissions, and can transparently apply a + /// runtime-to-storage address translation. + /// + /// The QSPI device must be in a serial command state before calling this + /// API — see notes on flash_range_erase(). + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn flash_range_program(addr: u32, data: *const u8, count: usize) -> () { + crate::rom_data::rom_table_lookup(*b"RP", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Flush the entire XIP cache, by issuing an invalidate by set/way + /// maintenance operation to every cache line (Section 4.4.1). + /// + /// This ensures that flash program/erase operations are visible to + /// subsequent cached XIP reads. + /// + /// Note that this unpins pinned cache lines, which may interfere with + /// cache-as-SRAM use of the XIP cache. + /// + /// No other operations are performed. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn flash_flush_cache() -> () { + crate::rom_data::rom_table_lookup(*b"FC", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Configure the QMI to generate a standard 03h serial read command, with + /// 24 address bits, upon each XIP access. + /// + /// This is a slow XIP configuration, but is widely supported. CLKDIV is set + /// to 12. The debugger may call this function to ensure that flash is + /// readable following a program/erase operation. + /// + /// Note that the same setup is performed by flash_exit_xip(), and the + /// RP2350 flash program/erase functions do not leave XIP in an inaccessible + /// state, so calls to this function are largely redundant. It is provided + /// for compatibility with RP2040. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn flash_enter_cmd_xip() -> () { + crate::rom_data::rom_table_lookup(*b"CX", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Configure QMI for one of a small menu of XIP read modes supported by the + /// bootrom. This mode is configured for both memory windows (both chip + /// selects), and the clock divisor is also applied to direct mode. + /// + /// The available modes are: + /// + /// * 0: `03h` serial read: serial address, serial data, no wait cycles + /// * 1: `0Bh` serial read: serial address, serial data, 8 wait cycles + /// * 2: `BBh` dual-IO read: dual address, dual data, 4 wait cycles + /// (including MODE bits, which are driven to 0) + /// * 3: `EBh` quad-IO read: quad address, quad data, 6 wait cycles + /// (including MODE bits, which are driven to 0) + /// + /// The XIP write command/format are not configured by this function. When + /// booting from flash, the bootrom tries each of these modes in turn, from + /// 3 down to 0. The first mode that is found to work is remembered, and a + /// default XIP setup function is written into bootram that calls this + /// function (flash_select_xip_read_mode) with the parameters discovered + /// during flash scanning. This can be called at any time to restore the + /// flash parameters discovered during flash boot. + /// + /// All XIP modes configured by the bootrom have an 8-bit serial command + /// prefix, so that the flash can remain in a serial command state, meaning + /// XIP accesses can be mixed more freely with program/erase serial + /// operations. This has a performance penalty, so users can perform their + /// own flash setup after flash boot using continuous read mode or QPI mode + /// to avoid or alleviate the command prefix cost. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn flash_select_xip_read_mode(bootrom_xip_mode: u8, clkdiv: u8) -> () { + crate::rom_data::rom_table_lookup(*b"XM", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Restore the QMI address translation registers, ATRANS0 through ATRANS7, + /// to their reset state. This makes the runtime- to-storage address map an + /// identity map, i.e. the mapped and unmapped address are equal, and the + /// entire space is fully mapped. + /// + /// See [Section 12.14.4](https://rptl.io/rp2350-datasheet#section_bootrom) of the RP2350 + /// datasheet. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn flash_reset_address_trans() -> () { + crate::rom_data::rom_table_lookup(*b"RA", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +// **************** High-level Flash Commands **************** + +declare_rom_function! { + /// Applies the address translation currently configured by QMI address + /// translation registers, ATRANS0 through ATRANS7. + /// + /// See [Section 12.14.4](https://rptl.io/rp2350-datasheet#section_bootrom) of the RP2350 + /// datasheet. + /// + /// Translating an address outside of the XIP runtime address window, or + /// beyond the bounds of an ATRANSx_SIZE field, returns + /// BOOTROM_ERROR_INVALID_ADDRESS, which is not a valid flash storage + /// address. Otherwise, return the storage address which QMI would access + /// when presented with the runtime address addr. This is effectively a + /// virtual-to-physical address translation for QMI. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn flash_runtime_to_storage_addr(addr: u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"FA", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Non-secure version of [flash_runtime_to_storage_addr()] + /// + /// Supported architectures: ARM-NS + #[cfg(all(target_arch = "arm", target_os = "none"))] + unsafe fn flash_runtime_to_storage_addr_ns(addr: u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"FA", crate::rom_data::inner::rt_flags::FUNC_ARM_NONSEC) + } +} + +declare_rom_function! { + /// Perform a flash read, erase, or program operation. + /// + /// Erase operations must be sector-aligned (4096 bytes) and sector- + /// multiple-sized, and program operations must be page-aligned (256 bytes) + /// and page-multiple-sized; misaligned erase and program operations will + /// return BOOTROM_ERROR_BAD_ALIGNMENT. The operation — erase, read, program + /// — is selected by the CFLASH_OP_BITS bitfield of the flags argument. + /// + /// See datasheet section 5.5.8.2 for more details. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn flash_op(flags: u32, addr: u32, size_bytes: u32, buffer: *mut u8) -> i32 { + crate::rom_data::rom_table_lookup(*b"FO", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Non-secure version of [flash_op()] + /// + /// Supported architectures: ARM-NS + #[cfg(all(target_arch = "arm", target_os = "none"))] + unsafe fn flash_op_ns(flags: u32, addr: u32, size_bytes: u32, buffer: *mut u8) -> i32 { + crate::rom_data::rom_table_lookup(*b"FO", crate::rom_data::inner::rt_flags::FUNC_ARM_NONSEC) + } +} + +// **************** Security Related Functions **************** + +declare_rom_function! { + /// Allow or disallow the specific NS API (note all NS APIs default to + /// disabled). + /// + /// See datasheet section 5.5.9.1 for more details. + /// + /// Supported architectures: ARM-S + #[cfg(all(target_arch = "arm", target_os = "none"))] + unsafe fn set_ns_api_permission(ns_api_num: u32, allowed: u8) -> i32 { + crate::rom_data::rom_table_lookup(*b"SP", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC) + } +} + +declare_rom_function! { + /// Utility method that can be used by secure ARM code to validate a buffer + /// passed to it from Non-secure code. + /// + /// See datasheet section 5.5.9.2 for more details. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn validate_ns_buffer() -> () { + crate::rom_data::rom_table_lookup(*b"VB", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +// **************** Miscellaneous Functions **************** + +declare_rom_function! { + /// Resets the RP2350 and uses the watchdog facility to restart. + /// + /// See datasheet section 5.5.10.1 for more details. + /// + /// Supported architectures: ARM-S, RISC-V + fn reboot(flags: u32, delay_ms: u32, p0: u32, p1: u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"RB", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Non-secure version of [reboot()] + /// + /// Supported architectures: ARM-NS + #[cfg(all(target_arch = "arm", target_os = "none"))] + fn reboot_ns(flags: u32, delay_ms: u32, p0: u32, p1: u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"RB", crate::rom_data::inner::rt_flags::FUNC_ARM_NONSEC) + } +} + +declare_rom_function! { + /// Resets internal bootrom state. + /// + /// See datasheet section 5.5.10.2 for more details. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn bootrom_state_reset(flags: u32) -> () { + crate::rom_data::rom_table_lookup(*b"SR", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Set a boot ROM callback. + /// + /// The only supported callback_number is 0 which sets the callback used for + /// the secure_call API. + /// + /// See datasheet section 5.5.10.3 for more details. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn set_rom_callback(callback_number: i32, callback_fn: *const ()) -> i32 { + crate::rom_data::rom_table_lookup(*b"RC", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +// **************** System Information Functions **************** + +declare_rom_function! { + /// Fills a buffer with various system information. + /// + /// Note that this API is also used to return information over the PICOBOOT + /// interface. + /// + /// See datasheet section 5.5.11.1 for more details. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn get_sys_info(out_buffer: *mut u32, out_buffer_word_size: usize, flags: u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"GS", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Non-secure version of [get_sys_info()] + /// + /// Supported architectures: ARM-NS + #[cfg(all(target_arch = "arm", target_os = "none"))] + unsafe fn get_sys_info_ns(out_buffer: *mut u32, out_buffer_word_size: usize, flags: u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"GS", crate::rom_data::inner::rt_flags::FUNC_ARM_NONSEC) + } +} + +declare_rom_function! { + /// Fills a buffer with information from the partition table. + /// + /// Note that this API is also used to return information over the PICOBOOT + /// interface. + /// + /// See datasheet section 5.5.11.2 for more details. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn get_partition_table_info(out_buffer: *mut u32, out_buffer_word_size: usize, flags_and_partition: u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"GP", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Non-secure version of [get_partition_table_info()] + /// + /// Supported architectures: ARM-NS + #[cfg(all(target_arch = "arm", target_os = "none"))] + unsafe fn get_partition_table_info_ns(out_buffer: *mut u32, out_buffer_word_size: usize, flags_and_partition: u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"GP", crate::rom_data::inner::rt_flags::FUNC_ARM_NONSEC) + } +} + +declare_rom_function! { + /// Loads the current partition table from flash, if present. + /// + /// See datasheet section 5.5.11.3 for more details. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn load_partition_table(workarea_base: *mut u8, workarea_size: usize, force_reload: bool) -> i32 { + crate::rom_data::rom_table_lookup(*b"LP", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Writes data from a buffer into OTP, or reads data from OTP into a buffer. + /// + /// See datasheet section 5.5.11.4 for more details. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn otp_access(buf: *mut u8, buf_len: usize, row_and_flags: u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"OA", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Non-secure version of [otp_access()] + /// + /// Supported architectures: ARM-NS + #[cfg(all(target_arch = "arm", target_os = "none"))] + unsafe fn otp_access_ns(buf: *mut u8, buf_len: usize, row_and_flags: u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"OA", crate::rom_data::inner::rt_flags::FUNC_ARM_NONSEC) + } +} + +// **************** Boot Related Functions **************** + +declare_rom_function! { + /// Determines which of the partitions has the "better" IMAGE_DEF. In the + /// case of executable images, this is the one that would be booted. + /// + /// See datasheet section 5.5.12.1 for more details. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn pick_ab_parition(workarea_base: *mut u8, workarea_size: usize, partition_a_num: u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"AB", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Searches a memory region for a launchable image, and executes it if + /// possible. + /// + /// See datasheet section 5.5.12.2 for more details. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn chain_image(workarea_base: *mut u8, workarea_size: usize, region_base: i32, region_size: u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"CI", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Perform an "explicit" buy of an executable launched via an IMAGE_DEF + /// which was "explicit buy" flagged. + /// + /// See datasheet section 5.5.12.3 for more details. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn explicit_buy(buffer: *mut u8, buffer_size: u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"EB", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Not yet documented. + /// + /// See datasheet section 5.5.12.4 for more details. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn get_uf2_target_partition(workarea_base: *mut u8, workarea_size: usize, family_id: u32, partition_out: *mut u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"GU", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +declare_rom_function! { + /// Returns: The index of the B partition of partition A if a partition + /// table is present and loaded, and there is a partition A with a B + /// partition; otherwise returns BOOTROM_ERROR_NOT_FOUND. + /// + /// See datasheet section 5.5.12.5 for more details. + /// + /// Supported architectures: ARM-S, RISC-V + unsafe fn get_b_partition(partition_a: u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"GB", crate::rom_data::inner::rt_flags::FUNC_ARM_SEC_RISCV) + } +} + +// **************** Non-secure-specific Functions **************** + +// NB: The "secure_call" function should be here, but it doesn't have a fixed +// function signature as it is designed to let you bounce into any secure +// function from non-secure mode. + +// **************** RISC-V Functions **************** + +declare_rom_function! { + /// Set stack for RISC-V bootrom functions to use. + /// + /// See datasheet section 5.5.14.1 for more details. + /// + /// Supported architectures: RISC-V + #[cfg(not(all(target_arch = "arm", target_os = "none")))] + unsafe fn set_bootrom_stack(base_size: *mut u32) -> i32 { + crate::rom_data::rom_table_lookup(*b"SS", crate::rom_data::inner::rt_flags::FUNC_RISCV) + } +} + +/// The version number of the rom. +pub fn rom_version_number() -> u8 { + unsafe { *VERSION_NUMBER } +} + +/// The 8 most significant hex digits of the Bootrom git revision. +pub fn git_revision() -> u32 { + let ptr = rom_data_lookup(*b"GR", rt_flags::DATA) as *const u32; + unsafe { ptr.read() } +} + +/// A pointer to the resident partition table info. +/// +/// The resident partition table is the subset of the full partition table that +/// is kept in memory, and used for flash permissions. +pub fn partition_table_pointer() -> *const u32 { + let ptr = rom_data_lookup(*b"PT", rt_flags::DATA) as *const *const u32; + unsafe { ptr.read() } +} + +/// Determine if we are in secure mode +/// +/// Returns `true` if we are in secure mode and `false` if we are in non-secure +/// mode. +#[cfg(all(target_arch = "arm", target_os = "none"))] +pub fn is_secure_mode() -> bool { + // Look at the start of ROM, which is always readable + #[allow(clippy::zero_ptr)] + let rom_base: *mut u32 = 0x0000_0000 as *mut u32; + // Use the 'tt' instruction to check the permissions for that address + let tt = cortex_m::asm::tt(rom_base); + // Is the secure bit set? => secure mode + (tt & (1 << 22)) != 0 +} + +/// Determine if we are in secure mode +/// +/// Always returns `false` on RISC-V as it is impossible to determine if +/// you are in Machine Mode or User Mode by design. +#[cfg(not(all(target_arch = "arm", target_os = "none")))] +pub fn is_secure_mode() -> bool { + false +} diff --git a/embassy-rp/src/rtc/datetime_chrono.rs b/embassy-rp/src/rtc/datetime_chrono.rs index b3c78dd47..2818e46af 100644 --- a/embassy-rp/src/rtc/datetime_chrono.rs +++ b/embassy-rp/src/rtc/datetime_chrono.rs @@ -10,7 +10,7 @@ pub type DayOfWeek = chrono::Weekday; /// Errors regarding the [`DateTime`] and [`DateTimeFilter`] structs. /// /// [`DateTimeFilter`]: struct.DateTimeFilter.html -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Error { /// The [DateTime] has an invalid year. The year must be between 0 and 4095. InvalidYear, diff --git a/embassy-rp/src/rtc/datetime_no_deps.rs b/embassy-rp/src/rtc/datetime_no_deps.rs index ea899c339..5de00e6b4 100644 --- a/embassy-rp/src/rtc/datetime_no_deps.rs +++ b/embassy-rp/src/rtc/datetime_no_deps.rs @@ -3,7 +3,7 @@ use crate::pac::rtc::regs::{Rtc0, Rtc1, Setup0, Setup1}; /// Errors regarding the [`DateTime`] and [`DateTimeFilter`] structs. /// /// [`DateTimeFilter`]: struct.DateTimeFilter.html -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Error { /// The [DateTime] contains an invalid year value. Must be between `0..=4095`. InvalidYear, diff --git a/embassy-rp/src/rtc/mod.rs b/embassy-rp/src/rtc/mod.rs index b696989f5..2ce7ac645 100644 --- a/embassy-rp/src/rtc/mod.rs +++ b/embassy-rp/src/rtc/mod.rs @@ -29,8 +29,7 @@ impl<'d, T: Instance> Rtc<'d, T> { // Set the RTC divider inner.regs().clkdiv_m1().write(|w| w.set_clkdiv_m1(clk_rtc_freq() - 1)); - let result = Self { inner }; - result + Self { inner } } /// Enable or disable the leap year check. The rp2040 chip will always add a Feb 29th on every year that is divisable by 4, but this may be incorrect (e.g. on century years). This function allows you to disable this check. @@ -189,16 +188,15 @@ pub enum RtcError { NotRunning, } -mod sealed { - pub trait Instance { - fn regs(&self) -> crate::pac::rtc::Rtc; - } +trait SealedInstance { + fn regs(&self) -> crate::pac::rtc::Rtc; } /// RTC peripheral instance. -pub trait Instance: sealed::Instance {} +#[allow(private_bounds)] +pub trait Instance: SealedInstance {} -impl sealed::Instance for crate::peripherals::RTC { +impl SealedInstance for crate::peripherals::RTC { fn regs(&self) -> crate::pac::rtc::Rtc { crate::pac::RTC } diff --git a/embassy-rp/src/spi.rs b/embassy-rp/src/spi.rs index a2a22ffe5..a8f4e72c7 100644 --- a/embassy-rp/src/spi.rs +++ b/embassy-rp/src/spi.rs @@ -7,8 +7,7 @@ use embassy_hal_internal::{into_ref, PeripheralRef}; pub use embedded_hal_02::spi::{Phase, Polarity}; use crate::dma::{AnyChannel, Channel}; -use crate::gpio::sealed::Pin as _; -use crate::gpio::{AnyPin, Pin as GpioPin}; +use crate::gpio::{AnyPin, Pin as GpioPin, SealedPin as _}; use crate::{pac, peripherals, Peripheral}; /// SPI errors. @@ -107,15 +106,55 @@ impl<'d, T: Instance, M: Mode> Spi<'d, T, M> { if let Some(pin) = &clk { pin.gpio().ctrl().write(|w| w.set_funcsel(1)); + pin.pad_ctrl().write(|w| { + #[cfg(feature = "_rp235x")] + w.set_iso(false); + w.set_schmitt(true); + w.set_slewfast(false); + w.set_ie(true); + w.set_od(false); + w.set_pue(false); + w.set_pde(false); + }); } if let Some(pin) = &mosi { pin.gpio().ctrl().write(|w| w.set_funcsel(1)); + pin.pad_ctrl().write(|w| { + #[cfg(feature = "_rp235x")] + w.set_iso(false); + w.set_schmitt(true); + w.set_slewfast(false); + w.set_ie(true); + w.set_od(false); + w.set_pue(false); + w.set_pde(false); + }); } if let Some(pin) = &miso { pin.gpio().ctrl().write(|w| w.set_funcsel(1)); + pin.pad_ctrl().write(|w| { + #[cfg(feature = "_rp235x")] + w.set_iso(false); + w.set_schmitt(true); + w.set_slewfast(false); + w.set_ie(true); + w.set_od(false); + w.set_pue(false); + w.set_pde(false); + }); } if let Some(pin) = &cs { pin.gpio().ctrl().write(|w| w.set_funcsel(1)); + pin.pad_ctrl().write(|w| { + #[cfg(feature = "_rp235x")] + w.set_iso(false); + w.set_schmitt(true); + w.set_slewfast(false); + w.set_ie(true); + w.set_od(false); + w.set_pue(false); + w.set_pde(false); + }); } Self { inner, @@ -320,17 +359,18 @@ impl<'d, T: Instance> Spi<'d, T, Async> { inner: impl Peripheral

+ 'd, clk: impl Peripheral

+ 'd> + 'd, miso: impl Peripheral

+ 'd> + 'd, + tx_dma: impl Peripheral

+ 'd, rx_dma: impl Peripheral

+ 'd, config: Config, ) -> Self { - into_ref!(rx_dma, clk, miso); + into_ref!(tx_dma, rx_dma, clk, miso); Self::new_inner( inner, Some(clk.map_into()), None, Some(miso.map_into()), None, - None, + Some(tx_dma.map_into()), Some(rx_dma.map_into()), config, ) @@ -395,17 +435,14 @@ impl<'d, T: Instance> Spi<'d, T, Async> { self.transfer_inner(words, words).await } - async fn transfer_inner(&mut self, rx_ptr: *mut [u8], tx_ptr: *const [u8]) -> Result<(), Error> { - let (_, tx_len) = crate::dma::slice_ptr_parts(tx_ptr); - let (_, rx_len) = crate::dma::slice_ptr_parts_mut(rx_ptr); - + async fn transfer_inner(&mut self, rx: *mut [u8], tx: *const [u8]) -> Result<(), Error> { // Start RX first. Transfer starts when TX starts, if RX // is not started yet we might lose bytes. let rx_ch = self.rx_dma.as_mut().unwrap(); let rx_transfer = unsafe { // If we don't assign future to a variable, the data register pointer // is held across an await and makes the future non-Send. - crate::dma::read(rx_ch, self.inner.regs().dr().as_ptr() as *const _, rx_ptr, T::RX_DREQ) + crate::dma::read(rx_ch, self.inner.regs().dr().as_ptr() as *const _, rx, T::RX_DREQ) }; let mut tx_ch = self.tx_dma.as_mut().unwrap(); @@ -414,10 +451,10 @@ impl<'d, T: Instance> Spi<'d, T, Async> { let tx_transfer = async { let p = self.inner.regs(); unsafe { - crate::dma::write(&mut tx_ch, tx_ptr, p.dr().as_ptr() as *mut _, T::TX_DREQ).await; + crate::dma::write(&mut tx_ch, tx, p.dr().as_ptr() as *mut _, T::TX_DREQ).await; - if rx_len > tx_len { - let write_bytes_len = rx_len - tx_len; + if rx.len() > tx.len() { + let write_bytes_len = rx.len() - tx.len(); // write dummy data // this will disable incrementation of the buffers crate::dma::write_repeated(tx_ch, p.dr().as_ptr() as *mut u8, write_bytes_len, T::TX_DREQ).await @@ -427,7 +464,7 @@ impl<'d, T: Instance> Spi<'d, T, Async> { join(tx_transfer, rx_transfer).await; // if tx > rx we should clear any overflow of the FIFO SPI buffer - if tx_len > rx_len { + if tx.len() > rx.len() { let p = self.inner.regs(); while p.sr().read().bsy() {} @@ -443,30 +480,28 @@ impl<'d, T: Instance> Spi<'d, T, Async> { } } -mod sealed { - use super::*; +trait SealedMode {} - pub trait Mode {} +trait SealedInstance { + const TX_DREQ: pac::dma::vals::TreqSel; + const RX_DREQ: pac::dma::vals::TreqSel; - pub trait Instance { - const TX_DREQ: u8; - const RX_DREQ: u8; - - fn regs(&self) -> pac::spi::Spi; - } + fn regs(&self) -> pac::spi::Spi; } /// Mode. -pub trait Mode: sealed::Mode {} +#[allow(private_bounds)] +pub trait Mode: SealedMode {} /// SPI instance trait. -pub trait Instance: sealed::Instance {} +#[allow(private_bounds)] +pub trait Instance: SealedInstance {} macro_rules! impl_instance { ($type:ident, $irq:ident, $tx_dreq:expr, $rx_dreq:expr) => { - impl sealed::Instance for peripherals::$type { - const TX_DREQ: u8 = $tx_dreq; - const RX_DREQ: u8 = $rx_dreq; + impl SealedInstance for peripherals::$type { + const TX_DREQ: pac::dma::vals::TreqSel = $tx_dreq; + const RX_DREQ: pac::dma::vals::TreqSel = $rx_dreq; fn regs(&self) -> pac::spi::Spi { pac::$type @@ -476,8 +511,18 @@ macro_rules! impl_instance { }; } -impl_instance!(SPI0, Spi0, 16, 17); -impl_instance!(SPI1, Spi1, 18, 19); +impl_instance!( + SPI0, + Spi0, + pac::dma::vals::TreqSel::SPI0_TX, + pac::dma::vals::TreqSel::SPI0_RX +); +impl_instance!( + SPI1, + Spi1, + pac::dma::vals::TreqSel::SPI1_TX, + pac::dma::vals::TreqSel::SPI1_RX +); /// CLK pin. pub trait ClkPin: GpioPin {} @@ -524,10 +569,46 @@ impl_pin!(PIN_26, SPI1, ClkPin); impl_pin!(PIN_27, SPI1, MosiPin); impl_pin!(PIN_28, SPI1, MisoPin); impl_pin!(PIN_29, SPI1, CsPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_30, SPI1, ClkPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_31, SPI1, MosiPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_32, SPI0, MisoPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_33, SPI0, CsPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_34, SPI0, ClkPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_35, SPI0, MosiPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_36, SPI0, MisoPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_37, SPI0, CsPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_38, SPI0, ClkPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_39, SPI0, MosiPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_40, SPI1, MisoPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_41, SPI1, CsPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_42, SPI1, ClkPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_43, SPI1, MosiPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_44, SPI1, MisoPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_45, SPI1, CsPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_46, SPI1, ClkPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_47, SPI1, MosiPin); macro_rules! impl_mode { ($name:ident) => { - impl sealed::Mode for $name {} + impl SealedMode for $name {} impl Mode for $name {} }; } diff --git a/embassy-rp/src/time_driver.rs b/embassy-rp/src/time_driver.rs index bab1044cb..e5b407a29 100644 --- a/embassy-rp/src/time_driver.rs +++ b/embassy-rp/src/time_driver.rs @@ -6,6 +6,10 @@ use critical_section::CriticalSection; use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; use embassy_sync::blocking_mutex::Mutex; use embassy_time_driver::{AlarmHandle, Driver}; +#[cfg(feature = "rp2040")] +use pac::TIMER; +#[cfg(feature = "_rp235x")] +use pac::TIMER0 as TIMER; use crate::interrupt::InterruptExt; use crate::{interrupt, pac}; @@ -35,9 +39,9 @@ embassy_time_driver::time_driver_impl!(static DRIVER: TimerDriver = TimerDriver{ impl Driver for TimerDriver { fn now(&self) -> u64 { loop { - let hi = pac::TIMER.timerawh().read(); - let lo = pac::TIMER.timerawl().read(); - let hi2 = pac::TIMER.timerawh().read(); + let hi = TIMER.timerawh().read(); + let lo = TIMER.timerawl().read(); + let hi2 = TIMER.timerawh().read(); if hi == hi2 { return (hi as u64) << 32 | (lo as u64); } @@ -77,13 +81,13 @@ impl Driver for TimerDriver { // Note that we're not checking the high bits at all. This means the irq may fire early // if the alarm is more than 72 minutes (2^32 us) in the future. This is OK, since on irq fire // it is checked if the alarm time has passed. - pac::TIMER.alarm(n).write_value(timestamp as u32); + TIMER.alarm(n).write_value(timestamp as u32); let now = self.now(); if timestamp <= now { // If alarm timestamp has passed the alarm will not fire. // Disarm the alarm and return `false` to indicate that. - pac::TIMER.armed().write(|w| w.set_armed(1 << n)); + TIMER.armed().write(|w| w.set_armed(1 << n)); alarm.timestamp.set(u64::MAX); @@ -105,17 +109,17 @@ impl TimerDriver { } else { // Not elapsed, arm it again. // This can happen if it was set more than 2^32 us in the future. - pac::TIMER.alarm(n).write_value(timestamp as u32); + TIMER.alarm(n).write_value(timestamp as u32); } }); // clear the irq - pac::TIMER.intr().write(|w| w.set_alarm(n, true)); + TIMER.intr().write(|w| w.set_alarm(n, true)); } fn trigger_alarm(&self, n: usize, cs: CriticalSection) { // disarm - pac::TIMER.armed().write(|w| w.set_armed(1 << n)); + TIMER.armed().write(|w| w.set_armed(1 << n)); let alarm = &self.alarms.borrow(cs)[n]; alarm.timestamp.set(u64::MAX); @@ -138,38 +142,72 @@ pub unsafe fn init() { }); // enable all irqs - pac::TIMER.inte().write(|w| { + TIMER.inte().write(|w| { w.set_alarm(0, true); w.set_alarm(1, true); w.set_alarm(2, true); w.set_alarm(3, true); }); - interrupt::TIMER_IRQ_0.enable(); - interrupt::TIMER_IRQ_1.enable(); - interrupt::TIMER_IRQ_2.enable(); - interrupt::TIMER_IRQ_3.enable(); + #[cfg(feature = "rp2040")] + { + interrupt::TIMER_IRQ_0.enable(); + interrupt::TIMER_IRQ_1.enable(); + interrupt::TIMER_IRQ_2.enable(); + interrupt::TIMER_IRQ_3.enable(); + } + #[cfg(feature = "_rp235x")] + { + interrupt::TIMER0_IRQ_0.enable(); + interrupt::TIMER0_IRQ_1.enable(); + interrupt::TIMER0_IRQ_2.enable(); + interrupt::TIMER0_IRQ_3.enable(); + } } -#[cfg(feature = "rt")] +#[cfg(all(feature = "rt", feature = "rp2040"))] #[interrupt] fn TIMER_IRQ_0() { DRIVER.check_alarm(0) } -#[cfg(feature = "rt")] +#[cfg(all(feature = "rt", feature = "rp2040"))] #[interrupt] fn TIMER_IRQ_1() { DRIVER.check_alarm(1) } -#[cfg(feature = "rt")] +#[cfg(all(feature = "rt", feature = "rp2040"))] #[interrupt] fn TIMER_IRQ_2() { DRIVER.check_alarm(2) } -#[cfg(feature = "rt")] +#[cfg(all(feature = "rt", feature = "rp2040"))] #[interrupt] fn TIMER_IRQ_3() { DRIVER.check_alarm(3) } + +#[cfg(all(feature = "rt", feature = "_rp235x"))] +#[interrupt] +fn TIMER0_IRQ_0() { + DRIVER.check_alarm(0) +} + +#[cfg(all(feature = "rt", feature = "_rp235x"))] +#[interrupt] +fn TIMER0_IRQ_1() { + DRIVER.check_alarm(1) +} + +#[cfg(all(feature = "rt", feature = "_rp235x"))] +#[interrupt] +fn TIMER0_IRQ_2() { + DRIVER.check_alarm(2) +} + +#[cfg(all(feature = "rt", feature = "_rp235x"))] +#[interrupt] +fn TIMER0_IRQ_3() { + DRIVER.check_alarm(3) +} diff --git a/embassy-rp/src/trng.rs b/embassy-rp/src/trng.rs new file mode 100644 index 000000000..9f2f33c4b --- /dev/null +++ b/embassy-rp/src/trng.rs @@ -0,0 +1,405 @@ +//! True Random Number Generator (TRNG) driver. + +use core::future::poll_fn; +use core::marker::PhantomData; +use core::ops::Not; +use core::task::Poll; + +use embassy_hal_internal::Peripheral; +use embassy_sync::waitqueue::AtomicWaker; +use rand_core::Error; + +use crate::interrupt::typelevel::{Binding, Interrupt}; +use crate::peripherals::TRNG; +use crate::{interrupt, pac}; + +trait SealedInstance { + fn regs() -> pac::trng::Trng; + fn waker() -> &'static AtomicWaker; +} + +/// TRNG peripheral instance. +#[allow(private_bounds)] +pub trait Instance: SealedInstance { + /// Interrupt for this peripheral. + type Interrupt: Interrupt; +} + +impl SealedInstance for TRNG { + fn regs() -> rp_pac::trng::Trng { + pac::TRNG + } + + fn waker() -> &'static AtomicWaker { + static WAKER: AtomicWaker = AtomicWaker::new(); + &WAKER + } +} + +impl Instance for TRNG { + type Interrupt = interrupt::typelevel::TRNG_IRQ; +} + +#[derive(Copy, Clone, Debug)] +#[allow(missing_docs)] +/// TRNG ROSC Inverter chain length options. +pub enum InverterChainLength { + None = 0, + One, + Two, + Three, + Four, +} + +impl From for u8 { + fn from(value: InverterChainLength) -> Self { + value as u8 + } +} + +/// Configuration for the TRNG. +/// +/// - Three built in entropy checks +/// - ROSC frequency controlled by selecting one of ROSC chain lengths +/// - Sample period in terms of system clock ticks +/// +/// +/// Default configuration is based on the following from documentation: +/// +/// ---- +/// +/// RP2350 Datasheet 12.12.2 +/// +/// ... +/// +/// When configuring the TRNG block, consider the following principles: +/// • As average generation time increases, result quality increases and failed entropy checks decrease. +/// • A low sample count decreases average generation time, but increases the chance of NIST test-failing results and +/// failed entropy checks. +/// For acceptable results with an average generation time of about 2 milliseconds, use ROSC chain length settings of 0 or +/// 1 and sample count settings of 20-25. +/// +/// --- +/// +/// Note, Pico SDK and Bootrom don't use any of the entropy checks and sample the ROSC directly +/// by setting the sample period to 0. Random data collected this way is then passed through +/// either hardware accelerated SHA256 (Bootrom) or xoroshiro128** (version 1.0!). +#[non_exhaustive] +#[derive(Copy, Clone, Debug)] +pub struct Config { + /// Bypass TRNG autocorrelation test + pub disable_autocorrelation_test: bool, + /// Bypass CRNGT test + pub disable_crngt_test: bool, + /// When set, the Von-Neuman balancer is bypassed (including the + /// 32 consecutive bits test) + pub disable_von_neumann_balancer: bool, + /// Sets the number of rng_clk cycles between two consecutive + /// ring oscillator samples. + /// Note: If the von Neumann decorrelator is bypassed, the minimum value for + /// sample counter must not be less than seventeen + pub sample_count: u32, + /// Selects the number of inverters (out of four possible + /// selections) in the ring oscillator (the entropy source). Higher values select + /// longer inverter chain lengths. + pub inverter_chain_length: InverterChainLength, +} + +impl Default for Config { + fn default() -> Self { + Config { + disable_autocorrelation_test: true, + disable_crngt_test: true, + disable_von_neumann_balancer: true, + sample_count: 25, + inverter_chain_length: InverterChainLength::One, + } + } +} + +/// True Random Number Generator Driver for RP2350 +/// +/// This driver provides async and blocking options. +/// +/// See [Config] for configuration details. +/// +/// Usage example: +/// ```no_run +/// use embassy_executor::Spawner; +/// use embassy_rp::trng::Trng; +/// use embassy_rp::peripherals::TRNG; +/// use embassy_rp::bind_interrupts; +/// +/// bind_interrupts!(struct Irqs { +/// TRNG_IRQ => embassy_rp::trng::InterruptHandler; +/// }); +/// +/// #[embassy_executor::main] +/// async fn main(spawner: Spawner) { +/// let peripherals = embassy_rp::init(Default::default()); +/// let mut trng = Trng::new(peripherals.TRNG, Irqs, embassy_rp::trng::Config::default()); +/// +/// let mut randomness = [0u8; 58]; +/// loop { +/// trng.fill_bytes(&mut randomness).await; +/// assert_ne!(randomness, [0u8; 58]); +/// } +///} +/// ``` +pub struct Trng<'d, T: Instance> { + phantom: PhantomData<&'d mut T>, +} + +/// 12.12.1. Overview +/// On request, the TRNG block generates a block of 192 entropy bits generated by automatically processing a series of +/// periodic samples from the TRNG block’s internal Ring Oscillator (ROSC). +const TRNG_BLOCK_SIZE_BITS: usize = 192; +const TRNG_BLOCK_SIZE_BYTES: usize = TRNG_BLOCK_SIZE_BITS / 8; + +impl<'d, T: Instance> Trng<'d, T> { + /// Create a new TRNG driver. + pub fn new( + _trng: impl Peripheral

+ 'd, + _irq: impl Binding> + 'd, + config: Config, + ) -> Self { + let regs = T::regs(); + + regs.rng_imr().write(|w| w.set_ehr_valid_int_mask(false)); + + let trng_config_register = regs.trng_config(); + trng_config_register.write(|w| { + w.set_rnd_src_sel(config.inverter_chain_length.clone().into()); + }); + + let sample_count_register = regs.sample_cnt1(); + sample_count_register.write(|w| { + *w = config.sample_count; + }); + + let debug_control_register = regs.trng_debug_control(); + debug_control_register.write(|w| { + w.set_auto_correlate_bypass(config.disable_autocorrelation_test); + w.set_trng_crngt_bypass(config.disable_crngt_test); + w.set_vnc_bypass(config.disable_von_neumann_balancer) + }); + + Trng { phantom: PhantomData } + } + + fn start_rng(&self) { + let regs = T::regs(); + let source_enable_register = regs.rnd_source_enable(); + // Enable TRNG ROSC + source_enable_register.write(|w| w.set_rnd_src_en(true)); + } + + fn stop_rng(&self) { + let regs = T::regs(); + let source_enable_register = regs.rnd_source_enable(); + source_enable_register.write(|w| w.set_rnd_src_en(false)); + let reset_bits_counter_register = regs.rst_bits_counter(); + reset_bits_counter_register.write(|w| w.set_rst_bits_counter(true)); + } + + fn enable_irq(&self) { + unsafe { T::Interrupt::enable() } + } + + fn disable_irq(&self) { + T::Interrupt::disable(); + } + + fn blocking_wait_for_successful_generation(&self) { + let regs = T::regs(); + + let trng_busy_register = regs.trng_busy(); + let trng_valid_register = regs.trng_valid(); + + let mut success = false; + while success.not() { + while trng_busy_register.read().trng_busy() {} + if trng_valid_register.read().ehr_valid().not() { + if regs.rng_isr().read().autocorr_err() { + regs.trng_sw_reset().write(|w| w.set_trng_sw_reset(true)); + } else { + panic!("RNG not busy, but ehr is not valid!") + } + } else { + success = true + } + } + } + + fn read_ehr_registers_into_array(&mut self, buffer: &mut [u8; TRNG_BLOCK_SIZE_BYTES]) { + let regs = T::regs(); + let ehr_data_regs = [ + regs.ehr_data0(), + regs.ehr_data1(), + regs.ehr_data2(), + regs.ehr_data3(), + regs.ehr_data4(), + regs.ehr_data5(), + ]; + + for (i, reg) in ehr_data_regs.iter().enumerate() { + buffer[i * 4..i * 4 + 4].copy_from_slice(®.read().to_ne_bytes()); + } + } + + fn blocking_read_ehr_registers_into_array(&mut self, buffer: &mut [u8; TRNG_BLOCK_SIZE_BYTES]) { + self.blocking_wait_for_successful_generation(); + self.read_ehr_registers_into_array(buffer); + } + + /// Fill the buffer with random bytes, async version. + pub async fn fill_bytes(&mut self, destination: &mut [u8]) { + if destination.is_empty() { + return; // Nothing to fill + } + + self.start_rng(); + self.enable_irq(); + + let mut bytes_transferred = 0usize; + let mut buffer = [0u8; TRNG_BLOCK_SIZE_BYTES]; + + let regs = T::regs(); + + let trng_busy_register = regs.trng_busy(); + let trng_valid_register = regs.trng_valid(); + + let waker = T::waker(); + + let destination_length = destination.len(); + + poll_fn(|context| { + waker.register(context.waker()); + if bytes_transferred == destination_length { + self.stop_rng(); + self.disable_irq(); + Poll::Ready(()) + } else { + if trng_busy_register.read().trng_busy() { + Poll::Pending + } else { + if trng_valid_register.read().ehr_valid().not() { + panic!("RNG not busy, but ehr is not valid!") + } + self.read_ehr_registers_into_array(&mut buffer); + let remaining = destination_length - bytes_transferred; + if remaining > TRNG_BLOCK_SIZE_BYTES { + destination[bytes_transferred..bytes_transferred + TRNG_BLOCK_SIZE_BYTES] + .copy_from_slice(&buffer); + bytes_transferred += TRNG_BLOCK_SIZE_BYTES + } else { + destination[bytes_transferred..bytes_transferred + remaining] + .copy_from_slice(&buffer[0..remaining]); + bytes_transferred += remaining + } + if bytes_transferred == destination_length { + self.stop_rng(); + self.disable_irq(); + Poll::Ready(()) + } else { + Poll::Pending + } + } + } + }) + .await + } + + /// Fill the buffer with random bytes, blocking version. + pub fn blocking_fill_bytes(&mut self, destination: &mut [u8]) { + if destination.is_empty() { + return; // Nothing to fill + } + self.start_rng(); + + let mut buffer = [0u8; TRNG_BLOCK_SIZE_BYTES]; + + for chunk in destination.chunks_mut(TRNG_BLOCK_SIZE_BYTES) { + self.blocking_wait_for_successful_generation(); + self.blocking_read_ehr_registers_into_array(&mut buffer); + chunk.copy_from_slice(&buffer[..chunk.len()]) + } + self.stop_rng() + } + + /// Return a random u32, blocking. + pub fn blocking_next_u32(&mut self) -> u32 { + let regs = T::regs(); + self.start_rng(); + self.blocking_wait_for_successful_generation(); + // 12.12.3 After successful generation, read the last result register, EHR_DATA[5] to + // clear all of the result registers. + let result = regs.ehr_data5().read(); + self.stop_rng(); + result + } + + /// Return a random u64, blocking. + pub fn blocking_next_u64(&mut self) -> u64 { + let regs = T::regs(); + self.start_rng(); + self.blocking_wait_for_successful_generation(); + + let low = regs.ehr_data4().read() as u64; + // 12.12.3 After successful generation, read the last result register, EHR_DATA[5] to + // clear all of the result registers. + let result = (regs.ehr_data5().read() as u64) << 32 | low; + self.stop_rng(); + result + } +} + +impl<'d, T: Instance> rand_core::RngCore for Trng<'d, T> { + fn next_u32(&mut self) -> u32 { + self.blocking_next_u32() + } + + fn next_u64(&mut self) -> u64 { + self.blocking_next_u64() + } + + fn fill_bytes(&mut self, dest: &mut [u8]) { + self.blocking_fill_bytes(dest) + } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + self.blocking_fill_bytes(dest); + Ok(()) + } +} +/// TRNG interrupt handler. +pub struct InterruptHandler { + _trng: PhantomData, +} + +impl interrupt::typelevel::Handler for InterruptHandler { + unsafe fn on_interrupt() { + let regs = T::regs(); + let isr = regs.rng_isr().read(); + // Clear ehr bit + regs.rng_icr().write(|w| { + w.set_ehr_valid(true); + }); + if isr.ehr_valid() { + T::waker().wake(); + } else { + // 12.12.5. List of Registers + // ... + // TRNG: RNG_ISR Register + // ... + // AUTOCORR_ERR: 1 indicates Autocorrelation test failed four times in a row. + // When set, RNG ceases functioning until next reset + if isr.autocorr_err() { + warn!("TRNG Autocorrect error! Resetting TRNG"); + regs.trng_sw_reset().write(|w| { + w.set_trng_sw_reset(true); + }); + } + } + } +} diff --git a/embassy-rp/src/uart/buffered.rs b/embassy-rp/src/uart/buffered.rs index 99c958129..152a432c9 100644 --- a/embassy-rp/src/uart/buffered.rs +++ b/embassy-rp/src/uart/buffered.rs @@ -1,17 +1,11 @@ //! Buffered UART driver. -use core::future::{poll_fn, Future}; +use core::future::Future; use core::slice; -use core::task::Poll; -use atomic_polyfill::{AtomicU8, Ordering}; +use atomic_polyfill::AtomicU8; use embassy_hal_internal::atomic_ring_buffer::RingBuffer; -use embassy_sync::waitqueue::AtomicWaker; -use embassy_time::Timer; use super::*; -use crate::clocks::clk_peri_freq; -use crate::interrupt::typelevel::{Binding, Interrupt}; -use crate::{interrupt, RegExt}; pub struct State { tx_waker: AtomicWaker, @@ -57,14 +51,20 @@ pub struct BufferedUartTx<'d, T: Instance> { pub(crate) fn init_buffers<'d, T: Instance + 'd>( _irq: impl Binding>, - tx_buffer: &'d mut [u8], - rx_buffer: &'d mut [u8], + tx_buffer: Option<&'d mut [u8]>, + rx_buffer: Option<&'d mut [u8]>, ) { let state = T::buffered_state(); - let len = tx_buffer.len(); - unsafe { state.tx_buf.init(tx_buffer.as_mut_ptr(), len) }; - let len = rx_buffer.len(); - unsafe { state.rx_buf.init(rx_buffer.as_mut_ptr(), len) }; + + if let Some(tx_buffer) = tx_buffer { + let len = tx_buffer.len(); + unsafe { state.tx_buf.init(tx_buffer.as_mut_ptr(), len) }; + } + + if let Some(rx_buffer) = rx_buffer { + let len = rx_buffer.len(); + unsafe { state.rx_buf.init(rx_buffer.as_mut_ptr(), len) }; + } // From the datasheet: // "The transmit interrupt is based on a transition through a level, rather @@ -101,7 +101,7 @@ impl<'d, T: Instance> BufferedUart<'d, T> { into_ref!(tx, rx); super::Uart::<'d, T, Async>::init(Some(tx.map_into()), Some(rx.map_into()), None, None, config); - init_buffers::(irq, tx_buffer, rx_buffer); + init_buffers::(irq, Some(tx_buffer), Some(rx_buffer)); Self { rx: BufferedUartRx { phantom: PhantomData }, @@ -130,7 +130,7 @@ impl<'d, T: Instance> BufferedUart<'d, T> { Some(cts.map_into()), config, ); - init_buffers::(irq, tx_buffer, rx_buffer); + init_buffers::(irq, Some(tx_buffer), Some(rx_buffer)); Self { rx: BufferedUartRx { phantom: PhantomData }, @@ -163,9 +163,21 @@ impl<'d, T: Instance> BufferedUart<'d, T> { self.tx.send_break(bits).await } + /// sets baudrate on runtime + pub fn set_baudrate(&mut self, baudrate: u32) { + super::Uart::<'d, T, Async>::set_baudrate_inner(baudrate); + } + /// Split into separate RX and TX handles. - pub fn split(self) -> (BufferedUartRx<'d, T>, BufferedUartTx<'d, T>) { - (self.rx, self.tx) + pub fn split(self) -> (BufferedUartTx<'d, T>, BufferedUartRx<'d, T>) { + (self.tx, self.rx) + } + + /// Split the Uart into a transmitter and receiver by mutable reference, + /// which is particularly useful when having two tasks correlating to + /// transmitting and receiving. + pub fn split_ref(&mut self) -> (&mut BufferedUartTx<'d, T>, &mut BufferedUartRx<'d, T>) { + (&mut self.tx, &mut self.rx) } } @@ -181,7 +193,7 @@ impl<'d, T: Instance> BufferedUartRx<'d, T> { into_ref!(rx); super::Uart::<'d, T, Async>::init(None, Some(rx.map_into()), None, None, config); - init_buffers::(irq, &mut [], rx_buffer); + init_buffers::(irq, None, Some(rx_buffer)); Self { phantom: PhantomData } } @@ -198,7 +210,7 @@ impl<'d, T: Instance> BufferedUartRx<'d, T> { into_ref!(rx, rts); super::Uart::<'d, T, Async>::init(None, Some(rx.map_into()), Some(rts.map_into()), None, config); - init_buffers::(irq, &mut [], rx_buffer); + init_buffers::(irq, None, Some(rx_buffer)); Self { phantom: PhantomData } } @@ -315,6 +327,12 @@ impl<'d, T: Instance> BufferedUartRx<'d, T> { w.set_rtim(true); }); } + + /// we are ready to read if there is data in the buffer + fn read_ready() -> Result { + let state = T::buffered_state(); + Ok(!state.rx_buf.is_empty()) + } } impl<'d, T: Instance> BufferedUartTx<'d, T> { @@ -329,7 +347,7 @@ impl<'d, T: Instance> BufferedUartTx<'d, T> { into_ref!(tx); super::Uart::<'d, T, Async>::init(Some(tx.map_into()), None, None, None, config); - init_buffers::(irq, tx_buffer, &mut []); + init_buffers::(irq, Some(tx_buffer), None); Self { phantom: PhantomData } } @@ -346,12 +364,12 @@ impl<'d, T: Instance> BufferedUartTx<'d, T> { into_ref!(tx, cts); super::Uart::<'d, T, Async>::init(Some(tx.map_into()), None, None, Some(cts.map_into()), config); - init_buffers::(irq, tx_buffer, &mut []); + init_buffers::(irq, Some(tx_buffer), None); Self { phantom: PhantomData } } - fn write<'a>(buf: &'a [u8]) -> impl Future> + 'a { + fn write(buf: &[u8]) -> impl Future> + '_ { poll_fn(move |cx| { if buf.is_empty() { return Poll::Ready(Ok(0)); @@ -465,9 +483,9 @@ impl<'d, T: Instance> Drop for BufferedUartRx<'d, T> { let state = T::buffered_state(); unsafe { state.rx_buf.deinit() } - // TX is inactive if the the buffer is not available. + // TX is inactive if the buffer is not available. // We can now unregister the interrupt handler - if state.tx_buf.len() == 0 { + if !state.tx_buf.is_available() { T::Interrupt::disable(); } } @@ -478,9 +496,9 @@ impl<'d, T: Instance> Drop for BufferedUartTx<'d, T> { let state = T::buffered_state(); unsafe { state.tx_buf.deinit() } - // RX is inactive if the the buffer is not available. + // RX is inactive if the buffer is not available. // We can now unregister the interrupt handler - if state.rx_buf.len() == 0 { + if !state.rx_buf.is_available() { T::Interrupt::disable(); } } @@ -526,64 +544,68 @@ impl interrupt::typelevel::Handler for BufferedInterr } // RX - let mut rx_writer = unsafe { s.rx_buf.writer() }; - let rx_buf = rx_writer.push_slice(); - let mut n_read = 0; - let mut error = false; - for rx_byte in rx_buf { - if r.uartfr().read().rxfe() { - break; + if s.rx_buf.is_available() { + let mut rx_writer = unsafe { s.rx_buf.writer() }; + let rx_buf = rx_writer.push_slice(); + let mut n_read = 0; + let mut error = false; + for rx_byte in rx_buf { + if r.uartfr().read().rxfe() { + break; + } + let dr = r.uartdr().read(); + if (dr.0 >> 8) != 0 { + s.rx_error.fetch_or((dr.0 >> 8) as u8, Ordering::Relaxed); + error = true; + // only fill the buffer with valid characters. the current character is fine + // if the error is an overrun, but if we add it to the buffer we'll report + // the overrun one character too late. drop it instead and pretend we were + // a bit slower at draining the rx fifo than we actually were. + // this is consistent with blocking uart error reporting. + break; + } + *rx_byte = dr.data(); + n_read += 1; } - let dr = r.uartdr().read(); - if (dr.0 >> 8) != 0 { - s.rx_error.fetch_or((dr.0 >> 8) as u8, Ordering::Relaxed); - error = true; - // only fill the buffer with valid characters. the current character is fine - // if the error is an overrun, but if we add it to the buffer we'll report - // the overrun one character too late. drop it instead and pretend we were - // a bit slower at draining the rx fifo than we actually were. - // this is consistent with blocking uart error reporting. - break; + if n_read > 0 { + rx_writer.push_done(n_read); + s.rx_waker.wake(); + } else if error { + s.rx_waker.wake(); + } + // Disable any further RX interrupts when the buffer becomes full or + // errors have occurred. This lets us buffer additional errors in the + // fifo without needing more error storage locations, and most applications + // will want to do a full reset of their uart state anyway once an error + // has happened. + if s.rx_buf.is_full() || error { + r.uartimsc().write_clear(|w| { + w.set_rxim(true); + w.set_rtim(true); + }); } - *rx_byte = dr.data(); - n_read += 1; - } - if n_read > 0 { - rx_writer.push_done(n_read); - s.rx_waker.wake(); - } else if error { - s.rx_waker.wake(); - } - // Disable any further RX interrupts when the buffer becomes full or - // errors have occurred. This lets us buffer additional errors in the - // fifo without needing more error storage locations, and most applications - // will want to do a full reset of their uart state anyway once an error - // has happened. - if s.rx_buf.is_full() || error { - r.uartimsc().write_clear(|w| { - w.set_rxim(true); - w.set_rtim(true); - }); } // TX - let mut tx_reader = unsafe { s.tx_buf.reader() }; - let tx_buf = tx_reader.pop_slice(); - let mut n_written = 0; - for tx_byte in tx_buf.iter_mut() { - if r.uartfr().read().txff() { - break; + if s.tx_buf.is_available() { + let mut tx_reader = unsafe { s.tx_buf.reader() }; + let tx_buf = tx_reader.pop_slice(); + let mut n_written = 0; + for tx_byte in tx_buf.iter_mut() { + if r.uartfr().read().txff() { + break; + } + r.uartdr().write(|w| w.set_data(*tx_byte)); + n_written += 1; } - r.uartdr().write(|w| w.set_data(*tx_byte)); - n_written += 1; + if n_written > 0 { + tx_reader.pop_done(n_written); + s.tx_waker.wake(); + } + // The TX interrupt only triggers once when the FIFO threshold is + // crossed. No need to disable it when the buffer becomes empty + // as it does re-trigger anymore once we have cleared it. } - if n_written > 0 { - tx_reader.pop_done(n_written); - s.tx_waker.wake(); - } - // The TX interrupt only triggers once when the FIFO threshold is - // crossed. No need to disable it when the buffer becomes empty - // as it does re-trigger anymore once we have cleared it. } } @@ -617,6 +639,18 @@ impl<'d, T: Instance + 'd> embedded_io_async::Read for BufferedUartRx<'d, T> { } } +impl<'d, T: Instance + 'd> embedded_io_async::ReadReady for BufferedUart<'d, T> { + fn read_ready(&mut self) -> Result { + BufferedUartRx::<'d, T>::read_ready() + } +} + +impl<'d, T: Instance + 'd> embedded_io_async::ReadReady for BufferedUartRx<'d, T> { + fn read_ready(&mut self) -> Result { + Self::read_ready() + } +} + impl<'d, T: Instance + 'd> embedded_io_async::BufRead for BufferedUart<'d, T> { async fn fill_buf(&mut self) -> Result<&[u8], Self::Error> { BufferedUartRx::<'d, T>::fill_buf().await diff --git a/embassy-rp/src/uart/mod.rs b/embassy-rp/src/uart/mod.rs index f372cb640..08f20924c 100644 --- a/embassy-rp/src/uart/mod.rs +++ b/embassy-rp/src/uart/mod.rs @@ -7,13 +7,12 @@ use atomic_polyfill::{AtomicU16, Ordering}; use embassy_futures::select::{select, Either}; use embassy_hal_internal::{into_ref, PeripheralRef}; use embassy_sync::waitqueue::AtomicWaker; -use embassy_time::Timer; +use embassy_time::{Delay, Timer}; use pac::uart::regs::Uartris; use crate::clocks::clk_peri_freq; use crate::dma::{AnyChannel, Channel}; -use crate::gpio::sealed::Pin; -use crate::gpio::AnyPin; +use crate::gpio::{AnyPin, SealedPin}; use crate::interrupt::typelevel::{Binding, Interrupt}; use crate::pac::io::vals::{Inover, Outover}; use crate::{interrupt, pac, peripherals, Peripheral, RegExt}; @@ -225,6 +224,17 @@ impl<'d, T: Instance, M: Mode> UartTx<'d, T, M> { } impl<'d, T: Instance> UartTx<'d, T, Blocking> { + /// Create a new UART TX instance for blocking mode operations. + pub fn new_blocking( + _uart: impl Peripheral

+ 'd, + tx: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + into_ref!(tx); + Uart::::init(Some(tx.map_into()), None, None, None, config); + Self::new_inner(None) + } + /// Convert this uart TX instance into a buffered uart using the provided /// irq and transmit buffer. pub fn into_buffered( @@ -232,7 +242,7 @@ impl<'d, T: Instance> UartTx<'d, T, Blocking> { irq: impl Binding>, tx_buffer: &'d mut [u8], ) -> BufferedUartTx<'d, T> { - buffered::init_buffers::(irq, tx_buffer, &mut []); + buffered::init_buffers::(irq, Some(tx_buffer), None); BufferedUartTx { phantom: PhantomData } } @@ -248,7 +258,7 @@ impl<'d, T: Instance> UartTx<'d, T, Async> { }); // If we don't assign future to a variable, the data register pointer // is held across an await and makes the future non-Send. - crate::dma::write(ch, buffer, T::regs().uartdr().as_ptr() as *mut _, T::TX_DREQ) + crate::dma::write(ch, buffer, T::regs().uartdr().as_ptr() as *mut _, T::TX_DREQ.into()) }; transfer.await; Ok(()) @@ -322,7 +332,7 @@ impl<'d, T: Instance, M: Mode> UartRx<'d, T, M> { impl<'d, T: Instance, M: Mode> Drop for UartRx<'d, T, M> { fn drop(&mut self) { - if let Some(_) = self.rx_dma { + if self.rx_dma.is_some() { T::Interrupt::disable(); // clear dma flags. irq handlers use these to disambiguate among themselves. T::regs().uartdmacr().write_clear(|reg| { @@ -353,7 +363,7 @@ impl<'d, T: Instance> UartRx<'d, T, Blocking> { irq: impl Binding>, rx_buffer: &'d mut [u8], ) -> BufferedUartRx<'d, T> { - buffered::init_buffers::(irq, &mut [], rx_buffer); + buffered::init_buffers::(irq, None, Some(rx_buffer)); BufferedUartRx { phantom: PhantomData } } @@ -423,7 +433,7 @@ impl<'d, T: Instance> UartRx<'d, T, Async> { let transfer = unsafe { // If we don't assign future to a variable, the data register pointer // is held across an await and makes the future non-Send. - crate::dma::read(ch, T::regs().uartdr().as_ptr() as *const _, buffer, T::RX_DREQ) + crate::dma::read(ch, T::regs().uartdr().as_ptr() as *const _, buffer, T::RX_DREQ.into()) }; // wait for either the transfer to complete or an error to happen. @@ -491,6 +501,36 @@ impl<'d, T: Instance> UartRx<'d, T, Async> { /// * The first call to `read_to_break()` will return `Ok(20)`. /// * The next call to `read_to_break()` will work as expected pub async fn read_to_break(&mut self, buffer: &mut [u8]) -> Result { + self.read_to_break_with_count(buffer, 0).await + } + + /// Read from the UART, waiting for a line break as soon as at least `min_count` bytes have been read. + /// + /// We read until one of the following occurs: + /// + /// * We read `buffer.len()` bytes without a line break + /// * returns `Err(ReadToBreakError::MissingBreak(buffer.len()))` + /// * We read `n > min_count` bytes then a line break occurs + /// * returns `Ok(n)` + /// * We encounter some error OTHER than a line break + /// * returns `Err(ReadToBreakError::Other(error))` + /// + /// If a line break occurs before `min_count` bytes have been read, the break will be ignored and the read will continue + /// + /// **NOTE**: you MUST provide a buffer one byte larger than your largest expected + /// message to reliably detect the framing on one single call to `read_to_break()`. + /// + /// * If you expect a message of 20 bytes + line break, and provide a 20-byte buffer: + /// * The first call to `read_to_break()` will return `Err(ReadToBreakError::MissingBreak(20))` + /// * The next call to `read_to_break()` will immediately return `Ok(0)`, from the "stale" line break + /// * If you expect a message of 20 bytes + line break, and provide a 21-byte buffer: + /// * The first call to `read_to_break()` will return `Ok(20)`. + /// * The next call to `read_to_break()` will work as expected + pub async fn read_to_break_with_count( + &mut self, + buffer: &mut [u8], + min_count: usize, + ) -> Result { // clear error flags before we drain the fifo. errors that have accumulated // in the flags will also be present in the fifo. T::dma_state().rx_errs.store(0, Ordering::Relaxed); @@ -503,7 +543,7 @@ impl<'d, T: Instance> UartRx<'d, T, Async> { // then drain the fifo. we need to read at most 32 bytes. errors that apply // to fifo bytes will be reported directly. - let sbuffer = match { + let mut sbuffer = match { let limit = buffer.len().min(32); self.drain_fifo(&mut buffer[0..limit]) } { @@ -512,7 +552,13 @@ impl<'d, T: Instance> UartRx<'d, T, Async> { // Drained (some/all of the fifo), no room left Ok(len) => return Err(ReadToBreakError::MissingBreak(len)), // We got a break WHILE draining the FIFO, return what we did get before the break - Err((i, Error::Break)) => return Ok(i), + Err((len, Error::Break)) => { + if len < min_count && len < buffer.len() { + &mut buffer[len..] + } else { + return Ok(len); + } + } // Some other error, just return the error Err((_i, e)) => return Err(ReadToBreakError::Other(e)), }; @@ -531,110 +577,123 @@ impl<'d, T: Instance> UartRx<'d, T, Async> { reg.set_rxdmae(true); reg.set_dmaonerr(true); }); - let transfer = unsafe { - // If we don't assign future to a variable, the data register pointer - // is held across an await and makes the future non-Send. - crate::dma::read(&mut ch, T::regs().uartdr().as_ptr() as *const _, sbuffer, T::RX_DREQ) - }; - // wait for either the transfer to complete or an error to happen. - let transfer_result = select( - transfer, - poll_fn(|cx| { - T::dma_state().rx_err_waker.register(cx.waker()); - match T::dma_state().rx_errs.swap(0, Ordering::Relaxed) { - 0 => Poll::Pending, - e => Poll::Ready(Uartris(e as u32)), + loop { + let transfer = unsafe { + // If we don't assign future to a variable, the data register pointer + // is held across an await and makes the future non-Send. + crate::dma::read( + &mut ch, + T::regs().uartdr().as_ptr() as *const _, + sbuffer, + T::RX_DREQ.into(), + ) + }; + + // wait for either the transfer to complete or an error to happen. + let transfer_result = select( + transfer, + poll_fn(|cx| { + T::dma_state().rx_err_waker.register(cx.waker()); + match T::dma_state().rx_errs.swap(0, Ordering::Relaxed) { + 0 => Poll::Pending, + e => Poll::Ready(Uartris(e as u32)), + } + }), + ) + .await; + + // Figure out our error state + let errors = match transfer_result { + Either::First(()) => { + // We're here because the DMA finished, BUT if an error occurred on the LAST + // byte, then we may still need to grab the error state! + Uartris(T::dma_state().rx_errs.swap(0, Ordering::Relaxed) as u32) } - }), - ) - .await; - - // Figure out our error state - let errors = match transfer_result { - Either::First(()) => { - // We're here because the DMA finished, BUT if an error occurred on the LAST - // byte, then we may still need to grab the error state! - Uartris(T::dma_state().rx_errs.swap(0, Ordering::Relaxed) as u32) - } - Either::Second(e) => { - // We're here because we errored, which means this is the error that - // was problematic. - e - } - }; - - if errors.0 == 0 { - // No errors? That means we filled the buffer without a line break. - // For THIS function, that's a problem. - return Err(ReadToBreakError::MissingBreak(buffer.len())); - } else if errors.beris() { - // We got a Line Break! By this point, we've finished/aborted the DMA - // transaction, which means that we need to figure out where it left off - // by looking at the write_addr. - // - // First, we do a sanity check to make sure the write value is within the - // range of DMA we just did. - let sval = buffer.as_ptr() as usize; - let eval = sval + buffer.len(); - - // This is the address where the DMA would write to next - let next_addr = ch.regs().write_addr().read() as usize; - - // If we DON'T end up inside the range, something has gone really wrong. - // Note that it's okay that `eval` is one past the end of the slice, as - // this is where the write pointer will end up at the end of a full - // transfer. - if (next_addr < sval) || (next_addr > eval) { - unreachable!("UART DMA reported invalid `write_addr`"); - } - - let regs = T::regs(); - let all_full = next_addr == eval; - - // NOTE: This is off label usage of RSR! See the issue below for - // why I am not checking if there is an "extra" FIFO byte, and why - // I am checking RSR directly (it seems to report the status of the LAST - // POPPED value, rather than the NEXT TO POP value like the datasheet - // suggests!) - // - // issue: https://github.com/raspberrypi/pico-feedback/issues/367 - let last_was_break = regs.uartrsr().read().be(); - - return match (all_full, last_was_break) { - (true, true) | (false, _) => { - // We got less than the full amount + a break, or the full amount - // and the last byte was a break. Subtract the break off by adding one to sval. - Ok(next_addr.saturating_sub(1 + sval)) - } - (true, false) => { - // We finished the whole DMA, and the last DMA'd byte was NOT a break - // character. This is an error. - // - // NOTE: we COULD potentially return Ok(buffer.len()) here, since we - // know a line break occured at SOME POINT after the DMA completed. - // - // However, we have no way of knowing if there was extra data BEFORE - // that line break, so instead return an Err to signal to the caller - // that there are "leftovers", and they'll catch the actual line break - // on the next call. - // - // Doing it like this also avoids racyness: now whether you finished - // the full read BEFORE the line break occurred or AFTER the line break - // occurs, you still get `MissingBreak(buffer.len())` instead of sometimes - // getting `Ok(buffer.len())` if you were "late enough" to observe the - // line break. - Err(ReadToBreakError::MissingBreak(buffer.len())) + Either::Second(e) => { + // We're here because we errored, which means this is the error that + // was problematic. + e } }; - } else if errors.oeris() { - return Err(ReadToBreakError::Other(Error::Overrun)); - } else if errors.peris() { - return Err(ReadToBreakError::Other(Error::Parity)); - } else if errors.feris() { - return Err(ReadToBreakError::Other(Error::Framing)); + + if errors.0 == 0 { + // No errors? That means we filled the buffer without a line break. + // For THIS function, that's a problem. + return Err(ReadToBreakError::MissingBreak(buffer.len())); + } else if errors.beris() { + // We got a Line Break! By this point, we've finished/aborted the DMA + // transaction, which means that we need to figure out where it left off + // by looking at the write_addr. + // + // First, we do a sanity check to make sure the write value is within the + // range of DMA we just did. + let sval = buffer.as_ptr() as usize; + let eval = sval + buffer.len(); + + // This is the address where the DMA would write to next + let next_addr = ch.regs().write_addr().read() as usize; + + // If we DON'T end up inside the range, something has gone really wrong. + // Note that it's okay that `eval` is one past the end of the slice, as + // this is where the write pointer will end up at the end of a full + // transfer. + if (next_addr < sval) || (next_addr > eval) { + unreachable!("UART DMA reported invalid `write_addr`"); + } + + if (next_addr - sval) < min_count { + sbuffer = &mut buffer[(next_addr - sval)..]; + continue; + } + + let regs = T::regs(); + let all_full = next_addr == eval; + + // NOTE: This is off label usage of RSR! See the issue below for + // why I am not checking if there is an "extra" FIFO byte, and why + // I am checking RSR directly (it seems to report the status of the LAST + // POPPED value, rather than the NEXT TO POP value like the datasheet + // suggests!) + // + // issue: https://github.com/raspberrypi/pico-feedback/issues/367 + let last_was_break = regs.uartrsr().read().be(); + + return match (all_full, last_was_break) { + (true, true) | (false, _) => { + // We got less than the full amount + a break, or the full amount + // and the last byte was a break. Subtract the break off by adding one to sval. + Ok(next_addr.saturating_sub(1 + sval)) + } + (true, false) => { + // We finished the whole DMA, and the last DMA'd byte was NOT a break + // character. This is an error. + // + // NOTE: we COULD potentially return Ok(buffer.len()) here, since we + // know a line break occured at SOME POINT after the DMA completed. + // + // However, we have no way of knowing if there was extra data BEFORE + // that line break, so instead return an Err to signal to the caller + // that there are "leftovers", and they'll catch the actual line break + // on the next call. + // + // Doing it like this also avoids racyness: now whether you finished + // the full read BEFORE the line break occurred or AFTER the line break + // occurs, you still get `MissingBreak(buffer.len())` instead of sometimes + // getting `Ok(buffer.len())` if you were "late enough" to observe the + // line break. + Err(ReadToBreakError::MissingBreak(buffer.len())) + } + }; + } else if errors.oeris() { + return Err(ReadToBreakError::Other(Error::Overrun)); + } else if errors.peris() { + return Err(ReadToBreakError::Other(Error::Parity)); + } else if errors.feris() { + return Err(ReadToBreakError::Other(Error::Framing)); + } + unreachable!("unrecognized rx error"); } - unreachable!("unrecognized rx error"); } } @@ -691,7 +750,7 @@ impl<'d, T: Instance> Uart<'d, T, Blocking> { tx_buffer: &'d mut [u8], rx_buffer: &'d mut [u8], ) -> BufferedUart<'d, T> { - buffered::init_buffers::(irq, tx_buffer, rx_buffer); + buffered::init_buffers::(irq, Some(tx_buffer), Some(rx_buffer)); BufferedUart { rx: BufferedUartRx { phantom: PhantomData }, @@ -787,26 +846,50 @@ impl<'d, T: Instance + 'd, M: Mode> Uart<'d, T, M> { ) { let r = T::regs(); if let Some(pin) = &tx { + let funcsel = { + let pin_number = ((pin.gpio().as_ptr() as u32) & 0x1FF) / 8; + if (pin_number % 4) == 0 { + 2 + } else { + 11 + } + }; pin.gpio().ctrl().write(|w| { - w.set_funcsel(2); + w.set_funcsel(funcsel); w.set_outover(if config.invert_tx { Outover::INVERT } else { Outover::NORMAL }); }); - pin.pad_ctrl().write(|w| w.set_ie(true)); + pin.pad_ctrl().write(|w| { + #[cfg(feature = "_rp235x")] + w.set_iso(false); + w.set_ie(true); + }); } if let Some(pin) = &rx { + let funcsel = { + let pin_number = ((pin.gpio().as_ptr() as u32) & 0x1FF) / 8; + if ((pin_number - 1) % 4) == 0 { + 2 + } else { + 11 + } + }; pin.gpio().ctrl().write(|w| { - w.set_funcsel(2); + w.set_funcsel(funcsel); w.set_inover(if config.invert_rx { Inover::INVERT } else { Inover::NORMAL }); }); - pin.pad_ctrl().write(|w| w.set_ie(true)); + pin.pad_ctrl().write(|w| { + #[cfg(feature = "_rp235x")] + w.set_iso(false); + w.set_ie(true); + }); } if let Some(pin) = &cts { pin.gpio().ctrl().write(|w| { @@ -817,7 +900,11 @@ impl<'d, T: Instance + 'd, M: Mode> Uart<'d, T, M> { Inover::NORMAL }); }); - pin.pad_ctrl().write(|w| w.set_ie(true)); + pin.pad_ctrl().write(|w| { + #[cfg(feature = "_rp235x")] + w.set_iso(false); + w.set_ie(true); + }); } if let Some(pin) = &rts { pin.gpio().ctrl().write(|w| { @@ -828,7 +915,11 @@ impl<'d, T: Instance + 'd, M: Mode> Uart<'d, T, M> { Outover::NORMAL }); }); - pin.pad_ctrl().write(|w| w.set_ie(true)); + pin.pad_ctrl().write(|w| { + #[cfg(feature = "_rp235x")] + w.set_iso(false); + w.set_ie(true); + }); } Self::set_baudrate_inner(config.baudrate); @@ -861,7 +952,57 @@ impl<'d, T: Instance + 'd, M: Mode> Uart<'d, T, M> { }); } - /// sets baudrate on runtime + fn lcr_modify(f: impl FnOnce(&mut crate::pac::uart::regs::UartlcrH) -> R) -> R { + let r = T::regs(); + + // Notes from PL011 reference manual: + // + // - Before writing the LCR, if the UART is enabled it needs to be + // disabled and any current TX + RX activity has to be completed + // + // - There is a BUSY flag which waits for the current TX char, but this is + // OR'd with TX FIFO !FULL, so not usable when FIFOs are enabled and + // potentially nonempty + // + // - FIFOs can't be set to disabled whilst a character is in progress + // (else "FIFO integrity is not guaranteed") + // + // Combination of these means there is no general way to halt and poll for + // end of TX character, if FIFOs may be enabled. Either way, there is no + // way to poll for end of RX character. + // + // So, insert a 15 Baud period delay before changing the settings. + // 15 Baud is comfortably higher than start + max data + parity + stop. + // Anything else would require API changes to permit a non-enabled UART + // state after init() where settings can be changed safely. + let clk_base = crate::clocks::clk_peri_freq(); + + let cr = r.uartcr().read(); + if cr.uarten() { + r.uartcr().modify(|w| { + w.set_uarten(false); + w.set_txe(false); + w.set_rxe(false); + }); + + // Note: Maximise precision here. Show working, the compiler will mop this up. + // Create a 16.6 fixed-point fractional division ratio; then scale to 32-bits. + let mut brdiv_ratio = 64 * r.uartibrd().read().0 + r.uartfbrd().read().0; + brdiv_ratio <<= 10; + // 3662 is ~(15 * 244.14) where 244.14 is 16e6 / 2^16 + let scaled_freq = clk_base / 3662; + let wait_time_us = brdiv_ratio / scaled_freq; + embedded_hal_1::delay::DelayNs::delay_us(&mut Delay, wait_time_us); + } + + let res = r.uartlcr_h().modify(f); + + r.uartcr().write_value(cr); + + res + } + + /// sets baudrate on runtime pub fn set_baudrate(&mut self, baudrate: u32) { Self::set_baudrate_inner(baudrate); } @@ -887,9 +1028,7 @@ impl<'d, T: Instance + 'd, M: Mode> Uart<'d, T, M> { r.uartibrd().write_value(pac::uart::regs::Uartibrd(baud_ibrd)); r.uartfbrd().write_value(pac::uart::regs::Uartfbrd(baud_fbrd)); - // PL011 needs a (dummy) line control register write to latch in the - // divisors. We don't want to actually change LCR contents here. - r.uartlcr_h().modify(|_| {}); + Self::lcr_modify(|_| {}); } } @@ -924,6 +1063,13 @@ impl<'d, T: Instance, M: Mode> Uart<'d, T, M> { pub fn split(self) -> (UartTx<'d, T, M>, UartRx<'d, T, M>) { (self.tx, self.rx) } + + /// Split the Uart into a transmitter and receiver by mutable reference, + /// which is particularly useful when having two tasks correlating to + /// transmitting and receiving. + pub fn split_ref(&mut self) -> (&mut UartTx<'d, T, M>, &mut UartRx<'d, T, M>) { + (&mut self.tx, &mut self.rx) + } } impl<'d, T: Instance> Uart<'d, T, Async> { @@ -943,6 +1089,17 @@ impl<'d, T: Instance> Uart<'d, T, Async> { pub async fn read_to_break<'a>(&mut self, buf: &'a mut [u8]) -> Result { self.rx.read_to_break(buf).await } + + /// Read until the buffer is full or a line break occurs after at least `min_count` bytes have been read. + /// + /// See [`UartRx::read_to_break_with_count()`] for more details + pub async fn read_to_break_with_count<'a>( + &mut self, + buf: &'a mut [u8], + min_count: usize, + ) -> Result { + self.rx.read_to_break_with_count(buf, min_count).await + } } impl<'d, T: Instance, M: Mode> embedded_hal_02::serial::Read for UartRx<'d, T, M> { @@ -1091,6 +1248,20 @@ impl<'d, T: Instance, M: Mode> embedded_hal_nb::serial::Write for UartTx<'d, T, } } +impl<'d, T: Instance> embedded_io::ErrorType for UartTx<'d, T, Blocking> { + type Error = Error; +} + +impl<'d, T: Instance> embedded_io::Write for UartTx<'d, T, Blocking> { + fn write(&mut self, buf: &[u8]) -> Result { + self.blocking_write(buf).map(|_| buf.len()) + } + + fn flush(&mut self) -> Result<(), Self::Error> { + self.blocking_flush() + } +} + impl<'d, T: Instance, M: Mode> embedded_hal_nb::serial::Read for Uart<'d, T, M> { fn read(&mut self) -> Result> { embedded_hal_02::serial::Read::read(&mut self.rx) @@ -1107,35 +1278,40 @@ impl<'d, T: Instance, M: Mode> embedded_hal_nb::serial::Write for Uart<'d, T, M> } } -mod sealed { - use super::*; +impl<'d, T: Instance> embedded_io::ErrorType for Uart<'d, T, Blocking> { + type Error = Error; +} - pub trait Mode {} - - pub trait Instance { - const TX_DREQ: u8; - const RX_DREQ: u8; - - type Interrupt: interrupt::typelevel::Interrupt; - - fn regs() -> pac::uart::Uart; - - fn buffered_state() -> &'static buffered::State; - - fn dma_state() -> &'static DmaState; +impl<'d, T: Instance> embedded_io::Write for Uart<'d, T, Blocking> { + fn write(&mut self, buf: &[u8]) -> Result { + self.blocking_write(buf).map(|_| buf.len()) } - pub trait TxPin {} - pub trait RxPin {} - pub trait CtsPin {} - pub trait RtsPin {} + + fn flush(&mut self) -> Result<(), Self::Error> { + self.blocking_flush() + } +} + +trait SealedMode {} + +trait SealedInstance { + const TX_DREQ: u8; + const RX_DREQ: u8; + + fn regs() -> pac::uart::Uart; + + fn buffered_state() -> &'static buffered::State; + + fn dma_state() -> &'static DmaState; } /// UART mode. -pub trait Mode: sealed::Mode {} +#[allow(private_bounds)] +pub trait Mode: SealedMode {} macro_rules! impl_mode { ($name:ident) => { - impl sealed::Mode for $name {} + impl SealedMode for $name {} impl Mode for $name {} }; } @@ -1149,16 +1325,18 @@ impl_mode!(Blocking); impl_mode!(Async); /// UART instance. -pub trait Instance: sealed::Instance {} +#[allow(private_bounds)] +pub trait Instance: SealedInstance { + /// Interrupt for this instance. + type Interrupt: interrupt::typelevel::Interrupt; +} macro_rules! impl_instance { ($inst:ident, $irq:ident, $tx_dreq:expr, $rx_dreq:expr) => { - impl sealed::Instance for peripherals::$inst { + impl SealedInstance for peripherals::$inst { const TX_DREQ: u8 = $tx_dreq; const RX_DREQ: u8 = $rx_dreq; - type Interrupt = crate::interrupt::typelevel::$irq; - fn regs() -> pac::uart::Uart { pac::$inst } @@ -1176,7 +1354,9 @@ macro_rules! impl_instance { &STATE } } - impl Instance for peripherals::$inst {} + impl Instance for peripherals::$inst { + type Interrupt = crate::interrupt::typelevel::$irq; + } }; } @@ -1184,17 +1364,16 @@ impl_instance!(UART0, UART0_IRQ, 20, 21); impl_instance!(UART1, UART1_IRQ, 22, 23); /// Trait for TX pins. -pub trait TxPin: sealed::TxPin + crate::gpio::Pin {} +pub trait TxPin: crate::gpio::Pin {} /// Trait for RX pins. -pub trait RxPin: sealed::RxPin + crate::gpio::Pin {} +pub trait RxPin: crate::gpio::Pin {} /// Trait for Clear To Send (CTS) pins. -pub trait CtsPin: sealed::CtsPin + crate::gpio::Pin {} +pub trait CtsPin: crate::gpio::Pin {} /// Trait for Request To Send (RTS) pins. -pub trait RtsPin: sealed::RtsPin + crate::gpio::Pin {} +pub trait RtsPin: crate::gpio::Pin {} macro_rules! impl_pin { ($pin:ident, $instance:ident, $function:ident) => { - impl sealed::$function for peripherals::$pin {} impl $function for peripherals::$pin {} }; } @@ -1229,3 +1408,92 @@ impl_pin!(PIN_26, UART1, CtsPin); impl_pin!(PIN_27, UART1, RtsPin); impl_pin!(PIN_28, UART0, TxPin); impl_pin!(PIN_29, UART0, RxPin); + +// Additional functions added by all 2350s +#[cfg(feature = "_rp235x")] +impl_pin!(PIN_2, UART0, TxPin); +#[cfg(feature = "_rp235x")] +impl_pin!(PIN_3, UART0, RxPin); +#[cfg(feature = "_rp235x")] +impl_pin!(PIN_6, UART1, TxPin); +#[cfg(feature = "_rp235x")] +impl_pin!(PIN_7, UART1, RxPin); +#[cfg(feature = "_rp235x")] +impl_pin!(PIN_10, UART1, TxPin); +#[cfg(feature = "_rp235x")] +impl_pin!(PIN_11, UART1, RxPin); +#[cfg(feature = "_rp235x")] +impl_pin!(PIN_14, UART0, TxPin); +#[cfg(feature = "_rp235x")] +impl_pin!(PIN_15, UART0, RxPin); +#[cfg(feature = "_rp235x")] +impl_pin!(PIN_18, UART0, TxPin); +#[cfg(feature = "_rp235x")] +impl_pin!(PIN_19, UART0, RxPin); +#[cfg(feature = "_rp235x")] +impl_pin!(PIN_22, UART1, TxPin); +#[cfg(feature = "_rp235x")] +impl_pin!(PIN_23, UART1, RxPin); +#[cfg(feature = "_rp235x")] +impl_pin!(PIN_26, UART1, TxPin); +#[cfg(feature = "_rp235x")] +impl_pin!(PIN_27, UART1, RxPin); + +// Additional pins added by larger 2350 packages. +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_30, UART0, CtsPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_31, UART0, RtsPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_32, UART0, TxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_33, UART0, RxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_34, UART0, CtsPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_35, UART0, RtsPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_36, UART1, TxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_37, UART1, RxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_38, UART1, CtsPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_39, UART1, RtsPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_40, UART1, TxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_41, UART1, RxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_42, UART1, CtsPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_43, UART1, RtsPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_44, UART0, TxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_45, UART0, RxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_46, UART0, CtsPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_47, UART0, RtsPin); + +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_30, UART0, TxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_31, UART0, RxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_34, UART0, TxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_35, UART0, RxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_38, UART1, TxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_39, UART1, RxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_42, UART1, TxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_43, UART1, RxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_46, UART0, TxPin); +#[cfg(feature = "rp235xb")] +impl_pin!(PIN_47, UART0, RxPin); diff --git a/embassy-rp/src/usb.rs b/embassy-rp/src/usb.rs index 905661d64..20ef881f9 100644 --- a/embassy-rp/src/usb.rs +++ b/embassy-rp/src/usb.rs @@ -14,25 +14,24 @@ use embassy_usb_driver::{ use crate::interrupt::typelevel::{Binding, Interrupt}; use crate::{interrupt, pac, peripherals, Peripheral, RegExt}; -pub(crate) mod sealed { - pub trait Instance { - fn regs() -> crate::pac::usb::Usb; - fn dpram() -> crate::pac::usb_dpram::UsbDpram; - } +trait SealedInstance { + fn regs() -> crate::pac::usb::Usb; + fn dpram() -> crate::pac::usb_dpram::UsbDpram; } /// USB peripheral instance. -pub trait Instance: sealed::Instance + 'static { +#[allow(private_bounds)] +pub trait Instance: SealedInstance + 'static { /// Interrupt for this peripheral. type Interrupt: interrupt::typelevel::Interrupt; } -impl crate::usb::sealed::Instance for peripherals::USB { +impl crate::usb::SealedInstance for peripherals::USB { fn regs() -> pac::usb::Usb { - pac::USBCTRL_REGS + pac::USB } fn dpram() -> crate::pac::usb_dpram::UsbDpram { - pac::USBCTRL_DPRAM + pac::USB_DPRAM } } @@ -42,7 +41,7 @@ impl crate::usb::Instance for peripherals::USB { const EP_COUNT: usize = 16; const EP_MEMORY_SIZE: usize = 4096; -const EP_MEMORY: *mut u8 = pac::USBCTRL_DPRAM.as_ptr() as *mut u8; +const EP_MEMORY: *mut u8 = pac::USB_DPRAM.as_ptr() as *mut u8; const NEW_AW: AtomicWaker = AtomicWaker::new(); static BUS_WAKER: AtomicWaker = NEW_AW; @@ -413,12 +412,41 @@ impl<'d, T: Instance> driver::Bus for Bus<'d, T> { .await } - fn endpoint_set_stalled(&mut self, _ep_addr: EndpointAddress, _stalled: bool) { - todo!(); + fn endpoint_set_stalled(&mut self, ep_addr: EndpointAddress, stalled: bool) { + let n = ep_addr.index(); + + if n == 0 { + T::regs().ep_stall_arm().modify(|w| { + if ep_addr.is_in() { + w.set_ep0_in(stalled); + } else { + w.set_ep0_out(stalled); + } + }); + } + + let ctrl = if ep_addr.is_in() { + T::dpram().ep_in_buffer_control(n) + } else { + T::dpram().ep_out_buffer_control(n) + }; + + ctrl.modify(|w| w.set_stall(stalled)); + + let wakers = if ep_addr.is_in() { &EP_IN_WAKERS } else { &EP_OUT_WAKERS }; + wakers[n].wake(); } - fn endpoint_is_stalled(&mut self, _ep_addr: EndpointAddress) -> bool { - todo!(); + fn endpoint_is_stalled(&mut self, ep_addr: EndpointAddress) -> bool { + let n = ep_addr.index(); + + let ctrl = if ep_addr.is_in() { + T::dpram().ep_in_buffer_control(n) + } else { + T::dpram().ep_out_buffer_control(n) + }; + + ctrl.read().stall() } fn endpoint_set_enabled(&mut self, ep_addr: EndpointAddress, enabled: bool) { @@ -465,7 +493,6 @@ impl<'d, T: Instance> driver::Bus for Bus<'d, T> { trait Dir { fn dir() -> Direction; - fn waker(i: usize) -> &'static AtomicWaker; } /// Type for In direction. @@ -474,11 +501,6 @@ impl Dir for In { fn dir() -> Direction { Direction::In } - - #[inline] - fn waker(i: usize) -> &'static AtomicWaker { - &EP_IN_WAKERS[i] - } } /// Type for Out direction. @@ -487,11 +509,6 @@ impl Dir for Out { fn dir() -> Direction { Direction::Out } - - #[inline] - fn waker(i: usize) -> &'static AtomicWaker { - &EP_OUT_WAKERS[i] - } } /// Endpoint for RP USB driver. diff --git a/embassy-rp/src/watchdog.rs b/embassy-rp/src/watchdog.rs index f1e986ec7..edd48e0e0 100644 --- a/embassy-rp/src/watchdog.rs +++ b/embassy-rp/src/watchdog.rs @@ -34,6 +34,7 @@ impl Watchdog { /// /// * `cycles` - Total number of tick cycles before the next tick is generated. /// It is expected to be the frequency in MHz of clk_ref. + #[cfg(feature = "rp2040")] pub fn enable_tick_generation(&mut self, cycles: u8) { let watchdog = pac::WATCHDOG; watchdog.tick().write(|w| { @@ -46,7 +47,7 @@ impl Watchdog { /// or when JTAG is accessing bus fabric pub fn pause_on_debug(&mut self, pause: bool) { let watchdog = pac::WATCHDOG; - watchdog.ctrl().write(|w| { + watchdog.ctrl().modify(|w| { w.set_pause_dbg0(pause); w.set_pause_dbg1(pause); w.set_pause_jtag(pause); @@ -60,7 +61,7 @@ impl Watchdog { fn enable(&self, bit: bool) { let watchdog = pac::WATCHDOG; - watchdog.ctrl().write(|w| w.set_enable(bit)) + watchdog.ctrl().modify(|w| w.set_enable(bit)) } // Configure which hardware will be reset by the watchdog diff --git a/embassy-stm32-wpan/Cargo.toml b/embassy-stm32-wpan/Cargo.toml index 360ca5f4b..54dfd39a6 100644 --- a/embassy-stm32-wpan/Cargo.toml +++ b/embassy-stm32-wpan/Cargo.toml @@ -20,14 +20,16 @@ features = ["stm32wb55rg"] [dependencies] embassy-stm32 = { version = "0.1.0", path = "../embassy-stm32" } -embassy-sync = { version = "0.5.0", path = "../embassy-sync" } -embassy-time = { version = "0.3.0", path = "../embassy-time", optional = true } +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } +embassy-time = { version = "0.3.2", path = "../embassy-time", optional = true } embassy-futures = { version = "0.1.0", path = "../embassy-futures" } -embassy-hal-internal = { version = "0.1.0", path = "../embassy-hal-internal" } -embassy-embedded-hal = { version = "0.1.0", path = "../embassy-embedded-hal" } +embassy-hal-internal = { version = "0.2.0", path = "../embassy-hal-internal" } +embassy-embedded-hal = { version = "0.2.0", path = "../embassy-embedded-hal" } embassy-net-driver = { version = "0.2.0", path = "../embassy-net-driver", optional=true } defmt = { version = "0.3", optional = true } +log = { version = "0.4.17", optional = true } + cortex-m = "0.7.6" heapless = "0.8" aligned = "0.4.1" @@ -35,7 +37,7 @@ aligned = "0.4.1" bit_field = "0.10.2" stm32-device-signature = { version = "0.3.3", features = ["stm32wb5x"] } stm32wb-hci = { version = "0.17.0", optional = true } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } +futures-util = { version = "0.3.30", default-features = false } bitflags = { version = "2.3.3", optional = true } [features] diff --git a/embassy-stm32-wpan/src/consts.rs b/embassy-stm32-wpan/src/consts.rs index bd70851ea..6aaef1d35 100644 --- a/embassy-stm32-wpan/src/consts.rs +++ b/embassy-stm32-wpan/src/consts.rs @@ -1,5 +1,3 @@ -use core::convert::TryFrom; - use crate::evt::CsEvt; use crate::PacketHeader; diff --git a/embassy-stm32-wpan/src/fmt.rs b/embassy-stm32-wpan/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-stm32-wpan/src/fmt.rs +++ b/embassy-stm32-wpan/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-stm32-wpan/src/lib.rs b/embassy-stm32-wpan/src/lib.rs index f9560d235..fb34d4ba0 100644 --- a/embassy-stm32-wpan/src/lib.rs +++ b/embassy-stm32-wpan/src/lib.rs @@ -2,6 +2,7 @@ #![allow(async_fn_in_trait)] #![doc = include_str!("../README.md")] // #![warn(missing_docs)] +#![allow(static_mut_refs)] // TODO: Fix // This must go FIRST so that all the other modules see its macros. mod fmt; diff --git a/embassy-stm32-wpan/src/mac/commands.rs b/embassy-stm32-wpan/src/mac/commands.rs index 8f6dcbbbc..82b9d2772 100644 --- a/embassy-stm32-wpan/src/mac/commands.rs +++ b/embassy-stm32-wpan/src/mac/commands.rs @@ -1,3 +1,5 @@ +#![allow(unused)] + use core::{mem, slice}; use super::opcodes::OpcodeM4ToM0; @@ -369,7 +371,7 @@ pub struct DataRequest { } impl DataRequest { - pub fn set_buffer<'a>(&'a mut self, buf: &'a [u8]) -> &mut Self { + pub fn set_buffer<'a>(&'a mut self, buf: &'a [u8]) -> &'a mut Self { self.msdu_ptr = buf as *const _ as *const u8; self.msdu_length = buf.len() as u8; diff --git a/embassy-stm32-wpan/src/mac/control.rs b/embassy-stm32-wpan/src/mac/control.rs index 8a13de81c..e8d2f9f7b 100644 --- a/embassy-stm32-wpan/src/mac/control.rs +++ b/embassy-stm32-wpan/src/mac/control.rs @@ -5,7 +5,7 @@ use core::task::Poll; use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; use embassy_sync::mutex::MutexGuard; use embassy_sync::signal::Signal; -use futures::FutureExt; +use futures_util::FutureExt; use super::commands::MacCommand; use super::event::MacEvent; diff --git a/embassy-stm32-wpan/src/mac/driver.rs b/embassy-stm32-wpan/src/mac/driver.rs index 5b9d5daf4..41cca09e3 100644 --- a/embassy-stm32-wpan/src/mac/driver.rs +++ b/embassy-stm32-wpan/src/mac/driver.rs @@ -23,8 +23,14 @@ impl<'d> Driver<'d> { impl<'d> embassy_net_driver::Driver for Driver<'d> { // type RxToken<'a> = RxToken<'a, 'd> where Self: 'a; // type TxToken<'a> = TxToken<'a, 'd> where Self: 'a; - type RxToken<'a> = RxToken<'d> where Self: 'a; - type TxToken<'a> = TxToken<'d> where Self: 'a; + type RxToken<'a> + = RxToken<'d> + where + Self: 'a; + type TxToken<'a> + = TxToken<'d> + where + Self: 'a; fn receive(&mut self, cx: &mut Context) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> { if self.runner.rx_channel.poll_ready_to_receive(cx).is_ready() diff --git a/embassy-stm32/Cargo.toml b/embassy-stm32/Cargo.toml index aed9f7a46..e2ba4fd60 100644 --- a/embassy-stm32/Cargo.toml +++ b/embassy-stm32/Cargo.toml @@ -24,12 +24,13 @@ flavors = [ { regex_feature = "stm32c0.*", target = "thumbv6m-none-eabi" }, { regex_feature = "stm32g0.*", target = "thumbv6m-none-eabi" }, { regex_feature = "stm32g4.*", target = "thumbv7em-none-eabi", features = ["low-power"] }, - { regex_feature = "stm32h5.*", target = "thumbv8m.main-none-eabihf" }, + { regex_feature = "stm32h5.*", target = "thumbv8m.main-none-eabihf", features = ["low-power"] }, { regex_feature = "stm32h7.*", target = "thumbv7em-none-eabi" }, { regex_feature = "stm32l0.*", target = "thumbv6m-none-eabi", features = ["low-power"] }, { regex_feature = "stm32l1.*", target = "thumbv7m-none-eabi" }, { regex_feature = "stm32l4.*", target = "thumbv7em-none-eabi" }, { regex_feature = "stm32l5.*", target = "thumbv8m.main-none-eabihf", features = ["low-power"] }, + { regex_feature = "stm32u0.*", target = "thumbv6m-none-eabi" }, { regex_feature = "stm32u5.*", target = "thumbv8m.main-none-eabihf" }, { regex_feature = "stm32wb.*", target = "thumbv7em-none-eabi" }, { regex_feature = "stm32wba.*", target = "thumbv8m.main-none-eabihf" }, @@ -41,56 +42,66 @@ features = ["defmt", "unstable-pac", "exti", "time-driver-any", "time", "stm32h7 rustdoc-args = ["--cfg", "docsrs"] [dependencies] -embassy-sync = { version = "0.5.0", path = "../embassy-sync" } -embassy-time = { version = "0.3.0", path = "../embassy-time", optional = true } +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } +embassy-time = { version = "0.3.2", path = "../embassy-time", optional = true } embassy-time-driver = { version = "0.1", path = "../embassy-time-driver", optional = true } embassy-futures = { version = "0.1.0", path = "../embassy-futures" } -embassy-hal-internal = {version = "0.1.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-4"] } -embassy-embedded-hal = {version = "0.1.0", path = "../embassy-embedded-hal" } +embassy-hal-internal = {version = "0.2.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-4"] } +embassy-embedded-hal = {version = "0.2.0", path = "../embassy-embedded-hal", default-features = false } embassy-net-driver = { version = "0.2.0", path = "../embassy-net-driver" } embassy-usb-driver = {version = "0.1.0", path = "../embassy-usb-driver" } -embassy-executor = { version = "0.5.0", path = "../embassy-executor", optional = true } +embassy-usb-synopsys-otg = {version = "0.1.0", path = "../embassy-usb-synopsys-otg" } +embassy-executor = { version = "0.6.2", path = "../embassy-executor", optional = true } embedded-hal-02 = { package = "embedded-hal", version = "0.2.6", features = ["unproven"] } embedded-hal-1 = { package = "embedded-hal", version = "1.0" } embedded-hal-async = { version = "1.0" } embedded-hal-nb = { version = "1.0" } +embedded-can = "0.4" embedded-storage = "0.3.1" embedded-storage-async = { version = "0.4.1" } + defmt = { version = "0.3", optional = true } log = { version = "0.4.14", optional = true } cortex-m-rt = ">=0.6.15,<0.8" cortex-m = "0.7.6" -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } +futures-util = { version = "0.3.30", default-features = false } rand_core = "0.6.3" sdio-host = "0.5.0" critical-section = "1.1" #stm32-metapac = { version = "15" } -stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-768b3e8e3199e03de0acd0d4590d06f51eebb7dd" } +stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-7bb5f235587c3a6886a7be1c8f58fdf22c5257f3" } + vcell = "0.1.3" -bxcan = "0.7.0" nb = "1.0.0" stm32-fmc = "0.3.0" cfg-if = "1.0.0" embedded-io = { version = "0.6.0" } embedded-io-async = { version = "0.6.1" } -chrono = { version = "^0.4", default-features = false, optional = true} +chrono = { version = "^0.4", default-features = false, optional = true } bit_field = "0.10.2" document-features = "0.2.7" -fdcan = { version = "0.2.0", optional = true } +static_assertions = { version = "1.1" } +volatile-register = { version = "0.2.1" } +bitflags = "2.4.2" + +block-device-driver = { version = "0.2" } +aligned = "0.4.1" [dev-dependencies] critical-section = { version = "1.1", features = ["std"] } +proptest = "1.5.0" +proptest-state-machine = "0.3.0" [build-dependencies] proc-macro2 = "1.0.36" quote = "1.0.15" -#stm32-metapac = { version = "15", default-features = false, features = ["metadata"]} -stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-768b3e8e3199e03de0acd0d4590d06f51eebb7dd", default-features = false, features = ["metadata"]} +#stm32-metapac = { version = "15", default-features = false, features = ["metadata"]} +stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-7bb5f235587c3a6886a7be1c8f58fdf22c5257f3", default-features = false, features = ["metadata"] } [features] default = ["rt"] @@ -99,7 +110,7 @@ default = ["rt"] rt = ["stm32-metapac/rt"] ## Use [`defmt`](https://docs.rs/defmt/latest/defmt/) for logging -defmt = ["dep:defmt", "bxcan/unstable-defmt", "embassy-sync/defmt", "embassy-embedded-hal/defmt", "embassy-hal-internal/defmt", "embedded-io-async/defmt-03", "embassy-usb-driver/defmt", "embassy-net-driver/defmt", "embassy-time?/defmt"] +defmt = ["dep:defmt", "embassy-sync/defmt", "embassy-embedded-hal/defmt", "embassy-hal-internal/defmt", "embedded-io-async/defmt-03", "embassy-usb-driver/defmt", "embassy-net-driver/defmt", "embassy-time?/defmt"] exti = [] low-power = [ "dep:embassy-executor", "embassy-executor?/arch-cortex-m", "time" ] @@ -108,6 +119,9 @@ low-power-debug-with-sleep = [] ## Automatically generate `memory.x` file using [`stm32-metapac`](https://docs.rs/stm32-metapac/) memory-x = ["stm32-metapac/memory-x"] +## Use secure registers when TrustZone is enabled +trustzone-secure = [] + ## Re-export stm32-metapac at `embassy_stm32::pac`. ## This is unstable because semver-minor (non-breaking) releases of embassy-stm32 may major-bump (breaking) the stm32-metapac version. ## If this is an issue for you, you're encouraged to directly depend on a fixed version of the PAC. @@ -117,7 +131,7 @@ unstable-pac = [] #! ## Time ## Enables additional driver features that depend on embassy-time -time = ["dep:embassy-time"] +time = ["dep:embassy-time", "embassy-embedded-hal/time"] # Features starting with `_` are for internal use only. They're not intended # to be enabled by other crates, and are not covered by semver guarantees. @@ -125,6 +139,8 @@ _time-driver = ["dep:embassy-time-driver", "time"] ## Use any time driver time-driver-any = ["_time-driver"] +## Use TIM1 as time driver +time-driver-tim1 = ["_time-driver"] ## Use TIM2 as time driver time-driver-tim2 = ["_time-driver"] ## Use TIM3 as time driver @@ -133,18 +149,24 @@ time-driver-tim3 = ["_time-driver"] time-driver-tim4 = ["_time-driver"] ## Use TIM5 as time driver time-driver-tim5 = ["_time-driver"] +## Use TIM8 as time driver +time-driver-tim8 = ["_time-driver"] ## Use TIM9 as time driver time-driver-tim9 = ["_time-driver"] -## Use TIM11 as time driver -time-driver-tim11 = ["_time-driver"] ## Use TIM12 as time driver time-driver-tim12 = ["_time-driver"] ## Use TIM15 as time driver time-driver-tim15 = ["_time-driver"] +## Use TIM20 as time driver +time-driver-tim20 = ["_time-driver"] ## Use TIM21 as time driver time-driver-tim21 = ["_time-driver"] ## Use TIM22 as time driver time-driver-tim22 = ["_time-driver"] +## Use TIM23 as time driver +time-driver-tim23 = ["_time-driver"] +## Use TIM24 as time driver +time-driver-tim24 = ["_time-driver"] #! ## Analog Switch Pins (Pxy_C) on STM32H7 series @@ -163,6 +185,9 @@ split-pc3 = ["_split-pins-enabled"] ## internal use only _split-pins-enabled = [] +## internal use only +_dual-core = [] + #! ## Chip-selection features #! Select your chip by specifying the model as a feature, e.g. `stm32c011d6`. #! Check the `Cargo.toml` for the latest list of supported chips. @@ -695,373 +720,407 @@ stm32f779ai = [ "stm32-metapac/stm32f779ai" ] stm32f779bi = [ "stm32-metapac/stm32f779bi" ] stm32f779ii = [ "stm32-metapac/stm32f779ii" ] stm32f779ni = [ "stm32-metapac/stm32f779ni" ] -stm32g030c6 = [ "stm32-metapac/stm32g030c6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g030c8 = [ "stm32-metapac/stm32g030c8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g030f6 = [ "stm32-metapac/stm32g030f6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g030j6 = [ "stm32-metapac/stm32g030j6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g030k6 = [ "stm32-metapac/stm32g030k6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g030k8 = [ "stm32-metapac/stm32g030k8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g031c4 = [ "stm32-metapac/stm32g031c4", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g031c6 = [ "stm32-metapac/stm32g031c6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g031c8 = [ "stm32-metapac/stm32g031c8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g031f4 = [ "stm32-metapac/stm32g031f4", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g031f6 = [ "stm32-metapac/stm32g031f6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g031f8 = [ "stm32-metapac/stm32g031f8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g031g4 = [ "stm32-metapac/stm32g031g4", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g031g6 = [ "stm32-metapac/stm32g031g6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g031g8 = [ "stm32-metapac/stm32g031g8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g031j4 = [ "stm32-metapac/stm32g031j4", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g031j6 = [ "stm32-metapac/stm32g031j6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g031k4 = [ "stm32-metapac/stm32g031k4", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g031k6 = [ "stm32-metapac/stm32g031k6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g031k8 = [ "stm32-metapac/stm32g031k8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g031y8 = [ "stm32-metapac/stm32g031y8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g041c6 = [ "stm32-metapac/stm32g041c6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g041c8 = [ "stm32-metapac/stm32g041c8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g041f6 = [ "stm32-metapac/stm32g041f6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g041f8 = [ "stm32-metapac/stm32g041f8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g041g6 = [ "stm32-metapac/stm32g041g6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g041g8 = [ "stm32-metapac/stm32g041g8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g041j6 = [ "stm32-metapac/stm32g041j6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g041k6 = [ "stm32-metapac/stm32g041k6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g041k8 = [ "stm32-metapac/stm32g041k8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g041y8 = [ "stm32-metapac/stm32g041y8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g050c6 = [ "stm32-metapac/stm32g050c6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g050c8 = [ "stm32-metapac/stm32g050c8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g050f6 = [ "stm32-metapac/stm32g050f6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g050k6 = [ "stm32-metapac/stm32g050k6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g050k8 = [ "stm32-metapac/stm32g050k8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g051c6 = [ "stm32-metapac/stm32g051c6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g051c8 = [ "stm32-metapac/stm32g051c8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g051f6 = [ "stm32-metapac/stm32g051f6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g051f8 = [ "stm32-metapac/stm32g051f8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g051g6 = [ "stm32-metapac/stm32g051g6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g051g8 = [ "stm32-metapac/stm32g051g8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g051k6 = [ "stm32-metapac/stm32g051k6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g051k8 = [ "stm32-metapac/stm32g051k8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g061c6 = [ "stm32-metapac/stm32g061c6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g061c8 = [ "stm32-metapac/stm32g061c8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g061f6 = [ "stm32-metapac/stm32g061f6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g061f8 = [ "stm32-metapac/stm32g061f8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g061g6 = [ "stm32-metapac/stm32g061g6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g061g8 = [ "stm32-metapac/stm32g061g8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g061k6 = [ "stm32-metapac/stm32g061k6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g061k8 = [ "stm32-metapac/stm32g061k8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g070cb = [ "stm32-metapac/stm32g070cb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g070kb = [ "stm32-metapac/stm32g070kb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g070rb = [ "stm32-metapac/stm32g070rb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g071c6 = [ "stm32-metapac/stm32g071c6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g071c8 = [ "stm32-metapac/stm32g071c8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g071cb = [ "stm32-metapac/stm32g071cb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g071eb = [ "stm32-metapac/stm32g071eb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g071g6 = [ "stm32-metapac/stm32g071g6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g071g8 = [ "stm32-metapac/stm32g071g8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g071gb = [ "stm32-metapac/stm32g071gb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g071k6 = [ "stm32-metapac/stm32g071k6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g071k8 = [ "stm32-metapac/stm32g071k8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g071kb = [ "stm32-metapac/stm32g071kb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g071r6 = [ "stm32-metapac/stm32g071r6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g071r8 = [ "stm32-metapac/stm32g071r8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g071rb = [ "stm32-metapac/stm32g071rb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g081cb = [ "stm32-metapac/stm32g081cb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g081eb = [ "stm32-metapac/stm32g081eb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g081gb = [ "stm32-metapac/stm32g081gb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g081kb = [ "stm32-metapac/stm32g081kb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g081rb = [ "stm32-metapac/stm32g081rb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b0ce = [ "stm32-metapac/stm32g0b0ce", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b0ke = [ "stm32-metapac/stm32g0b0ke", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b0re = [ "stm32-metapac/stm32g0b0re", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b0ve = [ "stm32-metapac/stm32g0b0ve", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1cb = [ "stm32-metapac/stm32g0b1cb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1cc = [ "stm32-metapac/stm32g0b1cc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1ce = [ "stm32-metapac/stm32g0b1ce", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1kb = [ "stm32-metapac/stm32g0b1kb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1kc = [ "stm32-metapac/stm32g0b1kc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1ke = [ "stm32-metapac/stm32g0b1ke", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1mb = [ "stm32-metapac/stm32g0b1mb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1mc = [ "stm32-metapac/stm32g0b1mc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1me = [ "stm32-metapac/stm32g0b1me", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1ne = [ "stm32-metapac/stm32g0b1ne", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1rb = [ "stm32-metapac/stm32g0b1rb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1rc = [ "stm32-metapac/stm32g0b1rc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1re = [ "stm32-metapac/stm32g0b1re", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1vb = [ "stm32-metapac/stm32g0b1vb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1vc = [ "stm32-metapac/stm32g0b1vc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0b1ve = [ "stm32-metapac/stm32g0b1ve", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0c1cc = [ "stm32-metapac/stm32g0c1cc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0c1ce = [ "stm32-metapac/stm32g0c1ce", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0c1kc = [ "stm32-metapac/stm32g0c1kc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0c1ke = [ "stm32-metapac/stm32g0c1ke", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0c1mc = [ "stm32-metapac/stm32g0c1mc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0c1me = [ "stm32-metapac/stm32g0c1me", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0c1ne = [ "stm32-metapac/stm32g0c1ne", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0c1rc = [ "stm32-metapac/stm32g0c1rc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0c1re = [ "stm32-metapac/stm32g0c1re", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0c1vc = [ "stm32-metapac/stm32g0c1vc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g0c1ve = [ "stm32-metapac/stm32g0c1ve", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g431c6 = [ "stm32-metapac/stm32g431c6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g431c8 = [ "stm32-metapac/stm32g431c8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g431cb = [ "stm32-metapac/stm32g431cb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g431k6 = [ "stm32-metapac/stm32g431k6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g431k8 = [ "stm32-metapac/stm32g431k8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g431kb = [ "stm32-metapac/stm32g431kb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g431m6 = [ "stm32-metapac/stm32g431m6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g431m8 = [ "stm32-metapac/stm32g431m8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g431mb = [ "stm32-metapac/stm32g431mb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g431r6 = [ "stm32-metapac/stm32g431r6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g431r8 = [ "stm32-metapac/stm32g431r8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g431rb = [ "stm32-metapac/stm32g431rb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g431v6 = [ "stm32-metapac/stm32g431v6", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g431v8 = [ "stm32-metapac/stm32g431v8", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g431vb = [ "stm32-metapac/stm32g431vb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g441cb = [ "stm32-metapac/stm32g441cb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g441kb = [ "stm32-metapac/stm32g441kb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g441mb = [ "stm32-metapac/stm32g441mb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g441rb = [ "stm32-metapac/stm32g441rb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g441vb = [ "stm32-metapac/stm32g441vb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g471cc = [ "stm32-metapac/stm32g471cc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g471ce = [ "stm32-metapac/stm32g471ce", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g471mc = [ "stm32-metapac/stm32g471mc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g471me = [ "stm32-metapac/stm32g471me", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g471qc = [ "stm32-metapac/stm32g471qc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g471qe = [ "stm32-metapac/stm32g471qe", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g471rc = [ "stm32-metapac/stm32g471rc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g471re = [ "stm32-metapac/stm32g471re", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g471vc = [ "stm32-metapac/stm32g471vc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g471ve = [ "stm32-metapac/stm32g471ve", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473cb = [ "stm32-metapac/stm32g473cb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473cc = [ "stm32-metapac/stm32g473cc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473ce = [ "stm32-metapac/stm32g473ce", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473mb = [ "stm32-metapac/stm32g473mb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473mc = [ "stm32-metapac/stm32g473mc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473me = [ "stm32-metapac/stm32g473me", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473pb = [ "stm32-metapac/stm32g473pb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473pc = [ "stm32-metapac/stm32g473pc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473pe = [ "stm32-metapac/stm32g473pe", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473qb = [ "stm32-metapac/stm32g473qb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473qc = [ "stm32-metapac/stm32g473qc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473qe = [ "stm32-metapac/stm32g473qe", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473rb = [ "stm32-metapac/stm32g473rb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473rc = [ "stm32-metapac/stm32g473rc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473re = [ "stm32-metapac/stm32g473re", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473vb = [ "stm32-metapac/stm32g473vb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473vc = [ "stm32-metapac/stm32g473vc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g473ve = [ "stm32-metapac/stm32g473ve", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474cb = [ "stm32-metapac/stm32g474cb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474cc = [ "stm32-metapac/stm32g474cc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474ce = [ "stm32-metapac/stm32g474ce", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474mb = [ "stm32-metapac/stm32g474mb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474mc = [ "stm32-metapac/stm32g474mc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474me = [ "stm32-metapac/stm32g474me", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474pb = [ "stm32-metapac/stm32g474pb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474pc = [ "stm32-metapac/stm32g474pc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474pe = [ "stm32-metapac/stm32g474pe", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474qb = [ "stm32-metapac/stm32g474qb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474qc = [ "stm32-metapac/stm32g474qc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474qe = [ "stm32-metapac/stm32g474qe", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474rb = [ "stm32-metapac/stm32g474rb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474rc = [ "stm32-metapac/stm32g474rc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474re = [ "stm32-metapac/stm32g474re", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474vb = [ "stm32-metapac/stm32g474vb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474vc = [ "stm32-metapac/stm32g474vc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g474ve = [ "stm32-metapac/stm32g474ve", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g483ce = [ "stm32-metapac/stm32g483ce", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g483me = [ "stm32-metapac/stm32g483me", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g483pe = [ "stm32-metapac/stm32g483pe", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g483qe = [ "stm32-metapac/stm32g483qe", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g483re = [ "stm32-metapac/stm32g483re", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g483ve = [ "stm32-metapac/stm32g483ve", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g484ce = [ "stm32-metapac/stm32g484ce", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g484me = [ "stm32-metapac/stm32g484me", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g484pe = [ "stm32-metapac/stm32g484pe", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g484qe = [ "stm32-metapac/stm32g484qe", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g484re = [ "stm32-metapac/stm32g484re", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g484ve = [ "stm32-metapac/stm32g484ve", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g491cc = [ "stm32-metapac/stm32g491cc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g491ce = [ "stm32-metapac/stm32g491ce", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g491kc = [ "stm32-metapac/stm32g491kc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g491ke = [ "stm32-metapac/stm32g491ke", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g491mc = [ "stm32-metapac/stm32g491mc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g491me = [ "stm32-metapac/stm32g491me", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g491rc = [ "stm32-metapac/stm32g491rc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g491re = [ "stm32-metapac/stm32g491re", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g491vc = [ "stm32-metapac/stm32g491vc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g491ve = [ "stm32-metapac/stm32g491ve", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g4a1ce = [ "stm32-metapac/stm32g4a1ce", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g4a1ke = [ "stm32-metapac/stm32g4a1ke", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g4a1me = [ "stm32-metapac/stm32g4a1me", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g4a1re = [ "stm32-metapac/stm32g4a1re", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32g4a1ve = [ "stm32-metapac/stm32g4a1ve", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h503cb = [ "stm32-metapac/stm32h503cb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h503eb = [ "stm32-metapac/stm32h503eb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h503kb = [ "stm32-metapac/stm32h503kb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h503rb = [ "stm32-metapac/stm32h503rb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h562ag = [ "stm32-metapac/stm32h562ag", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h562ai = [ "stm32-metapac/stm32h562ai", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h562ig = [ "stm32-metapac/stm32h562ig", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h562ii = [ "stm32-metapac/stm32h562ii", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h562rg = [ "stm32-metapac/stm32h562rg", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h562ri = [ "stm32-metapac/stm32h562ri", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h562vg = [ "stm32-metapac/stm32h562vg", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h562vi = [ "stm32-metapac/stm32h562vi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h562zg = [ "stm32-metapac/stm32h562zg", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h562zi = [ "stm32-metapac/stm32h562zi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h563ag = [ "stm32-metapac/stm32h563ag", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h563ai = [ "stm32-metapac/stm32h563ai", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h563ig = [ "stm32-metapac/stm32h563ig", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h563ii = [ "stm32-metapac/stm32h563ii", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h563mi = [ "stm32-metapac/stm32h563mi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h563rg = [ "stm32-metapac/stm32h563rg", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h563ri = [ "stm32-metapac/stm32h563ri", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h563vg = [ "stm32-metapac/stm32h563vg", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h563vi = [ "stm32-metapac/stm32h563vi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h563zg = [ "stm32-metapac/stm32h563zg", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h563zi = [ "stm32-metapac/stm32h563zi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h573ai = [ "stm32-metapac/stm32h573ai", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h573ii = [ "stm32-metapac/stm32h573ii", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h573mi = [ "stm32-metapac/stm32h573mi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h573ri = [ "stm32-metapac/stm32h573ri", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h573vi = [ "stm32-metapac/stm32h573vi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h573zi = [ "stm32-metapac/stm32h573zi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32h723ve = [ "stm32-metapac/stm32h723ve", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h723vg = [ "stm32-metapac/stm32h723vg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h723ze = [ "stm32-metapac/stm32h723ze", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h723zg = [ "stm32-metapac/stm32h723zg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h725ae = [ "stm32-metapac/stm32h725ae", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h725ag = [ "stm32-metapac/stm32h725ag", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h725ie = [ "stm32-metapac/stm32h725ie", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h725ig = [ "stm32-metapac/stm32h725ig", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h725re = [ "stm32-metapac/stm32h725re", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h725rg = [ "stm32-metapac/stm32h725rg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h725ve = [ "stm32-metapac/stm32h725ve", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h725vg = [ "stm32-metapac/stm32h725vg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h725ze = [ "stm32-metapac/stm32h725ze", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h725zg = [ "stm32-metapac/stm32h725zg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h730ab = [ "stm32-metapac/stm32h730ab", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h730ib = [ "stm32-metapac/stm32h730ib", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h730vb = [ "stm32-metapac/stm32h730vb", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h730zb = [ "stm32-metapac/stm32h730zb", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h733vg = [ "stm32-metapac/stm32h733vg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h733zg = [ "stm32-metapac/stm32h733zg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h735ag = [ "stm32-metapac/stm32h735ag", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h735ig = [ "stm32-metapac/stm32h735ig", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h735rg = [ "stm32-metapac/stm32h735rg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h735vg = [ "stm32-metapac/stm32h735vg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h735zg = [ "stm32-metapac/stm32h735zg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h742ag = [ "stm32-metapac/stm32h742ag", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h742ai = [ "stm32-metapac/stm32h742ai", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h742bg = [ "stm32-metapac/stm32h742bg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h742bi = [ "stm32-metapac/stm32h742bi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h742ig = [ "stm32-metapac/stm32h742ig", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h742ii = [ "stm32-metapac/stm32h742ii", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h742vg = [ "stm32-metapac/stm32h742vg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h742vi = [ "stm32-metapac/stm32h742vi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h742xg = [ "stm32-metapac/stm32h742xg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h742xi = [ "stm32-metapac/stm32h742xi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h742zg = [ "stm32-metapac/stm32h742zg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h742zi = [ "stm32-metapac/stm32h742zi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h743ag = [ "stm32-metapac/stm32h743ag", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h743ai = [ "stm32-metapac/stm32h743ai", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h743bg = [ "stm32-metapac/stm32h743bg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h743bi = [ "stm32-metapac/stm32h743bi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h743ig = [ "stm32-metapac/stm32h743ig", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h743ii = [ "stm32-metapac/stm32h743ii", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h743vg = [ "stm32-metapac/stm32h743vg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h743vi = [ "stm32-metapac/stm32h743vi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h743xg = [ "stm32-metapac/stm32h743xg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h743xi = [ "stm32-metapac/stm32h743xi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h743zg = [ "stm32-metapac/stm32h743zg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h743zi = [ "stm32-metapac/stm32h743zi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745bg-cm7 = [ "stm32-metapac/stm32h745bg-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745bg-cm4 = [ "stm32-metapac/stm32h745bg-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745bi-cm7 = [ "stm32-metapac/stm32h745bi-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745bi-cm4 = [ "stm32-metapac/stm32h745bi-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745ig-cm7 = [ "stm32-metapac/stm32h745ig-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745ig-cm4 = [ "stm32-metapac/stm32h745ig-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745ii-cm7 = [ "stm32-metapac/stm32h745ii-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745ii-cm4 = [ "stm32-metapac/stm32h745ii-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745xg-cm7 = [ "stm32-metapac/stm32h745xg-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745xg-cm4 = [ "stm32-metapac/stm32h745xg-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745xi-cm7 = [ "stm32-metapac/stm32h745xi-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745xi-cm4 = [ "stm32-metapac/stm32h745xi-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745zg-cm7 = [ "stm32-metapac/stm32h745zg-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745zg-cm4 = [ "stm32-metapac/stm32h745zg-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745zi-cm7 = [ "stm32-metapac/stm32h745zi-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h745zi-cm4 = [ "stm32-metapac/stm32h745zi-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747ag-cm7 = [ "stm32-metapac/stm32h747ag-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747ag-cm4 = [ "stm32-metapac/stm32h747ag-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747ai-cm7 = [ "stm32-metapac/stm32h747ai-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747ai-cm4 = [ "stm32-metapac/stm32h747ai-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747bg-cm7 = [ "stm32-metapac/stm32h747bg-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747bg-cm4 = [ "stm32-metapac/stm32h747bg-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747bi-cm7 = [ "stm32-metapac/stm32h747bi-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747bi-cm4 = [ "stm32-metapac/stm32h747bi-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747ig-cm7 = [ "stm32-metapac/stm32h747ig-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747ig-cm4 = [ "stm32-metapac/stm32h747ig-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747ii-cm7 = [ "stm32-metapac/stm32h747ii-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747ii-cm4 = [ "stm32-metapac/stm32h747ii-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747xg-cm7 = [ "stm32-metapac/stm32h747xg-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747xg-cm4 = [ "stm32-metapac/stm32h747xg-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747xi-cm7 = [ "stm32-metapac/stm32h747xi-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747xi-cm4 = [ "stm32-metapac/stm32h747xi-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747zi-cm7 = [ "stm32-metapac/stm32h747zi-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h747zi-cm4 = [ "stm32-metapac/stm32h747zi-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h750ib = [ "stm32-metapac/stm32h750ib", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h750vb = [ "stm32-metapac/stm32h750vb", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h750xb = [ "stm32-metapac/stm32h750xb", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h750zb = [ "stm32-metapac/stm32h750zb", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h753ai = [ "stm32-metapac/stm32h753ai", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h753bi = [ "stm32-metapac/stm32h753bi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h753ii = [ "stm32-metapac/stm32h753ii", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h753vi = [ "stm32-metapac/stm32h753vi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h753xi = [ "stm32-metapac/stm32h753xi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h753zi = [ "stm32-metapac/stm32h753zi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h755bi-cm7 = [ "stm32-metapac/stm32h755bi-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h755bi-cm4 = [ "stm32-metapac/stm32h755bi-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h755ii-cm7 = [ "stm32-metapac/stm32h755ii-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h755ii-cm4 = [ "stm32-metapac/stm32h755ii-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h755xi-cm7 = [ "stm32-metapac/stm32h755xi-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h755xi-cm4 = [ "stm32-metapac/stm32h755xi-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h755zi-cm7 = [ "stm32-metapac/stm32h755zi-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h755zi-cm4 = [ "stm32-metapac/stm32h755zi-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h757ai-cm7 = [ "stm32-metapac/stm32h757ai-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h757ai-cm4 = [ "stm32-metapac/stm32h757ai-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h757bi-cm7 = [ "stm32-metapac/stm32h757bi-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h757bi-cm4 = [ "stm32-metapac/stm32h757bi-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h757ii-cm7 = [ "stm32-metapac/stm32h757ii-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h757ii-cm4 = [ "stm32-metapac/stm32h757ii-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h757xi-cm7 = [ "stm32-metapac/stm32h757xi-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h757xi-cm4 = [ "stm32-metapac/stm32h757xi-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h757zi-cm7 = [ "stm32-metapac/stm32h757zi-cm7", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h757zi-cm4 = [ "stm32-metapac/stm32h757zi-cm4", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7a3ag = [ "stm32-metapac/stm32h7a3ag", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7a3ai = [ "stm32-metapac/stm32h7a3ai", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7a3ig = [ "stm32-metapac/stm32h7a3ig", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7a3ii = [ "stm32-metapac/stm32h7a3ii", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7a3lg = [ "stm32-metapac/stm32h7a3lg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7a3li = [ "stm32-metapac/stm32h7a3li", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7a3ng = [ "stm32-metapac/stm32h7a3ng", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7a3ni = [ "stm32-metapac/stm32h7a3ni", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7a3qi = [ "stm32-metapac/stm32h7a3qi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7a3rg = [ "stm32-metapac/stm32h7a3rg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7a3ri = [ "stm32-metapac/stm32h7a3ri", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7a3vg = [ "stm32-metapac/stm32h7a3vg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7a3vi = [ "stm32-metapac/stm32h7a3vi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7a3zg = [ "stm32-metapac/stm32h7a3zg", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7a3zi = [ "stm32-metapac/stm32h7a3zi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7b0ab = [ "stm32-metapac/stm32h7b0ab", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7b0ib = [ "stm32-metapac/stm32h7b0ib", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7b0rb = [ "stm32-metapac/stm32h7b0rb", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7b0vb = [ "stm32-metapac/stm32h7b0vb", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7b0zb = [ "stm32-metapac/stm32h7b0zb", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7b3ai = [ "stm32-metapac/stm32h7b3ai", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7b3ii = [ "stm32-metapac/stm32h7b3ii", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7b3li = [ "stm32-metapac/stm32h7b3li", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7b3ni = [ "stm32-metapac/stm32h7b3ni", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7b3qi = [ "stm32-metapac/stm32h7b3qi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7b3ri = [ "stm32-metapac/stm32h7b3ri", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7b3vi = [ "stm32-metapac/stm32h7b3vi", "dep:fdcan", "fdcan/fdcan_h7" ] -stm32h7b3zi = [ "stm32-metapac/stm32h7b3zi", "dep:fdcan", "fdcan/fdcan_h7" ] +stm32g030c6 = [ "stm32-metapac/stm32g030c6" ] +stm32g030c8 = [ "stm32-metapac/stm32g030c8" ] +stm32g030f6 = [ "stm32-metapac/stm32g030f6" ] +stm32g030j6 = [ "stm32-metapac/stm32g030j6" ] +stm32g030k6 = [ "stm32-metapac/stm32g030k6" ] +stm32g030k8 = [ "stm32-metapac/stm32g030k8" ] +stm32g031c4 = [ "stm32-metapac/stm32g031c4" ] +stm32g031c6 = [ "stm32-metapac/stm32g031c6" ] +stm32g031c8 = [ "stm32-metapac/stm32g031c8" ] +stm32g031f4 = [ "stm32-metapac/stm32g031f4" ] +stm32g031f6 = [ "stm32-metapac/stm32g031f6" ] +stm32g031f8 = [ "stm32-metapac/stm32g031f8" ] +stm32g031g4 = [ "stm32-metapac/stm32g031g4" ] +stm32g031g6 = [ "stm32-metapac/stm32g031g6" ] +stm32g031g8 = [ "stm32-metapac/stm32g031g8" ] +stm32g031j4 = [ "stm32-metapac/stm32g031j4" ] +stm32g031j6 = [ "stm32-metapac/stm32g031j6" ] +stm32g031k4 = [ "stm32-metapac/stm32g031k4" ] +stm32g031k6 = [ "stm32-metapac/stm32g031k6" ] +stm32g031k8 = [ "stm32-metapac/stm32g031k8" ] +stm32g031y8 = [ "stm32-metapac/stm32g031y8" ] +stm32g041c6 = [ "stm32-metapac/stm32g041c6" ] +stm32g041c8 = [ "stm32-metapac/stm32g041c8" ] +stm32g041f6 = [ "stm32-metapac/stm32g041f6" ] +stm32g041f8 = [ "stm32-metapac/stm32g041f8" ] +stm32g041g6 = [ "stm32-metapac/stm32g041g6" ] +stm32g041g8 = [ "stm32-metapac/stm32g041g8" ] +stm32g041j6 = [ "stm32-metapac/stm32g041j6" ] +stm32g041k6 = [ "stm32-metapac/stm32g041k6" ] +stm32g041k8 = [ "stm32-metapac/stm32g041k8" ] +stm32g041y8 = [ "stm32-metapac/stm32g041y8" ] +stm32g050c6 = [ "stm32-metapac/stm32g050c6" ] +stm32g050c8 = [ "stm32-metapac/stm32g050c8" ] +stm32g050f6 = [ "stm32-metapac/stm32g050f6" ] +stm32g050k6 = [ "stm32-metapac/stm32g050k6" ] +stm32g050k8 = [ "stm32-metapac/stm32g050k8" ] +stm32g051c6 = [ "stm32-metapac/stm32g051c6" ] +stm32g051c8 = [ "stm32-metapac/stm32g051c8" ] +stm32g051f6 = [ "stm32-metapac/stm32g051f6" ] +stm32g051f8 = [ "stm32-metapac/stm32g051f8" ] +stm32g051g6 = [ "stm32-metapac/stm32g051g6" ] +stm32g051g8 = [ "stm32-metapac/stm32g051g8" ] +stm32g051k6 = [ "stm32-metapac/stm32g051k6" ] +stm32g051k8 = [ "stm32-metapac/stm32g051k8" ] +stm32g061c6 = [ "stm32-metapac/stm32g061c6" ] +stm32g061c8 = [ "stm32-metapac/stm32g061c8" ] +stm32g061f6 = [ "stm32-metapac/stm32g061f6" ] +stm32g061f8 = [ "stm32-metapac/stm32g061f8" ] +stm32g061g6 = [ "stm32-metapac/stm32g061g6" ] +stm32g061g8 = [ "stm32-metapac/stm32g061g8" ] +stm32g061k6 = [ "stm32-metapac/stm32g061k6" ] +stm32g061k8 = [ "stm32-metapac/stm32g061k8" ] +stm32g070cb = [ "stm32-metapac/stm32g070cb" ] +stm32g070kb = [ "stm32-metapac/stm32g070kb" ] +stm32g070rb = [ "stm32-metapac/stm32g070rb" ] +stm32g071c6 = [ "stm32-metapac/stm32g071c6" ] +stm32g071c8 = [ "stm32-metapac/stm32g071c8" ] +stm32g071cb = [ "stm32-metapac/stm32g071cb" ] +stm32g071eb = [ "stm32-metapac/stm32g071eb" ] +stm32g071g6 = [ "stm32-metapac/stm32g071g6" ] +stm32g071g8 = [ "stm32-metapac/stm32g071g8" ] +stm32g071gb = [ "stm32-metapac/stm32g071gb" ] +stm32g071k6 = [ "stm32-metapac/stm32g071k6" ] +stm32g071k8 = [ "stm32-metapac/stm32g071k8" ] +stm32g071kb = [ "stm32-metapac/stm32g071kb" ] +stm32g071r6 = [ "stm32-metapac/stm32g071r6" ] +stm32g071r8 = [ "stm32-metapac/stm32g071r8" ] +stm32g071rb = [ "stm32-metapac/stm32g071rb" ] +stm32g081cb = [ "stm32-metapac/stm32g081cb" ] +stm32g081eb = [ "stm32-metapac/stm32g081eb" ] +stm32g081gb = [ "stm32-metapac/stm32g081gb" ] +stm32g081kb = [ "stm32-metapac/stm32g081kb" ] +stm32g081rb = [ "stm32-metapac/stm32g081rb" ] +stm32g0b0ce = [ "stm32-metapac/stm32g0b0ce" ] +stm32g0b0ke = [ "stm32-metapac/stm32g0b0ke" ] +stm32g0b0re = [ "stm32-metapac/stm32g0b0re" ] +stm32g0b0ve = [ "stm32-metapac/stm32g0b0ve" ] +stm32g0b1cb = [ "stm32-metapac/stm32g0b1cb" ] +stm32g0b1cc = [ "stm32-metapac/stm32g0b1cc" ] +stm32g0b1ce = [ "stm32-metapac/stm32g0b1ce" ] +stm32g0b1kb = [ "stm32-metapac/stm32g0b1kb" ] +stm32g0b1kc = [ "stm32-metapac/stm32g0b1kc" ] +stm32g0b1ke = [ "stm32-metapac/stm32g0b1ke" ] +stm32g0b1mb = [ "stm32-metapac/stm32g0b1mb" ] +stm32g0b1mc = [ "stm32-metapac/stm32g0b1mc" ] +stm32g0b1me = [ "stm32-metapac/stm32g0b1me" ] +stm32g0b1ne = [ "stm32-metapac/stm32g0b1ne" ] +stm32g0b1rb = [ "stm32-metapac/stm32g0b1rb" ] +stm32g0b1rc = [ "stm32-metapac/stm32g0b1rc" ] +stm32g0b1re = [ "stm32-metapac/stm32g0b1re" ] +stm32g0b1vb = [ "stm32-metapac/stm32g0b1vb" ] +stm32g0b1vc = [ "stm32-metapac/stm32g0b1vc" ] +stm32g0b1ve = [ "stm32-metapac/stm32g0b1ve" ] +stm32g0c1cc = [ "stm32-metapac/stm32g0c1cc" ] +stm32g0c1ce = [ "stm32-metapac/stm32g0c1ce" ] +stm32g0c1kc = [ "stm32-metapac/stm32g0c1kc" ] +stm32g0c1ke = [ "stm32-metapac/stm32g0c1ke" ] +stm32g0c1mc = [ "stm32-metapac/stm32g0c1mc" ] +stm32g0c1me = [ "stm32-metapac/stm32g0c1me" ] +stm32g0c1ne = [ "stm32-metapac/stm32g0c1ne" ] +stm32g0c1rc = [ "stm32-metapac/stm32g0c1rc" ] +stm32g0c1re = [ "stm32-metapac/stm32g0c1re" ] +stm32g0c1vc = [ "stm32-metapac/stm32g0c1vc" ] +stm32g0c1ve = [ "stm32-metapac/stm32g0c1ve" ] +stm32g431c6 = [ "stm32-metapac/stm32g431c6" ] +stm32g431c8 = [ "stm32-metapac/stm32g431c8" ] +stm32g431cb = [ "stm32-metapac/stm32g431cb" ] +stm32g431k6 = [ "stm32-metapac/stm32g431k6" ] +stm32g431k8 = [ "stm32-metapac/stm32g431k8" ] +stm32g431kb = [ "stm32-metapac/stm32g431kb" ] +stm32g431m6 = [ "stm32-metapac/stm32g431m6" ] +stm32g431m8 = [ "stm32-metapac/stm32g431m8" ] +stm32g431mb = [ "stm32-metapac/stm32g431mb" ] +stm32g431r6 = [ "stm32-metapac/stm32g431r6" ] +stm32g431r8 = [ "stm32-metapac/stm32g431r8" ] +stm32g431rb = [ "stm32-metapac/stm32g431rb" ] +stm32g431v6 = [ "stm32-metapac/stm32g431v6" ] +stm32g431v8 = [ "stm32-metapac/stm32g431v8" ] +stm32g431vb = [ "stm32-metapac/stm32g431vb" ] +stm32g441cb = [ "stm32-metapac/stm32g441cb" ] +stm32g441kb = [ "stm32-metapac/stm32g441kb" ] +stm32g441mb = [ "stm32-metapac/stm32g441mb" ] +stm32g441rb = [ "stm32-metapac/stm32g441rb" ] +stm32g441vb = [ "stm32-metapac/stm32g441vb" ] +stm32g471cc = [ "stm32-metapac/stm32g471cc" ] +stm32g471ce = [ "stm32-metapac/stm32g471ce" ] +stm32g471mc = [ "stm32-metapac/stm32g471mc" ] +stm32g471me = [ "stm32-metapac/stm32g471me" ] +stm32g471qc = [ "stm32-metapac/stm32g471qc" ] +stm32g471qe = [ "stm32-metapac/stm32g471qe" ] +stm32g471rc = [ "stm32-metapac/stm32g471rc" ] +stm32g471re = [ "stm32-metapac/stm32g471re" ] +stm32g471vc = [ "stm32-metapac/stm32g471vc" ] +stm32g471ve = [ "stm32-metapac/stm32g471ve" ] +stm32g473cb = [ "stm32-metapac/stm32g473cb" ] +stm32g473cc = [ "stm32-metapac/stm32g473cc" ] +stm32g473ce = [ "stm32-metapac/stm32g473ce" ] +stm32g473mb = [ "stm32-metapac/stm32g473mb" ] +stm32g473mc = [ "stm32-metapac/stm32g473mc" ] +stm32g473me = [ "stm32-metapac/stm32g473me" ] +stm32g473pb = [ "stm32-metapac/stm32g473pb" ] +stm32g473pc = [ "stm32-metapac/stm32g473pc" ] +stm32g473pe = [ "stm32-metapac/stm32g473pe" ] +stm32g473qb = [ "stm32-metapac/stm32g473qb" ] +stm32g473qc = [ "stm32-metapac/stm32g473qc" ] +stm32g473qe = [ "stm32-metapac/stm32g473qe" ] +stm32g473rb = [ "stm32-metapac/stm32g473rb" ] +stm32g473rc = [ "stm32-metapac/stm32g473rc" ] +stm32g473re = [ "stm32-metapac/stm32g473re" ] +stm32g473vb = [ "stm32-metapac/stm32g473vb" ] +stm32g473vc = [ "stm32-metapac/stm32g473vc" ] +stm32g473ve = [ "stm32-metapac/stm32g473ve" ] +stm32g474cb = [ "stm32-metapac/stm32g474cb" ] +stm32g474cc = [ "stm32-metapac/stm32g474cc" ] +stm32g474ce = [ "stm32-metapac/stm32g474ce" ] +stm32g474mb = [ "stm32-metapac/stm32g474mb" ] +stm32g474mc = [ "stm32-metapac/stm32g474mc" ] +stm32g474me = [ "stm32-metapac/stm32g474me" ] +stm32g474pb = [ "stm32-metapac/stm32g474pb" ] +stm32g474pc = [ "stm32-metapac/stm32g474pc" ] +stm32g474pe = [ "stm32-metapac/stm32g474pe" ] +stm32g474qb = [ "stm32-metapac/stm32g474qb" ] +stm32g474qc = [ "stm32-metapac/stm32g474qc" ] +stm32g474qe = [ "stm32-metapac/stm32g474qe" ] +stm32g474rb = [ "stm32-metapac/stm32g474rb" ] +stm32g474rc = [ "stm32-metapac/stm32g474rc" ] +stm32g474re = [ "stm32-metapac/stm32g474re" ] +stm32g474vb = [ "stm32-metapac/stm32g474vb" ] +stm32g474vc = [ "stm32-metapac/stm32g474vc" ] +stm32g474ve = [ "stm32-metapac/stm32g474ve" ] +stm32g483ce = [ "stm32-metapac/stm32g483ce" ] +stm32g483me = [ "stm32-metapac/stm32g483me" ] +stm32g483pe = [ "stm32-metapac/stm32g483pe" ] +stm32g483qe = [ "stm32-metapac/stm32g483qe" ] +stm32g483re = [ "stm32-metapac/stm32g483re" ] +stm32g483ve = [ "stm32-metapac/stm32g483ve" ] +stm32g484ce = [ "stm32-metapac/stm32g484ce" ] +stm32g484me = [ "stm32-metapac/stm32g484me" ] +stm32g484pe = [ "stm32-metapac/stm32g484pe" ] +stm32g484qe = [ "stm32-metapac/stm32g484qe" ] +stm32g484re = [ "stm32-metapac/stm32g484re" ] +stm32g484ve = [ "stm32-metapac/stm32g484ve" ] +stm32g491cc = [ "stm32-metapac/stm32g491cc" ] +stm32g491ce = [ "stm32-metapac/stm32g491ce" ] +stm32g491kc = [ "stm32-metapac/stm32g491kc" ] +stm32g491ke = [ "stm32-metapac/stm32g491ke" ] +stm32g491mc = [ "stm32-metapac/stm32g491mc" ] +stm32g491me = [ "stm32-metapac/stm32g491me" ] +stm32g491rc = [ "stm32-metapac/stm32g491rc" ] +stm32g491re = [ "stm32-metapac/stm32g491re" ] +stm32g491vc = [ "stm32-metapac/stm32g491vc" ] +stm32g491ve = [ "stm32-metapac/stm32g491ve" ] +stm32g4a1ce = [ "stm32-metapac/stm32g4a1ce" ] +stm32g4a1ke = [ "stm32-metapac/stm32g4a1ke" ] +stm32g4a1me = [ "stm32-metapac/stm32g4a1me" ] +stm32g4a1re = [ "stm32-metapac/stm32g4a1re" ] +stm32g4a1ve = [ "stm32-metapac/stm32g4a1ve" ] +stm32h503cb = [ "stm32-metapac/stm32h503cb" ] +stm32h503eb = [ "stm32-metapac/stm32h503eb" ] +stm32h503kb = [ "stm32-metapac/stm32h503kb" ] +stm32h503rb = [ "stm32-metapac/stm32h503rb" ] +stm32h523cc = [ "stm32-metapac/stm32h523cc" ] +stm32h523ce = [ "stm32-metapac/stm32h523ce" ] +stm32h523he = [ "stm32-metapac/stm32h523he" ] +stm32h523rc = [ "stm32-metapac/stm32h523rc" ] +stm32h523re = [ "stm32-metapac/stm32h523re" ] +stm32h523vc = [ "stm32-metapac/stm32h523vc" ] +stm32h523ve = [ "stm32-metapac/stm32h523ve" ] +stm32h523zc = [ "stm32-metapac/stm32h523zc" ] +stm32h523ze = [ "stm32-metapac/stm32h523ze" ] +stm32h533ce = [ "stm32-metapac/stm32h533ce" ] +stm32h533he = [ "stm32-metapac/stm32h533he" ] +stm32h533re = [ "stm32-metapac/stm32h533re" ] +stm32h533ve = [ "stm32-metapac/stm32h533ve" ] +stm32h533ze = [ "stm32-metapac/stm32h533ze" ] +stm32h562ag = [ "stm32-metapac/stm32h562ag" ] +stm32h562ai = [ "stm32-metapac/stm32h562ai" ] +stm32h562ig = [ "stm32-metapac/stm32h562ig" ] +stm32h562ii = [ "stm32-metapac/stm32h562ii" ] +stm32h562rg = [ "stm32-metapac/stm32h562rg" ] +stm32h562ri = [ "stm32-metapac/stm32h562ri" ] +stm32h562vg = [ "stm32-metapac/stm32h562vg" ] +stm32h562vi = [ "stm32-metapac/stm32h562vi" ] +stm32h562zg = [ "stm32-metapac/stm32h562zg" ] +stm32h562zi = [ "stm32-metapac/stm32h562zi" ] +stm32h563ag = [ "stm32-metapac/stm32h563ag" ] +stm32h563ai = [ "stm32-metapac/stm32h563ai" ] +stm32h563ig = [ "stm32-metapac/stm32h563ig" ] +stm32h563ii = [ "stm32-metapac/stm32h563ii" ] +stm32h563mi = [ "stm32-metapac/stm32h563mi" ] +stm32h563rg = [ "stm32-metapac/stm32h563rg" ] +stm32h563ri = [ "stm32-metapac/stm32h563ri" ] +stm32h563vg = [ "stm32-metapac/stm32h563vg" ] +stm32h563vi = [ "stm32-metapac/stm32h563vi" ] +stm32h563zg = [ "stm32-metapac/stm32h563zg" ] +stm32h563zi = [ "stm32-metapac/stm32h563zi" ] +stm32h573ai = [ "stm32-metapac/stm32h573ai" ] +stm32h573ii = [ "stm32-metapac/stm32h573ii" ] +stm32h573mi = [ "stm32-metapac/stm32h573mi" ] +stm32h573ri = [ "stm32-metapac/stm32h573ri" ] +stm32h573vi = [ "stm32-metapac/stm32h573vi" ] +stm32h573zi = [ "stm32-metapac/stm32h573zi" ] +stm32h723ve = [ "stm32-metapac/stm32h723ve" ] +stm32h723vg = [ "stm32-metapac/stm32h723vg" ] +stm32h723ze = [ "stm32-metapac/stm32h723ze" ] +stm32h723zg = [ "stm32-metapac/stm32h723zg" ] +stm32h725ae = [ "stm32-metapac/stm32h725ae" ] +stm32h725ag = [ "stm32-metapac/stm32h725ag" ] +stm32h725ie = [ "stm32-metapac/stm32h725ie" ] +stm32h725ig = [ "stm32-metapac/stm32h725ig" ] +stm32h725re = [ "stm32-metapac/stm32h725re" ] +stm32h725rg = [ "stm32-metapac/stm32h725rg" ] +stm32h725ve = [ "stm32-metapac/stm32h725ve" ] +stm32h725vg = [ "stm32-metapac/stm32h725vg" ] +stm32h725ze = [ "stm32-metapac/stm32h725ze" ] +stm32h725zg = [ "stm32-metapac/stm32h725zg" ] +stm32h730ab = [ "stm32-metapac/stm32h730ab" ] +stm32h730ib = [ "stm32-metapac/stm32h730ib" ] +stm32h730vb = [ "stm32-metapac/stm32h730vb" ] +stm32h730zb = [ "stm32-metapac/stm32h730zb" ] +stm32h733vg = [ "stm32-metapac/stm32h733vg" ] +stm32h733zg = [ "stm32-metapac/stm32h733zg" ] +stm32h735ag = [ "stm32-metapac/stm32h735ag" ] +stm32h735ig = [ "stm32-metapac/stm32h735ig" ] +stm32h735rg = [ "stm32-metapac/stm32h735rg" ] +stm32h735vg = [ "stm32-metapac/stm32h735vg" ] +stm32h735zg = [ "stm32-metapac/stm32h735zg" ] +stm32h742ag = [ "stm32-metapac/stm32h742ag" ] +stm32h742ai = [ "stm32-metapac/stm32h742ai" ] +stm32h742bg = [ "stm32-metapac/stm32h742bg" ] +stm32h742bi = [ "stm32-metapac/stm32h742bi" ] +stm32h742ig = [ "stm32-metapac/stm32h742ig" ] +stm32h742ii = [ "stm32-metapac/stm32h742ii" ] +stm32h742vg = [ "stm32-metapac/stm32h742vg" ] +stm32h742vi = [ "stm32-metapac/stm32h742vi" ] +stm32h742xg = [ "stm32-metapac/stm32h742xg" ] +stm32h742xi = [ "stm32-metapac/stm32h742xi" ] +stm32h742zg = [ "stm32-metapac/stm32h742zg" ] +stm32h742zi = [ "stm32-metapac/stm32h742zi" ] +stm32h743ag = [ "stm32-metapac/stm32h743ag" ] +stm32h743ai = [ "stm32-metapac/stm32h743ai" ] +stm32h743bg = [ "stm32-metapac/stm32h743bg" ] +stm32h743bi = [ "stm32-metapac/stm32h743bi" ] +stm32h743ig = [ "stm32-metapac/stm32h743ig" ] +stm32h743ii = [ "stm32-metapac/stm32h743ii" ] +stm32h743vg = [ "stm32-metapac/stm32h743vg" ] +stm32h743vi = [ "stm32-metapac/stm32h743vi" ] +stm32h743xg = [ "stm32-metapac/stm32h743xg" ] +stm32h743xi = [ "stm32-metapac/stm32h743xi" ] +stm32h743zg = [ "stm32-metapac/stm32h743zg" ] +stm32h743zi = [ "stm32-metapac/stm32h743zi" ] +stm32h745bg-cm7 = [ "stm32-metapac/stm32h745bg-cm7", "_dual-core" ] +stm32h745bg-cm4 = [ "stm32-metapac/stm32h745bg-cm4", "_dual-core" ] +stm32h745bi-cm7 = [ "stm32-metapac/stm32h745bi-cm7", "_dual-core" ] +stm32h745bi-cm4 = [ "stm32-metapac/stm32h745bi-cm4", "_dual-core" ] +stm32h745ig-cm7 = [ "stm32-metapac/stm32h745ig-cm7", "_dual-core" ] +stm32h745ig-cm4 = [ "stm32-metapac/stm32h745ig-cm4", "_dual-core" ] +stm32h745ii-cm7 = [ "stm32-metapac/stm32h745ii-cm7", "_dual-core" ] +stm32h745ii-cm4 = [ "stm32-metapac/stm32h745ii-cm4", "_dual-core" ] +stm32h745xg-cm7 = [ "stm32-metapac/stm32h745xg-cm7", "_dual-core" ] +stm32h745xg-cm4 = [ "stm32-metapac/stm32h745xg-cm4", "_dual-core" ] +stm32h745xi-cm7 = [ "stm32-metapac/stm32h745xi-cm7", "_dual-core" ] +stm32h745xi-cm4 = [ "stm32-metapac/stm32h745xi-cm4", "_dual-core" ] +stm32h745zg-cm7 = [ "stm32-metapac/stm32h745zg-cm7", "_dual-core" ] +stm32h745zg-cm4 = [ "stm32-metapac/stm32h745zg-cm4", "_dual-core" ] +stm32h745zi-cm7 = [ "stm32-metapac/stm32h745zi-cm7", "_dual-core" ] +stm32h745zi-cm4 = [ "stm32-metapac/stm32h745zi-cm4", "_dual-core" ] +stm32h747ag-cm7 = [ "stm32-metapac/stm32h747ag-cm7", "_dual-core" ] +stm32h747ag-cm4 = [ "stm32-metapac/stm32h747ag-cm4", "_dual-core" ] +stm32h747ai-cm7 = [ "stm32-metapac/stm32h747ai-cm7", "_dual-core" ] +stm32h747ai-cm4 = [ "stm32-metapac/stm32h747ai-cm4", "_dual-core" ] +stm32h747bg-cm7 = [ "stm32-metapac/stm32h747bg-cm7", "_dual-core" ] +stm32h747bg-cm4 = [ "stm32-metapac/stm32h747bg-cm4", "_dual-core" ] +stm32h747bi-cm7 = [ "stm32-metapac/stm32h747bi-cm7", "_dual-core" ] +stm32h747bi-cm4 = [ "stm32-metapac/stm32h747bi-cm4", "_dual-core" ] +stm32h747ig-cm7 = [ "stm32-metapac/stm32h747ig-cm7", "_dual-core" ] +stm32h747ig-cm4 = [ "stm32-metapac/stm32h747ig-cm4", "_dual-core" ] +stm32h747ii-cm7 = [ "stm32-metapac/stm32h747ii-cm7", "_dual-core" ] +stm32h747ii-cm4 = [ "stm32-metapac/stm32h747ii-cm4", "_dual-core" ] +stm32h747xg-cm7 = [ "stm32-metapac/stm32h747xg-cm7", "_dual-core" ] +stm32h747xg-cm4 = [ "stm32-metapac/stm32h747xg-cm4", "_dual-core" ] +stm32h747xi-cm7 = [ "stm32-metapac/stm32h747xi-cm7", "_dual-core" ] +stm32h747xi-cm4 = [ "stm32-metapac/stm32h747xi-cm4", "_dual-core" ] +stm32h747zi-cm7 = [ "stm32-metapac/stm32h747zi-cm7", "_dual-core" ] +stm32h747zi-cm4 = [ "stm32-metapac/stm32h747zi-cm4", "_dual-core" ] +stm32h750ib = [ "stm32-metapac/stm32h750ib" ] +stm32h750vb = [ "stm32-metapac/stm32h750vb" ] +stm32h750xb = [ "stm32-metapac/stm32h750xb" ] +stm32h750zb = [ "stm32-metapac/stm32h750zb" ] +stm32h753ai = [ "stm32-metapac/stm32h753ai" ] +stm32h753bi = [ "stm32-metapac/stm32h753bi" ] +stm32h753ii = [ "stm32-metapac/stm32h753ii" ] +stm32h753vi = [ "stm32-metapac/stm32h753vi" ] +stm32h753xi = [ "stm32-metapac/stm32h753xi" ] +stm32h753zi = [ "stm32-metapac/stm32h753zi" ] +stm32h755bi-cm7 = [ "stm32-metapac/stm32h755bi-cm7", "_dual-core" ] +stm32h755bi-cm4 = [ "stm32-metapac/stm32h755bi-cm4", "_dual-core" ] +stm32h755ii-cm7 = [ "stm32-metapac/stm32h755ii-cm7", "_dual-core" ] +stm32h755ii-cm4 = [ "stm32-metapac/stm32h755ii-cm4", "_dual-core" ] +stm32h755xi-cm7 = [ "stm32-metapac/stm32h755xi-cm7", "_dual-core" ] +stm32h755xi-cm4 = [ "stm32-metapac/stm32h755xi-cm4", "_dual-core" ] +stm32h755zi-cm7 = [ "stm32-metapac/stm32h755zi-cm7", "_dual-core" ] +stm32h755zi-cm4 = [ "stm32-metapac/stm32h755zi-cm4", "_dual-core" ] +stm32h757ai-cm7 = [ "stm32-metapac/stm32h757ai-cm7", "_dual-core" ] +stm32h757ai-cm4 = [ "stm32-metapac/stm32h757ai-cm4", "_dual-core" ] +stm32h757bi-cm7 = [ "stm32-metapac/stm32h757bi-cm7", "_dual-core" ] +stm32h757bi-cm4 = [ "stm32-metapac/stm32h757bi-cm4", "_dual-core" ] +stm32h757ii-cm7 = [ "stm32-metapac/stm32h757ii-cm7", "_dual-core" ] +stm32h757ii-cm4 = [ "stm32-metapac/stm32h757ii-cm4", "_dual-core" ] +stm32h757xi-cm7 = [ "stm32-metapac/stm32h757xi-cm7", "_dual-core" ] +stm32h757xi-cm4 = [ "stm32-metapac/stm32h757xi-cm4", "_dual-core" ] +stm32h757zi-cm7 = [ "stm32-metapac/stm32h757zi-cm7", "_dual-core" ] +stm32h757zi-cm4 = [ "stm32-metapac/stm32h757zi-cm4", "_dual-core" ] +stm32h7a3ag = [ "stm32-metapac/stm32h7a3ag" ] +stm32h7a3ai = [ "stm32-metapac/stm32h7a3ai" ] +stm32h7a3ig = [ "stm32-metapac/stm32h7a3ig" ] +stm32h7a3ii = [ "stm32-metapac/stm32h7a3ii" ] +stm32h7a3lg = [ "stm32-metapac/stm32h7a3lg" ] +stm32h7a3li = [ "stm32-metapac/stm32h7a3li" ] +stm32h7a3ng = [ "stm32-metapac/stm32h7a3ng" ] +stm32h7a3ni = [ "stm32-metapac/stm32h7a3ni" ] +stm32h7a3qi = [ "stm32-metapac/stm32h7a3qi" ] +stm32h7a3rg = [ "stm32-metapac/stm32h7a3rg" ] +stm32h7a3ri = [ "stm32-metapac/stm32h7a3ri" ] +stm32h7a3vg = [ "stm32-metapac/stm32h7a3vg" ] +stm32h7a3vi = [ "stm32-metapac/stm32h7a3vi" ] +stm32h7a3zg = [ "stm32-metapac/stm32h7a3zg" ] +stm32h7a3zi = [ "stm32-metapac/stm32h7a3zi" ] +stm32h7b0ab = [ "stm32-metapac/stm32h7b0ab" ] +stm32h7b0ib = [ "stm32-metapac/stm32h7b0ib" ] +stm32h7b0rb = [ "stm32-metapac/stm32h7b0rb" ] +stm32h7b0vb = [ "stm32-metapac/stm32h7b0vb" ] +stm32h7b0zb = [ "stm32-metapac/stm32h7b0zb" ] +stm32h7b3ai = [ "stm32-metapac/stm32h7b3ai" ] +stm32h7b3ii = [ "stm32-metapac/stm32h7b3ii" ] +stm32h7b3li = [ "stm32-metapac/stm32h7b3li" ] +stm32h7b3ni = [ "stm32-metapac/stm32h7b3ni" ] +stm32h7b3qi = [ "stm32-metapac/stm32h7b3qi" ] +stm32h7b3ri = [ "stm32-metapac/stm32h7b3ri" ] +stm32h7b3vi = [ "stm32-metapac/stm32h7b3vi" ] +stm32h7b3zi = [ "stm32-metapac/stm32h7b3zi" ] +stm32h7r3a8 = [ "stm32-metapac/stm32h7r3a8" ] +stm32h7r3i8 = [ "stm32-metapac/stm32h7r3i8" ] +stm32h7r3l8 = [ "stm32-metapac/stm32h7r3l8" ] +stm32h7r3r8 = [ "stm32-metapac/stm32h7r3r8" ] +stm32h7r3v8 = [ "stm32-metapac/stm32h7r3v8" ] +stm32h7r3z8 = [ "stm32-metapac/stm32h7r3z8" ] +stm32h7r7a8 = [ "stm32-metapac/stm32h7r7a8" ] +stm32h7r7i8 = [ "stm32-metapac/stm32h7r7i8" ] +stm32h7r7l8 = [ "stm32-metapac/stm32h7r7l8" ] +stm32h7r7z8 = [ "stm32-metapac/stm32h7r7z8" ] +stm32h7s3a8 = [ "stm32-metapac/stm32h7s3a8" ] +stm32h7s3i8 = [ "stm32-metapac/stm32h7s3i8" ] +stm32h7s3l8 = [ "stm32-metapac/stm32h7s3l8" ] +stm32h7s3r8 = [ "stm32-metapac/stm32h7s3r8" ] +stm32h7s3v8 = [ "stm32-metapac/stm32h7s3v8" ] +stm32h7s3z8 = [ "stm32-metapac/stm32h7s3z8" ] +stm32h7s7a8 = [ "stm32-metapac/stm32h7s7a8" ] +stm32h7s7i8 = [ "stm32-metapac/stm32h7s7i8" ] +stm32h7s7l8 = [ "stm32-metapac/stm32h7s7l8" ] +stm32h7s7z8 = [ "stm32-metapac/stm32h7s7z8" ] stm32l010c6 = [ "stm32-metapac/stm32l010c6" ] stm32l010f4 = [ "stm32-metapac/stm32l010f4" ] stm32l010k4 = [ "stm32-metapac/stm32l010k4" ] @@ -1388,86 +1447,132 @@ stm32l4s7zi = [ "stm32-metapac/stm32l4s7zi" ] stm32l4s9ai = [ "stm32-metapac/stm32l4s9ai" ] stm32l4s9vi = [ "stm32-metapac/stm32l4s9vi" ] stm32l4s9zi = [ "stm32-metapac/stm32l4s9zi" ] -stm32l552cc = [ "stm32-metapac/stm32l552cc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l552ce = [ "stm32-metapac/stm32l552ce", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l552me = [ "stm32-metapac/stm32l552me", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l552qc = [ "stm32-metapac/stm32l552qc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l552qe = [ "stm32-metapac/stm32l552qe", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l552rc = [ "stm32-metapac/stm32l552rc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l552re = [ "stm32-metapac/stm32l552re", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l552vc = [ "stm32-metapac/stm32l552vc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l552ve = [ "stm32-metapac/stm32l552ve", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l552zc = [ "stm32-metapac/stm32l552zc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l552ze = [ "stm32-metapac/stm32l552ze", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l562ce = [ "stm32-metapac/stm32l562ce", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l562me = [ "stm32-metapac/stm32l562me", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l562qe = [ "stm32-metapac/stm32l562qe", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l562re = [ "stm32-metapac/stm32l562re", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l562ve = [ "stm32-metapac/stm32l562ve", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32l562ze = [ "stm32-metapac/stm32l562ze", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u535cb = [ "stm32-metapac/stm32u535cb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u535cc = [ "stm32-metapac/stm32u535cc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u535ce = [ "stm32-metapac/stm32u535ce", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u535je = [ "stm32-metapac/stm32u535je", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u535nc = [ "stm32-metapac/stm32u535nc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u535ne = [ "stm32-metapac/stm32u535ne", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u535rb = [ "stm32-metapac/stm32u535rb", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u535rc = [ "stm32-metapac/stm32u535rc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u535re = [ "stm32-metapac/stm32u535re", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u535vc = [ "stm32-metapac/stm32u535vc", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u535ve = [ "stm32-metapac/stm32u535ve", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u545ce = [ "stm32-metapac/stm32u545ce", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u545je = [ "stm32-metapac/stm32u545je", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u545ne = [ "stm32-metapac/stm32u545ne", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u545re = [ "stm32-metapac/stm32u545re", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u545ve = [ "stm32-metapac/stm32u545ve", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u575ag = [ "stm32-metapac/stm32u575ag", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u575ai = [ "stm32-metapac/stm32u575ai", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u575cg = [ "stm32-metapac/stm32u575cg", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u575ci = [ "stm32-metapac/stm32u575ci", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u575og = [ "stm32-metapac/stm32u575og", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u575oi = [ "stm32-metapac/stm32u575oi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u575qg = [ "stm32-metapac/stm32u575qg", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u575qi = [ "stm32-metapac/stm32u575qi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u575rg = [ "stm32-metapac/stm32u575rg", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u575ri = [ "stm32-metapac/stm32u575ri", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u575vg = [ "stm32-metapac/stm32u575vg", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u575vi = [ "stm32-metapac/stm32u575vi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u575zg = [ "stm32-metapac/stm32u575zg", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u575zi = [ "stm32-metapac/stm32u575zi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u585ai = [ "stm32-metapac/stm32u585ai", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u585ci = [ "stm32-metapac/stm32u585ci", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u585oi = [ "stm32-metapac/stm32u585oi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u585qi = [ "stm32-metapac/stm32u585qi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u585ri = [ "stm32-metapac/stm32u585ri", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u585vi = [ "stm32-metapac/stm32u585vi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u585zi = [ "stm32-metapac/stm32u585zi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u595ai = [ "stm32-metapac/stm32u595ai", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u595aj = [ "stm32-metapac/stm32u595aj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u595qi = [ "stm32-metapac/stm32u595qi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u595qj = [ "stm32-metapac/stm32u595qj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u595ri = [ "stm32-metapac/stm32u595ri", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u595rj = [ "stm32-metapac/stm32u595rj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u595vi = [ "stm32-metapac/stm32u595vi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u595vj = [ "stm32-metapac/stm32u595vj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u595zi = [ "stm32-metapac/stm32u595zi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u595zj = [ "stm32-metapac/stm32u595zj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u599bj = [ "stm32-metapac/stm32u599bj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u599ni = [ "stm32-metapac/stm32u599ni", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u599nj = [ "stm32-metapac/stm32u599nj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u599vi = [ "stm32-metapac/stm32u599vi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u599vj = [ "stm32-metapac/stm32u599vj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u599zi = [ "stm32-metapac/stm32u599zi", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u599zj = [ "stm32-metapac/stm32u599zj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u5a5aj = [ "stm32-metapac/stm32u5a5aj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u5a5qj = [ "stm32-metapac/stm32u5a5qj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u5a5rj = [ "stm32-metapac/stm32u5a5rj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u5a5vj = [ "stm32-metapac/stm32u5a5vj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u5a5zj = [ "stm32-metapac/stm32u5a5zj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u5a9bj = [ "stm32-metapac/stm32u5a9bj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u5a9nj = [ "stm32-metapac/stm32u5a9nj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u5a9vj = [ "stm32-metapac/stm32u5a9vj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] -stm32u5a9zj = [ "stm32-metapac/stm32u5a9zj", "dep:fdcan", "fdcan/fdcan_g0_g4_l5" ] +stm32l552cc = [ "stm32-metapac/stm32l552cc" ] +stm32l552ce = [ "stm32-metapac/stm32l552ce" ] +stm32l552me = [ "stm32-metapac/stm32l552me" ] +stm32l552qc = [ "stm32-metapac/stm32l552qc" ] +stm32l552qe = [ "stm32-metapac/stm32l552qe" ] +stm32l552rc = [ "stm32-metapac/stm32l552rc" ] +stm32l552re = [ "stm32-metapac/stm32l552re" ] +stm32l552vc = [ "stm32-metapac/stm32l552vc" ] +stm32l552ve = [ "stm32-metapac/stm32l552ve" ] +stm32l552zc = [ "stm32-metapac/stm32l552zc" ] +stm32l552ze = [ "stm32-metapac/stm32l552ze" ] +stm32l562ce = [ "stm32-metapac/stm32l562ce" ] +stm32l562me = [ "stm32-metapac/stm32l562me" ] +stm32l562qe = [ "stm32-metapac/stm32l562qe" ] +stm32l562re = [ "stm32-metapac/stm32l562re" ] +stm32l562ve = [ "stm32-metapac/stm32l562ve" ] +stm32l562ze = [ "stm32-metapac/stm32l562ze" ] +stm32u031c6 = [ "stm32-metapac/stm32u031c6" ] +stm32u031c8 = [ "stm32-metapac/stm32u031c8" ] +stm32u031f4 = [ "stm32-metapac/stm32u031f4" ] +stm32u031f6 = [ "stm32-metapac/stm32u031f6" ] +stm32u031f8 = [ "stm32-metapac/stm32u031f8" ] +stm32u031g6 = [ "stm32-metapac/stm32u031g6" ] +stm32u031g8 = [ "stm32-metapac/stm32u031g8" ] +stm32u031k4 = [ "stm32-metapac/stm32u031k4" ] +stm32u031k6 = [ "stm32-metapac/stm32u031k6" ] +stm32u031k8 = [ "stm32-metapac/stm32u031k8" ] +stm32u031r6 = [ "stm32-metapac/stm32u031r6" ] +stm32u031r8 = [ "stm32-metapac/stm32u031r8" ] +stm32u073c8 = [ "stm32-metapac/stm32u073c8" ] +stm32u073cb = [ "stm32-metapac/stm32u073cb" ] +stm32u073cc = [ "stm32-metapac/stm32u073cc" ] +stm32u073h8 = [ "stm32-metapac/stm32u073h8" ] +stm32u073hb = [ "stm32-metapac/stm32u073hb" ] +stm32u073hc = [ "stm32-metapac/stm32u073hc" ] +stm32u073k8 = [ "stm32-metapac/stm32u073k8" ] +stm32u073kb = [ "stm32-metapac/stm32u073kb" ] +stm32u073kc = [ "stm32-metapac/stm32u073kc" ] +stm32u073m8 = [ "stm32-metapac/stm32u073m8" ] +stm32u073mb = [ "stm32-metapac/stm32u073mb" ] +stm32u073mc = [ "stm32-metapac/stm32u073mc" ] +stm32u073r8 = [ "stm32-metapac/stm32u073r8" ] +stm32u073rb = [ "stm32-metapac/stm32u073rb" ] +stm32u073rc = [ "stm32-metapac/stm32u073rc" ] +stm32u083cc = [ "stm32-metapac/stm32u083cc" ] +stm32u083hc = [ "stm32-metapac/stm32u083hc" ] +stm32u083kc = [ "stm32-metapac/stm32u083kc" ] +stm32u083mc = [ "stm32-metapac/stm32u083mc" ] +stm32u083rc = [ "stm32-metapac/stm32u083rc" ] +stm32u535cb = [ "stm32-metapac/stm32u535cb" ] +stm32u535cc = [ "stm32-metapac/stm32u535cc" ] +stm32u535ce = [ "stm32-metapac/stm32u535ce" ] +stm32u535je = [ "stm32-metapac/stm32u535je" ] +stm32u535nc = [ "stm32-metapac/stm32u535nc" ] +stm32u535ne = [ "stm32-metapac/stm32u535ne" ] +stm32u535rb = [ "stm32-metapac/stm32u535rb" ] +stm32u535rc = [ "stm32-metapac/stm32u535rc" ] +stm32u535re = [ "stm32-metapac/stm32u535re" ] +stm32u535vc = [ "stm32-metapac/stm32u535vc" ] +stm32u535ve = [ "stm32-metapac/stm32u535ve" ] +stm32u545ce = [ "stm32-metapac/stm32u545ce" ] +stm32u545je = [ "stm32-metapac/stm32u545je" ] +stm32u545ne = [ "stm32-metapac/stm32u545ne" ] +stm32u545re = [ "stm32-metapac/stm32u545re" ] +stm32u545ve = [ "stm32-metapac/stm32u545ve" ] +stm32u575ag = [ "stm32-metapac/stm32u575ag" ] +stm32u575ai = [ "stm32-metapac/stm32u575ai" ] +stm32u575cg = [ "stm32-metapac/stm32u575cg" ] +stm32u575ci = [ "stm32-metapac/stm32u575ci" ] +stm32u575og = [ "stm32-metapac/stm32u575og" ] +stm32u575oi = [ "stm32-metapac/stm32u575oi" ] +stm32u575qg = [ "stm32-metapac/stm32u575qg" ] +stm32u575qi = [ "stm32-metapac/stm32u575qi" ] +stm32u575rg = [ "stm32-metapac/stm32u575rg" ] +stm32u575ri = [ "stm32-metapac/stm32u575ri" ] +stm32u575vg = [ "stm32-metapac/stm32u575vg" ] +stm32u575vi = [ "stm32-metapac/stm32u575vi" ] +stm32u575zg = [ "stm32-metapac/stm32u575zg" ] +stm32u575zi = [ "stm32-metapac/stm32u575zi" ] +stm32u585ai = [ "stm32-metapac/stm32u585ai" ] +stm32u585ci = [ "stm32-metapac/stm32u585ci" ] +stm32u585oi = [ "stm32-metapac/stm32u585oi" ] +stm32u585qi = [ "stm32-metapac/stm32u585qi" ] +stm32u585ri = [ "stm32-metapac/stm32u585ri" ] +stm32u585vi = [ "stm32-metapac/stm32u585vi" ] +stm32u585zi = [ "stm32-metapac/stm32u585zi" ] +stm32u595ai = [ "stm32-metapac/stm32u595ai" ] +stm32u595aj = [ "stm32-metapac/stm32u595aj" ] +stm32u595qi = [ "stm32-metapac/stm32u595qi" ] +stm32u595qj = [ "stm32-metapac/stm32u595qj" ] +stm32u595ri = [ "stm32-metapac/stm32u595ri" ] +stm32u595rj = [ "stm32-metapac/stm32u595rj" ] +stm32u595vi = [ "stm32-metapac/stm32u595vi" ] +stm32u595vj = [ "stm32-metapac/stm32u595vj" ] +stm32u595zi = [ "stm32-metapac/stm32u595zi" ] +stm32u595zj = [ "stm32-metapac/stm32u595zj" ] +stm32u599bj = [ "stm32-metapac/stm32u599bj" ] +stm32u599ni = [ "stm32-metapac/stm32u599ni" ] +stm32u599nj = [ "stm32-metapac/stm32u599nj" ] +stm32u599vi = [ "stm32-metapac/stm32u599vi" ] +stm32u599vj = [ "stm32-metapac/stm32u599vj" ] +stm32u599zi = [ "stm32-metapac/stm32u599zi" ] +stm32u599zj = [ "stm32-metapac/stm32u599zj" ] +stm32u5a5aj = [ "stm32-metapac/stm32u5a5aj" ] +stm32u5a5qi = [ "stm32-metapac/stm32u5a5qi" ] +stm32u5a5qj = [ "stm32-metapac/stm32u5a5qj" ] +stm32u5a5rj = [ "stm32-metapac/stm32u5a5rj" ] +stm32u5a5vj = [ "stm32-metapac/stm32u5a5vj" ] +stm32u5a5zj = [ "stm32-metapac/stm32u5a5zj" ] +stm32u5a9bj = [ "stm32-metapac/stm32u5a9bj" ] +stm32u5a9nj = [ "stm32-metapac/stm32u5a9nj" ] +stm32u5a9vj = [ "stm32-metapac/stm32u5a9vj" ] +stm32u5a9zj = [ "stm32-metapac/stm32u5a9zj" ] +stm32u5f7vi = [ "stm32-metapac/stm32u5f7vi" ] +stm32u5f7vj = [ "stm32-metapac/stm32u5f7vj" ] +stm32u5f9bj = [ "stm32-metapac/stm32u5f9bj" ] +stm32u5f9nj = [ "stm32-metapac/stm32u5f9nj" ] +stm32u5f9vi = [ "stm32-metapac/stm32u5f9vi" ] +stm32u5f9vj = [ "stm32-metapac/stm32u5f9vj" ] +stm32u5f9zi = [ "stm32-metapac/stm32u5f9zi" ] +stm32u5f9zj = [ "stm32-metapac/stm32u5f9zj" ] +stm32u5g7vj = [ "stm32-metapac/stm32u5g7vj" ] +stm32u5g9bj = [ "stm32-metapac/stm32u5g9bj" ] +stm32u5g9nj = [ "stm32-metapac/stm32u5g9nj" ] +stm32u5g9vj = [ "stm32-metapac/stm32u5g9vj" ] +stm32u5g9zj = [ "stm32-metapac/stm32u5g9zj" ] stm32wb10cc = [ "stm32-metapac/stm32wb10cc" ] stm32wb15cc = [ "stm32-metapac/stm32wb15cc" ] stm32wb30ce = [ "stm32-metapac/stm32wb30ce" ] @@ -1484,18 +1589,30 @@ stm32wb55vc = [ "stm32-metapac/stm32wb55vc" ] stm32wb55ve = [ "stm32-metapac/stm32wb55ve" ] stm32wb55vg = [ "stm32-metapac/stm32wb55vg" ] stm32wb55vy = [ "stm32-metapac/stm32wb55vy" ] +stm32wba50ke = [ "stm32-metapac/stm32wba50ke" ] +stm32wba50kg = [ "stm32-metapac/stm32wba50kg" ] stm32wba52ce = [ "stm32-metapac/stm32wba52ce" ] stm32wba52cg = [ "stm32-metapac/stm32wba52cg" ] stm32wba52ke = [ "stm32-metapac/stm32wba52ke" ] stm32wba52kg = [ "stm32-metapac/stm32wba52kg" ] -stm32wl54cc-cm4 = [ "stm32-metapac/stm32wl54cc-cm4" ] -stm32wl54cc-cm0p = [ "stm32-metapac/stm32wl54cc-cm0p" ] -stm32wl54jc-cm4 = [ "stm32-metapac/stm32wl54jc-cm4" ] -stm32wl54jc-cm0p = [ "stm32-metapac/stm32wl54jc-cm0p" ] -stm32wl55cc-cm4 = [ "stm32-metapac/stm32wl55cc-cm4" ] -stm32wl55cc-cm0p = [ "stm32-metapac/stm32wl55cc-cm0p" ] -stm32wl55jc-cm4 = [ "stm32-metapac/stm32wl55jc-cm4" ] -stm32wl55jc-cm0p = [ "stm32-metapac/stm32wl55jc-cm0p" ] +stm32wba54ce = [ "stm32-metapac/stm32wba54ce" ] +stm32wba54cg = [ "stm32-metapac/stm32wba54cg" ] +stm32wba54ke = [ "stm32-metapac/stm32wba54ke" ] +stm32wba54kg = [ "stm32-metapac/stm32wba54kg" ] +stm32wba55ce = [ "stm32-metapac/stm32wba55ce" ] +stm32wba55cg = [ "stm32-metapac/stm32wba55cg" ] +stm32wba55he = [ "stm32-metapac/stm32wba55he" ] +stm32wba55hg = [ "stm32-metapac/stm32wba55hg" ] +stm32wba55ue = [ "stm32-metapac/stm32wba55ue" ] +stm32wba55ug = [ "stm32-metapac/stm32wba55ug" ] +stm32wl54cc-cm4 = [ "stm32-metapac/stm32wl54cc-cm4", "_dual-core" ] +stm32wl54cc-cm0p = [ "stm32-metapac/stm32wl54cc-cm0p", "_dual-core" ] +stm32wl54jc-cm4 = [ "stm32-metapac/stm32wl54jc-cm4", "_dual-core" ] +stm32wl54jc-cm0p = [ "stm32-metapac/stm32wl54jc-cm0p", "_dual-core" ] +stm32wl55cc-cm4 = [ "stm32-metapac/stm32wl55cc-cm4", "_dual-core" ] +stm32wl55cc-cm0p = [ "stm32-metapac/stm32wl55cc-cm0p", "_dual-core" ] +stm32wl55jc-cm4 = [ "stm32-metapac/stm32wl55jc-cm4", "_dual-core" ] +stm32wl55jc-cm0p = [ "stm32-metapac/stm32wl55jc-cm0p", "_dual-core" ] stm32wle4c8 = [ "stm32-metapac/stm32wle4c8" ] stm32wle4cb = [ "stm32-metapac/stm32wle4cb" ] stm32wle4cc = [ "stm32-metapac/stm32wle4cc" ] diff --git a/embassy-stm32/README.md b/embassy-stm32/README.md index e9ae455a4..445366f8d 100644 --- a/embassy-stm32/README.md +++ b/embassy-stm32/README.md @@ -35,4 +35,4 @@ This crate can run on any executor. Optionally, some features requiring [`embassy-time`](https://crates.io/crates/embassy-time) can be activated with the `time` feature. If you enable it, you must link an `embassy-time` driver in your project. -The `low-power` feature integrates specifically with `embassy-executor`, it can't be ued on other executors for now. +The `low-power` feature integrates specifically with `embassy-executor`, it can't be used on other executors for now. diff --git a/embassy-stm32/build.rs b/embassy-stm32/build.rs index 74cc3f8b9..71bfb3747 100644 --- a/embassy-stm32/build.rs +++ b/embassy-stm32/build.rs @@ -1,39 +1,24 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::fmt::Write as _; -use std::path::PathBuf; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::Command; use std::{env, fs}; use proc_macro2::{Ident, TokenStream}; use quote::{format_ident, quote}; -use stm32_metapac::metadata::ir::{BlockItemInner, Enum, FieldSet}; -use stm32_metapac::metadata::{MemoryRegionKind, PeripheralRccRegister, StopMode, METADATA}; +use stm32_metapac::metadata::ir::BitOffset; +use stm32_metapac::metadata::{ + MemoryRegionKind, PeripheralRccKernelClock, PeripheralRccRegister, PeripheralRegisters, StopMode, ALL_CHIPS, + ALL_PERIPHERAL_VERSIONS, METADATA, +}; + +#[path = "./build_common.rs"] +mod common; fn main() { - let target = env::var("TARGET").unwrap(); - - if target.starts_with("thumbv6m-") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv6m"); - } else if target.starts_with("thumbv7m-") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv7m"); - } else if target.starts_with("thumbv7em-") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv7m"); - println!("cargo:rustc-cfg=armv7em"); // (not currently used) - } else if target.starts_with("thumbv8m.base") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv8m"); - println!("cargo:rustc-cfg=armv8m_base"); - } else if target.starts_with("thumbv8m.main") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv8m"); - println!("cargo:rustc-cfg=armv8m_main"); - } - - if target.ends_with("-eabihf") { - println!("cargo:rustc-cfg=has_fpu"); - } + let mut cfgs = common::CfgSet::new(); + common::set_target_cfgs(&mut cfgs); let chip_name = match env::vars() .map(|(a, _)| a) @@ -48,10 +33,19 @@ fn main() { .unwrap() .to_ascii_lowercase(); + eprintln!("chip: {chip_name}"); + for p in METADATA.peripherals { if let Some(r) = &p.registers { - println!("cargo:rustc-cfg={}", r.kind); - println!("cargo:rustc-cfg={}_{}", r.kind, r.version); + cfgs.enable(r.kind); + cfgs.enable(format!("{}_{}", r.kind, r.version)); + } + } + + for &(kind, versions) in ALL_PERIPHERAL_VERSIONS.iter() { + cfgs.declare(kind); + for &version in versions.iter() { + cfgs.declare(format!("{}_{}", kind, version)); } } @@ -61,7 +55,13 @@ fn main() { let mut singletons: Vec = Vec::new(); for p in METADATA.peripherals { if let Some(r) = &p.registers { - println!("cargo:rustc-cfg=peri_{}", p.name.to_ascii_lowercase()); + if r.kind == "adccommon" || r.kind == "sai" || r.kind == "ucpd" || r.kind == "otg" || r.kind == "octospi" { + // TODO: should we emit this for all peripherals? if so, we will need a list of all + // possible peripherals across all chips, so that we can declare the configs + // (replacing the hard-coded list of `peri_*` cfgs below) + cfgs.enable(format!("peri_{}", p.name.to_ascii_lowercase())); + } + match r.kind { // Generate singletons per pin, not per port "gpio" => { @@ -81,7 +81,7 @@ fn main() { if pin.signal.starts_with("MCO") { let name = pin.signal.replace('_', "").to_string(); if !singletons.contains(&name) { - println!("cargo:rustc-cfg={}", name.to_ascii_lowercase()); + cfgs.enable(name.to_ascii_lowercase()); singletons.push(name); } } @@ -100,6 +100,23 @@ fn main() { } } + cfgs.declare_all(&[ + "peri_adc1_common", + "peri_adc3_common", + "peri_adc12_common", + "peri_adc34_common", + "peri_sai1", + "peri_sai2", + "peri_sai3", + "peri_sai4", + "peri_ucpd1", + "peri_ucpd2", + "peri_usb_otg_fs", + "peri_usb_otg_hs", + "peri_octospi2", + ]); + cfgs.declare_all(&["mco", "mco1", "mco2"]); + // One singleton per EXTI line for pin_num in 0..16 { singletons.push(format!("EXTI{}", pin_num)); @@ -183,46 +200,45 @@ fn main() { let time_driver_singleton = match time_driver.as_ref().map(|x| x.as_ref()) { None => "", + Some("tim1") => "TIM1", Some("tim2") => "TIM2", Some("tim3") => "TIM3", Some("tim4") => "TIM4", Some("tim5") => "TIM5", + Some("tim8") => "TIM8", Some("tim9") => "TIM9", - Some("tim11") => "TIM11", Some("tim12") => "TIM12", Some("tim15") => "TIM15", + Some("tim20") => "TIM20", Some("tim21") => "TIM21", Some("tim22") => "TIM22", + Some("tim23") => "TIM23", + Some("tim24") => "TIM24", Some("any") => { - if singletons.contains(&"TIM2".to_string()) { - "TIM2" - } else if singletons.contains(&"TIM3".to_string()) { - "TIM3" - } else if singletons.contains(&"TIM4".to_string()) { - "TIM4" - } else if singletons.contains(&"TIM5".to_string()) { - "TIM5" - } else if singletons.contains(&"TIM9".to_string()) { - "TIM9" - } else if singletons.contains(&"TIM11".to_string()) { - "TIM11" - } else if singletons.contains(&"TIM12".to_string()) { - "TIM12" - } else if singletons.contains(&"TIM15".to_string()) { - "TIM15" - } else if singletons.contains(&"TIM21".to_string()) { - "TIM21" - } else if singletons.contains(&"TIM22".to_string()) { - "TIM22" - } else { - panic!("time-driver-any requested, but the chip doesn't have TIM2, TIM3, TIM4, TIM5, TIM9, TIM11, TIM12 or TIM15.") - } + // Order of TIM candidators: + // 1. 2CH -> 2CH_CMP -> GP16 -> GP32 -> ADV + // 2. In same catagory: larger TIM number first + [ + "TIM22", "TIM21", "TIM12", "TIM9", // 2CH + "TIM15", // 2CH_CMP + "TIM19", "TIM4", "TIM3", // GP16 + "TIM24", "TIM23", "TIM5", "TIM2", // GP32 + "TIM20", "TIM8", "TIM1", //ADV + ] + .iter() + .find(|tim| singletons.contains(&tim.to_string())).expect("time-driver-any requested, but the chip doesn't have TIM1, TIM2, TIM3, TIM4, TIM5, TIM8, TIM9, TIM12, TIM15, TIM20, TIM21, TIM22, TIM23 or TIM24.") } _ => panic!("unknown time_driver {:?}", time_driver), }; if !time_driver_singleton.is_empty() { - println!("cargo:rustc-cfg=time_driver_{}", time_driver_singleton.to_lowercase()); + cfgs.enable(format!("time_driver_{}", time_driver_singleton.to_lowercase())); + } + for tim in [ + "tim1", "tim2", "tim3", "tim4", "tim5", "tim8", "tim9", "tim12", "tim15", "tim20", "tim21", "tim22", "tim23", + "tim24", + ] { + cfgs.declare(format!("time_driver_{}", tim)); } // ======== @@ -278,8 +294,6 @@ fn main() { "Bank1" } else if region.name.starts_with("BANK_2") { "Bank2" - } else if region.name == "OTP" { - "Otp" } else { continue; } @@ -361,90 +375,16 @@ fn main() { g.extend(quote! { pub mod flash_regions { #flash_regions } }); - // ======== - // Generate DMA IRQs. - - let mut dma_irqs: BTreeMap<&str, Vec<(&str, &str, &str)>> = BTreeMap::new(); - - for p in METADATA.peripherals { - if let Some(r) = &p.registers { - if r.kind == "dma" || r.kind == "bdma" || r.kind == "gpdma" { - if p.name == "BDMA1" { - // BDMA1 in H7 doesn't use DMAMUX, which breaks - continue; - } - for irq in p.interrupts { - dma_irqs - .entry(irq.interrupt) - .or_default() - .push((r.kind, p.name, irq.signal)); - } - } - } - } - - let dma_irqs: TokenStream = dma_irqs - .iter() - .map(|(irq, channels)| { - let irq = format_ident!("{}", irq); - - let xdma = format_ident!("{}", channels[0].0); - let channels = channels.iter().map(|(_, dma, ch)| format_ident!("{}_{}", dma, ch)); - - quote! { - #[cfg(feature = "rt")] - #[crate::interrupt] - unsafe fn #irq () { - #( - ::on_irq(); - )* - } - } - }) - .collect(); - - g.extend(dma_irqs); - // ======== // Extract the rcc registers + let rcc_registers = METADATA .peripherals .iter() .filter_map(|p| p.registers.as_ref()) .find(|r| r.kind == "rcc") .unwrap(); - - // ======== - // Generate rcc fieldset and enum maps - let rcc_enum_map: HashMap<&str, HashMap<&str, &Enum>> = { - let rcc_blocks = rcc_registers.ir.blocks.iter().find(|b| b.name == "Rcc").unwrap().items; - let rcc_fieldsets: HashMap<&str, &FieldSet> = rcc_registers.ir.fieldsets.iter().map(|f| (f.name, f)).collect(); - let rcc_enums: HashMap<&str, &Enum> = rcc_registers.ir.enums.iter().map(|e| (e.name, e)).collect(); - - rcc_blocks - .iter() - .filter_map(|b| match &b.inner { - BlockItemInner::Register(register) => register.fieldset.map(|f| (b.name, f)), - _ => None, - }) - .filter_map(|(b, f)| { - rcc_fieldsets.get(f).map(|f| { - ( - b, - f.fields - .iter() - .filter_map(|f| { - let enumm = f.enumm?; - let enumm = rcc_enums.get(enumm)?; - - Some((f.name, *enumm)) - }) - .collect(), - ) - }) - }) - .collect() - }; + let rcc_block = rcc_registers.ir.blocks.iter().find(|b| b.name == "Rcc").unwrap(); // ======== // Generate RccPeripheral impls @@ -458,8 +398,145 @@ fn main() { } } - let force_refcount = HashSet::from(["usart"]); - let mut refcount_statics = BTreeSet::new(); + struct ClockGen<'a> { + rcc_registers: &'a PeripheralRegisters, + chained_muxes: HashMap<&'a str, &'a PeripheralRccRegister>, + + clock_names: BTreeSet, + muxes: BTreeSet<(Ident, Ident, Ident)>, + } + + let mut clock_gen = ClockGen { + rcc_registers, + chained_muxes: HashMap::new(), + + clock_names: BTreeSet::new(), + muxes: BTreeSet::new(), + }; + if chip_name.starts_with("stm32h5") { + clock_gen.chained_muxes.insert( + "PER", + &PeripheralRccRegister { + register: "CCIPR5", + field: "PERSEL", + }, + ); + } + + if chip_name.starts_with("stm32h7r") || chip_name.starts_with("stm32h7s") { + clock_gen.chained_muxes.insert( + "PER", + &PeripheralRccRegister { + register: "AHBPERCKSELR", + field: "PERSEL", + }, + ); + } else if chip_name.starts_with("stm32h7") { + clock_gen.chained_muxes.insert( + "PER", + &PeripheralRccRegister { + register: "D1CCIPR", + field: "PERSEL", + }, + ); + } + if chip_name.starts_with("stm32u5") { + clock_gen.chained_muxes.insert( + "ICLK", + &PeripheralRccRegister { + register: "CCIPR1", + field: "ICLKSEL", + }, + ); + } + if chip_name.starts_with("stm32wb") && !chip_name.starts_with("stm32wba") { + clock_gen.chained_muxes.insert( + "CLK48", + &PeripheralRccRegister { + register: "CCIPR", + field: "CLK48SEL", + }, + ); + } + if chip_name.starts_with("stm32f7") { + clock_gen.chained_muxes.insert( + "CLK48", + &PeripheralRccRegister { + register: "DCKCFGR2", + field: "CLK48SEL", + }, + ); + } + if chip_name.starts_with("stm32f4") && !chip_name.starts_with("stm32f410") { + clock_gen.chained_muxes.insert( + "CLK48", + &PeripheralRccRegister { + register: "DCKCFGR", + field: "CLK48SEL", + }, + ); + } + + impl<'a> ClockGen<'a> { + fn gen_clock(&mut self, peripheral: &str, name: &str) -> TokenStream { + let clock_name = format_ident!("{}", name.to_ascii_lowercase()); + self.clock_names.insert(name.to_ascii_lowercase()); + quote!(unsafe { + unwrap!( + crate::rcc::get_freqs().#clock_name.to_hertz(), + "peripheral '{}' is configured to use the '{}' clock, which is not running. \ + Either enable it in 'config.rcc' or change 'config.rcc.mux' to use another clock", + #peripheral, + #name + ) + }) + } + + fn gen_mux(&mut self, peripheral: &str, mux: &PeripheralRccRegister) -> TokenStream { + let ir = &self.rcc_registers.ir; + let fieldset_name = mux.register.to_ascii_lowercase(); + let fieldset = ir + .fieldsets + .iter() + .find(|i| i.name.eq_ignore_ascii_case(&fieldset_name)) + .unwrap(); + let field_name = mux.field.to_ascii_lowercase(); + let field = fieldset.fields.iter().find(|i| i.name == field_name).unwrap(); + let enum_name = field.enumm.unwrap(); + let enumm = ir.enums.iter().find(|i| i.name == enum_name).unwrap(); + + let fieldset_name = format_ident!("{}", fieldset_name); + let field_name = format_ident!("{}", field_name); + let enum_name = format_ident!("{}", enum_name); + + self.muxes + .insert((fieldset_name.clone(), field_name.clone(), enum_name.clone())); + + let mut match_arms = TokenStream::new(); + + for v in enumm.variants.iter().filter(|v| v.name != "DISABLE") { + let variant_name = format_ident!("{}", v.name); + let expr = if let Some(mux) = self.chained_muxes.get(&v.name) { + self.gen_mux(peripheral, mux) + } else { + self.gen_clock(peripheral, v.name) + }; + match_arms.extend(quote! { + crate::pac::rcc::vals::#enum_name::#variant_name => #expr, + }); + } + + quote! { + match crate::pac::RCC.#fieldset_name().read().#field_name() { + #match_arms + #[allow(unreachable_patterns)] + _ => unreachable!(), + } + } + } + } + + let mut refcount_idxs = HashMap::new(); for p in METADATA.peripherals { if !singletons.contains(&p.name.to_string()) { @@ -467,160 +544,86 @@ fn main() { } if let Some(rcc) = &p.rcc { - let en = rcc.enable.as_ref().unwrap(); - - let rst = match &rcc.reset { - Some(rst) => { - let rst_reg = format_ident!("{}", rst.register.to_ascii_lowercase()); - let set_rst_field = format_ident!("set_{}", rst.field.to_ascii_lowercase()); - quote! { - crate::pac::RCC.#rst_reg().modify(|w| w.#set_rst_field(true)); - crate::pac::RCC.#rst_reg().modify(|w| w.#set_rst_field(false)); - } - } - None => TokenStream::new(), - }; - - let after_enable = if chip_name.starts_with("stm32f2") { - // Errata: ES0005 - 2.1.11 Delay after an RCC peripheral clock enabling - quote! { - cortex_m::asm::dsb(); - } - } else { - TokenStream::new() - }; - - let ptype = if let Some(reg) = &p.registers { reg.kind } else { "" }; + let rst_reg = rcc.reset.as_ref(); + let en_reg = rcc.enable.as_ref().unwrap(); let pname = format_ident!("{}", p.name); - let clk = format_ident!("{}", rcc.clock); - let en_reg = format_ident!("{}", en.register); - let set_en_field = format_ident!("set_{}", en.field); - let refcount = - force_refcount.contains(ptype) || *rcc_field_count.get(&(en.register, en.field)).unwrap() > 1; - let (before_enable, before_disable) = if refcount { - let refcount_static = - format_ident!("{}_{}", en.register.to_ascii_uppercase(), en.field.to_ascii_uppercase()); + let get_offset_and_bit = |reg: &PeripheralRccRegister| -> TokenStream { + let reg_offset = rcc_block + .items + .iter() + .find(|i| i.name.eq_ignore_ascii_case(reg.register)) + .unwrap() + .byte_offset; + let reg_offset: u8 = (reg_offset / 4).try_into().unwrap(); - refcount_statics.insert(refcount_static.clone()); + let bit_offset = &rcc_registers + .ir + .fieldsets + .iter() + .find(|i| i.name.eq_ignore_ascii_case(reg.register)) + .unwrap() + .fields + .iter() + .find(|i| i.name.eq_ignore_ascii_case(reg.field)) + .unwrap() + .bit_offset; + let BitOffset::Regular(bit_offset) = bit_offset else { + panic!("cursed bit offset") + }; + let bit_offset: u8 = bit_offset.offset.try_into().unwrap(); - ( - quote! { - unsafe { refcount_statics::#refcount_static += 1 }; - if unsafe { refcount_statics::#refcount_static } > 1 { - return; - } - }, - quote! { - unsafe { refcount_statics::#refcount_static -= 1 }; - if unsafe { refcount_statics::#refcount_static } > 0 { - return; - } - }, - ) + quote! { (#reg_offset, #bit_offset) } + }; + + let reset_offset_and_bit = match rst_reg { + Some(rst_reg) => { + let reset_offset_and_bit = get_offset_and_bit(rst_reg); + quote! { Some(#reset_offset_and_bit) } + } + None => quote! { None }, + }; + let enable_offset_and_bit = get_offset_and_bit(en_reg); + + let needs_refcount = *rcc_field_count.get(&(en_reg.register, en_reg.field)).unwrap() > 1; + let refcount_idx = if needs_refcount { + let next_refcount_idx = refcount_idxs.len() as u8; + let refcount_idx = *refcount_idxs + .entry((en_reg.register, en_reg.field)) + .or_insert(next_refcount_idx); + quote! { Some(#refcount_idx) } } else { - (TokenStream::new(), TokenStream::new()) + quote! { None } }; - let mux_supported = HashSet::from(["c0", "h5", "h50", "h7", "h7ab", "h7rm0433", "g0", "g4", "l4"]) - .contains(rcc_registers.version); - let mux_for = |mux: Option<&'static PeripheralRccRegister>| { - // restrict mux implementation to supported versions - if !mux_supported { - return None; - } - - let mux = mux?; - let fieldset = rcc_enum_map.get(mux.register)?; - let enumm = fieldset.get(mux.field)?; - - Some((mux, *enumm)) + let clock_frequency = match &rcc.kernel_clock { + PeripheralRccKernelClock::Mux(mux) => clock_gen.gen_mux(p.name, mux), + PeripheralRccKernelClock::Clock(clock) => clock_gen.gen_clock(p.name, clock), }; - let clock_frequency = match mux_for(rcc.mux.as_ref()) { - Some((mux, rcc_enumm)) => { - let fieldset_name = format_ident!("{}", mux.register); - let field_name = format_ident!("{}", mux.field); - let enum_name = format_ident!("{}", rcc_enumm.name); - - let match_arms: TokenStream = rcc_enumm - .variants - .iter() - .filter(|v| v.name != "DISABLE") - .map(|v| { - let variant_name = format_ident!("{}", v.name); - let clock_name = format_ident!("{}", v.name.to_ascii_lowercase()); - - if v.name.starts_with("HCLK") || v.name.starts_with("PCLK") || v.name == "SYS" { - quote! { - #enum_name::#variant_name => unsafe { crate::rcc::get_freqs().#clock_name }, - } - } else { - quote! { - #enum_name::#variant_name => unsafe { crate::rcc::get_freqs().#clock_name.unwrap() }, - } - } - }) - .collect(); - - quote! { - use crate::pac::rcc::vals::#enum_name; - - #[allow(unreachable_patterns)] - match crate::pac::RCC.#fieldset_name().read().#field_name() { - #match_arms - - _ => unreachable!(), - } - } - } - None => quote! { - unsafe { crate::rcc::get_freqs().#clk } - }, - }; - - /* - A refcount leak can result if the same field is shared by peripherals with different stop modes - - This condition should be checked in stm32-data - */ - let stop_refcount = match rcc.stop_mode { - StopMode::Standby => None, - StopMode::Stop2 => Some(quote! { REFCOUNT_STOP2 }), - StopMode::Stop1 => Some(quote! { REFCOUNT_STOP1 }), - }; - - let (incr_stop_refcount, decr_stop_refcount) = match stop_refcount { - Some(stop_refcount) => ( - quote! { - #[cfg(feature = "low-power")] - unsafe { crate::rcc::#stop_refcount += 1 }; - }, - quote! { - #[cfg(feature = "low-power")] - unsafe { crate::rcc::#stop_refcount -= 1 }; - }, - ), - None => (TokenStream::new(), TokenStream::new()), + // A refcount leak can result if the same field is shared by peripherals with different stop modes + // This condition should be checked in stm32-data + let stop_mode = match rcc.stop_mode { + StopMode::Standby => quote! { crate::rcc::StopMode::Standby }, + StopMode::Stop2 => quote! { crate::rcc::StopMode::Stop2 }, + StopMode::Stop1 => quote! { crate::rcc::StopMode::Stop1 }, }; g.extend(quote! { - impl crate::rcc::sealed::RccPeripheral for peripherals::#pname { + impl crate::rcc::SealedRccPeripheral for peripherals::#pname { fn frequency() -> crate::time::Hertz { #clock_frequency } - fn enable_and_reset_with_cs(_cs: critical_section::CriticalSection) { - #before_enable - #incr_stop_refcount - crate::pac::RCC.#en_reg().modify(|w| w.#set_en_field(true)); - #after_enable - #rst - } - fn disable_with_cs(_cs: critical_section::CriticalSection) { - #before_disable - crate::pac::RCC.#en_reg().modify(|w| w.#set_en_field(false)); - #decr_stop_refcount - } + + const RCC_INFO: crate::rcc::RccInfo = unsafe { + crate::rcc::RccInfo::new( + #reset_offset_and_bit, + #enable_offset_and_bit, + #refcount_idx, + #[cfg(feature = "low-power")] + #stop_mode, + ) + }; } impl crate::rcc::RccPeripheral for peripherals::#pname {} @@ -628,21 +631,118 @@ fn main() { } } - let refcount_mod: TokenStream = refcount_statics + g.extend({ + let refcounts_len = refcount_idxs.len(); + let refcount_zeros: TokenStream = refcount_idxs.iter().map(|_| quote! { 0u8, }).collect(); + quote! { + pub(crate) static mut REFCOUNTS: [u8; #refcounts_len] = [#refcount_zeros]; + } + }); + + let struct_fields: Vec<_> = clock_gen + .muxes .iter() - .map(|refcount_static| { + .map(|(_fieldset, fieldname, enum_name)| { quote! { - pub(crate) static mut #refcount_static: u8 = 0; + pub #fieldname: #enum_name } }) .collect(); + let mut inits = TokenStream::new(); + for fieldset in clock_gen + .muxes + .iter() + .map(|(f, _, _)| f) + .collect::>() + .into_iter() + { + let setters: Vec<_> = clock_gen + .muxes + .iter() + .filter(|(f, _, _)| f == fieldset) + .map(|(_, fieldname, _)| { + let setter = format_ident!("set_{}", fieldname); + quote! { + w.#setter(self.#fieldname); + } + }) + .collect(); + + inits.extend(quote! { + crate::pac::RCC.#fieldset().modify(|w| { + #(#setters)* + }); + }) + } + + let enum_names: BTreeSet<_> = clock_gen.muxes.iter().map(|(_, _, enum_name)| enum_name).collect(); + g.extend(quote! { - mod refcount_statics { - #refcount_mod + pub mod mux { + #(pub use crate::pac::rcc::vals::#enum_names as #enum_names; )* + + #[derive(Clone, Copy)] + #[non_exhaustive] + pub struct ClockMux { + #( #struct_fields, )* + } + + impl ClockMux { + pub(crate) const fn default() -> Self { + // safety: zero value is valid for all PAC enums. + unsafe { ::core::mem::zeroed() } + } + } + + impl Default for ClockMux { + fn default() -> Self { + Self::default() + } + } + + impl ClockMux { + pub(crate) fn init(&self) { + #inits + } + } } }); + // Generate RCC + clock_gen.clock_names.insert("sys".to_string()); + clock_gen.clock_names.insert("rtc".to_string()); + let clock_idents: Vec<_> = clock_gen.clock_names.iter().map(|n| format_ident!("{}", n)).collect(); + g.extend(quote! { + #[derive(Clone, Copy, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + #[repr(C)] + pub struct Clocks { + #( + pub #clock_idents: crate::time::MaybeHertz, + )* + } + }); + + let clocks_macro = quote!( + macro_rules! set_clocks { + ($($(#[$m:meta])* $k:ident: $v:expr,)*) => { + { + #[allow(unused)] + struct Temp { + $($(#[$m])* $k: Option,)* + } + let all = Temp { + $($(#[$m])* $k: $v,)* + }; + crate::rcc::set_freqs(crate::rcc::Clocks { + #( #clock_idents: all.#clock_idents.into(), )* + }); + } + }; + } + ); + // ======== // Generate fns to enable GPIO, DMA in RCC @@ -677,6 +777,8 @@ fn main() { #[rustfmt::skip] let signals: HashMap<_, _> = [ // (kind, signal) => trait + (("ucpd", "CC1"), quote!(crate::ucpd::Cc1Pin)), + (("ucpd", "CC2"), quote!(crate::ucpd::Cc2Pin)), (("usart", "TX"), quote!(crate::usart::TxPin)), (("usart", "RX"), quote!(crate::usart::RxPin)), (("usart", "CTS"), quote!(crate::usart::CtsPin)), @@ -727,22 +829,51 @@ fn main() { (("dcmi", "HSYNC"), quote!(crate::dcmi::HSyncPin)), (("dcmi", "VSYNC"), quote!(crate::dcmi::VSyncPin)), (("dcmi", "PIXCLK"), quote!(crate::dcmi::PixClkPin)), + (("dsihost", "TE"), quote!(crate::dsihost::TePin)), + (("ltdc", "CLK"), quote!(crate::ltdc::ClkPin)), + (("ltdc", "HSYNC"), quote!(crate::ltdc::HsyncPin)), + (("ltdc", "VSYNC"), quote!(crate::ltdc::VsyncPin)), + (("ltdc", "DE"), quote!(crate::ltdc::DePin)), + (("ltdc", "R0"), quote!(crate::ltdc::R0Pin)), + (("ltdc", "R1"), quote!(crate::ltdc::R1Pin)), + (("ltdc", "R2"), quote!(crate::ltdc::R2Pin)), + (("ltdc", "R3"), quote!(crate::ltdc::R3Pin)), + (("ltdc", "R4"), quote!(crate::ltdc::R4Pin)), + (("ltdc", "R5"), quote!(crate::ltdc::R5Pin)), + (("ltdc", "R6"), quote!(crate::ltdc::R6Pin)), + (("ltdc", "R7"), quote!(crate::ltdc::R7Pin)), + (("ltdc", "G0"), quote!(crate::ltdc::G0Pin)), + (("ltdc", "G1"), quote!(crate::ltdc::G1Pin)), + (("ltdc", "G2"), quote!(crate::ltdc::G2Pin)), + (("ltdc", "G3"), quote!(crate::ltdc::G3Pin)), + (("ltdc", "G4"), quote!(crate::ltdc::G4Pin)), + (("ltdc", "G5"), quote!(crate::ltdc::G5Pin)), + (("ltdc", "G6"), quote!(crate::ltdc::G6Pin)), + (("ltdc", "G7"), quote!(crate::ltdc::G7Pin)), + (("ltdc", "B0"), quote!(crate::ltdc::B0Pin)), + (("ltdc", "B1"), quote!(crate::ltdc::B1Pin)), + (("ltdc", "B2"), quote!(crate::ltdc::B2Pin)), + (("ltdc", "B3"), quote!(crate::ltdc::B3Pin)), + (("ltdc", "B4"), quote!(crate::ltdc::B4Pin)), + (("ltdc", "B5"), quote!(crate::ltdc::B5Pin)), + (("ltdc", "B6"), quote!(crate::ltdc::B6Pin)), + (("ltdc", "B7"), quote!(crate::ltdc::B7Pin)), (("usb", "DP"), quote!(crate::usb::DpPin)), (("usb", "DM"), quote!(crate::usb::DmPin)), - (("otg", "DP"), quote!(crate::usb_otg::DpPin)), - (("otg", "DM"), quote!(crate::usb_otg::DmPin)), - (("otg", "ULPI_CK"), quote!(crate::usb_otg::UlpiClkPin)), - (("otg", "ULPI_DIR"), quote!(crate::usb_otg::UlpiDirPin)), - (("otg", "ULPI_NXT"), quote!(crate::usb_otg::UlpiNxtPin)), - (("otg", "ULPI_STP"), quote!(crate::usb_otg::UlpiStpPin)), - (("otg", "ULPI_D0"), quote!(crate::usb_otg::UlpiD0Pin)), - (("otg", "ULPI_D1"), quote!(crate::usb_otg::UlpiD1Pin)), - (("otg", "ULPI_D2"), quote!(crate::usb_otg::UlpiD2Pin)), - (("otg", "ULPI_D3"), quote!(crate::usb_otg::UlpiD3Pin)), - (("otg", "ULPI_D4"), quote!(crate::usb_otg::UlpiD4Pin)), - (("otg", "ULPI_D5"), quote!(crate::usb_otg::UlpiD5Pin)), - (("otg", "ULPI_D6"), quote!(crate::usb_otg::UlpiD6Pin)), - (("otg", "ULPI_D7"), quote!(crate::usb_otg::UlpiD7Pin)), + (("otg", "DP"), quote!(crate::usb::DpPin)), + (("otg", "DM"), quote!(crate::usb::DmPin)), + (("otg", "ULPI_CK"), quote!(crate::usb::UlpiClkPin)), + (("otg", "ULPI_DIR"), quote!(crate::usb::UlpiDirPin)), + (("otg", "ULPI_NXT"), quote!(crate::usb::UlpiNxtPin)), + (("otg", "ULPI_STP"), quote!(crate::usb::UlpiStpPin)), + (("otg", "ULPI_D0"), quote!(crate::usb::UlpiD0Pin)), + (("otg", "ULPI_D1"), quote!(crate::usb::UlpiD1Pin)), + (("otg", "ULPI_D2"), quote!(crate::usb::UlpiD2Pin)), + (("otg", "ULPI_D3"), quote!(crate::usb::UlpiD3Pin)), + (("otg", "ULPI_D4"), quote!(crate::usb::UlpiD4Pin)), + (("otg", "ULPI_D5"), quote!(crate::usb::UlpiD5Pin)), + (("otg", "ULPI_D6"), quote!(crate::usb::UlpiD6Pin)), + (("otg", "ULPI_D7"), quote!(crate::usb::UlpiD7Pin)), (("can", "TX"), quote!(crate::can::TxPin)), (("can", "RX"), quote!(crate::can::RxPin)), (("eth", "REF_CLK"), quote!(crate::eth::RefClkPin)), @@ -887,6 +1018,9 @@ fn main() { (("hrtim", "CHE2"), quote!(crate::hrtim::ChannelEComplementaryPin)), (("hrtim", "CHF1"), quote!(crate::hrtim::ChannelFPin)), (("hrtim", "CHF2"), quote!(crate::hrtim::ChannelFComplementaryPin)), + (("lptim", "CH1"), quote!(crate::lptim::Channel1Pin)), + (("lptim", "CH2"), quote!(crate::lptim::Channel2Pin)), + (("lptim", "OUT"), quote!(crate::lptim::OutputPin)), (("sdmmc", "CK"), quote!(crate::sdmmc::CkPin)), (("sdmmc", "CMD"), quote!(crate::sdmmc::CmdPin)), (("sdmmc", "D0"), quote!(crate::sdmmc::D0Pin)), @@ -909,6 +1043,74 @@ fn main() { (("quadspi", "BK2_IO3"), quote!(crate::qspi::BK2D3Pin)), (("quadspi", "BK2_NCS"), quote!(crate::qspi::BK2NSSPin)), (("quadspi", "CLK"), quote!(crate::qspi::SckPin)), + (("octospi", "IO0"), quote!(crate::ospi::D0Pin)), + (("octospi", "IO1"), quote!(crate::ospi::D1Pin)), + (("octospi", "IO2"), quote!(crate::ospi::D2Pin)), + (("octospi", "IO3"), quote!(crate::ospi::D3Pin)), + (("octospi", "IO4"), quote!(crate::ospi::D4Pin)), + (("octospi", "IO5"), quote!(crate::ospi::D5Pin)), + (("octospi", "IO6"), quote!(crate::ospi::D6Pin)), + (("octospi", "IO7"), quote!(crate::ospi::D7Pin)), + (("octospi", "DQS"), quote!(crate::ospi::DQSPin)), + (("octospi", "NCS"), quote!(crate::ospi::NSSPin)), + (("octospi", "CLK"), quote!(crate::ospi::SckPin)), + (("octospi", "NCLK"), quote!(crate::ospi::NckPin)), + (("octospim", "P1_IO0"), quote!(crate::ospi::D0Pin)), + (("octospim", "P1_IO1"), quote!(crate::ospi::D1Pin)), + (("octospim", "P1_IO2"), quote!(crate::ospi::D2Pin)), + (("octospim", "P1_IO3"), quote!(crate::ospi::D3Pin)), + (("octospim", "P1_IO4"), quote!(crate::ospi::D4Pin)), + (("octospim", "P1_IO5"), quote!(crate::ospi::D5Pin)), + (("octospim", "P1_IO6"), quote!(crate::ospi::D6Pin)), + (("octospim", "P1_IO7"), quote!(crate::ospi::D7Pin)), + (("octospim", "P1_DQS"), quote!(crate::ospi::DQSPin)), + (("octospim", "P1_NCS"), quote!(crate::ospi::NSSPin)), + (("octospim", "P1_CLK"), quote!(crate::ospi::SckPin)), + (("octospim", "P1_NCLK"), quote!(crate::ospi::NckPin)), + (("octospim", "P2_IO0"), quote!(crate::ospi::D0Pin)), + (("octospim", "P2_IO1"), quote!(crate::ospi::D1Pin)), + (("octospim", "P2_IO2"), quote!(crate::ospi::D2Pin)), + (("octospim", "P2_IO3"), quote!(crate::ospi::D3Pin)), + (("octospim", "P2_IO4"), quote!(crate::ospi::D4Pin)), + (("octospim", "P2_IO5"), quote!(crate::ospi::D5Pin)), + (("octospim", "P2_IO6"), quote!(crate::ospi::D6Pin)), + (("octospim", "P2_IO7"), quote!(crate::ospi::D7Pin)), + (("octospim", "P2_DQS"), quote!(crate::ospi::DQSPin)), + (("octospim", "P2_NCS"), quote!(crate::ospi::NSSPin)), + (("octospim", "P2_CLK"), quote!(crate::ospi::SckPin)), + (("octospim", "P2_NCLK"), quote!(crate::ospi::NckPin)), + (("tsc", "G1_IO1"), quote!(crate::tsc::G1IO1Pin)), + (("tsc", "G1_IO2"), quote!(crate::tsc::G1IO2Pin)), + (("tsc", "G1_IO3"), quote!(crate::tsc::G1IO3Pin)), + (("tsc", "G1_IO4"), quote!(crate::tsc::G1IO4Pin)), + (("tsc", "G2_IO1"), quote!(crate::tsc::G2IO1Pin)), + (("tsc", "G2_IO2"), quote!(crate::tsc::G2IO2Pin)), + (("tsc", "G2_IO3"), quote!(crate::tsc::G2IO3Pin)), + (("tsc", "G2_IO4"), quote!(crate::tsc::G2IO4Pin)), + (("tsc", "G3_IO1"), quote!(crate::tsc::G3IO1Pin)), + (("tsc", "G3_IO2"), quote!(crate::tsc::G3IO2Pin)), + (("tsc", "G3_IO3"), quote!(crate::tsc::G3IO3Pin)), + (("tsc", "G3_IO4"), quote!(crate::tsc::G3IO4Pin)), + (("tsc", "G4_IO1"), quote!(crate::tsc::G4IO1Pin)), + (("tsc", "G4_IO2"), quote!(crate::tsc::G4IO2Pin)), + (("tsc", "G4_IO3"), quote!(crate::tsc::G4IO3Pin)), + (("tsc", "G4_IO4"), quote!(crate::tsc::G4IO4Pin)), + (("tsc", "G5_IO1"), quote!(crate::tsc::G5IO1Pin)), + (("tsc", "G5_IO2"), quote!(crate::tsc::G5IO2Pin)), + (("tsc", "G5_IO3"), quote!(crate::tsc::G5IO3Pin)), + (("tsc", "G5_IO4"), quote!(crate::tsc::G5IO4Pin)), + (("tsc", "G6_IO1"), quote!(crate::tsc::G6IO1Pin)), + (("tsc", "G6_IO2"), quote!(crate::tsc::G6IO2Pin)), + (("tsc", "G6_IO3"), quote!(crate::tsc::G6IO3Pin)), + (("tsc", "G6_IO4"), quote!(crate::tsc::G6IO4Pin)), + (("tsc", "G7_IO1"), quote!(crate::tsc::G7IO1Pin)), + (("tsc", "G7_IO2"), quote!(crate::tsc::G7IO2Pin)), + (("tsc", "G7_IO3"), quote!(crate::tsc::G7IO3Pin)), + (("tsc", "G7_IO4"), quote!(crate::tsc::G7IO4Pin)), + (("tsc", "G8_IO1"), quote!(crate::tsc::G8IO1Pin)), + (("tsc", "G8_IO2"), quote!(crate::tsc::G8IO2Pin)), + (("tsc", "G8_IO3"), quote!(crate::tsc::G8IO3Pin)), + (("tsc", "G8_IO4"), quote!(crate::tsc::G8IO4Pin)), ].into(); for p in METADATA.peripherals { @@ -934,6 +1136,18 @@ fn main() { peri = format_ident!("{}", pin.signal.replace('_', "")); } + // OCTOSPIM is special + if p.name == "OCTOSPIM" { + // Some chips have OCTOSPIM but not OCTOSPI2. + if METADATA.peripherals.iter().any(|p| p.name == "OCTOSPI2") { + peri = format_ident!("{}", "OCTOSPI2"); + g.extend(quote! { + pin_trait_impl!(#tr, #peri, #pin_name, #af); + }); + } + peri = format_ident!("{}", "OCTOSPI1"); + } + g.extend(quote! { pin_trait_impl!(#tr, #peri, #pin_name, #af); }) @@ -971,7 +1185,7 @@ fn main() { }; if let Some(ch) = ch { g.extend(quote! { - impl_adc_pin!( #peri, #pin_name, #ch); + impl_adc_pin!( #peri, #pin_name, #ch); }) } } @@ -1003,7 +1217,7 @@ fn main() { let ch: u8 = pin.signal.strip_prefix("OUT").unwrap().parse().unwrap(); g.extend(quote! { - impl_dac_pin!( #peri, #pin_name, #ch); + impl_dac_pin!( #peri, #pin_name, #ch); }) } } @@ -1015,6 +1229,13 @@ fn main() { let signals: HashMap<_, _> = [ // (kind, signal) => trait + (("adc", "ADC"), quote!(crate::adc::RxDma)), + (("adc", "ADC1"), quote!(crate::adc::RxDma)), + (("adc", "ADC2"), quote!(crate::adc::RxDma)), + (("adc", "ADC3"), quote!(crate::adc::RxDma)), + (("adc", "ADC4"), quote!(crate::adc::RxDma)), + (("ucpd", "RX"), quote!(crate::ucpd::RxDma)), + (("ucpd", "TX"), quote!(crate::ucpd::TxDma)), (("usart", "RX"), quote!(crate::usart::RxDma)), (("usart", "TX"), quote!(crate::usart::TxDma)), (("lpuart", "RX"), quote!(crate::usart::RxDma)), @@ -1030,56 +1251,77 @@ fn main() { // SDMMCv1 uses the same channel for both directions, so just implement for RX (("sdmmc", "RX"), quote!(crate::sdmmc::SdmmcDma)), (("quadspi", "QUADSPI"), quote!(crate::qspi::QuadDma)), + (("octospi", "OCTOSPI1"), quote!(crate::ospi::OctoDma)), (("dac", "CH1"), quote!(crate::dac::DacDma1)), (("dac", "CH2"), quote!(crate::dac::DacDma2)), (("timer", "UP"), quote!(crate::timer::UpDma)), + (("hash", "IN"), quote!(crate::hash::Dma)), + (("cryp", "IN"), quote!(crate::cryp::DmaIn)), + (("cryp", "OUT"), quote!(crate::cryp::DmaOut)), (("timer", "CH1"), quote!(crate::timer::Ch1Dma)), (("timer", "CH2"), quote!(crate::timer::Ch2Dma)), (("timer", "CH3"), quote!(crate::timer::Ch3Dma)), (("timer", "CH4"), quote!(crate::timer::Ch4Dma)), + (("cordic", "WRITE"), quote!(crate::cordic::WriteDma)), // FIXME: stm32u5a crash on Cordic driver + (("cordic", "READ"), quote!(crate::cordic::ReadDma)), // FIXME: stm32u5a crash on Cordic driver ] .into(); for p in METADATA.peripherals { if let Some(regs) = &p.registers { + // FIXME: stm32u5a crash on Cordic driver + if chip_name.starts_with("stm32u5a") && regs.kind == "cordic" { + continue; + } + let mut dupe = HashSet::new(); for ch in p.dma_channels { - // Some chips have multiple request numbers for the same (peri, signal, channel) combos. - // Ignore the dupes, picking the first one. Otherwise this causes conflicting trait impls - let key = (ch.signal, ch.channel); - if !dupe.insert(key) { - continue; - } - if let Some(tr) = signals.get(&(regs.kind, ch.signal)) { let peri = format_ident!("{}", p.name); - let channel = if let Some(channel) = &ch.channel { + let channels = if let Some(channel) = &ch.channel { // Chip with DMA/BDMA, without DMAMUX - let channel = format_ident!("{}", channel); - quote!({channel: #channel}) + vec![*channel] } else if let Some(dmamux) = &ch.dmamux { // Chip with DMAMUX - let dmamux = format_ident!("{}", dmamux); - quote!({dmamux: #dmamux}) + METADATA + .dma_channels + .iter() + .filter(|ch| ch.dmamux == Some(*dmamux)) + .map(|ch| ch.name) + .collect() } else if let Some(dma) = &ch.dma { // Chip with GPDMA - let dma = format_ident!("{}", dma); - quote!({dma: #dma}) + METADATA + .dma_channels + .iter() + .filter(|ch| ch.dma == *dma) + .map(|ch| ch.name) + .collect() } else { unreachable!(); }; - let request = if let Some(request) = ch.request { - let request = request as u8; - quote!(#request) - } else { - quote!(()) - }; + for channel in channels { + // Some chips have multiple request numbers for the same (peri, signal, channel) combos. + // Ignore the dupes, picking the first one. Otherwise this causes conflicting trait impls + let key = (ch.signal, channel.to_string()); + if !dupe.insert(key) { + continue; + } - g.extend(quote! { - dma_trait_impl!(#tr, #peri, #channel, #request); - }); + let request = if let Some(request) = ch.request { + let request = request as u8; + quote!(#request) + } else { + quote!(()) + }; + + let channel = format_ident!("{}", channel); + g.extend(quote! { + dma_trait_impl!(#tr, #peri, #channel, #request); + }); + } } } } @@ -1200,18 +1442,7 @@ fn main() { let mut interrupts_table: Vec> = Vec::new(); let mut peripherals_table: Vec> = Vec::new(); let mut pins_table: Vec> = Vec::new(); - let mut dma_channels_table: Vec> = Vec::new(); - let mut adc_common_table: Vec> = Vec::new(); - - /* - If ADC3_COMMON exists, ADC3 and higher are assigned to it - All other ADCs are assigned to ADC_COMMON - - ADC3 and higher are assigned to the adc34 clock in the table - The adc3_common cfg directive is added if ADC3_COMMON exists - */ - let has_adc3 = METADATA.peripherals.iter().any(|p| p.name == "ADC3_COMMON"); - let set_adc345 = HashSet::from(["ADC3", "ADC4", "ADC5"]); + let mut adc_table: Vec> = Vec::new(); for m in METADATA .memory @@ -1268,14 +1499,18 @@ fn main() { } if regs.kind == "adc" { - let (adc_common, adc_clock) = if set_adc345.contains(p.name) && has_adc3 { - ("ADC3_COMMON", "adc34") - } else { - ("ADC_COMMON", "adc") - }; - - let row = vec![p.name.to_string(), adc_common.to_string(), adc_clock.to_string()]; - adc_common_table.push(row); + let adc_num = p.name.strip_prefix("ADC").unwrap(); + let mut adc_common = None; + for p2 in METADATA.peripherals { + if let Some(common_nums) = p2.name.strip_prefix("ADC").and_then(|s| s.strip_suffix("_COMMON")) { + if common_nums.contains(adc_num) { + adc_common = Some(p2); + } + } + } + let adc_common = adc_common.map(|p| p.name).unwrap_or("none"); + let row = vec![p.name.to_string(), adc_common.to_string(), "adc".to_string()]; + adc_table.push(row); } for irq in p.interrupts { @@ -1294,51 +1529,136 @@ fn main() { } } - let mut dma_channel_count: usize = 0; - let mut bdma_channel_count: usize = 0; - let mut gpdma_channel_count: usize = 0; + let mut dmas = TokenStream::new(); + let has_dmamux = METADATA + .peripherals + .iter() + .flat_map(|p| &p.registers) + .any(|p| p.kind == "dmamux"); + + let mut dma_irqs: BTreeMap<&str, Vec> = BTreeMap::new(); + + for p in METADATA.peripherals { + if let Some(r) = &p.registers { + if r.kind == "dma" || r.kind == "bdma" || r.kind == "gpdma" || r.kind == "lpdma" { + for irq in p.interrupts { + let ch_name = format!("{}_{}", p.name, irq.signal); + let ch = METADATA.dma_channels.iter().find(|c| c.name == ch_name).unwrap(); + + // Some H7 chips have BDMA1 hardcoded for DFSDM, ie no DMAMUX. It's unsupported, skip it. + if has_dmamux && ch.dmamux.is_none() { + continue; + } + + dma_irqs.entry(irq.interrupt).or_default().push(ch_name); + } + } + } + } + + #[cfg(feature = "_dual-core")] + let mut dma_ch_to_irq: BTreeMap<&str, Vec> = BTreeMap::new(); + + #[cfg(feature = "_dual-core")] + for (irq, channels) in &dma_irqs { + for channel in channels { + dma_ch_to_irq.entry(channel).or_default().push(irq.to_string()); + } + } + + for (ch_idx, ch) in METADATA.dma_channels.iter().enumerate() { + // Some H7 chips have BDMA1 hardcoded for DFSDM, ie no DMAMUX. It's unsupported, skip it. + if has_dmamux && ch.dmamux.is_none() { + continue; + } + + let name = format_ident!("{}", ch.name); + let idx = ch_idx as u8; + #[cfg(feature = "_dual-core")] + let irq = { + let irq_name = if let Some(x) = &dma_ch_to_irq.get(ch.name) { + format_ident!("{}", x.get(0).unwrap()) + } else { + panic!("failed to find dma interrupt") + }; + quote!(crate::pac::Interrupt::#irq_name) + }; + + g.extend(quote!(dma_channel_impl!(#name, #idx);)); + + let dma = format_ident!("{}", ch.dma); + let ch_num = ch.channel as usize; - for ch in METADATA.dma_channels { - let mut row = Vec::new(); let dma_peri = METADATA.peripherals.iter().find(|p| p.name == ch.dma).unwrap(); let bi = dma_peri.registers.as_ref().unwrap(); - let num; - match bi.kind { - "dma" => { - num = dma_channel_count; - dma_channel_count += 1; - } - "bdma" => { - num = bdma_channel_count; - bdma_channel_count += 1; - } - "gpdma" => { - num = gpdma_channel_count; - gpdma_channel_count += 1; - } + let dma_info = match bi.kind { + "dma" => quote!(crate::dma::DmaInfo::Dma(crate::pac::#dma)), + "bdma" => quote!(crate::dma::DmaInfo::Bdma(crate::pac::#dma)), + "gpdma" => quote!(crate::pac::#dma), + "lpdma" => quote!(unsafe { crate::pac::gpdma::Gpdma::from_ptr(crate::pac::#dma.as_ptr())}), _ => panic!("bad dma channel kind {}", bi.kind), - } + }; - row.push(ch.name.to_string()); - row.push(ch.dma.to_string()); - row.push(bi.kind.to_string()); - row.push(ch.channel.to_string()); - row.push(num.to_string()); - if let Some(dmamux) = &ch.dmamux { - let dmamux_channel = ch.dmamux_channel.unwrap(); - row.push(format!("{{dmamux: {}, dmamux_channel: {}}}", dmamux, dmamux_channel)); - } else { - row.push("{}".to_string()); - } + let dmamux = match &ch.dmamux { + Some(dmamux) => { + let dmamux = format_ident!("{}", dmamux); + let num = ch.dmamux_channel.unwrap() as usize; + quote! { + dmamux: crate::dma::DmamuxInfo { + mux: crate::pac::#dmamux, + num: #num, + }, + } + } + None => quote!(), + }; - dma_channels_table.push(row); + #[cfg(not(feature = "_dual-core"))] + dmas.extend(quote! { + crate::dma::ChannelInfo { + dma: #dma_info, + num: #ch_num, + #dmamux + }, + }); + #[cfg(feature = "_dual-core")] + dmas.extend(quote! { + crate::dma::ChannelInfo { + dma: #dma_info, + num: #ch_num, + irq: #irq, + #dmamux + }, + }); } + // ======== + // Generate DMA IRQs. + + let dma_irqs: TokenStream = dma_irqs + .iter() + .map(|(irq, channels)| { + let irq = format_ident!("{}", irq); + + let channels = channels.iter().map(|c| format_ident!("{}", c)); + + quote! { + #[cfg(feature = "rt")] + #[crate::interrupt] + unsafe fn #irq () { + #( + ::on_irq(); + )* + } + } + }) + .collect(); + + g.extend(dma_irqs); + g.extend(quote! { - pub(crate) const DMA_CHANNEL_COUNT: usize = #dma_channel_count; - pub(crate) const BDMA_CHANNEL_COUNT: usize = #bdma_channel_count; - pub(crate) const GPDMA_CHANNEL_COUNT: usize = #gpdma_channel_count; + pub(crate) const DMA_CHANNELS: &[crate::dma::ChannelInfo] = &[#dmas]; }); for irq in METADATA.interrupts { @@ -1349,7 +1669,7 @@ fn main() { } } - let mut m = String::new(); + let mut m = clocks_macro.to_string(); // DO NOT ADD more macros like these. // These turned to be a bad idea! @@ -1358,71 +1678,80 @@ fn main() { make_table(&mut m, "foreach_interrupt", &interrupts_table); make_table(&mut m, "foreach_peripheral", &peripherals_table); make_table(&mut m, "foreach_pin", &pins_table); - make_table(&mut m, "foreach_dma_channel", &dma_channels_table); - make_table(&mut m, "foreach_adc", &adc_common_table); + make_table(&mut m, "foreach_adc", &adc_table); let out_dir = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); let out_file = out_dir.join("_macros.rs").to_string_lossy().to_string(); - fs::write(out_file, m).unwrap(); + fs::write(&out_file, m).unwrap(); + rustfmt(&out_file); // ======== // Write generated.rs let out_file = out_dir.join("_generated.rs").to_string_lossy().to_string(); - fs::write(out_file, g.to_string()).unwrap(); + fs::write(&out_file, g.to_string()).unwrap(); + rustfmt(&out_file); // ======== - // Multicore + // Configs for multicore and for targeting groups of chips - let mut s = chip_name.split('_'); - let mut chip_name: String = s.next().unwrap().to_string(); - let core_name = if let Some(c) = s.next() { - if !c.starts_with("CM") { - chip_name.push('_'); - chip_name.push_str(c); + fn get_chip_cfgs(chip_name: &str) -> Vec { + let mut cfgs = Vec::new(); + + // Multicore + + let mut s = chip_name.split('_'); + let mut chip_name: String = s.next().unwrap().to_string(); + let core_name = if let Some(c) = s.next() { + if !c.starts_with("CM") { + chip_name.push('_'); + chip_name.push_str(c); + None + } else { + Some(c) + } + } else { None - } else { - Some(c) + }; + + if let Some(core) = core_name { + cfgs.push(format!("{}_{}", &chip_name[..chip_name.len() - 2], core)); } - } else { - None - }; - if let Some(core) = core_name { - println!("cargo:rustc-cfg={}_{}", &chip_name[..chip_name.len() - 2], core); - } - - // ======= - // ADC3_COMMON is present - #[allow(clippy::print_literal)] - if has_adc3 { - println!("cargo:rustc-cfg={}", "adc3_common"); - } - - // ======= - // Features for targeting groups of chips - - if &chip_name[..8] == "stm32wba" { - println!("cargo:rustc-cfg={}", &chip_name[..8]); // stm32wba - println!("cargo:rustc-cfg={}", &chip_name[..10]); // stm32wba52 - println!("cargo:rustc-cfg=package_{}", &chip_name[10..11]); - println!("cargo:rustc-cfg=flashsize_{}", &chip_name[11..12]); - } else { - println!("cargo:rustc-cfg={}", &chip_name[..7]); // stm32f4 - println!("cargo:rustc-cfg={}", &chip_name[..9]); // stm32f429 - println!("cargo:rustc-cfg={}x", &chip_name[..8]); // stm32f42x - println!("cargo:rustc-cfg={}x{}", &chip_name[..7], &chip_name[8..9]); // stm32f4x9 - println!("cargo:rustc-cfg=package_{}", &chip_name[9..10]); - println!("cargo:rustc-cfg=flashsize_{}", &chip_name[10..11]); - } - - // Mark the L4+ chips as they have many differences to regular L4. - if &chip_name[..7] == "stm32l4" { - if "pqrs".contains(&chip_name[7..8]) { - println!("cargo:rustc-cfg=stm32l4_plus"); + // Configs for targeting groups of chips + if &chip_name[..8] == "stm32wba" { + cfgs.push(chip_name[..8].to_owned()); // stm32wba + cfgs.push(chip_name[..10].to_owned()); // stm32wba52 + cfgs.push(format!("package_{}", &chip_name[10..11])); + cfgs.push(format!("flashsize_{}", &chip_name[11..12])); } else { - println!("cargo:rustc-cfg=stm32l4_nonplus"); + if &chip_name[..8] == "stm32h7r" || &chip_name[..8] == "stm32h7s" { + cfgs.push("stm32h7rs".to_owned()); + } else { + cfgs.push(chip_name[..7].to_owned()); // stm32f4 + } + cfgs.push(chip_name[..9].to_owned()); // stm32f429 + cfgs.push(format!("{}x", &chip_name[..8])); // stm32f42x + cfgs.push(format!("{}x{}", &chip_name[..7], &chip_name[8..9])); // stm32f4x9 + cfgs.push(format!("package_{}", &chip_name[9..10])); + cfgs.push(format!("flashsize_{}", &chip_name[10..11])); } + + // Mark the L4+ chips as they have many differences to regular L4. + if &chip_name[..7] == "stm32l4" { + if "pqrs".contains(&chip_name[7..8]) { + cfgs.push("stm32l4_plus".to_owned()); + } else { + cfgs.push("stm32l4_nonplus".to_owned()); + } + } + + cfgs + } + + cfgs.enable_all(&get_chip_cfgs(&chip_name)); + for &chip_name in ALL_CHIPS.iter() { + cfgs.declare_all(&get_chip_cfgs(&chip_name.to_ascii_lowercase())); } println!("cargo:rerun-if-changed=build.rs"); @@ -1491,3 +1820,23 @@ fn get_flash_region_type_name(name: &str) -> String { .replace("REGION", "Region") .replace('_', "") } + +/// rustfmt a given path. +/// Failures are logged to stderr and ignored. +fn rustfmt(path: impl AsRef) { + let path = path.as_ref(); + match Command::new("rustfmt").args([path]).output() { + Err(e) => { + eprintln!("failed to exec rustfmt {:?}: {:?}", path, e); + } + Ok(out) => { + if !out.status.success() { + eprintln!("rustfmt {:?} failed:", path); + eprintln!("=== STDOUT:"); + std::io::stderr().write_all(&out.stdout).unwrap(); + eprintln!("=== STDERR:"); + std::io::stderr().write_all(&out.stderr).unwrap(); + } + } + } +} diff --git a/embassy-stm32/build_common.rs b/embassy-stm32/build_common.rs new file mode 100644 index 000000000..4f24e6d37 --- /dev/null +++ b/embassy-stm32/build_common.rs @@ -0,0 +1,94 @@ +// NOTE: this file is copy-pasted between several Embassy crates, because there is no +// straightforward way to share this code: +// - it cannot be placed into the root of the repo and linked from each build.rs using `#[path = +// "../build_common.rs"]`, because `cargo publish` requires that all files published with a crate +// reside in the crate's directory, +// - it cannot be symlinked from `embassy-xxx/build_common.rs` to `../build_common.rs`, because +// symlinks don't work on Windows. + +use std::collections::HashSet; +use std::env; + +/// Helper for emitting cargo instruction for enabling configs (`cargo:rustc-cfg=X`) and declaring +/// them (`cargo:rust-check-cfg=cfg(X)`). +#[derive(Debug)] +pub struct CfgSet { + enabled: HashSet, + declared: HashSet, +} + +impl CfgSet { + pub fn new() -> Self { + Self { + enabled: HashSet::new(), + declared: HashSet::new(), + } + } + + /// Enable a config, which can then be used in `#[cfg(...)]` for conditional compilation. + /// + /// All configs that can potentially be enabled should be unconditionally declared using + /// [`Self::declare()`]. + pub fn enable(&mut self, cfg: impl AsRef) { + if self.enabled.insert(cfg.as_ref().to_owned()) { + println!("cargo:rustc-cfg={}", cfg.as_ref()); + } + } + + pub fn enable_all(&mut self, cfgs: &[impl AsRef]) { + for cfg in cfgs.iter() { + self.enable(cfg.as_ref()); + } + } + + /// Declare a valid config for conditional compilation, without enabling it. + /// + /// This enables rustc to check that the configs in `#[cfg(...)]` attributes are valid. + pub fn declare(&mut self, cfg: impl AsRef) { + if self.declared.insert(cfg.as_ref().to_owned()) { + println!("cargo:rustc-check-cfg=cfg({})", cfg.as_ref()); + } + } + + pub fn declare_all(&mut self, cfgs: &[impl AsRef]) { + for cfg in cfgs.iter() { + self.declare(cfg.as_ref()); + } + } + + pub fn set(&mut self, cfg: impl Into, enable: bool) { + let cfg = cfg.into(); + if enable { + self.enable(cfg.clone()); + } + self.declare(cfg); + } +} + +/// Sets configs that describe the target platform. +pub fn set_target_cfgs(cfgs: &mut CfgSet) { + let target = env::var("TARGET").unwrap(); + + if target.starts_with("thumbv6m-") { + cfgs.enable_all(&["cortex_m", "armv6m"]); + } else if target.starts_with("thumbv7m-") { + cfgs.enable_all(&["cortex_m", "armv7m"]); + } else if target.starts_with("thumbv7em-") { + cfgs.enable_all(&["cortex_m", "armv7m", "armv7em"]); + } else if target.starts_with("thumbv8m.base") { + cfgs.enable_all(&["cortex_m", "armv8m", "armv8m_base"]); + } else if target.starts_with("thumbv8m.main") { + cfgs.enable_all(&["cortex_m", "armv8m", "armv8m_main"]); + } + cfgs.declare_all(&[ + "cortex_m", + "armv6m", + "armv7m", + "armv7em", + "armv8m", + "armv8m_base", + "armv8m_main", + ]); + + cfgs.set("has_fpu", target.ends_with("-eabihf")); +} diff --git a/embassy-stm32/src/adc/f1.rs b/embassy-stm32/src/adc/f1.rs index fb27bb87b..b37ec260f 100644 --- a/embassy-stm32/src/adc/f1.rs +++ b/embassy-stm32/src/adc/f1.rs @@ -3,12 +3,11 @@ use core::marker::PhantomData; use core::task::Poll; use embassy_hal_internal::into_ref; -use embedded_hal_02::blocking::delay::DelayUs; -use crate::adc::{Adc, AdcPin, Instance, SampleTime}; -use crate::rcc::get_freqs; +use super::blocking_delay_us; +use crate::adc::{Adc, AdcChannel, Instance, SampleTime}; use crate::time::Hertz; -use crate::{interrupt, Peripheral}; +use crate::{interrupt, rcc, Peripheral}; pub const VDDA_CALIB_MV: u32 = 3300; pub const ADC_MAX: u32 = (1 << 12) - 1; @@ -33,30 +32,30 @@ impl interrupt::typelevel::Handler for InterruptHandl } pub struct Vref; -impl AdcPin for Vref {} -impl super::sealed::AdcPin for Vref { +impl AdcChannel for Vref {} +impl super::SealedAdcChannel for Vref { fn channel(&self) -> u8 { 17 } } pub struct Temperature; -impl AdcPin for Temperature {} -impl super::sealed::AdcPin for Temperature { +impl AdcChannel for Temperature {} +impl super::SealedAdcChannel for Temperature { fn channel(&self) -> u8 { 16 } } impl<'d, T: Instance> Adc<'d, T> { - pub fn new(adc: impl Peripheral

+ 'd, delay: &mut impl DelayUs) -> Self { + pub fn new(adc: impl Peripheral

+ 'd) -> Self { into_ref!(adc); - T::enable_and_reset(); + rcc::enable_and_reset::(); T::regs().cr2().modify(|reg| reg.set_adon(true)); // 11.4: Before starting a calibration, the ADC must have been in power-on state (ADON bit = ‘1’) - // for at least two ADC clock cycles - delay.delay_us((1_000_000 * 2) / Self::freq().0 + 1); + // for at least two ADC clock cycles. + blocking_delay_us((1_000_000 * 2) / Self::freq().0 + 1); // Reset calibration T::regs().cr2().modify(|reg| reg.set_rstcal(true)); @@ -71,32 +70,32 @@ impl<'d, T: Instance> Adc<'d, T> { } // One cycle after calibration - delay.delay_us((1_000_000) / Self::freq().0 + 1); + blocking_delay_us((1_000_000 * 1) / Self::freq().0 + 1); Self { adc, - sample_time: Default::default(), + sample_time: SampleTime::from_bits(0), } } fn freq() -> Hertz { - unsafe { get_freqs() }.adc.unwrap() + T::frequency() } pub fn sample_time_for_us(&self, us: u32) -> SampleTime { match us * Self::freq().0 / 1_000_000 { - 0..=1 => SampleTime::Cycles1_5, - 2..=7 => SampleTime::Cycles7_5, - 8..=13 => SampleTime::Cycles13_5, - 14..=28 => SampleTime::Cycles28_5, - 29..=41 => SampleTime::Cycles41_5, - 42..=55 => SampleTime::Cycles55_5, - 56..=71 => SampleTime::Cycles71_5, - _ => SampleTime::Cycles239_5, + 0..=1 => SampleTime::CYCLES1_5, + 2..=7 => SampleTime::CYCLES7_5, + 8..=13 => SampleTime::CYCLES13_5, + 14..=28 => SampleTime::CYCLES28_5, + 29..=41 => SampleTime::CYCLES41_5, + 42..=55 => SampleTime::CYCLES55_5, + 56..=71 => SampleTime::CYCLES71_5, + _ => SampleTime::CYCLES239_5, } } - pub fn enable_vref(&self, _delay: &mut impl DelayUs) -> Vref { + pub fn enable_vref(&self) -> Vref { T::regs().cr2().modify(|reg| { reg.set_tsvrefe(true); }); @@ -136,8 +135,8 @@ impl<'d, T: Instance> Adc<'d, T> { T::regs().dr().read().0 as u16 } - pub async fn read(&mut self, pin: &mut impl AdcPin) -> u16 { - Self::set_channel_sample_time(pin.channel(), self.sample_time); + pub async fn read(&mut self, channel: &mut impl AdcChannel) -> u16 { + Self::set_channel_sample_time(channel.channel(), self.sample_time); T::regs().cr1().modify(|reg| { reg.set_scan(false); reg.set_discen(false); @@ -152,7 +151,7 @@ impl<'d, T: Instance> Adc<'d, T> { }); // Configure the channel to sample - T::regs().sqr3().write(|reg| reg.set_sq(0, pin.channel())); + T::regs().sqr3().write(|reg| reg.set_sq(0, channel.channel())); self.convert().await } @@ -170,6 +169,6 @@ impl<'d, T: Instance> Drop for Adc<'d, T> { fn drop(&mut self) { T::regs().cr2().modify(|reg| reg.set_adon(false)); - T::disable(); + rcc::disable::(); } } diff --git a/embassy-stm32/src/adc/f3.rs b/embassy-stm32/src/adc/f3.rs index 6f59c230f..0ebeb8a9e 100644 --- a/embassy-stm32/src/adc/f3.rs +++ b/embassy-stm32/src/adc/f3.rs @@ -3,12 +3,12 @@ use core::marker::PhantomData; use core::task::Poll; use embassy_hal_internal::into_ref; -use embedded_hal_02::blocking::delay::DelayUs; -use crate::adc::{Adc, AdcPin, Instance, SampleTime}; +use super::blocking_delay_us; +use crate::adc::{Adc, AdcChannel, Instance, SampleTime}; use crate::interrupt::typelevel::Interrupt; use crate::time::Hertz; -use crate::{interrupt, Peripheral}; +use crate::{interrupt, rcc, Peripheral}; pub const VDDA_CALIB_MV: u32 = 3300; pub const ADC_MAX: u32 = (1 << 12) - 1; @@ -32,8 +32,8 @@ impl interrupt::typelevel::Handler for InterruptHandl } pub struct Vref; -impl AdcPin for Vref {} -impl super::sealed::AdcPin for Vref { +impl AdcChannel for Vref {} +impl super::SealedAdcChannel for Vref { fn channel(&self) -> u8 { 18 } @@ -42,13 +42,13 @@ impl super::sealed::AdcPin for Vref { impl Vref { /// The value that vref would be if vdda was at 3300mv pub fn value(&self) -> u16 { - crate::pac::VREFINTCAL.data().read().value() + crate::pac::VREFINTCAL.data().read() } } pub struct Temperature; -impl AdcPin for Temperature {} -impl super::sealed::AdcPin for Temperature { +impl AdcChannel for Temperature {} +impl super::SealedAdcChannel for Temperature { fn channel(&self) -> u8 { 16 } @@ -58,20 +58,19 @@ impl<'d, T: Instance> Adc<'d, T> { pub fn new( adc: impl Peripheral

+ 'd, _irq: impl interrupt::typelevel::Binding> + 'd, - delay: &mut impl DelayUs, ) -> Self { use crate::pac::adc::vals; into_ref!(adc); - T::enable_and_reset(); + rcc::enable_and_reset::(); // Enable the adc regulator T::regs().cr().modify(|w| w.set_advregen(vals::Advregen::INTERMEDIATE)); T::regs().cr().modify(|w| w.set_advregen(vals::Advregen::ENABLED)); // Wait for the regulator to stabilize - delay.delay_us(10); + blocking_delay_us(10); assert!(!T::regs().cr().read().aden()); @@ -81,8 +80,8 @@ impl<'d, T: Instance> Adc<'d, T> { while T::regs().cr().read().adcal() {} - // Wait more than 4 clock cycles after adcal is cleared (RM0364 p. 223) - delay.delay_us(1 + (6 * 1_000_000 / Self::freq().0)); + // Wait more than 4 clock cycles after adcal is cleared (RM0364 p. 223). + blocking_delay_us((1_000_000 * 4) / Self::freq().0 + 1); // Enable the adc T::regs().cr().modify(|w| w.set_aden(true)); @@ -97,27 +96,27 @@ impl<'d, T: Instance> Adc<'d, T> { Self { adc, - sample_time: Default::default(), + sample_time: SampleTime::from_bits(0), } } fn freq() -> Hertz { - ::frequency() + ::frequency() } pub fn sample_time_for_us(&self, us: u32) -> SampleTime { match us * Self::freq().0 / 1_000_000 { - 0..=1 => SampleTime::Cycles1_5, - 2..=4 => SampleTime::Cycles4_5, - 5..=7 => SampleTime::Cycles7_5, - 8..=19 => SampleTime::Cycles19_5, - 20..=61 => SampleTime::Cycles61_5, - 62..=181 => SampleTime::Cycles181_5, - _ => SampleTime::Cycles601_5, + 0..=1 => SampleTime::CYCLES1_5, + 2..=4 => SampleTime::CYCLES4_5, + 5..=7 => SampleTime::CYCLES7_5, + 8..=19 => SampleTime::CYCLES19_5, + 20..=61 => SampleTime::CYCLES61_5, + 62..=181 => SampleTime::CYCLES181_5, + _ => SampleTime::CYCLES601_5, } } - pub fn enable_vref(&self, _delay: &mut impl DelayUs) -> Vref { + pub fn enable_vref(&self) -> Vref { T::common_regs().ccr().modify(|w| w.set_vrefen(true)); Vref {} @@ -155,11 +154,11 @@ impl<'d, T: Instance> Adc<'d, T> { T::regs().dr().read().rdata() } - pub async fn read(&mut self, pin: &mut impl AdcPin) -> u16 { - Self::set_channel_sample_time(pin.channel(), self.sample_time); + pub async fn read(&mut self, channel: &mut impl AdcChannel) -> u16 { + Self::set_channel_sample_time(channel.channel(), self.sample_time); // Configure the channel to sample - T::regs().sqr1().write(|w| w.set_sq(0, pin.channel())); + T::regs().sqr1().write(|w| w.set_sq(0, channel.channel())); self.convert().await } @@ -189,6 +188,6 @@ impl<'d, T: Instance> Drop for Adc<'d, T> { T::regs().cr().modify(|w| w.set_advregen(vals::Advregen::INTERMEDIATE)); T::regs().cr().modify(|w| w.set_advregen(vals::Advregen::DISABLED)); - T::disable(); + rcc::disable::(); } } diff --git a/embassy-stm32/src/adc/f3_v1_1.rs b/embassy-stm32/src/adc/f3_v1_1.rs index 6915a8f1c..291a3861e 100644 --- a/embassy-stm32/src/adc/f3_v1_1.rs +++ b/embassy-stm32/src/adc/f3_v1_1.rs @@ -7,10 +7,10 @@ use embassy_hal_internal::into_ref; use embassy_time::Instant; use super::Resolution; -use crate::adc::{Adc, AdcPin, Instance, SampleTime}; +use crate::adc::{Adc, AdcChannel, Instance, SampleTime}; use crate::interrupt::typelevel::Interrupt; use crate::time::Hertz; -use crate::{interrupt, Peripheral}; +use crate::{interrupt, rcc, Peripheral}; const ADC_FREQ: Hertz = crate::rcc::HSI_FREQ; @@ -64,8 +64,8 @@ fn update_vref(op: i8) { } pub struct Vref(core::marker::PhantomData); -impl AdcPin for Vref {} -impl super::sealed::AdcPin for Vref { +impl AdcChannel for Vref {} +impl super::SealedAdcChannel for Vref { fn channel(&self) -> u8 { 17 } @@ -74,7 +74,7 @@ impl super::sealed::AdcPin for Vref { impl Vref { /// The value that vref would be if vdda was at 3000mv pub fn calibrated_value(&self) -> u16 { - crate::pac::VREFINTCAL.data().read().value() + crate::pac::VREFINTCAL.data().read() } pub async fn calibrate(&mut self, adc: &mut Adc<'_, T>) -> Calibration { @@ -107,12 +107,12 @@ impl Calibration { /// Returns a calibrated voltage value as in microvolts (uV) pub fn cal_uv(&self, raw: u16, resolution: super::Resolution) -> u32 { - (self.vdda_uv() / resolution.to_max_count()) * raw as u32 + (self.vdda_uv() / super::resolution_to_max_count(resolution)) * raw as u32 } /// Returns a calibrated voltage value as an f32 pub fn cal_f32(&self, raw: u16, resolution: super::Resolution) -> f32 { - raw as f32 * self.vdda_f32() / resolution.to_max_count() as f32 + raw as f32 * self.vdda_f32() / super::resolution_to_max_count(resolution) as f32 } } @@ -123,8 +123,8 @@ impl Drop for Vref { } pub struct Temperature(core::marker::PhantomData); -impl AdcPin for Temperature {} -impl super::sealed::AdcPin for Temperature { +impl AdcChannel for Temperature {} +impl super::SealedAdcChannel for Temperature { fn channel(&self) -> u8 { 16 } @@ -143,7 +143,7 @@ impl<'d, T: Instance> Adc<'d, T> { ) -> Self { into_ref!(adc); - T::enable_and_reset(); + rcc::enable_and_reset::(); //let r = T::regs(); //r.cr2().write(|w| w.set_align(true)); @@ -175,12 +175,7 @@ impl<'d, T: Instance> Adc<'d, T> { } pub fn resolution(&self) -> Resolution { - match T::regs().cr1().read().res() { - crate::pac::adc::vals::Res::TWELVEBIT => Resolution::TwelveBit, - crate::pac::adc::vals::Res::TENBIT => Resolution::TenBit, - crate::pac::adc::vals::Res::EIGHTBIT => Resolution::EightBit, - crate::pac::adc::vals::Res::SIXBIT => Resolution::SixBit, - } + T::regs().cr1().read().res() } pub fn enable_vref(&self) -> Vref { @@ -276,8 +271,8 @@ impl<'d, T: Instance> Adc<'d, T> { } } - pub async fn read(&mut self, pin: &mut impl AdcPin) -> u16 { - self.set_sample_sequence(&[pin.channel()]).await; + pub async fn read(&mut self, channel: &mut impl AdcChannel) -> u16 { + self.set_sample_sequence(&[channel.channel()]).await; self.convert().await } @@ -288,18 +283,18 @@ impl<'d, T: Instance> Adc<'d, T> { } } - pub async fn set_sample_time(&mut self, pin: &mut impl AdcPin, sample_time: SampleTime) { - if Self::get_channel_sample_time(pin.channel()) != sample_time { + pub async fn set_sample_time(&mut self, channel: &mut impl AdcChannel, sample_time: SampleTime) { + if Self::get_channel_sample_time(channel.channel()) != sample_time { self.stop_adc().await; unsafe { - Self::set_channel_sample_time(pin.channel(), sample_time); + Self::set_channel_sample_time(channel.channel(), sample_time); } self.start_adc().await; } } - pub fn get_sample_time(&self, pin: &impl AdcPin) -> SampleTime { - Self::get_channel_sample_time(pin.channel()) + pub fn get_sample_time(&self, channel: &impl AdcChannel) -> SampleTime { + Self::get_channel_sample_time(channel.channel()) } /// Sets the channel sample time @@ -359,23 +354,23 @@ impl<'d, T: Instance> Adc<'d, T> { fn get_res_clks(res: Resolution) -> u32 { match res { - Resolution::TwelveBit => 12, - Resolution::TenBit => 11, - Resolution::EightBit => 9, - Resolution::SixBit => 7, + Resolution::BITS12 => 12, + Resolution::BITS10 => 11, + Resolution::BITS8 => 9, + Resolution::BITS6 => 7, } } fn get_sample_time_clks(sample_time: SampleTime) -> u32 { match sample_time { - SampleTime::Cycles4 => 4, - SampleTime::Cycles9 => 9, - SampleTime::Cycles16 => 16, - SampleTime::Cycles24 => 24, - SampleTime::Cycles48 => 48, - SampleTime::Cycles96 => 96, - SampleTime::Cycles192 => 192, - SampleTime::Cycles384 => 384, + SampleTime::CYCLES4 => 4, + SampleTime::CYCLES9 => 9, + SampleTime::CYCLES16 => 16, + SampleTime::CYCLES24 => 24, + SampleTime::CYCLES48 => 48, + SampleTime::CYCLES96 => 96, + SampleTime::CYCLES192 => 192, + SampleTime::CYCLES384 => 384, } } @@ -384,14 +379,14 @@ impl<'d, T: Instance> Adc<'d, T> { let us_clks = us * Self::freq().0 / 1_000_000; let clks = us_clks.saturating_sub(res_clks); match clks { - 0..=4 => SampleTime::Cycles4, - 5..=9 => SampleTime::Cycles9, - 10..=16 => SampleTime::Cycles16, - 17..=24 => SampleTime::Cycles24, - 25..=48 => SampleTime::Cycles48, - 49..=96 => SampleTime::Cycles96, - 97..=192 => SampleTime::Cycles192, - 193.. => SampleTime::Cycles384, + 0..=4 => SampleTime::CYCLES4, + 5..=9 => SampleTime::CYCLES9, + 10..=16 => SampleTime::CYCLES16, + 17..=24 => SampleTime::CYCLES24, + 25..=48 => SampleTime::CYCLES48, + 49..=96 => SampleTime::CYCLES96, + 97..=192 => SampleTime::CYCLES192, + 193.. => SampleTime::CYCLES384, } } @@ -408,6 +403,6 @@ impl<'d, T: Instance> Drop for Adc<'d, T> { T::regs().cr2().modify(|w| w.set_adon(false)); - T::disable(); + rcc::disable::(); } } diff --git a/embassy-stm32/src/adc/g4.rs b/embassy-stm32/src/adc/g4.rs new file mode 100644 index 000000000..3e9ba8ae2 --- /dev/null +++ b/embassy-stm32/src/adc/g4.rs @@ -0,0 +1,361 @@ +#[allow(unused)] +#[cfg(stm32h7)] +use pac::adc::vals::{Adcaldif, Difsel, Exten}; +#[allow(unused)] +#[cfg(stm32g4)] +use pac::adc::vals::{Adcaldif, Difsel, Exten, Rovsm, Trovs}; +use pac::adccommon::vals::Presc; + +use super::{blocking_delay_us, Adc, AdcChannel, Instance, Resolution, SampleTime}; +use crate::time::Hertz; +use crate::{pac, rcc, Peripheral}; + +/// Default VREF voltage used for sample conversion to millivolts. +pub const VREF_DEFAULT_MV: u32 = 3300; +/// VREF voltage used for factory calibration of VREFINTCAL register. +pub const VREF_CALIB_MV: u32 = 3300; + +/// Max single ADC operation clock frequency +#[cfg(stm32g4)] +const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(60); +#[cfg(stm32h7)] +const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(50); + +#[cfg(stm32g4)] +const VREF_CHANNEL: u8 = 18; +#[cfg(stm32g4)] +const TEMP_CHANNEL: u8 = 16; + +#[cfg(stm32h7)] +const VREF_CHANNEL: u8 = 19; +#[cfg(stm32h7)] +const TEMP_CHANNEL: u8 = 18; + +// TODO this should be 14 for H7a/b/35 +const VBAT_CHANNEL: u8 = 17; + +// NOTE: Vrefint/Temperature/Vbat are not available on all ADCs, this currently cannot be modeled with stm32-data, so these are available from the software on all ADCs +/// Internal voltage reference channel. +pub struct VrefInt; +impl AdcChannel for VrefInt {} +impl super::SealedAdcChannel for VrefInt { + fn channel(&self) -> u8 { + VREF_CHANNEL + } +} + +/// Internal temperature channel. +pub struct Temperature; +impl AdcChannel for Temperature {} +impl super::SealedAdcChannel for Temperature { + fn channel(&self) -> u8 { + TEMP_CHANNEL + } +} + +/// Internal battery voltage channel. +pub struct Vbat; +impl AdcChannel for Vbat {} +impl super::SealedAdcChannel for Vbat { + fn channel(&self) -> u8 { + VBAT_CHANNEL + } +} + +// NOTE (unused): The prescaler enum closely copies the hardware capabilities, +// but high prescaling doesn't make a lot of sense in the current implementation and is ommited. +#[allow(unused)] +enum Prescaler { + NotDivided, + DividedBy2, + DividedBy4, + DividedBy6, + DividedBy8, + DividedBy10, + DividedBy12, + DividedBy16, + DividedBy32, + DividedBy64, + DividedBy128, + DividedBy256, +} + +impl Prescaler { + fn from_ker_ck(frequency: Hertz) -> Self { + let raw_prescaler = frequency.0 / MAX_ADC_CLK_FREQ.0; + match raw_prescaler { + 0 => Self::NotDivided, + 1 => Self::DividedBy2, + 2..=3 => Self::DividedBy4, + 4..=5 => Self::DividedBy6, + 6..=7 => Self::DividedBy8, + 8..=9 => Self::DividedBy10, + 10..=11 => Self::DividedBy12, + _ => unimplemented!(), + } + } + + fn divisor(&self) -> u32 { + match self { + Prescaler::NotDivided => 1, + Prescaler::DividedBy2 => 2, + Prescaler::DividedBy4 => 4, + Prescaler::DividedBy6 => 6, + Prescaler::DividedBy8 => 8, + Prescaler::DividedBy10 => 10, + Prescaler::DividedBy12 => 12, + Prescaler::DividedBy16 => 16, + Prescaler::DividedBy32 => 32, + Prescaler::DividedBy64 => 64, + Prescaler::DividedBy128 => 128, + Prescaler::DividedBy256 => 256, + } + } + + fn presc(&self) -> Presc { + match self { + Prescaler::NotDivided => Presc::DIV1, + Prescaler::DividedBy2 => Presc::DIV2, + Prescaler::DividedBy4 => Presc::DIV4, + Prescaler::DividedBy6 => Presc::DIV6, + Prescaler::DividedBy8 => Presc::DIV8, + Prescaler::DividedBy10 => Presc::DIV10, + Prescaler::DividedBy12 => Presc::DIV12, + Prescaler::DividedBy16 => Presc::DIV16, + Prescaler::DividedBy32 => Presc::DIV32, + Prescaler::DividedBy64 => Presc::DIV64, + Prescaler::DividedBy128 => Presc::DIV128, + Prescaler::DividedBy256 => Presc::DIV256, + } + } +} + +impl<'d, T: Instance> Adc<'d, T> { + /// Create a new ADC driver. + pub fn new(adc: impl Peripheral

+ 'd) -> Self { + embassy_hal_internal::into_ref!(adc); + rcc::enable_and_reset::(); + + let prescaler = Prescaler::from_ker_ck(T::frequency()); + + T::common_regs().ccr().modify(|w| w.set_presc(prescaler.presc())); + + let frequency = Hertz(T::frequency().0 / prescaler.divisor()); + info!("ADC frequency set to {} Hz", frequency.0); + + if frequency > MAX_ADC_CLK_FREQ { + panic!("Maximal allowed frequency for the ADC is {} MHz and it varies with different packages, refer to ST docs for more information.", MAX_ADC_CLK_FREQ.0 / 1_000_000 ); + } + + let mut s = Self { + adc, + sample_time: SampleTime::from_bits(0), + }; + s.power_up(); + s.configure_differential_inputs(); + + s.calibrate(); + blocking_delay_us(1); + + s.enable(); + s.configure(); + + s + } + + fn power_up(&mut self) { + T::regs().cr().modify(|reg| { + reg.set_deeppwd(false); + reg.set_advregen(true); + }); + + blocking_delay_us(10); + } + + fn configure_differential_inputs(&mut self) { + T::regs().difsel().modify(|w| { + for n in 0..18 { + w.set_difsel(n, Difsel::SINGLEENDED); + } + }); + } + + fn calibrate(&mut self) { + T::regs().cr().modify(|w| { + w.set_adcaldif(Adcaldif::SINGLEENDED); + }); + + T::regs().cr().modify(|w| w.set_adcal(true)); + + while T::regs().cr().read().adcal() {} + } + + fn enable(&mut self) { + T::regs().isr().write(|w| w.set_adrdy(true)); + T::regs().cr().modify(|w| w.set_aden(true)); + while !T::regs().isr().read().adrdy() {} + T::regs().isr().write(|w| w.set_adrdy(true)); + } + + fn configure(&mut self) { + // single conversion mode, software trigger + T::regs().cfgr().modify(|w| { + w.set_cont(false); + w.set_exten(Exten::DISABLED); + }); + } + + /// Enable reading the voltage reference internal channel. + pub fn enable_vrefint(&self) -> VrefInt { + T::common_regs().ccr().modify(|reg| { + reg.set_vrefen(true); + }); + + VrefInt {} + } + + /// Enable reading the temperature internal channel. + pub fn enable_temperature(&self) -> Temperature { + T::common_regs().ccr().modify(|reg| { + reg.set_vsenseen(true); + }); + + Temperature {} + } + + /// Enable reading the vbat internal channel. + pub fn enable_vbat(&self) -> Vbat { + T::common_regs().ccr().modify(|reg| { + reg.set_vbaten(true); + }); + + Vbat {} + } + + /// Enable differential channel. + /// Caution: + /// : When configuring the channel “i” in differential input mode, its negative input voltage VINN[i] + /// is connected to another channel. As a consequence, this channel is no longer usable in + /// single-ended mode or in differential mode and must never be configured to be converted. + /// Some channels are shared between ADC1/ADC2/ADC3/ADC4/ADC5: this can make the + /// channel on the other ADC unusable. The only exception is when ADC master and the slave + /// operate in interleaved mode. + #[cfg(stm32g4)] + pub fn set_differential_channel(&mut self, ch: usize, enable: bool) { + T::regs().cr().modify(|w| w.set_aden(false)); // disable adc + T::regs().difsel().modify(|w| { + w.set_difsel( + ch, + if enable { + Difsel::DIFFERENTIAL + } else { + Difsel::SINGLEENDED + }, + ); + }); + T::regs().cr().modify(|w| w.set_aden(true)); + } + + #[cfg(stm32g4)] + pub fn set_differential(&mut self, channel: &mut impl AdcChannel, enable: bool) { + self.set_differential_channel(channel.channel() as usize, enable); + } + + /// Set oversampling shift. + #[cfg(stm32g4)] + pub fn set_oversampling_shift(&mut self, shift: u8) { + T::regs().cfgr2().modify(|reg| reg.set_ovss(shift)); + } + + /// Set oversampling ratio. + #[cfg(stm32g4)] + pub fn set_oversampling_ratio(&mut self, ratio: u8) { + T::regs().cfgr2().modify(|reg| reg.set_ovsr(ratio)); + } + + /// Enable oversampling in regular mode. + #[cfg(stm32g4)] + pub fn enable_regular_oversampling_mode(&mut self, mode: Rovsm, trig_mode: Trovs, enable: bool) { + T::regs().cfgr2().modify(|reg| reg.set_trovs(trig_mode)); + T::regs().cfgr2().modify(|reg| reg.set_rovsm(mode)); + T::regs().cfgr2().modify(|reg| reg.set_rovse(enable)); + } + + // Reads that are not implemented as INJECTED in "blocking_read" + // #[cfg(stm32g4)] + // pub fn enalble_injected_oversampling_mode(&mut self, enable: bool) { + // T::regs().cfgr2().modify(|reg| reg.set_jovse(enable)); + // } + + // #[cfg(stm32g4)] + // pub fn enable_oversampling_regular_injected_mode(&mut self, enable: bool) { + // // the regularoversampling mode is forced to resumed mode (ROVSM bit ignored), + // T::regs().cfgr2().modify(|reg| reg.set_rovse(enable)); + // T::regs().cfgr2().modify(|reg| reg.set_jovse(enable)); + // } + + /// Set the ADC sample time. + pub fn set_sample_time(&mut self, sample_time: SampleTime) { + self.sample_time = sample_time; + } + + /// Set the ADC resolution. + pub fn set_resolution(&mut self, resolution: Resolution) { + T::regs().cfgr().modify(|reg| reg.set_res(resolution.into())); + } + + /// Perform a single conversion. + fn convert(&mut self) -> u16 { + T::regs().isr().modify(|reg| { + reg.set_eos(true); + reg.set_eoc(true); + }); + + // Start conversion + T::regs().cr().modify(|reg| { + reg.set_adstart(true); + }); + + while !T::regs().isr().read().eos() { + // spin + } + + T::regs().dr().read().0 as u16 + } + + /// Read an ADC pin. + pub fn blocking_read(&mut self, channel: &mut impl AdcChannel) -> u16 { + channel.setup(); + + self.read_channel(channel.channel()) + } + + fn read_channel(&mut self, channel: u8) -> u16 { + // Configure channel + Self::set_channel_sample_time(channel, self.sample_time); + + #[cfg(stm32h7)] + { + T::regs().cfgr2().modify(|w| w.set_lshift(0)); + T::regs() + .pcsel() + .write(|w| w.set_pcsel(channel as _, Pcsel::PRESELECTED)); + } + + T::regs().sqr1().write(|reg| { + reg.set_sq(0, channel); + reg.set_l(0); + }); + + self.convert() + } + + fn set_channel_sample_time(ch: u8, sample_time: SampleTime) { + let sample_time = sample_time.into(); + if ch <= 9 { + T::regs().smpr().modify(|reg| reg.set_smp(ch as _, sample_time)); + } else { + T::regs().smpr2().modify(|reg| reg.set_smp((ch - 10) as _, sample_time)); + } + } +} diff --git a/embassy-stm32/src/adc/mod.rs b/embassy-stm32/src/adc/mod.rs index e4dd35c34..4ab82c1d9 100644 --- a/embassy-stm32/src/adc/mod.rs +++ b/embassy-stm32/src/adc/mod.rs @@ -2,139 +2,194 @@ #![macro_use] #![allow(missing_docs)] // TODO +#![cfg_attr(adc_f3_v2, allow(unused))] -#[cfg(not(adc_f3_v2))] +#[cfg(not(any(adc_f3_v2, adc_u5)))] #[cfg_attr(adc_f1, path = "f1.rs")] #[cfg_attr(adc_f3, path = "f3.rs")] #[cfg_attr(adc_f3_v1_1, path = "f3_v1_1.rs")] #[cfg_attr(adc_v1, path = "v1.rs")] +#[cfg_attr(adc_l0, path = "v1.rs")] #[cfg_attr(adc_v2, path = "v2.rs")] -#[cfg_attr(any(adc_v3, adc_g0), path = "v3.rs")] +#[cfg_attr(any(adc_v3, adc_g0, adc_h5, adc_u0), path = "v3.rs")] #[cfg_attr(adc_v4, path = "v4.rs")] +#[cfg_attr(adc_g4, path = "g4.rs")] mod _version; -#[cfg(not(any(adc_f1, adc_f3_v2)))] -mod resolution; -mod sample_time; +use core::marker::PhantomData; #[allow(unused)] -#[cfg(not(adc_f3_v2))] +#[cfg(not(any(adc_f3_v2, adc_u5)))] pub use _version::*; -#[cfg(not(any(adc_f1, adc_f3, adc_f3_v2)))] -pub use resolution::Resolution; -#[cfg(not(adc_f3_v2))] -pub use sample_time::SampleTime; +#[cfg(any(adc_f1, adc_f3, adc_v1, adc_l0, adc_f3_v1_1))] +use embassy_sync::waitqueue::AtomicWaker; +#[cfg(not(any(adc_u5)))] +pub use crate::pac::adc::vals; +#[cfg(not(any(adc_f1, adc_f3_v2, adc_u5)))] +pub use crate::pac::adc::vals::Res as Resolution; +#[cfg(not(any(adc_u5)))] +pub use crate::pac::adc::vals::SampleTime; use crate::peripherals; +dma_trait!(RxDma, Instance); + /// Analog to Digital driver. pub struct Adc<'d, T: Instance> { #[allow(unused)] adc: crate::PeripheralRef<'d, T>, - #[cfg(not(any(adc_f3_v2, adc_f3_v1_1)))] + #[cfg(not(any(adc_f3_v2, adc_f3_v1_1, adc_u5)))] sample_time: SampleTime, } -pub(crate) mod sealed { - #[cfg(any(adc_f1, adc_f3, adc_v1, adc_f3_v1_1))] - use embassy_sync::waitqueue::AtomicWaker; +#[cfg(any(adc_f1, adc_f3, adc_v1, adc_l0, adc_f3_v1_1))] +pub struct State { + pub waker: AtomicWaker, +} - #[cfg(any(adc_f1, adc_f3, adc_v1, adc_f3_v1_1))] - pub struct State { - pub waker: AtomicWaker, - } - - #[cfg(any(adc_f1, adc_f3, adc_v1, adc_f3_v1_1))] - impl State { - pub const fn new() -> Self { - Self { - waker: AtomicWaker::new(), - } +#[cfg(any(adc_f1, adc_f3, adc_v1, adc_l0, adc_f3_v1_1))] +impl State { + pub const fn new() -> Self { + Self { + waker: AtomicWaker::new(), } } +} - pub trait InterruptableInstance { - type Interrupt: crate::interrupt::typelevel::Interrupt; - } +trait SealedInstance { + #[allow(unused)] + fn regs() -> crate::pac::adc::Adc; + #[cfg(not(any(adc_f1, adc_v1, adc_l0, adc_f3_v2, adc_f3_v1_1, adc_g0, adc_u5)))] + #[allow(unused)] + fn common_regs() -> crate::pac::adccommon::AdcCommon; + #[cfg(any(adc_f1, adc_f3, adc_v1, adc_l0, adc_f3_v1_1))] + fn state() -> &'static State; +} - pub trait Instance: InterruptableInstance { - fn regs() -> crate::pac::adc::Adc; - #[cfg(not(any(adc_f1, adc_v1, adc_f3_v2, adc_f3_v1_1, adc_g0)))] - fn common_regs() -> crate::pac::adccommon::AdcCommon; - #[cfg(adc_f3)] - fn frequency() -> crate::time::Hertz; - #[cfg(any(adc_f1, adc_f3, adc_v1, adc_f3_v1_1))] - fn state() -> &'static State; - } +pub(crate) trait SealedAdcChannel { + #[cfg(any(adc_v1, adc_l0, adc_v2, adc_g4, adc_v4))] + fn setup(&mut self) {} - pub trait AdcPin { - #[cfg(any(adc_v1, adc_v2))] - fn set_as_analog(&mut self) {} + #[allow(unused)] + fn channel(&self) -> u8; +} - fn channel(&self) -> u8; - } - - pub trait InternalChannel { - fn channel(&self) -> u8; +/// Performs a busy-wait delay for a specified number of microseconds. +#[allow(unused)] +pub(crate) fn blocking_delay_us(us: u32) { + #[cfg(feature = "time")] + embassy_time::block_for(embassy_time::Duration::from_micros(us as u64)); + #[cfg(not(feature = "time"))] + { + let freq = unsafe { crate::rcc::get_freqs() }.sys.to_hertz().unwrap().0 as u64; + let us = us as u64; + let cycles = freq * us / 1_000_000; + cortex_m::asm::delay(cycles as u32); } } /// ADC instance. -#[cfg(not(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_f3_v1_1, adc_g0)))] -pub trait Instance: sealed::Instance + crate::Peripheral

{} +#[cfg(not(any( + adc_f1, + adc_v1, + adc_l0, + adc_v2, + adc_v3, + adc_v4, + adc_g4, + adc_f3, + adc_f3_v1_1, + adc_g0, + adc_u0, + adc_h5 +)))] +#[allow(private_bounds)] +pub trait Instance: SealedInstance + crate::Peripheral

{ + type Interrupt: crate::interrupt::typelevel::Interrupt; +} /// ADC instance. -#[cfg(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_f3_v1_1, adc_g0))] -pub trait Instance: sealed::Instance + crate::Peripheral

+ crate::rcc::RccPeripheral {} +#[cfg(any( + adc_f1, + adc_v1, + adc_l0, + adc_v2, + adc_v3, + adc_v4, + adc_g4, + adc_f3, + adc_f3_v1_1, + adc_g0, + adc_u0, + adc_h5 +))] +#[allow(private_bounds)] +pub trait Instance: SealedInstance + crate::Peripheral

+ crate::rcc::RccPeripheral { + type Interrupt: crate::interrupt::typelevel::Interrupt; +} -/// ADC pin. -pub trait AdcPin: sealed::AdcPin {} -/// ADC internal channel. -pub trait InternalChannel: sealed::InternalChannel {} +/// ADC channel. +#[allow(private_bounds)] +pub trait AdcChannel: SealedAdcChannel + Sized { + #[allow(unused_mut)] + fn degrade_adc(mut self) -> AnyAdcChannel { + #[cfg(any(adc_v1, adc_l0, adc_v2, adc_g4, adc_v4))] + self.setup(); + + AnyAdcChannel { + channel: self.channel(), + _phantom: PhantomData, + } + } +} + +/// A type-erased channel for a given ADC instance. +/// +/// This is useful in scenarios where you need the ADC channels to have the same type, such as +/// storing them in an array. +pub struct AnyAdcChannel { + channel: u8, + _phantom: PhantomData, +} + +impl AdcChannel for AnyAdcChannel {} +impl SealedAdcChannel for AnyAdcChannel { + fn channel(&self) -> u8 { + self.channel + } +} foreach_adc!( ($inst:ident, $common_inst:ident, $clock:ident) => { - impl crate::adc::sealed::Instance for peripherals::$inst { + impl crate::adc::SealedInstance for peripherals::$inst { fn regs() -> crate::pac::adc::Adc { crate::pac::$inst } - #[cfg(not(any(adc_f1, adc_v1, adc_f3_v2, adc_f3_v1_1, adc_g0)))] + #[cfg(not(any(adc_f1, adc_v1, adc_l0, adc_f3_v2, adc_f3_v1_1, adc_g0, adc_u5)))] fn common_regs() -> crate::pac::adccommon::AdcCommon { return crate::pac::$common_inst } - #[cfg(adc_f3)] - fn frequency() -> crate::time::Hertz { - unsafe { crate::rcc::get_freqs() }.$clock.unwrap() - } - - #[cfg(any(adc_f1, adc_f3, adc_v1, adc_f3_v1_1))] - fn state() -> &'static sealed::State { - static STATE: sealed::State = sealed::State::new(); + #[cfg(any(adc_f1, adc_f3, adc_v1, adc_l0, adc_f3_v1_1))] + fn state() -> &'static State { + static STATE: State = State::new(); &STATE } } - foreach_interrupt!( - ($inst,adc,ADC,GLOBAL,$irq:ident) => { - impl sealed::InterruptableInstance for peripherals::$inst { - type Interrupt = crate::interrupt::typelevel::$irq; - } - }; - ); - - impl crate::adc::Instance for peripherals::$inst {} + impl crate::adc::Instance for peripherals::$inst { + type Interrupt = crate::_generated::peripheral_interrupts::$inst::GLOBAL; + } }; ); macro_rules! impl_adc_pin { ($inst:ident, $pin:ident, $ch:expr) => { - impl crate::adc::AdcPin for crate::peripherals::$pin {} - - impl crate::adc::sealed::AdcPin for crate::peripherals::$pin { - #[cfg(any(adc_v1, adc_v2))] - fn set_as_analog(&mut self) { - ::set_as_analog(self); + impl crate::adc::AdcChannel for crate::peripherals::$pin {} + impl crate::adc::SealedAdcChannel for crate::peripherals::$pin { + #[cfg(any(adc_v1, adc_l0, adc_v2, adc_g4, adc_v4))] + fn setup(&mut self) { + ::set_as_analog(self); } fn channel(&self) -> u8 { @@ -143,3 +198,27 @@ macro_rules! impl_adc_pin { } }; } + +/// Get the maximum reading value for this resolution. +/// +/// This is `2**n - 1`. +#[cfg(not(any(adc_f1, adc_f3_v2, adc_u5)))] +pub const fn resolution_to_max_count(res: Resolution) -> u32 { + match res { + #[cfg(adc_v4)] + Resolution::BITS16 => (1 << 16) - 1, + #[cfg(adc_v4)] + Resolution::BITS14 => (1 << 14) - 1, + #[cfg(adc_v4)] + Resolution::BITS14V => (1 << 14) - 1, + #[cfg(adc_v4)] + Resolution::BITS12V => (1 << 12) - 1, + Resolution::BITS12 => (1 << 12) - 1, + Resolution::BITS10 => (1 << 10) - 1, + Resolution::BITS8 => (1 << 8) - 1, + #[cfg(any(adc_v1, adc_v2, adc_v3, adc_l0, adc_g0, adc_f3, adc_f3_v1_1, adc_h5))] + Resolution::BITS6 => (1 << 6) - 1, + #[allow(unreachable_patterns)] + _ => core::unreachable!(), + } +} diff --git a/embassy-stm32/src/adc/resolution.rs b/embassy-stm32/src/adc/resolution.rs deleted file mode 100644 index 9513e1df7..000000000 --- a/embassy-stm32/src/adc/resolution.rs +++ /dev/null @@ -1,72 +0,0 @@ -/// ADC resolution -#[allow(missing_docs)] -#[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3, adc_f3_v1_1))] -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub enum Resolution { - TwelveBit, - TenBit, - EightBit, - SixBit, -} - -/// ADC resolution -#[allow(missing_docs)] -#[cfg(adc_v4)] -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub enum Resolution { - SixteenBit, - FourteenBit, - TwelveBit, - TenBit, - EightBit, -} - -impl Default for Resolution { - fn default() -> Self { - #[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3, adc_f3_v1_1))] - { - Self::TwelveBit - } - #[cfg(adc_v4)] - { - Self::SixteenBit - } - } -} - -impl From for crate::pac::adc::vals::Res { - fn from(res: Resolution) -> crate::pac::adc::vals::Res { - match res { - #[cfg(adc_v4)] - Resolution::SixteenBit => crate::pac::adc::vals::Res::SIXTEENBIT, - #[cfg(adc_v4)] - Resolution::FourteenBit => crate::pac::adc::vals::Res::FOURTEENBITV, - Resolution::TwelveBit => crate::pac::adc::vals::Res::TWELVEBIT, - Resolution::TenBit => crate::pac::adc::vals::Res::TENBIT, - Resolution::EightBit => crate::pac::adc::vals::Res::EIGHTBIT, - #[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3, adc_f3_v1_1))] - Resolution::SixBit => crate::pac::adc::vals::Res::SIXBIT, - } - } -} - -impl Resolution { - /// Get the maximum reading value for this resolution. - /// - /// This is `2**n - 1`. - pub const fn to_max_count(&self) -> u32 { - match self { - #[cfg(adc_v4)] - Resolution::SixteenBit => (1 << 16) - 1, - #[cfg(adc_v4)] - Resolution::FourteenBit => (1 << 14) - 1, - Resolution::TwelveBit => (1 << 12) - 1, - Resolution::TenBit => (1 << 10) - 1, - Resolution::EightBit => (1 << 8) - 1, - #[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3, adc_f3_v1_1))] - Resolution::SixBit => (1 << 6) - 1, - } - } -} diff --git a/embassy-stm32/src/adc/ringbuffered_v2.rs b/embassy-stm32/src/adc/ringbuffered_v2.rs new file mode 100644 index 000000000..3f0c1a57a --- /dev/null +++ b/embassy-stm32/src/adc/ringbuffered_v2.rs @@ -0,0 +1,438 @@ +use core::marker::PhantomData; +use core::mem; +use core::sync::atomic::{compiler_fence, Ordering}; + +use embassy_hal_internal::{into_ref, Peripheral}; +use stm32_metapac::adc::vals::SampleTime; + +use crate::adc::{Adc, AdcChannel, Instance, RxDma}; +use crate::dma::{Priority, ReadableRingBuffer, TransferOptions}; +use crate::pac::adc::vals; +use crate::rcc; + +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct OverrunError; + +fn clear_interrupt_flags(r: crate::pac::adc::Adc) { + r.sr().modify(|regs| { + regs.set_eoc(false); + regs.set_ovr(false); + }); +} + +#[derive(PartialOrd, PartialEq, Debug, Clone, Copy)] +pub enum Sequence { + One, + Two, + Three, + Four, + Five, + Six, + Seven, + Eight, + Nine, + Ten, + Eleven, + Twelve, + Thirteen, + Fourteen, + Fifteen, + Sixteen, +} + +impl From for u8 { + fn from(s: Sequence) -> u8 { + match s { + Sequence::One => 0, + Sequence::Two => 1, + Sequence::Three => 2, + Sequence::Four => 3, + Sequence::Five => 4, + Sequence::Six => 5, + Sequence::Seven => 6, + Sequence::Eight => 7, + Sequence::Nine => 8, + Sequence::Ten => 9, + Sequence::Eleven => 10, + Sequence::Twelve => 11, + Sequence::Thirteen => 12, + Sequence::Fourteen => 13, + Sequence::Fifteen => 14, + Sequence::Sixteen => 15, + } + } +} + +impl From for Sequence { + fn from(val: u8) -> Self { + match val { + 0 => Sequence::One, + 1 => Sequence::Two, + 2 => Sequence::Three, + 3 => Sequence::Four, + 4 => Sequence::Five, + 5 => Sequence::Six, + 6 => Sequence::Seven, + 7 => Sequence::Eight, + 8 => Sequence::Nine, + 9 => Sequence::Ten, + 10 => Sequence::Eleven, + 11 => Sequence::Twelve, + 12 => Sequence::Thirteen, + 13 => Sequence::Fourteen, + 14 => Sequence::Fifteen, + 15 => Sequence::Sixteen, + _ => panic!("Invalid sequence number"), + } + } +} + +pub struct RingBufferedAdc<'d, T: Instance> { + _phantom: PhantomData, + ring_buf: ReadableRingBuffer<'d, u16>, +} + +impl<'d, T: Instance> Adc<'d, T> { + /// Configures the ADC to use a DMA ring buffer for continuous data acquisition. + /// + /// The `dma_buf` should be large enough to prevent DMA buffer overrun. + /// The length of the `dma_buf` should be a multiple of the ADC channel count. + /// For example, if 3 channels are measured, its length can be 3 * 40 = 120 measurements. + /// + /// `read` method is used to read out measurements from the DMA ring buffer, and its buffer should be exactly half of the `dma_buf` length. + /// It is critical to call `read` frequently to prevent DMA buffer overrun. + /// + /// [`read`]: #method.read + pub fn into_ring_buffered( + self, + dma: impl Peripheral

> + 'd, + dma_buf: &'d mut [u16], + ) -> RingBufferedAdc<'d, T> { + assert!(!dma_buf.is_empty() && dma_buf.len() <= 0xFFFF); + into_ref!(dma); + + let opts: crate::dma::TransferOptions = TransferOptions { + half_transfer_ir: true, + priority: Priority::VeryHigh, + ..Default::default() + }; + + // Safety: we forget the struct before this function returns. + let rx_src = T::regs().dr().as_ptr() as *mut u16; + let request = dma.request(); + + let ring_buf = unsafe { ReadableRingBuffer::new(dma, request, rx_src, dma_buf, opts) }; + + // Don't disable the clock + mem::forget(self); + + RingBufferedAdc { + _phantom: PhantomData, + ring_buf, + } + } +} + +impl<'d, T: Instance> RingBufferedAdc<'d, T> { + fn is_on() -> bool { + T::regs().cr2().read().adon() + } + + fn stop_adc() { + T::regs().cr2().modify(|reg| { + reg.set_adon(false); + }); + } + + fn start_adc() { + T::regs().cr2().modify(|reg| { + reg.set_adon(true); + }); + } + + /// Sets the channel sample time + /// + /// ## SAFETY: + /// - ADON == 0 i.e ADC must not be enabled when this is called. + unsafe fn set_channel_sample_time(ch: u8, sample_time: SampleTime) { + if ch <= 9 { + T::regs().smpr2().modify(|reg| reg.set_smp(ch as _, sample_time)); + } else { + T::regs().smpr1().modify(|reg| reg.set_smp((ch - 10) as _, sample_time)); + } + } + + fn set_channels_sample_time(&mut self, ch: &[u8], sample_time: SampleTime) { + let ch_iter = ch.iter(); + for idx in ch_iter { + unsafe { + Self::set_channel_sample_time(*idx, sample_time); + } + } + } + + pub fn set_sample_sequence( + &mut self, + sequence: Sequence, + channel: &mut impl AdcChannel, + sample_time: SampleTime, + ) { + let was_on = Self::is_on(); + if !was_on { + Self::start_adc(); + } + + // Check the sequence is long enough + T::regs().sqr1().modify(|r| { + let prev: Sequence = r.l().into(); + if prev < sequence { + let new_l: Sequence = sequence; + trace!("Setting sequence length from {:?} to {:?}", prev as u8, new_l as u8); + r.set_l(sequence.into()) + } else { + r.set_l(prev.into()) + } + }); + + // Set this GPIO as an analog input. + channel.setup(); + + // Set the channel in the right sequence field. + match sequence { + Sequence::One => T::regs().sqr3().modify(|w| w.set_sq(0, channel.channel())), + Sequence::Two => T::regs().sqr3().modify(|w| w.set_sq(1, channel.channel())), + Sequence::Three => T::regs().sqr3().modify(|w| w.set_sq(2, channel.channel())), + Sequence::Four => T::regs().sqr3().modify(|w| w.set_sq(3, channel.channel())), + Sequence::Five => T::regs().sqr3().modify(|w| w.set_sq(4, channel.channel())), + Sequence::Six => T::regs().sqr3().modify(|w| w.set_sq(5, channel.channel())), + Sequence::Seven => T::regs().sqr2().modify(|w| w.set_sq(6, channel.channel())), + Sequence::Eight => T::regs().sqr2().modify(|w| w.set_sq(7, channel.channel())), + Sequence::Nine => T::regs().sqr2().modify(|w| w.set_sq(8, channel.channel())), + Sequence::Ten => T::regs().sqr2().modify(|w| w.set_sq(9, channel.channel())), + Sequence::Eleven => T::regs().sqr2().modify(|w| w.set_sq(10, channel.channel())), + Sequence::Twelve => T::regs().sqr2().modify(|w| w.set_sq(11, channel.channel())), + Sequence::Thirteen => T::regs().sqr1().modify(|w| w.set_sq(12, channel.channel())), + Sequence::Fourteen => T::regs().sqr1().modify(|w| w.set_sq(13, channel.channel())), + Sequence::Fifteen => T::regs().sqr1().modify(|w| w.set_sq(14, channel.channel())), + Sequence::Sixteen => T::regs().sqr1().modify(|w| w.set_sq(15, channel.channel())), + }; + + if !was_on { + Self::stop_adc(); + } + + self.set_channels_sample_time(&[channel.channel()], sample_time); + + Self::start_adc(); + } + + /// Turns on ADC if it is not already turned on and starts continuous DMA transfer. + pub fn start(&mut self) -> Result<(), OverrunError> { + self.setup_adc(); + self.ring_buf.clear(); + + Ok(()) + } + + fn stop(&mut self, err: OverrunError) -> Result { + self.teardown_adc(); + Err(err) + } + + /// Stops DMA transfer. + /// It does not turn off ADC. + /// Calling `start` restarts continuous DMA transfer. + /// + /// [`start`]: #method.start + pub fn teardown_adc(&mut self) { + // Stop the DMA transfer + self.ring_buf.request_pause(); + + let r = T::regs(); + + // Stop ADC + r.cr2().modify(|reg| { + // Stop ADC + reg.set_swstart(false); + // Stop DMA + reg.set_dma(false); + }); + + r.cr1().modify(|w| { + // Disable interrupt for end of conversion + w.set_eocie(false); + // Disable interrupt for overrun + w.set_ovrie(false); + }); + + clear_interrupt_flags(r); + + compiler_fence(Ordering::SeqCst); + } + + fn setup_adc(&mut self) { + compiler_fence(Ordering::SeqCst); + + self.ring_buf.start(); + + let r = T::regs(); + + // Enable ADC + let was_on = Self::is_on(); + if !was_on { + r.cr2().modify(|reg| { + reg.set_adon(false); + reg.set_swstart(false); + }); + } + + // Clear all interrupts + r.sr().modify(|regs| { + regs.set_eoc(false); + regs.set_ovr(false); + regs.set_strt(false); + }); + + r.cr1().modify(|w| { + // Enable interrupt for end of conversion + w.set_eocie(true); + // Enable interrupt for overrun + w.set_ovrie(true); + // Scanning converisons of multiple channels + w.set_scan(true); + // Continuous conversion mode + w.set_discen(false); + }); + + r.cr2().modify(|w| { + // Enable DMA mode + w.set_dma(true); + // Enable continuous conversions + w.set_cont(true); + // DMA requests are issues as long as DMA=1 and data are converted. + w.set_dds(vals::Dds::CONTINUOUS); + // EOC flag is set at the end of each conversion. + w.set_eocs(vals::Eocs::EACHCONVERSION); + }); + + // Begin ADC conversions + T::regs().cr2().modify(|reg| { + reg.set_adon(true); + reg.set_swstart(true); + }); + + super::blocking_delay_us(3); + } + + /// Read bytes that are readily available in the ring buffer. + /// If no bytes are currently available in the buffer the call waits until the some + /// bytes are available (at least one byte and at most half the buffer size) + /// + /// Background receive is started if `start()` has not been previously called. + /// + /// Receive in the background is terminated if an error is returned. + /// It must then manually be started again by calling `start()` or by re-calling `read()`. + pub fn blocking_read(&mut self, buf: &mut [u16; N]) -> Result { + let r = T::regs(); + + // Start background receive if it was not already started + if !r.cr2().read().dma() { + self.start()?; + } + + // Clear overrun flag if set. + if r.sr().read().ovr() { + return self.stop(OverrunError); + } + + loop { + match self.ring_buf.read(buf) { + Ok((0, _)) => {} + Ok((len, _)) => { + return Ok(len); + } + Err(_) => { + return self.stop(OverrunError); + } + } + } + } + + /// Reads measurements from the DMA ring buffer. + /// + /// This method fills the provided `measurements` array with ADC readings from the DMA buffer. + /// The length of the `measurements` array should be exactly half of the DMA buffer length. Because interrupts are only generated if half or full DMA transfer completes. + /// + /// Each call to `read` will populate the `measurements` array in the same order as the channels defined with `set_sample_sequence`. + /// There will be many sequences worth of measurements in this array because it only returns if at least half of the DMA buffer is filled. + /// For example if 3 channels are sampled `measurements` contain: `[sq0 sq1 sq3 sq0 sq1 sq3 sq0 sq1 sq3 sq0 sq1 sq3..]`. + /// + /// If an error is returned, it indicates a DMA overrun, and the process must be restarted by calling `start` or `read` again. + /// + /// By default, the ADC fills the DMA buffer as quickly as possible. To control the sample rate, call `teardown_adc` after each readout, and then start the DMA again at the desired interval. + /// Note that even if using `teardown_adc` to control the sample rate, with each call to `read`, measurements equivalent to half the size of the DMA buffer are still collected. + /// + /// Example: + /// ```rust,ignore + /// const DMA_BUF_LEN: usize = 120; + /// let adc_dma_buf = [0u16; DMA_BUF_LEN]; + /// let mut adc: RingBufferedAdc = adc.into_ring_buffered(p.DMA2_CH0, adc_dma_buf); + /// + /// adc.set_sample_sequence(Sequence::One, &mut p.PA0, SampleTime::CYCLES112); + /// adc.set_sample_sequence(Sequence::Two, &mut p.PA1, SampleTime::CYCLES112); + /// adc.set_sample_sequence(Sequence::Three, &mut p.PA2, SampleTime::CYCLES112); + /// + /// let mut measurements = [0u16; DMA_BUF_LEN / 2]; + /// loop { + /// match adc.read(&mut measurements).await { + /// Ok(_) => { + /// defmt::info!("adc1: {}", measurements); + /// // Only needed to manually control sample rate. + /// adc.teardown_adc(); + /// } + /// Err(e) => { + /// defmt::warn!("Error: {:?}", e); + /// // DMA overrun, next call to `read` restarts ADC. + /// } + /// } + /// + /// // Manually control sample rate. + /// Timer::after_millis(100).await; + /// } + /// ``` + /// + /// + /// [`set_sample_sequence`]: #method.set_sample_sequence + /// [`teardown_adc`]: #method.teardown_adc + /// [`start`]: #method.start + pub async fn read(&mut self, measurements: &mut [u16; N]) -> Result { + assert_eq!( + self.ring_buf.capacity() / 2, + N, + "Buffer size must be half the size of the ring buffer" + ); + + let r = T::regs(); + + // Start background receive if it was not already started + if !r.cr2().read().dma() { + self.start()?; + } + + // Clear overrun flag if set. + if r.sr().read().ovr() { + return self.stop(OverrunError); + } + match self.ring_buf.read_exact(measurements).await { + Ok(len) => Ok(len), + Err(_) => self.stop(OverrunError), + } + } +} + +impl Drop for RingBufferedAdc<'_, T> { + fn drop(&mut self) { + self.teardown_adc(); + rcc::disable::(); + } +} diff --git a/embassy-stm32/src/adc/sample_time.rs b/embassy-stm32/src/adc/sample_time.rs deleted file mode 100644 index 5a06f1a5a..000000000 --- a/embassy-stm32/src/adc/sample_time.rs +++ /dev/null @@ -1,148 +0,0 @@ -#[cfg(not(adc_f3_v2))] -macro_rules! impl_sample_time { - ($default_doc:expr, $default:ident, ($(($doc:expr, $variant:ident, $pac_variant:ident)),*)) => { - #[doc = concat!("ADC sample time\n\nThe default setting is ", $default_doc, " ADC clock cycles.")] - #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)] - #[cfg_attr(feature = "defmt", derive(defmt::Format))] - pub enum SampleTime { - $( - #[doc = concat!($doc, " ADC clock cycles.")] - $variant, - )* - } - - impl From for crate::pac::adc::vals::SampleTime { - fn from(sample_time: SampleTime) -> crate::pac::adc::vals::SampleTime { - match sample_time { - $(SampleTime::$variant => crate::pac::adc::vals::SampleTime::$pac_variant),* - } - } - } - - impl From for SampleTime { - fn from(sample_time: crate::pac::adc::vals::SampleTime) -> SampleTime { - match sample_time { - $(crate::pac::adc::vals::SampleTime::$pac_variant => SampleTime::$variant),* - } - } - } - - impl Default for SampleTime { - fn default() -> Self { - Self::$default - } - } - }; -} - -#[cfg(any(adc_f1, adc_v1))] -impl_sample_time!( - "1.5", - Cycles1_5, - ( - ("1.5", Cycles1_5, CYCLES1_5), - ("7.5", Cycles7_5, CYCLES7_5), - ("13.5", Cycles13_5, CYCLES13_5), - ("28.5", Cycles28_5, CYCLES28_5), - ("41.5", Cycles41_5, CYCLES41_5), - ("55.5", Cycles55_5, CYCLES55_5), - ("71.5", Cycles71_5, CYCLES71_5), - ("239.5", Cycles239_5, CYCLES239_5) - ) -); - -#[cfg(adc_v2)] -impl_sample_time!( - "3", - Cycles3, - ( - ("3", Cycles3, CYCLES3), - ("15", Cycles15, CYCLES15), - ("28", Cycles28, CYCLES28), - ("56", Cycles56, CYCLES56), - ("84", Cycles84, CYCLES84), - ("112", Cycles112, CYCLES112), - ("144", Cycles144, CYCLES144), - ("480", Cycles480, CYCLES480) - ) -); - -#[cfg(adc_v3)] -impl_sample_time!( - "2.5", - Cycles2_5, - ( - ("2.5", Cycles2_5, CYCLES2_5), - ("6.5", Cycles6_5, CYCLES6_5), - ("12.5", Cycles12_5, CYCLES12_5), - ("24.5", Cycles24_5, CYCLES24_5), - ("47.5", Cycles47_5, CYCLES47_5), - ("92.5", Cycles92_5, CYCLES92_5), - ("247.5", Cycles247_5, CYCLES247_5), - ("640.5", Cycles640_5, CYCLES640_5) - ) -); - -#[cfg(adc_g0)] -impl_sample_time!( - "1.5", - Cycles1_5, - ( - ("1.5", Cycles1_5, CYCLES1_5), - ("3.5", Cycles3_5, CYCLES3_5), - ("7.5", Cycles7_5, CYCLES7_5), - ("12.5", Cycles12_5, CYCLES12_5), - ("19.5", Cycles19_5, CYCLES19_5), - ("39.5", Cycles39_5, CYCLES39_5), - ("79.5", Cycles79_5, CYCLES79_5), - ("160.5", Cycles160_5, CYCLES160_5) - ) -); - -#[cfg(adc_v4)] -impl_sample_time!( - "1.5", - Cycles1_5, - ( - ("1.5", Cycles1_5, CYCLES1_5), - ("2.5", Cycles2_5, CYCLES2_5), - ("8.5", Cycles8_5, CYCLES8_5), - ("16.5", Cycles16_5, CYCLES16_5), - ("32.5", Cycles32_5, CYCLES32_5), - ("64.5", Cycles64_5, CYCLES64_5), - ("387.5", Cycles387_5, CYCLES387_5), - ("810.5", Cycles810_5, CYCLES810_5) - ) -); - -#[cfg(adc_f3)] -impl_sample_time!( - "1.5", - Cycles1_5, - ( - ("1.5", Cycles1_5, CYCLES1_5), - ("2.5", Cycles2_5, CYCLES2_5), - ("4.5", Cycles4_5, CYCLES4_5), - ("7.5", Cycles7_5, CYCLES7_5), - ("19.5", Cycles19_5, CYCLES19_5), - ("61.5", Cycles61_5, CYCLES61_5), - ("181.5", Cycles181_5, CYCLES181_5), - ("601.5", Cycles601_5, CYCLES601_5) - ) -); - -#[cfg(any(adc_f3_v1_1))] -impl_sample_time!( - "4", - Cycles4, - ( - ("4", Cycles4, CYCLES4), - ("9", Cycles9, CYCLES9), - ("16", Cycles16, CYCLES16), - ("24", Cycles24, CYCLES24), - ("48", Cycles48, CYCLES48), - ("96", Cycles96, CYCLES96), - ("192", Cycles192, CYCLES192), - ("384", Cycles384, CYCLES384) - ) -); diff --git a/embassy-stm32/src/adc/v1.rs b/embassy-stm32/src/adc/v1.rs index 852b027df..9bec2e13b 100644 --- a/embassy-stm32/src/adc/v1.rs +++ b/embassy-stm32/src/adc/v1.rs @@ -3,12 +3,14 @@ use core::marker::PhantomData; use core::task::Poll; use embassy_hal_internal::into_ref; -use embedded_hal_02::blocking::delay::DelayUs; +#[cfg(adc_l0)] +use stm32_metapac::adc::vals::Ckmode; -use crate::adc::{Adc, AdcPin, Instance, Resolution, SampleTime}; +use super::blocking_delay_us; +use crate::adc::{Adc, AdcChannel, Instance, Resolution, SampleTime}; use crate::interrupt::typelevel::Interrupt; -use crate::peripherals::ADC; -use crate::{interrupt, Peripheral}; +use crate::peripherals::ADC1; +use crate::{interrupt, rcc, Peripheral}; pub const VDDA_CALIB_MV: u32 = 3300; pub const VREF_INT: u32 = 1230; @@ -30,25 +32,30 @@ impl interrupt::typelevel::Handler for InterruptHandl } } +#[cfg(not(adc_l0))] pub struct Vbat; -impl AdcPin for Vbat {} -impl super::sealed::AdcPin for Vbat { + +#[cfg(not(adc_l0))] +impl AdcChannel for Vbat {} + +#[cfg(not(adc_l0))] +impl super::SealedAdcChannel for Vbat { fn channel(&self) -> u8 { 18 } } pub struct Vref; -impl AdcPin for Vref {} -impl super::sealed::AdcPin for Vref { +impl AdcChannel for Vref {} +impl super::SealedAdcChannel for Vref { fn channel(&self) -> u8 { 17 } } pub struct Temperature; -impl AdcPin for Temperature {} -impl super::sealed::AdcPin for Temperature { +impl AdcChannel for Temperature {} +impl super::SealedAdcChannel for Temperature { fn channel(&self) -> u8 { 16 } @@ -58,20 +65,28 @@ impl<'d, T: Instance> Adc<'d, T> { pub fn new( adc: impl Peripheral

+ 'd, _irq: impl interrupt::typelevel::Binding> + 'd, - delay: &mut impl DelayUs, ) -> Self { into_ref!(adc); - T::enable_and_reset(); + rcc::enable_and_reset::(); // Delay 1μs when using HSI14 as the ADC clock. // // Table 57. ADC characteristics // tstab = 14 * 1/fadc - delay.delay_us(1); + blocking_delay_us(1); + + // set default PCKL/2 on L0s because HSI is disabled in the default clock config + #[cfg(adc_l0)] + T::regs().cfgr2().modify(|reg| reg.set_ckmode(Ckmode::PCLK_DIV2)); // A.7.1 ADC calibration code example T::regs().cfgr1().modify(|reg| reg.set_dmaen(false)); T::regs().cr().modify(|reg| reg.set_adcal(true)); + + #[cfg(adc_l0)] + while !T::regs().isr().read().eocal() {} + + #[cfg(not(adc_l0))] while T::regs().cr().read().adcal() {} // A.7.2 ADC enable sequence code example @@ -93,11 +108,12 @@ impl<'d, T: Instance> Adc<'d, T> { Self { adc, - sample_time: Default::default(), + sample_time: SampleTime::from_bits(0), } } - pub fn enable_vbat(&self, _delay: &mut impl DelayUs) -> Vbat { + #[cfg(not(adc_l0))] + pub fn enable_vbat(&self) -> Vbat { // SMP must be ≥ 56 ADC clock cycles when using HSI14. // // 6.3.20 Vbat monitoring characteristics @@ -106,22 +122,22 @@ impl<'d, T: Instance> Adc<'d, T> { Vbat } - pub fn enable_vref(&self, delay: &mut impl DelayUs) -> Vref { + pub fn enable_vref(&self) -> Vref { // Table 28. Embedded internal reference voltage // tstart = 10μs T::regs().ccr().modify(|reg| reg.set_vrefen(true)); - delay.delay_us(10); + blocking_delay_us(10); Vref } - pub fn enable_temperature(&self, delay: &mut impl DelayUs) -> Temperature { + pub fn enable_temperature(&self) -> Temperature { // SMP must be ≥ 56 ADC clock cycles when using HSI14. // // 6.3.19 Temperature sensor characteristics // tstart ≤ 10μs // ts_temp ≥ 4μs T::regs().ccr().modify(|reg| reg.set_tsen(true)); - delay.delay_us(10); + blocking_delay_us(10); Temperature } @@ -133,12 +149,18 @@ impl<'d, T: Instance> Adc<'d, T> { T::regs().cfgr1().modify(|reg| reg.set_res(resolution.into())); } - pub async fn read(&mut self, pin: &mut impl AdcPin) -> u16 { - let channel = pin.channel(); - pin.set_as_analog(); + #[cfg(adc_l0)] + pub fn set_ckmode(&mut self, ckmode: Ckmode) { + // set ADC clock mode + T::regs().cfgr2().modify(|reg| reg.set_ckmode(ckmode)); + } + + pub async fn read(&mut self, channel: &mut impl AdcChannel) -> u16 { + let ch_num = channel.channel(); + channel.setup(); // A.7.5 Single conversion sequence code example - Software trigger - T::regs().chselr().write(|reg| reg.set_chselx(channel as usize, true)); + T::regs().chselr().write(|reg| reg.set_chselx(ch_num as usize, true)); self.convert().await } @@ -177,6 +199,6 @@ impl<'d, T: Instance> Drop for Adc<'d, T> { T::regs().cr().modify(|reg| reg.set_addis(true)); while T::regs().cr().read().aden() {} - T::disable(); + rcc::disable::(); } } diff --git a/embassy-stm32/src/adc/v2.rs b/embassy-stm32/src/adc/v2.rs index b37ac5a5d..842a5ee6d 100644 --- a/embassy-stm32/src/adc/v2.rs +++ b/embassy-stm32/src/adc/v2.rs @@ -1,22 +1,22 @@ use embassy_hal_internal::into_ref; -use embedded_hal_02::blocking::delay::DelayUs; -use crate::adc::{Adc, AdcPin, Instance, Resolution, SampleTime}; +use super::blocking_delay_us; +use crate::adc::{Adc, AdcChannel, Instance, Resolution, SampleTime}; use crate::peripherals::ADC1; use crate::time::Hertz; -use crate::Peripheral; +use crate::{rcc, Peripheral}; + +mod ringbuffered_v2; +pub use ringbuffered_v2::{RingBufferedAdc, Sequence}; /// Default VREF voltage used for sample conversion to millivolts. pub const VREF_DEFAULT_MV: u32 = 3300; /// VREF voltage used for factory calibration of VREFINTCAL register. pub const VREF_CALIB_MV: u32 = 3300; -/// ADC turn-on time -pub const ADC_POWERUP_TIME_US: u32 = 3; - pub struct VrefInt; -impl AdcPin for VrefInt {} -impl super::sealed::AdcPin for VrefInt { +impl AdcChannel for VrefInt {} +impl super::SealedAdcChannel for VrefInt { fn channel(&self) -> u8 { 17 } @@ -30,11 +30,11 @@ impl VrefInt { } pub struct Temperature; -impl AdcPin for Temperature {} -impl super::sealed::AdcPin for Temperature { +impl AdcChannel for Temperature {} +impl super::SealedAdcChannel for Temperature { fn channel(&self) -> u8 { cfg_if::cfg_if! { - if #[cfg(any(stm32f2, stm32f40, stm32f41))] { + if #[cfg(any(stm32f2, stm32f40x, stm32f41x))] { 16 } else { 18 @@ -51,8 +51,8 @@ impl Temperature { } pub struct Vbat; -impl AdcPin for Vbat {} -impl super::sealed::AdcPin for Vbat { +impl AdcChannel for Vbat {} +impl super::SealedAdcChannel for Vbat { fn channel(&self) -> u8 { 18 } @@ -97,9 +97,9 @@ impl<'d, T> Adc<'d, T> where T: Instance, { - pub fn new(adc: impl Peripheral

+ 'd, delay: &mut impl DelayUs) -> Self { + pub fn new(adc: impl Peripheral

+ 'd) -> Self { into_ref!(adc); - T::enable_and_reset(); + rcc::enable_and_reset::(); let presc = Prescaler::from_pclk2(T::frequency()); T::common_regs().ccr().modify(|w| w.set_adcpre(presc.adcpre())); @@ -107,11 +107,11 @@ where reg.set_adon(true); }); - delay.delay_us(ADC_POWERUP_TIME_US); + blocking_delay_us(3); Self { adc, - sample_time: Default::default(), + sample_time: SampleTime::from_bits(0), } } @@ -178,11 +178,11 @@ where T::regs().dr().read().0 as u16 } - pub fn read(&mut self, pin: &mut impl AdcPin) -> u16 { - pin.set_as_analog(); + pub fn blocking_read(&mut self, channel: &mut impl AdcChannel) -> u16 { + channel.setup(); // Configure ADC - let channel = pin.channel(); + let channel = channel.channel(); // Select channel T::regs().sqr3().write(|reg| reg.set_sq(0, channel)); @@ -209,6 +209,6 @@ impl<'d, T: Instance> Drop for Adc<'d, T> { reg.set_adon(false); }); - T::disable(); + rcc::disable::(); } } diff --git a/embassy-stm32/src/adc/v3.rs b/embassy-stm32/src/adc/v3.rs index 281a99f72..9441e42ff 100644 --- a/embassy-stm32/src/adc/v3.rs +++ b/embassy-stm32/src/adc/v3.rs @@ -1,8 +1,12 @@ +use cfg_if::cfg_if; use embassy_hal_internal::into_ref; -use embedded_hal_02::blocking::delay::DelayUs; +use pac::adc::vals::Dmacfg; -use crate::adc::{Adc, AdcPin, Instance, Resolution, SampleTime}; -use crate::Peripheral; +use super::{ + blocking_delay_us, Adc, AdcChannel, AnyAdcChannel, Instance, Resolution, RxDma, SampleTime, SealedAdcChannel, +}; +use crate::dma::Transfer; +use crate::{pac, rcc, Peripheral}; /// Default VREF voltage used for sample conversion to millivolts. pub const VREF_DEFAULT_MV: u32 = 3300; @@ -10,57 +14,103 @@ pub const VREF_DEFAULT_MV: u32 = 3300; pub const VREF_CALIB_MV: u32 = 3000; pub struct VrefInt; -impl AdcPin for VrefInt {} -impl super::sealed::AdcPin for VrefInt { +impl AdcChannel for VrefInt {} +impl SealedAdcChannel for VrefInt { fn channel(&self) -> u8 { - #[cfg(not(adc_g0))] - let val = 0; - #[cfg(adc_g0)] - let val = 13; + cfg_if! { + if #[cfg(adc_g0)] { + let val = 13; + } else if #[cfg(adc_h5)] { + let val = 17; + } else if #[cfg(adc_u0)] { + let val = 12; + } else { + let val = 0; + } + } val } } pub struct Temperature; -impl AdcPin for Temperature {} -impl super::sealed::AdcPin for Temperature { +impl AdcChannel for Temperature {} +impl SealedAdcChannel for Temperature { fn channel(&self) -> u8 { - #[cfg(not(adc_g0))] - let val = 17; - #[cfg(adc_g0)] - let val = 12; + cfg_if! { + if #[cfg(adc_g0)] { + let val = 12; + } else if #[cfg(adc_h5)] { + let val = 16; + } else if #[cfg(adc_u0)] { + let val = 11; + } else { + let val = 17; + } + } val } } pub struct Vbat; -impl AdcPin for Vbat {} -impl super::sealed::AdcPin for Vbat { +impl AdcChannel for Vbat {} +impl SealedAdcChannel for Vbat { fn channel(&self) -> u8 { - #[cfg(not(adc_g0))] - let val = 18; - #[cfg(adc_g0)] - let val = 14; + cfg_if! { + if #[cfg(adc_g0)] { + let val = 14; + } else if #[cfg(adc_h5)] { + let val = 2; + } else if #[cfg(adc_h5)] { + let val = 13; + } else { + let val = 18; + } + } val } } +cfg_if! { + if #[cfg(adc_h5)] { + pub struct VddCore; + impl AdcChannel for VddCore {} + impl super::SealedAdcChannel for VddCore { + fn channel(&self) -> u8 { + 6 + } + } + } +} + +cfg_if! { + if #[cfg(adc_u0)] { + pub struct DacOut; + impl AdcChannel for DacOut {} + impl super::SealedAdcChannel for DacOut { + fn channel(&self) -> u8 { + 19 + } + } + } +} + impl<'d, T: Instance> Adc<'d, T> { - pub fn new(adc: impl Peripheral

+ 'd, delay: &mut impl DelayUs) -> Self { + pub fn new(adc: impl Peripheral

+ 'd) -> Self { into_ref!(adc); - T::enable_and_reset(); + rcc::enable_and_reset::(); T::regs().cr().modify(|reg| { - #[cfg(not(adc_g0))] + #[cfg(not(any(adc_g0, adc_u0)))] reg.set_deeppwd(false); reg.set_advregen(true); }); - #[cfg(adc_g0)] + // If this is false then each ADC_CHSELR bit enables an input channel. + #[cfg(any(adc_g0, adc_u0))] T::regs().cfgr1().modify(|reg| { reg.set_chselrmod(false); }); - delay.delay_us(20); + blocking_delay_us(20); T::regs().cr().modify(|reg| { reg.set_adcal(true); @@ -70,67 +120,108 @@ impl<'d, T: Instance> Adc<'d, T> { // spin } - delay.delay_us(1); + blocking_delay_us(1); Self { adc, - sample_time: Default::default(), + sample_time: SampleTime::from_bits(0), } } - pub fn enable_vrefint(&self, delay: &mut impl DelayUs) -> VrefInt { - #[cfg(not(adc_g0))] + // Enable ADC only when it is not already running. + fn enable(&mut self) { + // Make sure bits are off + while T::regs().cr().read().addis() { + // spin + } + + if !T::regs().cr().read().aden() { + // Enable ADC + T::regs().isr().modify(|reg| { + reg.set_adrdy(true); + }); + T::regs().cr().modify(|reg| { + reg.set_aden(true); + }); + + while !T::regs().isr().read().adrdy() { + // spin + } + } + } + + pub fn enable_vrefint(&self) -> VrefInt { + #[cfg(not(any(adc_g0, adc_u0)))] T::common_regs().ccr().modify(|reg| { reg.set_vrefen(true); }); - #[cfg(adc_g0)] + #[cfg(any(adc_g0, adc_u0))] T::regs().ccr().modify(|reg| { reg.set_vrefen(true); }); // "Table 24. Embedded internal voltage reference" states that it takes a maximum of 12 us - // to stabilize the internal voltage reference, we wait a little more. - // TODO: delay 15us - //cortex_m::asm::delay(20_000_000); - delay.delay_us(15); + // to stabilize the internal voltage reference. + blocking_delay_us(15); VrefInt {} } pub fn enable_temperature(&self) -> Temperature { - #[cfg(not(adc_g0))] - T::common_regs().ccr().modify(|reg| { - reg.set_ch17sel(true); - }); - #[cfg(adc_g0)] - T::regs().ccr().modify(|reg| { - reg.set_tsen(true); - }); + cfg_if! { + if #[cfg(any(adc_g0, adc_u0))] { + T::regs().ccr().modify(|reg| { + reg.set_tsen(true); + }); + } else if #[cfg(adc_h5)] { + T::common_regs().ccr().modify(|reg| { + reg.set_tsen(true); + }); + } else { + T::common_regs().ccr().modify(|reg| { + reg.set_ch17sel(true); + }); + } + } Temperature {} } pub fn enable_vbat(&self) -> Vbat { - #[cfg(not(adc_g0))] - T::common_regs().ccr().modify(|reg| { - reg.set_ch18sel(true); - }); - #[cfg(adc_g0)] - T::regs().ccr().modify(|reg| { - reg.set_vbaten(true); - }); + cfg_if! { + if #[cfg(any(adc_g0, adc_u0))] { + T::regs().ccr().modify(|reg| { + reg.set_vbaten(true); + }); + } else if #[cfg(adc_h5)] { + T::common_regs().ccr().modify(|reg| { + reg.set_vbaten(true); + }); + } else { + T::common_regs().ccr().modify(|reg| { + reg.set_ch18sel(true); + }); + } + } Vbat {} } + /// Set the ADC sample time. pub fn set_sample_time(&mut self, sample_time: SampleTime) { self.sample_time = sample_time; } + /// Get the ADC sample time. + pub fn sample_time(&self) -> SampleTime { + self.sample_time + } + + /// Set the ADC resolution. pub fn set_resolution(&mut self, resolution: Resolution) { - #[cfg(not(adc_g0))] + #[cfg(not(any(adc_g0, adc_u0)))] T::regs().cfgr().modify(|reg| reg.set_res(resolution.into())); - #[cfg(adc_g0)] + #[cfg(any(adc_g0, adc_u0))] T::regs().cfgr1().modify(|reg| reg.set_res(resolution.into())); } @@ -162,32 +253,184 @@ impl<'d, T: Instance> Adc<'d, T> { T::regs().dr().read().0 as u16 } - pub fn read(&mut self, pin: &mut impl AdcPin) -> u16 { - // Make sure bits are off - while T::regs().cr().read().addis() { - // spin + /// Read an ADC channel. + pub fn blocking_read(&mut self, channel: &mut impl AdcChannel) -> u16 { + self.read_channel(channel) + } + + /// Read one or multiple ADC channels using DMA. + /// + /// `sequence` iterator and `readings` must have the same length. + /// + /// Example + /// ```rust,ignore + /// use embassy_stm32::adc::{Adc, AdcChannel} + /// + /// let mut adc = Adc::new(p.ADC1); + /// let mut adc_pin0 = p.PA0.degrade_adc(); + /// let mut adc_pin1 = p.PA1.degrade_adc(); + /// let mut measurements = [0u16; 2]; + /// + /// adc.read_async( + /// p.DMA1_CH2, + /// [ + /// (&mut *adc_pin0, SampleTime::CYCLES160_5), + /// (&mut *adc_pin1, SampleTime::CYCLES160_5), + /// ] + /// .into_iter(), + /// &mut measurements, + /// ) + /// .await; + /// defmt::info!("measurements: {}", measurements); + /// ``` + pub async fn read( + &mut self, + rx_dma: &mut impl RxDma, + sequence: impl ExactSizeIterator, SampleTime)>, + readings: &mut [u16], + ) { + assert!(sequence.len() != 0, "Asynchronous read sequence cannot be empty"); + assert!( + sequence.len() == readings.len(), + "Sequence length must be equal to readings length" + ); + assert!( + sequence.len() <= 16, + "Asynchronous read sequence cannot be more than 16 in length" + ); + + // Ensure no conversions are ongoing and ADC is enabled. + Self::cancel_conversions(); + self.enable(); + + // Set sequence length + #[cfg(not(any(adc_g0, adc_u0)))] + T::regs().sqr1().modify(|w| { + w.set_l(sequence.len() as u8 - 1); + }); + + #[cfg(any(adc_g0, adc_u0))] + let mut channel_mask = 0; + + // Configure channels and ranks + for (_i, (channel, sample_time)) in sequence.enumerate() { + Self::configure_channel(channel, sample_time); + + // Each channel is sampled according to sequence + #[cfg(not(any(adc_g0, adc_u0)))] + match _i { + 0..=3 => { + T::regs().sqr1().modify(|w| { + w.set_sq(_i, channel.channel()); + }); + } + 4..=8 => { + T::regs().sqr2().modify(|w| { + w.set_sq(_i - 4, channel.channel()); + }); + } + 9..=13 => { + T::regs().sqr3().modify(|w| { + w.set_sq(_i - 9, channel.channel()); + }); + } + 14..=15 => { + T::regs().sqr4().modify(|w| { + w.set_sq(_i - 14, channel.channel()); + }); + } + _ => unreachable!(), + } + + #[cfg(any(adc_g0, adc_u0))] + { + channel_mask |= 1 << channel.channel(); + } } - // Enable ADC - T::regs().isr().modify(|reg| { - reg.set_adrdy(true); - }); - T::regs().cr().modify(|reg| { - reg.set_aden(true); + // On G0 and U0 enabled channels are sampled from 0 to last channel. + // It is possible to add up to 8 sequences if CHSELRMOD = 1. + // However for supporting more than 8 channels alternative CHSELRMOD = 0 approach is used. + #[cfg(any(adc_g0, adc_u0))] + T::regs().chselr().modify(|reg| { + reg.set_chsel(channel_mask); }); - while !T::regs().isr().read().adrdy() { - // spin + // Set continuous mode with oneshot dma. + // Clear overrun flag before starting transfer. + T::regs().isr().modify(|reg| { + reg.set_ovr(true); + }); + + #[cfg(not(any(adc_g0, adc_u0)))] + T::regs().cfgr().modify(|reg| { + reg.set_discen(false); + reg.set_cont(true); + reg.set_dmacfg(Dmacfg::ONESHOT); + reg.set_dmaen(true); + }); + #[cfg(any(adc_g0, adc_u0))] + T::regs().cfgr1().modify(|reg| { + reg.set_discen(false); + reg.set_cont(true); + reg.set_dmacfg(Dmacfg::ONESHOT); + reg.set_dmaen(true); + }); + + let request = rx_dma.request(); + let transfer = unsafe { + Transfer::new_read( + rx_dma, + request, + T::regs().dr().as_ptr() as *mut u16, + readings, + Default::default(), + ) + }; + + // Start conversion + T::regs().cr().modify(|reg| { + reg.set_adstart(true); + }); + + // Wait for conversion sequence to finish. + transfer.await; + + // Ensure conversions are finished. + Self::cancel_conversions(); + + // Reset configuration. + #[cfg(not(any(adc_g0, adc_u0)))] + T::regs().cfgr().modify(|reg| { + reg.set_cont(false); + }); + #[cfg(any(adc_g0, adc_u0))] + T::regs().cfgr1().modify(|reg| { + reg.set_cont(false); + }); + } + + fn configure_channel(channel: &mut impl AdcChannel, sample_time: SampleTime) { + // RM0492, RM0481, etc. + // "This option bit must be set to 1 when ADCx_INP0 or ADCx_INN1 channel is selected." + #[cfg(adc_h5)] + if channel.channel() == 0 { + T::regs().or().modify(|reg| reg.set_op0(true)); } // Configure channel - Self::set_channel_sample_time(pin.channel(), self.sample_time); + Self::set_channel_sample_time(channel.channel(), sample_time); + } + + fn read_channel(&mut self, channel: &mut impl AdcChannel) -> u16 { + self.enable(); + Self::configure_channel(channel, self.sample_time); // Select channel - #[cfg(not(adc_g0))] - T::regs().sqr1().write(|reg| reg.set_sq(0, pin.channel())); - #[cfg(adc_g0)] - T::regs().chselr().write(|reg| reg.set_chsel(1 << pin.channel())); + #[cfg(not(any(adc_g0, adc_u0)))] + T::regs().sqr1().write(|reg| reg.set_sq(0, channel.channel())); + #[cfg(any(adc_g0, adc_u0))] + T::regs().chselr().write(|reg| reg.set_chsel(1 << channel.channel())); // Some models are affected by an erratum: // If we perform conversions slower than 1 kHz, the first read ADC value can be @@ -197,24 +440,60 @@ impl<'d, T: Instance> Adc<'d, T> { // STM32G4: Section 2.7.3 #[cfg(any(rcc_l4, rcc_g4))] let _ = self.convert(); - let val = self.convert(); T::regs().cr().modify(|reg| reg.set_addis(true)); + // RM0492, RM0481, etc. + // "This option bit must be set to 1 when ADCx_INP0 or ADCx_INN1 channel is selected." + #[cfg(adc_h5)] + if channel.channel() == 0 { + T::regs().or().modify(|reg| reg.set_op0(false)); + } + val } - #[cfg(adc_g0)] - fn set_channel_sample_time(_ch: u8, sample_time: SampleTime) { - T::regs().smpr().modify(|reg| reg.set_smp1(sample_time.into())); + #[cfg(any(adc_g0, adc_u0))] + pub fn set_oversampling_shift(&mut self, shift: u8) { + T::regs().cfgr2().modify(|reg| reg.set_ovss(shift)); } - #[cfg(not(adc_g0))] - fn set_channel_sample_time(ch: u8, sample_time: SampleTime) { - let sample_time = sample_time.into(); - T::regs() - .smpr(ch as usize / 10) - .modify(|reg| reg.set_smp(ch as usize % 10, sample_time)); + #[cfg(any(adc_g0, adc_u0))] + pub fn set_oversampling_ratio(&mut self, ratio: u8) { + T::regs().cfgr2().modify(|reg| reg.set_ovsr(ratio)); + } + + #[cfg(any(adc_g0, adc_u0))] + pub fn oversampling_enable(&mut self, enable: bool) { + T::regs().cfgr2().modify(|reg| reg.set_ovse(enable)); + } + + fn set_channel_sample_time(_ch: u8, sample_time: SampleTime) { + cfg_if! { + if #[cfg(any(adc_g0, adc_u0))] { + // On G0 and U6 all channels use the same sampling time. + T::regs().smpr().modify(|reg| reg.set_smp1(sample_time.into())); + } else if #[cfg(adc_h5)] { + match _ch { + 0..=9 => T::regs().smpr1().modify(|w| w.set_smp(_ch as usize % 10, sample_time.into())), + _ => T::regs().smpr2().modify(|w| w.set_smp(_ch as usize % 10, sample_time.into())), + } + } else { + let sample_time = sample_time.into(); + T::regs() + .smpr(_ch as usize / 10) + .modify(|reg| reg.set_smp(_ch as usize % 10, sample_time)); + } + } + } + + fn cancel_conversions() { + if T::regs().cr().read().adstart() && !T::regs().cr().read().addis() { + T::regs().cr().modify(|reg| { + reg.set_adstp(true); + }); + while T::regs().cr().read().adstart() {} + } } } diff --git a/embassy-stm32/src/adc/v4.rs b/embassy-stm32/src/adc/v4.rs index 048e73184..63b5b58ea 100644 --- a/embassy-stm32/src/adc/v4.rs +++ b/embassy-stm32/src/adc/v4.rs @@ -1,11 +1,13 @@ -use embedded_hal_02::blocking::delay::DelayUs; #[allow(unused)] -use pac::adc::vals::{Adcaldif, Boost, Difsel, Exten, Pcsel}; +use pac::adc::vals::{Adcaldif, Adstp, Boost, Difsel, Dmngt, Exten, Pcsel}; use pac::adccommon::vals::Presc; -use super::{Adc, AdcPin, Instance, InternalChannel, Resolution, SampleTime}; +use super::{ + blocking_delay_us, Adc, AdcChannel, AnyAdcChannel, Instance, Resolution, RxDma, SampleTime, SealedAdcChannel, +}; +use crate::dma::Transfer; use crate::time::Hertz; -use crate::{pac, Peripheral}; +use crate::{pac, rcc, Peripheral}; /// Default VREF voltage used for sample conversion to millivolts. pub const VREF_DEFAULT_MV: u32 = 3300; @@ -34,8 +36,8 @@ const VBAT_CHANNEL: u8 = 17; // NOTE: Vrefint/Temperature/Vbat are not available on all ADCs, this currently cannot be modeled with stm32-data, so these are available from the software on all ADCs /// Internal voltage reference channel. pub struct VrefInt; -impl InternalChannel for VrefInt {} -impl super::sealed::InternalChannel for VrefInt { +impl AdcChannel for VrefInt {} +impl SealedAdcChannel for VrefInt { fn channel(&self) -> u8 { VREF_CHANNEL } @@ -43,8 +45,8 @@ impl super::sealed::InternalChannel for VrefInt { /// Internal temperature channel. pub struct Temperature; -impl InternalChannel for Temperature {} -impl super::sealed::InternalChannel for Temperature { +impl AdcChannel for Temperature {} +impl SealedAdcChannel for Temperature { fn channel(&self) -> u8 { TEMP_CHANNEL } @@ -52,8 +54,8 @@ impl super::sealed::InternalChannel for Temperature { /// Internal battery voltage channel. pub struct Vbat; -impl InternalChannel for Vbat {} -impl super::sealed::InternalChannel for Vbat { +impl AdcChannel for Vbat {} +impl SealedAdcChannel for Vbat { fn channel(&self) -> u8 { VBAT_CHANNEL } @@ -127,11 +129,26 @@ impl Prescaler { } } +/// Number of samples used for averaging. +pub enum Averaging { + Disabled, + Samples2, + Samples4, + Samples8, + Samples16, + Samples32, + Samples64, + Samples128, + Samples256, + Samples512, + Samples1024, +} + impl<'d, T: Instance> Adc<'d, T> { /// Create a new ADC driver. - pub fn new(adc: impl Peripheral

+ 'd, delay: &mut impl DelayUs) -> Self { + pub fn new(adc: impl Peripheral

+ 'd) -> Self { embassy_hal_internal::into_ref!(adc); - T::enable_and_reset(); + rcc::enable_and_reset::(); let prescaler = Prescaler::from_ker_ck(T::frequency()); @@ -159,13 +176,13 @@ impl<'d, T: Instance> Adc<'d, T> { } let mut s = Self { adc, - sample_time: Default::default(), + sample_time: SampleTime::from_bits(0), }; - s.power_up(delay); + s.power_up(); s.configure_differential_inputs(); s.calibrate(); - delay.delay_us(1); + blocking_delay_us(1); s.enable(); s.configure(); @@ -173,13 +190,13 @@ impl<'d, T: Instance> Adc<'d, T> { s } - fn power_up(&mut self, delay: &mut impl DelayUs) { + fn power_up(&mut self) { T::regs().cr().modify(|reg| { reg.set_deeppwd(false); reg.set_advregen(true); }); - delay.delay_us(10); + blocking_delay_us(10); } fn configure_differential_inputs(&mut self) { @@ -248,11 +265,39 @@ impl<'d, T: Instance> Adc<'d, T> { self.sample_time = sample_time; } + /// Get the ADC sample time. + pub fn sample_time(&self) -> SampleTime { + self.sample_time + } + /// Set the ADC resolution. pub fn set_resolution(&mut self, resolution: Resolution) { T::regs().cfgr().modify(|reg| reg.set_res(resolution.into())); } + /// Set hardware averaging. + pub fn set_averaging(&mut self, averaging: Averaging) { + let (enable, samples, right_shift) = match averaging { + Averaging::Disabled => (false, 0, 0), + Averaging::Samples2 => (true, 1, 1), + Averaging::Samples4 => (true, 3, 2), + Averaging::Samples8 => (true, 7, 3), + Averaging::Samples16 => (true, 15, 4), + Averaging::Samples32 => (true, 31, 5), + Averaging::Samples64 => (true, 63, 6), + Averaging::Samples128 => (true, 127, 7), + Averaging::Samples256 => (true, 255, 8), + Averaging::Samples512 => (true, 511, 9), + Averaging::Samples1024 => (true, 1023, 10), + }; + + T::regs().cfgr2().modify(|reg| { + reg.set_rovse(enable); + reg.set_osvr(samples); + reg.set_ovss(right_shift); + }) + } + /// Perform a single conversion. fn convert(&mut self) -> u16 { T::regs().isr().modify(|reg| { @@ -272,36 +317,149 @@ impl<'d, T: Instance> Adc<'d, T> { T::regs().dr().read().0 as u16 } - /// Read an ADC pin. - pub fn read

(&mut self, pin: &mut P) -> u16 - where - P: AdcPin, - P: crate::gpio::sealed::Pin, - { - pin.set_as_analog(); - - self.read_channel(pin.channel()) + /// Read an ADC channel. + pub fn blocking_read(&mut self, channel: &mut impl AdcChannel) -> u16 { + self.read_channel(channel) } - /// Read an ADC internal channel. - pub fn read_internal(&mut self, channel: &mut impl InternalChannel) -> u16 { - self.read_channel(channel.channel()) + /// Read one or multiple ADC channels using DMA. + /// + /// `sequence` iterator and `readings` must have the same length. + /// + /// Example + /// ```rust,ignore + /// use embassy_stm32::adc::{Adc, AdcChannel} + /// + /// let mut adc = Adc::new(p.ADC1); + /// let mut adc_pin0 = p.PA0.degrade_adc(); + /// let mut adc_pin2 = p.PA2.degrade_adc(); + /// let mut measurements = [0u16; 2]; + /// + /// adc.read_async( + /// p.DMA2_CH0, + /// [ + /// (&mut *adc_pin0, SampleTime::CYCLES112), + /// (&mut *adc_pin2, SampleTime::CYCLES112), + /// ] + /// .into_iter(), + /// &mut measurements, + /// ) + /// .await; + /// defmt::info!("measurements: {}", measurements); + /// ``` + pub async fn read( + &mut self, + rx_dma: &mut impl RxDma, + sequence: impl ExactSizeIterator, SampleTime)>, + readings: &mut [u16], + ) { + assert!(sequence.len() != 0, "Asynchronous read sequence cannot be empty"); + assert!( + sequence.len() == readings.len(), + "Sequence length must be equal to readings length" + ); + assert!( + sequence.len() <= 16, + "Asynchronous read sequence cannot be more than 16 in length" + ); + + // Ensure no conversions are ongoing + Self::cancel_conversions(); + + // Set sequence length + T::regs().sqr1().modify(|w| { + w.set_l(sequence.len() as u8 - 1); + }); + + // Configure channels and ranks + for (i, (channel, sample_time)) in sequence.enumerate() { + Self::configure_channel(channel, sample_time); + match i { + 0..=3 => { + T::regs().sqr1().modify(|w| { + w.set_sq(i, channel.channel()); + }); + } + 4..=8 => { + T::regs().sqr2().modify(|w| { + w.set_sq(i - 4, channel.channel()); + }); + } + 9..=13 => { + T::regs().sqr3().modify(|w| { + w.set_sq(i - 9, channel.channel()); + }); + } + 14..=15 => { + T::regs().sqr4().modify(|w| { + w.set_sq(i - 14, channel.channel()); + }); + } + _ => unreachable!(), + } + } + + // Set continuous mode with oneshot dma. + // Clear overrun flag before starting transfer. + + T::regs().isr().modify(|reg| { + reg.set_ovr(true); + }); + T::regs().cfgr().modify(|reg| { + reg.set_cont(true); + reg.set_dmngt(Dmngt::DMA_ONESHOT); + }); + + let request = rx_dma.request(); + let transfer = unsafe { + Transfer::new_read( + rx_dma, + request, + T::regs().dr().as_ptr() as *mut u16, + readings, + Default::default(), + ) + }; + + // Start conversion + T::regs().cr().modify(|reg| { + reg.set_adstart(true); + }); + + // Wait for conversion sequence to finish. + transfer.await; + + // Ensure conversions are finished. + Self::cancel_conversions(); + + // Reset configuration. + T::regs().cfgr().modify(|reg| { + reg.set_cont(false); + reg.set_dmngt(Dmngt::from_bits(0)); + }); } - fn read_channel(&mut self, channel: u8) -> u16 { - // Configure channel - Self::set_channel_sample_time(channel, self.sample_time); + fn configure_channel(channel: &mut impl AdcChannel, sample_time: SampleTime) { + channel.setup(); + + let channel = channel.channel(); + + Self::set_channel_sample_time(channel, sample_time); #[cfg(stm32h7)] { T::regs().cfgr2().modify(|w| w.set_lshift(0)); T::regs() .pcsel() - .write(|w| w.set_pcsel(channel as _, Pcsel::PRESELECTED)); + .modify(|w| w.set_pcsel(channel as _, Pcsel::PRESELECTED)); } + } - T::regs().sqr1().write(|reg| { - reg.set_sq(0, channel); + fn read_channel(&mut self, channel: &mut impl AdcChannel) -> u16 { + Self::configure_channel(channel, self.sample_time); + + T::regs().sqr1().modify(|reg| { + reg.set_sq(0, channel.channel()); reg.set_l(0); }); @@ -316,4 +474,13 @@ impl<'d, T: Instance> Adc<'d, T> { T::regs().smpr(1).modify(|reg| reg.set_smp((ch - 10) as _, sample_time)); } } + + fn cancel_conversions() { + if T::regs().cr().read().adstart() && !T::regs().cr().read().addis() { + T::regs().cr().modify(|reg| { + reg.set_adstp(Adstp::STOP); + }); + while T::regs().cr().read().adstart() {} + } + } } diff --git a/embassy-stm32/src/can/bxcan.rs b/embassy-stm32/src/can/bxcan.rs deleted file mode 100644 index 7e00eca6f..000000000 --- a/embassy-stm32/src/can/bxcan.rs +++ /dev/null @@ -1,637 +0,0 @@ -use core::convert::AsMut; -use core::future::poll_fn; -use core::marker::PhantomData; -use core::ops::{Deref, DerefMut}; -use core::task::Poll; - -pub use bxcan; -use bxcan::{Data, ExtendedId, Frame, Id, StandardId}; -use embassy_hal_internal::{into_ref, PeripheralRef}; -use futures::FutureExt; - -use crate::gpio::sealed::AFType; -use crate::interrupt::typelevel::Interrupt; -use crate::pac::can::vals::{Ide, Lec}; -use crate::rcc::RccPeripheral; -use crate::{interrupt, peripherals, Peripheral}; - -pub mod enums; -use enums::*; -pub mod util; - -/// Contains CAN frame and additional metadata. -/// -/// Timestamp is available if `time` feature is enabled. -#[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub struct Envelope { - /// Reception time. - #[cfg(feature = "time")] - pub ts: embassy_time::Instant, - /// The actual CAN frame. - pub frame: bxcan::Frame, -} - -/// Interrupt handler. -pub struct TxInterruptHandler { - _phantom: PhantomData, -} - -impl interrupt::typelevel::Handler for TxInterruptHandler { - unsafe fn on_interrupt() { - T::regs().tsr().write(|v| { - v.set_rqcp(0, true); - v.set_rqcp(1, true); - v.set_rqcp(2, true); - }); - - T::state().tx_waker.wake(); - } -} - -/// RX0 interrupt handler. -pub struct Rx0InterruptHandler { - _phantom: PhantomData, -} - -impl interrupt::typelevel::Handler for Rx0InterruptHandler { - unsafe fn on_interrupt() { - // info!("rx0 irq"); - Can::::receive_fifo(RxFifo::Fifo0); - } -} - -/// RX1 interrupt handler. -pub struct Rx1InterruptHandler { - _phantom: PhantomData, -} - -impl interrupt::typelevel::Handler for Rx1InterruptHandler { - unsafe fn on_interrupt() { - // info!("rx1 irq"); - Can::::receive_fifo(RxFifo::Fifo1); - } -} - -/// SCE interrupt handler. -pub struct SceInterruptHandler { - _phantom: PhantomData, -} - -impl interrupt::typelevel::Handler for SceInterruptHandler { - unsafe fn on_interrupt() { - // info!("sce irq"); - let msr = T::regs().msr(); - let msr_val = msr.read(); - - if msr_val.erri() { - msr.modify(|v| v.set_erri(true)); - T::state().err_waker.wake(); - } - } -} - -/// CAN driver -pub struct Can<'d, T: Instance> { - can: bxcan::Can>, -} - -/// Error returned by `try_read` -#[derive(Debug)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub enum TryReadError { - /// Bus error - BusError(BusError), - /// Receive buffer is empty - Empty, -} - -/// Error returned by `try_write` -#[derive(Debug)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub enum TryWriteError { - /// All transmit mailboxes are full - Full, -} - -impl<'d, T: Instance> Can<'d, T> { - /// Creates a new Bxcan instance, keeping the peripheral in sleep mode. - /// You must call [Can::enable_non_blocking] to use the peripheral. - pub fn new( - peri: impl Peripheral

+ 'd, - rx: impl Peripheral

> + 'd, - tx: impl Peripheral

> + 'd, - _irqs: impl interrupt::typelevel::Binding> - + interrupt::typelevel::Binding> - + interrupt::typelevel::Binding> - + interrupt::typelevel::Binding> - + 'd, - ) -> Self { - into_ref!(peri, rx, tx); - - rx.set_as_af(rx.af_num(), AFType::Input); - tx.set_as_af(tx.af_num(), AFType::OutputPushPull); - - T::enable_and_reset(); - - { - T::regs().ier().write(|w| { - w.set_errie(true); - w.set_fmpie(0, true); - w.set_fmpie(1, true); - w.set_tmeie(true); - }); - - T::regs().mcr().write(|w| { - // Enable timestamps on rx messages - - w.set_ttcm(true); - }); - } - - unsafe { - T::TXInterrupt::unpend(); - T::TXInterrupt::enable(); - - T::RX0Interrupt::unpend(); - T::RX0Interrupt::enable(); - - T::RX1Interrupt::unpend(); - T::RX1Interrupt::enable(); - - T::SCEInterrupt::unpend(); - T::SCEInterrupt::enable(); - } - - rx.set_as_af(rx.af_num(), AFType::Input); - tx.set_as_af(tx.af_num(), AFType::OutputPushPull); - - let can = bxcan::Can::builder(BxcanInstance(peri)).leave_disabled(); - Self { can } - } - - /// Set CAN bit rate. - pub fn set_bitrate(&mut self, bitrate: u32) { - let bit_timing = util::calc_can_timings(T::frequency(), bitrate).unwrap(); - let sjw = u8::from(bit_timing.sync_jump_width) as u32; - let seg1 = u8::from(bit_timing.seg1) as u32; - let seg2 = u8::from(bit_timing.seg2) as u32; - let prescaler = u16::from(bit_timing.prescaler) as u32; - self.can - .modify_config() - .set_bit_timing((sjw - 1) << 24 | (seg1 - 1) << 16 | (seg2 - 1) << 20 | (prescaler - 1)) - .leave_disabled(); - } - - /// Enables the peripheral and synchronizes with the bus. - /// - /// This will wait for 11 consecutive recessive bits (bus idle state). - /// Contrary to enable method from bxcan library, this will not freeze the executor while waiting. - pub async fn enable(&mut self) { - while self.enable_non_blocking().is_err() { - // SCE interrupt is only generated for entering sleep mode, but not leaving. - // Yield to allow other tasks to execute while can bus is initializing. - embassy_futures::yield_now().await; - } - } - - /// Queues the message to be sent. - /// - /// If the TX queue is full, this will wait until there is space, therefore exerting backpressure. - pub async fn write(&mut self, frame: &Frame) -> bxcan::TransmitStatus { - self.split().0.write(frame).await - } - - /// Attempts to transmit a frame without blocking. - /// - /// Returns [Err(TryWriteError::Full)] if all transmit mailboxes are full. - pub fn try_write(&mut self, frame: &Frame) -> Result { - self.split().0.try_write(frame) - } - - /// Waits for a specific transmit mailbox to become empty - pub async fn flush(&self, mb: bxcan::Mailbox) { - CanTx::::flush_inner(mb).await - } - - /// Waits until any of the transmit mailboxes become empty - pub async fn flush_any(&self) { - CanTx::::flush_any_inner().await - } - - /// Waits until all of the transmit mailboxes become empty - pub async fn flush_all(&self) { - CanTx::::flush_all_inner().await - } - - /// Read a CAN frame. - /// - /// If no CAN frame is in the RX buffer, this will wait until there is one. - /// - /// Returns a tuple of the time the message was received and the message frame - pub async fn read(&mut self) -> Result { - self.split().1.read().await - } - - /// Attempts to read a CAN frame without blocking. - /// - /// Returns [Err(TryReadError::Empty)] if there are no frames in the rx queue. - pub fn try_read(&mut self) -> Result { - self.split().1.try_read() - } - - /// Waits while receive queue is empty. - pub async fn wait_not_empty(&mut self) { - self.split().1.wait_not_empty().await - } - - unsafe fn receive_fifo(fifo: RxFifo) { - // Generate timestamp as early as possible - #[cfg(feature = "time")] - let ts = embassy_time::Instant::now(); - - let state = T::state(); - let regs = T::regs(); - let fifo_idx = match fifo { - RxFifo::Fifo0 => 0usize, - RxFifo::Fifo1 => 1usize, - }; - let rfr = regs.rfr(fifo_idx); - let fifo = regs.rx(fifo_idx); - - loop { - // If there are no pending messages, there is nothing to do - if rfr.read().fmp() == 0 { - return; - } - - let rir = fifo.rir().read(); - let id = if rir.ide() == Ide::STANDARD { - Id::from(StandardId::new_unchecked(rir.stid())) - } else { - let stid = (rir.stid() & 0x7FF) as u32; - let exid = rir.exid() & 0x3FFFF; - let id = (stid << 18) | (exid); - Id::from(ExtendedId::new_unchecked(id)) - }; - let data_len = fifo.rdtr().read().dlc() as usize; - let mut data: [u8; 8] = [0; 8]; - data[0..4].copy_from_slice(&fifo.rdlr().read().0.to_ne_bytes()); - data[4..8].copy_from_slice(&fifo.rdhr().read().0.to_ne_bytes()); - - let frame = Frame::new_data(id, Data::new(&data[0..data_len]).unwrap()); - let envelope = Envelope { - #[cfg(feature = "time")] - ts, - frame, - }; - - rfr.modify(|v| v.set_rfom(true)); - - /* - NOTE: consensus was reached that if rx_queue is full, packets should be dropped - */ - let _ = state.rx_queue.try_send(envelope); - } - } - - /// Split the CAN driver into transmit and receive halves. - /// - /// Useful for doing separate transmit/receive tasks. - pub fn split<'c>(&'c mut self) -> (CanTx<'c, 'd, T>, CanRx<'c, 'd, T>) { - let (tx, rx0, rx1) = self.can.split_by_ref(); - (CanTx { tx }, CanRx { rx0, rx1 }) - } -} - -impl<'d, T: Instance> AsMut>> for Can<'d, T> { - /// Get mutable access to the lower-level driver from the `bxcan` crate. - fn as_mut(&mut self) -> &mut bxcan::Can> { - &mut self.can - } -} - -/// CAN driver, transmit half. -pub struct CanTx<'c, 'd, T: Instance> { - tx: &'c mut bxcan::Tx>, -} - -impl<'c, 'd, T: Instance> CanTx<'c, 'd, T> { - /// Queues the message to be sent. - /// - /// If the TX queue is full, this will wait until there is space, therefore exerting backpressure. - pub async fn write(&mut self, frame: &Frame) -> bxcan::TransmitStatus { - poll_fn(|cx| { - T::state().tx_waker.register(cx.waker()); - if let Ok(status) = self.tx.transmit(frame) { - return Poll::Ready(status); - } - - Poll::Pending - }) - .await - } - - /// Attempts to transmit a frame without blocking. - /// - /// Returns [Err(TryWriteError::Full)] if all transmit mailboxes are full. - pub fn try_write(&mut self, frame: &Frame) -> Result { - self.tx.transmit(frame).map_err(|_| TryWriteError::Full) - } - - async fn flush_inner(mb: bxcan::Mailbox) { - poll_fn(|cx| { - T::state().tx_waker.register(cx.waker()); - if T::regs().tsr().read().tme(mb.index()) { - return Poll::Ready(()); - } - - Poll::Pending - }) - .await; - } - - /// Waits for a specific transmit mailbox to become empty - pub async fn flush(&self, mb: bxcan::Mailbox) { - Self::flush_inner(mb).await - } - - async fn flush_any_inner() { - poll_fn(|cx| { - T::state().tx_waker.register(cx.waker()); - - let tsr = T::regs().tsr().read(); - if tsr.tme(bxcan::Mailbox::Mailbox0.index()) - || tsr.tme(bxcan::Mailbox::Mailbox1.index()) - || tsr.tme(bxcan::Mailbox::Mailbox2.index()) - { - return Poll::Ready(()); - } - - Poll::Pending - }) - .await; - } - - /// Waits until any of the transmit mailboxes become empty - pub async fn flush_any(&self) { - Self::flush_any_inner().await - } - - async fn flush_all_inner() { - poll_fn(|cx| { - T::state().tx_waker.register(cx.waker()); - - let tsr = T::regs().tsr().read(); - if tsr.tme(bxcan::Mailbox::Mailbox0.index()) - && tsr.tme(bxcan::Mailbox::Mailbox1.index()) - && tsr.tme(bxcan::Mailbox::Mailbox2.index()) - { - return Poll::Ready(()); - } - - Poll::Pending - }) - .await; - } - - /// Waits until all of the transmit mailboxes become empty - pub async fn flush_all(&self) { - Self::flush_all_inner().await - } -} - -/// CAN driver, receive half. -#[allow(dead_code)] -pub struct CanRx<'c, 'd, T: Instance> { - rx0: &'c mut bxcan::Rx0>, - rx1: &'c mut bxcan::Rx1>, -} - -impl<'c, 'd, T: Instance> CanRx<'c, 'd, T> { - /// Read a CAN frame. - /// - /// If no CAN frame is in the RX buffer, this will wait until there is one. - /// - /// Returns a tuple of the time the message was received and the message frame - pub async fn read(&mut self) -> Result { - poll_fn(|cx| { - T::state().err_waker.register(cx.waker()); - if let Poll::Ready(envelope) = T::state().rx_queue.receive().poll_unpin(cx) { - return Poll::Ready(Ok(envelope)); - } else if let Some(err) = self.curr_error() { - return Poll::Ready(Err(err)); - } - - Poll::Pending - }) - .await - } - - /// Attempts to read a CAN frame without blocking. - /// - /// Returns [Err(TryReadError::Empty)] if there are no frames in the rx queue. - pub fn try_read(&mut self) -> Result { - if let Ok(envelope) = T::state().rx_queue.try_receive() { - return Ok(envelope); - } - - if let Some(err) = self.curr_error() { - return Err(TryReadError::BusError(err)); - } - - Err(TryReadError::Empty) - } - - /// Waits while receive queue is empty. - pub async fn wait_not_empty(&mut self) { - poll_fn(|cx| T::state().rx_queue.poll_ready_to_receive(cx)).await - } - - fn curr_error(&self) -> Option { - let err = { T::regs().esr().read() }; - if err.boff() { - return Some(BusError::BusOff); - } else if err.epvf() { - return Some(BusError::BusPassive); - } else if err.ewgf() { - return Some(BusError::BusWarning); - } else if let Some(err) = err.lec().into_bus_err() { - return Some(err); - } - None - } -} - -enum RxFifo { - Fifo0, - Fifo1, -} - -impl<'d, T: Instance> Drop for Can<'d, T> { - fn drop(&mut self) { - // Cannot call `free()` because it moves the instance. - // Manually reset the peripheral. - T::regs().mcr().write(|w| w.set_reset(true)); - T::disable(); - } -} - -impl<'d, T: Instance> Deref for Can<'d, T> { - type Target = bxcan::Can>; - - fn deref(&self) -> &Self::Target { - &self.can - } -} - -impl<'d, T: Instance> DerefMut for Can<'d, T> { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.can - } -} - -pub(crate) mod sealed { - use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; - use embassy_sync::channel::Channel; - use embassy_sync::waitqueue::AtomicWaker; - - use super::Envelope; - - pub struct State { - pub tx_waker: AtomicWaker, - pub err_waker: AtomicWaker, - pub rx_queue: Channel, - } - - impl State { - pub const fn new() -> Self { - Self { - tx_waker: AtomicWaker::new(), - err_waker: AtomicWaker::new(), - rx_queue: Channel::new(), - } - } - } - - pub trait Instance { - const REGISTERS: *mut bxcan::RegisterBlock; - - fn regs() -> crate::pac::can::Can; - fn state() -> &'static State; - } -} - -/// CAN instance trait. -pub trait Instance: sealed::Instance + RccPeripheral + 'static { - /// TX interrupt for this instance. - type TXInterrupt: crate::interrupt::typelevel::Interrupt; - /// RX0 interrupt for this instance. - type RX0Interrupt: crate::interrupt::typelevel::Interrupt; - /// RX1 interrupt for this instance. - type RX1Interrupt: crate::interrupt::typelevel::Interrupt; - /// SCE interrupt for this instance. - type SCEInterrupt: crate::interrupt::typelevel::Interrupt; -} - -/// BXCAN instance newtype. -pub struct BxcanInstance<'a, T>(PeripheralRef<'a, T>); - -unsafe impl<'d, T: Instance> bxcan::Instance for BxcanInstance<'d, T> { - const REGISTERS: *mut bxcan::RegisterBlock = T::REGISTERS; -} - -foreach_peripheral!( - (can, $inst:ident) => { - impl sealed::Instance for peripherals::$inst { - const REGISTERS: *mut bxcan::RegisterBlock = crate::pac::$inst.as_ptr() as *mut _; - - fn regs() -> crate::pac::can::Can { - crate::pac::$inst - } - - fn state() -> &'static sealed::State { - static STATE: sealed::State = sealed::State::new(); - &STATE - } - } - - impl Instance for peripherals::$inst { - type TXInterrupt = crate::_generated::peripheral_interrupts::$inst::TX; - type RX0Interrupt = crate::_generated::peripheral_interrupts::$inst::RX0; - type RX1Interrupt = crate::_generated::peripheral_interrupts::$inst::RX1; - type SCEInterrupt = crate::_generated::peripheral_interrupts::$inst::SCE; - } - }; -); - -foreach_peripheral!( - (can, CAN) => { - unsafe impl<'d> bxcan::FilterOwner for BxcanInstance<'d, peripherals::CAN> { - const NUM_FILTER_BANKS: u8 = 14; - } - }; - // CAN1 and CAN2 is a combination of master and slave instance. - // CAN1 owns the filter bank and needs to be enabled in order - // for CAN2 to receive messages. - (can, CAN1) => { - cfg_if::cfg_if! { - if #[cfg(all( - any(stm32l4, stm32f72, stm32f73), - not(any(stm32l49, stm32l4a)) - ))] { - // Most L4 devices and some F7 devices use the name "CAN1" - // even if there is no "CAN2" peripheral. - unsafe impl<'d> bxcan::FilterOwner for BxcanInstance<'d, peripherals::CAN1> { - const NUM_FILTER_BANKS: u8 = 14; - } - } else { - unsafe impl<'d> bxcan::FilterOwner for BxcanInstance<'d, peripherals::CAN1> { - const NUM_FILTER_BANKS: u8 = 28; - } - unsafe impl<'d> bxcan::MasterInstance for BxcanInstance<'d, peripherals::CAN1> {} - } - } - }; - (can, CAN3) => { - unsafe impl<'d> bxcan::FilterOwner for BxcanInstance<'d, peripherals::CAN3> { - const NUM_FILTER_BANKS: u8 = 14; - } - }; -); - -pin_trait!(RxPin, Instance); -pin_trait!(TxPin, Instance); - -trait Index { - fn index(&self) -> usize; -} - -impl Index for bxcan::Mailbox { - fn index(&self) -> usize { - match self { - bxcan::Mailbox::Mailbox0 => 0, - bxcan::Mailbox::Mailbox1 => 1, - bxcan::Mailbox::Mailbox2 => 2, - } - } -} - -trait IntoBusError { - fn into_bus_err(self) -> Option; -} - -impl IntoBusError for Lec { - fn into_bus_err(self) -> Option { - match self { - Lec::STUFF => Some(BusError::Stuff), - Lec::FORM => Some(BusError::Form), - Lec::ACK => Some(BusError::Acknowledge), - Lec::BITRECESSIVE => Some(BusError::BitRecessive), - Lec::BITDOMINANT => Some(BusError::BitDominant), - Lec::CRC => Some(BusError::Crc), - Lec::CUSTOM => Some(BusError::Software), - _ => None, - } - } -} diff --git a/embassy-stm32/src/can/bxcan/filter.rs b/embassy-stm32/src/can/bxcan/filter.rs new file mode 100644 index 000000000..167c6c572 --- /dev/null +++ b/embassy-stm32/src/can/bxcan/filter.rs @@ -0,0 +1,479 @@ +//! Filter bank API. + +use core::marker::PhantomData; + +use super::{ExtendedId, Fifo, Id, StandardId}; + +const F32_RTR: u32 = 0b010; // set the RTR bit to match remote frames +const F32_IDE: u32 = 0b100; // set the IDE bit to match extended identifiers +const F16_RTR: u16 = 0b10000; +const F16_IDE: u16 = 0b01000; + +/// A 16-bit filter list entry. +/// +/// This can match data and remote frames using standard IDs. +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct ListEntry16(u16); + +/// A 32-bit filter list entry. +/// +/// This can match data and remote frames using extended or standard IDs. +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct ListEntry32(u32); + +/// A 16-bit identifier mask. +#[derive(Debug, Copy, Clone)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct Mask16 { + id: u16, + mask: u16, +} + +/// A 32-bit identifier mask. +#[derive(Debug, Copy, Clone)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct Mask32 { + id: u32, + mask: u32, +} + +impl ListEntry16 { + /// Creates a filter list entry that accepts data frames with the given standard ID. + /// + /// This entry will *not* accept remote frames with the same ID. + pub fn data_frames_with_id(id: StandardId) -> Self { + Self(id.as_raw() << 5) + } + + /// Creates a filter list entry that accepts remote frames with the given standard ID. + pub fn remote_frames_with_id(id: StandardId) -> Self { + Self(id.as_raw() << 5 | F16_RTR) + } +} + +impl ListEntry32 { + /// Creates a filter list entry that accepts data frames with the given ID. + /// + /// This entry will *not* accept remote frames with the same ID. + /// + /// The filter will only accept *either* standard *or* extended frames, depending on `id`. + pub fn data_frames_with_id(id: impl Into) -> Self { + match id.into() { + Id::Standard(id) => Self(u32::from(id.as_raw()) << 21), + Id::Extended(id) => Self(id.as_raw() << 3 | F32_IDE), + } + } + + /// Creates a filter list entry that accepts remote frames with the given ID. + pub fn remote_frames_with_id(id: impl Into) -> Self { + match id.into() { + Id::Standard(id) => Self(u32::from(id.as_raw()) << 21 | F32_RTR), + Id::Extended(id) => Self(id.as_raw() << 3 | F32_IDE | F32_RTR), + } + } +} + +impl Mask16 { + /// Creates a 16-bit identifier mask that accepts all frames. + /// + /// This will accept both standard and extended data and remote frames with any ID. + pub fn accept_all() -> Self { + Self { id: 0, mask: 0 } + } + + /// Creates a 16-bit identifier mask that accepts all frames with the given standard + /// ID and mask combination. + /// + /// Filter logic: `frame_accepted = (incoming_id & mask) == (id & mask)` + /// + /// A mask of all all ones (`0x7FF`) matches an exact ID, a mask of 0 matches all IDs. + /// + /// Both data and remote frames with `id` will be accepted. Any extended frames will be + /// rejected. + pub fn frames_with_std_id(id: StandardId, mask: StandardId) -> Self { + Self { + id: id.as_raw() << 5, + mask: mask.as_raw() << 5 | F16_IDE, // also require IDE = 0 + } + } + + /// Make the filter accept data frames only. + pub fn data_frames_only(&mut self) -> &mut Self { + self.id &= !F16_RTR; // RTR = 0 + self.mask |= F16_RTR; + self + } + + /// Make the filter accept remote frames only. + pub fn remote_frames_only(&mut self) -> &mut Self { + self.id |= F16_RTR; // RTR = 1 + self.mask |= F16_RTR; + self + } +} + +impl Mask32 { + /// Creates a 32-bit identifier mask that accepts all frames. + /// + /// This will accept both standard and extended data and remote frames with any ID. + pub fn accept_all() -> Self { + Self { id: 0, mask: 0 } + } + + /// Creates a 32-bit identifier mask that accepts all frames with the given extended + /// ID and mask combination. + /// + /// Filter logic: `frame_accepted = (incoming_id & mask) == (id & mask)` + /// + /// A mask of all all ones (`0x1FFF_FFFF`) matches an exact ID, a mask of 0 matches all IDs. + /// + /// Both data and remote frames with `id` will be accepted. Standard frames will be rejected. + pub fn frames_with_ext_id(id: ExtendedId, mask: ExtendedId) -> Self { + Self { + id: id.as_raw() << 3 | F32_IDE, + mask: mask.as_raw() << 3 | F32_IDE, // also require IDE = 1 + } + } + + /// Creates a 32-bit identifier mask that accepts all frames with the given standard + /// ID and mask combination. + /// + /// Filter logic: `frame_accepted = (incoming_id & mask) == (id & mask)` + /// + /// A mask of all all ones (`0x7FF`) matches the exact ID, a mask of 0 matches all IDs. + /// + /// Both data and remote frames with `id` will be accepted. Extended frames will be rejected. + pub fn frames_with_std_id(id: StandardId, mask: StandardId) -> Self { + Self { + id: u32::from(id.as_raw()) << 21, + mask: u32::from(mask.as_raw()) << 21 | F32_IDE, // also require IDE = 0 + } + } + + /// Make the filter accept data frames only. + pub fn data_frames_only(&mut self) -> &mut Self { + self.id &= !F32_RTR; // RTR = 0 + self.mask |= F32_RTR; + self + } + + /// Make the filter accept remote frames only. + pub fn remote_frames_only(&mut self) -> &mut Self { + self.id |= F32_RTR; // RTR = 1 + self.mask |= F32_RTR; + self + } +} + +/// The configuration of a filter bank. +#[derive(Debug, Copy, Clone)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum BankConfig { + /// Specify up to 4 exact standard CAN ID's. + List16([ListEntry16; 4]), + /// Specify up to 2 exact standard or extended CAN ID's. + List32([ListEntry32; 2]), + /// Specify up to 2 standard ID's with masks. + Mask16([Mask16; 2]), + /// Specify a single extended ID with mask. + Mask32(Mask32), +} + +impl From<[ListEntry16; 4]> for BankConfig { + #[inline] + fn from(entries: [ListEntry16; 4]) -> Self { + Self::List16(entries) + } +} + +impl From<[ListEntry32; 2]> for BankConfig { + #[inline] + fn from(entries: [ListEntry32; 2]) -> Self { + Self::List32(entries) + } +} + +impl From<[Mask16; 2]> for BankConfig { + #[inline] + fn from(entries: [Mask16; 2]) -> Self { + Self::Mask16(entries) + } +} + +impl From for BankConfig { + #[inline] + fn from(filter: Mask32) -> Self { + Self::Mask32(filter) + } +} + +/// Interface to the filter banks of a CAN peripheral. +pub struct MasterFilters<'a> { + /// Number of assigned filter banks. + /// + /// On chips with splittable filter banks, this value can be dynamic. + bank_count: u8, + _phantom: PhantomData<&'a ()>, + info: &'static crate::can::Info, +} + +// NOTE: This type mutably borrows the CAN instance and has unique access to the registers while it +// exists. +impl MasterFilters<'_> { + pub(crate) unsafe fn new(info: &'static crate::can::Info) -> Self { + // Enable initialization mode. + info.regs.0.fmr().modify(|reg| reg.set_finit(true)); + + // Read the filter split value. + let bank_count = info.regs.0.fmr().read().can2sb(); + + // (Reset value of CAN2SB is 0x0E, 14, which, in devices with 14 filter banks, assigns all + // of them to the master peripheral, and in devices with 28, assigns them 50/50 to + // master/slave instances) + + Self { + bank_count, + _phantom: PhantomData, + info, + } + } + + fn banks_imm(&self) -> FilterBanks { + FilterBanks { + start_idx: 0, + bank_count: self.bank_count, + info: self.info, + } + } + + /// Returns the number of filter banks currently assigned to this instance. + /// + /// Chips with splittable filter banks may start out with some banks assigned to the master + /// instance and some assigned to the slave instance. + pub fn num_banks(&self) -> u8 { + self.bank_count + } + + /// Disables all enabled filter banks. + /// + /// This causes all incoming frames to be disposed. + pub fn clear(&mut self) -> &mut Self { + self.banks_imm().clear(); + self + } + + /// Disables a filter bank. + /// + /// If `index` is out of bounds, this will panic. + pub fn disable_bank(&mut self, index: u8) -> &mut Self { + self.banks_imm().disable(index); + self + } + + /// Configures a filter bank according to `config` and enables it. + /// + /// Each filter bank is associated with one of the two RX FIFOs, configured by the [`Fifo`] + /// passed to this function. In the event that both FIFOs are configured to accept an incoming + /// frame, the accepting filter bank with the lowest index wins. The FIFO state is ignored, so + /// if the FIFO is full, it will overflow, even if the other FIFO is also configured to accept + /// the frame. + /// + /// # Parameters + /// + /// - `index`: the filter index. + /// - `fifo`: the receive FIFO the filter should pass accepted messages to. + /// - `config`: the filter configuration. + pub fn enable_bank(&mut self, index: u8, fifo: Fifo, config: impl Into) -> &mut Self { + self.banks_imm().enable(index, fifo, config.into()); + self + } +} + +impl MasterFilters<'_> { + /// Sets the index at which the filter banks owned by the slave peripheral start. + pub fn set_split(&mut self, split_index: u8) -> &mut Self { + assert!(split_index <= self.info.num_filter_banks); + self.info.regs.0.fmr().modify(|reg| reg.set_can2sb(split_index)); + self.bank_count = split_index; + self + } + + /// Accesses the filters assigned to the slave peripheral. + pub fn slave_filters(&mut self) -> SlaveFilters<'_> { + // NB: This mutably borrows `self`, so it has full access to the filter bank registers. + SlaveFilters { + start_idx: self.bank_count, + bank_count: self.info.num_filter_banks - self.bank_count, + _phantom: PhantomData, + info: self.info, + } + } +} + +impl Drop for MasterFilters<'_> { + #[inline] + fn drop(&mut self) { + // Leave initialization mode. + self.info.regs.0.fmr().modify(|regs| regs.set_finit(false)); + } +} + +/// Interface to the filter banks assigned to a slave peripheral. +pub struct SlaveFilters<'a> { + start_idx: u8, + bank_count: u8, + _phantom: PhantomData<&'a ()>, + info: &'static crate::can::Info, +} + +impl SlaveFilters<'_> { + fn banks_imm(&self) -> FilterBanks { + FilterBanks { + start_idx: self.start_idx, + bank_count: self.bank_count, + info: self.info, + } + } + + /// Returns the number of filter banks currently assigned to this instance. + /// + /// Chips with splittable filter banks may start out with some banks assigned to the master + /// instance and some assigned to the slave instance. + pub fn num_banks(&self) -> u8 { + self.bank_count + } + + /// Disables all enabled filter banks. + /// + /// This causes all incoming frames to be disposed. + pub fn clear(&mut self) -> &mut Self { + self.banks_imm().clear(); + self + } + + /// Disables a filter bank. + /// + /// If `index` is out of bounds, this will panic. + pub fn disable_bank(&mut self, index: u8) -> &mut Self { + self.banks_imm().disable(index); + self + } + + /// Configures a filter bank according to `config` and enables it. + /// + /// # Parameters + /// + /// - `index`: the filter index. + /// - `fifo`: the receive FIFO the filter should pass accepted messages to. + /// - `config`: the filter configuration. + pub fn enable_bank(&mut self, index: u8, fifo: Fifo, config: impl Into) -> &mut Self { + self.banks_imm().enable(index, fifo, config.into()); + self + } +} + +struct FilterBanks { + start_idx: u8, + bank_count: u8, + info: &'static crate::can::Info, +} + +impl FilterBanks { + fn clear(&mut self) { + let mask = filter_bitmask(self.start_idx, self.bank_count); + + self.info.regs.0.fa1r().modify(|reg| { + for i in 0..28usize { + if (0x01u32 << i) & mask != 0 { + reg.set_fact(i, false); + } + } + }); + } + + fn assert_bank_index(&self, index: u8) { + assert!((self.start_idx..self.start_idx + self.bank_count).contains(&index)); + } + + fn disable(&mut self, index: u8) { + self.assert_bank_index(index); + self.info + .regs + .0 + .fa1r() + .modify(|reg| reg.set_fact(index as usize, false)) + } + + fn enable(&mut self, index: u8, fifo: Fifo, config: BankConfig) { + self.assert_bank_index(index); + + // Configure mode. + let mode = matches!(config, BankConfig::List16(_) | BankConfig::List32(_)); + self.info.regs.0.fm1r().modify(|reg| reg.set_fbm(index as usize, mode)); + + // Configure scale. + let scale = matches!(config, BankConfig::List32(_) | BankConfig::Mask32(_)); + self.info.regs.0.fs1r().modify(|reg| reg.set_fsc(index as usize, scale)); + + // Configure filter register. + let (fxr1, fxr2); + match config { + BankConfig::List16([a, b, c, d]) => { + fxr1 = (u32::from(b.0) << 16) | u32::from(a.0); + fxr2 = (u32::from(d.0) << 16) | u32::from(c.0); + } + BankConfig::List32([a, b]) => { + fxr1 = a.0; + fxr2 = b.0; + } + BankConfig::Mask16([a, b]) => { + fxr1 = (u32::from(a.mask) << 16) | u32::from(a.id); + fxr2 = (u32::from(b.mask) << 16) | u32::from(b.id); + } + BankConfig::Mask32(a) => { + fxr1 = a.id; + fxr2 = a.mask; + } + }; + let bank = self.info.regs.0.fb(index as usize); + bank.fr1().write(|w| w.0 = fxr1); + bank.fr2().write(|w| w.0 = fxr2); + + // Assign to the right FIFO + self.info.regs.0.ffa1r().modify(|reg| { + reg.set_ffa( + index as usize, + match fifo { + Fifo::Fifo0 => false, + Fifo::Fifo1 => true, + }, + ) + }); + + // Set active. + self.info.regs.0.fa1r().modify(|reg| reg.set_fact(index as usize, true)) + } +} + +/// Computes a bitmask for per-filter-bank registers that only includes filters in the given range. +fn filter_bitmask(start_idx: u8, bank_count: u8) -> u32 { + let count_mask = (1 << bank_count) - 1; // `bank_count` 1-bits + count_mask << start_idx +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_filter_bitmask() { + assert_eq!(filter_bitmask(0, 1), 0x1); + assert_eq!(filter_bitmask(1, 1), 0b10); + assert_eq!(filter_bitmask(0, 4), 0xf); + assert_eq!(filter_bitmask(1, 3), 0xe); + assert_eq!(filter_bitmask(8, 1), 0x100); + assert_eq!(filter_bitmask(8, 4), 0xf00); + } +} diff --git a/embassy-stm32/src/can/bxcan/mod.rs b/embassy-stm32/src/can/bxcan/mod.rs new file mode 100644 index 000000000..19f1cea29 --- /dev/null +++ b/embassy-stm32/src/can/bxcan/mod.rs @@ -0,0 +1,1196 @@ +pub mod filter; +mod registers; + +use core::future::poll_fn; +use core::marker::PhantomData; +use core::task::Poll; + +use embassy_hal_internal::interrupt::InterruptExt; +use embassy_hal_internal::into_ref; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +use embassy_sync::channel::Channel; +use embassy_sync::waitqueue::AtomicWaker; +pub use embedded_can::{ExtendedId, Id, StandardId}; + +use self::filter::MasterFilters; +use self::registers::{Registers, RxFifo}; +pub use super::common::{BufferedCanReceiver, BufferedCanSender}; +use super::frame::{Envelope, Frame}; +use super::util; +use crate::can::enums::{BusError, TryReadError}; +use crate::gpio::{AfType, OutputType, Pull, Speed}; +use crate::interrupt::typelevel::Interrupt; +use crate::rcc::{self, RccPeripheral}; +use crate::{interrupt, peripherals, Peripheral}; + +/// Interrupt handler. +pub struct TxInterruptHandler { + _phantom: PhantomData, +} + +impl interrupt::typelevel::Handler for TxInterruptHandler { + unsafe fn on_interrupt() { + T::regs().tsr().write(|v| { + v.set_rqcp(0, true); + v.set_rqcp(1, true); + v.set_rqcp(2, true); + }); + T::state().tx_mode.on_interrupt::(); + } +} + +/// RX0 interrupt handler. +pub struct Rx0InterruptHandler { + _phantom: PhantomData, +} + +impl interrupt::typelevel::Handler for Rx0InterruptHandler { + unsafe fn on_interrupt() { + T::state().rx_mode.on_interrupt::(RxFifo::Fifo0); + } +} + +/// RX1 interrupt handler. +pub struct Rx1InterruptHandler { + _phantom: PhantomData, +} + +impl interrupt::typelevel::Handler for Rx1InterruptHandler { + unsafe fn on_interrupt() { + T::state().rx_mode.on_interrupt::(RxFifo::Fifo1); + } +} + +/// SCE interrupt handler. +pub struct SceInterruptHandler { + _phantom: PhantomData, +} + +impl interrupt::typelevel::Handler for SceInterruptHandler { + unsafe fn on_interrupt() { + let msr = T::regs().msr(); + let msr_val = msr.read(); + + if msr_val.slaki() { + msr.modify(|m| m.set_slaki(true)); + T::state().err_waker.wake(); + } else if msr_val.erri() { + // Disable the interrupt, but don't acknowledge the error, so that it can be + // forwarded off the bus message consumer. If we don't provide some way for + // downstream code to determine that it has already provided this bus error instance + // to the bus message consumer, we are doomed to re-provide a single error instance for + // an indefinite amount of time. + let ier = T::regs().ier(); + ier.modify(|i| i.set_errie(false)); + + T::state().err_waker.wake(); + } + } +} + +/// Configuration proxy returned by [`Can::modify_config`]. +pub struct CanConfig<'a> { + phantom: PhantomData<&'a ()>, + info: &'static Info, + periph_clock: crate::time::Hertz, +} + +impl CanConfig<'_> { + /// Configures the bit timings. + /// + /// You can use to calculate the `btr` parameter. Enter + /// parameters as follows: + /// + /// - *Clock Rate*: The input clock speed to the CAN peripheral (*not* the CPU clock speed). + /// This is the clock rate of the peripheral bus the CAN peripheral is attached to (eg. APB1). + /// - *Sample Point*: Should normally be left at the default value of 87.5%. + /// - *SJW*: Should normally be left at the default value of 1. + /// + /// Then copy the `CAN_BUS_TIME` register value from the table and pass it as the `btr` + /// parameter to this method. + pub fn set_bit_timing(self, bt: crate::can::util::NominalBitTiming) -> Self { + self.info.regs.set_bit_timing(bt); + self + } + + /// Configure the CAN bit rate. + /// + /// This is a helper that internally calls `set_bit_timing()`[Self::set_bit_timing]. + pub fn set_bitrate(self, bitrate: u32) -> Self { + let bit_timing = util::calc_can_timings(self.periph_clock, bitrate).unwrap(); + self.set_bit_timing(bit_timing) + } + + /// Enables or disables loopback mode: Internally connects the TX and RX + /// signals together. + pub fn set_loopback(self, enabled: bool) -> Self { + self.info.regs.set_loopback(enabled); + self + } + + /// Enables or disables silent mode: Disconnects the TX signal from the pin. + pub fn set_silent(self, enabled: bool) -> Self { + self.info.regs.set_silent(enabled); + self + } + + /// Enables or disables automatic retransmission of frames. + /// + /// If this is enabled, the CAN peripheral will automatically try to retransmit each frame + /// until it can be sent. Otherwise, it will try only once to send each frame. + /// + /// Automatic retransmission is enabled by default. + pub fn set_automatic_retransmit(self, enabled: bool) -> Self { + self.info.regs.set_automatic_retransmit(enabled); + self + } +} + +impl Drop for CanConfig<'_> { + #[inline] + fn drop(&mut self) { + self.info.regs.leave_init_mode(); + } +} + +/// CAN driver +pub struct Can<'d> { + phantom: PhantomData<&'d ()>, + info: &'static Info, + state: &'static State, + periph_clock: crate::time::Hertz, +} + +/// Error returned by `try_write` +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum TryWriteError { + /// All transmit mailboxes are full + Full, +} + +impl<'d> Can<'d> { + /// Creates a new Bxcan instance, keeping the peripheral in sleep mode. + /// You must call [Can::enable_non_blocking] to use the peripheral. + pub fn new( + _peri: impl Peripheral

+ 'd, + rx: impl Peripheral

> + 'd, + tx: impl Peripheral

> + 'd, + _irqs: impl interrupt::typelevel::Binding> + + interrupt::typelevel::Binding> + + interrupt::typelevel::Binding> + + interrupt::typelevel::Binding> + + 'd, + ) -> Self { + into_ref!(_peri, rx, tx); + let info = T::info(); + let regs = &T::info().regs; + + rx.set_as_af(rx.af_num(), AfType::input(Pull::None)); + tx.set_as_af(tx.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); + + rcc::enable_and_reset::(); + + { + regs.0.ier().write(|w| { + w.set_errie(true); + w.set_fmpie(0, true); + w.set_fmpie(1, true); + w.set_tmeie(true); + w.set_bofie(true); + w.set_epvie(true); + w.set_ewgie(true); + w.set_lecie(true); + }); + + regs.0.mcr().write(|w| { + // Enable timestamps on rx messages + + w.set_ttcm(true); + }); + } + + unsafe { + info.tx_interrupt.unpend(); + info.tx_interrupt.enable(); + info.rx0_interrupt.unpend(); + info.rx0_interrupt.enable(); + info.rx1_interrupt.unpend(); + info.rx1_interrupt.enable(); + info.sce_interrupt.unpend(); + info.sce_interrupt.enable(); + } + + rx.set_as_af(rx.af_num(), AfType::input(Pull::None)); + tx.set_as_af(tx.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); + + Registers(T::regs()).leave_init_mode(); + + Self { + phantom: PhantomData, + info: T::info(), + state: T::state(), + periph_clock: T::frequency(), + } + } + + /// Set CAN bit rate. + pub fn set_bitrate(&mut self, bitrate: u32) { + let bit_timing = util::calc_can_timings(self.periph_clock, bitrate).unwrap(); + self.modify_config().set_bit_timing(bit_timing); + } + + /// Configure bit timings and silent/loop-back mode. + /// + /// Calling this method will enter initialization mode. You must enable the peripheral + /// again afterwards with [`enable`](Self::enable). + pub fn modify_config(&mut self) -> CanConfig<'_> { + self.info.regs.enter_init_mode(); + + CanConfig { + phantom: self.phantom, + info: self.info, + periph_clock: self.periph_clock, + } + } + + /// Enables the peripheral and synchronizes with the bus. + /// + /// This will wait for 11 consecutive recessive bits (bus idle state). + /// Contrary to enable method from bxcan library, this will not freeze the executor while waiting. + pub async fn enable(&mut self) { + while self.info.regs.enable_non_blocking().is_err() { + // SCE interrupt is only generated for entering sleep mode, but not leaving. + // Yield to allow other tasks to execute while can bus is initializing. + embassy_futures::yield_now().await; + } + } + + /// Enables or disables the peripheral from automatically wakeup when a SOF is detected on the bus + /// while the peripheral is in sleep mode + pub fn set_automatic_wakeup(&mut self, enabled: bool) { + self.info.regs.set_automatic_wakeup(enabled); + } + + /// Manually wake the peripheral from sleep mode. + /// + /// Waking the peripheral manually does not trigger a wake-up interrupt. + /// This will wait until the peripheral has acknowledged it has awoken from sleep mode + pub fn wakeup(&mut self) { + self.info.regs.wakeup() + } + + /// Check if the peripheral is currently in sleep mode + pub fn is_sleeping(&self) -> bool { + self.info.regs.0.msr().read().slak() + } + + /// Put the peripheral in sleep mode + /// + /// When the peripherial is in sleep mode, messages can still be queued for transmission + /// and any previously received messages can be read from the receive FIFOs, however + /// no messages will be transmitted and no additional messages will be received. + /// + /// If the peripheral has automatic wakeup enabled, when a Start-of-Frame is detected + /// the peripheral will automatically wake and receive the incoming message. + pub async fn sleep(&mut self) { + self.info.regs.0.ier().modify(|i| i.set_slkie(true)); + self.info.regs.0.mcr().modify(|m| m.set_sleep(true)); + + poll_fn(|cx| { + self.state.err_waker.register(cx.waker()); + if self.is_sleeping() { + Poll::Ready(()) + } else { + Poll::Pending + } + }) + .await; + + self.info.regs.0.ier().modify(|i| i.set_slkie(false)); + } + + /// Enable FIFO scheduling of outgoing frames. + /// + /// If this is enabled, frames will be transmitted in the order that they are passed to + /// [`write()`][Self::write] or [`try_write()`][Self::try_write()]. + /// + /// If this is disabled, frames are transmitted in order of priority. + /// + /// FIFO scheduling is disabled by default. + pub fn set_tx_fifo_scheduling(&mut self, enabled: bool) { + self.info.regs.set_tx_fifo_scheduling(enabled) + } + + /// Checks if FIFO scheduling of outgoing frames is enabled. + pub fn tx_fifo_scheduling_enabled(&self) -> bool { + self.info.regs.tx_fifo_scheduling_enabled() + } + + /// Queues the message to be sent. + /// + /// If the TX queue is full, this will wait until there is space, therefore exerting backpressure. + pub async fn write(&mut self, frame: &Frame) -> TransmitStatus { + self.split().0.write(frame).await + } + + /// Attempts to transmit a frame without blocking. + /// + /// Returns [Err(TryWriteError::Full)] if the frame can not be queued for transmission now. + /// + /// If FIFO scheduling is enabled, any empty mailbox will be used. + /// + /// Otherwise, the frame will only be accepted if there is no frame with the same priority already queued. + /// This is done to work around a hardware limitation that could lead to out-of-order delivery + /// of frames with the same priority. + pub fn try_write(&mut self, frame: &Frame) -> Result { + self.split().0.try_write(frame) + } + + /// Waits for a specific transmit mailbox to become empty + pub async fn flush(&self, mb: Mailbox) { + CanTx { + _phantom: PhantomData, + info: self.info, + state: self.state, + } + .flush_inner(mb) + .await; + } + + /// Waits until any of the transmit mailboxes become empty + /// + /// Note that [`Self::try_write()`] may fail with [`TryWriteError::Full`], + /// even after the future returned by this function completes. + /// This will happen if FIFO scheduling of outgoing frames is not enabled, + /// and a frame with equal priority is already queued for transmission. + pub async fn flush_any(&self) { + CanTx { + _phantom: PhantomData, + info: self.info, + state: self.state, + } + .flush_any_inner() + .await + } + + /// Waits until all of the transmit mailboxes become empty + pub async fn flush_all(&self) { + CanTx { + _phantom: PhantomData, + info: self.info, + state: self.state, + } + .flush_all_inner() + .await + } + + /// Attempts to abort the sending of a frame that is pending in a mailbox. + /// + /// If there is no frame in the provided mailbox, or its transmission succeeds before it can be + /// aborted, this function has no effect and returns `false`. + /// + /// If there is a frame in the provided mailbox, and it is canceled successfully, this function + /// returns `true`. + pub fn abort(&mut self, mailbox: Mailbox) -> bool { + self.info.regs.abort(mailbox) + } + + /// Returns `true` if no frame is pending for transmission. + pub fn is_transmitter_idle(&self) -> bool { + self.info.regs.is_idle() + } + + /// Read a CAN frame. + /// + /// If no CAN frame is in the RX buffer, this will wait until there is one. + /// + /// Returns a tuple of the time the message was received and the message frame + pub async fn read(&mut self) -> Result { + self.state.rx_mode.read(self.info, self.state).await + } + + /// Attempts to read a CAN frame without blocking. + /// + /// Returns [Err(TryReadError::Empty)] if there are no frames in the rx queue. + pub fn try_read(&mut self) -> Result { + self.state.rx_mode.try_read(self.info) + } + + /// Waits while receive queue is empty. + pub async fn wait_not_empty(&mut self) { + self.state.rx_mode.wait_not_empty(self.info, self.state).await + } + + /// Split the CAN driver into transmit and receive halves. + /// + /// Useful for doing separate transmit/receive tasks. + pub fn split<'c>(&'c mut self) -> (CanTx<'d>, CanRx<'d>) { + ( + CanTx { + _phantom: PhantomData, + info: self.info, + state: self.state, + }, + CanRx { + _phantom: PhantomData, + info: self.info, + state: self.state, + }, + ) + } + + /// Return a buffered instance of driver. User must supply Buffers + pub fn buffered<'c, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize>( + &'c mut self, + txb: &'static mut TxBuf, + rxb: &'static mut RxBuf, + ) -> BufferedCan<'d, TX_BUF_SIZE, RX_BUF_SIZE> { + let (tx, rx) = self.split(); + BufferedCan { + tx: tx.buffered(txb), + rx: rx.buffered(rxb), + } + } +} + +impl<'d> Can<'d> { + /// Accesses the filter banks owned by this CAN peripheral. + /// + /// To modify filters of a slave peripheral, `modify_filters` has to be called on the master + /// peripheral instead. + pub fn modify_filters(&mut self) -> MasterFilters<'_> { + unsafe { MasterFilters::new(self.info) } + } +} + +/// Buffered CAN driver. +pub struct BufferedCan<'d, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> { + tx: BufferedCanTx<'d, TX_BUF_SIZE>, + rx: BufferedCanRx<'d, RX_BUF_SIZE>, +} + +impl<'d, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> BufferedCan<'d, TX_BUF_SIZE, RX_BUF_SIZE> { + /// Async write frame to TX buffer. + pub async fn write(&mut self, frame: &Frame) { + self.tx.write(frame).await + } + + /// Returns a sender that can be used for sending CAN frames. + pub fn writer(&self) -> BufferedCanSender { + self.tx.writer() + } + + /// Async read frame from RX buffer. + pub async fn read(&mut self) -> Result { + self.rx.read().await + } + + /// Attempts to read a CAN frame without blocking. + /// + /// Returns [Err(TryReadError::Empty)] if there are no frames in the rx queue. + pub fn try_read(&mut self) -> Result { + self.rx.try_read() + } + + /// Waits while receive queue is empty. + pub async fn wait_not_empty(&mut self) { + self.rx.wait_not_empty().await + } + + /// Returns a receiver that can be used for receiving CAN frames. Note, each CAN frame will only be received by one receiver. + pub fn reader(&self) -> BufferedCanReceiver { + self.rx.reader() + } +} + +/// CAN driver, transmit half. +pub struct CanTx<'d> { + _phantom: PhantomData<&'d ()>, + info: &'static Info, + state: &'static State, +} + +impl<'d> CanTx<'d> { + /// Queues the message to be sent. + /// + /// If the TX queue is full, this will wait until there is space, therefore exerting backpressure. + pub async fn write(&mut self, frame: &Frame) -> TransmitStatus { + poll_fn(|cx| { + self.state.tx_mode.register(cx.waker()); + if let Ok(status) = self.info.regs.transmit(frame) { + return Poll::Ready(status); + } + + Poll::Pending + }) + .await + } + + /// Attempts to transmit a frame without blocking. + /// + /// Returns [Err(TryWriteError::Full)] if the frame can not be queued for transmission now. + /// + /// If FIFO scheduling is enabled, any empty mailbox will be used. + /// + /// Otherwise, the frame will only be accepted if there is no frame with the same priority already queued. + /// This is done to work around a hardware limitation that could lead to out-of-order delivery + /// of frames with the same priority. + pub fn try_write(&mut self, frame: &Frame) -> Result { + self.info.regs.transmit(frame).map_err(|_| TryWriteError::Full) + } + + async fn flush_inner(&self, mb: Mailbox) { + poll_fn(|cx| { + self.state.tx_mode.register(cx.waker()); + if self.info.regs.0.tsr().read().tme(mb.index()) { + return Poll::Ready(()); + } + + Poll::Pending + }) + .await; + } + + /// Waits for a specific transmit mailbox to become empty + pub async fn flush(&self, mb: Mailbox) { + self.flush_inner(mb).await + } + + async fn flush_any_inner(&self) { + poll_fn(|cx| { + self.state.tx_mode.register(cx.waker()); + + let tsr = self.info.regs.0.tsr().read(); + if tsr.tme(Mailbox::Mailbox0.index()) + || tsr.tme(Mailbox::Mailbox1.index()) + || tsr.tme(Mailbox::Mailbox2.index()) + { + return Poll::Ready(()); + } + + Poll::Pending + }) + .await; + } + + /// Waits until any of the transmit mailboxes become empty + /// + /// Note that [`Self::try_write()`] may fail with [`TryWriteError::Full`], + /// even after the future returned by this function completes. + /// This will happen if FIFO scheduling of outgoing frames is not enabled, + /// and a frame with equal priority is already queued for transmission. + pub async fn flush_any(&self) { + self.flush_any_inner().await + } + + async fn flush_all_inner(&self) { + poll_fn(|cx| { + self.state.tx_mode.register(cx.waker()); + + let tsr = self.info.regs.0.tsr().read(); + if tsr.tme(Mailbox::Mailbox0.index()) + && tsr.tme(Mailbox::Mailbox1.index()) + && tsr.tme(Mailbox::Mailbox2.index()) + { + return Poll::Ready(()); + } + + Poll::Pending + }) + .await; + } + + /// Waits until all of the transmit mailboxes become empty + pub async fn flush_all(&self) { + self.flush_all_inner().await + } + + /// Attempts to abort the sending of a frame that is pending in a mailbox. + /// + /// If there is no frame in the provided mailbox, or its transmission succeeds before it can be + /// aborted, this function has no effect and returns `false`. + /// + /// If there is a frame in the provided mailbox, and it is canceled successfully, this function + /// returns `true`. + pub fn abort(&mut self, mailbox: Mailbox) -> bool { + self.info.regs.abort(mailbox) + } + + /// Returns `true` if no frame is pending for transmission. + pub fn is_idle(&self) -> bool { + self.info.regs.is_idle() + } + + /// Return a buffered instance of driver. User must supply Buffers + pub fn buffered( + self, + txb: &'static mut TxBuf, + ) -> BufferedCanTx<'d, TX_BUF_SIZE> { + BufferedCanTx::new(self.info, self.state, self, txb) + } +} + +/// User supplied buffer for TX buffering +pub type TxBuf = Channel; + +/// Buffered CAN driver, transmit half. +pub struct BufferedCanTx<'d, const TX_BUF_SIZE: usize> { + info: &'static Info, + state: &'static State, + _tx: CanTx<'d>, + tx_buf: &'static TxBuf, +} + +impl<'d, const TX_BUF_SIZE: usize> BufferedCanTx<'d, TX_BUF_SIZE> { + fn new(info: &'static Info, state: &'static State, _tx: CanTx<'d>, tx_buf: &'static TxBuf) -> Self { + Self { + info, + state, + _tx, + tx_buf, + } + .setup() + } + + fn setup(self) -> Self { + // We don't want interrupts being processed while we change modes. + critical_section::with(|_| { + let tx_inner = super::common::ClassicBufferedTxInner { + tx_receiver: self.tx_buf.receiver().into(), + }; + let state = self.state as *const State; + unsafe { + let mut_state = state as *mut State; + (*mut_state).tx_mode = TxMode::Buffered(tx_inner); + } + }); + self + } + + /// Async write frame to TX buffer. + pub async fn write(&mut self, frame: &Frame) { + self.tx_buf.send(*frame).await; + let waker = self.info.tx_waker; + waker(); // Wake for Tx + } + + /// Returns a sender that can be used for sending CAN frames. + pub fn writer(&self) -> BufferedCanSender { + BufferedCanSender { + tx_buf: self.tx_buf.sender().into(), + waker: self.info.tx_waker, + } + } +} + +impl<'d, const TX_BUF_SIZE: usize> Drop for BufferedCanTx<'d, TX_BUF_SIZE> { + fn drop(&mut self) { + critical_section::with(|_| { + let state = self.state as *const State; + unsafe { + let mut_state = state as *mut State; + (*mut_state).tx_mode = TxMode::NonBuffered(embassy_sync::waitqueue::AtomicWaker::new()); + } + }); + } +} + +/// CAN driver, receive half. +#[allow(dead_code)] +pub struct CanRx<'d> { + _phantom: PhantomData<&'d ()>, + info: &'static Info, + state: &'static State, +} + +impl<'d> CanRx<'d> { + /// Read a CAN frame. + /// + /// If no CAN frame is in the RX buffer, this will wait until there is one. + /// + /// Returns a tuple of the time the message was received and the message frame + pub async fn read(&mut self) -> Result { + self.state.rx_mode.read(self.info, self.state).await + } + + /// Attempts to read a CAN frame without blocking. + /// + /// Returns [Err(TryReadError::Empty)] if there are no frames in the rx queue. + pub fn try_read(&mut self) -> Result { + self.state.rx_mode.try_read(self.info) + } + + /// Waits while receive queue is empty. + pub async fn wait_not_empty(&mut self) { + self.state.rx_mode.wait_not_empty(self.info, self.state).await + } + + /// Return a buffered instance of driver. User must supply Buffers + pub fn buffered( + self, + rxb: &'static mut RxBuf, + ) -> BufferedCanRx<'d, RX_BUF_SIZE> { + BufferedCanRx::new(self.info, self.state, self, rxb) + } +} + +/// User supplied buffer for RX Buffering +pub type RxBuf = Channel, BUF_SIZE>; + +/// CAN driver, receive half in Buffered mode. +pub struct BufferedCanRx<'d, const RX_BUF_SIZE: usize> { + info: &'static Info, + state: &'static State, + _rx: CanRx<'d>, + rx_buf: &'static RxBuf, +} + +impl<'d, const RX_BUF_SIZE: usize> BufferedCanRx<'d, RX_BUF_SIZE> { + fn new(info: &'static Info, state: &'static State, _rx: CanRx<'d>, rx_buf: &'static RxBuf) -> Self { + BufferedCanRx { + info, + state, + _rx, + rx_buf, + } + .setup() + } + + fn setup(self) -> Self { + // We don't want interrupts being processed while we change modes. + critical_section::with(|_| { + let rx_inner = super::common::ClassicBufferedRxInner { + rx_sender: self.rx_buf.sender().into(), + }; + let state = self.state as *const State; + unsafe { + let mut_state = state as *mut State; + (*mut_state).rx_mode = RxMode::Buffered(rx_inner); + } + }); + self + } + + /// Async read frame from RX buffer. + pub async fn read(&mut self) -> Result { + self.rx_buf.receive().await + } + + /// Attempts to read a CAN frame without blocking. + /// + /// Returns [Err(TryReadError::Empty)] if there are no frames in the rx queue. + pub fn try_read(&mut self) -> Result { + match &self.state.rx_mode { + RxMode::Buffered(_) => { + if let Ok(result) = self.rx_buf.try_receive() { + match result { + Ok(envelope) => Ok(envelope), + Err(e) => Err(TryReadError::BusError(e)), + } + } else { + if let Some(err) = self.info.regs.curr_error() { + return Err(TryReadError::BusError(err)); + } else { + Err(TryReadError::Empty) + } + } + } + _ => { + panic!("Bad Mode") + } + } + } + + /// Waits while receive queue is empty. + pub async fn wait_not_empty(&mut self) { + poll_fn(|cx| self.rx_buf.poll_ready_to_receive(cx)).await + } + + /// Returns a receiver that can be used for receiving CAN frames. Note, each CAN frame will only be received by one receiver. + pub fn reader(&self) -> BufferedCanReceiver { + self.rx_buf.receiver().into() + } +} + +impl<'d, const RX_BUF_SIZE: usize> Drop for BufferedCanRx<'d, RX_BUF_SIZE> { + fn drop(&mut self) { + critical_section::with(|_| { + let state = self.state as *const State; + unsafe { + let mut_state = state as *mut State; + (*mut_state).rx_mode = RxMode::NonBuffered(embassy_sync::waitqueue::AtomicWaker::new()); + } + }); + } +} + +impl Drop for Can<'_> { + fn drop(&mut self) { + // Cannot call `free()` because it moves the instance. + // Manually reset the peripheral. + self.info.regs.0.mcr().write(|w| w.set_reset(true)); + self.info.regs.enter_init_mode(); + self.info.regs.leave_init_mode(); + //rcc::disable::(); + } +} + +/// Identifies one of the two receive FIFOs. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Fifo { + /// First receive FIFO + Fifo0 = 0, + /// Second receive FIFO + Fifo1 = 1, +} + +/// Identifies one of the three transmit mailboxes. +#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Mailbox { + /// Transmit mailbox 0 + Mailbox0 = 0, + /// Transmit mailbox 1 + Mailbox1 = 1, + /// Transmit mailbox 2 + Mailbox2 = 2, +} + +/// Contains information about a frame enqueued for transmission via [`Can::transmit`] or +/// [`Tx::transmit`]. +pub struct TransmitStatus { + dequeued_frame: Option, + mailbox: Mailbox, +} + +impl TransmitStatus { + /// Returns the lower-priority frame that was dequeued to make space for the new frame. + #[inline] + pub fn dequeued_frame(&self) -> Option<&Frame> { + self.dequeued_frame.as_ref() + } + + /// Returns the [`Mailbox`] the frame was enqueued in. + #[inline] + pub fn mailbox(&self) -> Mailbox { + self.mailbox + } +} + +pub(crate) enum RxMode { + NonBuffered(AtomicWaker), + Buffered(super::common::ClassicBufferedRxInner), +} + +impl RxMode { + pub fn on_interrupt(&self, fifo: RxFifo) { + match self { + Self::NonBuffered(waker) => { + // Disable interrupts until read + let fifo_idx = match fifo { + RxFifo::Fifo0 => 0usize, + RxFifo::Fifo1 => 1usize, + }; + T::regs().ier().modify(|w| { + w.set_fmpie(fifo_idx, false); + }); + waker.wake(); + } + Self::Buffered(buf) => { + loop { + match Registers(T::regs()).receive_fifo(fifo) { + Some(envelope) => { + // NOTE: consensus was reached that if rx_queue is full, packets should be dropped + let _ = buf.rx_sender.try_send(Ok(envelope)); + } + None => return, + }; + } + } + } + } + + pub(crate) async fn read(&self, info: &Info, state: &State) -> Result { + match self { + Self::NonBuffered(waker) => { + poll_fn(|cx| { + state.err_waker.register(cx.waker()); + waker.register(cx.waker()); + match self.try_read(info) { + Ok(result) => Poll::Ready(Ok(result)), + Err(TryReadError::Empty) => Poll::Pending, + Err(TryReadError::BusError(be)) => Poll::Ready(Err(be)), + } + }) + .await + } + _ => { + panic!("Bad Mode") + } + } + } + pub(crate) fn try_read(&self, info: &Info) -> Result { + match self { + Self::NonBuffered(_) => { + let registers = &info.regs; + if let Some(msg) = registers.receive_fifo(RxFifo::Fifo0) { + registers.0.ier().modify(|w| { + w.set_fmpie(0, true); + }); + Ok(msg) + } else if let Some(msg) = registers.receive_fifo(RxFifo::Fifo1) { + registers.0.ier().modify(|w| { + w.set_fmpie(1, true); + }); + Ok(msg) + } else if let Some(err) = registers.curr_error() { + Err(TryReadError::BusError(err)) + } else { + registers.0.ier().modify(|w| { + w.set_fmpie(0, true); + w.set_fmpie(1, true); + }); + Err(TryReadError::Empty) + } + } + _ => { + panic!("Bad Mode") + } + } + } + pub(crate) async fn wait_not_empty(&self, info: &Info, state: &State) { + match &state.rx_mode { + Self::NonBuffered(waker) => { + poll_fn(|cx| { + waker.register(cx.waker()); + if info.regs.receive_frame_available() { + Poll::Ready(()) + } else { + Poll::Pending + } + }) + .await + } + _ => { + panic!("Bad Mode") + } + } + } +} + +pub(crate) enum TxMode { + NonBuffered(AtomicWaker), + Buffered(super::common::ClassicBufferedTxInner), +} + +impl TxMode { + pub fn buffer_free(&self) -> bool { + let tsr = T::regs().tsr().read(); + tsr.tme(Mailbox::Mailbox0.index()) || tsr.tme(Mailbox::Mailbox1.index()) || tsr.tme(Mailbox::Mailbox2.index()) + } + pub fn on_interrupt(&self) { + match &T::state().tx_mode { + TxMode::NonBuffered(waker) => waker.wake(), + TxMode::Buffered(buf) => { + while self.buffer_free::() { + match buf.tx_receiver.try_receive() { + Ok(frame) => { + _ = Registers(T::regs()).transmit(&frame); + } + Err(_) => { + break; + } + } + } + } + } + } + + fn register(&self, arg: &core::task::Waker) { + match self { + TxMode::NonBuffered(waker) => { + waker.register(arg); + } + _ => { + panic!("Bad mode"); + } + } + } +} + +pub(crate) struct State { + pub(crate) rx_mode: RxMode, + pub(crate) tx_mode: TxMode, + pub err_waker: AtomicWaker, +} + +impl State { + pub const fn new() -> Self { + Self { + rx_mode: RxMode::NonBuffered(AtomicWaker::new()), + tx_mode: TxMode::NonBuffered(AtomicWaker::new()), + err_waker: AtomicWaker::new(), + } + } +} + +pub(crate) struct Info { + regs: Registers, + tx_interrupt: crate::interrupt::Interrupt, + rx0_interrupt: crate::interrupt::Interrupt, + rx1_interrupt: crate::interrupt::Interrupt, + sce_interrupt: crate::interrupt::Interrupt, + tx_waker: fn(), + + /// The total number of filter banks available to the instance. + /// + /// This is usually either 14 or 28, and should be specified in the chip's reference manual or datasheet. + num_filter_banks: u8, +} + +trait SealedInstance { + fn info() -> &'static Info; + fn regs() -> crate::pac::can::Can; + fn state() -> &'static State; + unsafe fn mut_state() -> &'static mut State; +} + +/// CAN instance trait. +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + RccPeripheral + 'static { + /// TX interrupt for this instance. + type TXInterrupt: crate::interrupt::typelevel::Interrupt; + /// RX0 interrupt for this instance. + type RX0Interrupt: crate::interrupt::typelevel::Interrupt; + /// RX1 interrupt for this instance. + type RX1Interrupt: crate::interrupt::typelevel::Interrupt; + /// SCE interrupt for this instance. + type SCEInterrupt: crate::interrupt::typelevel::Interrupt; +} + +/// A bxCAN instance that owns filter banks. +/// +/// In master-slave-instance setups, only the master instance owns the filter banks, and needs to +/// split some of them off for use by the slave instance. In that case, the master instance should +/// implement [`FilterOwner`] and [`MasterInstance`], while the slave instance should only implement +/// [`Instance`]. +/// +/// In single-instance configurations, the instance owns all filter banks and they can not be split +/// off. In that case, the instance should implement [`Instance`] and [`FilterOwner`]. +/// +/// # Safety +/// +/// This trait must only be implemented if the instance does, in fact, own its associated filter +/// banks, and `NUM_FILTER_BANKS` must be correct. +pub unsafe trait FilterOwner: Instance { + /// The total number of filter banks available to the instance. + /// + /// This is usually either 14 or 28, and should be specified in the chip's reference manual or datasheet. + const NUM_FILTER_BANKS: u8; +} + +/// A bxCAN master instance that shares filter banks with a slave instance. +/// +/// In master-slave-instance setups, this trait should be implemented for the master instance. +/// +/// # Safety +/// +/// This trait must only be implemented when there is actually an associated slave instance. +pub unsafe trait MasterInstance: FilterOwner {} + +foreach_peripheral!( + (can, $inst:ident) => { + impl SealedInstance for peripherals::$inst { + + fn info() -> &'static Info { + static INFO: Info = Info { + regs: Registers(crate::pac::$inst), + tx_interrupt: crate::_generated::peripheral_interrupts::$inst::TX::IRQ, + rx0_interrupt: crate::_generated::peripheral_interrupts::$inst::RX0::IRQ, + rx1_interrupt: crate::_generated::peripheral_interrupts::$inst::RX1::IRQ, + sce_interrupt: crate::_generated::peripheral_interrupts::$inst::SCE::IRQ, + tx_waker: crate::_generated::peripheral_interrupts::$inst::TX::pend, + num_filter_banks: peripherals::$inst::NUM_FILTER_BANKS, + }; + &INFO + } + fn regs() -> crate::pac::can::Can { + crate::pac::$inst + } + + unsafe fn mut_state() -> & 'static mut State { + static mut STATE: State = State::new(); + &mut *core::ptr::addr_of_mut!(STATE) + } + fn state() -> &'static State { + unsafe { peripherals::$inst::mut_state() } + } + } + + impl Instance for peripherals::$inst { + type TXInterrupt = crate::_generated::peripheral_interrupts::$inst::TX; + type RX0Interrupt = crate::_generated::peripheral_interrupts::$inst::RX0; + type RX1Interrupt = crate::_generated::peripheral_interrupts::$inst::RX1; + type SCEInterrupt = crate::_generated::peripheral_interrupts::$inst::SCE; + } + }; +); + +foreach_peripheral!( + (can, CAN) => { + unsafe impl FilterOwner for peripherals::CAN { + const NUM_FILTER_BANKS: u8 = 14; + } + }; + // CAN1 and CAN2 is a combination of master and slave instance. + // CAN1 owns the filter bank and needs to be enabled in order + // for CAN2 to receive messages. + (can, CAN1) => { + cfg_if::cfg_if! { + if #[cfg(all( + any(stm32l4, stm32f72x, stm32f73x), + not(any(stm32l49x, stm32l4ax)) + ))] { + // Most L4 devices and some F7 devices use the name "CAN1" + // even if there is no "CAN2" peripheral. + unsafe impl FilterOwner for peripherals::CAN1 { + const NUM_FILTER_BANKS: u8 = 14; + } + } else { + unsafe impl FilterOwner for peripherals::CAN1 { + const NUM_FILTER_BANKS: u8 = 28; + } + unsafe impl MasterInstance for peripherals::CAN1 {} + } + } + }; + (can, CAN2) => { + unsafe impl FilterOwner for peripherals::CAN2 { + const NUM_FILTER_BANKS: u8 = 0; + } + }; + (can, CAN3) => { + unsafe impl FilterOwner for peripherals::CAN3 { + const NUM_FILTER_BANKS: u8 = 14; + } + }; +); + +pin_trait!(RxPin, Instance); +pin_trait!(TxPin, Instance); + +trait Index { + fn index(&self) -> usize; +} + +impl Index for Mailbox { + fn index(&self) -> usize { + match self { + Mailbox::Mailbox0 => 0, + Mailbox::Mailbox1 => 1, + Mailbox::Mailbox2 => 2, + } + } +} diff --git a/embassy-stm32/src/can/bxcan/registers.rs b/embassy-stm32/src/can/bxcan/registers.rs new file mode 100644 index 000000000..9798a058b --- /dev/null +++ b/embassy-stm32/src/can/bxcan/registers.rs @@ -0,0 +1,560 @@ +use core::cmp::Ordering; +use core::convert::Infallible; + +pub use embedded_can::{ExtendedId, Id, StandardId}; +use stm32_metapac::can::vals::{Lec, Rtr}; + +use super::{Mailbox, TransmitStatus}; +use crate::can::enums::BusError; +use crate::can::frame::{Envelope, Frame, Header}; + +pub(crate) struct Registers(pub crate::pac::can::Can); + +impl Registers { + pub fn enter_init_mode(&self) { + self.0.mcr().modify(|reg| { + reg.set_sleep(false); + reg.set_inrq(true); + }); + loop { + let msr = self.0.msr().read(); + if !msr.slak() && msr.inak() { + break; + } + } + } + + // Leaves initialization mode, enters sleep mode. + pub fn leave_init_mode(&self) { + self.0.mcr().modify(|reg| { + reg.set_sleep(true); + reg.set_inrq(false); + }); + loop { + let msr = self.0.msr().read(); + if msr.slak() && !msr.inak() { + break; + } + } + } + + pub fn set_bit_timing(&self, bt: crate::can::util::NominalBitTiming) { + let prescaler = u16::from(bt.prescaler) & 0x1FF; + let seg1 = u8::from(bt.seg1); + let seg2 = u8::from(bt.seg2) & 0x7F; + let sync_jump_width = u8::from(bt.sync_jump_width) & 0x7F; + self.0.btr().modify(|reg| { + reg.set_brp(prescaler - 1); + reg.set_ts(0, seg1 - 1); + reg.set_ts(1, seg2 - 1); + reg.set_sjw(sync_jump_width - 1); + }); + } + + /// Enables or disables silent mode: Disconnects the TX signal from the pin. + pub fn set_silent(&self, enabled: bool) { + let mode = match enabled { + false => stm32_metapac::can::vals::Silm::NORMAL, + true => stm32_metapac::can::vals::Silm::SILENT, + }; + self.0.btr().modify(|reg| reg.set_silm(mode)); + } + + /// Enables or disables automatic retransmission of messages. + /// + /// If this is enabled, the CAN peripheral will automatically try to retransmit each frame + /// until it can be sent. Otherwise, it will try only once to send each frame. + /// + /// Automatic retransmission is enabled by default. + pub fn set_automatic_retransmit(&self, enabled: bool) { + self.0.mcr().modify(|reg| reg.set_nart(enabled)); + } + + /// Enables or disables loopback mode: Internally connects the TX and RX + /// signals together. + pub fn set_loopback(&self, enabled: bool) { + self.0.btr().modify(|reg| reg.set_lbkm(enabled)); + } + + /// Configures the automatic wake-up feature. + /// + /// This is turned off by default. + /// + /// When turned on, an incoming frame will cause the peripheral to wake up from sleep and + /// receive the frame. If enabled, [`Interrupt::Wakeup`] will also be triggered by the incoming + /// frame. + #[allow(dead_code)] + pub fn set_automatic_wakeup(&self, enabled: bool) { + self.0.mcr().modify(|reg| reg.set_awum(enabled)); + } + + /// Leaves initialization mode and enables the peripheral (non-blocking version). + /// + /// Usually, it is recommended to call [`CanConfig::enable`] instead. This method is only needed + /// if you want non-blocking initialization. + /// + /// If this returns [`WouldBlock`][nb::Error::WouldBlock], the peripheral will enable itself + /// in the background. The peripheral is enabled and ready to use when this method returns + /// successfully. + pub fn enable_non_blocking(&self) -> nb::Result<(), Infallible> { + let msr = self.0.msr().read(); + if msr.slak() { + self.0.mcr().modify(|reg| { + reg.set_abom(true); + reg.set_sleep(false); + }); + Err(nb::Error::WouldBlock) + } else { + Ok(()) + } + } + + /// Puts the peripheral in a sleep mode to save power. + /// + /// While in sleep mode, an incoming CAN frame will trigger [`Interrupt::Wakeup`] if enabled. + #[allow(dead_code)] + pub fn sleep(&mut self) { + self.0.mcr().modify(|reg| { + reg.set_sleep(true); + reg.set_inrq(false); + }); + loop { + let msr = self.0.msr().read(); + if msr.slak() && !msr.inak() { + break; + } + } + } + + /// Wakes up from sleep mode. + /// + /// Note that this will not trigger [`Interrupt::Wakeup`], only reception of an incoming CAN + /// frame will cause that interrupt. + #[allow(dead_code)] + pub fn wakeup(&self) { + self.0.mcr().modify(|reg| { + reg.set_sleep(false); + reg.set_inrq(false); + }); + loop { + let msr = self.0.msr().read(); + if !msr.slak() && !msr.inak() { + break; + } + } + } + + pub fn curr_error(&self) -> Option { + if !self.0.msr().read().erri() { + // This ensures that once a single error instance has + // been acknowledged and forwared to the bus message consumer + // we don't continue to re-forward the same error occurrance for an + // in-definite amount of time. + return None; + } + + // Since we have not already acknowledge the error, and the interrupt was + // disabled in the ISR, we will acknowledge the current error and re-enable the interrupt + // so futher errors are captured + self.0.msr().modify(|m| m.set_erri(true)); + self.0.ier().modify(|i| i.set_errie(true)); + + let err = self.0.esr().read(); + if err.boff() { + return Some(BusError::BusOff); + } else if err.epvf() { + return Some(BusError::BusPassive); + } else if err.ewgf() { + return Some(BusError::BusWarning); + } else if err.lec() != Lec::NOERROR { + return Some(match err.lec() { + Lec::STUFF => BusError::Stuff, + Lec::FORM => BusError::Form, + Lec::ACK => BusError::Acknowledge, + Lec::BITRECESSIVE => BusError::BitRecessive, + Lec::BITDOMINANT => BusError::BitDominant, + Lec::CRC => BusError::Crc, + Lec::CUSTOM => BusError::Software, + Lec::NOERROR => unreachable!(), + }); + } + None + } + + /// Enables or disables FIFO scheduling of outgoing mailboxes. + /// + /// If this is enabled, mailboxes are scheduled based on the time when the transmit request bit of the mailbox was set. + /// + /// If this is disabled, mailboxes are scheduled based on the priority of the frame in the mailbox. + pub fn set_tx_fifo_scheduling(&self, enabled: bool) { + self.0.mcr().modify(|w| w.set_txfp(enabled)) + } + + /// Checks if FIFO scheduling of outgoing mailboxes is enabled. + pub fn tx_fifo_scheduling_enabled(&self) -> bool { + self.0.mcr().read().txfp() + } + + /// Puts a CAN frame in a transmit mailbox for transmission on the bus. + /// + /// The behavior of this function depends on wheter or not FIFO scheduling is enabled. + /// See [`Self::set_tx_fifo_scheduling()`] and [`Self::tx_fifo_scheduling_enabled()`]. + /// + /// # Priority based scheduling + /// + /// If FIFO scheduling is disabled, frames are transmitted to the bus based on their + /// priority (see [`FramePriority`]). Transmit order is preserved for frames with identical + /// priority. + /// + /// If all transmit mailboxes are full, and `frame` has a higher priority than the + /// lowest-priority message in the transmit mailboxes, transmission of the enqueued frame is + /// cancelled and `frame` is enqueued instead. The frame that was replaced is returned as + /// [`TransmitStatus::dequeued_frame`]. + /// + /// # FIFO scheduling + /// + /// If FIFO scheduling is enabled, frames are transmitted in the order that they are passed to this function. + /// + /// If all transmit mailboxes are full, this function returns [`nb::Error::WouldBlock`]. + pub fn transmit(&self, frame: &Frame) -> nb::Result { + // Check if FIFO scheduling is enabled. + let fifo_scheduling = self.0.mcr().read().txfp(); + + // Get the index of the next free mailbox or the one with the lowest priority. + let tsr = self.0.tsr().read(); + let idx = tsr.code() as usize; + + let frame_is_pending = !tsr.tme(0) || !tsr.tme(1) || !tsr.tme(2); + let all_frames_are_pending = !tsr.tme(0) && !tsr.tme(1) && !tsr.tme(2); + + let pending_frame; + if fifo_scheduling && all_frames_are_pending { + // FIFO scheduling is enabled and all mailboxes are full. + // We will not drop a lower priority frame, we just report WouldBlock. + return Err(nb::Error::WouldBlock); + } else if !fifo_scheduling && frame_is_pending { + // Priority scheduling is enabled and alteast one mailbox is full. + // + // In this mode, the peripheral transmits high priority frames first. + // Frames with identical priority should be transmitted in FIFO order, + // but the controller schedules pending frames of same priority based on the + // mailbox index. As a workaround check all pending mailboxes and only accept + // frames with a different priority. + self.check_priority(0, frame.id().into())?; + self.check_priority(1, frame.id().into())?; + self.check_priority(2, frame.id().into())?; + + if all_frames_are_pending { + // No free mailbox is available. This can only happen when three frames with + // ascending priority (descending IDs) were requested for transmission and all + // of them are blocked by bus traffic with even higher priority. + // To prevent a priority inversion abort and replace the lowest priority frame. + pending_frame = self.read_pending_mailbox(idx); + } else { + // There was a free mailbox. + pending_frame = None; + } + } else { + // Either we have FIFO scheduling and at-least one free mailbox, + // or we have priority scheduling and all mailboxes are free. + // No further checks are needed. + pending_frame = None + } + + self.write_mailbox(idx, frame); + + let mailbox = match idx { + 0 => Mailbox::Mailbox0, + 1 => Mailbox::Mailbox1, + 2 => Mailbox::Mailbox2, + _ => unreachable!(), + }; + Ok(TransmitStatus { + dequeued_frame: pending_frame, + mailbox, + }) + } + + /// Returns `Ok` when the mailbox is free or if it contains pending frame with a + /// different priority from the identifier `id`. + fn check_priority(&self, idx: usize, id: IdReg) -> nb::Result<(), Infallible> { + // Read the pending frame's id to check its priority. + assert!(idx < 3); + let tir = &self.0.tx(idx).tir().read(); + + // Check the priority by comparing the identifiers. But first make sure the + // frame has not finished the transmission (`TXRQ` == 0) in the meantime. + if tir.txrq() && id == IdReg::from_register(tir.0) { + // There's a mailbox whose priority is equal to the priority of the new frame. + return Err(nb::Error::WouldBlock); + } + + Ok(()) + } + + fn write_mailbox(&self, idx: usize, frame: &Frame) { + debug_assert!(idx < 3); + + let mb = self.0.tx(idx); + mb.tdtr().write(|w| w.set_dlc(frame.header().len() as u8)); + + mb.tdlr() + .write(|w| w.0 = u32::from_ne_bytes(unwrap!(frame.data()[0..4].try_into()))); + mb.tdhr() + .write(|w| w.0 = u32::from_ne_bytes(unwrap!(frame.data()[4..8].try_into()))); + let id: IdReg = frame.id().into(); + mb.tir().write(|w| { + w.0 = id.0; + w.set_txrq(true); + if frame.header().rtr() { + w.set_rtr(Rtr::REMOTE); + } + }); + } + + fn read_pending_mailbox(&self, idx: usize) -> Option { + if self.abort_by_index(idx) { + debug_assert!(idx < 3); + + let mb = self.0.tx(idx); + + let id = IdReg(mb.tir().read().0); + let mut data = [0xff; 8]; + data[0..4].copy_from_slice(&mb.tdlr().read().0.to_ne_bytes()); + data[4..8].copy_from_slice(&mb.tdhr().read().0.to_ne_bytes()); + let len = mb.tdtr().read().dlc(); + + Some(unwrap!(Frame::new(Header::new(id.id(), len, id.rtr()), &data))) + } else { + // Abort request failed because the frame was already sent (or being sent) on + // the bus. All mailboxes are now free. This can happen for small prescaler + // values (e.g. 1MBit/s bit timing with a source clock of 8MHz) or when an ISR + // has preempted the execution. + None + } + } + + /// Tries to abort a pending frame. Returns `true` when aborted. + fn abort_by_index(&self, idx: usize) -> bool { + self.0.tsr().write(|reg| reg.set_abrq(idx, true)); + + // Wait for the abort request to be finished. + loop { + let tsr = self.0.tsr().read(); + if false == tsr.abrq(idx) { + break tsr.txok(idx) == false; + } + } + } + + /// Attempts to abort the sending of a frame that is pending in a mailbox. + /// + /// If there is no frame in the provided mailbox, or its transmission succeeds before it can be + /// aborted, this function has no effect and returns `false`. + /// + /// If there is a frame in the provided mailbox, and it is canceled successfully, this function + /// returns `true`. + pub fn abort(&self, mailbox: Mailbox) -> bool { + // If the mailbox is empty, the value of TXOKx depends on what happened with the previous + // frame in that mailbox. Only call abort_by_index() if the mailbox is not empty. + let tsr = self.0.tsr().read(); + let mailbox_empty = match mailbox { + Mailbox::Mailbox0 => tsr.tme(0), + Mailbox::Mailbox1 => tsr.tme(1), + Mailbox::Mailbox2 => tsr.tme(2), + }; + if mailbox_empty { + false + } else { + self.abort_by_index(mailbox as usize) + } + } + + /// Returns `true` if no frame is pending for transmission. + pub fn is_idle(&self) -> bool { + let tsr = self.0.tsr().read(); + tsr.tme(0) && tsr.tme(1) && tsr.tme(2) + } + + pub fn receive_frame_available(&self) -> bool { + if self.0.rfr(0).read().fmp() != 0 { + true + } else if self.0.rfr(1).read().fmp() != 0 { + true + } else { + false + } + } + + pub fn receive_fifo(&self, fifo: RxFifo) -> Option { + // Generate timestamp as early as possible + #[cfg(feature = "time")] + let ts = embassy_time::Instant::now(); + + use crate::pac::can::vals::Ide; + + let fifo_idx = match fifo { + RxFifo::Fifo0 => 0usize, + RxFifo::Fifo1 => 1usize, + }; + let rfr = self.0.rfr(fifo_idx); + let fifo = self.0.rx(fifo_idx); + + // If there are no pending messages, there is nothing to do + if rfr.read().fmp() == 0 { + return None; + } + + let rir = fifo.rir().read(); + let id: embedded_can::Id = if rir.ide() == Ide::STANDARD { + unwrap!(embedded_can::StandardId::new(rir.stid())).into() + } else { + let stid = (rir.stid() & 0x7FF) as u32; + let exid = rir.exid() & 0x3FFFF; + let id = (stid << 18) | (exid); + unwrap!(embedded_can::ExtendedId::new(id)).into() + }; + let rdtr = fifo.rdtr().read(); + let data_len = rdtr.dlc(); + let rtr = rir.rtr() == stm32_metapac::can::vals::Rtr::REMOTE; + + #[cfg(not(feature = "time"))] + let ts = rdtr.time(); + + let mut data: [u8; 8] = [0; 8]; + data[0..4].copy_from_slice(&fifo.rdlr().read().0.to_ne_bytes()); + data[4..8].copy_from_slice(&fifo.rdhr().read().0.to_ne_bytes()); + + let frame = unwrap!(Frame::new(Header::new(id, data_len, rtr), &data)); + let envelope = Envelope { ts, frame }; + + rfr.modify(|v| v.set_rfom(true)); + + Some(envelope) + } +} + +/// Identifier of a CAN message. +/// +/// Can be either a standard identifier (11bit, Range: 0..0x3FF) or a +/// extendended identifier (29bit , Range: 0..0x1FFFFFFF). +/// +/// The `Ord` trait can be used to determine the frame’s priority this ID +/// belongs to. +/// Lower identifier values have a higher priority. Additionally standard frames +/// have a higher priority than extended frames and data frames have a higher +/// priority than remote frames. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub(crate) struct IdReg(u32); + +impl IdReg { + const STANDARD_SHIFT: u32 = 21; + + const EXTENDED_SHIFT: u32 = 3; + + const IDE_MASK: u32 = 0x0000_0004; + + const RTR_MASK: u32 = 0x0000_0002; + + /// Creates a new standard identifier (11bit, Range: 0..0x7FF) + /// + /// Panics for IDs outside the allowed range. + fn new_standard(id: StandardId) -> Self { + Self(u32::from(id.as_raw()) << Self::STANDARD_SHIFT) + } + + /// Creates a new extendended identifier (29bit , Range: 0..0x1FFFFFFF). + /// + /// Panics for IDs outside the allowed range. + fn new_extended(id: ExtendedId) -> IdReg { + Self(id.as_raw() << Self::EXTENDED_SHIFT | Self::IDE_MASK) + } + + fn from_register(reg: u32) -> IdReg { + Self(reg & 0xFFFF_FFFE) + } + + /// Returns the identifier. + fn to_id(self) -> Id { + if self.is_extended() { + Id::Extended(unsafe { ExtendedId::new_unchecked(self.0 >> Self::EXTENDED_SHIFT) }) + } else { + Id::Standard(unsafe { StandardId::new_unchecked((self.0 >> Self::STANDARD_SHIFT) as u16) }) + } + } + + /// Returns the identifier. + fn id(self) -> embedded_can::Id { + if self.is_extended() { + unwrap!(embedded_can::ExtendedId::new(self.0 >> Self::EXTENDED_SHIFT)).into() + } else { + unwrap!(embedded_can::StandardId::new((self.0 >> Self::STANDARD_SHIFT) as u16)).into() + } + } + + /// Returns `true` if the identifier is an extended identifier. + fn is_extended(self) -> bool { + self.0 & Self::IDE_MASK != 0 + } + + /// Returns `true` if the identifer is part of a remote frame (RTR bit set). + fn rtr(self) -> bool { + self.0 & Self::RTR_MASK != 0 + } +} + +impl From<&embedded_can::Id> for IdReg { + fn from(eid: &embedded_can::Id) -> Self { + match eid { + embedded_can::Id::Standard(id) => IdReg::new_standard(StandardId::new(id.as_raw()).unwrap()), + embedded_can::Id::Extended(id) => IdReg::new_extended(ExtendedId::new(id.as_raw()).unwrap()), + } + } +} + +impl From for embedded_can::Id { + fn from(idr: IdReg) -> Self { + idr.id() + } +} + +/// `IdReg` is ordered by priority. +impl Ord for IdReg { + fn cmp(&self, other: &Self) -> Ordering { + // When the IDs match, data frames have priority over remote frames. + let rtr = self.rtr().cmp(&other.rtr()).reverse(); + + let id_a = self.to_id(); + let id_b = other.to_id(); + match (id_a, id_b) { + (Id::Standard(a), Id::Standard(b)) => { + // Lower IDs have priority over higher IDs. + a.as_raw().cmp(&b.as_raw()).reverse().then(rtr) + } + (Id::Extended(a), Id::Extended(b)) => a.as_raw().cmp(&b.as_raw()).reverse().then(rtr), + (Id::Standard(a), Id::Extended(b)) => { + // Standard frames have priority over extended frames if their Base IDs match. + a.as_raw() + .cmp(&b.standard_id().as_raw()) + .reverse() + .then(Ordering::Greater) + } + (Id::Extended(a), Id::Standard(b)) => { + a.standard_id().as_raw().cmp(&b.as_raw()).reverse().then(Ordering::Less) + } + } + } +} + +impl PartialOrd for IdReg { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub(crate) enum RxFifo { + Fifo0, + Fifo1, +} diff --git a/embassy-stm32/src/can/common.rs b/embassy-stm32/src/can/common.rs new file mode 100644 index 000000000..a54b54f6e --- /dev/null +++ b/embassy-stm32/src/can/common.rs @@ -0,0 +1,52 @@ +use embassy_sync::channel::{DynamicReceiver, DynamicSender}; + +use super::enums::*; +use super::frame::*; + +pub(crate) struct ClassicBufferedRxInner { + pub rx_sender: DynamicSender<'static, Result>, +} +pub(crate) struct ClassicBufferedTxInner { + pub tx_receiver: DynamicReceiver<'static, Frame>, +} + +#[cfg(any(can_fdcan_v1, can_fdcan_h7))] + +pub(crate) struct FdBufferedRxInner { + pub rx_sender: DynamicSender<'static, Result>, +} + +#[cfg(any(can_fdcan_v1, can_fdcan_h7))] +pub(crate) struct FdBufferedTxInner { + pub tx_receiver: DynamicReceiver<'static, FdFrame>, +} + +/// Sender that can be used for sending CAN frames. +#[derive(Copy, Clone)] +pub struct BufferedCanSender { + pub(crate) tx_buf: embassy_sync::channel::DynamicSender<'static, Frame>, + pub(crate) waker: fn(), +} + +impl BufferedCanSender { + /// Async write frame to TX buffer. + pub fn try_write(&mut self, frame: Frame) -> Result<(), embassy_sync::channel::TrySendError> { + self.tx_buf.try_send(frame)?; + (self.waker)(); + Ok(()) + } + + /// Async write frame to TX buffer. + pub async fn write(&mut self, frame: Frame) { + self.tx_buf.send(frame).await; + (self.waker)(); + } + + /// Allows a poll_fn to poll until the channel is ready to write + pub fn poll_ready_to_send(&self, cx: &mut core::task::Context<'_>) -> core::task::Poll<()> { + self.tx_buf.poll_ready_to_send(cx) + } +} + +/// Receiver that can be used for receiving CAN frames. Note, each CAN frame will only be received by one receiver. +pub type BufferedCanReceiver = embassy_sync::channel::DynamicReceiver<'static, Result>; diff --git a/embassy-stm32/src/can/enums.rs b/embassy-stm32/src/can/enums.rs index 36139a45c..a5cca424d 100644 --- a/embassy-stm32/src/can/enums.rs +++ b/embassy-stm32/src/can/enums.rs @@ -28,3 +28,43 @@ pub enum BusError { /// At least one of error counter has reached the Error_Warning limit of 96. BusWarning, } + +/// Bus error modes. +/// +/// Contrary to the `BusError` enum which also includes last-seen acute protocol +/// errors, this enum includes only the mutually exclusive bus error modes. +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum BusErrorMode { + /// Error active mode (default). Controller will transmit an active error + /// frame upon protocol error. + ErrorActive, + /// Error passive mode. An error counter exceeded 127. Controller will + /// transmit a passive error frame upon protocol error. + ErrorPassive, + /// Bus off mode. The transmit error counter exceeded 255. Controller is not + /// participating in bus traffic. + BusOff, +} + +/// Frame Create Errors +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum FrameCreateError { + /// Data in header does not match supplied. + NotEnoughData, + /// Invalid data length not 0-8 for Classic packet or valid for FD. + InvalidDataLength, + /// Invalid ID. + InvalidCanId, +} + +/// Error returned by `try_read` +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum TryReadError { + /// Bus error + BusError(BusError), + /// Receive buffer is empty + Empty, +} diff --git a/embassy-stm32/src/can/fd/config.rs b/embassy-stm32/src/can/fd/config.rs new file mode 100644 index 000000000..68161ca50 --- /dev/null +++ b/embassy-stm32/src/can/fd/config.rs @@ -0,0 +1,475 @@ +//! Configuration for FDCAN Module +// Note: This file is copied and modified from fdcan crate by Richard Meadows + +use core::num::{NonZeroU16, NonZeroU8}; + +/// Configures the bit timings. +/// +/// You can use to calculate the `btr` parameter. Enter +/// parameters as follows: +/// +/// - *Clock Rate*: The input clock speed to the CAN peripheral (*not* the CPU clock speed). +/// This is the clock rate of the peripheral bus the CAN peripheral is attached to (eg. APB1). +/// - *Sample Point*: Should normally be left at the default value of 87.5%. +/// - *SJW*: Should normally be left at the default value of 1. +/// +/// Then copy the `CAN_BUS_TIME` register value from the table and pass it as the `btr` +/// parameter to this method. +#[derive(Clone, Copy, Debug)] +pub struct NominalBitTiming { + /// Value by which the oscillator frequency is divided for generating the bit time quanta. The bit + /// time is built up from a multiple of this quanta. Valid values are 1 to 512. + pub prescaler: NonZeroU16, + /// Valid values are 1 to 128. + pub seg1: NonZeroU8, + /// Valid values are 1 to 255. + pub seg2: NonZeroU8, + /// Valid values are 1 to 128. + pub sync_jump_width: NonZeroU8, +} +impl NominalBitTiming { + #[inline] + pub(crate) fn nbrp(&self) -> u16 { + u16::from(self.prescaler) & 0x1FF + } + #[inline] + pub(crate) fn ntseg1(&self) -> u8 { + u8::from(self.seg1) + } + #[inline] + pub(crate) fn ntseg2(&self) -> u8 { + u8::from(self.seg2) & 0x7F + } + #[inline] + pub(crate) fn nsjw(&self) -> u8 { + u8::from(self.sync_jump_width) & 0x7F + } +} + +impl Default for NominalBitTiming { + #[inline] + fn default() -> Self { + // Kernel Clock 8MHz, Bit rate: 500kbit/s. Corresponds to a NBTP + // register value of 0x0600_0A03 + Self { + prescaler: NonZeroU16::new(1).unwrap(), + seg1: NonZeroU8::new(11).unwrap(), + seg2: NonZeroU8::new(4).unwrap(), + sync_jump_width: NonZeroU8::new(4).unwrap(), + } + } +} + +/// Configures the data bit timings for the FdCan Variable Bitrates. +/// This is not used when frame_transmit is set to anything other than AllowFdCanAndBRS. +#[derive(Clone, Copy, Debug)] +pub struct DataBitTiming { + /// Tranceiver Delay Compensation + pub transceiver_delay_compensation: bool, + /// The value by which the oscillator frequency is divided to generate the bit time quanta. The bit + /// time is built up from a multiple of this quanta. Valid values for the Baud Rate Prescaler are 1 + /// to 31. + pub prescaler: NonZeroU16, + /// Valid values are 1 to 31. + pub seg1: NonZeroU8, + /// Valid values are 1 to 15. + pub seg2: NonZeroU8, + /// Must always be smaller than DTSEG2, valid values are 1 to 15. + pub sync_jump_width: NonZeroU8, +} +impl DataBitTiming { + // #[inline] + // fn tdc(&self) -> u8 { + // let tsd = self.transceiver_delay_compensation as u8; + // //TODO: stm32g4 does not export the TDC field + // todo!() + // } + #[inline] + pub(crate) fn dbrp(&self) -> u8 { + (u16::from(self.prescaler) & 0x001F) as u8 + } + #[inline] + pub(crate) fn dtseg1(&self) -> u8 { + u8::from(self.seg1) & 0x1F + } + #[inline] + pub(crate) fn dtseg2(&self) -> u8 { + u8::from(self.seg2) & 0x0F + } + #[inline] + pub(crate) fn dsjw(&self) -> u8 { + u8::from(self.sync_jump_width) & 0x0F + } +} + +impl Default for DataBitTiming { + #[inline] + fn default() -> Self { + // Kernel Clock 8MHz, Bit rate: 500kbit/s. Corresponds to a DBTP + // register value of 0x0000_0A33 + Self { + transceiver_delay_compensation: false, + prescaler: NonZeroU16::new(1).unwrap(), + seg1: NonZeroU8::new(11).unwrap(), + seg2: NonZeroU8::new(4).unwrap(), + sync_jump_width: NonZeroU8::new(4).unwrap(), + } + } +} + +/// Configures which modes to use +/// Individual headers can contain a desire to be send via FdCan +/// or use Bit rate switching. But if this general setting does not allow +/// that, only classic CAN is used instead. +#[derive(Clone, Copy, Debug)] +pub enum FrameTransmissionConfig { + /// Only allow Classic CAN message Frames + ClassicCanOnly, + /// Allow (non-brs) FdCAN Message Frames + AllowFdCan, + /// Allow FdCAN Message Frames and allow Bit Rate Switching + AllowFdCanAndBRS, +} + +/// +#[derive(Clone, Copy, Debug)] +pub enum ClockDivider { + /// Divide by 1 + _1 = 0b0000, + /// Divide by 2 + _2 = 0b0001, + /// Divide by 4 + _4 = 0b0010, + /// Divide by 6 + _6 = 0b0011, + /// Divide by 8 + _8 = 0b0100, + /// Divide by 10 + _10 = 0b0101, + /// Divide by 12 + _12 = 0b0110, + /// Divide by 14 + _14 = 0b0111, + /// Divide by 16 + _16 = 0b1000, + /// Divide by 18 + _18 = 0b1001, + /// Divide by 20 + _20 = 0b1010, + /// Divide by 22 + _22 = 0b1011, + /// Divide by 24 + _24 = 0b1100, + /// Divide by 26 + _26 = 0b1101, + /// Divide by 28 + _28 = 0b1110, + /// Divide by 30 + _30 = 0b1111, +} + +/// Prescaler of the Timestamp counter +#[derive(Clone, Copy, Debug)] +pub enum TimestampPrescaler { + /// 1 + _1 = 1, + /// 2 + _2 = 2, + /// 3 + _3 = 3, + /// 4 + _4 = 4, + /// 5 + _5 = 5, + /// 6 + _6 = 6, + /// 7 + _7 = 7, + /// 8 + _8 = 8, + /// 9 + _9 = 9, + /// 10 + _10 = 10, + /// 11 + _11 = 11, + /// 12 + _12 = 12, + /// 13 + _13 = 13, + /// 14 + _14 = 14, + /// 15 + _15 = 15, + /// 16 + _16 = 16, +} + +/// Selects the source of the Timestamp counter +#[derive(Clone, Copy, Debug)] +pub enum TimestampSource { + /// The Timestamp counter is disabled + None, + /// Using the FdCan input clock as the Timstamp counter's source, + /// and using a specific prescaler + Prescaler(TimestampPrescaler), + /// Using TIM3 as a source + FromTIM3, +} + +/// How to handle frames in the global filter +#[derive(Clone, Copy, Debug)] +pub enum NonMatchingFilter { + /// Frames will go to Fifo0 when they do no match any specific filter + IntoRxFifo0 = 0b00, + /// Frames will go to Fifo1 when they do no match any specific filter + IntoRxFifo1 = 0b01, + /// Frames will be rejected when they do not match any specific filter + Reject = 0b11, +} + +/// How to handle frames which do not match a specific filter +#[derive(Clone, Copy, Debug)] +pub struct GlobalFilter { + /// How to handle non-matching standard frames + pub handle_standard_frames: NonMatchingFilter, + + /// How to handle non-matching extended frames + pub handle_extended_frames: NonMatchingFilter, + + /// How to handle remote standard frames + pub reject_remote_standard_frames: bool, + + /// How to handle remote extended frames + pub reject_remote_extended_frames: bool, +} +impl GlobalFilter { + /// Reject all non-matching and remote frames + pub const fn reject_all() -> Self { + Self { + handle_standard_frames: NonMatchingFilter::Reject, + handle_extended_frames: NonMatchingFilter::Reject, + reject_remote_standard_frames: true, + reject_remote_extended_frames: true, + } + } + + /// How to handle non-matching standard frames + pub const fn set_handle_standard_frames(mut self, filter: NonMatchingFilter) -> Self { + self.handle_standard_frames = filter; + self + } + /// How to handle non-matching exteded frames + pub const fn set_handle_extended_frames(mut self, filter: NonMatchingFilter) -> Self { + self.handle_extended_frames = filter; + self + } + /// How to handle remote standard frames + pub const fn set_reject_remote_standard_frames(mut self, filter: bool) -> Self { + self.reject_remote_standard_frames = filter; + self + } + /// How to handle remote extended frames + pub const fn set_reject_remote_extended_frames(mut self, filter: bool) -> Self { + self.reject_remote_extended_frames = filter; + self + } +} +impl Default for GlobalFilter { + #[inline] + fn default() -> Self { + Self { + handle_standard_frames: NonMatchingFilter::IntoRxFifo0, + handle_extended_frames: NonMatchingFilter::IntoRxFifo0, + reject_remote_standard_frames: false, + reject_remote_extended_frames: false, + } + } +} + +/// TX buffer operation mode +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum TxBufferMode { + /// TX FIFO operation - In this mode CAN frames are trasmitted strictly in write order. + Fifo, + /// TX priority queue operation - In this mode CAN frames are transmitted according to CAN priority. + Priority, +} + +impl From for crate::pac::can::vals::Tfqm { + fn from(value: TxBufferMode) -> Self { + match value { + TxBufferMode::Priority => Self::QUEUE, + TxBufferMode::Fifo => Self::FIFO, + } + } +} + +impl From for TxBufferMode { + fn from(value: crate::pac::can::vals::Tfqm) -> Self { + match value { + crate::pac::can::vals::Tfqm::QUEUE => Self::Priority, + crate::pac::can::vals::Tfqm::FIFO => Self::Fifo, + } + } +} + +/// FdCan Config Struct +#[derive(Clone, Copy, Debug)] +pub struct FdCanConfig { + /// Nominal Bit Timings + pub nbtr: NominalBitTiming, + /// (Variable) Data Bit Timings + pub dbtr: DataBitTiming, + /// Enables or disables automatic retransmission of messages + /// + /// If this is enabled, the CAN peripheral will automatically try to retransmit each frame + /// util it can be sent. Otherwise, it will try only once to send each frame. + /// + /// Automatic retransmission is enabled by default. + pub automatic_retransmit: bool, + /// Enabled or disables the pausing between transmissions + /// + /// This feature looses up burst transmissions coming from a single node and it protects against + /// "babbling idiot" scenarios where the application program erroneously requests too many + /// transmissions. + pub transmit_pause: bool, + /// Enabled or disables the pausing between transmissions + /// + /// This feature looses up burst transmissions coming from a single node and it protects against + /// "babbling idiot" scenarios where the application program erroneously requests too many + /// transmissions. + pub frame_transmit: FrameTransmissionConfig, + /// Non Isoe Mode + /// If this is set, the FDCAN uses the CAN FD frame format as specified by the Bosch CAN + /// FD Specification V1.0. + pub non_iso_mode: bool, + /// Edge Filtering: Two consecutive dominant tq required to detect an edge for hard synchronization + pub edge_filtering: bool, + /// Enables protocol exception handling + pub protocol_exception_handling: bool, + /// Sets the general clock divider for this FdCAN instance + pub clock_divider: ClockDivider, + /// Sets the timestamp source + pub timestamp_source: TimestampSource, + /// Configures the Global Filter + pub global_filter: GlobalFilter, + /// TX buffer mode (FIFO or priority queue) + pub tx_buffer_mode: TxBufferMode, +} + +impl FdCanConfig { + /// Configures the bit timings. + #[inline] + pub const fn set_nominal_bit_timing(mut self, btr: NominalBitTiming) -> Self { + self.nbtr = btr; + self + } + + /// Configures the bit timings. + #[inline] + pub const fn set_data_bit_timing(mut self, btr: DataBitTiming) -> Self { + self.dbtr = btr; + self + } + + /// Enables or disables automatic retransmission of messages + /// + /// If this is enabled, the CAN peripheral will automatically try to retransmit each frame + /// util it can be sent. Otherwise, it will try only once to send each frame. + /// + /// Automatic retransmission is enabled by default. + #[inline] + pub const fn set_automatic_retransmit(mut self, enabled: bool) -> Self { + self.automatic_retransmit = enabled; + self + } + + /// Enabled or disables the pausing between transmissions + /// + /// This feature looses up burst transmissions coming from a single node and it protects against + /// "babbling idiot" scenarios where the application program erroneously requests too many + /// transmissions. + #[inline] + pub const fn set_transmit_pause(mut self, enabled: bool) -> Self { + self.transmit_pause = enabled; + self + } + + /// If this is set, the FDCAN uses the CAN FD frame format as specified by the Bosch CAN + /// FD Specification V1.0. + #[inline] + pub const fn set_non_iso_mode(mut self, enabled: bool) -> Self { + self.non_iso_mode = enabled; + self + } + + /// Two consecutive dominant tq required to detect an edge for hard synchronization + #[inline] + pub const fn set_edge_filtering(mut self, enabled: bool) -> Self { + self.edge_filtering = enabled; + self + } + + /// Sets the allowed transmission types for messages. + #[inline] + pub const fn set_frame_transmit(mut self, fts: FrameTransmissionConfig) -> Self { + self.frame_transmit = fts; + self + } + + /// Enables protocol exception handling + #[inline] + pub const fn set_protocol_exception_handling(mut self, peh: bool) -> Self { + self.protocol_exception_handling = peh; + self + } + + /// Sets the general clock divider for this FdCAN instance + #[inline] + pub const fn set_clock_divider(mut self, div: ClockDivider) -> Self { + self.clock_divider = div; + self + } + + /// Sets the timestamp source + #[inline] + pub const fn set_timestamp_source(mut self, tss: TimestampSource) -> Self { + self.timestamp_source = tss; + self + } + + /// Sets the global filter settings + #[inline] + pub const fn set_global_filter(mut self, filter: GlobalFilter) -> Self { + self.global_filter = filter; + self + } + + /// Sets the TX buffer mode (FIFO or priority queue) + #[inline] + pub const fn set_tx_buffer_mode(mut self, txbm: TxBufferMode) -> Self { + self.tx_buffer_mode = txbm; + self + } +} + +impl Default for FdCanConfig { + #[inline] + fn default() -> Self { + Self { + nbtr: NominalBitTiming::default(), + dbtr: DataBitTiming::default(), + automatic_retransmit: true, + transmit_pause: false, + frame_transmit: FrameTransmissionConfig::ClassicCanOnly, + non_iso_mode: false, + edge_filtering: false, + protocol_exception_handling: true, + clock_divider: ClockDivider::_1, + timestamp_source: TimestampSource::None, + global_filter: GlobalFilter::default(), + tx_buffer_mode: TxBufferMode::Priority, + } + } +} diff --git a/embassy-stm32/src/can/fd/filter.rs b/embassy-stm32/src/can/fd/filter.rs new file mode 100644 index 000000000..2023a2ef0 --- /dev/null +++ b/embassy-stm32/src/can/fd/filter.rs @@ -0,0 +1,379 @@ +//! Definition of Filter structs for FDCAN Module +// Note: This file is copied and modified from fdcan crate by Richard Meadows + +use embedded_can::{ExtendedId, StandardId}; + +use crate::can::fd::message_ram; +pub use crate::can::fd::message_ram::{EXTENDED_FILTER_MAX, STANDARD_FILTER_MAX}; + +/// A Standard Filter +pub type StandardFilter = Filter; +/// An Extended Filter +pub type ExtendedFilter = Filter; + +impl Default for StandardFilter { + fn default() -> Self { + StandardFilter::disable() + } +} +impl Default for ExtendedFilter { + fn default() -> Self { + ExtendedFilter::disable() + } +} + +impl StandardFilter { + /// Accept all messages in FIFO 0 + pub fn accept_all_into_fifo0() -> StandardFilter { + StandardFilter { + filter: FilterType::BitMask { filter: 0x0, mask: 0x0 }, + action: Action::StoreInFifo0, + } + } + + /// Accept all messages in FIFO 1 + pub fn accept_all_into_fifo1() -> StandardFilter { + StandardFilter { + filter: FilterType::BitMask { filter: 0x0, mask: 0x0 }, + action: Action::StoreInFifo1, + } + } + + /// Reject all messages + pub fn reject_all() -> StandardFilter { + StandardFilter { + filter: FilterType::BitMask { filter: 0x0, mask: 0x0 }, + action: Action::Reject, + } + } + + /// Disable the filter + pub fn disable() -> StandardFilter { + StandardFilter { + filter: FilterType::Disabled, + action: Action::Disable, + } + } +} + +impl ExtendedFilter { + /// Accept all messages in FIFO 0 + pub fn accept_all_into_fifo0() -> ExtendedFilter { + ExtendedFilter { + filter: FilterType::BitMask { filter: 0x0, mask: 0x0 }, + action: Action::StoreInFifo0, + } + } + + /// Accept all messages in FIFO 1 + pub fn accept_all_into_fifo1() -> ExtendedFilter { + ExtendedFilter { + filter: FilterType::BitMask { filter: 0x0, mask: 0x0 }, + action: Action::StoreInFifo1, + } + } + + /// Reject all messages + pub fn reject_all() -> ExtendedFilter { + ExtendedFilter { + filter: FilterType::BitMask { filter: 0x0, mask: 0x0 }, + action: Action::Reject, + } + } + + /// Disable the filter + pub fn disable() -> ExtendedFilter { + ExtendedFilter { + filter: FilterType::Disabled, + action: Action::Disable, + } + } +} + +/// Filter Type +#[derive(Clone, Copy, Debug)] +pub enum FilterType +where + ID: Copy + Clone + core::fmt::Debug, + UNIT: Copy + Clone + core::fmt::Debug, +{ + /// Match with a range between two messages + Range { + /// First Id of the range + from: ID, + /// Last Id of the range + to: ID, + }, + /// Match with a bitmask + BitMask { + /// Filter of the bitmask + filter: UNIT, + /// Mask of the bitmask + mask: UNIT, + }, + /// Match with a single ID + DedicatedSingle(ID), + /// Match with one of two ID's + DedicatedDual(ID, ID), + /// Filter is disabled + Disabled, +} +impl From> for message_ram::enums::FilterType +where + ID: Copy + Clone + core::fmt::Debug, + UNIT: Copy + Clone + core::fmt::Debug, +{ + fn from(f: FilterType) -> Self { + match f { + FilterType::Range { to: _, from: _ } => Self::RangeFilter, + FilterType::BitMask { filter: _, mask: _ } => Self::ClassicFilter, + FilterType::DedicatedSingle(_) => Self::DualIdFilter, + FilterType::DedicatedDual(_, _) => Self::DualIdFilter, + FilterType::Disabled => Self::FilterDisabled, + } + } +} + +/// Filter Action +#[derive(Clone, Copy, Debug)] +pub enum Action { + /// No Action + Disable = 0b000, + /// Store an matching message in FIFO 0 + StoreInFifo0 = 0b001, + /// Store an matching message in FIFO 1 + StoreInFifo1 = 0b010, + /// Reject an matching message + Reject = 0b011, + /// Flag a matching message (But not store?!?) + FlagHighPrio = 0b100, + /// Flag a matching message as a High Priority message and store it in FIFO 0 + FlagHighPrioAndStoreInFifo0 = 0b101, + /// Flag a matching message as a High Priority message and store it in FIFO 1 + FlagHighPrioAndStoreInFifo1 = 0b110, +} +impl From for message_ram::enums::FilterElementConfig { + fn from(a: Action) -> Self { + match a { + Action::Disable => Self::DisableFilterElement, + Action::StoreInFifo0 => Self::StoreInFifo0, + Action::StoreInFifo1 => Self::StoreInFifo1, + Action::Reject => Self::Reject, + Action::FlagHighPrio => Self::SetPriority, + Action::FlagHighPrioAndStoreInFifo0 => Self::SetPriorityAndStoreInFifo0, + Action::FlagHighPrioAndStoreInFifo1 => Self::SetPriorityAndStoreInFifo1, + } + } +} + +/// Filter +#[derive(Clone, Copy, Debug)] +pub struct Filter +where + ID: Copy + Clone + core::fmt::Debug, + UNIT: Copy + Clone + core::fmt::Debug, +{ + /// How to match an incoming message + pub filter: FilterType, + /// What to do with a matching message + pub action: Action, +} + +/// Standard Filter Slot +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum StandardFilterSlot { + /// 0 + _0 = 0, + /// 1 + _1 = 1, + /// 2 + _2 = 2, + /// 3 + _3 = 3, + /// 4 + _4 = 4, + /// 5 + _5 = 5, + /// 6 + _6 = 6, + /// 7 + _7 = 7, + /// 8 + _8 = 8, + /// 9 + _9 = 9, + /// 10 + _10 = 10, + /// 11 + _11 = 11, + /// 12 + _12 = 12, + /// 13 + _13 = 13, + /// 14 + _14 = 14, + /// 15 + _15 = 15, + /// 16 + _16 = 16, + /// 17 + _17 = 17, + /// 18 + _18 = 18, + /// 19 + _19 = 19, + /// 20 + _20 = 20, + /// 21 + _21 = 21, + /// 22 + _22 = 22, + /// 23 + _23 = 23, + /// 24 + _24 = 24, + /// 25 + _25 = 25, + /// 26 + _26 = 26, + /// 27 + _27 = 27, +} +impl From for StandardFilterSlot { + fn from(u: u8) -> Self { + match u { + 0 => StandardFilterSlot::_0, + 1 => StandardFilterSlot::_1, + 2 => StandardFilterSlot::_2, + 3 => StandardFilterSlot::_3, + 4 => StandardFilterSlot::_4, + 5 => StandardFilterSlot::_5, + 6 => StandardFilterSlot::_6, + 7 => StandardFilterSlot::_7, + 8 => StandardFilterSlot::_8, + 9 => StandardFilterSlot::_9, + 10 => StandardFilterSlot::_10, + 11 => StandardFilterSlot::_11, + 12 => StandardFilterSlot::_12, + 13 => StandardFilterSlot::_13, + 14 => StandardFilterSlot::_14, + 15 => StandardFilterSlot::_15, + 16 => StandardFilterSlot::_16, + 17 => StandardFilterSlot::_17, + 18 => StandardFilterSlot::_18, + 19 => StandardFilterSlot::_19, + 20 => StandardFilterSlot::_20, + 21 => StandardFilterSlot::_21, + 22 => StandardFilterSlot::_22, + 23 => StandardFilterSlot::_23, + 24 => StandardFilterSlot::_24, + 25 => StandardFilterSlot::_25, + 26 => StandardFilterSlot::_26, + 27 => StandardFilterSlot::_27, + _ => panic!("Standard Filter Slot Too High!"), + } + } +} + +/// Extended Filter Slot +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum ExtendedFilterSlot { + /// 0 + _0 = 0, + /// 1 + _1 = 1, + /// 2 + _2 = 2, + /// 3 + _3 = 3, + /// 4 + _4 = 4, + /// 5 + _5 = 5, + /// 6 + _6 = 6, + /// 7 + _7 = 7, +} +impl From for ExtendedFilterSlot { + fn from(u: u8) -> Self { + match u { + 0 => ExtendedFilterSlot::_0, + 1 => ExtendedFilterSlot::_1, + 2 => ExtendedFilterSlot::_2, + 3 => ExtendedFilterSlot::_3, + 4 => ExtendedFilterSlot::_4, + 5 => ExtendedFilterSlot::_5, + 6 => ExtendedFilterSlot::_6, + 7 => ExtendedFilterSlot::_7, + _ => panic!("Extended Filter Slot Too High!"), // Should be unreachable + } + } +} + +/// Enum over both Standard and Extended Filter ID's +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum FilterId { + /// Standard Filter Slots + Standard(StandardFilterSlot), + /// Extended Filter Slots + Extended(ExtendedFilterSlot), +} + +pub(crate) trait ActivateFilter +where + ID: Copy + Clone + core::fmt::Debug, + UNIT: Copy + Clone + core::fmt::Debug, +{ + fn activate(&mut self, f: Filter); + // fn read(&self) -> Filter; +} + +impl ActivateFilter for message_ram::StandardFilter { + fn activate(&mut self, f: Filter) { + let sft = f.filter.into(); + + let (sfid1, sfid2) = match f.filter { + FilterType::Range { to, from } => (to.as_raw(), from.as_raw()), + FilterType::DedicatedSingle(id) => (id.as_raw(), id.as_raw()), + FilterType::DedicatedDual(id1, id2) => (id1.as_raw(), id2.as_raw()), + FilterType::BitMask { filter, mask } => (filter, mask), + FilterType::Disabled => (0x0, 0x0), + }; + let sfec = f.action.into(); + self.write(|w| { + unsafe { w.sfid1().bits(sfid1).sfid2().bits(sfid2) } + .sft() + .set_filter_type(sft) + .sfec() + .set_filter_element_config(sfec) + }); + } + // fn read(&self) -> Filter { + // todo!() + // } +} +impl ActivateFilter for message_ram::ExtendedFilter { + fn activate(&mut self, f: Filter) { + let eft = f.filter.into(); + + let (efid1, efid2) = match f.filter { + FilterType::Range { to, from } => (to.as_raw(), from.as_raw()), + FilterType::DedicatedSingle(id) => (id.as_raw(), id.as_raw()), + FilterType::DedicatedDual(id1, id2) => (id1.as_raw(), id2.as_raw()), + FilterType::BitMask { filter, mask } => (filter, mask), + FilterType::Disabled => (0x0, 0x0), + }; + let efec = f.action.into(); + self.write(|w| { + unsafe { w.efid1().bits(efid1).efid2().bits(efid2) } + .eft() + .set_filter_type(eft) + .efec() + .set_filter_element_config(efec) + }); + } + // fn read(&self) -> Filter { + // todo!() + // } +} diff --git a/embassy-stm32/src/can/fd/message_ram/common.rs b/embassy-stm32/src/can/fd/message_ram/common.rs new file mode 100644 index 000000000..108c1a428 --- /dev/null +++ b/embassy-stm32/src/can/fd/message_ram/common.rs @@ -0,0 +1,134 @@ +// Note: This file is copied and modified from fdcan crate by Richard Meadows +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(unused)] + +use super::enums::{ + BitRateSwitching, ErrorStateIndicator, FilterElementConfig, FilterType, FrameFormat, IdType, + RemoteTransmissionRequest, +}; +use super::generic; + +#[doc = "Reader of field `ID`"] +pub type ID_R = generic::R; + +#[doc = "Reader of field `RTR`"] +pub type RTR_R = generic::R; +impl RTR_R { + pub fn rtr(&self) -> RemoteTransmissionRequest { + match self.bits { + false => RemoteTransmissionRequest::TransmitDataFrame, + true => RemoteTransmissionRequest::TransmitRemoteFrame, + } + } + pub fn is_transmit_remote_frame(&self) -> bool { + *self == RemoteTransmissionRequest::TransmitRemoteFrame + } + pub fn is_transmit_data_frame(&self) -> bool { + *self == RemoteTransmissionRequest::TransmitDataFrame + } +} + +#[doc = "Reader of field `XTD`"] +pub type XTD_R = generic::R; +impl XTD_R { + pub fn id_type(&self) -> IdType { + match self.bits() { + false => IdType::StandardId, + true => IdType::ExtendedId, + } + } + pub fn is_standard_id(&self) -> bool { + *self == IdType::StandardId + } + pub fn is_exteded_id(&self) -> bool { + *self == IdType::ExtendedId + } +} + +#[doc = "Reader of field `ESI`"] +pub type ESI_R = generic::R; +impl ESI_R { + pub fn error_state(&self) -> ErrorStateIndicator { + match self.bits() { + false => ErrorStateIndicator::ErrorActive, + true => ErrorStateIndicator::ErrorPassive, + } + } + pub fn is_error_active(&self) -> bool { + *self == ErrorStateIndicator::ErrorActive + } + pub fn is_error_passive(&self) -> bool { + *self == ErrorStateIndicator::ErrorPassive + } +} + +#[doc = "Reader of field `DLC`"] +pub type DLC_R = generic::R; + +#[doc = "Reader of field `BRS`"] +pub type BRS_R = generic::R; +impl BRS_R { + pub fn bit_rate_switching(&self) -> BitRateSwitching { + match self.bits() { + true => BitRateSwitching::WithBRS, + false => BitRateSwitching::WithoutBRS, + } + } + pub fn is_with_brs(&self) -> bool { + *self == BitRateSwitching::WithBRS + } + pub fn is_without_brs(&self) -> bool { + *self == BitRateSwitching::WithoutBRS + } +} + +#[doc = "Reader of field `FDF`"] +pub type FDF_R = generic::R; +impl FDF_R { + pub fn frame_format(&self) -> FrameFormat { + match self.bits() { + false => FrameFormat::Classic, + true => FrameFormat::Fdcan, + } + } + pub fn is_classic_format(&self) -> bool { + *self == FrameFormat::Classic + } + pub fn is_fdcan_format(&self) -> bool { + *self == FrameFormat::Fdcan + } +} + +#[doc = "Reader of field `(X|S)FT`"] +pub type ESFT_R = generic::R; +impl ESFT_R { + #[doc = r"Gets the Filtertype"] + #[inline(always)] + pub fn to_filter_type(&self) -> FilterType { + match self.bits() { + 0b00 => FilterType::RangeFilter, + 0b01 => FilterType::DualIdFilter, + 0b10 => FilterType::ClassicFilter, + 0b11 => FilterType::FilterDisabled, + _ => unreachable!(), + } + } +} + +#[doc = "Reader of field `(E|S)FEC`"] +pub type ESFEC_R = generic::R; +impl ESFEC_R { + pub fn to_filter_element_config(&self) -> FilterElementConfig { + match self.bits() { + 0b000 => FilterElementConfig::DisableFilterElement, + 0b001 => FilterElementConfig::StoreInFifo0, + 0b010 => FilterElementConfig::StoreInFifo1, + 0b011 => FilterElementConfig::Reject, + 0b100 => FilterElementConfig::SetPriority, + 0b101 => FilterElementConfig::SetPriorityAndStoreInFifo0, + 0b110 => FilterElementConfig::SetPriorityAndStoreInFifo1, + _ => unimplemented!(), + } + } +} diff --git a/embassy-stm32/src/can/fd/message_ram/enums.rs b/embassy-stm32/src/can/fd/message_ram/enums.rs new file mode 100644 index 000000000..0ec5e0f34 --- /dev/null +++ b/embassy-stm32/src/can/fd/message_ram/enums.rs @@ -0,0 +1,233 @@ +// Note: This file is copied and modified from fdcan crate by Richard Meadows + +/// Datalength is the message length generalised over +/// the Standard (Classic) and FDCAN message types + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum DataLength { + Classic(u8), + Fdcan(u8), +} +impl DataLength { + /// Creates a DataLength type + /// + /// Uses the byte length and Type of frame as input + pub fn new(len: u8, ff: FrameFormat) -> DataLength { + match ff { + FrameFormat::Classic => match len { + 0..=8 => DataLength::Classic(len), + _ => panic!("DataLength > 8"), + }, + FrameFormat::Fdcan => match len { + 0..=64 => DataLength::Fdcan(len), + _ => panic!("DataLength > 64"), + }, + } + } + /// Specialised function to create classic frames + pub fn new_classic(len: u8) -> DataLength { + Self::new(len, FrameFormat::Classic) + } + /// Specialised function to create FDCAN frames + pub fn new_fdcan(len: u8) -> DataLength { + Self::new(len, FrameFormat::Fdcan) + } + + /// returns the length in bytes + pub fn len(&self) -> u8 { + match self { + DataLength::Classic(l) | DataLength::Fdcan(l) => *l, + } + } + + pub(crate) fn dlc(&self) -> u8 { + match self { + DataLength::Classic(l) => *l, + // See RM0433 Rev 7 Table 475. DLC coding + DataLength::Fdcan(l) => match l { + 0..=8 => *l, + 9..=12 => 9, + 13..=16 => 10, + 17..=20 => 11, + 21..=24 => 12, + 25..=32 => 13, + 33..=48 => 14, + 49..=64 => 15, + _ => panic!("DataLength > 64"), + }, + } + } +} +impl From for FrameFormat { + fn from(dl: DataLength) -> FrameFormat { + match dl { + DataLength::Classic(_) => FrameFormat::Classic, + DataLength::Fdcan(_) => FrameFormat::Fdcan, + } + } +} + +/// Wheter or not to generate an Tx Event +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Event { + /// Do not generate an Tx Event + NoEvent, + /// Generate an Tx Event with a specified ID + Event(u8), +} + +impl From for EventControl { + fn from(e: Event) -> Self { + match e { + Event::NoEvent => EventControl::DoNotStore, + Event::Event(_) => EventControl::Store, + } + } +} + +impl From> for Event { + fn from(mm: Option) -> Self { + match mm { + None => Event::NoEvent, + Some(mm) => Event::Event(mm), + } + } +} + +impl From for Option { + fn from(e: Event) -> Option { + match e { + Event::NoEvent => None, + Event::Event(mm) => Some(mm), + } + } +} + +/// TODO +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ErrorStateIndicator { + /// TODO + ErrorActive = 0, + /// TODO + ErrorPassive = 1, +} +impl From for bool { + #[inline(always)] + fn from(e: ErrorStateIndicator) -> Self { + e as u8 != 0 + } +} + +/// Type of frame, standard (classic) or FdCAN +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum FrameFormat { + Classic = 0, + Fdcan = 1, +} +impl From for bool { + #[inline(always)] + fn from(e: FrameFormat) -> Self { + e as u8 != 0 + } +} + +/// Type of Id, Standard or Extended +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum IdType { + /// Standard ID + StandardId = 0, + /// Extended ID + ExtendedId = 1, +} +impl From for bool { + #[inline(always)] + fn from(e: IdType) -> Self { + e as u8 != 0 + } +} + +/// Whether the frame contains data or requests data +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum RemoteTransmissionRequest { + /// Frame contains data + TransmitDataFrame = 0, + /// frame does not contain data + TransmitRemoteFrame = 1, +} +impl From for bool { + #[inline(always)] + fn from(e: RemoteTransmissionRequest) -> Self { + e as u8 != 0 + } +} + +/// Whether BitRateSwitching should be or was enabled +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum BitRateSwitching { + /// disable bit rate switching + WithoutBRS = 0, + /// enable bit rate switching + WithBRS = 1, +} +impl From for bool { + #[inline(always)] + fn from(e: BitRateSwitching) -> Self { + e as u8 != 0 + } +} + +/// Whether to store transmit Events +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum EventControl { + /// do not store an tx event + DoNotStore, + /// store transmit events + Store, +} +impl From for bool { + #[inline(always)] + fn from(e: EventControl) -> Self { + e as u8 != 0 + } +} + +/// If an received message matched any filters +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum FilterFrameMatch { + /// This did match filter + DidMatch(u8), + /// This received frame did not match any specific filters + DidNotMatch, +} + +/// Type of filter to be used +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum FilterType { + /// Filter uses the range between two id's + RangeFilter = 0b00, + /// The filter matches on two specific id's (or one ID checked twice) + DualIdFilter = 0b01, + /// Filter is using a bitmask + ClassicFilter = 0b10, + /// Filter is disabled + FilterDisabled = 0b11, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum FilterElementConfig { + /// Filter is disabled + DisableFilterElement = 0b000, + /// Store a matching message in FIFO 0 + StoreInFifo0 = 0b001, + /// Store a matching message in FIFO 1 + StoreInFifo1 = 0b010, + /// Reject a matching message + Reject = 0b011, + /// Flag that a priority message has been received, *But do note store!*?? + SetPriority = 0b100, + /// Flag and store message in FIFO 0 + SetPriorityAndStoreInFifo0 = 0b101, + /// Flag and store message in FIFO 1 + SetPriorityAndStoreInFifo1 = 0b110, + //_Unused = 0b111, +} diff --git a/embassy-stm32/src/can/fd/message_ram/extended_filter.rs b/embassy-stm32/src/can/fd/message_ram/extended_filter.rs new file mode 100644 index 000000000..453e9056e --- /dev/null +++ b/embassy-stm32/src/can/fd/message_ram/extended_filter.rs @@ -0,0 +1,136 @@ +// Note: This file is copied and modified from fdcan crate by Richard Meadows + +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(unused)] + +use super::common::{ESFEC_R, ESFT_R}; +use super::enums::{FilterElementConfig, FilterType}; +use super::generic; + +#[doc = "Reader of register ExtendedFilter"] +pub(crate) type R = generic::R; +#[doc = "Writer for register ExtendedFilter"] +pub(crate) type W = generic::W; +#[doc = "Register ExtendedFilter `reset()`'s"] +impl generic::ResetValue for super::ExtendedFilter { + type Type = super::ExtendedFilterType; + #[inline(always)] + fn reset_value() -> Self::Type { + // Sets filter element to Disabled + [0x0, 0x0] + } +} + +#[doc = "Reader of field `EFID2`"] +pub(crate) type EFID2_R = generic::R; +#[doc = "Write proxy for field `EFID2`"] +pub(crate) struct EFID2_W<'a> { + w: &'a mut W, +} +impl<'a> EFID2_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits[1] = (self.w.bits[1] & !(0x1FFFFFFF)) | ((value as u32) & 0x1FFFFFFF); + self.w + } +} + +#[doc = "Reader of field `EFID1`"] +pub(crate) type EFID1_R = generic::R; +#[doc = "Write proxy for field `EFID1`"] +pub(crate) struct EFID1_W<'a> { + w: &'a mut W, +} +impl<'a> EFID1_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits[0] = (self.w.bits[0] & !(0x1FFFFFFF)) | ((value as u32) & 0x1FFFFFFF); + self.w + } +} + +#[doc = "Write proxy for field `EFEC`"] +pub(crate) struct EFEC_W<'a> { + w: &'a mut W, +} +impl<'a> EFEC_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits[0] = (self.w.bits[0] & !(0x07 << 29)) | (((value as u32) & 0x07) << 29); + self.w + } + #[doc = r"Sets the field according to FilterElementConfig"] + #[inline(always)] + pub fn set_filter_element_config(self, fec: FilterElementConfig) -> &'a mut W { + //SAFETY: FilterElementConfig only be valid options + unsafe { self.bits(fec as u8) } + } +} + +#[doc = "Write proxy for field `EFT`"] +pub(crate) struct EFT_W<'a> { + w: &'a mut W, +} +impl<'a> EFT_W<'a> { + #[doc = r"Sets the field according the FilterType"] + #[inline(always)] + pub fn set_filter_type(self, filter: FilterType) -> &'a mut W { + //SAFETY: FilterType only be valid options + unsafe { self.bits(filter as u8) } + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits[1] = (self.w.bits[1] & !(0x03 << 30)) | (((value as u32) & 0x03) << 30); + self.w + } +} + +impl R { + #[doc = "Byte 0 - Bits 0:28 - EFID1"] + #[inline(always)] + pub fn sfid1(&self) -> EFID1_R { + EFID1_R::new(((self.bits[0]) & 0x1FFFFFFF) as u32) + } + #[doc = "Byte 0 - Bits 29:31 - EFEC"] + #[inline(always)] + pub fn efec(&self) -> ESFEC_R { + ESFEC_R::new(((self.bits[0] >> 29) & 0x07) as u8) + } + #[doc = "Byte 1 - Bits 0:28 - EFID2"] + #[inline(always)] + pub fn sfid2(&self) -> EFID2_R { + EFID2_R::new(((self.bits[1]) & 0x1FFFFFFF) as u32) + } + #[doc = "Byte 1 - Bits 30:31 - EFT"] + #[inline(always)] + pub fn eft(&self) -> ESFT_R { + ESFT_R::new(((self.bits[1] >> 30) & 0x03) as u8) + } +} +impl W { + #[doc = "Byte 0 - Bits 0:28 - EFID1"] + #[inline(always)] + pub fn efid1(&mut self) -> EFID1_W { + EFID1_W { w: self } + } + #[doc = "Byte 0 - Bits 29:31 - EFEC"] + #[inline(always)] + pub fn efec(&mut self) -> EFEC_W { + EFEC_W { w: self } + } + #[doc = "Byte 1 - Bits 0:28 - EFID2"] + #[inline(always)] + pub fn efid2(&mut self) -> EFID2_W { + EFID2_W { w: self } + } + #[doc = "Byte 1 - Bits 30:31 - EFT"] + #[inline(always)] + pub fn eft(&mut self) -> EFT_W { + EFT_W { w: self } + } +} diff --git a/embassy-stm32/src/can/fd/message_ram/generic.rs b/embassy-stm32/src/can/fd/message_ram/generic.rs new file mode 100644 index 000000000..1a5e121b4 --- /dev/null +++ b/embassy-stm32/src/can/fd/message_ram/generic.rs @@ -0,0 +1,168 @@ +// Note: This file is copied and modified from fdcan crate by Richard Meadows + +use core::marker; + +///This trait shows that register has `read` method +/// +///Registers marked with `Writable` can be also `modify`'ed +pub trait Readable {} + +///This trait shows that register has `write`, `write_with_zero` and `reset` method +/// +///Registers marked with `Readable` can be also `modify`'ed +pub trait Writable {} + +///Reset value of the register +/// +///This value is initial value for `write` method. +///It can be also directly writed to register by `reset` method. +pub trait ResetValue { + ///Register size + type Type; + ///Reset value of the register + fn reset_value() -> Self::Type; +} + +///This structure provides volatile access to register +pub struct Reg { + register: vcell::VolatileCell, + _marker: marker::PhantomData, +} + +unsafe impl Send for Reg {} + +impl Reg +where + Self: Readable, + U: Copy, +{ + ///Reads the contents of `Readable` register + /// + ///You can read the contents of a register in such way: + ///```ignore + ///let bits = periph.reg.read().bits(); + ///``` + ///or get the content of a particular field of a register. + ///```ignore + ///let reader = periph.reg.read(); + ///let bits = reader.field1().bits(); + ///let flag = reader.field2().bit_is_set(); + ///``` + #[inline(always)] + pub fn read(&self) -> R { + R { + bits: self.register.get(), + _reg: marker::PhantomData, + } + } +} + +impl Reg +where + Self: ResetValue + Writable, + U: Copy, +{ + ///Writes the reset value to `Writable` register + /// + ///Resets the register to its initial state + #[inline(always)] + pub fn reset(&self) { + self.register.set(Self::reset_value()) + } +} + +impl Reg +where + Self: ResetValue + Writable, + U: Copy, +{ + ///Writes bits to `Writable` register + /// + ///You can write raw bits into a register: + ///```ignore + ///periph.reg.write(|w| unsafe { w.bits(rawbits) }); + ///``` + ///or write only the fields you need: + ///```ignore + ///periph.reg.write(|w| w + /// .field1().bits(newfield1bits) + /// .field2().set_bit() + /// .field3().variant(VARIANT) + ///); + ///``` + ///Other fields will have reset value. + #[inline(always)] + pub fn write(&self, f: F) + where + F: FnOnce(&mut W) -> &mut W, + { + self.register.set( + f(&mut W { + bits: Self::reset_value(), + _reg: marker::PhantomData, + }) + .bits, + ); + } +} + +///Register/field reader +/// +///Result of the [`read`](Reg::read) method of a register. +///Also it can be used in the [`modify`](Reg::read) method +pub struct R { + pub(crate) bits: U, + _reg: marker::PhantomData, +} + +impl R +where + U: Copy, +{ + ///Create new instance of reader + #[inline(always)] + pub(crate) fn new(bits: U) -> Self { + Self { + bits, + _reg: marker::PhantomData, + } + } + ///Read raw bits from register/field + #[inline(always)] + pub fn bits(&self) -> U { + self.bits + } +} + +impl PartialEq for R +where + U: PartialEq, + FI: Copy + Into, +{ + #[inline(always)] + fn eq(&self, other: &FI) -> bool { + self.bits.eq(&(*other).into()) + } +} + +impl R { + ///Value of the field as raw bits + #[inline(always)] + pub fn bit(&self) -> bool { + self.bits + } + ///Returns `true` if the bit is clear (0) + #[inline(always)] + pub fn bit_is_clear(&self) -> bool { + !self.bit() + } +} + +///Register writer +/// +///Used as an argument to the closures in the [`write`](Reg::write) and [`modify`](Reg::modify) methods of the register +pub struct W { + ///Writable bits + pub(crate) bits: U, + _reg: marker::PhantomData, +} diff --git a/embassy-stm32/src/can/fd/message_ram/mod.rs b/embassy-stm32/src/can/fd/message_ram/mod.rs new file mode 100644 index 000000000..040a999b4 --- /dev/null +++ b/embassy-stm32/src/can/fd/message_ram/mod.rs @@ -0,0 +1,150 @@ +// Note: This file is copied and modified from fdcan crate by Richard Meadows + +use volatile_register::RW; + +pub(crate) mod common; +pub(crate) mod enums; +pub(crate) mod generic; + +/// Number of Receive Fifos configured by this module +pub const RX_FIFOS_MAX: u8 = 2; +/// Number of Receive Messages per RxFifo configured by this module +pub const RX_FIFO_MAX: u8 = 3; +/// Number of Transmit Messages configured by this module +pub const TX_FIFO_MAX: u8 = 3; +/// Number of Transmit Events configured by this module +pub const TX_EVENT_MAX: u8 = 3; +/// Number of Standard Filters configured by this module +pub const STANDARD_FILTER_MAX: u8 = 28; +/// Number of Extended Filters configured by this module +pub const EXTENDED_FILTER_MAX: u8 = 8; + +/// MessageRam Overlay +#[repr(C)] +pub struct RegisterBlock { + pub(crate) filters: Filters, + pub(crate) receive: [Receive; RX_FIFOS_MAX as usize], + pub(crate) transmit: Transmit, +} +impl RegisterBlock { + pub fn reset(&mut self) { + self.filters.reset(); + self.receive[0].reset(); + self.receive[1].reset(); + self.transmit.reset(); + } +} + +#[repr(C)] +pub(crate) struct Filters { + pub(crate) flssa: [StandardFilter; STANDARD_FILTER_MAX as usize], + pub(crate) flesa: [ExtendedFilter; EXTENDED_FILTER_MAX as usize], +} +impl Filters { + pub fn reset(&mut self) { + for sf in &mut self.flssa { + sf.reset(); + } + for ef in &mut self.flesa { + ef.reset(); + } + } +} + +#[repr(C)] +pub(crate) struct Receive { + pub(crate) fxsa: [RxFifoElement; RX_FIFO_MAX as usize], +} +impl Receive { + pub fn reset(&mut self) { + for fe in &mut self.fxsa { + fe.reset(); + } + } +} + +#[repr(C)] +pub(crate) struct Transmit { + pub(crate) efsa: [TxEventElement; TX_EVENT_MAX as usize], + pub(crate) tbsa: [TxBufferElement; TX_FIFO_MAX as usize], +} +impl Transmit { + pub fn reset(&mut self) { + for ee in &mut self.efsa { + ee.reset(); + } + for be in &mut self.tbsa { + be.reset(); + } + } +} + +pub(crate) mod standard_filter; +pub(crate) type StandardFilterType = u32; +pub(crate) type StandardFilter = generic::Reg; +pub(crate) struct _StandardFilter; +impl generic::Readable for StandardFilter {} +impl generic::Writable for StandardFilter {} + +pub(crate) mod extended_filter; +pub(crate) type ExtendedFilterType = [u32; 2]; +pub(crate) type ExtendedFilter = generic::Reg; +pub(crate) struct _ExtendedFilter; +impl generic::Readable for ExtendedFilter {} +impl generic::Writable for ExtendedFilter {} + +pub(crate) mod txevent_element; +pub(crate) type TxEventElementType = [u32; 2]; +pub(crate) type TxEventElement = generic::Reg; +pub(crate) struct _TxEventElement; +impl generic::Readable for TxEventElement {} +impl generic::Writable for TxEventElement {} + +pub(crate) mod rxfifo_element; +#[repr(C)] +pub(crate) struct RxFifoElement { + pub(crate) header: RxFifoElementHeader, + pub(crate) data: [RW; 16], +} +impl RxFifoElement { + pub(crate) fn reset(&mut self) { + self.header.reset(); + for byte in self.data.iter_mut() { + unsafe { byte.write(0) }; + } + } +} +pub(crate) type RxFifoElementHeaderType = [u32; 2]; +pub(crate) type RxFifoElementHeader = generic::Reg; +pub(crate) struct _RxFifoElement; +impl generic::Readable for RxFifoElementHeader {} +impl generic::Writable for RxFifoElementHeader {} + +pub(crate) mod txbuffer_element; +#[repr(C)] +pub(crate) struct TxBufferElement { + pub(crate) header: TxBufferElementHeader, + pub(crate) data: [RW; 16], +} +impl TxBufferElement { + pub(crate) fn reset(&mut self) { + self.header.reset(); + for byte in self.data.iter_mut() { + unsafe { byte.write(0) }; + } + } +} +pub(crate) type TxBufferElementHeader = generic::Reg; +pub(crate) type TxBufferElementHeaderType = [u32; 2]; +pub(crate) struct _TxBufferElement; +impl generic::Readable for TxBufferElementHeader {} +impl generic::Writable for TxBufferElementHeader {} + +// Ensure the RegisterBlock is the same size as on pg 1957 of RM0440. +static_assertions::assert_eq_size!(Filters, [u32; 28 + 16]); +static_assertions::assert_eq_size!(Receive, [u32; 54]); +static_assertions::assert_eq_size!(Transmit, [u32; 6 + 54]); +static_assertions::assert_eq_size!( + RegisterBlock, + [u32; 28 /*Standard Filters*/ +16 /*Extended Filters*/ +54 /*RxFifo0*/ +54 /*RxFifo1*/ +6 /*TxEvent*/ +54 /*TxFifo */] +); diff --git a/embassy-stm32/src/can/fd/message_ram/rxfifo_element.rs b/embassy-stm32/src/can/fd/message_ram/rxfifo_element.rs new file mode 100644 index 000000000..48fc3a091 --- /dev/null +++ b/embassy-stm32/src/can/fd/message_ram/rxfifo_element.rs @@ -0,0 +1,122 @@ +// Note: This file is copied and modified from fdcan crate by Richard Meadows + +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(unused)] + +use super::common::{BRS_R, DLC_R, ESI_R, FDF_R, ID_R, RTR_R, XTD_R}; +use super::enums::{DataLength, FilterFrameMatch, FrameFormat}; +use super::generic; + +#[doc = "Reader of register RxFifoElement"] +pub(crate) type R = generic::R; +// #[doc = "Writer for register ExtendedFilter"] +// pub(crate) type W = generic::W; +#[doc = "Register ExtendedFilter `reset()`'s"] +impl generic::ResetValue for super::RxFifoElementHeader { + type Type = super::RxFifoElementHeaderType; + #[inline(always)] + fn reset_value() -> Self::Type { + [0x0, 0x0] + } +} + +#[doc = "Reader of field `RXTS`"] +pub(crate) type RXTS_R = generic::R; + +#[doc = "Reader of field `FIDX`"] +pub(crate) type FIDX_R = generic::R; + +pub(crate) struct _ANMF; +#[doc = "Reader of field `ANMF`"] +pub(crate) type ANMF_R = generic::R; +impl ANMF_R { + pub fn is_matching_frame(&self) -> bool { + self.bit_is_clear() + } +} + +impl R { + #[doc = "Byte 0 - Bits 0:28 - ID"] + #[inline(always)] + pub fn id(&self) -> ID_R { + ID_R::new(((self.bits[0]) & 0x1FFFFFFF) as u32) + } + #[doc = "Byte 0 - Bit 29 - RTR"] + #[inline(always)] + pub fn rtr(&self) -> RTR_R { + RTR_R::new(((self.bits[0] >> 29) & 0x01) != 0) + } + #[doc = "Byte 0 - Bit 30 - XTD"] + #[inline(always)] + pub fn xtd(&self) -> XTD_R { + XTD_R::new(((self.bits[0] >> 30) & 0x01) != 0) + } + #[doc = "Byte 0 - Bit 30 - ESI"] + #[inline(always)] + pub fn esi(&self) -> ESI_R { + ESI_R::new(((self.bits[0] >> 31) & 0x01) != 0) + } + #[doc = "Byte 1 - Bits 0:15 - RXTS"] + #[inline(always)] + pub fn txts(&self) -> RXTS_R { + RXTS_R::new(((self.bits[1]) & 0xFFFF) as u16) + } + #[doc = "Byte 1 - Bits 16:19 - DLC"] + #[inline(always)] + pub fn dlc(&self) -> DLC_R { + DLC_R::new(((self.bits[1] >> 16) & 0x0F) as u8) + } + #[doc = "Byte 1 - Bits 20 - BRS"] + #[inline(always)] + pub fn brs(&self) -> BRS_R { + BRS_R::new(((self.bits[1] >> 20) & 0x01) != 0) + } + #[doc = "Byte 1 - Bits 20 - FDF"] + #[inline(always)] + pub fn fdf(&self) -> FDF_R { + FDF_R::new(((self.bits[1] >> 21) & 0x01) != 0) + } + #[doc = "Byte 1 - Bits 24:30 - FIDX"] + #[inline(always)] + pub fn fidx(&self) -> FIDX_R { + FIDX_R::new(((self.bits[1] >> 24) & 0xFF) as u8) + } + #[doc = "Byte 1 - Bits 31 - ANMF"] + #[inline(always)] + pub fn anmf(&self) -> ANMF_R { + ANMF_R::new(((self.bits[1] >> 31) & 0x01) != 0) + } + pub fn to_data_length(&self) -> DataLength { + let dlc = self.dlc().bits(); + let ff = self.fdf().frame_format(); + let len = if ff == FrameFormat::Fdcan { + // See RM0433 Rev 7 Table 475. DLC coding + match dlc { + 0..=8 => dlc, + 9 => 12, + 10 => 16, + 11 => 20, + 12 => 24, + 13 => 32, + 14 => 48, + 15 => 64, + _ => panic!("DLC > 15"), + } + } else { + match dlc { + 0..=8 => dlc, + 9..=15 => 8, + _ => panic!("DLC > 15"), + } + }; + DataLength::new(len, ff) + } + pub fn to_filter_match(&self) -> FilterFrameMatch { + if self.anmf().is_matching_frame() { + FilterFrameMatch::DidMatch(self.fidx().bits()) + } else { + FilterFrameMatch::DidNotMatch + } + } +} diff --git a/embassy-stm32/src/can/fd/message_ram/standard_filter.rs b/embassy-stm32/src/can/fd/message_ram/standard_filter.rs new file mode 100644 index 000000000..3a3bbcf12 --- /dev/null +++ b/embassy-stm32/src/can/fd/message_ram/standard_filter.rs @@ -0,0 +1,136 @@ +// Note: This file is copied and modified from fdcan crate by Richard Meadows + +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(unused)] + +use super::common::{ESFEC_R, ESFT_R}; +use super::enums::{FilterElementConfig, FilterType}; +use super::generic; + +#[doc = "Reader of register StandardFilter"] +pub(crate) type R = generic::R; +#[doc = "Writer for register StandardFilter"] +pub(crate) type W = generic::W; +#[doc = "Register StandardFilter `reset()`'s with value 0xC0000"] +impl generic::ResetValue for super::StandardFilter { + type Type = super::StandardFilterType; + #[inline(always)] + fn reset_value() -> Self::Type { + // Sets filter element to Disabled + 0xC000 + } +} + +#[doc = "Reader of field `SFID2`"] +pub(crate) type SFID2_R = generic::R; +#[doc = "Write proxy for field `SFID2`"] +pub(crate) struct SFID2_W<'a> { + w: &'a mut W, +} +impl<'a> SFID2_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x07ff)) | ((value as u32) & 0x07ff); + self.w + } +} + +#[doc = "Reader of field `SFID1`"] +pub(crate) type SFID1_R = generic::R; +#[doc = "Write proxy for field `SFID1`"] +pub(crate) struct SFID1_W<'a> { + w: &'a mut W, +} +impl<'a> SFID1_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u16) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x07ff << 16)) | (((value as u32) & 0x07ff) << 16); + self.w + } +} + +#[doc = "Write proxy for field `SFEC`"] +pub(crate) struct SFEC_W<'a> { + w: &'a mut W, +} +impl<'a> SFEC_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x07 << 27)) | (((value as u32) & 0x07) << 27); + self.w + } + #[doc = r"Sets the field according to FilterElementConfig"] + #[inline(always)] + pub fn set_filter_element_config(self, fec: FilterElementConfig) -> &'a mut W { + //SAFETY: FilterElementConfig only be valid options + unsafe { self.bits(fec as u8) } + } +} + +#[doc = "Write proxy for field `SFT`"] +pub(crate) struct SFT_W<'a> { + w: &'a mut W, +} +impl<'a> SFT_W<'a> { + #[doc = r"Sets the field according the FilterType"] + #[inline(always)] + pub fn set_filter_type(self, filter: FilterType) -> &'a mut W { + //SAFETY: FilterType only be valid options + unsafe { self.bits(filter as u8) } + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits = (self.w.bits & !(0x03 << 30)) | (((value as u32) & 0x03) << 30); + self.w + } +} + +impl R { + #[doc = "Bits 0:10 - SFID2"] + #[inline(always)] + pub fn sfid2(&self) -> SFID2_R { + SFID2_R::new((self.bits & 0x07ff) as u16) + } + #[doc = "Bits 16:26 - SFID1"] + #[inline(always)] + pub fn sfid1(&self) -> SFID1_R { + SFID1_R::new(((self.bits >> 16) & 0x07ff) as u16) + } + #[doc = "Bits 27:29 - SFEC"] + #[inline(always)] + pub fn sfec(&self) -> ESFEC_R { + ESFEC_R::new(((self.bits >> 27) & 0x07) as u8) + } + #[doc = "Bits 30:31 - SFT"] + #[inline(always)] + pub fn sft(&self) -> ESFT_R { + ESFT_R::new(((self.bits >> 30) & 0x03) as u8) + } +} +impl W { + #[doc = "Bits 0:10 - SFID2"] + #[inline(always)] + pub fn sfid2(&mut self) -> SFID2_W { + SFID2_W { w: self } + } + #[doc = "Bits 16:26 - SFID1"] + #[inline(always)] + pub fn sfid1(&mut self) -> SFID1_W { + SFID1_W { w: self } + } + #[doc = "Bits 27:29 - SFEC"] + #[inline(always)] + pub fn sfec(&mut self) -> SFEC_W { + SFEC_W { w: self } + } + #[doc = "Bits 30:31 - SFT"] + #[inline(always)] + pub fn sft(&mut self) -> SFT_W { + SFT_W { w: self } + } +} diff --git a/embassy-stm32/src/can/fd/message_ram/txbuffer_element.rs b/embassy-stm32/src/can/fd/message_ram/txbuffer_element.rs new file mode 100644 index 000000000..455406a1c --- /dev/null +++ b/embassy-stm32/src/can/fd/message_ram/txbuffer_element.rs @@ -0,0 +1,433 @@ +// Note: This file is copied and modified from fdcan crate by Richard Meadows + +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(unused)] + +use super::common::{BRS_R, DLC_R, ESI_R, FDF_R, ID_R, RTR_R, XTD_R}; +use super::enums::{ + BitRateSwitching, DataLength, ErrorStateIndicator, Event, EventControl, FrameFormat, IdType, + RemoteTransmissionRequest, +}; +use super::generic; + +#[doc = "Reader of register TxBufferElement"] +pub(crate) type R = generic::R; +#[doc = "Writer for register TxBufferElement"] +pub(crate) type W = generic::W; +impl generic::ResetValue for super::TxBufferElementHeader { + type Type = super::TxBufferElementHeaderType; + + #[allow(dead_code)] + #[inline(always)] + fn reset_value() -> Self::Type { + [0; 2] + } +} + +#[doc = "Write proxy for field `ESI`"] +pub(crate) struct ESI_W<'a> { + w: &'a mut W, +} +impl<'a> ESI_W<'a> { + #[doc = r"Writes `variant` to the field"] + #[inline(always)] + #[allow(dead_code)] + pub fn set_error_indicator(self, esi: ErrorStateIndicator) -> &'a mut W { + self.bit(esi as u8 != 0) + } + + #[doc = r"Sets the field bit"] + #[inline(always)] + #[allow(dead_code)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + #[allow(dead_code)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + #[allow(dead_code)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits[0] = (self.w.bits[0] & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); + self.w + } +} + +#[doc = "Write proxy for field `XTD`"] +pub(crate) struct XTD_W<'a> { + w: &'a mut W, +} +impl<'a> XTD_W<'a> { + #[doc = r"Writes `variant` to the field"] + #[inline(always)] + #[allow(dead_code)] + pub fn set_id_type(self, idt: IdType) -> &'a mut W { + self.bit(idt as u8 != 0) + } + + #[doc = r"Sets the field bit"] + #[inline(always)] + #[allow(dead_code)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + #[allow(dead_code)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + #[allow(dead_code)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits[0] = (self.w.bits[0] & !(0x01 << 30)) | (((value as u32) & 0x01) << 30); + self.w + } +} + +#[doc = "Write proxy for field `RTR`"] +pub(crate) struct RTR_W<'a> { + w: &'a mut W, +} +impl<'a> RTR_W<'a> { + #[doc = r"Writes `variant` to the field"] + #[inline(always)] + #[allow(dead_code)] + pub fn set_rtr(self, rtr: RemoteTransmissionRequest) -> &'a mut W { + self.bit(rtr as u8 != 0) + } + + #[doc = r"Sets the field bit"] + #[inline(always)] + #[allow(dead_code)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + #[allow(dead_code)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + #[allow(dead_code)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits[0] = (self.w.bits[0] & !(0x01 << 29)) | (((value as u32) & 0x01) << 29); + self.w + } +} + +#[doc = "Write proxy for field `ID`"] +pub(crate) struct ID_W<'a> { + w: &'a mut W, +} +impl<'a> ID_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + #[allow(dead_code)] + pub unsafe fn bits(self, value: u32) -> &'a mut W { + self.w.bits[0] = (self.w.bits[0] & !(0x1FFFFFFF)) | ((value as u32) & 0x1FFFFFFF); + self.w + } +} + +#[doc = "Write proxy for field `DLC`"] +pub(crate) struct DLC_W<'a> { + w: &'a mut W, +} +impl<'a> DLC_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + #[allow(dead_code)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits[1] = (self.w.bits[1] & !(0x0F << 16)) | (((value as u32) & 0x0F) << 16); + self.w + } +} + +#[doc = "Write proxy for field `BRS`"] +pub(crate) struct BRS_W<'a> { + w: &'a mut W, +} +impl<'a> BRS_W<'a> { + #[doc = r"Writes `variant` to the field"] + #[inline(always)] + #[allow(dead_code)] + pub fn set_brs(self, brs: BitRateSwitching) -> &'a mut W { + self.bit(brs as u8 != 0) + } + + #[doc = r"Sets the field bit"] + #[inline(always)] + #[allow(dead_code)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + #[allow(dead_code)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + #[allow(dead_code)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits[1] = (self.w.bits[1] & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); + self.w + } +} + +#[doc = "Write proxy for field `FDF`"] +pub(crate) struct FDF_W<'a> { + w: &'a mut W, +} +impl<'a> FDF_W<'a> { + #[doc = r"Writes `variant` to the field"] + #[inline(always)] + #[allow(dead_code)] + pub fn set_format(self, fdf: FrameFormat) -> &'a mut W { + self.bit(fdf as u8 != 0) + } + + #[doc = r"Sets the field bit"] + #[inline(always)] + #[allow(dead_code)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + #[allow(dead_code)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + #[allow(dead_code)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits[1] = (self.w.bits[1] & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); + self.w + } +} + +#[doc = "Reader of field `EFC`"] +pub(crate) type EFC_R = generic::R; +impl EFC_R { + pub fn to_event_control(&self) -> EventControl { + match self.bit() { + false => EventControl::DoNotStore, + true => EventControl::Store, + } + } +} +#[doc = "Write proxy for field `EFC`"] +pub(crate) struct EFC_W<'a> { + w: &'a mut W, +} +impl<'a> EFC_W<'a> { + #[doc = r"Writes `variant` to the field"] + #[inline(always)] + #[allow(dead_code)] + pub fn set_event_control(self, efc: EventControl) -> &'a mut W { + self.bit(match efc { + EventControl::DoNotStore => false, + EventControl::Store => true, + }) + } + + #[doc = r"Sets the field bit"] + #[inline(always)] + #[allow(dead_code)] + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + #[doc = r"Clears the field bit"] + #[inline(always)] + #[allow(dead_code)] + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + #[allow(dead_code)] + pub fn bit(self, value: bool) -> &'a mut W { + self.w.bits[1] = (self.w.bits[1] & !(0x01 << 23)) | (((value as u32) & 0x01) << 23); + self.w + } +} + +struct Marker(u8); +impl From for Marker { + fn from(e: Event) -> Marker { + match e { + Event::NoEvent => Marker(0), + Event::Event(mm) => Marker(mm), + } + } +} + +#[doc = "Reader of field `MM`"] +pub(crate) type MM_R = generic::R; +#[doc = "Write proxy for field `MM`"] +pub(crate) struct MM_W<'a> { + w: &'a mut W, +} +impl<'a> MM_W<'a> { + #[doc = r"Writes raw bits to the field"] + #[inline(always)] + pub unsafe fn bits(self, value: u8) -> &'a mut W { + self.w.bits[1] = (self.w.bits[1] & !(0x7F << 24)) | (((value as u32) & 0x7F) << 24); + self.w + } + + fn set_message_marker(self, mm: Marker) -> &'a mut W { + unsafe { self.bits(mm.0) } + } +} + +impl R { + #[doc = "Byte 0 - Bits 0:28 - ID"] + #[inline(always)] + pub fn id(&self) -> ID_R { + ID_R::new(((self.bits[0]) & 0x1FFFFFFF) as u32) + } + #[doc = "Byte 0 - Bit 29 - RTR"] + #[inline(always)] + pub fn rtr(&self) -> RTR_R { + RTR_R::new(((self.bits[0] >> 29) & 0x01) != 0) + } + #[doc = "Byte 0 - Bit 30 - XTD"] + #[inline(always)] + pub fn xtd(&self) -> XTD_R { + XTD_R::new(((self.bits[0] >> 30) & 0x01) != 0) + } + #[doc = "Byte 0 - Bit 30 - ESI"] + #[inline(always)] + pub fn esi(&self) -> ESI_R { + ESI_R::new(((self.bits[0] >> 31) & 0x01) != 0) + } + #[doc = "Byte 1 - Bits 16:19 - DLC"] + #[inline(always)] + pub fn dlc(&self) -> DLC_R { + DLC_R::new(((self.bits[1] >> 16) & 0x0F) as u8) + } + #[doc = "Byte 1 - Bits 20 - BRS"] + #[inline(always)] + pub fn brs(&self) -> BRS_R { + BRS_R::new(((self.bits[1] >> 20) & 0x01) != 0) + } + #[doc = "Byte 1 - Bits 20 - FDF"] + #[inline(always)] + pub fn fdf(&self) -> FDF_R { + FDF_R::new(((self.bits[1] >> 21) & 0x01) != 0) + } + #[doc = "Byte 1 - Bits 23 - EFC"] + #[inline(always)] + pub fn efc(&self) -> EFC_R { + EFC_R::new(((self.bits[1] >> 23) & 0x01) != 0) + } + #[doc = "Byte 1 - Bits 24:31 - MM"] + #[inline(always)] + pub fn mm(&self) -> MM_R { + MM_R::new(((self.bits[1] >> 24) & 0xFF) as u8) + } + pub fn to_data_length(&self) -> DataLength { + let dlc = self.dlc().bits(); + let ff = self.fdf().frame_format(); + let len = if ff == FrameFormat::Fdcan { + // See RM0433 Rev 7 Table 475. DLC coding + match dlc { + 0..=8 => dlc, + 9 => 12, + 10 => 16, + 11 => 20, + 12 => 24, + 13 => 32, + 14 => 48, + 15 => 64, + _ => panic!("DLC > 15"), + } + } else { + match dlc { + 0..=8 => dlc, + 9..=15 => 8, + _ => panic!("DLC > 15"), + } + }; + DataLength::new(len, ff) + } + pub fn to_event(&self) -> Event { + let mm = self.mm().bits(); + let efc = self.efc().to_event_control(); + match efc { + EventControl::DoNotStore => Event::NoEvent, + EventControl::Store => Event::Event(mm), + } + } +} +impl W { + #[doc = "Byte 0 - Bits 0:28 - ID"] + #[inline(always)] + pub fn id(&mut self) -> ID_W { + ID_W { w: self } + } + #[doc = "Byte 0 - Bit 29 - RTR"] + #[inline(always)] + pub fn rtr(&mut self) -> RTR_W { + RTR_W { w: self } + } + #[doc = "Byte 0 - Bit 30 - XTD"] + #[inline(always)] + pub fn xtd(&mut self) -> XTD_W { + XTD_W { w: self } + } + #[doc = "Byte 0 - Bit 31 - ESI"] + #[inline(always)] + pub fn esi(&mut self) -> ESI_W { + ESI_W { w: self } + } + #[doc = "Byte 1 - Bit 16:19 - DLC"] + #[inline(always)] + pub fn dlc(&mut self) -> DLC_W { + DLC_W { w: self } + } + #[doc = "Byte 1 - Bit 20 - BRS"] + #[inline(always)] + pub fn brs(&mut self) -> BRS_W { + BRS_W { w: self } + } + #[doc = "Byte 1 - Bit 21 - FDF"] + #[inline(always)] + pub fn fdf(&mut self) -> FDF_W { + FDF_W { w: self } + } + #[doc = "Byte 1 - Bit 23 - EFC"] + #[inline(always)] + pub fn efc(&mut self) -> EFC_W { + EFC_W { w: self } + } + #[doc = "Byte 1 - Bit 24:31 - MM"] + #[inline(always)] + pub fn mm(&mut self) -> MM_W { + MM_W { w: self } + } + #[doc = "Convenience function for setting the data length and frame format"] + #[inline(always)] + pub fn set_len(&mut self, dl: impl Into) -> &mut Self { + let dl: DataLength = dl.into(); + self.fdf().set_format(dl.into()); + unsafe { self.dlc().bits(dl.dlc()) } + } + pub fn set_event(&mut self, event: Event) -> &mut Self { + self.mm().set_message_marker(event.into()); + self.efc().set_event_control(event.into()) + } +} diff --git a/embassy-stm32/src/can/fd/message_ram/txevent_element.rs b/embassy-stm32/src/can/fd/message_ram/txevent_element.rs new file mode 100644 index 000000000..817a4449f --- /dev/null +++ b/embassy-stm32/src/can/fd/message_ram/txevent_element.rs @@ -0,0 +1,138 @@ +// Note: This file is copied and modified from fdcan crate by Richard Meadows + +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(unused)] + +use super::common::{BRS_R, DLC_R, ESI_R, RTR_R, XTD_R}; +use super::generic; + +#[doc = "Reader of register TxEventElement"] +pub(crate) type R = generic::R; +// #[doc = "Writer for register TxEventElement"] +// pub(crate) type W = generic::W; +#[doc = "Register TxEventElement `reset()`'s"] +impl generic::ResetValue for super::TxEventElement { + type Type = super::TxEventElementType; + #[inline(always)] + fn reset_value() -> Self::Type { + [0, 0] + } +} + +#[doc = "Reader of field `ID`"] +pub(crate) type ID_R = generic::R; + +#[doc = "Reader of field `TXTS`"] +pub(crate) type TXTS_R = generic::R; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum DataLengthFormat { + StandardLength = 0, + FDCANLength = 1, +} +impl From for bool { + #[inline(always)] + fn from(dlf: DataLengthFormat) -> Self { + dlf as u8 != 0 + } +} + +#[doc = "Reader of field `EDL`"] +pub(crate) type EDL_R = generic::R; +impl EDL_R { + pub fn data_length_format(&self) -> DataLengthFormat { + match self.bits() { + false => DataLengthFormat::StandardLength, + true => DataLengthFormat::FDCANLength, + } + } + pub fn is_standard_length(&self) -> bool { + *self == DataLengthFormat::StandardLength + } + pub fn is_fdcan_length(&self) -> bool { + *self == DataLengthFormat::FDCANLength + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum EventType { + //_Reserved = 0b00, + TxEvent = 0b01, + TxDespiteAbort = 0b10, + //_Reserved = 0b10, +} + +#[doc = "Reader of field `EFC`"] +pub(crate) type EFC_R = generic::R; +impl EFC_R { + pub fn event_type(&self) -> EventType { + match self.bits() { + 0b01 => EventType::TxEvent, + 0b10 => EventType::TxDespiteAbort, + _ => unimplemented!(), + } + } + pub fn is_tx_event(&self) -> bool { + self.event_type() == EventType::TxEvent + } + pub fn is_despite_abort(&self) -> bool { + self.event_type() == EventType::TxDespiteAbort + } +} + +#[doc = "Reader of field `MM`"] +pub(crate) type MM_R = generic::R; + +impl R { + #[doc = "Byte 0 - Bits 0:28 - ID"] + #[inline(always)] + pub fn id(&self) -> ID_R { + ID_R::new(((self.bits[0]) & 0x1FFFFFFF) as u32) + } + #[doc = "Byte 0 - Bit 29 - RTR"] + #[inline(always)] + pub fn rtr(&self) -> RTR_R { + RTR_R::new(((self.bits[0] >> 29) & 0x01) != 0) + } + #[doc = "Byte 0 - Bit 30 - XTD"] + #[inline(always)] + pub fn xtd(&self) -> XTD_R { + XTD_R::new(((self.bits[0] >> 30) & 0x01) != 0) + } + #[doc = "Byte 0 - Bit 30 - ESI"] + #[inline(always)] + pub fn esi(&self) -> ESI_R { + ESI_R::new(((self.bits[0] >> 31) & 0x01) != 0) + } + #[doc = "Byte 1 - Bits 0:15 - TXTS"] + #[inline(always)] + pub fn txts(&self) -> TXTS_R { + TXTS_R::new(((self.bits[1]) & 0xFFFF) as u16) + } + #[doc = "Byte 1 - Bits 16:19 - DLC"] + #[inline(always)] + pub fn dlc(&self) -> DLC_R { + DLC_R::new(((self.bits[1] >> 16) & 0x0F) as u8) + } + #[doc = "Byte 1 - Bits 20 - BRS"] + #[inline(always)] + pub fn brs(&self) -> BRS_R { + BRS_R::new(((self.bits[1] >> 20) & 0x01) != 0) + } + #[doc = "Byte 1 - Bits 21 - EDL"] + #[inline(always)] + pub fn edl(&self) -> EDL_R { + EDL_R::new(((self.bits[1] >> 21) & 0x01) != 0) + } + #[doc = "Byte 1 - Bits 22:23 - EFC"] + #[inline(always)] + pub fn efc(&self) -> EFC_R { + EFC_R::new(((self.bits[1] >> 22) & 0x03) as u8) + } + #[doc = "Byte 1 - Bits 24:31 - MM"] + #[inline(always)] + pub fn mm(&self) -> MM_R { + MM_R::new(((self.bits[1] >> 24) & 0xFF) as u8) + } +} diff --git a/embassy-stm32/src/can/fd/mod.rs b/embassy-stm32/src/can/fd/mod.rs new file mode 100644 index 000000000..271ca0b3c --- /dev/null +++ b/embassy-stm32/src/can/fd/mod.rs @@ -0,0 +1,6 @@ +//! Module containing that which is specific to fdcan hardware variant + +pub mod config; +pub mod filter; +pub(crate) mod message_ram; +pub(crate) mod peripheral; diff --git a/embassy-stm32/src/can/fd/peripheral.rs b/embassy-stm32/src/can/fd/peripheral.rs new file mode 100644 index 000000000..1c7abfcb2 --- /dev/null +++ b/embassy-stm32/src/can/fd/peripheral.rs @@ -0,0 +1,738 @@ +// Note: This file is copied and modified from fdcan crate by Richard Meadows + +use core::convert::Infallible; +use core::slice; + +use cfg_if::cfg_if; + +use crate::can::enums::*; +use crate::can::fd::config::*; +use crate::can::fd::message_ram::enums::*; +use crate::can::fd::message_ram::{RegisterBlock, RxFifoElement, TxBufferElement}; +use crate::can::frame::*; + +/// Loopback Mode +#[derive(Clone, Copy, Debug)] +enum LoopbackMode { + None, + Internal, + External, +} + +pub struct Registers { + pub regs: crate::pac::can::Fdcan, + pub msgram: crate::pac::fdcanram::Fdcanram, + #[allow(dead_code)] + pub msg_ram_offset: usize, +} + +impl Registers { + fn tx_buffer_element(&self, bufidx: usize) -> &mut TxBufferElement { + &mut self.msg_ram_mut().transmit.tbsa[bufidx] + } + pub fn msg_ram_mut(&self) -> &mut RegisterBlock { + #[cfg(can_fdcan_h7)] + let ptr = self.msgram.ram(self.msg_ram_offset / 4).as_ptr() as *mut RegisterBlock; + + #[cfg(not(can_fdcan_h7))] + let ptr = self.msgram.as_ptr() as *mut RegisterBlock; + + unsafe { &mut (*ptr) } + } + + fn rx_fifo_element(&self, fifonr: usize, bufnum: usize) -> &mut RxFifoElement { + &mut self.msg_ram_mut().receive[fifonr].fxsa[bufnum] + } + + pub fn read(&self, fifonr: usize) -> Option<(F, u16)> { + // Fill level - do we have a msg? + if self.regs.rxfs(fifonr).read().ffl() < 1 { + return None; + } + + let read_idx = self.regs.rxfs(fifonr).read().fgi(); + let mailbox = self.rx_fifo_element(fifonr, read_idx as usize); + + let mut buffer = [0u8; 64]; + let maybe_header = extract_frame(mailbox, &mut buffer); + + // Clear FIFO, reduces count and increments read buf + self.regs.rxfa(fifonr).modify(|w| w.set_fai(read_idx)); + + match maybe_header { + Some((header, ts)) => { + let data = &buffer[0..header.len() as usize]; + match F::from_header(header, data) { + Ok(frame) => Some((frame, ts)), + Err(_) => None, + } + } + None => None, + } + } + + pub fn put_tx_frame(&self, bufidx: usize, header: &Header, buffer: &[u8]) { + let mailbox = self.tx_buffer_element(bufidx); + mailbox.reset(); + put_tx_header(mailbox, header); + put_tx_data(mailbox, &buffer[..header.len() as usize]); + + // Set as ready to transmit + self.regs.txbar().modify(|w| w.set_ar(bufidx, true)); + } + + fn reg_to_error(value: u8) -> Option { + match value { + //0b000 => None, + 0b001 => Some(BusError::Stuff), + 0b010 => Some(BusError::Form), + 0b011 => Some(BusError::Acknowledge), + 0b100 => Some(BusError::BitRecessive), + 0b101 => Some(BusError::BitDominant), + 0b110 => Some(BusError::Crc), + //0b111 => Some(BusError::NoError), + _ => None, + } + } + + pub fn curr_error(&self) -> Option { + let err = { self.regs.psr().read() }; + if err.bo() { + return Some(BusError::BusOff); + } else if err.ep() { + return Some(BusError::BusPassive); + } else if err.ew() { + return Some(BusError::BusWarning); + } else { + cfg_if! { + if #[cfg(can_fdcan_h7)] { + let lec = err.lec(); + } else { + let lec = err.lec().to_bits(); + } + } + if let Some(err) = Self::reg_to_error(lec) { + return Some(err); + } + } + None + } + /// Returns if the tx queue is able to accept new messages without having to cancel an existing one + #[inline] + pub fn tx_queue_is_full(&self) -> bool { + self.regs.txfqs().read().tfqf() + } + + /// Returns the current TX buffer operation mode (queue or FIFO) + #[inline] + pub fn tx_queue_mode(&self) -> TxBufferMode { + self.regs.txbc().read().tfqm().into() + } + + #[inline] + pub fn has_pending_frame(&self, idx: usize) -> bool { + self.regs.txbrp().read().trp(idx) + } + + /// Returns `Ok` when the mailbox is free or if it contains pending frame with a + /// lower priority (higher ID) than the identifier `id`. + #[inline] + pub fn is_available(&self, bufidx: usize, id: &embedded_can::Id) -> bool { + if self.has_pending_frame(bufidx) { + let mailbox = self.tx_buffer_element(bufidx); + + let header_reg = mailbox.header.read(); + let old_id = make_id(header_reg.id().bits(), header_reg.xtd().bits()); + + *id > old_id + } else { + true + } + } + + /// Attempts to abort the sending of a frame that is pending in a mailbox. + /// + /// If there is no frame in the provided mailbox, or its transmission succeeds before it can be + /// aborted, this function has no effect and returns `false`. + /// + /// If there is a frame in the provided mailbox, and it is canceled successfully, this function + /// returns `true`. + #[inline] + pub fn abort(&self, bufidx: usize) -> bool { + let can = self.regs; + + // Check if there is a request pending to abort + if self.has_pending_frame(bufidx) { + // Abort Request + can.txbcr().write(|w| w.set_cr(bufidx, true)); + + // Wait for the abort request to be finished. + loop { + if can.txbcf().read().cf(bufidx) { + // Return false when a transmission has occured + break can.txbto().read().to(bufidx) == false; + } + } + } else { + false + } + } + + #[inline] + fn abort_pending_mailbox(&self, bufidx: usize) -> Option { + if self.abort(bufidx) { + let mailbox = self.tx_buffer_element(bufidx); + + let header_reg = mailbox.header.read(); + let id = make_id(header_reg.id().bits(), header_reg.xtd().bits()); + + let len = match header_reg.to_data_length() { + DataLength::Fdcan(len) => len, + DataLength::Classic(len) => len, + }; + if len as usize > ClassicData::MAX_DATA_LEN { + return None; + } + + let mut data = [0u8; 64]; + data_from_tx_buffer(&mut data, mailbox, len as usize); + + if header_reg.rtr().bit() { + F::new_remote(id, len as usize) + } else { + F::new(id, &data[0..(len as usize)]) + } + } else { + // Abort request failed because the frame was already sent (or being sent) on + // the bus. All mailboxes are now free. This can happen for small prescaler + // values (e.g. 1MBit/s bit timing with a source clock of 8MHz) or when an ISR + // has preempted the execution. + None + } + } + + pub fn write(&self, frame: &F) -> nb::Result, Infallible> { + let (idx, pending_frame) = if self.tx_queue_is_full() { + if self.tx_queue_mode() == TxBufferMode::Fifo { + // Does not make sense to cancel a pending frame when using FIFO + return Err(nb::Error::WouldBlock); + } + // If the queue is full, + // Discard the first slot with a lower priority message + let id = frame.header().id(); + if self.is_available(0, id) { + (0, self.abort_pending_mailbox(0)) + } else if self.is_available(1, id) { + (1, self.abort_pending_mailbox(1)) + } else if self.is_available(2, id) { + (2, self.abort_pending_mailbox(2)) + } else { + // For now we bail when there is no lower priority slot available + // Can this lead to priority inversion? + return Err(nb::Error::WouldBlock); + } + } else { + // Read the Write Pointer + let idx = self.regs.txfqs().read().tfqpi(); + + (idx, None) + }; + + self.put_tx_frame(idx as usize, frame.header(), frame.data()); + + Ok(pending_frame) + } + + #[inline] + fn reset_msg_ram(&self) { + self.msg_ram_mut().reset(); + } + + #[inline] + fn enter_init_mode(&self) { + self.regs.cccr().modify(|w| w.set_init(true)); + while false == self.regs.cccr().read().init() {} + self.regs.cccr().modify(|w| w.set_cce(true)); + } + + /// Enables or disables loopback mode: Internally connects the TX and RX + /// signals together. + #[inline] + fn set_loopback_mode(&self, mode: LoopbackMode) { + let (test, mon, lbck) = match mode { + LoopbackMode::None => (false, false, false), + LoopbackMode::Internal => (true, true, true), + LoopbackMode::External => (true, false, true), + }; + + self.set_test_mode(test); + self.set_bus_monitoring_mode(mon); + + self.regs.test().modify(|w| w.set_lbck(lbck)); + } + + /// Enables or disables silent mode: Disconnects the TX signal from the pin. + #[inline] + fn set_bus_monitoring_mode(&self, enabled: bool) { + self.regs.cccr().modify(|w| w.set_mon(enabled)); + } + + #[inline] + fn set_restricted_operations(&self, enabled: bool) { + self.regs.cccr().modify(|w| w.set_asm(enabled)); + } + + #[inline] + fn set_normal_operations(&self, _enabled: bool) { + self.set_loopback_mode(LoopbackMode::None); + } + + #[inline] + fn set_test_mode(&self, enabled: bool) { + self.regs.cccr().modify(|w| w.set_test(enabled)); + } + + #[inline] + fn set_power_down_mode(&self, enabled: bool) { + self.regs.cccr().modify(|w| w.set_csr(enabled)); + while self.regs.cccr().read().csa() != enabled {} + } + + /// Moves out of PoweredDownMode and into ConfigMode + #[inline] + pub fn into_config_mode(self, _config: FdCanConfig) { + self.set_power_down_mode(false); + self.enter_init_mode(); + self.reset_msg_ram(); + + // check the FDCAN core matches our expections + assert!( + self.regs.crel().read().rel() == 3, + "Expected FDCAN core major release 3" + ); + assert!( + self.regs.endn().read().etv() == 0x87654321_u32, + "Error reading endianness test value from FDCAN core" + ); + + /* + for fid in 0..crate::can::message_ram::STANDARD_FILTER_MAX { + self.set_standard_filter((fid as u8).into(), StandardFilter::disable()); + } + for fid in 0..Ecrate::can::message_ram::XTENDED_FILTER_MAX { + self.set_extended_filter(fid.into(), ExtendedFilter::disable()); + } + */ + } + + /// Applies the settings of a new FdCanConfig See [`FdCanConfig`] + #[inline] + pub fn apply_config(&self, config: FdCanConfig) { + self.set_tx_buffer_mode(config.tx_buffer_mode); + + // set standard filters list size to 28 + // set extended filters list size to 8 + // REQUIRED: we use the memory map as if these settings are set + // instead of re-calculating them. + #[cfg(not(can_fdcan_h7))] + { + self.regs.rxgfc().modify(|w| { + w.set_lss(crate::can::fd::message_ram::STANDARD_FILTER_MAX); + w.set_lse(crate::can::fd::message_ram::EXTENDED_FILTER_MAX); + }); + } + #[cfg(can_fdcan_h7)] + { + self.regs + .sidfc() + .modify(|w| w.set_lss(crate::can::fd::message_ram::STANDARD_FILTER_MAX)); + self.regs + .xidfc() + .modify(|w| w.set_lse(crate::can::fd::message_ram::EXTENDED_FILTER_MAX)); + } + + self.configure_msg_ram(); + + // Enable timestamping + #[cfg(not(can_fdcan_h7))] + self.regs + .tscc() + .write(|w| w.set_tss(stm32_metapac::can::vals::Tss::INCREMENT)); + #[cfg(can_fdcan_h7)] + self.regs.tscc().write(|w| w.set_tss(0x01)); + + // this isn't really documented in the reference manual + // but corresponding txbtie bit has to be set for the TC (TxComplete) interrupt to fire + self.regs.txbtie().write(|w| w.0 = 0xffff_ffff); + self.regs.ie().modify(|w| { + w.set_rfne(0, true); // Rx Fifo 0 New Msg + w.set_rfne(1, true); // Rx Fifo 1 New Msg + w.set_tce(true); // Tx Complete + w.set_boe(true); // Bus-Off Status Changed + }); + self.regs.ile().modify(|w| { + w.set_eint0(true); // Interrupt Line 0 + w.set_eint1(true); // Interrupt Line 1 + }); + + self.set_data_bit_timing(config.dbtr); + self.set_nominal_bit_timing(config.nbtr); + self.set_automatic_retransmit(config.automatic_retransmit); + self.set_transmit_pause(config.transmit_pause); + self.set_frame_transmit(config.frame_transmit); + //self.set_interrupt_line_config(config.interrupt_line_config); + self.set_non_iso_mode(config.non_iso_mode); + self.set_edge_filtering(config.edge_filtering); + self.set_protocol_exception_handling(config.protocol_exception_handling); + self.set_global_filter(config.global_filter); + } + + #[inline] + fn leave_init_mode(&self, config: FdCanConfig) { + self.apply_config(config); + + self.regs.cccr().modify(|w| w.set_cce(false)); + self.regs.cccr().modify(|w| w.set_init(false)); + while self.regs.cccr().read().init() == true {} + } + + /// Moves out of ConfigMode and into specified mode + #[inline] + pub fn into_mode(&self, config: FdCanConfig, mode: crate::can::_version::OperatingMode) { + match mode { + crate::can::OperatingMode::InternalLoopbackMode => self.set_loopback_mode(LoopbackMode::Internal), + crate::can::OperatingMode::ExternalLoopbackMode => self.set_loopback_mode(LoopbackMode::External), + crate::can::OperatingMode::NormalOperationMode => self.set_normal_operations(true), + crate::can::OperatingMode::RestrictedOperationMode => self.set_restricted_operations(true), + crate::can::OperatingMode::BusMonitoringMode => self.set_bus_monitoring_mode(true), + } + self.leave_init_mode(config); + } + + /// Configures the bit timings. + /// + /// You can use to calculate the `btr` parameter. Enter + /// parameters as follows: + /// + /// - *Clock Rate*: The input clock speed to the CAN peripheral (*not* the CPU clock speed). + /// This is the clock rate of the peripheral bus the CAN peripheral is attached to (eg. APB1). + /// - *Sample Point*: Should normally be left at the default value of 87.5%. + /// - *SJW*: Should normally be left at the default value of 1. + /// + /// Then copy the `CAN_BUS_TIME` register value from the table and pass it as the `btr` + /// parameter to this method. + #[inline] + pub fn set_nominal_bit_timing(&self, btr: NominalBitTiming) { + self.regs.nbtp().write(|w| { + w.set_nbrp(btr.nbrp() - 1); + w.set_ntseg1(btr.ntseg1() - 1); + w.set_ntseg2(btr.ntseg2() - 1); + w.set_nsjw(btr.nsjw() - 1); + }); + } + + /// Configures the data bit timings for the FdCan Variable Bitrates. + /// This is not used when frame_transmit is set to anything other than AllowFdCanAndBRS. + #[inline] + pub fn set_data_bit_timing(&self, btr: DataBitTiming) { + self.regs.dbtp().write(|w| { + w.set_dbrp(btr.dbrp() - 1); + w.set_dtseg1(btr.dtseg1() - 1); + w.set_dtseg2(btr.dtseg2() - 1); + w.set_dsjw(btr.dsjw() - 1); + }); + } + + /// Enables or disables automatic retransmission of messages + /// + /// If this is enabled, the CAN peripheral will automatically try to retransmit each frame + /// util it can be sent. Otherwise, it will try only once to send each frame. + /// + /// Automatic retransmission is enabled by default. + #[inline] + pub fn set_automatic_retransmit(&self, enabled: bool) { + self.regs.cccr().modify(|w| w.set_dar(!enabled)); + } + + /// Configures the transmit pause feature. See + /// [`FdCanConfig::set_transmit_pause`] + #[inline] + pub fn set_transmit_pause(&self, enabled: bool) { + self.regs.cccr().modify(|w| w.set_txp(!enabled)); + } + + /// Configures non-iso mode. See [`FdCanConfig::set_non_iso_mode`] + #[inline] + pub fn set_non_iso_mode(&self, enabled: bool) { + self.regs.cccr().modify(|w| w.set_niso(enabled)); + } + + /// Configures edge filtering. See [`FdCanConfig::set_edge_filtering`] + #[inline] + pub fn set_edge_filtering(&self, enabled: bool) { + self.regs.cccr().modify(|w| w.set_efbi(enabled)); + } + + /// Configures TX Buffer Mode + #[inline] + pub fn set_tx_buffer_mode(&self, tbm: TxBufferMode) { + self.regs.txbc().write(|w| w.set_tfqm(tbm.into())); + } + + /// Configures frame transmission mode. See + /// [`FdCanConfig::set_frame_transmit`] + #[inline] + pub fn set_frame_transmit(&self, fts: FrameTransmissionConfig) { + let (fdoe, brse) = match fts { + FrameTransmissionConfig::ClassicCanOnly => (false, false), + FrameTransmissionConfig::AllowFdCan => (true, false), + FrameTransmissionConfig::AllowFdCanAndBRS => (true, true), + }; + + self.regs.cccr().modify(|w| { + w.set_fdoe(fdoe); + #[cfg(can_fdcan_h7)] + w.set_bse(brse); + #[cfg(not(can_fdcan_h7))] + w.set_brse(brse); + }); + } + + /// Sets the protocol exception handling on/off + #[inline] + pub fn set_protocol_exception_handling(&self, enabled: bool) { + self.regs.cccr().modify(|w| w.set_pxhd(!enabled)); + } + + /// Configures and resets the timestamp counter + #[inline] + #[allow(unused)] + pub fn set_timestamp_counter_source(&self, select: TimestampSource) { + #[cfg(can_fdcan_h7)] + let (tcp, tss) = match select { + TimestampSource::None => (0, 0), + TimestampSource::Prescaler(p) => (p as u8, 1), + TimestampSource::FromTIM3 => (0, 2), + }; + + #[cfg(not(can_fdcan_h7))] + let (tcp, tss) = match select { + TimestampSource::None => (0, stm32_metapac::can::vals::Tss::ZERO), + TimestampSource::Prescaler(p) => (p as u8, stm32_metapac::can::vals::Tss::INCREMENT), + TimestampSource::FromTIM3 => (0, stm32_metapac::can::vals::Tss::EXTERNAL), + }; + + self.regs.tscc().write(|w| { + w.set_tcp(tcp); + w.set_tss(tss); + }); + } + + #[cfg(not(can_fdcan_h7))] + /// Configures the global filter settings + #[inline] + pub fn set_global_filter(&self, filter: GlobalFilter) { + let anfs = match filter.handle_standard_frames { + crate::can::fd::config::NonMatchingFilter::IntoRxFifo0 => stm32_metapac::can::vals::Anfs::ACCEPT_FIFO_0, + crate::can::fd::config::NonMatchingFilter::IntoRxFifo1 => stm32_metapac::can::vals::Anfs::ACCEPT_FIFO_1, + crate::can::fd::config::NonMatchingFilter::Reject => stm32_metapac::can::vals::Anfs::REJECT, + }; + let anfe = match filter.handle_extended_frames { + crate::can::fd::config::NonMatchingFilter::IntoRxFifo0 => stm32_metapac::can::vals::Anfe::ACCEPT_FIFO_0, + crate::can::fd::config::NonMatchingFilter::IntoRxFifo1 => stm32_metapac::can::vals::Anfe::ACCEPT_FIFO_1, + crate::can::fd::config::NonMatchingFilter::Reject => stm32_metapac::can::vals::Anfe::REJECT, + }; + + self.regs.rxgfc().modify(|w| { + w.set_anfs(anfs); + w.set_anfe(anfe); + w.set_rrfs(filter.reject_remote_standard_frames); + w.set_rrfe(filter.reject_remote_extended_frames); + }); + } + + #[cfg(can_fdcan_h7)] + /// Configures the global filter settings + #[inline] + pub fn set_global_filter(&self, filter: GlobalFilter) { + let anfs = match filter.handle_standard_frames { + crate::can::fd::config::NonMatchingFilter::IntoRxFifo0 => 0, + crate::can::fd::config::NonMatchingFilter::IntoRxFifo1 => 1, + crate::can::fd::config::NonMatchingFilter::Reject => 2, + }; + + let anfe = match filter.handle_extended_frames { + crate::can::fd::config::NonMatchingFilter::IntoRxFifo0 => 0, + crate::can::fd::config::NonMatchingFilter::IntoRxFifo1 => 1, + crate::can::fd::config::NonMatchingFilter::Reject => 2, + }; + + self.regs.gfc().modify(|w| { + w.set_anfs(anfs); + w.set_anfe(anfe); + w.set_rrfs(filter.reject_remote_standard_frames); + w.set_rrfe(filter.reject_remote_extended_frames); + }); + } + + #[cfg(not(can_fdcan_h7))] + fn configure_msg_ram(&self) {} + + #[cfg(can_fdcan_h7)] + fn configure_msg_ram(&self) { + let r = self.regs; + + use crate::can::fd::message_ram::*; + //use fdcan::message_ram::*; + let mut offset_words = (self.msg_ram_offset / 4) as u16; + + // 11-bit filter + r.sidfc().modify(|w| w.set_flssa(offset_words)); + offset_words += STANDARD_FILTER_MAX as u16; + + // 29-bit filter + r.xidfc().modify(|w| w.set_flesa(offset_words)); + offset_words += 2 * EXTENDED_FILTER_MAX as u16; + + // Rx FIFO 0 and 1 + for i in 0..=1 { + r.rxfc(i).modify(|w| { + w.set_fsa(offset_words); + w.set_fs(RX_FIFO_MAX); + w.set_fwm(RX_FIFO_MAX); + }); + offset_words += 18 * RX_FIFO_MAX as u16; + } + + // Rx buffer - see below + // Tx event FIFO + r.txefc().modify(|w| { + w.set_efsa(offset_words); + w.set_efs(TX_EVENT_MAX); + w.set_efwm(TX_EVENT_MAX); + }); + offset_words += 2 * TX_EVENT_MAX as u16; + + // Tx buffers + r.txbc().modify(|w| { + w.set_tbsa(offset_words); + w.set_tfqs(TX_FIFO_MAX); + }); + offset_words += 18 * TX_FIFO_MAX as u16; + + // Rx Buffer - not used + r.rxbc().modify(|w| { + w.set_rbsa(offset_words); + }); + + // TX event FIFO? + // Trigger memory? + + // Set the element sizes to 16 bytes + r.rxesc().modify(|w| { + w.set_rbds(0b111); + for i in 0..=1 { + w.set_fds(i, 0b111); + } + }); + r.txesc().modify(|w| { + w.set_tbds(0b111); + }) + } +} + +fn make_id(id: u32, extended: bool) -> embedded_can::Id { + if extended { + embedded_can::Id::from(unsafe { embedded_can::ExtendedId::new_unchecked(id & 0x1FFFFFFF) }) + } else { + // A standard identifier is stored into ID[28:18]. + embedded_can::Id::from(unsafe { embedded_can::StandardId::new_unchecked(((id >> 18) & 0x000007FF) as u16) }) + } +} + +fn put_tx_header(mailbox: &mut TxBufferElement, header: &Header) { + let (id, id_type) = match header.id() { + // A standard identifier has to be written to ID[28:18]. + embedded_can::Id::Standard(id) => ((id.as_raw() as u32) << 18, IdType::StandardId), + embedded_can::Id::Extended(id) => (id.as_raw() as u32, IdType::ExtendedId), + }; + + // Use FDCAN only for DLC > 8. FDCAN users can revise this if required. + let frame_format = if header.len() > 8 || header.fdcan() { + FrameFormat::Fdcan + } else { + FrameFormat::Classic + }; + let brs = (frame_format == FrameFormat::Fdcan) && header.bit_rate_switching(); + + mailbox.header.write(|w| { + unsafe { w.id().bits(id) } + .rtr() + .bit(header.len() == 0 && header.rtr()) + .xtd() + .set_id_type(id_type) + .set_len(DataLength::new(header.len(), frame_format)) + .set_event(Event::NoEvent) + .fdf() + .set_format(frame_format) + .brs() + .bit(brs) + //esi.set_error_indicator(//TODO//) + }); +} + +fn put_tx_data(mailbox: &mut TxBufferElement, buffer: &[u8]) { + let mut lbuffer = [0_u32; 16]; + let len = buffer.len(); + let data = unsafe { slice::from_raw_parts_mut(lbuffer.as_mut_ptr() as *mut u8, len) }; + data[..len].copy_from_slice(&buffer[..len]); + let data_len = ((len) + 3) / 4; + for (register, byte) in mailbox.data.iter_mut().zip(lbuffer[..data_len].iter()) { + unsafe { register.write(*byte) }; + } +} + +fn data_from_fifo(buffer: &mut [u8], mailbox: &RxFifoElement, len: usize) { + for (i, register) in mailbox.data.iter().enumerate() { + let register_value = register.read(); + let register_bytes = unsafe { slice::from_raw_parts(®ister_value as *const u32 as *const u8, 4) }; + let num_bytes = (len) - i * 4; + if num_bytes <= 4 { + buffer[i * 4..i * 4 + num_bytes].copy_from_slice(®ister_bytes[..num_bytes]); + break; + } + buffer[i * 4..(i + 1) * 4].copy_from_slice(register_bytes); + } +} + +fn data_from_tx_buffer(buffer: &mut [u8], mailbox: &TxBufferElement, len: usize) { + for (i, register) in mailbox.data.iter().enumerate() { + let register_value = register.read(); + let register_bytes = unsafe { slice::from_raw_parts(®ister_value as *const u32 as *const u8, 4) }; + let num_bytes = (len) - i * 4; + if num_bytes <= 4 { + buffer[i * 4..i * 4 + num_bytes].copy_from_slice(®ister_bytes[..num_bytes]); + break; + } + buffer[i * 4..(i + 1) * 4].copy_from_slice(register_bytes); + } +} + +fn extract_frame(mailbox: &RxFifoElement, buffer: &mut [u8]) -> Option<(Header, u16)> { + let header_reg = mailbox.header.read(); + + let id = make_id(header_reg.id().bits(), header_reg.xtd().bits()); + let dlc = header_reg.to_data_length().len(); + let len = dlc as usize; + let timestamp = header_reg.txts().bits; + if len > buffer.len() { + return None; + } + data_from_fifo(buffer, mailbox, len); + let header = if header_reg.fdf().bits { + Header::new_fd(id, dlc, header_reg.rtr().bits(), header_reg.brs().bits()) + } else { + Header::new(id, dlc, header_reg.rtr().bits()) + }; + Some((header, timestamp)) +} diff --git a/embassy-stm32/src/can/fdcan.rs b/embassy-stm32/src/can/fdcan.rs index faf4af73f..c549313f3 100644 --- a/embassy-stm32/src/can/fdcan.rs +++ b/embassy-stm32/src/can/fdcan.rs @@ -1,146 +1,37 @@ +#[allow(unused_variables)] use core::future::poll_fn; use core::marker::PhantomData; -use core::ops::{Deref, DerefMut}; use core::task::Poll; -use cfg_if::cfg_if; +use embassy_hal_internal::interrupt::InterruptExt; use embassy_hal_internal::{into_ref, PeripheralRef}; -pub use fdcan::frame::{FrameFormat, RxFrameInfo, TxFrameHeader}; -pub use fdcan::id::{ExtendedId, Id, StandardId}; -use fdcan::message_ram::RegisterBlock; -use fdcan::{self, LastErrorCode}; -pub use fdcan::{config, filter}; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +use embassy_sync::channel::{Channel, DynamicReceiver, DynamicSender}; +use embassy_sync::waitqueue::AtomicWaker; -use crate::gpio::sealed::AFType; +use crate::can::fd::peripheral::Registers; +use crate::gpio::{AfType, OutputType, Pull, Speed}; use crate::interrupt::typelevel::Interrupt; -use crate::rcc::RccPeripheral; +use crate::rcc::{self, RccPeripheral}; use crate::{interrupt, peripherals, Peripheral}; -pub mod enums; -use enums::*; -pub mod util; +pub(crate) mod fd; -/// CAN Frame returned by read -pub struct RxFrame { - /// CAN Header info: frame ID, data length and other meta - pub header: RxFrameInfo, - /// CAN(0-8 bytes) or FDCAN(0-64 bytes) Frame data - pub data: Data, - /// Reception time. - #[cfg(feature = "time")] - pub timestamp: embassy_time::Instant, -} +use self::fd::config::*; +use self::fd::filter::*; +pub use self::fd::{config, filter}; +pub use super::common::{BufferedCanReceiver, BufferedCanSender}; +use super::enums::*; +use super::frame::*; +use super::util; -/// CAN frame used for write -pub struct TxFrame { - /// CAN Header info: frame ID, data length and other meta - pub header: TxFrameHeader, - /// CAN(0-8 bytes) or FDCAN(0-64 bytes) Frame data - pub data: Data, -} +/// Timestamp for incoming packets. Use Embassy time when enabled. +#[cfg(feature = "time")] +pub type Timestamp = embassy_time::Instant; -impl TxFrame { - /// Create new TX frame from header and data - pub fn new(header: TxFrameHeader, data: &[u8]) -> Option { - if data.len() < header.len as usize { - return None; - } - - let Some(data) = Data::new(data) else { return None }; - - Some(TxFrame { header, data }) - } - - fn from_preserved(header: TxFrameHeader, data32: &[u32]) -> Option { - let mut data = [0u8; 64]; - - for i in 0..data32.len() { - data[4 * i..][..4].copy_from_slice(&data32[i].to_le_bytes()); - } - - let Some(data) = Data::new(&data) else { return None }; - - Some(TxFrame { header, data }) - } - - /// Access frame data. Slice length will match header. - pub fn data(&self) -> &[u8] { - &self.data.bytes[..(self.header.len as usize)] - } -} - -impl RxFrame { - pub(crate) fn new( - header: RxFrameInfo, - data: &[u8], - #[cfg(feature = "time")] timestamp: embassy_time::Instant, - ) -> Self { - let data = Data::new(&data).unwrap_or_else(|| Data::empty()); - - RxFrame { - header, - data, - #[cfg(feature = "time")] - timestamp, - } - } - - /// Access frame data. Slice length will match header. - pub fn data(&self) -> &[u8] { - &self.data.bytes[..(self.header.len as usize)] - } -} - -/// Payload of a (FD)CAN data frame. -/// -/// Contains 0 to 64 Bytes of data. -#[derive(Debug, Copy, Clone)] -pub struct Data { - pub(crate) bytes: [u8; 64], -} - -impl Data { - /// Creates a data payload from a raw byte slice. - /// - /// Returns `None` if `data` is more than 64 bytes (which is the maximum) or - /// cannot be represented with an FDCAN DLC. - pub fn new(data: &[u8]) -> Option { - if !Data::is_valid_len(data.len()) { - return None; - } - - let mut bytes = [0; 64]; - bytes[..data.len()].copy_from_slice(data); - - Some(Self { bytes }) - } - - /// Raw read access to data. - pub fn raw(&self) -> &[u8] { - &self.bytes - } - - /// Checks if the length can be encoded in FDCAN DLC field. - pub const fn is_valid_len(len: usize) -> bool { - match len { - 0..=8 => true, - 12 => true, - 16 => true, - 20 => true, - 24 => true, - 32 => true, - 48 => true, - 64 => true, - _ => false, - } - } - - /// Creates an empty data payload containing 0 bytes. - #[inline] - pub const fn empty() -> Self { - Self { bytes: [0; 64] } - } -} +/// Timestamp for incoming packets. +#[cfg(not(feature = "time"))] +pub type Timestamp = u16; /// Interrupt handler channel 0. pub struct IT0InterruptHandler { @@ -150,35 +41,54 @@ pub struct IT0InterruptHandler { // We use IT0 for everything currently impl interrupt::typelevel::Handler for IT0InterruptHandler { unsafe fn on_interrupt() { - let regs = T::regs(); + let regs = T::registers().regs; let ir = regs.ir().read(); if ir.tc() { regs.ir().write(|w| w.set_tc(true)); - T::state().tx_waker.wake(); } - if ir.tefn() { regs.ir().write(|w| w.set_tefn(true)); - T::state().tx_waker.wake(); } - if ir.ped() || ir.pea() { - regs.ir().write(|w| { - w.set_ped(true); - w.set_pea(true); - }); + match &T::state().tx_mode { + TxMode::NonBuffered(waker) => waker.wake(), + TxMode::ClassicBuffered(buf) => { + if !T::registers().tx_queue_is_full() { + match buf.tx_receiver.try_receive() { + Ok(frame) => { + _ = T::registers().write(&frame); + } + Err(_) => {} + } + } + } + TxMode::FdBuffered(buf) => { + if !T::registers().tx_queue_is_full() { + match buf.tx_receiver.try_receive() { + Ok(frame) => { + _ = T::registers().write(&frame); + } + Err(_) => {} + } + } + } } if ir.rfn(0) { - regs.ir().write(|w| w.set_rfn(0, true)); - T::state().rx_waker.wake(); + T::state().rx_mode.on_interrupt::(0); + } + if ir.rfn(1) { + T::state().rx_mode.on_interrupt::(1); } - if ir.rfn(1) { - regs.ir().write(|w| w.set_rfn(1, true)); - T::state().rx_waker.wake(); + if ir.bo() { + regs.ir().write(|w| w.set_bo(true)); + if regs.psr().read().bo() { + // Initiate bus-off recovery sequence by resetting CCCR.INIT + regs.cccr().modify(|w| w.set_init(false)); + } } } } @@ -192,47 +102,55 @@ impl interrupt::typelevel::Handler for IT1Interrup unsafe fn on_interrupt() {} } -impl BusError { - fn try_from(lec: LastErrorCode) -> Option { - match lec { - LastErrorCode::AckError => Some(BusError::Acknowledge), - // `0` data bit encodes a dominant state. `1` data bit is recessive. - // Bit0Error: During transmit, the node wanted to send a 0 but monitored a 1 - LastErrorCode::Bit0Error => Some(BusError::BitRecessive), - LastErrorCode::Bit1Error => Some(BusError::BitDominant), - LastErrorCode::CRCError => Some(BusError::Crc), - LastErrorCode::FormError => Some(BusError::Form), - LastErrorCode::StuffError => Some(BusError::Stuff), - _ => None, - } - } +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +/// Different operating modes +pub enum OperatingMode { + //PoweredDownMode, + //ConfigMode, + /// This mode can be used for a “Hot Selftest”, meaning the FDCAN can be tested without + /// affecting a running CAN system connected to the FDCAN_TX and FDCAN_RX pins. In this + /// mode, FDCAN_RX pin is disconnected from the FDCAN and FDCAN_TX pin is held + /// recessive. + InternalLoopbackMode, + /// This mode is provided for hardware self-test. To be independent from external stimulation, + /// the FDCAN ignores acknowledge errors (recessive bit sampled in the acknowledge slot of a + /// data / remote frame) in Loop Back mode. In this mode the FDCAN performs an internal + /// feedback from its transmit output to its receive input. The actual value of the FDCAN_RX + /// input pin is disregarded by the FDCAN. The transmitted messages can be monitored at the + /// FDCAN_TX transmit pin. + ExternalLoopbackMode, + /// The normal use of the Fdcan instance after configurations + NormalOperationMode, + /// In Restricted operation mode the node is able to receive data and remote frames and to give + /// acknowledge to valid frames, but it does not send data frames, remote frames, active error + /// frames, or overload frames. In case of an error condition or overload condition, it does not + /// send dominant bits, instead it waits for the occurrence of bus idle condition to resynchronize + /// itself to the CAN communication. The error counters for transmit and receive are frozen while + /// error logging (can_errors) is active. TODO: automatically enter in this mode? + RestrictedOperationMode, + /// In Bus monitoring mode (for more details refer to ISO11898-1, 10.12 Bus monitoring), + /// the FDCAN is able to receive valid data frames and valid remote frames, but cannot start a + /// transmission. In this mode, it sends only recessive bits on the CAN bus. If the FDCAN is + /// required to send a dominant bit (ACK bit, overload flag, active error flag), the bit is + /// rerouted internally so that the FDCAN can monitor it, even if the CAN bus remains in recessive + /// state. In Bus monitoring mode the TXBRP register is held in reset state. The Bus monitoring + /// mode can be used to analyze the traffic on a CAN bus without affecting it by the transmission + /// of dominant bits. + BusMonitoringMode, + //TestMode, } -/// Operating modes trait -pub trait FdcanOperatingMode {} -impl FdcanOperatingMode for fdcan::PoweredDownMode {} -impl FdcanOperatingMode for fdcan::ConfigMode {} -impl FdcanOperatingMode for fdcan::InternalLoopbackMode {} -impl FdcanOperatingMode for fdcan::ExternalLoopbackMode {} -impl FdcanOperatingMode for fdcan::NormalOperationMode {} -impl FdcanOperatingMode for fdcan::RestrictedOperationMode {} -impl FdcanOperatingMode for fdcan::BusMonitoringMode {} -impl FdcanOperatingMode for fdcan::TestMode {} - -/// FDCAN Instance -pub struct Fdcan<'d, T: Instance, M: FdcanOperatingMode> { - /// Reference to internals. - pub can: fdcan::FdCan, M>, - ns_per_timer_tick: u64, // For FDCAN internal timer -} - -fn calc_ns_per_timer_tick(mode: config::FrameTransmissionConfig) -> u64 { +fn calc_ns_per_timer_tick( + info: &'static Info, + freq: crate::time::Hertz, + mode: crate::can::fd::config::FrameTransmissionConfig, +) -> u64 { match mode { // Use timestamp from Rx FIFO to adjust timestamp reported to user - config::FrameTransmissionConfig::ClassicCanOnly => { - let freq = T::frequency(); - let prescale: u64 = - ({ T::regs().nbtp().read().nbrp() } + 1) as u64 * ({ T::regs().tscc().read().tcp() } + 1) as u64; + crate::can::fd::config::FrameTransmissionConfig::ClassicCanOnly => { + let prescale: u64 = ({ info.regs.regs.nbtp().read().nbrp() } + 1) as u64 + * ({ info.regs.regs.tscc().read().tcp() } + 1) as u64; 1_000_000_000 as u64 / (freq.0 as u64 * prescale) } // For VBR this is too hard because the FDCAN timer switches clock rate you need to configure to use @@ -241,175 +159,166 @@ fn calc_ns_per_timer_tick(mode: config::FrameTransmissionConfig) -> } } -#[cfg(feature = "time")] -fn calc_timestamp(ns_per_timer_tick: u64, ts_val: u16) -> embassy_time::Instant { - let now_embassy = embassy_time::Instant::now(); - if ns_per_timer_tick == 0 { - return now_embassy; - } - let now_can = { T::regs().tscv().read().tsc() }; - let delta = now_can.overflowing_sub(ts_val).0 as u64; - let ns = ns_per_timer_tick * delta as u64; - now_embassy - embassy_time::Duration::from_nanos(ns) +/// FDCAN Configuration instance instance +/// Create instance of this first +pub struct CanConfigurator<'d> { + _phantom: PhantomData<&'d ()>, + config: crate::can::fd::config::FdCanConfig, + info: &'static Info, + state: &'static State, + /// Reference to internals. + properties: Properties, + periph_clock: crate::time::Hertz, } -fn curr_error() -> Option { - let err = { T::regs().psr().read() }; - if err.bo() { - return Some(BusError::BusOff); - } else if err.ep() { - return Some(BusError::BusPassive); - } else if err.ew() { - return Some(BusError::BusWarning); - } else { - cfg_if! { - if #[cfg(stm32h7)] { - let lec = err.lec(); - } else { - let lec = err.lec().to_bits(); - } - } - if let Ok(err) = LastErrorCode::try_from(lec) { - return BusError::try_from(err); - } - } - None -} - -impl<'d, T: Instance> Fdcan<'d, T, fdcan::ConfigMode> { +impl<'d> CanConfigurator<'d> { /// Creates a new Fdcan instance, keeping the peripheral in sleep mode. /// You must call [Fdcan::enable_non_blocking] to use the peripheral. - pub fn new( - peri: impl Peripheral

+ 'd, + pub fn new( + _peri: impl Peripheral

+ 'd, rx: impl Peripheral

> + 'd, tx: impl Peripheral

> + 'd, _irqs: impl interrupt::typelevel::Binding> + interrupt::typelevel::Binding> + 'd, - ) -> Fdcan<'d, T, fdcan::ConfigMode> { - into_ref!(peri, rx, tx); + ) -> CanConfigurator<'d> { + into_ref!(_peri, rx, tx); - rx.set_as_af(rx.af_num(), AFType::Input); - tx.set_as_af(tx.af_num(), AFType::OutputPushPull); + rx.set_as_af(rx.af_num(), AfType::input(Pull::None)); + tx.set_as_af(tx.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); - T::enable_and_reset(); + rcc::enable_and_reset::(); - rx.set_as_af(rx.af_num(), AFType::Input); - tx.set_as_af(tx.af_num(), AFType::OutputPushPull); + let mut config = crate::can::fd::config::FdCanConfig::default(); + config.timestamp_source = TimestampSource::Prescaler(TimestampPrescaler::_1); + T::registers().into_config_mode(config); - let mut can = fdcan::FdCan::new(FdcanInstance(peri)).into_config_mode(); + rx.set_as_af(rx.af_num(), AfType::input(Pull::None)); + tx.set_as_af(tx.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); - T::configure_msg_ram(); unsafe { - // Enable timestamping - #[cfg(not(stm32h7))] - T::regs() - .tscc() - .write(|w| w.set_tss(stm32_metapac::can::vals::Tss::INCREMENT)); - #[cfg(stm32h7)] - T::regs().tscc().write(|w| w.set_tss(0x01)); - T::IT0Interrupt::unpend(); // Not unsafe T::IT0Interrupt::enable(); T::IT1Interrupt::unpend(); // Not unsafe T::IT1Interrupt::enable(); - - // this isn't really documented in the reference manual - // but corresponding txbtie bit has to be set for the TC (TxComplete) interrupt to fire - T::regs().txbtie().write(|w| w.0 = 0xffff_ffff); } + Self { + _phantom: PhantomData, + config, + info: T::info(), + state: T::state(), + properties: Properties::new(T::info()), + periph_clock: T::frequency(), + } + } - can.enable_interrupt(fdcan::interrupt::Interrupt::RxFifo0NewMsg); - can.enable_interrupt(fdcan::interrupt::Interrupt::RxFifo1NewMsg); - can.enable_interrupt(fdcan::interrupt::Interrupt::TxComplete); - can.enable_interrupt_line(fdcan::interrupt::InterruptLine::_0, true); - can.enable_interrupt_line(fdcan::interrupt::InterruptLine::_1, true); + /// Get driver properties + pub fn properties(&self) -> &Properties { + &self.properties + } - let ns_per_timer_tick = calc_ns_per_timer_tick::(can.get_config().frame_transmit); - Self { can, ns_per_timer_tick } + /// Get configuration + pub fn config(&self) -> crate::can::fd::config::FdCanConfig { + return self.config; + } + + /// Set configuration + pub fn set_config(&mut self, config: crate::can::fd::config::FdCanConfig) { + self.config = config; } /// Configures the bit timings calculated from supplied bitrate. pub fn set_bitrate(&mut self, bitrate: u32) { - let bit_timing = util::calc_can_timings(T::frequency(), bitrate).unwrap(); - self.can.set_nominal_bit_timing(config::NominalBitTiming { + let bit_timing = util::calc_can_timings(self.periph_clock, bitrate).unwrap(); + + let nbtr = crate::can::fd::config::NominalBitTiming { sync_jump_width: bit_timing.sync_jump_width, prescaler: bit_timing.prescaler, seg1: bit_timing.seg1, seg2: bit_timing.seg2, + }; + self.config = self.config.set_nominal_bit_timing(nbtr); + } + + /// Configures the bit timings for VBR data calculated from supplied bitrate. This also sets confit to allow can FD and VBR + pub fn set_fd_data_bitrate(&mut self, bitrate: u32, transceiver_delay_compensation: bool) { + let bit_timing = util::calc_can_timings(self.periph_clock, bitrate).unwrap(); + // Note, used existing calcluation for normal(non-VBR) bitrate, appears to work for 250k/1M + let nbtr = crate::can::fd::config::DataBitTiming { + transceiver_delay_compensation, + sync_jump_width: bit_timing.sync_jump_width, + prescaler: bit_timing.prescaler, + seg1: bit_timing.seg1, + seg2: bit_timing.seg2, + }; + self.config.frame_transmit = FrameTransmissionConfig::AllowFdCanAndBRS; + self.config = self.config.set_data_bit_timing(nbtr); + } + + /// Start in mode. + pub fn start(self, mode: OperatingMode) -> Can<'d> { + let ns_per_timer_tick = calc_ns_per_timer_tick(self.info, self.periph_clock, self.config.frame_transmit); + critical_section::with(|_| { + let state = self.state as *const State; + unsafe { + let mut_state = state as *mut State; + (*mut_state).ns_per_timer_tick = ns_per_timer_tick; + } }); + self.info.regs.into_mode(self.config, mode); + Can { + _phantom: PhantomData, + config: self.config, + info: self.info, + state: self.state, + _mode: mode, + properties: Properties::new(self.info), + } + } + + /// Start, entering mode. Does same as start(mode) + pub fn into_normal_mode(self) -> Can<'d> { + self.start(OperatingMode::NormalOperationMode) + } + + /// Start, entering mode. Does same as start(mode) + pub fn into_internal_loopback_mode(self) -> Can<'d> { + self.start(OperatingMode::InternalLoopbackMode) + } + + /// Start, entering mode. Does same as start(mode) + pub fn into_external_loopback_mode(self) -> Can<'d> { + self.start(OperatingMode::ExternalLoopbackMode) } } -macro_rules! impl_transition { - ($from_mode:ident, $to_mode:ident, $name:ident, $func: ident) => { - impl<'d, T: Instance> Fdcan<'d, T, fdcan::$from_mode> { - /// Transition from $from_mode:ident mode to $to_mode:ident mode - pub fn $name(self) -> Fdcan<'d, T, fdcan::$to_mode> { - let ns_per_timer_tick = calc_ns_per_timer_tick::(self.can.get_config().frame_transmit); - Fdcan { - can: self.can.$func(), - ns_per_timer_tick, - } - } - } - }; +/// FDCAN Instance +pub struct Can<'d> { + _phantom: PhantomData<&'d ()>, + config: crate::can::fd::config::FdCanConfig, + info: &'static Info, + state: &'static State, + _mode: OperatingMode, + properties: Properties, } -impl_transition!(PoweredDownMode, ConfigMode, into_config_mode, into_config_mode); -impl_transition!(InternalLoopbackMode, ConfigMode, into_config_mode, into_config_mode); - -impl_transition!(ConfigMode, NormalOperationMode, into_normal_mode, into_normal); -impl_transition!( - ConfigMode, - ExternalLoopbackMode, - into_external_loopback_mode, - into_external_loopback -); -impl_transition!( - ConfigMode, - InternalLoopbackMode, - into_internal_loopback_mode, - into_internal_loopback -); - -impl<'d, T: Instance, M: FdcanOperatingMode> Fdcan<'d, T, M> -where - M: fdcan::Transmit, - M: fdcan::Receive, -{ - /// Queues the message to be sent but exerts backpressure. If a lower-priority - /// frame is dropped from the mailbox, it is returned. If no lower-priority frames - /// can be replaced, this call asynchronously waits for a frame to be successfully - /// transmitted, then tries again. - pub async fn write(&mut self, frame: &TxFrame) -> Option { - poll_fn(|cx| { - T::state().tx_waker.register(cx.waker()); - if let Ok(dropped) = self - .can - .transmit_preserve(frame.header, &frame.data.bytes, &mut |_, hdr, data32| { - TxFrame::from_preserved(hdr, data32) - }) - { - return Poll::Ready(dropped.flatten()); - } - - // Couldn't replace any lower priority frames. Need to wait for some mailboxes - // to clear. - Poll::Pending - }) - .await +impl<'d> Can<'d> { + /// Get driver properties + pub fn properties(&self) -> &Properties { + &self.properties } /// Flush one of the TX mailboxes. - pub async fn flush(&self, mb: fdcan::Mailbox) { + pub async fn flush(&self, idx: usize) { poll_fn(|cx| { - T::state().tx_waker.register(cx.waker()); + self.state.tx_mode.register(cx.waker()); - let idx: u8 = mb.into(); + if idx > 3 { + panic!("Bad mailbox"); + } let idx = 1 << idx; - if !T::regs().txbrp().read().trp(idx) { + if !self.info.regs.regs.txbrp().read().trp(idx) { return Poll::Ready(()); } @@ -418,81 +327,504 @@ where .await; } - /// Returns the next received message frame - pub async fn read(&mut self) -> Result { - poll_fn(|cx| { - T::state().err_waker.register(cx.waker()); - T::state().rx_waker.register(cx.waker()); - - let mut buffer: [u8; 64] = [0; 64]; - if let Ok(rx) = self.can.receive0(&mut buffer) { - // rx: fdcan::ReceiveOverrun - // TODO: report overrun? - // for now we just drop it - - let frame: RxFrame = RxFrame::new( - rx.unwrap(), - &buffer, - #[cfg(feature = "time")] - calc_timestamp::(self.ns_per_timer_tick, rx.unwrap().time_stamp), - ); - return Poll::Ready(Ok(frame)); - } else if let Ok(rx) = self.can.receive1(&mut buffer) { - // rx: fdcan::ReceiveOverrun - // TODO: report overrun? - // for now we just drop it - - let frame: RxFrame = RxFrame::new( - rx.unwrap(), - &buffer, - #[cfg(feature = "time")] - calc_timestamp::(self.ns_per_timer_tick, rx.unwrap().time_stamp), - ); - return Poll::Ready(Ok(frame)); - } else if let Some(err) = curr_error::() { - // TODO: this is probably wrong - return Poll::Ready(Err(err)); - } - Poll::Pending - }) - .await - } - - /// Split instance into separate Tx(write) and Rx(read) portions - pub fn split<'c>(&'c mut self) -> (FdcanTx<'c, 'd, T, M>, FdcanRx<'c, 'd, T, M>) { - let (mut _control, tx, rx0, rx1) = self.can.split_by_ref(); - ( - FdcanTx { _control, tx }, - FdcanRx { - rx0, - rx1, - ns_per_timer_tick: self.ns_per_timer_tick, - }, - ) - } -} - -/// FDCAN Tx only Instance -pub struct FdcanTx<'c, 'd, T: Instance, M: fdcan::Transmit> { - _control: &'c mut fdcan::FdCanControl, M>, - tx: &'c mut fdcan::Tx, M>, -} - -impl<'c, 'd, T: Instance, M: fdcan::Transmit> FdcanTx<'c, 'd, T, M> { /// Queues the message to be sent but exerts backpressure. If a lower-priority /// frame is dropped from the mailbox, it is returned. If no lower-priority frames /// can be replaced, this call asynchronously waits for a frame to be successfully /// transmitted, then tries again. - pub async fn write(&mut self, frame: &TxFrame) -> Option { + pub async fn write(&mut self, frame: &Frame) -> Option { + self.state.tx_mode.write(self.info, frame).await + } + + /// Returns the next received message frame + pub async fn read(&mut self) -> Result { + self.state.rx_mode.read_classic(self.info, self.state).await + } + + /// Queues the message to be sent but exerts backpressure. If a lower-priority + /// frame is dropped from the mailbox, it is returned. If no lower-priority frames + /// can be replaced, this call asynchronously waits for a frame to be successfully + /// transmitted, then tries again. + pub async fn write_fd(&mut self, frame: &FdFrame) -> Option { + self.state.tx_mode.write_fd(self.info, frame).await + } + + /// Returns the next received message frame + pub async fn read_fd(&mut self) -> Result { + self.state.rx_mode.read_fd(self.info, self.state).await + } + + /// Split instance into separate portions: Tx(write), Rx(read), common properties + pub fn split(self) -> (CanTx<'d>, CanRx<'d>, Properties) { + ( + CanTx { + _phantom: PhantomData, + info: self.info, + state: self.state, + config: self.config, + _mode: self._mode, + }, + CanRx { + _phantom: PhantomData, + info: self.info, + state: self.state, + _mode: self._mode, + }, + self.properties, + ) + } + /// Join split rx and tx portions back together + pub fn join(tx: CanTx<'d>, rx: CanRx<'d>) -> Self { + Can { + _phantom: PhantomData, + config: tx.config, + info: tx.info, + state: tx.state, + _mode: rx._mode, + properties: Properties::new(tx.info), + } + } + + /// Return a buffered instance of driver without CAN FD support. User must supply Buffers + pub fn buffered( + self, + tx_buf: &'static mut TxBuf, + rxb: &'static mut RxBuf, + ) -> BufferedCan<'d, TX_BUF_SIZE, RX_BUF_SIZE> { + BufferedCan::new(self.info, self.state, self._mode, tx_buf, rxb) + } + + /// Return a buffered instance of driver with CAN FD support. User must supply Buffers + pub fn buffered_fd( + self, + tx_buf: &'static mut TxFdBuf, + rxb: &'static mut RxFdBuf, + ) -> BufferedCanFd<'d, TX_BUF_SIZE, RX_BUF_SIZE> { + BufferedCanFd::new(self.info, self.state, self._mode, tx_buf, rxb) + } +} + +/// User supplied buffer for RX Buffering +pub type RxBuf = Channel, BUF_SIZE>; + +/// User supplied buffer for TX buffering +pub type TxBuf = Channel; + +/// Buffered FDCAN Instance +pub struct BufferedCan<'d, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> { + _phantom: PhantomData<&'d ()>, + info: &'static Info, + state: &'static State, + _mode: OperatingMode, + tx_buf: &'static TxBuf, + rx_buf: &'static RxBuf, + properties: Properties, +} + +impl<'c, 'd, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> BufferedCan<'d, TX_BUF_SIZE, RX_BUF_SIZE> { + fn new( + info: &'static Info, + state: &'static State, + _mode: OperatingMode, + tx_buf: &'static TxBuf, + rx_buf: &'static RxBuf, + ) -> Self { + BufferedCan { + _phantom: PhantomData, + info, + state, + _mode, + tx_buf, + rx_buf, + properties: Properties::new(info), + } + .setup() + } + + /// Get driver properties + pub fn properties(&self) -> &Properties { + &self.properties + } + + fn setup(self) -> Self { + // We don't want interrupts being processed while we change modes. + critical_section::with(|_| { + let rx_inner = super::common::ClassicBufferedRxInner { + rx_sender: self.rx_buf.sender().into(), + }; + let tx_inner = super::common::ClassicBufferedTxInner { + tx_receiver: self.tx_buf.receiver().into(), + }; + let state = self.state as *const State; + unsafe { + let mut_state = state as *mut State; + (*mut_state).rx_mode = RxMode::ClassicBuffered(rx_inner); + (*mut_state).tx_mode = TxMode::ClassicBuffered(tx_inner); + } + }); + self + } + + /// Async write frame to TX buffer. + pub async fn write(&mut self, frame: Frame) { + self.tx_buf.send(frame).await; + self.info.interrupt0.pend(); // Wake for Tx + //T::IT0Interrupt::pend(); // Wake for Tx + } + + /// Async read frame from RX buffer. + pub async fn read(&mut self) -> Result { + self.rx_buf.receive().await + } + + /// Returns a sender that can be used for sending CAN frames. + pub fn writer(&self) -> BufferedCanSender { + BufferedCanSender { + tx_buf: self.tx_buf.sender().into(), + waker: self.info.tx_waker, + } + } + + /// Returns a receiver that can be used for receiving CAN frames. Note, each CAN frame will only be received by one receiver. + pub fn reader(&self) -> BufferedCanReceiver { + self.rx_buf.receiver().into() + } +} + +impl<'c, 'd, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> Drop for BufferedCan<'d, TX_BUF_SIZE, RX_BUF_SIZE> { + fn drop(&mut self) { + critical_section::with(|_| { + let state = self.state as *const State; + unsafe { + let mut_state = state as *mut State; + (*mut_state).rx_mode = RxMode::NonBuffered(embassy_sync::waitqueue::AtomicWaker::new()); + (*mut_state).tx_mode = TxMode::NonBuffered(embassy_sync::waitqueue::AtomicWaker::new()); + } + }); + } +} + +/// User supplied buffer for RX Buffering +pub type RxFdBuf = Channel, BUF_SIZE>; + +/// User supplied buffer for TX buffering +pub type TxFdBuf = Channel; + +/// Sender that can be used for sending CAN frames. +#[derive(Copy, Clone)] +pub struct BufferedFdCanSender { + tx_buf: DynamicSender<'static, FdFrame>, + waker: fn(), +} + +impl BufferedFdCanSender { + /// Async write frame to TX buffer. + pub fn try_write(&mut self, frame: FdFrame) -> Result<(), embassy_sync::channel::TrySendError> { + self.tx_buf.try_send(frame)?; + (self.waker)(); + Ok(()) + } + + /// Async write frame to TX buffer. + pub async fn write(&mut self, frame: FdFrame) { + self.tx_buf.send(frame).await; + (self.waker)(); + } + + /// Allows a poll_fn to poll until the channel is ready to write + pub fn poll_ready_to_send(&self, cx: &mut core::task::Context<'_>) -> core::task::Poll<()> { + self.tx_buf.poll_ready_to_send(cx) + } +} + +/// Receiver that can be used for receiving CAN frames. Note, each CAN frame will only be received by one receiver. +pub type BufferedFdCanReceiver = DynamicReceiver<'static, Result>; + +/// Buffered FDCAN Instance +pub struct BufferedCanFd<'d, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> { + _phantom: PhantomData<&'d ()>, + info: &'static Info, + state: &'static State, + _mode: OperatingMode, + tx_buf: &'static TxFdBuf, + rx_buf: &'static RxFdBuf, + properties: Properties, +} + +impl<'c, 'd, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> BufferedCanFd<'d, TX_BUF_SIZE, RX_BUF_SIZE> { + fn new( + info: &'static Info, + state: &'static State, + _mode: OperatingMode, + tx_buf: &'static TxFdBuf, + rx_buf: &'static RxFdBuf, + ) -> Self { + BufferedCanFd { + _phantom: PhantomData, + info, + state, + _mode, + tx_buf, + rx_buf, + properties: Properties::new(info), + } + .setup() + } + + /// Get driver properties + pub fn properties(&self) -> &Properties { + &self.properties + } + + fn setup(self) -> Self { + // We don't want interrupts being processed while we change modes. + critical_section::with(|_| { + let rx_inner = super::common::FdBufferedRxInner { + rx_sender: self.rx_buf.sender().into(), + }; + let tx_inner = super::common::FdBufferedTxInner { + tx_receiver: self.tx_buf.receiver().into(), + }; + let state = self.state as *const State; + unsafe { + let mut_state = state as *mut State; + (*mut_state).rx_mode = RxMode::FdBuffered(rx_inner); + (*mut_state).tx_mode = TxMode::FdBuffered(tx_inner); + } + }); + self + } + + /// Async write frame to TX buffer. + pub async fn write(&mut self, frame: FdFrame) { + self.tx_buf.send(frame).await; + self.info.interrupt0.pend(); // Wake for Tx + //T::IT0Interrupt::pend(); // Wake for Tx + } + + /// Async read frame from RX buffer. + pub async fn read(&mut self) -> Result { + self.rx_buf.receive().await + } + + /// Returns a sender that can be used for sending CAN frames. + pub fn writer(&self) -> BufferedFdCanSender { + BufferedFdCanSender { + tx_buf: self.tx_buf.sender().into(), + waker: self.info.tx_waker, + } + } + + /// Returns a receiver that can be used for receiving CAN frames. Note, each CAN frame will only be received by one receiver. + pub fn reader(&self) -> BufferedFdCanReceiver { + self.rx_buf.receiver().into() + } +} + +impl<'c, 'd, const TX_BUF_SIZE: usize, const RX_BUF_SIZE: usize> Drop for BufferedCanFd<'d, TX_BUF_SIZE, RX_BUF_SIZE> { + fn drop(&mut self) { + critical_section::with(|_| { + let state = self.state as *const State; + unsafe { + let mut_state = state as *mut State; + (*mut_state).rx_mode = RxMode::NonBuffered(embassy_sync::waitqueue::AtomicWaker::new()); + (*mut_state).tx_mode = TxMode::NonBuffered(embassy_sync::waitqueue::AtomicWaker::new()); + } + }); + } +} + +/// FDCAN Rx only Instance +pub struct CanRx<'d> { + _phantom: PhantomData<&'d ()>, + info: &'static Info, + state: &'static State, + _mode: OperatingMode, +} + +impl<'d> CanRx<'d> { + /// Returns the next received message frame + pub async fn read(&mut self) -> Result { + self.state.rx_mode.read_classic(&self.info, &self.state).await + } + + /// Returns the next received message frame + pub async fn read_fd(&mut self) -> Result { + self.state.rx_mode.read_fd(&self.info, &self.state).await + } +} + +/// FDCAN Tx only Instance +pub struct CanTx<'d> { + _phantom: PhantomData<&'d ()>, + info: &'static Info, + state: &'static State, + config: crate::can::fd::config::FdCanConfig, + _mode: OperatingMode, +} + +impl<'c, 'd> CanTx<'d> { + /// Queues the message to be sent but exerts backpressure. If a lower-priority + /// frame is dropped from the mailbox, it is returned. If no lower-priority frames + /// can be replaced, this call asynchronously waits for a frame to be successfully + /// transmitted, then tries again. + pub async fn write(&mut self, frame: &Frame) -> Option { + self.state.tx_mode.write(self.info, frame).await + } + + /// Queues the message to be sent but exerts backpressure. If a lower-priority + /// frame is dropped from the mailbox, it is returned. If no lower-priority frames + /// can be replaced, this call asynchronously waits for a frame to be successfully + /// transmitted, then tries again. + pub async fn write_fd(&mut self, frame: &FdFrame) -> Option { + self.state.tx_mode.write_fd(self.info, frame).await + } +} + +enum RxMode { + NonBuffered(AtomicWaker), + ClassicBuffered(super::common::ClassicBufferedRxInner), + FdBuffered(super::common::FdBufferedRxInner), +} + +impl RxMode { + fn register(&self, arg: &core::task::Waker) { + match self { + RxMode::NonBuffered(waker) => waker.register(arg), + _ => { + panic!("Bad Mode") + } + } + } + + fn on_interrupt(&self, fifonr: usize) { + T::registers().regs.ir().write(|w| w.set_rfn(fifonr, true)); + match self { + RxMode::NonBuffered(waker) => { + waker.wake(); + } + RxMode::ClassicBuffered(buf) => { + if let Some(result) = self.try_read::() { + let _ = buf.rx_sender.try_send(result); + } + } + RxMode::FdBuffered(buf) => { + if let Some(result) = self.try_read_fd::() { + let _ = buf.rx_sender.try_send(result); + } + } + } + } + + //async fn read_classic(&self) -> Result { + fn try_read(&self) -> Option> { + if let Some((frame, ts)) = T::registers().read(0) { + let ts = T::calc_timestamp(T::state().ns_per_timer_tick, ts); + Some(Ok(Envelope { ts, frame })) + } else if let Some((frame, ts)) = T::registers().read(1) { + let ts = T::calc_timestamp(T::state().ns_per_timer_tick, ts); + Some(Ok(Envelope { ts, frame })) + } else if let Some(err) = T::registers().curr_error() { + // TODO: this is probably wrong + Some(Err(err)) + } else { + None + } + } + + fn try_read_fd(&self) -> Option> { + if let Some((frame, ts)) = T::registers().read(0) { + let ts = T::calc_timestamp(T::state().ns_per_timer_tick, ts); + Some(Ok(FdEnvelope { ts, frame })) + } else if let Some((frame, ts)) = T::registers().read(1) { + let ts = T::calc_timestamp(T::state().ns_per_timer_tick, ts); + Some(Ok(FdEnvelope { ts, frame })) + } else if let Some(err) = T::registers().curr_error() { + // TODO: this is probably wrong + Some(Err(err)) + } else { + None + } + } + + fn read( + &self, + info: &'static Info, + state: &'static State, + ) -> Option> { + if let Some((msg, ts)) = info.regs.read(0) { + let ts = info.calc_timestamp(state.ns_per_timer_tick, ts); + Some(Ok((msg, ts))) + } else if let Some((msg, ts)) = info.regs.read(1) { + let ts = info.calc_timestamp(state.ns_per_timer_tick, ts); + Some(Ok((msg, ts))) + } else if let Some(err) = info.regs.curr_error() { + // TODO: this is probably wrong + Some(Err(err)) + } else { + None + } + } + + async fn read_async( + &self, + info: &'static Info, + state: &'static State, + ) -> Result<(F, Timestamp), BusError> { + //let _ = self.read::(info, state); + poll_fn(move |cx| { + state.err_waker.register(cx.waker()); + self.register(cx.waker()); + match self.read::<_>(info, state) { + Some(result) => Poll::Ready(result), + None => Poll::Pending, + } + }) + .await + } + + async fn read_classic(&self, info: &'static Info, state: &'static State) -> Result { + match self.read_async::<_>(info, state).await { + Ok((frame, ts)) => Ok(Envelope { ts, frame }), + Err(e) => Err(e), + } + } + + async fn read_fd(&self, info: &'static Info, state: &'static State) -> Result { + match self.read_async::<_>(info, state).await { + Ok((frame, ts)) => Ok(FdEnvelope { ts, frame }), + Err(e) => Err(e), + } + } +} + +enum TxMode { + NonBuffered(AtomicWaker), + ClassicBuffered(super::common::ClassicBufferedTxInner), + FdBuffered(super::common::FdBufferedTxInner), +} + +impl TxMode { + fn register(&self, arg: &core::task::Waker) { + match self { + TxMode::NonBuffered(waker) => { + waker.register(arg); + } + _ => { + panic!("Bad mode"); + } + } + } + + /// Queues the message to be sent but exerts backpressure. If a lower-priority + /// frame is dropped from the mailbox, it is returned. If no lower-priority frames + /// can be replaced, this call asynchronously waits for a frame to be successfully + /// transmitted, then tries again. + async fn write_generic(&self, info: &'static Info, frame: &F) -> Option { poll_fn(|cx| { - T::state().tx_waker.register(cx.waker()); - if let Ok(dropped) = self - .tx - .transmit_preserve(frame.header, &frame.data.bytes, &mut |_, hdr, data32| { - TxFrame::from_preserved(hdr, data32) - }) - { - return Poll::Ready(dropped.flatten()); + self.register(cx.waker()); + + if let Ok(dropped) = info.regs.write(frame) { + return Poll::Ready(dropped); } // Couldn't replace any lower priority frames. Need to wait for some mailboxes @@ -501,226 +833,220 @@ impl<'c, 'd, T: Instance, M: fdcan::Transmit> FdcanTx<'c, 'd, T, M> { }) .await } -} -/// FDCAN Rx only Instance -#[allow(dead_code)] -pub struct FdcanRx<'c, 'd, T: Instance, M: fdcan::Receive> { - rx0: &'c mut fdcan::Rx, M, fdcan::Fifo0>, - rx1: &'c mut fdcan::Rx, M, fdcan::Fifo1>, - ns_per_timer_tick: u64, // For FDCAN internal timer -} - -impl<'c, 'd, T: Instance, M: fdcan::Receive> FdcanRx<'c, 'd, T, M> { - /// Returns the next received message frame - pub async fn read(&mut self) -> Result { - poll_fn(|cx| { - T::state().err_waker.register(cx.waker()); - T::state().rx_waker.register(cx.waker()); - - let mut buffer: [u8; 64] = [0; 64]; - if let Ok(rx) = self.rx0.receive(&mut buffer) { - // rx: fdcan::ReceiveOverrun - // TODO: report overrun? - // for now we just drop it - let frame: RxFrame = RxFrame::new( - rx.unwrap(), - &buffer, - #[cfg(feature = "time")] - calc_timestamp::(self.ns_per_timer_tick, rx.unwrap().time_stamp), - ); - return Poll::Ready(Ok(frame)); - } else if let Ok(rx) = self.rx1.receive(&mut buffer) { - // rx: fdcan::ReceiveOverrun - // TODO: report overrun? - // for now we just drop it - let frame: RxFrame = RxFrame::new( - rx.unwrap(), - &buffer, - #[cfg(feature = "time")] - calc_timestamp::(self.ns_per_timer_tick, rx.unwrap().time_stamp), - ); - return Poll::Ready(Ok(frame)); - } else if let Some(err) = curr_error::() { - // TODO: this is probably wrong - return Poll::Ready(Err(err)); - } - - Poll::Pending - }) - .await + /// Queues the message to be sent but exerts backpressure. If a lower-priority + /// frame is dropped from the mailbox, it is returned. If no lower-priority frames + /// can be replaced, this call asynchronously waits for a frame to be successfully + /// transmitted, then tries again. + async fn write(&self, info: &'static Info, frame: &Frame) -> Option { + self.write_generic::<_>(info, frame).await } -} -impl<'d, T: Instance, M: FdcanOperatingMode> Deref for Fdcan<'d, T, M> { - type Target = fdcan::FdCan, M>; - fn deref(&self) -> &Self::Target { - &self.can + /// Queues the message to be sent but exerts backpressure. If a lower-priority + /// frame is dropped from the mailbox, it is returned. If no lower-priority frames + /// can be replaced, this call asynchronously waits for a frame to be successfully + /// transmitted, then tries again. + async fn write_fd(&self, info: &'static Info, frame: &FdFrame) -> Option { + self.write_generic::<_>(info, frame).await } } -impl<'d, T: Instance, M: FdcanOperatingMode> DerefMut for Fdcan<'d, T, M> { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.can - } +/// Common driver properties, including filters and error counters +pub struct Properties { + info: &'static Info, + // phantom pointer to ensure !Sync + //instance: PhantomData<*const T>, } -pub(crate) mod sealed { - use embassy_sync::waitqueue::AtomicWaker; - - pub struct State { - pub tx_waker: AtomicWaker, - pub err_waker: AtomicWaker, - pub rx_waker: AtomicWaker, - } - - impl State { - pub const fn new() -> Self { - Self { - tx_waker: AtomicWaker::new(), - err_waker: AtomicWaker::new(), - rx_waker: AtomicWaker::new(), - } +impl Properties { + fn new(info: &'static Info) -> Self { + Self { + info, + //instance: Default::default(), } } - pub trait Instance { - const REGISTERS: *mut fdcan::RegisterBlock; - const MSG_RAM: *mut fdcan::message_ram::RegisterBlock; - const MSG_RAM_OFFSET: usize; + /// Set a standard address CAN filter in the specified slot in FDCAN memory. + #[inline] + pub fn set_standard_filter(&self, slot: StandardFilterSlot, filter: StandardFilter) { + self.info.regs.msg_ram_mut().filters.flssa[slot as usize].activate(filter); + } - fn regs() -> &'static crate::pac::can::Fdcan; - fn state() -> &'static State; + /// Set the full array of standard address CAN filters in FDCAN memory. + /// Overwrites all standard address filters in memory. + pub fn set_standard_filters(&self, filters: &[StandardFilter; STANDARD_FILTER_MAX as usize]) { + for (i, f) in filters.iter().enumerate() { + self.info.regs.msg_ram_mut().filters.flssa[i].activate(*f); + } + } - #[cfg(not(stm32h7))] - fn configure_msg_ram() {} + /// Set an extended address CAN filter in the specified slot in FDCAN memory. + #[inline] + pub fn set_extended_filter(&self, slot: ExtendedFilterSlot, filter: ExtendedFilter) { + self.info.regs.msg_ram_mut().filters.flesa[slot as usize].activate(filter); + } - #[cfg(stm32h7)] - fn configure_msg_ram() { - let r = Self::regs(); + /// Set the full array of extended address CAN filters in FDCAN memory. + /// Overwrites all extended address filters in memory. + pub fn set_extended_filters(&self, filters: &[ExtendedFilter; EXTENDED_FILTER_MAX as usize]) { + for (i, f) in filters.iter().enumerate() { + self.info.regs.msg_ram_mut().filters.flesa[i].activate(*f); + } + } - use fdcan::message_ram::*; - let mut offset_words = Self::MSG_RAM_OFFSET as u16; + /// Get the CAN RX error counter + pub fn rx_error_count(&self) -> u8 { + self.info.regs.regs.ecr().read().rec() + } - // 11-bit filter - r.sidfc().modify(|w| w.set_flssa(offset_words)); - offset_words += STANDARD_FILTER_MAX as u16; + /// Get the CAN TX error counter + pub fn tx_error_count(&self) -> u8 { + self.info.regs.regs.ecr().read().tec() + } - // 29-bit filter - r.xidfc().modify(|w| w.set_flesa(offset_words)); - offset_words += 2 * EXTENDED_FILTER_MAX as u16; - - // Rx FIFO 0 and 1 - for i in 0..=1 { - r.rxfc(i).modify(|w| { - w.set_fsa(offset_words); - w.set_fs(RX_FIFO_MAX); - w.set_fwm(RX_FIFO_MAX); - }); - offset_words += 18 * RX_FIFO_MAX as u16; - } - - // Rx buffer - see below - // Tx event FIFO - r.txefc().modify(|w| { - w.set_efsa(offset_words); - w.set_efs(TX_EVENT_MAX); - w.set_efwm(TX_EVENT_MAX); - }); - offset_words += 2 * TX_EVENT_MAX as u16; - - // Tx buffers - r.txbc().modify(|w| { - w.set_tbsa(offset_words); - w.set_tfqs(TX_FIFO_MAX); - }); - offset_words += 18 * TX_FIFO_MAX as u16; - - // Rx Buffer - not used - r.rxbc().modify(|w| { - w.set_rbsa(offset_words); - }); - - // TX event FIFO? - // Trigger memory? - - // Set the element sizes to 16 bytes - r.rxesc().modify(|w| { - w.set_rbds(0b111); - for i in 0..=1 { - w.set_fds(i, 0b111); - } - }); - r.txesc().modify(|w| { - w.set_tbds(0b111); - }) + /// Get the current bus error mode + pub fn bus_error_mode(&self) -> BusErrorMode { + // This read will clear LEC and DLEC. This is not ideal, but protocol + // error reporting in this driver should have a big ol' FIXME on it + // anyway! + let psr = self.info.regs.regs.psr().read(); + match (psr.bo(), psr.ep()) { + (false, false) => BusErrorMode::ErrorActive, + (false, true) => BusErrorMode::ErrorPassive, + (true, _) => BusErrorMode::BusOff, } } } -/// Trait for FDCAN interrupt channel 0 -pub trait IT0Instance { - /// Type for FDCAN interrupt channel 0 +struct State { + pub rx_mode: RxMode, + pub tx_mode: TxMode, + pub ns_per_timer_tick: u64, + + pub err_waker: AtomicWaker, +} + +impl State { + const fn new() -> Self { + Self { + rx_mode: RxMode::NonBuffered(AtomicWaker::new()), + tx_mode: TxMode::NonBuffered(AtomicWaker::new()), + ns_per_timer_tick: 0, + err_waker: AtomicWaker::new(), + } + } +} + +struct Info { + regs: Registers, + interrupt0: crate::interrupt::Interrupt, + _interrupt1: crate::interrupt::Interrupt, + tx_waker: fn(), +} + +impl Info { + #[cfg(feature = "time")] + fn calc_timestamp(&self, ns_per_timer_tick: u64, ts_val: u16) -> Timestamp { + let now_embassy = embassy_time::Instant::now(); + if ns_per_timer_tick == 0 { + return now_embassy; + } + let cantime = { self.regs.regs.tscv().read().tsc() }; + let delta = cantime.overflowing_sub(ts_val).0 as u64; + let ns = ns_per_timer_tick * delta as u64; + now_embassy - embassy_time::Duration::from_nanos(ns) + } + + #[cfg(not(feature = "time"))] + fn calc_timestamp(&self, _ns_per_timer_tick: u64, ts_val: u16) -> Timestamp { + ts_val + } +} + +trait SealedInstance { + const MSG_RAM_OFFSET: usize; + + fn info() -> &'static Info; + fn registers() -> crate::can::fd::peripheral::Registers; + fn state() -> &'static State; + unsafe fn mut_state() -> &'static mut State; + fn calc_timestamp(ns_per_timer_tick: u64, ts_val: u16) -> Timestamp; +} + +/// Instance trait +#[allow(private_bounds)] +pub trait Instance: SealedInstance + RccPeripheral + 'static { + /// Interrupt 0 type IT0Interrupt: crate::interrupt::typelevel::Interrupt; -} - -/// Trait for FDCAN interrupt channel 1 -pub trait IT1Instance { - /// Type for FDCAN interrupt channel 1 + /// Interrupt 1 type IT1Interrupt: crate::interrupt::typelevel::Interrupt; } -/// InterruptableInstance trait -pub trait InterruptableInstance: IT0Instance + IT1Instance {} -/// Instance trait -pub trait Instance: sealed::Instance + RccPeripheral + InterruptableInstance + 'static {} /// Fdcan Instance struct pub struct FdcanInstance<'a, T>(PeripheralRef<'a, T>); -unsafe impl<'d, T: Instance> fdcan::message_ram::Instance for FdcanInstance<'d, T> { - const MSG_RAM: *mut RegisterBlock = T::MSG_RAM; -} - -unsafe impl<'d, T: Instance> fdcan::Instance for FdcanInstance<'d, T> -where - FdcanInstance<'d, T>: fdcan::message_ram::Instance, -{ - const REGISTERS: *mut fdcan::RegisterBlock = T::REGISTERS; -} - macro_rules! impl_fdcan { - ($inst:ident, $msg_ram_inst:ident, $msg_ram_offset:literal) => { - impl sealed::Instance for peripherals::$inst { - const REGISTERS: *mut fdcan::RegisterBlock = crate::pac::$inst.as_ptr() as *mut _; - const MSG_RAM: *mut fdcan::message_ram::RegisterBlock = crate::pac::$msg_ram_inst.as_ptr() as *mut _; + ($inst:ident, + //$irq0:ident, $irq1:ident, + $msg_ram_inst:ident, $msg_ram_offset:literal) => { + impl SealedInstance for peripherals::$inst { const MSG_RAM_OFFSET: usize = $msg_ram_offset; - fn regs() -> &'static crate::pac::can::Fdcan { - &crate::pac::$inst + fn info() -> &'static Info { + static INFO: Info = Info { + regs: Registers{regs: crate::pac::$inst, msgram: crate::pac::$msg_ram_inst, msg_ram_offset: $msg_ram_offset}, + interrupt0: crate::_generated::peripheral_interrupts::$inst::IT0::IRQ, + _interrupt1: crate::_generated::peripheral_interrupts::$inst::IT1::IRQ, + tx_waker: crate::_generated::peripheral_interrupts::$inst::IT0::pend, + }; + &INFO + } + fn registers() -> Registers { + Registers{regs: crate::pac::$inst, msgram: crate::pac::$msg_ram_inst, msg_ram_offset: Self::MSG_RAM_OFFSET} + } + unsafe fn mut_state() -> &'static mut State { + static mut STATE: State = State::new(); + &mut *core::ptr::addr_of_mut!(STATE) + } + fn state() -> &'static State { + unsafe { peripherals::$inst::mut_state() } } - fn state() -> &'static sealed::State { - static STATE: sealed::State = sealed::State::new(); - &STATE + #[cfg(feature = "time")] + fn calc_timestamp(ns_per_timer_tick: u64, ts_val: u16) -> Timestamp { + let now_embassy = embassy_time::Instant::now(); + if ns_per_timer_tick == 0 { + return now_embassy; + } + let cantime = { Self::registers().regs.tscv().read().tsc() }; + let delta = cantime.overflowing_sub(ts_val).0 as u64; + let ns = ns_per_timer_tick * delta as u64; + now_embassy - embassy_time::Duration::from_nanos(ns) } + + #[cfg(not(feature = "time"))] + fn calc_timestamp(_ns_per_timer_tick: u64, ts_val: u16) -> Timestamp { + ts_val + } + } - impl Instance for peripherals::$inst {} + #[allow(non_snake_case)] + pub(crate) mod $inst { - foreach_interrupt!( - ($inst,can,FDCAN,IT0,$irq:ident) => { - impl IT0Instance for peripherals::$inst { - type IT0Interrupt = crate::interrupt::typelevel::$irq; - } - }; - ($inst,can,FDCAN,IT1,$irq:ident) => { - impl IT1Instance for peripherals::$inst { - type IT1Interrupt = crate::interrupt::typelevel::$irq; - } - }; - ); - - impl InterruptableInstance for peripherals::$inst {} + foreach_interrupt!( + ($inst,can,FDCAN,IT0,$irq:ident) => { + pub type Interrupt0 = crate::interrupt::typelevel::$irq; + }; + ($inst,can,FDCAN,IT1,$irq:ident) => { + pub type Interrupt1 = crate::interrupt::typelevel::$irq; + }; + ); + } + impl Instance for peripherals::$inst { + type IT0Interrupt = $inst::Interrupt0; + type IT1Interrupt = $inst::Interrupt1; + } }; ($inst:ident, $msg_ram_inst:ident) => { @@ -728,7 +1054,7 @@ macro_rules! impl_fdcan { }; } -#[cfg(not(stm32h7))] +#[cfg(not(can_fdcan_h7))] foreach_peripheral!( (can, FDCAN) => { impl_fdcan!(FDCAN, FDCANRAM); }; (can, FDCAN1) => { impl_fdcan!(FDCAN1, FDCANRAM1); }; @@ -736,7 +1062,7 @@ foreach_peripheral!( (can, FDCAN3) => { impl_fdcan!(FDCAN3, FDCANRAM3); }; ); -#[cfg(stm32h7)] +#[cfg(can_fdcan_h7)] foreach_peripheral!( (can, FDCAN1) => { impl_fdcan!(FDCAN1, FDCANRAM, 0x0000); }; (can, FDCAN2) => { impl_fdcan!(FDCAN2, FDCANRAM, 0x0C00); }; diff --git a/embassy-stm32/src/can/frame.rs b/embassy-stm32/src/can/frame.rs new file mode 100644 index 000000000..d2d1f7aa6 --- /dev/null +++ b/embassy-stm32/src/can/frame.rs @@ -0,0 +1,463 @@ +//! Definition for CAN Frames +use bit_field::BitField; + +use crate::can::enums::FrameCreateError; + +/// Calculate proper timestamp when available. +#[cfg(feature = "time")] +pub type Timestamp = embassy_time::Instant; + +/// Raw register timestamp +#[cfg(not(feature = "time"))] +pub type Timestamp = u16; + +/// CAN Header, without meta data +#[derive(Debug, Copy, Clone)] +pub struct Header { + id: embedded_can::Id, + len: u8, + flags: u8, +} + +#[cfg(feature = "defmt")] +impl defmt::Format for Header { + fn format(&self, fmt: defmt::Formatter<'_>) { + match self.id() { + embedded_can::Id::Standard(id) => { + defmt::write!(fmt, "Can Standard ID={:x} len={}", id.as_raw(), self.len,) + } + embedded_can::Id::Extended(id) => { + defmt::write!(fmt, "Can Extended ID={:x} len={}", id.as_raw(), self.len,) + } + } + } +} + +impl Header { + const FLAG_RTR: usize = 0; // Remote + const FLAG_FDCAN: usize = 1; // FDCan vs Classic CAN + const FLAG_BRS: usize = 2; // Bit-rate switching, ignored for Classic CAN + + /// Create new CAN Header + pub fn new(id: embedded_can::Id, len: u8, rtr: bool) -> Header { + let mut flags = 0u8; + flags.set_bit(Self::FLAG_RTR, rtr); + Header { id, len, flags } + } + + /// Create new CAN FD Header + pub fn new_fd(id: embedded_can::Id, len: u8, rtr: bool, brs: bool) -> Header { + let mut flags = 0u8; + flags.set_bit(Self::FLAG_RTR, rtr); + flags.set_bit(Self::FLAG_FDCAN, true); + flags.set_bit(Self::FLAG_BRS, brs); + Header { id, len, flags } + } + + /// Return ID + pub fn id(&self) -> &embedded_can::Id { + &self.id + } + + /// Return length as u8 + pub fn len(&self) -> u8 { + self.len + } + + /// Is remote frame + pub fn rtr(&self) -> bool { + self.flags.get_bit(Self::FLAG_RTR) + } + + /// Request/is FDCAN frame + pub fn fdcan(&self) -> bool { + self.flags.get_bit(Self::FLAG_FDCAN) + } + + /// Request/is Flexible Data Rate + pub fn bit_rate_switching(&self) -> bool { + self.flags.get_bit(Self::FLAG_BRS) + } + + /// Get priority of frame + pub(crate) fn priority(&self) -> u32 { + match self.id() { + embedded_can::Id::Standard(id) => (id.as_raw() as u32) << 18, + embedded_can::Id::Extended(id) => id.as_raw(), + } + } +} + +/// Trait for FDCAN frame types, providing ability to construct from a Header +/// and to retrieve the Header from a frame +pub trait CanHeader: Sized { + /// Construct frame from header and payload + fn from_header(header: Header, data: &[u8]) -> Result; + + /// Get this frame's header struct + fn header(&self) -> &Header; +} + +/// Payload of a classic CAN data frame. +/// +/// Contains 0 to 8 Bytes of data. +#[derive(Debug, Copy, Clone)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct ClassicData { + pub(crate) bytes: [u8; Self::MAX_DATA_LEN], +} + +impl ClassicData { + pub(crate) const MAX_DATA_LEN: usize = 8; + /// Creates a data payload from a raw byte slice. + /// + /// Returns `None` if `data` is more than 64 bytes (which is the maximum) or + /// cannot be represented with an FDCAN DLC. + pub fn new(data: &[u8]) -> Result { + if data.len() > 8 { + return Err(FrameCreateError::InvalidDataLength); + } + + let mut bytes = [0; 8]; + bytes[..data.len()].copy_from_slice(data); + + Ok(Self { bytes }) + } + + /// Raw read access to data. + pub fn raw(&self) -> &[u8] { + &self.bytes + } + + /// Checks if the length can be encoded in FDCAN DLC field. + pub const fn is_valid_len(len: usize) -> bool { + match len { + 0..=8 => true, + _ => false, + } + } + + /// Creates an empty data payload containing 0 bytes. + #[inline] + pub const fn empty() -> Self { + Self { bytes: [0; 8] } + } +} + +/// Frame with up to 8 bytes of data payload as per Classic(non-FD) CAN +/// For CAN-FD support use FdFrame +#[derive(Debug, Copy, Clone)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct Frame { + can_header: Header, + data: ClassicData, +} + +impl Frame { + /// Create a new CAN classic Frame + pub fn new(can_header: Header, raw_data: &[u8]) -> Result { + let data = ClassicData::new(raw_data)?; + Ok(Frame { can_header, data: data }) + } + + /// Creates a new data frame. + pub fn new_data(id: impl Into, data: &[u8]) -> Result { + let eid: embedded_can::Id = id.into(); + let header = Header::new(eid, data.len() as u8, false); + Self::new(header, data) + } + + /// Create new extended frame + pub fn new_extended(raw_id: u32, raw_data: &[u8]) -> Result { + if let Some(id) = embedded_can::ExtendedId::new(raw_id) { + Self::new(Header::new(id.into(), raw_data.len() as u8, false), raw_data) + } else { + Err(FrameCreateError::InvalidCanId) + } + } + + /// Create new standard frame + pub fn new_standard(raw_id: u16, raw_data: &[u8]) -> Result { + if let Some(id) = embedded_can::StandardId::new(raw_id) { + Self::new(Header::new(id.into(), raw_data.len() as u8, false), raw_data) + } else { + Err(FrameCreateError::InvalidCanId) + } + } + + /// Create new remote frame + pub fn new_remote(id: impl Into, len: usize) -> Result { + if len <= 8usize { + Self::new(Header::new(id.into(), len as u8, true), &[0; 8]) + } else { + Err(FrameCreateError::InvalidDataLength) + } + } + + /// Get reference to data + pub fn header(&self) -> &Header { + &self.can_header + } + + /// Return ID + pub fn id(&self) -> &embedded_can::Id { + &self.can_header.id + } + + /// Get reference to data + pub fn data(&self) -> &[u8] { + &self.data.raw() + } + + /// Get priority of frame + pub fn priority(&self) -> u32 { + self.header().priority() + } +} + +impl embedded_can::Frame for Frame { + fn new(id: impl Into, raw_data: &[u8]) -> Option { + let frameopt = Frame::new(Header::new(id.into(), raw_data.len() as u8, false), raw_data); + match frameopt { + Ok(frame) => Some(frame), + Err(_) => None, + } + } + fn new_remote(id: impl Into, len: usize) -> Option { + if len <= 8 { + let frameopt = Frame::new(Header::new(id.into(), len as u8, true), &[0; 8]); + match frameopt { + Ok(frame) => Some(frame), + Err(_) => None, + } + } else { + None + } + } + fn is_extended(&self) -> bool { + match self.can_header.id { + embedded_can::Id::Extended(_) => true, + embedded_can::Id::Standard(_) => false, + } + } + fn is_remote_frame(&self) -> bool { + self.can_header.rtr() + } + fn id(&self) -> embedded_can::Id { + self.can_header.id + } + fn dlc(&self) -> usize { + self.can_header.len as usize + } + fn data(&self) -> &[u8] { + &self.data.raw() + } +} + +impl CanHeader for Frame { + fn from_header(header: Header, data: &[u8]) -> Result { + Self::new(header, data) + } + + fn header(&self) -> &Header { + self.header() + } +} + +/// Contains CAN frame and additional metadata. +/// +/// Timestamp is available if `time` feature is enabled. +/// For CAN-FD support use FdEnvelope +#[derive(Debug, Clone)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct Envelope { + /// Reception time. + pub ts: Timestamp, + /// The actual CAN frame. + pub frame: Frame, +} + +impl Envelope { + /// Convert into a tuple + pub fn parts(self) -> (Frame, Timestamp) { + (self.frame, self.ts) + } +} + +/// Payload of a (FD)CAN data frame. +/// +/// Contains 0 to 64 Bytes of data. +#[derive(Debug, Copy, Clone)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct FdData { + pub(crate) bytes: [u8; 64], +} + +impl FdData { + /// Creates a data payload from a raw byte slice. + /// + /// Returns `None` if `data` is more than 64 bytes (which is the maximum) or + /// cannot be represented with an FDCAN DLC. + pub fn new(data: &[u8]) -> Result { + if !FdData::is_valid_len(data.len()) { + return Err(FrameCreateError::InvalidDataLength); + } + + let mut bytes = [0; 64]; + bytes[..data.len()].copy_from_slice(data); + + Ok(Self { bytes }) + } + + /// Raw read access to data. + pub fn raw(&self) -> &[u8] { + &self.bytes + } + + /// Checks if the length can be encoded in FDCAN DLC field. + pub const fn is_valid_len(len: usize) -> bool { + match len { + 0..=8 => true, + 12 => true, + 16 => true, + 20 => true, + 24 => true, + 32 => true, + 48 => true, + 64 => true, + _ => false, + } + } + + /// Creates an empty data payload containing 0 bytes. + #[inline] + pub const fn empty() -> Self { + Self { bytes: [0; 64] } + } +} + +/// Frame with up to 8 bytes of data payload as per Fd CAN +#[derive(Debug, Copy, Clone)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct FdFrame { + can_header: Header, + data: FdData, +} + +impl FdFrame { + /// Create a new CAN classic Frame + pub fn new(can_header: Header, raw_data: &[u8]) -> Result { + let data = FdData::new(raw_data)?; + Ok(FdFrame { can_header, data }) + } + + /// Create new extended frame + pub fn new_extended(raw_id: u32, raw_data: &[u8]) -> Result { + if let Some(id) = embedded_can::ExtendedId::new(raw_id) { + Self::new(Header::new(id.into(), raw_data.len() as u8, false), raw_data) + } else { + Err(FrameCreateError::InvalidCanId) + } + } + + /// Create new standard frame + pub fn new_standard(raw_id: u16, raw_data: &[u8]) -> Result { + if let Some(id) = embedded_can::StandardId::new(raw_id) { + Self::new(Header::new(id.into(), raw_data.len() as u8, false), raw_data) + } else { + Err(FrameCreateError::InvalidCanId) + } + } + + /// Create new remote frame + pub fn new_remote(id: impl Into, len: usize) -> Result { + if len <= 8 { + Self::new(Header::new(id.into(), len as u8, true), &[0; 8]) + } else { + Err(FrameCreateError::InvalidDataLength) + } + } + + /// Get reference to data + pub fn header(&self) -> &Header { + &self.can_header + } + + /// Return ID + pub fn id(&self) -> &embedded_can::Id { + &self.can_header.id + } + + /// Get reference to data + pub fn data(&self) -> &[u8] { + &self.data.raw() + } +} + +impl embedded_can::Frame for FdFrame { + fn new(id: impl Into, raw_data: &[u8]) -> Option { + match FdFrame::new(Header::new_fd(id.into(), raw_data.len() as u8, false, true), raw_data) { + Ok(frame) => Some(frame), + Err(_) => None, + } + } + fn new_remote(id: impl Into, len: usize) -> Option { + if len <= 8 { + match FdFrame::new(Header::new_fd(id.into(), len as u8, true, true), &[0; 64]) { + Ok(frame) => Some(frame), + Err(_) => None, + } + } else { + None + } + } + fn is_extended(&self) -> bool { + match self.can_header.id { + embedded_can::Id::Extended(_) => true, + embedded_can::Id::Standard(_) => false, + } + } + fn is_remote_frame(&self) -> bool { + self.can_header.rtr() + } + fn id(&self) -> embedded_can::Id { + self.can_header.id + } + // Returns length in bytes even for CANFD packets which embedded-can does not really mention. + fn dlc(&self) -> usize { + self.can_header.len as usize + } + fn data(&self) -> &[u8] { + &self.data.raw() + } +} + +impl CanHeader for FdFrame { + fn from_header(header: Header, data: &[u8]) -> Result { + Self::new(header, data) + } + + fn header(&self) -> &Header { + self.header() + } +} + +/// Contains CAN FD frame and additional metadata. +/// +/// Timestamp is available if `time` feature is enabled. +#[derive(Debug, Clone)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct FdEnvelope { + /// Reception time. + pub ts: Timestamp, + + /// The actual CAN frame. + pub frame: FdFrame, +} + +impl FdEnvelope { + /// Convert into a tuple + pub fn parts(self) -> (FdFrame, Timestamp) { + (self.frame, self.ts) + } +} diff --git a/embassy-stm32/src/can/mod.rs b/embassy-stm32/src/can/mod.rs index 915edb3a6..410a6bfcb 100644 --- a/embassy-stm32/src/can/mod.rs +++ b/embassy-stm32/src/can/mod.rs @@ -1,7 +1,14 @@ //! Controller Area Network (CAN) #![macro_use] -#[cfg_attr(can_bxcan, path = "bxcan.rs")] +#[cfg_attr(can_bxcan, path = "bxcan/mod.rs")] #[cfg_attr(any(can_fdcan_v1, can_fdcan_h7), path = "fdcan.rs")] mod _version; pub use _version::*; + +mod common; +pub mod enums; +pub mod frame; +pub mod util; + +pub use frame::Frame; diff --git a/embassy-stm32/src/cordic/enums.rs b/embassy-stm32/src/cordic/enums.rs new file mode 100644 index 000000000..e8695fac7 --- /dev/null +++ b/embassy-stm32/src/cordic/enums.rs @@ -0,0 +1,71 @@ +/// CORDIC function +#[allow(missing_docs)] +#[derive(Debug, Clone, Copy)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Function { + Cos = 0, + Sin, + Phase, + Modulus, + Arctan, + Cosh, + Sinh, + Arctanh, + Ln, + Sqrt, +} + +/// CORDIC precision +#[allow(missing_docs)] +#[derive(Debug, Clone, Copy, Default)] +pub enum Precision { + Iters4 = 1, + Iters8, + Iters12, + Iters16, + Iters20, + #[default] + Iters24, // this value is recommended by Reference Manual + Iters28, + Iters32, + Iters36, + Iters40, + Iters44, + Iters48, + Iters52, + Iters56, + Iters60, +} + +/// CORDIC scale +#[allow(missing_docs)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Scale { + #[default] + Arg1Res1 = 0, + Arg1o2Res2, + Arg1o4Res4, + Arg1o8Res8, + Arg1o16Res16, + Arg1o32Res32, + Arg1o64Res64, + Arg1o128Res128, +} + +/// CORDIC argument/result register access count +#[allow(missing_docs)] +#[derive(Clone, Copy, Default)] +pub enum AccessCount { + #[default] + One, + Two, +} + +/// CORDIC argument/result data width +#[allow(missing_docs)] +#[derive(Clone, Copy)] +pub enum Width { + Bits32, + Bits16, +} diff --git a/embassy-stm32/src/cordic/errors.rs b/embassy-stm32/src/cordic/errors.rs new file mode 100644 index 000000000..3c70fc9e7 --- /dev/null +++ b/embassy-stm32/src/cordic/errors.rs @@ -0,0 +1,144 @@ +use super::{Function, Scale}; + +/// Error for [Cordic](super::Cordic) +#[derive(Debug)] +pub enum CordicError { + /// Config error + ConfigError(ConfigError), + /// Argument length is incorrect + ArgumentLengthIncorrect, + /// Result buffer length error + ResultLengthNotEnough, + /// Input value is out of range for Q1.x format + NumberOutOfRange(NumberOutOfRange), + /// Argument error + ArgError(ArgError), +} + +impl From for CordicError { + fn from(value: ConfigError) -> Self { + Self::ConfigError(value) + } +} + +impl From for CordicError { + fn from(value: NumberOutOfRange) -> Self { + Self::NumberOutOfRange(value) + } +} + +impl From for CordicError { + fn from(value: ArgError) -> Self { + Self::ArgError(value) + } +} + +#[cfg(feature = "defmt")] +impl defmt::Format for CordicError { + fn format(&self, fmt: defmt::Formatter) { + use CordicError::*; + + match self { + ConfigError(e) => defmt::write!(fmt, "{}", e), + ResultLengthNotEnough => defmt::write!(fmt, "Output buffer length is not long enough"), + ArgumentLengthIncorrect => defmt::write!(fmt, "Argument length incorrect"), + NumberOutOfRange(e) => defmt::write!(fmt, "{}", e), + ArgError(e) => defmt::write!(fmt, "{}", e), + } + } +} + +/// Error during parsing [Cordic::Config](super::Config) +#[allow(dead_code)] +#[derive(Debug)] +pub struct ConfigError { + pub(super) func: Function, + pub(super) scale_range: [u8; 2], +} + +#[cfg(feature = "defmt")] +impl defmt::Format for ConfigError { + fn format(&self, fmt: defmt::Formatter) { + defmt::write!(fmt, "For FUNCTION: {},", self.func); + + if self.scale_range[0] == self.scale_range[1] { + defmt::write!(fmt, " SCALE value should be {}", self.scale_range[0]) + } else { + defmt::write!( + fmt, + " SCALE value should be {} <= SCALE <= {}", + self.scale_range[0], + self.scale_range[1] + ) + } + } +} + +/// Input value is out of range for Q1.x format +#[allow(missing_docs)] +#[derive(Debug)] +pub enum NumberOutOfRange { + BelowLowerBound, + AboveUpperBound, +} + +#[cfg(feature = "defmt")] +impl defmt::Format for NumberOutOfRange { + fn format(&self, fmt: defmt::Formatter) { + use NumberOutOfRange::*; + + match self { + BelowLowerBound => defmt::write!(fmt, "input value should be equal or greater than -1"), + AboveUpperBound => defmt::write!(fmt, "input value should be equal or less than 1"), + } + } +} + +/// Error on checking input arguments +#[allow(dead_code)] +#[derive(Debug)] +pub struct ArgError { + pub(super) func: Function, + pub(super) scale: Option, + pub(super) arg_range: [f32; 2], // only for debug display, f32 is ok + pub(super) inclusive_upper_bound: bool, + pub(super) arg_type: ArgType, +} + +#[cfg(feature = "defmt")] +impl defmt::Format for ArgError { + fn format(&self, fmt: defmt::Formatter) { + defmt::write!(fmt, "For FUNCTION: {},", self.func); + + if let Some(scale) = self.scale { + defmt::write!(fmt, " when SCALE is {},", scale); + } + + defmt::write!(fmt, " {} should be", self.arg_type); + + if self.inclusive_upper_bound { + defmt::write!( + fmt, + " {} <= {} <= {}", + self.arg_range[0], + self.arg_type, + self.arg_range[1] + ) + } else { + defmt::write!( + fmt, + " {} <= {} < {}", + self.arg_range[0], + self.arg_type, + self.arg_range[1] + ) + }; + } +} + +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub(super) enum ArgType { + Arg1, + Arg2, +} diff --git a/embassy-stm32/src/cordic/mod.rs b/embassy-stm32/src/cordic/mod.rs new file mode 100644 index 000000000..fb342d2e7 --- /dev/null +++ b/embassy-stm32/src/cordic/mod.rs @@ -0,0 +1,730 @@ +//! coordinate rotation digital computer (CORDIC) + +use embassy_hal_internal::drop::OnDrop; +use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef}; + +use crate::pac::cordic::vals; +use crate::{dma, peripherals, rcc}; + +mod enums; +pub use enums::*; + +mod errors; +pub use errors::*; + +pub mod utils; + +/// CORDIC driver +pub struct Cordic<'d, T: Instance> { + peri: PeripheralRef<'d, T>, + config: Config, +} + +/// Cordic instance +trait SealedInstance { + /// Get access to CORDIC registers + fn regs() -> crate::pac::cordic::Cordic; + + /// Set Function value + fn set_func(&self, func: Function) { + Self::regs() + .csr() + .modify(|v| v.set_func(vals::Func::from_bits(func as u8))); + } + + /// Set Precision value + fn set_precision(&self, precision: Precision) { + Self::regs() + .csr() + .modify(|v| v.set_precision(vals::Precision::from_bits(precision as u8))) + } + + /// Set Scale value + fn set_scale(&self, scale: Scale) { + Self::regs() + .csr() + .modify(|v| v.set_scale(vals::Scale::from_bits(scale as u8))) + } + + /// Enable global interrupt + #[allow(unused)] + fn enable_irq(&self) { + Self::regs().csr().modify(|v| v.set_ien(true)) + } + + /// Disable global interrupt + fn disable_irq(&self) { + Self::regs().csr().modify(|v| v.set_ien(false)) + } + + /// Enable Read DMA + fn enable_read_dma(&self) { + Self::regs().csr().modify(|v| { + v.set_dmaren(true); + }) + } + + /// Disable Read DMA + fn disable_read_dma(&self) { + Self::regs().csr().modify(|v| { + v.set_dmaren(false); + }) + } + + /// Enable Write DMA + fn enable_write_dma(&self) { + Self::regs().csr().modify(|v| { + v.set_dmawen(true); + }) + } + + /// Disable Write DMA + fn disable_write_dma(&self) { + Self::regs().csr().modify(|v| { + v.set_dmawen(false); + }) + } + + /// Set NARGS value + fn set_argument_count(&self, n: AccessCount) { + Self::regs().csr().modify(|v| { + v.set_nargs(match n { + AccessCount::One => vals::Num::NUM1, + AccessCount::Two => vals::Num::NUM2, + }) + }) + } + + /// Set NRES value + fn set_result_count(&self, n: AccessCount) { + Self::regs().csr().modify(|v| { + v.set_nres(match n { + AccessCount::One => vals::Num::NUM1, + AccessCount::Two => vals::Num::NUM2, + }); + }) + } + + /// Set ARGSIZE and RESSIZE value + fn set_data_width(&self, arg: Width, res: Width) { + Self::regs().csr().modify(|v| { + v.set_argsize(match arg { + Width::Bits32 => vals::Size::BITS32, + Width::Bits16 => vals::Size::BITS16, + }); + v.set_ressize(match res { + Width::Bits32 => vals::Size::BITS32, + Width::Bits16 => vals::Size::BITS16, + }) + }) + } + + /// Read RRDY flag + fn ready_to_read(&self) -> bool { + Self::regs().csr().read().rrdy() + } + + /// Write value to WDATA + fn write_argument(&self, arg: u32) { + Self::regs().wdata().write_value(arg) + } + + /// Read value from RDATA + fn read_result(&self) -> u32 { + Self::regs().rdata().read() + } +} + +/// CORDIC instance trait +#[allow(private_bounds)] +pub trait Instance: SealedInstance + Peripheral

+ crate::rcc::RccPeripheral {} + +/// CORDIC configuration +#[derive(Debug)] +pub struct Config { + function: Function, + precision: Precision, + scale: Scale, +} + +impl Config { + /// Create a config for Cordic driver + pub fn new(function: Function, precision: Precision, scale: Scale) -> Result { + let config = Self { + function, + precision, + scale, + }; + + config.check_scale()?; + + Ok(config) + } + + fn check_scale(&self) -> Result<(), ConfigError> { + use Function::*; + + let scale_raw = self.scale as u8; + + let err_range = match self.function { + Cos | Sin | Phase | Modulus if !(0..=0).contains(&scale_raw) => Some([0, 0]), + + Arctan if !(0..=7).contains(&scale_raw) => Some([0, 7]), + + Cosh | Sinh | Arctanh if !(1..=1).contains(&scale_raw) => Some([1, 1]), + + Ln if !(1..=4).contains(&scale_raw) => Some([1, 4]), + + Sqrt if !(0..=2).contains(&scale_raw) => Some([0, 2]), + + Cos | Sin | Phase | Modulus | Arctan | Cosh | Sinh | Arctanh | Ln | Sqrt => None, + }; + + if let Some(range) = err_range { + Err(ConfigError { + func: self.function, + scale_range: range, + }) + } else { + Ok(()) + } + } +} + +// common method +impl<'d, T: Instance> Cordic<'d, T> { + /// Create a Cordic driver instance + /// + /// Note: + /// If you need a peripheral -> CORDIC -> peripheral mode, + /// you may want to set Cordic into [Mode::ZeroOverhead] mode, and add extra arguments with [Self::extra_config] + pub fn new(peri: impl Peripheral

+ 'd, config: Config) -> Self { + rcc::enable_and_reset::(); + + into_ref!(peri); + + let mut instance = Self { peri, config }; + + instance.reconfigure(); + + instance + } + + /// Set a new config for Cordic driver + pub fn set_config(&mut self, config: Config) { + self.config = config; + self.reconfigure(); + } + + /// Set extra config for data count and data width. + pub fn extra_config(&mut self, arg_cnt: AccessCount, arg_width: Width, res_width: Width) { + self.peri.set_argument_count(arg_cnt); + self.peri.set_data_width(arg_width, res_width); + } + + fn clean_rrdy_flag(&mut self) { + while self.peri.ready_to_read() { + self.peri.read_result(); + } + } + + /// Disable IRQ and DMA, clean RRDY, and set ARG2 to +1 (0x7FFFFFFF) + pub fn reconfigure(&mut self) { + // reset ARG2 to +1 + { + self.peri.disable_irq(); + self.peri.disable_read_dma(); + self.peri.disable_write_dma(); + self.clean_rrdy_flag(); + + self.peri.set_func(Function::Cos); + self.peri.set_precision(Precision::Iters4); + self.peri.set_scale(Scale::Arg1Res1); + self.peri.set_argument_count(AccessCount::Two); + self.peri.set_data_width(Width::Bits32, Width::Bits32); + self.peri.write_argument(0x0u32); + self.peri.write_argument(0x7FFFFFFFu32); + + self.clean_rrdy_flag(); + } + + self.peri.set_func(self.config.function); + self.peri.set_precision(self.config.precision); + self.peri.set_scale(self.config.scale); + + // we don't set NRES in here, but to make sure NRES is set each time user call "calc"-ish functions, + // since each "calc"-ish functions can have different ARGSIZE and RESSIZE, thus NRES should be change accordingly. + } +} + +impl<'d, T: Instance> Drop for Cordic<'d, T> { + fn drop(&mut self) { + rcc::disable::(); + } +} + +// q1.31 related +impl<'d, T: Instance> Cordic<'d, T> { + /// Run a blocking CORDIC calculation in q1.31 format + /// + /// Notice: + /// If you set `arg1_only` to `true`, please be sure ARG2 value has been set to desired value before. + /// This function won't set ARG2 to +1 before or after each round of calculation. + /// If you want to make sure ARG2 is set to +1, consider run [.reconfigure()](Self::reconfigure). + pub fn blocking_calc_32bit( + &mut self, + arg: &[u32], + res: &mut [u32], + arg1_only: bool, + res1_only: bool, + ) -> Result { + if arg.is_empty() { + return Ok(0); + } + + let res_cnt = Self::check_arg_res_length_32bit(arg.len(), res.len(), arg1_only, res1_only)?; + + self.peri + .set_argument_count(if arg1_only { AccessCount::One } else { AccessCount::Two }); + + self.peri + .set_result_count(if res1_only { AccessCount::One } else { AccessCount::Two }); + + self.peri.set_data_width(Width::Bits32, Width::Bits32); + + let mut cnt = 0; + + match arg1_only { + true => { + // To use cordic preload function, the first value is special. + // It is loaded to CORDIC WDATA register out side of loop + let first_value = arg[0]; + + // preload 1st value to CORDIC, to start the CORDIC calc + self.peri.write_argument(first_value); + + for &arg1 in &arg[1..] { + // preload arg1 (for next calc) + self.peri.write_argument(arg1); + + // then read current result out + res[cnt] = self.peri.read_result(); + cnt += 1; + if !res1_only { + res[cnt] = self.peri.read_result(); + cnt += 1; + } + } + + // read the last result + res[cnt] = self.peri.read_result(); + cnt += 1; + if !res1_only { + res[cnt] = self.peri.read_result(); + // cnt += 1; + } + } + false => { + // To use cordic preload function, the first and last value is special. + // They are load to CORDIC WDATA register out side of loop + let first_value = arg[0]; + let last_value = arg[arg.len() - 1]; + + let paired_args = &arg[1..arg.len() - 1]; + + // preload 1st value to CORDIC + self.peri.write_argument(first_value); + + for args in paired_args.chunks(2) { + let arg2 = args[0]; + let arg1 = args[1]; + + // load arg2 (for current calc) first, to start the CORDIC calc + self.peri.write_argument(arg2); + + // preload arg1 (for next calc) + self.peri.write_argument(arg1); + + // then read current result out + res[cnt] = self.peri.read_result(); + cnt += 1; + if !res1_only { + res[cnt] = self.peri.read_result(); + cnt += 1; + } + } + + // load last value to CORDIC, and finish the calculation + self.peri.write_argument(last_value); + res[cnt] = self.peri.read_result(); + cnt += 1; + if !res1_only { + res[cnt] = self.peri.read_result(); + // cnt += 1; + } + } + } + + // at this point cnt should be equal to res_cnt + + Ok(res_cnt) + } + + /// Run a async CORDIC calculation in q.1.31 format + /// + /// Notice: + /// If you set `arg1_only` to `true`, please be sure ARG2 value has been set to desired value before. + /// This function won't set ARG2 to +1 before or after each round of calculation. + /// If you want to make sure ARG2 is set to +1, consider run [.reconfigure()](Self::reconfigure). + pub async fn async_calc_32bit( + &mut self, + write_dma: impl Peripheral

>, + read_dma: impl Peripheral

>, + arg: &[u32], + res: &mut [u32], + arg1_only: bool, + res1_only: bool, + ) -> Result { + if arg.is_empty() { + return Ok(0); + } + + let res_cnt = Self::check_arg_res_length_32bit(arg.len(), res.len(), arg1_only, res1_only)?; + + let active_res_buf = &mut res[..res_cnt]; + + into_ref!(write_dma, read_dma); + + self.peri + .set_argument_count(if arg1_only { AccessCount::One } else { AccessCount::Two }); + + self.peri + .set_result_count(if res1_only { AccessCount::One } else { AccessCount::Two }); + + self.peri.set_data_width(Width::Bits32, Width::Bits32); + + let write_req = write_dma.request(); + let read_req = read_dma.request(); + + self.peri.enable_write_dma(); + self.peri.enable_read_dma(); + + let _on_drop = OnDrop::new(|| { + self.peri.disable_write_dma(); + self.peri.disable_read_dma(); + }); + + unsafe { + let write_transfer = dma::Transfer::new_write( + &mut write_dma, + write_req, + arg, + T::regs().wdata().as_ptr() as *mut _, + Default::default(), + ); + + let read_transfer = dma::Transfer::new_read( + &mut read_dma, + read_req, + T::regs().rdata().as_ptr() as *mut _, + active_res_buf, + Default::default(), + ); + + embassy_futures::join::join(write_transfer, read_transfer).await; + } + + Ok(res_cnt) + } + + fn check_arg_res_length_32bit( + arg_len: usize, + res_len: usize, + arg1_only: bool, + res1_only: bool, + ) -> Result { + if !arg1_only && arg_len % 2 != 0 { + return Err(CordicError::ArgumentLengthIncorrect); + } + + let mut minimal_res_length = arg_len; + + if !res1_only { + minimal_res_length *= 2; + } + + if !arg1_only { + minimal_res_length /= 2 + } + + if minimal_res_length > res_len { + return Err(CordicError::ResultLengthNotEnough); + } + + Ok(minimal_res_length) + } +} + +// q1.15 related +impl<'d, T: Instance> Cordic<'d, T> { + /// Run a blocking CORDIC calculation in q1.15 format + /// + /// Notice:: + /// User will take respond to merge two u16 arguments into one u32 data, and/or split one u32 data into two u16 results. + pub fn blocking_calc_16bit(&mut self, arg: &[u32], res: &mut [u32]) -> Result { + if arg.is_empty() { + return Ok(0); + } + + if arg.len() > res.len() { + return Err(CordicError::ResultLengthNotEnough); + } + + let res_cnt = arg.len(); + + // In q1.15 mode, 1 write/read to access 2 arguments/results + self.peri.set_argument_count(AccessCount::One); + self.peri.set_result_count(AccessCount::One); + + self.peri.set_data_width(Width::Bits16, Width::Bits16); + + // To use cordic preload function, the first value is special. + // It is loaded to CORDIC WDATA register out side of loop + let first_value = arg[0]; + + // preload 1st value to CORDIC, to start the CORDIC calc + self.peri.write_argument(first_value); + + let mut cnt = 0; + + for &arg_val in &arg[1..] { + // preload arg_val (for next calc) + self.peri.write_argument(arg_val); + + // then read current result out + res[cnt] = self.peri.read_result(); + cnt += 1; + } + + // read last result out + res[cnt] = self.peri.read_result(); + // cnt += 1; + + Ok(res_cnt) + } + + /// Run a async CORDIC calculation in q1.15 format + /// + /// Notice:: + /// User will take respond to merge two u16 arguments into one u32 data, and/or split one u32 data into two u16 results. + pub async fn async_calc_16bit( + &mut self, + write_dma: impl Peripheral

>, + read_dma: impl Peripheral

>, + arg: &[u32], + res: &mut [u32], + ) -> Result { + if arg.is_empty() { + return Ok(0); + } + + if arg.len() > res.len() { + return Err(CordicError::ResultLengthNotEnough); + } + + let res_cnt = arg.len(); + + let active_res_buf = &mut res[..res_cnt]; + + into_ref!(write_dma, read_dma); + + // In q1.15 mode, 1 write/read to access 2 arguments/results + self.peri.set_argument_count(AccessCount::One); + self.peri.set_result_count(AccessCount::One); + + self.peri.set_data_width(Width::Bits16, Width::Bits16); + + let write_req = write_dma.request(); + let read_req = read_dma.request(); + + self.peri.enable_write_dma(); + self.peri.enable_read_dma(); + + let _on_drop = OnDrop::new(|| { + self.peri.disable_write_dma(); + self.peri.disable_read_dma(); + }); + + unsafe { + let write_transfer = dma::Transfer::new_write( + &mut write_dma, + write_req, + arg, + T::regs().wdata().as_ptr() as *mut _, + Default::default(), + ); + + let read_transfer = dma::Transfer::new_read( + &mut read_dma, + read_req, + T::regs().rdata().as_ptr() as *mut _, + active_res_buf, + Default::default(), + ); + + embassy_futures::join::join(write_transfer, read_transfer).await; + } + + Ok(res_cnt) + } +} + +macro_rules! check_arg_value { + ($func_arg1_name:ident, $func_arg2_name:ident, $float_type:ty) => { + impl<'d, T: Instance> Cordic<'d, T> { + /// check input value ARG1, SCALE and FUNCTION are compatible with each other + pub fn $func_arg1_name(&self, arg: $float_type) -> Result<(), ArgError> { + let config = &self.config; + + use Function::*; + + struct Arg1ErrInfo { + scale: Option, + range: [f32; 2], // f32 is ok, it only used in error display + inclusive_upper_bound: bool, + } + + let err_info = match config.function { + Cos | Sin | Phase | Modulus | Arctan if !(-1.0..=1.0).contains(arg) => Some(Arg1ErrInfo { + scale: None, + range: [-1.0, 1.0], + inclusive_upper_bound: true, + }), + + Cosh | Sinh if !(-0.559..=0.559).contains(arg) => Some(Arg1ErrInfo { + scale: None, + range: [-0.559, 0.559], + inclusive_upper_bound: true, + }), + + Arctanh if !(-0.403..=0.403).contains(arg) => Some(Arg1ErrInfo { + scale: None, + range: [-0.403, 0.403], + inclusive_upper_bound: true, + }), + + Ln => match config.scale { + Scale::Arg1o2Res2 if !(0.0535..0.5).contains(arg) => Some(Arg1ErrInfo { + scale: Some(Scale::Arg1o2Res2), + range: [0.0535, 0.5], + inclusive_upper_bound: false, + }), + Scale::Arg1o4Res4 if !(0.25..0.75).contains(arg) => Some(Arg1ErrInfo { + scale: Some(Scale::Arg1o4Res4), + range: [0.25, 0.75], + inclusive_upper_bound: false, + }), + Scale::Arg1o8Res8 if !(0.375..0.875).contains(arg) => Some(Arg1ErrInfo { + scale: Some(Scale::Arg1o8Res8), + range: [0.375, 0.875], + inclusive_upper_bound: false, + }), + Scale::Arg1o16Res16 if !(0.4375..0.584).contains(arg) => Some(Arg1ErrInfo { + scale: Some(Scale::Arg1o16Res16), + range: [0.4375, 0.584], + inclusive_upper_bound: false, + }), + + Scale::Arg1o2Res2 | Scale::Arg1o4Res4 | Scale::Arg1o8Res8 | Scale::Arg1o16Res16 => None, + + _ => unreachable!(), + }, + + Sqrt => match config.scale { + Scale::Arg1Res1 if !(0.027..0.75).contains(arg) => Some(Arg1ErrInfo { + scale: Some(Scale::Arg1Res1), + range: [0.027, 0.75], + inclusive_upper_bound: false, + }), + Scale::Arg1o2Res2 if !(0.375..0.875).contains(arg) => Some(Arg1ErrInfo { + scale: Some(Scale::Arg1o2Res2), + range: [0.375, 0.875], + inclusive_upper_bound: false, + }), + Scale::Arg1o4Res4 if !(0.4375..0.584).contains(arg) => Some(Arg1ErrInfo { + scale: Some(Scale::Arg1o4Res4), + range: [0.4375, 0.584], + inclusive_upper_bound: false, + }), + Scale::Arg1Res1 | Scale::Arg1o2Res2 | Scale::Arg1o4Res4 => None, + _ => unreachable!(), + }, + + Cos | Sin | Phase | Modulus | Arctan | Cosh | Sinh | Arctanh => None, + }; + + if let Some(err) = err_info { + return Err(ArgError { + func: config.function, + scale: err.scale, + arg_range: err.range, + inclusive_upper_bound: err.inclusive_upper_bound, + arg_type: ArgType::Arg1, + }); + } + + Ok(()) + } + + /// check input value ARG2 and FUNCTION are compatible with each other + pub fn $func_arg2_name(&self, arg: $float_type) -> Result<(), ArgError> { + let config = &self.config; + + use Function::*; + + struct Arg2ErrInfo { + range: [f32; 2], // f32 is ok, it only used in error display + } + + let err_info = match config.function { + Cos | Sin if !(0.0..=1.0).contains(arg) => Some(Arg2ErrInfo { range: [0.0, 1.0] }), + + Phase | Modulus if !(-1.0..=1.0).contains(arg) => Some(Arg2ErrInfo { range: [-1.0, 1.0] }), + + Cos | Sin | Phase | Modulus | Arctan | Cosh | Sinh | Arctanh | Ln | Sqrt => None, + }; + + if let Some(err) = err_info { + return Err(ArgError { + func: config.function, + scale: None, + arg_range: err.range, + inclusive_upper_bound: true, + arg_type: ArgType::Arg2, + }); + } + + Ok(()) + } + } + }; +} + +check_arg_value!(check_f64_arg1, check_f64_arg2, &f64); +check_arg_value!(check_f32_arg1, check_f32_arg2, &f32); + +foreach_interrupt!( + ($inst:ident, cordic, $block:ident, GLOBAL, $irq:ident) => { + impl Instance for peripherals::$inst { + } + + impl SealedInstance for peripherals::$inst { + fn regs() -> crate::pac::cordic::Cordic { + crate::pac::$inst + } + } + }; +); + +dma_trait!(WriteDma, Instance); +dma_trait!(ReadDma, Instance); diff --git a/embassy-stm32/src/cordic/utils.rs b/embassy-stm32/src/cordic/utils.rs new file mode 100644 index 000000000..008f50270 --- /dev/null +++ b/embassy-stm32/src/cordic/utils.rs @@ -0,0 +1,62 @@ +//! Common math utils +use super::errors::NumberOutOfRange; + +macro_rules! floating_fixed_convert { + ($f_to_q:ident, $q_to_f:ident, $unsigned_bin_typ:ty, $signed_bin_typ:ty, $float_ty:ty, $offset:literal, $min_positive:literal) => { + /// convert float point to fixed point format + pub fn $f_to_q(value: $float_ty) -> Result<$unsigned_bin_typ, NumberOutOfRange> { + const MIN_POSITIVE: $float_ty = unsafe { core::mem::transmute($min_positive) }; + + if value < -1.0 { + return Err(NumberOutOfRange::BelowLowerBound) + } + + if value > 1.0 { + return Err(NumberOutOfRange::AboveUpperBound) + } + + + let value = if 1.0 - MIN_POSITIVE < value && value <= 1.0 { + // make a exception for value between (1.0^{-x} , 1.0] float point, + // convert it to max representable value of q1.x format + (1.0 as $float_ty) - MIN_POSITIVE + } else { + value + }; + + // It's necessary to cast the float value to signed integer, before convert it to a unsigned value. + // Since value from register is actually a "signed value", a "as" cast will keep original binary format but mark it as a unsigned value for register writing. + // see https://doc.rust-lang.org/reference/expressions/operator-expr.html#numeric-cast + Ok((value * ((1 as $unsigned_bin_typ << $offset) as $float_ty)) as $signed_bin_typ as $unsigned_bin_typ) + } + + #[inline(always)] + /// convert fixed point to float point format + pub fn $q_to_f(value: $unsigned_bin_typ) -> $float_ty { + // It's necessary to cast the unsigned integer to signed integer, before convert it to a float value. + // Since value from register is actually a "signed value", a "as" cast will keep original binary format but mark it as a signed value. + // see https://doc.rust-lang.org/reference/expressions/operator-expr.html#numeric-cast + (value as $signed_bin_typ as $float_ty) / ((1 as $unsigned_bin_typ << $offset) as $float_ty) + } + }; +} + +floating_fixed_convert!( + f64_to_q1_31, + q1_31_to_f64, + u32, + i32, + f64, + 31, + 0x3E00_0000_0000_0000u64 // binary form of 1f64^(-31) +); + +floating_fixed_convert!( + f32_to_q1_15, + q1_15_to_f32, + u16, + i16, + f32, + 15, + 0x3800_0000u32 // binary form of 1f32^(-15) +); diff --git a/embassy-stm32/src/crc/v1.rs b/embassy-stm32/src/crc/v1.rs index 0166ab819..f3d13de7c 100644 --- a/embassy-stm32/src/crc/v1.rs +++ b/embassy-stm32/src/crc/v1.rs @@ -2,8 +2,7 @@ use embassy_hal_internal::{into_ref, PeripheralRef}; use crate::pac::CRC as PAC_CRC; use crate::peripherals::CRC; -use crate::rcc::sealed::RccPeripheral; -use crate::Peripheral; +use crate::{rcc, Peripheral}; /// CRC driver. pub struct Crc<'d> { @@ -17,7 +16,7 @@ impl<'d> Crc<'d> { // Note: enable and reset come from RccPeripheral. // enable CRC clock in RCC. - CRC::enable_and_reset(); + rcc::enable_and_reset::(); // Peripheral the peripheral let mut instance = Self { _peri: peripheral }; instance.reset(); @@ -32,6 +31,9 @@ impl<'d> Crc<'d> { /// Feeds a word to the peripheral and returns the current CRC value pub fn feed_word(&mut self, word: u32) -> u32 { // write a single byte to the device, and return the result + #[cfg(not(crc_v1))] + PAC_CRC.dr32().write_value(word); + #[cfg(crc_v1)] PAC_CRC.dr().write_value(word); self.read() } @@ -39,6 +41,9 @@ impl<'d> Crc<'d> { /// Feed a slice of words to the peripheral and return the result. pub fn feed_words(&mut self, words: &[u32]) -> u32 { for word in words { + #[cfg(not(crc_v1))] + PAC_CRC.dr32().write_value(*word); + #[cfg(crc_v1)] PAC_CRC.dr().write_value(*word); } @@ -46,6 +51,12 @@ impl<'d> Crc<'d> { } /// Read the CRC result value. + #[cfg(not(crc_v1))] + pub fn read(&self) -> u32 { + PAC_CRC.dr32().read() + } + /// Read the CRC result value. + #[cfg(crc_v1)] pub fn read(&self) -> u32 { PAC_CRC.dr().read() } diff --git a/embassy-stm32/src/crc/v2v3.rs b/embassy-stm32/src/crc/v2v3.rs index 0c4ae55ce..09d956d7c 100644 --- a/embassy-stm32/src/crc/v2v3.rs +++ b/embassy-stm32/src/crc/v2v3.rs @@ -3,8 +3,7 @@ use embassy_hal_internal::{into_ref, PeripheralRef}; use crate::pac::crc::vals; use crate::pac::CRC as PAC_CRC; use crate::peripherals::CRC; -use crate::rcc::sealed::RccPeripheral; -use crate::Peripheral; +use crate::{rcc, Peripheral}; /// CRC driver. pub struct Crc<'d> { @@ -13,6 +12,8 @@ pub struct Crc<'d> { } /// CRC configuration errlr +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum ConfigError { /// The selected polynomial is invalid. InvalidPolynomial, @@ -82,7 +83,7 @@ impl<'d> Crc<'d> { pub fn new(peripheral: impl Peripheral

+ 'd, config: Config) -> Self { // Note: enable and reset come from RccPeripheral. // reset to default values and enable CRC clock in RCC. - CRC::enable_and_reset(); + rcc::enable_and_reset::(); into_ref!(peripheral); let mut instance = Self { _peripheral: peripheral, @@ -136,7 +137,7 @@ impl<'d> Crc<'d> { /// Feeds a byte into the CRC peripheral. Returns the computed checksum. pub fn feed_byte(&mut self, byte: u8) -> u32 { PAC_CRC.dr8().write_value(byte); - PAC_CRC.dr().read() + PAC_CRC.dr32().read() } /// Feeds an slice of bytes into the CRC peripheral. Returns the computed checksum. @@ -144,30 +145,30 @@ impl<'d> Crc<'d> { for byte in bytes { PAC_CRC.dr8().write_value(*byte); } - PAC_CRC.dr().read() + PAC_CRC.dr32().read() } /// Feeds a halfword into the CRC peripheral. Returns the computed checksum. pub fn feed_halfword(&mut self, halfword: u16) -> u32 { PAC_CRC.dr16().write_value(halfword); - PAC_CRC.dr().read() + PAC_CRC.dr32().read() } /// Feeds an slice of halfwords into the CRC peripheral. Returns the computed checksum. pub fn feed_halfwords(&mut self, halfwords: &[u16]) -> u32 { for halfword in halfwords { PAC_CRC.dr16().write_value(*halfword); } - PAC_CRC.dr().read() + PAC_CRC.dr32().read() } /// Feeds a words into the CRC peripheral. Returns the computed checksum. pub fn feed_word(&mut self, word: u32) -> u32 { - PAC_CRC.dr().write_value(word as u32); - PAC_CRC.dr().read() + PAC_CRC.dr32().write_value(word as u32); + PAC_CRC.dr32().read() } /// Feeds an slice of words into the CRC peripheral. Returns the computed checksum. pub fn feed_words(&mut self, words: &[u32]) -> u32 { for word in words { - PAC_CRC.dr().write_value(*word as u32); + PAC_CRC.dr32().write_value(*word as u32); } - PAC_CRC.dr().read() + PAC_CRC.dr32().read() } } diff --git a/embassy-stm32/src/cryp/mod.rs b/embassy-stm32/src/cryp/mod.rs new file mode 100644 index 000000000..8d600c73c --- /dev/null +++ b/embassy-stm32/src/cryp/mod.rs @@ -0,0 +1,1909 @@ +//! Crypto Accelerator (CRYP) +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +use core::cmp::min; +use core::marker::PhantomData; +use core::ptr; + +use embassy_hal_internal::{into_ref, PeripheralRef}; +use embassy_sync::waitqueue::AtomicWaker; + +use crate::dma::{NoDma, Transfer, TransferOptions}; +use crate::interrupt::typelevel::Interrupt; +use crate::{interrupt, pac, peripherals, rcc, Peripheral}; + +const DES_BLOCK_SIZE: usize = 8; // 64 bits +const AES_BLOCK_SIZE: usize = 16; // 128 bits + +static CRYP_WAKER: AtomicWaker = AtomicWaker::new(); + +/// CRYP interrupt handler. +pub struct InterruptHandler { + _phantom: PhantomData, +} + +impl interrupt::typelevel::Handler for InterruptHandler { + unsafe fn on_interrupt() { + let bits = T::regs().misr().read(); + if bits.inmis() { + T::regs().imscr().modify(|w| w.set_inim(false)); + CRYP_WAKER.wake(); + } + if bits.outmis() { + T::regs().imscr().modify(|w| w.set_outim(false)); + CRYP_WAKER.wake(); + } + } +} + +/// This trait encapsulates all cipher-specific behavior/ +pub trait Cipher<'c> { + /// Processing block size. Determined by the processor and the algorithm. + const BLOCK_SIZE: usize; + + /// Indicates whether the cipher requires the application to provide padding. + /// If `true`, no partial blocks will be accepted (a panic will occur). + const REQUIRES_PADDING: bool = false; + + /// Returns the symmetric key. + fn key(&self) -> &[u8]; + + /// Returns the initialization vector. + fn iv(&self) -> &[u8]; + + /// Sets the processor algorithm mode according to the associated cipher. + fn set_algomode(&self, p: pac::cryp::Cryp); + + /// Performs any key preparation within the processor, if necessary. + fn prepare_key(&self, _p: pac::cryp::Cryp) {} + + /// Performs any cipher-specific initialization. + fn init_phase_blocking(&self, _p: pac::cryp::Cryp, _cryp: &Cryp) {} + + /// Performs any cipher-specific initialization. + async fn init_phase(&self, _p: pac::cryp::Cryp, _cryp: &mut Cryp<'_, T, DmaIn, DmaOut>) + where + DmaIn: crate::cryp::DmaIn, + DmaOut: crate::cryp::DmaOut, + { + } + + /// Called prior to processing the last data block for cipher-specific operations. + fn pre_final(&self, _p: pac::cryp::Cryp, _dir: Direction, _padding_len: usize) -> [u32; 4] { + return [0; 4]; + } + + /// Called after processing the last data block for cipher-specific operations. + fn post_final_blocking( + &self, + _p: pac::cryp::Cryp, + _cryp: &Cryp, + _dir: Direction, + _int_data: &mut [u8; AES_BLOCK_SIZE], + _temp1: [u32; 4], + _padding_mask: [u8; 16], + ) { + } + + /// Called after processing the last data block for cipher-specific operations. + async fn post_final( + &self, + _p: pac::cryp::Cryp, + _cryp: &mut Cryp<'_, T, DmaIn, DmaOut>, + _dir: Direction, + _int_data: &mut [u8; AES_BLOCK_SIZE], + _temp1: [u32; 4], + _padding_mask: [u8; 16], + ) where + DmaIn: crate::cryp::DmaIn, + DmaOut: crate::cryp::DmaOut, + { + } + + /// Returns the AAD header block as required by the cipher. + fn get_header_block(&self) -> &[u8] { + return [0; 0].as_slice(); + } +} + +/// This trait enables restriction of ciphers to specific key sizes. +pub trait CipherSized {} + +/// This trait enables restriction of initialization vectors to sizes compatibile with a cipher mode. +pub trait IVSized {} + +/// This trait enables restriction of a header phase to authenticated ciphers only. +pub trait CipherAuthenticated { + /// Defines the authentication tag size. + const TAG_SIZE: usize = TAG_SIZE; +} + +/// TDES-ECB Cipher Mode +pub struct TdesEcb<'c, const KEY_SIZE: usize> { + iv: &'c [u8; 0], + key: &'c [u8; KEY_SIZE], +} + +impl<'c, const KEY_SIZE: usize> TdesEcb<'c, KEY_SIZE> { + /// Constructs a new AES-ECB cipher for a cryptographic operation. + pub fn new(key: &'c [u8; KEY_SIZE]) -> Self { + return Self { key: key, iv: &[0; 0] }; + } +} + +impl<'c, const KEY_SIZE: usize> Cipher<'c> for TdesEcb<'c, KEY_SIZE> { + const BLOCK_SIZE: usize = DES_BLOCK_SIZE; + const REQUIRES_PADDING: bool = true; + + fn key(&self) -> &'c [u8] { + self.key + } + + fn iv(&self) -> &'c [u8] { + self.iv + } + + fn set_algomode(&self, p: pac::cryp::Cryp) { + #[cfg(cryp_v1)] + { + p.cr().modify(|w| w.set_algomode(0)); + } + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + { + p.cr().modify(|w| w.set_algomode0(0)); + p.cr().modify(|w| w.set_algomode3(false)); + } + } +} + +impl<'c> CipherSized for TdesEcb<'c, { 112 / 8 }> {} +impl<'c> CipherSized for TdesEcb<'c, { 168 / 8 }> {} +impl<'c, const KEY_SIZE: usize> IVSized for TdesEcb<'c, KEY_SIZE> {} + +/// TDES-CBC Cipher Mode +pub struct TdesCbc<'c, const KEY_SIZE: usize> { + iv: &'c [u8; 8], + key: &'c [u8; KEY_SIZE], +} + +impl<'c, const KEY_SIZE: usize> TdesCbc<'c, KEY_SIZE> { + /// Constructs a new TDES-CBC cipher for a cryptographic operation. + pub fn new(key: &'c [u8; KEY_SIZE], iv: &'c [u8; 8]) -> Self { + return Self { key: key, iv: iv }; + } +} + +impl<'c, const KEY_SIZE: usize> Cipher<'c> for TdesCbc<'c, KEY_SIZE> { + const BLOCK_SIZE: usize = DES_BLOCK_SIZE; + const REQUIRES_PADDING: bool = true; + + fn key(&self) -> &'c [u8] { + self.key + } + + fn iv(&self) -> &'c [u8] { + self.iv + } + + fn set_algomode(&self, p: pac::cryp::Cryp) { + #[cfg(cryp_v1)] + { + p.cr().modify(|w| w.set_algomode(1)); + } + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + { + p.cr().modify(|w| w.set_algomode0(1)); + p.cr().modify(|w| w.set_algomode3(false)); + } + } +} + +impl<'c> CipherSized for TdesCbc<'c, { 112 / 8 }> {} +impl<'c> CipherSized for TdesCbc<'c, { 168 / 8 }> {} +impl<'c, const KEY_SIZE: usize> IVSized for TdesCbc<'c, KEY_SIZE> {} + +/// DES-ECB Cipher Mode +pub struct DesEcb<'c, const KEY_SIZE: usize> { + iv: &'c [u8; 0], + key: &'c [u8; KEY_SIZE], +} + +impl<'c, const KEY_SIZE: usize> DesEcb<'c, KEY_SIZE> { + /// Constructs a new AES-ECB cipher for a cryptographic operation. + pub fn new(key: &'c [u8; KEY_SIZE]) -> Self { + return Self { key: key, iv: &[0; 0] }; + } +} + +impl<'c, const KEY_SIZE: usize> Cipher<'c> for DesEcb<'c, KEY_SIZE> { + const BLOCK_SIZE: usize = DES_BLOCK_SIZE; + const REQUIRES_PADDING: bool = true; + + fn key(&self) -> &'c [u8] { + self.key + } + + fn iv(&self) -> &'c [u8] { + self.iv + } + + fn set_algomode(&self, p: pac::cryp::Cryp) { + #[cfg(cryp_v1)] + { + p.cr().modify(|w| w.set_algomode(2)); + } + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + { + p.cr().modify(|w| w.set_algomode0(2)); + p.cr().modify(|w| w.set_algomode3(false)); + } + } +} + +impl<'c> CipherSized for DesEcb<'c, { 56 / 8 }> {} +impl<'c, const KEY_SIZE: usize> IVSized for DesEcb<'c, KEY_SIZE> {} + +/// DES-CBC Cipher Mode +pub struct DesCbc<'c, const KEY_SIZE: usize> { + iv: &'c [u8; 8], + key: &'c [u8; KEY_SIZE], +} + +impl<'c, const KEY_SIZE: usize> DesCbc<'c, KEY_SIZE> { + /// Constructs a new AES-CBC cipher for a cryptographic operation. + pub fn new(key: &'c [u8; KEY_SIZE], iv: &'c [u8; 8]) -> Self { + return Self { key: key, iv: iv }; + } +} + +impl<'c, const KEY_SIZE: usize> Cipher<'c> for DesCbc<'c, KEY_SIZE> { + const BLOCK_SIZE: usize = DES_BLOCK_SIZE; + const REQUIRES_PADDING: bool = true; + + fn key(&self) -> &'c [u8] { + self.key + } + + fn iv(&self) -> &'c [u8] { + self.iv + } + + fn set_algomode(&self, p: pac::cryp::Cryp) { + #[cfg(cryp_v1)] + { + p.cr().modify(|w| w.set_algomode(3)); + } + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + { + p.cr().modify(|w| w.set_algomode0(3)); + p.cr().modify(|w| w.set_algomode3(false)); + } + } +} + +impl<'c> CipherSized for DesCbc<'c, { 56 / 8 }> {} +impl<'c, const KEY_SIZE: usize> IVSized for DesCbc<'c, KEY_SIZE> {} + +/// AES-ECB Cipher Mode +pub struct AesEcb<'c, const KEY_SIZE: usize> { + iv: &'c [u8; 0], + key: &'c [u8; KEY_SIZE], +} + +impl<'c, const KEY_SIZE: usize> AesEcb<'c, KEY_SIZE> { + /// Constructs a new AES-ECB cipher for a cryptographic operation. + pub fn new(key: &'c [u8; KEY_SIZE]) -> Self { + return Self { key: key, iv: &[0; 0] }; + } +} + +impl<'c, const KEY_SIZE: usize> Cipher<'c> for AesEcb<'c, KEY_SIZE> { + const BLOCK_SIZE: usize = AES_BLOCK_SIZE; + const REQUIRES_PADDING: bool = true; + + fn key(&self) -> &'c [u8] { + self.key + } + + fn iv(&self) -> &'c [u8] { + self.iv + } + + fn prepare_key(&self, p: pac::cryp::Cryp) { + #[cfg(cryp_v1)] + { + p.cr().modify(|w| w.set_algomode(7)); + } + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + { + p.cr().modify(|w| w.set_algomode0(7)); + p.cr().modify(|w| w.set_algomode3(false)); + } + p.cr().modify(|w| w.set_crypen(true)); + while p.sr().read().busy() {} + } + + fn set_algomode(&self, p: pac::cryp::Cryp) { + #[cfg(cryp_v1)] + { + p.cr().modify(|w| w.set_algomode(2)); + } + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + { + p.cr().modify(|w| w.set_algomode0(2)); + p.cr().modify(|w| w.set_algomode3(false)); + } + } +} + +impl<'c> CipherSized for AesEcb<'c, { 128 / 8 }> {} +impl<'c> CipherSized for AesEcb<'c, { 192 / 8 }> {} +impl<'c> CipherSized for AesEcb<'c, { 256 / 8 }> {} +impl<'c, const KEY_SIZE: usize> IVSized for AesEcb<'c, KEY_SIZE> {} + +/// AES-CBC Cipher Mode +pub struct AesCbc<'c, const KEY_SIZE: usize> { + iv: &'c [u8; 16], + key: &'c [u8; KEY_SIZE], +} + +impl<'c, const KEY_SIZE: usize> AesCbc<'c, KEY_SIZE> { + /// Constructs a new AES-CBC cipher for a cryptographic operation. + pub fn new(key: &'c [u8; KEY_SIZE], iv: &'c [u8; 16]) -> Self { + return Self { key: key, iv: iv }; + } +} + +impl<'c, const KEY_SIZE: usize> Cipher<'c> for AesCbc<'c, KEY_SIZE> { + const BLOCK_SIZE: usize = AES_BLOCK_SIZE; + const REQUIRES_PADDING: bool = true; + + fn key(&self) -> &'c [u8] { + self.key + } + + fn iv(&self) -> &'c [u8] { + self.iv + } + + fn prepare_key(&self, p: pac::cryp::Cryp) { + #[cfg(cryp_v1)] + { + p.cr().modify(|w| w.set_algomode(7)); + } + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + { + p.cr().modify(|w| w.set_algomode0(7)); + p.cr().modify(|w| w.set_algomode3(false)); + } + p.cr().modify(|w| w.set_crypen(true)); + while p.sr().read().busy() {} + } + + fn set_algomode(&self, p: pac::cryp::Cryp) { + #[cfg(cryp_v1)] + { + p.cr().modify(|w| w.set_algomode(5)); + } + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + { + p.cr().modify(|w| w.set_algomode0(5)); + p.cr().modify(|w| w.set_algomode3(false)); + } + } +} + +impl<'c> CipherSized for AesCbc<'c, { 128 / 8 }> {} +impl<'c> CipherSized for AesCbc<'c, { 192 / 8 }> {} +impl<'c> CipherSized for AesCbc<'c, { 256 / 8 }> {} +impl<'c, const KEY_SIZE: usize> IVSized for AesCbc<'c, KEY_SIZE> {} + +/// AES-CTR Cipher Mode +pub struct AesCtr<'c, const KEY_SIZE: usize> { + iv: &'c [u8; 16], + key: &'c [u8; KEY_SIZE], +} + +impl<'c, const KEY_SIZE: usize> AesCtr<'c, KEY_SIZE> { + /// Constructs a new AES-CTR cipher for a cryptographic operation. + pub fn new(key: &'c [u8; KEY_SIZE], iv: &'c [u8; 16]) -> Self { + return Self { key: key, iv: iv }; + } +} + +impl<'c, const KEY_SIZE: usize> Cipher<'c> for AesCtr<'c, KEY_SIZE> { + const BLOCK_SIZE: usize = AES_BLOCK_SIZE; + + fn key(&self) -> &'c [u8] { + self.key + } + + fn iv(&self) -> &'c [u8] { + self.iv + } + + fn set_algomode(&self, p: pac::cryp::Cryp) { + #[cfg(cryp_v1)] + { + p.cr().modify(|w| w.set_algomode(6)); + } + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + { + p.cr().modify(|w| w.set_algomode0(6)); + p.cr().modify(|w| w.set_algomode3(false)); + } + } +} + +impl<'c> CipherSized for AesCtr<'c, { 128 / 8 }> {} +impl<'c> CipherSized for AesCtr<'c, { 192 / 8 }> {} +impl<'c> CipherSized for AesCtr<'c, { 256 / 8 }> {} +impl<'c, const KEY_SIZE: usize> IVSized for AesCtr<'c, KEY_SIZE> {} + +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +///AES-GCM Cipher Mode +pub struct AesGcm<'c, const KEY_SIZE: usize> { + iv: [u8; 16], + key: &'c [u8; KEY_SIZE], +} + +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize> AesGcm<'c, KEY_SIZE> { + /// Constucts a new AES-GCM cipher for a cryptographic operation. + pub fn new(key: &'c [u8; KEY_SIZE], iv: &'c [u8; 12]) -> Self { + let mut new_gcm = Self { key: key, iv: [0; 16] }; + new_gcm.iv[..12].copy_from_slice(iv); + new_gcm.iv[15] = 2; + new_gcm + } +} + +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize> Cipher<'c> for AesGcm<'c, KEY_SIZE> { + const BLOCK_SIZE: usize = AES_BLOCK_SIZE; + + fn key(&self) -> &'c [u8] { + self.key + } + + fn iv(&self) -> &[u8] { + self.iv.as_slice() + } + + fn set_algomode(&self, p: pac::cryp::Cryp) { + p.cr().modify(|w| w.set_algomode0(0)); + p.cr().modify(|w| w.set_algomode3(true)); + } + + fn init_phase_blocking(&self, p: pac::cryp::Cryp, _cryp: &Cryp) { + p.cr().modify(|w| w.set_gcm_ccmph(0)); + p.cr().modify(|w| w.set_crypen(true)); + while p.cr().read().crypen() {} + } + + async fn init_phase(&self, p: pac::cryp::Cryp, _cryp: &mut Cryp<'_, T, DmaIn, DmaOut>) { + p.cr().modify(|w| w.set_gcm_ccmph(0)); + p.cr().modify(|w| w.set_crypen(true)); + while p.cr().read().crypen() {} + } + + #[cfg(cryp_v2)] + fn pre_final(&self, p: pac::cryp::Cryp, dir: Direction, _padding_len: usize) -> [u32; 4] { + //Handle special GCM partial block process. + if dir == Direction::Encrypt { + p.cr().modify(|w| w.set_crypen(false)); + p.cr().modify(|w| w.set_algomode3(false)); + p.cr().modify(|w| w.set_algomode0(6)); + let iv1r = p.csgcmccmr(7).read() - 1; + p.init(1).ivrr().write_value(iv1r); + p.cr().modify(|w| w.set_crypen(true)); + } + [0; 4] + } + + #[cfg(any(cryp_v3, cryp_v4))] + fn pre_final(&self, p: pac::cryp::Cryp, _dir: Direction, padding_len: usize) -> [u32; 4] { + //Handle special GCM partial block process. + p.cr().modify(|w| w.set_npblb(padding_len as u8)); + [0; 4] + } + + #[cfg(cryp_v2)] + fn post_final_blocking( + &self, + p: pac::cryp::Cryp, + cryp: &Cryp, + dir: Direction, + int_data: &mut [u8; AES_BLOCK_SIZE], + _temp1: [u32; 4], + padding_mask: [u8; AES_BLOCK_SIZE], + ) { + if dir == Direction::Encrypt { + //Handle special GCM partial block process. + p.cr().modify(|w| w.set_crypen(false)); + p.cr().modify(|w| w.set_algomode3(true)); + p.cr().modify(|w| w.set_algomode0(0)); + for i in 0..AES_BLOCK_SIZE { + int_data[i] = int_data[i] & padding_mask[i]; + } + p.cr().modify(|w| w.set_crypen(true)); + p.cr().modify(|w| w.set_gcm_ccmph(3)); + + cryp.write_bytes_blocking(Self::BLOCK_SIZE, int_data); + cryp.read_bytes_blocking(Self::BLOCK_SIZE, int_data); + } + } + + #[cfg(cryp_v2)] + async fn post_final( + &self, + p: pac::cryp::Cryp, + cryp: &mut Cryp<'_, T, DmaIn, DmaOut>, + dir: Direction, + int_data: &mut [u8; AES_BLOCK_SIZE], + _temp1: [u32; 4], + padding_mask: [u8; AES_BLOCK_SIZE], + ) where + DmaIn: crate::cryp::DmaIn, + DmaOut: crate::cryp::DmaOut, + { + if dir == Direction::Encrypt { + // Handle special GCM partial block process. + p.cr().modify(|w| w.set_crypen(false)); + p.cr().modify(|w| w.set_algomode3(true)); + p.cr().modify(|w| w.set_algomode0(0)); + for i in 0..AES_BLOCK_SIZE { + int_data[i] = int_data[i] & padding_mask[i]; + } + p.cr().modify(|w| w.set_crypen(true)); + p.cr().modify(|w| w.set_gcm_ccmph(3)); + + let mut out_data: [u8; AES_BLOCK_SIZE] = [0; AES_BLOCK_SIZE]; + + let read = Cryp::::read_bytes(&mut cryp.outdma, Self::BLOCK_SIZE, &mut out_data); + let write = Cryp::::write_bytes(&mut cryp.indma, Self::BLOCK_SIZE, int_data); + + embassy_futures::join::join(read, write).await; + + int_data.copy_from_slice(&out_data); + } + } +} + +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c> CipherSized for AesGcm<'c, { 128 / 8 }> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c> CipherSized for AesGcm<'c, { 192 / 8 }> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c> CipherSized for AesGcm<'c, { 256 / 8 }> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize> CipherAuthenticated<16> for AesGcm<'c, KEY_SIZE> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize> IVSized for AesGcm<'c, KEY_SIZE> {} + +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +/// AES-GMAC Cipher Mode +pub struct AesGmac<'c, const KEY_SIZE: usize> { + iv: [u8; 16], + key: &'c [u8; KEY_SIZE], +} + +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize> AesGmac<'c, KEY_SIZE> { + /// Constructs a new AES-GMAC cipher for a cryptographic operation. + pub fn new(key: &'c [u8; KEY_SIZE], iv: &'c [u8; 12]) -> Self { + let mut new_gmac = Self { key: key, iv: [0; 16] }; + new_gmac.iv[..12].copy_from_slice(iv); + new_gmac.iv[15] = 2; + new_gmac + } +} + +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize> Cipher<'c> for AesGmac<'c, KEY_SIZE> { + const BLOCK_SIZE: usize = AES_BLOCK_SIZE; + + fn key(&self) -> &'c [u8] { + self.key + } + + fn iv(&self) -> &[u8] { + self.iv.as_slice() + } + + fn set_algomode(&self, p: pac::cryp::Cryp) { + p.cr().modify(|w| w.set_algomode0(0)); + p.cr().modify(|w| w.set_algomode3(true)); + } + + fn init_phase_blocking(&self, p: pac::cryp::Cryp, _cryp: &Cryp) { + p.cr().modify(|w| w.set_gcm_ccmph(0)); + p.cr().modify(|w| w.set_crypen(true)); + while p.cr().read().crypen() {} + } + + async fn init_phase(&self, p: pac::cryp::Cryp, _cryp: &mut Cryp<'_, T, DmaIn, DmaOut>) { + p.cr().modify(|w| w.set_gcm_ccmph(0)); + p.cr().modify(|w| w.set_crypen(true)); + while p.cr().read().crypen() {} + } + + #[cfg(cryp_v2)] + fn pre_final(&self, p: pac::cryp::Cryp, dir: Direction, _padding_len: usize) -> [u32; 4] { + //Handle special GCM partial block process. + if dir == Direction::Encrypt { + p.cr().modify(|w| w.set_crypen(false)); + p.cr().modify(|w| w.set_algomode3(false)); + p.cr().modify(|w| w.set_algomode0(6)); + let iv1r = p.csgcmccmr(7).read() - 1; + p.init(1).ivrr().write_value(iv1r); + p.cr().modify(|w| w.set_crypen(true)); + } + [0; 4] + } + + #[cfg(any(cryp_v3, cryp_v4))] + fn pre_final(&self, p: pac::cryp::Cryp, _dir: Direction, padding_len: usize) -> [u32; 4] { + //Handle special GCM partial block process. + p.cr().modify(|w| w.set_npblb(padding_len as u8)); + [0; 4] + } + + #[cfg(cryp_v2)] + fn post_final_blocking( + &self, + p: pac::cryp::Cryp, + cryp: &Cryp, + dir: Direction, + int_data: &mut [u8; AES_BLOCK_SIZE], + _temp1: [u32; 4], + padding_mask: [u8; AES_BLOCK_SIZE], + ) { + if dir == Direction::Encrypt { + //Handle special GCM partial block process. + p.cr().modify(|w| w.set_crypen(false)); + p.cr().modify(|w| w.set_algomode3(true)); + p.cr().modify(|w| w.set_algomode0(0)); + for i in 0..AES_BLOCK_SIZE { + int_data[i] = int_data[i] & padding_mask[i]; + } + p.cr().modify(|w| w.set_crypen(true)); + p.cr().modify(|w| w.set_gcm_ccmph(3)); + + cryp.write_bytes_blocking(Self::BLOCK_SIZE, int_data); + cryp.read_bytes_blocking(Self::BLOCK_SIZE, int_data); + } + } + + #[cfg(cryp_v2)] + async fn post_final( + &self, + p: pac::cryp::Cryp, + cryp: &mut Cryp<'_, T, DmaIn, DmaOut>, + dir: Direction, + int_data: &mut [u8; AES_BLOCK_SIZE], + _temp1: [u32; 4], + padding_mask: [u8; AES_BLOCK_SIZE], + ) where + DmaIn: crate::cryp::DmaIn, + DmaOut: crate::cryp::DmaOut, + { + if dir == Direction::Encrypt { + // Handle special GCM partial block process. + p.cr().modify(|w| w.set_crypen(false)); + p.cr().modify(|w| w.set_algomode3(true)); + p.cr().modify(|w| w.set_algomode0(0)); + for i in 0..AES_BLOCK_SIZE { + int_data[i] = int_data[i] & padding_mask[i]; + } + p.cr().modify(|w| w.set_crypen(true)); + p.cr().modify(|w| w.set_gcm_ccmph(3)); + + let mut out_data: [u8; AES_BLOCK_SIZE] = [0; AES_BLOCK_SIZE]; + + let read = Cryp::::read_bytes(&mut cryp.outdma, Self::BLOCK_SIZE, &mut out_data); + let write = Cryp::::write_bytes(&mut cryp.indma, Self::BLOCK_SIZE, int_data); + + embassy_futures::join::join(read, write).await; + } + } +} + +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c> CipherSized for AesGmac<'c, { 128 / 8 }> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c> CipherSized for AesGmac<'c, { 192 / 8 }> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c> CipherSized for AesGmac<'c, { 256 / 8 }> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize> CipherAuthenticated<16> for AesGmac<'c, KEY_SIZE> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize> IVSized for AesGmac<'c, KEY_SIZE> {} + +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +/// AES-CCM Cipher Mode +pub struct AesCcm<'c, const KEY_SIZE: usize, const TAG_SIZE: usize, const IV_SIZE: usize> { + key: &'c [u8; KEY_SIZE], + aad_header: [u8; 6], + aad_header_len: usize, + block0: [u8; 16], + ctr: [u8; 16], +} + +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize, const IV_SIZE: usize> AesCcm<'c, KEY_SIZE, TAG_SIZE, IV_SIZE> { + /// Constructs a new AES-CCM cipher for a cryptographic operation. + pub fn new(key: &'c [u8; KEY_SIZE], iv: &'c [u8; IV_SIZE], aad_len: usize, payload_len: usize) -> Self { + let mut aad_header: [u8; 6] = [0; 6]; + let mut aad_header_len = 0; + let mut block0: [u8; 16] = [0; 16]; + if aad_len != 0 { + if aad_len < 65280 { + aad_header[0] = (aad_len >> 8) as u8 & 0xFF; + aad_header[1] = aad_len as u8 & 0xFF; + aad_header_len = 2; + } else { + aad_header[0] = 0xFF; + aad_header[1] = 0xFE; + let aad_len_bytes: [u8; 4] = (aad_len as u32).to_be_bytes(); + aad_header[2] = aad_len_bytes[0]; + aad_header[3] = aad_len_bytes[1]; + aad_header[4] = aad_len_bytes[2]; + aad_header[5] = aad_len_bytes[3]; + aad_header_len = 6; + } + } + let total_aad_len = aad_header_len + aad_len; + let mut aad_padding_len = 16 - (total_aad_len % 16); + if aad_padding_len == 16 { + aad_padding_len = 0; + } + aad_header_len += aad_padding_len; + let total_aad_len_padded = aad_header_len + aad_len; + if total_aad_len_padded > 0 { + block0[0] = 0x40; + } + block0[0] |= ((((TAG_SIZE as u8) - 2) >> 1) & 0x07) << 3; + block0[0] |= ((15 - (iv.len() as u8)) - 1) & 0x07; + block0[1..1 + iv.len()].copy_from_slice(iv); + let payload_len_bytes: [u8; 4] = (payload_len as u32).to_be_bytes(); + if iv.len() <= 11 { + block0[12] = payload_len_bytes[0]; + } else if payload_len_bytes[0] > 0 { + panic!("Message is too large for given IV size."); + } + if iv.len() <= 12 { + block0[13] = payload_len_bytes[1]; + } else if payload_len_bytes[1] > 0 { + panic!("Message is too large for given IV size."); + } + block0[14] = payload_len_bytes[2]; + block0[15] = payload_len_bytes[3]; + let mut ctr: [u8; 16] = [0; 16]; + ctr[0] = block0[0] & 0x07; + ctr[1..1 + iv.len()].copy_from_slice(&block0[1..1 + iv.len()]); + ctr[15] = 0x01; + + return Self { + key: key, + aad_header: aad_header, + aad_header_len: aad_header_len, + block0: block0, + ctr: ctr, + }; + } +} + +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize, const IV_SIZE: usize> Cipher<'c> + for AesCcm<'c, KEY_SIZE, TAG_SIZE, IV_SIZE> +{ + const BLOCK_SIZE: usize = AES_BLOCK_SIZE; + + fn key(&self) -> &'c [u8] { + self.key + } + + fn iv(&self) -> &[u8] { + self.ctr.as_slice() + } + + fn set_algomode(&self, p: pac::cryp::Cryp) { + p.cr().modify(|w| w.set_algomode0(1)); + p.cr().modify(|w| w.set_algomode3(true)); + } + + fn init_phase_blocking(&self, p: pac::cryp::Cryp, cryp: &Cryp) { + p.cr().modify(|w| w.set_gcm_ccmph(0)); + + cryp.write_bytes_blocking(Self::BLOCK_SIZE, &self.block0); + + p.cr().modify(|w| w.set_crypen(true)); + while p.cr().read().crypen() {} + } + + async fn init_phase(&self, p: pac::cryp::Cryp, cryp: &mut Cryp<'_, T, DmaIn, DmaOut>) + where + DmaIn: crate::cryp::DmaIn, + DmaOut: crate::cryp::DmaOut, + { + p.cr().modify(|w| w.set_gcm_ccmph(0)); + + Cryp::::write_bytes(&mut cryp.indma, Self::BLOCK_SIZE, &self.block0).await; + + p.cr().modify(|w| w.set_crypen(true)); + while p.cr().read().crypen() {} + } + + fn get_header_block(&self) -> &[u8] { + return &self.aad_header[0..self.aad_header_len]; + } + + #[cfg(cryp_v2)] + fn pre_final(&self, p: pac::cryp::Cryp, dir: Direction, _padding_len: usize) -> [u32; 4] { + //Handle special CCM partial block process. + let mut temp1 = [0; 4]; + if dir == Direction::Decrypt { + p.cr().modify(|w| w.set_crypen(false)); + let iv1temp = p.init(1).ivrr().read(); + temp1[0] = p.csgcmccmr(0).read().swap_bytes(); + temp1[1] = p.csgcmccmr(1).read().swap_bytes(); + temp1[2] = p.csgcmccmr(2).read().swap_bytes(); + temp1[3] = p.csgcmccmr(3).read().swap_bytes(); + p.init(1).ivrr().write_value(iv1temp); + p.cr().modify(|w| w.set_algomode3(false)); + p.cr().modify(|w| w.set_algomode0(6)); + p.cr().modify(|w| w.set_crypen(true)); + } + return temp1; + } + + #[cfg(any(cryp_v3, cryp_v4))] + fn pre_final(&self, p: pac::cryp::Cryp, _dir: Direction, padding_len: usize) -> [u32; 4] { + //Handle special GCM partial block process. + p.cr().modify(|w| w.set_npblb(padding_len as u8)); + [0; 4] + } + + #[cfg(cryp_v2)] + fn post_final_blocking( + &self, + p: pac::cryp::Cryp, + cryp: &Cryp, + dir: Direction, + int_data: &mut [u8; AES_BLOCK_SIZE], + temp1: [u32; 4], + padding_mask: [u8; 16], + ) { + if dir == Direction::Decrypt { + //Handle special CCM partial block process. + let mut temp2 = [0; 4]; + temp2[0] = p.csgcmccmr(0).read().swap_bytes(); + temp2[1] = p.csgcmccmr(1).read().swap_bytes(); + temp2[2] = p.csgcmccmr(2).read().swap_bytes(); + temp2[3] = p.csgcmccmr(3).read().swap_bytes(); + p.cr().modify(|w| w.set_algomode3(true)); + p.cr().modify(|w| w.set_algomode0(1)); + p.cr().modify(|w| w.set_gcm_ccmph(3)); + // Header phase + p.cr().modify(|w| w.set_gcm_ccmph(1)); + for i in 0..AES_BLOCK_SIZE { + int_data[i] = int_data[i] & padding_mask[i]; + } + let mut in_data: [u32; 4] = [0; 4]; + for i in 0..in_data.len() { + let mut int_bytes: [u8; 4] = [0; 4]; + int_bytes.copy_from_slice(&int_data[(i * 4)..(i * 4) + 4]); + let int_word = u32::from_le_bytes(int_bytes); + in_data[i] = int_word; + in_data[i] = in_data[i] ^ temp1[i] ^ temp2[i]; + } + cryp.write_words_blocking(Self::BLOCK_SIZE, &in_data); + } + } + + #[cfg(cryp_v2)] + async fn post_final( + &self, + p: pac::cryp::Cryp, + cryp: &mut Cryp<'_, T, DmaIn, DmaOut>, + dir: Direction, + int_data: &mut [u8; AES_BLOCK_SIZE], + temp1: [u32; 4], + padding_mask: [u8; 16], + ) where + DmaIn: crate::cryp::DmaIn, + DmaOut: crate::cryp::DmaOut, + { + if dir == Direction::Decrypt { + //Handle special CCM partial block process. + let mut temp2 = [0; 4]; + temp2[0] = p.csgcmccmr(0).read().swap_bytes(); + temp2[1] = p.csgcmccmr(1).read().swap_bytes(); + temp2[2] = p.csgcmccmr(2).read().swap_bytes(); + temp2[3] = p.csgcmccmr(3).read().swap_bytes(); + p.cr().modify(|w| w.set_algomode3(true)); + p.cr().modify(|w| w.set_algomode0(1)); + p.cr().modify(|w| w.set_gcm_ccmph(3)); + // Header phase + p.cr().modify(|w| w.set_gcm_ccmph(1)); + for i in 0..AES_BLOCK_SIZE { + int_data[i] = int_data[i] & padding_mask[i]; + } + let mut in_data: [u32; 4] = [0; 4]; + for i in 0..in_data.len() { + let mut int_bytes: [u8; 4] = [0; 4]; + int_bytes.copy_from_slice(&int_data[(i * 4)..(i * 4) + 4]); + let int_word = u32::from_le_bytes(int_bytes); + in_data[i] = int_word; + in_data[i] = in_data[i] ^ temp1[i] ^ temp2[i]; + } + Cryp::::write_words(&mut cryp.indma, Self::BLOCK_SIZE, &in_data).await; + } + } +} + +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const TAG_SIZE: usize, const IV_SIZE: usize> CipherSized for AesCcm<'c, { 128 / 8 }, TAG_SIZE, IV_SIZE> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const TAG_SIZE: usize, const IV_SIZE: usize> CipherSized for AesCcm<'c, { 192 / 8 }, TAG_SIZE, IV_SIZE> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const TAG_SIZE: usize, const IV_SIZE: usize> CipherSized for AesCcm<'c, { 256 / 8 }, TAG_SIZE, IV_SIZE> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const IV_SIZE: usize> CipherAuthenticated<4> for AesCcm<'c, KEY_SIZE, 4, IV_SIZE> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const IV_SIZE: usize> CipherAuthenticated<6> for AesCcm<'c, KEY_SIZE, 6, IV_SIZE> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const IV_SIZE: usize> CipherAuthenticated<8> for AesCcm<'c, KEY_SIZE, 8, IV_SIZE> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const IV_SIZE: usize> CipherAuthenticated<10> for AesCcm<'c, KEY_SIZE, 10, IV_SIZE> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const IV_SIZE: usize> CipherAuthenticated<12> for AesCcm<'c, KEY_SIZE, 12, IV_SIZE> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const IV_SIZE: usize> CipherAuthenticated<14> for AesCcm<'c, KEY_SIZE, 14, IV_SIZE> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const IV_SIZE: usize> CipherAuthenticated<16> for AesCcm<'c, KEY_SIZE, 16, IV_SIZE> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize> IVSized for AesCcm<'c, KEY_SIZE, TAG_SIZE, 7> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize> IVSized for AesCcm<'c, KEY_SIZE, TAG_SIZE, 8> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize> IVSized for AesCcm<'c, KEY_SIZE, TAG_SIZE, 9> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize> IVSized for AesCcm<'c, KEY_SIZE, TAG_SIZE, 10> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize> IVSized for AesCcm<'c, KEY_SIZE, TAG_SIZE, 11> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize> IVSized for AesCcm<'c, KEY_SIZE, TAG_SIZE, 12> {} +#[cfg(any(cryp_v2, cryp_v3, cryp_v4))] +impl<'c, const KEY_SIZE: usize, const TAG_SIZE: usize> IVSized for AesCcm<'c, KEY_SIZE, TAG_SIZE, 13> {} + +#[allow(dead_code)] +/// Holds the state information for a cipher operation. +/// Allows suspending/resuming of cipher operations. +pub struct Context<'c, C: Cipher<'c> + CipherSized> { + phantom_data: PhantomData<&'c C>, + cipher: &'c C, + dir: Direction, + last_block_processed: bool, + header_processed: bool, + aad_complete: bool, + cr: u32, + iv: [u32; 4], + csgcmccm: [u32; 8], + csgcm: [u32; 8], + header_len: u64, + payload_len: u64, + aad_buffer: [u8; 16], + aad_buffer_len: usize, +} + +/// Selects whether the crypto processor operates in encryption or decryption mode. +#[derive(PartialEq, Clone, Copy)] +pub enum Direction { + /// Encryption mode + Encrypt, + /// Decryption mode + Decrypt, +} + +/// Crypto Accelerator Driver +pub struct Cryp<'d, T: Instance, DmaIn = NoDma, DmaOut = NoDma> { + _peripheral: PeripheralRef<'d, T>, + indma: PeripheralRef<'d, DmaIn>, + outdma: PeripheralRef<'d, DmaOut>, +} + +impl<'d, T: Instance, DmaIn, DmaOut> Cryp<'d, T, DmaIn, DmaOut> { + /// Create a new CRYP driver. + pub fn new( + peri: impl Peripheral

+ 'd, + indma: impl Peripheral

+ 'd, + outdma: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + ) -> Self { + rcc::enable_and_reset::(); + into_ref!(peri, indma, outdma); + let instance = Self { + _peripheral: peri, + indma: indma, + outdma: outdma, + }; + + T::Interrupt::unpend(); + unsafe { T::Interrupt::enable() }; + + instance + } + + /// Start a new encrypt or decrypt operation for the given cipher. + pub fn start_blocking<'c, C: Cipher<'c> + CipherSized + IVSized>( + &self, + cipher: &'c C, + dir: Direction, + ) -> Context<'c, C> { + let mut ctx: Context<'c, C> = Context { + dir, + last_block_processed: false, + cr: 0, + iv: [0; 4], + csgcmccm: [0; 8], + csgcm: [0; 8], + aad_complete: false, + header_len: 0, + payload_len: 0, + cipher: cipher, + phantom_data: PhantomData, + header_processed: false, + aad_buffer: [0; 16], + aad_buffer_len: 0, + }; + + T::regs().cr().modify(|w| w.set_crypen(false)); + + let key = ctx.cipher.key(); + + if key.len() == (128 / 8) { + T::regs().cr().modify(|w| w.set_keysize(0)); + } else if key.len() == (192 / 8) { + T::regs().cr().modify(|w| w.set_keysize(1)); + } else if key.len() == (256 / 8) { + T::regs().cr().modify(|w| w.set_keysize(2)); + } + + self.load_key(key); + + // Set data type to 8-bit. This will match software implementations. + T::regs().cr().modify(|w| w.set_datatype(2)); + + ctx.cipher.prepare_key(T::regs()); + + ctx.cipher.set_algomode(T::regs()); + + // Set encrypt/decrypt + if dir == Direction::Encrypt { + T::regs().cr().modify(|w| w.set_algodir(false)); + } else { + T::regs().cr().modify(|w| w.set_algodir(true)); + } + + // Load the IV into the registers. + let iv = ctx.cipher.iv(); + let mut full_iv: [u8; 16] = [0; 16]; + full_iv[0..iv.len()].copy_from_slice(iv); + let mut iv_idx = 0; + let mut iv_word: [u8; 4] = [0; 4]; + iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]); + iv_idx += 4; + T::regs().init(0).ivlr().write_value(u32::from_be_bytes(iv_word)); + iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]); + iv_idx += 4; + T::regs().init(0).ivrr().write_value(u32::from_be_bytes(iv_word)); + iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]); + iv_idx += 4; + T::regs().init(1).ivlr().write_value(u32::from_be_bytes(iv_word)); + iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]); + T::regs().init(1).ivrr().write_value(u32::from_be_bytes(iv_word)); + + // Flush in/out FIFOs + T::regs().cr().modify(|w| w.fflush()); + + ctx.cipher.init_phase_blocking(T::regs(), self); + + self.store_context(&mut ctx); + + ctx + } + + /// Start a new encrypt or decrypt operation for the given cipher. + pub async fn start<'c, C: Cipher<'c> + CipherSized + IVSized>( + &mut self, + cipher: &'c C, + dir: Direction, + ) -> Context<'c, C> + where + DmaIn: crate::cryp::DmaIn, + DmaOut: crate::cryp::DmaOut, + { + let mut ctx: Context<'c, C> = Context { + dir, + last_block_processed: false, + cr: 0, + iv: [0; 4], + csgcmccm: [0; 8], + csgcm: [0; 8], + aad_complete: false, + header_len: 0, + payload_len: 0, + cipher: cipher, + phantom_data: PhantomData, + header_processed: false, + aad_buffer: [0; 16], + aad_buffer_len: 0, + }; + + T::regs().cr().modify(|w| w.set_crypen(false)); + + let key = ctx.cipher.key(); + + if key.len() == (128 / 8) { + T::regs().cr().modify(|w| w.set_keysize(0)); + } else if key.len() == (192 / 8) { + T::regs().cr().modify(|w| w.set_keysize(1)); + } else if key.len() == (256 / 8) { + T::regs().cr().modify(|w| w.set_keysize(2)); + } + + self.load_key(key); + + // Set data type to 8-bit. This will match software implementations. + T::regs().cr().modify(|w| w.set_datatype(2)); + + ctx.cipher.prepare_key(T::regs()); + + ctx.cipher.set_algomode(T::regs()); + + // Set encrypt/decrypt + if dir == Direction::Encrypt { + T::regs().cr().modify(|w| w.set_algodir(false)); + } else { + T::regs().cr().modify(|w| w.set_algodir(true)); + } + + // Load the IV into the registers. + let iv = ctx.cipher.iv(); + let mut full_iv: [u8; 16] = [0; 16]; + full_iv[0..iv.len()].copy_from_slice(iv); + let mut iv_idx = 0; + let mut iv_word: [u8; 4] = [0; 4]; + iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]); + iv_idx += 4; + T::regs().init(0).ivlr().write_value(u32::from_be_bytes(iv_word)); + iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]); + iv_idx += 4; + T::regs().init(0).ivrr().write_value(u32::from_be_bytes(iv_word)); + iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]); + iv_idx += 4; + T::regs().init(1).ivlr().write_value(u32::from_be_bytes(iv_word)); + iv_word.copy_from_slice(&full_iv[iv_idx..iv_idx + 4]); + T::regs().init(1).ivrr().write_value(u32::from_be_bytes(iv_word)); + + // Flush in/out FIFOs + T::regs().cr().modify(|w| w.fflush()); + + ctx.cipher.init_phase(T::regs(), self).await; + + self.store_context(&mut ctx); + + ctx + } + + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + /// Controls the header phase of cipher processing. + /// This function is only valid for authenticated ciphers including GCM, CCM, and GMAC. + /// All additional associated data (AAD) must be supplied to this function prior to starting the payload phase with `payload_blocking`. + /// The AAD must be supplied in multiples of the block size (128-bits for AES, 64-bits for DES), except when supplying the last block. + /// When supplying the last block of AAD, `last_aad_block` must be `true`. + pub fn aad_blocking< + 'c, + const TAG_SIZE: usize, + C: Cipher<'c> + CipherSized + IVSized + CipherAuthenticated, + >( + &self, + ctx: &mut Context<'c, C>, + aad: &[u8], + last_aad_block: bool, + ) { + self.load_context(ctx); + + // Perform checks for correctness. + if ctx.aad_complete { + panic!("Cannot update AAD after starting payload!") + } + + ctx.header_len += aad.len() as u64; + + // Header phase + T::regs().cr().modify(|w| w.set_crypen(false)); + T::regs().cr().modify(|w| w.set_gcm_ccmph(1)); + T::regs().cr().modify(|w| w.set_crypen(true)); + + // First write the header B1 block if not yet written. + if !ctx.header_processed { + ctx.header_processed = true; + let header = ctx.cipher.get_header_block(); + ctx.aad_buffer[0..header.len()].copy_from_slice(header); + ctx.aad_buffer_len += header.len(); + } + + // Fill the header block to make a full block. + let len_to_copy = min(aad.len(), C::BLOCK_SIZE - ctx.aad_buffer_len); + ctx.aad_buffer[ctx.aad_buffer_len..ctx.aad_buffer_len + len_to_copy].copy_from_slice(&aad[..len_to_copy]); + ctx.aad_buffer_len += len_to_copy; + ctx.aad_buffer[ctx.aad_buffer_len..].fill(0); + let mut aad_len_remaining = aad.len() - len_to_copy; + + if ctx.aad_buffer_len < C::BLOCK_SIZE { + // The buffer isn't full and this is the last buffer, so process it as is (already padded). + if last_aad_block { + self.write_bytes_blocking(C::BLOCK_SIZE, &ctx.aad_buffer); + // Block until input FIFO is empty. + while !T::regs().sr().read().ifem() {} + + // Switch to payload phase. + ctx.aad_complete = true; + T::regs().cr().modify(|w| w.set_crypen(false)); + T::regs().cr().modify(|w| w.set_gcm_ccmph(2)); + T::regs().cr().modify(|w| w.fflush()); + } else { + // Just return because we don't yet have a full block to process. + return; + } + } else { + // Load the full block from the buffer. + self.write_bytes_blocking(C::BLOCK_SIZE, &ctx.aad_buffer); + // Block until input FIFO is empty. + while !T::regs().sr().read().ifem() {} + } + + // Handle a partial block that is passed in. + ctx.aad_buffer_len = 0; + let leftovers = aad_len_remaining % C::BLOCK_SIZE; + ctx.aad_buffer[..leftovers].copy_from_slice(&aad[aad.len() - leftovers..aad.len()]); + ctx.aad_buffer_len += leftovers; + ctx.aad_buffer[ctx.aad_buffer_len..].fill(0); + aad_len_remaining -= leftovers; + assert_eq!(aad_len_remaining % C::BLOCK_SIZE, 0); + + // Load full data blocks into core. + let num_full_blocks = aad_len_remaining / C::BLOCK_SIZE; + let start_index = len_to_copy; + let end_index = start_index + (C::BLOCK_SIZE * num_full_blocks); + self.write_bytes_blocking(C::BLOCK_SIZE, &aad[start_index..end_index]); + + if last_aad_block { + if leftovers > 0 { + self.write_bytes_blocking(C::BLOCK_SIZE, &ctx.aad_buffer); + } + // Switch to payload phase. + ctx.aad_complete = true; + T::regs().cr().modify(|w| w.set_crypen(false)); + T::regs().cr().modify(|w| w.set_gcm_ccmph(2)); + T::regs().cr().modify(|w| w.fflush()); + } + + self.store_context(ctx); + } + + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + /// Controls the header phase of cipher processing. + /// This function is only valid for authenticated ciphers including GCM, CCM, and GMAC. + /// All additional associated data (AAD) must be supplied to this function prior to starting the payload phase with `payload`. + /// The AAD must be supplied in multiples of the block size (128-bits for AES, 64-bits for DES), except when supplying the last block. + /// When supplying the last block of AAD, `last_aad_block` must be `true`. + pub async fn aad<'c, const TAG_SIZE: usize, C: Cipher<'c> + CipherSized + IVSized + CipherAuthenticated>( + &mut self, + ctx: &mut Context<'c, C>, + aad: &[u8], + last_aad_block: bool, + ) where + DmaIn: crate::cryp::DmaIn, + DmaOut: crate::cryp::DmaOut, + { + self.load_context(ctx); + + // Perform checks for correctness. + if ctx.aad_complete { + panic!("Cannot update AAD after starting payload!") + } + + ctx.header_len += aad.len() as u64; + + // Header phase + T::regs().cr().modify(|w| w.set_crypen(false)); + T::regs().cr().modify(|w| w.set_gcm_ccmph(1)); + T::regs().cr().modify(|w| w.set_crypen(true)); + + // First write the header B1 block if not yet written. + if !ctx.header_processed { + ctx.header_processed = true; + let header = ctx.cipher.get_header_block(); + ctx.aad_buffer[0..header.len()].copy_from_slice(header); + ctx.aad_buffer_len += header.len(); + } + + // Fill the header block to make a full block. + let len_to_copy = min(aad.len(), C::BLOCK_SIZE - ctx.aad_buffer_len); + ctx.aad_buffer[ctx.aad_buffer_len..ctx.aad_buffer_len + len_to_copy].copy_from_slice(&aad[..len_to_copy]); + ctx.aad_buffer_len += len_to_copy; + ctx.aad_buffer[ctx.aad_buffer_len..].fill(0); + let mut aad_len_remaining = aad.len() - len_to_copy; + + if ctx.aad_buffer_len < C::BLOCK_SIZE { + // The buffer isn't full and this is the last buffer, so process it as is (already padded). + if last_aad_block { + Self::write_bytes(&mut self.indma, C::BLOCK_SIZE, &ctx.aad_buffer).await; + assert_eq!(T::regs().sr().read().ifem(), true); + + // Switch to payload phase. + ctx.aad_complete = true; + T::regs().cr().modify(|w| w.set_crypen(false)); + T::regs().cr().modify(|w| w.set_gcm_ccmph(2)); + T::regs().cr().modify(|w| w.fflush()); + } else { + // Just return because we don't yet have a full block to process. + return; + } + } else { + // Load the full block from the buffer. + Self::write_bytes(&mut self.indma, C::BLOCK_SIZE, &ctx.aad_buffer).await; + assert_eq!(T::regs().sr().read().ifem(), true); + } + + // Handle a partial block that is passed in. + ctx.aad_buffer_len = 0; + let leftovers = aad_len_remaining % C::BLOCK_SIZE; + ctx.aad_buffer[..leftovers].copy_from_slice(&aad[aad.len() - leftovers..aad.len()]); + ctx.aad_buffer_len += leftovers; + ctx.aad_buffer[ctx.aad_buffer_len..].fill(0); + aad_len_remaining -= leftovers; + assert_eq!(aad_len_remaining % C::BLOCK_SIZE, 0); + + // Load full data blocks into core. + let num_full_blocks = aad_len_remaining / C::BLOCK_SIZE; + let start_index = len_to_copy; + let end_index = start_index + (C::BLOCK_SIZE * num_full_blocks); + Self::write_bytes(&mut self.indma, C::BLOCK_SIZE, &aad[start_index..end_index]).await; + + if last_aad_block { + if leftovers > 0 { + Self::write_bytes(&mut self.indma, C::BLOCK_SIZE, &ctx.aad_buffer).await; + assert_eq!(T::regs().sr().read().ifem(), true); + } + // Switch to payload phase. + ctx.aad_complete = true; + T::regs().cr().modify(|w| w.set_crypen(false)); + T::regs().cr().modify(|w| w.set_gcm_ccmph(2)); + T::regs().cr().modify(|w| w.fflush()); + } + + self.store_context(ctx); + } + + /// Performs encryption/decryption on the provided context. + /// The context determines algorithm, mode, and state of the crypto accelerator. + /// When the last piece of data is supplied, `last_block` should be `true`. + /// This function panics under various mismatches of parameters. + /// Output buffer must be at least as long as the input buffer. + /// Data must be a multiple of block size (128-bits for AES, 64-bits for DES) for CBC and ECB modes. + /// Padding or ciphertext stealing must be managed by the application for these modes. + /// Data must also be a multiple of block size unless `last_block` is `true`. + pub fn payload_blocking<'c, C: Cipher<'c> + CipherSized + IVSized>( + &self, + ctx: &mut Context<'c, C>, + input: &[u8], + output: &mut [u8], + last_block: bool, + ) { + self.load_context(ctx); + + let last_block_remainder = input.len() % C::BLOCK_SIZE; + + // Perform checks for correctness. + if !ctx.aad_complete && ctx.header_len > 0 { + panic!("Additional associated data must be processed first!"); + } else if !ctx.aad_complete { + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + { + ctx.aad_complete = true; + T::regs().cr().modify(|w| w.set_crypen(false)); + T::regs().cr().modify(|w| w.set_gcm_ccmph(2)); + T::regs().cr().modify(|w| w.fflush()); + T::regs().cr().modify(|w| w.set_crypen(true)); + } + } + if ctx.last_block_processed { + panic!("The last block has already been processed!"); + } + if input.len() > output.len() { + panic!("Output buffer length must match input length."); + } + if !last_block { + if last_block_remainder != 0 { + panic!("Input length must be a multiple of {} bytes.", C::BLOCK_SIZE); + } + } + if C::REQUIRES_PADDING { + if last_block_remainder != 0 { + panic!("Input must be a multiple of {} bytes in ECB and CBC modes. Consider padding or ciphertext stealing.", C::BLOCK_SIZE); + } + } + if last_block { + ctx.last_block_processed = true; + } + + // Load data into core, block by block. + let num_full_blocks = input.len() / C::BLOCK_SIZE; + for block in 0..num_full_blocks { + let index = block * C::BLOCK_SIZE; + // Write block in + self.write_bytes_blocking(C::BLOCK_SIZE, &input[index..index + C::BLOCK_SIZE]); + // Read block out + self.read_bytes_blocking(C::BLOCK_SIZE, &mut output[index..index + C::BLOCK_SIZE]); + } + + // Handle the final block, which is incomplete. + if last_block_remainder > 0 { + let padding_len = C::BLOCK_SIZE - last_block_remainder; + let temp1 = ctx.cipher.pre_final(T::regs(), ctx.dir, padding_len); + + let mut intermediate_data: [u8; AES_BLOCK_SIZE] = [0; AES_BLOCK_SIZE]; + let mut last_block: [u8; AES_BLOCK_SIZE] = [0; AES_BLOCK_SIZE]; + last_block[..last_block_remainder].copy_from_slice(&input[input.len() - last_block_remainder..input.len()]); + self.write_bytes_blocking(C::BLOCK_SIZE, &last_block); + self.read_bytes_blocking(C::BLOCK_SIZE, &mut intermediate_data); + + // Handle the last block depending on mode. + let output_len = output.len(); + output[output_len - last_block_remainder..output_len] + .copy_from_slice(&intermediate_data[0..last_block_remainder]); + + let mut mask: [u8; 16] = [0; 16]; + mask[..last_block_remainder].fill(0xFF); + ctx.cipher + .post_final_blocking(T::regs(), self, ctx.dir, &mut intermediate_data, temp1, mask); + } + + ctx.payload_len += input.len() as u64; + + self.store_context(ctx); + } + + /// Performs encryption/decryption on the provided context. + /// The context determines algorithm, mode, and state of the crypto accelerator. + /// When the last piece of data is supplied, `last_block` should be `true`. + /// This function panics under various mismatches of parameters. + /// Output buffer must be at least as long as the input buffer. + /// Data must be a multiple of block size (128-bits for AES, 64-bits for DES) for CBC and ECB modes. + /// Padding or ciphertext stealing must be managed by the application for these modes. + /// Data must also be a multiple of block size unless `last_block` is `true`. + pub async fn payload<'c, C: Cipher<'c> + CipherSized + IVSized>( + &mut self, + ctx: &mut Context<'c, C>, + input: &[u8], + output: &mut [u8], + last_block: bool, + ) where + DmaIn: crate::cryp::DmaIn, + DmaOut: crate::cryp::DmaOut, + { + self.load_context(ctx); + + let last_block_remainder = input.len() % C::BLOCK_SIZE; + + // Perform checks for correctness. + if !ctx.aad_complete && ctx.header_len > 0 { + panic!("Additional associated data must be processed first!"); + } else if !ctx.aad_complete { + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + { + ctx.aad_complete = true; + T::regs().cr().modify(|w| w.set_crypen(false)); + T::regs().cr().modify(|w| w.set_gcm_ccmph(2)); + T::regs().cr().modify(|w| w.fflush()); + T::regs().cr().modify(|w| w.set_crypen(true)); + } + } + if ctx.last_block_processed { + panic!("The last block has already been processed!"); + } + if input.len() > output.len() { + panic!("Output buffer length must match input length."); + } + if !last_block { + if last_block_remainder != 0 { + panic!("Input length must be a multiple of {} bytes.", C::BLOCK_SIZE); + } + } + if C::REQUIRES_PADDING { + if last_block_remainder != 0 { + panic!("Input must be a multiple of {} bytes in ECB and CBC modes. Consider padding or ciphertext stealing.", C::BLOCK_SIZE); + } + } + if last_block { + ctx.last_block_processed = true; + } + + // Load data into core, block by block. + let num_full_blocks = input.len() / C::BLOCK_SIZE; + for block in 0..num_full_blocks { + let index = block * C::BLOCK_SIZE; + // Read block out + let read = Self::read_bytes( + &mut self.outdma, + C::BLOCK_SIZE, + &mut output[index..index + C::BLOCK_SIZE], + ); + // Write block in + let write = Self::write_bytes(&mut self.indma, C::BLOCK_SIZE, &input[index..index + C::BLOCK_SIZE]); + embassy_futures::join::join(read, write).await; + } + + // Handle the final block, which is incomplete. + if last_block_remainder > 0 { + let padding_len = C::BLOCK_SIZE - last_block_remainder; + let temp1 = ctx.cipher.pre_final(T::regs(), ctx.dir, padding_len); + + let mut intermediate_data: [u8; AES_BLOCK_SIZE] = [0; AES_BLOCK_SIZE]; + let mut last_block: [u8; AES_BLOCK_SIZE] = [0; AES_BLOCK_SIZE]; + last_block[..last_block_remainder].copy_from_slice(&input[input.len() - last_block_remainder..input.len()]); + let read = Self::read_bytes(&mut self.outdma, C::BLOCK_SIZE, &mut intermediate_data); + let write = Self::write_bytes(&mut self.indma, C::BLOCK_SIZE, &last_block); + embassy_futures::join::join(read, write).await; + + // Handle the last block depending on mode. + let output_len = output.len(); + output[output_len - last_block_remainder..output_len] + .copy_from_slice(&intermediate_data[0..last_block_remainder]); + + let mut mask: [u8; 16] = [0; 16]; + mask[..last_block_remainder].fill(0xFF); + ctx.cipher + .post_final(T::regs(), self, ctx.dir, &mut intermediate_data, temp1, mask) + .await; + } + + ctx.payload_len += input.len() as u64; + + self.store_context(ctx); + } + + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + /// Generates an authentication tag for authenticated ciphers including GCM, CCM, and GMAC. + /// Called after the all data has been encrypted/decrypted by `payload`. + pub fn finish_blocking< + 'c, + const TAG_SIZE: usize, + C: Cipher<'c> + CipherSized + IVSized + CipherAuthenticated, + >( + &self, + mut ctx: Context<'c, C>, + ) -> [u8; TAG_SIZE] { + self.load_context(&mut ctx); + + T::regs().cr().modify(|w| w.set_crypen(false)); + T::regs().cr().modify(|w| w.set_gcm_ccmph(3)); + T::regs().cr().modify(|w| w.set_crypen(true)); + + let headerlen1: u32 = ((ctx.header_len * 8) >> 32) as u32; + let headerlen2: u32 = (ctx.header_len * 8) as u32; + let payloadlen1: u32 = ((ctx.payload_len * 8) >> 32) as u32; + let payloadlen2: u32 = (ctx.payload_len * 8) as u32; + + #[cfg(cryp_v2)] + let footer: [u32; 4] = [ + headerlen1.swap_bytes(), + headerlen2.swap_bytes(), + payloadlen1.swap_bytes(), + payloadlen2.swap_bytes(), + ]; + #[cfg(any(cryp_v3, cryp_v4))] + let footer: [u32; 4] = [headerlen1, headerlen2, payloadlen1, payloadlen2]; + + self.write_words_blocking(C::BLOCK_SIZE, &footer); + + while !T::regs().sr().read().ofne() {} + + let mut full_tag: [u8; 16] = [0; 16]; + self.read_bytes_blocking(C::BLOCK_SIZE, &mut full_tag); + let mut tag: [u8; TAG_SIZE] = [0; TAG_SIZE]; + tag.copy_from_slice(&full_tag[0..TAG_SIZE]); + + T::regs().cr().modify(|w| w.set_crypen(false)); + + tag + } + + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + // Generates an authentication tag for authenticated ciphers including GCM, CCM, and GMAC. + /// Called after the all data has been encrypted/decrypted by `payload`. + pub async fn finish< + 'c, + const TAG_SIZE: usize, + C: Cipher<'c> + CipherSized + IVSized + CipherAuthenticated, + >( + &mut self, + mut ctx: Context<'c, C>, + ) -> [u8; TAG_SIZE] + where + DmaIn: crate::cryp::DmaIn, + DmaOut: crate::cryp::DmaOut, + { + self.load_context(&mut ctx); + + T::regs().cr().modify(|w| w.set_crypen(false)); + T::regs().cr().modify(|w| w.set_gcm_ccmph(3)); + T::regs().cr().modify(|w| w.set_crypen(true)); + + let headerlen1: u32 = ((ctx.header_len * 8) >> 32) as u32; + let headerlen2: u32 = (ctx.header_len * 8) as u32; + let payloadlen1: u32 = ((ctx.payload_len * 8) >> 32) as u32; + let payloadlen2: u32 = (ctx.payload_len * 8) as u32; + + #[cfg(cryp_v2)] + let footer: [u32; 4] = [ + headerlen1.swap_bytes(), + headerlen2.swap_bytes(), + payloadlen1.swap_bytes(), + payloadlen2.swap_bytes(), + ]; + #[cfg(any(cryp_v3, cryp_v4))] + let footer: [u32; 4] = [headerlen1, headerlen2, payloadlen1, payloadlen2]; + + let write = Self::write_words(&mut self.indma, C::BLOCK_SIZE, &footer); + + let mut full_tag: [u8; 16] = [0; 16]; + let read = Self::read_bytes(&mut self.outdma, C::BLOCK_SIZE, &mut full_tag); + + embassy_futures::join::join(read, write).await; + + let mut tag: [u8; TAG_SIZE] = [0; TAG_SIZE]; + tag.copy_from_slice(&full_tag[0..TAG_SIZE]); + + T::regs().cr().modify(|w| w.set_crypen(false)); + + tag + } + + fn load_key(&self, key: &[u8]) { + // Load the key into the registers. + let mut keyidx = 0; + let mut keyword: [u8; 4] = [0; 4]; + let keylen = key.len() * 8; + if keylen > 192 { + keyword.copy_from_slice(&key[keyidx..keyidx + 4]); + keyidx += 4; + T::regs().key(0).klr().write_value(u32::from_be_bytes(keyword)); + keyword.copy_from_slice(&key[keyidx..keyidx + 4]); + keyidx += 4; + T::regs().key(0).krr().write_value(u32::from_be_bytes(keyword)); + } + if keylen > 128 { + keyword.copy_from_slice(&key[keyidx..keyidx + 4]); + keyidx += 4; + T::regs().key(1).klr().write_value(u32::from_be_bytes(keyword)); + keyword.copy_from_slice(&key[keyidx..keyidx + 4]); + keyidx += 4; + T::regs().key(1).krr().write_value(u32::from_be_bytes(keyword)); + } + if keylen > 64 { + keyword.copy_from_slice(&key[keyidx..keyidx + 4]); + keyidx += 4; + T::regs().key(2).klr().write_value(u32::from_be_bytes(keyword)); + keyword.copy_from_slice(&key[keyidx..keyidx + 4]); + keyidx += 4; + T::regs().key(2).krr().write_value(u32::from_be_bytes(keyword)); + } + keyword.copy_from_slice(&key[keyidx..keyidx + 4]); + keyidx += 4; + T::regs().key(3).klr().write_value(u32::from_be_bytes(keyword)); + keyword = [0; 4]; + keyword[0..key.len() - keyidx].copy_from_slice(&key[keyidx..key.len()]); + T::regs().key(3).krr().write_value(u32::from_be_bytes(keyword)); + } + + fn store_context<'c, C: Cipher<'c> + CipherSized>(&self, ctx: &mut Context<'c, C>) { + // Wait for data block processing to finish. + while !T::regs().sr().read().ifem() {} + while T::regs().sr().read().ofne() {} + while T::regs().sr().read().busy() {} + + // Disable crypto processor. + T::regs().cr().modify(|w| w.set_crypen(false)); + + // Save the peripheral state. + ctx.cr = T::regs().cr().read().0; + ctx.iv[0] = T::regs().init(0).ivlr().read(); + ctx.iv[1] = T::regs().init(0).ivrr().read(); + ctx.iv[2] = T::regs().init(1).ivlr().read(); + ctx.iv[3] = T::regs().init(1).ivrr().read(); + + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + for i in 0..8 { + ctx.csgcmccm[i] = T::regs().csgcmccmr(i).read(); + ctx.csgcm[i] = T::regs().csgcmr(i).read(); + } + } + + fn load_context<'c, C: Cipher<'c> + CipherSized>(&self, ctx: &Context<'c, C>) { + // Reload state registers. + T::regs().cr().write(|w| w.0 = ctx.cr); + T::regs().init(0).ivlr().write_value(ctx.iv[0]); + T::regs().init(0).ivrr().write_value(ctx.iv[1]); + T::regs().init(1).ivlr().write_value(ctx.iv[2]); + T::regs().init(1).ivrr().write_value(ctx.iv[3]); + + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + for i in 0..8 { + T::regs().csgcmccmr(i).write_value(ctx.csgcmccm[i]); + T::regs().csgcmr(i).write_value(ctx.csgcm[i]); + } + self.load_key(ctx.cipher.key()); + + // Prepare key if applicable. + ctx.cipher.prepare_key(T::regs()); + T::regs().cr().write(|w| w.0 = ctx.cr); + + // Enable crypto processor. + T::regs().cr().modify(|w| w.set_crypen(true)); + } + + fn write_bytes_blocking(&self, block_size: usize, blocks: &[u8]) { + // Ensure input is a multiple of block size. + assert_eq!(blocks.len() % block_size, 0); + let mut index = 0; + let end_index = blocks.len(); + while index < end_index { + let mut in_word: [u8; 4] = [0; 4]; + in_word.copy_from_slice(&blocks[index..index + 4]); + T::regs().din().write_value(u32::from_ne_bytes(in_word)); + index += 4; + if index % block_size == 0 { + // Block until input FIFO is empty. + while !T::regs().sr().read().ifem() {} + } + } + } + + async fn write_bytes(dma: &mut PeripheralRef<'_, DmaIn>, block_size: usize, blocks: &[u8]) + where + DmaIn: crate::cryp::DmaIn, + { + if blocks.len() == 0 { + return; + } + // Ensure input is a multiple of block size. + assert_eq!(blocks.len() % block_size, 0); + // Configure DMA to transfer input to crypto core. + let dma_request = dma.request(); + let dst_ptr = T::regs().din().as_ptr(); + let num_words = blocks.len() / 4; + let src_ptr = ptr::slice_from_raw_parts(blocks.as_ptr().cast(), num_words); + let options = TransferOptions { + #[cfg(not(gpdma))] + priority: crate::dma::Priority::High, + ..Default::default() + }; + let dma_transfer = unsafe { Transfer::new_write_raw(dma, dma_request, src_ptr, dst_ptr, options) }; + T::regs().dmacr().modify(|w| w.set_dien(true)); + // Wait for the transfer to complete. + dma_transfer.await; + } + + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + fn write_words_blocking(&self, block_size: usize, blocks: &[u32]) { + assert_eq!((blocks.len() * 4) % block_size, 0); + let mut byte_counter: usize = 0; + for word in blocks { + T::regs().din().write_value(*word); + byte_counter += 4; + if byte_counter % block_size == 0 { + // Block until input FIFO is empty. + while !T::regs().sr().read().ifem() {} + } + } + } + + #[cfg(any(cryp_v2, cryp_v3, cryp_v4))] + async fn write_words(dma: &mut PeripheralRef<'_, DmaIn>, block_size: usize, blocks: &[u32]) + where + DmaIn: crate::cryp::DmaIn, + { + if blocks.len() == 0 { + return; + } + // Ensure input is a multiple of block size. + assert_eq!((blocks.len() * 4) % block_size, 0); + // Configure DMA to transfer input to crypto core. + let dma_request = dma.request(); + let dst_ptr = T::regs().din().as_ptr(); + let num_words = blocks.len(); + let src_ptr = ptr::slice_from_raw_parts(blocks.as_ptr().cast(), num_words); + let options = TransferOptions { + #[cfg(not(gpdma))] + priority: crate::dma::Priority::High, + ..Default::default() + }; + let dma_transfer = unsafe { Transfer::new_write_raw(dma, dma_request, src_ptr, dst_ptr, options) }; + T::regs().dmacr().modify(|w| w.set_dien(true)); + // Wait for the transfer to complete. + dma_transfer.await; + } + + fn read_bytes_blocking(&self, block_size: usize, blocks: &mut [u8]) { + // Block until there is output to read. + while !T::regs().sr().read().ofne() {} + // Ensure input is a multiple of block size. + assert_eq!(blocks.len() % block_size, 0); + // Read block out + let mut index = 0; + let end_index = blocks.len(); + while index < end_index { + let out_word: u32 = T::regs().dout().read(); + blocks[index..index + 4].copy_from_slice(u32::to_ne_bytes(out_word).as_slice()); + index += 4; + } + } + + async fn read_bytes(dma: &mut PeripheralRef<'_, DmaOut>, block_size: usize, blocks: &mut [u8]) + where + DmaOut: crate::cryp::DmaOut, + { + if blocks.len() == 0 { + return; + } + // Ensure input is a multiple of block size. + assert_eq!(blocks.len() % block_size, 0); + // Configure DMA to get output from crypto core. + let dma_request = dma.request(); + let src_ptr = T::regs().dout().as_ptr(); + let num_words = blocks.len() / 4; + let dst_ptr = ptr::slice_from_raw_parts_mut(blocks.as_mut_ptr().cast(), num_words); + let options = TransferOptions { + #[cfg(not(gpdma))] + priority: crate::dma::Priority::VeryHigh, + ..Default::default() + }; + let dma_transfer = unsafe { Transfer::new_read_raw(dma, dma_request, src_ptr, dst_ptr, options) }; + T::regs().dmacr().modify(|w| w.set_doen(true)); + // Wait for the transfer to complete. + dma_transfer.await; + } +} + +trait SealedInstance { + fn regs() -> pac::cryp::Cryp; +} + +/// CRYP instance trait. +#[allow(private_bounds)] +pub trait Instance: SealedInstance + Peripheral

+ crate::rcc::RccPeripheral + 'static + Send { + /// Interrupt for this CRYP instance. + type Interrupt: interrupt::typelevel::Interrupt; +} + +foreach_interrupt!( + ($inst:ident, cryp, CRYP, GLOBAL, $irq:ident) => { + impl Instance for peripherals::$inst { + type Interrupt = crate::interrupt::typelevel::$irq; + } + + impl SealedInstance for peripherals::$inst { + fn regs() -> crate::pac::cryp::Cryp { + crate::pac::$inst + } + } + }; +); + +dma_trait!(DmaIn, Instance); +dma_trait!(DmaOut, Instance); diff --git a/embassy-stm32/src/dac/mod.rs b/embassy-stm32/src/dac/mod.rs index 60f9404c2..8bba5ded0 100644 --- a/embassy-stm32/src/dac/mod.rs +++ b/embassy-stm32/src/dac/mod.rs @@ -8,7 +8,7 @@ use embassy_hal_internal::{into_ref, PeripheralRef}; use crate::dma::NoDma; #[cfg(any(dac_v3, dac_v4, dac_v5, dac_v6, dac_v7))] use crate::pac::dac; -use crate::rcc::RccPeripheral; +use crate::rcc::{self, RccPeripheral}; use crate::{peripherals, Peripheral}; mod tsel; @@ -118,7 +118,7 @@ impl<'d, T: Instance, const N: u8, DMA> DacChannel<'d, T, N, DMA> { /// /// If you're not using DMA, pass [`dma::NoDma`] for the `dma` argument. /// - /// The channel is enabled on creation and begins to drive the output pin. + /// The channel is enabled on creation and begin to drive the output pin. /// Note that some methods, such as `set_trigger()` and `set_mode()`, will /// disable the channel; you must re-enable it with `enable()`. /// @@ -127,11 +127,11 @@ impl<'d, T: Instance, const N: u8, DMA> DacChannel<'d, T, N, DMA> { pub fn new( _peri: impl Peripheral

+ 'd, dma: impl Peripheral

+ 'd, - pin: impl Peripheral

+ crate::gpio::sealed::Pin> + 'd, + pin: impl Peripheral

+ crate::gpio::Pin> + 'd, ) -> Self { into_ref!(dma, pin); pin.set_as_analog(); - T::enable_and_reset(); + rcc::enable_and_reset::(); let mut dac = Self { phantom: PhantomData, dma, @@ -157,7 +157,7 @@ impl<'d, T: Instance, const N: u8, DMA> DacChannel<'d, T, N, DMA> { #[cfg(all(any(dac_v3, dac_v4, dac_v5, dac_v6, dac_v7), not(any(stm32h56x, stm32h57x))))] pub fn new_internal(_peri: impl Peripheral

+ 'd, dma: impl Peripheral

+ 'd) -> Self { into_ref!(dma); - T::enable_and_reset(); + rcc::enable_and_reset::(); let mut dac = Self { phantom: PhantomData, dma, @@ -356,7 +356,7 @@ impl_dma_methods!(2, DacDma2); impl<'d, T: Instance, const N: u8, DMA> Drop for DacChannel<'d, T, N, DMA> { fn drop(&mut self) { - T::disable(); + rcc::disable::(); } } @@ -368,7 +368,7 @@ impl<'d, T: Instance, const N: u8, DMA> Drop for DacChannel<'d, T, N, DMA> { /// /// ```ignore /// // Pins may need to be changed for your specific device. -/// let (dac_ch1, dac_ch2) = embassy_stm32::dac::Dac::new(p.DAC, NoDma, NoDma, p.PA4, p.PA5).split(); +/// let (dac_ch1, dac_ch2) = embassy_stm32::dac::Dac::new(p.DAC1, NoDma, NoDma, p.PA4, p.PA5).split(); /// ``` pub struct Dac<'d, T: Instance, DMACh1 = NoDma, DMACh2 = NoDma> { ch1: DacChannel<'d, T, 1, DMACh1>, @@ -382,7 +382,7 @@ impl<'d, T: Instance, DMACh1, DMACh2> Dac<'d, T, DMACh1, DMACh2> { /// call `split()` to obtain separate `DacChannel`s, or use methods on `Dac` to use /// the two channels together. /// - /// The channels are enabled on creation and begins to drive their output pins. + /// The channels are enabled on creation and begin to drive their output pins. /// Note that some methods, such as `set_trigger()` and `set_mode()`, will /// disable the channel; you must re-enable them with `enable()`. /// @@ -392,25 +392,34 @@ impl<'d, T: Instance, DMACh1, DMACh2> Dac<'d, T, DMACh1, DMACh2> { _peri: impl Peripheral

+ 'd, dma_ch1: impl Peripheral

+ 'd, dma_ch2: impl Peripheral

+ 'd, - pin_ch1: impl Peripheral

+ crate::gpio::sealed::Pin> + 'd, - pin_ch2: impl Peripheral

+ crate::gpio::sealed::Pin> + 'd, + pin_ch1: impl Peripheral

+ crate::gpio::Pin> + 'd, + pin_ch2: impl Peripheral

+ crate::gpio::Pin> + 'd, ) -> Self { into_ref!(dma_ch1, dma_ch2, pin_ch1, pin_ch2); pin_ch1.set_as_analog(); pin_ch2.set_as_analog(); + // Enable twice to increment the DAC refcount for each channel. - T::enable_and_reset(); - T::enable_and_reset(); - Self { - ch1: DacCh1 { - phantom: PhantomData, - dma: dma_ch1, - }, - ch2: DacCh2 { - phantom: PhantomData, - dma: dma_ch2, - }, - } + rcc::enable_and_reset::(); + rcc::enable_and_reset::(); + + let mut ch1 = DacCh1 { + phantom: PhantomData, + dma: dma_ch1, + }; + #[cfg(any(dac_v5, dac_v6, dac_v7))] + ch1.set_hfsel(); + ch1.enable(); + + let mut ch2 = DacCh2 { + phantom: PhantomData, + dma: dma_ch2, + }; + #[cfg(any(dac_v5, dac_v6, dac_v7))] + ch2.set_hfsel(); + ch2.enable(); + + Self { ch1, ch2 } } /// Create a new `Dac` instance where the external output pins are not used, @@ -435,18 +444,28 @@ impl<'d, T: Instance, DMACh1, DMACh2> Dac<'d, T, DMACh1, DMACh2> { ) -> Self { into_ref!(dma_ch1, dma_ch2); // Enable twice to increment the DAC refcount for each channel. - T::enable_and_reset(); - T::enable_and_reset(); - Self { - ch1: DacCh1 { - phantom: PhantomData, - dma: dma_ch1, - }, - ch2: DacCh2 { - phantom: PhantomData, - dma: dma_ch2, - }, - } + rcc::enable_and_reset::(); + rcc::enable_and_reset::(); + + let mut ch1 = DacCh1 { + phantom: PhantomData, + dma: dma_ch1, + }; + #[cfg(any(dac_v5, dac_v6, dac_v7))] + ch1.set_hfsel(); + ch1.set_mode(Mode::NormalInternalUnbuffered); + ch1.enable(); + + let mut ch2 = DacCh2 { + phantom: PhantomData, + dma: dma_ch2, + }; + #[cfg(any(dac_v5, dac_v6, dac_v7))] + ch2.set_hfsel(); + ch2.set_mode(Mode::NormalInternalUnbuffered); + ch2.enable(); + + Self { ch1, ch2 } } /// Split this `Dac` into separate channels. @@ -488,14 +507,13 @@ impl<'d, T: Instance, DMACh1, DMACh2> Dac<'d, T, DMACh1, DMACh2> { } } -pub(crate) mod sealed { - pub trait Instance { - fn regs() -> &'static crate::pac::dac::Dac; - } +trait SealedInstance { + fn regs() -> crate::pac::dac::Dac; } /// DAC instance. -pub trait Instance: sealed::Instance + RccPeripheral + 'static {} +#[allow(private_bounds)] +pub trait Instance: SealedInstance + RccPeripheral + 'static {} dma_trait!(DacDma1, Instance); dma_trait!(DacDma2, Instance); @@ -504,9 +522,9 @@ pub trait DacPin: crate::gpio::Pin + 'static {} foreach_peripheral!( (dac, $inst:ident) => { - impl crate::dac::sealed::Instance for peripherals::$inst { - fn regs() -> &'static crate::pac::dac::Dac { - &crate::pac::$inst + impl crate::dac::SealedInstance for peripherals::$inst { + fn regs() -> crate::pac::dac::Dac { + crate::pac::$inst } } diff --git a/embassy-stm32/src/dac/tsel.rs b/embassy-stm32/src/dac/tsel.rs index 22d8d3dfa..1877954b9 100644 --- a/embassy-stm32/src/dac/tsel.rs +++ b/embassy-stm32/src/dac/tsel.rs @@ -235,6 +235,23 @@ pub enum TriggerSel { Exti9 = 13, } +/// Trigger selection for U0. +#[cfg(stm32u0)] +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum TriggerSel { + Software = 0, + Tim1 = 1, + Tim2 = 2, + Tim3 = 3, + Tim6 = 5, + Tim7 = 6, + Tim15 = 8, + Lptim1 = 11, + Lptim2 = 12, + Exti9 = 14, +} + /// Trigger selection for G4. #[cfg(stm32g4)] #[derive(Debug, Copy, Clone, Eq, PartialEq)] diff --git a/embassy-stm32/src/dcmi.rs b/embassy-stm32/src/dcmi.rs index 4d02284b2..4ba4e824e 100644 --- a/embassy-stm32/src/dcmi.rs +++ b/embassy-stm32/src/dcmi.rs @@ -7,10 +7,9 @@ use embassy_hal_internal::{into_ref, PeripheralRef}; use embassy_sync::waitqueue::AtomicWaker; use crate::dma::Transfer; -use crate::gpio::sealed::AFType; -use crate::gpio::Speed; +use crate::gpio::{AfType, Pull}; use crate::interrupt::typelevel::Interrupt; -use crate::{interrupt, Peripheral}; +use crate::{interrupt, rcc, Peripheral}; /// Interrupt handler. pub struct InterruptHandler { @@ -110,8 +109,7 @@ macro_rules! config_pins { into_ref!($($pin),*); critical_section::with(|_| { $( - $pin.set_as_af($pin.af_num(), AFType::Input); - $pin.set_speed(Speed::VeryHigh); + $pin.set_as_af($pin.af_num(), AfType::input(Pull::None)); )* }) }; @@ -351,7 +349,7 @@ where use_embedded_synchronization: bool, edm: u8, ) -> Self { - T::enable_and_reset(); + rcc::enable_and_reset::(); peri.regs().cr().modify(|r| { r.set_cm(true); // disable continuous mode (snapshot mode) @@ -394,19 +392,7 @@ where /// This method starts the capture and finishes when both the dma transfer and DCMI finish the frame transfer. /// The implication is that the input buffer size must be exactly the size of the captured frame. - /// - /// Note that when `buffer.len() > 0xffff` the capture future requires some real-time guarantees to be upheld - /// (must be polled fast enough so the buffers get switched before data is overwritten). - /// It is therefore recommended that it is run on higher priority executor. pub async fn capture(&mut self, buffer: &mut [u32]) -> Result<(), Error> { - if buffer.len() <= 0xffff { - return self.capture_small(buffer).await; - } else { - return self.capture_giant(buffer).await; - } - } - - async fn capture_small(&mut self, buffer: &mut [u32]) -> Result<(), Error> { let r = self.inner.regs(); let src = r.dr().as_ptr() as *mut u32; let request = self.dma.request(); @@ -441,126 +427,15 @@ where result } - - #[cfg(not(dma))] - async fn capture_giant(&mut self, _buffer: &mut [u32]) -> Result<(), Error> { - panic!("capturing to buffers larger than 0xffff is only supported on DMA for now, not on BDMA or GPDMA."); - } - - #[cfg(dma)] - async fn capture_giant(&mut self, buffer: &mut [u32]) -> Result<(), Error> { - use crate::dma::TransferOptions; - - let data_len = buffer.len(); - let chunk_estimate = data_len / 0xffff; - - let mut chunks = chunk_estimate + 1; - while data_len % chunks != 0 { - chunks += 1; - } - - let chunk_size = data_len / chunks; - - let mut remaining_chunks = chunks - 2; - - let mut m0ar = buffer.as_mut_ptr(); - let mut m1ar = unsafe { buffer.as_mut_ptr().add(chunk_size) }; - - let channel = &mut self.dma; - let request = channel.request(); - - let r = self.inner.regs(); - let src = r.dr().as_ptr() as *mut u32; - - let mut transfer = unsafe { - crate::dma::DoubleBuffered::new_read( - &mut self.dma, - request, - src, - m0ar, - m1ar, - chunk_size, - TransferOptions::default(), - ) - }; - - let mut last_chunk_set_for_transfer = false; - let mut buffer0_last_accessible = false; - let dma_result = poll_fn(|cx| { - transfer.set_waker(cx.waker()); - - let buffer0_currently_accessible = transfer.is_buffer0_accessible(); - - // check if the accessible buffer changed since last poll - if buffer0_last_accessible == buffer0_currently_accessible { - return Poll::Pending; - } - buffer0_last_accessible = !buffer0_last_accessible; - - if remaining_chunks != 0 { - if remaining_chunks % 2 == 0 && buffer0_currently_accessible { - m0ar = unsafe { m0ar.add(2 * chunk_size) }; - unsafe { transfer.set_buffer0(m0ar) } - remaining_chunks -= 1; - } else if !buffer0_currently_accessible { - m1ar = unsafe { m1ar.add(2 * chunk_size) }; - unsafe { transfer.set_buffer1(m1ar) }; - remaining_chunks -= 1; - } - } else { - if buffer0_currently_accessible { - unsafe { transfer.set_buffer0(buffer.as_mut_ptr()) } - } else { - unsafe { transfer.set_buffer1(buffer.as_mut_ptr()) } - } - if last_chunk_set_for_transfer { - transfer.request_stop(); - return Poll::Ready(()); - } - last_chunk_set_for_transfer = true; - } - Poll::Pending - }); - - Self::clear_interrupt_flags(); - Self::enable_irqs(); - - let result = poll_fn(|cx| { - STATE.waker.register(cx.waker()); - - let ris = crate::pac::DCMI.ris().read(); - if ris.err_ris() { - crate::pac::DCMI.icr().write(|r| r.set_err_isc(true)); - Poll::Ready(Err(Error::PeripheralError)) - } else if ris.ovr_ris() { - crate::pac::DCMI.icr().write(|r| r.set_ovr_isc(true)); - Poll::Ready(Err(Error::Overrun)) - } else if ris.frame_ris() { - crate::pac::DCMI.icr().write(|r| r.set_frame_isc(true)); - Poll::Ready(Ok(())) - } else { - Poll::Pending - } - }); - - Self::toggle(true); - - let (_, result) = embassy_futures::join::join(dma_result, result).await; - - Self::toggle(false); - - result - } } -mod sealed { - pub trait Instance: crate::rcc::RccPeripheral { - fn regs(&self) -> crate::pac::dcmi::Dcmi; - } +trait SealedInstance: crate::rcc::RccPeripheral { + fn regs(&self) -> crate::pac::dcmi::Dcmi; } /// DCMI instance. -pub trait Instance: sealed::Instance + 'static { +#[allow(private_bounds)] +pub trait Instance: SealedInstance + 'static { /// Interrupt for this instance. type Interrupt: interrupt::typelevel::Interrupt; } @@ -587,7 +462,7 @@ pin_trait!(PixClkPin, Instance); #[allow(unused)] macro_rules! impl_peripheral { ($inst:ident, $irq:ident) => { - impl sealed::Instance for crate::peripherals::$inst { + impl SealedInstance for crate::peripherals::$inst { fn regs(&self) -> crate::pac::dcmi::Dcmi { crate::pac::$inst } diff --git a/embassy-stm32/src/dma/bdma.rs b/embassy-stm32/src/dma/bdma.rs deleted file mode 100644 index a2b83716d..000000000 --- a/embassy-stm32/src/dma/bdma.rs +++ /dev/null @@ -1,733 +0,0 @@ -//! Basic Direct Memory Acccess (BDMA) - -use core::future::Future; -use core::pin::Pin; -use core::sync::atomic::{fence, AtomicUsize, Ordering}; -use core::task::{Context, Poll, Waker}; - -use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef}; -use embassy_sync::waitqueue::AtomicWaker; - -use super::ringbuffer::{DmaCtrl, OverrunError, ReadableDmaRingBuffer, WritableDmaRingBuffer}; -use super::word::{Word, WordSize}; -use super::Dir; -use crate::_generated::BDMA_CHANNEL_COUNT; -use crate::interrupt::typelevel::Interrupt; -use crate::interrupt::Priority; -use crate::pac; -use crate::pac::bdma::{regs, vals}; - -/// BDMA transfer options. -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -#[non_exhaustive] -pub struct TransferOptions { - /// Enable circular DMA - /// - /// Note: - /// If you enable circular mode manually, you may want to build and `.await` the `Transfer` in a separate task. - /// Since DMA in circular mode need manually stop, `.await` in current task would block the task forever. - pub circular: bool, - /// Enable half transfer interrupt - pub half_transfer_ir: bool, - /// Enable transfer complete interrupt - pub complete_transfer_ir: bool, -} - -impl Default for TransferOptions { - fn default() -> Self { - Self { - circular: false, - half_transfer_ir: false, - complete_transfer_ir: true, - } - } -} - -impl From for vals::Size { - fn from(raw: WordSize) -> Self { - match raw { - WordSize::OneByte => Self::BITS8, - WordSize::TwoBytes => Self::BITS16, - WordSize::FourBytes => Self::BITS32, - } - } -} - -impl From

for vals::Dir { - fn from(raw: Dir) -> Self { - match raw { - Dir::MemoryToPeripheral => Self::FROMMEMORY, - Dir::PeripheralToMemory => Self::FROMPERIPHERAL, - } - } -} - -struct State { - ch_wakers: [AtomicWaker; BDMA_CHANNEL_COUNT], - complete_count: [AtomicUsize; BDMA_CHANNEL_COUNT], -} - -impl State { - const fn new() -> Self { - const ZERO: AtomicUsize = AtomicUsize::new(0); - const AW: AtomicWaker = AtomicWaker::new(); - Self { - ch_wakers: [AW; BDMA_CHANNEL_COUNT], - complete_count: [ZERO; BDMA_CHANNEL_COUNT], - } - } -} - -static STATE: State = State::new(); - -/// safety: must be called only once -pub(crate) unsafe fn init(cs: critical_section::CriticalSection, irq_priority: Priority) { - foreach_interrupt! { - ($peri:ident, bdma, $block:ident, $signal_name:ident, $irq:ident) => { - crate::interrupt::typelevel::$irq::set_priority_with_cs(cs, irq_priority); - crate::interrupt::typelevel::$irq::enable(); - }; - } - crate::_generated::init_bdma(); -} - -foreach_dma_channel! { - ($channel_peri:ident, BDMA1, bdma, $channel_num:expr, $index:expr, $dmamux:tt) => { - // BDMA1 in H7 doesn't use DMAMUX, which breaks - }; - ($channel_peri:ident, $dma_peri:ident, bdma, $channel_num:expr, $index:expr, $dmamux:tt) => { - impl sealed::Channel for crate::peripherals::$channel_peri { - fn regs(&self) -> pac::bdma::Dma { - pac::$dma_peri - } - fn num(&self) -> usize { - $channel_num - } - fn index(&self) -> usize { - $index - } - fn on_irq() { - unsafe { on_irq_inner(pac::$dma_peri, $channel_num, $index) } - } - } - - impl Channel for crate::peripherals::$channel_peri {} - }; -} - -/// Safety: Must be called with a matching set of parameters for a valid dma channel -pub(crate) unsafe fn on_irq_inner(dma: pac::bdma::Dma, channel_num: usize, index: usize) { - let isr = dma.isr().read(); - let cr = dma.ch(channel_num).cr(); - - if isr.teif(channel_num) { - panic!("DMA: error on BDMA@{:08x} channel {}", dma.as_ptr() as u32, channel_num); - } - - if isr.htif(channel_num) && cr.read().htie() { - // Acknowledge half transfer complete interrupt - dma.ifcr().write(|w| w.set_htif(channel_num, true)); - } else if isr.tcif(channel_num) && cr.read().tcie() { - // Acknowledge transfer complete interrupt - dma.ifcr().write(|w| w.set_tcif(channel_num, true)); - #[cfg(not(armv6m))] - STATE.complete_count[index].fetch_add(1, Ordering::Release); - #[cfg(armv6m)] - critical_section::with(|_| { - let x = STATE.complete_count[index].load(Ordering::Relaxed); - STATE.complete_count[index].store(x + 1, Ordering::Release); - }) - } else { - return; - } - - STATE.ch_wakers[index].wake(); -} - -/// DMA request type alias. -#[cfg(any(bdma_v2, dmamux))] -pub type Request = u8; -/// DMA request type alias. -#[cfg(not(any(bdma_v2, dmamux)))] -pub type Request = (); - -/// DMA channel. -#[cfg(dmamux)] -pub trait Channel: sealed::Channel + Peripheral

+ 'static + super::dmamux::MuxChannel {} -/// DMA channel. -#[cfg(not(dmamux))] -pub trait Channel: sealed::Channel + Peripheral

+ 'static {} - -pub(crate) mod sealed { - use super::*; - - pub trait Channel { - fn regs(&self) -> pac::bdma::Dma; - fn num(&self) -> usize; - fn index(&self) -> usize; - fn on_irq(); - } -} - -/// DMA transfer. -#[must_use = "futures do nothing unless you `.await` or poll them"] -pub struct Transfer<'a, C: Channel> { - channel: PeripheralRef<'a, C>, -} - -impl<'a, C: Channel> Transfer<'a, C> { - /// Create a new read DMA transfer (peripheral to memory). - pub unsafe fn new_read( - channel: impl Peripheral

+ 'a, - request: Request, - peri_addr: *mut W, - buf: &'a mut [W], - options: TransferOptions, - ) -> Self { - Self::new_read_raw(channel, request, peri_addr, buf, options) - } - - /// Create a new read DMA transfer (peripheral to memory), using raw pointers. - pub unsafe fn new_read_raw( - channel: impl Peripheral

+ 'a, - request: Request, - peri_addr: *mut W, - buf: *mut [W], - options: TransferOptions, - ) -> Self { - into_ref!(channel); - - let (ptr, len) = super::slice_ptr_parts_mut(buf); - assert!(len > 0 && len <= 0xFFFF); - - Self::new_inner( - channel, - request, - Dir::PeripheralToMemory, - peri_addr as *const u32, - ptr as *mut u32, - len, - true, - W::size(), - options, - ) - } - - /// Create a new write DMA transfer (memory to peripheral). - pub unsafe fn new_write( - channel: impl Peripheral

+ 'a, - request: Request, - buf: &'a [W], - peri_addr: *mut W, - options: TransferOptions, - ) -> Self { - Self::new_write_raw(channel, request, buf, peri_addr, options) - } - - /// Create a new write DMA transfer (memory to peripheral), using raw pointers. - pub unsafe fn new_write_raw( - channel: impl Peripheral

+ 'a, - request: Request, - buf: *const [W], - peri_addr: *mut W, - options: TransferOptions, - ) -> Self { - into_ref!(channel); - - let (ptr, len) = super::slice_ptr_parts(buf); - assert!(len > 0 && len <= 0xFFFF); - - Self::new_inner( - channel, - request, - Dir::MemoryToPeripheral, - peri_addr as *const u32, - ptr as *mut u32, - len, - true, - W::size(), - options, - ) - } - - /// Create a new write DMA transfer (memory to peripheral), writing the same value repeatedly. - pub unsafe fn new_write_repeated( - channel: impl Peripheral

+ 'a, - request: Request, - repeated: &'a W, - count: usize, - peri_addr: *mut W, - options: TransferOptions, - ) -> Self { - into_ref!(channel); - - Self::new_inner( - channel, - request, - Dir::MemoryToPeripheral, - peri_addr as *const u32, - repeated as *const W as *mut u32, - count, - false, - W::size(), - options, - ) - } - - unsafe fn new_inner( - channel: PeripheralRef<'a, C>, - _request: Request, - dir: Dir, - peri_addr: *const u32, - mem_addr: *mut u32, - mem_len: usize, - incr_mem: bool, - data_size: WordSize, - options: TransferOptions, - ) -> Self { - let ch = channel.regs().ch(channel.num()); - - // "Preceding reads and writes cannot be moved past subsequent writes." - fence(Ordering::SeqCst); - - #[cfg(bdma_v2)] - critical_section::with(|_| channel.regs().cselr().modify(|w| w.set_cs(channel.num(), _request))); - - let mut this = Self { channel }; - this.clear_irqs(); - STATE.complete_count[this.channel.index()].store(0, Ordering::Release); - - #[cfg(dmamux)] - super::dmamux::configure_dmamux(&mut *this.channel, _request); - - ch.par().write_value(peri_addr as u32); - ch.mar().write_value(mem_addr as u32); - ch.ndtr().write(|w| w.set_ndt(mem_len as u16)); - ch.cr().write(|w| { - w.set_psize(data_size.into()); - w.set_msize(data_size.into()); - w.set_minc(incr_mem); - w.set_dir(dir.into()); - w.set_teie(true); - w.set_tcie(options.complete_transfer_ir); - w.set_htie(options.half_transfer_ir); - w.set_circ(options.circular); - if options.circular { - debug!("Setting circular mode"); - } - w.set_pl(vals::Pl::VERYHIGH); - w.set_en(true); - }); - - this - } - - fn clear_irqs(&mut self) { - self.channel.regs().ifcr().write(|w| { - w.set_tcif(self.channel.num(), true); - w.set_teif(self.channel.num(), true); - }); - } - - /// Request the transfer to stop. - /// - /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false. - pub fn request_stop(&mut self) { - let ch = self.channel.regs().ch(self.channel.num()); - - // Disable the channel. Keep the IEs enabled so the irqs still fire. - ch.cr().write(|w| { - w.set_teie(true); - w.set_tcie(true); - }); - } - - /// Return whether this transfer is still running. - /// - /// If this returns `false`, it can be because either the transfer finished, or - /// it was requested to stop early with [`request_stop`](Self::request_stop). - pub fn is_running(&mut self) -> bool { - let ch = self.channel.regs().ch(self.channel.num()); - let en = ch.cr().read().en(); - let circular = ch.cr().read().circ(); - let tcif = STATE.complete_count[self.channel.index()].load(Ordering::Acquire) != 0; - en && (circular || !tcif) - } - - /// Get the total remaining transfers for the channel. - /// - /// This will be zero for transfers that completed instead of being canceled with [`request_stop`](Self::request_stop). - pub fn get_remaining_transfers(&self) -> u16 { - let ch = self.channel.regs().ch(self.channel.num()); - ch.ndtr().read().ndt() - } - - /// Blocking wait until the transfer finishes. - pub fn blocking_wait(mut self) { - while self.is_running() {} - self.request_stop(); - - // "Subsequent reads and writes cannot be moved ahead of preceding reads." - fence(Ordering::SeqCst); - - core::mem::forget(self); - } -} - -impl<'a, C: Channel> Drop for Transfer<'a, C> { - fn drop(&mut self) { - self.request_stop(); - while self.is_running() {} - - // "Subsequent reads and writes cannot be moved ahead of preceding reads." - fence(Ordering::SeqCst); - } -} - -impl<'a, C: Channel> Unpin for Transfer<'a, C> {} -impl<'a, C: Channel> Future for Transfer<'a, C> { - type Output = (); - fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - STATE.ch_wakers[self.channel.index()].register(cx.waker()); - - if self.is_running() { - Poll::Pending - } else { - Poll::Ready(()) - } - } -} - -// ============================== - -struct DmaCtrlImpl<'a, C: Channel>(PeripheralRef<'a, C>); - -impl<'a, C: Channel> DmaCtrl for DmaCtrlImpl<'a, C> { - fn get_remaining_transfers(&self) -> usize { - let ch = self.0.regs().ch(self.0.num()); - ch.ndtr().read().ndt() as usize - } - - fn get_complete_count(&self) -> usize { - STATE.complete_count[self.0.index()].load(Ordering::Acquire) - } - - fn reset_complete_count(&mut self) -> usize { - #[cfg(not(armv6m))] - return STATE.complete_count[self.0.index()].swap(0, Ordering::AcqRel); - #[cfg(armv6m)] - return critical_section::with(|_| { - let x = STATE.complete_count[self.0.index()].load(Ordering::Acquire); - STATE.complete_count[self.0.index()].store(0, Ordering::Release); - x - }); - } - - fn set_waker(&mut self, waker: &Waker) { - STATE.ch_wakers[self.0.index()].register(waker); - } -} - -/// Ringbuffer for reading data using DMA circular mode. -pub struct ReadableRingBuffer<'a, C: Channel, W: Word> { - cr: regs::Cr, - channel: PeripheralRef<'a, C>, - ringbuf: ReadableDmaRingBuffer<'a, W>, -} - -impl<'a, C: Channel, W: Word> ReadableRingBuffer<'a, C, W> { - /// Create a new ring buffer. - pub unsafe fn new( - channel: impl Peripheral

+ 'a, - _request: Request, - peri_addr: *mut W, - buffer: &'a mut [W], - _options: TransferOptions, - ) -> Self { - into_ref!(channel); - - let len = buffer.len(); - assert!(len > 0 && len <= 0xFFFF); - - let dir = Dir::PeripheralToMemory; - let data_size = W::size(); - - let channel_number = channel.num(); - let dma = channel.regs(); - - // "Preceding reads and writes cannot be moved past subsequent writes." - fence(Ordering::SeqCst); - - #[cfg(bdma_v2)] - critical_section::with(|_| channel.regs().cselr().modify(|w| w.set_cs(channel.num(), _request))); - - let mut w = regs::Cr(0); - w.set_psize(data_size.into()); - w.set_msize(data_size.into()); - w.set_minc(true); - w.set_dir(dir.into()); - w.set_teie(true); - w.set_htie(true); - w.set_tcie(true); - w.set_circ(true); - w.set_pl(vals::Pl::VERYHIGH); - w.set_en(true); - - let buffer_ptr = buffer.as_mut_ptr(); - let mut this = Self { - channel, - cr: w, - ringbuf: ReadableDmaRingBuffer::new(buffer), - }; - this.clear_irqs(); - - #[cfg(dmamux)] - super::dmamux::configure_dmamux(&mut *this.channel, _request); - - let ch = dma.ch(channel_number); - ch.par().write_value(peri_addr as u32); - ch.mar().write_value(buffer_ptr as u32); - ch.ndtr().write(|w| w.set_ndt(len as u16)); - - this - } - - /// Start the ring buffer operation. - /// - /// You must call this after creating it for it to work. - pub fn start(&mut self) { - let ch = self.channel.regs().ch(self.channel.num()); - ch.cr().write_value(self.cr) - } - - /// Clear all data in the ring buffer. - pub fn clear(&mut self) { - self.ringbuf.clear(&mut DmaCtrlImpl(self.channel.reborrow())); - } - - /// Read elements from the ring buffer - /// Return a tuple of the length read and the length remaining in the buffer - /// If not all of the elements were read, then there will be some elements in the buffer remaining - /// The length remaining is the capacity, ring_buf.len(), less the elements remaining after the read - /// OverrunError is returned if the portion to be read was overwritten by the DMA controller. - pub fn read(&mut self, buf: &mut [W]) -> Result<(usize, usize), OverrunError> { - self.ringbuf.read(&mut DmaCtrlImpl(self.channel.reborrow()), buf) - } - - /// Read an exact number of elements from the ringbuffer. - /// - /// Returns the remaining number of elements available for immediate reading. - /// OverrunError is returned if the portion to be read was overwritten by the DMA controller. - /// - /// Async/Wake Behavior: - /// The underlying DMA peripheral only can wake us when its buffer pointer has reached the halfway point, - /// and when it wraps around. This means that when called with a buffer of length 'M', when this - /// ring buffer was created with a buffer of size 'N': - /// - If M equals N/2 or N/2 divides evenly into M, this function will return every N/2 elements read on the DMA source. - /// - Otherwise, this function may need up to N/2 extra elements to arrive before returning. - pub async fn read_exact(&mut self, buffer: &mut [W]) -> Result { - self.ringbuf - .read_exact(&mut DmaCtrlImpl(self.channel.reborrow()), buffer) - .await - } - - /// The capacity of the ringbuffer. - pub const fn capacity(&self) -> usize { - self.ringbuf.cap() - } - - /// Set a waker to be woken when at least one byte is received. - pub fn set_waker(&mut self, waker: &Waker) { - DmaCtrlImpl(self.channel.reborrow()).set_waker(waker); - } - - fn clear_irqs(&mut self) { - let dma = self.channel.regs(); - dma.ifcr().write(|w| { - w.set_htif(self.channel.num(), true); - w.set_tcif(self.channel.num(), true); - w.set_teif(self.channel.num(), true); - }); - } - - /// Request DMA to stop. - /// - /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false. - pub fn request_stop(&mut self) { - let ch = self.channel.regs().ch(self.channel.num()); - - // Disable the channel. Keep the IEs enabled so the irqs still fire. - // If the channel is enabled and transfer is not completed, we need to perform - // two separate write access to the CR register to disable the channel. - ch.cr().write(|w| { - w.set_teie(true); - w.set_htie(true); - w.set_tcie(true); - }); - } - - /// Return whether DMA is still running. - /// - /// If this returns `false`, it can be because either the transfer finished, or - /// it was requested to stop early with [`request_stop`](Self::request_stop). - pub fn is_running(&mut self) -> bool { - let ch = self.channel.regs().ch(self.channel.num()); - ch.cr().read().en() - } -} - -impl<'a, C: Channel, W: Word> Drop for ReadableRingBuffer<'a, C, W> { - fn drop(&mut self) { - self.request_stop(); - while self.is_running() {} - - // "Subsequent reads and writes cannot be moved ahead of preceding reads." - fence(Ordering::SeqCst); - } -} - -/// Ringbuffer for writing data using DMA circular mode. -pub struct WritableRingBuffer<'a, C: Channel, W: Word> { - cr: regs::Cr, - channel: PeripheralRef<'a, C>, - ringbuf: WritableDmaRingBuffer<'a, W>, -} - -impl<'a, C: Channel, W: Word> WritableRingBuffer<'a, C, W> { - /// Create a new ring buffer. - pub unsafe fn new( - channel: impl Peripheral

+ 'a, - _request: Request, - peri_addr: *mut W, - buffer: &'a mut [W], - _options: TransferOptions, - ) -> Self { - into_ref!(channel); - - let len = buffer.len(); - assert!(len > 0 && len <= 0xFFFF); - - let dir = Dir::MemoryToPeripheral; - let data_size = W::size(); - - let channel_number = channel.num(); - let dma = channel.regs(); - - // "Preceding reads and writes cannot be moved past subsequent writes." - fence(Ordering::SeqCst); - - #[cfg(bdma_v2)] - critical_section::with(|_| channel.regs().cselr().modify(|w| w.set_cs(channel.num(), _request))); - - let mut w = regs::Cr(0); - w.set_psize(data_size.into()); - w.set_msize(data_size.into()); - w.set_minc(true); - w.set_dir(dir.into()); - w.set_teie(true); - w.set_htie(true); - w.set_tcie(true); - w.set_circ(true); - w.set_pl(vals::Pl::VERYHIGH); - w.set_en(true); - - let buffer_ptr = buffer.as_mut_ptr(); - let mut this = Self { - channel, - cr: w, - ringbuf: WritableDmaRingBuffer::new(buffer), - }; - this.clear_irqs(); - - #[cfg(dmamux)] - super::dmamux::configure_dmamux(&mut *this.channel, _request); - - let ch = dma.ch(channel_number); - ch.par().write_value(peri_addr as u32); - ch.mar().write_value(buffer_ptr as u32); - ch.ndtr().write(|w| w.set_ndt(len as u16)); - - this - } - - /// Start the ring buffer operation. - /// - /// You must call this after creating it for it to work. - pub fn start(&mut self) { - let ch = self.channel.regs().ch(self.channel.num()); - ch.cr().write_value(self.cr) - } - - /// Clear all data in the ring buffer. - pub fn clear(&mut self) { - self.ringbuf.clear(&mut DmaCtrlImpl(self.channel.reborrow())); - } - - /// Write elements to the ring buffer - /// Return a tuple of the length written and the length remaining in the buffer - pub fn write(&mut self, buf: &[W]) -> Result<(usize, usize), OverrunError> { - self.ringbuf.write(&mut DmaCtrlImpl(self.channel.reborrow()), buf) - } - - /// Write an exact number of elements to the ringbuffer. - pub async fn write_exact(&mut self, buffer: &[W]) -> Result { - self.ringbuf - .write_exact(&mut DmaCtrlImpl(self.channel.reborrow()), buffer) - .await - } - - /// The capacity of the ringbuffer. - pub const fn capacity(&self) -> usize { - self.ringbuf.cap() - } - - /// Set a waker to be woken when at least one byte is sent. - pub fn set_waker(&mut self, waker: &Waker) { - DmaCtrlImpl(self.channel.reborrow()).set_waker(waker); - } - - fn clear_irqs(&mut self) { - let dma = self.channel.regs(); - dma.ifcr().write(|w| { - w.set_htif(self.channel.num(), true); - w.set_tcif(self.channel.num(), true); - w.set_teif(self.channel.num(), true); - }); - } - - /// Request DMA to stop. - /// - /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false. - pub fn request_stop(&mut self) { - let ch = self.channel.regs().ch(self.channel.num()); - - // Disable the channel. Keep the IEs enabled so the irqs still fire. - // If the channel is enabled and transfer is not completed, we need to perform - // two separate write access to the CR register to disable the channel. - ch.cr().write(|w| { - w.set_teie(true); - w.set_htie(true); - w.set_tcie(true); - }); - } - - /// Return whether DMA is still running. - /// - /// If this returns `false`, it can be because either the transfer finished, or - /// it was requested to stop early with [`request_stop`](Self::request_stop). - pub fn is_running(&mut self) -> bool { - let ch = self.channel.regs().ch(self.channel.num()); - ch.cr().read().en() - } -} - -impl<'a, C: Channel, W: Word> Drop for WritableRingBuffer<'a, C, W> { - fn drop(&mut self) { - self.request_stop(); - while self.is_running() {} - - // "Subsequent reads and writes cannot be moved ahead of preceding reads." - fence(Ordering::SeqCst); - } -} diff --git a/embassy-stm32/src/dma/dma.rs b/embassy-stm32/src/dma/dma.rs deleted file mode 100644 index 16d02f273..000000000 --- a/embassy-stm32/src/dma/dma.rs +++ /dev/null @@ -1,1005 +0,0 @@ -use core::future::Future; -use core::marker::PhantomData; -use core::pin::Pin; -use core::sync::atomic::{fence, AtomicUsize, Ordering}; -use core::task::{Context, Poll, Waker}; - -use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef}; -use embassy_sync::waitqueue::AtomicWaker; - -use super::ringbuffer::{DmaCtrl, OverrunError, ReadableDmaRingBuffer, WritableDmaRingBuffer}; -use super::word::{Word, WordSize}; -use super::Dir; -use crate::_generated::DMA_CHANNEL_COUNT; -use crate::interrupt::typelevel::Interrupt; -use crate::interrupt::Priority; -use crate::pac::dma::{regs, vals}; -use crate::{interrupt, pac}; - -/// DMA transfer options. -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -#[non_exhaustive] -pub struct TransferOptions { - /// Peripheral burst transfer configuration - pub pburst: Burst, - /// Memory burst transfer configuration - pub mburst: Burst, - /// Flow control configuration - pub flow_ctrl: FlowControl, - /// FIFO threshold for DMA FIFO mode. If none, direct mode is used. - pub fifo_threshold: Option, - /// Enable circular DMA - /// - /// Note: - /// If you enable circular mode manually, you may want to build and `.await` the `Transfer` in a separate task. - /// Since DMA in circular mode need manually stop, `.await` in current task would block the task forever. - pub circular: bool, - /// Enable half transfer interrupt - pub half_transfer_ir: bool, - /// Enable transfer complete interrupt - pub complete_transfer_ir: bool, -} - -impl Default for TransferOptions { - fn default() -> Self { - Self { - pburst: Burst::Single, - mburst: Burst::Single, - flow_ctrl: FlowControl::Dma, - fifo_threshold: None, - circular: false, - half_transfer_ir: false, - complete_transfer_ir: true, - } - } -} - -impl From for vals::Size { - fn from(raw: WordSize) -> Self { - match raw { - WordSize::OneByte => Self::BITS8, - WordSize::TwoBytes => Self::BITS16, - WordSize::FourBytes => Self::BITS32, - } - } -} - -impl From

for vals::Dir { - fn from(raw: Dir) -> Self { - match raw { - Dir::MemoryToPeripheral => Self::MEMORYTOPERIPHERAL, - Dir::PeripheralToMemory => Self::PERIPHERALTOMEMORY, - } - } -} - -/// DMA transfer burst setting. -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub enum Burst { - /// Single transfer - Single, - /// Incremental burst of 4 beats - Incr4, - /// Incremental burst of 8 beats - Incr8, - /// Incremental burst of 16 beats - Incr16, -} - -impl From for vals::Burst { - fn from(burst: Burst) -> Self { - match burst { - Burst::Single => vals::Burst::SINGLE, - Burst::Incr4 => vals::Burst::INCR4, - Burst::Incr8 => vals::Burst::INCR8, - Burst::Incr16 => vals::Burst::INCR16, - } - } -} - -/// DMA flow control setting. -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub enum FlowControl { - /// Flow control by DMA - Dma, - /// Flow control by peripheral - Peripheral, -} - -impl From for vals::Pfctrl { - fn from(flow: FlowControl) -> Self { - match flow { - FlowControl::Dma => vals::Pfctrl::DMA, - FlowControl::Peripheral => vals::Pfctrl::PERIPHERAL, - } - } -} - -/// DMA FIFO threshold. -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub enum FifoThreshold { - /// 1/4 full FIFO - Quarter, - /// 1/2 full FIFO - Half, - /// 3/4 full FIFO - ThreeQuarters, - /// Full FIFO - Full, -} - -impl From for vals::Fth { - fn from(value: FifoThreshold) -> Self { - match value { - FifoThreshold::Quarter => vals::Fth::QUARTER, - FifoThreshold::Half => vals::Fth::HALF, - FifoThreshold::ThreeQuarters => vals::Fth::THREEQUARTERS, - FifoThreshold::Full => vals::Fth::FULL, - } - } -} - -struct State { - ch_wakers: [AtomicWaker; DMA_CHANNEL_COUNT], - complete_count: [AtomicUsize; DMA_CHANNEL_COUNT], -} - -impl State { - const fn new() -> Self { - const ZERO: AtomicUsize = AtomicUsize::new(0); - const AW: AtomicWaker = AtomicWaker::new(); - Self { - ch_wakers: [AW; DMA_CHANNEL_COUNT], - complete_count: [ZERO; DMA_CHANNEL_COUNT], - } - } -} - -static STATE: State = State::new(); - -/// safety: must be called only once -pub(crate) unsafe fn init(cs: critical_section::CriticalSection, irq_priority: Priority) { - foreach_interrupt! { - ($peri:ident, dma, $block:ident, $signal_name:ident, $irq:ident) => { - interrupt::typelevel::$irq::set_priority_with_cs(cs, irq_priority); - interrupt::typelevel::$irq::enable(); - }; - } - crate::_generated::init_dma(); -} - -foreach_dma_channel! { - ($channel_peri:ident, $dma_peri:ident, dma, $channel_num:expr, $index:expr, $dmamux:tt) => { - impl sealed::Channel for crate::peripherals::$channel_peri { - fn regs(&self) -> pac::dma::Dma { - pac::$dma_peri - } - fn num(&self) -> usize { - $channel_num - } - fn index(&self) -> usize { - $index - } - fn on_irq() { - unsafe { on_irq_inner(pac::$dma_peri, $channel_num, $index) } - } - } - - impl Channel for crate::peripherals::$channel_peri {} - }; -} - -/// Safety: Must be called with a matching set of parameters for a valid dma channel -pub(crate) unsafe fn on_irq_inner(dma: pac::dma::Dma, channel_num: usize, index: usize) { - let cr = dma.st(channel_num).cr(); - let isr = dma.isr(channel_num / 4).read(); - - if isr.teif(channel_num % 4) { - panic!("DMA: error on DMA@{:08x} channel {}", dma.as_ptr() as u32, channel_num); - } - - if isr.htif(channel_num % 4) && cr.read().htie() { - // Acknowledge half transfer complete interrupt - dma.ifcr(channel_num / 4).write(|w| w.set_htif(channel_num % 4, true)); - } else if isr.tcif(channel_num % 4) && cr.read().tcie() { - // Acknowledge transfer complete interrupt - dma.ifcr(channel_num / 4).write(|w| w.set_tcif(channel_num % 4, true)); - STATE.complete_count[index].fetch_add(1, Ordering::Release); - } else { - return; - } - - STATE.ch_wakers[index].wake(); -} - -/// DMA request type alias. (also known as DMA channel number in some chips) -#[cfg(any(dma_v2, dmamux))] -pub type Request = u8; -/// DMA request type alias. (also known as DMA channel number in some chips) -#[cfg(not(any(dma_v2, dmamux)))] -pub type Request = (); - -/// DMA channel. -#[cfg(dmamux)] -pub trait Channel: sealed::Channel + Peripheral

+ 'static + super::dmamux::MuxChannel {} -/// DMA channel. -#[cfg(not(dmamux))] -pub trait Channel: sealed::Channel + Peripheral

+ 'static {} - -pub(crate) mod sealed { - use super::*; - - pub trait Channel { - fn regs(&self) -> pac::dma::Dma; - fn num(&self) -> usize; - fn index(&self) -> usize; - fn on_irq(); - } -} - -/// DMA transfer. -#[must_use = "futures do nothing unless you `.await` or poll them"] -pub struct Transfer<'a, C: Channel> { - channel: PeripheralRef<'a, C>, -} - -impl<'a, C: Channel> Transfer<'a, C> { - /// Create a new read DMA transfer (peripheral to memory). - pub unsafe fn new_read( - channel: impl Peripheral

+ 'a, - request: Request, - peri_addr: *mut W, - buf: &'a mut [W], - options: TransferOptions, - ) -> Self { - Self::new_read_raw(channel, request, peri_addr, buf, options) - } - - /// Create a new read DMA transfer (peripheral to memory), using raw pointers. - pub unsafe fn new_read_raw( - channel: impl Peripheral

+ 'a, - request: Request, - peri_addr: *mut W, - buf: *mut [W], - options: TransferOptions, - ) -> Self { - into_ref!(channel); - - let (ptr, len) = super::slice_ptr_parts_mut(buf); - assert!(len > 0 && len <= 0xFFFF); - - Self::new_inner( - channel, - request, - Dir::PeripheralToMemory, - peri_addr as *const u32, - ptr as *mut u32, - len, - true, - W::size(), - options, - ) - } - - /// Create a new write DMA transfer (memory to peripheral). - pub unsafe fn new_write( - channel: impl Peripheral

+ 'a, - request: Request, - buf: &'a [W], - peri_addr: *mut W, - options: TransferOptions, - ) -> Self { - Self::new_write_raw(channel, request, buf, peri_addr, options) - } - - /// Create a new write DMA transfer (memory to peripheral), using raw pointers. - pub unsafe fn new_write_raw( - channel: impl Peripheral

+ 'a, - request: Request, - buf: *const [W], - peri_addr: *mut W, - options: TransferOptions, - ) -> Self { - into_ref!(channel); - - let (ptr, len) = super::slice_ptr_parts(buf); - assert!(len > 0 && len <= 0xFFFF); - - Self::new_inner( - channel, - request, - Dir::MemoryToPeripheral, - peri_addr as *const u32, - ptr as *mut u32, - len, - true, - W::size(), - options, - ) - } - - /// Create a new write DMA transfer (memory to peripheral), writing the same value repeatedly. - pub unsafe fn new_write_repeated( - channel: impl Peripheral

+ 'a, - request: Request, - repeated: &'a W, - count: usize, - peri_addr: *mut W, - options: TransferOptions, - ) -> Self { - into_ref!(channel); - - Self::new_inner( - channel, - request, - Dir::MemoryToPeripheral, - peri_addr as *const u32, - repeated as *const W as *mut u32, - count, - false, - W::size(), - options, - ) - } - - unsafe fn new_inner( - channel: PeripheralRef<'a, C>, - _request: Request, - dir: Dir, - peri_addr: *const u32, - mem_addr: *mut u32, - mem_len: usize, - incr_mem: bool, - data_size: WordSize, - options: TransferOptions, - ) -> Self { - let ch = channel.regs().st(channel.num()); - - // "Preceding reads and writes cannot be moved past subsequent writes." - fence(Ordering::SeqCst); - - let mut this = Self { channel }; - this.clear_irqs(); - - #[cfg(dmamux)] - super::dmamux::configure_dmamux(&mut *this.channel, _request); - - ch.par().write_value(peri_addr as u32); - ch.m0ar().write_value(mem_addr as u32); - ch.ndtr().write_value(regs::Ndtr(mem_len as _)); - ch.fcr().write(|w| { - if let Some(fth) = options.fifo_threshold { - // FIFO mode - w.set_dmdis(vals::Dmdis::DISABLED); - w.set_fth(fth.into()); - } else { - // Direct mode - w.set_dmdis(vals::Dmdis::ENABLED); - } - }); - ch.cr().write(|w| { - w.set_dir(dir.into()); - w.set_msize(data_size.into()); - w.set_psize(data_size.into()); - w.set_pl(vals::Pl::VERYHIGH); - w.set_minc(incr_mem); - w.set_pinc(false); - w.set_teie(true); - w.set_tcie(options.complete_transfer_ir); - w.set_circ(options.circular); - if options.circular { - debug!("Setting circular mode"); - } - #[cfg(dma_v1)] - w.set_trbuff(true); - - #[cfg(dma_v2)] - w.set_chsel(_request); - - w.set_pburst(options.pburst.into()); - w.set_mburst(options.mburst.into()); - w.set_pfctrl(options.flow_ctrl.into()); - - w.set_en(true); - }); - - this - } - - fn clear_irqs(&mut self) { - let isrn = self.channel.num() / 4; - let isrbit = self.channel.num() % 4; - - self.channel.regs().ifcr(isrn).write(|w| { - w.set_tcif(isrbit, true); - w.set_teif(isrbit, true); - }); - } - - /// Request the transfer to stop. - /// - /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false. - pub fn request_stop(&mut self) { - let ch = self.channel.regs().st(self.channel.num()); - - // Disable the channel. Keep the IEs enabled so the irqs still fire. - ch.cr().write(|w| { - w.set_teie(true); - w.set_tcie(true); - }); - } - - /// Return whether this transfer is still running. - /// - /// If this returns `false`, it can be because either the transfer finished, or - /// it was requested to stop early with [`request_stop`](Self::request_stop). - pub fn is_running(&mut self) -> bool { - let ch = self.channel.regs().st(self.channel.num()); - ch.cr().read().en() - } - - /// Gets the total remaining transfers for the channel - /// Note: this will be zero for transfers that completed without cancellation. - pub fn get_remaining_transfers(&self) -> u16 { - let ch = self.channel.regs().st(self.channel.num()); - ch.ndtr().read().ndt() - } - - /// Blocking wait until the transfer finishes. - pub fn blocking_wait(mut self) { - while self.is_running() {} - - // "Subsequent reads and writes cannot be moved ahead of preceding reads." - fence(Ordering::SeqCst); - - core::mem::forget(self); - } -} - -impl<'a, C: Channel> Drop for Transfer<'a, C> { - fn drop(&mut self) { - self.request_stop(); - while self.is_running() {} - - // "Subsequent reads and writes cannot be moved ahead of preceding reads." - fence(Ordering::SeqCst); - } -} - -impl<'a, C: Channel> Unpin for Transfer<'a, C> {} -impl<'a, C: Channel> Future for Transfer<'a, C> { - type Output = (); - fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - STATE.ch_wakers[self.channel.index()].register(cx.waker()); - - if self.is_running() { - Poll::Pending - } else { - Poll::Ready(()) - } - } -} - -// ================================== - -/// Double-buffered DMA transfer. -pub struct DoubleBuffered<'a, C: Channel, W: Word> { - channel: PeripheralRef<'a, C>, - _phantom: PhantomData, -} - -impl<'a, C: Channel, W: Word> DoubleBuffered<'a, C, W> { - /// Create a new read DMA transfer (peripheral to memory). - pub unsafe fn new_read( - channel: impl Peripheral

+ 'a, - _request: Request, - peri_addr: *mut W, - buf0: *mut W, - buf1: *mut W, - len: usize, - options: TransferOptions, - ) -> Self { - into_ref!(channel); - assert!(len > 0 && len <= 0xFFFF); - - let dir = Dir::PeripheralToMemory; - let data_size = W::size(); - - let channel_number = channel.num(); - let dma = channel.regs(); - - // "Preceding reads and writes cannot be moved past subsequent writes." - fence(Ordering::SeqCst); - - let mut this = Self { - channel, - _phantom: PhantomData, - }; - this.clear_irqs(); - - #[cfg(dmamux)] - super::dmamux::configure_dmamux(&mut *this.channel, _request); - - let ch = dma.st(channel_number); - ch.par().write_value(peri_addr as u32); - ch.m0ar().write_value(buf0 as u32); - ch.m1ar().write_value(buf1 as u32); - ch.ndtr().write_value(regs::Ndtr(len as _)); - ch.fcr().write(|w| { - if let Some(fth) = options.fifo_threshold { - // FIFO mode - w.set_dmdis(vals::Dmdis::DISABLED); - w.set_fth(fth.into()); - } else { - // Direct mode - w.set_dmdis(vals::Dmdis::ENABLED); - } - }); - ch.cr().write(|w| { - w.set_dir(dir.into()); - w.set_msize(data_size.into()); - w.set_psize(data_size.into()); - w.set_pl(vals::Pl::VERYHIGH); - w.set_minc(true); - w.set_pinc(false); - w.set_teie(true); - w.set_tcie(true); - #[cfg(dma_v1)] - w.set_trbuff(true); - - #[cfg(dma_v2)] - w.set_chsel(_request); - - w.set_pburst(options.pburst.into()); - w.set_mburst(options.mburst.into()); - w.set_pfctrl(options.flow_ctrl.into()); - - w.set_en(true); - }); - - this - } - - fn clear_irqs(&mut self) { - let channel_number = self.channel.num(); - let dma = self.channel.regs(); - let isrn = channel_number / 4; - let isrbit = channel_number % 4; - - dma.ifcr(isrn).write(|w| { - w.set_htif(isrbit, true); - w.set_tcif(isrbit, true); - w.set_teif(isrbit, true); - }); - } - - /// Set the first buffer address. - /// - /// You may call this while DMA is transferring the other buffer. - pub unsafe fn set_buffer0(&mut self, buffer: *mut W) { - let ch = self.channel.regs().st(self.channel.num()); - ch.m0ar().write_value(buffer as _); - } - - /// Set the second buffer address. - /// - /// You may call this while DMA is transferring the other buffer. - pub unsafe fn set_buffer1(&mut self, buffer: *mut W) { - let ch = self.channel.regs().st(self.channel.num()); - ch.m1ar().write_value(buffer as _); - } - - /// Returh whether buffer0 is accessible (i.e. whether DMA is transferring buffer1 now) - pub fn is_buffer0_accessible(&mut self) -> bool { - let ch = self.channel.regs().st(self.channel.num()); - ch.cr().read().ct() == vals::Ct::MEMORY1 - } - - /// Set a waker to be woken when one of the buffers is being transferred. - pub fn set_waker(&mut self, waker: &Waker) { - STATE.ch_wakers[self.channel.index()].register(waker); - } - - /// Request the transfer to stop. - /// - /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false. - pub fn request_stop(&mut self) { - let ch = self.channel.regs().st(self.channel.num()); - - // Disable the channel. Keep the IEs enabled so the irqs still fire. - ch.cr().write(|w| { - w.set_teie(true); - w.set_tcie(true); - }); - } - - /// Return whether this transfer is still running. - /// - /// If this returns `false`, it can be because either the transfer finished, or - /// it was requested to stop early with [`request_stop`](Self::request_stop). - pub fn is_running(&mut self) -> bool { - let ch = self.channel.regs().st(self.channel.num()); - ch.cr().read().en() - } - - /// Gets the total remaining transfers for the channel - /// Note: this will be zero for transfers that completed without cancellation. - pub fn get_remaining_transfers(&self) -> u16 { - let ch = self.channel.regs().st(self.channel.num()); - ch.ndtr().read().ndt() - } -} - -impl<'a, C: Channel, W: Word> Drop for DoubleBuffered<'a, C, W> { - fn drop(&mut self) { - self.request_stop(); - while self.is_running() {} - - // "Subsequent reads and writes cannot be moved ahead of preceding reads." - fence(Ordering::SeqCst); - } -} - -// ============================== - -struct DmaCtrlImpl<'a, C: Channel>(PeripheralRef<'a, C>); - -impl<'a, C: Channel> DmaCtrl for DmaCtrlImpl<'a, C> { - fn get_remaining_transfers(&self) -> usize { - let ch = self.0.regs().st(self.0.num()); - ch.ndtr().read().ndt() as usize - } - - fn get_complete_count(&self) -> usize { - STATE.complete_count[self.0.index()].load(Ordering::Acquire) - } - - fn reset_complete_count(&mut self) -> usize { - STATE.complete_count[self.0.index()].swap(0, Ordering::AcqRel) - } - - fn set_waker(&mut self, waker: &Waker) { - STATE.ch_wakers[self.0.index()].register(waker); - } -} - -/// Ringbuffer for receiving data using DMA circular mode. -pub struct ReadableRingBuffer<'a, C: Channel, W: Word> { - cr: regs::Cr, - channel: PeripheralRef<'a, C>, - ringbuf: ReadableDmaRingBuffer<'a, W>, -} - -impl<'a, C: Channel, W: Word> ReadableRingBuffer<'a, C, W> { - /// Create a new ring buffer. - pub unsafe fn new( - channel: impl Peripheral

+ 'a, - _request: Request, - peri_addr: *mut W, - buffer: &'a mut [W], - options: TransferOptions, - ) -> Self { - into_ref!(channel); - - let len = buffer.len(); - assert!(len > 0 && len <= 0xFFFF); - - let dir = Dir::PeripheralToMemory; - let data_size = W::size(); - - let channel_number = channel.num(); - let dma = channel.regs(); - - // "Preceding reads and writes cannot be moved past subsequent writes." - fence(Ordering::SeqCst); - - let mut w = regs::Cr(0); - w.set_dir(dir.into()); - w.set_msize(data_size.into()); - w.set_psize(data_size.into()); - w.set_pl(vals::Pl::VERYHIGH); - w.set_minc(true); - w.set_pinc(false); - w.set_teie(true); - w.set_htie(options.half_transfer_ir); - w.set_tcie(true); - w.set_circ(true); - #[cfg(dma_v1)] - w.set_trbuff(true); - #[cfg(dma_v2)] - w.set_chsel(_request); - w.set_pburst(options.pburst.into()); - w.set_mburst(options.mburst.into()); - w.set_pfctrl(options.flow_ctrl.into()); - w.set_en(true); - - let buffer_ptr = buffer.as_mut_ptr(); - let mut this = Self { - channel, - cr: w, - ringbuf: ReadableDmaRingBuffer::new(buffer), - }; - this.clear_irqs(); - - #[cfg(dmamux)] - super::dmamux::configure_dmamux(&mut *this.channel, _request); - - let ch = dma.st(channel_number); - ch.par().write_value(peri_addr as u32); - ch.m0ar().write_value(buffer_ptr as u32); - ch.ndtr().write_value(regs::Ndtr(len as _)); - ch.fcr().write(|w| { - if let Some(fth) = options.fifo_threshold { - // FIFO mode - w.set_dmdis(vals::Dmdis::DISABLED); - w.set_fth(fth.into()); - } else { - // Direct mode - w.set_dmdis(vals::Dmdis::ENABLED); - } - }); - - this - } - - /// Start the ring buffer operation. - /// - /// You must call this after creating it for it to work. - pub fn start(&mut self) { - let ch = self.channel.regs().st(self.channel.num()); - ch.cr().write_value(self.cr); - } - - /// Clear all data in the ring buffer. - pub fn clear(&mut self) { - self.ringbuf.clear(&mut DmaCtrlImpl(self.channel.reborrow())); - } - - /// Read elements from the ring buffer - /// Return a tuple of the length read and the length remaining in the buffer - /// If not all of the elements were read, then there will be some elements in the buffer remaining - /// The length remaining is the capacity, ring_buf.len(), less the elements remaining after the read - /// OverrunError is returned if the portion to be read was overwritten by the DMA controller. - pub fn read(&mut self, buf: &mut [W]) -> Result<(usize, usize), OverrunError> { - self.ringbuf.read(&mut DmaCtrlImpl(self.channel.reborrow()), buf) - } - - /// Read an exact number of elements from the ringbuffer. - /// - /// Returns the remaining number of elements available for immediate reading. - /// OverrunError is returned if the portion to be read was overwritten by the DMA controller. - /// - /// Async/Wake Behavior: - /// The underlying DMA peripheral only can wake us when its buffer pointer has reached the halfway point, - /// and when it wraps around. This means that when called with a buffer of length 'M', when this - /// ring buffer was created with a buffer of size 'N': - /// - If M equals N/2 or N/2 divides evenly into M, this function will return every N/2 elements read on the DMA source. - /// - Otherwise, this function may need up to N/2 extra elements to arrive before returning. - pub async fn read_exact(&mut self, buffer: &mut [W]) -> Result { - self.ringbuf - .read_exact(&mut DmaCtrlImpl(self.channel.reborrow()), buffer) - .await - } - - /// The capacity of the ringbuffer - pub const fn capacity(&self) -> usize { - self.ringbuf.cap() - } - - /// Set a waker to be woken when at least one byte is received. - pub fn set_waker(&mut self, waker: &Waker) { - DmaCtrlImpl(self.channel.reborrow()).set_waker(waker); - } - - fn clear_irqs(&mut self) { - let channel_number = self.channel.num(); - let dma = self.channel.regs(); - let isrn = channel_number / 4; - let isrbit = channel_number % 4; - - dma.ifcr(isrn).write(|w| { - w.set_htif(isrbit, true); - w.set_tcif(isrbit, true); - w.set_teif(isrbit, true); - }); - } - - /// Request DMA to stop. - /// - /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false. - pub fn request_stop(&mut self) { - let ch = self.channel.regs().st(self.channel.num()); - - // Disable the channel. Keep the IEs enabled so the irqs still fire. - ch.cr().write(|w| { - w.set_teie(true); - w.set_htie(true); - w.set_tcie(true); - }); - } - - /// Return whether DMA is still running. - /// - /// If this returns `false`, it can be because either the transfer finished, or - /// it was requested to stop early with [`request_stop`](Self::request_stop). - pub fn is_running(&mut self) -> bool { - let ch = self.channel.regs().st(self.channel.num()); - ch.cr().read().en() - } -} - -impl<'a, C: Channel, W: Word> Drop for ReadableRingBuffer<'a, C, W> { - fn drop(&mut self) { - self.request_stop(); - while self.is_running() {} - - // "Subsequent reads and writes cannot be moved ahead of preceding reads." - fence(Ordering::SeqCst); - } -} - -/// Ringbuffer for writing data using DMA circular mode. -pub struct WritableRingBuffer<'a, C: Channel, W: Word> { - cr: regs::Cr, - channel: PeripheralRef<'a, C>, - ringbuf: WritableDmaRingBuffer<'a, W>, -} - -impl<'a, C: Channel, W: Word> WritableRingBuffer<'a, C, W> { - /// Create a new ring buffer. - pub unsafe fn new( - channel: impl Peripheral

+ 'a, - _request: Request, - peri_addr: *mut W, - buffer: &'a mut [W], - options: TransferOptions, - ) -> Self { - into_ref!(channel); - - let len = buffer.len(); - assert!(len > 0 && len <= 0xFFFF); - - let dir = Dir::MemoryToPeripheral; - let data_size = W::size(); - - let channel_number = channel.num(); - let dma = channel.regs(); - - // "Preceding reads and writes cannot be moved past subsequent writes." - fence(Ordering::SeqCst); - - let mut w = regs::Cr(0); - w.set_dir(dir.into()); - w.set_msize(data_size.into()); - w.set_psize(data_size.into()); - w.set_pl(vals::Pl::VERYHIGH); - w.set_minc(true); - w.set_pinc(false); - w.set_teie(true); - w.set_htie(options.half_transfer_ir); - w.set_tcie(true); - w.set_circ(true); - #[cfg(dma_v1)] - w.set_trbuff(true); - #[cfg(dma_v2)] - w.set_chsel(_request); - w.set_pburst(options.pburst.into()); - w.set_mburst(options.mburst.into()); - w.set_pfctrl(options.flow_ctrl.into()); - w.set_en(true); - - let buffer_ptr = buffer.as_mut_ptr(); - let mut this = Self { - channel, - cr: w, - ringbuf: WritableDmaRingBuffer::new(buffer), - }; - this.clear_irqs(); - - #[cfg(dmamux)] - super::dmamux::configure_dmamux(&mut *this.channel, _request); - - let ch = dma.st(channel_number); - ch.par().write_value(peri_addr as u32); - ch.m0ar().write_value(buffer_ptr as u32); - ch.ndtr().write_value(regs::Ndtr(len as _)); - ch.fcr().write(|w| { - if let Some(fth) = options.fifo_threshold { - // FIFO mode - w.set_dmdis(vals::Dmdis::DISABLED); - w.set_fth(fth.into()); - } else { - // Direct mode - w.set_dmdis(vals::Dmdis::ENABLED); - } - }); - - this - } - - /// Start the ring buffer operation. - /// - /// You must call this after creating it for it to work. - pub fn start(&mut self) { - let ch = self.channel.regs().st(self.channel.num()); - ch.cr().write_value(self.cr); - } - - /// Clear all data in the ring buffer. - pub fn clear(&mut self) { - self.ringbuf.clear(&mut DmaCtrlImpl(self.channel.reborrow())); - } - - /// Write elements from the ring buffer - /// Return a tuple of the length written and the length remaining in the buffer - pub fn write(&mut self, buf: &[W]) -> Result<(usize, usize), OverrunError> { - self.ringbuf.write(&mut DmaCtrlImpl(self.channel.reborrow()), buf) - } - - /// Write an exact number of elements to the ringbuffer. - pub async fn write_exact(&mut self, buffer: &[W]) -> Result { - self.ringbuf - .write_exact(&mut DmaCtrlImpl(self.channel.reborrow()), buffer) - .await - } - - /// The capacity of the ringbuffer - pub const fn capacity(&self) -> usize { - self.ringbuf.cap() - } - - /// Set a waker to be woken when at least one byte is received. - pub fn set_waker(&mut self, waker: &Waker) { - DmaCtrlImpl(self.channel.reborrow()).set_waker(waker); - } - - fn clear_irqs(&mut self) { - let channel_number = self.channel.num(); - let dma = self.channel.regs(); - let isrn = channel_number / 4; - let isrbit = channel_number % 4; - - dma.ifcr(isrn).write(|w| { - w.set_htif(isrbit, true); - w.set_tcif(isrbit, true); - w.set_teif(isrbit, true); - }); - } - - /// Request DMA to stop. - /// - /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false. - pub fn request_stop(&mut self) { - let ch = self.channel.regs().st(self.channel.num()); - - // Disable the channel. Keep the IEs enabled so the irqs still fire. - ch.cr().write(|w| { - w.set_teie(true); - w.set_htie(true); - w.set_tcie(true); - }); - } - - /// Return whether DMA is still running. - /// - /// If this returns `false`, it can be because either the transfer finished, or - /// it was requested to stop early with [`request_stop`](Self::request_stop). - pub fn is_running(&mut self) -> bool { - let ch = self.channel.regs().st(self.channel.num()); - ch.cr().read().en() - } -} - -impl<'a, C: Channel, W: Word> Drop for WritableRingBuffer<'a, C, W> { - fn drop(&mut self) { - self.request_stop(); - while self.is_running() {} - - // "Subsequent reads and writes cannot be moved ahead of preceding reads." - fence(Ordering::SeqCst); - } -} diff --git a/embassy-stm32/src/dma/dma_bdma.rs b/embassy-stm32/src/dma/dma_bdma.rs new file mode 100644 index 000000000..cdc603e2c --- /dev/null +++ b/embassy-stm32/src/dma/dma_bdma.rs @@ -0,0 +1,1078 @@ +use core::future::{poll_fn, Future}; +use core::pin::Pin; +use core::sync::atomic::{fence, AtomicUsize, Ordering}; +use core::task::{Context, Poll, Waker}; + +use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef}; +use embassy_sync::waitqueue::AtomicWaker; + +use super::ringbuffer::{DmaCtrl, Error, ReadableDmaRingBuffer, WritableDmaRingBuffer}; +use super::word::{Word, WordSize}; +use super::{AnyChannel, Channel, Dir, Request, STATE}; +use crate::interrupt::typelevel::Interrupt; +use crate::{interrupt, pac}; + +pub(crate) struct ChannelInfo { + pub(crate) dma: DmaInfo, + pub(crate) num: usize, + #[cfg(feature = "_dual-core")] + pub(crate) irq: pac::Interrupt, + #[cfg(dmamux)] + pub(crate) dmamux: super::DmamuxInfo, +} + +#[derive(Clone, Copy)] +pub(crate) enum DmaInfo { + #[cfg(dma)] + Dma(pac::dma::Dma), + #[cfg(bdma)] + Bdma(pac::bdma::Dma), +} + +/// DMA transfer options. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub struct TransferOptions { + /// Peripheral burst transfer configuration + #[cfg(dma)] + pub pburst: Burst, + /// Memory burst transfer configuration + #[cfg(dma)] + pub mburst: Burst, + /// Flow control configuration + #[cfg(dma)] + pub flow_ctrl: FlowControl, + /// FIFO threshold for DMA FIFO mode. If none, direct mode is used. + #[cfg(dma)] + pub fifo_threshold: Option, + /// Request priority level + pub priority: Priority, + /// Enable circular DMA + /// + /// Note: + /// If you enable circular mode manually, you may want to build and `.await` the `Transfer` in a separate task. + /// Since DMA in circular mode need manually stop, `.await` in current task would block the task forever. + pub circular: bool, + /// Enable half transfer interrupt + pub half_transfer_ir: bool, + /// Enable transfer complete interrupt + pub complete_transfer_ir: bool, +} + +impl Default for TransferOptions { + fn default() -> Self { + Self { + #[cfg(dma)] + pburst: Burst::Single, + #[cfg(dma)] + mburst: Burst::Single, + #[cfg(dma)] + flow_ctrl: FlowControl::Dma, + #[cfg(dma)] + fifo_threshold: None, + priority: Priority::VeryHigh, + circular: false, + half_transfer_ir: false, + complete_transfer_ir: true, + } + } +} + +/// DMA request priority +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Priority { + /// Low Priority + Low, + /// Medium Priority + Medium, + /// High Priority + High, + /// Very High Priority + VeryHigh, +} + +#[cfg(dma)] +impl From for pac::dma::vals::Pl { + fn from(value: Priority) -> Self { + match value { + Priority::Low => pac::dma::vals::Pl::LOW, + Priority::Medium => pac::dma::vals::Pl::MEDIUM, + Priority::High => pac::dma::vals::Pl::HIGH, + Priority::VeryHigh => pac::dma::vals::Pl::VERYHIGH, + } + } +} + +#[cfg(bdma)] +impl From for pac::bdma::vals::Pl { + fn from(value: Priority) -> Self { + match value { + Priority::Low => pac::bdma::vals::Pl::LOW, + Priority::Medium => pac::bdma::vals::Pl::MEDIUM, + Priority::High => pac::bdma::vals::Pl::HIGH, + Priority::VeryHigh => pac::bdma::vals::Pl::VERYHIGH, + } + } +} + +#[cfg(dma)] +pub use dma_only::*; +#[cfg(dma)] +mod dma_only { + use pac::dma::vals; + + use super::*; + + impl From for vals::Size { + fn from(raw: WordSize) -> Self { + match raw { + WordSize::OneByte => Self::BITS8, + WordSize::TwoBytes => Self::BITS16, + WordSize::FourBytes => Self::BITS32, + } + } + } + + impl From

for vals::Dir { + fn from(raw: Dir) -> Self { + match raw { + Dir::MemoryToPeripheral => Self::MEMORYTOPERIPHERAL, + Dir::PeripheralToMemory => Self::PERIPHERALTOMEMORY, + } + } + } + + /// DMA transfer burst setting. + #[derive(Debug, Copy, Clone, PartialEq, Eq)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum Burst { + /// Single transfer + Single, + /// Incremental burst of 4 beats + Incr4, + /// Incremental burst of 8 beats + Incr8, + /// Incremental burst of 16 beats + Incr16, + } + + impl From for vals::Burst { + fn from(burst: Burst) -> Self { + match burst { + Burst::Single => vals::Burst::SINGLE, + Burst::Incr4 => vals::Burst::INCR4, + Burst::Incr8 => vals::Burst::INCR8, + Burst::Incr16 => vals::Burst::INCR16, + } + } + } + + /// DMA flow control setting. + #[derive(Debug, Copy, Clone, PartialEq, Eq)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum FlowControl { + /// Flow control by DMA + Dma, + /// Flow control by peripheral + Peripheral, + } + + impl From for vals::Pfctrl { + fn from(flow: FlowControl) -> Self { + match flow { + FlowControl::Dma => vals::Pfctrl::DMA, + FlowControl::Peripheral => vals::Pfctrl::PERIPHERAL, + } + } + } + + /// DMA FIFO threshold. + #[derive(Debug, Copy, Clone, PartialEq, Eq)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum FifoThreshold { + /// 1/4 full FIFO + Quarter, + /// 1/2 full FIFO + Half, + /// 3/4 full FIFO + ThreeQuarters, + /// Full FIFO + Full, + } + + impl From for vals::Fth { + fn from(value: FifoThreshold) -> Self { + match value { + FifoThreshold::Quarter => vals::Fth::QUARTER, + FifoThreshold::Half => vals::Fth::HALF, + FifoThreshold::ThreeQuarters => vals::Fth::THREEQUARTERS, + FifoThreshold::Full => vals::Fth::FULL, + } + } + } +} + +#[cfg(bdma)] +mod bdma_only { + use pac::bdma::vals; + + use super::*; + + impl From for vals::Size { + fn from(raw: WordSize) -> Self { + match raw { + WordSize::OneByte => Self::BITS8, + WordSize::TwoBytes => Self::BITS16, + WordSize::FourBytes => Self::BITS32, + } + } + } + + impl From for vals::Dir { + fn from(raw: Dir) -> Self { + match raw { + Dir::MemoryToPeripheral => Self::FROMMEMORY, + Dir::PeripheralToMemory => Self::FROMPERIPHERAL, + } + } + } +} + +pub(crate) struct ChannelState { + waker: AtomicWaker, + complete_count: AtomicUsize, +} + +impl ChannelState { + pub(crate) const NEW: Self = Self { + waker: AtomicWaker::new(), + complete_count: AtomicUsize::new(0), + }; +} + +/// safety: must be called only once +pub(crate) unsafe fn init( + cs: critical_section::CriticalSection, + #[cfg(dma)] dma_priority: interrupt::Priority, + #[cfg(bdma)] bdma_priority: interrupt::Priority, +) { + foreach_interrupt! { + ($peri:ident, dma, $block:ident, $signal_name:ident, $irq:ident) => { + crate::interrupt::typelevel::$irq::set_priority_with_cs(cs, dma_priority); + #[cfg(not(feature = "_dual-core"))] + crate::interrupt::typelevel::$irq::enable(); + }; + ($peri:ident, bdma, $block:ident, $signal_name:ident, $irq:ident) => { + crate::interrupt::typelevel::$irq::set_priority_with_cs(cs, bdma_priority); + #[cfg(not(feature = "_dual-core"))] + crate::interrupt::typelevel::$irq::enable(); + }; + } + crate::_generated::init_dma(); + crate::_generated::init_bdma(); +} + +impl AnyChannel { + /// Safety: Must be called with a matching set of parameters for a valid dma channel + pub(crate) unsafe fn on_irq(&self) { + let info = self.info(); + let state = &STATE[self.id as usize]; + match self.info().dma { + #[cfg(dma)] + DmaInfo::Dma(r) => { + let cr = r.st(info.num).cr(); + let isr = r.isr(info.num / 4).read(); + + if isr.teif(info.num % 4) { + panic!("DMA: error on DMA@{:08x} channel {}", r.as_ptr() as u32, info.num); + } + + if isr.htif(info.num % 4) && cr.read().htie() { + // Acknowledge half transfer complete interrupt + r.ifcr(info.num / 4).write(|w| w.set_htif(info.num % 4, true)); + } else if isr.tcif(info.num % 4) && cr.read().tcie() { + // Acknowledge transfer complete interrupt + r.ifcr(info.num / 4).write(|w| w.set_tcif(info.num % 4, true)); + state.complete_count.fetch_add(1, Ordering::Release); + } else { + return; + } + state.waker.wake(); + } + #[cfg(bdma)] + DmaInfo::Bdma(r) => { + let isr = r.isr().read(); + let cr = r.ch(info.num).cr(); + + if isr.teif(info.num) { + panic!("DMA: error on BDMA@{:08x} channel {}", r.as_ptr() as u32, info.num); + } + + if isr.htif(info.num) && cr.read().htie() { + // Acknowledge half transfer complete interrupt + r.ifcr().write(|w| w.set_htif(info.num, true)); + } else if isr.tcif(info.num) && cr.read().tcie() { + // Acknowledge transfer complete interrupt + r.ifcr().write(|w| w.set_tcif(info.num, true)); + #[cfg(not(armv6m))] + state.complete_count.fetch_add(1, Ordering::Release); + #[cfg(armv6m)] + critical_section::with(|_| { + let x = state.complete_count.load(Ordering::Relaxed); + state.complete_count.store(x + 1, Ordering::Release); + }) + } else { + return; + } + + state.waker.wake(); + } + } + } + + unsafe fn configure( + &self, + _request: Request, + dir: Dir, + peri_addr: *const u32, + mem_addr: *mut u32, + mem_len: usize, + incr_mem: bool, + data_size: WordSize, + options: TransferOptions, + ) { + let info = self.info(); + #[cfg(feature = "_dual-core")] + { + use embassy_hal_internal::interrupt::InterruptExt as _; + info.irq.enable(); + } + + #[cfg(dmamux)] + super::dmamux::configure_dmamux(&info.dmamux, _request); + + assert!(mem_len > 0 && mem_len <= 0xFFFF); + + match self.info().dma { + #[cfg(dma)] + DmaInfo::Dma(r) => { + let ch = r.st(info.num); + + // "Preceding reads and writes cannot be moved past subsequent writes." + fence(Ordering::SeqCst); + + self.clear_irqs(); + + ch.par().write_value(peri_addr as u32); + ch.m0ar().write_value(mem_addr as u32); + ch.ndtr().write_value(pac::dma::regs::Ndtr(mem_len as _)); + ch.fcr().write(|w| { + if let Some(fth) = options.fifo_threshold { + // FIFO mode + w.set_dmdis(pac::dma::vals::Dmdis::DISABLED); + w.set_fth(fth.into()); + } else { + // Direct mode + w.set_dmdis(pac::dma::vals::Dmdis::ENABLED); + } + }); + ch.cr().write(|w| { + w.set_dir(dir.into()); + w.set_msize(data_size.into()); + w.set_psize(data_size.into()); + w.set_pl(options.priority.into()); + w.set_minc(incr_mem); + w.set_pinc(false); + w.set_teie(true); + w.set_htie(options.half_transfer_ir); + w.set_tcie(options.complete_transfer_ir); + w.set_circ(options.circular); + #[cfg(dma_v1)] + w.set_trbuff(true); + #[cfg(dma_v2)] + w.set_chsel(_request); + w.set_pburst(options.pburst.into()); + w.set_mburst(options.mburst.into()); + w.set_pfctrl(options.flow_ctrl.into()); + w.set_en(false); // don't start yet + }); + } + #[cfg(bdma)] + DmaInfo::Bdma(r) => { + #[cfg(bdma_v2)] + critical_section::with(|_| r.cselr().modify(|w| w.set_cs(info.num, _request))); + + let state: &ChannelState = &STATE[self.id as usize]; + let ch = r.ch(info.num); + + state.complete_count.store(0, Ordering::Release); + self.clear_irqs(); + + ch.par().write_value(peri_addr as u32); + ch.mar().write_value(mem_addr as u32); + ch.ndtr().write(|w| w.set_ndt(mem_len as u16)); + ch.cr().write(|w| { + w.set_psize(data_size.into()); + w.set_msize(data_size.into()); + w.set_minc(incr_mem); + w.set_dir(dir.into()); + w.set_teie(true); + w.set_tcie(options.complete_transfer_ir); + w.set_htie(options.half_transfer_ir); + w.set_circ(options.circular); + w.set_pl(options.priority.into()); + w.set_en(false); // don't start yet + }); + } + } + } + + fn start(&self) { + let info = self.info(); + match self.info().dma { + #[cfg(dma)] + DmaInfo::Dma(r) => { + let ch = r.st(info.num); + ch.cr().modify(|w| w.set_en(true)) + } + #[cfg(bdma)] + DmaInfo::Bdma(r) => { + let ch = r.ch(info.num); + ch.cr().modify(|w| w.set_en(true)); + } + } + } + + fn clear_irqs(&self) { + let info = self.info(); + match self.info().dma { + #[cfg(dma)] + DmaInfo::Dma(r) => { + let isrn = info.num / 4; + let isrbit = info.num % 4; + + r.ifcr(isrn).write(|w| { + w.set_htif(isrbit, true); + w.set_tcif(isrbit, true); + w.set_teif(isrbit, true); + }); + } + #[cfg(bdma)] + DmaInfo::Bdma(r) => { + r.ifcr().write(|w| { + w.set_htif(info.num, true); + w.set_tcif(info.num, true); + w.set_teif(info.num, true); + }); + } + } + } + + fn request_stop(&self) { + let info = self.info(); + match self.info().dma { + #[cfg(dma)] + DmaInfo::Dma(r) => { + // Disable the channel. Keep the IEs enabled so the irqs still fire. + r.st(info.num).cr().write(|w| { + w.set_teie(true); + w.set_tcie(true); + }); + } + #[cfg(bdma)] + DmaInfo::Bdma(r) => { + // Disable the channel. Keep the IEs enabled so the irqs still fire. + r.ch(info.num).cr().write(|w| { + w.set_teie(true); + w.set_tcie(true); + }); + } + } + } + + fn request_pause(&self) { + let info = self.info(); + match self.info().dma { + #[cfg(dma)] + DmaInfo::Dma(r) => { + // Disable the channel without overwriting the existing configuration + r.st(info.num).cr().modify(|w| { + w.set_en(false); + }); + } + #[cfg(bdma)] + DmaInfo::Bdma(r) => { + // Disable the channel without overwriting the existing configuration + r.ch(info.num).cr().modify(|w| { + w.set_en(false); + }); + } + } + } + + fn is_running(&self) -> bool { + let info = self.info(); + match self.info().dma { + #[cfg(dma)] + DmaInfo::Dma(r) => r.st(info.num).cr().read().en(), + #[cfg(bdma)] + DmaInfo::Bdma(r) => { + let state: &ChannelState = &STATE[self.id as usize]; + let ch = r.ch(info.num); + let en = ch.cr().read().en(); + let circular = ch.cr().read().circ(); + let tcif = state.complete_count.load(Ordering::Acquire) != 0; + en && (circular || !tcif) + } + } + } + + fn get_remaining_transfers(&self) -> u16 { + let info = self.info(); + match self.info().dma { + #[cfg(dma)] + DmaInfo::Dma(r) => r.st(info.num).ndtr().read().ndt(), + #[cfg(bdma)] + DmaInfo::Bdma(r) => r.ch(info.num).ndtr().read().ndt(), + } + } + + fn disable_circular_mode(&self) { + let info = self.info(); + match self.info().dma { + #[cfg(dma)] + DmaInfo::Dma(regs) => regs.st(info.num).cr().modify(|w| { + w.set_circ(false); + }), + #[cfg(bdma)] + DmaInfo::Bdma(regs) => regs.ch(info.num).cr().modify(|w| { + w.set_circ(false); + }), + } + } + + fn poll_stop(&self) -> Poll<()> { + use core::sync::atomic::compiler_fence; + compiler_fence(Ordering::SeqCst); + + if !self.is_running() { + Poll::Ready(()) + } else { + Poll::Pending + } + } +} + +/// DMA transfer. +#[must_use = "futures do nothing unless you `.await` or poll them"] +pub struct Transfer<'a> { + channel: PeripheralRef<'a, AnyChannel>, +} + +impl<'a> Transfer<'a> { + /// Create a new read DMA transfer (peripheral to memory). + pub unsafe fn new_read( + channel: impl Peripheral

+ 'a, + request: Request, + peri_addr: *mut W, + buf: &'a mut [W], + options: TransferOptions, + ) -> Self { + Self::new_read_raw(channel, request, peri_addr, buf, options) + } + + /// Create a new read DMA transfer (peripheral to memory), using raw pointers. + pub unsafe fn new_read_raw( + channel: impl Peripheral

+ 'a, + request: Request, + peri_addr: *mut W, + buf: *mut [W], + options: TransferOptions, + ) -> Self { + into_ref!(channel); + + Self::new_inner( + channel.map_into(), + request, + Dir::PeripheralToMemory, + peri_addr as *const u32, + buf as *mut W as *mut u32, + buf.len(), + true, + W::size(), + options, + ) + } + + /// Create a new write DMA transfer (memory to peripheral). + pub unsafe fn new_write( + channel: impl Peripheral

+ 'a, + request: Request, + buf: &'a [W], + peri_addr: *mut W, + options: TransferOptions, + ) -> Self { + Self::new_write_raw(channel, request, buf, peri_addr, options) + } + + /// Create a new write DMA transfer (memory to peripheral), using raw pointers. + pub unsafe fn new_write_raw( + channel: impl Peripheral

+ 'a, + request: Request, + buf: *const [W], + peri_addr: *mut W, + options: TransferOptions, + ) -> Self { + into_ref!(channel); + + Self::new_inner( + channel.map_into(), + request, + Dir::MemoryToPeripheral, + peri_addr as *const u32, + buf as *const W as *mut u32, + buf.len(), + true, + W::size(), + options, + ) + } + + /// Create a new write DMA transfer (memory to peripheral), writing the same value repeatedly. + pub unsafe fn new_write_repeated( + channel: impl Peripheral

+ 'a, + request: Request, + repeated: &'a W, + count: usize, + peri_addr: *mut W, + options: TransferOptions, + ) -> Self { + into_ref!(channel); + + Self::new_inner( + channel.map_into(), + request, + Dir::MemoryToPeripheral, + peri_addr as *const u32, + repeated as *const W as *mut u32, + count, + false, + W::size(), + options, + ) + } + + unsafe fn new_inner( + channel: PeripheralRef<'a, AnyChannel>, + _request: Request, + dir: Dir, + peri_addr: *const u32, + mem_addr: *mut u32, + mem_len: usize, + incr_mem: bool, + data_size: WordSize, + options: TransferOptions, + ) -> Self { + assert!(mem_len > 0 && mem_len <= 0xFFFF); + + channel.configure( + _request, dir, peri_addr, mem_addr, mem_len, incr_mem, data_size, options, + ); + channel.start(); + + Self { channel } + } + + /// Request the transfer to stop. + /// The configuration for this channel will **not be preserved**. If you need to restart the transfer + /// at a later point with the same configuration, see [`request_pause`](Self::request_pause) instead. + /// + /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false. + pub fn request_stop(&mut self) { + self.channel.request_stop() + } + + /// Request the transfer to pause, keeping the existing configuration for this channel. + /// To restart the transfer, call [`start`](Self::start) again. + /// + /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false. + pub fn request_pause(&mut self) { + self.channel.request_pause() + } + + /// Return whether this transfer is still running. + /// + /// If this returns `false`, it can be because either the transfer finished, or + /// it was requested to stop early with [`request_stop`](Self::request_stop). + pub fn is_running(&mut self) -> bool { + self.channel.is_running() + } + + /// Gets the total remaining transfers for the channel + /// Note: this will be zero for transfers that completed without cancellation. + pub fn get_remaining_transfers(&self) -> u16 { + self.channel.get_remaining_transfers() + } + + /// Blocking wait until the transfer finishes. + pub fn blocking_wait(mut self) { + while self.is_running() {} + + // "Subsequent reads and writes cannot be moved ahead of preceding reads." + fence(Ordering::SeqCst); + + core::mem::forget(self); + } +} + +impl<'a> Drop for Transfer<'a> { + fn drop(&mut self) { + self.request_stop(); + while self.is_running() {} + + // "Subsequent reads and writes cannot be moved ahead of preceding reads." + fence(Ordering::SeqCst); + } +} + +impl<'a> Unpin for Transfer<'a> {} +impl<'a> Future for Transfer<'a> { + type Output = (); + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let state: &ChannelState = &STATE[self.channel.id as usize]; + + state.waker.register(cx.waker()); + + if self.is_running() { + Poll::Pending + } else { + Poll::Ready(()) + } + } +} + +// ============================== + +struct DmaCtrlImpl<'a>(PeripheralRef<'a, AnyChannel>); + +impl<'a> DmaCtrl for DmaCtrlImpl<'a> { + fn get_remaining_transfers(&self) -> usize { + self.0.get_remaining_transfers() as _ + } + + fn reset_complete_count(&mut self) -> usize { + let state = &STATE[self.0.id as usize]; + #[cfg(not(armv6m))] + return state.complete_count.swap(0, Ordering::AcqRel); + #[cfg(armv6m)] + return critical_section::with(|_| { + let x = state.complete_count.load(Ordering::Acquire); + state.complete_count.store(0, Ordering::Release); + x + }); + } + + fn set_waker(&mut self, waker: &Waker) { + STATE[self.0.id as usize].waker.register(waker); + } +} + +/// Ringbuffer for receiving data using DMA circular mode. +pub struct ReadableRingBuffer<'a, W: Word> { + channel: PeripheralRef<'a, AnyChannel>, + ringbuf: ReadableDmaRingBuffer<'a, W>, +} + +impl<'a, W: Word> ReadableRingBuffer<'a, W> { + /// Create a new ring buffer. + pub unsafe fn new( + channel: impl Peripheral

+ 'a, + _request: Request, + peri_addr: *mut W, + buffer: &'a mut [W], + mut options: TransferOptions, + ) -> Self { + into_ref!(channel); + let channel: PeripheralRef<'a, AnyChannel> = channel.map_into(); + + let buffer_ptr = buffer.as_mut_ptr(); + let len = buffer.len(); + let dir = Dir::PeripheralToMemory; + let data_size = W::size(); + + options.half_transfer_ir = true; + options.complete_transfer_ir = true; + options.circular = true; + + channel.configure( + _request, + dir, + peri_addr as *mut u32, + buffer_ptr as *mut u32, + len, + true, + data_size, + options, + ); + + Self { + channel, + ringbuf: ReadableDmaRingBuffer::new(buffer), + } + } + + /// Start the ring buffer operation. + /// + /// You must call this after creating it for it to work. + pub fn start(&mut self) { + self.channel.start(); + self.clear(); + } + + /// Clear all data in the ring buffer. + pub fn clear(&mut self) { + self.ringbuf.reset(&mut DmaCtrlImpl(self.channel.reborrow())); + } + + /// Read elements from the ring buffer + /// Return a tuple of the length read and the length remaining in the buffer + /// If not all of the elements were read, then there will be some elements in the buffer remaining + /// The length remaining is the capacity, ring_buf.len(), less the elements remaining after the read + /// Error is returned if the portion to be read was overwritten by the DMA controller. + pub fn read(&mut self, buf: &mut [W]) -> Result<(usize, usize), Error> { + self.ringbuf.read(&mut DmaCtrlImpl(self.channel.reborrow()), buf) + } + + /// Read an exact number of elements from the ringbuffer. + /// + /// Returns the remaining number of elements available for immediate reading. + /// Error is returned if the portion to be read was overwritten by the DMA controller. + /// + /// Async/Wake Behavior: + /// The underlying DMA peripheral only can wake us when its buffer pointer has reached the halfway point, + /// and when it wraps around. This means that when called with a buffer of length 'M', when this + /// ring buffer was created with a buffer of size 'N': + /// - If M equals N/2 or N/2 divides evenly into M, this function will return every N/2 elements read on the DMA source. + /// - Otherwise, this function may need up to N/2 extra elements to arrive before returning. + pub async fn read_exact(&mut self, buffer: &mut [W]) -> Result { + self.ringbuf + .read_exact(&mut DmaCtrlImpl(self.channel.reborrow()), buffer) + .await + } + + /// The current length of the ringbuffer + pub fn len(&mut self) -> Result { + Ok(self.ringbuf.len(&mut DmaCtrlImpl(self.channel.reborrow()))?) + } + + /// The capacity of the ringbuffer + pub const fn capacity(&self) -> usize { + self.ringbuf.cap() + } + + /// Set a waker to be woken when at least one byte is received. + pub fn set_waker(&mut self, waker: &Waker) { + DmaCtrlImpl(self.channel.reborrow()).set_waker(waker); + } + + /// Request the DMA to stop. + /// The configuration for this channel will **not be preserved**. If you need to restart the transfer + /// at a later point with the same configuration, see [`request_pause`](Self::request_pause) instead. + /// + /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false. + pub fn request_stop(&mut self) { + self.channel.request_stop() + } + + /// Request the transfer to pause, keeping the existing configuration for this channel. + /// To restart the transfer, call [`start`](Self::start) again. + /// + /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false. + pub fn request_pause(&mut self) { + self.channel.request_pause() + } + + /// Return whether DMA is still running. + /// + /// If this returns `false`, it can be because either the transfer finished, or + /// it was requested to stop early with [`request_stop`](Self::request_stop). + pub fn is_running(&mut self) -> bool { + self.channel.is_running() + } + + /// Stop the DMA transfer and await until the buffer is full. + /// + /// This disables the DMA transfer's circular mode so that the transfer + /// stops when the buffer is full. + /// + /// This is designed to be used with streaming input data such as the + /// I2S/SAI or ADC. + /// + /// When using the UART, you probably want `request_stop()`. + pub async fn stop(&mut self) { + self.channel.disable_circular_mode(); + //wait until cr.susp reads as true + poll_fn(|cx| { + self.set_waker(cx.waker()); + self.channel.poll_stop() + }) + .await + } +} + +impl<'a, W: Word> Drop for ReadableRingBuffer<'a, W> { + fn drop(&mut self) { + self.request_stop(); + while self.is_running() {} + + // "Subsequent reads and writes cannot be moved ahead of preceding reads." + fence(Ordering::SeqCst); + } +} + +/// Ringbuffer for writing data using DMA circular mode. +pub struct WritableRingBuffer<'a, W: Word> { + channel: PeripheralRef<'a, AnyChannel>, + ringbuf: WritableDmaRingBuffer<'a, W>, +} + +impl<'a, W: Word> WritableRingBuffer<'a, W> { + /// Create a new ring buffer. + pub unsafe fn new( + channel: impl Peripheral

+ 'a, + _request: Request, + peri_addr: *mut W, + buffer: &'a mut [W], + mut options: TransferOptions, + ) -> Self { + into_ref!(channel); + let channel: PeripheralRef<'a, AnyChannel> = channel.map_into(); + + let len = buffer.len(); + let dir = Dir::MemoryToPeripheral; + let data_size = W::size(); + let buffer_ptr = buffer.as_mut_ptr(); + + options.half_transfer_ir = true; + options.complete_transfer_ir = true; + options.circular = true; + + channel.configure( + _request, + dir, + peri_addr as *mut u32, + buffer_ptr as *mut u32, + len, + true, + data_size, + options, + ); + + Self { + channel, + ringbuf: WritableDmaRingBuffer::new(buffer), + } + } + + /// Start the ring buffer operation. + /// + /// You must call this after creating it for it to work. + pub fn start(&mut self) { + self.channel.start(); + self.clear(); + } + + /// Clear all data in the ring buffer. + pub fn clear(&mut self) { + self.ringbuf.reset(&mut DmaCtrlImpl(self.channel.reborrow())); + } + + /// Write elements directly to the raw buffer. + /// This can be used to fill the buffer before starting the DMA transfer. + #[allow(dead_code)] + pub fn write_immediate(&mut self, buf: &[W]) -> Result<(usize, usize), Error> { + self.ringbuf.write_immediate(buf) + } + + /// Write elements from the ring buffer + /// Return a tuple of the length written and the length remaining in the buffer + pub fn write(&mut self, buf: &[W]) -> Result<(usize, usize), Error> { + self.ringbuf.write(&mut DmaCtrlImpl(self.channel.reborrow()), buf) + } + + /// Write an exact number of elements to the ringbuffer. + pub async fn write_exact(&mut self, buffer: &[W]) -> Result { + self.ringbuf + .write_exact(&mut DmaCtrlImpl(self.channel.reborrow()), buffer) + .await + } + + /// The current length of the ringbuffer + pub fn len(&mut self) -> Result { + Ok(self.ringbuf.len(&mut DmaCtrlImpl(self.channel.reborrow()))?) + } + + /// The capacity of the ringbuffer + pub const fn capacity(&self) -> usize { + self.ringbuf.cap() + } + + /// Set a waker to be woken when at least one byte is received. + pub fn set_waker(&mut self, waker: &Waker) { + DmaCtrlImpl(self.channel.reborrow()).set_waker(waker); + } + + /// Request the DMA to stop. + /// The configuration for this channel will **not be preserved**. If you need to restart the transfer + /// at a later point with the same configuration, see [`request_pause`](Self::request_pause) instead. + /// + /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false. + pub fn request_stop(&mut self) { + self.channel.request_stop() + } + + /// Request the transfer to pause, keeping the existing configuration for this channel. + /// To restart the transfer, call [`start`](Self::start) again. + /// + /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false. + pub fn request_pause(&mut self) { + self.channel.request_pause() + } + + /// Return whether DMA is still running. + /// + /// If this returns `false`, it can be because either the transfer finished, or + /// it was requested to stop early with [`request_stop`](Self::request_stop). + pub fn is_running(&mut self) -> bool { + self.channel.is_running() + } + + /// Stop the DMA transfer and await until the buffer is empty. + /// + /// This disables the DMA transfer's circular mode so that the transfer + /// stops when all available data has been written. + /// + /// This is designed to be used with streaming output data such as the + /// I2S/SAI or DAC. + pub async fn stop(&mut self) { + self.channel.disable_circular_mode(); + //wait until cr.susp reads as true + poll_fn(|cx| { + self.set_waker(cx.waker()); + self.channel.poll_stop() + }) + .await + } +} + +impl<'a, W: Word> Drop for WritableRingBuffer<'a, W> { + fn drop(&mut self) { + self.request_stop(); + while self.is_running() {} + + // "Subsequent reads and writes cannot be moved ahead of preceding reads." + fence(Ordering::SeqCst); + } +} diff --git a/embassy-stm32/src/dma/dmamux.rs b/embassy-stm32/src/dma/dmamux.rs index 9cd494724..1585b30d4 100644 --- a/embassy-stm32/src/dma/dmamux.rs +++ b/embassy-stm32/src/dma/dmamux.rs @@ -1,9 +1,14 @@ #![macro_use] -use crate::{pac, peripherals}; +use crate::pac; -pub(crate) fn configure_dmamux(channel: &mut M, request: u8) { - let ch_mux_regs = channel.mux_regs().ccr(channel.mux_num()); +pub(crate) struct DmamuxInfo { + pub(crate) mux: pac::dmamux::Dmamux, + pub(crate) num: usize, +} + +pub(crate) fn configure_dmamux(info: &DmamuxInfo, request: u8) { + let ch_mux_regs = info.mux.ccr(info.num); ch_mux_regs.write(|reg| { reg.set_nbreq(0); reg.set_dmareq_id(request); @@ -14,42 +19,6 @@ pub(crate) fn configure_dmamux(channel: &mut M, request: u8) { }); } -pub(crate) mod dmamux_sealed { - use super::*; - pub trait MuxChannel { - fn mux_regs(&self) -> pac::dmamux::Dmamux; - fn mux_num(&self) -> usize; - } -} - -/// DMAMUX1 instance. -pub struct DMAMUX1; -/// DMAMUX2 instance. -#[cfg(stm32h7)] -pub struct DMAMUX2; - -/// DMAMUX channel trait. -pub trait MuxChannel: dmamux_sealed::MuxChannel { - /// DMAMUX instance this channel is on. - type Mux; -} - -foreach_dma_channel! { - ($channel_peri:ident, $dma_peri:ident, $version:ident, $channel_num:expr, $index:expr, {dmamux: $dmamux:ident, dmamux_channel: $dmamux_channel:expr}) => { - impl dmamux_sealed::MuxChannel for peripherals::$channel_peri { - fn mux_regs(&self) -> pac::dmamux::Dmamux { - pac::$dmamux - } - fn mux_num(&self) -> usize { - $dmamux_channel - } - } - impl MuxChannel for peripherals::$channel_peri { - type Mux = $dmamux; - } - }; -} - /// safety: must be called only once pub(crate) unsafe fn init(_cs: critical_section::CriticalSection) { crate::_generated::init_dmamux(); diff --git a/embassy-stm32/src/dma/gpdma.rs b/embassy-stm32/src/dma/gpdma.rs index 34b2426b9..a877bb8d4 100644 --- a/embassy-stm32/src/dma/gpdma.rs +++ b/embassy-stm32/src/dma/gpdma.rs @@ -9,13 +9,19 @@ use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef}; use embassy_sync::waitqueue::AtomicWaker; use super::word::{Word, WordSize}; -use super::Dir; -use crate::_generated::GPDMA_CHANNEL_COUNT; +use super::{AnyChannel, Channel, Dir, Request, STATE}; use crate::interrupt::typelevel::Interrupt; use crate::interrupt::Priority; use crate::pac; use crate::pac::gpdma::vals; +pub(crate) struct ChannelInfo { + pub(crate) dma: pac::gpdma::Gpdma, + pub(crate) num: usize, + #[cfg(feature = "_dual-core")] + pub(crate) irq: pac::Interrupt, +} + /// GPDMA transfer options. #[derive(Debug, Copy, Clone, PartialEq, Eq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -28,7 +34,7 @@ impl Default for TransferOptions { } } -impl From for vals::ChTr1Dw { +impl From for vals::Dw { fn from(raw: WordSize) -> Self { match raw { WordSize::OneByte => Self::BYTE, @@ -38,113 +44,78 @@ impl From for vals::ChTr1Dw { } } -struct State { - ch_wakers: [AtomicWaker; GPDMA_CHANNEL_COUNT], +pub(crate) struct ChannelState { + waker: AtomicWaker, } -impl State { - const fn new() -> Self { - const AW: AtomicWaker = AtomicWaker::new(); - Self { - ch_wakers: [AW; GPDMA_CHANNEL_COUNT], - } - } +impl ChannelState { + pub(crate) const NEW: Self = Self { + waker: AtomicWaker::new(), + }; } -static STATE: State = State::new(); - /// safety: must be called only once pub(crate) unsafe fn init(cs: critical_section::CriticalSection, irq_priority: Priority) { foreach_interrupt! { ($peri:ident, gpdma, $block:ident, $signal_name:ident, $irq:ident) => { crate::interrupt::typelevel::$irq::set_priority_with_cs(cs, irq_priority); + #[cfg(not(feature = "_dual-core"))] crate::interrupt::typelevel::$irq::enable(); }; } crate::_generated::init_gpdma(); } -foreach_dma_channel! { - ($channel_peri:ident, $dma_peri:ident, gpdma, $channel_num:expr, $index:expr, $dmamux:tt) => { - impl sealed::Channel for crate::peripherals::$channel_peri { - fn regs(&self) -> pac::gpdma::Gpdma { - pac::$dma_peri - } - fn num(&self) -> usize { - $channel_num - } - fn index(&self) -> usize { - $index - } - fn on_irq() { - unsafe { on_irq_inner(pac::$dma_peri, $channel_num, $index) } - } +impl AnyChannel { + /// Safety: Must be called with a matching set of parameters for a valid dma channel + pub(crate) unsafe fn on_irq(&self) { + let info = self.info(); + #[cfg(feature = "_dual-core")] + { + use embassy_hal_internal::interrupt::InterruptExt as _; + info.irq.enable(); } - impl Channel for crate::peripherals::$channel_peri {} - }; -} + let state = &STATE[self.id as usize]; -/// Safety: Must be called with a matching set of parameters for a valid dma channel -pub(crate) unsafe fn on_irq_inner(dma: pac::gpdma::Gpdma, channel_num: usize, index: usize) { - let ch = dma.ch(channel_num); - let sr = ch.sr().read(); + let ch = info.dma.ch(info.num); + let sr = ch.sr().read(); - if sr.dtef() { - panic!( - "DMA: data transfer error on DMA@{:08x} channel {}", - dma.as_ptr() as u32, - channel_num - ); - } - if sr.usef() { - panic!( - "DMA: user settings error on DMA@{:08x} channel {}", - dma.as_ptr() as u32, - channel_num - ); - } + if sr.dtef() { + panic!( + "DMA: data transfer error on DMA@{:08x} channel {}", + info.dma.as_ptr() as u32, + info.num + ); + } + if sr.usef() { + panic!( + "DMA: user settings error on DMA@{:08x} channel {}", + info.dma.as_ptr() as u32, + info.num + ); + } - if sr.suspf() || sr.tcf() { - // disable all xxIEs to prevent the irq from firing again. - ch.cr().write(|_| {}); + if sr.suspf() || sr.tcf() { + // disable all xxIEs to prevent the irq from firing again. + ch.cr().write(|_| {}); - // Wake the future. It'll look at tcf and see it's set. - STATE.ch_wakers[index].wake(); - } -} - -/// DMA request type alias. (also known as DMA channel number in some chips) -pub type Request = u8; - -/// DMA channel. -#[cfg(dmamux)] -pub trait Channel: sealed::Channel + Peripheral

+ 'static + super::dmamux::MuxChannel {} -/// DMA channel. -#[cfg(not(dmamux))] -pub trait Channel: sealed::Channel + Peripheral

+ 'static {} - -pub(crate) mod sealed { - use super::*; - - pub trait Channel { - fn regs(&self) -> pac::gpdma::Gpdma; - fn num(&self) -> usize; - fn index(&self) -> usize; - fn on_irq(); + // Wake the future. It'll look at tcf and see it's set. + state.waker.wake(); + } } } /// DMA transfer. #[must_use = "futures do nothing unless you `.await` or poll them"] -pub struct Transfer<'a, C: Channel> { - channel: PeripheralRef<'a, C>, +pub struct Transfer<'a> { + channel: PeripheralRef<'a, AnyChannel>, } -impl<'a, C: Channel> Transfer<'a, C> { +impl<'a> Transfer<'a> { /// Create a new read DMA transfer (peripheral to memory). pub unsafe fn new_read( - channel: impl Peripheral

+ 'a, + channel: impl Peripheral

+ 'a, request: Request, peri_addr: *mut W, buf: &'a mut [W], @@ -155,7 +126,7 @@ impl<'a, C: Channel> Transfer<'a, C> { /// Create a new read DMA transfer (peripheral to memory), using raw pointers. pub unsafe fn new_read_raw( - channel: impl Peripheral

+ 'a, + channel: impl Peripheral

+ 'a, request: Request, peri_addr: *mut W, buf: *mut [W], @@ -163,16 +134,13 @@ impl<'a, C: Channel> Transfer<'a, C> { ) -> Self { into_ref!(channel); - let (ptr, len) = super::slice_ptr_parts_mut(buf); - assert!(len > 0 && len <= 0xFFFF); - Self::new_inner( - channel, + channel.map_into(), request, Dir::PeripheralToMemory, peri_addr as *const u32, - ptr as *mut u32, - len, + buf as *mut W as *mut u32, + buf.len(), true, W::size(), options, @@ -181,7 +149,7 @@ impl<'a, C: Channel> Transfer<'a, C> { /// Create a new write DMA transfer (memory to peripheral). pub unsafe fn new_write( - channel: impl Peripheral

+ 'a, + channel: impl Peripheral

+ 'a, request: Request, buf: &'a [W], peri_addr: *mut W, @@ -192,7 +160,7 @@ impl<'a, C: Channel> Transfer<'a, C> { /// Create a new write DMA transfer (memory to peripheral), using raw pointers. pub unsafe fn new_write_raw( - channel: impl Peripheral

+ 'a, + channel: impl Peripheral

+ 'a, request: Request, buf: *const [W], peri_addr: *mut W, @@ -200,16 +168,13 @@ impl<'a, C: Channel> Transfer<'a, C> { ) -> Self { into_ref!(channel); - let (ptr, len) = super::slice_ptr_parts(buf); - assert!(len > 0 && len <= 0xFFFF); - Self::new_inner( - channel, + channel.map_into(), request, Dir::MemoryToPeripheral, peri_addr as *const u32, - ptr as *mut u32, - len, + buf as *const W as *mut u32, + buf.len(), true, W::size(), options, @@ -218,7 +183,7 @@ impl<'a, C: Channel> Transfer<'a, C> { /// Create a new write DMA transfer (memory to peripheral), writing the same value repeatedly. pub unsafe fn new_write_repeated( - channel: impl Peripheral

+ 'a, + channel: impl Peripheral

+ 'a, request: Request, repeated: &'a W, count: usize, @@ -228,7 +193,7 @@ impl<'a, C: Channel> Transfer<'a, C> { into_ref!(channel); Self::new_inner( - channel, + channel.map_into(), request, Dir::MemoryToPeripheral, peri_addr as *const u32, @@ -241,7 +206,7 @@ impl<'a, C: Channel> Transfer<'a, C> { } unsafe fn new_inner( - channel: PeripheralRef<'a, C>, + channel: PeripheralRef<'a, AnyChannel>, request: Request, dir: Dir, peri_addr: *const u32, @@ -251,16 +216,19 @@ impl<'a, C: Channel> Transfer<'a, C> { data_size: WordSize, _options: TransferOptions, ) -> Self { - let ch = channel.regs().ch(channel.num()); + // BNDT is specified as bytes, not as number of transfers. + let Ok(bndt) = (mem_len * data_size.bytes()).try_into() else { + panic!("DMA transfers may not be larger than 65535 bytes."); + }; + + let info = channel.info(); + let ch = info.dma.ch(info.num); // "Preceding reads and writes cannot be moved past subsequent writes." fence(Ordering::SeqCst); let this = Self { channel }; - #[cfg(dmamux)] - super::dmamux::configure_dmamux(&mut *this.channel, request); - ch.cr().write(|w| w.set_reset(true)); ch.fcr().write(|w| w.0 = 0xFFFF_FFFF); // clear all irqs ch.llr().write(|_| {}); // no linked list @@ -272,15 +240,13 @@ impl<'a, C: Channel> Transfer<'a, C> { }); ch.tr2().write(|w| { w.set_dreq(match dir { - Dir::MemoryToPeripheral => vals::ChTr2Dreq::DESTINATIONPERIPHERAL, - Dir::PeripheralToMemory => vals::ChTr2Dreq::SOURCEPERIPHERAL, + Dir::MemoryToPeripheral => vals::Dreq::DESTINATIONPERIPHERAL, + Dir::PeripheralToMemory => vals::Dreq::SOURCEPERIPHERAL, }); w.set_reqsel(request); }); - ch.br1().write(|w| { - // BNDT is specified as bytes, not as number of transfers. - w.set_bndt((mem_len * data_size.bytes()) as u16) - }); + ch.tr3().write(|_| {}); // no address offsets. + ch.br1().write(|w| w.set_bndt(bndt)); match dir { Dir::MemoryToPeripheral => { @@ -311,10 +277,10 @@ impl<'a, C: Channel> Transfer<'a, C> { /// /// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false. pub fn request_stop(&mut self) { - let ch = self.channel.regs().ch(self.channel.num()); - ch.cr().modify(|w| { - w.set_susp(true); - }) + let info = self.channel.info(); + let ch = info.dma.ch(info.num); + + ch.cr().modify(|w| w.set_susp(true)) } /// Return whether this transfer is still running. @@ -322,7 +288,9 @@ impl<'a, C: Channel> Transfer<'a, C> { /// If this returns `false`, it can be because either the transfer finished, or /// it was requested to stop early with [`request_stop`](Self::request_stop). pub fn is_running(&mut self) -> bool { - let ch = self.channel.regs().ch(self.channel.num()); + let info = self.channel.info(); + let ch = info.dma.ch(info.num); + let sr = ch.sr().read(); !sr.tcf() && !sr.suspf() } @@ -330,7 +298,9 @@ impl<'a, C: Channel> Transfer<'a, C> { /// Gets the total remaining transfers for the channel /// Note: this will be zero for transfers that completed without cancellation. pub fn get_remaining_transfers(&self) -> u16 { - let ch = self.channel.regs().ch(self.channel.num()); + let info = self.channel.info(); + let ch = info.dma.ch(info.num); + ch.br1().read().bndt() } @@ -345,7 +315,7 @@ impl<'a, C: Channel> Transfer<'a, C> { } } -impl<'a, C: Channel> Drop for Transfer<'a, C> { +impl<'a> Drop for Transfer<'a> { fn drop(&mut self) { self.request_stop(); while self.is_running() {} @@ -355,11 +325,12 @@ impl<'a, C: Channel> Drop for Transfer<'a, C> { } } -impl<'a, C: Channel> Unpin for Transfer<'a, C> {} -impl<'a, C: Channel> Future for Transfer<'a, C> { +impl<'a> Unpin for Transfer<'a> {} +impl<'a> Future for Transfer<'a> { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - STATE.ch_wakers[self.channel.index()].register(cx.waker()); + let state = &STATE[self.channel.id as usize]; + state.waker.register(cx.waker()); if self.is_running() { Poll::Pending diff --git a/embassy-stm32/src/dma/mod.rs b/embassy-stm32/src/dma/mod.rs index 38945ac33..66c4aa53c 100644 --- a/embassy-stm32/src/dma/mod.rs +++ b/embassy-stm32/src/dma/mod.rs @@ -1,19 +1,10 @@ //! Direct Memory Access (DMA) +#![macro_use] -#[cfg(dma)] -pub(crate) mod dma; -#[cfg(dma)] -pub use dma::*; - -// stm32h7 has both dma and bdma. In that case, we export dma as "main" dma, -// and bdma as "secondary", under `embassy_stm32::dma::bdma`. -#[cfg(all(bdma, dma))] -pub mod bdma; - -#[cfg(all(bdma, not(dma)))] -pub(crate) mod bdma; -#[cfg(all(bdma, not(dma)))] -pub use bdma::*; +#[cfg(any(bdma, dma))] +mod dma_bdma; +#[cfg(any(bdma, dma))] +pub use dma_bdma::*; #[cfg(gpdma)] pub(crate) mod gpdma; @@ -22,17 +13,18 @@ pub use gpdma::*; #[cfg(dmamux)] mod dmamux; +#[cfg(dmamux)] +pub(crate) use dmamux::*; + +mod util; +pub(crate) use util::*; pub(crate) mod ringbuffer; pub mod word; -use core::mem; +use embassy_hal_internal::{impl_peripheral, Peripheral}; -use embassy_hal_internal::impl_peripheral; - -#[cfg(dmamux)] -pub use self::dmamux::*; -use crate::interrupt::Priority; +use crate::interrupt; #[derive(Debug, Copy, Clone, PartialEq, Eq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -41,6 +33,81 @@ enum Dir { PeripheralToMemory, } +/// DMA request type alias. (also known as DMA channel number in some chips) +#[cfg(any(dma_v2, bdma_v2, gpdma, dmamux))] +pub type Request = u8; +/// DMA request type alias. (also known as DMA channel number in some chips) +#[cfg(not(any(dma_v2, bdma_v2, gpdma, dmamux)))] +pub type Request = (); + +pub(crate) trait SealedChannel { + fn id(&self) -> u8; +} + +pub(crate) trait ChannelInterrupt { + #[cfg_attr(not(feature = "rt"), allow(unused))] + unsafe fn on_irq(); +} + +/// DMA channel. +#[allow(private_bounds)] +pub trait Channel: SealedChannel + Peripheral

+ Into + 'static { + /// Type-erase (degrade) this pin into an `AnyChannel`. + /// + /// This converts DMA channel singletons (`DMA1_CH3`, `DMA2_CH1`, ...), which + /// are all different types, into the same type. It is useful for + /// creating arrays of channels, or avoiding generics. + #[inline] + fn degrade(self) -> AnyChannel { + AnyChannel { id: self.id() } + } +} + +macro_rules! dma_channel_impl { + ($channel_peri:ident, $index:expr) => { + impl crate::dma::SealedChannel for crate::peripherals::$channel_peri { + fn id(&self) -> u8 { + $index + } + } + impl crate::dma::ChannelInterrupt for crate::peripherals::$channel_peri { + unsafe fn on_irq() { + crate::dma::AnyChannel { id: $index }.on_irq(); + } + } + + impl crate::dma::Channel for crate::peripherals::$channel_peri {} + + impl From for crate::dma::AnyChannel { + fn from(x: crate::peripherals::$channel_peri) -> Self { + crate::dma::Channel::degrade(x) + } + } + }; +} + +/// Type-erased DMA channel. +pub struct AnyChannel { + pub(crate) id: u8, +} +impl_peripheral!(AnyChannel); + +impl AnyChannel { + fn info(&self) -> &ChannelInfo { + &crate::_generated::DMA_CHANNELS[self.id as usize] + } +} + +impl SealedChannel for AnyChannel { + fn id(&self) -> u8 { + self.id + } +} +impl Channel for AnyChannel {} + +const CHANNEL_COUNT: usize = crate::_generated::DMA_CHANNELS.len(); +static STATE: [ChannelState; CHANNEL_COUNT] = [ChannelState::NEW; CHANNEL_COUNT]; + /// "No DMA" placeholder. /// /// You may pass this in place of a real DMA channel when creating a driver @@ -52,28 +119,21 @@ pub struct NoDma; impl_peripheral!(NoDma); -// TODO: replace transmutes with core::ptr::metadata once it's stable -#[allow(unused)] -pub(crate) fn slice_ptr_parts(slice: *const [T]) -> (usize, usize) { - unsafe { mem::transmute(slice) } -} - -#[allow(unused)] -pub(crate) fn slice_ptr_parts_mut(slice: *mut [T]) -> (usize, usize) { - unsafe { mem::transmute(slice) } -} - // safety: must be called only once at startup pub(crate) unsafe fn init( cs: critical_section::CriticalSection, - #[cfg(bdma)] bdma_priority: Priority, - #[cfg(dma)] dma_priority: Priority, - #[cfg(gpdma)] gpdma_priority: Priority, + #[cfg(bdma)] bdma_priority: interrupt::Priority, + #[cfg(dma)] dma_priority: interrupt::Priority, + #[cfg(gpdma)] gpdma_priority: interrupt::Priority, ) { - #[cfg(bdma)] - bdma::init(cs, bdma_priority); - #[cfg(dma)] - dma::init(cs, dma_priority); + #[cfg(any(dma, bdma))] + dma_bdma::init( + cs, + #[cfg(dma)] + dma_priority, + #[cfg(bdma)] + bdma_priority, + ); #[cfg(gpdma)] gpdma::init(cs, gpdma_priority); #[cfg(dmamux)] diff --git a/embassy-stm32/src/dma/ringbuffer.rs b/embassy-stm32/src/dma/ringbuffer.rs deleted file mode 100644 index c9f7a3026..000000000 --- a/embassy-stm32/src/dma/ringbuffer.rs +++ /dev/null @@ -1,656 +0,0 @@ -#![cfg_attr(gpdma, allow(unused))] - -use core::future::poll_fn; -use core::ops::Range; -use core::sync::atomic::{compiler_fence, Ordering}; -use core::task::{Poll, Waker}; - -use super::word::Word; - -/// A "read-only" ring-buffer to be used together with the DMA controller which -/// writes in a circular way, "uncontrolled" to the buffer. -/// -/// A snapshot of the ring buffer state can be attained by setting the `ndtr` field -/// to the current register value. `ndtr` describes the current position of the DMA -/// write. -/// -/// # Buffer layout -/// -/// ```text -/// Without wraparound: With wraparound: -/// -/// + buf +--- NDTR ---+ + buf +---------- NDTR ----------+ -/// | | | | | | -/// v v v v v v -/// +-----------------------------------------+ +-----------------------------------------+ -/// |oooooooooooXXXXXXXXXXXXXXXXoooooooooooooo| |XXXXXXXXXXXXXooooooooooooXXXXXXXXXXXXXXXX| -/// +-----------------------------------------+ +-----------------------------------------+ -/// ^ ^ ^ ^ ^ ^ -/// | | | | | | -/// +- start --+ | +- end ------+ | -/// | | | | -/// +- end --------------------+ +- start ----------------+ -/// ``` -pub struct ReadableDmaRingBuffer<'a, W: Word> { - pub(crate) dma_buf: &'a mut [W], - start: usize, -} - -#[derive(Debug, PartialEq)] -pub struct OverrunError; - -pub trait DmaCtrl { - /// Get the NDTR register value, i.e. the space left in the underlying - /// buffer until the dma writer wraps. - fn get_remaining_transfers(&self) -> usize; - - /// Get the transfer completed counter. - /// This counter is incremented by the dma controller when NDTR is reloaded, - /// i.e. when the writing wraps. - fn get_complete_count(&self) -> usize; - - /// Reset the transfer completed counter to 0 and return the value just prior to the reset. - fn reset_complete_count(&mut self) -> usize; - - /// Set the waker for a running poll_fn - fn set_waker(&mut self, waker: &Waker); -} - -impl<'a, W: Word> ReadableDmaRingBuffer<'a, W> { - pub fn new(dma_buf: &'a mut [W]) -> Self { - Self { dma_buf, start: 0 } - } - - /// Reset the ring buffer to its initial state - pub fn clear(&mut self, dma: &mut impl DmaCtrl) { - self.start = 0; - dma.reset_complete_count(); - } - - /// The capacity of the ringbuffer - pub const fn cap(&self) -> usize { - self.dma_buf.len() - } - - /// The current position of the ringbuffer - fn pos(&self, dma: &mut impl DmaCtrl) -> usize { - self.cap() - dma.get_remaining_transfers() - } - - /// Read an exact number of elements from the ringbuffer. - /// - /// Returns the remaining number of elements available for immediate reading. - /// OverrunError is returned if the portion to be read was overwritten by the DMA controller. - /// - /// Async/Wake Behavior: - /// The underlying DMA peripheral only can wake us when its buffer pointer has reached the halfway point, - /// and when it wraps around. This means that when called with a buffer of length 'M', when this - /// ring buffer was created with a buffer of size 'N': - /// - If M equals N/2 or N/2 divides evenly into M, this function will return every N/2 elements read on the DMA source. - /// - Otherwise, this function may need up to N/2 extra elements to arrive before returning. - pub async fn read_exact(&mut self, dma: &mut impl DmaCtrl, buffer: &mut [W]) -> Result { - let mut read_data = 0; - let buffer_len = buffer.len(); - - poll_fn(|cx| { - dma.set_waker(cx.waker()); - - compiler_fence(Ordering::SeqCst); - - match self.read(dma, &mut buffer[read_data..buffer_len]) { - Ok((len, remaining)) => { - read_data += len; - if read_data == buffer_len { - Poll::Ready(Ok(remaining)) - } else { - Poll::Pending - } - } - Err(e) => Poll::Ready(Err(e)), - } - }) - .await - } - - /// Read elements from the ring buffer - /// Return a tuple of the length read and the length remaining in the buffer - /// If not all of the elements were read, then there will be some elements in the buffer remaining - /// The length remaining is the capacity, ring_buf.len(), less the elements remaining after the read - /// OverrunError is returned if the portion to be read was overwritten by the DMA controller. - pub fn read(&mut self, dma: &mut impl DmaCtrl, buf: &mut [W]) -> Result<(usize, usize), OverrunError> { - /* - This algorithm is optimistic: we assume we haven't overrun more than a full buffer and then check - after we've done our work to see we have. This is because on stm32, an interrupt is not guaranteed - to fire in the same clock cycle that a register is read, so checking get_complete_count early does - not yield relevant information. - - Therefore, the only variable we really need to know is ndtr. If the dma has overrun by more than a full - buffer, we will do a bit more work than we have to, but algorithms should not be optimized for error - conditions. - - After we've done our work, we confirm that we haven't overrun more than a full buffer, and also that - the dma has not overrun within the data we could have copied. We check the data we could have copied - rather than the data we actually copied because it costs nothing and confirms an error condition - earlier. - */ - let end = self.pos(dma); - if self.start == end && dma.get_complete_count() == 0 { - // No elements are available in the buffer - Ok((0, self.cap())) - } else if self.start < end { - // The available, unread portion in the ring buffer DOES NOT wrap - // Copy out the elements from the dma buffer - let len = self.copy_to(buf, self.start..end); - - compiler_fence(Ordering::SeqCst); - - /* - first, check if the dma has wrapped at all if it's after end - or more than once if it's before start - - this is in a critical section to try to reduce mushy behavior. - it's not ideal but it's the best we can do - - then, get the current position of of the dma write and check - if it's inside data we could have copied - */ - let (pos, complete_count) = critical_section::with(|_| (self.pos(dma), dma.get_complete_count())); - if (pos >= self.start && pos < end) || (complete_count > 0 && pos >= end) || complete_count > 1 { - Err(OverrunError) - } else { - self.start = (self.start + len) % self.cap(); - - Ok((len, self.cap() - self.start)) - } - } else if self.start + buf.len() < self.cap() { - // The available, unread portion in the ring buffer DOES wrap - // The DMA writer has wrapped since we last read and is currently - // writing (or the next byte added will be) in the beginning of the ring buffer. - - // The provided read buffer is not large enough to include all elements from the tail of the dma buffer. - - // Copy out from the dma buffer - let len = self.copy_to(buf, self.start..self.cap()); - - compiler_fence(Ordering::SeqCst); - - /* - first, check if the dma has wrapped around more than once - - then, get the current position of of the dma write and check - if it's inside data we could have copied - */ - let pos = self.pos(dma); - if pos > self.start || pos < end || dma.get_complete_count() > 1 { - Err(OverrunError) - } else { - self.start = (self.start + len) % self.cap(); - - Ok((len, self.start + end)) - } - } else { - // The available, unread portion in the ring buffer DOES wrap - // The DMA writer has wrapped since we last read and is currently - // writing (or the next byte added will be) in the beginning of the ring buffer. - - // The provided read buffer is large enough to include all elements from the tail of the dma buffer, - // so the next read will not have any unread tail elements in the ring buffer. - - // Copy out from the dma buffer - let tail = self.copy_to(buf, self.start..self.cap()); - let head = self.copy_to(&mut buf[tail..], 0..end); - - compiler_fence(Ordering::SeqCst); - - /* - first, check if the dma has wrapped around more than once - - then, get the current position of of the dma write and check - if it's inside data we could have copied - */ - let pos = self.pos(dma); - if pos > self.start || pos < end || dma.reset_complete_count() > 1 { - Err(OverrunError) - } else { - self.start = head; - Ok((tail + head, self.cap() - self.start)) - } - } - } - /// Copy from the dma buffer at `data_range` into `buf` - fn copy_to(&mut self, buf: &mut [W], data_range: Range) -> usize { - // Limit the number of elements that can be copied - let length = usize::min(data_range.len(), buf.len()); - - // Copy from dma buffer into read buffer - // We need to do it like this instead of a simple copy_from_slice() because - // reading from a part of memory that may be simultaneously written to is unsafe - unsafe { - let dma_buf = self.dma_buf.as_ptr(); - - for i in 0..length { - buf[i] = core::ptr::read_volatile(dma_buf.offset((data_range.start + i) as isize)); - } - } - - length - } -} - -pub struct WritableDmaRingBuffer<'a, W: Word> { - pub(crate) dma_buf: &'a mut [W], - end: usize, -} - -impl<'a, W: Word> WritableDmaRingBuffer<'a, W> { - pub fn new(dma_buf: &'a mut [W]) -> Self { - Self { dma_buf, end: 0 } - } - - /// Reset the ring buffer to its initial state - pub fn clear(&mut self, dma: &mut impl DmaCtrl) { - self.end = 0; - dma.reset_complete_count(); - } - - /// The capacity of the ringbuffer - pub const fn cap(&self) -> usize { - self.dma_buf.len() - } - - /// The current position of the ringbuffer - fn pos(&self, dma: &mut impl DmaCtrl) -> usize { - self.cap() - dma.get_remaining_transfers() - } - - /// Write an exact number of elements to the ringbuffer. - pub async fn write_exact(&mut self, dma: &mut impl DmaCtrl, buffer: &[W]) -> Result { - let mut written_data = 0; - let buffer_len = buffer.len(); - - poll_fn(|cx| { - dma.set_waker(cx.waker()); - - compiler_fence(Ordering::SeqCst); - - match self.write(dma, &buffer[written_data..buffer_len]) { - Ok((len, remaining)) => { - written_data += len; - if written_data == buffer_len { - Poll::Ready(Ok(remaining)) - } else { - Poll::Pending - } - } - Err(e) => Poll::Ready(Err(e)), - } - }) - .await - } - - /// Write elements from the ring buffer - /// Return a tuple of the length written and the capacity remaining to be written in the buffer - pub fn write(&mut self, dma: &mut impl DmaCtrl, buf: &[W]) -> Result<(usize, usize), OverrunError> { - let start = self.pos(dma); - if start > self.end { - // The occupied portion in the ring buffer DOES wrap - let len = self.copy_from(buf, self.end..start); - - compiler_fence(Ordering::SeqCst); - - // Confirm that the DMA is not inside data we could have written - let (pos, complete_count) = critical_section::with(|_| (self.pos(dma), dma.get_complete_count())); - if (pos >= self.end && pos < start) || (complete_count > 0 && pos >= start) || complete_count > 1 { - Err(OverrunError) - } else { - self.end = (self.end + len) % self.cap(); - - Ok((len, self.cap() - (start - self.end))) - } - } else if start == self.end && dma.get_complete_count() == 0 { - Ok((0, 0)) - } else if start <= self.end && self.end + buf.len() < self.cap() { - // The occupied portion in the ring buffer DOES NOT wrap - // and copying elements into the buffer WILL NOT cause it to - - // Copy into the dma buffer - let len = self.copy_from(buf, self.end..self.cap()); - - compiler_fence(Ordering::SeqCst); - - // Confirm that the DMA is not inside data we could have written - let pos = self.pos(dma); - if pos > self.end || pos < start || dma.get_complete_count() > 1 { - Err(OverrunError) - } else { - self.end = (self.end + len) % self.cap(); - - Ok((len, self.cap() - (self.end - start))) - } - } else { - // The occupied portion in the ring buffer DOES NOT wrap - // and copying elements into the buffer WILL cause it to - - let tail = self.copy_from(buf, self.end..self.cap()); - let head = self.copy_from(&buf[tail..], 0..start); - - compiler_fence(Ordering::SeqCst); - - // Confirm that the DMA is not inside data we could have written - let pos = self.pos(dma); - if pos > self.end || pos < start || dma.reset_complete_count() > 1 { - Err(OverrunError) - } else { - self.end = head; - - Ok((tail + head, self.cap() - (start - self.end))) - } - } - } - /// Copy into the dma buffer at `data_range` from `buf` - fn copy_from(&mut self, buf: &[W], data_range: Range) -> usize { - // Limit the number of elements that can be copied - let length = usize::min(data_range.len(), buf.len()); - - // Copy into dma buffer from read buffer - // We need to do it like this instead of a simple copy_from_slice() because - // reading from a part of memory that may be simultaneously written to is unsafe - unsafe { - let dma_buf = self.dma_buf.as_mut_ptr(); - - for i in 0..length { - core::ptr::write_volatile(dma_buf.offset((data_range.start + i) as isize), buf[i]); - } - } - - length - } -} -#[cfg(test)] -mod tests { - use core::array; - use std::{cell, vec}; - - use super::*; - - #[allow(dead_code)] - #[derive(PartialEq, Debug)] - enum TestCircularTransferRequest { - GetCompleteCount(usize), - ResetCompleteCount(usize), - PositionRequest(usize), - } - - struct TestCircularTransfer { - len: usize, - requests: cell::RefCell>, - } - - impl DmaCtrl for TestCircularTransfer { - fn get_remaining_transfers(&self) -> usize { - match self.requests.borrow_mut().pop().unwrap() { - TestCircularTransferRequest::PositionRequest(pos) => { - let len = self.len; - - assert!(len >= pos); - - len - pos - } - _ => unreachable!(), - } - } - - fn get_complete_count(&self) -> usize { - match self.requests.borrow_mut().pop().unwrap() { - TestCircularTransferRequest::GetCompleteCount(complete_count) => complete_count, - _ => unreachable!(), - } - } - - fn reset_complete_count(&mut self) -> usize { - match self.requests.get_mut().pop().unwrap() { - TestCircularTransferRequest::ResetCompleteCount(complete_count) => complete_count, - _ => unreachable!(), - } - } - - fn set_waker(&mut self, waker: &Waker) {} - } - - impl TestCircularTransfer { - pub fn new(len: usize) -> Self { - Self { - requests: cell::RefCell::new(vec![]), - len, - } - } - - pub fn setup(&self, mut requests: vec::Vec) { - requests.reverse(); - self.requests.replace(requests); - } - } - - #[test] - fn empty_and_read_not_started() { - let mut dma_buf = [0u8; 16]; - let ringbuf = ReadableDmaRingBuffer::new(&mut dma_buf); - - assert_eq!(0, ringbuf.start); - } - - #[test] - fn can_read() { - let mut dma = TestCircularTransfer::new(16); - - let mut dma_buf: [u8; 16] = array::from_fn(|idx| idx as u8); // 0, 1, ..., 15 - let mut ringbuf = ReadableDmaRingBuffer::new(&mut dma_buf); - - assert_eq!(0, ringbuf.start); - assert_eq!(16, ringbuf.cap()); - - dma.setup(vec![ - TestCircularTransferRequest::PositionRequest(8), - TestCircularTransferRequest::PositionRequest(10), - TestCircularTransferRequest::GetCompleteCount(0), - ]); - let mut buf = [0; 2]; - assert_eq!(2, ringbuf.read(&mut dma, &mut buf).unwrap().0); - assert_eq!([0, 1], buf); - assert_eq!(2, ringbuf.start); - - dma.setup(vec![ - TestCircularTransferRequest::PositionRequest(10), - TestCircularTransferRequest::PositionRequest(12), - TestCircularTransferRequest::GetCompleteCount(0), - ]); - let mut buf = [0; 2]; - assert_eq!(2, ringbuf.read(&mut dma, &mut buf).unwrap().0); - assert_eq!([2, 3], buf); - assert_eq!(4, ringbuf.start); - - dma.setup(vec![ - TestCircularTransferRequest::PositionRequest(12), - TestCircularTransferRequest::PositionRequest(14), - TestCircularTransferRequest::GetCompleteCount(0), - ]); - let mut buf = [0; 8]; - assert_eq!(8, ringbuf.read(&mut dma, &mut buf).unwrap().0); - assert_eq!([4, 5, 6, 7, 8, 9], buf[..6]); - assert_eq!(12, ringbuf.start); - } - - #[test] - fn can_read_with_wrap() { - let mut dma = TestCircularTransfer::new(16); - - let mut dma_buf: [u8; 16] = array::from_fn(|idx| idx as u8); // 0, 1, ..., 15 - let mut ringbuf = ReadableDmaRingBuffer::new(&mut dma_buf); - - assert_eq!(0, ringbuf.start); - assert_eq!(16, ringbuf.cap()); - - /* - Read to close to the end of the buffer - */ - dma.setup(vec![ - TestCircularTransferRequest::PositionRequest(14), - TestCircularTransferRequest::PositionRequest(16), - TestCircularTransferRequest::GetCompleteCount(0), - ]); - let mut buf = [0; 14]; - assert_eq!(14, ringbuf.read(&mut dma, &mut buf).unwrap().0); - assert_eq!(14, ringbuf.start); - - /* - Now, read around the buffer - */ - dma.setup(vec![ - TestCircularTransferRequest::PositionRequest(6), - TestCircularTransferRequest::PositionRequest(8), - TestCircularTransferRequest::ResetCompleteCount(1), - ]); - let mut buf = [0; 6]; - assert_eq!(6, ringbuf.read(&mut dma, &mut buf).unwrap().0); - assert_eq!(4, ringbuf.start); - } - - #[test] - fn can_read_when_dma_writer_is_wrapped_and_read_does_not_wrap() { - let mut dma = TestCircularTransfer::new(16); - - let mut dma_buf: [u8; 16] = array::from_fn(|idx| idx as u8); // 0, 1, ..., 15 - let mut ringbuf = ReadableDmaRingBuffer::new(&mut dma_buf); - - assert_eq!(0, ringbuf.start); - assert_eq!(16, ringbuf.cap()); - - /* - Read to close to the end of the buffer - */ - dma.setup(vec![ - TestCircularTransferRequest::PositionRequest(14), - TestCircularTransferRequest::PositionRequest(16), - TestCircularTransferRequest::GetCompleteCount(0), - ]); - let mut buf = [0; 14]; - assert_eq!(14, ringbuf.read(&mut dma, &mut buf).unwrap().0); - assert_eq!(14, ringbuf.start); - - /* - Now, read to the end of the buffer - */ - dma.setup(vec![ - TestCircularTransferRequest::PositionRequest(6), - TestCircularTransferRequest::PositionRequest(8), - TestCircularTransferRequest::ResetCompleteCount(1), - ]); - let mut buf = [0; 2]; - assert_eq!(2, ringbuf.read(&mut dma, &mut buf).unwrap().0); - assert_eq!(0, ringbuf.start); - } - - #[test] - fn can_read_when_dma_writer_wraps_once_with_same_ndtr() { - let mut dma = TestCircularTransfer::new(16); - - let mut dma_buf: [u8; 16] = array::from_fn(|idx| idx as u8); // 0, 1, ..., 15 - let mut ringbuf = ReadableDmaRingBuffer::new(&mut dma_buf); - - assert_eq!(0, ringbuf.start); - assert_eq!(16, ringbuf.cap()); - - /* - Read to about the middle of the buffer - */ - dma.setup(vec![ - TestCircularTransferRequest::PositionRequest(6), - TestCircularTransferRequest::PositionRequest(6), - TestCircularTransferRequest::GetCompleteCount(0), - ]); - let mut buf = [0; 6]; - assert_eq!(6, ringbuf.read(&mut dma, &mut buf).unwrap().0); - assert_eq!(6, ringbuf.start); - - /* - Now, wrap the DMA controller around - */ - dma.setup(vec![ - TestCircularTransferRequest::PositionRequest(6), - TestCircularTransferRequest::GetCompleteCount(1), - TestCircularTransferRequest::PositionRequest(6), - TestCircularTransferRequest::GetCompleteCount(1), - ]); - let mut buf = [0; 6]; - assert_eq!(6, ringbuf.read(&mut dma, &mut buf).unwrap().0); - assert_eq!(12, ringbuf.start); - } - - #[test] - fn cannot_read_when_dma_writer_overwrites_during_not_wrapping_read() { - let mut dma = TestCircularTransfer::new(16); - - let mut dma_buf: [u8; 16] = array::from_fn(|idx| idx as u8); // 0, 1, ..., 15 - let mut ringbuf = ReadableDmaRingBuffer::new(&mut dma_buf); - - assert_eq!(0, ringbuf.start); - assert_eq!(16, ringbuf.cap()); - - /* - Read a few bytes - */ - dma.setup(vec![ - TestCircularTransferRequest::PositionRequest(2), - TestCircularTransferRequest::PositionRequest(2), - TestCircularTransferRequest::GetCompleteCount(0), - ]); - let mut buf = [0; 6]; - assert_eq!(2, ringbuf.read(&mut dma, &mut buf).unwrap().0); - assert_eq!(2, ringbuf.start); - - /* - Now, overtake the reader - */ - dma.setup(vec![ - TestCircularTransferRequest::PositionRequest(4), - TestCircularTransferRequest::PositionRequest(6), - TestCircularTransferRequest::GetCompleteCount(1), - ]); - let mut buf = [0; 6]; - assert_eq!(OverrunError, ringbuf.read(&mut dma, &mut buf).unwrap_err()); - } - - #[test] - fn cannot_read_when_dma_writer_overwrites_during_wrapping_read() { - let mut dma = TestCircularTransfer::new(16); - - let mut dma_buf: [u8; 16] = array::from_fn(|idx| idx as u8); // 0, 1, ..., 15 - let mut ringbuf = ReadableDmaRingBuffer::new(&mut dma_buf); - - assert_eq!(0, ringbuf.start); - assert_eq!(16, ringbuf.cap()); - - /* - Read to close to the end of the buffer - */ - dma.setup(vec![ - TestCircularTransferRequest::PositionRequest(14), - TestCircularTransferRequest::PositionRequest(16), - TestCircularTransferRequest::GetCompleteCount(0), - ]); - let mut buf = [0; 14]; - assert_eq!(14, ringbuf.read(&mut dma, &mut buf).unwrap().0); - assert_eq!(14, ringbuf.start); - - /* - Now, overtake the reader - */ - dma.setup(vec![ - TestCircularTransferRequest::PositionRequest(8), - TestCircularTransferRequest::PositionRequest(10), - TestCircularTransferRequest::ResetCompleteCount(2), - ]); - let mut buf = [0; 6]; - assert_eq!(OverrunError, ringbuf.read(&mut dma, &mut buf).unwrap_err()); - } -} diff --git a/embassy-stm32/src/dma/ringbuffer/mod.rs b/embassy-stm32/src/dma/ringbuffer/mod.rs new file mode 100644 index 000000000..0da8c374f --- /dev/null +++ b/embassy-stm32/src/dma/ringbuffer/mod.rs @@ -0,0 +1,309 @@ +#![cfg_attr(gpdma, allow(unused))] + +use core::future::poll_fn; +use core::task::{Poll, Waker}; + +use crate::dma::word::Word; + +pub trait DmaCtrl { + /// Get the NDTR register value, i.e. the space left in the underlying + /// buffer until the dma writer wraps. + fn get_remaining_transfers(&self) -> usize; + + /// Reset the transfer completed counter to 0 and return the value just prior to the reset. + fn reset_complete_count(&mut self) -> usize; + + /// Set the waker for a running poll_fn + fn set_waker(&mut self, waker: &Waker); +} + +#[derive(Debug, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Error { + Overrun, + /// the newly read DMA positions don't make sense compared to the previous + /// ones. This can usually only occur due to wrong Driver implementation, if + /// the driver author (or the user using raw metapac code) directly resets + /// the channel for instance. + DmaUnsynced, +} + +#[derive(Debug, Clone, Copy, Default)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +struct DmaIndex { + complete_count: usize, + pos: usize, +} + +impl DmaIndex { + fn reset(&mut self) { + self.pos = 0; + self.complete_count = 0; + } + + fn as_index(&self, cap: usize, offset: usize) -> usize { + (self.pos + offset) % cap + } + + fn dma_sync(&mut self, cap: usize, dma: &mut impl DmaCtrl) { + // Important! + // The ordering of the first two lines matters! + // If changed, the code will detect a wrong +capacity + // jump at wrap-around. + let count_diff = dma.reset_complete_count(); + let pos = cap - dma.get_remaining_transfers(); + self.pos = if pos < self.pos && count_diff == 0 { + cap - 1 + } else { + pos + }; + + self.complete_count += count_diff; + } + + fn advance(&mut self, cap: usize, steps: usize) { + let next = self.pos + steps; + self.complete_count += next / cap; + self.pos = next % cap; + } + + fn normalize(lhs: &mut DmaIndex, rhs: &mut DmaIndex) { + let min_count = lhs.complete_count.min(rhs.complete_count); + lhs.complete_count -= min_count; + rhs.complete_count -= min_count; + } + + fn diff(&self, cap: usize, rhs: &DmaIndex) -> isize { + (self.complete_count * cap + self.pos) as isize - (rhs.complete_count * cap + rhs.pos) as isize + } +} + +pub struct ReadableDmaRingBuffer<'a, W: Word> { + dma_buf: &'a mut [W], + write_index: DmaIndex, + read_index: DmaIndex, +} + +impl<'a, W: Word> ReadableDmaRingBuffer<'a, W> { + /// Construct an empty buffer. + pub fn new(dma_buf: &'a mut [W]) -> Self { + Self { + dma_buf, + write_index: Default::default(), + read_index: Default::default(), + } + } + + /// Reset the ring buffer to its initial state. + pub fn reset(&mut self, dma: &mut impl DmaCtrl) { + dma.reset_complete_count(); + self.write_index.reset(); + self.write_index.dma_sync(self.cap(), dma); + self.read_index = self.write_index; + } + + /// Get the full ringbuffer capacity. + pub const fn cap(&self) -> usize { + self.dma_buf.len() + } + + /// Get the available readable dma samples. + pub fn len(&mut self, dma: &mut impl DmaCtrl) -> Result { + self.write_index.dma_sync(self.cap(), dma); + DmaIndex::normalize(&mut self.write_index, &mut self.read_index); + + let diff = self.write_index.diff(self.cap(), &self.read_index); + + if diff < 0 { + Err(Error::DmaUnsynced) + } else if diff > self.cap() as isize { + Err(Error::Overrun) + } else { + Ok(diff as usize) + } + } + + /// Read elements from the ring buffer. + /// + /// Return a tuple of the length read and the length remaining in the buffer + /// If not all of the elements were read, then there will be some elements in the buffer remaining + /// The length remaining is the capacity, ring_buf.len(), less the elements remaining after the read + /// Error is returned if the portion to be read was overwritten by the DMA controller, + /// in which case the rinbuffer will automatically reset itself. + pub fn read(&mut self, dma: &mut impl DmaCtrl, buf: &mut [W]) -> Result<(usize, usize), Error> { + self.read_raw(dma, buf).inspect_err(|_e| { + self.reset(dma); + }) + } + + /// Read an exact number of elements from the ringbuffer. + /// + /// Returns the remaining number of elements available for immediate reading. + /// Error is returned if the portion to be read was overwritten by the DMA controller. + /// + /// Async/Wake Behavior: + /// The underlying DMA peripheral only can wake us when its buffer pointer has reached the halfway point, + /// and when it wraps around. This means that when called with a buffer of length 'M', when this + /// ring buffer was created with a buffer of size 'N': + /// - If M equals N/2 or N/2 divides evenly into M, this function will return every N/2 elements read on the DMA source. + /// - Otherwise, this function may need up to N/2 extra elements to arrive before returning. + pub async fn read_exact(&mut self, dma: &mut impl DmaCtrl, buffer: &mut [W]) -> Result { + let mut read_data = 0; + let buffer_len = buffer.len(); + + poll_fn(|cx| { + dma.set_waker(cx.waker()); + + match self.read(dma, &mut buffer[read_data..buffer_len]) { + Ok((len, remaining)) => { + read_data += len; + if read_data == buffer_len { + Poll::Ready(Ok(remaining)) + } else { + Poll::Pending + } + } + Err(e) => Poll::Ready(Err(e)), + } + }) + .await + } + + fn read_raw(&mut self, dma: &mut impl DmaCtrl, buf: &mut [W]) -> Result<(usize, usize), Error> { + let readable = self.len(dma)?.min(buf.len()); + for i in 0..readable { + buf[i] = self.read_buf(i); + } + let available = self.len(dma)?; + self.read_index.advance(self.cap(), readable); + Ok((readable, available - readable)) + } + + fn read_buf(&self, offset: usize) -> W { + unsafe { + core::ptr::read_volatile( + self.dma_buf + .as_ptr() + .offset(self.read_index.as_index(self.cap(), offset) as isize), + ) + } + } +} + +pub struct WritableDmaRingBuffer<'a, W: Word> { + dma_buf: &'a mut [W], + read_index: DmaIndex, + write_index: DmaIndex, +} + +impl<'a, W: Word> WritableDmaRingBuffer<'a, W> { + /// Construct a ringbuffer filled with the given buffer data. + pub fn new(dma_buf: &'a mut [W]) -> Self { + let len = dma_buf.len(); + Self { + dma_buf, + read_index: Default::default(), + write_index: DmaIndex { + complete_count: 0, + pos: len, + }, + } + } + + /// Reset the ring buffer to its initial state. The buffer after the reset will be full. + pub fn reset(&mut self, dma: &mut impl DmaCtrl) { + dma.reset_complete_count(); + self.read_index.reset(); + self.read_index.dma_sync(self.cap(), dma); + self.write_index = self.read_index; + self.write_index.advance(self.cap(), self.cap()); + } + + /// Get the remaining writable dma samples. + pub fn len(&mut self, dma: &mut impl DmaCtrl) -> Result { + self.read_index.dma_sync(self.cap(), dma); + DmaIndex::normalize(&mut self.read_index, &mut self.write_index); + + let diff = self.write_index.diff(self.cap(), &self.read_index); + + if diff < 0 { + Err(Error::Overrun) + } else if diff > self.cap() as isize { + Err(Error::DmaUnsynced) + } else { + Ok(self.cap().saturating_sub(diff as usize)) + } + } + + /// Get the full ringbuffer capacity. + pub const fn cap(&self) -> usize { + self.dma_buf.len() + } + + /// Append data to the ring buffer. + /// Returns a tuple of the data written and the remaining write capacity in the buffer. + /// Error is returned if the portion to be written was previously read by the DMA controller. + /// In this case, the ringbuffer will automatically reset itself, giving a full buffer worth of + /// leeway between the write index and the DMA. + pub fn write(&mut self, dma: &mut impl DmaCtrl, buf: &[W]) -> Result<(usize, usize), Error> { + self.write_raw(dma, buf).inspect_err(|_e| { + self.reset(dma); + }) + } + + /// Write elements directly to the buffer. + pub fn write_immediate(&mut self, buf: &[W]) -> Result<(usize, usize), Error> { + for (i, data) in buf.iter().enumerate() { + self.write_buf(i, *data) + } + let written = buf.len().min(self.cap()); + Ok((written, self.cap() - written)) + } + + /// Write an exact number of elements to the ringbuffer. + pub async fn write_exact(&mut self, dma: &mut impl DmaCtrl, buffer: &[W]) -> Result { + let mut written_data = 0; + let buffer_len = buffer.len(); + + poll_fn(|cx| { + dma.set_waker(cx.waker()); + + match self.write(dma, &buffer[written_data..buffer_len]) { + Ok((len, remaining)) => { + written_data += len; + if written_data == buffer_len { + Poll::Ready(Ok(remaining)) + } else { + Poll::Pending + } + } + Err(e) => Poll::Ready(Err(e)), + } + }) + .await + } + + fn write_raw(&mut self, dma: &mut impl DmaCtrl, buf: &[W]) -> Result<(usize, usize), Error> { + let writable = self.len(dma)?.min(buf.len()); + for i in 0..writable { + self.write_buf(i, buf[i]); + } + let available = self.len(dma)?; + self.write_index.advance(self.cap(), writable); + Ok((writable, available - writable)) + } + + fn write_buf(&mut self, offset: usize, value: W) { + unsafe { + core::ptr::write_volatile( + self.dma_buf + .as_mut_ptr() + .offset(self.write_index.as_index(self.cap(), offset) as isize), + value, + ) + } + } +} + +#[cfg(test)] +mod tests; diff --git a/embassy-stm32/src/dma/ringbuffer/tests/mod.rs b/embassy-stm32/src/dma/ringbuffer/tests/mod.rs new file mode 100644 index 000000000..6fabedb83 --- /dev/null +++ b/embassy-stm32/src/dma/ringbuffer/tests/mod.rs @@ -0,0 +1,90 @@ +use std::{cell, vec}; + +use super::*; + +#[allow(unused)] +#[derive(PartialEq, Debug)] +enum TestCircularTransferRequest { + ResetCompleteCount(usize), + PositionRequest(usize), +} + +#[allow(unused)] +struct TestCircularTransfer { + len: usize, + requests: cell::RefCell>, +} + +impl DmaCtrl for TestCircularTransfer { + fn get_remaining_transfers(&self) -> usize { + match self.requests.borrow_mut().pop().unwrap() { + TestCircularTransferRequest::PositionRequest(pos) => { + let len = self.len; + + assert!(len >= pos); + + len - pos + } + _ => unreachable!(), + } + } + + fn reset_complete_count(&mut self) -> usize { + match self.requests.get_mut().pop().unwrap() { + TestCircularTransferRequest::ResetCompleteCount(complete_count) => complete_count, + _ => unreachable!(), + } + } + + fn set_waker(&mut self, _waker: &Waker) {} +} + +impl TestCircularTransfer { + #[allow(unused)] + pub fn new(len: usize) -> Self { + Self { + requests: cell::RefCell::new(vec![]), + len, + } + } + + #[allow(unused)] + pub fn setup(&self, mut requests: vec::Vec) { + requests.reverse(); + self.requests.replace(requests); + } +} + +const CAP: usize = 16; + +#[test] +fn dma_index_as_index_returns_index_mod_cap_by_default() { + let index = DmaIndex::default(); + assert_eq!(index.as_index(CAP, 0), 0); + assert_eq!(index.as_index(CAP, 1), 1); + assert_eq!(index.as_index(CAP, 2), 2); + assert_eq!(index.as_index(CAP, 3), 3); + assert_eq!(index.as_index(CAP, 4), 4); + assert_eq!(index.as_index(CAP, CAP), 0); + assert_eq!(index.as_index(CAP, CAP + 1), 1); +} + +#[test] +fn dma_index_advancing_increases_as_index() { + let mut index = DmaIndex::default(); + assert_eq!(index.as_index(CAP, 0), 0); + index.advance(CAP, 1); + assert_eq!(index.as_index(CAP, 0), 1); + index.advance(CAP, 1); + assert_eq!(index.as_index(CAP, 0), 2); + index.advance(CAP, 1); + assert_eq!(index.as_index(CAP, 0), 3); + index.advance(CAP, 1); + assert_eq!(index.as_index(CAP, 0), 4); + index.advance(CAP, CAP - 4); + assert_eq!(index.as_index(CAP, 0), 0); + index.advance(CAP, 1); + assert_eq!(index.as_index(CAP, 0), 1); +} + +mod prop_test; diff --git a/embassy-stm32/src/dma/ringbuffer/tests/prop_test/mod.rs b/embassy-stm32/src/dma/ringbuffer/tests/prop_test/mod.rs new file mode 100644 index 000000000..661fb1728 --- /dev/null +++ b/embassy-stm32/src/dma/ringbuffer/tests/prop_test/mod.rs @@ -0,0 +1,50 @@ +use std::task::Waker; + +use proptest::prop_oneof; +use proptest::strategy::{self, BoxedStrategy, Strategy as _}; +use proptest_state_machine::{prop_state_machine, ReferenceStateMachine, StateMachineTest}; + +use super::*; + +const CAP: usize = 128; + +#[derive(Debug, Default)] +struct DmaMock { + pos: usize, + wraps: usize, +} + +impl DmaMock { + pub fn advance(&mut self, steps: usize) { + let next = self.pos + steps; + self.pos = next % CAP; + self.wraps += next / CAP; + } +} + +impl DmaCtrl for DmaMock { + fn get_remaining_transfers(&self) -> usize { + CAP - self.pos + } + + fn reset_complete_count(&mut self) -> usize { + core::mem::replace(&mut self.wraps, 0) + } + + fn set_waker(&mut self, _waker: &Waker) {} +} + +#[derive(Debug, Clone)] +enum Status { + Available(usize), + Failed, +} + +impl Status { + pub fn new(capacity: usize) -> Self { + Self::Available(capacity) + } +} + +mod reader; +mod writer; diff --git a/embassy-stm32/src/dma/ringbuffer/tests/prop_test/reader.rs b/embassy-stm32/src/dma/ringbuffer/tests/prop_test/reader.rs new file mode 100644 index 000000000..4f3957a68 --- /dev/null +++ b/embassy-stm32/src/dma/ringbuffer/tests/prop_test/reader.rs @@ -0,0 +1,123 @@ +use core::fmt::Debug; + +use super::*; + +#[derive(Debug, Clone)] +enum ReaderTransition { + Write(usize), + Reset, + ReadUpTo(usize), +} + +struct ReaderSM; + +impl ReferenceStateMachine for ReaderSM { + type State = Status; + type Transition = ReaderTransition; + + fn init_state() -> BoxedStrategy { + strategy::Just(Status::new(0)).boxed() + } + + fn transitions(_state: &Self::State) -> BoxedStrategy { + prop_oneof![ + (1..50_usize).prop_map(ReaderTransition::Write), + (1..50_usize).prop_map(ReaderTransition::ReadUpTo), + strategy::Just(ReaderTransition::Reset), + ] + .boxed() + } + + fn apply(status: Self::State, transition: &Self::Transition) -> Self::State { + match (status, transition) { + (_, ReaderTransition::Reset) => Status::Available(0), + (Status::Available(x), ReaderTransition::Write(y)) => { + if x + y > CAP { + Status::Failed + } else { + Status::Available(x + y) + } + } + (Status::Failed, ReaderTransition::Write(_)) => Status::Failed, + (Status::Available(x), ReaderTransition::ReadUpTo(y)) => Status::Available(x.saturating_sub(*y)), + (Status::Failed, ReaderTransition::ReadUpTo(_)) => Status::Available(0), + } + } +} + +struct ReaderSut { + status: Status, + buffer: *mut [u8], + producer: DmaMock, + consumer: ReadableDmaRingBuffer<'static, u8>, +} + +impl Debug for ReaderSut { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + ::fmt(&self.producer, f) + } +} + +struct ReaderTest; + +impl StateMachineTest for ReaderTest { + type SystemUnderTest = ReaderSut; + type Reference = ReaderSM; + + fn init_test(ref_status: &::State) -> Self::SystemUnderTest { + let buffer = Box::into_raw(Box::new([0; CAP])); + ReaderSut { + status: ref_status.clone(), + buffer, + producer: DmaMock::default(), + consumer: ReadableDmaRingBuffer::new(unsafe { &mut *buffer }), + } + } + + fn teardown(state: Self::SystemUnderTest) { + unsafe { + let _ = Box::from_raw(state.buffer); + }; + } + + fn apply( + mut sut: Self::SystemUnderTest, + ref_state: &::State, + transition: ::Transition, + ) -> Self::SystemUnderTest { + match transition { + ReaderTransition::Write(x) => sut.producer.advance(x), + ReaderTransition::Reset => { + sut.consumer.reset(&mut sut.producer); + } + ReaderTransition::ReadUpTo(x) => { + let status = sut.status; + let ReaderSut { + ref mut producer, + ref mut consumer, + .. + } = sut; + let mut buf = vec![0; x]; + let res = consumer.read(producer, &mut buf); + match status { + Status::Available(n) => { + let readable = x.min(n); + + assert_eq!(res.unwrap().0, readable); + } + Status::Failed => assert!(res.is_err()), + } + } + } + + ReaderSut { + status: ref_state.clone(), + ..sut + } + } +} + +prop_state_machine! { + #[test] + fn reader_state_test(sequential 1..20 => ReaderTest); +} diff --git a/embassy-stm32/src/dma/ringbuffer/tests/prop_test/writer.rs b/embassy-stm32/src/dma/ringbuffer/tests/prop_test/writer.rs new file mode 100644 index 000000000..15433c0ee --- /dev/null +++ b/embassy-stm32/src/dma/ringbuffer/tests/prop_test/writer.rs @@ -0,0 +1,122 @@ +use core::fmt::Debug; + +use super::*; + +#[derive(Debug, Clone)] +enum WriterTransition { + Read(usize), + WriteUpTo(usize), + Reset, +} + +struct WriterSM; + +impl ReferenceStateMachine for WriterSM { + type State = Status; + type Transition = WriterTransition; + + fn init_state() -> BoxedStrategy { + strategy::Just(Status::new(CAP)).boxed() + } + + fn transitions(_state: &Self::State) -> BoxedStrategy { + prop_oneof![ + (1..50_usize).prop_map(WriterTransition::Read), + (1..50_usize).prop_map(WriterTransition::WriteUpTo), + strategy::Just(WriterTransition::Reset), + ] + .boxed() + } + + fn apply(status: Self::State, transition: &Self::Transition) -> Self::State { + match (status, transition) { + (_, WriterTransition::Reset) => Status::Available(CAP), + (Status::Available(x), WriterTransition::Read(y)) => { + if x < *y { + Status::Failed + } else { + Status::Available(x - y) + } + } + (Status::Failed, WriterTransition::Read(_)) => Status::Failed, + (Status::Available(x), WriterTransition::WriteUpTo(y)) => Status::Available((x + *y).min(CAP)), + (Status::Failed, WriterTransition::WriteUpTo(_)) => Status::Available(CAP), + } + } +} + +struct WriterSut { + status: Status, + buffer: *mut [u8], + producer: WritableDmaRingBuffer<'static, u8>, + consumer: DmaMock, +} + +impl Debug for WriterSut { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + ::fmt(&self.consumer, f) + } +} + +struct WriterTest; + +impl StateMachineTest for WriterTest { + type SystemUnderTest = WriterSut; + type Reference = WriterSM; + + fn init_test(ref_status: &::State) -> Self::SystemUnderTest { + let buffer = Box::into_raw(Box::new([0; CAP])); + WriterSut { + status: ref_status.clone(), + buffer, + producer: WritableDmaRingBuffer::new(unsafe { &mut *buffer }), + consumer: DmaMock::default(), + } + } + + fn teardown(state: Self::SystemUnderTest) { + unsafe { + let _ = Box::from_raw(state.buffer); + }; + } + + fn apply( + mut sut: Self::SystemUnderTest, + ref_status: &::State, + transition: ::Transition, + ) -> Self::SystemUnderTest { + match transition { + WriterTransition::Read(x) => sut.consumer.advance(x), + WriterTransition::Reset => { + sut.producer.reset(&mut sut.consumer); + } + WriterTransition::WriteUpTo(x) => { + let status = sut.status; + let WriterSut { + ref mut producer, + ref mut consumer, + .. + } = sut; + let mut buf = vec![0; x]; + let res = producer.write(consumer, &mut buf); + match status { + Status::Available(n) => { + let writable = x.min(CAP - n.min(CAP)); + assert_eq!(res.unwrap().0, writable); + } + Status::Failed => assert!(res.is_err()), + } + } + } + + WriterSut { + status: ref_status.clone(), + ..sut + } + } +} + +prop_state_machine! { + #[test] + fn writer_state_test(sequential 1..20 => WriterTest); +} diff --git a/embassy-stm32/src/dma/util.rs b/embassy-stm32/src/dma/util.rs new file mode 100644 index 000000000..5aaca57c9 --- /dev/null +++ b/embassy-stm32/src/dma/util.rs @@ -0,0 +1,61 @@ +use embassy_hal_internal::PeripheralRef; + +use super::word::Word; +use super::{AnyChannel, Request, Transfer, TransferOptions}; + +/// Convenience wrapper, contains a channel and a request number. +/// +/// Commonly used in peripheral drivers that own DMA channels. +pub(crate) struct ChannelAndRequest<'d> { + pub channel: PeripheralRef<'d, AnyChannel>, + pub request: Request, +} + +impl<'d> ChannelAndRequest<'d> { + pub unsafe fn read<'a, W: Word>( + &'a mut self, + peri_addr: *mut W, + buf: &'a mut [W], + options: TransferOptions, + ) -> Transfer<'a> { + Transfer::new_read(&mut self.channel, self.request, peri_addr, buf, options) + } + + pub unsafe fn read_raw<'a, W: Word>( + &'a mut self, + peri_addr: *mut W, + buf: *mut [W], + options: TransferOptions, + ) -> Transfer<'a> { + Transfer::new_read_raw(&mut self.channel, self.request, peri_addr, buf, options) + } + + pub unsafe fn write<'a, W: Word>( + &'a mut self, + buf: &'a [W], + peri_addr: *mut W, + options: TransferOptions, + ) -> Transfer<'a> { + Transfer::new_write(&mut self.channel, self.request, buf, peri_addr, options) + } + + pub unsafe fn write_raw<'a, W: Word>( + &'a mut self, + buf: *const [W], + peri_addr: *mut W, + options: TransferOptions, + ) -> Transfer<'a> { + Transfer::new_write_raw(&mut self.channel, self.request, buf, peri_addr, options) + } + + #[allow(dead_code)] + pub unsafe fn write_repeated<'a, W: Word>( + &'a mut self, + repeated: &'a W, + count: usize, + peri_addr: *mut W, + options: TransferOptions, + ) -> Transfer<'a> { + Transfer::new_write_repeated(&mut self.channel, self.request, repeated, count, peri_addr, options) + } +} diff --git a/embassy-stm32/src/dma/word.rs b/embassy-stm32/src/dma/word.rs index a72c4b7d9..fb1bde860 100644 --- a/embassy-stm32/src/dma/word.rs +++ b/embassy-stm32/src/dma/word.rs @@ -20,14 +20,13 @@ impl WordSize { } } -mod sealed { - pub trait Word {} -} +trait SealedWord {} /// DMA word trait. /// /// This is implemented for u8, u16, u32, etc. -pub trait Word: sealed::Word + Default + Copy + 'static { +#[allow(private_bounds)] +pub trait Word: SealedWord + Default + Copy + 'static { /// Word size fn size() -> WordSize; /// Amount of bits of this word size. @@ -36,7 +35,7 @@ pub trait Word: sealed::Word + Default + Copy + 'static { macro_rules! impl_word { (_, $T:ident, $bits:literal, $size:ident) => { - impl sealed::Word for $T {} + impl SealedWord for $T {} impl Word for $T { fn bits() -> usize { $bits diff --git a/embassy-stm32/src/dsihost.rs b/embassy-stm32/src/dsihost.rs new file mode 100644 index 000000000..77c3d95c3 --- /dev/null +++ b/embassy-stm32/src/dsihost.rs @@ -0,0 +1,429 @@ +//! DSI HOST + +use core::marker::PhantomData; + +use embassy_hal_internal::{into_ref, PeripheralRef}; + +//use crate::gpio::{AnyPin, SealedPin}; +use crate::gpio::{AfType, AnyPin, OutputType, Speed}; +use crate::rcc::{self, RccPeripheral}; +use crate::{peripherals, Peripheral}; + +/// Performs a busy-wait delay for a specified number of microseconds. +pub fn blocking_delay_ms(ms: u32) { + #[cfg(feature = "time")] + embassy_time::block_for(embassy_time::Duration::from_millis(ms as u64)); + #[cfg(not(feature = "time"))] + cortex_m::asm::delay(unsafe { crate::rcc::get_freqs() }.sys.to_hertz().unwrap().0 / 1_000 * ms); +} + +/// PacketTypes extracted from CubeMX +#[repr(u8)] +#[allow(dead_code)] +pub enum PacketType { + /// DCS short write, no parameters + DcsShortPktWriteP0, + /// DCS short write, one parameter + DcsShortPktWriteP1, + /// Generic short write, no parameters + GenShortPktWriteP0, + /// Generic short write, one parameter + GenShortPktWriteP1, + /// Generic short write, two parameters + GenShortPktWriteP2, + /// DCS long write + DcsLongPktWrite, + /// Generic long write + GenLongPktWrite, + /// DCS short read + DcsShortPktRead(u8), + /// Generic short read, no parameters + GenShortPktReadP0, + /// Generic short read, one parameter + GenShortPktReadP1(u8), + /// Generic short read, two parameters + GenShortPktReadP2(u8, u8), + /// Used to set the maximum return packet size for reading data + MaxReturnPktSize, +} + +impl From for u8 { + fn from(packet_type: PacketType) -> u8 { + match packet_type { + PacketType::DcsShortPktWriteP0 => 0x05, + PacketType::DcsShortPktWriteP1 => 0x15, + PacketType::GenShortPktWriteP0 => 0x03, + PacketType::GenShortPktWriteP1 => 0x13, + PacketType::GenShortPktWriteP2 => 0x23, + PacketType::DcsLongPktWrite => 0x39, + PacketType::GenLongPktWrite => 0x29, + PacketType::DcsShortPktRead(_) => 0x06, + PacketType::GenShortPktReadP0 => 0x04, + PacketType::GenShortPktReadP1(_) => 0x14, + PacketType::GenShortPktReadP2(_, _) => 0x24, + PacketType::MaxReturnPktSize => 0x37, + } + } +} + +/// DSIHOST driver. +pub struct DsiHost<'d, T: Instance> { + _peri: PhantomData<&'d mut T>, + _te: PeripheralRef<'d, AnyPin>, +} + +impl<'d, T: Instance> DsiHost<'d, T> { + /// Note: Full-Duplex modes are not supported at this time + pub fn new(_peri: impl Peripheral

+ 'd, te: impl Peripheral

> + 'd) -> Self { + into_ref!(te); + + rcc::enable_and_reset::(); + + // Set Tearing Enable pin according to CubeMx example + te.set_as_af(te.af_num(), AfType::output(OutputType::PushPull, Speed::Low)); + /* + T::regs().wcr().modify(|w| { + w.set_dsien(true); + }); + */ + Self { + _peri: PhantomData, + _te: te.map_into(), + } + } + + /// Get the DSIHOST hardware version. Found in the reference manual for comparison. + pub fn get_version(&self) -> u32 { + T::regs().vr().read().version() + } + + /// Set the enable bit in the control register and assert that it has been enabled + pub fn enable(&mut self) { + T::regs().cr().modify(|w| w.set_en(true)); + assert!(T::regs().cr().read().en()) + } + + /// Unset the enable bit in the control register and assert that it has been disabled + pub fn disable(&mut self) { + T::regs().cr().modify(|w| w.set_en(false)); + assert!(!T::regs().cr().read().en()) + } + + /// Set the DSI enable bit in the wrapper control register and assert that it has been enabled + pub fn enable_wrapper_dsi(&mut self) { + T::regs().wcr().modify(|w| w.set_dsien(true)); + assert!(T::regs().wcr().read().dsien()) + } + + /// Unset the DSI enable bit in the wrapper control register and assert that it has been disabled + pub fn disable_wrapper_dsi(&mut self) { + T::regs().wcr().modify(|w| w.set_dsien(false)); + assert!(!T::regs().wcr().read().dsien()) + } + + /// DCS or Generic short/long write command + pub fn write_cmd(&mut self, channel_id: u8, address: u8, data: &[u8]) -> Result<(), Error> { + assert!(data.len() > 0); + + if data.len() == 1 { + self.short_write(channel_id, PacketType::DcsShortPktWriteP1, address, data[0]) + } else { + self.long_write( + channel_id, + PacketType::DcsLongPktWrite, // FIXME: This might be a generic long packet, as well... + address, + data, + ) + } + } + + fn short_write(&mut self, channel_id: u8, packet_type: PacketType, param1: u8, param2: u8) -> Result<(), Error> { + #[cfg(feature = "defmt")] + defmt::debug!("short_write: BEGIN wait for command fifo empty"); + + // Wait for Command FIFO empty + self.wait_command_fifo_empty()?; + #[cfg(feature = "defmt")] + defmt::debug!("short_write: END wait for command fifo empty"); + + // Configure the packet to send a short DCS command with 0 or 1 parameters + // Update the DSI packet header with new information + self.config_packet_header(channel_id, packet_type, param1, param2); + + self.wait_command_fifo_empty()?; + + let status = T::regs().isr1().read().0; + if status != 0 { + error!("ISR1 after short_write(): {:b}", status); + } + Ok(()) + } + + fn config_packet_header(&mut self, channel_id: u8, packet_type: PacketType, param1: u8, param2: u8) { + T::regs().ghcr().write(|w| { + w.set_dt(packet_type.into()); + w.set_vcid(channel_id); + w.set_wclsb(param1); + w.set_wcmsb(param2); + }); + } + + /// Write long DCS or long Generic command. + /// + /// `params` is expected to contain at least 2 elements. Use [`short_write`] for a single element. + fn long_write(&mut self, channel_id: u8, packet_type: PacketType, address: u8, data: &[u8]) -> Result<(), Error> { + // Must be a long packet if we do the long write, obviously. + assert!(matches!( + packet_type, + PacketType::DcsLongPktWrite | PacketType::GenLongPktWrite + )); + + // params needs to have at least 2 elements, otherwise short_write should be used + assert!(data.len() >= 2); + + #[cfg(feature = "defmt")] + defmt::debug!("long_write: BEGIN wait for command fifo empty"); + + self.wait_command_fifo_empty()?; + + #[cfg(feature = "defmt")] + defmt::debug!("long_write: DONE wait for command fifo empty"); + + // Note: CubeMX example "NbParams" is always one LESS than params.len() + // DCS code (last element of params) must be on payload byte 1 and if we have only 2 more params, + // then they must go into data2 and data3 + T::regs().gpdr().write(|w| { + // data[2] may or may not exist. + if let Some(x) = data.get(2) { + w.set_data4(*x); + } + // data[0] and [1] have to exist if long_write is called. + w.set_data3(data[1]); + w.set_data2(data[0]); + + // DCS Code + w.set_data1(address); + }); + + self.wait_command_fifo_empty()?; + + // These steps are only necessary if more than 1x 4 bytes need to go into the FIFO + if data.len() >= 4 { + // Generate an iterator that iterates over chunks of exactly 4 bytes + let iter = data[3..data.len()].chunks_exact(4); + // Obtain remainder before consuming iter + let remainder = iter.remainder(); + + // Keep filling the buffer with remaining data + for param in iter { + self.wait_command_fifo_not_full()?; + T::regs().gpdr().write(|w| { + w.set_data4(param[3]); + w.set_data3(param[2]); + w.set_data2(param[1]); + w.set_data1(param[0]); + }); + + self.wait_command_fifo_empty().unwrap(); + } + + // If the remaining data was not devisible by 4 we get a remainder + if remainder.len() >= 1 { + self.wait_command_fifo_not_full()?; + T::regs().gpdr().write(|w| { + if let Some(x) = remainder.get(2) { + w.set_data3(*x); + } + if let Some(x) = remainder.get(1) { + w.set_data2(*x); + } + w.set_data1(remainder[0]); + }); + self.wait_command_fifo_empty().unwrap(); + } + } + // Configure the packet to send a long DCS command + self.config_packet_header( + channel_id, + packet_type, + ((data.len() + 1) & 0x00FF) as u8, // +1 to account for address byte + (((data.len() + 1) & 0xFF00) >> 8) as u8, // +1 to account for address byte + ); + + self.wait_command_fifo_empty()?; + + let status = T::regs().isr1().read().0; + if status != 0 { + error!("ISR1 after long_write(): {:b}", status); + } + Ok(()) + } + + /// Read DSI Register + pub fn read( + &mut self, + channel_id: u8, + packet_type: PacketType, + read_size: u16, + data: &mut [u8], + ) -> Result<(), Error> { + if data.len() != read_size as usize { + return Err(Error::InvalidReadSize); + } + + // Set the maximum return packet size + self.short_write( + channel_id, + PacketType::MaxReturnPktSize, + (read_size & 0xFF) as u8, + ((read_size & 0xFF00) >> 8) as u8, + )?; + + // Set the packet header according to the packet_type + use PacketType::*; + match packet_type { + DcsShortPktRead(cmd) => self.config_packet_header(channel_id, packet_type, cmd, 0), + GenShortPktReadP0 => self.config_packet_header(channel_id, packet_type, 0, 0), + GenShortPktReadP1(param1) => self.config_packet_header(channel_id, packet_type, param1, 0), + GenShortPktReadP2(param1, param2) => self.config_packet_header(channel_id, packet_type, param1, param2), + _ => return Err(Error::InvalidPacketType), + } + + self.wait_read_not_busy()?; + + // Obtain chunks of 32-bit so the entire FIFO data register can be read + for bytes in data.chunks_exact_mut(4) { + self.wait_payload_read_fifo_not_empty()?; + + // Only perform a single read on the entire register to avoid unintended side-effects + let gpdr = T::regs().gpdr().read(); + bytes[0] = gpdr.data1(); + bytes[1] = gpdr.data2(); + bytes[2] = gpdr.data3(); + bytes[3] = gpdr.data4(); + } + + // Collect the remaining chunks and read the corresponding number of bytes from the FIFO + let remainder = data.chunks_exact_mut(4).into_remainder(); + if !remainder.is_empty() { + self.wait_payload_read_fifo_not_empty()?; + // Only perform a single read on the entire register to avoid unintended side-effects + let gpdr = T::regs().gpdr().read(); + if let Some(x) = remainder.get_mut(0) { + *x = gpdr.data1() + } + if let Some(x) = remainder.get_mut(1) { + *x = gpdr.data2() + } + if let Some(x) = remainder.get_mut(2) { + *x = gpdr.data3() + } + } + + /* + // Used this to check whether there are read errors. Does not seem like it. + if !self.read_busy() { + defmt::debug!("Read not busy!"); + if self.packet_size_error() { + return Err(Error::ReadError); + } + } + */ + Ok(()) + } + + fn wait_command_fifo_empty(&self) -> Result<(), Error> { + for _ in 1..1000 { + // Wait for Command FIFO empty + if T::regs().gpsr().read().cmdfe() { + return Ok(()); + } + blocking_delay_ms(1); + } + Err(Error::FifoTimeout) + } + + fn wait_command_fifo_not_full(&self) -> Result<(), Error> { + for _ in 1..1000 { + // Wait for Command FIFO not empty + if !T::regs().gpsr().read().cmdff() { + return Ok(()); + } + blocking_delay_ms(1); + } + Err(Error::FifoTimeout) + } + + fn wait_read_not_busy(&self) -> Result<(), Error> { + for _ in 1..1000 { + // Wait for read not busy + if !self.read_busy() { + return Ok(()); + } + blocking_delay_ms(1); + } + Err(Error::ReadTimeout) + } + + fn wait_payload_read_fifo_not_empty(&self) -> Result<(), Error> { + for _ in 1..1000 { + // Wait for payload read FIFO not empty + if !T::regs().gpsr().read().prdfe() { + return Ok(()); + } + blocking_delay_ms(1); + } + Err(Error::FifoTimeout) + } + + fn _packet_size_error(&self) -> bool { + T::regs().isr1().read().pse() + } + + fn read_busy(&self) -> bool { + T::regs().gpsr().read().rcb() + } +} + +/// Possible Error Types for DSI HOST +#[non_exhaustive] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Error { + /// Waiting for FIFO empty flag timed out + FifoTimeout, + /// The specified `PacketType` is invalid for the selected operation + InvalidPacketType, + /// Provided read size does not match the read buffer length + InvalidReadSize, + /// Error during read + ReadError, + /// Read operation timed out + ReadTimeout, +} + +impl<'d, T: Instance> Drop for DsiHost<'d, T> { + fn drop(&mut self) {} +} + +trait SealedInstance: crate::rcc::SealedRccPeripheral { + fn regs() -> crate::pac::dsihost::Dsihost; +} + +/// DSI instance trait. +#[allow(private_bounds)] +pub trait Instance: SealedInstance + RccPeripheral + 'static {} + +pin_trait!(TePin, Instance); + +foreach_peripheral!( + (dsihost, $inst:ident) => { + impl crate::dsihost::SealedInstance for peripherals::$inst { + fn regs() -> crate::pac::dsihost::Dsihost { + crate::pac::$inst + } + } + + impl crate::dsihost::Instance for peripherals::$inst {} + }; +); diff --git a/embassy-stm32/src/eth/generic_smi.rs b/embassy-stm32/src/eth/generic_smi.rs index 9c26e90f1..3b43051f4 100644 --- a/embassy-stm32/src/eth/generic_smi.rs +++ b/embassy-stm32/src/eth/generic_smi.rs @@ -1,10 +1,11 @@ //! Generic SMI Ethernet PHY +use core::task::Context; + #[cfg(feature = "time")] use embassy_time::{Duration, Timer}; -use futures::task::Context; #[cfg(feature = "time")] -use futures::FutureExt; +use futures_util::FutureExt; use super::{StationManagement, PHY}; diff --git a/embassy-stm32/src/eth/mod.rs b/embassy-stm32/src/eth/mod.rs index fbcdd7fae..1b875b71a 100644 --- a/embassy-stm32/src/eth/mod.rs +++ b/embassy-stm32/src/eth/mod.rs @@ -13,6 +13,7 @@ use embassy_net_driver::{Capabilities, HardwareAddress, LinkState}; use embassy_sync::waitqueue::AtomicWaker; pub use self::_version::{InterruptHandler, *}; +use crate::rcc::RccPeripheral; #[allow(unused)] const MTU: usize = 1514; @@ -73,8 +74,14 @@ impl PacketQueue { static WAKER: AtomicWaker = AtomicWaker::new(); impl<'d, T: Instance, P: PHY> embassy_net_driver::Driver for Ethernet<'d, T, P> { - type RxToken<'a> = RxToken<'a, 'd> where Self: 'a; - type TxToken<'a> = TxToken<'a, 'd> where Self: 'a; + type RxToken<'a> + = RxToken<'a, 'd> + where + Self: 'a; + type TxToken<'a> + = TxToken<'a, 'd> + where + Self: 'a; fn receive(&mut self, cx: &mut Context) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> { WAKER.register(cx.waker()); @@ -176,16 +183,29 @@ pub unsafe trait PHY { fn poll_link(&mut self, sm: &mut S, cx: &mut Context) -> bool; } -pub(crate) mod sealed { - pub trait Instance { - fn regs() -> crate::pac::eth::Eth; +impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> { + /// Directly expose the SMI interface used by the Ethernet driver. + /// + /// This can be used to for example configure special PHY registers for compliance testing. + /// + /// # Safety + /// + /// Revert any temporary PHY register changes such as to enable test modes before handing + /// the Ethernet device over to the networking stack otherwise things likely won't work. + pub unsafe fn station_management(&mut self) -> &mut impl StationManagement { + &mut self.station_management } } -/// Ethernet instance. -pub trait Instance: sealed::Instance + Send + 'static {} +trait SealedInstance { + fn regs() -> crate::pac::eth::Eth; +} -impl sealed::Instance for crate::peripherals::ETH { +/// Ethernet instance. +#[allow(private_bounds)] +pub trait Instance: SealedInstance + RccPeripheral + Send + 'static {} + +impl SealedInstance for crate::peripherals::ETH { fn regs() -> crate::pac::eth::Eth { crate::pac::ETH } diff --git a/embassy-stm32/src/eth/v1/mod.rs b/embassy-stm32/src/eth/v1/mod.rs index 2ce5b3927..cce75ece7 100644 --- a/embassy-stm32/src/eth/v1/mod.rs +++ b/embassy-stm32/src/eth/v1/mod.rs @@ -12,14 +12,16 @@ use stm32_metapac::eth::vals::{Apcs, Cr, Dm, DmaomrSr, Fes, Ftf, Ifg, MbProgress pub(crate) use self::rx_desc::{RDes, RDesRing}; pub(crate) use self::tx_desc::{TDes, TDesRing}; use super::*; -use crate::gpio::sealed::{AFType, Pin as __GpioPin}; -use crate::gpio::AnyPin; +#[cfg(eth_v1a)] +use crate::gpio::Pull; +use crate::gpio::{AfType, AnyPin, OutputType, SealedPin, Speed}; use crate::interrupt::InterruptExt; #[cfg(eth_v1a)] use crate::pac::AFIO; #[cfg(any(eth_v1b, eth_v1c))] use crate::pac::SYSCFG; use crate::pac::{ETH, RCC}; +use crate::rcc::SealedRccPeripheral; use crate::{interrupt, Peripheral}; /// Interrupt handler. @@ -61,7 +63,7 @@ macro_rules! config_in_pins { critical_section::with(|_| { $( // TODO properly create a set_as_input function - $pin.set_as_af($pin.af_num(), AFType::Input); + $pin.set_as_af($pin.af_num(), AfType::input(Pull::None)); )* }) } @@ -72,8 +74,7 @@ macro_rules! config_af_pins { ($($pin:ident),*) => { critical_section::with(|_| { $( - // We are lucky here, this configures to max speed (50MHz) - $pin.set_as_af($pin.af_num(), AFType::OutputPushPull); + $pin.set_as_af($pin.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); )* }) }; @@ -84,8 +85,7 @@ macro_rules! config_pins { ($($pin:ident),*) => { critical_section::with(|_| { $( - $pin.set_as_af($pin.af_num(), AFType::OutputPushPull); - $pin.set_speed(crate::gpio::Speed::VeryHigh); + $pin.set_as_af($pin.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); )* }) }; @@ -148,8 +148,8 @@ impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> { #[cfg(any(eth_v1b, eth_v1c))] config_pins!(ref_clk, mdio, mdc, crs, rx_d0, rx_d1, tx_d0, tx_d1, tx_en); - let dma = ETH.ethernet_dma(); - let mac = ETH.ethernet_mac(); + let dma = T::regs().ethernet_dma(); + let mac = T::regs().ethernet_mac(); // Reset and wait dma.dmabmr().modify(|w| w.set_sr(true)); @@ -191,8 +191,7 @@ impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> { // TODO MTU size setting not found for v1 ethernet, check if correct - // NOTE(unsafe) We got the peripheral singleton, which means that `rcc::init` was called - let hclk = unsafe { crate::rcc::get_freqs() }.hclk1; + let hclk = ::frequency(); let hclk_mhz = hclk.0 / 1_000_000; // Set the MDC clock frequency in the range 1MHz - 2.5MHz @@ -235,8 +234,8 @@ impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> { fence(Ordering::SeqCst); - let mac = ETH.ethernet_mac(); - let dma = ETH.ethernet_dma(); + let mac = T::regs().ethernet_mac(); + let dma = T::regs().ethernet_dma(); mac.maccr().modify(|w| { w.set_re(true); @@ -275,7 +274,7 @@ pub struct EthernetStationManagement { unsafe impl StationManagement for EthernetStationManagement { fn smi_read(&mut self, phy_addr: u8, reg: u8) -> u16 { - let mac = ETH.ethernet_mac(); + let mac = T::regs().ethernet_mac(); mac.macmiiar().modify(|w| { w.set_pa(phy_addr); @@ -289,7 +288,7 @@ unsafe impl StationManagement for EthernetStationManagement { } fn smi_write(&mut self, phy_addr: u8, reg: u8, val: u16) { - let mac = ETH.ethernet_mac(); + let mac = T::regs().ethernet_mac(); mac.macmiidr().write(|w| w.set_md(val)); mac.macmiiar().modify(|w| { @@ -305,8 +304,8 @@ unsafe impl StationManagement for EthernetStationManagement { impl<'d, T: Instance, P: PHY> Drop for Ethernet<'d, T, P> { fn drop(&mut self) { - let dma = ETH.ethernet_dma(); - let mac = ETH.ethernet_mac(); + let dma = T::regs().ethernet_dma(); + let mac = T::regs().ethernet_mac(); // Disable the TX DMA and wait for any previous transmissions to be completed dma.dmaomr().modify(|w| w.set_st(St::STOPPED)); diff --git a/embassy-stm32/src/eth/v2/descriptors.rs b/embassy-stm32/src/eth/v2/descriptors.rs index 01ea8e574..645bfdb14 100644 --- a/embassy-stm32/src/eth/v2/descriptors.rs +++ b/embassy-stm32/src/eth/v2/descriptors.rs @@ -129,7 +129,7 @@ impl<'a> TDesRing<'a> { /// Receive Descriptor representation /// -/// * rdes0: recieve buffer address +/// * rdes0: receive buffer address /// * rdes1: /// * rdes2: /// * rdes3: OWN and Status diff --git a/embassy-stm32/src/eth/v2/mod.rs b/embassy-stm32/src/eth/v2/mod.rs index 4b22d1d21..9dd7f7d95 100644 --- a/embassy-stm32/src/eth/v2/mod.rs +++ b/embassy-stm32/src/eth/v2/mod.rs @@ -4,13 +4,14 @@ use core::marker::PhantomData; use core::sync::atomic::{fence, Ordering}; use embassy_hal_internal::{into_ref, PeripheralRef}; +use stm32_metapac::syscfg::vals::EthSelPhy; pub(crate) use self::descriptors::{RDes, RDesRing, TDes, TDesRing}; use super::*; -use crate::gpio::sealed::{AFType, Pin as _}; -use crate::gpio::{AnyPin, Speed}; +use crate::gpio::{AfType, AnyPin, OutputType, SealedPin as _, Speed}; use crate::interrupt::InterruptExt; use crate::pac::ETH; +use crate::rcc::SealedRccPeripheral; use crate::{interrupt, Peripheral}; /// Interrupt handler. @@ -55,8 +56,8 @@ macro_rules! config_pins { ($($pin:ident),*) => { critical_section::with(|_| { $( - $pin.set_as_af($pin.af_num(), AFType::OutputPushPull); - $pin.set_speed(Speed::VeryHigh); + // TODO: shouldn't some pins be configured as inputs? + $pin.set_as_af($pin.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); )* }) }; @@ -80,31 +81,15 @@ impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> { phy: P, mac_addr: [u8; 6], ) -> Self { - // Enable the necessary Clocks - #[cfg(not(rcc_h5))] + // Enable the necessary clocks critical_section::with(|_| { - crate::pac::RCC.ahb1enr().modify(|w| { - w.set_eth1macen(true); - w.set_eth1txen(true); - w.set_eth1rxen(true); - }); - - crate::pac::SYSCFG.pmcr().modify(|w| w.set_epis(0b100)); - }); - - #[cfg(rcc_h5)] - critical_section::with(|_| { - crate::pac::RCC.apb3enr().modify(|w| w.set_sbsen(true)); - crate::pac::RCC.ahb1enr().modify(|w| { w.set_ethen(true); w.set_ethtxen(true); w.set_ethrxen(true); }); - crate::pac::SYSCFG - .pmcr() - .modify(|w| w.set_eth_sel_phy(crate::pac::syscfg::vals::EthSelPhy::B_0X4)); + crate::pac::SYSCFG.pmcr().modify(|w| w.set_eth_sel_phy(EthSelPhy::RMII)); }); into_ref!(ref_clk, mdio, mdc, crs, rx_d0, rx_d1, tx_d0, tx_d1, tx_en); @@ -147,32 +132,17 @@ impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> { phy: P, mac_addr: [u8; 6], ) -> Self { - // Enable necessary clocks. - #[cfg(not(rcc_h5))] + // Enable the necessary clocks critical_section::with(|_| { - crate::pac::RCC.ahb1enr().modify(|w| { - w.set_eth1macen(true); - w.set_eth1txen(true); - w.set_eth1rxen(true); - }); - - crate::pac::SYSCFG.pmcr().modify(|w| w.set_epis(0b000)); - }); - - #[cfg(rcc_h5)] - critical_section::with(|_| { - crate::pac::RCC.apb3enr().modify(|w| w.set_sbsen(true)); - crate::pac::RCC.ahb1enr().modify(|w| { w.set_ethen(true); w.set_ethtxen(true); w.set_ethrxen(true); }); - // TODO: This is for RMII - what would MII need here? crate::pac::SYSCFG .pmcr() - .modify(|w| w.set_eth_sel_phy(crate::pac::syscfg::vals::EthSelPhy::B_0X4)); + .modify(|w| w.set_eth_sel_phy(EthSelPhy::MII_GMII)); }); into_ref!(rx_clk, tx_clk, mdio, mdc, rxdv, rx_d0, rx_d1, rx_d2, rx_d3, tx_d0, tx_d1, tx_d2, tx_d3, tx_en); @@ -206,9 +176,9 @@ impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> { phy: P, mac_addr: [u8; 6], ) -> Self { - let dma = ETH.ethernet_dma(); - let mac = ETH.ethernet_mac(); - let mtl = ETH.ethernet_mtl(); + let dma = T::regs().ethernet_dma(); + let mac = T::regs().ethernet_mac(); + let mtl = T::regs().ethernet_mtl(); // Reset and wait dma.dmamr().modify(|w| w.set_swr(true)); @@ -222,6 +192,9 @@ impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> { // TODO: Carrier sense ? ECRSFD }); + // Disable multicast filter + mac.macpfr().modify(|w| w.set_pm(true)); + // Note: Writing to LR triggers synchronisation of both LR and HR into the MAC core, // so the LR write must happen after the HR write. mac.maca0hr() @@ -264,8 +237,7 @@ impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> { w.set_rbsz(RX_BUFFER_SIZE as u16); }); - // NOTE(unsafe) We got the peripheral singleton, which means that `rcc::init` was called - let hclk = unsafe { crate::rcc::get_freqs() }.hclk1; + let hclk = ::frequency(); let hclk_mhz = hclk.0 / 1_000_000; // Set the MDC clock frequency in the range 1MHz - 2.5MHz @@ -296,9 +268,9 @@ impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> { fence(Ordering::SeqCst); - let mac = ETH.ethernet_mac(); - let mtl = ETH.ethernet_mtl(); - let dma = ETH.ethernet_dma(); + let mac = T::regs().ethernet_mac(); + let mtl = T::regs().ethernet_mtl(); + let dma = T::regs().ethernet_dma(); mac.maccr().modify(|w| { w.set_re(true); @@ -334,7 +306,7 @@ pub struct EthernetStationManagement { unsafe impl StationManagement for EthernetStationManagement { fn smi_read(&mut self, phy_addr: u8, reg: u8) -> u16 { - let mac = ETH.ethernet_mac(); + let mac = T::regs().ethernet_mac(); mac.macmdioar().modify(|w| { w.set_pa(phy_addr); @@ -348,7 +320,7 @@ unsafe impl StationManagement for EthernetStationManagement { } fn smi_write(&mut self, phy_addr: u8, reg: u8, val: u16) { - let mac = ETH.ethernet_mac(); + let mac = T::regs().ethernet_mac(); mac.macmdiodr().write(|w| w.set_md(val)); mac.macmdioar().modify(|w| { @@ -364,9 +336,9 @@ unsafe impl StationManagement for EthernetStationManagement { impl<'d, T: Instance, P: PHY> Drop for Ethernet<'d, T, P> { fn drop(&mut self) { - let dma = ETH.ethernet_dma(); - let mac = ETH.ethernet_mac(); - let mtl = ETH.ethernet_mtl(); + let dma = T::regs().ethernet_dma(); + let mac = T::regs().ethernet_mac(); + let mtl = T::regs().ethernet_mtl(); // Disable the TX DMA and wait for any previous transmissions to be completed dma.dmactx_cr().modify(|w| w.set_st(false)); diff --git a/embassy-stm32/src/exti.rs b/embassy-stm32/src/exti.rs index bd10ba158..87512c92d 100644 --- a/embassy-stm32/src/exti.rs +++ b/embassy-stm32/src/exti.rs @@ -27,11 +27,11 @@ fn cpu_regs() -> pac::exti::Exti { EXTI } -#[cfg(not(any(exti_c0, exti_g0, exti_l5, gpio_v1, exti_u5, exti_h5, exti_h50)))] +#[cfg(not(any(exti_c0, exti_g0, exti_u0, exti_l5, gpio_v1, exti_u5, exti_h5, exti_h50)))] fn exticr_regs() -> pac::syscfg::Syscfg { pac::SYSCFG } -#[cfg(any(exti_c0, exti_g0, exti_l5, exti_u5, exti_h5, exti_h50))] +#[cfg(any(exti_c0, exti_g0, exti_u0, exti_l5, exti_u5, exti_h5, exti_h50))] fn exticr_regs() -> pac::exti::Exti { EXTI } @@ -41,12 +41,9 @@ fn exticr_regs() -> pac::afio::Afio { } unsafe fn on_irq() { - #[cfg(feature = "low-power")] - crate::low_power::on_wakeup_irq(); - - #[cfg(not(any(exti_c0, exti_g0, exti_l5, exti_u5, exti_h5, exti_h50)))] + #[cfg(not(any(exti_c0, exti_g0, exti_u0, exti_l5, exti_u5, exti_h5, exti_h50)))] let bits = EXTI.pr(0).read().0; - #[cfg(any(exti_c0, exti_g0, exti_l5, exti_u5, exti_h5, exti_h50))] + #[cfg(any(exti_c0, exti_g0, exti_u0, exti_l5, exti_u5, exti_h5, exti_h50))] let bits = EXTI.rpr(0).read().0 | EXTI.fpr(0).read().0; // We don't handle or change any EXTI lines above 16. @@ -61,13 +58,16 @@ unsafe fn on_irq() { } // Clear pending - #[cfg(not(any(exti_c0, exti_g0, exti_l5, exti_u5, exti_h5, exti_h50)))] + #[cfg(not(any(exti_c0, exti_g0, exti_u0, exti_l5, exti_u5, exti_h5, exti_h50)))] EXTI.pr(0).write_value(Lines(bits)); - #[cfg(any(exti_c0, exti_g0, exti_l5, exti_u5, exti_h5, exti_h50))] + #[cfg(any(exti_c0, exti_g0, exti_u0, exti_l5, exti_u5, exti_h5, exti_h50))] { EXTI.rpr(0).write_value(Lines(bits)); EXTI.fpr(0).write_value(Lines(bits)); } + + #[cfg(feature = "low-power")] + crate::low_power::on_wakeup_irq(); } struct BitIter(u32); @@ -241,9 +241,9 @@ impl<'a> ExtiInputFuture<'a> { EXTI.ftsr(0).modify(|w| w.set_line(pin, falling)); // clear pending bit - #[cfg(not(any(exti_c0, exti_g0, exti_l5, exti_u5, exti_h5, exti_h50)))] + #[cfg(not(any(exti_c0, exti_g0, exti_u0, exti_l5, exti_u5, exti_h5, exti_h50)))] EXTI.pr(0).write(|w| w.set_line(pin, true)); - #[cfg(any(exti_c0, exti_g0, exti_l5, exti_u5, exti_h5, exti_h50))] + #[cfg(any(exti_c0, exti_g0, exti_u0, exti_l5, exti_u5, exti_h5, exti_h50))] { EXTI.rpr(0).write(|w| w.set_line(pin, true)); EXTI.fpr(0).write(|w| w.set_line(pin, true)); @@ -330,12 +330,11 @@ macro_rules! impl_irq { foreach_exti_irq!(impl_irq); -pub(crate) mod sealed { - pub trait Channel {} -} +trait SealedChannel {} /// EXTI channel trait. -pub trait Channel: sealed::Channel + Sized { +#[allow(private_bounds)] +pub trait Channel: SealedChannel + Sized { /// Get the EXTI channel number. fn number(&self) -> u8; @@ -359,7 +358,7 @@ pub struct AnyChannel { } impl_peripheral!(AnyChannel); -impl sealed::Channel for AnyChannel {} +impl SealedChannel for AnyChannel {} impl Channel for AnyChannel { fn number(&self) -> u8 { self.number @@ -368,7 +367,7 @@ impl Channel for AnyChannel { macro_rules! impl_exti { ($type:ident, $number:expr) => { - impl sealed::Channel for peripherals::$type {} + impl SealedChannel for peripherals::$type {} impl Channel for peripherals::$type { fn number(&self) -> u8 { $number diff --git a/embassy-stm32/src/flash/asynch.rs b/embassy-stm32/src/flash/asynch.rs index 97eaece81..9468ac632 100644 --- a/embassy-stm32/src/flash/asynch.rs +++ b/embassy-stm32/src/flash/asynch.rs @@ -117,7 +117,7 @@ pub(super) async unsafe fn write_chunked(base: u32, size: u32, offset: u32, byte family::lock(); }); - family::write(address, chunk.try_into().unwrap()).await?; + family::write(address, unwrap!(chunk.try_into())).await?; address += WRITE_SIZE as u32; } Ok(()) diff --git a/embassy-stm32/src/flash/common.rs b/embassy-stm32/src/flash/common.rs index f8561edb3..8ec4bb2a1 100644 --- a/embassy-stm32/src/flash/common.rs +++ b/embassy-stm32/src/flash/common.rs @@ -125,7 +125,7 @@ pub(super) unsafe fn write_chunk_unlocked(address: u32, chunk: &[u8]) -> Result< family::lock(); }); - family::blocking_write(address, chunk.try_into().unwrap()) + family::blocking_write(address, unwrap!(chunk.try_into())) } pub(super) unsafe fn write_chunk_with_critical_section(address: u32, chunk: &[u8]) -> Result<(), Error> { diff --git a/embassy-stm32/src/flash/f0.rs b/embassy-stm32/src/flash/f0.rs index e0c76e6b2..402312f68 100644 --- a/embassy-stm32/src/flash/f0.rs +++ b/embassy-stm32/src/flash/f0.rs @@ -1,4 +1,3 @@ -use core::convert::TryInto; use core::ptr::write_volatile; use core::sync::atomic::{fence, Ordering}; @@ -38,7 +37,7 @@ pub(crate) unsafe fn disable_blocking_write() { pub(crate) unsafe fn blocking_write(start_address: u32, buf: &[u8; WRITE_SIZE]) -> Result<(), Error> { let mut address = start_address; for chunk in buf.chunks(2) { - write_volatile(address as *mut u16, u16::from_le_bytes(chunk.try_into().unwrap())); + write_volatile(address as *mut u16, u16::from_le_bytes(unwrap!(chunk.try_into()))); address += chunk.len() as u32; // prevents parallelism errors diff --git a/embassy-stm32/src/flash/f1f3.rs b/embassy-stm32/src/flash/f1f3.rs index e7790369a..ff7f810ea 100644 --- a/embassy-stm32/src/flash/f1f3.rs +++ b/embassy-stm32/src/flash/f1f3.rs @@ -1,4 +1,3 @@ -use core::convert::TryInto; use core::ptr::write_volatile; use core::sync::atomic::{fence, Ordering}; @@ -38,14 +37,16 @@ pub(crate) unsafe fn disable_blocking_write() { pub(crate) unsafe fn blocking_write(start_address: u32, buf: &[u8; WRITE_SIZE]) -> Result<(), Error> { let mut address = start_address; for chunk in buf.chunks(2) { - write_volatile(address as *mut u16, u16::from_le_bytes(chunk.try_into().unwrap())); + write_volatile(address as *mut u16, u16::from_le_bytes(unwrap!(chunk.try_into()))); address += chunk.len() as u32; // prevents parallelism errors fence(Ordering::SeqCst); + + wait_ready_blocking()?; } - wait_ready_blocking() + Ok(()) } pub(crate) unsafe fn blocking_erase_sector(sector: &FlashSector) -> Result<(), Error> { diff --git a/embassy-stm32/src/flash/f2.rs b/embassy-stm32/src/flash/f2.rs new file mode 100644 index 000000000..cdab1fd2d --- /dev/null +++ b/embassy-stm32/src/flash/f2.rs @@ -0,0 +1,142 @@ +use core::ptr::write_volatile; +use core::sync::atomic::{fence, AtomicBool, Ordering}; + +use pac::flash::regs::Sr; + +use super::{FlashBank, FlashRegion, FlashSector, FLASH_REGIONS, WRITE_SIZE}; +use crate::flash::Error; +use crate::pac; + +static DATA_CACHE_WAS_ENABLED: AtomicBool = AtomicBool::new(false); + +impl FlashSector { + const fn snb(&self) -> u8 { + ((self.bank as u8) << 4) + self.index_in_bank + } +} + +pub(crate) const fn is_default_layout() -> bool { + true +} + +pub(crate) const fn get_flash_regions() -> &'static [&'static FlashRegion] { + &FLASH_REGIONS +} + +pub(crate) unsafe fn lock() { + pac::FLASH.cr().modify(|w| w.set_lock(true)); +} + +pub(crate) unsafe fn unlock() { + if pac::FLASH.cr().read().lock() { + pac::FLASH.keyr().write_value(0x4567_0123); + pac::FLASH.keyr().write_value(0xCDEF_89AB); + } +} + +pub(crate) unsafe fn enable_blocking_write() { + assert_eq!(0, WRITE_SIZE % 4); + save_data_cache_state(); + + pac::FLASH.cr().write(|w| { + w.set_pg(true); + w.set_psize(pac::flash::vals::Psize::PSIZE32); + }); +} + +pub(crate) unsafe fn disable_blocking_write() { + pac::FLASH.cr().write(|w| w.set_pg(false)); + restore_data_cache_state(); +} + +pub(crate) unsafe fn blocking_write(start_address: u32, buf: &[u8; WRITE_SIZE]) -> Result<(), Error> { + write_start(start_address, buf); + blocking_wait_ready() +} + +unsafe fn write_start(start_address: u32, buf: &[u8; WRITE_SIZE]) { + let mut address = start_address; + for val in buf.chunks(4) { + write_volatile(address as *mut u32, u32::from_le_bytes(unwrap!(val.try_into()))); + address += val.len() as u32; + + // prevents parallelism errors + fence(Ordering::SeqCst); + } +} + +pub(crate) unsafe fn blocking_erase_sector(sector: &FlashSector) -> Result<(), Error> { + save_data_cache_state(); + + trace!("Blocking erasing sector number {}", sector.snb()); + + pac::FLASH.cr().modify(|w| { + w.set_ser(true); + w.set_snb(sector.snb()) + }); + + pac::FLASH.cr().modify(|w| { + w.set_strt(true); + }); + + let ret: Result<(), Error> = blocking_wait_ready(); + clear_all_err(); + restore_data_cache_state(); + ret +} + +pub(crate) unsafe fn clear_all_err() { + // read and write back the same value. + // This clears all "write 1 to clear" bits. + pac::FLASH.sr().modify(|_| {}); +} + +unsafe fn blocking_wait_ready() -> Result<(), Error> { + loop { + let sr = pac::FLASH.sr().read(); + + if !sr.bsy() { + return get_result(sr); + } + } +} + +fn get_result(sr: Sr) -> Result<(), Error> { + if sr.pgserr() { + Err(Error::Seq) + } else if sr.pgperr() { + Err(Error::Parallelism) + } else if sr.pgaerr() { + Err(Error::Unaligned) + } else if sr.wrperr() { + Err(Error::Protected) + } else { + Ok(()) + } +} + +fn save_data_cache_state() { + let dual_bank = unwrap!(get_flash_regions().last()).bank == FlashBank::Bank2; + if dual_bank { + // Disable data cache during write/erase if there are two banks, see errata 2.2.12 + let dcen = pac::FLASH.acr().read().dcen(); + DATA_CACHE_WAS_ENABLED.store(dcen, Ordering::Relaxed); + if dcen { + pac::FLASH.acr().modify(|w| w.set_dcen(false)); + } + } +} + +fn restore_data_cache_state() { + let dual_bank = unwrap!(get_flash_regions().last()).bank == FlashBank::Bank2; + if dual_bank { + // Restore data cache if it was enabled + let dcen = DATA_CACHE_WAS_ENABLED.load(Ordering::Relaxed); + if dcen { + // Reset data cache before we enable it again + pac::FLASH.acr().modify(|w| w.set_dcrst(true)); + pac::FLASH.acr().modify(|w| w.set_dcrst(false)); + pac::FLASH.acr().modify(|w| w.set_dcen(true)) + } + } +} diff --git a/embassy-stm32/src/flash/f4.rs b/embassy-stm32/src/flash/f4.rs index 57447bea5..d0bb957ee 100644 --- a/embassy-stm32/src/flash/f4.rs +++ b/embassy-stm32/src/flash/f4.rs @@ -1,4 +1,3 @@ -use core::convert::TryInto; use core::ptr::write_volatile; use core::sync::atomic::{fence, AtomicBool, Ordering}; @@ -17,7 +16,7 @@ mod alt_regions { use embassy_hal_internal::PeripheralRef; use stm32_metapac::FLASH_SIZE; - use crate::_generated::flash_regions::{OTPRegion, BANK1_REGION1, BANK1_REGION2, BANK1_REGION3, OTP_REGION}; + use crate::_generated::flash_regions::{BANK1_REGION1, BANK1_REGION2, BANK1_REGION3}; use crate::flash::{asynch, Async, Bank1Region1, Bank1Region2, Blocking, Error, Flash, FlashBank, FlashRegion}; use crate::peripherals::FLASH; @@ -63,7 +62,6 @@ mod alt_regions { pub bank2_region1: AltBank2Region1<'d, MODE>, pub bank2_region2: AltBank2Region2<'d, MODE>, pub bank2_region3: AltBank2Region3<'d, MODE>, - pub otp_region: OTPRegion<'d, MODE>, } impl<'d> Flash<'d> { @@ -80,7 +78,6 @@ mod alt_regions { bank2_region1: AltBank2Region1(&ALT_BANK2_REGION1, unsafe { p.clone_unchecked() }, PhantomData), bank2_region2: AltBank2Region2(&ALT_BANK2_REGION2, unsafe { p.clone_unchecked() }, PhantomData), bank2_region3: AltBank2Region3(&ALT_BANK2_REGION3, unsafe { p.clone_unchecked() }, PhantomData), - otp_region: OTPRegion(&OTP_REGION, unsafe { p.clone_unchecked() }, PhantomData), } } @@ -97,7 +94,6 @@ mod alt_regions { bank2_region1: AltBank2Region1(&ALT_BANK2_REGION1, unsafe { p.clone_unchecked() }, PhantomData), bank2_region2: AltBank2Region2(&ALT_BANK2_REGION2, unsafe { p.clone_unchecked() }, PhantomData), bank2_region3: AltBank2Region3(&ALT_BANK2_REGION3, unsafe { p.clone_unchecked() }, PhantomData), - otp_region: OTPRegion(&OTP_REGION, unsafe { p.clone_unchecked() }, PhantomData), } } } @@ -281,7 +277,7 @@ pub(crate) unsafe fn blocking_write(start_address: u32, buf: &[u8; WRITE_SIZE]) unsafe fn write_start(start_address: u32, buf: &[u8; WRITE_SIZE]) { let mut address = start_address; for val in buf.chunks(4) { - write_volatile(address as *mut u32, u32::from_le_bytes(val.try_into().unwrap())); + write_volatile(address as *mut u32, u32::from_le_bytes(unwrap!(val.try_into()))); address += val.len() as u32; // prevents parallelism errors @@ -342,10 +338,9 @@ pub(crate) fn clear_all_err() { } pub(crate) async fn wait_ready() -> Result<(), Error> { + use core::future::poll_fn; use core::task::Poll; - use futures::future::poll_fn; - poll_fn(|cx| { WAKER.register(cx.waker()); @@ -384,7 +379,7 @@ fn get_result(sr: Sr) -> Result<(), Error> { } fn save_data_cache_state() { - let dual_bank = get_flash_regions().last().unwrap().bank == FlashBank::Bank2; + let dual_bank = unwrap!(get_flash_regions().last()).bank == FlashBank::Bank2; if dual_bank { // Disable data cache during write/erase if there are two banks, see errata 2.2.12 let dcen = pac::FLASH.acr().read().dcen(); @@ -396,7 +391,7 @@ fn save_data_cache_state() { } fn restore_data_cache_state() { - let dual_bank = get_flash_regions().last().unwrap().bank == FlashBank::Bank2; + let dual_bank = unwrap!(get_flash_regions().last()).bank == FlashBank::Bank2; if dual_bank { // Restore data cache if it was enabled let dcen = DATA_CACHE_WAS_ENABLED.load(Ordering::Relaxed); @@ -415,7 +410,7 @@ pub(crate) fn assert_not_corrupted_read(end_address: u32) { #[allow(unused)] let second_bank_read = - get_flash_regions().last().unwrap().bank == FlashBank::Bank2 && end_address > (FLASH_SIZE / 2) as u32; + unwrap!(get_flash_regions().last()).bank == FlashBank::Bank2 && end_address > (FLASH_SIZE / 2) as u32; #[cfg(any( feature = "stm32f427ai", diff --git a/embassy-stm32/src/flash/f7.rs b/embassy-stm32/src/flash/f7.rs index 0f512bbc4..09ebe9db9 100644 --- a/embassy-stm32/src/flash/f7.rs +++ b/embassy-stm32/src/flash/f7.rs @@ -1,4 +1,3 @@ -use core::convert::TryInto; use core::ptr::write_volatile; use core::sync::atomic::{fence, Ordering}; @@ -41,7 +40,7 @@ pub(crate) unsafe fn disable_blocking_write() { pub(crate) unsafe fn blocking_write(start_address: u32, buf: &[u8; WRITE_SIZE]) -> Result<(), Error> { let mut address = start_address; for val in buf.chunks(4) { - write_volatile(address as *mut u32, u32::from_le_bytes(val.try_into().unwrap())); + write_volatile(address as *mut u32, u32::from_le_bytes(unwrap!(val.try_into()))); address += val.len() as u32; // prevents parallelism errors diff --git a/embassy-stm32/src/flash/g.rs b/embassy-stm32/src/flash/g.rs index b69c4343b..01a0c603f 100644 --- a/embassy-stm32/src/flash/g.rs +++ b/embassy-stm32/src/flash/g.rs @@ -1,4 +1,3 @@ -use core::convert::TryInto; use core::ptr::write_volatile; use core::sync::atomic::{fence, Ordering}; @@ -42,7 +41,7 @@ pub(crate) unsafe fn disable_blocking_write() { pub(crate) unsafe fn blocking_write(start_address: u32, buf: &[u8; WRITE_SIZE]) -> Result<(), Error> { let mut address = start_address; for val in buf.chunks(4) { - write_volatile(address as *mut u32, u32::from_le_bytes(val.try_into().unwrap())); + write_volatile(address as *mut u32, u32::from_le_bytes(unwrap!(val.try_into()))); address += val.len() as u32; // prevents parallelism errors diff --git a/embassy-stm32/src/flash/h5.rs b/embassy-stm32/src/flash/h5.rs new file mode 100644 index 000000000..9e131ca2b --- /dev/null +++ b/embassy-stm32/src/flash/h5.rs @@ -0,0 +1,177 @@ +use core::ptr::write_volatile; +use core::sync::atomic::{fence, Ordering}; + +use super::{FlashRegion, FlashSector, FLASH_REGIONS, WRITE_SIZE}; +use crate::flash::Error; +use crate::pac; + +pub(crate) const fn is_default_layout() -> bool { + true +} + +// const fn is_dual_bank() -> bool { +// FLASH_REGIONS.len() >= 2 +// } + +pub(crate) fn get_flash_regions() -> &'static [&'static FlashRegion] { + &FLASH_REGIONS +} + +pub(crate) unsafe fn lock() { + if !pac::FLASH.nscr().read().lock() { + pac::FLASH.nscr().modify(|r| { + r.set_lock(true); + }); + } +} + +pub(crate) unsafe fn unlock() { + // TODO: check locked first + while pac::FLASH.nssr().read().bsy() { + #[cfg(feature = "defmt")] + defmt::trace!("busy") + } + + // only unlock if locked to begin with + if pac::FLASH.nscr().read().lock() { + pac::FLASH.nskeyr().write_value(0x4567_0123); + pac::FLASH.nskeyr().write_value(0xCDEF_89AB); + } +} + +pub(crate) unsafe fn enable_blocking_write() { + assert_eq!(0, WRITE_SIZE % 4); +} + +pub(crate) unsafe fn disable_blocking_write() {} + +pub(crate) unsafe fn blocking_write(start_address: u32, buf: &[u8; WRITE_SIZE]) -> Result<(), Error> { + // // We cannot have the write setup sequence in begin_write as it depends on the address + // let bank = if start_address < BANK1_REGION.end() { + // pac::FLASH.bank(0) + // } else { + // pac::FLASH.bank(1) + // }; + + cortex_m::asm::isb(); + cortex_m::asm::dsb(); + fence(Ordering::SeqCst); + + clear_all_err(); + + pac::FLASH.nscr().write(|w| { + w.set_pg(true); + // w.set_psize(2); // 32 bits at once + }); + + let mut res = None; + let mut address = start_address; + // TODO: see write size + for val in buf.chunks(4) { + write_volatile(address as *mut u32, u32::from_le_bytes(unwrap!(val.try_into()))); + address += val.len() as u32; + + res = Some(blocking_wait_ready().map_err(|e| { + error!("write err"); + e + })); + pac::FLASH.nssr().modify(|w| { + if w.eop() { + w.set_eop(true); + } + }); + if unwrap!(res).is_err() { + break; + } + } + + cortex_m::asm::isb(); + cortex_m::asm::dsb(); + fence(Ordering::SeqCst); + + pac::FLASH.nscr().write(|w| w.set_pg(false)); + + unwrap!(res) +} + +pub(crate) unsafe fn blocking_erase_sector(sector: &FlashSector) -> Result<(), Error> { + // pac::FLASH.wrp2r_cur().read().wrpsg() + // TODO: write protection check + if pac::FLASH.nscr().read().lock() == true { + error!("flash locked"); + } + + loop { + let sr = pac::FLASH.nssr().read(); + if !sr.bsy() && !sr.dbne() { + break; + } + } + clear_all_err(); + + pac::FLASH.nscr().modify(|r| { + // TODO: later check bank swap + r.set_bksel(match sector.bank { + crate::flash::FlashBank::Bank1 => stm32_metapac::flash::vals::NscrBksel::B_0X0, + crate::flash::FlashBank::Bank2 => stm32_metapac::flash::vals::NscrBksel::B_0X1, + }); + r.set_snb(sector.index_in_bank); + r.set_ser(true); + }); + + pac::FLASH.nscr().modify(|r| { + r.set_strt(true); + }); + + cortex_m::asm::isb(); + cortex_m::asm::dsb(); + fence(Ordering::SeqCst); + + let ret: Result<(), Error> = blocking_wait_ready().map_err(|e| { + error!("erase err"); + e + }); + + pac::FLASH.nscr().modify(|w| w.set_ser(false)); + clear_all_err(); + ret +} + +pub(crate) unsafe fn clear_all_err() { + pac::FLASH.nssr().modify(|_| {}) +} + +unsafe fn blocking_wait_ready() -> Result<(), Error> { + loop { + let sr = pac::FLASH.nssr().read(); + + if !sr.bsy() { + if sr.optchangeerr() { + error!("optchangeerr"); + return Err(Error::Prog); + } + if sr.obkwerr() { + error!("obkwerr"); + return Err(Error::Seq); + } + if sr.obkerr() { + error!("obkerr"); + return Err(Error::Seq); + } + if sr.incerr() { + error!("incerr"); + return Err(Error::Unaligned); + } + if sr.strberr() { + error!("strberr"); + return Err(Error::Parallelism); + } + if sr.wrperr() { + error!("protected"); + return Err(Error::Protected); + } + + return Ok(()); + } + } +} diff --git a/embassy-stm32/src/flash/h50.rs b/embassy-stm32/src/flash/h50.rs new file mode 100644 index 000000000..82e77d130 --- /dev/null +++ b/embassy-stm32/src/flash/h50.rs @@ -0,0 +1,166 @@ +/// STM32H50 series flash impl. See RM0492 +use core::{ + ptr::write_volatile, + sync::atomic::{fence, Ordering}, +}; + +use cortex_m::interrupt; +use pac::flash::regs::Nssr; +use pac::flash::vals::Bksel; + +use super::{Error, FlashBank, FlashRegion, FlashSector, FLASH_REGIONS, WRITE_SIZE}; +use crate::pac; + +pub(crate) const fn is_default_layout() -> bool { + true +} + +pub(crate) const fn get_flash_regions() -> &'static [&'static FlashRegion] { + &FLASH_REGIONS +} + +pub(crate) unsafe fn lock() { + pac::FLASH.nscr().modify(|w| w.set_lock(true)); +} + +pub(crate) unsafe fn unlock() { + while busy() {} + + if pac::FLASH.nscr().read().lock() { + pac::FLASH.nskeyr().write_value(0x4567_0123); + pac::FLASH.nskeyr().write_value(0xCDEF_89AB); + } +} + +pub(crate) unsafe fn enable_blocking_write() { + assert_eq!(0, WRITE_SIZE % 4); + pac::FLASH.nscr().write(|w| w.set_pg(true)); +} + +pub(crate) unsafe fn disable_blocking_write() { + pac::FLASH.nscr().write(|w| w.set_pg(false)); +} + +pub(crate) unsafe fn blocking_write(start_address: u32, buf: &[u8; WRITE_SIZE]) -> Result<(), Error> { + let mut address = start_address; + for val in buf.chunks(4) { + write_volatile(address as *mut u32, u32::from_le_bytes(unwrap!(val.try_into()))); + address += val.len() as u32; + + // prevents parallelism errors + fence(Ordering::SeqCst); + } + + wait_ready_blocking() +} + +pub(crate) unsafe fn blocking_erase_sector(sector: &FlashSector) -> Result<(), Error> { + assert!(sector.index_in_bank < 8); + + while busy() {} + + interrupt::free(|_| { + pac::FLASH.nscr().modify(|w| { + // BKSEL ignores SWAP_BANK, so we must take it into account here + w.set_bksel(match (sector.bank, banks_swapped()) { + (FlashBank::Bank1, false) => Bksel::BANK1, + (FlashBank::Bank2, true) => Bksel::BANK1, + (FlashBank::Bank2, false) => Bksel::BANK2, + (FlashBank::Bank1, true) => Bksel::BANK2, + }); + w.set_snb(sector.index_in_bank); + w.set_ser(true); + w.set_strt(true); + }) + }); + + let ret = wait_ready_blocking(); + pac::FLASH.nscr().modify(|w| w.set_ser(false)); + ret +} + +pub(crate) unsafe fn wait_ready_blocking() -> Result<(), Error> { + loop { + let sr = pac::FLASH.nssr().read(); + + if !sr_busy(sr) { + if sr.wrperr() { + return Err(Error::Protected); + } + if sr.pgserr() { + return Err(Error::Seq); + } + if sr.strberr() { + // writing several times to the same byte in the write buffer + return Err(Error::Prog); + } + if sr.incerr() { + // attempting write operation before completion of previous + // write operation + return Err(Error::Seq); + } + + return Ok(()); + } + } +} + +pub(crate) unsafe fn clear_all_err() { + pac::FLASH.nsccr().modify(|w| { + w.set_clr_wrperr(true); + w.set_clr_pgserr(true); + w.set_clr_strberr(true); + w.set_clr_incerr(true); + }) +} + +/// Get the current SWAP_BANK option. +/// +/// This value is only loaded on system or power-on reset. `perform_bank_swap()` +/// will not reflect here. +pub fn banks_swapped() -> bool { + pac::FLASH.optcr().read().swap_bank() +} + +/// Logical, persistent swap of flash banks 1 and 2. +/// +/// This allows the application to write a new firmware blob into bank 2, then +/// swap the banks and perform a reset, loading the new firmware. +/// +/// Swap does not take effect until system or power-on reset. +/// +/// PLEASE READ THE REFERENCE MANUAL - there are nuances to this feature. For +/// instance, erase commands and interrupt enables which take a flash bank as a +/// parameter ignore the swap! +pub fn perform_bank_swap() { + while busy() {} + + unsafe { + clear_all_err(); + } + + // unlock OPTLOCK + pac::FLASH.optkeyr().write(|w| *w = 0x0819_2A3B); + pac::FLASH.optkeyr().write(|w| *w = 0x4C5D_6E7F); + while pac::FLASH.optcr().read().optlock() {} + + // toggle SWAP_BANK option + pac::FLASH.optsr_prg().modify(|w| w.set_swap_bank(!banks_swapped())); + + // load option bytes + pac::FLASH.optcr().modify(|w| w.set_optstrt(true)); + while pac::FLASH.optcr().read().optstrt() {} + + // re-lock OPTLOCK + pac::FLASH.optcr().modify(|w| w.set_optlock(true)); +} + +fn sr_busy(sr: Nssr) -> bool { + // Note: RM0492 sometimes incorrectly refers to WBNE as NSWBNE + sr.bsy() || sr.dbne() || sr.wbne() +} + +fn busy() -> bool { + let sr = pac::FLASH.nssr().read(); + sr_busy(sr) +} diff --git a/embassy-stm32/src/flash/h7.rs b/embassy-stm32/src/flash/h7.rs index ae395d568..254915381 100644 --- a/embassy-stm32/src/flash/h7.rs +++ b/embassy-stm32/src/flash/h7.rs @@ -1,4 +1,3 @@ -use core::convert::TryInto; use core::ptr::write_volatile; use core::sync::atomic::{fence, Ordering}; @@ -63,7 +62,7 @@ pub(crate) unsafe fn blocking_write(start_address: u32, buf: &[u8; WRITE_SIZE]) let mut res = None; let mut address = start_address; for val in buf.chunks(4) { - write_volatile(address as *mut u32, u32::from_le_bytes(val.try_into().unwrap())); + write_volatile(address as *mut u32, u32::from_le_bytes(unwrap!(val.try_into()))); address += val.len() as u32; res = Some(blocking_wait_ready(bank)); @@ -72,18 +71,18 @@ pub(crate) unsafe fn blocking_write(start_address: u32, buf: &[u8; WRITE_SIZE]) w.set_eop(true); } }); - if res.unwrap().is_err() { + if unwrap!(res).is_err() { break; } } - bank.cr().write(|w| w.set_pg(false)); - cortex_m::asm::isb(); cortex_m::asm::dsb(); fence(Ordering::SeqCst); - res.unwrap() + bank.cr().write(|w| w.set_pg(false)); + + unwrap!(res) } pub(crate) unsafe fn blocking_erase_sector(sector: &FlashSector) -> Result<(), Error> { @@ -100,6 +99,10 @@ pub(crate) unsafe fn blocking_erase_sector(sector: &FlashSector) -> Result<(), E w.set_start(true); }); + cortex_m::asm::isb(); + cortex_m::asm::dsb(); + fence(Ordering::SeqCst); + let ret: Result<(), Error> = blocking_wait_ready(bank); bank.cr().modify(|w| w.set_ser(false)); bank_clear_all_err(bank); diff --git a/embassy-stm32/src/flash/l.rs b/embassy-stm32/src/flash/l.rs index b14224bff..ea00bf499 100644 --- a/embassy-stm32/src/flash/l.rs +++ b/embassy-stm32/src/flash/l.rs @@ -23,6 +23,9 @@ pub(crate) unsafe fn lock() { w.set_prglock(true); w.set_pelock(true); }); + + #[cfg(any(flash_l5))] + pac::FLASH.nscr().modify(|w| w.set_nslock(true)); } pub(crate) unsafe fn unlock() { @@ -46,6 +49,14 @@ pub(crate) unsafe fn unlock() { pac::FLASH.prgkeyr().write_value(0x1314_1516); } } + + #[cfg(any(flash_l5))] + { + if pac::FLASH.nscr().read().nslock() { + pac::FLASH.nskeyr().write_value(0x4567_0123); + pac::FLASH.nskeyr().write_value(0xCDEF_89AB); + } + } } pub(crate) unsafe fn enable_blocking_write() { @@ -53,17 +64,23 @@ pub(crate) unsafe fn enable_blocking_write() { #[cfg(any(flash_wl, flash_wb, flash_l4))] pac::FLASH.cr().write(|w| w.set_pg(true)); + + #[cfg(any(flash_l5))] + pac::FLASH.nscr().write(|w| w.set_nspg(true)); } pub(crate) unsafe fn disable_blocking_write() { #[cfg(any(flash_wl, flash_wb, flash_l4))] pac::FLASH.cr().write(|w| w.set_pg(false)); + + #[cfg(any(flash_l5))] + pac::FLASH.nscr().write(|w| w.set_nspg(false)); } pub(crate) unsafe fn blocking_write(start_address: u32, buf: &[u8; WRITE_SIZE]) -> Result<(), Error> { let mut address = start_address; for val in buf.chunks(4) { - write_volatile(address as *mut u32, u32::from_le_bytes(val.try_into().unwrap())); + write_volatile(address as *mut u32, u32::from_le_bytes(unwrap!(val.try_into()))); address += val.len() as u32; // prevents parallelism errors @@ -84,13 +101,25 @@ pub(crate) unsafe fn blocking_erase_sector(sector: &FlashSector) -> Result<(), E write_volatile(sector.start as *mut u32, 0xFFFFFFFF); } - #[cfg(any(flash_wl, flash_wb, flash_l4))] + #[cfg(any(flash_wl, flash_wb, flash_l4, flash_l5))] { let idx = (sector.start - super::FLASH_BASE as u32) / super::BANK1_REGION.erase_size as u32; #[cfg(flash_l4)] let (idx, bank) = if idx > 255 { (idx - 256, true) } else { (idx, false) }; + #[cfg(flash_l5)] + let (idx, bank) = if pac::FLASH.optr().read().dbank() { + if idx > 255 { + (idx - 256, Some(true)) + } else { + (idx, Some(false)) + } + } else { + (idx, None) + }; + + #[cfg(not(flash_l5))] pac::FLASH.cr().modify(|w| { w.set_per(true); w.set_pnb(idx as u8); @@ -101,6 +130,16 @@ pub(crate) unsafe fn blocking_erase_sector(sector: &FlashSector) -> Result<(), E #[cfg(any(flash_l4))] w.set_bker(bank); }); + + #[cfg(flash_l5)] + pac::FLASH.nscr().modify(|w| { + w.set_nsper(true); + w.set_nspnb(idx as u8); + if let Some(bank) = bank { + w.set_nsbker(bank); + } + w.set_nsstrt(true); + }); } let ret: Result<(), Error> = wait_ready_blocking(); @@ -108,6 +147,9 @@ pub(crate) unsafe fn blocking_erase_sector(sector: &FlashSector) -> Result<(), E #[cfg(any(flash_wl, flash_wb, flash_l4))] pac::FLASH.cr().modify(|w| w.set_per(false)); + #[cfg(any(flash_l5))] + pac::FLASH.nscr().modify(|w| w.set_nsper(false)); + #[cfg(any(flash_l0, flash_l1))] pac::FLASH.pecr().modify(|w| { w.set_erase(false); @@ -121,42 +163,78 @@ pub(crate) unsafe fn blocking_erase_sector(sector: &FlashSector) -> Result<(), E pub(crate) unsafe fn clear_all_err() { // read and write back the same value. // This clears all "write 1 to clear" bits. + #[cfg(not(flash_l5))] pac::FLASH.sr().modify(|_| {}); + + #[cfg(flash_l5)] + pac::FLASH.nssr().modify(|_| {}); } unsafe fn wait_ready_blocking() -> Result<(), Error> { loop { - let sr = pac::FLASH.sr().read(); + #[cfg(not(flash_l5))] + { + let sr = pac::FLASH.sr().read(); - if !sr.bsy() { - #[cfg(any(flash_wl, flash_wb, flash_l4))] - if sr.progerr() { - return Err(Error::Prog); + if !sr.bsy() { + #[cfg(any(flash_wl, flash_wb, flash_l4))] + if sr.progerr() { + return Err(Error::Prog); + } + + if sr.wrperr() { + return Err(Error::Protected); + } + + if sr.pgaerr() { + return Err(Error::Unaligned); + } + + if sr.sizerr() { + return Err(Error::Size); + } + + #[cfg(any(flash_wl, flash_wb, flash_l4))] + if sr.miserr() { + return Err(Error::Miss); + } + + #[cfg(any(flash_wl, flash_wb, flash_l4))] + if sr.pgserr() { + return Err(Error::Seq); + } + + return Ok(()); } + } - if sr.wrperr() { - return Err(Error::Protected); + #[cfg(flash_l5)] + { + let nssr = pac::FLASH.nssr().read(); + + if !nssr.nsbsy() { + if nssr.nsprogerr() { + return Err(Error::Prog); + } + + if nssr.nswrperr() { + return Err(Error::Protected); + } + + if nssr.nspgaerr() { + return Err(Error::Unaligned); + } + + if nssr.nssizerr() { + return Err(Error::Size); + } + + if nssr.nspgserr() { + return Err(Error::Seq); + } + + return Ok(()); } - - if sr.pgaerr() { - return Err(Error::Unaligned); - } - - if sr.sizerr() { - return Err(Error::Size); - } - - #[cfg(any(flash_wl, flash_wb, flash_l4))] - if sr.miserr() { - return Err(Error::Miss); - } - - #[cfg(any(flash_wl, flash_wb, flash_l4))] - if sr.pgserr() { - return Err(Error::Seq); - } - - return Ok(()); } } } diff --git a/embassy-stm32/src/flash/mod.rs b/embassy-stm32/src/flash/mod.rs index 47232f4a4..88fe6a291 100644 --- a/embassy-stm32/src/flash/mod.rs +++ b/embassy-stm32/src/flash/mod.rs @@ -89,22 +89,26 @@ pub enum FlashBank { Bank1 = 0, /// Bank 2 Bank2 = 1, - /// OTP region - Otp, } -#[cfg_attr(any(flash_l0, flash_l1, flash_l4, flash_wl, flash_wb), path = "l.rs")] +#[cfg_attr(any(flash_l0, flash_l1, flash_l4, flash_l5, flash_wl, flash_wb), path = "l.rs")] #[cfg_attr(flash_f0, path = "f0.rs")] #[cfg_attr(any(flash_f1, flash_f3), path = "f1f3.rs")] +#[cfg_attr(flash_f2, path = "f2.rs")] #[cfg_attr(flash_f4, path = "f4.rs")] #[cfg_attr(flash_f7, path = "f7.rs")] -#[cfg_attr(any(flash_g0, flash_g4), path = "g.rs")] +#[cfg_attr(any(flash_g0, flash_g4c2, flash_g4c3, flash_g4c4), path = "g.rs")] #[cfg_attr(flash_h7, path = "h7.rs")] #[cfg_attr(flash_h7ab, path = "h7.rs")] +#[cfg_attr(flash_u5, path = "u5.rs")] +#[cfg_attr(flash_h5, path = "h5.rs")] +#[cfg_attr(flash_h50, path = "h50.rs")] +#[cfg_attr(flash_u0, path = "u0.rs")] #[cfg_attr( not(any( - flash_l0, flash_l1, flash_l4, flash_wl, flash_wb, flash_f0, flash_f1, flash_f3, flash_f4, flash_f7, flash_g0, - flash_g4, flash_h7, flash_h7ab + flash_l0, flash_l1, flash_l4, flash_l5, flash_wl, flash_wb, flash_f0, flash_f1, flash_f2, flash_f3, flash_f4, + flash_f7, flash_g0, flash_g4c2, flash_g4c3, flash_g4c4, flash_h7, flash_h7ab, flash_u5, flash_h50, flash_u0, + flash_h5, )), path = "other.rs" )] diff --git a/embassy-stm32/src/flash/u0.rs b/embassy-stm32/src/flash/u0.rs new file mode 100644 index 000000000..bfdbd15a5 --- /dev/null +++ b/embassy-stm32/src/flash/u0.rs @@ -0,0 +1,96 @@ +use core::ptr::write_volatile; +use core::sync::atomic::{fence, Ordering}; + +use cortex_m::interrupt; + +use super::{FlashRegion, FlashSector, FLASH_REGIONS, WRITE_SIZE}; +use crate::flash::Error; +use crate::pac; + +pub(crate) const fn is_default_layout() -> bool { + true +} + +pub(crate) const fn get_flash_regions() -> &'static [&'static FlashRegion] { + &FLASH_REGIONS +} + +pub(crate) unsafe fn lock() { + pac::FLASH.cr().modify(|w| w.set_lock(true)); +} +pub(crate) unsafe fn unlock() { + // Wait, while the memory interface is busy. + while pac::FLASH.sr().read().bsy1() {} + + // Unlock flash + if pac::FLASH.cr().read().lock() { + pac::FLASH.keyr().write(|w| w.set_key(0x4567_0123)); + pac::FLASH.keyr().write(|w| w.set_key(0xCDEF_89AB)); + } +} + +pub(crate) unsafe fn enable_blocking_write() { + assert_eq!(0, WRITE_SIZE % 4); + pac::FLASH.cr().write(|w| w.set_pg(true)); +} + +pub(crate) unsafe fn disable_blocking_write() { + pac::FLASH.cr().write(|w| w.set_pg(false)); +} + +pub(crate) unsafe fn blocking_write(start_address: u32, buf: &[u8; WRITE_SIZE]) -> Result<(), Error> { + let mut address = start_address; + for val in buf.chunks(4) { + write_volatile(address as *mut u32, u32::from_le_bytes(unwrap!(val.try_into()))); + address += val.len() as u32; + + // prevents parallelism errors + fence(Ordering::SeqCst); + } + + wait_ready_blocking() +} + +pub(crate) unsafe fn blocking_erase_sector(sector: &FlashSector) -> Result<(), Error> { + let idx = (sector.start - super::FLASH_BASE as u32) / super::BANK1_REGION.erase_size as u32; + while pac::FLASH.sr().read().bsy1() {} + clear_all_err(); + + interrupt::free(|_| { + pac::FLASH.cr().modify(|w| { + w.set_per(true); + w.set_pnb(idx as u8); + w.set_strt(true); + }); + }); + + let ret: Result<(), Error> = wait_ready_blocking(); + pac::FLASH.cr().modify(|w| w.set_per(false)); + ret +} + +pub(crate) unsafe fn wait_ready_blocking() -> Result<(), Error> { + while pac::FLASH.sr().read().bsy1() {} + + let sr = pac::FLASH.sr().read(); + + if sr.progerr() { + return Err(Error::Prog); + } + + if sr.wrperr() { + return Err(Error::Protected); + } + + if sr.pgaerr() { + return Err(Error::Unaligned); + } + + Ok(()) +} + +pub(crate) unsafe fn clear_all_err() { + // read and write back the same value. + // This clears all "write 1 to clear" bits. + pac::FLASH.sr().modify(|_| {}); +} diff --git a/embassy-stm32/src/flash/u5.rs b/embassy-stm32/src/flash/u5.rs new file mode 100644 index 000000000..0601017ce --- /dev/null +++ b/embassy-stm32/src/flash/u5.rs @@ -0,0 +1,143 @@ +use core::ptr::write_volatile; +use core::sync::atomic::{fence, Ordering}; + +use super::{FlashRegion, FlashSector, FLASH_REGIONS, WRITE_SIZE}; +use crate::flash::Error; +use crate::pac; + +pub(crate) const fn is_default_layout() -> bool { + true +} + +pub(crate) const fn get_flash_regions() -> &'static [&'static FlashRegion] { + &FLASH_REGIONS +} + +pub(crate) unsafe fn lock() { + #[cfg(feature = "trustzone-secure")] + pac::FLASH.seccr().modify(|w| w.set_lock(true)); + #[cfg(not(feature = "trustzone-secure"))] + pac::FLASH.nscr().modify(|w| w.set_lock(true)); +} + +pub(crate) unsafe fn unlock() { + #[cfg(feature = "trustzone-secure")] + if pac::FLASH.seccr().read().lock() { + pac::FLASH.seckeyr().write_value(0x4567_0123); + pac::FLASH.seckeyr().write_value(0xCDEF_89AB); + } + #[cfg(not(feature = "trustzone-secure"))] + if pac::FLASH.nscr().read().lock() { + pac::FLASH.nskeyr().write_value(0x4567_0123); + pac::FLASH.nskeyr().write_value(0xCDEF_89AB); + } +} + +pub(crate) unsafe fn enable_blocking_write() { + assert_eq!(0, WRITE_SIZE % 4); + + #[cfg(feature = "trustzone-secure")] + pac::FLASH.seccr().write(|w| { + w.set_pg(pac::flash::vals::SeccrPg::B_0X1); + }); + #[cfg(not(feature = "trustzone-secure"))] + pac::FLASH.nscr().write(|w| { + w.set_pg(pac::flash::vals::NscrPg::B_0X1); + }); +} + +pub(crate) unsafe fn disable_blocking_write() { + #[cfg(feature = "trustzone-secure")] + pac::FLASH.seccr().write(|w| w.set_pg(pac::flash::vals::SeccrPg::B_0X0)); + #[cfg(not(feature = "trustzone-secure"))] + pac::FLASH.nscr().write(|w| w.set_pg(pac::flash::vals::NscrPg::B_0X0)); +} + +pub(crate) unsafe fn blocking_write(start_address: u32, buf: &[u8; WRITE_SIZE]) -> Result<(), Error> { + let mut address = start_address; + for val in buf.chunks(4) { + write_volatile(address as *mut u32, u32::from_le_bytes(unwrap!(val.try_into()))); + address += val.len() as u32; + + // prevents parallelism errors + fence(Ordering::SeqCst); + } + + blocking_wait_ready() +} + +pub(crate) unsafe fn blocking_erase_sector(sector: &FlashSector) -> Result<(), Error> { + #[cfg(feature = "trustzone-secure")] + pac::FLASH.seccr().modify(|w| { + w.set_per(pac::flash::vals::SeccrPer::B_0X1); + w.set_pnb(sector.index_in_bank) + }); + #[cfg(not(feature = "trustzone-secure"))] + pac::FLASH.nscr().modify(|w| { + w.set_per(pac::flash::vals::NscrPer::B_0X1); + w.set_pnb(sector.index_in_bank) + }); + + #[cfg(feature = "trustzone-secure")] + pac::FLASH.seccr().modify(|w| { + w.set_strt(true); + }); + #[cfg(not(feature = "trustzone-secure"))] + pac::FLASH.nscr().modify(|w| { + w.set_strt(true); + }); + + let ret: Result<(), Error> = blocking_wait_ready(); + #[cfg(feature = "trustzone-secure")] + pac::FLASH + .seccr() + .modify(|w| w.set_per(pac::flash::vals::SeccrPer::B_0X0)); + #[cfg(not(feature = "trustzone-secure"))] + pac::FLASH + .nscr() + .modify(|w| w.set_per(pac::flash::vals::NscrPer::B_0X0)); + clear_all_err(); + ret +} + +pub(crate) unsafe fn clear_all_err() { + // read and write back the same value. + // This clears all "write 1 to clear" bits. + #[cfg(feature = "trustzone-secure")] + pac::FLASH.secsr().modify(|_| {}); + #[cfg(not(feature = "trustzone-secure"))] + pac::FLASH.nssr().modify(|_| {}); +} + +unsafe fn blocking_wait_ready() -> Result<(), Error> { + loop { + #[cfg(feature = "trustzone-secure")] + let sr = pac::FLASH.secsr().read(); + #[cfg(not(feature = "trustzone-secure"))] + let sr = pac::FLASH.nssr().read(); + + if !sr.bsy() { + if sr.pgserr() { + return Err(Error::Seq); + } + + if sr.sizerr() { + return Err(Error::Size); + } + + if sr.pgaerr() { + return Err(Error::Unaligned); + } + + if sr.wrperr() { + return Err(Error::Protected); + } + + if sr.progerr() { + return Err(Error::Prog); + } + + return Ok(()); + } + } +} diff --git a/embassy-stm32/src/fmc.rs b/embassy-stm32/src/fmc.rs index 873c8a70c..83b49a3dd 100644 --- a/embassy-stm32/src/fmc.rs +++ b/embassy-stm32/src/fmc.rs @@ -3,9 +3,8 @@ use core::marker::PhantomData; use embassy_hal_internal::into_ref; -use crate::gpio::sealed::AFType; -use crate::gpio::{Pull, Speed}; -use crate::Peripheral; +use crate::gpio::{AfType, OutputType, Pull, Speed}; +use crate::{rcc, Peripheral}; /// FMC driver pub struct Fmc<'d, T: Instance> { @@ -28,7 +27,7 @@ where /// Enable the FMC peripheral and reset it. pub fn enable(&mut self) { - T::enable_and_reset(); + rcc::enable_and_reset::(); } /// Enable the memory controller on applicable chips. @@ -36,13 +35,15 @@ where // fmc v1 and v2 does not have the fmcen bit // fsmc v1, v2 and v3 does not have the fmcen bit // This is a "not" because it is expected that all future versions have this bit - #[cfg(not(any(fmc_v1x3, fmc_v2x1, fsmc_v1x0, fsmc_v1x3, fsmc_v2x3, fsmc_v3x1)))] + #[cfg(not(any(fmc_v1x3, fmc_v2x1, fsmc_v1x0, fsmc_v1x3, fmc_v4)))] T::REGS.bcr1().modify(|r| r.set_fmcen(true)); + #[cfg(any(fmc_v4))] + T::REGS.nor_psram().bcr1().modify(|r| r.set_fmcen(true)); } /// Get the kernel clock currently in use for this FMC instance. pub fn source_clock_hz(&self) -> u32 { - ::frequency().0 + ::frequency().0 } } @@ -53,19 +54,21 @@ where const REGISTERS: *const () = T::REGS.as_ptr() as *const _; fn enable(&mut self) { - T::enable_and_reset(); + rcc::enable_and_reset::(); } fn memory_controller_enable(&mut self) { // fmc v1 and v2 does not have the fmcen bit // fsmc v1, v2 and v3 does not have the fmcen bit // This is a "not" because it is expected that all future versions have this bit - #[cfg(not(any(fmc_v1x3, fmc_v2x1, fsmc_v1x0, fsmc_v1x3, fsmc_v2x3, fsmc_v3x1)))] + #[cfg(not(any(fmc_v1x3, fmc_v2x1, fsmc_v1x0, fsmc_v1x3, fmc_v4)))] T::REGS.bcr1().modify(|r| r.set_fmcen(true)); + #[cfg(any(fmc_v4))] + T::REGS.nor_psram().bcr1().modify(|r| r.set_fmcen(true)); } fn source_clock_hz(&self) -> u32 { - ::frequency().0 + ::frequency().0 } } @@ -73,8 +76,7 @@ macro_rules! config_pins { ($($pin:ident),*) => { into_ref!($($pin),*); $( - $pin.set_as_af_pull($pin.af_num(), AFType::OutputPushPull, Pull::Up); - $pin.set_speed(Speed::VeryHigh); + $pin.set_as_af($pin.af_num(), AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up)); )* }; } @@ -158,6 +160,26 @@ impl<'d, T: Instance> Fmc<'d, T> { ] )); + fmc_sdram_constructor!(sdram_a13bits_d32bits_4banks_bank1: ( + bank: stm32_fmc::SdramTargetBank::Bank1, + addr: [ + (a0: A0Pin), (a1: A1Pin), (a2: A2Pin), (a3: A3Pin), (a4: A4Pin), (a5: A5Pin), (a6: A6Pin), (a7: A7Pin), (a8: A8Pin), (a9: A9Pin), (a10: A10Pin), (a11: A11Pin), (a12: A12Pin) + ], + ba: [(ba0: BA0Pin), (ba1: BA1Pin)], + d: [ + (d0: D0Pin), (d1: D1Pin), (d2: D2Pin), (d3: D3Pin), (d4: D4Pin), (d5: D5Pin), (d6: D6Pin), (d7: D7Pin), + (d8: D8Pin), (d9: D9Pin), (d10: D10Pin), (d11: D11Pin), (d12: D12Pin), (d13: D13Pin), (d14: D14Pin), (d15: D15Pin), + (d16: D16Pin), (d17: D17Pin), (d18: D18Pin), (d19: D19Pin), (d20: D20Pin), (d21: D21Pin), (d22: D22Pin), (d23: D23Pin), + (d24: D24Pin), (d25: D25Pin), (d26: D26Pin), (d27: D27Pin), (d28: D28Pin), (d29: D29Pin), (d30: D30Pin), (d31: D31Pin) + ], + nbl: [ + (nbl0: NBL0Pin), (nbl1: NBL1Pin), (nbl2: NBL2Pin), (nbl3: NBL3Pin) + ], + ctrl: [ + (sdcke: SDCKE0Pin), (sdclk: SDCLKPin), (sdncas: SDNCASPin), (sdne: SDNE0Pin), (sdnras: SDNRASPin), (sdnwe: SDNWEPin) + ] + )); + fmc_sdram_constructor!(sdram_a12bits_d16bits_4banks_bank2: ( bank: stm32_fmc::SdramTargetBank::Bank2, addr: [ @@ -195,20 +217,39 @@ impl<'d, T: Instance> Fmc<'d, T> { (sdcke: SDCKE1Pin), (sdclk: SDCLKPin), (sdncas: SDNCASPin), (sdne: SDNE1Pin), (sdnras: SDNRASPin), (sdnwe: SDNWEPin) ] )); + + fmc_sdram_constructor!(sdram_a13bits_d32bits_4banks_bank2: ( + bank: stm32_fmc::SdramTargetBank::Bank2, + addr: [ + (a0: A0Pin), (a1: A1Pin), (a2: A2Pin), (a3: A3Pin), (a4: A4Pin), (a5: A5Pin), (a6: A6Pin), (a7: A7Pin), (a8: A8Pin), (a9: A9Pin), (a10: A10Pin), (a11: A11Pin), (a12: A12Pin) + ], + ba: [(ba0: BA0Pin), (ba1: BA1Pin)], + d: [ + (d0: D0Pin), (d1: D1Pin), (d2: D2Pin), (d3: D3Pin), (d4: D4Pin), (d5: D5Pin), (d6: D6Pin), (d7: D7Pin), + (d8: D8Pin), (d9: D9Pin), (d10: D10Pin), (d11: D11Pin), (d12: D12Pin), (d13: D13Pin), (d14: D14Pin), (d15: D15Pin), + (d16: D16Pin), (d17: D17Pin), (d18: D18Pin), (d19: D19Pin), (d20: D20Pin), (d21: D21Pin), (d22: D22Pin), (d23: D23Pin), + (d24: D24Pin), (d25: D25Pin), (d26: D26Pin), (d27: D27Pin), (d28: D28Pin), (d29: D29Pin), (d30: D30Pin), (d31: D31Pin) + ], + nbl: [ + (nbl0: NBL0Pin), (nbl1: NBL1Pin), (nbl2: NBL2Pin), (nbl3: NBL3Pin) + ], + ctrl: [ + (sdcke: SDCKE1Pin), (sdclk: SDCLKPin), (sdncas: SDNCASPin), (sdne: SDNE1Pin), (sdnras: SDNRASPin), (sdnwe: SDNWEPin) + ] + )); } -pub(crate) mod sealed { - pub trait Instance: crate::rcc::sealed::RccPeripheral { - const REGS: crate::pac::fmc::Fmc; - } +trait SealedInstance: crate::rcc::RccPeripheral { + const REGS: crate::pac::fmc::Fmc; } /// FMC instance trait. -pub trait Instance: sealed::Instance + 'static {} +#[allow(private_bounds)] +pub trait Instance: SealedInstance + 'static {} foreach_peripheral!( (fmc, $inst:ident) => { - impl crate::fmc::sealed::Instance for crate::peripherals::$inst { + impl crate::fmc::SealedInstance for crate::peripherals::$inst { const REGS: crate::pac::fmc::Fmc = crate::pac::$inst; } impl crate::fmc::Instance for crate::peripherals::$inst {} diff --git a/embassy-stm32/src/fmt.rs b/embassy-stm32/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-stm32/src/fmt.rs +++ b/embassy-stm32/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-stm32/src/gpio.rs b/embassy-stm32/src/gpio.rs index 1051a13c8..87519f51e 100644 --- a/embassy-stm32/src/gpio.rs +++ b/embassy-stm32/src/gpio.rs @@ -6,7 +6,6 @@ use core::convert::Infallible; use critical_section::CriticalSection; use embassy_hal_internal::{impl_peripheral, into_ref, PeripheralRef}; -use self::sealed::Pin as _; use crate::pac::gpio::{self, vals}; use crate::{pac, peripherals, Peripheral}; @@ -33,7 +32,9 @@ impl<'d> Flex<'d> { } /// Put the pin into input mode. - #[inline] + /// + /// The internal weak pull-up and pull-down resistors will be enabled according to `pull`. + #[inline(never)] pub fn set_as_input(&mut self, pull: Pull) { critical_section::with(|_| { let r = self.pin.block(); @@ -52,35 +53,35 @@ impl<'d> Flex<'d> { Pull::None => vals::CnfIn::FLOATING, }; - let crlh = if n < 8 { 0 } else { 1 }; - r.cr(crlh).modify(|w| { + r.cr(n / 8).modify(|w| { w.set_mode(n % 8, vals::Mode::INPUT); w.set_cnf_in(n % 8, cnf); }); } #[cfg(gpio_v2)] { - r.pupdr().modify(|w| w.set_pupdr(n, pull.into())); + r.pupdr().modify(|w| w.set_pupdr(n, pull.to_pupdr())); r.otyper().modify(|w| w.set_ot(n, vals::Ot::PUSHPULL)); r.moder().modify(|w| w.set_moder(n, vals::Moder::INPUT)); } }); } - /// Put the pin into output mode. + /// Put the pin into push-pull output mode. /// /// The pin level will be whatever was set before (or low by default). If you want it to begin /// at a specific level, call `set_high`/`set_low` on the pin first. - #[inline] + /// + /// The internal weak pull-up and pull-down resistors will be disabled. + #[inline(never)] pub fn set_as_output(&mut self, speed: Speed) { critical_section::with(|_| { let r = self.pin.block(); let n = self.pin.pin() as usize; #[cfg(gpio_v1)] { - let crlh = if n < 8 { 0 } else { 1 }; - r.cr(crlh).modify(|w| { - w.set_mode(n % 8, speed.into()); + r.cr(n / 8).modify(|w| { + w.set_mode(n % 8, speed.to_mode()); w.set_cnf_out(n % 8, vals::CnfOut::PUSHPULL); }); } @@ -88,44 +89,71 @@ impl<'d> Flex<'d> { { r.pupdr().modify(|w| w.set_pupdr(n, vals::Pupdr::FLOATING)); r.otyper().modify(|w| w.set_ot(n, vals::Ot::PUSHPULL)); - self.pin.set_speed(speed); + r.ospeedr().modify(|w| w.set_ospeedr(n, speed.to_ospeedr())); r.moder().modify(|w| w.set_moder(n, vals::Moder::OUTPUT)); } }); } - /// Put the pin into input + output mode. + /// Put the pin into input + open-drain output mode. /// - /// This is commonly used for "open drain" mode. - /// the hardware will drive the line low if you set it to low, and will leave it floating if you set + /// The hardware will drive the line low if you set it to low, and will leave it floating if you set /// it to high, in which case you can read the input to figure out whether another device /// is driving the line low. /// /// The pin level will be whatever was set before (or low by default). If you want it to begin /// at a specific level, call `set_high`/`set_low` on the pin first. - #[inline] - pub fn set_as_input_output(&mut self, speed: Speed, pull: Pull) { + /// + /// The internal weak pull-up and pull-down resistors will be disabled. + #[inline(never)] + pub fn set_as_input_output(&mut self, speed: Speed) { + #[cfg(gpio_v1)] critical_section::with(|_| { let r = self.pin.block(); let n = self.pin.pin() as usize; - #[cfg(gpio_v1)] - { - let crlh = if n < 8 { 0 } else { 1 }; - match pull { - Pull::Up => r.bsrr().write(|w| w.set_bs(n, true)), - Pull::Down => r.bsrr().write(|w| w.set_br(n, true)), - Pull::None => {} - } - r.cr(crlh).modify(|w| w.set_mode(n % 8, speed.into())); - r.cr(crlh).modify(|w| w.set_cnf_out(n % 8, vals::CnfOut::OPENDRAIN)); - } - #[cfg(gpio_v2)] - { - r.pupdr().modify(|w| w.set_pupdr(n, pull.into())); - r.otyper().modify(|w| w.set_ot(n, vals::Ot::OPENDRAIN)); - self.pin.set_speed(speed); - r.moder().modify(|w| w.set_moder(n, vals::Moder::OUTPUT)); - } + r.cr(n / 8).modify(|w| w.set_mode(n % 8, speed.to_mode())); + r.cr(n / 8).modify(|w| w.set_cnf_out(n % 8, vals::CnfOut::OPENDRAIN)); + }); + + #[cfg(gpio_v2)] + self.set_as_input_output_pull(speed, Pull::None); + } + + /// Put the pin into input + open-drain output mode with internal pullup or pulldown. + /// + /// This works like [`Self::set_as_input_output()`], but it also allows to enable the internal + /// weak pull-up or pull-down resistors. + #[inline(never)] + #[cfg(gpio_v2)] + pub fn set_as_input_output_pull(&mut self, speed: Speed, pull: Pull) { + critical_section::with(|_| { + let r = self.pin.block(); + let n = self.pin.pin() as usize; + r.pupdr().modify(|w| w.set_pupdr(n, pull.to_pupdr())); + r.otyper().modify(|w| w.set_ot(n, vals::Ot::OPENDRAIN)); + r.ospeedr().modify(|w| w.set_ospeedr(n, speed.to_ospeedr())); + r.moder().modify(|w| w.set_moder(n, vals::Moder::OUTPUT)); + }); + } + + /// Put the pin into analog mode + /// + /// This mode is used by ADC and COMP but usually there is no need to set this manually + /// as the mode change is handled by the driver. + #[inline] + pub fn set_as_analog(&mut self) { + // TODO: does this also need a critical section, like other methods? + self.pin.set_as_analog(); + } + + /// Put the pin into AF mode, unchecked. + /// + /// This puts the pin into the AF mode, with the requested number and AF type. This is + /// completely unchecked, it can attach the pin to literally any peripheral, so use with care. + #[inline] + pub fn set_as_af_unchecked(&mut self, af_num: u8, af_type: AfType) { + critical_section::with(|_| { + self.pin.set_as_af(af_num, af_type); }); } @@ -203,21 +231,7 @@ impl<'d> Drop for Flex<'d> { #[inline] fn drop(&mut self) { critical_section::with(|_| { - let r = self.pin.block(); - let n = self.pin.pin() as usize; - #[cfg(gpio_v1)] - { - let crlh = if n < 8 { 0 } else { 1 }; - r.cr(crlh).modify(|w| { - w.set_mode(n % 8, vals::Mode::INPUT); - w.set_cnf_in(n % 8, vals::CnfIn::FLOATING); - }); - } - #[cfg(gpio_v2)] - { - r.pupdr().modify(|w| w.set_pupdr(n, vals::Pupdr::FLOATING)); - r.moder().modify(|w| w.set_moder(n, vals::Moder::INPUT)); - } + self.pin.set_as_disconnected(); }); } } @@ -234,57 +248,56 @@ pub enum Pull { Down, } -#[cfg(gpio_v2)] -impl From for vals::Pupdr { - fn from(pull: Pull) -> Self { - use Pull::*; - - match pull { - None => vals::Pupdr::FLOATING, - Up => vals::Pupdr::PULLUP, - Down => vals::Pupdr::PULLDOWN, +impl Pull { + #[cfg(gpio_v2)] + const fn to_pupdr(self) -> vals::Pupdr { + match self { + Pull::None => vals::Pupdr::FLOATING, + Pull::Up => vals::Pupdr::PULLUP, + Pull::Down => vals::Pupdr::PULLDOWN, } } } -/// Speed settings +/// Speed setting for an output. /// -/// These vary dpeending on the chip, ceck the reference manual or datasheet for details. -#[allow(missing_docs)] +/// These vary depending on the chip, check the reference manual and datasheet ("I/O port +/// characteristics") for details. #[derive(Debug, Copy, Clone)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Speed { + #[cfg_attr(gpio_v1, doc = "Output speed OUTPUT2MHZ")] + #[cfg_attr(gpio_v2, doc = "Output speed 00")] Low, + #[cfg_attr(gpio_v1, doc = "Output speed OUTPUT10MHZ")] + #[cfg_attr(gpio_v2, doc = "Output speed 01")] Medium, - #[cfg(not(any(syscfg_f0, gpio_v1)))] + #[cfg_attr(gpio_v2, doc = "Output speed 10")] + #[cfg(not(any(gpio_v1, syscfg_f0)))] High, + #[cfg_attr(gpio_v1, doc = "Output speed OUTPUT50MHZ")] + #[cfg_attr(gpio_v2, doc = "Output speed 11")] VeryHigh, } -#[cfg(gpio_v1)] -impl From for vals::Mode { - fn from(speed: Speed) -> Self { - use Speed::*; - - match speed { - Low => vals::Mode::OUTPUT2MHZ, - Medium => vals::Mode::OUTPUT10MHZ, - VeryHigh => vals::Mode::OUTPUT50MHZ, +impl Speed { + #[cfg(gpio_v1)] + const fn to_mode(self) -> vals::Mode { + match self { + Speed::Low => vals::Mode::OUTPUT2MHZ, + Speed::Medium => vals::Mode::OUTPUT10MHZ, + Speed::VeryHigh => vals::Mode::OUTPUT50MHZ, } } -} -#[cfg(gpio_v2)] -impl From for vals::Ospeedr { - fn from(speed: Speed) -> Self { - use Speed::*; - - match speed { - Low => vals::Ospeedr::LOWSPEED, - Medium => vals::Ospeedr::MEDIUMSPEED, + #[cfg(gpio_v2)] + const fn to_ospeedr(self: Speed) -> vals::Ospeedr { + match self { + Speed::Low => vals::Ospeedr::LOWSPEED, + Speed::Medium => vals::Ospeedr::MEDIUMSPEED, #[cfg(not(syscfg_f0))] - High => vals::Ospeedr::HIGHSPEED, - VeryHigh => vals::Ospeedr::VERYHIGHSPEED, + Speed::High => vals::Ospeedr::HIGHSPEED, + Speed::VeryHigh => vals::Ospeedr::VERYHIGHSPEED, } } } @@ -425,17 +438,29 @@ pub struct OutputOpenDrain<'d> { } impl<'d> OutputOpenDrain<'d> { - /// Create a new GPIO open drain output driver for a [Pin] with the provided [Level] and [Speed], [Pull] configuration. + /// Create a new GPIO open drain output driver for a [Pin] with the provided [Level] and [Speed]. #[inline] - pub fn new(pin: impl Peripheral

+ 'd, initial_output: Level, speed: Speed, pull: Pull) -> Self { + pub fn new(pin: impl Peripheral

+ 'd, initial_output: Level, speed: Speed) -> Self { let mut pin = Flex::new(pin); - match initial_output { Level::High => pin.set_high(), Level::Low => pin.set_low(), } + pin.set_as_input_output(speed); + Self { pin } + } - pin.set_as_input_output(speed, pull); + /// Create a new GPIO open drain output driver for a [Pin] with the provided [Level], [Speed] + /// and [Pull]. + #[inline] + #[cfg(gpio_v2)] + pub fn new_pull(pin: impl Peripheral

+ 'd, initial_output: Level, speed: Speed, pull: Pull) -> Self { + let mut pin = Flex::new(pin); + match initial_output { + Level::High => pin.set_high(), + Level::Low => pin.set_low(), + } + pin.set_as_input_output_pull(speed, pull); Self { pin } } @@ -501,6 +526,8 @@ impl<'d> OutputOpenDrain<'d> { } /// GPIO output type +#[derive(Debug, Copy, Clone)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum OutputType { /// Drive the pin both high or low. PushPull, @@ -508,172 +535,236 @@ pub enum OutputType { OpenDrain, } -impl From for sealed::AFType { - fn from(value: OutputType) -> Self { - match value { - OutputType::OpenDrain => sealed::AFType::OutputOpenDrain, - OutputType::PushPull => sealed::AFType::OutputPushPull, +impl OutputType { + #[cfg(gpio_v1)] + const fn to_cnf_out(self) -> vals::CnfOut { + match self { + OutputType::PushPull => vals::CnfOut::ALTPUSHPULL, + OutputType::OpenDrain => vals::CnfOut::ALTOPENDRAIN, + } + } + + #[cfg(gpio_v2)] + const fn to_ot(self) -> vals::Ot { + match self { + OutputType::PushPull => vals::Ot::PUSHPULL, + OutputType::OpenDrain => vals::Ot::OPENDRAIN, } } } -#[allow(missing_docs)] -pub(crate) mod sealed { - use super::*; +/// Alternate function type settings. +#[derive(Copy, Clone)] +#[cfg(gpio_v1)] +pub struct AfType { + mode: vals::Mode, + cnf: u8, + pull: Pull, +} - /// Alternate function type settings - #[derive(Debug, Copy, Clone)] - #[cfg_attr(feature = "defmt", derive(defmt::Format))] - pub enum AFType { - /// Input - Input, - /// Output, drive the pin both high or low. - OutputPushPull, - /// Output, drive the pin low, or don't drive it at all if the output level is high. - OutputOpenDrain, +#[cfg(gpio_v1)] +impl AfType { + /// Input with optional pullup or pulldown. + pub const fn input(pull: Pull) -> Self { + let cnf_in = match pull { + Pull::Up | Pull::Down => vals::CnfIn::PULL, + Pull::None => vals::CnfIn::FLOATING, + }; + Self { + mode: vals::Mode::INPUT, + cnf: cnf_in.to_bits(), + pull, + } } - pub trait Pin { - fn pin_port(&self) -> u8; - - #[inline] - fn _pin(&self) -> u8 { - self.pin_port() % 16 + /// Output with output type and speed and no pull-up or pull-down. + pub const fn output(output_type: OutputType, speed: Speed) -> Self { + Self { + mode: speed.to_mode(), + cnf: output_type.to_cnf_out().to_bits(), + pull: Pull::None, } - #[inline] - fn _port(&self) -> u8 { - self.pin_port() / 16 + } +} + +#[inline(never)] +#[cfg(gpio_v1)] +fn set_as_af(pin_port: u8, _af_num: u8, af_type: AfType) { + let pin = unsafe { AnyPin::steal(pin_port) }; + let r = pin.block(); + let n = pin._pin() as usize; + + r.cr(n / 8).modify(|w| { + w.set_mode(n % 8, af_type.mode); + // note that we are writing the CNF field, which is exposed as both `cnf_in` and `cnf_out` + // in the PAC. the choice of `cnf_in` instead of `cnf_out` in this code is arbitrary and + // does not affect the result. + w.set_cnf_in(n % 8, vals::CnfIn::from_bits(af_type.cnf)); + }); + + match af_type.pull { + Pull::Up => r.bsrr().write(|w| w.set_bs(n, true)), + Pull::Down => r.bsrr().write(|w| w.set_br(n, true)), + Pull::None => {} + } +} + +/// Alternate function type settings. +#[derive(Copy, Clone)] +#[cfg(gpio_v2)] +pub struct AfType { + pupdr: vals::Pupdr, + ot: vals::Ot, + ospeedr: vals::Ospeedr, +} + +#[cfg(gpio_v2)] +impl AfType { + /// Input with optional pullup or pulldown. + pub const fn input(pull: Pull) -> Self { + Self { + pupdr: pull.to_pupdr(), + ot: vals::Ot::PUSHPULL, + ospeedr: vals::Ospeedr::LOWSPEED, } + } - #[inline] - fn block(&self) -> gpio::Gpio { - pac::GPIO(self._port() as _) + /// Output with output type and speed and no pull-up or pull-down. + pub const fn output(output_type: OutputType, speed: Speed) -> Self { + Self::output_pull(output_type, speed, Pull::None) + } + + /// Output with output type, speed and pull-up or pull-down; + pub const fn output_pull(output_type: OutputType, speed: Speed, pull: Pull) -> Self { + Self { + pupdr: pull.to_pupdr(), + ot: output_type.to_ot(), + ospeedr: speed.to_ospeedr(), } + } +} - /// Set the output as high. - #[inline] - fn set_high(&self) { - let n = self._pin() as _; - self.block().bsrr().write(|w| w.set_bs(n, true)); - } +#[inline(never)] +#[cfg(gpio_v2)] +fn set_as_af(pin_port: u8, af_num: u8, af_type: AfType) { + let pin = unsafe { AnyPin::steal(pin_port) }; + let r = pin.block(); + let n = pin._pin() as usize; - /// Set the output as low. - #[inline] - fn set_low(&self) { - let n = self._pin() as _; - self.block().bsrr().write(|w| w.set_br(n, true)); - } + r.afr(n / 8).modify(|w| w.set_afr(n % 8, af_num)); + r.pupdr().modify(|w| w.set_pupdr(n, af_type.pupdr)); + r.otyper().modify(|w| w.set_ot(n, af_type.ot)); + r.ospeedr().modify(|w| w.set_ospeedr(n, af_type.ospeedr)); + r.moder().modify(|w| w.set_moder(n, vals::Moder::ALTERNATE)); +} - #[inline] - fn set_as_af(&self, af_num: u8, af_type: AFType) { - self.set_as_af_pull(af_num, af_type, Pull::None); - } +#[inline(never)] +fn set_as_analog(pin_port: u8) { + let pin = unsafe { AnyPin::steal(pin_port) }; + let r = pin.block(); + let n = pin._pin() as usize; - #[cfg(gpio_v1)] - #[inline] - fn set_as_af_pull(&self, _af_num: u8, af_type: AFType, pull: Pull) { - // F1 uses the AFIO register for remapping. - // For now, this is not implemented, so af_num is ignored - // _af_num should be zero here, since it is not set by stm32-data - let r = self.block(); - let n = self._pin() as usize; - let crlh = if n < 8 { 0 } else { 1 }; - match af_type { - AFType::Input => { - let cnf = match pull { - Pull::Up => { - r.bsrr().write(|w| w.set_bs(n, true)); - vals::CnfIn::PULL - } - Pull::Down => { - r.bsrr().write(|w| w.set_br(n, true)); - vals::CnfIn::PULL - } - Pull::None => vals::CnfIn::FLOATING, - }; + #[cfg(gpio_v1)] + r.cr(n / 8).modify(|w| { + w.set_mode(n % 8, vals::Mode::INPUT); + w.set_cnf_in(n % 8, vals::CnfIn::ANALOG); + }); - r.cr(crlh).modify(|w| { - w.set_mode(n % 8, vals::Mode::INPUT); - w.set_cnf_in(n % 8, cnf); - }); - } - AFType::OutputPushPull => { - r.cr(crlh).modify(|w| { - w.set_mode(n % 8, vals::Mode::OUTPUT50MHZ); - w.set_cnf_out(n % 8, vals::CnfOut::ALTPUSHPULL); - }); - } - AFType::OutputOpenDrain => { - r.cr(crlh).modify(|w| { - w.set_mode(n % 8, vals::Mode::OUTPUT50MHZ); - w.set_cnf_out(n % 8, vals::CnfOut::ALTOPENDRAIN); - }); - } - } - } + #[cfg(gpio_v2)] + r.moder().modify(|w| w.set_moder(n, vals::Moder::ANALOG)); +} - #[cfg(gpio_v2)] - #[inline] - fn set_as_af_pull(&self, af_num: u8, af_type: AFType, pull: Pull) { - let pin = self._pin() as usize; - let block = self.block(); - block.afr(pin / 8).modify(|w| w.set_afr(pin % 8, af_num)); - match af_type { - AFType::Input => {} - AFType::OutputPushPull => block.otyper().modify(|w| w.set_ot(pin, vals::Ot::PUSHPULL)), - AFType::OutputOpenDrain => block.otyper().modify(|w| w.set_ot(pin, vals::Ot::OPENDRAIN)), - } - block.pupdr().modify(|w| w.set_pupdr(pin, pull.into())); +#[inline(never)] +fn get_pull(pin_port: u8) -> Pull { + let pin = unsafe { AnyPin::steal(pin_port) }; + let r = pin.block(); + let n = pin._pin() as usize; - block.moder().modify(|w| w.set_moder(pin, vals::Moder::ALTERNATE)); - } + #[cfg(gpio_v1)] + return match r.cr(n / 8).read().mode(n % 8) { + vals::Mode::INPUT => match r.cr(n / 8).read().cnf_in(n % 8) { + vals::CnfIn::PULL => match r.odr().read().odr(n) { + vals::Odr::LOW => Pull::Down, + vals::Odr::HIGH => Pull::Up, + }, + _ => Pull::None, + }, + _ => Pull::None, + }; - #[inline] - fn set_as_analog(&self) { - let pin = self._pin() as usize; - let block = self.block(); - #[cfg(gpio_v1)] - { - let crlh = if pin < 8 { 0 } else { 1 }; - block.cr(crlh).modify(|w| { - w.set_mode(pin % 8, vals::Mode::INPUT); - w.set_cnf_in(pin % 8, vals::CnfIn::ANALOG); - }); - } - #[cfg(gpio_v2)] - block.moder().modify(|w| w.set_moder(pin, vals::Moder::ANALOG)); - } + #[cfg(gpio_v2)] + return match r.pupdr().read().pupdr(n) { + vals::Pupdr::FLOATING => Pull::None, + vals::Pupdr::PULLDOWN => Pull::Down, + vals::Pupdr::PULLUP => Pull::Up, + vals::Pupdr::_RESERVED_3 => Pull::None, + }; +} - /// Set the pin as "disconnected", ie doing nothing and consuming the lowest - /// amount of power possible. - /// - /// This is currently the same as set_as_analog but is semantically different really. - /// Drivers should set_as_disconnected pins when dropped. - #[inline] - fn set_as_disconnected(&self) { - self.set_as_analog(); - } +pub(crate) trait SealedPin { + fn pin_port(&self) -> u8; - #[inline] - fn set_speed(&self, speed: Speed) { - let pin = self._pin() as usize; + #[inline] + fn _pin(&self) -> u8 { + self.pin_port() % 16 + } - #[cfg(gpio_v1)] - { - let crlh = if pin < 8 { 0 } else { 1 }; - self.block().cr(crlh).modify(|w| { - w.set_mode(pin % 8, speed.into()); - }); - } + #[inline] + fn _port(&self) -> u8 { + self.pin_port() / 16 + } - #[cfg(gpio_v2)] - self.block().ospeedr().modify(|w| w.set_ospeedr(pin, speed.into())); - } + #[inline] + fn block(&self) -> gpio::Gpio { + pac::GPIO(self._port() as _) + } + + /// Set the output as high. + #[inline] + fn set_high(&self) { + let n = self._pin() as _; + self.block().bsrr().write(|w| w.set_bs(n, true)); + } + + /// Set the output as low. + #[inline] + fn set_low(&self) { + let n = self._pin() as _; + self.block().bsrr().write(|w| w.set_br(n, true)); + } + + #[inline] + fn set_as_af(&self, af_num: u8, af_type: AfType) { + set_as_af(self.pin_port(), af_num, af_type) + } + + #[inline] + fn set_as_analog(&self) { + set_as_analog(self.pin_port()); + } + + /// Set the pin as "disconnected", ie doing nothing and consuming the lowest + /// amount of power possible. + /// + /// This is currently the same as [`Self::set_as_analog()`] but is semantically different + /// really. Drivers should `set_as_disconnected()` pins when dropped. + /// + /// Note that this also disables the internal weak pull-up and pull-down resistors. + #[inline] + fn set_as_disconnected(&self) { + self.set_as_analog(); + } + + /// Get the pull-up configuration. + #[inline] + fn pull(&self) -> Pull { + critical_section::with(|_| get_pull(self.pin_port())) } } /// GPIO pin trait. -pub trait Pin: Peripheral

+ Into + sealed::Pin + Sized + 'static { +#[allow(private_bounds)] +pub trait Pin: Peripheral

+ Into + SealedPin + Sized + 'static { /// EXTI channel assigned to this pin. /// /// For example, PC4 uses EXTI4. @@ -737,7 +828,7 @@ impl Pin for AnyPin { #[cfg(feature = "exti")] type ExtiChannel = crate::exti::AnyChannel; } -impl sealed::Pin for AnyPin { +impl SealedPin for AnyPin { #[inline] fn pin_port(&self) -> u8 { self.pin_port @@ -752,7 +843,7 @@ foreach_pin!( #[cfg(feature = "exti")] type ExtiChannel = peripherals::$exti_ch; } - impl sealed::Pin for peripherals::$pin_name { + impl SealedPin for peripherals::$pin_name { #[inline] fn pin_port(&self) -> u8 { $port_num * 16 + $pin_num @@ -769,16 +860,9 @@ foreach_pin!( pub(crate) unsafe fn init(_cs: CriticalSection) { #[cfg(afio)] - ::enable_and_reset_with_cs(_cs); + crate::rcc::enable_and_reset_with_cs::(_cs); crate::_generated::init_gpio(); - - // Setting this bit is mandatory to use PG[15:2]. - #[cfg(stm32u5)] - crate::pac::PWR.svmcr().modify(|w| { - w.set_io2sv(true); - w.set_io2vmen(true); - }); } impl<'d> embedded_hal_02::digital::v2::InputPin for Input<'d> { @@ -833,6 +917,18 @@ impl<'d> embedded_hal_02::digital::v2::ToggleableOutputPin for Output<'d> { } } +impl<'d> embedded_hal_02::digital::v2::InputPin for OutputOpenDrain<'d> { + type Error = Infallible; + + fn is_high(&self) -> Result { + Ok(self.is_high()) + } + + fn is_low(&self) -> Result { + Ok(self.is_low()) + } +} + impl<'d> embedded_hal_02::digital::v2::OutputPin for OutputOpenDrain<'d> { type Error = Infallible; @@ -1049,9 +1145,3 @@ impl<'d> embedded_hal_1::digital::StatefulOutputPin for Flex<'d> { Ok((*self).is_set_low()) } } - -/// Low-level GPIO manipulation. -#[cfg(feature = "unstable-pac")] -pub mod low_level { - pub use super::sealed::*; -} diff --git a/embassy-stm32/src/hash/mod.rs b/embassy-stm32/src/hash/mod.rs new file mode 100644 index 000000000..4d4a8ec5b --- /dev/null +++ b/embassy-stm32/src/hash/mod.rs @@ -0,0 +1,588 @@ +//! Hash generator (HASH) +use core::cmp::min; +#[cfg(hash_v2)] +use core::future::poll_fn; +use core::marker::PhantomData; +#[cfg(hash_v2)] +use core::ptr; +#[cfg(hash_v2)] +use core::task::Poll; + +use embassy_hal_internal::{into_ref, PeripheralRef}; +use embassy_sync::waitqueue::AtomicWaker; +use stm32_metapac::hash::regs::*; + +use crate::dma::NoDma; +#[cfg(hash_v2)] +use crate::dma::Transfer; +use crate::interrupt::typelevel::Interrupt; +use crate::peripherals::HASH; +use crate::{interrupt, pac, peripherals, rcc, Peripheral}; + +#[cfg(hash_v1)] +const NUM_CONTEXT_REGS: usize = 51; +#[cfg(hash_v3)] +const NUM_CONTEXT_REGS: usize = 103; +#[cfg(any(hash_v2, hash_v4))] +const NUM_CONTEXT_REGS: usize = 54; + +const HASH_BUFFER_LEN: usize = 132; +const DIGEST_BLOCK_SIZE: usize = 128; + +static HASH_WAKER: AtomicWaker = AtomicWaker::new(); + +/// HASH interrupt handler. +pub struct InterruptHandler { + _phantom: PhantomData, +} + +impl interrupt::typelevel::Handler for InterruptHandler { + unsafe fn on_interrupt() { + let bits = T::regs().sr().read(); + if bits.dinis() { + T::regs().imr().modify(|reg| reg.set_dinie(false)); + HASH_WAKER.wake(); + } + if bits.dcis() { + T::regs().imr().modify(|reg| reg.set_dcie(false)); + HASH_WAKER.wake(); + } + } +} + +///Hash algorithm selection +#[derive(Clone, Copy, PartialEq)] +pub enum Algorithm { + /// SHA-1 Algorithm + SHA1 = 0, + + #[cfg(any(hash_v1, hash_v2, hash_v4))] + /// MD5 Algorithm + MD5 = 1, + + /// SHA-224 Algorithm + SHA224 = 2, + + /// SHA-256 Algorithm + SHA256 = 3, + + #[cfg(hash_v3)] + /// SHA-384 Algorithm + SHA384 = 12, + + #[cfg(hash_v3)] + /// SHA-512/224 Algorithm + SHA512_224 = 13, + + #[cfg(hash_v3)] + /// SHA-512/256 Algorithm + SHA512_256 = 14, + + #[cfg(hash_v3)] + /// SHA-256 Algorithm + SHA512 = 15, +} + +/// Input data width selection +#[repr(u8)] +#[derive(Clone, Copy)] +pub enum DataType { + ///32-bit data, no data is swapped. + Width32 = 0, + ///16-bit data, each half-word is swapped. + Width16 = 1, + ///8-bit data, all bytes are swapped. + Width8 = 2, + ///1-bit data, all bits are swapped. + Width1 = 3, +} + +/// Stores the state of the HASH peripheral for suspending/resuming +/// digest calculation. +pub struct Context<'c> { + first_word_sent: bool, + key_sent: bool, + buffer: [u8; HASH_BUFFER_LEN], + buflen: usize, + algo: Algorithm, + format: DataType, + imr: u32, + str: u32, + cr: u32, + csr: [u32; NUM_CONTEXT_REGS], + key: HmacKey<'c>, +} + +type HmacKey<'k> = Option<&'k [u8]>; + +/// HASH driver. +pub struct Hash<'d, T: Instance, D = NoDma> { + _peripheral: PeripheralRef<'d, T>, + #[allow(dead_code)] + dma: PeripheralRef<'d, D>, +} + +impl<'d, T: Instance, D> Hash<'d, T, D> { + /// Instantiates, resets, and enables the HASH peripheral. + pub fn new( + peripheral: impl Peripheral

+ 'd, + dma: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + ) -> Self { + rcc::enable_and_reset::(); + into_ref!(peripheral, dma); + let instance = Self { + _peripheral: peripheral, + dma: dma, + }; + + T::Interrupt::unpend(); + unsafe { T::Interrupt::enable() }; + + instance + } + + /// Starts computation of a new hash and returns the saved peripheral state. + pub fn start<'c>(&mut self, algorithm: Algorithm, format: DataType, key: HmacKey<'c>) -> Context<'c> { + // Define a context for this new computation. + let mut ctx = Context { + first_word_sent: false, + key_sent: false, + buffer: [0; HASH_BUFFER_LEN], + buflen: 0, + algo: algorithm, + format: format, + imr: 0, + str: 0, + cr: 0, + csr: [0; NUM_CONTEXT_REGS], + key, + }; + + // Set the data type in the peripheral. + T::regs().cr().modify(|w| w.set_datatype(ctx.format as u8)); + + // Select the algorithm. + #[cfg(hash_v1)] + if ctx.algo == Algorithm::MD5 { + T::regs().cr().modify(|w| w.set_algo(true)); + } + + #[cfg(hash_v2)] + { + // Select the algorithm. + let mut algo0 = false; + let mut algo1 = false; + if ctx.algo == Algorithm::MD5 || ctx.algo == Algorithm::SHA256 { + algo0 = true; + } + if ctx.algo == Algorithm::SHA224 || ctx.algo == Algorithm::SHA256 { + algo1 = true; + } + T::regs().cr().modify(|w| w.set_algo0(algo0)); + T::regs().cr().modify(|w| w.set_algo1(algo1)); + } + + #[cfg(any(hash_v3, hash_v4))] + T::regs().cr().modify(|w| w.set_algo(ctx.algo as u8)); + + // Configure HMAC mode if a key is provided. + if let Some(key) = ctx.key { + T::regs().cr().modify(|w| w.set_mode(true)); + if key.len() > 64 { + T::regs().cr().modify(|w| w.set_lkey(true)); + } + } + + T::regs().cr().modify(|w| w.set_init(true)); + + // Store and return the state of the peripheral. + self.store_context(&mut ctx); + ctx + } + + /// Restores the peripheral state using the given context, + /// then updates the state with the provided data. + /// Peripheral state is saved upon return. + pub fn update_blocking<'c>(&mut self, ctx: &mut Context<'c>, input: &[u8]) { + // Restore the peripheral state. + self.load_context(&ctx); + + // Load the HMAC key if provided. + if !ctx.key_sent { + if let Some(key) = ctx.key { + self.accumulate_blocking(key); + T::regs().str().write(|w| w.set_dcal(true)); + // Block waiting for digest. + while !T::regs().sr().read().dinis() {} + } + ctx.key_sent = true; + } + + let mut data_waiting = input.len() + ctx.buflen; + if data_waiting < DIGEST_BLOCK_SIZE || (data_waiting < ctx.buffer.len() && !ctx.first_word_sent) { + // There isn't enough data to digest a block, so append it to the buffer. + ctx.buffer[ctx.buflen..ctx.buflen + input.len()].copy_from_slice(input); + ctx.buflen += input.len(); + self.store_context(ctx); + return; + } + + let mut ilen_remaining = input.len(); + let mut input_start = 0; + + // Handle first block. + if !ctx.first_word_sent { + let empty_len = ctx.buffer.len() - ctx.buflen; + let copy_len = min(empty_len, ilen_remaining); + // Fill the buffer. + if copy_len > 0 { + ctx.buffer[ctx.buflen..ctx.buflen + copy_len].copy_from_slice(&input[0..copy_len]); + ctx.buflen += copy_len; + ilen_remaining -= copy_len; + input_start += copy_len; + } + self.accumulate_blocking(ctx.buffer.as_slice()); + data_waiting -= ctx.buflen; + ctx.buflen = 0; + ctx.first_word_sent = true; + } + + if data_waiting < DIGEST_BLOCK_SIZE { + // There isn't enough data remaining to process another block, so store it. + ctx.buffer[0..ilen_remaining].copy_from_slice(&input[input_start..input_start + ilen_remaining]); + ctx.buflen += ilen_remaining; + } else { + // First ingest the data in the buffer. + let empty_len = DIGEST_BLOCK_SIZE - ctx.buflen; + if empty_len > 0 { + let copy_len = min(empty_len, ilen_remaining); + ctx.buffer[ctx.buflen..ctx.buflen + copy_len] + .copy_from_slice(&input[input_start..input_start + copy_len]); + ctx.buflen += copy_len; + ilen_remaining -= copy_len; + input_start += copy_len; + } + self.accumulate_blocking(&ctx.buffer[0..DIGEST_BLOCK_SIZE]); + ctx.buflen = 0; + + // Move any extra data to the now-empty buffer. + let leftovers = ilen_remaining % 64; + if leftovers > 0 { + ctx.buffer[0..leftovers].copy_from_slice(&input[input.len() - leftovers..input.len()]); + ctx.buflen += leftovers; + ilen_remaining -= leftovers; + } + + // Hash the remaining data. + self.accumulate_blocking(&input[input_start..input_start + ilen_remaining]); + } + + // Save the peripheral context. + self.store_context(ctx); + } + + /// Restores the peripheral state using the given context, + /// then updates the state with the provided data. + /// Peripheral state is saved upon return. + #[cfg(hash_v2)] + pub async fn update<'c>(&mut self, ctx: &mut Context<'c>, input: &[u8]) + where + D: crate::hash::Dma, + { + // Restore the peripheral state. + self.load_context(&ctx); + + // Load the HMAC key if provided. + if !ctx.key_sent { + if let Some(key) = ctx.key { + self.accumulate(key).await; + } + ctx.key_sent = true; + } + + let data_waiting = input.len() + ctx.buflen; + if data_waiting < DIGEST_BLOCK_SIZE { + // There isn't enough data to digest a block, so append it to the buffer. + ctx.buffer[ctx.buflen..ctx.buflen + input.len()].copy_from_slice(input); + ctx.buflen += input.len(); + self.store_context(ctx); + return; + } + + // Enable multiple DMA transfers. + T::regs().cr().modify(|w| w.set_mdmat(true)); + + let mut ilen_remaining = input.len(); + let mut input_start = 0; + + // First ingest the data in the buffer. + let empty_len = DIGEST_BLOCK_SIZE - ctx.buflen; + if empty_len > 0 { + let copy_len = min(empty_len, ilen_remaining); + ctx.buffer[ctx.buflen..ctx.buflen + copy_len].copy_from_slice(&input[input_start..input_start + copy_len]); + ctx.buflen += copy_len; + ilen_remaining -= copy_len; + input_start += copy_len; + } + self.accumulate(&ctx.buffer[..DIGEST_BLOCK_SIZE]).await; + ctx.buflen = 0; + + // Move any extra data to the now-empty buffer. + let leftovers = ilen_remaining % DIGEST_BLOCK_SIZE; + if leftovers > 0 { + assert!(ilen_remaining >= leftovers); + ctx.buffer[0..leftovers].copy_from_slice(&input[input.len() - leftovers..input.len()]); + ctx.buflen += leftovers; + ilen_remaining -= leftovers; + } else { + ctx.buffer + .copy_from_slice(&input[input.len() - DIGEST_BLOCK_SIZE..input.len()]); + ctx.buflen += DIGEST_BLOCK_SIZE; + ilen_remaining -= DIGEST_BLOCK_SIZE; + } + + // Hash the remaining data. + self.accumulate(&input[input_start..input_start + ilen_remaining]).await; + + // Save the peripheral context. + self.store_context(ctx); + } + + /// Computes a digest for the given context. + /// The digest buffer must be large enough to accomodate a digest for the selected algorithm. + /// The largest returned digest size is 128 bytes for SHA-512. + /// Panics if the supplied digest buffer is too short. + pub fn finish_blocking<'c>(&mut self, mut ctx: Context<'c>, digest: &mut [u8]) -> usize { + // Restore the peripheral state. + self.load_context(&ctx); + + // Hash the leftover bytes, if any. + self.accumulate_blocking(&ctx.buffer[0..ctx.buflen]); + ctx.buflen = 0; + + //Start the digest calculation. + T::regs().str().write(|w| w.set_dcal(true)); + + // Load the HMAC key if provided. + if let Some(key) = ctx.key { + while !T::regs().sr().read().dinis() {} + self.accumulate_blocking(key); + T::regs().str().write(|w| w.set_dcal(true)); + } + + // Block until digest computation is complete. + while !T::regs().sr().read().dcis() {} + + // Return the digest. + let digest_words = match ctx.algo { + Algorithm::SHA1 => 5, + #[cfg(any(hash_v1, hash_v2, hash_v4))] + Algorithm::MD5 => 4, + Algorithm::SHA224 => 7, + Algorithm::SHA256 => 8, + #[cfg(hash_v3)] + Algorithm::SHA384 => 12, + #[cfg(hash_v3)] + Algorithm::SHA512_224 => 7, + #[cfg(hash_v3)] + Algorithm::SHA512_256 => 8, + #[cfg(hash_v3)] + Algorithm::SHA512 => 16, + }; + + let digest_len_bytes = digest_words * 4; + // Panics if the supplied digest buffer is too short. + if digest.len() < digest_len_bytes { + panic!("Digest buffer must be at least {} bytes long.", digest_words * 4); + } + + let mut i = 0; + while i < digest_words { + let word = T::regs().hr(i).read(); + digest[(i * 4)..((i * 4) + 4)].copy_from_slice(word.to_be_bytes().as_slice()); + i += 1; + } + digest_len_bytes + } + + /// Computes a digest for the given context. + /// The digest buffer must be large enough to accomodate a digest for the selected algorithm. + /// The largest returned digest size is 128 bytes for SHA-512. + /// Panics if the supplied digest buffer is too short. + #[cfg(hash_v2)] + pub async fn finish<'c>(&mut self, mut ctx: Context<'c>, digest: &mut [u8]) -> usize + where + D: crate::hash::Dma, + { + // Restore the peripheral state. + self.load_context(&ctx); + + // Must be cleared prior to the last DMA transfer. + T::regs().cr().modify(|w| w.set_mdmat(false)); + + // Hash the leftover bytes, if any. + self.accumulate(&ctx.buffer[0..ctx.buflen]).await; + ctx.buflen = 0; + + // Load the HMAC key if provided. + if let Some(key) = ctx.key { + self.accumulate(key).await; + } + + // Wait for completion. + poll_fn(|cx| { + // Check if already done. + let bits = T::regs().sr().read(); + if bits.dcis() { + return Poll::Ready(()); + } + // Register waker, then enable interrupts. + HASH_WAKER.register(cx.waker()); + T::regs().imr().modify(|reg| reg.set_dcie(true)); + // Check for completion. + let bits = T::regs().sr().read(); + if bits.dcis() { + Poll::Ready(()) + } else { + Poll::Pending + } + }) + .await; + + // Return the digest. + let digest_words = match ctx.algo { + Algorithm::SHA1 => 5, + #[cfg(any(hash_v1, hash_v2, hash_v4))] + Algorithm::MD5 => 4, + Algorithm::SHA224 => 7, + Algorithm::SHA256 => 8, + #[cfg(hash_v3)] + Algorithm::SHA384 => 12, + #[cfg(hash_v3)] + Algorithm::SHA512_224 => 7, + #[cfg(hash_v3)] + Algorithm::SHA512_256 => 8, + #[cfg(hash_v3)] + Algorithm::SHA512 => 16, + }; + + let digest_len_bytes = digest_words * 4; + // Panics if the supplied digest buffer is too short. + if digest.len() < digest_len_bytes { + panic!("Digest buffer must be at least {} bytes long.", digest_words * 4); + } + + let mut i = 0; + while i < digest_words { + let word = T::regs().hr(i).read(); + digest[(i * 4)..((i * 4) + 4)].copy_from_slice(word.to_be_bytes().as_slice()); + i += 1; + } + digest_len_bytes + } + + /// Push data into the hash core. + fn accumulate_blocking(&mut self, input: &[u8]) { + // Set the number of valid bits. + let num_valid_bits: u8 = (8 * (input.len() % 4)) as u8; + T::regs().str().modify(|w| w.set_nblw(num_valid_bits)); + + let mut i = 0; + while i < input.len() { + let mut word: [u8; 4] = [0; 4]; + let copy_idx = min(i + 4, input.len()); + word[0..copy_idx - i].copy_from_slice(&input[i..copy_idx]); + T::regs().din().write_value(u32::from_ne_bytes(word)); + i += 4; + } + } + + /// Push data into the hash core. + #[cfg(hash_v2)] + async fn accumulate(&mut self, input: &[u8]) + where + D: crate::hash::Dma, + { + // Ignore an input length of 0. + if input.len() == 0 { + return; + } + + // Set the number of valid bits. + let num_valid_bits: u8 = (8 * (input.len() % 4)) as u8; + T::regs().str().modify(|w| w.set_nblw(num_valid_bits)); + + // Configure DMA to transfer input to hash core. + let dma_request = self.dma.request(); + let dst_ptr = T::regs().din().as_ptr(); + let mut num_words = input.len() / 4; + if input.len() % 4 > 0 { + num_words += 1; + } + let src_ptr = ptr::slice_from_raw_parts(input.as_ptr().cast(), num_words); + let dma_transfer = + unsafe { Transfer::new_write_raw(&mut self.dma, dma_request, src_ptr, dst_ptr, Default::default()) }; + T::regs().cr().modify(|w| w.set_dmae(true)); + + // Wait for the transfer to complete. + dma_transfer.await; + } + + /// Save the peripheral state to a context. + fn store_context<'c>(&mut self, ctx: &mut Context<'c>) { + // Block waiting for data in ready. + while !T::regs().sr().read().dinis() {} + + // Store peripheral context. + ctx.imr = T::regs().imr().read().0; + ctx.str = T::regs().str().read().0; + ctx.cr = T::regs().cr().read().0; + let mut i = 0; + while i < NUM_CONTEXT_REGS { + ctx.csr[i] = T::regs().csr(i).read(); + i += 1; + } + } + + /// Restore the peripheral state from a context. + fn load_context(&mut self, ctx: &Context) { + // Restore the peripheral state from the context. + T::regs().imr().write_value(Imr { 0: ctx.imr }); + T::regs().str().write_value(Str { 0: ctx.str }); + T::regs().cr().write_value(Cr { 0: ctx.cr }); + T::regs().cr().modify(|w| w.set_init(true)); + let mut i = 0; + while i < NUM_CONTEXT_REGS { + T::regs().csr(i).write_value(ctx.csr[i]); + i += 1; + } + } +} + +trait SealedInstance { + fn regs() -> pac::hash::Hash; +} + +/// HASH instance trait. +#[allow(private_bounds)] +pub trait Instance: SealedInstance + Peripheral

+ crate::rcc::RccPeripheral + 'static + Send { + /// Interrupt for this HASH instance. + type Interrupt: interrupt::typelevel::Interrupt; +} + +foreach_interrupt!( + ($inst:ident, hash, HASH, GLOBAL, $irq:ident) => { + impl Instance for peripherals::$inst { + type Interrupt = crate::interrupt::typelevel::$irq; + } + + impl SealedInstance for peripherals::$inst { + fn regs() -> crate::pac::hash::Hash { + crate::pac::$inst + } + } + }; +); + +dma_trait!(Dma, Instance); diff --git a/embassy-stm32/src/hrtim/mod.rs b/embassy-stm32/src/hrtim/mod.rs index faefaabbc..13343fc2a 100644 --- a/embassy-stm32/src/hrtim/mod.rs +++ b/embassy-stm32/src/hrtim/mod.rs @@ -7,13 +7,9 @@ use core::marker::PhantomData; use embassy_hal_internal::{into_ref, PeripheralRef}; pub use traits::Instance; -#[allow(unused_imports)] -use crate::gpio::sealed::{AFType, Pin}; -use crate::gpio::AnyPin; -#[cfg(stm32f334)] -use crate::rcc::get_freqs; +use crate::gpio::{AfType, AnyPin, OutputType, Speed}; use crate::time::Hertz; -use crate::Peripheral; +use crate::{rcc, Peripheral}; /// HRTIM burst controller instance. pub struct BurstController { @@ -56,16 +52,13 @@ pub struct ChF { phantom: PhantomData, } -mod sealed { - use super::Instance; - - pub trait AdvancedChannel { - fn raw() -> usize; - } +trait SealedAdvancedChannel { + fn raw() -> usize; } /// Advanced channel instance trait. -pub trait AdvancedChannel: sealed::AdvancedChannel {} +#[allow(private_bounds)] +pub trait AdvancedChannel: SealedAdvancedChannel {} /// HRTIM PWM pin. pub struct PwmPin<'d, T, C> { @@ -87,9 +80,10 @@ macro_rules! advanced_channel_impl { into_ref!(pin); critical_section::with(|_| { pin.set_low(); - pin.set_as_af(pin.af_num(), AFType::OutputPushPull); - #[cfg(gpio_v2)] - pin.set_speed(crate::gpio::Speed::VeryHigh); + pin.set_as_af( + pin.af_num(), + AfType::output(OutputType::PushPull, Speed::VeryHigh), + ); }); PwmPin { _pin: pin.map_into(), @@ -104,9 +98,10 @@ macro_rules! advanced_channel_impl { into_ref!(pin); critical_section::with(|_| { pin.set_low(); - pin.set_as_af(pin.af_num(), AFType::OutputPushPull); - #[cfg(gpio_v2)] - pin.set_speed(crate::gpio::Speed::VeryHigh); + pin.set_as_af( + pin.af_num(), + AfType::output(OutputType::PushPull, Speed::VeryHigh), + ); }); ComplementaryPwmPin { _pin: pin.map_into(), @@ -115,7 +110,7 @@ macro_rules! advanced_channel_impl { } } - impl sealed::AdvancedChannel for $channel { + impl SealedAdvancedChannel for $channel { fn raw() -> usize { $ch_num } @@ -179,10 +174,10 @@ impl<'d, T: Instance> AdvancedPwm<'d, T> { fn new_inner(tim: impl Peripheral

+ 'd) -> Self { into_ref!(tim); - T::enable_and_reset(); + rcc::enable_and_reset::(); #[cfg(stm32f334)] - if unsafe { get_freqs() }.hrtim.is_some() { + if crate::pac::RCC.cfgr3().read().hrtim1sw() == crate::pac::rcc::vals::Timsw::PLL1_P { // Enable and and stabilize the DLL T::regs().dllcr().modify(|w| { w.set_cal(true); diff --git a/embassy-stm32/src/hrtim/traits.rs b/embassy-stm32/src/hrtim/traits.rs index cfd31c47c..75f9971e2 100644 --- a/embassy-stm32/src/hrtim/traits.rs +++ b/embassy-stm32/src/hrtim/traits.rs @@ -1,4 +1,4 @@ -use crate::rcc::sealed::RccPeripheral; +use crate::rcc::RccPeripheral; use crate::time::Hertz; #[repr(u8)] @@ -72,90 +72,92 @@ impl Prescaler { } } -pub(crate) mod sealed { - use super::*; +pub(crate) trait SealedInstance: RccPeripheral { + fn regs() -> crate::pac::hrtim::Hrtim; - pub trait Instance: RccPeripheral { - fn regs() -> crate::pac::hrtim::Hrtim; + #[allow(unused)] + fn set_master_frequency(frequency: Hertz) { + let f = frequency.0; - fn set_master_frequency(frequency: Hertz) { - let f = frequency.0; - #[cfg(not(stm32f334))] - let timer_f = Self::frequency().0; - #[cfg(stm32f334)] - let timer_f = unsafe { crate::rcc::get_freqs() }.hrtim.unwrap_or(Self::frequency()).0; + // TODO: wire up HRTIM to the RCC mux infra. + //#[cfg(stm32f334)] + //let timer_f = unsafe { crate::rcc::get_freqs() }.hrtim.unwrap_or(Self::frequency()).0; + //#[cfg(not(stm32f334))] + let timer_f = Self::frequency().0; - let psc_min = (timer_f / f) / (u16::MAX as u32 / 32); - let psc = if Self::regs().isr().read().dllrdy() { - Prescaler::compute_min_high_res(psc_min) - } else { - Prescaler::compute_min_low_res(psc_min) - }; + let psc_min = (timer_f / f) / (u16::MAX as u32 / 32); + let psc = if Self::regs().isr().read().dllrdy() { + Prescaler::compute_min_high_res(psc_min) + } else { + Prescaler::compute_min_low_res(psc_min) + }; - let timer_f = 32 * (timer_f / psc as u32); - let per: u16 = (timer_f / f) as u16; + let timer_f = 32 * (timer_f / psc as u32); + let per: u16 = (timer_f / f) as u16; - let regs = Self::regs(); + let regs = Self::regs(); - regs.mcr().modify(|w| w.set_ckpsc(psc.into())); - regs.mper().modify(|w| w.set_mper(per)); - } + regs.mcr().modify(|w| w.set_ckpsc(psc.into())); + regs.mper().modify(|w| w.set_mper(per)); + } - fn set_channel_frequency(channel: usize, frequency: Hertz) { - let f = frequency.0; - #[cfg(not(stm32f334))] - let timer_f = Self::frequency().0; - #[cfg(stm32f334)] - let timer_f = unsafe { crate::rcc::get_freqs() }.hrtim.unwrap_or(Self::frequency()).0; + fn set_channel_frequency(channel: usize, frequency: Hertz) { + let f = frequency.0; - let psc_min = (timer_f / f) / (u16::MAX as u32 / 32); - let psc = if Self::regs().isr().read().dllrdy() { - Prescaler::compute_min_high_res(psc_min) - } else { - Prescaler::compute_min_low_res(psc_min) - }; + // TODO: wire up HRTIM to the RCC mux infra. + //#[cfg(stm32f334)] + //let timer_f = unsafe { crate::rcc::get_freqs() }.hrtim.unwrap_or(Self::frequency()).0; + //#[cfg(not(stm32f334))] + let timer_f = Self::frequency().0; - let timer_f = 32 * (timer_f / psc as u32); - let per: u16 = (timer_f / f) as u16; + let psc_min = (timer_f / f) / (u16::MAX as u32 / 32); + let psc = if Self::regs().isr().read().dllrdy() { + Prescaler::compute_min_high_res(psc_min) + } else { + Prescaler::compute_min_low_res(psc_min) + }; - let regs = Self::regs(); + let timer_f = 32 * (timer_f / psc as u32); + let per: u16 = (timer_f / f) as u16; - regs.tim(channel).cr().modify(|w| w.set_ckpsc(psc.into())); - regs.tim(channel).per().modify(|w| w.set_per(per)); - } + let regs = Self::regs(); - /// Set the dead time as a proportion of max_duty - fn set_channel_dead_time(channel: usize, dead_time: u16) { - let regs = Self::regs(); + regs.tim(channel).cr().modify(|w| w.set_ckpsc(psc.into())); + regs.tim(channel).per().modify(|w| w.set_per(per)); + } - let channel_psc: Prescaler = regs.tim(channel).cr().read().ckpsc().into(); + /// Set the dead time as a proportion of max_duty + fn set_channel_dead_time(channel: usize, dead_time: u16) { + let regs = Self::regs(); - // The dead-time base clock runs 4 times slower than the hrtim base clock - // u9::MAX = 511 - let psc_min = (channel_psc as u32 * dead_time as u32) / (4 * 511); - let psc = if Self::regs().isr().read().dllrdy() { - Prescaler::compute_min_high_res(psc_min) - } else { - Prescaler::compute_min_low_res(psc_min) - }; + let channel_psc: Prescaler = regs.tim(channel).cr().read().ckpsc().into(); - let dt_val = (psc as u32 * dead_time as u32) / (4 * channel_psc as u32); + // The dead-time base clock runs 4 times slower than the hrtim base clock + // u9::MAX = 511 + let psc_min = (channel_psc as u32 * dead_time as u32) / (4 * 511); + let psc = if Self::regs().isr().read().dllrdy() { + Prescaler::compute_min_high_res(psc_min) + } else { + Prescaler::compute_min_low_res(psc_min) + }; - regs.tim(channel).dt().modify(|w| { - w.set_dtprsc(psc.into()); - w.set_dtf(dt_val as u16); - w.set_dtr(dt_val as u16); - }); - } + let dt_val = (psc as u32 * dead_time as u32) / (4 * channel_psc as u32); + + regs.tim(channel).dt().modify(|w| { + w.set_dtprsc(psc.into()); + w.set_dtf(dt_val as u16); + w.set_dtr(dt_val as u16); + }); } } /// HRTIM instance trait. -pub trait Instance: sealed::Instance + 'static {} +#[allow(private_bounds)] +pub trait Instance: SealedInstance + 'static {} foreach_interrupt! { ($inst:ident, hrtim, HRTIM, MASTER, $irq:ident) => { - impl sealed::Instance for crate::peripherals::$inst { + impl SealedInstance for crate::peripherals::$inst { fn regs() -> crate::pac::hrtim::Hrtim { crate::pac::$inst } diff --git a/embassy-stm32/src/hsem/mod.rs b/embassy-stm32/src/hsem/mod.rs new file mode 100644 index 000000000..06ab7a9bc --- /dev/null +++ b/embassy-stm32/src/hsem/mod.rs @@ -0,0 +1,187 @@ +//! Hardware Semaphore (HSEM) + +// TODO: This code works for all HSEM implemenations except for the STM32WBA52/4/5xx MCUs. +// Those MCUs have a different HSEM implementation (Secure semaphore lock support, +// Privileged / unprivileged semaphore lock support, Semaphore lock protection via semaphore attribute), +// which is not yet supported by this code. +use embassy_hal_internal::{into_ref, PeripheralRef}; + +use crate::rcc::RccPeripheral; +use crate::{pac, Peripheral}; + +/// HSEM error. +#[derive(Debug)] +pub enum HsemError { + /// Locking the semaphore failed. + LockFailed, +} + +/// CPU core. +/// The enum values are identical to the bus master IDs / core Ids defined for each +/// chip family (i.e. stm32h747 see rm0399 table 95) +#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] +#[repr(u8)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum CoreId { + #[cfg(any(stm32h745, stm32h747, stm32h755, stm32h757))] + /// Cortex-M7, core 1. + Core0 = 0x3, + + #[cfg(any(stm32h745, stm32h747, stm32h755, stm32h757))] + /// Cortex-M4, core 2. + Core1 = 0x1, + + #[cfg(not(any(stm32h745, stm32h747, stm32h755, stm32h757)))] + /// Cortex-M4, core 1 + Core0 = 0x4, + + #[cfg(any(stm32wb, stm32wl))] + /// Cortex-M0+, core 2. + Core1 = 0x8, +} + +/// Get the current core id +/// This code assume that it is only executed on a Cortex-M M0+, M4 or M7 core. +#[inline(always)] +pub fn get_current_coreid() -> CoreId { + let cpuid = unsafe { cortex_m::peripheral::CPUID::PTR.read_volatile().base.read() }; + match cpuid & 0x000000F0 { + #[cfg(any(stm32wb, stm32wl))] + 0x0 => CoreId::Core1, + + #[cfg(not(any(stm32h745, stm32h747, stm32h755, stm32h757)))] + 0x4 => CoreId::Core0, + + #[cfg(any(stm32h745, stm32h747, stm32h755, stm32h757))] + 0x4 => CoreId::Core1, + + #[cfg(any(stm32h745, stm32h747, stm32h755, stm32h757))] + 0x7 => CoreId::Core0, + _ => panic!("Unknown Cortex-M core"), + } +} + +/// Translates the core ID to an index into the interrupt registers. +#[inline(always)] +fn core_id_to_index(core: CoreId) -> usize { + match core { + CoreId::Core0 => 0, + #[cfg(any(stm32h745, stm32h747, stm32h755, stm32h757, stm32wb, stm32wl))] + CoreId::Core1 => 1, + } +} + +/// HSEM driver +pub struct HardwareSemaphore<'d, T: Instance> { + _peri: PeripheralRef<'d, T>, +} + +impl<'d, T: Instance> HardwareSemaphore<'d, T> { + /// Creates a new HardwareSemaphore instance. + pub fn new(peripheral: impl Peripheral

+ 'd) -> Self { + into_ref!(peripheral); + HardwareSemaphore { _peri: peripheral } + } + + /// Locks the semaphore. + /// The 2-step lock procedure consists in a write to lock the semaphore, followed by a read to + /// check if the lock has been successful, carried out from the HSEM_Rx register. + pub fn two_step_lock(&mut self, sem_id: u8, process_id: u8) -> Result<(), HsemError> { + T::regs().r(sem_id as usize).write(|w| { + w.set_procid(process_id); + w.set_coreid(get_current_coreid() as u8); + w.set_lock(true); + }); + let reg = T::regs().r(sem_id as usize).read(); + match ( + reg.lock(), + reg.coreid() == get_current_coreid() as u8, + reg.procid() == process_id, + ) { + (true, true, true) => Ok(()), + _ => Err(HsemError::LockFailed), + } + } + + /// Locks the semaphore. + /// The 1-step procedure consists in a read to lock and check the semaphore in a single step, + /// carried out from the HSEM_RLRx register. + pub fn one_step_lock(&mut self, sem_id: u8) -> Result<(), HsemError> { + let reg = T::regs().rlr(sem_id as usize).read(); + match (reg.lock(), reg.coreid() == get_current_coreid() as u8, reg.procid()) { + (false, true, 0) => Ok(()), + _ => Err(HsemError::LockFailed), + } + } + + /// Unlocks the semaphore. + /// Unlocking a semaphore is a protected process, to prevent accidental clearing by a AHB bus + /// core ID or by a process not having the semaphore lock right. + pub fn unlock(&mut self, sem_id: u8, process_id: u8) { + T::regs().r(sem_id as usize).write(|w| { + w.set_procid(process_id); + w.set_coreid(get_current_coreid() as u8); + w.set_lock(false); + }); + } + + /// Unlocks all semaphores. + /// All semaphores locked by a COREID can be unlocked at once by using the HSEM_CR + /// register. Write COREID and correct KEY value in HSEM_CR. All locked semaphores with a + /// matching COREID are unlocked, and may generate an interrupt when enabled. + pub fn unlock_all(&mut self, key: u16, core_id: u8) { + T::regs().cr().write(|w| { + w.set_key(key); + w.set_coreid(core_id); + }); + } + + /// Checks if the semaphore is locked. + pub fn is_semaphore_locked(&self, sem_id: u8) -> bool { + T::regs().r(sem_id as usize).read().lock() + } + + /// Sets the clear (unlock) key + pub fn set_clear_key(&mut self, key: u16) { + T::regs().keyr().modify(|w| w.set_key(key)); + } + + /// Gets the clear (unlock) key + pub fn get_clear_key(&mut self) -> u16 { + T::regs().keyr().read().key() + } + + /// Sets the interrupt enable bit for the semaphore. + pub fn enable_interrupt(&mut self, core_id: CoreId, sem_x: usize, enable: bool) { + T::regs() + .ier(core_id_to_index(core_id)) + .modify(|w| w.set_ise(sem_x, enable)); + } + + /// Gets the interrupt flag for the semaphore. + pub fn is_interrupt_active(&mut self, core_id: CoreId, sem_x: usize) -> bool { + T::regs().isr(core_id_to_index(core_id)).read().isf(sem_x) + } + + /// Clears the interrupt flag for the semaphore. + pub fn clear_interrupt(&mut self, core_id: CoreId, sem_x: usize) { + T::regs() + .icr(core_id_to_index(core_id)) + .write(|w| w.set_isc(sem_x, false)); + } +} + +trait SealedInstance { + fn regs() -> pac::hsem::Hsem; +} + +/// HSEM instance trait. +#[allow(private_bounds)] +pub trait Instance: SealedInstance + RccPeripheral + Send + 'static {} + +impl SealedInstance for crate::peripherals::HSEM { + fn regs() -> crate::pac::hsem::Hsem { + crate::pac::HSEM + } +} +impl Instance for crate::peripherals::HSEM {} diff --git a/embassy-stm32/src/i2c/mod.rs b/embassy-stm32/src/i2c/mod.rs index 2416005b5..1fc91f1ef 100644 --- a/embassy-stm32/src/i2c/mod.rs +++ b/embassy-stm32/src/i2c/mod.rs @@ -2,26 +2,30 @@ #![macro_use] #[cfg_attr(i2c_v1, path = "v1.rs")] -#[cfg_attr(i2c_v2, path = "v2.rs")] +#[cfg_attr(any(i2c_v2, i2c_v3), path = "v2.rs")] mod _version; use core::future::Future; +use core::iter; use core::marker::PhantomData; -use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef}; +use embassy_hal_internal::{Peripheral, PeripheralRef}; use embassy_sync::waitqueue::AtomicWaker; #[cfg(feature = "time")] use embassy_time::{Duration, Instant}; -use crate::dma::NoDma; -use crate::gpio::sealed::AFType; +use crate::dma::ChannelAndRequest; +#[cfg(gpio_v2)] use crate::gpio::Pull; +use crate::gpio::{AfType, AnyPin, OutputType, SealedPin as _, Speed}; use crate::interrupt::typelevel::Interrupt; +use crate::mode::{Async, Blocking, Mode}; +use crate::rcc::{RccInfo, SealedRccPeripheral}; use crate::time::Hertz; use crate::{interrupt, peripherals}; /// I2C error. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Copy, Clone)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Error { /// Bus error @@ -48,11 +52,13 @@ pub struct Config { /// /// Using external pullup resistors is recommended for I2C. If you do /// have external pullups you should not enable this. + #[cfg(gpio_v2)] pub sda_pullup: bool, /// Enable internal pullup on SCL. /// /// Using external pullup resistors is recommended for I2C. If you do /// have external pullups you should not enable this. + #[cfg(gpio_v2)] pub scl_pullup: bool, /// Timeout. #[cfg(feature = "time")] @@ -62,7 +68,9 @@ pub struct Config { impl Default for Config { fn default() -> Self { Self { + #[cfg(gpio_v2)] sda_pullup: false, + #[cfg(gpio_v2)] scl_pullup: false, #[cfg(feature = "time")] timeout: embassy_time::Duration::from_millis(1000), @@ -70,68 +78,132 @@ impl Default for Config { } } -/// I2C driver. -pub struct I2c<'d, T: Instance, TXDMA = NoDma, RXDMA = NoDma> { - _peri: PeripheralRef<'d, T>, - #[allow(dead_code)] - tx_dma: PeripheralRef<'d, TXDMA>, - #[allow(dead_code)] - rx_dma: PeripheralRef<'d, RXDMA>, - #[cfg(feature = "time")] - timeout: Duration, +impl Config { + fn scl_af(&self) -> AfType { + #[cfg(gpio_v1)] + return AfType::output(OutputType::OpenDrain, Speed::Medium); + #[cfg(gpio_v2)] + return AfType::output_pull( + OutputType::OpenDrain, + Speed::Medium, + match self.scl_pullup { + true => Pull::Up, + false => Pull::None, + }, + ); + } + + fn sda_af(&self) -> AfType { + #[cfg(gpio_v1)] + return AfType::output(OutputType::OpenDrain, Speed::Medium); + #[cfg(gpio_v2)] + return AfType::output_pull( + OutputType::OpenDrain, + Speed::Medium, + match self.sda_pullup { + true => Pull::Up, + false => Pull::None, + }, + ); + } } -impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { +/// I2C driver. +pub struct I2c<'d, M: Mode> { + info: &'static Info, + state: &'static State, + kernel_clock: Hertz, + scl: Option>, + sda: Option>, + tx_dma: Option>, + rx_dma: Option>, + #[cfg(feature = "time")] + timeout: Duration, + _phantom: PhantomData, +} + +impl<'d> I2c<'d, Async> { /// Create a new I2C driver. - pub fn new( + pub fn new( peri: impl Peripheral

+ 'd, scl: impl Peripheral

> + 'd, sda: impl Peripheral

> + 'd, _irq: impl interrupt::typelevel::Binding> + interrupt::typelevel::Binding> + 'd, - tx_dma: impl Peripheral

+ 'd, - rx_dma: impl Peripheral

+ 'd, + tx_dma: impl Peripheral

> + 'd, + rx_dma: impl Peripheral

> + 'd, freq: Hertz, config: Config, ) -> Self { - into_ref!(peri, scl, sda, tx_dma, rx_dma); + Self::new_inner( + peri, + new_pin!(scl, config.scl_af()), + new_pin!(sda, config.sda_af()), + new_dma!(tx_dma), + new_dma!(rx_dma), + freq, + config, + ) + } +} - T::enable_and_reset(); - - scl.set_as_af_pull( - scl.af_num(), - AFType::OutputOpenDrain, - match config.scl_pullup { - true => Pull::Up, - false => Pull::None, - }, - ); - sda.set_as_af_pull( - sda.af_num(), - AFType::OutputOpenDrain, - match config.sda_pullup { - true => Pull::Up, - false => Pull::None, - }, - ); +impl<'d> I2c<'d, Blocking> { + /// Create a new blocking I2C driver. + pub fn new_blocking( + peri: impl Peripheral

+ 'd, + scl: impl Peripheral

> + 'd, + sda: impl Peripheral

> + 'd, + freq: Hertz, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(scl, config.scl_af()), + new_pin!(sda, config.sda_af()), + None, + None, + freq, + config, + ) + } +} +impl<'d, M: Mode> I2c<'d, M> { + /// Create a new I2C driver. + fn new_inner( + _peri: impl Peripheral

+ 'd, + scl: Option>, + sda: Option>, + tx_dma: Option>, + rx_dma: Option>, + freq: Hertz, + config: Config, + ) -> Self { unsafe { T::EventInterrupt::enable() }; unsafe { T::ErrorInterrupt::enable() }; let mut this = Self { - _peri: peri, + info: T::info(), + state: T::state(), + kernel_clock: T::frequency(), + scl, + sda, tx_dma, rx_dma, #[cfg(feature = "time")] timeout: config.timeout, + _phantom: PhantomData, }; - - this.init(freq, config); - + this.enable_and_init(freq, config); this } + fn enable_and_init(&mut self, freq: Hertz, config: Config) { + self.info.rcc.enable_and_reset(); + self.init(freq, config); + } + fn timeout(&self) -> Timeout { Timeout { #[cfg(feature = "time")] @@ -140,6 +212,15 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { } } +impl<'d, M: Mode> Drop for I2c<'d, M> { + fn drop(&mut self) { + self.scl.as_ref().map(|x| x.set_as_disconnected()); + self.sda.as_ref().map(|x| x.set_as_disconnected()); + + self.info.rcc.disable() + } +} + #[derive(Copy, Clone)] struct Timeout { #[cfg(feature = "time")] @@ -162,7 +243,7 @@ impl Timeout { fn with(self, fut: impl Future>) -> impl Future> { #[cfg(feature = "time")] { - use futures::FutureExt; + use futures_util::FutureExt; embassy_futures::select::select(embassy_time::Timer::at(self.deadline), fut).map(|r| match r { embassy_futures::select::Either::First(_) => Err(Error::Timeout), @@ -175,36 +256,28 @@ impl Timeout { } } -pub(crate) mod sealed { - use super::*; +struct State { + #[allow(unused)] + waker: AtomicWaker, +} - pub struct State { - #[allow(unused)] - pub waker: AtomicWaker, - } - - impl State { - pub const fn new() -> Self { - Self { - waker: AtomicWaker::new(), - } +impl State { + const fn new() -> Self { + Self { + waker: AtomicWaker::new(), } } - - pub trait Instance: crate::rcc::RccPeripheral { - fn regs() -> crate::pac::i2c::I2c; - fn state() -> &'static State; - } } -/// I2C peripheral instance -pub trait Instance: sealed::Instance + 'static { - /// Event interrupt for this instance - type EventInterrupt: interrupt::typelevel::Interrupt; - /// Error interrupt for this instance - type ErrorInterrupt: interrupt::typelevel::Interrupt; +struct Info { + regs: crate::pac::i2c::I2c, + rcc: RccInfo, } +peri_trait!( + irqs: [EventInterrupt, ErrorInterrupt], +); + pin_trait!(SclPin, Instance); pin_trait!(SdaPin, Instance); dma_trait!(RxDma, Instance); @@ -234,13 +307,17 @@ impl interrupt::typelevel::Handler for ErrorInte foreach_peripheral!( (i2c, $inst:ident) => { - impl sealed::Instance for peripherals::$inst { - fn regs() -> crate::pac::i2c::I2c { - crate::pac::$inst + #[allow(private_interfaces)] + impl SealedInstance for peripherals::$inst { + fn info() -> &'static Info { + static INFO: Info = Info{ + regs: crate::pac::$inst, + rcc: crate::peripherals::$inst::RCC_INFO, + }; + &INFO } - - fn state() -> &'static sealed::State { - static STATE: sealed::State = sealed::State::new(); + fn state() -> &'static State { + static STATE: State = State::new(); &STATE } } @@ -252,7 +329,7 @@ foreach_peripheral!( }; ); -impl<'d, T: Instance> embedded_hal_02::blocking::i2c::Read for I2c<'d, T> { +impl<'d, M: Mode> embedded_hal_02::blocking::i2c::Read for I2c<'d, M> { type Error = Error; fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Self::Error> { @@ -260,7 +337,7 @@ impl<'d, T: Instance> embedded_hal_02::blocking::i2c::Read for I2c<'d, T> { } } -impl<'d, T: Instance> embedded_hal_02::blocking::i2c::Write for I2c<'d, T> { +impl<'d, M: Mode> embedded_hal_02::blocking::i2c::Write for I2c<'d, M> { type Error = Error; fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Self::Error> { @@ -268,7 +345,7 @@ impl<'d, T: Instance> embedded_hal_02::blocking::i2c::Write for I2c<'d, T> { } } -impl<'d, T: Instance> embedded_hal_02::blocking::i2c::WriteRead for I2c<'d, T> { +impl<'d, M: Mode> embedded_hal_02::blocking::i2c::WriteRead for I2c<'d, M> { type Error = Error; fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Self::Error> { @@ -292,11 +369,11 @@ impl embedded_hal_1::i2c::Error for Error { } } -impl<'d, T: Instance, TXDMA, RXDMA> embedded_hal_1::i2c::ErrorType for I2c<'d, T, TXDMA, RXDMA> { +impl<'d, M: Mode> embedded_hal_1::i2c::ErrorType for I2c<'d, M> { type Error = Error; } -impl<'d, T: Instance> embedded_hal_1::i2c::I2c for I2c<'d, T, NoDma, NoDma> { +impl<'d, M: Mode> embedded_hal_1::i2c::I2c for I2c<'d, M> { fn read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Self::Error> { self.blocking_read(address, read) } @@ -311,14 +388,14 @@ impl<'d, T: Instance> embedded_hal_1::i2c::I2c for I2c<'d, T, NoDma, NoDma> { fn transaction( &mut self, - _address: u8, - _operations: &mut [embedded_hal_1::i2c::Operation<'_>], + address: u8, + operations: &mut [embedded_hal_1::i2c::Operation<'_>], ) -> Result<(), Self::Error> { - todo!(); + self.blocking_transaction(address, operations) } } -impl<'d, T: Instance, TXDMA: TxDma, RXDMA: RxDma> embedded_hal_async::i2c::I2c for I2c<'d, T, TXDMA, RXDMA> { +impl<'d> embedded_hal_async::i2c::I2c for I2c<'d, Async> { async fn read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Self::Error> { self.read(address, read).await } @@ -336,8 +413,142 @@ impl<'d, T: Instance, TXDMA: TxDma, RXDMA: RxDma> embedded_hal_async::i2c: address: u8, operations: &mut [embedded_hal_1::i2c::Operation<'_>], ) -> Result<(), Self::Error> { - let _ = address; - let _ = operations; - todo!() + self.transaction(address, operations).await } } + +/// Frame type in I2C transaction. +/// +/// This tells each method what kind of framing to use, to generate a (repeated) start condition (ST +/// or SR), and/or a stop condition (SP). For read operations, this also controls whether to send an +/// ACK or NACK after the last byte received. +/// +/// For write operations, the following options are identical because they differ only in the (N)ACK +/// treatment relevant for read operations: +/// +/// - `FirstFrame` and `FirstAndNextFrame` +/// - `NextFrame` and `LastFrameNoStop` +/// +/// Abbreviations used below: +/// +/// - `ST` = start condition +/// - `SR` = repeated start condition +/// - `SP` = stop condition +/// - `ACK`/`NACK` = last byte in read operation +#[derive(Copy, Clone)] +#[allow(dead_code)] +enum FrameOptions { + /// `[ST/SR]+[NACK]+[SP]` First frame (of this type) in transaction and also last frame overall. + FirstAndLastFrame, + /// `[ST/SR]+[NACK]` First frame of this type in transaction, last frame in a read operation but + /// not the last frame overall. + FirstFrame, + /// `[ST/SR]+[ACK]` First frame of this type in transaction, neither last frame overall nor last + /// frame in a read operation. + FirstAndNextFrame, + /// `[ACK]` Middle frame in a read operation (neither first nor last). + NextFrame, + /// `[NACK]+[SP]` Last frame overall in this transaction but not the first frame. + LastFrame, + /// `[NACK]` Last frame in a read operation but not last frame overall in this transaction. + LastFrameNoStop, +} + +#[allow(dead_code)] +impl FrameOptions { + /// Sends start or repeated start condition before transfer. + fn send_start(self) -> bool { + match self { + Self::FirstAndLastFrame | Self::FirstFrame | Self::FirstAndNextFrame => true, + Self::NextFrame | Self::LastFrame | Self::LastFrameNoStop => false, + } + } + + /// Sends stop condition after transfer. + fn send_stop(self) -> bool { + match self { + Self::FirstAndLastFrame | Self::LastFrame => true, + Self::FirstFrame | Self::FirstAndNextFrame | Self::NextFrame | Self::LastFrameNoStop => false, + } + } + + /// Sends NACK after last byte received, indicating end of read operation. + fn send_nack(self) -> bool { + match self { + Self::FirstAndLastFrame | Self::FirstFrame | Self::LastFrame | Self::LastFrameNoStop => true, + Self::FirstAndNextFrame | Self::NextFrame => false, + } + } +} + +/// Iterates over operations in transaction. +/// +/// Returns necessary frame options for each operation to uphold the [transaction contract] and have +/// the right start/stop/(N)ACK conditions on the wire. +/// +/// [transaction contract]: embedded_hal_1::i2c::I2c::transaction +#[allow(dead_code)] +fn operation_frames<'a, 'b: 'a>( + operations: &'a mut [embedded_hal_1::i2c::Operation<'b>], +) -> Result, FrameOptions)>, Error> { + use embedded_hal_1::i2c::Operation::{Read, Write}; + + // Check empty read buffer before starting transaction. Otherwise, we would risk halting with an + // error in the middle of the transaction. + // + // In principle, we could allow empty read frames within consecutive read operations, as long as + // at least one byte remains in the final (merged) read operation, but that makes the logic more + // complicated and error-prone. + if operations.iter().any(|op| match op { + Read(read) => read.is_empty(), + Write(_) => false, + }) { + return Err(Error::Overrun); + } + + let mut operations = operations.iter_mut().peekable(); + + let mut next_first_frame = true; + + Ok(iter::from_fn(move || { + let Some(op) = operations.next() else { + return None; + }; + + // Is `op` first frame of its type? + let first_frame = next_first_frame; + let next_op = operations.peek(); + + // Get appropriate frame options as combination of the following properties: + // + // - For each first operation of its type, generate a (repeated) start condition. + // - For the last operation overall in the entire transaction, generate a stop condition. + // - For read operations, check the next operation: if it is also a read operation, we merge + // these and send ACK for all bytes in the current operation; send NACK only for the final + // read operation's last byte (before write or end of entire transaction) to indicate last + // byte read and release the bus for transmission of the bus master's next byte (or stop). + // + // We check the third property unconditionally, i.e. even for write opeartions. This is okay + // because the resulting frame options are identical for write operations. + let frame = match (first_frame, next_op) { + (true, None) => FrameOptions::FirstAndLastFrame, + (true, Some(Read(_))) => FrameOptions::FirstAndNextFrame, + (true, Some(Write(_))) => FrameOptions::FirstFrame, + // + (false, None) => FrameOptions::LastFrame, + (false, Some(Read(_))) => FrameOptions::NextFrame, + (false, Some(Write(_))) => FrameOptions::LastFrameNoStop, + }; + + // Pre-calculate if `next_op` is the first operation of its type. We do this here and not at + // the beginning of the loop because we hand out `op` as iterator value and cannot access it + // anymore in the next iteration. + next_first_frame = match (&op, next_op) { + (_, None) => false, + (Read(_), Some(Write(_))) | (Write(_), Some(Read(_))) => true, + (Read(_), Some(Read(_))) | (Write(_), Some(Write(_))) => false, + }; + + Some((op, frame)) + })) +} diff --git a/embassy-stm32/src/i2c/v1.rs b/embassy-stm32/src/i2c/v1.rs index cbbc201de..28026f83c 100644 --- a/embassy-stm32/src/i2c/v1.rs +++ b/embassy-stm32/src/i2c/v1.rs @@ -10,11 +10,11 @@ use core::task::Poll; use embassy_embedded_hal::SetConfig; use embassy_futures::select::{select, Either}; use embassy_hal_internal::drop::OnDrop; +use embedded_hal_1::i2c::Operation; use super::*; -use crate::dma::Transfer; +use crate::mode::Mode as PeriMode; use crate::pac::i2c; -use crate::time::Hertz; // /!\ /!\ // /!\ Implementation note! /!\ @@ -28,7 +28,7 @@ use crate::time::Hertz; // There's some more details there, and we might have a fix for you. But please let us know if you // hit a case like this! pub unsafe fn on_interrupt() { - let regs = T::regs(); + let regs = T::info().regs; // i2c v2 only woke the task on transfer complete interrupts. v1 uses interrupts for a bunch of // other stuff, so we wake the task on every interrupt. T::state().waker.wake(); @@ -41,39 +41,65 @@ pub unsafe fn on_interrupt() { }); } -impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { +impl<'d, M: PeriMode> I2c<'d, M> { pub(crate) fn init(&mut self, freq: Hertz, _config: Config) { - T::regs().cr1().modify(|reg| { + self.info.regs.cr1().modify(|reg| { reg.set_pe(false); //reg.set_anfoff(false); }); - let timings = Timings::new(T::frequency(), freq); + // Errata: "Start cannot be generated after a misplaced Stop" + // + // > If a master generates a misplaced Stop on the bus (bus error) + // > while the microcontroller I2C peripheral attempts to switch to + // > Master mode by setting the START bit, the Start condition is + // > not properly generated. + // + // This also can occur with falsely detected STOP events, for example + // if the SDA line is shorted to low. + // + // The workaround for this is to trigger the SWRST line AFTER power is + // enabled, AFTER PE is disabled and BEFORE making any other configuration. + // + // It COULD be possible to apply this workaround at runtime, instead of + // only on initialization, however this would require detecting the timeout + // or BUSY lockup condition, and re-configuring the peripheral after reset. + // + // This presents as an ~infinite hang on read or write, as the START condition + // is never generated, meaning the start event is never generated. + self.info.regs.cr1().modify(|reg| { + reg.set_swrst(true); + }); + self.info.regs.cr1().modify(|reg| { + reg.set_swrst(false); + }); - T::regs().cr2().modify(|reg| { + let timings = Timings::new(self.kernel_clock, freq); + + self.info.regs.cr2().modify(|reg| { reg.set_freq(timings.freq); }); - T::regs().ccr().modify(|reg| { + self.info.regs.ccr().modify(|reg| { reg.set_f_s(timings.mode.f_s()); reg.set_duty(timings.duty.duty()); reg.set_ccr(timings.ccr); }); - T::regs().trise().modify(|reg| { + self.info.regs.trise().modify(|reg| { reg.set_trise(timings.trise); }); - T::regs().cr1().modify(|reg| { + self.info.regs.cr1().modify(|reg| { reg.set_pe(true); }); } - fn check_and_clear_error_flags() -> Result { + fn check_and_clear_error_flags(info: &'static Info) -> Result { // Note that flags should only be cleared once they have been registered. If flags are // cleared otherwise, there may be an inherent race condition and flags may be missed. - let sr1 = T::regs().sr1().read(); + let sr1 = info.regs.sr1().read(); if sr1.timeout() { - T::regs().sr1().write(|reg| { + info.regs.sr1().write(|reg| { reg.0 = !0; reg.set_timeout(false); }); @@ -81,7 +107,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { } if sr1.pecerr() { - T::regs().sr1().write(|reg| { + info.regs.sr1().write(|reg| { reg.0 = !0; reg.set_pecerr(false); }); @@ -89,7 +115,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { } if sr1.ovr() { - T::regs().sr1().write(|reg| { + info.regs.sr1().write(|reg| { reg.0 = !0; reg.set_ovr(false); }); @@ -97,7 +123,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { } if sr1.af() { - T::regs().sr1().write(|reg| { + info.regs.sr1().write(|reg| { reg.0 = !0; reg.set_af(false); }); @@ -105,7 +131,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { } if sr1.arlo() { - T::regs().sr1().write(|reg| { + info.regs.sr1().write(|reg| { reg.0 = !0; reg.set_arlo(false); }); @@ -115,7 +141,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { // The errata indicates that BERR may be incorrectly detected. It recommends ignoring and // clearing the BERR bit instead. if sr1.berr() { - T::regs().sr1().write(|reg| { + info.regs.sr1().write(|reg| { reg.0 = !0; reg.set_berr(false); }); @@ -124,46 +150,48 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { Ok(sr1) } - fn write_bytes(&mut self, addr: u8, bytes: &[u8], timeout: Timeout) -> Result<(), Error> { - // Send a START condition + fn write_bytes(&mut self, addr: u8, bytes: &[u8], timeout: Timeout, frame: FrameOptions) -> Result<(), Error> { + if frame.send_start() { + // Send a START condition - T::regs().cr1().modify(|reg| { - reg.set_start(true); - }); + self.info.regs.cr1().modify(|reg| { + reg.set_start(true); + }); - // Wait until START condition was generated - while !Self::check_and_clear_error_flags()?.start() { - timeout.check()?; + // Wait until START condition was generated + while !Self::check_and_clear_error_flags(self.info)?.start() { + timeout.check()?; + } + + // Check if we were the ones to generate START + if self.info.regs.cr1().read().start() || !self.info.regs.sr2().read().msl() { + return Err(Error::Arbitration); + } + + // Set up current address we're trying to talk to + self.info.regs.dr().write(|reg| reg.set_dr(addr << 1)); + + // Wait until address was sent + // Wait for the address to be acknowledged + // Check for any I2C errors. If a NACK occurs, the ADDR bit will never be set. + while !Self::check_and_clear_error_flags(self.info)?.addr() { + timeout.check()?; + } + + // Clear condition by reading SR2 + let _ = self.info.regs.sr2().read(); } - // Also wait until signalled we're master and everything is waiting for us - while { - Self::check_and_clear_error_flags()?; - - let sr2 = T::regs().sr2().read(); - !sr2.msl() && !sr2.busy() - } { - timeout.check()?; - } - - // Set up current address, we're trying to talk to - T::regs().dr().write(|reg| reg.set_dr(addr << 1)); - - // Wait until address was sent - // Wait for the address to be acknowledged - // Check for any I2C errors. If a NACK occurs, the ADDR bit will never be set. - while !Self::check_and_clear_error_flags()?.addr() { - timeout.check()?; - } - - // Clear condition by reading SR2 - let _ = T::regs().sr2().read(); - // Send bytes for c in bytes { self.send_byte(*c, timeout)?; } + if frame.send_stop() { + // Send a STOP condition + self.info.regs.cr1().modify(|reg| reg.set_stop(true)); + } + // Fallthrough is success Ok(()) } @@ -172,18 +200,18 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { // Wait until we're ready for sending while { // Check for any I2C errors. If a NACK occurs, the ADDR bit will never be set. - !Self::check_and_clear_error_flags()?.txe() + !Self::check_and_clear_error_flags(self.info)?.txe() } { timeout.check()?; } // Push out a byte of data - T::regs().dr().write(|reg| reg.set_dr(byte)); + self.info.regs.dr().write(|reg| reg.set_dr(byte)); // Wait until byte is transferred while { // Check for any potential error conditions. - !Self::check_and_clear_error_flags()?.btf() + !Self::check_and_clear_error_flags(self.info)?.btf() } { timeout.check()?; } @@ -194,92 +222,88 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { fn recv_byte(&self, timeout: Timeout) -> Result { while { // Check for any potential error conditions. - Self::check_and_clear_error_flags()?; + Self::check_and_clear_error_flags(self.info)?; - !T::regs().sr1().read().rxne() + !self.info.regs.sr1().read().rxne() } { timeout.check()?; } - let value = T::regs().dr().read().dr(); + let value = self.info.regs.dr().read().dr(); Ok(value) } - fn blocking_read_timeout(&mut self, addr: u8, buffer: &mut [u8], timeout: Timeout) -> Result<(), Error> { - if let Some((last, buffer)) = buffer.split_last_mut() { + fn blocking_read_timeout( + &mut self, + addr: u8, + buffer: &mut [u8], + timeout: Timeout, + frame: FrameOptions, + ) -> Result<(), Error> { + let Some((last, buffer)) = buffer.split_last_mut() else { + return Err(Error::Overrun); + }; + + if frame.send_start() { // Send a START condition and set ACK bit - T::regs().cr1().modify(|reg| { + self.info.regs.cr1().modify(|reg| { reg.set_start(true); reg.set_ack(true); }); // Wait until START condition was generated - while !Self::check_and_clear_error_flags()?.start() { + while !Self::check_and_clear_error_flags(self.info)?.start() { timeout.check()?; } - // Also wait until signalled we're master and everything is waiting for us - while { - let sr2 = T::regs().sr2().read(); - !sr2.msl() && !sr2.busy() - } { - timeout.check()?; + // Check if we were the ones to generate START + if self.info.regs.cr1().read().start() || !self.info.regs.sr2().read().msl() { + return Err(Error::Arbitration); } - // Set up current address, we're trying to talk to - T::regs().dr().write(|reg| reg.set_dr((addr << 1) + 1)); + // Set up current address we're trying to talk to + self.info.regs.dr().write(|reg| reg.set_dr((addr << 1) + 1)); // Wait until address was sent // Wait for the address to be acknowledged - while !Self::check_and_clear_error_flags()?.addr() { + while !Self::check_and_clear_error_flags(self.info)?.addr() { timeout.check()?; } // Clear condition by reading SR2 - let _ = T::regs().sr2().read(); - - // Receive bytes into buffer - for c in buffer { - *c = self.recv_byte(timeout)?; - } - - // Prepare to send NACK then STOP after next byte - T::regs().cr1().modify(|reg| { - reg.set_ack(false); - reg.set_stop(true); - }); - - // Receive last byte - *last = self.recv_byte(timeout)?; - - // Wait for the STOP to be sent. - while T::regs().cr1().read().stop() { - timeout.check()?; - } - - // Fallthrough is success - Ok(()) - } else { - Err(Error::Overrun) + let _ = self.info.regs.sr2().read(); } + + // Receive bytes into buffer + for c in buffer { + *c = self.recv_byte(timeout)?; + } + + // Prepare to send NACK then STOP after next byte + self.info.regs.cr1().modify(|reg| { + if frame.send_nack() { + reg.set_ack(false); + } + if frame.send_stop() { + reg.set_stop(true); + } + }); + + // Receive last byte + *last = self.recv_byte(timeout)?; + + // Fallthrough is success + Ok(()) } /// Blocking read. pub fn blocking_read(&mut self, addr: u8, read: &mut [u8]) -> Result<(), Error> { - self.blocking_read_timeout(addr, read, self.timeout()) + self.blocking_read_timeout(addr, read, self.timeout(), FrameOptions::FirstAndLastFrame) } /// Blocking write. pub fn blocking_write(&mut self, addr: u8, write: &[u8]) -> Result<(), Error> { - let timeout = self.timeout(); - - self.write_bytes(addr, write, timeout)?; - // Send a STOP condition - T::regs().cr1().modify(|reg| reg.set_stop(true)); - // Wait for STOP condition to transmit. - while T::regs().cr1().read().stop() { - timeout.check()?; - } + self.write_bytes(addr, write, self.timeout(), FrameOptions::FirstAndLastFrame)?; // Fallthrough is success Ok(()) @@ -287,10 +311,34 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { /// Blocking write, restart, read. pub fn blocking_write_read(&mut self, addr: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error> { + // Check empty read buffer before starting transaction. Otherwise, we would not generate the + // stop condition below. + if read.is_empty() { + return Err(Error::Overrun); + } + let timeout = self.timeout(); - self.write_bytes(addr, write, timeout)?; - self.blocking_read_timeout(addr, read, timeout)?; + self.write_bytes(addr, write, timeout, FrameOptions::FirstFrame)?; + self.blocking_read_timeout(addr, read, timeout, FrameOptions::FirstAndLastFrame)?; + + Ok(()) + } + + /// Blocking transaction with operations. + /// + /// Consecutive operations of same type are merged. See [transaction contract] for details. + /// + /// [transaction contract]: embedded_hal_1::i2c::I2c::transaction + pub fn blocking_transaction(&mut self, addr: u8, operations: &mut [Operation<'_>]) -> Result<(), Error> { + let timeout = self.timeout(); + + for (op, frame) in operation_frames(operations)? { + match op { + Operation::Read(read) => self.blocking_read_timeout(addr, read, timeout, frame)?, + Operation::Write(write) => self.write_bytes(addr, write, timeout, frame)?, + } + } Ok(()) } @@ -298,118 +346,112 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { // Async #[inline] // pretty sure this should always be inlined - fn enable_interrupts() -> () { - T::regs().cr2().modify(|w| { + fn enable_interrupts(info: &'static Info) -> () { + info.regs.cr2().modify(|w| { w.set_iterren(true); w.set_itevten(true); }); } +} - async fn write_with_stop(&mut self, address: u8, write: &[u8], send_stop: bool) -> Result<(), Error> - where - TXDMA: crate::i2c::TxDma, - { - let dma_transfer = unsafe { - let regs = T::regs(); - regs.cr2().modify(|w| { - // DMA mode can be enabled for transmission by setting the DMAEN bit in the I2C_CR2 register. - w.set_dmaen(true); - w.set_itbufen(false); - }); - // Set the I2C_DR register address in the DMA_SxPAR register. The data will be moved to this address from the memory after each TxE event. - let dst = regs.dr().as_ptr() as *mut u8; - - let ch = &mut self.tx_dma; - let request = ch.request(); - Transfer::new_write(ch, request, write, dst, Default::default()) - }; +impl<'d> I2c<'d, Async> { + async fn write_frame(&mut self, address: u8, write: &[u8], frame: FrameOptions) -> Result<(), Error> { + self.info.regs.cr2().modify(|w| { + // Note: Do not enable the ITBUFEN bit in the I2C_CR2 register if DMA is used for + // reception. + w.set_itbufen(false); + // DMA mode can be enabled for transmission by setting the DMAEN bit in the I2C_CR2 + // register. + w.set_dmaen(true); + // Sending NACK is not necessary (nor possible) for write transfer. + w.set_last(false); + }); + // Sentinel to disable transfer when an error occurs or future is canceled. + // TODO: Generate STOP condition on cancel? let on_drop = OnDrop::new(|| { - let regs = T::regs(); - regs.cr2().modify(|w| { + self.info.regs.cr2().modify(|w| { w.set_dmaen(false); w.set_iterren(false); w.set_itevten(false); }) }); - Self::enable_interrupts(); + if frame.send_start() { + // Send a START condition + self.info.regs.cr1().modify(|reg| { + reg.set_start(true); + }); - // Send a START condition - T::regs().cr1().modify(|reg| { - reg.set_start(true); - }); + // Wait until START condition was generated + poll_fn(|cx| { + self.state.waker.register(cx.waker()); - let state = T::state(); - - // Wait until START condition was generated - poll_fn(|cx| { - state.waker.register(cx.waker()); - - match Self::check_and_clear_error_flags() { - Err(e) => Poll::Ready(Err(e)), - Ok(sr1) => { - if sr1.start() { - Poll::Ready(Ok(())) - } else { - Poll::Pending + match Self::check_and_clear_error_flags(self.info) { + Err(e) => Poll::Ready(Err(e)), + Ok(sr1) => { + if sr1.start() { + Poll::Ready(Ok(())) + } else { + // When pending, (re-)enable interrupts to wake us up. + Self::enable_interrupts(self.info); + Poll::Pending + } } } + }) + .await?; + + // Check if we were the ones to generate START + if self.info.regs.cr1().read().start() || !self.info.regs.sr2().read().msl() { + return Err(Error::Arbitration); } - }) - .await?; - // Also wait until signalled we're master and everything is waiting for us - Self::enable_interrupts(); - poll_fn(|cx| { - state.waker.register(cx.waker()); + // Set up current address we're trying to talk to + self.info.regs.dr().write(|reg| reg.set_dr(address << 1)); - match Self::check_and_clear_error_flags() { - Err(e) => Poll::Ready(Err(e)), - Ok(_) => { - let sr2 = T::regs().sr2().read(); - if !sr2.msl() && !sr2.busy() { - Poll::Pending - } else { - Poll::Ready(Ok(())) + // Wait for the address to be acknowledged + poll_fn(|cx| { + self.state.waker.register(cx.waker()); + + match Self::check_and_clear_error_flags(self.info) { + Err(e) => Poll::Ready(Err(e)), + Ok(sr1) => { + if sr1.addr() { + Poll::Ready(Ok(())) + } else { + // When pending, (re-)enable interrupts to wake us up. + Self::enable_interrupts(self.info); + Poll::Pending + } } } - } - }) - .await?; + }) + .await?; - // Set up current address, we're trying to talk to - Self::enable_interrupts(); - T::regs().dr().write(|reg| reg.set_dr(address << 1)); + // Clear condition by reading SR2 + self.info.regs.sr2().read(); + } - poll_fn(|cx| { - state.waker.register(cx.waker()); - match Self::check_and_clear_error_flags() { - Err(e) => Poll::Ready(Err(e)), - Ok(sr1) => { - if sr1.addr() { - // Clear the ADDR condition by reading SR2. - T::regs().sr2().read(); - Poll::Ready(Ok(())) - } else { - // If we need to go around, then re-enable the interrupts, otherwise nothing - // can wake us up and we'll hang. - Self::enable_interrupts(); - Poll::Pending - } - } - } - }) - .await?; - Self::enable_interrupts(); + let dma_transfer = unsafe { + // Set the I2C_DR register address in the DMA_SxPAR register. The data will be moved to + // this address from the memory after each TxE event. + let dst = self.info.regs.dr().as_ptr() as *mut u8; + + self.tx_dma.as_mut().unwrap().write(write, dst, Default::default()) + }; + + // Wait for bytes to be sent, or an error to occur. let poll_error = poll_fn(|cx| { - state.waker.register(cx.waker()); + self.state.waker.register(cx.waker()); - match Self::check_and_clear_error_flags() { - // Unclear why the Err turbofish is necessary here? The compiler didn’t require it in the other - // identical poll_fn check_and_clear matches. - Err(e) => Poll::Ready(Err::(e)), - Ok(_) => Poll::Pending, + match Self::check_and_clear_error_flags(self.info) { + Err(e) => Poll::Ready(Err::<(), Error>(e)), + Ok(_) => { + // When pending, (re-)enable interrupts to wake us up. + Self::enable_interrupts(self.info); + Poll::Pending + } } }); @@ -419,38 +461,37 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { _ => Ok(()), }?; - // The I2C transfer itself will take longer than the DMA transfer, so wait for that to finish too. - - // 18.3.8 “Master transmitter: In the interrupt routine after the EOT interrupt, disable DMA - // requests then wait for a BTF event before programming the Stop condition.” - - // TODO: If this has to be done “in the interrupt routine after the EOT interrupt”, where to put it? - T::regs().cr2().modify(|w| { + self.info.regs.cr2().modify(|w| { w.set_dmaen(false); }); - Self::enable_interrupts(); - poll_fn(|cx| { - state.waker.register(cx.waker()); + if frame.send_stop() { + // The I2C transfer itself will take longer than the DMA transfer, so wait for that to finish too. - match Self::check_and_clear_error_flags() { - Err(e) => Poll::Ready(Err(e)), - Ok(sr1) => { - if sr1.btf() { - if send_stop { - T::regs().cr1().modify(|w| { - w.set_stop(true); - }); + // 18.3.8 “Master transmitter: In the interrupt routine after the EOT interrupt, disable DMA + // requests then wait for a BTF event before programming the Stop condition.” + poll_fn(|cx| { + self.state.waker.register(cx.waker()); + + match Self::check_and_clear_error_flags(self.info) { + Err(e) => Poll::Ready(Err(e)), + Ok(sr1) => { + if sr1.btf() { + Poll::Ready(Ok(())) + } else { + // When pending, (re-)enable interrupts to wake us up. + Self::enable_interrupts(self.info); + Poll::Pending } - - Poll::Ready(Ok(())) - } else { - Poll::Pending } } - } - }) - .await?; + }) + .await?; + + self.info.regs.cr1().modify(|w| { + w.set_stop(true); + }); + } drop(on_drop); @@ -459,162 +500,153 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { } /// Write. - pub async fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Error> - where - TXDMA: crate::i2c::TxDma, - { - self.write_with_stop(address, write, true).await?; - - // Wait for STOP condition to transmit. - Self::enable_interrupts(); - poll_fn(|cx| { - T::state().waker.register(cx.waker()); - // TODO: error interrupts are enabled here, should we additional check for and return errors? - if T::regs().cr1().read().stop() { - Poll::Pending - } else { - Poll::Ready(Ok(())) - } - }) - .await?; + pub async fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Error> { + self.write_frame(address, write, FrameOptions::FirstAndLastFrame) + .await?; Ok(()) } /// Read. - pub async fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Error> - where - RXDMA: crate::i2c::RxDma, - { - let state = T::state(); - let buffer_len = buffer.len(); + pub async fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Error> { + self.read_frame(address, buffer, FrameOptions::FirstAndLastFrame) + .await?; - let dma_transfer = unsafe { - let regs = T::regs(); - regs.cr2().modify(|w| { - // DMA mode can be enabled for transmission by setting the DMAEN bit in the I2C_CR2 register. - w.set_itbufen(false); - w.set_dmaen(true); - }); - // Set the I2C_DR register address in the DMA_SxPAR register. The data will be moved to this address from the memory after each TxE event. - let src = regs.dr().as_ptr() as *mut u8; + Ok(()) + } - let ch = &mut self.rx_dma; - let request = ch.request(); - Transfer::new_read(ch, request, src, buffer, Default::default()) - }; + async fn read_frame(&mut self, address: u8, buffer: &mut [u8], frame: FrameOptions) -> Result<(), Error> { + if buffer.is_empty() { + return Err(Error::Overrun); + } + // Some branches below depend on whether the buffer contains only a single byte. + let single_byte = buffer.len() == 1; + + self.info.regs.cr2().modify(|w| { + // Note: Do not enable the ITBUFEN bit in the I2C_CR2 register if DMA is used for + // reception. + w.set_itbufen(false); + // DMA mode can be enabled for transmission by setting the DMAEN bit in the I2C_CR2 + // register. + w.set_dmaen(true); + // If, in the I2C_CR2 register, the LAST bit is set, I2C automatically sends a NACK + // after the next byte following EOT_1. The user can generate a Stop condition in + // the DMA Transfer Complete interrupt routine if enabled. + w.set_last(frame.send_nack() && !single_byte); + }); + + // Sentinel to disable transfer when an error occurs or future is canceled. + // TODO: Generate STOP condition on cancel? let on_drop = OnDrop::new(|| { - let regs = T::regs(); - regs.cr2().modify(|w| { + self.info.regs.cr2().modify(|w| { w.set_dmaen(false); w.set_iterren(false); w.set_itevten(false); }) }); - Self::enable_interrupts(); - - // Send a START condition and set ACK bit - T::regs().cr1().modify(|reg| { - reg.set_start(true); - reg.set_ack(true); - }); - - // Wait until START condition was generated - poll_fn(|cx| { - state.waker.register(cx.waker()); - - match Self::check_and_clear_error_flags() { - Err(e) => Poll::Ready(Err(e)), - Ok(sr1) => { - if sr1.start() { - Poll::Ready(Ok(())) - } else { - Poll::Pending - } - } - } - }) - .await?; - - // Also wait until signalled we're master and everything is waiting for us - Self::enable_interrupts(); - poll_fn(|cx| { - state.waker.register(cx.waker()); - - // blocking read didn’t have a check_and_clear call here, but blocking write did so - // I’m adding it here in case that was an oversight. - match Self::check_and_clear_error_flags() { - Err(e) => Poll::Ready(Err(e)), - Ok(_) => { - let sr2 = T::regs().sr2().read(); - if !sr2.msl() && !sr2.busy() { - Poll::Pending - } else { - Poll::Ready(Ok(())) - } - } - } - }) - .await?; - - // Set up current address, we're trying to talk to - T::regs().dr().write(|reg| reg.set_dr((address << 1) + 1)); - - // Wait for the address to be acknowledged - - Self::enable_interrupts(); - poll_fn(|cx| { - state.waker.register(cx.waker()); - - match Self::check_and_clear_error_flags() { - Err(e) => Poll::Ready(Err(e)), - Ok(sr1) => { - if sr1.addr() { - // 18.3.8: When a single byte must be received: the NACK must be programmed during EV6 - // event, i.e. program ACK=0 when ADDR=1, before clearing ADDR flag. - if buffer_len == 1 { - T::regs().cr1().modify(|w| { - w.set_ack(false); - }); - } - Poll::Ready(Ok(())) - } else { - Poll::Pending - } - } - } - }) - .await?; - - // Clear ADDR condition by reading SR2 - T::regs().sr2().read(); - - // 18.3.8: When a single byte must be received: [snip] Then the - // user can program the STOP condition either after clearing ADDR flag, or in the - // DMA Transfer Complete interrupt routine. - if buffer_len == 1 { - T::regs().cr1().modify(|w| { - w.set_stop(true); + if frame.send_start() { + // Send a START condition and set ACK bit + self.info.regs.cr1().modify(|reg| { + reg.set_start(true); + reg.set_ack(true); }); - } else { - // If, in the I2C_CR2 register, the LAST bit is set, I2C - // automatically sends a NACK after the next byte following EOT_1. The user can - // generate a Stop condition in the DMA Transfer Complete interrupt routine if enabled. - T::regs().cr2().modify(|w| { - w.set_last(true); + + // Wait until START condition was generated + poll_fn(|cx| { + self.state.waker.register(cx.waker()); + + match Self::check_and_clear_error_flags(self.info) { + Err(e) => Poll::Ready(Err(e)), + Ok(sr1) => { + if sr1.start() { + Poll::Ready(Ok(())) + } else { + // When pending, (re-)enable interrupts to wake us up. + Self::enable_interrupts(self.info); + Poll::Pending + } + } + } }) + .await?; + + // Check if we were the ones to generate START + if self.info.regs.cr1().read().start() || !self.info.regs.sr2().read().msl() { + return Err(Error::Arbitration); + } + + // Set up current address we're trying to talk to + self.info.regs.dr().write(|reg| reg.set_dr((address << 1) + 1)); + + // Wait for the address to be acknowledged + poll_fn(|cx| { + self.state.waker.register(cx.waker()); + + match Self::check_and_clear_error_flags(self.info) { + Err(e) => Poll::Ready(Err(e)), + Ok(sr1) => { + if sr1.addr() { + Poll::Ready(Ok(())) + } else { + // When pending, (re-)enable interrupts to wake us up. + Self::enable_interrupts(self.info); + Poll::Pending + } + } + } + }) + .await?; + + // 18.3.8: When a single byte must be received: the NACK must be programmed during EV6 + // event, i.e. program ACK=0 when ADDR=1, before clearing ADDR flag. + if frame.send_nack() && single_byte { + self.info.regs.cr1().modify(|w| { + w.set_ack(false); + }); + } + + // Clear condition by reading SR2 + self.info.regs.sr2().read(); + } else { + // Before starting reception of single byte (but without START condition, i.e. in case + // of continued frame), program NACK to emit at end of this byte. + if frame.send_nack() && single_byte { + self.info.regs.cr1().modify(|w| { + w.set_ack(false); + }); + } } - // Wait for bytes to be received, or an error to occur. - Self::enable_interrupts(); - let poll_error = poll_fn(|cx| { - state.waker.register(cx.waker()); + // 18.3.8: When a single byte must be received: [snip] Then the user can program the STOP + // condition either after clearing ADDR flag, or in the DMA Transfer Complete interrupt + // routine. + if frame.send_stop() && single_byte { + self.info.regs.cr1().modify(|w| { + w.set_stop(true); + }); + } - match Self::check_and_clear_error_flags() { - Err(e) => Poll::Ready(Err::(e)), - _ => Poll::Pending, + let dma_transfer = unsafe { + // Set the I2C_DR register address in the DMA_SxPAR register. The data will be moved + // from this address from the memory after each RxE event. + let src = self.info.regs.dr().as_ptr() as *mut u8; + + self.rx_dma.as_mut().unwrap().read(src, buffer, Default::default()) + }; + + // Wait for bytes to be received, or an error to occur. + let poll_error = poll_fn(|cx| { + self.state.waker.register(cx.waker()); + + match Self::check_and_clear_error_flags(self.info) { + Err(e) => Poll::Ready(Err::<(), Error>(e)), + _ => { + // When pending, (re-)enable interrupts to wake us up. + Self::enable_interrupts(self.info); + Poll::Pending + } } }); @@ -623,18 +655,16 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { _ => Ok(()), }?; - // Wait for the STOP to be sent (STOP bit cleared). - Self::enable_interrupts(); - poll_fn(|cx| { - state.waker.register(cx.waker()); - // TODO: error interrupts are enabled here, should we additional check for and return errors? - if T::regs().cr1().read().stop() { - Poll::Pending - } else { - Poll::Ready(Ok(())) - } - }) - .await?; + self.info.regs.cr2().modify(|w| { + w.set_dmaen(false); + }); + + if frame.send_stop() && !single_byte { + self.info.regs.cr1().modify(|w| { + w.set_stop(true); + }); + } + drop(on_drop); // Fallthrough is success @@ -642,19 +672,31 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { } /// Write, restart, read. - pub async fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error> - where - RXDMA: crate::i2c::RxDma, - TXDMA: crate::i2c::TxDma, - { - self.write_with_stop(address, write, false).await?; - self.read(address, read).await - } -} + pub async fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error> { + // Check empty read buffer before starting transaction. Otherwise, we would not generate the + // stop condition below. + if read.is_empty() { + return Err(Error::Overrun); + } -impl<'d, T: Instance, TXDMA, RXDMA> Drop for I2c<'d, T, TXDMA, RXDMA> { - fn drop(&mut self) { - T::disable(); + self.write_frame(address, write, FrameOptions::FirstFrame).await?; + self.read_frame(address, read, FrameOptions::FirstAndLastFrame).await + } + + /// Transaction with operations. + /// + /// Consecutive operations of same type are merged. See [transaction contract] for details. + /// + /// [transaction contract]: embedded_hal_1::i2c::I2c::transaction + pub async fn transaction(&mut self, addr: u8, operations: &mut [Operation<'_>]) -> Result<(), Error> { + for (op, frame) in operation_frames(operations)? { + match op { + Operation::Read(read) => self.read_frame(addr, read, frame).await?, + Operation::Write(write) => self.write_frame(addr, write, frame).await?, + } + } + + Ok(()) } } @@ -758,20 +800,20 @@ impl Timings { } } -impl<'d, T: Instance> SetConfig for I2c<'d, T> { +impl<'d, M: PeriMode> SetConfig for I2c<'d, M> { type Config = Hertz; type ConfigError = (); fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> { - let timings = Timings::new(T::frequency(), *config); - T::regs().cr2().modify(|reg| { + let timings = Timings::new(self.kernel_clock, *config); + self.info.regs.cr2().modify(|reg| { reg.set_freq(timings.freq); }); - T::regs().ccr().modify(|reg| { + self.info.regs.ccr().modify(|reg| { reg.set_f_s(timings.mode.f_s()); reg.set_duty(timings.duty.duty()); reg.set_ccr(timings.ccr); }); - T::regs().trise().modify(|reg| { + self.info.regs.trise().modify(|reg| { reg.set_trise(timings.trise); }); diff --git a/embassy-stm32/src/i2c/v2.rs b/embassy-stm32/src/i2c/v2.rs index bd3abaac1..8c8df79dd 100644 --- a/embassy-stm32/src/i2c/v2.rs +++ b/embassy-stm32/src/i2c/v2.rs @@ -4,14 +4,13 @@ use core::task::Poll; use embassy_embedded_hal::SetConfig; use embassy_hal_internal::drop::OnDrop; +use embedded_hal_1::i2c::Operation; use super::*; -use crate::dma::Transfer; use crate::pac::i2c; -use crate::time::Hertz; pub(crate) unsafe fn on_interrupt() { - let regs = T::regs(); + let regs = T::info().regs; let isr = regs.isr().read(); if isr.tcr() || isr.tc() { @@ -24,16 +23,16 @@ pub(crate) unsafe fn on_interrupt() { }); } -impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { +impl<'d, M: Mode> I2c<'d, M> { pub(crate) fn init(&mut self, freq: Hertz, _config: Config) { - T::regs().cr1().modify(|reg| { + self.info.regs.cr1().modify(|reg| { reg.set_pe(false); reg.set_anfoff(false); }); - let timings = Timings::new(T::frequency(), freq.into()); + let timings = Timings::new(self.kernel_clock, freq.into()); - T::regs().timingr().write(|reg| { + self.info.regs.timingr().write(|reg| { reg.set_presc(timings.prescale); reg.set_scll(timings.scll); reg.set_sclh(timings.sclh); @@ -41,16 +40,17 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { reg.set_scldel(timings.scldel); }); - T::regs().cr1().modify(|reg| { + self.info.regs.cr1().modify(|reg| { reg.set_pe(true); }); } fn master_stop(&mut self) { - T::regs().cr2().write(|w| w.set_stop(true)); + self.info.regs.cr2().write(|w| w.set_stop(true)); } fn master_read( + info: &'static Info, address: u8, length: usize, stop: Stop, @@ -64,7 +64,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { // Wait for any previous address sequence to end // automatically. This could be up to 50% of a bus // cycle (ie. up to 0.5/freq) - while T::regs().cr2().read().start() { + while info.regs.cr2().read().start() { timeout.check()?; } } @@ -79,7 +79,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { i2c::vals::Reload::COMPLETED }; - T::regs().cr2().modify(|w| { + info.regs.cr2().modify(|w| { w.set_sadd((address << 1 | 0) as u16); w.set_add10(i2c::vals::Addmode::BIT7); w.set_dir(i2c::vals::Dir::READ); @@ -92,13 +92,25 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { Ok(()) } - fn master_write(address: u8, length: usize, stop: Stop, reload: bool, timeout: Timeout) -> Result<(), Error> { + fn master_write( + info: &'static Info, + address: u8, + length: usize, + stop: Stop, + reload: bool, + timeout: Timeout, + ) -> Result<(), Error> { assert!(length < 256); // Wait for any previous address sequence to end // automatically. This could be up to 50% of a bus // cycle (ie. up to 0.5/freq) - while T::regs().cr2().read().start() { + while info.regs.cr2().read().start() { + timeout.check()?; + } + + // Wait for the bus to be free + while info.regs.isr().read().busy() { timeout.check()?; } @@ -111,7 +123,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { // Set START and prepare to send `bytes`. The // START bit can be set even if the bus is BUSY or // I2C is in slave mode. - T::regs().cr2().modify(|w| { + info.regs.cr2().modify(|w| { w.set_sadd((address << 1 | 0) as u16); w.set_add10(i2c::vals::Addmode::BIT7); w.set_dir(i2c::vals::Dir::WRITE); @@ -124,10 +136,10 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { Ok(()) } - fn master_continue(length: usize, reload: bool, timeout: Timeout) -> Result<(), Error> { + fn master_continue(info: &'static Info, length: usize, reload: bool, timeout: Timeout) -> Result<(), Error> { assert!(length < 256 && length > 0); - while !T::regs().isr().read().tcr() { + while !info.regs.isr().read().tcr() { timeout.check()?; } @@ -137,7 +149,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { i2c::vals::Reload::COMPLETED }; - T::regs().cr2().modify(|w| { + info.regs.cr2().modify(|w| { w.set_nbytes(length as u8); w.set_reload(reload); }); @@ -146,27 +158,27 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { } fn flush_txdr(&self) { - if T::regs().isr().read().txis() { - T::regs().txdr().write(|w| w.set_txdata(0)); + if self.info.regs.isr().read().txis() { + self.info.regs.txdr().write(|w| w.set_txdata(0)); } - if !T::regs().isr().read().txe() { - T::regs().isr().modify(|w| w.set_txe(true)) + if !self.info.regs.isr().read().txe() { + self.info.regs.isr().modify(|w| w.set_txe(true)) } } fn wait_txe(&self, timeout: Timeout) -> Result<(), Error> { loop { - let isr = T::regs().isr().read(); + let isr = self.info.regs.isr().read(); if isr.txe() { return Ok(()); } else if isr.berr() { - T::regs().icr().write(|reg| reg.set_berrcf(true)); + self.info.regs.icr().write(|reg| reg.set_berrcf(true)); return Err(Error::Bus); } else if isr.arlo() { - T::regs().icr().write(|reg| reg.set_arlocf(true)); + self.info.regs.icr().write(|reg| reg.set_arlocf(true)); return Err(Error::Arbitration); } else if isr.nackf() { - T::regs().icr().write(|reg| reg.set_nackcf(true)); + self.info.regs.icr().write(|reg| reg.set_nackcf(true)); self.flush_txdr(); return Err(Error::Nack); } @@ -177,17 +189,17 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { fn wait_rxne(&self, timeout: Timeout) -> Result<(), Error> { loop { - let isr = T::regs().isr().read(); + let isr = self.info.regs.isr().read(); if isr.rxne() { return Ok(()); } else if isr.berr() { - T::regs().icr().write(|reg| reg.set_berrcf(true)); + self.info.regs.icr().write(|reg| reg.set_berrcf(true)); return Err(Error::Bus); } else if isr.arlo() { - T::regs().icr().write(|reg| reg.set_arlocf(true)); + self.info.regs.icr().write(|reg| reg.set_arlocf(true)); return Err(Error::Arbitration); } else if isr.nackf() { - T::regs().icr().write(|reg| reg.set_nackcf(true)); + self.info.regs.icr().write(|reg| reg.set_nackcf(true)); self.flush_txdr(); return Err(Error::Nack); } @@ -198,17 +210,17 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { fn wait_tc(&self, timeout: Timeout) -> Result<(), Error> { loop { - let isr = T::regs().isr().read(); + let isr = self.info.regs.isr().read(); if isr.tc() { return Ok(()); } else if isr.berr() { - T::regs().icr().write(|reg| reg.set_berrcf(true)); + self.info.regs.icr().write(|reg| reg.set_berrcf(true)); return Err(Error::Bus); } else if isr.arlo() { - T::regs().icr().write(|reg| reg.set_arlocf(true)); + self.info.regs.icr().write(|reg| reg.set_arlocf(true)); return Err(Error::Arbitration); } else if isr.nackf() { - T::regs().icr().write(|reg| reg.set_nackcf(true)); + self.info.regs.icr().write(|reg| reg.set_nackcf(true)); self.flush_txdr(); return Err(Error::Nack); } @@ -227,6 +239,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { let last_chunk_idx = total_chunks.saturating_sub(1); Self::master_read( + self.info, address, read.len().min(255), Stop::Automatic, @@ -237,14 +250,14 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { for (number, chunk) in read.chunks_mut(255).enumerate() { if number != 0 { - Self::master_continue(chunk.len(), number != last_chunk_idx, timeout)?; + Self::master_continue(self.info, chunk.len(), number != last_chunk_idx, timeout)?; } for byte in chunk { // Wait until we have received something self.wait_rxne(timeout)?; - *byte = T::regs().rxdr().read().rxdata(); + *byte = self.info.regs.rxdr().read().rxdata(); } } Ok(()) @@ -263,6 +276,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { // // ST SAD+W if let Err(err) = Self::master_write( + self.info, address, write.len().min(255), Stop::Software, @@ -277,7 +291,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { for (number, chunk) in write.chunks(255).enumerate() { if number != 0 { - Self::master_continue(chunk.len(), number != last_chunk_idx, timeout)?; + Self::master_continue(self.info, chunk.len(), number != last_chunk_idx, timeout)?; } for byte in chunk { @@ -291,7 +305,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { return Err(err); } - T::regs().txdr().write(|w| w.set_txdata(*byte)); + self.info.regs.txdr().write(|w| w.set_txdata(*byte)); } } // Wait until the write finishes @@ -302,6 +316,122 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { result } + // ========================= + // Blocking public API + + /// Blocking read. + pub fn blocking_read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Error> { + self.read_internal(address, read, false, self.timeout()) + // Automatic Stop + } + + /// Blocking write. + pub fn blocking_write(&mut self, address: u8, write: &[u8]) -> Result<(), Error> { + self.write_internal(address, write, true, self.timeout()) + } + + /// Blocking write, restart, read. + pub fn blocking_write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error> { + let timeout = self.timeout(); + self.write_internal(address, write, false, timeout)?; + self.read_internal(address, read, true, timeout) + // Automatic Stop + } + + /// Blocking transaction with operations. + /// + /// Consecutive operations of same type are merged. See [transaction contract] for details. + /// + /// [transaction contract]: embedded_hal_1::i2c::I2c::transaction + pub fn blocking_transaction(&mut self, addr: u8, operations: &mut [Operation<'_>]) -> Result<(), Error> { + let _ = addr; + let _ = operations; + todo!() + } + + /// Blocking write multiple buffers. + /// + /// The buffers are concatenated in a single write transaction. + pub fn blocking_write_vectored(&mut self, address: u8, write: &[&[u8]]) -> Result<(), Error> { + if write.is_empty() { + return Err(Error::ZeroLengthTransfer); + } + + let timeout = self.timeout(); + + let first_length = write[0].len(); + let last_slice_index = write.len() - 1; + + if let Err(err) = Self::master_write( + self.info, + address, + first_length.min(255), + Stop::Software, + (first_length > 255) || (last_slice_index != 0), + timeout, + ) { + self.master_stop(); + return Err(err); + } + + for (idx, slice) in write.iter().enumerate() { + let slice_len = slice.len(); + let completed_chunks = slice_len / 255; + let total_chunks = if completed_chunks * 255 == slice_len { + completed_chunks + } else { + completed_chunks + 1 + }; + let last_chunk_idx = total_chunks.saturating_sub(1); + + if idx != 0 { + if let Err(err) = Self::master_continue( + self.info, + slice_len.min(255), + (idx != last_slice_index) || (slice_len > 255), + timeout, + ) { + self.master_stop(); + return Err(err); + } + } + + for (number, chunk) in slice.chunks(255).enumerate() { + if number != 0 { + if let Err(err) = Self::master_continue( + self.info, + chunk.len(), + (number != last_chunk_idx) || (idx != last_slice_index), + timeout, + ) { + self.master_stop(); + return Err(err); + } + } + + for byte in chunk { + // Wait until we are allowed to send data + // (START has been ACKed or last byte when + // through) + if let Err(err) = self.wait_txe(timeout) { + self.master_stop(); + return Err(err); + } + + // Put byte on the wire + //self.i2c.txdr.write(|w| w.txdata().bits(*byte)); + self.info.regs.txdr().write(|w| w.set_txdata(*byte)); + } + } + } + // Wait until the write finishes + let result = self.wait_tc(timeout); + self.master_stop(); + result + } +} + +impl<'d> I2c<'d, Async> { async fn write_dma_internal( &mut self, address: u8, @@ -309,14 +439,11 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { first_slice: bool, last_slice: bool, timeout: Timeout, - ) -> Result<(), Error> - where - TXDMA: crate::i2c::TxDma, - { + ) -> Result<(), Error> { let total_len = write.len(); let dma_transfer = unsafe { - let regs = T::regs(); + let regs = self.info.regs; regs.cr1().modify(|w| { w.set_txdmaen(true); if first_slice { @@ -325,16 +452,13 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { }); let dst = regs.txdr().as_ptr() as *mut u8; - let ch = &mut self.tx_dma; - let request = ch.request(); - Transfer::new_write(ch, request, write, dst, Default::default()) + self.tx_dma.as_mut().unwrap().write(write, dst, Default::default()) }; - let state = T::state(); let mut remaining_len = total_len; let on_drop = OnDrop::new(|| { - let regs = T::regs(); + let regs = self.info.regs; regs.cr1().modify(|w| { if last_slice { w.set_txdmaen(false); @@ -344,12 +468,13 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { }); poll_fn(|cx| { - state.waker.register(cx.waker()); + self.state.waker.register(cx.waker()); - let isr = T::regs().isr().read(); + let isr = self.info.regs.isr().read(); if remaining_len == total_len { if first_slice { Self::master_write( + self.info, address, total_len.min(255), Stop::Software, @@ -357,8 +482,8 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { timeout, )?; } else { - Self::master_continue(total_len.min(255), (total_len > 255) || !last_slice, timeout)?; - T::regs().cr1().modify(|w| w.set_tcie(true)); + Self::master_continue(self.info, total_len.min(255), (total_len > 255) || !last_slice, timeout)?; + self.info.regs.cr1().modify(|w| w.set_tcie(true)); } } else if !(isr.tcr() || isr.tc()) { // poll_fn was woken without an interrupt present @@ -368,10 +493,10 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { } else { let last_piece = (remaining_len <= 255) && last_slice; - if let Err(e) = Self::master_continue(remaining_len.min(255), !last_piece, timeout) { + if let Err(e) = Self::master_continue(self.info, remaining_len.min(255), !last_piece, timeout) { return Poll::Ready(Err(e)); } - T::regs().cr1().modify(|w| w.set_tcie(true)); + self.info.regs.cr1().modify(|w| w.set_tcie(true)); } remaining_len = remaining_len.saturating_sub(255); @@ -398,30 +523,24 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { buffer: &mut [u8], restart: bool, timeout: Timeout, - ) -> Result<(), Error> - where - RXDMA: crate::i2c::RxDma, - { + ) -> Result<(), Error> { let total_len = buffer.len(); let dma_transfer = unsafe { - let regs = T::regs(); + let regs = self.info.regs; regs.cr1().modify(|w| { w.set_rxdmaen(true); w.set_tcie(true); }); let src = regs.rxdr().as_ptr() as *mut u8; - let ch = &mut self.rx_dma; - let request = ch.request(); - Transfer::new_read(ch, request, src, buffer, Default::default()) + self.rx_dma.as_mut().unwrap().read(src, buffer, Default::default()) }; - let state = T::state(); let mut remaining_len = total_len; let on_drop = OnDrop::new(|| { - let regs = T::regs(); + let regs = self.info.regs; regs.cr1().modify(|w| { w.set_rxdmaen(false); w.set_tcie(false); @@ -429,11 +548,12 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { }); poll_fn(|cx| { - state.waker.register(cx.waker()); + self.state.waker.register(cx.waker()); - let isr = T::regs().isr().read(); + let isr = self.info.regs.isr().read(); if remaining_len == total_len { Self::master_read( + self.info, address, total_len.min(255), Stop::Software, @@ -449,10 +569,10 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { } else { let last_piece = remaining_len <= 255; - if let Err(e) = Self::master_continue(remaining_len.min(255), !last_piece, timeout) { + if let Err(e) = Self::master_continue(self.info, remaining_len.min(255), !last_piece, timeout) { return Poll::Ready(Err(e)); } - T::regs().cr1().modify(|w| w.set_tcie(true)); + self.info.regs.cr1().modify(|w| w.set_tcie(true)); } remaining_len = remaining_len.saturating_sub(255); @@ -475,10 +595,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { // Async public API /// Write. - pub async fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Error> - where - TXDMA: crate::i2c::TxDma, - { + pub async fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Error> { let timeout = self.timeout(); if write.is_empty() { self.write_internal(address, write, true, timeout) @@ -492,10 +609,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { /// Write multiple buffers. /// /// The buffers are concatenated in a single write transaction. - pub async fn write_vectored(&mut self, address: u8, write: &[&[u8]]) -> Result<(), Error> - where - TXDMA: crate::i2c::TxDma, - { + pub async fn write_vectored(&mut self, address: u8, write: &[&[u8]]) -> Result<(), Error> { let timeout = self.timeout(); if write.is_empty() { @@ -518,10 +632,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { } /// Read. - pub async fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Error> - where - RXDMA: crate::i2c::RxDma, - { + pub async fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Error> { let timeout = self.timeout(); if buffer.is_empty() { @@ -533,11 +644,7 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { } /// Write, restart, read. - pub async fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error> - where - TXDMA: super::TxDma, - RXDMA: super::RxDma, - { + pub async fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error> { let timeout = self.timeout(); if write.is_empty() { @@ -557,110 +664,15 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> { Ok(()) } - // ========================= - // Blocking public API - - /// Blocking read. - pub fn blocking_read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Error> { - self.read_internal(address, read, false, self.timeout()) - // Automatic Stop - } - - /// Blocking write. - pub fn blocking_write(&mut self, address: u8, write: &[u8]) -> Result<(), Error> { - self.write_internal(address, write, true, self.timeout()) - } - - /// Blocking write, restart, read. - pub fn blocking_write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Error> { - let timeout = self.timeout(); - self.write_internal(address, write, false, timeout)?; - self.read_internal(address, read, true, timeout) - // Automatic Stop - } - - /// Blocking write multiple buffers. + /// Transaction with operations. /// - /// The buffers are concatenated in a single write transaction. - pub fn blocking_write_vectored(&mut self, address: u8, write: &[&[u8]]) -> Result<(), Error> { - if write.is_empty() { - return Err(Error::ZeroLengthTransfer); - } - - let timeout = self.timeout(); - - let first_length = write[0].len(); - let last_slice_index = write.len() - 1; - - if let Err(err) = Self::master_write( - address, - first_length.min(255), - Stop::Software, - (first_length > 255) || (last_slice_index != 0), - timeout, - ) { - self.master_stop(); - return Err(err); - } - - for (idx, slice) in write.iter().enumerate() { - let slice_len = slice.len(); - let completed_chunks = slice_len / 255; - let total_chunks = if completed_chunks * 255 == slice_len { - completed_chunks - } else { - completed_chunks + 1 - }; - let last_chunk_idx = total_chunks.saturating_sub(1); - - if idx != 0 { - if let Err(err) = Self::master_continue( - slice_len.min(255), - (idx != last_slice_index) || (slice_len > 255), - timeout, - ) { - self.master_stop(); - return Err(err); - } - } - - for (number, chunk) in slice.chunks(255).enumerate() { - if number != 0 { - if let Err(err) = Self::master_continue( - chunk.len(), - (number != last_chunk_idx) || (idx != last_slice_index), - timeout, - ) { - self.master_stop(); - return Err(err); - } - } - - for byte in chunk { - // Wait until we are allowed to send data - // (START has been ACKed or last byte when - // through) - if let Err(err) = self.wait_txe(timeout) { - self.master_stop(); - return Err(err); - } - - // Put byte on the wire - //self.i2c.txdr.write(|w| w.txdata().bits(*byte)); - T::regs().txdr().write(|w| w.set_txdata(*byte)); - } - } - } - // Wait until the write finishes - let result = self.wait_tc(timeout); - self.master_stop(); - result - } -} - -impl<'d, T: Instance, TXDMA, RXDMA> Drop for I2c<'d, T, TXDMA, RXDMA> { - fn drop(&mut self) { - T::disable(); + /// Consecutive operations of same type are merged. See [transaction contract] for details. + /// + /// [transaction contract]: embedded_hal_1::i2c::I2c::transaction + pub async fn transaction(&mut self, addr: u8, operations: &mut [Operation<'_>]) -> Result<(), Error> { + let _ = addr; + let _ = operations; + todo!() } } @@ -788,12 +800,12 @@ impl Timings { } } -impl<'d, T: Instance> SetConfig for I2c<'d, T> { +impl<'d, M: Mode> SetConfig for I2c<'d, M> { type Config = Hertz; type ConfigError = (); fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> { - let timings = Timings::new(T::frequency(), *config); - T::regs().timingr().write(|reg| { + let timings = Timings::new(self.kernel_clock, *config); + self.info.regs.timingr().write(|reg| { reg.set_presc(timings.prescale); reg.set_scll(timings.scll); reg.set_sclh(timings.sclh); diff --git a/embassy-stm32/src/i2s.rs b/embassy-stm32/src/i2s.rs index 1f85c0bc5..f11371f98 100644 --- a/embassy-stm32/src/i2s.rs +++ b/embassy-stm32/src/i2s.rs @@ -1,11 +1,13 @@ //! Inter-IC Sound (I2S) -use embassy_hal_internal::into_ref; -use crate::gpio::sealed::{AFType, Pin as _}; -use crate::gpio::AnyPin; -use crate::pac::spi::vals; -use crate::rcc::get_freqs; -use crate::spi::{Config as SpiConfig, *}; +use embassy_futures::join::join; +use embassy_hal_internal::into_ref; +use stm32_metapac::spi::vals; + +use crate::dma::{ringbuffer, ChannelAndRequest, ReadableRingBuffer, TransferOptions, WritableRingBuffer}; +use crate::gpio::{AfType, AnyPin, OutputType, SealedPin, Speed}; +use crate::mode::Async; +use crate::spi::{Config as SpiConfig, RegsExt as _, *}; use crate::time::Hertz; use crate::{Peripheral, PeripheralRef}; @@ -20,11 +22,15 @@ pub enum Mode { /// I2S function #[derive(Copy, Clone)] -pub enum Function { +#[allow(dead_code)] +enum Function { /// Transmit audio data Transmit, /// Receive audio data Receive, + #[cfg(spi_v3)] + /// Transmit and Receive audio data + FullDuplex, } /// I2C standard @@ -42,8 +48,32 @@ pub enum Standard { PcmShortSync, } +/// SAI error +#[derive(Debug, PartialEq, Eq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Error { + /// `write` called on a SAI in receive mode. + NotATransmitter, + /// `read` called on a SAI in transmit mode. + NotAReceiver, + /// Overrun + Overrun, +} + +impl From for Error { + fn from(#[allow(unused)] err: ringbuffer::Error) -> Self { + #[cfg(feature = "defmt")] + { + if err == ringbuffer::Error::DmaUnsynced { + defmt::error!("Ringbuffer broken invariants detected!"); + } + } + Self::Overrun + } +} + impl Standard { - #[cfg(any(spi_v1, spi_f1))] + #[cfg(any(spi_v1, spi_v3, spi_f1))] const fn i2sstd(&self) -> vals::I2sstd { match self { Standard::Philips => vals::I2sstd::PHILIPS, @@ -54,7 +84,7 @@ impl Standard { } } - #[cfg(any(spi_v1, spi_f1))] + #[cfg(any(spi_v1, spi_v3, spi_f1))] const fn pcmsync(&self) -> vals::Pcmsync { match self { Standard::PcmLongSync => vals::Pcmsync::LONG, @@ -77,23 +107,23 @@ pub enum Format { } impl Format { - #[cfg(any(spi_v1, spi_f1))] + #[cfg(any(spi_v1, spi_v3, spi_f1))] const fn datlen(&self) -> vals::Datlen { match self { - Format::Data16Channel16 => vals::Datlen::SIXTEENBIT, - Format::Data16Channel32 => vals::Datlen::SIXTEENBIT, - Format::Data24Channel32 => vals::Datlen::TWENTYFOURBIT, - Format::Data32Channel32 => vals::Datlen::THIRTYTWOBIT, + Format::Data16Channel16 => vals::Datlen::BITS16, + Format::Data16Channel32 => vals::Datlen::BITS16, + Format::Data24Channel32 => vals::Datlen::BITS24, + Format::Data32Channel32 => vals::Datlen::BITS32, } } - #[cfg(any(spi_v1, spi_f1))] + #[cfg(any(spi_v1, spi_v3, spi_f1))] const fn chlen(&self) -> vals::Chlen { match self { - Format::Data16Channel16 => vals::Chlen::SIXTEENBIT, - Format::Data16Channel32 => vals::Chlen::THIRTYTWOBIT, - Format::Data24Channel32 => vals::Chlen::THIRTYTWOBIT, - Format::Data32Channel32 => vals::Chlen::THIRTYTWOBIT, + Format::Data16Channel16 => vals::Chlen::BITS16, + Format::Data16Channel32 => vals::Chlen::BITS32, + Format::Data24Channel32 => vals::Chlen::BITS32, + Format::Data32Channel32 => vals::Chlen::BITS32, } } } @@ -108,7 +138,7 @@ pub enum ClockPolarity { } impl ClockPolarity { - #[cfg(any(spi_v1, spi_f1))] + #[cfg(any(spi_v1, spi_v3, spi_f1))] const fn ckpol(&self) -> vals::Ckpol { match self { ClockPolarity::IdleHigh => vals::Ckpol::IDLEHIGH, @@ -128,15 +158,13 @@ impl ClockPolarity { pub struct Config { /// Mode pub mode: Mode, - /// Function (transmit, receive) - pub function: Function, /// Which I2S standard to use. pub standard: Standard, /// Data format. pub format: Format, /// Clock polarity. pub clock_polarity: ClockPolarity, - /// True to eanble master clock output from this instance. + /// True to enable master clock output from this instance. pub master_clock: bool, } @@ -144,7 +172,6 @@ impl Default for Config { fn default() -> Self { Self { mode: Mode::Master, - function: Function::Transmit, standard: Standard::Philips, format: Format::Data16Channel16, clock_polarity: ClockPolarity::IdleLow, @@ -153,74 +180,342 @@ impl Default for Config { } } +/// I2S driver writer. Useful for moving write functionality across tasks. +pub struct Writer<'s, 'd, W: Word>(&'s mut WritableRingBuffer<'d, W>); + +impl<'s, 'd, W: Word> Writer<'s, 'd, W> { + /// Write data to the I2S ringbuffer. + /// This appends the data to the buffer and returns immediately. The data will be transmitted in the background. + /// If thfre’s no space in the buffer, this waits until there is. + pub async fn write(&mut self, data: &[W]) -> Result<(), Error> { + self.0.write_exact(data).await?; + Ok(()) + } + + /// Reset the ring buffer to its initial state. + /// Can be used to recover from overrun. + /// The ringbuffer will always auto-reset on Overrun in any case. + pub fn reset(&mut self) { + self.0.clear(); + } +} + +/// I2S driver reader. Useful for moving read functionality across tasks. +pub struct Reader<'s, 'd, W: Word>(&'s mut ReadableRingBuffer<'d, W>); + +impl<'s, 'd, W: Word> Reader<'s, 'd, W> { + /// Read data from the I2S ringbuffer. + /// SAI is always receiving data in the background. This function pops already-received data from the buffer. + /// If there’s less than data.len() data in the buffer, this waits until there is. + pub async fn read(&mut self, data: &mut [W]) -> Result<(), Error> { + self.0.read_exact(data).await?; + Ok(()) + } + + /// Reset the ring buffer to its initial state. + /// Can be used to prevent overrun. + /// The ringbuffer will always auto-reset on Overrun in any case. + pub fn reset(&mut self) { + self.0.clear(); + } +} + /// I2S driver. -pub struct I2S<'d, T: Instance, Tx, Rx> { - _peri: Spi<'d, T, Tx, Rx>, - sd: Option>, +pub struct I2S<'d, W: Word> { + #[allow(dead_code)] + mode: Mode, + spi: Spi<'d, Async>, + txsd: Option>, + rxsd: Option>, ws: Option>, ck: Option>, mck: Option>, + tx_ring_buffer: Option>, + rx_ring_buffer: Option>, } -impl<'d, T: Instance, Tx, Rx> I2S<'d, T, Tx, Rx> { - /// Note: Full-Duplex modes are not supported at this time - pub fn new( +impl<'d, W: Word> I2S<'d, W> { + /// Create a transmitter driver. + pub fn new_txonly( peri: impl Peripheral

+ 'd, sd: impl Peripheral

> + 'd, ws: impl Peripheral

> + 'd, ck: impl Peripheral

> + 'd, mck: impl Peripheral

> + 'd, - txdma: impl Peripheral

+ 'd, - rxdma: impl Peripheral

+ 'd, + txdma: impl Peripheral

> + 'd, + txdma_buf: &'d mut [W], freq: Hertz, config: Config, ) -> Self { - into_ref!(sd, ws, ck, mck); + Self::new_inner( + peri, + new_pin!(sd, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + None, + ws, + ck, + new_pin!(mck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_dma!(txdma).map(|d| (d, txdma_buf)), + None, + freq, + config, + Function::Transmit, + ) + } - sd.set_as_af(sd.af_num(), AFType::OutputPushPull); - sd.set_speed(crate::gpio::Speed::VeryHigh); + /// Create a transmitter driver without a master clock pin. + pub fn new_txonly_nomck( + peri: impl Peripheral

+ 'd, + sd: impl Peripheral

> + 'd, + ws: impl Peripheral

> + 'd, + ck: impl Peripheral

> + 'd, + txdma: impl Peripheral

> + 'd, + txdma_buf: &'d mut [W], + freq: Hertz, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(sd, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + None, + ws, + ck, + None, + new_dma!(txdma).map(|d| (d, txdma_buf)), + None, + freq, + config, + Function::Transmit, + ) + } - ws.set_as_af(ws.af_num(), AFType::OutputPushPull); - ws.set_speed(crate::gpio::Speed::VeryHigh); + /// Create a receiver driver. + pub fn new_rxonly( + peri: impl Peripheral

+ 'd, + sd: impl Peripheral

> + 'd, + ws: impl Peripheral

> + 'd, + ck: impl Peripheral

> + 'd, + mck: impl Peripheral

> + 'd, + rxdma: impl Peripheral

> + 'd, + rxdma_buf: &'d mut [W], + freq: Hertz, + config: Config, + ) -> Self { + Self::new_inner( + peri, + None, + new_pin!(sd, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + ws, + ck, + new_pin!(mck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + None, + new_dma!(rxdma).map(|d| (d, rxdma_buf)), + freq, + config, + Function::Receive, + ) + } - ck.set_as_af(ck.af_num(), AFType::OutputPushPull); - ck.set_speed(crate::gpio::Speed::VeryHigh); + #[cfg(spi_v3)] + /// Create a full duplex driver. + pub fn new_full_duplex( + peri: impl Peripheral

+ 'd, + txsd: impl Peripheral

> + 'd, + rxsd: impl Peripheral

> + 'd, + ws: impl Peripheral

> + 'd, + ck: impl Peripheral

> + 'd, + mck: impl Peripheral

> + 'd, + txdma: impl Peripheral

> + 'd, + txdma_buf: &'d mut [W], + rxdma: impl Peripheral

> + 'd, + rxdma_buf: &'d mut [W], + freq: Hertz, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(txsd, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(rxsd, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + ws, + ck, + new_pin!(mck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_dma!(txdma).map(|d| (d, txdma_buf)), + new_dma!(rxdma).map(|d| (d, rxdma_buf)), + freq, + config, + Function::FullDuplex, + ) + } - mck.set_as_af(mck.af_num(), AFType::OutputPushPull); - mck.set_speed(crate::gpio::Speed::VeryHigh); + /// Start I2S driver. + pub fn start(&mut self) { + self.spi.info.regs.cr1().modify(|w| { + w.set_spe(false); + }); + self.spi.set_word_size(W::CONFIG); + if let Some(tx_ring_buffer) = &mut self.tx_ring_buffer { + tx_ring_buffer.start(); - let mut spi_cfg = SpiConfig::default(); - spi_cfg.frequency = freq; - let spi = Spi::new_internal(peri, txdma, rxdma, spi_cfg); + set_txdmaen(self.spi.info.regs, true); + } + if let Some(rx_ring_buffer) = &mut self.rx_ring_buffer { + rx_ring_buffer.start(); + // SPIv3 clears rxfifo on SPE=0 + #[cfg(not(any(spi_v3, spi_v4, spi_v5)))] + flush_rx_fifo(self.spi.info.regs); - #[cfg(all(rcc_f4, not(stm32f410)))] - let pclk = unsafe { get_freqs() }.plli2s1_q.unwrap(); + set_rxdmaen(self.spi.info.regs, true); + } + self.spi.info.regs.cr1().modify(|w| { + w.set_spe(true); + }); + #[cfg(any(spi_v3, spi_v4, spi_v5))] + self.spi.info.regs.cr1().modify(|w| { + w.set_cstart(true); + }); + } - #[cfg(stm32f410)] + /// Reset the ring buffer to its initial state. + /// Can be used to recover from overrun. + pub fn clear(&mut self) { + if let Some(rx_ring_buffer) = &mut self.rx_ring_buffer { + rx_ring_buffer.clear(); + } + if let Some(tx_ring_buffer) = &mut self.tx_ring_buffer { + tx_ring_buffer.clear(); + } + } + + /// Stop I2S driver. + pub async fn stop(&mut self) { + let regs = self.spi.info.regs; + + let tx_f = async { + if let Some(tx_ring_buffer) = &mut self.tx_ring_buffer { + tx_ring_buffer.stop().await; + + set_txdmaen(regs, false); + } + }; + + let rx_f = async { + if let Some(rx_ring_buffer) = &mut self.rx_ring_buffer { + rx_ring_buffer.stop().await; + + set_rxdmaen(regs, false); + } + }; + + join(rx_f, tx_f).await; + + #[cfg(any(spi_v3, spi_v4, spi_v5))] + { + if let Mode::Master = self.mode { + regs.cr1().modify(|w| { + w.set_csusp(true); + }); + + while regs.cr1().read().cstart() {} + } + } + + regs.cr1().modify(|w| { + w.set_spe(false); + }); + + self.clear(); + } + + /// Split the driver into a Reader/Writer pair. + /// Useful for splitting the reader/writer functionality across tasks or + /// for calling the read/write methods in parallel. + pub fn split<'s>(&'s mut self) -> Result<(Reader<'s, 'd, W>, Writer<'s, 'd, W>), Error> { + match (&mut self.rx_ring_buffer, &mut self.tx_ring_buffer) { + (None, _) => Err(Error::NotAReceiver), + (_, None) => Err(Error::NotATransmitter), + (Some(rx_ring), Some(tx_ring)) => Ok((Reader(rx_ring), Writer(tx_ring))), + } + } + + /// Read data from the I2S ringbuffer. + /// SAI is always receiving data in the background. This function pops already-received data from the buffer. + /// If there’s less than data.len() data in the buffer, this waits until there is. + pub async fn read(&mut self, data: &mut [W]) -> Result<(), Error> { + match &mut self.rx_ring_buffer { + Some(ring) => Reader(ring).read(data).await, + _ => Err(Error::NotAReceiver), + } + } + + /// Write data to the I2S ringbuffer. + /// This appends the data to the buffer and returns immediately. The data will be transmitted in the background. + /// If thfre’s no space in the buffer, this waits until there is. + pub async fn write(&mut self, data: &[W]) -> Result<(), Error> { + match &mut self.tx_ring_buffer { + Some(ring) => Writer(ring).write(data).await, + _ => Err(Error::NotATransmitter), + } + } + + /// Write data directly to the raw I2S ringbuffer. + /// This can be used to fill the buffer before starting the DMA transfer. + pub async fn write_immediate(&mut self, data: &mut [W]) -> Result<(usize, usize), Error> { + match &mut self.tx_ring_buffer { + Some(ring) => Ok(ring.write_immediate(data)?), + _ => return Err(Error::NotATransmitter), + } + } + + fn new_inner( + peri: impl Peripheral

+ 'd, + txsd: Option>, + rxsd: Option>, + ws: impl Peripheral

> + 'd, + ck: impl Peripheral

> + 'd, + mck: Option>, + txdma: Option<(ChannelAndRequest<'d>, &'d mut [W])>, + rxdma: Option<(ChannelAndRequest<'d>, &'d mut [W])>, + freq: Hertz, + config: Config, + function: Function, + ) -> Self { + into_ref!(ws, ck); + + ws.set_as_af(ws.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); + ck.set_as_af(ck.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); + + let spi = Spi::new_internal(peri, None, None, { + let mut config = SpiConfig::default(); + config.frequency = freq; + config + }); + + let regs = T::info().regs; + + // TODO move i2s to the new mux infra. + //#[cfg(all(rcc_f4, not(stm32f410)))] + //let pclk = unsafe { get_freqs() }.plli2s1_q.unwrap(); + //#[cfg(stm32f410)] let pclk = T::frequency(); let (odd, div) = compute_baud_rate(pclk, freq, config.master_clock, config.format); - #[cfg(any(spi_v1, spi_f1))] + #[cfg(any(spi_v1, spi_v3, spi_f1))] { + #[cfg(spi_v3)] + { + regs.cr1().modify(|w| w.set_spe(false)); + + reset_incompatible_bitfields::(); + } + use stm32_metapac::spi::vals::{I2scfg, Odd}; - // 1. Select the I2SDIV[7:0] bits in the SPI_I2SPR register to define the serial clock baud - // rate to reach the proper audio sample frequency. The ODD bit in the SPI_I2SPR - // register also has to be defined. - - T::REGS.i2spr().modify(|w| { - w.set_i2sdiv(div); - w.set_odd(match odd { - true => Odd::ODD, - false => Odd::EVEN, - }); - - w.set_mckoe(config.master_clock); - }); + // 1. Select the I2SDIV[7:0] bits in the SPI_I2SPR/SPI_I2SCFGR register to define the serial clock baud + // rate to reach the proper audio sample frequency. The ODD bit in the + // SPI_I2SPR/SPI_I2SCFGR register also has to be defined. // 2. Select the CKPOL bit to define the steady level for the communication clock. Set the - // MCKOE bit in the SPI_I2SPR register if the master clock MCK needs to be provided to + // MCKOE bit in the SPI_I2SPR/SPI_I2SCFGR register if the master clock MCK needs to be provided to // the external DAC/ADC audio component (the I2SDIV and ODD values should be // computed depending on the state of the MCK output, for more details refer to // Section 28.4.4: Clock generator). @@ -236,57 +531,79 @@ impl<'d, T: Instance, Tx, Rx> I2S<'d, T, Tx, Rx> { // 5. The I2SE bit in SPI_I2SCFGR register must be set. - T::REGS.i2scfgr().modify(|w| { + let clk_reg = { + #[cfg(any(spi_v1, spi_f1))] + { + regs.i2spr() + } + #[cfg(spi_v3)] + { + regs.i2scfgr() + } + }; + + clk_reg.modify(|w| { + w.set_i2sdiv(div); + w.set_odd(match odd { + true => Odd::ODD, + false => Odd::EVEN, + }); + + w.set_mckoe(config.master_clock); + }); + + regs.i2scfgr().modify(|w| { w.set_ckpol(config.clock_polarity.ckpol()); w.set_i2smod(true); + w.set_i2sstd(config.standard.i2sstd()); w.set_pcmsync(config.standard.pcmsync()); w.set_datlen(config.format.datlen()); w.set_chlen(config.format.chlen()); - w.set_i2scfg(match (config.mode, config.function) { + w.set_i2scfg(match (config.mode, function) { (Mode::Master, Function::Transmit) => I2scfg::MASTERTX, (Mode::Master, Function::Receive) => I2scfg::MASTERRX, + #[cfg(spi_v3)] + (Mode::Master, Function::FullDuplex) => I2scfg::MASTERFULLDUPLEX, (Mode::Slave, Function::Transmit) => I2scfg::SLAVETX, (Mode::Slave, Function::Receive) => I2scfg::SLAVERX, + #[cfg(spi_v3)] + (Mode::Slave, Function::FullDuplex) => I2scfg::SLAVEFULLDUPLEX, }); - w.set_i2se(true) + #[cfg(any(spi_v1, spi_f1))] + w.set_i2se(true); }); + + let mut opts = TransferOptions::default(); + opts.half_transfer_ir = true; + + Self { + mode: config.mode, + spi, + txsd: txsd.map(|w| w.map_into()), + rxsd: rxsd.map(|w| w.map_into()), + ws: Some(ws.map_into()), + ck: Some(ck.map_into()), + mck: mck.map(|w| w.map_into()), + tx_ring_buffer: txdma.map(|(ch, buf)| unsafe { + WritableRingBuffer::new(ch.channel, ch.request, regs.tx_ptr(), buf, opts) + }), + rx_ring_buffer: rxdma.map(|(ch, buf)| unsafe { + ReadableRingBuffer::new(ch.channel, ch.request, regs.rx_ptr(), buf, opts) + }), + } } - - Self { - _peri: spi, - sd: Some(sd.map_into()), - ws: Some(ws.map_into()), - ck: Some(ck.map_into()), - mck: Some(mck.map_into()), - } - } - - /// Write audio data. - pub async fn write(&mut self, data: &[W]) -> Result<(), Error> - where - Tx: TxDma, - { - self._peri.write(data).await - } - - /// Read audio data. - pub async fn read(&mut self, data: &mut [W]) -> Result<(), Error> - where - Tx: TxDma, - Rx: RxDma, - { - self._peri.read(data).await } } -impl<'d, T: Instance, Tx, Rx> Drop for I2S<'d, T, Tx, Rx> { +impl<'d, W: Word> Drop for I2S<'d, W> { fn drop(&mut self) { - self.sd.as_ref().map(|x| x.set_as_disconnected()); + self.txsd.as_ref().map(|x| x.set_as_disconnected()); + self.rxsd.as_ref().map(|x| x.set_as_disconnected()); self.ws.as_ref().map(|x| x.set_as_disconnected()); self.ck.as_ref().map(|x| x.set_as_disconnected()); self.mck.as_ref().map(|x| x.set_as_disconnected()); @@ -328,3 +645,71 @@ fn compute_baud_rate(i2s_clock: Hertz, request_freq: Hertz, mclk: bool, data_for ((division & 1) == 1, (division >> 1) as u8) } } + +#[cfg(spi_v3)] +// The STM32H7 reference manual specifies that any incompatible bitfields should be reset +// to their reset values while operating in I2S mode. +fn reset_incompatible_bitfields() { + let regs = T::info().regs; + regs.cr1().modify(|w| { + let iolock = w.iolock(); + let csusp = w.csusp(); + let spe = w.cstart(); + let cstart = w.cstart(); + w.0 = 0; + w.set_iolock(iolock); + w.set_csusp(csusp); + w.set_spe(spe); + w.set_cstart(cstart); + }); + + regs.cr2().write(|w| w.0 = 0); + + regs.cfg1().modify(|w| { + let txdmaen = w.txdmaen(); + let rxdmaen = w.rxdmaen(); + let fthlv = w.fthlv(); + w.0 = 0; + w.set_txdmaen(txdmaen); + w.set_rxdmaen(rxdmaen); + w.set_fthlv(fthlv); + }); + + regs.cfg2().modify(|w| { + let afcntr = w.afcntr(); + let lsbfirst = w.lsbfirst(); + let ioswp = w.ioswp(); + w.0 = 0; + w.set_afcntr(afcntr); + w.set_lsbfirst(lsbfirst); + w.set_ioswp(ioswp); + }); + + regs.ier().modify(|w| { + let tifreie = w.tifreie(); + let ovrie = w.ovrie(); + let udrie = w.udrie(); + let txpie = w.txpie(); + let rxpie = w.rxpie(); + + w.0 = 0; + + w.set_tifreie(tifreie); + w.set_ovrie(ovrie); + w.set_udrie(udrie); + w.set_txpie(txpie); + w.set_rxpie(rxpie); + }); + + regs.ifcr().write(|w| { + w.set_suspc(true); + w.set_tifrec(true); + w.set_ovrc(true); + w.set_udrc(true); + }); + + regs.crcpoly().write(|w| w.0 = 0x107); + regs.txcrc().write(|w| w.0 = 0); + regs.rxcrc().write(|w| w.0 = 0); + regs.udrdr().write(|w| w.0 = 0); +} diff --git a/embassy-stm32/src/ipcc.rs b/embassy-stm32/src/ipcc.rs index 663a7f59d..6c8347311 100644 --- a/embassy-stm32/src/ipcc.rs +++ b/embassy-stm32/src/ipcc.rs @@ -4,12 +4,11 @@ use core::future::poll_fn; use core::sync::atomic::{compiler_fence, Ordering}; use core::task::Poll; -use self::sealed::Instance; -use crate::interrupt; +use embassy_sync::waitqueue::AtomicWaker; + use crate::interrupt::typelevel::Interrupt; -use crate::pac::rcc::vals::{Lptim1sel, Lptim2sel}; use crate::peripherals::IPCC; -use crate::rcc::sealed::RccPeripheral; +use crate::{interrupt, rcc}; /// Interrupt handler. pub struct ReceiveInterruptHandler {} @@ -102,10 +101,11 @@ pub struct Ipcc; impl Ipcc { /// Enable IPCC. pub fn enable(_config: Config) { - IPCC::enable_and_reset(); + rcc::enable_and_reset::(); IPCC::set_cpu2(true); - _configure_pwr(); + // set RF wake-up clock = LSE + crate::pac::RCC.csr().modify(|w| w.set_rfwkpsel(0b01)); let regs = IPCC::regs(); @@ -207,7 +207,7 @@ impl Ipcc { } } -impl sealed::Instance for crate::peripherals::IPCC { +impl SealedInstance for crate::peripherals::IPCC { fn regs() -> crate::pac::ipcc::Ipcc { crate::pac::IPCC } @@ -216,73 +216,52 @@ impl sealed::Instance for crate::peripherals::IPCC { crate::pac::PWR.cr4().modify(|w| w.set_c2boot(enabled)); } - fn state() -> &'static self::sealed::State { - static STATE: self::sealed::State = self::sealed::State::new(); + fn state() -> &'static State { + static STATE: State = State::new(); &STATE } } -pub(crate) mod sealed { - use embassy_sync::waitqueue::AtomicWaker; +struct State { + rx_wakers: [AtomicWaker; 6], + tx_wakers: [AtomicWaker; 6], +} - use super::*; +impl State { + const fn new() -> Self { + const WAKER: AtomicWaker = AtomicWaker::new(); - pub struct State { - rx_wakers: [AtomicWaker; 6], - tx_wakers: [AtomicWaker; 6], - } - - impl State { - pub const fn new() -> Self { - const WAKER: AtomicWaker = AtomicWaker::new(); - - Self { - rx_wakers: [WAKER; 6], - tx_wakers: [WAKER; 6], - } - } - - pub const fn rx_waker_for(&self, channel: IpccChannel) -> &AtomicWaker { - match channel { - IpccChannel::Channel1 => &self.rx_wakers[0], - IpccChannel::Channel2 => &self.rx_wakers[1], - IpccChannel::Channel3 => &self.rx_wakers[2], - IpccChannel::Channel4 => &self.rx_wakers[3], - IpccChannel::Channel5 => &self.rx_wakers[4], - IpccChannel::Channel6 => &self.rx_wakers[5], - } - } - - pub const fn tx_waker_for(&self, channel: IpccChannel) -> &AtomicWaker { - match channel { - IpccChannel::Channel1 => &self.tx_wakers[0], - IpccChannel::Channel2 => &self.tx_wakers[1], - IpccChannel::Channel3 => &self.tx_wakers[2], - IpccChannel::Channel4 => &self.tx_wakers[3], - IpccChannel::Channel5 => &self.tx_wakers[4], - IpccChannel::Channel6 => &self.tx_wakers[5], - } + Self { + rx_wakers: [WAKER; 6], + tx_wakers: [WAKER; 6], } } - pub trait Instance: crate::rcc::RccPeripheral { - fn regs() -> crate::pac::ipcc::Ipcc; - fn set_cpu2(enabled: bool); - fn state() -> &'static State; + const fn rx_waker_for(&self, channel: IpccChannel) -> &AtomicWaker { + match channel { + IpccChannel::Channel1 => &self.rx_wakers[0], + IpccChannel::Channel2 => &self.rx_wakers[1], + IpccChannel::Channel3 => &self.rx_wakers[2], + IpccChannel::Channel4 => &self.rx_wakers[3], + IpccChannel::Channel5 => &self.rx_wakers[4], + IpccChannel::Channel6 => &self.rx_wakers[5], + } + } + + const fn tx_waker_for(&self, channel: IpccChannel) -> &AtomicWaker { + match channel { + IpccChannel::Channel1 => &self.tx_wakers[0], + IpccChannel::Channel2 => &self.tx_wakers[1], + IpccChannel::Channel3 => &self.tx_wakers[2], + IpccChannel::Channel4 => &self.tx_wakers[3], + IpccChannel::Channel5 => &self.tx_wakers[4], + IpccChannel::Channel6 => &self.tx_wakers[5], + } } } -fn _configure_pwr() { - // TODO: move the rest of this to rcc - let rcc = crate::pac::RCC; - - // TODO: required - // set RF wake-up clock = LSE - rcc.csr().modify(|w| w.set_rfwkpsel(0b01)); - - // set LPTIM1 & LPTIM2 clock source - rcc.ccipr().modify(|w| { - w.set_lptim1sel(Lptim1sel::PCLK1); - w.set_lptim2sel(Lptim2sel::PCLK1); - }); +trait SealedInstance: crate::rcc::RccPeripheral { + fn regs() -> crate::pac::ipcc::Ipcc; + fn set_cpu2(enabled: bool); + fn state() -> &'static State; } diff --git a/embassy-stm32/src/lib.rs b/embassy-stm32/src/lib.rs index a465fccd8..286a18da2 100644 --- a/embassy-stm32/src/lib.rs +++ b/embassy-stm32/src/lib.rs @@ -2,7 +2,7 @@ #![allow(async_fn_in_trait)] #![cfg_attr( docsrs, - doc = "

You might want to browse the `embassy-stm32` documentation on the Embassy website instead.

The documentation here on `docs.rs` is built for a single chip only (STM32H755 in particular), while on the Embassy website you can pick your exact chip from the top menu. Available peripherals and their APIs change depending on the chip.

\n\n" + doc = "

You might want to browse the `embassy-stm32` documentation on the Embassy website instead.

The documentation here on `docs.rs` is built for a single chip only (stm32h7, stm32h7rs55 in particular), while on the Embassy website you can pick your exact chip from the top menu. Available peripherals and their APIs change depending on the chip.

\n\n" )] #![doc = include_str!("../README.md")] #![warn(missing_docs)] @@ -15,8 +15,31 @@ mod fmt; include!(concat!(env!("OUT_DIR"), "/_macros.rs")); // Utilities +mod macros; pub mod time; -mod traits; +/// Operating modes for peripherals. +pub mod mode { + trait SealedMode {} + + /// Operating mode for a peripheral. + #[allow(private_bounds)] + pub trait Mode: SealedMode {} + + macro_rules! impl_mode { + ($name:ident) => { + impl SealedMode for $name {} + impl Mode for $name {} + }; + } + + /// Blocking mode. + pub struct Blocking; + /// Async mode. + pub struct Async; + + impl_mode!(Blocking); + impl_mode!(Async); +} // Always-present hardware pub mod dma; @@ -32,12 +55,19 @@ pub mod timer; pub mod adc; #[cfg(can)] pub mod can; +// FIXME: Cordic driver cause stm32u5a5zj crash +#[cfg(all(cordic, not(any(stm32u5a5, stm32u5a9))))] +pub mod cordic; #[cfg(crc)] pub mod crc; +#[cfg(cryp)] +pub mod cryp; #[cfg(dac)] pub mod dac; #[cfg(dcmi)] pub mod dcmi; +#[cfg(dsihost)] +pub mod dsihost; #[cfg(eth)] pub mod eth; #[cfg(feature = "exti")] @@ -45,18 +75,28 @@ pub mod exti; pub mod flash; #[cfg(fmc)] pub mod fmc; +#[cfg(hash)] +pub mod hash; #[cfg(hrtim)] pub mod hrtim; +#[cfg(hsem)] +pub mod hsem; #[cfg(i2c)] pub mod i2c; -#[cfg(all(spi_v1, rcc_f4))] +#[cfg(any(all(spi_v1, rcc_f4), spi_v3))] pub mod i2s; #[cfg(stm32wb)] pub mod ipcc; #[cfg(feature = "low-power")] pub mod low_power; +#[cfg(lptim)] +pub mod lptim; +#[cfg(ltdc)] +pub mod ltdc; #[cfg(opamp)] pub mod opamp; +#[cfg(octospi)] +pub mod ospi; #[cfg(quadspi)] pub mod qspi; #[cfg(rng)] @@ -69,14 +109,16 @@ pub mod sai; pub mod sdmmc; #[cfg(spi)] pub mod spi; +#[cfg(tsc)] +pub mod tsc; +#[cfg(ucpd)] +pub mod ucpd; #[cfg(uid)] pub mod uid; #[cfg(usart)] pub mod usart; -#[cfg(usb)] +#[cfg(any(usb, otg))] pub mod usb; -#[cfg(otg)] -pub mod usb_otg; #[cfg(iwdg)] pub mod wdg; @@ -101,10 +143,10 @@ pub use crate::_generated::interrupt; /// Example of how to bind one interrupt: /// /// ```rust,ignore -/// use embassy_stm32::{bind_interrupts, usb_otg, peripherals}; +/// use embassy_stm32::{bind_interrupts, usb, peripherals}; /// /// bind_interrupts!(struct Irqs { -/// OTG_FS => usb_otg::InterruptHandler; +/// OTG_FS => usb::InterruptHandler; /// }); /// ``` /// @@ -123,24 +165,42 @@ pub use crate::_generated::interrupt; // developer note: this macro can't be in `embassy-hal-internal` due to the use of `$crate`. #[macro_export] macro_rules! bind_interrupts { - ($vis:vis struct $name:ident { $($irq:ident => $($handler:ty),*;)* }) => { + ($vis:vis struct $name:ident { + $( + $(#[cfg($cond_irq:meta)])? + $irq:ident => $( + $(#[cfg($cond_handler:meta)])? + $handler:ty + ),*; + )* + }) => { #[derive(Copy, Clone)] $vis struct $name; $( #[allow(non_snake_case)] #[no_mangle] + $(#[cfg($cond_irq)])? unsafe extern "C" fn $irq() { $( + $(#[cfg($cond_handler)])? <$handler as $crate::interrupt::typelevel::Handler<$crate::interrupt::typelevel::$irq>>::on_interrupt(); + )* } - $( - unsafe impl $crate::interrupt::typelevel::Binding<$crate::interrupt::typelevel::$irq, $handler> for $name {} - )* + $(#[cfg($cond_irq)])? + $crate::bind_interrupts!(@inner + $( + $(#[cfg($cond_handler)])? + unsafe impl $crate::interrupt::typelevel::Binding<$crate::interrupt::typelevel::$irq, $handler> for $name {} + )* + ); )* }; + (@inner $($t:tt)*) => { + $($t)* + } } // Reexports @@ -154,20 +214,28 @@ pub(crate) use stm32_metapac as pac; use crate::interrupt::Priority; #[cfg(feature = "rt")] pub use crate::pac::NVIC_PRIO_BITS; -use crate::rcc::sealed::RccPeripheral; /// `embassy-stm32` global configuration. #[non_exhaustive] +#[derive(Clone, Copy)] pub struct Config { /// RCC config. pub rcc: rcc::Config, /// Enable debug during sleep and stop. /// - /// May incrase power consumption. Defaults to true. + /// May increase power consumption. Defaults to true. #[cfg(dbgmcu)] pub enable_debug_during_sleep: bool, + /// On low-power boards (eg. `stm32l4`, `stm32l5` and `stm32u5`), + /// some GPIO pins are powered by an auxiliary, independent power supply (`VDDIO2`), + /// which needs to be enabled before these pins can be used. + /// + /// May increase power consumption. Defaults to true. + #[cfg(any(stm32l4, stm32l5, stm32u5))] + pub enable_independent_io_supply: bool, + /// BDMA interrupt priority. /// /// Defaults to P0 (highest). @@ -185,6 +253,18 @@ pub struct Config { /// Defaults to P0 (highest). #[cfg(gpdma)] pub gpdma_interrupt_priority: Priority, + + /// Enables UCPD1 dead battery functionality. + /// + /// Defaults to false (disabled). + #[cfg(peri_ucpd1)] + pub enable_ucpd1_dead_battery: bool, + + /// Enables UCPD2 dead battery functionality. + /// + /// Defaults to false (disabled). + #[cfg(peri_ucpd2)] + pub enable_ucpd2_dead_battery: bool, } impl Default for Config { @@ -193,12 +273,18 @@ impl Default for Config { rcc: Default::default(), #[cfg(dbgmcu)] enable_debug_during_sleep: true, + #[cfg(any(stm32l4, stm32l5, stm32u5))] + enable_independent_io_supply: true, #[cfg(bdma)] bdma_interrupt_priority: Priority::P0, #[cfg(dma)] dma_interrupt_priority: Priority::P0, #[cfg(gpdma)] gpdma_interrupt_priority: Priority::P0, + #[cfg(peri_ucpd1)] + enable_ucpd1_dead_battery: false, + #[cfg(peri_ucpd2)] + enable_ucpd2_dead_battery: false, } } } @@ -208,12 +294,150 @@ impl Default for Config { /// This returns the peripheral singletons that can be used for creating drivers. /// /// This should only be called once at startup, otherwise it panics. +#[cfg(not(feature = "_dual-core"))] pub fn init(config: Config) -> Peripherals { + init_hw(config) +} + +#[cfg(feature = "_dual-core")] +mod dual_core { + use core::cell::UnsafeCell; + use core::mem::MaybeUninit; + use core::sync::atomic::{AtomicUsize, Ordering}; + + use rcc::Clocks; + + use super::*; + + /// Object containing data that embassy needs to share between cores. + /// + /// It cannot be initialized by the user. The intended use is: + /// + /// ``` + /// use core::mem::MaybeUninit; + /// use embassy_stm32::{init_secondary, SharedData}; + /// + /// #[link_section = ".ram_d3"] + /// static SHARED_DATA: MaybeUninit = MaybeUninit::uninit(); + /// + /// init_secondary(&SHARED_DATA); + /// ``` + /// + /// This static must be placed in the same position for both cores. How and where this is done is left to the user. + pub struct SharedData { + init_flag: AtomicUsize, + clocks: UnsafeCell>, + config: UnsafeCell>, + } + + unsafe impl Sync for SharedData {} + + const INIT_DONE_FLAG: usize = 0xca11ab1e; + + /// Initialize the `embassy-stm32` HAL with the provided configuration. + /// This function does the actual initialization of the hardware, in contrast to [init_secondary] or [try_init_secondary]. + /// Any core can do the init, but it's important only one core does it. + /// + /// This returns the peripheral singletons that can be used for creating drivers. + /// + /// This should only be called once at startup, otherwise it panics. + /// + /// The `shared_data` is used to coordinate the init with the second core. Read the [SharedData] docs + /// for more information on its requirements. + pub fn init_primary(config: Config, shared_data: &'static MaybeUninit) -> Peripherals { + let shared_data = unsafe { shared_data.assume_init_ref() }; + + rcc::set_freqs_ptr(shared_data.clocks.get()); + let p = init_hw(config); + + unsafe { *shared_data.config.get() }.write(config); + + shared_data.init_flag.store(INIT_DONE_FLAG, Ordering::SeqCst); + + p + } + + /// Try to initialize the `embassy-stm32` HAL based on the init done by the other core using [init_primary]. + /// + /// This returns the peripheral singletons that can be used for creating drivers if the other core is done with its init. + /// If the other core is not done yet, this will return `None`. + /// + /// This should only be called once at startup, otherwise it may panic. + /// + /// The `shared_data` is used to coordinate the init with the second core. Read the [SharedData] docs + /// for more information on its requirements. + pub fn try_init_secondary(shared_data: &'static MaybeUninit) -> Option { + let shared_data = unsafe { shared_data.assume_init_ref() }; + + if shared_data.init_flag.load(Ordering::SeqCst) != INIT_DONE_FLAG { + return None; + } + + // Separate load and store to support the CM0 of the STM32WL + shared_data.init_flag.store(0, Ordering::SeqCst); + + Some(init_secondary_hw(shared_data)) + } + + /// Initialize the `embassy-stm32` HAL based on the init done by the other core using [init_primary]. + /// + /// This returns the peripheral singletons that can be used for creating drivers when the other core is done with its init. + /// If the other core is not done yet, this will spinloop wait on it. + /// + /// This should only be called once at startup, otherwise it may panic. + /// + /// The `shared_data` is used to coordinate the init with the second core. Read the [SharedData] docs + /// for more information on its requirements. + pub fn init_secondary(shared_data: &'static MaybeUninit) -> Peripherals { + loop { + if let Some(p) = try_init_secondary(shared_data) { + return p; + } + } + } + + fn init_secondary_hw(shared_data: &'static SharedData) -> Peripherals { + rcc::set_freqs_ptr(shared_data.clocks.get()); + + let config = unsafe { (*shared_data.config.get()).assume_init() }; + + // We use different timers on the different cores, so we have to still initialize one here + critical_section::with(|cs| { + unsafe { + dma::init( + cs, + #[cfg(bdma)] + config.bdma_interrupt_priority, + #[cfg(dma)] + config.dma_interrupt_priority, + #[cfg(gpdma)] + config.gpdma_interrupt_priority, + ) + } + + #[cfg(feature = "_time-driver")] + // must be after rcc init + time_driver::init(cs); + }); + + Peripherals::take() + } +} + +#[cfg(feature = "_dual-core")] +pub use dual_core::*; + +fn init_hw(config: Config) -> Peripherals { critical_section::with(|cs| { let p = Peripherals::take_with_cs(cs); #[cfg(dbgmcu)] crate::pac::DBGMCU.cr().modify(|cr| { + #[cfg(dbgmcu_h5)] + { + cr.set_stop(config.enable_debug_during_sleep); + cr.set_standby(config.enable_debug_during_sleep); + } #[cfg(any(dbgmcu_f0, dbgmcu_c0, dbgmcu_g0, dbgmcu_u5, dbgmcu_wba, dbgmcu_l5))] { cr.set_dbg_stop(config.enable_debug_during_sleep); @@ -239,13 +463,50 @@ pub fn init(config: Config) -> Peripherals { }); #[cfg(not(any(stm32f1, stm32wb, stm32wl)))] - peripherals::SYSCFG::enable_and_reset_with_cs(cs); - #[cfg(not(any(stm32h5, stm32h7, stm32wb, stm32wl)))] - peripherals::PWR::enable_and_reset_with_cs(cs); - #[cfg(not(any(stm32f2, stm32f4, stm32f7, stm32l0, stm32h5, stm32h7)))] - peripherals::FLASH::enable_and_reset_with_cs(cs); + rcc::enable_and_reset_with_cs::(cs); + #[cfg(not(any(stm32h5, stm32h7, stm32h7rs, stm32wb, stm32wl)))] + rcc::enable_and_reset_with_cs::(cs); + #[cfg(not(any(stm32f2, stm32f4, stm32f7, stm32l0, stm32h5, stm32h7, stm32h7rs)))] + rcc::enable_and_reset_with_cs::(cs); + + // Enable the VDDIO2 power supply on chips that have it. + // Note that this requires the PWR peripheral to be enabled first. + #[cfg(any(stm32l4, stm32l5))] + { + crate::pac::PWR.cr2().modify(|w| { + // The official documentation states that we should ideally enable VDDIO2 + // through the PVME2 bit, but it looks like this isn't required, + // and CubeMX itself skips this step. + w.set_iosv(config.enable_independent_io_supply); + }); + } + #[cfg(stm32u5)] + { + crate::pac::PWR.svmcr().modify(|w| { + w.set_io2sv(config.enable_independent_io_supply); + }); + } + + // dead battery functionality is still present on these + // chips despite them not having UCPD- disable it + #[cfg(any(stm32g070, stm32g0b0))] + { + crate::pac::SYSCFG.cfgr1().modify(|w| { + w.set_ucpd1_strobe(true); + w.set_ucpd2_strobe(true); + }); + } unsafe { + #[cfg(ucpd)] + ucpd::init( + cs, + #[cfg(peri_ucpd1)] + config.enable_ucpd1_dead_battery, + #[cfg(peri_ucpd2)] + config.enable_ucpd2_dead_battery, + ); + #[cfg(feature = "_split-pins-enabled")] crate::pac::SYSCFG.pmcr().modify(|pmcr| { #[cfg(feature = "split-pa0")] diff --git a/embassy-stm32/src/low_power.rs b/embassy-stm32/src/low_power.rs index 4c3d288fd..a779b8a09 100644 --- a/embassy-stm32/src/low_power.rs +++ b/embassy-stm32/src/low_power.rs @@ -10,14 +10,14 @@ //! exceptions to this rule: //! //! * `GPIO` -//! * `RCC` +//! * `RTC` //! //! Since entering and leaving low-power modes typically incurs a significant latency, the //! low-power executor will only attempt to enter when the next timer event is at least //! [`time_driver::MIN_STOP_PAUSE`] in the future. //! //! Currently there is no macro analogous to `embassy_executor::main` for this executor; -//! consequently one must define their entrypoint manually. Moveover, you must relinquish control +//! consequently one must define their entrypoint manually. Moreover, you must relinquish control //! of the `RTC` peripheral to the executor. This will typically look like //! //! ```rust,no_run @@ -51,6 +51,9 @@ //! } //! ``` +// TODO: Usage of `static mut` here is unsound. Fix then remove this `allow`.` +#![allow(static_mut_refs)] + use core::arch::asm; use core::marker::PhantomData; use core::sync::atomic::{compiler_fence, Ordering}; @@ -99,7 +102,7 @@ pub fn stop_ready(stop_mode: StopMode) -> bool { } } -/// Available stop modes. +/// Available Stop modes. #[non_exhaustive] #[derive(PartialEq)] pub enum StopMode { @@ -109,10 +112,10 @@ pub enum StopMode { Stop2, } -#[cfg(stm32l5)] +#[cfg(any(stm32l4, stm32l5, stm32u5))] use stm32_metapac::pwr::vals::Lpms; -#[cfg(stm32l5)] +#[cfg(any(stm32l4, stm32l5, stm32u5))] impl Into for StopMode { fn into(self) -> Lpms { match self { @@ -181,8 +184,14 @@ impl Executor { #[allow(unused_variables)] fn configure_stop(&mut self, stop_mode: StopMode) { - #[cfg(stm32l5)] + #[cfg(any(stm32l4, stm32l5, stm32u5))] crate::pac::PWR.cr1().modify(|m| m.set_lpms(stop_mode.into())); + #[cfg(stm32h5)] + crate::pac::PWR.pmcr().modify(|v| { + use crate::pac::pwr::vals; + v.set_lpms(vals::Lpms::STOP); + v.set_svos(vals::Svos::SCALE3); + }); } fn configure_pwr(&mut self) { @@ -191,21 +200,26 @@ impl Executor { compiler_fence(Ordering::SeqCst); let stop_mode = self.stop_mode(); + if stop_mode.is_none() { trace!("low power: not ready to stop"); - } else if self.time_driver.pause_time().is_err() { - trace!("low power: failed to pause time"); - } else { - let stop_mode = stop_mode.unwrap(); - match stop_mode { - StopMode::Stop1 => trace!("low power: stop 1"), - StopMode::Stop2 => trace!("low power: stop 2"), - } - self.configure_stop(stop_mode); - - #[cfg(not(feature = "low-power-debug-with-sleep"))] - self.scb.set_sleepdeep(); + return; } + + if self.time_driver.pause_time().is_err() { + trace!("low power: failed to pause time"); + return; + } + + let stop_mode = stop_mode.unwrap(); + match stop_mode { + StopMode::Stop1 => trace!("low power: stop 1"), + StopMode::Stop2 => trace!("low power: stop 2"), + } + self.configure_stop(stop_mode); + + #[cfg(not(feature = "low-power-debug-with-sleep"))] + self.scb.set_sleepdeep(); } /// Run the executor. diff --git a/embassy-stm32/src/lptim/channel.rs b/embassy-stm32/src/lptim/channel.rs new file mode 100644 index 000000000..17fc2fb86 --- /dev/null +++ b/embassy-stm32/src/lptim/channel.rs @@ -0,0 +1,18 @@ +/// Timer channel. +#[derive(Clone, Copy)] +pub enum Channel { + /// Channel 1. + Ch1, + /// Channel 2. + Ch2, +} + +impl Channel { + /// Get the channel index (0..1) + pub fn index(&self) -> usize { + match self { + Channel::Ch1 => 0, + Channel::Ch2 => 1, + } + } +} diff --git a/embassy-stm32/src/lptim/mod.rs b/embassy-stm32/src/lptim/mod.rs new file mode 100644 index 000000000..1649cc5b4 --- /dev/null +++ b/embassy-stm32/src/lptim/mod.rs @@ -0,0 +1,48 @@ +//! Low-power timer (LPTIM) + +pub mod pwm; +pub mod timer; + +use crate::rcc::RccPeripheral; + +/// Timer channel. +#[cfg(any(lptim_v2a, lptim_v2b))] +mod channel; +#[cfg(any(lptim_v2a, lptim_v2b))] +pub use channel::Channel; + +pin_trait!(OutputPin, BasicInstance); +pin_trait!(Channel1Pin, BasicInstance); +pin_trait!(Channel2Pin, BasicInstance); + +pub(crate) trait SealedInstance: RccPeripheral { + fn regs() -> crate::pac::lptim::Lptim; +} +pub(crate) trait SealedBasicInstance: RccPeripheral {} + +/// LPTIM basic instance trait. +#[allow(private_bounds)] +pub trait BasicInstance: SealedBasicInstance + 'static {} + +/// LPTIM instance trait. +#[allow(private_bounds)] +pub trait Instance: BasicInstance + SealedInstance + 'static {} + +foreach_interrupt! { + ($inst:ident, lptim, LPTIM, GLOBAL, $irq:ident) => { + impl SealedInstance for crate::peripherals::$inst { + fn regs() -> crate::pac::lptim::Lptim { + crate::pac::$inst + } + } + impl SealedBasicInstance for crate::peripherals::$inst { + } + impl BasicInstance for crate::peripherals::$inst {} + impl Instance for crate::peripherals::$inst {} + }; + ($inst:ident, lptim, LPTIM_BASIC, GLOBAL, $irq:ident) => { + impl SealedBasicInstance for crate::peripherals::$inst { + } + impl BasicInstance for crate::peripherals::$inst {} + }; +} diff --git a/embassy-stm32/src/lptim/pwm.rs b/embassy-stm32/src/lptim/pwm.rs new file mode 100644 index 000000000..1f43eb6ee --- /dev/null +++ b/embassy-stm32/src/lptim/pwm.rs @@ -0,0 +1,168 @@ +//! PWM driver. + +use core::marker::PhantomData; + +use embassy_hal_internal::{into_ref, PeripheralRef}; + +use super::timer::Timer; +#[cfg(not(any(lptim_v2a, lptim_v2b)))] +use super::OutputPin; +#[cfg(any(lptim_v2a, lptim_v2b))] +use super::{channel::Channel, timer::ChannelDirection, Channel1Pin, Channel2Pin}; +use super::{BasicInstance, Instance}; +use crate::gpio::{AfType, AnyPin, OutputType, Speed}; +use crate::time::Hertz; +use crate::Peripheral; + +/// Output marker type. +pub enum Output {} +/// Channel 1 marker type. +pub enum Ch1 {} +/// Channel 2 marker type. +pub enum Ch2 {} + +/// PWM pin wrapper. +/// +/// This wraps a pin to make it usable with PWM. +pub struct PwmPin<'d, T, C> { + _pin: PeripheralRef<'d, AnyPin>, + phantom: PhantomData<(T, C)>, +} + +macro_rules! channel_impl { + ($new_chx:ident, $channel:ident, $pin_trait:ident) => { + impl<'d, T: BasicInstance> PwmPin<'d, T, $channel> { + #[doc = concat!("Create a new ", stringify!($channel), " PWM pin instance.")] + pub fn $new_chx(pin: impl Peripheral

> + 'd) -> Self { + into_ref!(pin); + critical_section::with(|_| { + pin.set_low(); + pin.set_as_af( + pin.af_num(), + AfType::output(OutputType::PushPull, Speed::VeryHigh), + ); + }); + PwmPin { + _pin: pin.map_into(), + phantom: PhantomData, + } + } + } + }; +} + +#[cfg(not(any(lptim_v2a, lptim_v2b)))] +channel_impl!(new, Output, OutputPin); +#[cfg(any(lptim_v2a, lptim_v2b))] +channel_impl!(new_ch1, Ch1, Channel1Pin); +#[cfg(any(lptim_v2a, lptim_v2b))] +channel_impl!(new_ch2, Ch2, Channel2Pin); + +/// PWM driver. +pub struct Pwm<'d, T: Instance> { + inner: Timer<'d, T>, +} + +#[cfg(not(any(lptim_v2a, lptim_v2b)))] +impl<'d, T: Instance> Pwm<'d, T> { + /// Create a new PWM driver. + pub fn new(tim: impl Peripheral

+ 'd, _output_pin: PwmPin<'d, T, Output>, freq: Hertz) -> Self { + Self::new_inner(tim, freq) + } + + /// Set the duty. + /// + /// The value ranges from 0 for 0% duty, to [`get_max_duty`](Self::get_max_duty) for 100% duty, both included. + pub fn set_duty(&mut self, duty: u16) { + assert!(duty <= self.get_max_duty()); + self.inner.set_compare_value(duty) + } + + /// Get the duty. + /// + /// The value ranges from 0 for 0% duty, to [`get_max_duty`](Self::get_max_duty) for 100% duty, both included. + pub fn get_duty(&self) -> u16 { + self.inner.get_compare_value() + } + + fn post_init(&mut self) {} +} + +#[cfg(any(lptim_v2a, lptim_v2b))] +impl<'d, T: Instance> Pwm<'d, T> { + /// Create a new PWM driver. + pub fn new( + tim: impl Peripheral

+ 'd, + _ch1_pin: Option>, + _ch2_pin: Option>, + freq: Hertz, + ) -> Self { + Self::new_inner(tim, freq) + } + + /// Enable the given channel. + pub fn enable(&mut self, channel: Channel) { + self.inner.enable_channel(channel, true); + } + + /// Disable the given channel. + pub fn disable(&mut self, channel: Channel) { + self.inner.enable_channel(channel, false); + } + + /// Check whether given channel is enabled + pub fn is_enabled(&self, channel: Channel) -> bool { + self.inner.get_channel_enable_state(channel) + } + + /// Set the duty for a given channel. + /// + /// The value ranges from 0 for 0% duty, to [`get_max_duty`](Self::get_max_duty) for 100% duty, both included. + pub fn set_duty(&mut self, channel: Channel, duty: u16) { + assert!(duty <= self.get_max_duty()); + self.inner.set_compare_value(channel, duty) + } + + /// Get the duty for a given channel. + /// + /// The value ranges from 0 for 0% duty, to [`get_max_duty`](Self::get_max_duty) for 100% duty, both included. + pub fn get_duty(&self, channel: Channel) -> u16 { + self.inner.get_compare_value(channel) + } + + fn post_init(&mut self) { + [Channel::Ch1, Channel::Ch2].iter().for_each(|&channel| { + self.inner.set_channel_direction(channel, ChannelDirection::OutputPwm); + }); + } +} + +impl<'d, T: Instance> Pwm<'d, T> { + fn new_inner(tim: impl Peripheral

+ 'd, freq: Hertz) -> Self { + let mut this = Self { inner: Timer::new(tim) }; + + this.inner.enable(); + this.set_frequency(freq); + + this.post_init(); + + this.inner.continuous_mode_start(); + + this + } + + /// Set PWM frequency. + /// + /// Note: when you call this, the max duty value changes, so you will have to + /// call `set_duty` on all channels with the duty calculated based on the new max duty. + pub fn set_frequency(&mut self, frequency: Hertz) { + self.inner.set_frequency(frequency); + } + + /// Get max duty value. + /// + /// This value depends on the configured frequency and the timer's clock rate from RCC. + pub fn get_max_duty(&self) -> u16 { + self.inner.get_max_compare_value() + 1 + } +} diff --git a/embassy-stm32/src/lptim/timer/channel_direction.rs b/embassy-stm32/src/lptim/timer/channel_direction.rs new file mode 100644 index 000000000..a38df63cd --- /dev/null +++ b/embassy-stm32/src/lptim/timer/channel_direction.rs @@ -0,0 +1,18 @@ +use crate::pac::lptim::vals; + +/// Direction of a low-power timer channel +pub enum ChannelDirection { + /// Use channel as a PWM output + OutputPwm, + /// Use channel as an input capture + InputCapture, +} + +impl From for vals::Ccsel { + fn from(direction: ChannelDirection) -> Self { + match direction { + ChannelDirection::OutputPwm => vals::Ccsel::OUTPUTCOMPARE, + ChannelDirection::InputCapture => vals::Ccsel::INPUTCAPTURE, + } + } +} diff --git a/embassy-stm32/src/lptim/timer/mod.rs b/embassy-stm32/src/lptim/timer/mod.rs new file mode 100644 index 000000000..e62fcab49 --- /dev/null +++ b/embassy-stm32/src/lptim/timer/mod.rs @@ -0,0 +1,133 @@ +//! Low-level timer driver. +mod prescaler; + +use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef}; + +#[cfg(any(lptim_v2a, lptim_v2b))] +use super::channel::Channel; +#[cfg(any(lptim_v2a, lptim_v2b))] +mod channel_direction; +#[cfg(any(lptim_v2a, lptim_v2b))] +pub use channel_direction::ChannelDirection; +use prescaler::Prescaler; + +use super::Instance; +use crate::rcc; +use crate::time::Hertz; + +/// Low-level timer driver. +pub struct Timer<'d, T: Instance> { + _tim: PeripheralRef<'d, T>, +} + +impl<'d, T: Instance> Timer<'d, T> { + /// Create a new timer driver. + pub fn new(tim: impl Peripheral

+ 'd) -> Self { + into_ref!(tim); + + rcc::enable_and_reset::(); + + Self { _tim: tim } + } + + /// Enable the timer. + pub fn enable(&self) { + T::regs().cr().modify(|w| w.set_enable(true)); + } + + /// Disable the timer. + pub fn disable(&self) { + T::regs().cr().modify(|w| w.set_enable(false)); + } + + /// Start the timer in single pulse mode. + pub fn single_mode_start(&self) { + T::regs().cr().modify(|w| w.set_sngstrt(true)); + } + + /// Start the timer in continuous mode. + pub fn continuous_mode_start(&self) { + T::regs().cr().modify(|w| w.set_cntstrt(true)); + } + + /// Set the frequency of how many times per second the timer counts up to the max value or down to 0. + pub fn set_frequency(&self, frequency: Hertz) { + let f = frequency.0; + assert!(f > 0); + + let pclk_f = T::frequency().0; + + let pclk_ticks_per_timer_period = pclk_f / f; + + let psc = Prescaler::from_ticks(pclk_ticks_per_timer_period); + let arr = psc.scale_down(pclk_ticks_per_timer_period); + + T::regs().cfgr().modify(|r| r.set_presc((&psc).into())); + T::regs().arr().modify(|r| r.set_arr(arr.into())); + } + + /// Get the timer frequency. + pub fn get_frequency(&self) -> Hertz { + let pclk_f = T::frequency(); + let arr = T::regs().arr().read().arr(); + let psc = Prescaler::from(T::regs().cfgr().read().presc()); + + pclk_f / psc.scale_up(arr) + } + + /// Get the clock frequency of the timer (before prescaler is applied). + pub fn get_clock_frequency(&self) -> Hertz { + T::frequency() + } + + /// Get max compare value. This depends on the timer frequency and the clock frequency from RCC. + pub fn get_max_compare_value(&self) -> u16 { + T::regs().arr().read().arr() + } +} + +#[cfg(any(lptim_v2a, lptim_v2b))] +impl<'d, T: Instance> Timer<'d, T> { + /// Enable/disable a channel. + pub fn enable_channel(&self, channel: Channel, enable: bool) { + T::regs().ccmr(0).modify(|w| { + w.set_cce(channel.index(), enable); + }); + } + + /// Get enable/disable state of a channel + pub fn get_channel_enable_state(&self, channel: Channel) -> bool { + T::regs().ccmr(0).read().cce(channel.index()) + } + + /// Set compare value for a channel. + pub fn set_compare_value(&self, channel: Channel, value: u16) { + T::regs().ccr(channel.index()).modify(|w| w.set_ccr(value)); + } + + /// Get compare value for a channel. + pub fn get_compare_value(&self, channel: Channel) -> u16 { + T::regs().ccr(channel.index()).read().ccr() + } + + /// Set channel direction. + #[cfg(any(lptim_v2a, lptim_v2b))] + pub fn set_channel_direction(&self, channel: Channel, direction: ChannelDirection) { + T::regs() + .ccmr(0) + .modify(|w| w.set_ccsel(channel.index(), direction.into())); + } +} + +#[cfg(not(any(lptim_v2a, lptim_v2b)))] +impl<'d, T: Instance> Timer<'d, T> { + /// Set compare value for a channel. + pub fn set_compare_value(&self, value: u16) { + T::regs().cmp().modify(|w| w.set_cmp(value)); + } + + /// Get compare value for a channel. + pub fn get_compare_value(&self) -> u16 { + T::regs().cmp().read().cmp() + } +} diff --git a/embassy-stm32/src/lptim/timer/prescaler.rs b/embassy-stm32/src/lptim/timer/prescaler.rs new file mode 100644 index 000000000..5d2326faf --- /dev/null +++ b/embassy-stm32/src/lptim/timer/prescaler.rs @@ -0,0 +1,90 @@ +//! Low-level timer driver. + +use crate::pac::lptim::vals; + +pub enum Prescaler { + Div1, + Div2, + Div4, + Div8, + Div16, + Div32, + Div64, + Div128, +} + +impl From<&Prescaler> for vals::Presc { + fn from(prescaler: &Prescaler) -> Self { + match prescaler { + Prescaler::Div1 => vals::Presc::DIV1, + Prescaler::Div2 => vals::Presc::DIV2, + Prescaler::Div4 => vals::Presc::DIV4, + Prescaler::Div8 => vals::Presc::DIV8, + Prescaler::Div16 => vals::Presc::DIV16, + Prescaler::Div32 => vals::Presc::DIV32, + Prescaler::Div64 => vals::Presc::DIV64, + Prescaler::Div128 => vals::Presc::DIV128, + } + } +} + +impl From for Prescaler { + fn from(prescaler: vals::Presc) -> Self { + match prescaler { + vals::Presc::DIV1 => Prescaler::Div1, + vals::Presc::DIV2 => Prescaler::Div2, + vals::Presc::DIV4 => Prescaler::Div4, + vals::Presc::DIV8 => Prescaler::Div8, + vals::Presc::DIV16 => Prescaler::Div16, + vals::Presc::DIV32 => Prescaler::Div32, + vals::Presc::DIV64 => Prescaler::Div64, + vals::Presc::DIV128 => Prescaler::Div128, + } + } +} + +impl From<&Prescaler> for u32 { + fn from(prescaler: &Prescaler) -> Self { + match prescaler { + Prescaler::Div1 => 1, + Prescaler::Div2 => 2, + Prescaler::Div4 => 4, + Prescaler::Div8 => 8, + Prescaler::Div16 => 16, + Prescaler::Div32 => 32, + Prescaler::Div64 => 64, + Prescaler::Div128 => 128, + } + } +} + +impl From for Prescaler { + fn from(prescaler: u32) -> Self { + match prescaler { + 1 => Prescaler::Div1, + 2 => Prescaler::Div2, + 4 => Prescaler::Div4, + 8 => Prescaler::Div8, + 16 => Prescaler::Div16, + 32 => Prescaler::Div32, + 64 => Prescaler::Div64, + 128 => Prescaler::Div128, + _ => unreachable!(), + } + } +} + +impl Prescaler { + pub fn from_ticks(ticks: u32) -> Self { + // We need to scale down to a 16-bit range + (ticks >> 16).next_power_of_two().into() + } + + pub fn scale_down(&self, ticks: u32) -> u16 { + (ticks / u32::from(self)).try_into().unwrap() + } + + pub fn scale_up(&self, ticks: u16) -> u32 { + u32::from(self) * ticks as u32 + } +} diff --git a/embassy-stm32/src/ltdc.rs b/embassy-stm32/src/ltdc.rs new file mode 100644 index 000000000..e25c4f3fb --- /dev/null +++ b/embassy-stm32/src/ltdc.rs @@ -0,0 +1,578 @@ +//! LTDC - LCD-TFT Display Controller +//! See ST application note AN4861: Introduction to LCD-TFT display controller (LTDC) on STM32 MCUs for high level details +//! This module was tested against the stm32h735g-dk using the RM0468 ST reference manual for detailed register information + +use core::future::poll_fn; +use core::marker::PhantomData; +use core::task::Poll; + +use embassy_hal_internal::{into_ref, PeripheralRef}; +use embassy_sync::waitqueue::AtomicWaker; +use stm32_metapac::ltdc::regs::Dccr; +use stm32_metapac::ltdc::vals::{Bf1, Bf2, Cfuif, Clif, Crrif, Cterrif, Pf, Vbr}; + +use crate::gpio::{AfType, OutputType, Speed}; +use crate::interrupt::typelevel::Interrupt; +use crate::interrupt::{self}; +use crate::{peripherals, rcc, Peripheral}; + +static LTDC_WAKER: AtomicWaker = AtomicWaker::new(); + +/// LTDC error +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Error { + /// FIFO underrun. Generated when a pixel is requested while the FIFO is empty + FifoUnderrun, + /// Transfer error. Generated when a bus error occurs + TransferError, +} + +/// Display configuration parameters +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct LtdcConfiguration { + /// Active width in pixels + pub active_width: u16, + /// Active height in pixels + pub active_height: u16, + + /// Horizontal back porch (in units of pixel clock period) + pub h_back_porch: u16, + /// Horizontal front porch (in units of pixel clock period) + pub h_front_porch: u16, + /// Vertical back porch (in units of horizontal scan line) + pub v_back_porch: u16, + /// Vertical front porch (in units of horizontal scan line) + pub v_front_porch: u16, + + /// Horizontal synchronization width (in units of pixel clock period) + pub h_sync: u16, + /// Vertical synchronization height (in units of horizontal scan line) + pub v_sync: u16, + + /// Horizontal synchronization polarity: `false`: active low, `true`: active high + pub h_sync_polarity: PolarityActive, + /// Vertical synchronization polarity: `false`: active low, `true`: active high + pub v_sync_polarity: PolarityActive, + /// Data enable polarity: `false`: active low, `true`: active high + pub data_enable_polarity: PolarityActive, + /// Pixel clock polarity: `false`: falling edge, `true`: rising edge + pub pixel_clock_polarity: PolarityEdge, +} + +/// Edge polarity +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum PolarityEdge { + /// Falling edge + FallingEdge, + /// Rising edge + RisingEdge, +} + +/// Active polarity +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum PolarityActive { + /// Active low + ActiveLow, + /// Active high + ActiveHigh, +} + +/// LTDC driver. +pub struct Ltdc<'d, T: Instance> { + _peri: PeripheralRef<'d, T>, +} + +/// LTDC interrupt handler. +pub struct InterruptHandler { + _phantom: PhantomData, +} + +/// 24 bit color +#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct RgbColor { + /// Red + pub red: u8, + /// Green + pub green: u8, + /// Blue + pub blue: u8, +} + +/// Layer +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct LtdcLayerConfig { + /// Layer number + pub layer: LtdcLayer, + /// Pixel format + pub pixel_format: PixelFormat, + /// Window left x in pixels + pub window_x0: u16, + /// Window right x in pixels + pub window_x1: u16, + /// Window top y in pixels + pub window_y0: u16, + /// Window bottom y in pixels + pub window_y1: u16, +} + +/// Pixel format +#[repr(u8)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum PixelFormat { + /// ARGB8888 + ARGB8888 = Pf::ARGB8888 as u8, + /// RGB888 + RGB888 = Pf::RGB888 as u8, + /// RGB565 + RGB565 = Pf::RGB565 as u8, + /// ARGB1555 + ARGB1555 = Pf::ARGB1555 as u8, + /// ARGB4444 + ARGB4444 = Pf::ARGB4444 as u8, + /// L8 (8-bit luminance) + L8 = Pf::L8 as u8, + /// AL44 (4-bit alpha, 4-bit luminance + AL44 = Pf::AL44 as u8, + /// AL88 (8-bit alpha, 8-bit luminance) + AL88 = Pf::AL88 as u8, +} + +impl PixelFormat { + /// Number of bytes per pixel + pub fn bytes_per_pixel(&self) -> usize { + match self { + PixelFormat::ARGB8888 => 4, + PixelFormat::RGB888 => 3, + PixelFormat::RGB565 | PixelFormat::ARGB4444 | PixelFormat::ARGB1555 | PixelFormat::AL88 => 2, + PixelFormat::AL44 | PixelFormat::L8 => 1, + } + } +} + +/// Ltdc Blending Layer +#[repr(usize)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum LtdcLayer { + /// Bottom layer + Layer1 = 0, + /// Top layer + Layer2 = 1, +} + +impl interrupt::typelevel::Handler for InterruptHandler { + unsafe fn on_interrupt() { + cortex_m::asm::dsb(); + Ltdc::::enable_interrupts(false); + LTDC_WAKER.wake(); + } +} + +impl<'d, T: Instance> Ltdc<'d, T> { + // Create a new LTDC driver without specifying color and control pins. This is typically used if you want to drive a display though a DsiHost + /// Note: Full-Duplex modes are not supported at this time + pub fn new(peri: impl Peripheral

+ 'd) -> Self { + Self::setup_clocks(); + into_ref!(peri); + Self { _peri: peri } + } + + /// Create a new LTDC driver. 8 pins per color channel for blue, green and red + #[allow(clippy::too_many_arguments)] + pub fn new_with_pins( + peri: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + clk: impl Peripheral

> + 'd, + hsync: impl Peripheral

> + 'd, + vsync: impl Peripheral

> + 'd, + b0: impl Peripheral

> + 'd, + b1: impl Peripheral

> + 'd, + b2: impl Peripheral

> + 'd, + b3: impl Peripheral

> + 'd, + b4: impl Peripheral

> + 'd, + b5: impl Peripheral

> + 'd, + b6: impl Peripheral

> + 'd, + b7: impl Peripheral

> + 'd, + g0: impl Peripheral

> + 'd, + g1: impl Peripheral

> + 'd, + g2: impl Peripheral

> + 'd, + g3: impl Peripheral

> + 'd, + g4: impl Peripheral

> + 'd, + g5: impl Peripheral

> + 'd, + g6: impl Peripheral

> + 'd, + g7: impl Peripheral

> + 'd, + r0: impl Peripheral

> + 'd, + r1: impl Peripheral

> + 'd, + r2: impl Peripheral

> + 'd, + r3: impl Peripheral

> + 'd, + r4: impl Peripheral

> + 'd, + r5: impl Peripheral

> + 'd, + r6: impl Peripheral

> + 'd, + r7: impl Peripheral

> + 'd, + ) -> Self { + Self::setup_clocks(); + into_ref!(peri); + new_pin!(clk, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(hsync, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(vsync, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(b0, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(b1, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(b2, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(b3, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(b4, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(b5, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(b6, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(b7, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(g0, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(g1, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(g2, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(g3, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(g4, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(g5, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(g6, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(g7, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(r0, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(r1, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(r2, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(r3, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(r4, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(r5, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(r6, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + new_pin!(r7, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + + Self { _peri: peri } + } + + /// Initialise and enable the display + pub fn init(&mut self, config: &LtdcConfiguration) { + use stm32_metapac::ltdc::vals::{Depol, Hspol, Pcpol, Vspol}; + let ltdc = T::regs(); + + // check bus access + assert!(ltdc.gcr().read().0 == 0x2220); // reset value + + // configure the HS, VS, DE and PC polarity + ltdc.gcr().modify(|w| { + w.set_hspol(match config.h_sync_polarity { + PolarityActive::ActiveHigh => Hspol::ACTIVEHIGH, + PolarityActive::ActiveLow => Hspol::ACTIVELOW, + }); + + w.set_vspol(match config.v_sync_polarity { + PolarityActive::ActiveHigh => Vspol::ACTIVEHIGH, + PolarityActive::ActiveLow => Vspol::ACTIVELOW, + }); + + w.set_depol(match config.data_enable_polarity { + PolarityActive::ActiveHigh => Depol::ACTIVEHIGH, + PolarityActive::ActiveLow => Depol::ACTIVELOW, + }); + + w.set_pcpol(match config.pixel_clock_polarity { + PolarityEdge::RisingEdge => Pcpol::RISINGEDGE, + PolarityEdge::FallingEdge => Pcpol::FALLINGEDGE, + }); + }); + + // set synchronization pulse width + ltdc.sscr().modify(|w| { + w.set_vsh(config.v_sync - 1); + w.set_hsw(config.h_sync - 1); + }); + + // set accumulated back porch + ltdc.bpcr().modify(|w| { + w.set_avbp(config.v_sync + config.v_back_porch - 1); + w.set_ahbp(config.h_sync + config.h_back_porch - 1); + }); + + // set accumulated active width + let aa_height = config.v_sync + config.v_back_porch + config.active_height - 1; + let aa_width = config.h_sync + config.h_back_porch + config.active_width - 1; + ltdc.awcr().modify(|w| { + w.set_aah(aa_height); + w.set_aaw(aa_width); + }); + + // set total width and height + let total_height: u16 = config.v_sync + config.v_back_porch + config.active_height + config.v_front_porch - 1; + let total_width: u16 = config.h_sync + config.h_back_porch + config.active_width + config.h_front_porch - 1; + ltdc.twcr().modify(|w| { + w.set_totalh(total_height); + w.set_totalw(total_width) + }); + + // set the background color value to black + ltdc.bccr().modify(|w| { + w.set_bcred(0); + w.set_bcgreen(0); + w.set_bcblue(0); + }); + + self.enable(); + } + + /// Set the enable bit in the control register and assert that it has been enabled + /// + /// This does need to be called if init has already been called + pub fn enable(&mut self) { + T::regs().gcr().modify(|w| w.set_ltdcen(true)); + assert!(T::regs().gcr().read().ltdcen()) + } + + /// Unset the enable bit in the control register and assert that it has been disabled + pub fn disable(&mut self) { + T::regs().gcr().modify(|w| w.set_ltdcen(false)); + assert!(!T::regs().gcr().read().ltdcen()) + } + + /// Initialise and enable the layer + /// + /// clut - a 256 length color look-up table applies to L8, AL44 and AL88 pixel format and will default to greyscale if `None` supplied and these pixel formats are used + pub fn init_layer(&mut self, layer_config: &LtdcLayerConfig, clut: Option<&[RgbColor]>) { + let ltdc = T::regs(); + let layer = ltdc.layer(layer_config.layer as usize); + + // 256 color look-up table for L8, AL88 and AL88 pixel formats + if let Some(clut) = clut { + assert_eq!(clut.len(), 256, "Color lookup table must be exactly 256 in length"); + for (index, color) in clut.iter().enumerate() { + layer.clutwr().write(|w| { + w.set_clutadd(index as u8); + w.set_red(color.red); + w.set_green(color.green); + w.set_blue(color.blue); + }); + } + } + + // configure the horizontal start and stop position + let h_win_start = layer_config.window_x0 + ltdc.bpcr().read().ahbp() + 1; + let h_win_stop = layer_config.window_x1 + ltdc.bpcr().read().ahbp(); + layer.whpcr().write(|w| { + w.set_whstpos(h_win_start); + w.set_whsppos(h_win_stop); + }); + + // configure the vertical start and stop position + let v_win_start = layer_config.window_y0 + ltdc.bpcr().read().avbp() + 1; + let v_win_stop = layer_config.window_y1 + ltdc.bpcr().read().avbp(); + layer.wvpcr().write(|w| { + w.set_wvstpos(v_win_start); + w.set_wvsppos(v_win_stop) + }); + + // set the pixel format + layer + .pfcr() + .write(|w| w.set_pf(Pf::from_bits(layer_config.pixel_format as u8))); + + // set the default color value to transparent black + layer.dccr().write_value(Dccr::default()); + + // set the global constant alpha value + let alpha = 0xFF; + layer.cacr().write(|w| w.set_consta(alpha)); + + // set the blending factors. + layer.bfcr().modify(|w| { + w.set_bf1(Bf1::PIXEL); + w.set_bf2(Bf2::PIXEL); + }); + + // calculate framebuffer pixel size in bytes + let bytes_per_pixel = layer_config.pixel_format.bytes_per_pixel() as u16; + let width = layer_config.window_x1 - layer_config.window_x0; + let height = layer_config.window_y1 - layer_config.window_y0; + + // framebuffer pitch and line length + layer.cfblr().modify(|w| { + w.set_cfbp(width * bytes_per_pixel); + #[cfg(not(stm32u5))] + w.set_cfbll(width * bytes_per_pixel + 7); + #[cfg(stm32u5)] + w.set_cfbll(width * bytes_per_pixel + 3); + }); + + // framebuffer line number + layer.cfblnr().modify(|w| w.set_cfblnbr(height)); + + // enable LTDC_Layer by setting LEN bit + layer.cr().modify(|w| { + if clut.is_some() { + w.set_cluten(true); + } + w.set_len(true); + }); + } + + /// Set the current buffer. The async function will return when buffer has been completely copied to the LCD screen + /// frame_buffer_addr is a pointer to memory that should not move (best to make it static) + pub async fn set_buffer(&mut self, layer: LtdcLayer, frame_buffer_addr: *const ()) -> Result<(), Error> { + let mut bits = T::regs().isr().read(); + + // if all clear + if !bits.fuif() && !bits.lif() && !bits.rrif() && !bits.terrif() { + // wait for interrupt + poll_fn(|cx| { + // quick check to avoid registration if already done. + let bits = T::regs().isr().read(); + if bits.fuif() || bits.lif() || bits.rrif() || bits.terrif() { + return Poll::Ready(()); + } + + LTDC_WAKER.register(cx.waker()); + Self::clear_interrupt_flags(); // don't poison the request with old flags + Self::enable_interrupts(true); + + // set the new frame buffer address + let layer = T::regs().layer(layer as usize); + layer.cfbar().modify(|w| w.set_cfbadd(frame_buffer_addr as u32)); + + // configure a shadow reload for the next blanking period + T::regs().srcr().write(|w| { + w.set_vbr(Vbr::RELOAD); + }); + + // need to check condition after register to avoid a race + // condition that would result in lost notifications. + let bits = T::regs().isr().read(); + if bits.fuif() || bits.lif() || bits.rrif() || bits.terrif() { + Poll::Ready(()) + } else { + Poll::Pending + } + }) + .await; + + // re-read the status register after wait. + bits = T::regs().isr().read(); + } + + let result = if bits.fuif() { + Err(Error::FifoUnderrun) + } else if bits.terrif() { + Err(Error::TransferError) + } else if bits.lif() { + panic!("line interrupt event is disabled") + } else if bits.rrif() { + // register reload flag is expected + Ok(()) + } else { + unreachable!("all interrupt status values checked") + }; + + Self::clear_interrupt_flags(); + result + } + + fn setup_clocks() { + critical_section::with(|_cs| { + // RM says the pllsaidivr should only be changed when pllsai is off. But this could have other unintended side effects. So let's just give it a try like this. + // According to the debugger, this bit gets set, anyway. + #[cfg(stm32f7)] + crate::pac::RCC + .dckcfgr1() + .modify(|w| w.set_pllsaidivr(stm32_metapac::rcc::vals::Pllsaidivr::DIV2)); + + // It is set to RCC_PLLSAIDIVR_2 in ST's BSP example for the STM32469I-DISCO. + #[cfg(stm32f4)] + crate::pac::RCC + .dckcfgr() + .modify(|w| w.set_pllsaidivr(stm32_metapac::rcc::vals::Pllsaidivr::DIV2)); + }); + + rcc::enable_and_reset::(); + } + + fn clear_interrupt_flags() { + T::regs().icr().write(|w| { + w.set_cfuif(Cfuif::CLEAR); + w.set_clif(Clif::CLEAR); + w.set_crrif(Crrif::CLEAR); + w.set_cterrif(Cterrif::CLEAR); + }); + } + + fn enable_interrupts(enable: bool) { + T::regs().ier().write(|w| { + w.set_fuie(enable); + w.set_lie(false); // we are not interested in the line interrupt enable event + w.set_rrie(enable); + w.set_terrie(enable) + }); + + // enable interrupts for LTDC peripheral + T::Interrupt::unpend(); + if enable { + unsafe { T::Interrupt::enable() }; + } else { + T::Interrupt::disable() + } + } +} + +impl<'d, T: Instance> Drop for Ltdc<'d, T> { + fn drop(&mut self) {} +} + +trait SealedInstance: crate::rcc::SealedRccPeripheral { + fn regs() -> crate::pac::ltdc::Ltdc; +} + +/// LTDC instance trait. +#[allow(private_bounds)] +pub trait Instance: SealedInstance + Peripheral

+ crate::rcc::RccPeripheral + 'static + Send { + /// Interrupt for this LTDC instance. + type Interrupt: interrupt::typelevel::Interrupt; +} + +pin_trait!(ClkPin, Instance); +pin_trait!(HsyncPin, Instance); +pin_trait!(VsyncPin, Instance); +pin_trait!(DePin, Instance); +pin_trait!(R0Pin, Instance); +pin_trait!(R1Pin, Instance); +pin_trait!(R2Pin, Instance); +pin_trait!(R3Pin, Instance); +pin_trait!(R4Pin, Instance); +pin_trait!(R5Pin, Instance); +pin_trait!(R6Pin, Instance); +pin_trait!(R7Pin, Instance); +pin_trait!(G0Pin, Instance); +pin_trait!(G1Pin, Instance); +pin_trait!(G2Pin, Instance); +pin_trait!(G3Pin, Instance); +pin_trait!(G4Pin, Instance); +pin_trait!(G5Pin, Instance); +pin_trait!(G6Pin, Instance); +pin_trait!(G7Pin, Instance); +pin_trait!(B0Pin, Instance); +pin_trait!(B1Pin, Instance); +pin_trait!(B2Pin, Instance); +pin_trait!(B3Pin, Instance); +pin_trait!(B4Pin, Instance); +pin_trait!(B5Pin, Instance); +pin_trait!(B6Pin, Instance); +pin_trait!(B7Pin, Instance); + +foreach_interrupt!( + ($inst:ident, ltdc, LTDC, GLOBAL, $irq:ident) => { + impl Instance for peripherals::$inst { + type Interrupt = crate::interrupt::typelevel::$irq; + } + + impl SealedInstance for peripherals::$inst { + fn regs() -> crate::pac::ltdc::Ltdc { + crate::pac::$inst + } + } + }; +); diff --git a/embassy-stm32/src/traits.rs b/embassy-stm32/src/macros.rs similarity index 52% rename from embassy-stm32/src/traits.rs rename to embassy-stm32/src/macros.rs index 13f695821..ae53deb08 100644 --- a/embassy-stm32/src/traits.rs +++ b/embassy-stm32/src/macros.rs @@ -1,5 +1,45 @@ #![macro_use] +macro_rules! peri_trait { + ( + $(irqs: [$($irq:ident),*],)? + ) => { + #[allow(private_interfaces)] + pub(crate) trait SealedInstance { + #[allow(unused)] + fn info() -> &'static Info; + #[allow(unused)] + fn state() -> &'static State; + } + + /// Peripheral instance trait. + #[allow(private_bounds)] + pub trait Instance: crate::Peripheral

+ SealedInstance + crate::rcc::RccPeripheral { + $($( + /// Interrupt for this peripheral. + type $irq: crate::interrupt::typelevel::Interrupt; + )*)? + } + }; +} + +macro_rules! peri_trait_impl { + ($instance:ident, $info:expr) => { + #[allow(private_interfaces)] + impl SealedInstance for crate::peripherals::$instance { + fn info() -> &'static Info { + static INFO: Info = $info; + &INFO + } + fn state() -> &'static State { + static STATE: State = State::new(); + &STATE + } + } + impl Instance for crate::peripherals::$instance {} + }; +} + macro_rules! pin_trait { ($signal:ident, $instance:path $(, $mode:path)?) => { #[doc = concat!(stringify!($signal), " pin trait")] @@ -36,32 +76,7 @@ macro_rules! dma_trait { #[allow(unused)] macro_rules! dma_trait_impl { - // DMAMUX - (crate::$mod:ident::$trait:ident$(<$mode:ident>)?, $instance:ident, {dmamux: $dmamux:ident}, $request:expr) => { - impl crate::$mod::$trait for T - where - T: crate::dma::Channel + crate::dma::MuxChannel, - { - fn request(&self) -> crate::dma::Request { - $request - } - } - }; - - // DMAMUX - (crate::$mod:ident::$trait:ident$(<$mode:ident>)?, $instance:ident, {dma: $dma:ident}, $request:expr) => { - impl crate::$mod::$trait for T - where - T: crate::dma::Channel, - { - fn request(&self) -> crate::dma::Request { - $request - } - } - }; - - // DMA/GPDMA, without DMAMUX - (crate::$mod:ident::$trait:ident$(<$mode:ident>)?, $instance:ident, {channel: $channel:ident}, $request:expr) => { + (crate::$mod:ident::$trait:ident$(<$mode:ident>)?, $instance:ident, $channel:ident, $request:expr) => { impl crate::$mod::$trait for crate::peripherals::$channel { fn request(&self) -> crate::dma::Request { $request @@ -69,3 +84,22 @@ macro_rules! dma_trait_impl { } }; } + +macro_rules! new_dma { + ($name:ident) => {{ + let dma = $name.into_ref(); + let request = dma.request(); + Some(crate::dma::ChannelAndRequest { + channel: dma.map_into(), + request, + }) + }}; +} + +macro_rules! new_pin { + ($name:ident, $af_type:expr) => {{ + let pin = $name.into_ref(); + pin.set_as_af(pin.af_num(), $af_type); + Some(pin.map_into()) + }}; +} diff --git a/embassy-stm32/src/opamp.rs b/embassy-stm32/src/opamp.rs index ae8b3cacc..c86c18e22 100644 --- a/embassy-stm32/src/opamp.rs +++ b/embassy-stm32/src/opamp.rs @@ -45,6 +45,7 @@ pub struct OpAmpOutput<'d, T: Instance> { /// OpAmp internal outputs, wired directly to ADC inputs. /// /// This struct can be used as an ADC input. +#[cfg(opamp_g4)] pub struct OpAmpInternalOutput<'d, T: Instance> { _inner: &'d OpAmp<'d, T>, } @@ -80,16 +81,17 @@ impl<'d, T: Instance> OpAmp<'d, T> { /// directly used as an ADC input. The opamp will be disabled when the /// [`OpAmpOutput`] is dropped. pub fn buffer_ext( - &'d mut self, - in_pin: impl Peripheral

+ crate::gpio::sealed::Pin>, - out_pin: impl Peripheral

+ crate::gpio::sealed::Pin> + 'd, + &mut self, + in_pin: impl Peripheral

+ crate::gpio::Pin>, + out_pin: impl Peripheral

+ crate::gpio::Pin>, gain: OpAmpGain, - ) -> OpAmpOutput<'d, T> { + ) -> OpAmpOutput<'_, T> { into_ref!(in_pin); into_ref!(out_pin); in_pin.set_as_analog(); out_pin.set_as_analog(); + // PGA_GAIN value may have different meaning in different MCU serials, use with caution. let (vm_sel, pga_gain) = match gain { OpAmpGain::Mul1 => (0b11, 0b00), OpAmpGain::Mul2 => (0b10, 0b00), @@ -109,6 +111,32 @@ impl<'d, T: Instance> OpAmp<'d, T> { OpAmpOutput { _inner: self } } + /// Configure the OpAmp as a buffer for the DAC it is connected to, + /// outputting to the provided output pin, and enable the opamp. + /// + /// The output pin is held within the returned [`OpAmpOutput`] struct, + /// preventing it being used elsewhere. The `OpAmpOutput` can then be + /// directly used as an ADC input. The opamp will be disabled when the + /// [`OpAmpOutput`] is dropped. + #[cfg(opamp_g4)] + pub fn buffer_dac( + &mut self, + out_pin: impl Peripheral

+ crate::gpio::Pin>, + ) -> OpAmpOutput<'_, T> { + into_ref!(out_pin); + out_pin.set_as_analog(); + + T::regs().csr().modify(|w| { + use crate::pac::opamp::vals::*; + + w.set_vm_sel(VmSel::OUTPUT); + w.set_vp_sel(VpSel::DAC3_CH1); + w.set_opaintoen(Opaintoen::OUTPUTPIN); + w.set_opampen(true); + }); + + OpAmpOutput { _inner: self } + } /// Configure the OpAmp as a buffer for the provided input pin, /// with the output only used internally, and enable the opamp. @@ -120,13 +148,14 @@ impl<'d, T: Instance> OpAmp<'d, T> { /// The opamp output will be disabled when it is dropped. #[cfg(opamp_g4)] pub fn buffer_int( - &'d mut self, - pin: impl Peripheral

+ crate::gpio::sealed::Pin>, + &mut self, + pin: impl Peripheral

+ crate::gpio::Pin>, gain: OpAmpGain, - ) -> OpAmpInternalOutput<'d, T> { + ) -> OpAmpInternalOutput<'_, T> { into_ref!(pin); pin.set_as_analog(); + // PGA_GAIN value may have different meaning in different MCU serials, use with caution. let (vm_sel, pga_gain) = match gain { OpAmpGain::Mul1 => (0b11, 0b00), OpAmpGain::Mul2 => (0b10, 0b00), @@ -156,6 +185,7 @@ impl<'d, T: Instance> Drop for OpAmpOutput<'d, T> { } } +#[cfg(opamp_g4)] impl<'d, T: Instance> Drop for OpAmpInternalOutput<'d, T> { fn drop(&mut self) { T::regs().csr().modify(|w| { @@ -164,37 +194,39 @@ impl<'d, T: Instance> Drop for OpAmpInternalOutput<'d, T> { } } -/// Opamp instance trait. -pub trait Instance: sealed::Instance + 'static {} - -pub(crate) mod sealed { - pub trait Instance { - fn regs() -> crate::pac::opamp::Opamp; - } - - pub trait NonInvertingPin { - fn channel(&self) -> u8; - } - - pub trait InvertingPin { - fn channel(&self) -> u8; - } - - pub trait OutputPin {} +pub(crate) trait SealedInstance { + fn regs() -> crate::pac::opamp::Opamp; } +pub(crate) trait SealedNonInvertingPin { + fn channel(&self) -> u8; +} + +pub(crate) trait SealedInvertingPin { + #[allow(unused)] + fn channel(&self) -> u8; +} + +pub(crate) trait SealedOutputPin {} + +/// Opamp instance trait. +#[allow(private_bounds)] +pub trait Instance: SealedInstance + 'static {} /// Non-inverting pin trait. -pub trait NonInvertingPin: sealed::NonInvertingPin {} +#[allow(private_bounds)] +pub trait NonInvertingPin: SealedNonInvertingPin {} /// Inverting pin trait. -pub trait InvertingPin: sealed::InvertingPin {} +#[allow(private_bounds)] +pub trait InvertingPin: SealedInvertingPin {} /// Output pin trait. -pub trait OutputPin: sealed::OutputPin {} +#[allow(private_bounds)] +pub trait OutputPin: SealedOutputPin {} macro_rules! impl_opamp_external_output { ($inst:ident, $adc:ident, $ch:expr) => { foreach_adc!( ($adc, $common_inst:ident, $adc_clock:ident) => { - impl<'d> crate::adc::sealed::AdcPin + impl<'d> crate::adc::SealedAdcChannel for OpAmpOutput<'d, crate::peripherals::$inst> { fn channel(&self) -> u8 { @@ -202,7 +234,7 @@ macro_rules! impl_opamp_external_output { } } - impl<'d> crate::adc::AdcPin + impl<'d> crate::adc::AdcChannel for OpAmpOutput<'d, crate::peripherals::$inst> { } @@ -240,7 +272,7 @@ macro_rules! impl_opamp_internal_output { ($inst:ident, $adc:ident, $ch:expr) => { foreach_adc!( ($adc, $common_inst:ident, $adc_clock:ident) => { - impl<'d> crate::adc::sealed::AdcPin + impl<'d> crate::adc::SealedAdcChannel for OpAmpInternalOutput<'d, crate::peripherals::$inst> { fn channel(&self) -> u8 { @@ -248,7 +280,7 @@ macro_rules! impl_opamp_internal_output { } } - impl<'d> crate::adc::AdcPin + impl<'d> crate::adc::AdcChannel for OpAmpInternalOutput<'d, crate::peripherals::$inst> { } @@ -289,7 +321,7 @@ foreach_peripheral!( foreach_peripheral! { (opamp, $inst:ident) => { - impl sealed::Instance for crate::peripherals::$inst { + impl SealedInstance for crate::peripherals::$inst { fn regs() -> crate::pac::opamp::Opamp { crate::pac::$inst } @@ -304,7 +336,7 @@ foreach_peripheral! { macro_rules! impl_opamp_vp_pin { ($inst:ident, $pin:ident, $ch:expr) => { impl crate::opamp::NonInvertingPin for crate::peripherals::$pin {} - impl crate::opamp::sealed::NonInvertingPin for crate::peripherals::$pin { + impl crate::opamp::SealedNonInvertingPin for crate::peripherals::$pin { fn channel(&self) -> u8 { $ch } @@ -316,6 +348,6 @@ macro_rules! impl_opamp_vp_pin { macro_rules! impl_opamp_vout_pin { ($inst:ident, $pin:ident) => { impl crate::opamp::OutputPin for crate::peripherals::$pin {} - impl crate::opamp::sealed::OutputPin for crate::peripherals::$pin {} + impl crate::opamp::SealedOutputPin for crate::peripherals::$pin {} }; } diff --git a/embassy-stm32/src/ospi/enums.rs b/embassy-stm32/src/ospi/enums.rs new file mode 100644 index 000000000..4021f7ce3 --- /dev/null +++ b/embassy-stm32/src/ospi/enums.rs @@ -0,0 +1,386 @@ +//! Enums used in Ospi configuration. + +#[allow(dead_code)] +#[derive(Copy, Clone)] +pub(crate) enum OspiMode { + IndirectWrite, + IndirectRead, + AutoPolling, + MemoryMapped, +} + +impl Into for OspiMode { + fn into(self) -> u8 { + match self { + OspiMode::IndirectWrite => 0b00, + OspiMode::IndirectRead => 0b01, + OspiMode::AutoPolling => 0b10, + OspiMode::MemoryMapped => 0b11, + } + } +} + +/// Ospi lane width +#[allow(dead_code)] +#[derive(Copy, Clone)] +pub enum OspiWidth { + /// None + NONE, + /// Single lane + SING, + /// Dual lanes + DUAL, + /// Quad lanes + QUAD, + /// Eight lanes + OCTO, +} + +impl Into for OspiWidth { + fn into(self) -> u8 { + match self { + OspiWidth::NONE => 0b00, + OspiWidth::SING => 0b01, + OspiWidth::DUAL => 0b10, + OspiWidth::QUAD => 0b11, + OspiWidth::OCTO => 0b100, + } + } +} + +/// Flash bank selection +#[allow(dead_code)] +#[derive(Copy, Clone)] +pub enum FlashSelection { + /// Bank 1 + Flash1, + /// Bank 2 + Flash2, +} + +impl Into for FlashSelection { + fn into(self) -> bool { + match self { + FlashSelection::Flash1 => false, + FlashSelection::Flash2 => true, + } + } +} + +/// Wrap Size +#[allow(dead_code)] +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum WrapSize { + None, + _16Bytes, + _32Bytes, + _64Bytes, + _128Bytes, +} + +impl Into for WrapSize { + fn into(self) -> u8 { + match self { + WrapSize::None => 0x00, + WrapSize::_16Bytes => 0x02, + WrapSize::_32Bytes => 0x03, + WrapSize::_64Bytes => 0x04, + WrapSize::_128Bytes => 0x05, + } + } +} + +/// Memory Type +#[allow(missing_docs)] +#[allow(dead_code)] +#[derive(Copy, Clone)] +pub enum MemoryType { + Micron, + Macronix, + Standard, + MacronixRam, + HyperBusMemory, + HyperBusRegister, +} + +impl Into for MemoryType { + fn into(self) -> u8 { + match self { + MemoryType::Micron => 0x00, + MemoryType::Macronix => 0x01, + MemoryType::Standard => 0x02, + MemoryType::MacronixRam => 0x03, + MemoryType::HyperBusMemory => 0x04, + MemoryType::HyperBusRegister => 0x04, + } + } +} + +/// Ospi memory size. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum MemorySize { + _1KiB, + _2KiB, + _4KiB, + _8KiB, + _16KiB, + _32KiB, + _64KiB, + _128KiB, + _256KiB, + _512KiB, + _1MiB, + _2MiB, + _4MiB, + _8MiB, + _16MiB, + _32MiB, + _64MiB, + _128MiB, + _256MiB, + _512MiB, + _1GiB, + _2GiB, + _4GiB, + Other(u8), +} + +impl Into for MemorySize { + fn into(self) -> u8 { + match self { + MemorySize::_1KiB => 9, + MemorySize::_2KiB => 10, + MemorySize::_4KiB => 11, + MemorySize::_8KiB => 12, + MemorySize::_16KiB => 13, + MemorySize::_32KiB => 14, + MemorySize::_64KiB => 15, + MemorySize::_128KiB => 16, + MemorySize::_256KiB => 17, + MemorySize::_512KiB => 18, + MemorySize::_1MiB => 19, + MemorySize::_2MiB => 20, + MemorySize::_4MiB => 21, + MemorySize::_8MiB => 22, + MemorySize::_16MiB => 23, + MemorySize::_32MiB => 24, + MemorySize::_64MiB => 25, + MemorySize::_128MiB => 26, + MemorySize::_256MiB => 27, + MemorySize::_512MiB => 28, + MemorySize::_1GiB => 29, + MemorySize::_2GiB => 30, + MemorySize::_4GiB => 31, + MemorySize::Other(val) => val, + } + } +} + +/// Ospi Address size +#[derive(Copy, Clone)] +pub enum AddressSize { + /// 8-bit address + _8Bit, + /// 16-bit address + _16Bit, + /// 24-bit address + _24bit, + /// 32-bit address + _32bit, +} + +impl Into for AddressSize { + fn into(self) -> u8 { + match self { + AddressSize::_8Bit => 0b00, + AddressSize::_16Bit => 0b01, + AddressSize::_24bit => 0b10, + AddressSize::_32bit => 0b11, + } + } +} + +/// Time the Chip Select line stays high. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum ChipSelectHighTime { + _1Cycle, + _2Cycle, + _3Cycle, + _4Cycle, + _5Cycle, + _6Cycle, + _7Cycle, + _8Cycle, +} + +impl Into for ChipSelectHighTime { + fn into(self) -> u8 { + match self { + ChipSelectHighTime::_1Cycle => 0, + ChipSelectHighTime::_2Cycle => 1, + ChipSelectHighTime::_3Cycle => 2, + ChipSelectHighTime::_4Cycle => 3, + ChipSelectHighTime::_5Cycle => 4, + ChipSelectHighTime::_6Cycle => 5, + ChipSelectHighTime::_7Cycle => 6, + ChipSelectHighTime::_8Cycle => 7, + } + } +} + +/// FIFO threshold. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum FIFOThresholdLevel { + _1Bytes, + _2Bytes, + _3Bytes, + _4Bytes, + _5Bytes, + _6Bytes, + _7Bytes, + _8Bytes, + _9Bytes, + _10Bytes, + _11Bytes, + _12Bytes, + _13Bytes, + _14Bytes, + _15Bytes, + _16Bytes, + _17Bytes, + _18Bytes, + _19Bytes, + _20Bytes, + _21Bytes, + _22Bytes, + _23Bytes, + _24Bytes, + _25Bytes, + _26Bytes, + _27Bytes, + _28Bytes, + _29Bytes, + _30Bytes, + _31Bytes, + _32Bytes, +} + +impl Into for FIFOThresholdLevel { + fn into(self) -> u8 { + match self { + FIFOThresholdLevel::_1Bytes => 0, + FIFOThresholdLevel::_2Bytes => 1, + FIFOThresholdLevel::_3Bytes => 2, + FIFOThresholdLevel::_4Bytes => 3, + FIFOThresholdLevel::_5Bytes => 4, + FIFOThresholdLevel::_6Bytes => 5, + FIFOThresholdLevel::_7Bytes => 6, + FIFOThresholdLevel::_8Bytes => 7, + FIFOThresholdLevel::_9Bytes => 8, + FIFOThresholdLevel::_10Bytes => 9, + FIFOThresholdLevel::_11Bytes => 10, + FIFOThresholdLevel::_12Bytes => 11, + FIFOThresholdLevel::_13Bytes => 12, + FIFOThresholdLevel::_14Bytes => 13, + FIFOThresholdLevel::_15Bytes => 14, + FIFOThresholdLevel::_16Bytes => 15, + FIFOThresholdLevel::_17Bytes => 16, + FIFOThresholdLevel::_18Bytes => 17, + FIFOThresholdLevel::_19Bytes => 18, + FIFOThresholdLevel::_20Bytes => 19, + FIFOThresholdLevel::_21Bytes => 20, + FIFOThresholdLevel::_22Bytes => 21, + FIFOThresholdLevel::_23Bytes => 22, + FIFOThresholdLevel::_24Bytes => 23, + FIFOThresholdLevel::_25Bytes => 24, + FIFOThresholdLevel::_26Bytes => 25, + FIFOThresholdLevel::_27Bytes => 26, + FIFOThresholdLevel::_28Bytes => 27, + FIFOThresholdLevel::_29Bytes => 28, + FIFOThresholdLevel::_30Bytes => 29, + FIFOThresholdLevel::_31Bytes => 30, + FIFOThresholdLevel::_32Bytes => 31, + } + } +} + +/// Dummy cycle count +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum DummyCycles { + _0, + _1, + _2, + _3, + _4, + _5, + _6, + _7, + _8, + _9, + _10, + _11, + _12, + _13, + _14, + _15, + _16, + _17, + _18, + _19, + _20, + _21, + _22, + _23, + _24, + _25, + _26, + _27, + _28, + _29, + _30, + _31, +} + +impl Into for DummyCycles { + fn into(self) -> u8 { + match self { + DummyCycles::_0 => 0, + DummyCycles::_1 => 1, + DummyCycles::_2 => 2, + DummyCycles::_3 => 3, + DummyCycles::_4 => 4, + DummyCycles::_5 => 5, + DummyCycles::_6 => 6, + DummyCycles::_7 => 7, + DummyCycles::_8 => 8, + DummyCycles::_9 => 9, + DummyCycles::_10 => 10, + DummyCycles::_11 => 11, + DummyCycles::_12 => 12, + DummyCycles::_13 => 13, + DummyCycles::_14 => 14, + DummyCycles::_15 => 15, + DummyCycles::_16 => 16, + DummyCycles::_17 => 17, + DummyCycles::_18 => 18, + DummyCycles::_19 => 19, + DummyCycles::_20 => 20, + DummyCycles::_21 => 21, + DummyCycles::_22 => 22, + DummyCycles::_23 => 23, + DummyCycles::_24 => 24, + DummyCycles::_25 => 25, + DummyCycles::_26 => 26, + DummyCycles::_27 => 27, + DummyCycles::_28 => 28, + DummyCycles::_29 => 29, + DummyCycles::_30 => 30, + DummyCycles::_31 => 31, + } + } +} diff --git a/embassy-stm32/src/ospi/mod.rs b/embassy-stm32/src/ospi/mod.rs new file mode 100644 index 000000000..f8ef66216 --- /dev/null +++ b/embassy-stm32/src/ospi/mod.rs @@ -0,0 +1,1302 @@ +//! OCTOSPI Serial Peripheral Interface +//! + +#![macro_use] + +pub mod enums; + +use core::marker::PhantomData; + +use embassy_embedded_hal::{GetConfig, SetConfig}; +use embassy_hal_internal::{into_ref, PeripheralRef}; +pub use enums::*; +use stm32_metapac::octospi::vals::{PhaseMode, SizeInBits}; + +use crate::dma::{word, ChannelAndRequest}; +use crate::gpio::{AfType, AnyPin, OutputType, Pull, SealedPin as _, Speed}; +use crate::mode::{Async, Blocking, Mode as PeriMode}; +use crate::pac::octospi::{vals, Octospi as Regs}; +#[cfg(octospim_v1)] +use crate::pac::octospim::Octospim; +use crate::rcc::{self, RccPeripheral}; +use crate::{peripherals, Peripheral}; + +/// OPSI driver config. +#[derive(Clone, Copy)] +pub struct Config { + /// Fifo threshold used by the peripheral to generate the interrupt indicating data + /// or space is available in the FIFO + pub fifo_threshold: FIFOThresholdLevel, + /// Indicates the type of external device connected + pub memory_type: MemoryType, // Need to add an additional enum to provide this public interface + /// Defines the size of the external device connected to the OSPI corresponding + /// to the number of address bits required to access the device + pub device_size: MemorySize, + /// Sets the minimum number of clock cycles that the chip select signal must be held high + /// between commands + pub chip_select_high_time: ChipSelectHighTime, + /// Enables the free running clock + pub free_running_clock: bool, + /// Sets the clock level when the device is not selected + pub clock_mode: bool, + /// Indicates the wrap size corresponding to the external device configuration + pub wrap_size: WrapSize, + /// Specified the prescaler factor used for generating the external clock based + /// on the AHB clock + pub clock_prescaler: u8, + /// Allows the delay of 1/2 cycle the data sampling to account for external + /// signal delays + pub sample_shifting: bool, + /// Allows hold to 1/4 cycle the data + pub delay_hold_quarter_cycle: bool, + /// Enables the transaction boundary feature and defines the boundary to release + /// the chip select + pub chip_select_boundary: u8, + /// Enbales the delay block bypass so the sampling is not affected by the delay block + pub delay_block_bypass: bool, + /// Enables communication regulation feature. Chip select is released when the other + /// OctoSpi requests access to the bus + pub max_transfer: u8, + /// Enables the refresh feature, chip select is released every refresh + 1 clock cycles + pub refresh: u32, +} + +impl Default for Config { + fn default() -> Self { + Self { + fifo_threshold: FIFOThresholdLevel::_16Bytes, // 32 bytes FIFO, half capacity + memory_type: MemoryType::Micron, + device_size: MemorySize::Other(0), + chip_select_high_time: ChipSelectHighTime::_5Cycle, + free_running_clock: false, + clock_mode: false, + wrap_size: WrapSize::None, + clock_prescaler: 0, + sample_shifting: false, + delay_hold_quarter_cycle: false, + chip_select_boundary: 0, // Acceptable range 0 to 31 + delay_block_bypass: true, + max_transfer: 0, + refresh: 0, + } + } +} + +/// OSPI transfer configuration. +pub struct TransferConfig { + /// Instruction width (IMODE) + pub iwidth: OspiWidth, + /// Instruction Id + pub instruction: Option, + /// Number of Instruction Bytes + pub isize: AddressSize, + /// Instruction Double Transfer rate enable + pub idtr: bool, + + /// Address width (ADMODE) + pub adwidth: OspiWidth, + /// Device memory address + pub address: Option, + /// Number of Address Bytes + pub adsize: AddressSize, + /// Address Double Transfer rate enable + pub addtr: bool, + + /// Alternate bytes width (ABMODE) + pub abwidth: OspiWidth, + /// Alternate Bytes + pub alternate_bytes: Option, + /// Number of Alternate Bytes + pub absize: AddressSize, + /// Alternate Bytes Double Transfer rate enable + pub abdtr: bool, + + /// Data width (DMODE) + pub dwidth: OspiWidth, + /// Data buffer + pub ddtr: bool, + + /// Number of dummy cycles (DCYC) + pub dummy: DummyCycles, +} + +impl Default for TransferConfig { + fn default() -> Self { + Self { + iwidth: OspiWidth::NONE, + instruction: None, + isize: AddressSize::_8Bit, + idtr: false, + + adwidth: OspiWidth::NONE, + address: None, + adsize: AddressSize::_8Bit, + addtr: false, + + abwidth: OspiWidth::NONE, + alternate_bytes: None, + absize: AddressSize::_8Bit, + abdtr: false, + + dwidth: OspiWidth::NONE, + ddtr: false, + + dummy: DummyCycles::_0, + } + } +} + +/// Error used for Octospi implementation +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum OspiError { + /// Peripheral configuration is invalid + InvalidConfiguration, + /// Operation configuration is invalid + InvalidCommand, + /// Size zero buffer passed to instruction + EmptyBuffer, +} + +/// OSPI driver. +pub struct Ospi<'d, T: Instance, M: PeriMode> { + _peri: PeripheralRef<'d, T>, + sck: Option>, + d0: Option>, + d1: Option>, + d2: Option>, + d3: Option>, + d4: Option>, + d5: Option>, + d6: Option>, + d7: Option>, + nss: Option>, + dqs: Option>, + dma: Option>, + _phantom: PhantomData, + config: Config, + width: OspiWidth, +} + +impl<'d, T: Instance, M: PeriMode> Ospi<'d, T, M> { + /// Enter memory mode. + /// The Input `read_config` is used to configure the read operation in memory mode + pub fn enable_memory_mapped_mode( + &mut self, + read_config: TransferConfig, + write_config: TransferConfig, + ) -> Result<(), OspiError> { + // Use configure command to set read config + self.configure_command(&read_config, None)?; + + let reg = T::REGS; + while reg.sr().read().busy() {} + + reg.ccr().modify(|r| { + r.set_dqse(false); + r.set_sioo(true); + }); + + // Set wrting configurations, there are separate registers for write configurations in memory mapped mode + reg.wccr().modify(|w| { + w.set_imode(PhaseMode::from_bits(write_config.iwidth.into())); + w.set_idtr(write_config.idtr); + w.set_isize(SizeInBits::from_bits(write_config.isize.into())); + + w.set_admode(PhaseMode::from_bits(write_config.adwidth.into())); + w.set_addtr(write_config.idtr); + w.set_adsize(SizeInBits::from_bits(write_config.adsize.into())); + + w.set_dmode(PhaseMode::from_bits(write_config.dwidth.into())); + w.set_ddtr(write_config.ddtr); + + w.set_abmode(PhaseMode::from_bits(write_config.abwidth.into())); + w.set_dqse(true); + }); + + reg.wtcr().modify(|w| w.set_dcyc(write_config.dummy.into())); + + // Enable memory mapped mode + reg.cr().modify(|r| { + r.set_fmode(crate::ospi::vals::FunctionalMode::MEMORYMAPPED); + r.set_tcen(false); + }); + Ok(()) + } + + /// Quit from memory mapped mode + pub fn disable_memory_mapped_mode(&mut self) { + let reg = T::REGS; + + reg.cr().modify(|r| { + r.set_fmode(crate::ospi::vals::FunctionalMode::INDIRECTWRITE); + r.set_abort(true); + r.set_dmaen(false); + r.set_en(false); + }); + + // Clear transfer complete flag + reg.fcr().write(|w| w.set_ctcf(true)); + + // Re-enable ospi + reg.cr().modify(|r| { + r.set_en(true); + }); + } + + fn new_inner( + peri: impl Peripheral

+ 'd, + d0: Option>, + d1: Option>, + d2: Option>, + d3: Option>, + d4: Option>, + d5: Option>, + d6: Option>, + d7: Option>, + sck: Option>, + nss: Option>, + dqs: Option>, + dma: Option>, + config: Config, + width: OspiWidth, + dual_quad: bool, + ) -> Self { + into_ref!(peri); + + #[cfg(octospim_v1)] + { + // RCC for octospim should be enabled before writing register + #[cfg(stm32l4)] + crate::pac::RCC.ahb2smenr().modify(|w| w.set_octospimsmen(true)); + #[cfg(stm32u5)] + crate::pac::RCC.ahb2enr1().modify(|w| w.set_octospimen(true)); + #[cfg(not(any(stm32l4, stm32u5)))] + crate::pac::RCC.ahb3enr().modify(|w| w.set_iomngren(true)); + + // Disable OctoSPI peripheral first + T::REGS.cr().modify(|w| { + w.set_en(false); + }); + + // OctoSPI IO Manager has been enabled before + T::OCTOSPIM_REGS.cr().modify(|w| { + w.set_muxen(false); + w.set_req2ack_time(0xff); + }); + + // Clear config + T::OCTOSPIM_REGS.p1cr().modify(|w| { + w.set_clksrc(false); + w.set_dqssrc(false); + w.set_ncssrc(false); + w.set_clken(false); + w.set_dqsen(false); + w.set_ncsen(false); + w.set_iolsrc(0); + w.set_iohsrc(0); + }); + + T::OCTOSPIM_REGS.p1cr().modify(|w| { + let octospi_src = if T::OCTOSPI_IDX == 1 { false } else { true }; + w.set_ncsen(true); + w.set_ncssrc(octospi_src); + w.set_clken(true); + w.set_clksrc(octospi_src); + if dqs.is_some() { + w.set_dqsen(true); + w.set_dqssrc(octospi_src); + } + + // Set OCTOSPIM IOL and IOH according to the index of OCTOSPI instance + if T::OCTOSPI_IDX == 1 { + w.set_iolen(true); + w.set_iolsrc(0); + // Enable IOH in octo and dual quad mode + if let OspiWidth::OCTO = width { + w.set_iohen(true); + w.set_iohsrc(0b01); + } else if dual_quad { + w.set_iohen(true); + w.set_iohsrc(0b00); + } else { + w.set_iohen(false); + w.set_iohsrc(0b00); + } + } else { + w.set_iolen(true); + w.set_iolsrc(0b10); + // Enable IOH in octo and dual quad mode + if let OspiWidth::OCTO = width { + w.set_iohen(true); + w.set_iohsrc(0b11); + } else if dual_quad { + w.set_iohen(true); + w.set_iohsrc(0b10); + } else { + w.set_iohen(false); + w.set_iohsrc(0b00); + } + } + }); + } + + // System configuration + rcc::enable_and_reset::(); + while T::REGS.sr().read().busy() {} + + // Device configuration + T::REGS.dcr1().modify(|w| { + w.set_devsize(config.device_size.into()); + w.set_mtyp(vals::MemType::from_bits(config.memory_type.into())); + w.set_csht(config.chip_select_high_time.into()); + w.set_dlybyp(config.delay_block_bypass); + w.set_frck(false); + w.set_ckmode(config.clock_mode); + }); + + T::REGS.dcr2().modify(|w| { + w.set_wrapsize(config.wrap_size.into()); + }); + + T::REGS.dcr3().modify(|w| { + w.set_csbound(config.chip_select_boundary); + #[cfg(octospi_v1)] + { + w.set_maxtran(config.max_transfer); + } + }); + + T::REGS.dcr4().modify(|w| { + w.set_refresh(config.refresh); + }); + + T::REGS.cr().modify(|w| { + w.set_fthres(vals::Threshold(config.fifo_threshold.into())); + }); + + // Wait for busy flag to clear + while T::REGS.sr().read().busy() {} + + T::REGS.dcr2().modify(|w| { + w.set_prescaler(config.clock_prescaler); + }); + + T::REGS.cr().modify(|w| { + w.set_dmm(dual_quad); + }); + + T::REGS.tcr().modify(|w| { + w.set_sshift(match config.sample_shifting { + true => vals::SampleShift::HALFCYCLE, + false => vals::SampleShift::NONE, + }); + w.set_dhqc(config.delay_hold_quarter_cycle); + }); + + // Enable peripheral + T::REGS.cr().modify(|w| { + w.set_en(true); + }); + + // Free running clock needs to be set after peripheral enable + if config.free_running_clock { + T::REGS.dcr1().modify(|w| { + w.set_frck(config.free_running_clock); + }); + } + + Self { + _peri: peri, + sck, + d0, + d1, + d2, + d3, + d4, + d5, + d6, + d7, + nss, + dqs, + dma, + _phantom: PhantomData, + config, + width, + } + } + + // Function to configure the peripheral for the requested command + fn configure_command(&mut self, command: &TransferConfig, data_len: Option) -> Result<(), OspiError> { + // Check that transaction doesn't use more than hardware initialized pins + if >::into(command.iwidth) > >::into(self.width) + || >::into(command.adwidth) > >::into(self.width) + || >::into(command.abwidth) > >::into(self.width) + || >::into(command.dwidth) > >::into(self.width) + { + return Err(OspiError::InvalidCommand); + } + + T::REGS.cr().modify(|w| { + w.set_fmode(0.into()); + }); + + // Configure alternate bytes + if let Some(ab) = command.alternate_bytes { + T::REGS.abr().write(|v| v.set_alternate(ab)); + T::REGS.ccr().modify(|w| { + w.set_abmode(PhaseMode::from_bits(command.abwidth.into())); + w.set_abdtr(command.abdtr); + w.set_absize(SizeInBits::from_bits(command.absize.into())); + }) + } + + // Configure dummy cycles + T::REGS.tcr().modify(|w| { + w.set_dcyc(command.dummy.into()); + }); + + // Configure data + if let Some(data_length) = data_len { + T::REGS.dlr().write(|v| { + v.set_dl((data_length - 1) as u32); + }) + } else { + T::REGS.dlr().write(|v| { + v.set_dl((0) as u32); + }) + } + + // Configure instruction/address/data modes + T::REGS.ccr().modify(|w| { + w.set_imode(PhaseMode::from_bits(command.iwidth.into())); + w.set_idtr(command.idtr); + w.set_isize(SizeInBits::from_bits(command.isize.into())); + + w.set_admode(PhaseMode::from_bits(command.adwidth.into())); + w.set_addtr(command.idtr); + w.set_adsize(SizeInBits::from_bits(command.adsize.into())); + + w.set_dmode(PhaseMode::from_bits(command.dwidth.into())); + w.set_ddtr(command.ddtr); + }); + + // Set informationrequired to initiate transaction + if let Some(instruction) = command.instruction { + if let Some(address) = command.address { + T::REGS.ir().write(|v| { + v.set_instruction(instruction); + }); + + T::REGS.ar().write(|v| { + v.set_address(address); + }); + } else { + // Double check requirements for delay hold and sample shifting + // if let None = command.data_len { + // if self.config.delay_hold_quarter_cycle && command.idtr { + // T::REGS.ccr().modify(|w| { + // w.set_ddtr(true); + // }); + // } + // } + + T::REGS.ir().write(|v| { + v.set_instruction(instruction); + }); + } + } else { + if let Some(address) = command.address { + T::REGS.ar().write(|v| { + v.set_address(address); + }); + } else { + // The only single phase transaction supported is instruction only + return Err(OspiError::InvalidCommand); + } + } + + Ok(()) + } + + /// Function used to control or configure the target device without data transfer + pub async fn command(&mut self, command: &TransferConfig) -> Result<(), OspiError> { + // Wait for peripheral to be free + while T::REGS.sr().read().busy() {} + + // Need additional validation that command configuration doesn't have data set + self.configure_command(command, None)?; + + // Transaction initiated by setting final configuration, i.e the instruction register + while !T::REGS.sr().read().tcf() {} + T::REGS.fcr().write(|w| { + w.set_ctcf(true); + }); + + Ok(()) + } + + /// Blocking read with byte by byte data transfer + pub fn blocking_read(&mut self, buf: &mut [W], transaction: TransferConfig) -> Result<(), OspiError> { + if buf.is_empty() { + return Err(OspiError::EmptyBuffer); + } + + // Wait for peripheral to be free + while T::REGS.sr().read().busy() {} + + // Ensure DMA is not enabled for this transaction + T::REGS.cr().modify(|w| { + w.set_dmaen(false); + }); + + self.configure_command(&transaction, Some(buf.len()))?; + + let current_address = T::REGS.ar().read().address(); + let current_instruction = T::REGS.ir().read().instruction(); + + // For a indirect read transaction, the transaction begins when the instruction/address is set + T::REGS.cr().modify(|v| v.set_fmode(vals::FunctionalMode::INDIRECTREAD)); + if T::REGS.ccr().read().admode() == vals::PhaseMode::NONE { + T::REGS.ir().write(|v| v.set_instruction(current_instruction)); + } else { + T::REGS.ar().write(|v| v.set_address(current_address)); + } + + for idx in 0..buf.len() { + while !T::REGS.sr().read().tcf() && !T::REGS.sr().read().ftf() {} + buf[idx] = unsafe { (T::REGS.dr().as_ptr() as *mut W).read_volatile() }; + } + + while !T::REGS.sr().read().tcf() {} + T::REGS.fcr().write(|v| v.set_ctcf(true)); + + Ok(()) + } + + /// Blocking write with byte by byte data transfer + pub fn blocking_write(&mut self, buf: &[W], transaction: TransferConfig) -> Result<(), OspiError> { + if buf.is_empty() { + return Err(OspiError::EmptyBuffer); + } + + // Wait for peripheral to be free + while T::REGS.sr().read().busy() {} + + T::REGS.cr().modify(|w| { + w.set_dmaen(false); + }); + + self.configure_command(&transaction, Some(buf.len()))?; + + T::REGS + .cr() + .modify(|v| v.set_fmode(vals::FunctionalMode::INDIRECTWRITE)); + + for idx in 0..buf.len() { + while !T::REGS.sr().read().ftf() {} + unsafe { (T::REGS.dr().as_ptr() as *mut W).write_volatile(buf[idx]) }; + } + + while !T::REGS.sr().read().tcf() {} + T::REGS.fcr().write(|v| v.set_ctcf(true)); + + Ok(()) + } + + /// Set new bus configuration + pub fn set_config(&mut self, config: &Config) { + // Wait for busy flag to clear + while T::REGS.sr().read().busy() {} + + // Disable DMA channel while configuring the peripheral + T::REGS.cr().modify(|w| { + w.set_dmaen(false); + }); + + // Device configuration + T::REGS.dcr1().modify(|w| { + w.set_devsize(config.device_size.into()); + w.set_mtyp(vals::MemType::from_bits(config.memory_type.into())); + w.set_csht(config.chip_select_high_time.into()); + w.set_dlybyp(config.delay_block_bypass); + w.set_frck(false); + w.set_ckmode(config.clock_mode); + }); + + T::REGS.dcr2().modify(|w| { + w.set_wrapsize(config.wrap_size.into()); + }); + + T::REGS.dcr3().modify(|w| { + w.set_csbound(config.chip_select_boundary); + #[cfg(octospi_v1)] + { + w.set_maxtran(config.max_transfer); + } + }); + + T::REGS.dcr4().modify(|w| { + w.set_refresh(config.refresh); + }); + + T::REGS.cr().modify(|w| { + w.set_fthres(vals::Threshold(config.fifo_threshold.into())); + }); + + // Wait for busy flag to clear + while T::REGS.sr().read().busy() {} + + T::REGS.dcr2().modify(|w| { + w.set_prescaler(config.clock_prescaler); + }); + + T::REGS.tcr().modify(|w| { + w.set_sshift(match config.sample_shifting { + true => vals::SampleShift::HALFCYCLE, + false => vals::SampleShift::NONE, + }); + w.set_dhqc(config.delay_hold_quarter_cycle); + }); + + // Enable peripheral + T::REGS.cr().modify(|w| { + w.set_en(true); + }); + + // Free running clock needs to be set after peripheral enable + if config.free_running_clock { + T::REGS.dcr1().modify(|w| { + w.set_frck(config.free_running_clock); + }); + } + + self.config = *config; + } + + /// Get current configuration + pub fn get_config(&self) -> Config { + self.config + } +} + +impl<'d, T: Instance> Ospi<'d, T, Blocking> { + /// Create new blocking OSPI driver for a single spi external chip + pub fn new_blocking_singlespi( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + d0: impl Peripheral

> + 'd, + d1: impl Peripheral

> + 'd, + nss: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(d0, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d1, AfType::input(Pull::None)), + None, + None, + None, + None, + None, + None, + new_pin!(sck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!( + nss, + AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up) + ), + None, + None, + config, + OspiWidth::SING, + false, + ) + } + + /// Create new blocking OSPI driver for a dualspi external chip + pub fn new_blocking_dualspi( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + d0: impl Peripheral

> + 'd, + d1: impl Peripheral

> + 'd, + nss: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(d0, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d1, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + None, + None, + None, + None, + None, + None, + new_pin!(sck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!( + nss, + AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up) + ), + None, + None, + config, + OspiWidth::DUAL, + false, + ) + } + + /// Create new blocking OSPI driver for a quadspi external chip + pub fn new_blocking_quadspi( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + d0: impl Peripheral

> + 'd, + d1: impl Peripheral

> + 'd, + d2: impl Peripheral

> + 'd, + d3: impl Peripheral

> + 'd, + nss: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(d0, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d1, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d2, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d3, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + None, + None, + None, + None, + new_pin!(sck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!( + nss, + AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up) + ), + None, + None, + config, + OspiWidth::QUAD, + false, + ) + } + + /// Create new blocking OSPI driver for two quadspi external chips + pub fn new_blocking_dualquadspi( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + d0: impl Peripheral

> + 'd, + d1: impl Peripheral

> + 'd, + d2: impl Peripheral

> + 'd, + d3: impl Peripheral

> + 'd, + d4: impl Peripheral

> + 'd, + d5: impl Peripheral

> + 'd, + d6: impl Peripheral

> + 'd, + d7: impl Peripheral

> + 'd, + nss: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(d0, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d1, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d2, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d3, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d4, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d5, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d6, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d7, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(sck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!( + nss, + AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up) + ), + None, + None, + config, + OspiWidth::QUAD, + true, + ) + } + + /// Create new blocking OSPI driver for octospi external chips + pub fn new_blocking_octospi( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + d0: impl Peripheral

> + 'd, + d1: impl Peripheral

> + 'd, + d2: impl Peripheral

> + 'd, + d3: impl Peripheral

> + 'd, + d4: impl Peripheral

> + 'd, + d5: impl Peripheral

> + 'd, + d6: impl Peripheral

> + 'd, + d7: impl Peripheral

> + 'd, + nss: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(d0, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d1, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d2, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d3, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d4, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d5, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d6, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d7, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(sck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!( + nss, + AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up) + ), + None, + None, + config, + OspiWidth::OCTO, + false, + ) + } +} + +impl<'d, T: Instance> Ospi<'d, T, Async> { + /// Create new blocking OSPI driver for a single spi external chip + pub fn new_singlespi( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + d0: impl Peripheral

> + 'd, + d1: impl Peripheral

> + 'd, + nss: impl Peripheral

> + 'd, + dma: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(d0, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d1, AfType::input(Pull::None)), + None, + None, + None, + None, + None, + None, + new_pin!(sck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!( + nss, + AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up) + ), + None, + new_dma!(dma), + config, + OspiWidth::SING, + false, + ) + } + + /// Create new blocking OSPI driver for a dualspi external chip + pub fn new_dualspi( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + d0: impl Peripheral

> + 'd, + d1: impl Peripheral

> + 'd, + nss: impl Peripheral

> + 'd, + dma: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(d0, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d1, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + None, + None, + None, + None, + None, + None, + new_pin!(sck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!( + nss, + AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up) + ), + None, + new_dma!(dma), + config, + OspiWidth::DUAL, + false, + ) + } + + /// Create new blocking OSPI driver for a quadspi external chip + pub fn new_quadspi( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + d0: impl Peripheral

> + 'd, + d1: impl Peripheral

> + 'd, + d2: impl Peripheral

> + 'd, + d3: impl Peripheral

> + 'd, + nss: impl Peripheral

> + 'd, + dma: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(d0, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d1, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d2, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d3, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + None, + None, + None, + None, + new_pin!(sck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!( + nss, + AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up) + ), + None, + new_dma!(dma), + config, + OspiWidth::QUAD, + false, + ) + } + + /// Create new blocking OSPI driver for two quadspi external chips + pub fn new_dualquadspi( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + d0: impl Peripheral

> + 'd, + d1: impl Peripheral

> + 'd, + d2: impl Peripheral

> + 'd, + d3: impl Peripheral

> + 'd, + d4: impl Peripheral

> + 'd, + d5: impl Peripheral

> + 'd, + d6: impl Peripheral

> + 'd, + d7: impl Peripheral

> + 'd, + nss: impl Peripheral

> + 'd, + dma: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(d0, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d1, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d2, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d3, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d4, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d5, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d6, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d7, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(sck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!( + nss, + AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up) + ), + None, + new_dma!(dma), + config, + OspiWidth::QUAD, + true, + ) + } + + /// Create new blocking OSPI driver for octospi external chips + pub fn new_octospi( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + d0: impl Peripheral

> + 'd, + d1: impl Peripheral

> + 'd, + d2: impl Peripheral

> + 'd, + d3: impl Peripheral

> + 'd, + d4: impl Peripheral

> + 'd, + d5: impl Peripheral

> + 'd, + d6: impl Peripheral

> + 'd, + d7: impl Peripheral

> + 'd, + nss: impl Peripheral

> + 'd, + dma: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(d0, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d1, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d2, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d3, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d4, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d5, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d6, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d7, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(sck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!( + nss, + AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up) + ), + None, + new_dma!(dma), + config, + OspiWidth::OCTO, + false, + ) + } + + /// Blocking read with DMA transfer + pub fn blocking_read_dma(&mut self, buf: &mut [W], transaction: TransferConfig) -> Result<(), OspiError> { + if buf.is_empty() { + return Err(OspiError::EmptyBuffer); + } + + // Wait for peripheral to be free + while T::REGS.sr().read().busy() {} + + self.configure_command(&transaction, Some(buf.len()))?; + + let current_address = T::REGS.ar().read().address(); + let current_instruction = T::REGS.ir().read().instruction(); + + // For a indirect read transaction, the transaction begins when the instruction/address is set + T::REGS.cr().modify(|v| v.set_fmode(vals::FunctionalMode::INDIRECTREAD)); + if T::REGS.ccr().read().admode() == vals::PhaseMode::NONE { + T::REGS.ir().write(|v| v.set_instruction(current_instruction)); + } else { + T::REGS.ar().write(|v| v.set_address(current_address)); + } + + let transfer = unsafe { + self.dma + .as_mut() + .unwrap() + .read(T::REGS.dr().as_ptr() as *mut W, buf, Default::default()) + }; + + T::REGS.cr().modify(|w| w.set_dmaen(true)); + + transfer.blocking_wait(); + + finish_dma(T::REGS); + + Ok(()) + } + + /// Blocking write with DMA transfer + pub fn blocking_write_dma(&mut self, buf: &[W], transaction: TransferConfig) -> Result<(), OspiError> { + if buf.is_empty() { + return Err(OspiError::EmptyBuffer); + } + + // Wait for peripheral to be free + while T::REGS.sr().read().busy() {} + + self.configure_command(&transaction, Some(buf.len()))?; + T::REGS + .cr() + .modify(|v| v.set_fmode(vals::FunctionalMode::INDIRECTWRITE)); + + let transfer = unsafe { + self.dma + .as_mut() + .unwrap() + .write(buf, T::REGS.dr().as_ptr() as *mut W, Default::default()) + }; + + T::REGS.cr().modify(|w| w.set_dmaen(true)); + + transfer.blocking_wait(); + + finish_dma(T::REGS); + + Ok(()) + } + + /// Asynchronous read from external device + pub async fn read(&mut self, buf: &mut [W], transaction: TransferConfig) -> Result<(), OspiError> { + if buf.is_empty() { + return Err(OspiError::EmptyBuffer); + } + + // Wait for peripheral to be free + while T::REGS.sr().read().busy() {} + + self.configure_command(&transaction, Some(buf.len()))?; + + let current_address = T::REGS.ar().read().address(); + let current_instruction = T::REGS.ir().read().instruction(); + + // For a indirect read transaction, the transaction begins when the instruction/address is set + T::REGS.cr().modify(|v| v.set_fmode(vals::FunctionalMode::INDIRECTREAD)); + if T::REGS.ccr().read().admode() == vals::PhaseMode::NONE { + T::REGS.ir().write(|v| v.set_instruction(current_instruction)); + } else { + T::REGS.ar().write(|v| v.set_address(current_address)); + } + + let transfer = unsafe { + self.dma + .as_mut() + .unwrap() + .read(T::REGS.dr().as_ptr() as *mut W, buf, Default::default()) + }; + + T::REGS.cr().modify(|w| w.set_dmaen(true)); + + transfer.await; + + finish_dma(T::REGS); + + Ok(()) + } + + /// Asynchronous write to external device + pub async fn write(&mut self, buf: &[W], transaction: TransferConfig) -> Result<(), OspiError> { + if buf.is_empty() { + return Err(OspiError::EmptyBuffer); + } + + // Wait for peripheral to be free + while T::REGS.sr().read().busy() {} + + self.configure_command(&transaction, Some(buf.len()))?; + T::REGS + .cr() + .modify(|v| v.set_fmode(vals::FunctionalMode::INDIRECTWRITE)); + + let transfer = unsafe { + self.dma + .as_mut() + .unwrap() + .write(buf, T::REGS.dr().as_ptr() as *mut W, Default::default()) + }; + + T::REGS.cr().modify(|w| w.set_dmaen(true)); + + transfer.await; + + finish_dma(T::REGS); + + Ok(()) + } +} + +impl<'d, T: Instance, M: PeriMode> Drop for Ospi<'d, T, M> { + fn drop(&mut self) { + self.sck.as_ref().map(|x| x.set_as_disconnected()); + self.d0.as_ref().map(|x| x.set_as_disconnected()); + self.d1.as_ref().map(|x| x.set_as_disconnected()); + self.d2.as_ref().map(|x| x.set_as_disconnected()); + self.d3.as_ref().map(|x| x.set_as_disconnected()); + self.d4.as_ref().map(|x| x.set_as_disconnected()); + self.d5.as_ref().map(|x| x.set_as_disconnected()); + self.d6.as_ref().map(|x| x.set_as_disconnected()); + self.d7.as_ref().map(|x| x.set_as_disconnected()); + self.nss.as_ref().map(|x| x.set_as_disconnected()); + self.dqs.as_ref().map(|x| x.set_as_disconnected()); + + rcc::disable::(); + } +} + +fn finish_dma(regs: Regs) { + while !regs.sr().read().tcf() {} + regs.fcr().write(|v| v.set_ctcf(true)); + + regs.cr().modify(|w| { + w.set_dmaen(false); + }); +} + +#[cfg(octospim_v1)] +/// OctoSPI I/O manager instance trait. +pub(crate) trait SealedOctospimInstance { + const OCTOSPIM_REGS: Octospim; + const OCTOSPI_IDX: u8; +} + +/// OctoSPI instance trait. +pub(crate) trait SealedInstance { + const REGS: Regs; +} + +/// OSPI instance trait. +#[cfg(octospim_v1)] +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + RccPeripheral + SealedOctospimInstance {} + +/// OSPI instance trait. +#[cfg(not(octospim_v1))] +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + RccPeripheral {} + +pin_trait!(SckPin, Instance); +pin_trait!(NckPin, Instance); +pin_trait!(D0Pin, Instance); +pin_trait!(D1Pin, Instance); +pin_trait!(D2Pin, Instance); +pin_trait!(D3Pin, Instance); +pin_trait!(D4Pin, Instance); +pin_trait!(D5Pin, Instance); +pin_trait!(D6Pin, Instance); +pin_trait!(D7Pin, Instance); +pin_trait!(DQSPin, Instance); +pin_trait!(NSSPin, Instance); +dma_trait!(OctoDma, Instance); + +// Hard-coded the octospi index, for OCTOSPIM +#[cfg(octospim_v1)] +impl SealedOctospimInstance for peripherals::OCTOSPI1 { + const OCTOSPIM_REGS: Octospim = crate::pac::OCTOSPIM; + const OCTOSPI_IDX: u8 = 1; +} + +#[cfg(all(octospim_v1, peri_octospi2))] +impl SealedOctospimInstance for peripherals::OCTOSPI2 { + const OCTOSPIM_REGS: Octospim = crate::pac::OCTOSPIM; + const OCTOSPI_IDX: u8 = 2; +} + +#[cfg(octospim_v1)] +foreach_peripheral!( + (octospi, $inst:ident) => { + impl SealedInstance for peripherals::$inst { + const REGS: Regs = crate::pac::$inst; + } + + impl Instance for peripherals::$inst {} + }; +); + +#[cfg(not(octospim_v1))] +foreach_peripheral!( + (octospi, $inst:ident) => { + impl SealedInstance for peripherals::$inst { + const REGS: Regs = crate::pac::$inst; + } + + impl Instance for peripherals::$inst {} + }; +); + +impl<'d, T: Instance, M: PeriMode> SetConfig for Ospi<'d, T, M> { + type Config = Config; + type ConfigError = (); + fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> { + self.set_config(config); + Ok(()) + } +} + +impl<'d, T: Instance, M: PeriMode> GetConfig for Ospi<'d, T, M> { + type Config = Config; + fn get_config(&self) -> Self::Config { + self.get_config() + } +} + +/// Word sizes usable for OSPI. +#[allow(private_bounds)] +pub trait Word: word::Word {} + +macro_rules! impl_word { + ($T:ty) => { + impl Word for $T {} + }; +} + +impl_word!(u8); +impl_word!(u16); +impl_word!(u32); diff --git a/embassy-stm32/src/qspi/mod.rs b/embassy-stm32/src/qspi/mod.rs index 8a709a89e..49836aa57 100644 --- a/embassy-stm32/src/qspi/mod.rs +++ b/embassy-stm32/src/qspi/mod.rs @@ -4,19 +4,21 @@ pub mod enums; +use core::marker::PhantomData; + use embassy_hal_internal::{into_ref, PeripheralRef}; use enums::*; -use crate::dma::Transfer; -use crate::gpio::sealed::AFType; -use crate::gpio::{AnyPin, Pull}; +use crate::dma::ChannelAndRequest; +use crate::gpio::{AfType, AnyPin, OutputType, Pull, Speed}; +use crate::mode::{Async, Blocking, Mode as PeriMode}; use crate::pac::quadspi::Quadspi as Regs; -use crate::rcc::RccPeripheral; +use crate::rcc::{self, RccPeripheral}; use crate::{peripherals, Peripheral}; /// QSPI transfer configuration. pub struct TransferConfig { - /// Instraction width (IMODE) + /// Instruction width (IMODE) pub iwidth: QspiWidth, /// Address width (ADMODE) pub awidth: QspiWidth, @@ -28,8 +30,6 @@ pub struct TransferConfig { pub address: Option, /// Number of dummy cycles (DCYC) pub dummy: DummyCycles, - /// Length of data - pub data_len: Option, } impl Default for TransferConfig { @@ -41,7 +41,6 @@ impl Default for TransferConfig { instruction: 0, address: None, dummy: DummyCycles::_0, - data_len: None, } } } @@ -75,7 +74,7 @@ impl Default for Config { /// QSPI driver. #[allow(dead_code)] -pub struct Qspi<'d, T: Instance, Dma> { +pub struct Qspi<'d, T: Instance, M: PeriMode> { _peri: PeripheralRef<'d, T>, sck: Option>, d0: Option>, @@ -83,93 +82,12 @@ pub struct Qspi<'d, T: Instance, Dma> { d2: Option>, d3: Option>, nss: Option>, - dma: PeripheralRef<'d, Dma>, + dma: Option>, + _phantom: PhantomData, config: Config, } -impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> { - /// Create a new QSPI driver for bank 1. - pub fn new_bk1( - peri: impl Peripheral

+ 'd, - d0: impl Peripheral

> + 'd, - d1: impl Peripheral

> + 'd, - d2: impl Peripheral

> + 'd, - d3: impl Peripheral

> + 'd, - sck: impl Peripheral

> + 'd, - nss: impl Peripheral

> + 'd, - dma: impl Peripheral

+ 'd, - config: Config, - ) -> Self { - into_ref!(peri, d0, d1, d2, d3, sck, nss); - - sck.set_as_af_pull(sck.af_num(), AFType::OutputPushPull, Pull::None); - sck.set_speed(crate::gpio::Speed::VeryHigh); - nss.set_as_af_pull(nss.af_num(), AFType::OutputPushPull, Pull::Up); - nss.set_speed(crate::gpio::Speed::VeryHigh); - d0.set_as_af_pull(d0.af_num(), AFType::OutputPushPull, Pull::None); - d0.set_speed(crate::gpio::Speed::VeryHigh); - d1.set_as_af_pull(d1.af_num(), AFType::OutputPushPull, Pull::None); - d1.set_speed(crate::gpio::Speed::VeryHigh); - d2.set_as_af_pull(d2.af_num(), AFType::OutputPushPull, Pull::None); - d2.set_speed(crate::gpio::Speed::VeryHigh); - d3.set_as_af_pull(d3.af_num(), AFType::OutputPushPull, Pull::None); - d3.set_speed(crate::gpio::Speed::VeryHigh); - - Self::new_inner( - peri, - Some(d0.map_into()), - Some(d1.map_into()), - Some(d2.map_into()), - Some(d3.map_into()), - Some(sck.map_into()), - Some(nss.map_into()), - dma, - config, - FlashSelection::Flash1, - ) - } - - /// Create a new QSPI driver for bank 2. - pub fn new_bk2( - peri: impl Peripheral

+ 'd, - d0: impl Peripheral

> + 'd, - d1: impl Peripheral

> + 'd, - d2: impl Peripheral

> + 'd, - d3: impl Peripheral

> + 'd, - sck: impl Peripheral

> + 'd, - nss: impl Peripheral

> + 'd, - dma: impl Peripheral

+ 'd, - config: Config, - ) -> Self { - into_ref!(peri, d0, d1, d2, d3, sck, nss); - - sck.set_as_af_pull(sck.af_num(), AFType::OutputPushPull, Pull::None); - sck.set_speed(crate::gpio::Speed::VeryHigh); - nss.set_as_af_pull(nss.af_num(), AFType::OutputPushPull, Pull::Up); - nss.set_speed(crate::gpio::Speed::VeryHigh); - d0.set_as_af_pull(d0.af_num(), AFType::OutputPushPull, Pull::None); - d0.set_speed(crate::gpio::Speed::VeryHigh); - d1.set_as_af_pull(d1.af_num(), AFType::OutputPushPull, Pull::None); - d1.set_speed(crate::gpio::Speed::VeryHigh); - d2.set_as_af_pull(d2.af_num(), AFType::OutputPushPull, Pull::None); - d2.set_speed(crate::gpio::Speed::VeryHigh); - d3.set_as_af_pull(d3.af_num(), AFType::OutputPushPull, Pull::None); - d3.set_speed(crate::gpio::Speed::VeryHigh); - - Self::new_inner( - peri, - Some(d0.map_into()), - Some(d1.map_into()), - Some(d2.map_into()), - Some(d3.map_into()), - Some(sck.map_into()), - Some(nss.map_into()), - dma, - config, - FlashSelection::Flash2, - ) - } - +impl<'d, T: Instance, M: PeriMode> Qspi<'d, T, M> { fn new_inner( peri: impl Peripheral

+ 'd, d0: Option>, @@ -178,13 +96,13 @@ impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> { d3: Option>, sck: Option>, nss: Option>, - dma: impl Peripheral

+ 'd, + dma: Option>, config: Config, fsel: FlashSelection, ) -> Self { - into_ref!(peri, dma); + into_ref!(peri); - T::enable_and_reset(); + rcc::enable_and_reset::(); while T::REGS.sr().read().busy() {} @@ -224,6 +142,7 @@ impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> { d3, nss, dma, + _phantom: PhantomData, config, } } @@ -232,7 +151,7 @@ impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> { pub fn command(&mut self, transaction: TransferConfig) { #[cfg(not(stm32h7))] T::REGS.cr().modify(|v| v.set_dmaen(false)); - self.setup_transaction(QspiMode::IndirectWrite, &transaction); + self.setup_transaction(QspiMode::IndirectWrite, &transaction, None); while !T::REGS.sr().read().tcf() {} T::REGS.fcr().modify(|v| v.set_ctcf(true)); @@ -242,21 +161,19 @@ impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> { pub fn blocking_read(&mut self, buf: &mut [u8], transaction: TransferConfig) { #[cfg(not(stm32h7))] T::REGS.cr().modify(|v| v.set_dmaen(false)); - self.setup_transaction(QspiMode::IndirectWrite, &transaction); + self.setup_transaction(QspiMode::IndirectWrite, &transaction, Some(buf.len())); - if let Some(len) = transaction.data_len { - let current_ar = T::REGS.ar().read().address(); - T::REGS.ccr().modify(|v| { - v.set_fmode(QspiMode::IndirectRead.into()); - }); - T::REGS.ar().write(|v| { - v.set_address(current_ar); - }); + let current_ar = T::REGS.ar().read().address(); + T::REGS.ccr().modify(|v| { + v.set_fmode(QspiMode::IndirectRead.into()); + }); + T::REGS.ar().write(|v| { + v.set_address(current_ar); + }); - for idx in 0..len { - while !T::REGS.sr().read().tcf() && !T::REGS.sr().read().ftf() {} - buf[idx] = unsafe { (T::REGS.dr().as_ptr() as *mut u8).read_volatile() }; - } + for b in buf { + while !T::REGS.sr().read().tcf() && !T::REGS.sr().read().ftf() {} + *b = unsafe { (T::REGS.dr().as_ptr() as *mut u8).read_volatile() }; } while !T::REGS.sr().read().tcf() {} @@ -269,86 +186,37 @@ impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> { #[cfg(not(stm32h7))] T::REGS.cr().modify(|v| v.set_dmaen(false)); - self.setup_transaction(QspiMode::IndirectWrite, &transaction); + self.setup_transaction(QspiMode::IndirectWrite, &transaction, Some(buf.len())); - if let Some(len) = transaction.data_len { - T::REGS.ccr().modify(|v| { - v.set_fmode(QspiMode::IndirectWrite.into()); - }); + T::REGS.ccr().modify(|v| { + v.set_fmode(QspiMode::IndirectWrite.into()); + }); - for idx in 0..len { - while !T::REGS.sr().read().ftf() {} - unsafe { (T::REGS.dr().as_ptr() as *mut u8).write_volatile(buf[idx]) }; - } + for &b in buf { + while !T::REGS.sr().read().ftf() {} + unsafe { (T::REGS.dr().as_ptr() as *mut u8).write_volatile(b) }; } while !T::REGS.sr().read().tcf() {} T::REGS.fcr().modify(|v| v.set_ctcf(true)); } - /// Blocking read data, using DMA. - pub fn blocking_read_dma(&mut self, buf: &mut [u8], transaction: TransferConfig) - where - Dma: QuadDma, - { - self.setup_transaction(QspiMode::IndirectWrite, &transaction); + fn setup_transaction(&mut self, fmode: QspiMode, transaction: &TransferConfig, data_len: Option) { + match (transaction.address, transaction.awidth) { + (Some(_), QspiWidth::NONE) => panic!("QSPI address can't be sent with an address width of NONE"), + (Some(_), _) => {} + (None, QspiWidth::NONE) => {} + (None, _) => panic!("QSPI address is not set, so the address width should be NONE"), + } - T::REGS.ccr().modify(|v| { - v.set_fmode(QspiMode::IndirectRead.into()); - }); - let current_ar = T::REGS.ar().read().address(); - T::REGS.ar().write(|v| { - v.set_address(current_ar); - }); + match (data_len, transaction.dwidth) { + (Some(0), _) => panic!("QSPI data must be at least one byte"), + (Some(_), QspiWidth::NONE) => panic!("QSPI data can't be sent with a data width of NONE"), + (Some(_), _) => {} + (None, QspiWidth::NONE) => {} + (None, _) => panic!("QSPI data is empty, so the data width should be NONE"), + } - let request = self.dma.request(); - let transfer = unsafe { - Transfer::new_read( - &mut self.dma, - request, - T::REGS.dr().as_ptr() as *mut u8, - buf, - Default::default(), - ) - }; - - // STM32H7 does not have dmaen - #[cfg(not(stm32h7))] - T::REGS.cr().modify(|v| v.set_dmaen(true)); - - transfer.blocking_wait(); - } - - /// Blocking write data, using DMA. - pub fn blocking_write_dma(&mut self, buf: &[u8], transaction: TransferConfig) - where - Dma: QuadDma, - { - self.setup_transaction(QspiMode::IndirectWrite, &transaction); - - T::REGS.ccr().modify(|v| { - v.set_fmode(QspiMode::IndirectWrite.into()); - }); - - let request = self.dma.request(); - let transfer = unsafe { - Transfer::new_write( - &mut self.dma, - request, - buf, - T::REGS.dr().as_ptr() as *mut u8, - Default::default(), - ) - }; - - // STM32H7 does not have dmaen - #[cfg(not(stm32h7))] - T::REGS.cr().modify(|v| v.set_dmaen(true)); - - transfer.blocking_wait(); - } - - fn setup_transaction(&mut self, fmode: QspiMode, transaction: &TransferConfig) { T::REGS.fcr().modify(|v| { v.set_csmf(true); v.set_ctcf(true); @@ -358,7 +226,7 @@ impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> { while T::REGS.sr().read().busy() {} - if let Some(len) = transaction.data_len { + if let Some(len) = data_len { T::REGS.dlr().write(|v| v.set_dl(len as u32 - 1)); } @@ -381,16 +249,203 @@ impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> { } } -pub(crate) mod sealed { - use super::*; +impl<'d, T: Instance> Qspi<'d, T, Blocking> { + /// Create a new QSPI driver for bank 1, in blocking mode. + pub fn new_blocking_bank1( + peri: impl Peripheral

+ 'd, + d0: impl Peripheral

> + 'd, + d1: impl Peripheral

> + 'd, + d2: impl Peripheral

> + 'd, + d3: impl Peripheral

> + 'd, + sck: impl Peripheral

> + 'd, + nss: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(d0, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d1, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d2, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d3, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(sck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!( + nss, + AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up) + ), + None, + config, + FlashSelection::Flash1, + ) + } - pub trait Instance { - const REGS: Regs; + /// Create a new QSPI driver for bank 2, in blocking mode. + pub fn new_blocking_bank2( + peri: impl Peripheral

+ 'd, + d0: impl Peripheral

> + 'd, + d1: impl Peripheral

> + 'd, + d2: impl Peripheral

> + 'd, + d3: impl Peripheral

> + 'd, + sck: impl Peripheral

> + 'd, + nss: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(d0, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d1, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d2, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d3, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(sck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!( + nss, + AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up) + ), + None, + config, + FlashSelection::Flash2, + ) } } +impl<'d, T: Instance> Qspi<'d, T, Async> { + /// Create a new QSPI driver for bank 1. + pub fn new_bank1( + peri: impl Peripheral

+ 'd, + d0: impl Peripheral

> + 'd, + d1: impl Peripheral

> + 'd, + d2: impl Peripheral

> + 'd, + d3: impl Peripheral

> + 'd, + sck: impl Peripheral

> + 'd, + nss: impl Peripheral

> + 'd, + dma: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(d0, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d1, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d2, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d3, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(sck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!( + nss, + AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up) + ), + new_dma!(dma), + config, + FlashSelection::Flash1, + ) + } + + /// Create a new QSPI driver for bank 2. + pub fn new_bank2( + peri: impl Peripheral

+ 'd, + d0: impl Peripheral

> + 'd, + d1: impl Peripheral

> + 'd, + d2: impl Peripheral

> + 'd, + d3: impl Peripheral

> + 'd, + sck: impl Peripheral

> + 'd, + nss: impl Peripheral

> + 'd, + dma: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(d0, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d1, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d2, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(d3, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(sck, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!( + nss, + AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up) + ), + new_dma!(dma), + config, + FlashSelection::Flash2, + ) + } + + /// Blocking read data, using DMA. + pub fn blocking_read_dma(&mut self, buf: &mut [u8], transaction: TransferConfig) { + let transfer = self.start_read_transfer(transaction, buf); + transfer.blocking_wait(); + } + + /// Async read data, using DMA. + pub async fn read_dma(&mut self, buf: &mut [u8], transaction: TransferConfig) { + let transfer = self.start_read_transfer(transaction, buf); + transfer.await; + } + + fn start_read_transfer<'a>( + &'a mut self, + transaction: TransferConfig, + buf: &'a mut [u8], + ) -> crate::dma::Transfer<'a> { + self.setup_transaction(QspiMode::IndirectWrite, &transaction, Some(buf.len())); + + T::REGS.ccr().modify(|v| { + v.set_fmode(QspiMode::IndirectRead.into()); + }); + let current_ar = T::REGS.ar().read().address(); + T::REGS.ar().write(|v| { + v.set_address(current_ar); + }); + + let transfer = unsafe { + self.dma + .as_mut() + .unwrap() + .read(T::REGS.dr().as_ptr() as *mut u8, buf, Default::default()) + }; + + // STM32H7 does not have dmaen + #[cfg(not(stm32h7))] + T::REGS.cr().modify(|v| v.set_dmaen(true)); + transfer + } + + /// Blocking write data, using DMA. + pub fn blocking_write_dma(&mut self, buf: &[u8], transaction: TransferConfig) { + let transfer = self.start_write_transfer(transaction, buf); + transfer.blocking_wait(); + } + + /// Async write data, using DMA. + pub async fn write_dma(&mut self, buf: &[u8], transaction: TransferConfig) { + let transfer = self.start_write_transfer(transaction, buf); + transfer.await; + } + + fn start_write_transfer<'a>(&'a mut self, transaction: TransferConfig, buf: &'a [u8]) -> crate::dma::Transfer<'a> { + self.setup_transaction(QspiMode::IndirectWrite, &transaction, Some(buf.len())); + + T::REGS.ccr().modify(|v| { + v.set_fmode(QspiMode::IndirectWrite.into()); + }); + + let transfer = unsafe { + self.dma + .as_mut() + .unwrap() + .write(buf, T::REGS.dr().as_ptr() as *mut u8, Default::default()) + }; + + // STM32H7 does not have dmaen + #[cfg(not(stm32h7))] + T::REGS.cr().modify(|v| v.set_dmaen(true)); + transfer + } +} + +trait SealedInstance { + const REGS: Regs; +} + /// QSPI instance trait. -pub trait Instance: Peripheral

+ sealed::Instance + RccPeripheral {} +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + RccPeripheral {} pin_trait!(SckPin, Instance); pin_trait!(BK1D0Pin, Instance); @@ -409,7 +464,7 @@ dma_trait!(QuadDma, Instance); foreach_peripheral!( (quadspi, $inst:ident) => { - impl sealed::Instance for peripherals::$inst { + impl SealedInstance for peripherals::$inst { const REGS: Regs = crate::pac::$inst; } diff --git a/embassy-stm32/src/rcc/bd.rs b/embassy-stm32/src/rcc/bd.rs index d20f58185..9ccca8a2a 100644 --- a/embassy-stm32/src/rcc/bd.rs +++ b/embassy-stm32/src/rcc/bd.rs @@ -16,6 +16,7 @@ pub enum LseMode { Bypass, } +#[derive(Clone, Copy)] pub struct LseConfig { pub frequency: Hertz, pub mode: LseMode, @@ -24,6 +25,7 @@ pub struct LseConfig { #[allow(dead_code)] #[derive(Default, Clone, Copy)] pub enum LseDrive { + #[cfg(not(stm32h5))] // ES0565: LSE Low drive mode is not functional Low = 0, MediumLow = 0x01, #[default] @@ -32,12 +34,13 @@ pub enum LseDrive { } // All families but these have the LSEDRV register -#[cfg(not(any(rcc_f1, rcc_f1cl, rcc_f100, rcc_f2, rcc_f4, rcc_f400, rcc_f410, rcc_l1)))] +#[cfg(not(any(rcc_f1, rcc_f1cl, rcc_f100, rcc_f2, rcc_f4, rcc_f410, rcc_l1)))] impl From for crate::pac::rcc::vals::Lsedrv { fn from(value: LseDrive) -> Self { use crate::pac::rcc::vals::Lsedrv; match value { + #[cfg(not(stm32h5))] // ES0565: LSE Low drive mode is not functional LseDrive::Low => Lsedrv::LOW, LseDrive::MediumLow => Lsedrv::MEDIUMLOW, LseDrive::MediumHigh => Lsedrv::MEDIUMHIGH, @@ -78,6 +81,7 @@ fn bdcr() -> Reg { return crate::pac::RCC.csr1(); } +#[derive(Clone, Copy)] pub struct LsConfig { pub rtc: RtcClockSource, pub lsi: bool, @@ -184,7 +188,7 @@ impl LsConfig { } ok &= reg.lseon() == lse_en; ok &= reg.lsebyp() == lse_byp; - #[cfg(not(any(rcc_f1, rcc_f1cl, rcc_f100, rcc_f2, rcc_f4, rcc_f400, rcc_f410, rcc_l1)))] + #[cfg(not(any(rcc_f1, rcc_f1cl, rcc_f100, rcc_f2, rcc_f4, rcc_f410, rcc_l1)))] if let Some(lse_drv) = lse_drv { ok &= reg.lsedrv() == lse_drv.into(); } @@ -196,17 +200,25 @@ impl LsConfig { } // If not OK, reset backup domain and configure it. - #[cfg(not(any(rcc_l0, rcc_l0_v2, rcc_l1, stm32h5, stm32c0)))] + #[cfg(not(any(rcc_l0, rcc_l0_v2, rcc_l1, stm32h5, stm32h7rs, stm32c0)))] { bdcr().modify(|w| w.set_bdrst(true)); bdcr().modify(|w| w.set_bdrst(false)); } - #[cfg(any(stm32h5))] + // H5 has a terrible, terrible errata: 'SRAM2 is erased when the backup domain is reset' + // pending a more sane sane way to handle this, just don't reset BD for now. + // This means the RTCSEL write below will have no effect, only if it has already been written + // after last power-on. Since it's uncommon to dynamically change RTCSEL, this is better than + // letting half our RAM go magically *poof*. + // STM32H503CB/EB/KB/RB device errata - 2.2.8 SRAM2 unduly erased upon a backup domain reset + // STM32H562xx/563xx/573xx device errata - 2.2.14 SRAM2 is erased when the backup domain is reset + //#[cfg(any(stm32h5, stm32h7rs))] + #[cfg(any(stm32h7rs))] { bdcr().modify(|w| w.set_vswrst(true)); bdcr().modify(|w| w.set_vswrst(false)); } - #[cfg(any(stm32c0))] + #[cfg(any(stm32c0, stm32l0))] { bdcr().modify(|w| w.set_rtcrst(true)); bdcr().modify(|w| w.set_rtcrst(false)); @@ -214,7 +226,7 @@ impl LsConfig { if lse_en { bdcr().modify(|w| { - #[cfg(not(any(rcc_f1, rcc_f1cl, rcc_f100, rcc_f2, rcc_f4, rcc_f400, rcc_f410, rcc_l1)))] + #[cfg(not(any(rcc_f1, rcc_f1cl, rcc_f100, rcc_f2, rcc_f4, rcc_f410, rcc_l1)))] if let Some(lse_drv) = lse_drv { w.set_lsedrv(lse_drv.into()); } diff --git a/embassy-stm32/src/rcc/c0.rs b/embassy-stm32/src/rcc/c0.rs index 68f029ca0..6712aedc4 100644 --- a/embassy-stm32/src/rcc/c0.rs +++ b/embassy-stm32/src/rcc/c0.rs @@ -1,145 +1,195 @@ use crate::pac::flash::vals::Latency; -use crate::pac::rcc::vals::Sw; -pub use crate::pac::rcc::vals::{Hpre as AHBPrescaler, Hsidiv as HSIPrescaler, Ppre as APBPrescaler}; +pub use crate::pac::rcc::vals::{ + Hpre as AHBPrescaler, Hsidiv as HsiSysDiv, Hsikerdiv as HsiKerDiv, Ppre as APBPrescaler, Sw as Sysclk, +}; use crate::pac::{FLASH, RCC}; -use crate::rcc::{set_freqs, Clocks}; use crate::time::Hertz; /// HSI speed pub const HSI_FREQ: Hertz = Hertz(48_000_000); -/// System clock mux source -#[derive(Clone, Copy)] -pub enum ClockSrc { - HSE(Hertz), - HSI(HSIPrescaler), - LSI, +/// HSE Mode +#[derive(Clone, Copy, Eq, PartialEq)] +pub enum HseMode { + /// crystal/ceramic oscillator (HSEBYP=0) + Oscillator, + /// external analog clock (low swing) (HSEBYP=1) + Bypass, +} + +/// HSE Configuration +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct Hse { + /// HSE frequency. + pub freq: Hertz, + /// HSE mode. + pub mode: HseMode, +} + +/// HSI Configuration +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct Hsi { + /// Division factor for HSISYS clock. Default is 4. + pub sys_div: HsiSysDiv, + /// Division factor for HSIKER clock. Default is 3. + pub ker_div: HsiKerDiv, } /// Clocks configutation +#[non_exhaustive] +#[derive(Clone, Copy)] pub struct Config { - pub mux: ClockSrc, + /// HSI Configuration + pub hsi: Option, + + /// HSE Configuration + pub hse: Option, + + /// System Clock Configuration + pub sys: Sysclk, + pub ahb_pre: AHBPrescaler, - pub apb_pre: APBPrescaler, + pub apb1_pre: APBPrescaler, + + /// Low-Speed Clock Configuration pub ls: super::LsConfig, + + /// Per-peripheral kernel clock selection muxes + pub mux: super::mux::ClockMux, } impl Default for Config { #[inline] fn default() -> Config { Config { - mux: ClockSrc::HSI(HSIPrescaler::DIV1), + hsi: Some(Hsi { + sys_div: HsiSysDiv::DIV4, + ker_div: HsiKerDiv::DIV3, + }), + hse: None, + sys: Sysclk::HSISYS, ahb_pre: AHBPrescaler::DIV1, - apb_pre: APBPrescaler::DIV1, + apb1_pre: APBPrescaler::DIV1, ls: Default::default(), + mux: Default::default(), } } } pub(crate) unsafe fn init(config: Config) { - let (sys_clk, sw) = match config.mux { - ClockSrc::HSI(div) => { - // Enable HSI - RCC.cr().write(|w| { - w.set_hsidiv(div); - w.set_hsion(true) - }); - while !RCC.cr().read().hsirdy() {} + // Turn on the HSI + match config.hsi { + None => RCC.cr().modify(|w| w.set_hsion(true)), + Some(hsi) => RCC.cr().modify(|w| { + w.set_hsidiv(hsi.sys_div); + w.set_hsikerdiv(hsi.ker_div); + w.set_hsion(true); + }), + } + while !RCC.cr().read().hsirdy() {} - (HSI_FREQ / div, Sw::HSI) + // Use the HSI clock as system clock during the actual clock setup + RCC.cfgr().modify(|w| w.set_sw(Sysclk::HSISYS)); + while RCC.cfgr().read().sws() != Sysclk::HSISYS {} + + // Configure HSI + let (hsi, hsisys, hsiker) = match config.hsi { + None => (None, None, None), + Some(hsi) => ( + Some(HSI_FREQ), + Some(HSI_FREQ / hsi.sys_div), + Some(HSI_FREQ / hsi.ker_div), + ), + }; + + // Configure HSE + let hse = match config.hse { + None => { + RCC.cr().modify(|w| w.set_hseon(false)); + None } - ClockSrc::HSE(freq) => { - // Enable HSE - RCC.cr().write(|w| w.set_hseon(true)); + Some(hse) => { + match hse.mode { + HseMode::Bypass => assert!(max::HSE_BYP.contains(&hse.freq)), + HseMode::Oscillator => assert!(max::HSE_OSC.contains(&hse.freq)), + } + + RCC.cr().modify(|w| w.set_hsebyp(hse.mode != HseMode::Oscillator)); + RCC.cr().modify(|w| w.set_hseon(true)); while !RCC.cr().read().hserdy() {} - - (freq, Sw::HSE) - } - ClockSrc::LSI => { - // Enable LSI - RCC.csr2().write(|w| w.set_lsion(true)); - while !RCC.csr2().read().lsirdy() {} - (super::LSI_FREQ, Sw::LSI) + Some(hse.freq) } }; + let sys = match config.sys { + Sysclk::HSISYS => unwrap!(hsisys), + Sysclk::HSE => unwrap!(hse), + _ => unreachable!(), + }; + + assert!(max::SYSCLK.contains(&sys)); + + // Calculate the AHB frequency (HCLK), among other things so we can calculate the correct flash read latency. + let hclk = sys / config.ahb_pre; + assert!(max::HCLK.contains(&hclk)); + + let (pclk1, pclk1_tim) = super::util::calc_pclk(hclk, config.apb1_pre); + assert!(max::PCLK.contains(&pclk1)); + + let latency = match hclk.0 { + ..=24_000_000 => Latency::WS0, + _ => Latency::WS1, + }; + + // Configure flash read access latency based on voltage scale and frequency + FLASH.acr().modify(|w| { + w.set_latency(latency); + }); + + // Spin until the effective flash latency is set. + while FLASH.acr().read().latency() != latency {} + + // Now that boost mode and flash read access latency are configured, set up SYSCLK + RCC.cfgr().modify(|w| { + w.set_sw(config.sys); + w.set_hpre(config.ahb_pre); + w.set_ppre(config.apb1_pre); + }); + while RCC.cfgr().read().sws() != config.sys {} + + // Disable HSI if not used + if config.hsi.is_none() { + RCC.cr().modify(|w| w.set_hsion(false)); + } + let rtc = config.ls.init(); - // Determine the flash latency implied by the target clock speed - // RM0454 § 3.3.4: - let target_flash_latency = if sys_clk <= Hertz(24_000_000) { - Latency::WS0 - } else { - Latency::WS1 - }; + config.mux.init(); - // Increase the number of cycles we wait for flash if the new value is higher - // There's no harm in waiting a little too much before the clock change, but we'll - // crash immediately if we don't wait enough after the clock change - let mut set_flash_latency_after = false; - FLASH.acr().modify(|w| { - // Is the current flash latency less than what we need at the new SYSCLK? - if w.latency().to_bits() <= target_flash_latency.to_bits() { - // We must increase the number of wait states now - w.set_latency(target_flash_latency) - } else { - // We may decrease the number of wait states later - set_flash_latency_after = true; - } + set_clocks!( + sys: Some(sys), + hclk1: Some(hclk), + pclk1: Some(pclk1), + pclk1_tim: Some(pclk1_tim), + hsi: hsi, + hsiker: hsiker, + hse: hse, + rtc: rtc, - // RM0490 § 3.3.4: - // > Prefetch is enabled by setting the PRFTEN bit of the FLASH access control register - // > (FLASH_ACR). This feature is useful if at least one wait state is needed to access the - // > Flash memory. - // - // Enable flash prefetching if we have at least one wait state, and disable it otherwise. - w.set_prften(target_flash_latency.to_bits() > 0); - }); - - if !set_flash_latency_after { - // Spin until the effective flash latency is compatible with the clock change - while FLASH.acr().read().latency().to_bits() < target_flash_latency.to_bits() {} - } - - // Configure SYSCLK source, HCLK divisor, and PCLK divisor all at once - let (sw, hpre, ppre) = (sw.into(), config.ahb_pre, config.apb_pre); - RCC.cfgr().modify(|w| { - w.set_sw(sw); - w.set_hpre(hpre); - w.set_ppre(ppre); - }); - - if set_flash_latency_after { - // We can make the flash require fewer wait states - // Spin until the SYSCLK changes have taken effect - loop { - let cfgr = RCC.cfgr().read(); - if cfgr.sw() == sw && cfgr.hpre() == hpre && cfgr.ppre() == ppre { - break; - } - } - - // Set the flash latency to require fewer wait states - FLASH.acr().modify(|w| w.set_latency(target_flash_latency)); - } - - let ahb_freq = sys_clk / config.ahb_pre; - - let (apb_freq, apb_tim_freq) = match config.apb_pre { - APBPrescaler::DIV1 => (ahb_freq, ahb_freq), - pre => { - let freq = ahb_freq / pre; - (freq, freq * 2u32) - } - }; - - set_freqs(Clocks { - hsi: None, + // TODO + lsi: None, lse: None, - sys: sys_clk, - hclk1: ahb_freq, - pclk1: apb_freq, - pclk1_tim: apb_tim_freq, - rtc, - }); + ); +} + +mod max { + use core::ops::RangeInclusive; + + use crate::time::Hertz; + + pub(crate) const HSE_OSC: RangeInclusive = Hertz(4_000_000)..=Hertz(48_000_000); + pub(crate) const HSE_BYP: RangeInclusive = Hertz(0)..=Hertz(48_000_000); + pub(crate) const SYSCLK: RangeInclusive = Hertz(0)..=Hertz(48_000_000); + pub(crate) const PCLK: RangeInclusive = Hertz(8)..=Hertz(48_000_000); + pub(crate) const HCLK: RangeInclusive = Hertz(0)..=Hertz(48_000_000); } diff --git a/embassy-stm32/src/rcc/f0.rs b/embassy-stm32/src/rcc/f0.rs deleted file mode 100644 index feaa2f4c0..000000000 --- a/embassy-stm32/src/rcc/f0.rs +++ /dev/null @@ -1,172 +0,0 @@ -use stm32_metapac::flash::vals::Latency; - -use super::{set_freqs, Clocks}; -use crate::pac::rcc::vals::{Hpre, Pllmul, Pllsrc, Ppre, Sw, Usbsw}; -use crate::pac::{FLASH, RCC}; -use crate::time::Hertz; - -/// HSI speed -pub const HSI_FREQ: Hertz = Hertz(8_000_000); - -/// Configuration of the clocks -/// -/// hse takes precedence over hsi48 if both are enabled -#[non_exhaustive] -#[derive(Default)] -pub struct Config { - pub hse: Option, - pub bypass_hse: bool, - pub usb_pll: bool, - - #[cfg(not(stm32f0x0))] - pub hsi48: bool, - - pub sys_ck: Option, - pub hclk: Option, - pub pclk: Option, - - pub ls: super::LsConfig, -} - -pub(crate) unsafe fn init(config: Config) { - let sysclk = config.sys_ck.map(|v| v.0).unwrap_or(HSI_FREQ.0); - - let (src_clk, use_hsi48) = config.hse.map(|v| (v.0, false)).unwrap_or_else(|| { - #[cfg(not(stm32f0x0))] - if config.hsi48 { - return (48_000_000, true); - } - (HSI_FREQ.0, false) - }); - - let (pllmul_bits, real_sysclk) = if sysclk == src_clk { - (None, sysclk) - } else { - let prediv = if config.hse.is_some() { 1 } else { 2 }; - let pllmul = (2 * prediv * sysclk + src_clk) / src_clk / 2; - let pllmul = pllmul.max(2).min(16); - - let pllmul_bits = pllmul as u8 - 2; - let real_sysclk = pllmul * src_clk / prediv; - (Some(pllmul_bits), real_sysclk) - }; - - let hpre_bits = config - .hclk - .map(|hclk| match real_sysclk / hclk.0 { - 0 => unreachable!(), - 1 => 0b0111, - 2 => 0b1000, - 3..=5 => 0b1001, - 6..=11 => 0b1010, - 12..=39 => 0b1011, - 40..=95 => 0b1100, - 96..=191 => 0b1101, - 192..=383 => 0b1110, - _ => 0b1111, - }) - .unwrap_or(0b0111); - let hclk = real_sysclk / (1 << (hpre_bits - 0b0111)); - - let ppre_bits = config - .pclk - .map(|pclk| match hclk / pclk.0 { - 0 => unreachable!(), - 1 => 0b011, - 2 => 0b100, - 3..=5 => 0b101, - 6..=11 => 0b110, - _ => 0b111, - }) - .unwrap_or(0b011); - - let ppre: u8 = 1 << (ppre_bits - 0b011); - let pclk = hclk / u32::from(ppre); - - let timer_mul = if ppre == 1 { 1 } else { 2 }; - - FLASH.acr().write(|w| { - w.set_latency(if real_sysclk <= 24_000_000 { - Latency::WS0 - } else { - Latency::WS1 - }); - }); - - match (config.hse.is_some(), use_hsi48) { - (true, _) => { - RCC.cr().modify(|w| { - w.set_csson(true); - w.set_hseon(true); - w.set_hsebyp(config.bypass_hse); - }); - while !RCC.cr().read().hserdy() {} - - if pllmul_bits.is_some() { - RCC.cfgr().modify(|w| w.set_pllsrc(Pllsrc::HSE_DIV_PREDIV)) - } - } - // use_hsi48 will always be false for stm32f0x0 - #[cfg(not(stm32f0x0))] - (false, true) => { - RCC.cr2().modify(|w| w.set_hsi48on(true)); - while !RCC.cr2().read().hsi48rdy() {} - - if pllmul_bits.is_some() { - RCC.cfgr().modify(|w| w.set_pllsrc(Pllsrc::HSI48_DIV_PREDIV)) - } - } - _ => { - RCC.cr().modify(|w| w.set_hsion(true)); - while !RCC.cr().read().hsirdy() {} - - if pllmul_bits.is_some() { - RCC.cfgr().modify(|w| w.set_pllsrc(Pllsrc::HSI_DIV2)) - } - } - } - - if config.usb_pll { - RCC.cfgr3().modify(|w| w.set_usbsw(Usbsw::PLL1_P)); - } - // TODO: Option to use CRS (Clock Recovery) - - if let Some(pllmul_bits) = pllmul_bits { - RCC.cfgr().modify(|w| w.set_pllmul(Pllmul::from_bits(pllmul_bits))); - - RCC.cr().modify(|w| w.set_pllon(true)); - while !RCC.cr().read().pllrdy() {} - - RCC.cfgr().modify(|w| { - w.set_ppre(Ppre::from_bits(ppre_bits)); - w.set_hpre(Hpre::from_bits(hpre_bits)); - w.set_sw(Sw::PLL1_P) - }); - } else { - RCC.cfgr().modify(|w| { - w.set_ppre(Ppre::from_bits(ppre_bits)); - w.set_hpre(Hpre::from_bits(hpre_bits)); - - if config.hse.is_some() { - w.set_sw(Sw::HSE); - } else if use_hsi48 { - #[cfg(not(stm32f0x0))] - w.set_sw(Sw::HSI48); - } else { - w.set_sw(Sw::HSI) - } - }) - } - - let rtc = config.ls.init(); - - set_freqs(Clocks { - sys: Hertz(real_sysclk), - pclk1: Hertz(pclk), - pclk2: Hertz(pclk), - pclk1_tim: Hertz(pclk * timer_mul), - pclk2_tim: Hertz(pclk * timer_mul), - hclk1: Hertz(hclk), - rtc, - }); -} diff --git a/embassy-stm32/src/rcc/f013.rs b/embassy-stm32/src/rcc/f013.rs new file mode 100644 index 000000000..60577b213 --- /dev/null +++ b/embassy-stm32/src/rcc/f013.rs @@ -0,0 +1,475 @@ +use crate::pac::flash::vals::Latency; +#[cfg(stm32f1)] +pub use crate::pac::rcc::vals::Adcpre as ADCPrescaler; +#[cfg(stm32f3)] +pub use crate::pac::rcc::vals::Adcpres as AdcPllPrescaler; +use crate::pac::rcc::vals::Pllsrc; +#[cfg(stm32f1)] +pub use crate::pac::rcc::vals::Pllxtpre as PllPreDiv; +#[cfg(any(stm32f0, stm32f3))] +pub use crate::pac::rcc::vals::Prediv as PllPreDiv; +pub use crate::pac::rcc::vals::{Hpre as AHBPrescaler, Pllmul as PllMul, Ppre as APBPrescaler, Sw as Sysclk}; +use crate::pac::{FLASH, RCC}; +use crate::time::Hertz; + +/// HSI speed +pub const HSI_FREQ: Hertz = Hertz(8_000_000); + +#[derive(Clone, Copy, Eq, PartialEq)] +pub enum HseMode { + /// crystal/ceramic oscillator (HSEBYP=0) + Oscillator, + /// external analog clock (low swing) (HSEBYP=1) + Bypass, +} + +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct Hse { + /// HSE frequency. + pub freq: Hertz, + /// HSE mode. + pub mode: HseMode, +} + +#[derive(Clone, Copy, Eq, PartialEq)] +pub enum PllSource { + HSE, + HSI, + #[cfg(rcc_f0v4)] + HSI48, +} + +#[derive(Clone, Copy)] +pub struct Pll { + pub src: PllSource, + + /// PLL pre-divider. + /// + /// On some chips, this must be 2 if `src == HSI`. Init will panic if this is not the case. + pub prediv: PllPreDiv, + + /// PLL multiplication factor. + pub mul: PllMul, +} + +#[cfg(all(stm32f3, not(rcc_f37)))] +#[derive(Clone, Copy)] +pub enum AdcClockSource { + Pll(AdcPllPrescaler), + Hclk(AdcHclkPrescaler), +} + +#[cfg(all(stm32f3, not(rcc_f37)))] +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum AdcHclkPrescaler { + Div1, + Div2, + Div4, +} + +#[cfg(stm32f334)] +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum HrtimClockSource { + BusClk, + PllClk, +} + +/// Clocks configutation +#[non_exhaustive] +#[derive(Clone, Copy)] +pub struct Config { + pub hsi: bool, + pub hse: Option, + #[cfg(crs)] + pub hsi48: Option, + pub sys: Sysclk, + + pub pll: Option, + + pub ahb_pre: AHBPrescaler, + pub apb1_pre: APBPrescaler, + #[cfg(not(stm32f0))] + pub apb2_pre: APBPrescaler, + + #[cfg(stm32f1)] + pub adc_pre: ADCPrescaler, + + #[cfg(all(stm32f3, not(rcc_f37)))] + pub adc: AdcClockSource, + #[cfg(all(stm32f3, not(rcc_f37), any(peri_adc3_common, peri_adc34_common)))] + pub adc34: AdcClockSource, + + /// Per-peripheral kernel clock selection muxes + pub mux: super::mux::ClockMux, + + pub ls: super::LsConfig, +} + +impl Default for Config { + fn default() -> Self { + Self { + hsi: true, + hse: None, + #[cfg(crs)] + hsi48: Some(Default::default()), + sys: Sysclk::HSI, + pll: None, + ahb_pre: AHBPrescaler::DIV1, + apb1_pre: APBPrescaler::DIV1, + #[cfg(not(stm32f0))] + apb2_pre: APBPrescaler::DIV1, + ls: Default::default(), + + #[cfg(stm32f1)] + // ensure ADC is not out of range by default even if APB2 is maxxed out (36mhz) + adc_pre: ADCPrescaler::DIV6, + + #[cfg(all(stm32f3, not(rcc_f37)))] + adc: AdcClockSource::Hclk(AdcHclkPrescaler::Div1), + #[cfg(all(stm32f3, not(rcc_f37), any(peri_adc3_common, peri_adc34_common)))] + adc34: AdcClockSource::Hclk(AdcHclkPrescaler::Div1), + + mux: Default::default(), + } + } +} + +/// Initialize and Set the clock frequencies +pub(crate) unsafe fn init(config: Config) { + // Turn on the HSI + RCC.cr().modify(|w| w.set_hsion(true)); + while !RCC.cr().read().hsirdy() {} + + // Use the HSI clock as system clock during the actual clock setup + RCC.cfgr().modify(|w| w.set_sw(Sysclk::HSI)); + while RCC.cfgr().read().sws() != Sysclk::HSI {} + + // Configure HSI + let hsi = match config.hsi { + false => None, + true => Some(HSI_FREQ), + }; + + // Configure HSE + let hse = match config.hse { + None => { + RCC.cr().modify(|w| w.set_hseon(false)); + None + } + Some(hse) => { + match hse.mode { + HseMode::Bypass => assert!(max::HSE_BYP.contains(&hse.freq)), + HseMode::Oscillator => assert!(max::HSE_OSC.contains(&hse.freq)), + } + + RCC.cr().modify(|w| w.set_hsebyp(hse.mode != HseMode::Oscillator)); + RCC.cr().modify(|w| w.set_hseon(true)); + while !RCC.cr().read().hserdy() {} + Some(hse.freq) + } + }; + + // configure HSI48 + #[cfg(crs)] + let hsi48 = config.hsi48.map(|config| super::init_hsi48(config)); + #[cfg(not(crs))] + let hsi48: Option = None; + + // Enable PLL + let pll = config.pll.map(|pll| { + let (src_val, src_freq) = match pll.src { + #[cfg(any(rcc_f0v3, rcc_f0v4, rcc_f3v3))] + PllSource::HSI => (Pllsrc::HSI_DIV_PREDIV, unwrap!(hsi)), + #[cfg(not(any(rcc_f0v3, rcc_f0v4, rcc_f3v3)))] + PllSource::HSI => { + if pll.prediv != PllPreDiv::DIV2 { + panic!("if PLL source is HSI, PLL prediv must be 2."); + } + (Pllsrc::HSI_DIV2, unwrap!(hsi)) + } + PllSource::HSE => (Pllsrc::HSE_DIV_PREDIV, unwrap!(hse)), + #[cfg(rcc_f0v4)] + PllSource::HSI48 => (Pllsrc::HSI48_DIV_PREDIV, unwrap!(hsi48)), + }; + let in_freq = src_freq / pll.prediv; + assert!(max::PLL_IN.contains(&in_freq)); + let out_freq = in_freq * pll.mul; + assert!(max::PLL_OUT.contains(&out_freq)); + + #[cfg(not(stm32f1))] + RCC.cfgr2().modify(|w| w.set_prediv(pll.prediv)); + RCC.cfgr().modify(|w| { + w.set_pllmul(pll.mul); + w.set_pllsrc(src_val); + #[cfg(stm32f1)] + w.set_pllxtpre(pll.prediv); + }); + RCC.cr().modify(|w| w.set_pllon(true)); + while !RCC.cr().read().pllrdy() {} + + out_freq + }); + + #[cfg(stm32f3)] + let pll_mul_2 = pll.map(|pll| pll * 2u32); + + #[cfg(any(rcc_f1, rcc_f1cl, stm32f3))] + let usb = match pll { + Some(Hertz(72_000_000)) => Some(crate::pac::rcc::vals::Usbpre::DIV1_5), + Some(Hertz(48_000_000)) => Some(crate::pac::rcc::vals::Usbpre::DIV1), + _ => None, + } + .map(|usbpre| { + RCC.cfgr().modify(|w| w.set_usbpre(usbpre)); + Hertz(48_000_000) + }); + + // Configure sysclk + let sys = match config.sys { + Sysclk::HSI => unwrap!(hsi), + Sysclk::HSE => unwrap!(hse), + Sysclk::PLL1_P => unwrap!(pll), + _ => unreachable!(), + }; + + let hclk = sys / config.ahb_pre; + let (pclk1, pclk1_tim) = super::util::calc_pclk(hclk, config.apb1_pre); + #[cfg(not(stm32f0))] + let (pclk2, pclk2_tim) = super::util::calc_pclk(hclk, config.apb2_pre); + #[cfg(stm32f0)] + let (pclk2, pclk2_tim) = (pclk1, pclk1_tim); + + assert!(max::HCLK.contains(&hclk)); + assert!(max::PCLK1.contains(&pclk1)); + #[cfg(not(stm32f0))] + assert!(max::PCLK2.contains(&pclk2)); + + #[cfg(stm32f1)] + let adc = pclk2 / config.adc_pre; + #[cfg(stm32f1)] + assert!(max::ADC.contains(&adc)); + + // Set latency based on HCLK frquency + #[cfg(stm32f0)] + let latency = match hclk.0 { + ..=24_000_000 => Latency::WS0, + _ => Latency::WS1, + }; + #[cfg(any(stm32f1, stm32f3))] + let latency = match hclk.0 { + ..=24_000_000 => Latency::WS0, + ..=48_000_000 => Latency::WS1, + _ => Latency::WS2, + }; + FLASH.acr().modify(|w| { + w.set_latency(latency); + // RM0316: "The prefetch buffer must be kept on when using a prescaler + // different from 1 on the AHB clock.", "Half-cycle access cannot be + // used when there is a prescaler different from 1 on the AHB clock" + #[cfg(stm32f3)] + if config.ahb_pre != AHBPrescaler::DIV1 { + w.set_hlfcya(false); + w.set_prftbe(true); + } + #[cfg(not(stm32f3))] + w.set_prftbe(true); + }); + + // Set prescalers + // CFGR has been written before (PLL, PLL48) don't overwrite these settings + RCC.cfgr().modify(|w| { + #[cfg(not(stm32f0))] + { + w.set_ppre1(config.apb1_pre); + w.set_ppre2(config.apb2_pre); + } + #[cfg(stm32f0)] + w.set_ppre(config.apb1_pre); + w.set_hpre(config.ahb_pre); + #[cfg(stm32f1)] + w.set_adcpre(config.adc_pre); + }); + + // Wait for the new prescalers to kick in + // "The clocks are divided with the new prescaler factor from + // 1 to 16 AHB cycles after write" + cortex_m::asm::delay(16); + + // CFGR has been written before (PLL, PLL48, clock divider) don't overwrite these settings + RCC.cfgr().modify(|w| w.set_sw(config.sys)); + while RCC.cfgr().read().sws() != config.sys {} + + // Disable HSI if not used + if !config.hsi { + RCC.cr().modify(|w| w.set_hsion(false)); + } + + let rtc = config.ls.init(); + + // TODO: all this ADC stuff should probably go into the ADC module, not here. + // Most STM32s manage ADC clocks in a similar way with ADCx_COMMON. + #[cfg(all(stm32f3, not(rcc_f37)))] + use crate::pac::adccommon::vals::Ckmode; + + #[cfg(all(stm32f3, not(rcc_f37)))] + let adc = { + #[cfg(peri_adc1_common)] + let common = crate::pac::ADC1_COMMON; + #[cfg(peri_adc12_common)] + let common = crate::pac::ADC12_COMMON; + + match config.adc { + AdcClockSource::Pll(adcpres) => { + RCC.cfgr2().modify(|w| w.set_adc12pres(adcpres)); + common.ccr().modify(|w| w.set_ckmode(Ckmode::ASYNCHRONOUS)); + + unwrap!(pll) / adcpres + } + AdcClockSource::Hclk(adcpres) => { + assert!(!(adcpres == AdcHclkPrescaler::Div1 && config.ahb_pre != AHBPrescaler::DIV1)); + + let (div, ckmode) = match adcpres { + AdcHclkPrescaler::Div1 => (1u32, Ckmode::SYNCDIV1), + AdcHclkPrescaler::Div2 => (2u32, Ckmode::SYNCDIV2), + AdcHclkPrescaler::Div4 => (4u32, Ckmode::SYNCDIV4), + }; + common.ccr().modify(|w| w.set_ckmode(ckmode)); + + hclk / div + } + } + }; + + #[cfg(all(stm32f3, not(rcc_f37), any(peri_adc3_common, peri_adc34_common)))] + let adc34 = { + #[cfg(peri_adc3_common)] + let common = crate::pac::ADC3_COMMON; + #[cfg(peri_adc34_common)] + let common = crate::pac::ADC34_COMMON; + + match config.adc34 { + AdcClockSource::Pll(adcpres) => { + RCC.cfgr2().modify(|w| w.set_adc34pres(adcpres)); + common.ccr().modify(|w| w.set_ckmode(Ckmode::ASYNCHRONOUS)); + + unwrap!(pll) / adcpres + } + AdcClockSource::Hclk(adcpres) => { + assert!(!(adcpres == AdcHclkPrescaler::Div1 && config.ahb_pre != AHBPrescaler::DIV1)); + + let (div, ckmode) = match adcpres { + AdcHclkPrescaler::Div1 => (1u32, Ckmode::SYNCDIV1), + AdcHclkPrescaler::Div2 => (2u32, Ckmode::SYNCDIV2), + AdcHclkPrescaler::Div4 => (4u32, Ckmode::SYNCDIV4), + }; + common.ccr().modify(|w| w.set_ckmode(ckmode)); + + hclk / div + } + } + }; + + /* + TODO: Maybe add something like this to clock_mux? How can we autogenerate the data for this? + let hrtim = match config.hrtim { + // Must be configured after the bus is ready, otherwise it won't work + HrtimClockSource::BusClk => None, + HrtimClockSource::PllClk => { + use crate::pac::rcc::vals::Timsw; + + // Make sure that we're using the PLL + let pll = unwrap!(pll); + assert!((pclk2 == pll) || (pclk2 * 2u32 == pll)); + + RCC.cfgr3().modify(|w| w.set_hrtim1sw(Timsw::PLL1_P)); + + Some(pll * 2u32) + } + }; + */ + + config.mux.init(); + + set_clocks!( + hsi: hsi, + hse: hse, + pll1_p: pll, + #[cfg(stm32f3)] + pll1_p_mul_2: pll_mul_2, + hsi_div_244: hsi.map(|h| h / 244u32), + sys: Some(sys), + pclk1: Some(pclk1), + pclk2: Some(pclk2), + pclk1_tim: Some(pclk1_tim), + pclk2_tim: Some(pclk2_tim), + hclk1: Some(hclk), + #[cfg(all(stm32f3, not(rcc_f37)))] + adc: Some(adc), + #[cfg(all(stm32f3, not(rcc_f37), any(peri_adc3_common, peri_adc34_common)))] + adc34: Some(adc34), + rtc: rtc, + hsi48: hsi48, + #[cfg(any(rcc_f1, rcc_f1cl, stm32f3))] + usb: usb, + lse: None, + ); +} + +#[cfg(stm32f0)] +mod max { + use core::ops::RangeInclusive; + + use crate::time::Hertz; + + pub(crate) const HSE_OSC: RangeInclusive = Hertz(4_000_000)..=Hertz(32_000_000); + pub(crate) const HSE_BYP: RangeInclusive = Hertz(1_000_000)..=Hertz(32_000_000); + + pub(crate) const HCLK: RangeInclusive = Hertz(0)..=Hertz(48_000_000); + pub(crate) const PCLK1: RangeInclusive = Hertz(0)..=Hertz(48_000_000); + + pub(crate) const PLL_IN: RangeInclusive = Hertz(1_000_000)..=Hertz(24_000_000); + pub(crate) const PLL_OUT: RangeInclusive = Hertz(16_000_000)..=Hertz(48_000_000); +} + +#[cfg(stm32f1)] +mod max { + use core::ops::RangeInclusive; + + use crate::time::Hertz; + + #[cfg(not(rcc_f1cl))] + pub(crate) const HSE_OSC: RangeInclusive = Hertz(4_000_000)..=Hertz(16_000_000); + #[cfg(not(rcc_f1cl))] + pub(crate) const HSE_BYP: RangeInclusive = Hertz(1_000_000)..=Hertz(25_000_000); + + #[cfg(rcc_f1cl)] + pub(crate) const HSE_OSC: RangeInclusive = Hertz(3_000_000)..=Hertz(25_000_000); + #[cfg(rcc_f1cl)] + pub(crate) const HSE_BYP: RangeInclusive = Hertz(1_000_000)..=Hertz(50_000_000); + + pub(crate) const HCLK: RangeInclusive = Hertz(0)..=Hertz(72_000_000); + pub(crate) const PCLK1: RangeInclusive = Hertz(0)..=Hertz(36_000_000); + pub(crate) const PCLK2: RangeInclusive = Hertz(0)..=Hertz(72_000_000); + + pub(crate) const PLL_IN: RangeInclusive = Hertz(1_000_000)..=Hertz(25_000_000); + pub(crate) const PLL_OUT: RangeInclusive = Hertz(16_000_000)..=Hertz(72_000_000); + + pub(crate) const ADC: RangeInclusive = Hertz(0)..=Hertz(14_000_000); +} + +#[cfg(stm32f3)] +mod max { + use core::ops::RangeInclusive; + + use crate::time::Hertz; + + pub(crate) const HSE_OSC: RangeInclusive = Hertz(4_000_000)..=Hertz(32_000_000); + pub(crate) const HSE_BYP: RangeInclusive = Hertz(1_000_000)..=Hertz(32_000_000); + + pub(crate) const HCLK: RangeInclusive = Hertz(0)..=Hertz(72_000_000); + pub(crate) const PCLK1: RangeInclusive = Hertz(0)..=Hertz(36_000_000); + pub(crate) const PCLK2: RangeInclusive = Hertz(0)..=Hertz(72_000_000); + + pub(crate) const PLL_IN: RangeInclusive = Hertz(1_000_000)..=Hertz(24_000_000); + pub(crate) const PLL_OUT: RangeInclusive = Hertz(16_000_000)..=Hertz(72_000_000); +} diff --git a/embassy-stm32/src/rcc/f1.rs b/embassy-stm32/src/rcc/f1.rs deleted file mode 100644 index 169551e45..000000000 --- a/embassy-stm32/src/rcc/f1.rs +++ /dev/null @@ -1,192 +0,0 @@ -use core::convert::TryFrom; - -use super::{set_freqs, Clocks}; -use crate::pac::flash::vals::Latency; -use crate::pac::rcc::vals::*; -use crate::pac::{FLASH, RCC}; -use crate::time::Hertz; - -/// HSI speed -pub const HSI_FREQ: Hertz = Hertz(8_000_000); - -/// Configuration of the clocks -/// -#[non_exhaustive] -#[derive(Default)] -pub struct Config { - pub hse: Option, - - pub sys_ck: Option, - pub hclk: Option, - pub pclk1: Option, - pub pclk2: Option, - pub adcclk: Option, - pub pllxtpre: bool, - - pub ls: super::LsConfig, -} - -pub(crate) unsafe fn init(config: Config) { - let pllxtpre_div = if config.pllxtpre { 2 } else { 1 }; - let pllsrcclk = config.hse.map(|hse| hse.0 / pllxtpre_div).unwrap_or(HSI_FREQ.0 / 2); - - let sysclk = config.sys_ck.map(|sys| sys.0).unwrap_or(pllsrcclk); - let pllmul = sysclk / pllsrcclk; - - let (pllmul_bits, real_sysclk) = if pllmul == 1 { - (None, config.hse.map(|hse| hse.0).unwrap_or(HSI_FREQ.0)) - } else { - let pllmul = core::cmp::min(core::cmp::max(pllmul, 1), 16); - (Some(pllmul as u8 - 2), pllsrcclk * pllmul) - }; - - assert!(real_sysclk <= 72_000_000); - - let hpre_bits = config - .hclk - .map(|hclk| match real_sysclk / hclk.0 { - 0 => unreachable!(), - 1 => 0b0111, - 2 => 0b1000, - 3..=5 => 0b1001, - 6..=11 => 0b1010, - 12..=39 => 0b1011, - 40..=95 => 0b1100, - 96..=191 => 0b1101, - 192..=383 => 0b1110, - _ => 0b1111, - }) - .unwrap_or(0b0111); - - let hclk = if hpre_bits >= 0b1100 { - real_sysclk / (1 << (hpre_bits - 0b0110)) - } else { - real_sysclk / (1 << (hpre_bits - 0b0111)) - }; - - assert!(hclk <= 72_000_000); - - let ppre1_bits = config - .pclk1 - .map(|pclk1| match hclk / pclk1.0 { - 0 => unreachable!(), - 1 => 0b011, - 2 => 0b100, - 3..=5 => 0b101, - 6..=11 => 0b110, - _ => 0b111, - }) - .unwrap_or(0b011); - - let ppre1 = 1 << (ppre1_bits - 0b011); - let pclk1 = hclk / u32::try_from(ppre1).unwrap(); - let timer_mul1 = if ppre1 == 1 { 1 } else { 2 }; - - assert!(pclk1 <= 36_000_000); - - let ppre2_bits = config - .pclk2 - .map(|pclk2| match hclk / pclk2.0 { - 0 => unreachable!(), - 1 => 0b011, - 2 => 0b100, - 3..=5 => 0b101, - 6..=11 => 0b110, - _ => 0b111, - }) - .unwrap_or(0b011); - - let ppre2 = 1 << (ppre2_bits - 0b011); - let pclk2 = hclk / u32::try_from(ppre2).unwrap(); - let timer_mul2 = if ppre2 == 1 { 1 } else { 2 }; - - assert!(pclk2 <= 72_000_000); - - FLASH.acr().write(|w| { - w.set_latency(if real_sysclk <= 24_000_000 { - Latency::WS0 - } else if real_sysclk <= 48_000_000 { - Latency::WS1 - } else { - Latency::WS2 - }); - // the prefetch buffer is enabled by default, let's keep it enabled - w.set_prftbe(true); - }); - - // the USB clock is only valid if an external crystal is used, the PLL is enabled, and the - // PLL output frequency is a supported one. - // usbpre == false: divide clock by 1.5, otherwise no division - #[cfg(not(rcc_f100))] - let (usbpre, _usbclk_valid) = match (config.hse, pllmul_bits, real_sysclk) { - (Some(_), Some(_), 72_000_000) => (false, true), - (Some(_), Some(_), 48_000_000) => (true, true), - _ => (true, false), - }; - - let apre_bits: u8 = config - .adcclk - .map(|adcclk| match pclk2 / adcclk.0 { - 0..=2 => 0b00, - 3..=4 => 0b01, - 5..=7 => 0b10, - _ => 0b11, - }) - .unwrap_or(0b11); - - let apre = (apre_bits + 1) << 1; - let adcclk = pclk2 / unwrap!(u32::try_from(apre)); - - assert!(adcclk <= 14_000_000); - - if config.hse.is_some() { - // enable HSE and wait for it to be ready - RCC.cr().modify(|w| w.set_hseon(true)); - while !RCC.cr().read().hserdy() {} - } - - if let Some(pllmul_bits) = pllmul_bits { - let pllctpre_flag: u8 = if config.pllxtpre { 1 } else { 0 }; - RCC.cfgr() - .modify(|w| w.set_pllxtpre(Pllxtpre::from_bits(pllctpre_flag))); - - // enable PLL and wait for it to be ready - RCC.cfgr().modify(|w| { - w.set_pllmul(Pllmul::from_bits(pllmul_bits)); - w.set_pllsrc(Pllsrc::from_bits(config.hse.is_some() as u8)); - }); - - RCC.cr().modify(|w| w.set_pllon(true)); - while !RCC.cr().read().pllrdy() {} - } - - // Only needed for stm32f103? - RCC.cfgr().modify(|w| { - w.set_adcpre(Adcpre::from_bits(apre_bits)); - w.set_ppre2(Ppre::from_bits(ppre2_bits)); - w.set_ppre1(Ppre::from_bits(ppre1_bits)); - w.set_hpre(Hpre::from_bits(hpre_bits)); - #[cfg(not(rcc_f100))] - w.set_usbpre(Usbpre::from_bits(usbpre as u8)); - w.set_sw(if pllmul_bits.is_some() { - Sw::PLL1_P - } else if config.hse.is_some() { - Sw::HSE - } else { - Sw::HSI - }); - }); - - let rtc = config.ls.init(); - - set_freqs(Clocks { - sys: Hertz(real_sysclk), - pclk1: Hertz(pclk1), - pclk2: Hertz(pclk2), - pclk1_tim: Hertz(pclk1 * timer_mul1), - pclk2_tim: Hertz(pclk2 * timer_mul2), - hclk1: Hertz(hclk), - adc: Some(Hertz(adcclk)), - rtc, - }); -} diff --git a/embassy-stm32/src/rcc/f.rs b/embassy-stm32/src/rcc/f247.rs similarity index 86% rename from embassy-stm32/src/rcc/f.rs rename to embassy-stm32/src/rcc/f247.rs index 36d9f178f..58056301a 100644 --- a/embassy-stm32/src/rcc/f.rs +++ b/embassy-stm32/src/rcc/f247.rs @@ -7,7 +7,6 @@ pub use crate::pac::rcc::vals::{ #[cfg(any(stm32f4, stm32f7))] use crate::pac::PWR; use crate::pac::{FLASH, RCC}; -use crate::rcc::{set_freqs, Clocks}; use crate::time::Hertz; // TODO: on some F4s, PLLM is shared between all PLLs. Enforce that. @@ -64,6 +63,7 @@ pub struct Pll { /// Used to calculate flash waitstates. See /// RM0033 - Table 3. Number of wait states according to Cortex®-M3 clock frequency #[cfg(stm32f2)] +#[derive(Clone, Copy)] pub enum VoltageScale { /// 2.7 to 3.6 V Range0, @@ -77,6 +77,7 @@ pub enum VoltageScale { /// Configuration of the core clocks #[non_exhaustive] +#[derive(Clone, Copy)] pub struct Config { pub hsi: bool, pub hse: Option, @@ -96,6 +97,9 @@ pub struct Config { pub ls: super::LsConfig, + /// Per-peripheral kernel clock selection muxes + pub mux: super::mux::ClockMux, + #[cfg(stm32f2)] pub voltage: VoltageScale, } @@ -121,6 +125,7 @@ impl Default for Config { #[cfg(stm32f2)] voltage: VoltageScale::Range3, + mux: Default::default(), } } } @@ -143,17 +148,18 @@ pub(crate) unsafe fn init(config: Config) { while !PWR.csr1().read().odswrdy() {} } + // Turn on the HSI + RCC.cr().modify(|w| w.set_hsion(true)); + while !RCC.cr().read().hsirdy() {} + + // Use the HSI clock as system clock during the actual clock setup + RCC.cfgr().modify(|w| w.set_sw(Sysclk::HSI)); + while RCC.cfgr().read().sws() != Sysclk::HSI {} + // Configure HSI let hsi = match config.hsi { - false => { - RCC.cr().modify(|w| w.set_hsion(false)); - None - } - true => { - RCC.cr().modify(|w| w.set_hsion(true)); - while !RCC.cr().read().hsirdy() {} - Some(HSI_FREQ) - } + false => None, + true => Some(HSI_FREQ), }; // Configure HSE @@ -183,9 +189,9 @@ pub(crate) unsafe fn init(config: Config) { }; let pll = init_pll(PllInstance::Pll, config.pll, &pll_input); #[cfg(any(stm32f2, all(stm32f4, not(stm32f410)), stm32f7))] - let _plli2s = init_pll(PllInstance::Plli2s, config.plli2s, &pll_input); + let plli2s = init_pll(PllInstance::Plli2s, config.plli2s, &pll_input); #[cfg(any(stm32f446, stm32f427, stm32f437, stm32f4x9, stm32f7))] - let _pllsai = init_pll(PllInstance::Pllsai, config.pllsai, &pll_input); + let pllsai = init_pll(PllInstance::Pllsai, config.pllsai, &pll_input); // Configure sysclk let sys = match config.sys { @@ -257,27 +263,55 @@ pub(crate) unsafe fn init(config: Config) { }); while RCC.cfgr().read().sws() != config.sys {} - set_freqs(Clocks { - sys, - hclk1: hclk, - hclk2: hclk, - hclk3: hclk, - pclk1, - pclk2, - pclk1_tim, - pclk2_tim, - rtc, - pll1_q: pll.q, - #[cfg(all(rcc_f4, not(stm32f410)))] - plli2s1_q: _plli2s.q, - #[cfg(all(rcc_f4, not(stm32f410)))] - plli2s1_r: _plli2s.r, + // Disable HSI if not used + if !config.hsi { + RCC.cr().modify(|w| w.set_hsion(false)); + } - #[cfg(any(stm32f427, stm32f429, stm32f437, stm32f439, stm32f446, stm32f469, stm32f479))] - pllsai1_q: _pllsai.q, - #[cfg(any(stm32f427, stm32f429, stm32f437, stm32f439, stm32f446, stm32f469, stm32f479))] - pllsai1_r: _pllsai.r, - }); + config.mux.init(); + + set_clocks!( + hsi: hsi, + hse: hse, + lse: None, // TODO + lsi: None, // TODO + sys: Some(sys), + hclk1: Some(hclk), + hclk2: Some(hclk), + hclk3: Some(hclk), + pclk1: Some(pclk1), + pclk2: Some(pclk2), + pclk1_tim: Some(pclk1_tim), + pclk2_tim: Some(pclk2_tim), + rtc: rtc, + pll1_q: pll.q, + pll1_r: pll.r, + + #[cfg(any(stm32f2, all(stm32f4, not(stm32f410)), stm32f7))] + plli2s1_p: plli2s.p, + #[cfg(any(stm32f2, all(stm32f4, not(stm32f410)), stm32f7))] + plli2s1_q: plli2s.q, + #[cfg(any(stm32f2, all(stm32f4, not(stm32f410)), stm32f7))] + plli2s1_r: plli2s.r, + + #[cfg(any(stm32f446, stm32f427, stm32f437, stm32f4x9, stm32f7))] + pllsai1_p: pllsai.p, + #[cfg(any(stm32f446, stm32f427, stm32f437, stm32f4x9, stm32f7))] + pllsai1_q: pllsai.q, + #[cfg(any(stm32f446, stm32f427, stm32f437, stm32f4x9, stm32f7))] + pllsai1_r: pllsai.r, + + // TODO workaround until f4 rcc is fixed in stm32-data + #[cfg(not(any(stm32f446, stm32f427, stm32f437, stm32f4x9, stm32f7)))] + pllsai1_q: None, + + #[cfg(dsihost)] + dsi_phy: None, // DSI PLL clock not supported, don't call `RccPeripheral::frequency()` in the drivers + + hsi_div488: hsi.map(|hsi| hsi/488u32), + hsi_hse: None, + afif: None, + ); } struct PllInput { diff --git a/embassy-stm32/src/rcc/f3.rs b/embassy-stm32/src/rcc/f3.rs deleted file mode 100644 index bf035fd25..000000000 --- a/embassy-stm32/src/rcc/f3.rs +++ /dev/null @@ -1,459 +0,0 @@ -#[cfg(rcc_f3)] -use crate::pac::adccommon::vals::Ckmode; -use crate::pac::flash::vals::Latency; -pub use crate::pac::rcc::vals::Adcpres; -use crate::pac::rcc::vals::{Hpre, Pllmul, Pllsrc, Ppre, Prediv, Sw, Usbpre}; -use crate::pac::{FLASH, RCC}; -use crate::rcc::{set_freqs, Clocks}; -use crate::time::Hertz; - -/// HSI speed -pub const HSI_FREQ: Hertz = Hertz(8_000_000); - -#[cfg(rcc_f3)] -impl From for Ckmode { - fn from(value: AdcClockSource) -> Self { - match value { - AdcClockSource::BusDiv1 => Ckmode::SYNCDIV1, - AdcClockSource::BusDiv2 => Ckmode::SYNCDIV2, - AdcClockSource::BusDiv4 => Ckmode::SYNCDIV4, - _ => unreachable!(), - } - } -} - -#[derive(Clone, Copy)] -pub enum AdcClockSource { - Pll(Adcpres), - BusDiv1, - BusDiv2, - BusDiv4, -} - -impl AdcClockSource { - pub fn bus_div(&self) -> u32 { - match self { - Self::BusDiv1 => 1, - Self::BusDiv2 => 2, - Self::BusDiv4 => 4, - _ => unreachable!(), - } - } -} - -#[derive(Default)] -pub enum HrtimClockSource { - #[default] - BusClk, - PllClk, -} - -/// Clocks configutation -#[non_exhaustive] -#[derive(Default)] -pub struct Config { - /// Frequency of HSE oscillator - /// 4MHz to 32MHz - pub hse: Option, - /// Bypass HSE for an external clock - pub bypass_hse: bool, - /// Frequency of the System Clock - pub sysclk: Option, - /// Frequency of AHB bus - pub hclk: Option, - /// Frequency of APB1 bus - /// - Max frequency 36MHz - pub pclk1: Option, - /// Frequency of APB2 bus - /// - Max frequency with HSE is 72MHz - /// - Max frequency without HSE is 64MHz - pub pclk2: Option, - /// USB clock setup - /// It is valid only when, - /// - HSE is enabled, - /// - The System clock frequency is either 48MHz or 72MHz - /// - APB1 clock has a minimum frequency of 10MHz - pub pll48: bool, - #[cfg(rcc_f3)] - /// ADC clock setup - /// - For AHB, a psc of 4 or less must be used - pub adc: Option, - #[cfg(rcc_f3)] - /// ADC clock setup - /// - For AHB, a psc of 4 or less must be used - pub adc34: Option, - #[cfg(stm32f334)] - pub hrtim: HrtimClockSource, - pub ls: super::LsConfig, -} - -// Information required to setup the PLL clock -#[derive(Clone, Copy)] -struct PllConfig { - pll_src: Pllsrc, - pll_mul: Pllmul, - pll_div: Option, -} - -/// Initialize and Set the clock frequencies -pub(crate) unsafe fn init(config: Config) { - // Calculate the real System clock, and PLL configuration if applicable - let (sysclk, pll_config) = get_sysclk(&config); - assert!(sysclk.0 <= 72_000_000); - - // Calculate real AHB clock - let hclk = config.hclk.map(|h| h).unwrap_or(sysclk); - let hpre = match sysclk.0 / hclk.0 { - 0 => unreachable!(), - 1 => Hpre::DIV1, - 2 => Hpre::DIV2, - 3..=5 => Hpre::DIV4, - 6..=11 => Hpre::DIV8, - 12..=39 => Hpre::DIV16, - 40..=95 => Hpre::DIV64, - 96..=191 => Hpre::DIV128, - 192..=383 => Hpre::DIV256, - _ => Hpre::DIV512, - }; - let hclk = sysclk / hpre; - assert!(hclk <= Hertz(72_000_000)); - - // Calculate real APB1 clock - let pclk1 = config.pclk1.unwrap_or(hclk); - let ppre1 = match hclk / pclk1 { - 0 => unreachable!(), - 1 => Ppre::DIV1, - 2 => Ppre::DIV2, - 3..=5 => Ppre::DIV4, - 6..=11 => Ppre::DIV8, - _ => Ppre::DIV16, - }; - let timer_mul1 = if ppre1 == Ppre::DIV1 { 1u32 } else { 2 }; - let pclk1 = hclk / ppre1; - assert!(pclk1 <= Hertz(36_000_000)); - - // Calculate real APB2 clock - let pclk2 = config.pclk2.unwrap_or(hclk); - let ppre2 = match hclk / pclk2 { - 0 => unreachable!(), - 1 => Ppre::DIV1, - 2 => Ppre::DIV2, - 3..=5 => Ppre::DIV4, - 6..=11 => Ppre::DIV8, - _ => Ppre::DIV16, - }; - let timer_mul2 = if ppre2 == Ppre::DIV1 { 1u32 } else { 2 }; - let pclk2 = hclk / ppre2; - assert!(pclk2 <= Hertz(72_000_000)); - - // Set latency based on HCLK frquency - // RM0316: "The prefetch buffer must be kept on when using a prescaler - // different from 1 on the AHB clock.", "Half-cycle access cannot be - // used when there is a prescaler different from 1 on the AHB clock" - FLASH.acr().modify(|w| { - w.set_latency(if hclk <= Hertz(24_000_000) { - Latency::WS0 - } else if hclk <= Hertz(48_000_000) { - Latency::WS1 - } else { - Latency::WS2 - }); - if hpre != Hpre::DIV1 { - w.set_hlfcya(false); - w.set_prftbe(true); - } - }); - - // Enable HSE - // RM0316: "Bits 31:26 Reserved, must be kept at reset value." - if config.hse.is_some() { - RCC.cr().modify(|w| { - w.set_hsebyp(config.bypass_hse); - // We turn on clock security to switch to HSI when HSE fails - w.set_csson(true); - w.set_hseon(true); - }); - while !RCC.cr().read().hserdy() {} - } - - // Enable PLL - // RM0316: "Reserved, must be kept at reset value." - if let Some(ref pll_config) = pll_config { - RCC.cfgr().modify(|w| { - w.set_pllmul(pll_config.pll_mul); - w.set_pllsrc(pll_config.pll_src); - }); - if let Some(pll_div) = pll_config.pll_div { - RCC.cfgr2().modify(|w| w.set_prediv(pll_div)); - } - RCC.cr().modify(|w| w.set_pllon(true)); - while !RCC.cr().read().pllrdy() {} - } - - // CFGR has been written before (PLL) don't overwrite these settings - if config.pll48 { - let usb_pre = get_usb_pre(&config, sysclk, pclk1, &pll_config); - RCC.cfgr().modify(|w| { - w.set_usbpre(usb_pre); - }); - } - - // Set prescalers - // CFGR has been written before (PLL, PLL48) don't overwrite these settings - RCC.cfgr().modify(|w| { - w.set_ppre2(ppre2); - w.set_ppre1(ppre1); - w.set_hpre(hpre); - }); - - // Wait for the new prescalers to kick in - // "The clocks are divided with the new prescaler factor from - // 1 to 16 AHB cycles after write" - cortex_m::asm::delay(16); - - // CFGR has been written before (PLL, PLL48, clock divider) don't overwrite these settings - RCC.cfgr().modify(|w| { - w.set_sw(match (pll_config, config.hse) { - (Some(_), _) => Sw::PLL1_P, - (None, Some(_)) => Sw::HSE, - (None, None) => Sw::HSI, - }) - }); - - #[cfg(rcc_f3)] - let adc = config.adc.map(|adc| match adc { - AdcClockSource::Pll(adcpres) => { - RCC.cfgr2().modify(|w| { - // Make sure that we're using the PLL - pll_config.unwrap(); - w.set_adc12pres(adcpres); - - sysclk / adcpres - }) - } - _ => crate::pac::ADC_COMMON.ccr().modify(|w| { - assert!(!(adc.bus_div() == 1 && hpre != Hpre::DIV1)); - - w.set_ckmode(adc.into()); - - sysclk / adc.bus_div() - }), - }); - - #[cfg(all(rcc_f3, adc3_common))] - let adc34 = config.adc34.map(|adc| match adc { - AdcClockSource::Pll(adcpres) => { - RCC.cfgr2().modify(|w| { - // Make sure that we're using the PLL - pll_config.unwrap(); - w.set_adc34pres(adcpres); - - sysclk / adcpres - }) - } - _ => crate::pac::ADC_COMMON.ccr().modify(|w| { - assert!(!(adc.bus_div() == 1 && hpre != Hpre::DIV1)); - - w.set_ckmode(adc.into()); - - sysclk / adc.bus_div() - }), - }); - - #[cfg(stm32f334)] - let hrtim = match config.hrtim { - // Must be configured after the bus is ready, otherwise it won't work - HrtimClockSource::BusClk => None, - HrtimClockSource::PllClk => { - use crate::pac::rcc::vals::Timsw; - - // Make sure that we're using the PLL - pll_config.unwrap(); - assert!((pclk2 == sysclk) || (pclk2 * 2u32 == sysclk)); - - RCC.cfgr3().modify(|w| w.set_hrtim1sw(Timsw::PLL1_P)); - - Some(sysclk * 2u32) - } - }; - - let rtc = config.ls.init(); - - set_freqs(Clocks { - sys: sysclk, - pclk1: pclk1, - pclk2: pclk2, - pclk1_tim: pclk1 * timer_mul1, - pclk2_tim: pclk2 * timer_mul2, - hclk1: hclk, - #[cfg(rcc_f3)] - adc: adc, - #[cfg(all(rcc_f3, adc3_common))] - adc34: adc34, - #[cfg(all(rcc_f3, not(adc3_common)))] - adc34: None, - #[cfg(stm32f334)] - hrtim: hrtim, - rtc, - }); -} - -#[inline] -fn get_sysclk(config: &Config) -> (Hertz, Option) { - match (config.sysclk, config.hse) { - (Some(sysclk), Some(hse)) if sysclk == hse => (hse, None), - (Some(sysclk), None) if sysclk == HSI_FREQ => (HSI_FREQ, None), - // If the user selected System clock is different from HSI or HSE - // we will have to setup PLL clock source - (Some(sysclk), _) => { - let (sysclk, pll_config) = calc_pll(config, sysclk); - (sysclk, Some(pll_config)) - } - (None, Some(hse)) => (hse, None), - (None, None) => (HSI_FREQ, None), - } -} - -#[inline] -fn calc_pll(config: &Config, Hertz(sysclk): Hertz) -> (Hertz, PllConfig) { - // Calculates the Multiplier and the Divisor to arrive at - // the required System clock from PLL source frequency - let get_mul_div = |sysclk, pllsrcclk| { - let bus_div = gcd(sysclk, pllsrcclk); - let mut multiplier = sysclk / bus_div; - let mut divisor = pllsrcclk / bus_div; - // Minimum PLL multiplier is two - if multiplier == 1 { - multiplier *= 2; - divisor *= 2; - } - assert!(multiplier <= 16); - assert!(divisor <= 16); - (multiplier, divisor) - }; - // Based on the source of Pll, we calculate the actual system clock - // frequency, PLL's source identifier, multiplier and divisor - let (act_sysclk, pll_src, pll_mul, pll_div) = match config.hse { - Some(Hertz(hse)) => { - let (multiplier, divisor) = get_mul_div(sysclk, hse); - ( - Hertz((hse / divisor) * multiplier), - Pllsrc::HSE_DIV_PREDIV, - into_pll_mul(multiplier), - Some(into_pre_div(divisor)), - ) - } - None => { - cfg_if::cfg_if! { - // For some chips PREDIV is always two, and cannot be changed - if #[cfg(any(flashsize_d, flashsize_e))] { - let (multiplier, divisor) = get_mul_div(sysclk, HSI_FREQ.0); - ( - Hertz((HSI_FREQ.0 / divisor) * multiplier), - Pllsrc::HSI_DIV_PREDIV, - into_pll_mul(multiplier), - Some(into_pre_div(divisor)), - ) - } else { - let pllsrcclk = HSI_FREQ.0 / 2; - let multiplier = sysclk / pllsrcclk; - assert!(multiplier <= 16); - ( - Hertz(pllsrcclk * multiplier), - Pllsrc::HSI_DIV2, - into_pll_mul(multiplier), - None, - ) - } - } - } - }; - ( - act_sysclk, - PllConfig { - pll_src, - pll_mul, - pll_div, - }, - ) -} - -#[inline] -#[allow(unused_variables)] -fn get_usb_pre(config: &Config, sysclk: Hertz, pclk1: Hertz, pll_config: &Option) -> Usbpre { - cfg_if::cfg_if! { - // Some chips do not have USB - if #[cfg(any(stm32f301, stm32f318, stm32f334))] { - panic!("USB clock not supported by the chip"); - } else { - let usb_ok = config.hse.is_some() && pll_config.is_some() && (pclk1 >= Hertz(10_000_000)); - match (usb_ok, sysclk) { - (true, Hertz(72_000_000)) => Usbpre::DIV1_5, - (true, Hertz(48_000_000)) => Usbpre::DIV1, - _ => panic!( - "USB clock is only valid if the PLL output frequency is either 48MHz or 72MHz" - ), - } - } - } -} - -// This function assumes cases when multiplier is one and it -// being greater than 16 is made impossible -#[inline] -fn into_pll_mul(multiplier: u32) -> Pllmul { - match multiplier { - 2 => Pllmul::MUL2, - 3 => Pllmul::MUL3, - 4 => Pllmul::MUL4, - 5 => Pllmul::MUL5, - 6 => Pllmul::MUL6, - 7 => Pllmul::MUL7, - 8 => Pllmul::MUL8, - 9 => Pllmul::MUL9, - 10 => Pllmul::MUL10, - 11 => Pllmul::MUL11, - 12 => Pllmul::MUL12, - 13 => Pllmul::MUL13, - 14 => Pllmul::MUL14, - 15 => Pllmul::MUL15, - 16 => Pllmul::MUL16, - _ => unreachable!(), - } -} - -// This function assumes the incoming divisor cannot be greater -// than 16 -#[inline] -fn into_pre_div(divisor: u32) -> Prediv { - match divisor { - 1 => Prediv::DIV1, - 2 => Prediv::DIV2, - 3 => Prediv::DIV3, - 4 => Prediv::DIV4, - 5 => Prediv::DIV5, - 6 => Prediv::DIV6, - 7 => Prediv::DIV7, - 8 => Prediv::DIV8, - 9 => Prediv::DIV9, - 10 => Prediv::DIV10, - 11 => Prediv::DIV11, - 12 => Prediv::DIV12, - 13 => Prediv::DIV13, - 14 => Prediv::DIV14, - 15 => Prediv::DIV15, - 16 => Prediv::DIV16, - _ => unreachable!(), - } -} - -// Determine GCD using Euclidean algorithm -#[inline] -fn gcd(mut a: u32, mut b: u32) -> u32 { - while b != 0 { - let r = a % b; - a = b; - b = r; - } - a -} diff --git a/embassy-stm32/src/rcc/g0.rs b/embassy-stm32/src/rcc/g0.rs index b38fe1dcc..c53c83b0e 100644 --- a/embassy-stm32/src/rcc/g0.rs +++ b/embassy-stm32/src/rcc/g0.rs @@ -1,15 +1,16 @@ use crate::pac::flash::vals::Latency; -use crate::pac::rcc::vals::{self, Sw}; +pub use crate::pac::pwr::vals::Vos as VoltageRange; pub use crate::pac::rcc::vals::{ - Hpre as AHBPrescaler, Hsidiv as HSIPrescaler, Pllm, Plln, Pllp, Pllq, Pllr, Ppre as APBPrescaler, + Hpre as AHBPrescaler, Pllm as PllPreDiv, Plln as PllMul, Pllp as PllPDiv, Pllq as PllQDiv, Pllr as PllRDiv, + Pllsrc as PllSource, Ppre as APBPrescaler, Sw as Sysclk, }; use crate::pac::{FLASH, PWR, RCC}; -use crate::rcc::{set_freqs, Clocks}; use crate::time::Hertz; /// HSI speed pub const HSI_FREQ: Hertz = Hertz(16_000_000); +/// HSE Mode #[derive(Clone, Copy, Eq, PartialEq)] pub enum HseMode { /// crystal/ceramic oscillator (HSEBYP=0) @@ -18,353 +19,300 @@ pub enum HseMode { Bypass, } -/// System clock mux source -#[derive(Clone, Copy)] -pub enum ClockSrc { - HSE(Hertz, HseMode), - HSI(HSIPrescaler), - PLL(PllConfig), - LSI, -} - -/// The PLL configuration. -/// -/// * `VCOCLK = source / m * n` -/// * `PLLRCLK = VCOCLK / r` -/// * `PLLQCLK = VCOCLK / q` -/// * `PLLPCLK = VCOCLK / p` -#[derive(Clone, Copy)] -pub struct PllConfig { - /// The source from which the PLL receives a clock signal - pub source: PllSource, - /// The initial divisor of that clock signal - pub m: Pllm, - /// The PLL VCO multiplier, which must be in the range `8..=86`. - pub n: Plln, - /// The final divisor for `PLLRCLK` output which drives the system clock - pub r: Pllr, - - /// The divisor for the `PLLQCLK` output, if desired - pub q: Option, - - /// The divisor for the `PLLPCLK` output, if desired - pub p: Option, -} - -impl Default for PllConfig { - #[inline] - fn default() -> PllConfig { - // HSI / 1 * 8 / 2 = 64 MHz - PllConfig { - source: PllSource::HSI, - m: Pllm::DIV1, - n: Plln::MUL8, - r: Pllr::DIV2, - q: None, - p: None, - } - } -} - +/// HSE Configuration #[derive(Clone, Copy, Eq, PartialEq)] -pub enum PllSource { - HSI, - HSE(Hertz, HseMode), +pub struct Hse { + /// HSE frequency. + pub freq: Hertz, + /// HSE mode. + pub mode: HseMode, } -/// Sets the source for the 48MHz clock to the USB peripheral. -#[cfg(any(stm32g0b1, stm32g0c1, stm32g0b0))] -pub enum UsbSrc { - /// Use the High Speed Internal Oscillator. The CRS must be used to calibrate the - /// oscillator to comply with the USB specification for oscillator tolerance. - #[cfg(any(stm32g0b1, stm32g0c1))] - Hsi48(super::Hsi48Config), - /// Use the PLLQ output. The PLL must be configured to output a 48MHz clock. The - /// PLL needs to be using the HSE source to comply with the USB specification for oscillator - /// tolerance. - PllQ, - /// Use the HSE source directly. The HSE must be a 48MHz source. The HSE source must comply - /// with the USB specification for oscillator tolerance. - HSE, +/// PLL Configuration +/// +/// Use this struct to configure the PLL source, input frequency, multiplication factor, and output +/// dividers. Be sure to keep check the datasheet for your specific part for the appropriate +/// frequency ranges for each of these settings. +#[derive(Clone, Copy)] +pub struct Pll { + /// PLL Source clock selection. + pub source: PllSource, + + /// PLL pre-divider + pub prediv: PllPreDiv, + + /// PLL multiplication factor for VCO + pub mul: PllMul, + + /// PLL division factor for P clock (ADC Clock) + pub divp: Option, + + /// PLL division factor for Q clock (USB, I2S23, SAI1, FDCAN, QSPI) + pub divq: Option, + + /// PLL division factor for R clock (SYSCLK) + pub divr: Option, } /// Clocks configutation +#[non_exhaustive] +#[derive(Clone, Copy)] pub struct Config { - pub mux: ClockSrc, + /// HSI Enable + pub hsi: bool, + + /// HSE Configuration + pub hse: Option, + + /// System Clock Configuration + pub sys: Sysclk, + + /// HSI48 Configuration + #[cfg(crs)] + pub hsi48: Option, + + /// PLL Configuration + pub pll: Option, + + /// If PLL is requested as the main clock source in the `sys` field then the PLL configuration + /// MUST turn on the PLLR output. pub ahb_pre: AHBPrescaler, - pub apb_pre: APBPrescaler, - pub low_power_run: bool, + pub apb1_pre: APBPrescaler, + + /// Low-Speed Clock Configuration pub ls: super::LsConfig, - #[cfg(any(stm32g0b1, stm32g0c1, stm32g0b0))] - pub usb_src: Option, + + pub low_power_run: bool, + + pub voltage_range: VoltageRange, + + /// Per-peripheral kernel clock selection muxes + pub mux: super::mux::ClockMux, } impl Default for Config { #[inline] fn default() -> Config { Config { - mux: ClockSrc::HSI(HSIPrescaler::DIV1), + hsi: true, + hse: None, + sys: Sysclk::HSI, + #[cfg(crs)] + hsi48: Some(Default::default()), + pll: None, ahb_pre: AHBPrescaler::DIV1, - apb_pre: APBPrescaler::DIV1, + apb1_pre: APBPrescaler::DIV1, low_power_run: false, ls: Default::default(), - #[cfg(any(stm32g0b1, stm32g0c1, stm32g0b0))] - usb_src: None, + voltage_range: VoltageRange::RANGE1, + mux: Default::default(), } } } -impl PllConfig { - pub(crate) fn init(self) -> (Hertz, Option, Option) { - let (src, input_freq) = match self.source { - PllSource::HSI => (vals::Pllsrc::HSI, HSI_FREQ), - PllSource::HSE(freq, _) => (vals::Pllsrc::HSE, freq), - }; - - let m_freq = input_freq / self.m; - // RM0454 § 5.4.4: - // > Caution: The software must set these bits so that the PLL input frequency after the - // > /M divider is between 2.66 and 16 MHz. - debug_assert!(m_freq.0 >= 2_660_000 && m_freq.0 <= 16_000_000); - - let n_freq = m_freq * self.n as u32; - // RM0454 § 5.4.4: - // > Caution: The software must set these bits so that the VCO output frequency is between - // > 64 and 344 MHz. - debug_assert!(n_freq.0 >= 64_000_000 && n_freq.0 <= 344_000_000); - - let r_freq = n_freq / self.r; - // RM0454 § 5.4.4: - // > Caution: The software must set this bitfield so as not to exceed 64 MHz on this clock. - debug_assert!(r_freq.0 <= 64_000_000); - - let q_freq = self.q.map(|q| n_freq / q); - let p_freq = self.p.map(|p| n_freq / p); - - // RM0454 § 5.2.3: - // > To modify the PLL configuration, proceed as follows: - // > 1. Disable the PLL by setting PLLON to 0 in Clock control register (RCC_CR). - RCC.cr().modify(|w| w.set_pllon(false)); - - // > 2. Wait until PLLRDY is cleared. The PLL is now fully stopped. - while RCC.cr().read().pllrdy() {} - - // > 3. Change the desired parameter. - // Enable whichever clock source we're using, and wait for it to become ready - match self.source { - PllSource::HSI => { - RCC.cr().write(|w| w.set_hsion(true)); - while !RCC.cr().read().hsirdy() {} - } - PllSource::HSE(_, mode) => { - RCC.cr().write(|w| { - w.set_hsebyp(mode != HseMode::Oscillator); - w.set_hseon(true); - }); - while !RCC.cr().read().hserdy() {} - } - } - - // Configure PLLCFGR - RCC.pllcfgr().modify(|w| { - w.set_pllr(self.r); - w.set_pllren(false); - w.set_pllq(self.q.unwrap_or(Pllq::DIV2)); - w.set_pllqen(false); - w.set_pllp(self.p.unwrap_or(Pllp::DIV2)); - w.set_pllpen(false); - w.set_plln(self.n); - w.set_pllm(self.m); - w.set_pllsrc(src) - }); - - // > 4. Enable the PLL again by setting PLLON to 1. - RCC.cr().modify(|w| w.set_pllon(true)); - - // Wait for the PLL to become ready - while !RCC.cr().read().pllrdy() {} - - // > 5. Enable the desired PLL outputs by configuring PLLPEN, PLLQEN, and PLLREN in PLL - // > configuration register (RCC_PLLCFGR). - RCC.pllcfgr().modify(|w| { - // We'll use R for system clock, so enable that unconditionally - w.set_pllren(true); - - // We may also use Q or P - w.set_pllqen(self.q.is_some()); - w.set_pllpen(self.p.is_some()); - }); - - (r_freq, q_freq, p_freq) - } +#[derive(Default)] +pub struct PllFreq { + pub pll_p: Option, + pub pll_q: Option, + pub pll_r: Option, } pub(crate) unsafe fn init(config: Config) { - let mut pll1_q_freq = None; - let mut pll1_p_freq = None; + // Turn on the HSI + RCC.cr().modify(|w| w.set_hsion(true)); + while !RCC.cr().read().hsirdy() {} - let (sys_clk, sw) = match config.mux { - ClockSrc::HSI(div) => { - // Enable HSI - RCC.cr().write(|w| { - w.set_hsidiv(div); - w.set_hsion(true) - }); - while !RCC.cr().read().hsirdy() {} + // Use the HSI clock as system clock during the actual clock setup + RCC.cfgr().modify(|w| w.set_sw(Sysclk::HSI)); + while RCC.cfgr().read().sws() != Sysclk::HSI {} - (HSI_FREQ / div, Sw::HSI) - } - ClockSrc::HSE(freq, mode) => { - // Enable HSE - RCC.cr().write(|w| { - w.set_hseon(true); - w.set_hsebyp(mode != HseMode::Oscillator); - }); - while !RCC.cr().read().hserdy() {} - - (freq, Sw::HSE) - } - ClockSrc::PLL(pll) => { - let (r_freq, q_freq, p_freq) = pll.init(); - - pll1_q_freq = q_freq; - pll1_p_freq = p_freq; - - (r_freq, Sw::PLL1_R) - } - ClockSrc::LSI => { - // Enable LSI - RCC.csr().write(|w| w.set_lsion(true)); - while !RCC.csr().read().lsirdy() {} - (super::LSI_FREQ, Sw::LSI) - } + // Configure HSI + let hsi = match config.hsi { + false => None, + true => Some(HSI_FREQ), }; - // Determine the flash latency implied by the target clock speed - // RM0454 § 3.3.4: - let target_flash_latency = if sys_clk.0 <= 24_000_000 { - Latency::WS0 - } else if sys_clk.0 <= 48_000_000 { - Latency::WS1 - } else { - Latency::WS2 - }; - - // Increase the number of cycles we wait for flash if the new value is higher - // There's no harm in waiting a little too much before the clock change, but we'll - // crash immediately if we don't wait enough after the clock change - let mut set_flash_latency_after = false; - FLASH.acr().modify(|w| { - // Is the current flash latency less than what we need at the new SYSCLK? - if w.latency().to_bits() <= target_flash_latency.to_bits() { - // We must increase the number of wait states now - w.set_latency(target_flash_latency) - } else { - // We may decrease the number of wait states later - set_flash_latency_after = true; + // Configure HSE + let hse = match config.hse { + None => { + RCC.cr().modify(|w| w.set_hseon(false)); + None } - - // RM0454 § 3.3.5: - // > Prefetch is enabled by setting the PRFTEN bit of the FLASH access control register - // > (FLASH_ACR). This feature is useful if at least one wait state is needed to access the - // > Flash memory. - // - // Enable flash prefetching if we have at least one wait state, and disable it otherwise. - w.set_prften(target_flash_latency.to_bits() > 0); - }); - - if !set_flash_latency_after { - // Spin until the effective flash latency is compatible with the clock change - while FLASH.acr().read().latency().to_bits() < target_flash_latency.to_bits() {} - } - - // Configure SYSCLK source, HCLK divisor, and PCLK divisor all at once - let (sw, hpre, ppre) = (sw.into(), config.ahb_pre, config.apb_pre); - RCC.cfgr().modify(|w| { - w.set_sw(sw); - w.set_hpre(hpre); - w.set_ppre(ppre); - }); - - if set_flash_latency_after { - // We can make the flash require fewer wait states - // Spin until the SYSCLK changes have taken effect - loop { - let cfgr = RCC.cfgr().read(); - if cfgr.sw() == sw && cfgr.hpre() == hpre && cfgr.ppre() == ppre { - break; + Some(hse) => { + match hse.mode { + HseMode::Bypass => assert!(max::HSE_BYP.contains(&hse.freq)), + HseMode::Oscillator => assert!(max::HSE_OSC.contains(&hse.freq)), } - } - // Set the flash latency to require fewer wait states - FLASH.acr().modify(|w| w.set_latency(target_flash_latency)); - } - - let ahb_freq = sys_clk / config.ahb_pre; - - let (apb_freq, apb_tim_freq) = match config.apb_pre { - APBPrescaler::DIV1 => (ahb_freq, ahb_freq), - pre => { - let freq = ahb_freq / pre; - (freq, freq * 2u32) + RCC.cr().modify(|w| w.set_hsebyp(hse.mode != HseMode::Oscillator)); + RCC.cr().modify(|w| w.set_hseon(true)); + while !RCC.cr().read().hserdy() {} + Some(hse.freq) } }; + // Configure HSI48 if required + #[cfg(crs)] + let hsi48 = config.hsi48.map(super::init_hsi48); + + let pll = config + .pll + .map(|pll_config| { + let src_freq = match pll_config.source { + PllSource::HSI => unwrap!(hsi), + PllSource::HSE => unwrap!(hse), + _ => unreachable!(), + }; + + // Disable PLL before configuration + RCC.cr().modify(|w| w.set_pllon(false)); + while RCC.cr().read().pllrdy() {} + + let in_freq = src_freq / pll_config.prediv; + assert!(max::PLL_IN.contains(&in_freq)); + let internal_freq = in_freq * pll_config.mul; + + assert!(max::PLL_VCO.contains(&internal_freq)); + + RCC.pllcfgr().write(|w| { + w.set_plln(pll_config.mul); + w.set_pllm(pll_config.prediv); + w.set_pllsrc(pll_config.source.into()); + }); + + let pll_p_freq = pll_config.divp.map(|div_p| { + RCC.pllcfgr().modify(|w| { + w.set_pllp(div_p); + w.set_pllpen(true); + }); + let freq = internal_freq / div_p; + assert!(max::PLL_P.contains(&freq)); + freq + }); + + let pll_q_freq = pll_config.divq.map(|div_q| { + RCC.pllcfgr().modify(|w| { + w.set_pllq(div_q); + w.set_pllqen(true); + }); + let freq = internal_freq / div_q; + assert!(max::PLL_Q.contains(&freq)); + freq + }); + + let pll_r_freq = pll_config.divr.map(|div_r| { + RCC.pllcfgr().modify(|w| { + w.set_pllr(div_r); + w.set_pllren(true); + }); + let freq = internal_freq / div_r; + assert!(max::PLL_R.contains(&freq)); + freq + }); + + // Enable the PLL + RCC.cr().modify(|w| w.set_pllon(true)); + while !RCC.cr().read().pllrdy() {} + + PllFreq { + pll_p: pll_p_freq, + pll_q: pll_q_freq, + pll_r: pll_r_freq, + } + }) + .unwrap_or_default(); + + let sys = match config.sys { + Sysclk::HSI => unwrap!(hsi), + Sysclk::HSE => unwrap!(hse), + Sysclk::PLL1_R => unwrap!(pll.pll_r), + _ => unreachable!(), + }; + + assert!(max::SYSCLK.contains(&sys)); + + // Calculate the AHB frequency (HCLK), among other things so we can calculate the correct flash read latency. + let hclk = sys / config.ahb_pre; + assert!(max::HCLK.contains(&hclk)); + + let (pclk1, pclk1_tim) = super::util::calc_pclk(hclk, config.apb1_pre); + assert!(max::PCLK.contains(&pclk1)); + + let latency = match (config.voltage_range, hclk.0) { + (VoltageRange::RANGE1, ..=24_000_000) => Latency::WS0, + (VoltageRange::RANGE1, ..=48_000_000) => Latency::WS1, + (VoltageRange::RANGE1, _) => Latency::WS2, + (VoltageRange::RANGE2, ..=8_000_000) => Latency::WS0, + (VoltageRange::RANGE2, ..=16_000_000) => Latency::WS1, + (VoltageRange::RANGE2, _) => Latency::WS2, + _ => unreachable!(), + }; + + // Configure flash read access latency based on voltage scale and frequency (RM0444 3.3.4) + FLASH.acr().modify(|w| { + w.set_latency(latency); + }); + + // Spin until the effective flash latency is set. + while FLASH.acr().read().latency() != latency {} + + // Now that boost mode and flash read access latency are configured, set up SYSCLK + RCC.cfgr().modify(|w| { + w.set_sw(config.sys); + w.set_hpre(config.ahb_pre); + w.set_ppre(config.apb1_pre); + }); + while RCC.cfgr().read().sws() != config.sys {} + + // Disable HSI if not used + if !config.hsi { + RCC.cr().modify(|w| w.set_hsion(false)); + } + if config.low_power_run { - assert!(sys_clk.0 <= 2_000_000); + assert!(sys <= Hertz(2_000_000)); PWR.cr1().modify(|w| w.set_lpr(true)); } let rtc = config.ls.init(); - let lse_freq = config.ls.lse.map(|lse| lse.frequency); - let hsi_freq = (sw == Sw::HSI).then_some(HSI_FREQ); - let hsi_div_8_freq = hsi_freq.map(|f| f / 8u32); - let lsi_freq = (sw == Sw::LSI).then_some(super::LSI_FREQ); - let hse_freq = (sw == Sw::HSE).then_some(sys_clk); + config.mux.init(); - #[cfg(any(stm32g0b1, stm32g0c1, stm32g0b0))] - let hsi48_freq = config.usb_src.and_then(|config| { - match config { - UsbSrc::PllQ => { - // Make sure the PLLQ is enabled and running at 48Mhz - assert!(pll1_q_freq.is_some() && pll1_q_freq.unwrap().0 == 48_000_000); - RCC.ccipr2() - .modify(|w| w.set_usbsel(crate::pac::rcc::vals::Usbsel::PLL1_Q)); - None - } - UsbSrc::HSE => { - // Make sure the HSE is enabled and running at 48Mhz - assert!(hse_freq.is_some() && hse_freq.unwrap().0 == 48_000_000); - RCC.ccipr2() - .modify(|w| w.set_usbsel(crate::pac::rcc::vals::Usbsel::HSE)); - None - } - #[cfg(any(stm32g0b1, stm32g0c1))] - UsbSrc::Hsi48(config) => { - let freq = super::init_hsi48(config); - RCC.ccipr2() - .modify(|w| w.set_usbsel(crate::pac::rcc::vals::Usbsel::HSI48)); - Some(freq) - } - } - }); - #[cfg(not(any(stm32g0b1, stm32g0c1, stm32g0b0)))] - let hsi48_freq: Option = None; + set_clocks!( + sys: Some(sys), + hclk1: Some(hclk), + pclk1: Some(pclk1), + pclk1_tim: Some(pclk1_tim), + pll1_p: pll.pll_p, + pll1_q: pll.pll_q, + pll1_r: pll.pll_r, + hsi: hsi, + hse: hse, + #[cfg(crs)] + hsi48: hsi48, + rtc: rtc, + hsi_div_8: hsi.map(|h| h / 8u32), + hsi_div_488: hsi.map(|h| h / 488u32), - set_freqs(Clocks { - sys: sys_clk, - hclk1: ahb_freq, - pclk1: apb_freq, - pclk1_tim: apb_tim_freq, - hsi: hsi_freq, - hsi48: hsi48_freq, - hsi_div_8: hsi_div_8_freq, - hse: hse_freq, - lse: lse_freq, - lsi: lsi_freq, - pll1_q: pll1_q_freq, - pll1_p: pll1_p_freq, - rtc, - }); + // TODO + lsi: None, + lse: None, + ); +} + +mod max { + use core::ops::RangeInclusive; + + use crate::time::Hertz; + + pub(crate) const HSE_OSC: RangeInclusive = Hertz(4_000_000)..=Hertz(48_000_000); + pub(crate) const HSE_BYP: RangeInclusive = Hertz(0)..=Hertz(48_000_000); + pub(crate) const SYSCLK: RangeInclusive = Hertz(0)..=Hertz(64_000_000); + pub(crate) const PCLK: RangeInclusive = Hertz(8)..=Hertz(64_000_000); + pub(crate) const HCLK: RangeInclusive = Hertz(0)..=Hertz(64_000_000); + pub(crate) const PLL_IN: RangeInclusive = Hertz(2_660_000)..=Hertz(16_000_000); + pub(crate) const PLL_VCO: RangeInclusive = Hertz(96_000_000)..=Hertz(344_000_000); + pub(crate) const PLL_P: RangeInclusive = Hertz(3_090_000)..=Hertz(122_000_000); + pub(crate) const PLL_Q: RangeInclusive = Hertz(12_000_000)..=Hertz(128_000_000); + pub(crate) const PLL_R: RangeInclusive = Hertz(12_000_000)..=Hertz(64_000_000); } diff --git a/embassy-stm32/src/rcc/g4.rs b/embassy-stm32/src/rcc/g4.rs index 891f0490b..16561f908 100644 --- a/embassy-stm32/src/rcc/g4.rs +++ b/embassy-stm32/src/rcc/g4.rs @@ -1,40 +1,30 @@ -use stm32_metapac::flash::vals::Latency; -use stm32_metapac::rcc::vals::{Adcsel, Pllsrc, Sw}; -use stm32_metapac::FLASH; - +use crate::pac::flash::vals::Latency; pub use crate::pac::rcc::vals::{ - Adcsel as AdcClockSource, Fdcansel as FdCanClockSource, Hpre as AHBPrescaler, Pllm as PllM, Plln as PllN, - Pllp as PllP, Pllq as PllQ, Pllr as PllR, Ppre as APBPrescaler, + Hpre as AHBPrescaler, Pllm as PllPreDiv, Plln as PllMul, Pllp as PllPDiv, Pllq as PllQDiv, Pllr as PllRDiv, + Pllsrc as PllSource, Ppre as APBPrescaler, Sw as Sysclk, }; -use crate::pac::{PWR, RCC}; -use crate::rcc::{set_freqs, Clocks}; +use crate::pac::{FLASH, PWR, RCC}; use crate::time::Hertz; /// HSI speed pub const HSI_FREQ: Hertz = Hertz(16_000_000); -/// System clock mux source -#[derive(Clone, Copy)] -pub enum ClockSrc { - HSE(Hertz), - HSI, - PLL, +/// HSE Mode +#[derive(Clone, Copy, Eq, PartialEq)] +pub enum HseMode { + /// crystal/ceramic oscillator (HSEBYP=0) + Oscillator, + /// external analog clock (low swing) (HSEBYP=1) + Bypass, } -/// PLL clock input source -#[derive(Clone, Copy, Debug)] -pub enum PllSource { - HSI, - HSE(Hertz), -} - -impl Into for PllSource { - fn into(self) -> Pllsrc { - match self { - PllSource::HSE(..) => Pllsrc::HSE, - PllSource::HSI => Pllsrc::HSI, - } - } +/// HSE Configuration +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct Hse { + /// HSE frequency. + pub freq: Hertz, + /// HSE mode. + pub mode: HseMode, } /// PLL Configuration @@ -42,75 +32,86 @@ impl Into for PllSource { /// Use this struct to configure the PLL source, input frequency, multiplication factor, and output /// dividers. Be sure to keep check the datasheet for your specific part for the appropriate /// frequency ranges for each of these settings. +#[derive(Clone, Copy)] pub struct Pll { /// PLL Source clock selection. pub source: PllSource, /// PLL pre-divider - pub prediv_m: PllM, + pub prediv: PllPreDiv, /// PLL multiplication factor for VCO - pub mul_n: PllN, + pub mul: PllMul, /// PLL division factor for P clock (ADC Clock) - pub div_p: Option, + pub divp: Option, /// PLL division factor for Q clock (USB, I2S23, SAI1, FDCAN, QSPI) - pub div_q: Option, + pub divq: Option, /// PLL division factor for R clock (SYSCLK) - pub div_r: Option, -} - -/// Sets the source for the 48MHz clock to the USB and RNG peripherals. -pub enum Clock48MhzSrc { - /// Use the High Speed Internal Oscillator. For USB usage, the CRS must be used to calibrate the - /// oscillator to comply with the USB specification for oscillator tolerance. - Hsi48(super::Hsi48Config), - /// Use the PLLQ output. The PLL must be configured to output a 48MHz clock. For USB usage the - /// PLL needs to be using the HSE source to comply with the USB specification for oscillator - /// tolerance. - PllQ, + pub divr: Option, } /// Clocks configutation +#[non_exhaustive] +#[derive(Clone, Copy)] pub struct Config { - pub mux: ClockSrc, + /// HSI Enable + pub hsi: bool, + + /// HSE Configuration + pub hse: Option, + + /// System Clock Configuration + pub sys: Sysclk, + + /// HSI48 Configuration + pub hsi48: Option, + + /// PLL Configuration + pub pll: Option, + + /// If PLL is requested as the main clock source in the `sys` field then the PLL configuration + /// MUST turn on the PLLR output. pub ahb_pre: AHBPrescaler, pub apb1_pre: APBPrescaler, pub apb2_pre: APBPrescaler, - pub low_power_run: bool, - /// Iff PLL is requested as the main clock source in the `mux` field then the PLL configuration - /// MUST turn on the PLLR output. - pub pll: Option, - /// Sets the clock source for the 48MHz clock used by the USB and RNG peripherals. - pub clock_48mhz_src: Option, - pub adc12_clock_source: AdcClockSource, - pub adc345_clock_source: AdcClockSource, - pub fdcan_clock_source: FdCanClockSource, + pub low_power_run: bool, + + /// Low-Speed Clock Configuration pub ls: super::LsConfig, + + /// Enable range1 boost mode + /// Recommended when the SYSCLK frequency is greater than 150MHz. + pub boost: bool, + + /// Per-peripheral kernel clock selection muxes + pub mux: super::mux::ClockMux, } impl Default for Config { #[inline] fn default() -> Config { Config { - mux: ClockSrc::HSI, + hsi: true, + hse: None, + sys: Sysclk::HSI, + hsi48: Some(Default::default()), + pll: None, ahb_pre: AHBPrescaler::DIV1, apb1_pre: APBPrescaler::DIV1, apb2_pre: APBPrescaler::DIV1, low_power_run: false, - pll: None, - clock_48mhz_src: Some(Clock48MhzSrc::Hsi48(Default::default())), - adc12_clock_source: Adcsel::DISABLE, - adc345_clock_source: Adcsel::DISABLE, - fdcan_clock_source: FdCanClockSource::PCLK1, ls: Default::default(), + boost: false, + mux: Default::default(), } } } +#[derive(Default)] pub struct PllFreq { pub pll_p: Option, pub pll_q: Option, @@ -118,209 +119,240 @@ pub struct PllFreq { } pub(crate) unsafe fn init(config: Config) { - let pll_freq = config.pll.map(|pll_config| { - let src_freq = match pll_config.source { - PllSource::HSI => { - RCC.cr().write(|w| w.set_hsion(true)); - while !RCC.cr().read().hsirdy() {} + // Turn on the HSI + RCC.cr().modify(|w| w.set_hsion(true)); + while !RCC.cr().read().hsirdy() {} - HSI_FREQ - } - PllSource::HSE(freq) => { - RCC.cr().write(|w| w.set_hseon(true)); - while !RCC.cr().read().hserdy() {} - freq - } - }; + // Use the HSI clock as system clock during the actual clock setup + RCC.cfgr().modify(|w| w.set_sw(Sysclk::HSI)); + while RCC.cfgr().read().sws() != Sysclk::HSI {} - // Disable PLL before configuration - RCC.cr().modify(|w| w.set_pllon(false)); - while RCC.cr().read().pllrdy() {} + // Configure HSI + let hsi = match config.hsi { + false => None, + true => Some(HSI_FREQ), + }; - let internal_freq = src_freq / pll_config.prediv_m * pll_config.mul_n; - - RCC.pllcfgr().write(|w| { - w.set_plln(pll_config.mul_n); - w.set_pllm(pll_config.prediv_m); - w.set_pllsrc(pll_config.source.into()); - }); - - let pll_p_freq = pll_config.div_p.map(|div_p| { - RCC.pllcfgr().modify(|w| { - w.set_pllp(div_p); - w.set_pllpen(true); - }); - internal_freq / div_p - }); - - let pll_q_freq = pll_config.div_q.map(|div_q| { - RCC.pllcfgr().modify(|w| { - w.set_pllq(div_q); - w.set_pllqen(true); - }); - internal_freq / div_q - }); - - let pll_r_freq = pll_config.div_r.map(|div_r| { - RCC.pllcfgr().modify(|w| { - w.set_pllr(div_r); - w.set_pllren(true); - }); - internal_freq / div_r - }); - - // Enable the PLL - RCC.cr().modify(|w| w.set_pllon(true)); - while !RCC.cr().read().pllrdy() {} - - PllFreq { - pll_p: pll_p_freq, - pll_q: pll_q_freq, - pll_r: pll_r_freq, + // Configure HSE + let hse = match config.hse { + None => { + RCC.cr().modify(|w| w.set_hseon(false)); + None } - }); + Some(hse) => { + match hse.mode { + HseMode::Bypass => assert!(max::HSE_BYP.contains(&hse.freq)), + HseMode::Oscillator => assert!(max::HSE_OSC.contains(&hse.freq)), + } - let (sys_clk, sw) = match config.mux { - ClockSrc::HSI => { - // Enable HSI - RCC.cr().write(|w| w.set_hsion(true)); - while !RCC.cr().read().hsirdy() {} - - (HSI_FREQ, Sw::HSI) - } - ClockSrc::HSE(freq) => { - // Enable HSE - RCC.cr().write(|w| w.set_hseon(true)); + RCC.cr().modify(|w| w.set_hsebyp(hse.mode != HseMode::Oscillator)); + RCC.cr().modify(|w| w.set_hseon(true)); while !RCC.cr().read().hserdy() {} - - (freq, Sw::HSE) - } - ClockSrc::PLL => { - assert!(pll_freq.is_some()); - assert!(pll_freq.as_ref().unwrap().pll_r.is_some()); - - let freq = pll_freq.as_ref().unwrap().pll_r.unwrap().0; - - assert!(freq <= 170_000_000); - - if freq >= 150_000_000 { - // Enable Core Boost mode on freq >= 150Mhz ([RM0440] p234) - PWR.cr5().modify(|w| w.set_r1mode(false)); - // Set flash wait state in boost mode based on frequency ([RM0440] p191) - if freq <= 36_000_000 { - FLASH.acr().modify(|w| w.set_latency(Latency::WS0)); - } else if freq <= 68_000_000 { - FLASH.acr().modify(|w| w.set_latency(Latency::WS1)); - } else if freq <= 102_000_000 { - FLASH.acr().modify(|w| w.set_latency(Latency::WS2)); - } else if freq <= 136_000_000 { - FLASH.acr().modify(|w| w.set_latency(Latency::WS3)); - } else { - FLASH.acr().modify(|w| w.set_latency(Latency::WS4)); - } - } else { - PWR.cr5().modify(|w| w.set_r1mode(true)); - // Set flash wait state in normal mode based on frequency ([RM0440] p191) - if freq <= 30_000_000 { - FLASH.acr().modify(|w| w.set_latency(Latency::WS0)); - } else if freq <= 60_000_000 { - FLASH.acr().modify(|w| w.set_latency(Latency::WS1)); - } else if freq <= 80_000_000 { - FLASH.acr().modify(|w| w.set_latency(Latency::WS2)); - } else if freq <= 120_000_000 { - FLASH.acr().modify(|w| w.set_latency(Latency::WS3)); - } else { - FLASH.acr().modify(|w| w.set_latency(Latency::WS4)); - } - } - - (Hertz(freq), Sw::PLL1_R) + Some(hse.freq) } }; + // Configure HSI48 if required + let hsi48 = config.hsi48.map(super::init_hsi48); + + let pll = config + .pll + .map(|pll_config| { + let src_freq = match pll_config.source { + PllSource::HSI => unwrap!(hsi), + PllSource::HSE => unwrap!(hse), + _ => unreachable!(), + }; + + // Disable PLL before configuration + RCC.cr().modify(|w| w.set_pllon(false)); + while RCC.cr().read().pllrdy() {} + + let in_freq = src_freq / pll_config.prediv; + assert!(max::PLL_IN.contains(&in_freq)); + let internal_freq = in_freq * pll_config.mul; + + assert!(max::PLL_VCO.contains(&internal_freq)); + + RCC.pllcfgr().write(|w| { + w.set_plln(pll_config.mul); + w.set_pllm(pll_config.prediv); + w.set_pllsrc(pll_config.source.into()); + }); + + let pll_p_freq = pll_config.divp.map(|div_p| { + RCC.pllcfgr().modify(|w| { + w.set_pllp(div_p); + w.set_pllpen(true); + }); + let freq = internal_freq / div_p; + assert!(max::PLL_P.contains(&freq)); + freq + }); + + let pll_q_freq = pll_config.divq.map(|div_q| { + RCC.pllcfgr().modify(|w| { + w.set_pllq(div_q); + w.set_pllqen(true); + }); + let freq = internal_freq / div_q; + assert!(max::PLL_Q.contains(&freq)); + freq + }); + + let pll_r_freq = pll_config.divr.map(|div_r| { + RCC.pllcfgr().modify(|w| { + w.set_pllr(div_r); + w.set_pllren(true); + }); + let freq = internal_freq / div_r; + assert!(max::PLL_R.contains(&freq)); + freq + }); + + // Enable the PLL + RCC.cr().modify(|w| w.set_pllon(true)); + while !RCC.cr().read().pllrdy() {} + + PllFreq { + pll_p: pll_p_freq, + pll_q: pll_q_freq, + pll_r: pll_r_freq, + } + }) + .unwrap_or_default(); + + let sys = match config.sys { + Sysclk::HSI => unwrap!(hsi), + Sysclk::HSE => unwrap!(hse), + Sysclk::PLL1_R => unwrap!(pll.pll_r), + _ => unreachable!(), + }; + + assert!(max::SYSCLK.contains(&sys)); + + // Calculate the AHB frequency (HCLK), among other things so we can calculate the correct flash read latency. + let hclk = sys / config.ahb_pre; + assert!(max::HCLK.contains(&hclk)); + + let (pclk1, pclk1_tim) = super::util::calc_pclk(hclk, config.apb1_pre); + let (pclk2, pclk2_tim) = super::util::calc_pclk(hclk, config.apb2_pre); + assert!(max::PCLK.contains(&pclk2)); + assert!(max::PCLK.contains(&pclk2)); + + // Configure Core Boost mode ([RM0440] p234 – inverted because setting r1mode to 0 enables boost mode!) + if config.boost { + // RM0440 p235 + // “The sequence to switch from Range1 normal mode to Range1 boost mode is: + // 1. The system clock must be divided by 2 using the AHB prescaler before switching to a higher system frequency. + RCC.cfgr().modify(|w| w.set_hpre(AHBPrescaler::DIV2)); + // 2. Clear the R1MODE bit in the PWR_CR5 register. (enables boost mode) + PWR.cr5().modify(|w| w.set_r1mode(false)); + + // Below: + // 3. Adjust wait states according to new freq target + // 4. Configure and switch to new frequency + } + + let latency = match (config.boost, hclk.0) { + (true, ..=34_000_000) => Latency::WS0, + (true, ..=68_000_000) => Latency::WS1, + (true, ..=102_000_000) => Latency::WS2, + (true, ..=136_000_000) => Latency::WS3, + (true, _) => Latency::WS4, + + (false, ..=36_000_000) => Latency::WS0, + (false, ..=60_000_000) => Latency::WS1, + (false, ..=90_000_000) => Latency::WS2, + (false, ..=120_000_000) => Latency::WS3, + (false, _) => Latency::WS4, + }; + + // Configure flash read access latency based on boost mode and frequency (RM0440 p98) + FLASH.acr().modify(|w| { + w.set_latency(latency); + }); + + // Spin until the effective flash latency is set. + while FLASH.acr().read().latency() != latency {} + + if config.boost { + // 5. Wait for at least 1us and then reconfigure the AHB prescaler to get the needed HCLK clock frequency. + cortex_m::asm::delay(16); + } + + // Now that boost mode and flash read access latency are configured, set up SYSCLK RCC.cfgr().modify(|w| { - w.set_sw(sw); + w.set_sw(config.sys); w.set_hpre(config.ahb_pre); w.set_ppre1(config.apb1_pre); w.set_ppre2(config.apb2_pre); }); + while RCC.cfgr().read().sws() != config.sys {} - let ahb_freq = sys_clk / config.ahb_pre; - - let (apb1_freq, apb1_tim_freq) = match config.apb1_pre { - APBPrescaler::DIV1 => (ahb_freq, ahb_freq), - pre => { - let freq = ahb_freq / pre; - (freq, freq * 2u32) - } - }; - - let (apb2_freq, apb2_tim_freq) = match config.apb2_pre { - APBPrescaler::DIV1 => (ahb_freq, ahb_freq), - pre => { - let freq = ahb_freq / pre; - (freq, freq * 2u32) - } - }; - - // Setup the 48 MHz clock if needed - if let Some(clock_48mhz_src) = config.clock_48mhz_src { - let source = match clock_48mhz_src { - Clock48MhzSrc::PllQ => { - // Make sure the PLLQ is enabled and running at 48Mhz - let pllq_freq = pll_freq.as_ref().and_then(|f| f.pll_q); - assert!(pllq_freq.is_some() && pllq_freq.unwrap().0 == 48_000_000); - - crate::pac::rcc::vals::Clk48sel::PLL1_Q - } - Clock48MhzSrc::Hsi48(config) => { - super::init_hsi48(config); - crate::pac::rcc::vals::Clk48sel::HSI48 - } - }; - - RCC.ccipr().modify(|w| w.set_clk48sel(source)); + // Disable HSI if not used + if !config.hsi { + RCC.cr().modify(|w| w.set_hsion(false)); } - RCC.ccipr().modify(|w| w.set_adc12sel(config.adc12_clock_source)); - RCC.ccipr().modify(|w| w.set_adc345sel(config.adc345_clock_source)); - RCC.ccipr().modify(|w| w.set_fdcansel(config.fdcan_clock_source)); - - let adc12_ck = match config.adc12_clock_source { - AdcClockSource::DISABLE => None, - AdcClockSource::PLL1_P => pll_freq.as_ref().unwrap().pll_p, - AdcClockSource::SYS => Some(sys_clk), - _ => unreachable!(), - }; - - let adc345_ck = match config.adc345_clock_source { - AdcClockSource::DISABLE => None, - AdcClockSource::PLL1_P => pll_freq.as_ref().unwrap().pll_p, - AdcClockSource::SYS => Some(sys_clk), - _ => unreachable!(), - }; - if config.low_power_run { - assert!(sys_clk <= Hertz(2_000_000)); + assert!(sys <= Hertz(2_000_000)); PWR.cr1().modify(|w| w.set_lpr(true)); } let rtc = config.ls.init(); - set_freqs(Clocks { - sys: sys_clk, - hclk1: ahb_freq, - hclk2: ahb_freq, - hclk3: ahb_freq, - pclk1: apb1_freq, - pclk1_tim: apb1_tim_freq, - pclk2: apb2_freq, - pclk2_tim: apb2_tim_freq, - adc: adc12_ck, - adc34: adc345_ck, - pll1_p: None, - pll1_q: None, // TODO - hse: None, // TODO - rtc, - }); + config.mux.init(); + + set_clocks!( + sys: Some(sys), + hclk1: Some(hclk), + hclk2: Some(hclk), + hclk3: Some(hclk), + pclk1: Some(pclk1), + pclk1_tim: Some(pclk1_tim), + pclk2: Some(pclk2), + pclk2_tim: Some(pclk2_tim), + pll1_p: pll.pll_p, + pll1_q: pll.pll_q, + pll1_r: pll.pll_r, + hsi: hsi, + hse: hse, + hsi48: hsi48, + rtc: rtc, + ); +} + +/// Acceptable Frequency Ranges +/// Currently assuming voltage scaling range 1 boost mode. +/// Where not specified in the generic G4 reference manual (RM0440), values taken from the STM32G474 datasheet. +/// If acceptable ranges for other G4-family chips differ, make additional max modules gated behind cfg attrs. +mod max { + use core::ops::RangeInclusive; + + use crate::time::Hertz; + + /// HSE Frequency Range (RM0440 p280) + pub(crate) const HSE_OSC: RangeInclusive = Hertz(4_000_000)..=Hertz(48_000_000); + + /// External Clock Frequency Range (RM0440 p280) + pub(crate) const HSE_BYP: RangeInclusive = Hertz(0)..=Hertz(48_000_000); + + /// SYSCLK Frequency Range (RM0440 p282) + pub(crate) const SYSCLK: RangeInclusive = Hertz(0)..=Hertz(170_000_000); + + /// PLL Output Frequency Range (RM0440 p281, STM32G474 Datasheet p123, Table 46) + pub(crate) const PCLK: RangeInclusive = Hertz(8)..=Hertz(170_000_000); + + /// HCLK (AHB) Clock Frequency Range (STM32G474 Datasheet) + pub(crate) const HCLK: RangeInclusive = Hertz(0)..=Hertz(170_000_000); + + /// PLL Source Frequency Range (STM32G474 Datasheet p123, Table 46) + pub(crate) const PLL_IN: RangeInclusive = Hertz(2_660_000)..=Hertz(16_000_000); + + /// PLL VCO (internal) Frequency Range (STM32G474 Datasheet p123, Table 46) + pub(crate) const PLL_VCO: RangeInclusive = Hertz(96_000_000)..=Hertz(344_000_000); + pub(crate) const PLL_P: RangeInclusive = Hertz(2_064_500)..=Hertz(170_000_000); + pub(crate) const PLL_Q: RangeInclusive = Hertz(8_000_000)..=Hertz(170_000_000); + pub(crate) const PLL_R: RangeInclusive = Hertz(8_000_000)..=Hertz(170_000_000); } diff --git a/embassy-stm32/src/rcc/h.rs b/embassy-stm32/src/rcc/h.rs index dcaf2dced..df2929ba4 100644 --- a/embassy-stm32/src/rcc/h.rs +++ b/embassy-stm32/src/rcc/h.rs @@ -1,18 +1,11 @@ use core::ops::RangeInclusive; use crate::pac; -use crate::pac::pwr::vals::Vos; -#[cfg(stm32h5)] -pub use crate::pac::rcc::vals::Adcdacsel as AdcClockSource; -#[cfg(stm32h7)] -pub use crate::pac::rcc::vals::Adcsel as AdcClockSource; pub use crate::pac::rcc::vals::{ - Ckpersel as PerClockSource, Fdcansel as FdCanClockSource, Hsidiv as HSIPrescaler, Plldiv as PllDiv, - Pllm as PllPreDiv, Plln as PllMul, Pllsrc as PllSource, Sw as Sysclk, + Hsidiv as HSIPrescaler, Plldiv as PllDiv, Pllm as PllPreDiv, Plln as PllMul, Pllsrc as PllSource, Sw as Sysclk, }; -use crate::pac::rcc::vals::{Ckpersel, Pllrge, Pllvcosel, Timpre}; +use crate::pac::rcc::vals::{Pllrge, Pllvcosel, Timpre}; use crate::pac::{FLASH, PWR, RCC}; -use crate::rcc::{set_freqs, Clocks}; use crate::time::Hertz; /// HSI speed @@ -28,9 +21,12 @@ const VCO_WIDE_RANGE: RangeInclusive = Hertz(128_000_000)..=Hertz(560_000 const VCO_WIDE_RANGE: RangeInclusive = Hertz(192_000_000)..=Hertz(836_000_000); #[cfg(any(pwr_h7rm0399, pwr_h7rm0433))] const VCO_WIDE_RANGE: RangeInclusive = Hertz(192_000_000)..=Hertz(960_000_000); +#[cfg(any(stm32h7rs))] +const VCO_WIDE_RANGE: RangeInclusive = Hertz(384_000_000)..=Hertz(1672_000_000); pub use crate::pac::rcc::vals::{Hpre as AHBPrescaler, Ppre as APBPrescaler}; +#[cfg(any(stm32h5, stm32h7))] #[derive(Clone, Copy, Eq, PartialEq)] pub enum VoltageScale { Scale0, @@ -38,6 +34,10 @@ pub enum VoltageScale { Scale2, Scale3, } +#[cfg(stm32h7rs)] +pub use crate::pac::pwr::vals::Vos as VoltageScale; +#[cfg(all(stm32h7rs, peri_usb_otg_hs))] +pub use crate::pac::rcc::vals::{Usbphycsel, Usbrefcksel}; #[derive(Clone, Copy, Eq, PartialEq)] pub enum HseMode { @@ -46,7 +46,7 @@ pub enum HseMode { /// external analog clock (low swing) (HSEBYP=1, HSEEXT=0) Bypass, /// external digital clock (full swing) (HSEBYP=1, HSEEXT=1) - #[cfg(any(rcc_h5, rcc_h50))] + #[cfg(any(rcc_h5, rcc_h50, rcc_h7rs))] BypassDigital, } @@ -71,8 +71,8 @@ pub struct Pll { /// PLL P division factor. If None, PLL P output is disabled. /// On PLL1, it must be even for most series (in particular, - /// it cannot be 1 in series other than STM32H723/733, - /// STM32H725/735 and STM32H730.) + /// it cannot be 1 in series other than stm32h7, stm32h7rs23/733, + /// stm32h7, stm32h7rs25/735 and stm32h7, stm32h7rs30.) pub divp: Option, /// PLL Q division factor. If None, PLL Q output is disabled. pub divq: Option, @@ -121,8 +121,8 @@ impl From for Timpre { /// Power supply configuration /// See RM0433 Rev 4 7.4 -#[cfg(any(pwr_h7rm0399, pwr_h7rm0455, pwr_h7rm0468))] -#[derive(PartialEq)] +#[cfg(any(pwr_h7rm0399, pwr_h7rm0455, pwr_h7rm0468, pwr_h7rs))] +#[derive(Clone, Copy, PartialEq)] pub enum SupplyConfig { /// Default power supply configuration. /// V CORE Power Domains are supplied from the LDO according to VOS. @@ -170,26 +170,19 @@ pub enum SupplyConfig { /// SMPS step-down converter voltage output level. /// This is only used in certain power supply configurations: /// SMPSLDO, SMPSExternalLDO, SMPSExternalLDOBypass. -#[cfg(any(pwr_h7rm0399, pwr_h7rm0455, pwr_h7rm0468))] -#[derive(PartialEq)] +#[cfg(any(pwr_h7rm0399, pwr_h7rm0455, pwr_h7rm0468, pwr_h7rs))] +#[derive(Clone, Copy, Eq, PartialEq, Debug)] pub enum SMPSSupplyVoltage { + /// 1.8v V1_8, + /// 2.5v + #[cfg(not(pwr_h7rs))] V2_5, } -#[cfg(any(pwr_h7rm0399, pwr_h7rm0455, pwr_h7rm0468))] -impl SMPSSupplyVoltage { - /// Convert SMPSSupplyVoltage to u8 representation. - fn to_u8(&self) -> u8 { - match self { - SMPSSupplyVoltage::V1_8 => 0b01, - SMPSSupplyVoltage::V2_5 => 0b10, - } - } -} - /// Configuration of the core clocks #[non_exhaustive] +#[derive(Clone, Copy)] pub struct Config { pub hsi: Option, pub hse: Option, @@ -199,27 +192,30 @@ pub struct Config { pub pll1: Option, pub pll2: Option, - #[cfg(any(rcc_h5, stm32h7))] + #[cfg(any(rcc_h5, stm32h7, stm32h7rs))] pub pll3: Option, + #[cfg(any(stm32h7, stm32h7rs))] pub d1c_pre: AHBPrescaler, pub ahb_pre: AHBPrescaler, pub apb1_pre: APBPrescaler, pub apb2_pre: APBPrescaler, + #[cfg(not(stm32h7rs))] pub apb3_pre: APBPrescaler, - #[cfg(stm32h7)] + #[cfg(any(stm32h7, stm32h7rs))] pub apb4_pre: APBPrescaler, - - pub per_clock_source: PerClockSource, - pub adc_clock_source: AdcClockSource, - pub fdcan_clock_source: FdCanClockSource, + #[cfg(stm32h7rs)] + pub apb5_pre: APBPrescaler, pub timer_prescaler: TimerPrescaler, pub voltage_scale: VoltageScale, pub ls: super::LsConfig, - #[cfg(any(pwr_h7rm0399, pwr_h7rm0455, pwr_h7rm0468))] + #[cfg(any(pwr_h7rm0399, pwr_h7rm0455, pwr_h7rm0468, pwr_h7rs))] pub supply_config: SupplyConfig, + + /// Per-peripheral kernel clock selection muxes + pub mux: super::mux::ClockMux, } impl Default for Config { @@ -232,55 +228,61 @@ impl Default for Config { sys: Sysclk::HSI, pll1: None, pll2: None, - #[cfg(any(rcc_h5, stm32h7))] + #[cfg(any(rcc_h5, stm32h7, stm32h7rs))] pll3: None, + #[cfg(any(stm32h7, stm32h7rs))] d1c_pre: AHBPrescaler::DIV1, ahb_pre: AHBPrescaler::DIV1, apb1_pre: APBPrescaler::DIV1, apb2_pre: APBPrescaler::DIV1, + #[cfg(not(stm32h7rs))] apb3_pre: APBPrescaler::DIV1, - #[cfg(stm32h7)] + #[cfg(any(stm32h7, stm32h7rs))] apb4_pre: APBPrescaler::DIV1, - - per_clock_source: PerClockSource::HSI, - - #[cfg(stm32h5)] - adc_clock_source: AdcClockSource::HCLK1, - #[cfg(stm32h7)] - adc_clock_source: AdcClockSource::PER, - - fdcan_clock_source: FdCanClockSource::from_bits(0), // HSE + #[cfg(stm32h7rs)] + apb5_pre: APBPrescaler::DIV1, timer_prescaler: TimerPrescaler::DefaultX2, + #[cfg(not(rcc_h7rs))] voltage_scale: VoltageScale::Scale0, + #[cfg(rcc_h7rs)] + voltage_scale: VoltageScale::HIGH, ls: Default::default(), - #[cfg(any(pwr_h7rm0399, pwr_h7rm0455, pwr_h7rm0468))] - supply_config: SupplyConfig::Default, + #[cfg(any(pwr_h7rm0399, pwr_h7rm0455, pwr_h7rm0468, pwr_h7rs))] + supply_config: SupplyConfig::LDO, + + mux: Default::default(), } } } pub(crate) unsafe fn init(config: Config) { + #[cfg(any(stm32h7))] + let pwr_reg = PWR.cr3(); + #[cfg(any(stm32h7rs))] + let pwr_reg = PWR.csr2(); + // NB. The lower bytes of CR3 can only be written once after // POR, and must be written with a valid combination. Refer to // RM0433 Rev 7 6.8.4. This is partially enforced by dropping // `self` at the end of this method, but of course we cannot // know what happened between the previous POR and here. #[cfg(pwr_h7rm0433)] - PWR.cr3().modify(|w| { + pwr_reg.modify(|w| { w.set_scuen(true); w.set_ldoen(true); w.set_bypass(false); }); - #[cfg(any(pwr_h7rm0399, pwr_h7rm0455, pwr_h7rm0468))] + #[cfg(any(pwr_h7rm0399, pwr_h7rm0455, pwr_h7rm0468, pwr_h7rs))] { + use pac::pwr::vals::Sdlevel; match config.supply_config { SupplyConfig::Default => { - PWR.cr3().modify(|w| { - w.set_sdlevel(0b00); + pwr_reg.modify(|w| { + w.set_sdlevel(Sdlevel::RESET); w.set_sdexthp(false); w.set_sden(true); w.set_ldoen(true); @@ -288,25 +290,30 @@ pub(crate) unsafe fn init(config: Config) { }); } SupplyConfig::LDO => { - PWR.cr3().modify(|w| { + pwr_reg.modify(|w| { w.set_sden(false); w.set_ldoen(true); w.set_bypass(false); }); } SupplyConfig::DirectSMPS => { - PWR.cr3().modify(|w| { + pwr_reg.modify(|w| { w.set_sdexthp(false); w.set_sden(true); w.set_ldoen(false); w.set_bypass(false); }); } - SupplyConfig::SMPSLDO(ref smps_supply_voltage) - | SupplyConfig::SMPSExternalLDO(ref smps_supply_voltage) - | SupplyConfig::SMPSExternalLDOBypass(ref smps_supply_voltage) => { - PWR.cr3().modify(|w| { - w.set_sdlevel(smps_supply_voltage.to_u8()); + SupplyConfig::SMPSLDO(sdlevel) + | SupplyConfig::SMPSExternalLDO(sdlevel) + | SupplyConfig::SMPSExternalLDOBypass(sdlevel) => { + let sdlevel = match sdlevel { + SMPSSupplyVoltage::V1_8 => Sdlevel::V1_8, + #[cfg(not(pwr_h7rs))] + SMPSSupplyVoltage::V2_5 => Sdlevel::V2_5, + }; + pwr_reg.modify(|w| { + w.set_sdlevel(sdlevel); w.set_sdexthp(matches!( config.supply_config, SupplyConfig::SMPSExternalLDO(_) | SupplyConfig::SMPSExternalLDOBypass(_) @@ -320,7 +327,7 @@ pub(crate) unsafe fn init(config: Config) { }); } SupplyConfig::SMPSDisabledLDOBypass => { - PWR.cr3().modify(|w| { + pwr_reg.modify(|w| { w.set_sden(false); w.set_ldoen(false); w.set_bypass(true); @@ -334,43 +341,49 @@ pub(crate) unsafe fn init(config: Config) { // in the D3CR.VOS and CR3.SDLEVEL fields. By default after reset // VOS = Scale 3, so check that the voltage on the VCAP pins = // 1.0V. - #[cfg(any(pwr_h7rm0433, pwr_h7rm0399, pwr_h7rm0455, pwr_h7rm0468))] + #[cfg(any(stm32h7))] while !PWR.csr1().read().actvosrdy() {} + #[cfg(any(stm32h7rs))] + while !PWR.sr1().read().actvosrdy() {} // Configure voltage scale. #[cfg(any(pwr_h5, pwr_h50))] { PWR.voscr().modify(|w| { w.set_vos(match config.voltage_scale { - VoltageScale::Scale0 => Vos::SCALE0, - VoltageScale::Scale1 => Vos::SCALE1, - VoltageScale::Scale2 => Vos::SCALE2, - VoltageScale::Scale3 => Vos::SCALE3, + VoltageScale::Scale0 => crate::pac::pwr::vals::Vos::SCALE0, + VoltageScale::Scale1 => crate::pac::pwr::vals::Vos::SCALE1, + VoltageScale::Scale2 => crate::pac::pwr::vals::Vos::SCALE2, + VoltageScale::Scale3 => crate::pac::pwr::vals::Vos::SCALE3, }) }); while !PWR.vossr().read().vosrdy() {} } - #[cfg(syscfg_h7)] { // in chips without the overdrive bit, we can go from any scale to any scale directly. PWR.d3cr().modify(|w| { w.set_vos(match config.voltage_scale { - VoltageScale::Scale0 => Vos::SCALE0, - VoltageScale::Scale1 => Vos::SCALE1, - VoltageScale::Scale2 => Vos::SCALE2, - VoltageScale::Scale3 => Vos::SCALE3, + VoltageScale::Scale0 => crate::pac::pwr::vals::Vos::SCALE0, + VoltageScale::Scale1 => crate::pac::pwr::vals::Vos::SCALE1, + VoltageScale::Scale2 => crate::pac::pwr::vals::Vos::SCALE2, + VoltageScale::Scale3 => crate::pac::pwr::vals::Vos::SCALE3, }) }); while !PWR.d3cr().read().vosrdy() {} } + #[cfg(pwr_h7rs)] + { + PWR.csr4().modify(|w| w.set_vos(config.voltage_scale)); + while !PWR.csr4().read().vosrdy() {} + } #[cfg(syscfg_h7od)] { match config.voltage_scale { VoltageScale::Scale0 => { // to go to scale0, we must go to Scale1 first... - PWR.d3cr().modify(|w| w.set_vos(Vos::SCALE1)); + PWR.d3cr().modify(|w| w.set_vos(crate::pac::pwr::vals::Vos::SCALE1)); while !PWR.d3cr().read().vosrdy() {} // Then enable overdrive. @@ -382,9 +395,9 @@ pub(crate) unsafe fn init(config: Config) { PWR.d3cr().modify(|w| { w.set_vos(match config.voltage_scale { VoltageScale::Scale0 => unreachable!(), - VoltageScale::Scale1 => Vos::SCALE1, - VoltageScale::Scale2 => Vos::SCALE2, - VoltageScale::Scale3 => Vos::SCALE3, + VoltageScale::Scale1 => crate::pac::pwr::vals::Vos::SCALE1, + VoltageScale::Scale2 => crate::pac::pwr::vals::Vos::SCALE2, + VoltageScale::Scale3 => crate::pac::pwr::vals::Vos::SCALE3, }) }); while !PWR.d3cr().read().vosrdy() {} @@ -392,20 +405,24 @@ pub(crate) unsafe fn init(config: Config) { } } + // Turn on the HSI + match config.hsi { + None => RCC.cr().modify(|w| w.set_hsion(true)), + Some(hsidiv) => RCC.cr().modify(|w| { + w.set_hsidiv(hsidiv); + w.set_hsion(true); + }), + } + while !RCC.cr().read().hsirdy() {} + + // Use the HSI clock as system clock during the actual clock setup + RCC.cfgr().modify(|w| w.set_sw(Sysclk::HSI)); + while RCC.cfgr().read().sws() != Sysclk::HSI {} + // Configure HSI let hsi = match config.hsi { - None => { - RCC.cr().modify(|w| w.set_hsion(false)); - None - } - Some(hsidiv) => { - RCC.cr().modify(|w| { - w.set_hsidiv(hsidiv); - w.set_hsion(true); - }); - while !RCC.cr().read().hsirdy() {} - Some(HSI_FREQ / hsidiv) - } + None => None, + Some(hsidiv) => Some(HSI_FREQ / hsidiv), }; // Configure HSE @@ -417,7 +434,7 @@ pub(crate) unsafe fn init(config: Config) { Some(hse) => { RCC.cr().modify(|w| { w.set_hsebyp(hse.mode != HseMode::Oscillator); - #[cfg(any(rcc_h5, rcc_h50))] + #[cfg(any(rcc_h5, rcc_h50, rcc_h7rs))] w.set_hseext(match hse.mode { HseMode::Oscillator | HseMode::Bypass => pac::rcc::vals::Hseext::ANALOG, HseMode::BypassDigital => pac::rcc::vals::Hseext::DIGITAL, @@ -430,7 +447,7 @@ pub(crate) unsafe fn init(config: Config) { }; // Configure HSI48. - let _hsi48 = config.hsi48.map(super::init_hsi48); + let hsi48 = config.hsi48.map(super::init_hsi48); // Configure CSI. RCC.cr().modify(|w| w.set_csion(config.csi)); @@ -443,7 +460,7 @@ pub(crate) unsafe fn init(config: Config) { }; // H7 has shared PLLSRC, check it's equal in all PLLs. - #[cfg(stm32h7)] + #[cfg(any(stm32h7, stm32h7rs))] { let plls = [&config.pll1, &config.pll2, &config.pll3]; if !super::util::all_equal(plls.into_iter().flatten().map(|p| p.source)) { @@ -455,7 +472,7 @@ pub(crate) unsafe fn init(config: Config) { let pll_input = PllInput { csi, hse, hsi }; let pll1 = init_pll(0, config.pll1, &pll_input); let pll2 = init_pll(1, config.pll2, &pll_input); - #[cfg(any(rcc_h5, stm32h7))] + #[cfg(any(rcc_h5, stm32h7, stm32h7rs))] let pll3 = init_pll(2, config.pll3, &pll_input); // Configure sysclk @@ -484,7 +501,14 @@ pub(crate) unsafe fn init(config: Config) { }; #[cfg(pwr_h7rm0468)] let (d1cpre_clk_max, hclk_max, pclk_max) = match config.voltage_scale { - VoltageScale::Scale0 => (Hertz(520_000_000), Hertz(275_000_000), Hertz(137_500_000)), + VoltageScale::Scale0 => { + let d1cpre_clk_max = if pac::SYSCFG.ur18().read().cpu_freq_boost() { + 550_000_000 + } else { + 520_000_000 + }; + (Hertz(d1cpre_clk_max), Hertz(275_000_000), Hertz(137_500_000)) + } VoltageScale::Scale1 => (Hertz(400_000_000), Hertz(200_000_000), Hertz(100_000_000)), VoltageScale::Scale2 => (Hertz(300_000_000), Hertz(150_000_000), Hertz(75_000_000)), VoltageScale::Scale3 => (Hertz(170_000_000), Hertz(85_000_000), Hertz(42_500_000)), @@ -496,8 +520,13 @@ pub(crate) unsafe fn init(config: Config) { VoltageScale::Scale2 => (Hertz(300_000_000), Hertz(150_000_000), Hertz(75_000_000)), VoltageScale::Scale3 => (Hertz(200_000_000), Hertz(100_000_000), Hertz(50_000_000)), }; + #[cfg(stm32h7rs)] + let (d1cpre_clk_max, hclk_max, pclk_max) = match config.voltage_scale { + VoltageScale::HIGH => (Hertz(600_000_000), Hertz(300_000_000), Hertz(150_000_000)), + VoltageScale::LOW => (Hertz(400_000_000), Hertz(200_000_000), Hertz(100_000_000)), + }; - #[cfg(stm32h7)] + #[cfg(any(stm32h7, stm32h7rs))] let hclk = { let d1cpre_clk = sys / config.d1c_pre; assert!(d1cpre_clk <= d1cpre_clk_max); @@ -513,42 +542,44 @@ pub(crate) unsafe fn init(config: Config) { let apb2 = hclk / config.apb2_pre; let apb2_tim = apb_div_tim(&config.apb2_pre, hclk, config.timer_prescaler); assert!(apb2 <= pclk_max); + #[cfg(not(stm32h7rs))] let apb3 = hclk / config.apb3_pre; + #[cfg(not(stm32h7rs))] assert!(apb3 <= pclk_max); - #[cfg(stm32h7)] + #[cfg(any(stm32h7, stm32h7rs))] let apb4 = hclk / config.apb4_pre; - #[cfg(stm32h7)] + #[cfg(any(stm32h7, stm32h7rs))] assert!(apb4 <= pclk_max); - - let _per_ck = match config.per_clock_source { - Ckpersel::HSI => hsi, - Ckpersel::CSI => csi, - Ckpersel::HSE => hse, - _ => unreachable!(), - }; - - #[cfg(stm32h7)] - let adc = match config.adc_clock_source { - AdcClockSource::PLL2_P => pll2.p, - AdcClockSource::PLL3_R => pll3.r, - AdcClockSource::PER => _per_ck, - _ => unreachable!(), - }; - #[cfg(stm32h5)] - let adc = match config.adc_clock_source { - AdcClockSource::HCLK1 => Some(hclk), - AdcClockSource::SYS => Some(sys), - AdcClockSource::PLL2_R => pll2.r, - AdcClockSource::HSE => hse, - AdcClockSource::HSI => hsi, - AdcClockSource::CSI => csi, - _ => unreachable!(), - }; + #[cfg(stm32h7rs)] + let apb5 = hclk / config.apb5_pre; + #[cfg(stm32h7rs)] + assert!(apb5 <= pclk_max); flash_setup(hclk, config.voltage_scale); let rtc = config.ls.init(); + #[cfg(all(stm32h7rs, peri_usb_otg_hs))] + let usb_refck = match config.mux.usbphycsel { + Usbphycsel::HSE => hse, + Usbphycsel::HSE_DIV_2 => hse.map(|hse_val| hse_val / 2u8), + Usbphycsel::PLL3_Q => pll3.q, + _ => None, + }; + #[cfg(all(stm32h7rs, peri_usb_otg_hs))] + let usb_refck_sel = match usb_refck { + Some(clk_val) => match clk_val { + Hertz(16_000_000) => Usbrefcksel::MHZ16, + Hertz(19_200_000) => Usbrefcksel::MHZ19_2, + Hertz(20_000_000) => Usbrefcksel::MHZ20, + Hertz(24_000_000) => Usbrefcksel::MHZ24, + Hertz(26_000_000) => Usbrefcksel::MHZ26, + Hertz(32_000_000) => Usbrefcksel::MHZ32, + _ => panic!("cannot select USBPHYC reference clock with source frequency of {} Hz, must be one of 16, 19.2, 20, 24, 26, 32 MHz", clk_val), + }, + None => Usbrefcksel::MHZ24, + }; + #[cfg(stm32h7)] { RCC.d1cfgr().modify(|w| { @@ -566,12 +597,29 @@ pub(crate) unsafe fn init(config: Config) { RCC.d3cfgr().modify(|w| { w.set_d3ppre(config.apb4_pre); }); - - RCC.d1ccipr().modify(|w| { - w.set_ckpersel(config.per_clock_source); + } + #[cfg(stm32h7rs)] + { + RCC.cdcfgr().write(|w| { + w.set_cpre(config.d1c_pre); }); - RCC.d3ccipr().modify(|w| { - w.set_adcsel(config.adc_clock_source); + while RCC.cdcfgr().read().cpre() != config.d1c_pre {} + + RCC.bmcfgr().write(|w| { + w.set_bmpre(config.ahb_pre); + }); + while RCC.bmcfgr().read().bmpre() != config.ahb_pre {} + + RCC.apbcfgr().modify(|w| { + w.set_ppre1(config.apb1_pre); + w.set_ppre2(config.apb2_pre); + w.set_ppre4(config.apb4_pre); + w.set_ppre5(config.apb5_pre); + }); + + #[cfg(peri_usb_otg_hs)] + RCC.ahbperckselr().modify(|w| { + w.set_usbrefcksel(usb_refck_sel); }); } #[cfg(stm32h5)] @@ -586,12 +634,6 @@ pub(crate) unsafe fn init(config: Config) { w.set_ppre2(config.apb2_pre); w.set_ppre3(config.apb3_pre); }); - - RCC.ccipr5().modify(|w| { - w.set_ckpersel(config.per_clock_source); - w.set_adcdacsel(config.adc_clock_source); - w.set_fdcan12sel(config.fdcan_clock_source) - }); } RCC.cfgr().modify(|w| w.set_timpre(config.timer_prescaler.into())); @@ -599,8 +641,13 @@ pub(crate) unsafe fn init(config: Config) { RCC.cfgr().modify(|w| w.set_sw(config.sys)); while RCC.cfgr().read().sws() != config.sys {} + // Disable HSI if not used + if config.hsi.is_none() { + RCC.cr().modify(|w| w.set_hsion(false)); + } + // IO compensation cell - Requires CSI clock and SYSCFG - #[cfg(stm32h7)] // TODO h5 + #[cfg(any(stm32h7))] // TODO h5, h7rs if csi.is_some() { // Enable the compensation cell, using back-bias voltage code // provide by the cell. @@ -611,54 +658,54 @@ pub(crate) unsafe fn init(config: Config) { w.set_hslv(false); }) }); - while !pac::SYSCFG.cccsr().read().ready() {} + while !pac::SYSCFG.cccsr().read().rdy() {} } - set_freqs(Clocks { - sys, - hclk1: hclk, - hclk2: hclk, - hclk3: hclk, - hclk4: hclk, - pclk1: apb1, - pclk2: apb2, - pclk3: apb3, - #[cfg(stm32h7)] - pclk4: apb4, - #[cfg(stm32h5)] - pclk4: Hertz(1), - pclk1_tim: apb1_tim, - pclk2_tim: apb2_tim, - adc, - rtc, + config.mux.init(); - #[cfg(any(stm32h5, stm32h7))] - hsi: None, - #[cfg(stm32h5)] - hsi48: None, - #[cfg(stm32h5)] - lsi: None, - #[cfg(any(stm32h5, stm32h7))] - csi: None, + set_clocks!( + sys: Some(sys), + hclk1: Some(hclk), + hclk2: Some(hclk), + hclk3: Some(hclk), + hclk4: Some(hclk), + #[cfg(stm32h7rs)] + hclk5: Some(hclk), + pclk1: Some(apb1), + pclk2: Some(apb2), + #[cfg(not(stm32h7rs))] + pclk3: Some(apb3), + #[cfg(any(stm32h7, stm32h7rs))] + pclk4: Some(apb4), + #[cfg(stm32h7rs)] + pclk5: Some(apb5), + + pclk1_tim: Some(apb1_tim), + pclk2_tim: Some(apb2_tim), + rtc: rtc, + + hsi: hsi, + hsi48: hsi48, + csi: csi, + csi_div_122: csi.map(|c| c / 122u32), + hse: hse, - #[cfg(any(stm32h5, stm32h7))] lse: None, - #[cfg(any(stm32h5, stm32h7))] - hse: None, + lsi: None, - #[cfg(any(stm32h5, stm32h7))] pll1_q: pll1.q, - #[cfg(any(stm32h5, stm32h7))] pll2_p: pll2.p, - #[cfg(any(stm32h5, stm32h7))] pll2_q: pll2.q, - #[cfg(any(stm32h5, stm32h7))] pll2_r: pll2.r, - #[cfg(any(rcc_h5, stm32h7))] + #[cfg(stm32h7rs)] + pll2_s: None, // TODO + #[cfg(stm32h7rs)] + pll2_t: None, // TODO + #[cfg(any(rcc_h5, stm32h7, stm32h7rs))] pll3_p: pll3.p, - #[cfg(any(rcc_h5, stm32h7))] + #[cfg(any(rcc_h5, stm32h7, stm32h7rs))] pll3_q: pll3.q, - #[cfg(any(rcc_h5, stm32h7))] + #[cfg(any(rcc_h5, stm32h7, stm32h7rs))] pll3_r: pll3.r, #[cfg(rcc_h50)] @@ -668,14 +715,21 @@ pub(crate) unsafe fn init(config: Config) { #[cfg(rcc_h50)] pll3_r: None, + #[cfg(dsihost)] + dsi_phy: None, // DSI PLL clock not supported, don't call `RccPeripheral::frequency()` in the drivers + #[cfg(stm32h5)] audioclk: None, - #[cfg(any(stm32h5, stm32h7))] - per: None, - - #[cfg(stm32h7)] - rcc_pclk_d3: None, - }); + i2s_ckin: None, + #[cfg(stm32h7rs)] + spdifrx_symb: None, // TODO + #[cfg(stm32h7rs)] + clk48mohci: None, // TODO + #[cfg(stm32h7rs)] + hse_div_2: hse.map(|clk| clk / 2u32), + #[cfg(stm32h7rs)] + usb: Some(Hertz(48_000_000)), + ); } struct PllInput { @@ -699,7 +753,7 @@ fn init_pll(num: usize, config: Option, input: &PllInput) -> PllOutput { while RCC.cr().read().pllrdy(num) {} // "To save power when PLL1 is not used, the value of PLL1M must be set to 0."" - #[cfg(stm32h7)] + #[cfg(any(stm32h7, stm32h7rs))] RCC.pllckselr().write(|w| w.set_divm(num, PllPreDiv::from_bits(0))); #[cfg(stm32h5)] RCC.pllcfgr(num).write(|w| w.set_divm(PllPreDiv::from_bits(0))); @@ -725,7 +779,7 @@ fn init_pll(num: usize, config: Option, input: &PllInput) -> PllOutput { ..=3_999_999 => Pllrge::RANGE2, ..=7_999_999 => Pllrge::RANGE4, ..=16_000_000 => Pllrge::RANGE8, - x => panic!("pll ref_clk out of range: {} mhz", x), + x => panic!("pll ref_clk out of range: {} hz", x), }; // The smaller range (150 to 420 MHz) must @@ -738,14 +792,14 @@ fn init_pll(num: usize, config: Option, input: &PllInput) -> PllOutput { } else if wide_allowed && VCO_WIDE_RANGE.contains(&vco_clk) { Pllvcosel::WIDEVCO } else { - panic!("pll vco_clk out of range: {} mhz", vco_clk.0) + panic!("pll vco_clk out of range: {} hz", vco_clk.0) }; let p = config.divp.map(|div| { if num == 0 { // on PLL1, DIVP must be even for most series. // The enum value is 1 less than the divider, so check it's odd. - #[cfg(not(pwr_h7rm0468))] + #[cfg(not(any(pwr_h7rm0468, stm32h7rs)))] assert!(div.to_bits() % 2 == 1); #[cfg(pwr_h7rm0468)] assert!(div.to_bits() % 2 == 1 || div.to_bits() == 0); @@ -768,7 +822,7 @@ fn init_pll(num: usize, config: Option, input: &PllInput) -> PllOutput { w.set_pllren(r.is_some()); }); - #[cfg(stm32h7)] + #[cfg(any(stm32h7, stm32h7rs))] { RCC.pllckselr().modify(|w| { w.set_divm(num, config.prediv); @@ -922,6 +976,26 @@ fn flash_setup(clk: Hertz, vos: VoltageScale) { (VoltageScale::Scale3, ..=88) => (3, 1), _ => unreachable!(), }; + #[cfg(flash_h7rs)] + let (latency, wrhighfreq) = match (vos, clk.0) { + // VOS high range VCORE 1.30V - 1.40V + (VoltageScale::HIGH, ..=40_000_000) => (0, 0), + (VoltageScale::HIGH, ..=80_000_000) => (1, 0), + (VoltageScale::HIGH, ..=120_000_000) => (2, 1), + (VoltageScale::HIGH, ..=160_000_000) => (3, 1), + (VoltageScale::HIGH, ..=200_000_000) => (4, 2), + (VoltageScale::HIGH, ..=240_000_000) => (5, 2), + (VoltageScale::HIGH, ..=280_000_000) => (6, 3), + (VoltageScale::HIGH, ..=320_000_000) => (7, 3), + // VOS low range VCORE 1.15V - 1.26V + (VoltageScale::LOW, ..=36_000_000) => (0, 0), + (VoltageScale::LOW, ..=72_000_000) => (1, 0), + (VoltageScale::LOW, ..=108_000_000) => (2, 1), + (VoltageScale::LOW, ..=144_000_000) => (3, 1), + (VoltageScale::LOW, ..=180_000_000) => (4, 2), + (VoltageScale::LOW, ..=216_000_000) => (5, 2), + _ => unreachable!(), + }; debug!("flash: latency={} wrhighfreq={}", latency, wrhighfreq); diff --git a/embassy-stm32/src/rcc/hsi48.rs b/embassy-stm32/src/rcc/hsi48.rs index 19a8c8cb9..efabd059f 100644 --- a/embassy-stm32/src/rcc/hsi48.rs +++ b/embassy-stm32/src/rcc/hsi48.rs @@ -2,7 +2,7 @@ use crate::pac::crs::vals::Syncsrc; use crate::pac::{CRS, RCC}; -use crate::rcc::sealed::RccPeripheral; +use crate::rcc::{self, SealedRccPeripheral}; use crate::time::Hertz; /// HSI48 speed @@ -33,9 +33,9 @@ pub(crate) fn init_hsi48(config: Hsi48Config) -> Hertz { }); // Enable HSI48 - #[cfg(not(any(stm32u5, stm32g0, stm32h5, stm32h7, stm32u5, stm32wba, stm32f0)))] + #[cfg(not(any(stm32u5, stm32g0, stm32h5, stm32h7, stm32h7rs, stm32u5, stm32wba, stm32f0)))] let r = RCC.crrcr(); - #[cfg(any(stm32u5, stm32g0, stm32h5, stm32h7, stm32u5, stm32wba))] + #[cfg(any(stm32u5, stm32g0, stm32h5, stm32h7, stm32h7rs, stm32u5, stm32wba))] let r = RCC.cr(); #[cfg(any(stm32f0))] let r = RCC.cr2(); @@ -44,7 +44,7 @@ pub(crate) fn init_hsi48(config: Hsi48Config) -> Hertz { while r.read().hsi48rdy() == false {} if config.sync_from_usb { - crate::peripherals::CRS::enable_and_reset(); + rcc::enable_and_reset::(); CRS.cfgr().modify(|w| { w.set_syncsrc(Syncsrc::USB); diff --git a/embassy-stm32/src/rcc/l.rs b/embassy-stm32/src/rcc/l.rs index 257fd83fe..6120d33be 100644 --- a/embassy-stm32/src/rcc/l.rs +++ b/embassy-stm32/src/rcc/l.rs @@ -1,15 +1,10 @@ #[cfg(any(stm32l0, stm32l1))] pub use crate::pac::pwr::vals::Vos as VoltageScale; use crate::pac::rcc::regs::Cfgr; -#[cfg(any(stm32l4, stm32l5, stm32wb, stm32wl))] -pub use crate::pac::rcc::vals::Adcsel as AdcClockSource; -#[cfg(any(rcc_l0_v2, stm32l4, stm32l5, stm32wb))] -pub use crate::pac::rcc::vals::Clk48sel as Clk48Src; #[cfg(any(stm32wb, stm32wl))] pub use crate::pac::rcc::vals::Hsepre as HsePrescaler; -pub use crate::pac::rcc::vals::{Hpre as AHBPrescaler, Msirange as MSIRange, Ppre as APBPrescaler, Sw as ClockSrc}; +pub use crate::pac::rcc::vals::{Hpre as AHBPrescaler, Msirange as MSIRange, Ppre as APBPrescaler, Sw as Sysclk}; use crate::pac::{FLASH, RCC}; -use crate::rcc::{set_freqs, Clocks}; use crate::time::Hertz; /// HSI speed @@ -35,6 +30,7 @@ pub struct Hse { } /// Clocks configuration +#[derive(Clone, Copy)] pub struct Config { // base clock sources pub msi: Option, @@ -51,27 +47,24 @@ pub struct Config { pub pllsai2: Option, // sysclk, buses. - pub mux: ClockSrc, + pub sys: Sysclk, pub ahb_pre: AHBPrescaler, pub apb1_pre: APBPrescaler, + #[cfg(not(stm32u0))] pub apb2_pre: APBPrescaler, #[cfg(any(stm32wl5x, stm32wb))] pub core2_ahb_pre: AHBPrescaler, #[cfg(any(stm32wl, stm32wb))] pub shared_ahb_pre: AHBPrescaler, - // muxes - #[cfg(any(rcc_l0_v2, stm32l4, stm32l5, stm32wb))] - pub clk48_src: Clk48Src, - // low speed LSI/LSE/RTC pub ls: super::LsConfig, - #[cfg(any(stm32l4, stm32l5, stm32wb, stm32wl))] - pub adc_clock_source: AdcClockSource, - #[cfg(any(stm32l0, stm32l1))] pub voltage_scale: VoltageScale, + + /// Per-peripheral kernel clock selection muxes + pub mux: super::mux::ClockMux, } impl Default for Config { @@ -81,9 +74,10 @@ impl Default for Config { hse: None, hsi: false, msi: Some(MSIRange::RANGE4M), - mux: ClockSrc::MSI, + sys: Sysclk::MSI, ahb_pre: AHBPrescaler::DIV1, apb1_pre: APBPrescaler::DIV1, + #[cfg(not(stm32u0))] apb2_pre: APBPrescaler::DIV1, #[cfg(any(stm32wl5x, stm32wb))] core2_ahb_pre: AHBPrescaler::DIV1, @@ -96,13 +90,10 @@ impl Default for Config { pllsai2: None, #[cfg(crs)] hsi48: Some(Default::default()), - #[cfg(any(rcc_l0_v2, stm32l4, stm32l5, stm32wb))] - clk48_src: Clk48Src::HSI48, ls: Default::default(), - #[cfg(any(stm32l4, stm32l5, stm32wb, stm32wl))] - adc_clock_source: AdcClockSource::SYS, #[cfg(any(stm32l0, stm32l1))] voltage_scale: VoltageScale::RANGE1, + mux: Default::default(), } } } @@ -114,12 +105,11 @@ pub const WPAN_DEFAULT: Config = Config { mode: HseMode::Oscillator, prescaler: HsePrescaler::DIV1, }), - mux: ClockSrc::PLL1_R, + sys: Sysclk::PLL1_R, #[cfg(crs)] hsi48: Some(super::Hsi48Config { sync_from_usb: false }), msi: None, hsi: false, - clk48_src: Clk48Src::PLL1_Q, ls: super::LsConfig::default_lse(), @@ -138,11 +128,12 @@ pub const WPAN_DEFAULT: Config = Config { shared_ahb_pre: AHBPrescaler::DIV1, apb1_pre: APBPrescaler::DIV1, apb2_pre: APBPrescaler::DIV1, - adc_clock_source: AdcClockSource::SYS, + + mux: super::mux::ClockMux::default(), }; fn msi_enable(range: MSIRange) { - #[cfg(any(stm32l4, stm32l5, stm32wb, stm32wl))] + #[cfg(any(stm32l4, stm32l5, stm32wb, stm32wl, stm32u0))] RCC.cr().modify(|w| { #[cfg(not(stm32wb))] w.set_msirgsel(crate::pac::rcc::vals::Msirgsel::CR); @@ -162,11 +153,18 @@ pub(crate) unsafe fn init(config: Config) { // Turn on MSI and configure it to 4MHz. msi_enable(MSIRange::RANGE4M) } - if RCC.cfgr().read().sws() != ClockSrc::MSI { + if RCC.cfgr().read().sws() != Sysclk::MSI { // Set MSI as a clock source, reset prescalers. RCC.cfgr().write_value(Cfgr::default()); // Wait for clock switch status bits to change. - while RCC.cfgr().read().sws() != ClockSrc::MSI {} + while RCC.cfgr().read().sws() != Sysclk::MSI {} + } + + #[cfg(stm32wl)] + { + // Set max latency + FLASH.acr().modify(|w| w.set_prften(true)); + FLASH.acr().modify(|w| w.set_latency(2)); } // Set voltage scale @@ -216,12 +214,9 @@ pub(crate) unsafe fn init(config: Config) { }); #[cfg(crs)] - let _hsi48 = config.hsi48.map(|config| { - // - super::init_hsi48(config) - }); + let hsi48 = config.hsi48.map(|config| super::init_hsi48(config)); #[cfg(not(crs))] - let _hsi48: Option = None; + let hsi48: Option = None; let _plls = [ &config.pll, @@ -255,35 +250,24 @@ pub(crate) unsafe fn init(config: Config) { let pll_input = PllInput { hse, hsi, - #[cfg(any(stm32l4, stm32l5, stm32wb, stm32wl))] + #[cfg(any(stm32l4, stm32l5, stm32wb, stm32wl, stm32u0))] msi, }; let pll = init_pll(PllInstance::Pll, config.pll, &pll_input); #[cfg(any(stm32l4, stm32l5, stm32wb))] let pllsai1 = init_pll(PllInstance::Pllsai1, config.pllsai1, &pll_input); #[cfg(any(stm32l47x, stm32l48x, stm32l49x, stm32l4ax, rcc_l4plus, stm32l5))] - let _pllsai2 = init_pll(PllInstance::Pllsai2, config.pllsai2, &pll_input); + let pllsai2 = init_pll(PllInstance::Pllsai2, config.pllsai2, &pll_input); - let sys_clk = match config.mux { - ClockSrc::HSE => hse.unwrap(), - ClockSrc::HSI => hsi.unwrap(), - ClockSrc::MSI => msi.unwrap(), - ClockSrc::PLL1_R => pll.r.unwrap(), - }; - - #[cfg(any(rcc_l0_v2, stm32l4, stm32l5, stm32wb))] - RCC.ccipr().modify(|w| w.set_clk48sel(config.clk48_src)); - #[cfg(any(rcc_l0_v2))] - let _clk48 = match config.clk48_src { - Clk48Src::HSI48 => _hsi48, - Clk48Src::PLL1_VCO_DIV_2 => pll.clk48, - }; - #[cfg(any(stm32l4, stm32l5, stm32wb))] - let _clk48 = match config.clk48_src { - Clk48Src::HSI48 => _hsi48, - Clk48Src::MSI => msi, - Clk48Src::PLLSAI1_Q => pllsai1.q, - Clk48Src::PLL1_Q => pll.q, + let sys_clk = match config.sys { + Sysclk::HSE => hse.unwrap(), + Sysclk::HSI => hsi.unwrap(), + Sysclk::MSI => msi.unwrap(), + Sysclk::PLL1_R => pll.r.unwrap(), + #[cfg(stm32u0)] + Sysclk::LSI | Sysclk::LSE => todo!(), + #[cfg(stm32u0)] + Sysclk::_RESERVED_6 | Sysclk::_RESERVED_7 => unreachable!(), }; #[cfg(rcc_l4plus)] @@ -293,6 +277,7 @@ pub(crate) unsafe fn init(config: Config) { let hclk1 = sys_clk / config.ahb_pre; let (pclk1, pclk1_tim) = super::util::calc_pclk(hclk1, config.apb1_pre); + #[cfg(not(stm32u0))] let (pclk2, pclk2_tim) = super::util::calc_pclk(hclk1, config.apb2_pre); #[cfg(any(stm32l4, stm32l5, stm32wlex))] let hclk2 = hclk1; @@ -345,6 +330,13 @@ pub(crate) unsafe fn init(config: Config) { ..=64_000_000 => 3, _ => 4, }; + #[cfg(stm32u0)] + let latency = match hclk1.0 { + // VOS RANGE1, others TODO. + ..=24_000_000 => 0, + ..=48_000_000 => 1, + _ => 2, + }; #[cfg(stm32l1)] FLASH.acr().write(|w| w.set_acc64(true)); @@ -354,15 +346,16 @@ pub(crate) unsafe fn init(config: Config) { while FLASH.acr().read().latency() != latency {} RCC.cfgr().modify(|w| { - w.set_sw(config.mux); + w.set_sw(config.sys); w.set_hpre(config.ahb_pre); + #[cfg(stm32u0)] + w.set_ppre(config.apb1_pre); + #[cfg(not(stm32u0))] w.set_ppre1(config.apb1_pre); + #[cfg(not(stm32u0))] w.set_ppre2(config.apb2_pre); }); - while RCC.cfgr().read().sws() != config.mux {} - - #[cfg(any(stm32l4, stm32l5, stm32wb, stm32wl))] - RCC.ccipr().modify(|w| w.set_adcsel(config.adc_clock_source)); + while RCC.cfgr().read().sws() != config.sys {} #[cfg(any(stm32wl, stm32wb))] { @@ -376,37 +369,69 @@ pub(crate) unsafe fn init(config: Config) { while !RCC.extcfgr().read().c2hpref() {} } - set_freqs(Clocks { - sys: sys_clk, - hclk1, + config.mux.init(); + + set_clocks!( + sys: Some(sys_clk), + hclk1: Some(hclk1), #[cfg(any(stm32l4, stm32l5, stm32wb, stm32wl))] - hclk2, + hclk2: Some(hclk2), #[cfg(any(stm32l4, stm32l5, stm32wb, stm32wl))] - hclk3, - pclk1, - pclk2, - pclk1_tim, - pclk2_tim, + hclk3: Some(hclk3), + pclk1: Some(pclk1), + #[cfg(not(stm32u0))] + pclk2: Some(pclk2), + pclk1_tim: Some(pclk1_tim), + #[cfg(not(stm32u0))] + pclk2_tim: Some(pclk2_tim), #[cfg(stm32wl)] - pclk3: hclk3, - #[cfg(rcc_l4)] - hsi: None, - #[cfg(rcc_l4)] - lse: None, - #[cfg(rcc_l4)] - pllsai1_p: None, - #[cfg(rcc_l4)] + pclk3: Some(hclk3), + hsi: hsi, + hse: hse, + msi: msi, + hsi48: hsi48, + + #[cfg(any(stm32l0, stm32l1))] + pll1_vco_div_2: pll.vco.map(|c| c/2u32), + + #[cfg(not(any(stm32l0, stm32l1)))] + pll1_p: pll.p, + #[cfg(not(any(stm32l0, stm32l1)))] + pll1_q: pll.q, + pll1_r: pll.r, + + #[cfg(any(stm32l4, stm32l5, stm32wb))] + pllsai1_p: pllsai1.p, + #[cfg(any(stm32l4, stm32l5, stm32wb))] + pllsai1_q: pllsai1.q, + #[cfg(any(stm32l4, stm32l5, stm32wb))] + pllsai1_r: pllsai1.r, + + #[cfg(not(any(stm32l47x, stm32l48x, stm32l49x, stm32l4ax, rcc_l4plus, stm32l5)))] pllsai2_p: None, - #[cfg(rcc_l4)] - pll1_p: None, - #[cfg(rcc_l4)] - pll1_q: None, - #[cfg(rcc_l4)] + #[cfg(not(any(stm32l47x, stm32l48x, stm32l49x, stm32l4ax, rcc_l4plus, stm32l5)))] + pllsai2_q: None, + #[cfg(not(any(stm32l47x, stm32l48x, stm32l49x, stm32l4ax, rcc_l4plus, stm32l5)))] + pllsai2_r: None, + + #[cfg(any(stm32l47x, stm32l48x, stm32l49x, stm32l4ax, rcc_l4plus, stm32l5))] + pllsai2_p: pllsai2.p, + #[cfg(any(stm32l47x, stm32l48x, stm32l49x, stm32l4ax, rcc_l4plus, stm32l5))] + pllsai2_q: pllsai2.q, + #[cfg(any(stm32l47x, stm32l48x, stm32l49x, stm32l4ax, rcc_l4plus, stm32l5))] + pllsai2_r: pllsai2.r, + + #[cfg(dsihost)] + dsi_phy: None, // DSI PLL clock not supported, don't call `RccPeripheral::frequency()` in the drivers + + rtc: rtc, + + // TODO sai1_extclk: None, - #[cfg(rcc_l4)] sai2_extclk: None, - rtc, - }); + lsi: None, + lse: None, + ); } #[cfg(any(stm32l0, stm32l1))] @@ -414,7 +439,7 @@ fn msirange_to_hertz(range: MSIRange) -> Hertz { Hertz(32_768 * (1 << (range as u8 + 1))) } -#[cfg(any(stm32l4, stm32l5, stm32wb, stm32wl))] +#[cfg(any(stm32l4, stm32l5, stm32wb, stm32wl, stm32u0))] fn msirange_to_hertz(range: MSIRange) -> Hertz { match range { MSIRange::RANGE100K => Hertz(100_000), @@ -491,7 +516,7 @@ mod pll { #[derive(Default)] pub(super) struct PllOutput { pub r: Option, - pub clk48: Option, + pub vco: Option, } pub(super) fn init_pll(instance: PllInstance, config: Option, input: &PllInput) -> PllOutput { @@ -508,7 +533,6 @@ mod pll { let vco_freq = pll_src * pll.mul; let r = vco_freq / pll.div; - let clk48 = (vco_freq == Hertz(96_000_000)).then_some(Hertz(48_000_000)); assert!(r <= Hertz(32_000_000)); @@ -521,11 +545,14 @@ mod pll { // Enable PLL pll_enable(instance, true); - PllOutput { r: Some(r), clk48 } + PllOutput { + r: Some(r), + vco: Some(vco_freq), + } } } -#[cfg(any(stm32l4, stm32l5, stm32wb, stm32wl))] +#[cfg(any(stm32l4, stm32l5, stm32wb, stm32wl, stm32u0))] mod pll { use super::{pll_enable, PllInstance}; pub use crate::pac::rcc::vals::{ diff --git a/embassy-stm32/src/rcc/mco.rs b/embassy-stm32/src/rcc/mco.rs index eaaf8071c..d1ce14c86 100644 --- a/embassy-stm32/src/rcc/mco.rs +++ b/embassy-stm32/src/rcc/mco.rs @@ -2,34 +2,63 @@ use core::marker::PhantomData; use embassy_hal_internal::into_ref; -use crate::gpio::sealed::AFType; -use crate::gpio::Speed; -#[cfg(not(stm32f1))] +use crate::gpio::{AfType, OutputType, Speed}; +#[cfg(not(any(stm32f1, rcc_f0v1, rcc_f3v1, rcc_f37)))] pub use crate::pac::rcc::vals::Mcopre as McoPrescaler; -#[cfg(not(any(rcc_f2, rcc_f410, rcc_f4, rcc_f7, rcc_h50, rcc_h5, rcc_h7ab, rcc_h7rm0433, rcc_h7)))] +#[cfg(not(any( + rcc_f2, + rcc_f410, + rcc_f4, + rcc_f7, + rcc_h50, + rcc_h5, + rcc_h7ab, + rcc_h7rm0433, + rcc_h7, + rcc_h7rs +)))] pub use crate::pac::rcc::vals::Mcosel as McoSource; -#[cfg(any(rcc_f2, rcc_f410, rcc_f4, rcc_f7, rcc_h50, rcc_h5, rcc_h7ab, rcc_h7rm0433, rcc_h7))] +#[cfg(any( + rcc_f2, + rcc_f410, + rcc_f4, + rcc_f7, + rcc_h50, + rcc_h5, + rcc_h7ab, + rcc_h7rm0433, + rcc_h7, + rcc_h7rs +))] pub use crate::pac::rcc::vals::{Mco1sel as Mco1Source, Mco2sel as Mco2Source}; use crate::pac::RCC; use crate::{peripherals, Peripheral}; -pub(crate) mod sealed { - pub trait McoInstance { - type Source; - unsafe fn apply_clock_settings(source: Self::Source, #[cfg(not(stm32f1))] prescaler: super::McoPrescaler); - } +#[cfg(any(stm32f1, rcc_f0v1, rcc_f3v1, rcc_f37))] +#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] +pub enum McoPrescaler { + DIV1, } -pub trait McoInstance: sealed::McoInstance + 'static {} +pub(crate) trait SealedMcoInstance {} + +#[allow(private_bounds)] +pub trait McoInstance: SealedMcoInstance + 'static { + type Source; + + #[doc(hidden)] + unsafe fn _apply_clock_settings(source: Self::Source, prescaler: super::McoPrescaler); +} pin_trait!(McoPin, McoInstance); macro_rules! impl_peri { ($peri:ident, $source:ident, $set_source:ident, $set_prescaler:ident) => { - impl sealed::McoInstance for peripherals::$peri { + impl SealedMcoInstance for peripherals::$peri {} + impl McoInstance for peripherals::$peri { type Source = $source; - unsafe fn apply_clock_settings(source: Self::Source, #[cfg(not(stm32f1))] prescaler: McoPrescaler) { + unsafe fn _apply_clock_settings(source: Self::Source, _prescaler: McoPrescaler) { #[cfg(not(any(stm32u5, stm32wba)))] let r = RCC.cfgr(); #[cfg(any(stm32u5, stm32wba))] @@ -37,17 +66,15 @@ macro_rules! impl_peri { r.modify(|w| { w.$set_source(source); - #[cfg(not(stm32f1))] - w.$set_prescaler(prescaler); + #[cfg(not(any(stm32f1, rcc_f0v1, rcc_f3v1, rcc_f37)))] + w.$set_prescaler(_prescaler); }); } } - - impl McoInstance for peripherals::$peri {} }; } -#[cfg(any(rcc_c0, rcc_g0))] +#[cfg(any(rcc_c0, rcc_g0, rcc_u0))] #[allow(unused_imports)] use self::{McoSource as Mco1Source, McoSource as Mco2Source}; @@ -68,18 +95,13 @@ impl<'d, T: McoInstance> Mco<'d, T> { _peri: impl Peripheral

+ 'd, pin: impl Peripheral

> + 'd, source: T::Source, - #[cfg(not(stm32f1))] prescaler: McoPrescaler, + prescaler: McoPrescaler, ) -> Self { into_ref!(pin); critical_section::with(|_| unsafe { - T::apply_clock_settings( - source, - #[cfg(not(stm32f1))] - prescaler, - ); - pin.set_as_af(pin.af_num(), AFType::OutputPushPull); - pin.set_speed(Speed::VeryHigh); + T::_apply_clock_settings(source, prescaler); + pin.set_as_af(pin.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); }); Self { phantom: PhantomData } diff --git a/embassy-stm32/src/rcc/mod.rs b/embassy-stm32/src/rcc/mod.rs index 240ffc6d2..4f43d3748 100644 --- a/embassy-stm32/src/rcc/mod.rs +++ b/embassy-stm32/src/rcc/mod.rs @@ -5,11 +5,13 @@ use core::mem::MaybeUninit; -use crate::time::Hertz; - mod bd; -mod mco; pub use bd::*; + +#[cfg(any(mco, mco1, mco2))] +mod mco; +use critical_section::CriticalSection; +#[cfg(any(mco, mco1, mco2))] pub use mco::*; #[cfg(crs)] @@ -17,177 +19,22 @@ mod hsi48; #[cfg(crs)] pub use hsi48::*; -#[cfg_attr(rcc_f0, path = "f0.rs")] -#[cfg_attr(any(stm32f1), path = "f1.rs")] -#[cfg_attr(any(stm32f3), path = "f3.rs")] -#[cfg_attr(any(stm32f2, stm32f4, stm32f7), path = "f.rs")] -#[cfg_attr(rcc_c0, path = "c0.rs")] -#[cfg_attr(rcc_g0, path = "g0.rs")] -#[cfg_attr(rcc_g4, path = "g4.rs")] -#[cfg_attr(any(stm32h5, stm32h7), path = "h.rs")] -#[cfg_attr(any(stm32l0, stm32l1, stm32l4, stm32l5, stm32wb, stm32wl), path = "l.rs")] -#[cfg_attr(rcc_u5, path = "u5.rs")] -#[cfg_attr(rcc_wba, path = "wba.rs")] +#[cfg_attr(any(stm32f0, stm32f1, stm32f3), path = "f013.rs")] +#[cfg_attr(any(stm32f2, stm32f4, stm32f7), path = "f247.rs")] +#[cfg_attr(stm32c0, path = "c0.rs")] +#[cfg_attr(stm32g0, path = "g0.rs")] +#[cfg_attr(stm32g4, path = "g4.rs")] +#[cfg_attr(any(stm32h5, stm32h7, stm32h7rs), path = "h.rs")] +#[cfg_attr(any(stm32l0, stm32l1, stm32l4, stm32l5, stm32wb, stm32wl, stm32u0), path = "l.rs")] +#[cfg_attr(stm32u5, path = "u5.rs")] +#[cfg_attr(stm32wba, path = "wba.rs")] mod _version; pub use _version::*; +use stm32_metapac::RCC; -// Model Clock Configuration -// -// pub struct Clocks { -// hse: Option, -// hsi: bool, -// lse: Option, -// lsi: bool, -// rtc: RtcSource, -// } - -#[derive(Clone, Copy, Debug)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub struct Clocks { - pub sys: Hertz, - - // APB - pub pclk1: Hertz, - pub pclk1_tim: Hertz, - #[cfg(not(any(rcc_c0, rcc_g0)))] - pub pclk2: Hertz, - #[cfg(not(any(rcc_c0, rcc_g0)))] - pub pclk2_tim: Hertz, - #[cfg(any(rcc_wl5, rcc_wle, rcc_h5, rcc_h50, rcc_h7, rcc_h7rm0433, rcc_h7ab, rcc_u5))] - pub pclk3: Hertz, - #[cfg(any(rcc_h7, rcc_h7rm0433, rcc_h7ab, stm32h5))] - pub pclk4: Hertz, - #[cfg(any(rcc_wba))] - pub pclk7: Hertz, - - // AHB - pub hclk1: Hertz, - #[cfg(any( - rcc_l4, - rcc_l4plus, - rcc_l5, - rcc_f2, - rcc_f4, - rcc_f410, - rcc_f7, - rcc_h5, - rcc_h50, - rcc_h7, - rcc_h7rm0433, - rcc_h7ab, - rcc_g4, - rcc_u5, - rcc_wb, - rcc_wba, - rcc_wl5, - rcc_wle - ))] - pub hclk2: Hertz, - #[cfg(any( - rcc_l4, - rcc_l4plus, - rcc_l5, - rcc_f2, - rcc_f4, - rcc_f410, - rcc_f7, - rcc_h5, - rcc_h50, - rcc_h7, - rcc_h7rm0433, - rcc_h7ab, - rcc_u5, - rcc_g4, - rcc_wb, - rcc_wl5, - rcc_wle - ))] - pub hclk3: Hertz, - #[cfg(any(rcc_h5, rcc_h50, rcc_h7, rcc_h7rm0433, rcc_h7ab, rcc_wba))] - pub hclk4: Hertz, - - #[cfg(all(rcc_f4, not(stm32f410)))] - pub plli2s1_q: Option, - #[cfg(all(rcc_f4, not(stm32f410)))] - pub plli2s1_r: Option, - - #[cfg(rcc_l4)] - pub pllsai1_p: Option, - #[cfg(any(stm32f427, stm32f429, stm32f437, stm32f439, stm32f446, stm32f469, stm32f479))] - pub pllsai1_q: Option, - #[cfg(any(stm32f427, stm32f429, stm32f437, stm32f439, stm32f446, stm32f469, stm32f479))] - pub pllsai1_r: Option, - #[cfg(rcc_l4)] - pub pllsai2_p: Option, - - #[cfg(any(stm32g0, stm32g4, rcc_l4))] - pub pll1_p: Option, - #[cfg(any(stm32h5, stm32h7, stm32f2, stm32f4, stm32f7, rcc_l4, stm32g0, stm32g4))] - pub pll1_q: Option, - #[cfg(any(stm32h5, stm32h7))] - pub pll2_p: Option, - #[cfg(any(stm32h5, stm32h7))] - pub pll2_q: Option, - #[cfg(any(stm32h5, stm32h7))] - pub pll2_r: Option, - #[cfg(any(stm32h5, stm32h7))] - pub pll3_p: Option, - #[cfg(any(stm32h5, stm32h7))] - pub pll3_q: Option, - #[cfg(any(stm32h5, stm32h7))] - pub pll3_r: Option, - - #[cfg(any( - rcc_f1, - rcc_f100, - rcc_f1cl, - rcc_h5, - rcc_h50, - rcc_h7, - rcc_h7rm0433, - rcc_h7ab, - rcc_f3, - rcc_g4 - ))] - pub adc: Option, - - #[cfg(any(rcc_f3, rcc_g4))] - pub adc34: Option, - - #[cfg(stm32f334)] - pub hrtim: Option, - - pub rtc: Option, - - #[cfg(any(stm32h5, stm32h7, rcc_l4, rcc_c0, stm32g0))] - pub hsi: Option, - #[cfg(any(stm32h5, stm32g0))] - pub hsi48: Option, - #[cfg(stm32g0)] - pub hsi_div_8: Option, - #[cfg(any(stm32g0, stm32h5))] - pub lsi: Option, - #[cfg(any(stm32h5, stm32h7))] - pub csi: Option, - - #[cfg(any(stm32h5, stm32h7, rcc_l4, rcc_c0, stm32g0))] - pub lse: Option, - #[cfg(any(stm32h5, stm32h7, stm32g0, stm32g4))] - pub hse: Option, - - #[cfg(stm32h5)] - pub audioclk: Option, - #[cfg(any(stm32h5, stm32h7))] - pub per: Option, - - #[cfg(stm32h7)] - pub rcc_pclk_d3: Option, - #[cfg(rcc_l4)] - pub sai1_extclk: Option, - #[cfg(rcc_l4)] - pub sai2_extclk: Option, -} +pub use crate::_generated::{mux, Clocks}; +use crate::time::Hertz; #[cfg(feature = "low-power")] /// Must be written within a critical section @@ -201,11 +48,22 @@ pub(crate) static mut REFCOUNT_STOP1: u32 = 0; /// May be read without a critical section pub(crate) static mut REFCOUNT_STOP2: u32 = 0; +#[cfg(not(feature = "_dual-core"))] /// Frozen clock frequencies /// /// The existence of this value indicates that the clock configuration can no longer be changed static mut CLOCK_FREQS: MaybeUninit = MaybeUninit::uninit(); +#[cfg(feature = "_dual-core")] +static CLOCK_FREQS_PTR: core::sync::atomic::AtomicPtr> = + core::sync::atomic::AtomicPtr::new(core::ptr::null_mut()); + +#[cfg(feature = "_dual-core")] +pub(crate) fn set_freqs_ptr(freqs: *mut MaybeUninit) { + CLOCK_FREQS_PTR.store(freqs, core::sync::atomic::Ordering::SeqCst); +} + +#[cfg(not(feature = "_dual-core"))] /// Sets the clock frequencies /// /// Safety: Sets a mutable global. @@ -214,34 +72,224 @@ pub(crate) unsafe fn set_freqs(freqs: Clocks) { CLOCK_FREQS = MaybeUninit::new(freqs); } +#[cfg(feature = "_dual-core")] +/// Sets the clock frequencies +/// +/// Safety: Sets a mutable global. +pub(crate) unsafe fn set_freqs(freqs: Clocks) { + debug!("rcc: {:?}", freqs); + CLOCK_FREQS_PTR + .load(core::sync::atomic::Ordering::SeqCst) + .write(MaybeUninit::new(freqs)); +} + +#[cfg(not(feature = "_dual-core"))] /// Safety: Reads a mutable global. pub(crate) unsafe fn get_freqs() -> &'static Clocks { - CLOCK_FREQS.assume_init_ref() + (*core::ptr::addr_of_mut!(CLOCK_FREQS)).assume_init_ref() } -#[cfg(feature = "unstable-pac")] -pub mod low_level { - pub use super::sealed::*; +#[cfg(feature = "_dual-core")] +/// Safety: Reads a mutable global. +pub(crate) unsafe fn get_freqs() -> &'static Clocks { + unwrap!(CLOCK_FREQS_PTR.load(core::sync::atomic::Ordering::SeqCst).as_ref()).assume_init_ref() } -pub(crate) mod sealed { - use critical_section::CriticalSection; +pub(crate) trait SealedRccPeripheral { + fn frequency() -> Hertz; + const RCC_INFO: RccInfo; +} - pub trait RccPeripheral { - fn frequency() -> crate::time::Hertz; - fn enable_and_reset_with_cs(cs: CriticalSection); - fn disable_with_cs(cs: CriticalSection); +#[allow(private_bounds)] +pub trait RccPeripheral: SealedRccPeripheral + 'static {} - fn enable_and_reset() { - critical_section::with(|cs| Self::enable_and_reset_with_cs(cs)) - } - fn disable() { - critical_section::with(|cs| Self::disable_with_cs(cs)) +/// Runtime information necessary to reset, enable and disable a peripheral. +pub(crate) struct RccInfo { + /// Offset in 32-bit words of the xxxRSTR register into the RCC register block, or 0xff if the + /// peripheral has no reset bit (we don't use an `Option` to save one byte of storage). + reset_offset_or_0xff: u8, + /// Position of the xxxRST bit within the xxxRSTR register (0..=31). + reset_bit: u8, + /// Offset in 32-bit words of the xxxENR register into the RCC register block. + enable_offset: u8, + /// Position of the xxxEN bit within the xxxENR register (0..=31). + enable_bit: u8, + /// If this peripheral shares the same xxxRSTR bit and xxxEN bit with other peripherals, we + /// maintain a refcount in `crate::_generated::REFCOUNTS` at this index. If the bit is not + /// shared, this is 0xff (we don't use an `Option` to save one byte of storage). + refcount_idx_or_0xff: u8, + /// Stop mode of the peripheral, used to maintain `REFCOUNT_STOP1` and `REFCOUNT_STOP2`. + #[cfg(feature = "low-power")] + stop_mode: StopMode, +} + +#[cfg(feature = "low-power")] +#[allow(dead_code)] +pub(crate) enum StopMode { + Standby, + Stop2, + Stop1, +} + +impl RccInfo { + /// Safety: + /// - `reset_offset_and_bit`, if set, must correspond to valid xxxRST bit + /// - `enable_offset_and_bit` must correspond to valid xxxEN bit + /// - `refcount_idx`, if set, must correspond to valid refcount in `_generated::REFCOUNTS` + /// - `stop_mode` must be valid + pub(crate) const unsafe fn new( + reset_offset_and_bit: Option<(u8, u8)>, + enable_offset_and_bit: (u8, u8), + refcount_idx: Option, + #[cfg(feature = "low-power")] stop_mode: StopMode, + ) -> Self { + let (reset_offset_or_0xff, reset_bit) = match reset_offset_and_bit { + Some((offset, bit)) => (offset, bit), + None => (0xff, 0xff), + }; + let (enable_offset, enable_bit) = enable_offset_and_bit; + let refcount_idx_or_0xff = match refcount_idx { + Some(idx) => idx, + None => 0xff, + }; + Self { + reset_offset_or_0xff, + reset_bit, + enable_offset, + enable_bit, + refcount_idx_or_0xff, + #[cfg(feature = "low-power")] + stop_mode, } } -} -pub trait RccPeripheral: sealed::RccPeripheral + 'static {} + // TODO: should this be `unsafe`? + pub(crate) fn enable_and_reset_with_cs(&self, _cs: CriticalSection) { + if self.refcount_idx_or_0xff != 0xff { + let refcount_idx = self.refcount_idx_or_0xff as usize; + + // Use .get_mut instead of []-operator so that we control how bounds checks happen. + // Otherwise, core::fmt will be pulled in here in order to format the integer in the + // out-of-bounds error. + if let Some(refcount) = + unsafe { (*core::ptr::addr_of_mut!(crate::_generated::REFCOUNTS)).get_mut(refcount_idx) } + { + *refcount += 1; + if *refcount > 1 { + return; + } + } else { + panic!("refcount_idx out of bounds: {}", refcount_idx) + } + } + + #[cfg(feature = "low-power")] + match self.stop_mode { + StopMode::Standby => {} + StopMode::Stop2 => unsafe { + REFCOUNT_STOP2 += 1; + }, + StopMode::Stop1 => unsafe { + REFCOUNT_STOP1 += 1; + }, + } + + // set the xxxRST bit + let reset_ptr = self.reset_ptr(); + if let Some(reset_ptr) = reset_ptr { + unsafe { + let val = reset_ptr.read_volatile(); + reset_ptr.write_volatile(val | 1u32 << self.reset_bit); + } + } + + // set the xxxEN bit + let enable_ptr = self.enable_ptr(); + unsafe { + let val = enable_ptr.read_volatile(); + enable_ptr.write_volatile(val | 1u32 << self.enable_bit); + } + + // we must wait two peripheral clock cycles before the clock is active + // this seems to work, but might be incorrect + // see http://efton.sk/STM32/gotcha/g183.html + + // dummy read (like in the ST HALs) + let _ = unsafe { enable_ptr.read_volatile() }; + + // DSB for good measure + cortex_m::asm::dsb(); + + // clear the xxxRST bit + if let Some(reset_ptr) = reset_ptr { + unsafe { + let val = reset_ptr.read_volatile(); + reset_ptr.write_volatile(val & !(1u32 << self.reset_bit)); + } + } + } + + // TODO: should this be `unsafe`? + pub(crate) fn disable_with_cs(&self, _cs: CriticalSection) { + if self.refcount_idx_or_0xff != 0xff { + let refcount_idx = self.refcount_idx_or_0xff as usize; + + // Use .get_mut instead of []-operator so that we control how bounds checks happen. + // Otherwise, core::fmt will be pulled in here in order to format the integer in the + // out-of-bounds error. + if let Some(refcount) = + unsafe { (*core::ptr::addr_of_mut!(crate::_generated::REFCOUNTS)).get_mut(refcount_idx) } + { + *refcount -= 1; + if *refcount > 0 { + return; + } + } else { + panic!("refcount_idx out of bounds: {}", refcount_idx) + } + } + + #[cfg(feature = "low-power")] + match self.stop_mode { + StopMode::Standby => {} + StopMode::Stop2 => unsafe { + REFCOUNT_STOP2 -= 1; + }, + StopMode::Stop1 => unsafe { + REFCOUNT_STOP1 -= 1; + }, + } + + // clear the xxxEN bit + let enable_ptr = self.enable_ptr(); + unsafe { + let val = enable_ptr.read_volatile(); + enable_ptr.write_volatile(val & !(1u32 << self.enable_bit)); + } + } + + // TODO: should this be `unsafe`? + pub(crate) fn enable_and_reset(&self) { + critical_section::with(|cs| self.enable_and_reset_with_cs(cs)) + } + + // TODO: should this be `unsafe`? + pub(crate) fn disable(&self) { + critical_section::with(|cs| self.disable_with_cs(cs)) + } + + fn reset_ptr(&self) -> Option<*mut u32> { + if self.reset_offset_or_0xff != 0xff { + Some(unsafe { (RCC.as_ptr() as *mut u32).add(self.reset_offset_or_0xff as _) }) + } else { + None + } + } + + fn enable_ptr(&self) -> *mut u32 { + unsafe { (RCC.as_ptr() as *mut u32).add(self.enable_offset as _) } + } +} #[allow(unused)] mod util { @@ -272,3 +320,52 @@ mod util { Ok(Some(x)) } } + +/// Get the kernel clock frequency of the peripheral `T`. +/// +/// # Panics +/// +/// Panics if the clock is not active. +pub fn frequency() -> Hertz { + T::frequency() +} + +/// Enables and resets peripheral `T`. +/// +/// # Safety +/// +/// Peripheral must not be in use. +// TODO: should this be `unsafe`? +pub fn enable_and_reset_with_cs(cs: CriticalSection) { + T::RCC_INFO.enable_and_reset_with_cs(cs); +} + +/// Disables peripheral `T`. +/// +/// # Safety +/// +/// Peripheral must not be in use. +// TODO: should this be `unsafe`? +pub fn disable_with_cs(cs: CriticalSection) { + T::RCC_INFO.disable_with_cs(cs); +} + +/// Enables and resets peripheral `T`. +/// +/// # Safety +/// +/// Peripheral must not be in use. +// TODO: should this be `unsafe`? +pub fn enable_and_reset() { + T::RCC_INFO.enable_and_reset(); +} + +/// Disables peripheral `T`. +/// +/// # Safety +/// +/// Peripheral must not be in use. +// TODO: should this be `unsafe`? +pub fn disable() { + T::RCC_INFO.disable(); +} diff --git a/embassy-stm32/src/rcc/u5.rs b/embassy-stm32/src/rcc/u5.rs index dff08dc9b..af99c77bc 100644 --- a/embassy-stm32/src/rcc/u5.rs +++ b/embassy-stm32/src/rcc/u5.rs @@ -1,135 +1,86 @@ -pub use crate::pac::rcc::vals::{Hpre as AHBPrescaler, Msirange, Plldiv, Pllm, Plln, Ppre as APBPrescaler}; -use crate::pac::rcc::vals::{Msirgsel, Pllmboost, Pllrge, Pllsrc, Sw}; +pub use crate::pac::pwr::vals::Vos as VoltageScale; +pub use crate::pac::rcc::vals::{ + Hpre as AHBPrescaler, Msirange, Msirange as MSIRange, Plldiv as PllDiv, Pllm as PllPreDiv, Plln as PllMul, + Pllsrc as PllSource, Ppre as APBPrescaler, Sw as Sysclk, +}; +use crate::pac::rcc::vals::{Hseext, Msirgsel, Pllmboost, Pllrge}; use crate::pac::{FLASH, PWR, RCC}; -use crate::rcc::{set_freqs, Clocks}; +use crate::rcc::LSI_FREQ; use crate::time::Hertz; /// HSI speed pub const HSI_FREQ: Hertz = Hertz(16_000_000); -pub use crate::pac::pwr::vals::Vos as VoltageScale; - -#[derive(Copy, Clone)] -#[allow(non_camel_case_types)] -pub enum ClockSrc { - /// Use an internal medium speed oscillator (MSIS) as the system clock. - MSI(Msirange), - /// Use the external high speed clock as the system clock. - /// - /// HSE clocks faster than 25 MHz require at least `VoltageScale::RANGE3`, and HSE clocks must - /// never exceed 50 MHz. - HSE(Hertz), - /// Use the 16 MHz internal high speed oscillator as the system clock. - HSI, - /// Use PLL1 as the system clock. - PLL1_R(PllConfig), +#[derive(Clone, Copy, Eq, PartialEq)] +pub enum HseMode { + /// crystal/ceramic oscillator (HSEBYP=0) + Oscillator, + /// external analog clock (low swing) (HSEBYP=1, HSEEXT=0) + Bypass, + /// external digital clock (full swing) (HSEBYP=1, HSEEXT=1) + BypassDigital, } -impl Default for ClockSrc { - fn default() -> Self { - // The default system clock source is MSIS @ 4 MHz, per RM0456 § 11.4.9 - ClockSrc::MSI(Msirange::RANGE_4MHZ) - } +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct Hse { + /// HSE frequency. + pub freq: Hertz, + /// HSE mode. + pub mode: HseMode, } #[derive(Clone, Copy)] -pub struct PllConfig { +pub struct Pll { /// The clock source for the PLL. pub source: PllSource, - /// The PLL prescaler. + /// The PLL pre-divider. /// /// The clock speed of the `source` divided by `m` must be between 4 and 16 MHz. - pub m: Pllm, + pub prediv: PllPreDiv, /// The PLL multiplier. /// /// The multiplied clock – `source` divided by `m` times `n` – must be between 128 and 544 /// MHz. The upper limit may be lower depending on the `Config { voltage_range }`. - pub n: Plln, + pub mul: PllMul, /// The divider for the P output. /// /// The P output is one of several options /// that can be used to feed the SAI/MDF/ADF Clock mux's. - pub p: Plldiv, + pub divp: Option, /// The divider for the Q output. /// /// The Q ouput is one of severals options that can be used to feed the 48MHz clocks /// and the OCTOSPI clock. It may also be used on the MDF/ADF clock mux's. - pub q: Plldiv, + pub divq: Option, /// The divider for the R output. /// /// When used to drive the system clock, `source` divided by `m` times `n` divided by `r` /// must not exceed 160 MHz. System clocks above 55 MHz require a non-default /// `Config { voltage_range }`. - pub r: Plldiv, -} - -impl PllConfig { - /// A configuration for HSI / 1 * 10 / 1 = 160 MHz - pub const fn hsi_160mhz() -> Self { - PllConfig { - source: PllSource::HSI, - m: Pllm::DIV1, - n: Plln::MUL10, - p: Plldiv::DIV3, - q: Plldiv::DIV2, - r: Plldiv::DIV1, - } - } - - /// A configuration for MSIS @ 48 MHz / 3 * 10 / 1 = 160 MHz - pub const fn msis_160mhz() -> Self { - PllConfig { - source: PllSource::MSIS(Msirange::RANGE_48MHZ), - m: Pllm::DIV3, - n: Plln::MUL10, - p: Plldiv::DIV3, - q: Plldiv::DIV2, - r: Plldiv::DIV1, - } - } + pub divr: Option, } #[derive(Clone, Copy)] -pub enum PllSource { - /// Use an internal medium speed oscillator as the PLL source. - MSIS(Msirange), - /// Use the external high speed clock as the system PLL source. - /// - /// HSE clocks faster than 25 MHz require at least `VoltageScale::RANGE3`, and HSE clocks must - /// never exceed 50 MHz. - HSE(Hertz), - /// Use the 16 MHz internal high speed oscillator as the PLL source. - HSI, -} - -impl Into for PllSource { - fn into(self) -> Pllsrc { - match self { - PllSource::MSIS(..) => Pllsrc::MSIS, - PllSource::HSE(..) => Pllsrc::HSE, - PllSource::HSI => Pllsrc::HSI, - } - } -} - -impl Into for ClockSrc { - fn into(self) -> Sw { - match self { - ClockSrc::MSI(..) => Sw::MSIS, - ClockSrc::HSE(..) => Sw::HSE, - ClockSrc::HSI => Sw::HSI, - ClockSrc::PLL1_R(..) => Sw::PLL1_R, - } - } -} - pub struct Config { - pub mux: ClockSrc, + // base clock sources + pub msis: Option, + pub msik: Option, + pub hsi: bool, + pub hse: Option, + pub hsi48: Option, + + // pll + pub pll1: Option, + pub pll2: Option, + pub pll3: Option, + + // sysclk, buses. + pub sys: Sysclk, pub ahb_pre: AHBPrescaler, pub apb1_pre: APBPrescaler, pub apb2_pre: APBPrescaler, pub apb3_pre: APBPrescaler, - pub hsi48: Option, + /// The voltage range influences the maximum clock frequencies for different parts of the /// device. In particular, system clocks exceeding 110 MHz require `RANGE1`, and system clocks /// exceeding 55 MHz require at least `RANGE2`. @@ -137,37 +88,42 @@ pub struct Config { /// See RM0456 § 10.5.4 for a general overview and § 11.4.10 for clock source frequency limits. pub voltage_range: VoltageScale, pub ls: super::LsConfig, + + /// Per-peripheral kernel clock selection muxes + pub mux: super::mux::ClockMux, } -impl Config { - unsafe fn init_hsi(&self) -> Hertz { - RCC.cr().write(|w| w.set_hsion(true)); - while !RCC.cr().read().hsirdy() {} - - HSI_FREQ - } - - unsafe fn init_hse(&self, frequency: Hertz) -> Hertz { - // Check frequency limits per RM456 § 11.4.10 - match self.voltage_range { - VoltageScale::RANGE1 | VoltageScale::RANGE2 | VoltageScale::RANGE3 => { - assert!(frequency.0 <= 50_000_000); - } - VoltageScale::RANGE4 => { - assert!(frequency.0 <= 25_000_000); - } +impl Default for Config { + fn default() -> Self { + Self { + msis: Some(Msirange::RANGE_4MHZ), + msik: Some(Msirange::RANGE_4MHZ), + hse: None, + hsi: false, + hsi48: Some(Default::default()), + pll1: None, + pll2: None, + pll3: None, + sys: Sysclk::MSIS, + ahb_pre: AHBPrescaler::DIV1, + apb1_pre: APBPrescaler::DIV1, + apb2_pre: APBPrescaler::DIV1, + apb3_pre: APBPrescaler::DIV1, + voltage_range: VoltageScale::RANGE1, + ls: Default::default(), + mux: Default::default(), } - - // Enable HSE, and wait for it to stabilize - RCC.cr().write(|w| w.set_hseon(true)); - while !RCC.cr().read().hserdy() {} - - frequency } +} - unsafe fn init_msis(&self, range: Msirange) -> Hertz { +pub(crate) unsafe fn init(config: Config) { + // Set the requested power mode + PWR.vosr().modify(|w| w.set_vos(config.voltage_range)); + while !PWR.vosr().read().vosrdy() {} + + let msis = config.msis.map(|range| { // Check MSI output per RM0456 § 11.4.10 - match self.voltage_range { + match config.voltage_range { VoltageScale::RANGE4 => { assert!(msirange_to_hertz(range).0 <= 24_000_000); } @@ -192,223 +148,126 @@ impl Config { }); while !RCC.cr().read().msisrdy() {} msirange_to_hertz(range) - } -} - -impl Default for Config { - fn default() -> Self { - Self { - mux: ClockSrc::default(), - ahb_pre: AHBPrescaler::DIV1, - apb1_pre: APBPrescaler::DIV1, - apb2_pre: APBPrescaler::DIV1, - apb3_pre: APBPrescaler::DIV1, - hsi48: Some(Default::default()), - voltage_range: VoltageScale::RANGE3, - ls: Default::default(), - } - } -} - -pub(crate) unsafe fn init(config: Config) { - // Ensure PWR peripheral clock is enabled - RCC.ahb3enr().modify(|w| { - w.set_pwren(true); }); - RCC.ahb3enr().read(); // synchronize - // Set the requested power mode - PWR.vosr().modify(|w| { - w.set_vos(config.voltage_range); - }); - while !PWR.vosr().read().vosrdy() {} - - let sys_clk = match config.mux { - ClockSrc::MSI(range) => config.init_msis(range), - ClockSrc::HSE(freq) => config.init_hse(freq), - ClockSrc::HSI => config.init_hsi(), - ClockSrc::PLL1_R(pll) => { - // Configure the PLL source - let source_clk = match pll.source { - PllSource::MSIS(range) => config.init_msis(range), - PllSource::HSE(hertz) => config.init_hse(hertz), - PllSource::HSI => config.init_hsi(), - }; - - // Calculate the reference clock, which is the source divided by m - let reference_clk = source_clk / pll.m; - - // Check limits per RM0456 § 11.4.6 - assert!(Hertz::mhz(4) <= reference_clk && reference_clk <= Hertz::mhz(16)); - - // Calculate the PLL1 VCO clock and PLL1 R output clock - let pll1_clk = reference_clk * pll.n; - let pll1r_clk = pll1_clk / pll.r; - - // Check system clock per RM0456 § 11.4.9 - assert!(pll1r_clk <= Hertz::mhz(160)); - - // Check PLL clocks per RM0456 § 11.4.10 - match config.voltage_range { - VoltageScale::RANGE1 => { - assert!(pll1_clk >= Hertz::mhz(128) && pll1_clk <= Hertz::mhz(544)); - assert!(pll1r_clk <= Hertz::mhz(208)); - } - VoltageScale::RANGE2 => { - assert!(pll1_clk >= Hertz::mhz(128) && pll1_clk <= Hertz::mhz(544)); - assert!(pll1r_clk <= Hertz::mhz(110)); - } - VoltageScale::RANGE3 => { - assert!(pll1_clk >= Hertz::mhz(128) && pll1_clk <= Hertz::mhz(330)); - assert!(pll1r_clk <= Hertz::mhz(55)); - } - VoltageScale::RANGE4 => { - panic!("PLL is unavailable in voltage range 4"); - } + let msik = config.msik.map(|range| { + // Check MSI output per RM0456 § 11.4.10 + match config.voltage_range { + VoltageScale::RANGE4 => { + assert!(msirange_to_hertz(range).0 <= 24_000_000); } - - // § 10.5.4: if we're targeting >= 55 MHz, we must configure PLL1MBOOST to a prescaler - // value that results in an output between 4 and 16 MHz for the PWR EPOD boost - let mboost = if pll1r_clk >= Hertz::mhz(55) { - // source_clk can be up to 50 MHz, so there's just a few cases: - if source_clk > Hertz::mhz(32) { - // Divide by 4, giving EPOD 8-12.5 MHz - Pllmboost::DIV4 - } else if source_clk > Hertz::mhz(16) { - // Divide by 2, giving EPOD 8-16 MHz - Pllmboost::DIV2 - } else { - // Bypass, giving EPOD 4-16 MHz - Pllmboost::DIV1 - } - } else { - // Nothing to do - Pllmboost::DIV1 - }; - - // Disable the PLL, and wait for it to disable - RCC.cr().modify(|w| w.set_pllon(0, false)); - while RCC.cr().read().pllrdy(0) {} - - // Configure the PLL - RCC.pll1cfgr().write(|w| { - // Configure PLL1 source and prescaler - w.set_pllsrc(pll.source.into()); - w.set_pllm(pll.m); - - // Configure PLL1 input frequncy range - let input_range = if reference_clk <= Hertz::mhz(8) { - Pllrge::FREQ_4TO8MHZ - } else { - Pllrge::FREQ_8TO16MHZ - }; - w.set_pllrge(input_range); - - // Set the prescaler for PWR EPOD - w.set_pllmboost(mboost); - - // Enable PLL1_R output - w.set_pllren(true); - }); - - // Configure the PLL divisors - RCC.pll1divr().modify(|w| { - // Set the VCO multiplier - w.set_plln(pll.n); - w.set_pllp(pll.p); - w.set_pllq(pll.q); - // Set the R output divisor - w.set_pllr(pll.r); - }); - - // Do we need the EPOD booster to reach the target clock speed per § 10.5.4? - if pll1r_clk >= Hertz::mhz(55) { - // Enable the booster - PWR.vosr().modify(|w| { - w.set_boosten(true); - }); - while !PWR.vosr().read().boostrdy() {} - } - - // Enable the PLL - RCC.cr().modify(|w| w.set_pllon(0, true)); - while !RCC.cr().read().pllrdy(0) {} - - pll1r_clk + _ => {} } + + // RM0456 § 11.8.2: spin until MSIS is off or MSIS is ready before setting its range + loop { + let cr = RCC.cr().read(); + if cr.msikon() == false || cr.msikrdy() == true { + break; + } + } + + RCC.icscr1().modify(|w| { + w.set_msikrange(range); + w.set_msirgsel(Msirgsel::ICSCR1); + }); + RCC.cr().write(|w| { + w.set_msikon(true); + }); + while !RCC.cr().read().msikrdy() {} + msirange_to_hertz(range) + }); + + let hsi = config.hsi.then(|| { + RCC.cr().write(|w| w.set_hsion(true)); + while !RCC.cr().read().hsirdy() {} + + HSI_FREQ + }); + + let hse = config.hse.map(|hse| { + // Check frequency limits per RM456 § 11.4.10 + match config.voltage_range { + VoltageScale::RANGE1 | VoltageScale::RANGE2 | VoltageScale::RANGE3 => { + assert!(hse.freq.0 <= 50_000_000); + } + VoltageScale::RANGE4 => { + assert!(hse.freq.0 <= 25_000_000); + } + } + + // Enable HSE, and wait for it to stabilize + RCC.cr().write(|w| { + w.set_hseon(true); + w.set_hsebyp(hse.mode != HseMode::Oscillator); + w.set_hseext(match hse.mode { + HseMode::Oscillator | HseMode::Bypass => Hseext::ANALOG, + HseMode::BypassDigital => Hseext::DIGITAL, + }); + }); + while !RCC.cr().read().hserdy() {} + + hse.freq + }); + + let hsi48 = config.hsi48.map(super::init_hsi48); + + let pll_input = PllInput { hse, hsi, msi: msis }; + let pll1 = init_pll(PllInstance::Pll1, config.pll1, &pll_input, config.voltage_range); + let pll2 = init_pll(PllInstance::Pll2, config.pll2, &pll_input, config.voltage_range); + let pll3 = init_pll(PllInstance::Pll3, config.pll3, &pll_input, config.voltage_range); + + let sys_clk = match config.sys { + Sysclk::HSE => hse.unwrap(), + Sysclk::HSI => hsi.unwrap(), + Sysclk::MSIS => msis.unwrap(), + Sysclk::PLL1_R => pll1.r.unwrap(), }; - let _hsi48 = config.hsi48.map(super::init_hsi48); + // Do we need the EPOD booster to reach the target clock speed per § 10.5.4? + if sys_clk >= Hertz::mhz(55) { + // Enable the booster + PWR.vosr().modify(|w| w.set_boosten(true)); + while !PWR.vosr().read().boostrdy() {} + } // The clock source is ready // Calculate and set the flash wait states let wait_states = match config.voltage_range { // VOS 1 range VCORE 1.26V - 1.40V - VoltageScale::RANGE1 => { - if sys_clk.0 < 32_000_000 { - 0 - } else if sys_clk.0 < 64_000_000 { - 1 - } else if sys_clk.0 < 96_000_000 { - 2 - } else if sys_clk.0 < 128_000_000 { - 3 - } else { - 4 - } - } + VoltageScale::RANGE1 => match sys_clk.0 { + ..=32_000_000 => 0, + ..=64_000_000 => 1, + ..=96_000_000 => 2, + ..=128_000_000 => 3, + _ => 4, + }, // VOS 2 range VCORE 1.15V - 1.26V - VoltageScale::RANGE2 => { - if sys_clk.0 < 30_000_000 { - 0 - } else if sys_clk.0 < 60_000_000 { - 1 - } else if sys_clk.0 < 90_000_000 { - 2 - } else { - 3 - } - } + VoltageScale::RANGE2 => match sys_clk.0 { + ..=30_000_000 => 0, + ..=60_000_000 => 1, + ..=90_000_000 => 2, + _ => 3, + }, // VOS 3 range VCORE 1.05V - 1.15V - VoltageScale::RANGE3 => { - if sys_clk.0 < 24_000_000 { - 0 - } else if sys_clk.0 < 48_000_000 { - 1 - } else { - 2 - } - } + VoltageScale::RANGE3 => match sys_clk.0 { + ..=24_000_000 => 0, + ..=48_000_000 => 1, + _ => 2, + }, // VOS 4 range VCORE 0.95V - 1.05V - VoltageScale::RANGE4 => { - if sys_clk.0 < 12_000_000 { - 0 - } else { - 1 - } - } + VoltageScale::RANGE4 => match sys_clk.0 { + ..=12_000_000 => 0, + _ => 1, + }, }; FLASH.acr().modify(|w| { w.set_latency(wait_states); }); // Switch the system clock source - RCC.cfgr1().modify(|w| { - w.set_sw(config.mux.into()); - }); - - // RM0456 § 11.4.9 specifies maximum bus frequencies per voltage range, but the maximum bus - // frequency for each voltage range exactly matches the maximum permitted PLL output frequency. - // Given that: - // - // 1. Any bus frequency can never exceed the system clock frequency; - // 2. We checked the PLL output frequency if we're using it as a system clock; - // 3. The maximum HSE frequencies at each voltage range are lower than the bus limits, and - // we checked the HSE frequency if configured as a system clock; and - // 4. The maximum frequencies from the other clock sources are lower than the lowest bus - // frequency limit - // - // ...then we do not need to perform additional bus-related frequency checks. + RCC.cfgr1().modify(|w| w.set_sw(config.sys)); + while RCC.cfgr1().read().sws() != config.sys {} // Configure the bus prescalers RCC.cfgr2().modify(|w| { @@ -420,46 +279,65 @@ pub(crate) unsafe fn init(config: Config) { w.set_ppre3(config.apb3_pre); }); - let ahb_freq = sys_clk / config.ahb_pre; + let hclk = sys_clk / config.ahb_pre; - let (apb1_freq, apb1_tim_freq) = match config.apb1_pre { - APBPrescaler::DIV1 => (ahb_freq, ahb_freq), - pre => { - let freq = ahb_freq / pre; - (freq, freq * 2u32) - } + let hclk_max = match config.voltage_range { + VoltageScale::RANGE1 => Hertz::mhz(160), + VoltageScale::RANGE2 => Hertz::mhz(110), + VoltageScale::RANGE3 => Hertz::mhz(55), + VoltageScale::RANGE4 => Hertz::mhz(25), }; + assert!(hclk <= hclk_max); - let (apb2_freq, apb2_tim_freq) = match config.apb2_pre { - APBPrescaler::DIV1 => (ahb_freq, ahb_freq), - pre => { - let freq = ahb_freq / pre; - (freq, freq * 2u32) - } - }; - - let (apb3_freq, _apb3_tim_freq) = match config.apb3_pre { - APBPrescaler::DIV1 => (ahb_freq, ahb_freq), - pre => { - let freq = ahb_freq / pre; - (freq, freq * 2u32) - } - }; + let (pclk1, pclk1_tim) = super::util::calc_pclk(hclk, config.apb1_pre); + let (pclk2, pclk2_tim) = super::util::calc_pclk(hclk, config.apb2_pre); + let (pclk3, _) = super::util::calc_pclk(hclk, config.apb3_pre); let rtc = config.ls.init(); - set_freqs(Clocks { - sys: sys_clk, - hclk1: ahb_freq, - hclk2: ahb_freq, - hclk3: ahb_freq, - pclk1: apb1_freq, - pclk2: apb2_freq, - pclk3: apb3_freq, - pclk1_tim: apb1_tim_freq, - pclk2_tim: apb2_tim_freq, - rtc, - }); + let lse = config.ls.lse.map(|l| l.frequency); + let lsi = config.ls.lsi.then_some(LSI_FREQ); + + config.mux.init(); + + set_clocks!( + sys: Some(sys_clk), + hclk1: Some(hclk), + hclk2: Some(hclk), + hclk3: Some(hclk), + pclk1: Some(pclk1), + pclk2: Some(pclk2), + pclk3: Some(pclk3), + pclk1_tim: Some(pclk1_tim), + pclk2_tim: Some(pclk2_tim), + msik: msik, + hsi48: hsi48, + rtc: rtc, + lse: lse, + lsi: lsi, + hse: hse, + hse_div_2: hse.map(|clk| clk / 2u32), + hsi: hsi, + pll1_p: pll1.p, + pll1_p_div_2: pll1.p.map(|clk| clk / 2u32), + pll1_q: pll1.q, + pll1_r: pll1.r, + pll2_p: pll2.p, + pll2_q: pll2.q, + pll2_r: pll2.r, + pll3_p: pll3.p, + pll3_q: pll3.q, + pll3_r: pll3.r, + + #[cfg(dsihost)] + dsi_phy: None, // DSI PLL clock not supported, don't call `RccPeripheral::frequency()` in the drivers + + // TODO + audioclk: None, + hsi48_div_2: None, + shsi: None, + shsi_div_2: None, + ); } fn msirange_to_hertz(range: Msirange) -> Hertz { @@ -482,3 +360,126 @@ fn msirange_to_hertz(range: Msirange) -> Hertz { Msirange::RANGE_100KHZ => Hertz(100_000), } } + +pub(super) struct PllInput { + pub hsi: Option, + pub hse: Option, + pub msi: Option, +} + +#[allow(unused)] +#[derive(Default)] +pub(super) struct PllOutput { + pub p: Option, + pub q: Option, + pub r: Option, +} + +#[derive(PartialEq, Eq, Clone, Copy)] +enum PllInstance { + Pll1 = 0, + Pll2 = 1, + Pll3 = 2, +} + +fn pll_enable(instance: PllInstance, enabled: bool) { + RCC.cr().modify(|w| w.set_pllon(instance as _, enabled)); + while RCC.cr().read().pllrdy(instance as _) != enabled {} +} + +fn init_pll(instance: PllInstance, config: Option, input: &PllInput, voltage_range: VoltageScale) -> PllOutput { + // Disable PLL + pll_enable(instance, false); + + let Some(pll) = config else { return PllOutput::default() }; + + let src_freq = match pll.source { + PllSource::DISABLE => panic!("must not select PLL source as DISABLE"), + PllSource::HSE => unwrap!(input.hse), + PllSource::HSI => unwrap!(input.hsi), + PllSource::MSIS => unwrap!(input.msi), + }; + + // Calculate the reference clock, which is the source divided by m + let ref_freq = src_freq / pll.prediv; + // Check limits per RM0456 § 11.4.6 + assert!(Hertz::mhz(4) <= ref_freq && ref_freq <= Hertz::mhz(16)); + + // Check PLL clocks per RM0456 § 11.4.10 + let (vco_min, vco_max, out_max) = match voltage_range { + VoltageScale::RANGE1 => (Hertz::mhz(128), Hertz::mhz(544), Hertz::mhz(208)), + VoltageScale::RANGE2 => (Hertz::mhz(128), Hertz::mhz(544), Hertz::mhz(110)), + VoltageScale::RANGE3 => (Hertz::mhz(128), Hertz::mhz(330), Hertz::mhz(55)), + VoltageScale::RANGE4 => panic!("PLL is unavailable in voltage range 4"), + }; + + // Calculate the PLL VCO clock + let vco_freq = ref_freq * pll.mul; + assert!(vco_freq >= vco_min && vco_freq <= vco_max); + + // Calculate output clocks. + let p = pll.divp.map(|div| vco_freq / div); + let q = pll.divq.map(|div| vco_freq / div); + let r = pll.divr.map(|div| vco_freq / div); + for freq in [p, q, r] { + if let Some(freq) = freq { + assert!(freq <= out_max); + } + } + + let divr = match instance { + PllInstance::Pll1 => RCC.pll1divr(), + PllInstance::Pll2 => RCC.pll2divr(), + PllInstance::Pll3 => RCC.pll3divr(), + }; + divr.write(|w| { + w.set_plln(pll.mul); + w.set_pllp(pll.divp.unwrap_or(PllDiv::DIV1)); + w.set_pllq(pll.divq.unwrap_or(PllDiv::DIV1)); + w.set_pllr(pll.divr.unwrap_or(PllDiv::DIV1)); + }); + + let input_range = match ref_freq.0 { + ..=8_000_000 => Pllrge::FREQ_4TO8MHZ, + _ => Pllrge::FREQ_8TO16MHZ, + }; + + macro_rules! write_fields { + ($w:ident) => { + $w.set_pllpen(pll.divp.is_some()); + $w.set_pllqen(pll.divq.is_some()); + $w.set_pllren(pll.divr.is_some()); + $w.set_pllm(pll.prediv); + $w.set_pllsrc(pll.source); + $w.set_pllrge(input_range); + }; + } + + match instance { + PllInstance::Pll1 => RCC.pll1cfgr().write(|w| { + // § 10.5.4: if we're targeting >= 55 MHz, we must configure PLL1MBOOST to a prescaler + // value that results in an output between 4 and 16 MHz for the PWR EPOD boost + if r.unwrap() >= Hertz::mhz(55) { + // source_clk can be up to 50 MHz, so there's just a few cases: + let mboost = match src_freq.0 { + ..=16_000_000 => Pllmboost::DIV1, // Bypass, giving EPOD 4-16 MHz + ..=32_000_000 => Pllmboost::DIV2, // Divide by 2, giving EPOD 8-16 MHz + _ => Pllmboost::DIV4, // Divide by 4, giving EPOD 8-12.5 MHz + }; + w.set_pllmboost(mboost); + } + write_fields!(w); + }), + PllInstance::Pll2 => RCC.pll2cfgr().write(|w| { + write_fields!(w); + }), + PllInstance::Pll3 => RCC.pll3cfgr().write(|w| { + write_fields!(w); + }), + } + + // Enable PLL + pll_enable(instance, true); + + PllOutput { p, q, r } +} diff --git a/embassy-stm32/src/rcc/wba.rs b/embassy-stm32/src/rcc/wba.rs index 1d04d480a..1fee648d4 100644 --- a/embassy-stm32/src/rcc/wba.rs +++ b/embassy-stm32/src/rcc/wba.rs @@ -1,7 +1,7 @@ -use stm32_metapac::rcc::vals::{Pllsrc, Sw}; - +pub use crate::pac::pwr::vals::Vos as VoltageScale; +use crate::pac::rcc::regs::Cfgr1; +pub use crate::pac::rcc::vals::{Hpre as AHBPrescaler, Hsepre as HsePrescaler, Ppre as APBPrescaler, Sw as Sysclk}; use crate::pac::{FLASH, RCC}; -use crate::rcc::{set_freqs, Clocks}; use crate::time::Hertz; /// HSI speed @@ -9,82 +9,110 @@ pub const HSI_FREQ: Hertz = Hertz(16_000_000); // HSE speed pub const HSE_FREQ: Hertz = Hertz(32_000_000); -pub use crate::pac::pwr::vals::Vos as VoltageScale; -pub use crate::pac::rcc::vals::{Hpre as AHBPrescaler, Ppre as APBPrescaler}; - -#[derive(Copy, Clone)] -pub enum ClockSrc { - HSE, - HSI, -} - -#[derive(Clone, Copy, Debug)] -pub enum PllSource { - HSE, - HSI, -} - -impl Into for PllSource { - fn into(self) -> Pllsrc { - match self { - PllSource::HSE => Pllsrc::HSE, - PllSource::HSI => Pllsrc::HSI, - } - } -} - -impl Into for ClockSrc { - fn into(self) -> Sw { - match self { - ClockSrc::HSE => Sw::HSE, - ClockSrc::HSI => Sw::HSI, - } - } +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct Hse { + pub prescaler: HsePrescaler, } +/// Clocks configuration +#[derive(Clone, Copy)] pub struct Config { - pub mux: ClockSrc, + // base clock sources + pub hsi: bool, + pub hse: Option, + + // sysclk, buses. + pub sys: Sysclk, pub ahb_pre: AHBPrescaler, pub apb1_pre: APBPrescaler, pub apb2_pre: APBPrescaler, pub apb7_pre: APBPrescaler, + + // low speed LSI/LSE/RTC pub ls: super::LsConfig, + + pub voltage_scale: VoltageScale, + + /// Per-peripheral kernel clock selection muxes + pub mux: super::mux::ClockMux, } impl Default for Config { - fn default() -> Self { - Self { - mux: ClockSrc::HSI, + #[inline] + fn default() -> Config { + Config { + hse: None, + hsi: true, + sys: Sysclk::HSI, ahb_pre: AHBPrescaler::DIV1, apb1_pre: APBPrescaler::DIV1, apb2_pre: APBPrescaler::DIV1, apb7_pre: APBPrescaler::DIV1, ls: Default::default(), + voltage_scale: VoltageScale::RANGE2, + mux: Default::default(), } } } +fn hsi_enable() { + RCC.cr().modify(|w| w.set_hsion(true)); + while !RCC.cr().read().hsirdy() {} +} + pub(crate) unsafe fn init(config: Config) { - let sys_clk = match config.mux { - ClockSrc::HSE => { - RCC.cr().write(|w| w.set_hseon(true)); - while !RCC.cr().read().hserdy() {} + // Switch to HSI to prevent problems with PLL configuration. + if !RCC.cr().read().hsion() { + hsi_enable() + } + if RCC.cfgr1().read().sws() != Sysclk::HSI { + // Set HSI as a clock source, reset prescalers. + RCC.cfgr1().write_value(Cfgr1::default()); + // Wait for clock switch status bits to change. + while RCC.cfgr1().read().sws() != Sysclk::HSI {} + } - HSE_FREQ - } - ClockSrc::HSI => { - RCC.cr().write(|w| w.set_hsion(true)); - while !RCC.cr().read().hsirdy() {} + // Set voltage scale + crate::pac::PWR.vosr().write(|w| w.set_vos(config.voltage_scale)); + while !crate::pac::PWR.vosr().read().vosrdy() {} - HSI_FREQ - } + let rtc = config.ls.init(); + + let hsi = config.hsi.then(|| { + hsi_enable(); + + HSI_FREQ + }); + + let hse = config.hse.map(|hse| { + RCC.cr().write(|w| { + w.set_hseon(true); + w.set_hsepre(hse.prescaler); + }); + while !RCC.cr().read().hserdy() {} + + HSE_FREQ + }); + + let sys_clk = match config.sys { + Sysclk::HSE => hse.unwrap(), + Sysclk::HSI => hsi.unwrap(), + Sysclk::_RESERVED_1 => unreachable!(), + Sysclk::PLL1_R => todo!(), }; - // TODO make configurable - let power_vos = VoltageScale::RANGE1; + assert!(sys_clk.0 <= 100_000_000); - // states and programming delay - let wait_states = match power_vos { + let hclk1 = sys_clk / config.ahb_pre; + let hclk2 = hclk1; + let hclk4 = hclk1; + // TODO: hclk5 + let (pclk1, pclk1_tim) = super::util::calc_pclk(hclk1, config.apb1_pre); + let (pclk2, pclk2_tim) = super::util::calc_pclk(hclk1, config.apb2_pre); + let (pclk7, _) = super::util::calc_pclk(hclk1, config.apb7_pre); + + // Set flash wait states + let flash_latency = match config.voltage_scale { VoltageScale::RANGE1 => match sys_clk.0 { ..=32_000_000 => 0, ..=64_000_000 => 1, @@ -99,13 +127,24 @@ pub(crate) unsafe fn init(config: Config) { }, }; - FLASH.acr().modify(|w| { - w.set_latency(wait_states); - }); + FLASH.acr().modify(|w| w.set_latency(flash_latency)); + while FLASH.acr().read().latency() != flash_latency {} + + // Set sram wait states + let _sram_latency = match config.voltage_scale { + VoltageScale::RANGE1 => 0, + VoltageScale::RANGE2 => match sys_clk.0 { + ..=12_000_000 => 0, + ..=16_000_000 => 1, + _ => 2, + }, + }; + // TODO: Set the SRAM wait states RCC.cfgr1().modify(|w| { - w.set_sw(config.mux.into()); + w.set_sw(config.sys); }); + while RCC.cfgr1().read().sws() != config.sys {} RCC.cfgr2().modify(|w| { w.set_hpre(config.ahb_pre); @@ -113,45 +152,25 @@ pub(crate) unsafe fn init(config: Config) { w.set_ppre2(config.apb2_pre); }); - RCC.cfgr3().modify(|w| { - w.set_ppre7(config.apb7_pre); - }); + config.mux.init(); - let ahb_freq = sys_clk / config.ahb_pre; - let (apb1_freq, apb1_tim_freq) = match config.apb1_pre { - APBPrescaler::DIV1 => (ahb_freq, ahb_freq), - pre => { - let freq = ahb_freq / pre; - (freq, freq * 2u32) - } - }; - let (apb2_freq, apb2_tim_freq) = match config.apb2_pre { - APBPrescaler::DIV1 => (ahb_freq, ahb_freq), - pre => { - let freq = ahb_freq / pre; - (freq, freq * 2u32) - } - }; - let (apb7_freq, _apb7_tim_freq) = match config.apb7_pre { - APBPrescaler::DIV1 => (ahb_freq, ahb_freq), - pre => { - let freq = ahb_freq / pre; - (freq, freq * 2u32) - } - }; + set_clocks!( + sys: Some(sys_clk), + hclk1: Some(hclk1), + hclk2: Some(hclk2), + hclk4: Some(hclk4), + pclk1: Some(pclk1), + pclk2: Some(pclk2), + pclk7: Some(pclk7), + pclk1_tim: Some(pclk1_tim), + pclk2_tim: Some(pclk2_tim), + rtc: rtc, + hse: hse, + hsi: hsi, - let rtc = config.ls.init(); - - set_freqs(Clocks { - sys: sys_clk, - hclk1: ahb_freq, - hclk2: ahb_freq, - hclk4: ahb_freq, - pclk1: apb1_freq, - pclk2: apb2_freq, - pclk7: apb7_freq, - pclk1_tim: apb1_tim_freq, - pclk2_tim: apb2_tim_freq, - rtc, - }); + // TODO + lse: None, + lsi: None, + pll1_q: None, + ); } diff --git a/embassy-stm32/src/rng.rs b/embassy-stm32/src/rng.rs index ca641f352..6f4c81c8a 100644 --- a/embassy-stm32/src/rng.rs +++ b/embassy-stm32/src/rng.rs @@ -10,12 +10,12 @@ use embassy_sync::waitqueue::AtomicWaker; use rand_core::{CryptoRng, RngCore}; use crate::interrupt::typelevel::Interrupt; -use crate::{interrupt, pac, peripherals, Peripheral}; +use crate::{interrupt, pac, peripherals, rcc, Peripheral}; static RNG_WAKER: AtomicWaker = AtomicWaker::new(); /// RNG error -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Error { /// Seed error. @@ -52,7 +52,7 @@ impl<'d, T: Instance> Rng<'d, T> { inner: impl Peripheral

+ 'd, _irq: impl interrupt::typelevel::Binding> + 'd, ) -> Self { - T::enable_and_reset(); + rcc::enable_and_reset::(); into_ref!(inner); let mut random = Self { _inner: inner }; random.reset(); @@ -222,16 +222,13 @@ impl<'d, T: Instance> RngCore for Rng<'d, T> { impl<'d, T: Instance> CryptoRng for Rng<'d, T> {} -pub(crate) mod sealed { - use super::*; - - pub trait Instance { - fn regs() -> pac::rng::Rng; - } +trait SealedInstance { + fn regs() -> pac::rng::Rng; } /// RNG instance trait. -pub trait Instance: sealed::Instance + Peripheral

+ crate::rcc::RccPeripheral + 'static + Send { +#[allow(private_bounds)] +pub trait Instance: SealedInstance + Peripheral

+ crate::rcc::RccPeripheral + 'static + Send { /// Interrupt for this RNG instance. type Interrupt: interrupt::typelevel::Interrupt; } @@ -242,7 +239,7 @@ foreach_interrupt!( type Interrupt = crate::interrupt::typelevel::$irq; } - impl sealed::Instance for peripherals::$inst { + impl SealedInstance for peripherals::$inst { fn regs() -> crate::pac::rng::Rng { crate::pac::$inst } diff --git a/embassy-stm32/src/rtc/datetime.rs b/embassy-stm32/src/rtc/datetime.rs index ef92fa4bb..32732e96e 100644 --- a/embassy-stm32/src/rtc/datetime.rs +++ b/embassy-stm32/src/rtc/datetime.rs @@ -1,67 +1,5 @@ #[cfg(feature = "chrono")] -use core::convert::From; - -#[cfg(feature = "chrono")] -use chrono::{self, Datelike, NaiveDate, Timelike, Weekday}; - -#[cfg(any(feature = "defmt", feature = "time"))] -use crate::peripherals::RTC; -#[cfg(any(feature = "defmt", feature = "time"))] -use crate::rtc::sealed::Instance; - -/// Represents an instant in time that can be substracted to compute a duration -pub struct RtcInstant { - /// 0..59 - pub second: u8, - /// 0..256 - pub subsecond: u16, -} - -impl RtcInstant { - #[cfg(not(rtc_v2f2))] - pub(super) const fn from(second: u8, subsecond: u16) -> Result { - if second > 59 { - Err(Error::InvalidSecond) - } else { - Ok(Self { second, subsecond }) - } - } -} - -#[cfg(feature = "defmt")] -impl defmt::Format for RtcInstant { - fn format(&self, fmt: defmt::Formatter) { - defmt::write!( - fmt, - "{}:{}", - self.second, - RTC::regs().prer().read().prediv_s() - self.subsecond, - ) - } -} - -#[cfg(feature = "time")] -impl core::ops::Sub for RtcInstant { - type Output = embassy_time::Duration; - - fn sub(self, rhs: Self) -> Self::Output { - use embassy_time::{Duration, TICK_HZ}; - - let second = if self.second < rhs.second { - self.second + 60 - } else { - self.second - }; - - let psc = RTC::regs().prer().read().prediv_s() as u32; - - let self_ticks = second as u32 * (psc + 1) + (psc - self.subsecond as u32); - let other_ticks = rhs.second as u32 * (psc + 1) + (psc - rhs.subsecond as u32); - let rtc_ticks = self_ticks - other_ticks; - - Duration::from_ticks(((rtc_ticks * TICK_HZ as u32) / (psc + 1)) as u64) - } -} +use chrono::{Datelike, NaiveDate, Timelike, Weekday}; /// Errors regarding the [`DateTime`] struct. #[derive(Clone, Debug, PartialEq, Eq)] @@ -151,9 +89,9 @@ impl DateTime { ) -> Result { if year > 4095 { Err(Error::InvalidYear) - } else if month < 1 || month > 12 { + } else if !(1..=12).contains(&month) { Err(Error::InvalidMonth) - } else if day < 1 || day > 31 { + } else if !(1..=31).contains(&day) { Err(Error::InvalidDay) } else if hour > 23 { Err(Error::InvalidHour) diff --git a/embassy-stm32/src/rtc/low_power.rs b/embassy-stm32/src/rtc/low_power.rs new file mode 100644 index 000000000..bba359f31 --- /dev/null +++ b/embassy-stm32/src/rtc/low_power.rs @@ -0,0 +1,239 @@ +use super::{bcd2_to_byte, DateTimeError, Rtc, RtcError}; +use crate::peripherals::RTC; +use crate::rtc::SealedInstance; + +/// Represents an instant in time that can be substracted to compute a duration +pub(super) struct RtcInstant { + /// 0..59 + second: u8, + /// 0..256 + subsecond: u16, +} + +impl RtcInstant { + #[cfg(not(rtc_v2f2))] + const fn from(second: u8, subsecond: u16) -> Result { + if second > 59 { + Err(DateTimeError::InvalidSecond) + } else { + Ok(Self { second, subsecond }) + } + } +} + +#[cfg(feature = "defmt")] +impl defmt::Format for RtcInstant { + fn format(&self, fmt: defmt::Formatter) { + defmt::write!( + fmt, + "{}:{}", + self.second, + RTC::regs().prer().read().prediv_s() - self.subsecond, + ) + } +} + +#[cfg(feature = "time")] +impl core::ops::Sub for RtcInstant { + type Output = embassy_time::Duration; + + fn sub(self, rhs: Self) -> Self::Output { + use embassy_time::{Duration, TICK_HZ}; + + let second = if self.second < rhs.second { + self.second + 60 + } else { + self.second + }; + + let psc = RTC::regs().prer().read().prediv_s() as u32; + + let self_ticks = second as u32 * (psc + 1) + (psc - self.subsecond as u32); + let other_ticks = rhs.second as u32 * (psc + 1) + (psc - rhs.subsecond as u32); + let rtc_ticks = self_ticks - other_ticks; + + Duration::from_ticks(((rtc_ticks * TICK_HZ as u32) / (psc + 1)) as u64) + } +} + +#[repr(u8)] +#[derive(Clone, Copy, Debug)] +pub(crate) enum WakeupPrescaler { + Div2 = 2, + Div4 = 4, + Div8 = 8, + Div16 = 16, +} + +#[cfg(any(stm32f4, stm32l0, stm32g4, stm32l4, stm32l5, stm32wb, stm32h5, stm32g0, stm32u5))] +impl From for crate::pac::rtc::vals::Wucksel { + fn from(val: WakeupPrescaler) -> Self { + use crate::pac::rtc::vals::Wucksel; + + match val { + WakeupPrescaler::Div2 => Wucksel::DIV2, + WakeupPrescaler::Div4 => Wucksel::DIV4, + WakeupPrescaler::Div8 => Wucksel::DIV8, + WakeupPrescaler::Div16 => Wucksel::DIV16, + } + } +} + +#[cfg(any(stm32f4, stm32l0, stm32g4, stm32l4, stm32l5, stm32wb, stm32h5, stm32g0, stm32u5))] +impl From for WakeupPrescaler { + fn from(val: crate::pac::rtc::vals::Wucksel) -> Self { + use crate::pac::rtc::vals::Wucksel; + + match val { + Wucksel::DIV2 => WakeupPrescaler::Div2, + Wucksel::DIV4 => WakeupPrescaler::Div4, + Wucksel::DIV8 => WakeupPrescaler::Div8, + Wucksel::DIV16 => WakeupPrescaler::Div16, + _ => unreachable!(), + } + } +} + +impl WakeupPrescaler { + pub fn compute_min(val: u32) -> Self { + *[ + WakeupPrescaler::Div2, + WakeupPrescaler::Div4, + WakeupPrescaler::Div8, + WakeupPrescaler::Div16, + ] + .iter() + .find(|psc| **psc as u32 > val) + .unwrap_or(&WakeupPrescaler::Div16) + } +} + +impl Rtc { + /// Return the current instant. + fn instant(&self) -> Result { + self.time_provider().read(|_, tr, ss| { + let second = bcd2_to_byte((tr.st(), tr.su())); + + RtcInstant::from(second, ss).map_err(RtcError::InvalidDateTime) + }) + } + + /// start the wakeup alarm and with a duration that is as close to but less than + /// the requested duration, and record the instant the wakeup alarm was started + pub(crate) fn start_wakeup_alarm( + &self, + requested_duration: embassy_time::Duration, + cs: critical_section::CriticalSection, + ) { + use embassy_time::{Duration, TICK_HZ}; + + #[cfg(any(rtc_v3, rtc_v3u5, rtc_v3l5))] + use crate::pac::rtc::vals::Calrf; + + // Panic if the rcc mod knows we're not using low-power rtc + #[cfg(any(rcc_wb, rcc_f4, rcc_f410))] + unsafe { crate::rcc::get_freqs() }.rtc.to_hertz().unwrap(); + + let requested_duration = requested_duration.as_ticks().clamp(0, u32::MAX as u64); + let rtc_hz = Self::frequency().0 as u64; + let rtc_ticks = requested_duration * rtc_hz / TICK_HZ; + let prescaler = WakeupPrescaler::compute_min((rtc_ticks / u16::MAX as u64) as u32); + + // adjust the rtc ticks to the prescaler and subtract one rtc tick + let rtc_ticks = rtc_ticks / prescaler as u64; + let rtc_ticks = rtc_ticks.clamp(0, (u16::MAX - 1) as u64).saturating_sub(1) as u16; + + self.write(false, |regs| { + regs.cr().modify(|w| w.set_wute(false)); + + #[cfg(any( + rtc_v2f0, rtc_v2f2, rtc_v2f3, rtc_v2f4, rtc_v2f7, rtc_v2h7, rtc_v2l0, rtc_v2l1, rtc_v2l4, rtc_v2wb + ))] + { + regs.isr().modify(|w| w.set_wutf(false)); + while !regs.isr().read().wutwf() {} + } + + #[cfg(any(rtc_v3, rtc_v3u5, rtc_v3l5))] + { + regs.scr().write(|w| w.set_cwutf(Calrf::CLEAR)); + while !regs.icsr().read().wutwf() {} + } + + regs.cr().modify(|w| w.set_wucksel(prescaler.into())); + regs.wutr().write(|w| w.set_wut(rtc_ticks)); + regs.cr().modify(|w| w.set_wute(true)); + regs.cr().modify(|w| w.set_wutie(true)); + }); + + let instant = self.instant().unwrap(); + trace!( + "rtc: start wakeup alarm for {} ms (psc: {}, ticks: {}) at {}", + Duration::from_ticks(rtc_ticks as u64 * TICK_HZ * prescaler as u64 / rtc_hz).as_millis(), + prescaler as u32, + rtc_ticks, + instant, + ); + + assert!(self.stop_time.borrow(cs).replace(Some(instant)).is_none()) + } + + /// stop the wakeup alarm and return the time elapsed since `start_wakeup_alarm` + /// was called, otherwise none + pub(crate) fn stop_wakeup_alarm(&self, cs: critical_section::CriticalSection) -> Option { + use crate::interrupt::typelevel::Interrupt; + #[cfg(any(rtc_v3, rtc_v3u5, rtc_v3l5))] + use crate::pac::rtc::vals::Calrf; + + let instant = self.instant().unwrap(); + if RTC::regs().cr().read().wute() { + trace!("rtc: stop wakeup alarm at {}", instant); + + self.write(false, |regs| { + regs.cr().modify(|w| w.set_wutie(false)); + regs.cr().modify(|w| w.set_wute(false)); + + #[cfg(any( + rtc_v2f0, rtc_v2f2, rtc_v2f3, rtc_v2f4, rtc_v2f7, rtc_v2h7, rtc_v2l0, rtc_v2l1, rtc_v2l4, rtc_v2wb + ))] + regs.isr().modify(|w| w.set_wutf(false)); + + #[cfg(any(rtc_v3, rtc_v3u5, rtc_v3l5))] + regs.scr().write(|w| w.set_cwutf(Calrf::CLEAR)); + + // Check RM for EXTI and/or NVIC section, "Event event input mapping" or "EXTI interrupt/event mapping" or something similar, + // there is a table for every "Event input" / "EXTI Line". + // If you find the EXTI line related to "RTC wakeup" marks as "Configurable" (not "Direct"), + // then write 1 to related field of Pending Register, to clean it's pending state. + #[cfg(any(exti_v1, stm32h7, stm32wb))] + crate::pac::EXTI + .pr(0) + .modify(|w| w.set_line(RTC::EXTI_WAKEUP_LINE, true)); + + ::WakeupInterrupt::unpend(); + }); + } + + self.stop_time.borrow(cs).take().map(|stop_time| instant - stop_time) + } + + pub(crate) fn enable_wakeup_line(&self) { + use crate::interrupt::typelevel::Interrupt; + + ::WakeupInterrupt::unpend(); + unsafe { ::WakeupInterrupt::enable() }; + + #[cfg(not(stm32u5))] + { + use crate::pac::EXTI; + EXTI.rtsr(0).modify(|w| w.set_line(RTC::EXTI_WAKEUP_LINE, true)); + EXTI.imr(0).modify(|w| w.set_line(RTC::EXTI_WAKEUP_LINE, true)); + } + #[cfg(stm32u5)] + { + use crate::pac::RCC; + RCC.srdamr().modify(|w| w.set_rtcapbamen(true)); + RCC.apb3smenr().modify(|w| w.set_rtcapbsmen(true)); + } + } +} diff --git a/embassy-stm32/src/rtc/mod.rs b/embassy-stm32/src/rtc/mod.rs index 169505501..3722d11ab 100644 --- a/embassy-stm32/src/rtc/mod.rs +++ b/embassy-stm32/src/rtc/mod.rs @@ -1,6 +1,9 @@ //! Real Time Clock (RTC) mod datetime; +#[cfg(feature = "low-power")] +mod low_power; + #[cfg(feature = "low-power")] use core::cell::Cell; @@ -9,8 +12,6 @@ use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; #[cfg(feature = "low-power")] use embassy_sync::blocking_mutex::Mutex; -#[cfg(not(rtc_v2f2))] -use self::datetime::RtcInstant; use self::datetime::{day_of_week_from_u8, day_of_week_to_u8}; pub use self::datetime::{DateTime, DayOfWeek, Error as DateTimeError}; use crate::pac::rtc::regs::{Dr, Tr}; @@ -31,62 +32,6 @@ pub use _version::*; use embassy_hal_internal::Peripheral; use crate::peripherals::RTC; -use crate::rtc::sealed::Instance; - -#[allow(dead_code)] -#[repr(u8)] -#[derive(Clone, Copy, Debug)] -pub(crate) enum WakeupPrescaler { - Div2 = 2, - Div4 = 4, - Div8 = 8, - Div16 = 16, -} - -#[cfg(any(stm32wb, stm32f4, stm32l0, stm32g4, stm32l5, stm32g0))] -impl From for crate::pac::rtc::vals::Wucksel { - fn from(val: WakeupPrescaler) -> Self { - use crate::pac::rtc::vals::Wucksel; - - match val { - WakeupPrescaler::Div2 => Wucksel::DIV2, - WakeupPrescaler::Div4 => Wucksel::DIV4, - WakeupPrescaler::Div8 => Wucksel::DIV8, - WakeupPrescaler::Div16 => Wucksel::DIV16, - } - } -} - -#[cfg(any(stm32wb, stm32f4, stm32l0, stm32g4, stm32l5, stm32g0))] -impl From for WakeupPrescaler { - fn from(val: crate::pac::rtc::vals::Wucksel) -> Self { - use crate::pac::rtc::vals::Wucksel; - - match val { - Wucksel::DIV2 => WakeupPrescaler::Div2, - Wucksel::DIV4 => WakeupPrescaler::Div4, - Wucksel::DIV8 => WakeupPrescaler::Div8, - Wucksel::DIV16 => WakeupPrescaler::Div16, - _ => unreachable!(), - } - } -} - -#[cfg(feature = "low-power")] -impl WakeupPrescaler { - pub fn compute_min(val: u32) -> Self { - *[ - WakeupPrescaler::Div2, - WakeupPrescaler::Div4, - WakeupPrescaler::Div8, - WakeupPrescaler::Div16, - ] - .iter() - .skip_while(|psc| **psc as u32 <= val) - .next() - .unwrap_or(&WakeupPrescaler::Div16) - } -} /// Errors that can occur on methods on [RtcClock] #[non_exhaustive] @@ -108,15 +53,6 @@ pub struct RtcTimeProvider { } impl RtcTimeProvider { - #[cfg(not(rtc_v2f2))] - pub(crate) fn instant(&self) -> Result { - self.read(|_, tr, ss| { - let second = bcd2_to_byte((tr.st(), tr.su())); - - RtcInstant::from(second, ss).map_err(RtcError::InvalidDateTime) - }) - } - /// Return the current datetime. /// /// # Errors @@ -160,15 +96,14 @@ impl RtcTimeProvider { } } - return Err(RtcError::ReadFailure); + Err(RtcError::ReadFailure) } } /// RTC driver. pub struct Rtc { #[cfg(feature = "low-power")] - stop_time: Mutex>>, - #[cfg(not(feature = "low-power"))] + stop_time: Mutex>>, _private: (), } @@ -191,7 +126,7 @@ impl Default for RtcConfig { } /// Calibration cycle period. -#[derive(Copy, Clone, Debug, PartialEq)] +#[derive(Default, Copy, Clone, Debug, PartialEq)] #[repr(u8)] pub enum RtcCalibrationCyclePeriod { /// 8-second calibration period @@ -199,25 +134,19 @@ pub enum RtcCalibrationCyclePeriod { /// 16-second calibration period Seconds16, /// 32-second calibration period + #[default] Seconds32, } -impl Default for RtcCalibrationCyclePeriod { - fn default() -> Self { - RtcCalibrationCyclePeriod::Seconds32 - } -} - impl Rtc { /// Create a new RTC instance. pub fn new(_rtc: impl Peripheral

, rtc_config: RtcConfig) -> Self { #[cfg(not(any(stm32l0, stm32f3, stm32l1, stm32f0, stm32f2)))] - ::enable_and_reset(); + crate::rcc::enable_and_reset::(); let mut this = Self { #[cfg(feature = "low-power")] stop_time: Mutex::const_new(CriticalSectionRawMutex::new(), Cell::new(None)), - #[cfg(not(feature = "low-power"))] _private: (), }; @@ -230,9 +159,8 @@ impl Rtc { // Wait for the clock to update after initialization #[cfg(not(rtc_v2f2))] { - let now = this.instant().unwrap(); - - while this.instant().unwrap().subsecond == now.subsecond {} + let now = this.time_provider().read(|_, _, ss| Ok(ss)).unwrap(); + while now == this.time_provider().read(|_, _, ss| Ok(ss)).unwrap() {} } this @@ -240,7 +168,7 @@ impl Rtc { fn frequency() -> Hertz { let freqs = unsafe { crate::rcc::get_freqs() }; - freqs.rtc.unwrap() + freqs.rtc.to_hertz().unwrap() } /// Acquire a [`RtcTimeProvider`] instance. @@ -255,13 +183,13 @@ impl Rtc { /// Will return `RtcError::InvalidDateTime` if the datetime is not a valid range. pub fn set_datetime(&mut self, t: DateTime) -> Result<(), RtcError> { self.write(true, |rtc| { - let (ht, hu) = byte_to_bcd2(t.hour() as u8); - let (mnt, mnu) = byte_to_bcd2(t.minute() as u8); - let (st, su) = byte_to_bcd2(t.second() as u8); + let (ht, hu) = byte_to_bcd2(t.hour()); + let (mnt, mnu) = byte_to_bcd2(t.minute()); + let (st, su) = byte_to_bcd2(t.second()); - let (dt, du) = byte_to_bcd2(t.day() as u8); - let (mt, mu) = byte_to_bcd2(t.month() as u8); - let yr = t.year() as u16; + let (dt, du) = byte_to_bcd2(t.day()); + let (mt, mu) = byte_to_bcd2(t.month()); + let yr = t.year(); let yr_offset = (yr - 2000_u16) as u8; let (yt, yu) = byte_to_bcd2(yr_offset); @@ -291,12 +219,6 @@ impl Rtc { Ok(()) } - #[cfg(not(rtc_v2f2))] - /// Return the current instant. - fn instant(&self) -> Result { - self.time_provider().instant() - } - /// Return the current datetime. /// /// # Errors @@ -327,7 +249,7 @@ impl Rtc { /// The registers retain their values during wakes from standby mode or system resets. They also /// retain their value when Vdd is switched off as long as V_BAT is powered. pub fn read_backup_register(&self, register: usize) -> Option { - RTC::read_backup_register(&RTC::regs(), register) + RTC::read_backup_register(RTC::regs(), register) } /// Set content of the backup register. @@ -335,125 +257,7 @@ impl Rtc { /// The registers retain their values during wakes from standby mode or system resets. They also /// retain their value when Vdd is switched off as long as V_BAT is powered. pub fn write_backup_register(&self, register: usize, value: u32) { - RTC::write_backup_register(&RTC::regs(), register, value) - } - - #[cfg(feature = "low-power")] - /// start the wakeup alarm and wtih a duration that is as close to but less than - /// the requested duration, and record the instant the wakeup alarm was started - pub(crate) fn start_wakeup_alarm( - &self, - requested_duration: embassy_time::Duration, - cs: critical_section::CriticalSection, - ) { - use embassy_time::{Duration, TICK_HZ}; - - #[cfg(any(rtc_v3, rtc_v3u5, rtc_v3l5))] - use crate::pac::rtc::vals::Calrf; - - // Panic if the rcc mod knows we're not using low-power rtc - #[cfg(any(rcc_wb, rcc_f4, rcc_f410))] - unsafe { crate::rcc::get_freqs() }.rtc.unwrap(); - - let requested_duration = requested_duration.as_ticks().clamp(0, u32::MAX as u64); - let rtc_hz = Self::frequency().0 as u64; - let rtc_ticks = requested_duration * rtc_hz / TICK_HZ; - let prescaler = WakeupPrescaler::compute_min((rtc_ticks / u16::MAX as u64) as u32); - - // adjust the rtc ticks to the prescaler and subtract one rtc tick - let rtc_ticks = rtc_ticks / prescaler as u64; - let rtc_ticks = rtc_ticks.clamp(0, (u16::MAX - 1) as u64).saturating_sub(1) as u16; - - self.write(false, |regs| { - regs.cr().modify(|w| w.set_wute(false)); - - #[cfg(any( - rtc_v2f0, rtc_v2f2, rtc_v2f3, rtc_v2f4, rtc_v2f7, rtc_v2h7, rtc_v2l0, rtc_v2l1, rtc_v2l4, rtc_v2wb - ))] - { - regs.isr().modify(|w| w.set_wutf(false)); - while !regs.isr().read().wutwf() {} - } - - #[cfg(any(rtc_v3, rtc_v3u5, rtc_v3l5))] - { - regs.scr().write(|w| w.set_cwutf(Calrf::CLEAR)); - while !regs.icsr().read().wutwf() {} - } - - regs.cr().modify(|w| w.set_wucksel(prescaler.into())); - regs.wutr().write(|w| w.set_wut(rtc_ticks)); - regs.cr().modify(|w| w.set_wute(true)); - regs.cr().modify(|w| w.set_wutie(true)); - }); - - let instant = self.instant().unwrap(); - trace!( - "rtc: start wakeup alarm for {} ms (psc: {}, ticks: {}) at {}", - Duration::from_ticks(rtc_ticks as u64 * TICK_HZ * prescaler as u64 / rtc_hz).as_millis(), - prescaler as u32, - rtc_ticks, - instant, - ); - - assert!(self.stop_time.borrow(cs).replace(Some(instant)).is_none()) - } - - #[cfg(feature = "low-power")] - /// stop the wakeup alarm and return the time elapsed since `start_wakeup_alarm` - /// was called, otherwise none - pub(crate) fn stop_wakeup_alarm(&self, cs: critical_section::CriticalSection) -> Option { - use crate::interrupt::typelevel::Interrupt; - #[cfg(any(rtc_v3, rtc_v3u5, rtc_v3l5))] - use crate::pac::rtc::vals::Calrf; - - let instant = self.instant().unwrap(); - if RTC::regs().cr().read().wute() { - trace!("rtc: stop wakeup alarm at {}", instant); - - self.write(false, |regs| { - regs.cr().modify(|w| w.set_wutie(false)); - regs.cr().modify(|w| w.set_wute(false)); - - #[cfg(any( - rtc_v2f0, rtc_v2f2, rtc_v2f3, rtc_v2f4, rtc_v2f7, rtc_v2h7, rtc_v2l0, rtc_v2l1, rtc_v2l4, rtc_v2wb - ))] - regs.isr().modify(|w| w.set_wutf(false)); - - #[cfg(any(rtc_v3, rtc_v3u5, rtc_v3l5))] - regs.scr().write(|w| w.set_cwutf(Calrf::CLEAR)); - - #[cfg(all(stm32g0))] - crate::pac::EXTI - .rpr(0) - .modify(|w| w.set_line(RTC::EXTI_WAKEUP_LINE, true)); - #[cfg(all(not(stm32g0), not(stm32l5)))] - crate::pac::EXTI - .pr(0) - .modify(|w| w.set_line(RTC::EXTI_WAKEUP_LINE, true)); - - #[cfg(stm32l5)] - crate::pac::EXTI - .fpr(0) - .modify(|w| w.set_line(RTC::EXTI_WAKEUP_LINE, true)); - - ::WakeupInterrupt::unpend(); - }); - } - - self.stop_time.borrow(cs).take().map(|stop_time| instant - stop_time) - } - - #[cfg(feature = "low-power")] - pub(crate) fn enable_wakeup_line(&self) { - use crate::interrupt::typelevel::Interrupt; - use crate::pac::EXTI; - - ::WakeupInterrupt::unpend(); - unsafe { ::WakeupInterrupt::enable() }; - - EXTI.rtsr(0).modify(|w| w.set_line(RTC::EXTI_WAKEUP_LINE, true)); - EXTI.imr(0).modify(|w| w.set_line(RTC::EXTI_WAKEUP_LINE, true)); + RTC::write_backup_register(RTC::regs(), register, value) } } @@ -466,7 +270,7 @@ pub(crate) fn byte_to_bcd2(byte: u8) -> (u8, u8) { value -= 10; } - (bcd_high, ((bcd_high << 4) | value) as u8) + (bcd_high, ((bcd_high << 4) | value)) } pub(crate) fn bcd2_to_byte(bcd: (u8, u8)) -> u8 { @@ -477,34 +281,31 @@ pub(crate) fn bcd2_to_byte(bcd: (u8, u8)) -> u8 { tmp + (value & 0x0F) } -pub(crate) mod sealed { - use crate::pac::rtc::Rtc; +trait SealedInstance { + const BACKUP_REGISTER_COUNT: usize; - pub trait Instance { - const BACKUP_REGISTER_COUNT: usize; + #[cfg(feature = "low-power")] + #[cfg(not(stm32u5))] + const EXTI_WAKEUP_LINE: usize; - #[cfg(feature = "low-power")] - const EXTI_WAKEUP_LINE: usize; + #[cfg(feature = "low-power")] + type WakeupInterrupt: crate::interrupt::typelevel::Interrupt; - #[cfg(feature = "low-power")] - type WakeupInterrupt: crate::interrupt::typelevel::Interrupt; - - fn regs() -> Rtc { - crate::pac::RTC - } - - /// Read content of the backup register. - /// - /// The registers retain their values during wakes from standby mode or system resets. They also - /// retain their value when Vdd is switched off as long as V_BAT is powered. - fn read_backup_register(rtc: &Rtc, register: usize) -> Option; - - /// Set content of the backup register. - /// - /// The registers retain their values during wakes from standby mode or system resets. They also - /// retain their value when Vdd is switched off as long as V_BAT is powered. - fn write_backup_register(rtc: &Rtc, register: usize, value: u32); - - // fn apply_config(&mut self, rtc_config: RtcConfig); + fn regs() -> crate::pac::rtc::Rtc { + crate::pac::RTC } + + /// Read content of the backup register. + /// + /// The registers retain their values during wakes from standby mode or system resets. They also + /// retain their value when Vdd is switched off as long as V_BAT is powered. + fn read_backup_register(rtc: crate::pac::rtc::Rtc, register: usize) -> Option; + + /// Set content of the backup register. + /// + /// The registers retain their values during wakes from standby mode or system resets. They also + /// retain their value when Vdd is switched off as long as V_BAT is powered. + fn write_backup_register(rtc: crate::pac::rtc::Rtc, register: usize, value: u32); + + // fn apply_config(&mut self, rtc_config: RtcConfig); } diff --git a/embassy-stm32/src/rtc/v2.rs b/embassy-stm32/src/rtc/v2.rs index 1eda097a7..5d9025bbe 100644 --- a/embassy-stm32/src/rtc/v2.rs +++ b/embassy-stm32/src/rtc/v2.rs @@ -1,9 +1,8 @@ use stm32_metapac::rtc::vals::{Osel, Pol}; -use super::sealed; +use super::SealedInstance; use crate::pac::rtc::Rtc; use crate::peripherals::RTC; -use crate::rtc::sealed::Instance; #[allow(dead_code)] impl super::Rtc { @@ -96,7 +95,7 @@ impl super::Rtc { pub(super) fn write(&self, init_mode: bool, f: F) -> R where - F: FnOnce(&crate::pac::rtc::Rtc) -> R, + F: FnOnce(crate::pac::rtc::Rtc) -> R, { let r = RTC::regs(); // Disable write protection. @@ -113,7 +112,7 @@ impl super::Rtc { while !r.isr().read().initf() {} } - let result = f(&r); + let result = f(r); if init_mode { r.isr().modify(|w| w.set_init(false)); // Exits init mode @@ -126,22 +125,25 @@ impl super::Rtc { } } -impl sealed::Instance for crate::peripherals::RTC { +impl SealedInstance for crate::peripherals::RTC { const BACKUP_REGISTER_COUNT: usize = 20; #[cfg(all(feature = "low-power", stm32f4))] const EXTI_WAKEUP_LINE: usize = 22; + #[cfg(all(feature = "low-power", stm32l4))] + const EXTI_WAKEUP_LINE: usize = 20; + #[cfg(all(feature = "low-power", stm32l0))] const EXTI_WAKEUP_LINE: usize = 20; - #[cfg(all(feature = "low-power", stm32f4))] + #[cfg(all(feature = "low-power", any(stm32f4, stm32l4)))] type WakeupInterrupt = crate::interrupt::typelevel::RTC_WKUP; #[cfg(all(feature = "low-power", stm32l0))] type WakeupInterrupt = crate::interrupt::typelevel::RTC; - fn read_backup_register(rtc: &Rtc, register: usize) -> Option { + fn read_backup_register(rtc: Rtc, register: usize) -> Option { if register < Self::BACKUP_REGISTER_COUNT { Some(rtc.bkpr(register).read().bkp()) } else { @@ -149,7 +151,7 @@ impl sealed::Instance for crate::peripherals::RTC { } } - fn write_backup_register(rtc: &Rtc, register: usize, value: u32) { + fn write_backup_register(rtc: Rtc, register: usize, value: u32) { if register < Self::BACKUP_REGISTER_COUNT { rtc.bkpr(register).write(|w| w.set_bkp(value)); } diff --git a/embassy-stm32/src/rtc/v3.rs b/embassy-stm32/src/rtc/v3.rs index 3d44a52ff..12cb10bc7 100644 --- a/embassy-stm32/src/rtc/v3.rs +++ b/embassy-stm32/src/rtc/v3.rs @@ -1,9 +1,9 @@ use stm32_metapac::rtc::vals::{Calp, Calw16, Calw8, Fmt, Key, Osel, Pol, TampalrmType}; -use super::{sealed, RtcCalibrationCyclePeriod}; +use super::RtcCalibrationCyclePeriod; use crate::pac::rtc::Rtc; use crate::peripherals::RTC; -use crate::rtc::sealed::Instance; +use crate::rtc::SealedInstance; impl super::Rtc { /// Applies the RTC config @@ -50,7 +50,7 @@ impl super::Rtc { clock_drift = Self::RTC_CALR_MAX_PPM; } - clock_drift = clock_drift / Self::RTC_CALR_RESOLUTION_PPM; + clock_drift /= Self::RTC_CALR_RESOLUTION_PPM; self.write(false, |rtc| { rtc.calr().write(|w| { @@ -97,7 +97,7 @@ impl super::Rtc { pub(super) fn write(&self, init_mode: bool, f: F) -> R where - F: FnOnce(&crate::pac::rtc::Rtc) -> R, + F: FnOnce(crate::pac::rtc::Rtc) -> R, { let r = RTC::regs(); // Disable write protection. @@ -112,7 +112,7 @@ impl super::Rtc { while !r.icsr().read().initf() {} } - let result = f(&r); + let result = f(r); if init_mode { r.icsr().modify(|w| w.set_init(false)); // Exits init mode @@ -126,40 +126,38 @@ impl super::Rtc { } } -impl sealed::Instance for crate::peripherals::RTC { +impl SealedInstance for crate::peripherals::RTC { const BACKUP_REGISTER_COUNT: usize = 32; - #[cfg(all(feature = "low-power", stm32g4))] - const EXTI_WAKEUP_LINE: usize = 20; + #[cfg(feature = "low-power")] + cfg_if::cfg_if!( + if #[cfg(stm32g4)] { + const EXTI_WAKEUP_LINE: usize = 20; + type WakeupInterrupt = crate::interrupt::typelevel::RTC_WKUP; + } else if #[cfg(stm32g0)] { + const EXTI_WAKEUP_LINE: usize = 19; + type WakeupInterrupt = crate::interrupt::typelevel::RTC_TAMP; + } else if #[cfg(any(stm32l5, stm32h5))] { + const EXTI_WAKEUP_LINE: usize = 17; + type WakeupInterrupt = crate::interrupt::typelevel::RTC; + } else if #[cfg(stm32u5)] { + type WakeupInterrupt = crate::interrupt::typelevel::RTC; + } + ); - #[cfg(all(feature = "low-power", stm32g0))] - const EXTI_WAKEUP_LINE: usize = 19; - - #[cfg(all(feature = "low-power", stm32g0))] - type WakeupInterrupt = crate::interrupt::typelevel::RTC_TAMP; - - #[cfg(all(feature = "low-power", stm32g4))] - type WakeupInterrupt = crate::interrupt::typelevel::RTC_WKUP; - - #[cfg(all(feature = "low-power", stm32l5))] - const EXTI_WAKEUP_LINE: usize = 17; - - #[cfg(all(feature = "low-power", stm32l5))] - type WakeupInterrupt = crate::interrupt::typelevel::RTC; - - fn read_backup_register(_rtc: &Rtc, register: usize) -> Option { + fn read_backup_register(_rtc: Rtc, register: usize) -> Option { #[allow(clippy::if_same_then_else)] if register < Self::BACKUP_REGISTER_COUNT { //Some(rtc.bkpr()[register].read().bits()) - None // RTC3 backup registers come from the TAMP peripe=heral, not RTC. Not() even in the L412 PAC + None // RTC3 backup registers come from the TAMP peripheral, not RTC. Not() even in the L412 PAC } else { None } } - fn write_backup_register(_rtc: &Rtc, register: usize, _value: u32) { + fn write_backup_register(_rtc: Rtc, register: usize, _value: u32) { if register < Self::BACKUP_REGISTER_COUNT { - // RTC3 backup registers come from the TAMP peripe=heral, not RTC. Not() even in the L412 PAC + // RTC3 backup registers come from the TAMP peripheral, not RTC. Not() even in the L412 PAC //self.rtc.bkpr()[register].write(|w| w.bits(value)) } } diff --git a/embassy-stm32/src/sai/mod.rs b/embassy-stm32/src/sai/mod.rs index 5e647612c..7d2f071de 100644 --- a/embassy-stm32/src/sai/mod.rs +++ b/embassy-stm32/src/sai/mod.rs @@ -1,21 +1,21 @@ //! Serial Audio Interface (SAI) #![macro_use] +#![cfg_attr(gpdma, allow(unused))] use core::marker::PhantomData; use embassy_hal_internal::{into_ref, PeripheralRef}; -use self::sealed::WhichSubBlock; pub use crate::dma::word; +#[cfg(not(gpdma))] use crate::dma::{ringbuffer, Channel, ReadableRingBuffer, Request, TransferOptions, WritableRingBuffer}; -use crate::gpio::sealed::{AFType, Pin as _}; -use crate::gpio::AnyPin; +use crate::gpio::{AfType, AnyPin, OutputType, Pull, SealedPin as _, Speed}; use crate::pac::sai::{vals, Sai as Regs}; -use crate::rcc::RccPeripheral; +use crate::rcc::{self, RccPeripheral}; use crate::{peripherals, Peripheral}; /// SAI error -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Error { /// `write` called on a SAI in receive mode. @@ -26,8 +26,15 @@ pub enum Error { Overrun, } -impl From for Error { - fn from(_: ringbuffer::OverrunError) -> Self { +#[cfg(not(gpdma))] +impl From for Error { + fn from(#[allow(unused)] err: ringbuffer::Error) -> Self { + #[cfg(feature = "defmt")] + { + if err == ringbuffer::Error::DmaUnsynced { + defmt::error!("Ringbuffer broken invariants detected!"); + } + } Self::Overrun } } @@ -41,7 +48,7 @@ pub enum Mode { } impl Mode { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] const fn mode(&self, tx_rx: TxRx) -> vals::Mode { match tx_rx { TxRx::Transmitter => match self { @@ -76,7 +83,7 @@ pub enum SlotSize { } impl SlotSize { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] const fn slotsz(&self) -> vals::Slotsz { match self { SlotSize::DataSize => vals::Slotsz::DATASIZE, @@ -99,7 +106,7 @@ pub enum DataSize { } impl DataSize { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] const fn ds(&self) -> vals::Ds { match self { DataSize::Data8 => vals::Ds::BIT8, @@ -124,7 +131,7 @@ pub enum FifoThreshold { } impl FifoThreshold { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] const fn fth(&self) -> vals::Fth { match self { FifoThreshold::Empty => vals::Fth::EMPTY, @@ -145,7 +152,7 @@ pub enum MuteValue { } impl MuteValue { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] const fn muteval(&self) -> vals::Muteval { match self { MuteValue::Zero => vals::Muteval::SENDZERO, @@ -164,7 +171,7 @@ pub enum Protocol { } impl Protocol { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] const fn prtcfg(&self) -> vals::Prtcfg { match self { Protocol::Free => vals::Prtcfg::FREE, @@ -183,7 +190,7 @@ pub enum SyncInput { /// Syncs with the other A/B sub-block within the SAI unit Internal, /// Syncs with a sub-block in the other SAI unit - #[cfg(sai_v4)] + #[cfg(any(sai_v4_2pdm, sai_v4_4pdm))] External(SyncInputInstance), } @@ -192,14 +199,14 @@ impl SyncInput { match self { SyncInput::None => vals::Syncen::ASYNCHRONOUS, SyncInput::Internal => vals::Syncen::INTERNAL, - #[cfg(any(sai_v4))] + #[cfg(any(sai_v4_2pdm, sai_v4_4pdm))] SyncInput::External(_) => vals::Syncen::EXTERNAL, } } } /// SAI instance to sync from. -#[cfg(sai_v4)] +#[cfg(any(sai_v4_2pdm, sai_v4_4pdm))] #[derive(Copy, Clone, PartialEq)] #[allow(missing_docs)] pub enum SyncInputInstance { @@ -222,7 +229,7 @@ pub enum StereoMono { } impl StereoMono { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] const fn mono(&self) -> vals::Mono { match self { StereoMono::Stereo => vals::Mono::STEREO, @@ -241,7 +248,7 @@ pub enum BitOrder { } impl BitOrder { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] const fn lsbfirst(&self) -> vals::Lsbfirst { match self { BitOrder::LsbFirst => vals::Lsbfirst::LSBFIRST, @@ -260,7 +267,7 @@ pub enum FrameSyncOffset { } impl FrameSyncOffset { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] const fn fsoff(&self) -> vals::Fsoff { match self { FrameSyncOffset::OnFirstBit => vals::Fsoff::ONFIRST, @@ -279,7 +286,7 @@ pub enum FrameSyncPolarity { } impl FrameSyncPolarity { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] const fn fspol(&self) -> vals::Fspol { match self { FrameSyncPolarity::ActiveLow => vals::Fspol::FALLINGEDGE, @@ -297,7 +304,7 @@ pub enum FrameSyncDefinition { } impl FrameSyncDefinition { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] const fn fsdef(&self) -> bool { match self { FrameSyncDefinition::StartOfFrame => false, @@ -315,7 +322,7 @@ pub enum ClockStrobe { } impl ClockStrobe { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] const fn ckstr(&self) -> vals::Ckstr { match self { ClockStrobe::Falling => vals::Ckstr::FALLINGEDGE, @@ -333,7 +340,7 @@ pub enum ComplementFormat { } impl ComplementFormat { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] const fn cpl(&self) -> vals::Cpl { match self { ComplementFormat::OnesComplement => vals::Cpl::ONESCOMPLEMENT, @@ -352,7 +359,7 @@ pub enum Companding { } impl Companding { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] const fn comp(&self) -> vals::Comp { match self { Companding::None => vals::Comp::NOCOMPANDING, @@ -371,7 +378,7 @@ pub enum OutputDrive { } impl OutputDrive { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] const fn outdriv(&self) -> vals::Outdriv { match self { OutputDrive::OnStart => vals::Outdriv::ONSTART, @@ -383,6 +390,7 @@ impl OutputDrive { /// Master clock divider. #[derive(Copy, Clone, PartialEq)] #[allow(missing_docs)] +#[cfg(any(sai_v1, sai_v2))] pub enum MasterClockDivider { MasterClockDisabled, Div1, @@ -403,8 +411,79 @@ pub enum MasterClockDivider { Div30, } +/// Master clock divider. +#[derive(Copy, Clone, PartialEq)] +#[allow(missing_docs)] +#[cfg(any(sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] +pub enum MasterClockDivider { + MasterClockDisabled, + Div1, + Div2, + Div3, + Div4, + Div5, + Div6, + Div7, + Div8, + Div9, + Div10, + Div11, + Div12, + Div13, + Div14, + Div15, + Div16, + Div17, + Div18, + Div19, + Div20, + Div21, + Div22, + Div23, + Div24, + Div25, + Div26, + Div27, + Div28, + Div29, + Div30, + Div31, + Div32, + Div33, + Div34, + Div35, + Div36, + Div37, + Div38, + Div39, + Div40, + Div41, + Div42, + Div43, + Div44, + Div45, + Div46, + Div47, + Div48, + Div49, + Div50, + Div51, + Div52, + Div53, + Div54, + Div55, + Div56, + Div57, + Div58, + Div59, + Div60, + Div61, + Div62, + Div63, +} + impl MasterClockDivider { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2))] const fn mckdiv(&self) -> u8 { match self { MasterClockDivider::MasterClockDisabled => 0, @@ -426,6 +505,76 @@ impl MasterClockDivider { MasterClockDivider::Div30 => 15, } } + + #[cfg(any(sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] + const fn mckdiv(&self) -> u8 { + match self { + MasterClockDivider::MasterClockDisabled => 0, + MasterClockDivider::Div1 => 1, + MasterClockDivider::Div2 => 2, + MasterClockDivider::Div3 => 3, + MasterClockDivider::Div4 => 4, + MasterClockDivider::Div5 => 5, + MasterClockDivider::Div6 => 6, + MasterClockDivider::Div7 => 7, + MasterClockDivider::Div8 => 8, + MasterClockDivider::Div9 => 9, + MasterClockDivider::Div10 => 10, + MasterClockDivider::Div11 => 11, + MasterClockDivider::Div12 => 12, + MasterClockDivider::Div13 => 13, + MasterClockDivider::Div14 => 14, + MasterClockDivider::Div15 => 15, + MasterClockDivider::Div16 => 16, + MasterClockDivider::Div17 => 17, + MasterClockDivider::Div18 => 18, + MasterClockDivider::Div19 => 19, + MasterClockDivider::Div20 => 20, + MasterClockDivider::Div21 => 21, + MasterClockDivider::Div22 => 22, + MasterClockDivider::Div23 => 23, + MasterClockDivider::Div24 => 24, + MasterClockDivider::Div25 => 25, + MasterClockDivider::Div26 => 26, + MasterClockDivider::Div27 => 27, + MasterClockDivider::Div28 => 28, + MasterClockDivider::Div29 => 29, + MasterClockDivider::Div30 => 30, + MasterClockDivider::Div31 => 31, + MasterClockDivider::Div32 => 32, + MasterClockDivider::Div33 => 33, + MasterClockDivider::Div34 => 34, + MasterClockDivider::Div35 => 35, + MasterClockDivider::Div36 => 36, + MasterClockDivider::Div37 => 37, + MasterClockDivider::Div38 => 38, + MasterClockDivider::Div39 => 39, + MasterClockDivider::Div40 => 40, + MasterClockDivider::Div41 => 41, + MasterClockDivider::Div42 => 42, + MasterClockDivider::Div43 => 43, + MasterClockDivider::Div44 => 44, + MasterClockDivider::Div45 => 45, + MasterClockDivider::Div46 => 46, + MasterClockDivider::Div47 => 47, + MasterClockDivider::Div48 => 48, + MasterClockDivider::Div49 => 49, + MasterClockDivider::Div50 => 50, + MasterClockDivider::Div51 => 51, + MasterClockDivider::Div52 => 52, + MasterClockDivider::Div53 => 53, + MasterClockDivider::Div54 => 54, + MasterClockDivider::Div55 => 55, + MasterClockDivider::Div56 => 56, + MasterClockDivider::Div57 => 57, + MasterClockDivider::Div58 => 58, + MasterClockDivider::Div59 => 59, + MasterClockDivider::Div60 => 60, + MasterClockDivider::Div61 => 61, + MasterClockDivider::Div62 => 62, + MasterClockDivider::Div63 => 63, + } + } } /// [`SAI`] configuration. @@ -501,40 +650,41 @@ impl Config { } } -enum RingBuffer<'d, C: Channel, W: word::Word> { - Writable(WritableRingBuffer<'d, C, W>), - Readable(ReadableRingBuffer<'d, C, W>), +#[cfg(not(gpdma))] +enum RingBuffer<'d, W: word::Word> { + Writable(WritableRingBuffer<'d, W>), + Readable(ReadableRingBuffer<'d, W>), } -#[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] fn dr(w: crate::pac::sai::Sai, sub_block: WhichSubBlock) -> *mut W { let ch = w.ch(sub_block as usize); ch.dr().as_ptr() as _ } // return the type for (sd, sck) -fn get_af_types(mode: Mode, tx_rx: TxRx) -> (AFType, AFType) { +fn get_af_types(mode: Mode, tx_rx: TxRx) -> (AfType, AfType) { ( //sd is defined by tx/rx mode match tx_rx { - TxRx::Transmitter => AFType::OutputPushPull, - TxRx::Receiver => AFType::Input, + TxRx::Transmitter => AfType::output(OutputType::PushPull, Speed::VeryHigh), + TxRx::Receiver => AfType::input(Pull::Down), // Ensure mute level when no input is connected. }, //clocks (mclk, sck and fs) are defined by master/slave match mode { - Mode::Master => AFType::OutputPushPull, - Mode::Slave => AFType::Input, + Mode::Master => AfType::output(OutputType::PushPull, Speed::VeryHigh), + Mode::Slave => AfType::input(Pull::Down), // Ensure no clocks when no input is connected. }, ) } -fn get_ring_buffer<'d, T: Instance, C: Channel, W: word::Word>( - dma: impl Peripheral

+ 'd, +#[cfg(not(gpdma))] +fn get_ring_buffer<'d, T: Instance, W: word::Word>( + dma: impl Peripheral

+ 'd, dma_buf: &'d mut [W], request: Request, sub_block: WhichSubBlock, tx_rx: TxRx, -) -> RingBuffer<'d, C, W> { +) -> RingBuffer<'d, W> { let opts = TransferOptions { half_transfer_ir: true, //the new_write() and new_read() always use circular mode @@ -554,12 +704,12 @@ fn update_synchronous_config(config: &mut Config) { config.mode = Mode::Slave; config.sync_output = false; - #[cfg(any(sai_v1, sai_v2, sai_v3))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm))] { config.sync_input = SyncInput::Internal; } - #[cfg(any(sai_v4))] + #[cfg(any(sai_v4_2pdm, sai_v4_4pdm))] { //this must either be Internal or External //The asynchronous sub-block on the same SAI needs to enable sync_output @@ -578,7 +728,7 @@ pub struct SubBlock<'d, T, S: SubBlockInstance> { /// You can then create a [`Sai`] driver for each each half. pub fn split_subblocks<'d, T: Instance>(peri: impl Peripheral

+ 'd) -> (SubBlock<'d, T, A>, SubBlock<'d, T, B>) { into_ref!(peri); - T::enable_and_reset(); + rcc::enable_and_reset::(); ( SubBlock { @@ -593,17 +743,21 @@ pub fn split_subblocks<'d, T: Instance>(peri: impl Peripheral

+ 'd) -> (S } /// SAI sub-block driver. -pub struct Sai<'d, T: Instance, C: Channel, W: word::Word> { +pub struct Sai<'d, T: Instance, W: word::Word> { _peri: PeripheralRef<'d, T>, sd: Option>, fs: Option>, sck: Option>, mclk: Option>, - ring_buffer: RingBuffer<'d, C, W>, + #[cfg(gpdma)] + ring_buffer: PhantomData, + #[cfg(not(gpdma))] + ring_buffer: RingBuffer<'d, W>, sub_block: WhichSubBlock, } -impl<'d, T: Instance, C: Channel, W: word::Word> Sai<'d, T, C, W> { +#[cfg(not(gpdma))] +impl<'d, T: Instance, W: word::Word> Sai<'d, T, W> { /// Create a new SAI driver in asynchronous mode with MCLK. /// /// You can obtain the [`SubBlock`] with [`split_subblocks`]. @@ -613,19 +767,14 @@ impl<'d, T: Instance, C: Channel, W: word::Word> Sai<'d, T, C, W> { sd: impl Peripheral

> + 'd, fs: impl Peripheral

> + 'd, mclk: impl Peripheral

> + 'd, - dma: impl Peripheral

+ 'd, + dma: impl Peripheral

> + 'd, dma_buf: &'d mut [W], mut config: Config, - ) -> Self - where - C: Channel + Dma, - { + ) -> Self { into_ref!(mclk); let (_sd_af_type, ck_af_type) = get_af_types(config.mode, config.tx_rx); - mclk.set_as_af(mclk.af_num(), ck_af_type); - mclk.set_speed(crate::gpio::Speed::VeryHigh); if config.master_clock_divider == MasterClockDivider::MasterClockDisabled { config.master_clock_divider = MasterClockDivider::Div1; @@ -642,24 +791,17 @@ impl<'d, T: Instance, C: Channel, W: word::Word> Sai<'d, T, C, W> { sck: impl Peripheral

> + 'd, sd: impl Peripheral

> + 'd, fs: impl Peripheral

> + 'd, - dma: impl Peripheral

+ 'd, + dma: impl Peripheral

> + 'd, dma_buf: &'d mut [W], config: Config, - ) -> Self - where - C: Channel + Dma, - { + ) -> Self { let peri = peri.peri; into_ref!(peri, dma, sck, sd, fs); let (sd_af_type, ck_af_type) = get_af_types(config.mode, config.tx_rx); sd.set_as_af(sd.af_num(), sd_af_type); - sd.set_speed(crate::gpio::Speed::VeryHigh); - sck.set_as_af(sck.af_num(), ck_af_type); - sck.set_speed(crate::gpio::Speed::VeryHigh); fs.set_as_af(fs.af_num(), ck_af_type); - fs.set_speed(crate::gpio::Speed::VeryHigh); let sub_block = S::WHICH; let request = dma.request(); @@ -671,7 +813,7 @@ impl<'d, T: Instance, C: Channel, W: word::Word> Sai<'d, T, C, W> { None, Some(sd.map_into()), Some(fs.map_into()), - get_ring_buffer::(dma, dma_buf, request, sub_block, config.tx_rx), + get_ring_buffer::(dma, dma_buf, request, sub_block, config.tx_rx), config, ) } @@ -682,22 +824,17 @@ impl<'d, T: Instance, C: Channel, W: word::Word> Sai<'d, T, C, W> { pub fn new_synchronous( peri: SubBlock<'d, T, S>, sd: impl Peripheral

> + 'd, - dma: impl Peripheral

+ 'd, + dma: impl Peripheral

> + 'd, dma_buf: &'d mut [W], mut config: Config, - ) -> Self - where - C: Channel + Dma, - { + ) -> Self { update_synchronous_config(&mut config); let peri = peri.peri; into_ref!(dma, peri, sd); let (sd_af_type, _ck_af_type) = get_af_types(config.mode, config.tx_rx); - sd.set_as_af(sd.af_num(), sd_af_type); - sd.set_speed(crate::gpio::Speed::VeryHigh); let sub_block = S::WHICH; let request = dma.request(); @@ -709,7 +846,7 @@ impl<'d, T: Instance, C: Channel, W: word::Word> Sai<'d, T, C, W> { None, Some(sd.map_into()), None, - get_ring_buffer::(dma, dma_buf, request, sub_block, config.tx_rx), + get_ring_buffer::(dma, dma_buf, request, sub_block, config.tx_rx), config, ) } @@ -721,16 +858,16 @@ impl<'d, T: Instance, C: Channel, W: word::Word> Sai<'d, T, C, W> { mclk: Option>, sd: Option>, fs: Option>, - ring_buffer: RingBuffer<'d, C, W>, + ring_buffer: RingBuffer<'d, W>, config: Config, ) -> Self { - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] { let ch = T::REGS.ch(sub_block as usize); ch.cr1().modify(|w| w.set_saien(false)); } - #[cfg(any(sai_v4))] + #[cfg(any(sai_v4_2pdm, sai_v4_4pdm))] { if let SyncInput::External(i) = config.sync_input { T::REGS.gcr().modify(|w| { @@ -749,7 +886,7 @@ impl<'d, T: Instance, C: Channel, W: word::Word> Sai<'d, T, C, W> { } } - #[cfg(any(sai_v1, sai_v2, sai_v3, sai_v4))] + #[cfg(any(sai_v1, sai_v2, sai_v3_2pdm, sai_v3_4pdm, sai_v4_2pdm, sai_v4_4pdm))] { let ch = T::REGS.ch(sub_block as usize); ch.cr1().modify(|w| { @@ -830,7 +967,7 @@ impl<'d, T: Instance, C: Channel, W: word::Word> Sai<'d, T, C, W> { } } - fn is_transmitter(ring_buffer: &RingBuffer) -> bool { + fn is_transmitter(ring_buffer: &RingBuffer) -> bool { match ring_buffer { RingBuffer::Writable(_) => true, _ => false, @@ -839,7 +976,7 @@ impl<'d, T: Instance, C: Channel, W: word::Word> Sai<'d, T, C, W> { /// Reset SAI operation. pub fn reset() { - T::enable_and_reset(); + rcc::enable_and_reset::(); } /// Flush. @@ -856,6 +993,21 @@ impl<'d, T: Instance, C: Channel, W: word::Word> Sai<'d, T, C, W> { ch.cr2().modify(|w| w.set_mute(value)); } + /// Determine the mute state of the receiver. + /// + /// Clears the mute state flag in the status register. + pub fn is_muted(&self) -> Result { + match &self.ring_buffer { + RingBuffer::Readable(_) => { + let ch = T::REGS.ch(self.sub_block as usize); + let mute_state = ch.sr().read().mutedet(); + ch.clrfr().write(|w| w.set_cmutedet(true)); + Ok(mute_state) + } + _ => Err(Error::NotAReceiver), + } + } + /// Write data to the SAI ringbuffer. /// /// This appends the data to the buffer and returns immediately. The @@ -889,7 +1041,7 @@ impl<'d, T: Instance, C: Channel, W: word::Word> Sai<'d, T, C, W> { } } -impl<'d, T: Instance, C: Channel, W: word::Word> Drop for Sai<'d, T, C, W> { +impl<'d, T: Instance, W: word::Word> Drop for Sai<'d, T, W> { fn drop(&mut self) { let ch = T::REGS.ch(self.sub_block as usize); ch.cr1().modify(|w| w.set_saien(false)); @@ -900,43 +1052,42 @@ impl<'d, T: Instance, C: Channel, W: word::Word> Drop for Sai<'d, T, C, W> { } } -pub(crate) mod sealed { - use super::*; +trait SealedInstance { + const REGS: Regs; +} - pub trait Instance { - const REGS: Regs; - } +#[derive(Copy, Clone)] +enum WhichSubBlock { + A = 0, + B = 1, +} - #[derive(Copy, Clone)] - pub enum WhichSubBlock { - A = 0, - B = 1, - } - - pub trait SubBlock { - const WHICH: WhichSubBlock; - } +trait SealedSubBlock { + const WHICH: WhichSubBlock; } /// Sub-block instance trait. -pub trait SubBlockInstance: sealed::SubBlock {} +#[allow(private_bounds)] +pub trait SubBlockInstance: SealedSubBlock {} /// Sub-block A. pub enum A {} -impl sealed::SubBlock for A { +impl SealedSubBlock for A { const WHICH: WhichSubBlock = WhichSubBlock::A; } impl SubBlockInstance for A {} /// Sub-block B. pub enum B {} -impl sealed::SubBlock for B { +impl SealedSubBlock for B { const WHICH: WhichSubBlock = WhichSubBlock::B; } impl SubBlockInstance for B {} /// SAI instance trait. -pub trait Instance: Peripheral

+ sealed::Instance + RccPeripheral {} +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + RccPeripheral {} + pin_trait!(SckPin, Instance, SubBlockInstance); pin_trait!(FsPin, Instance, SubBlockInstance); pin_trait!(SdPin, Instance, SubBlockInstance); @@ -946,7 +1097,7 @@ dma_trait!(Dma, Instance, SubBlockInstance); foreach_peripheral!( (sai, $inst:ident) => { - impl sealed::Instance for peripherals::$inst { + impl SealedInstance for peripherals::$inst { const REGS: Regs = crate::pac::$inst; } diff --git a/embassy-stm32/src/sdmmc/mod.rs b/embassy-stm32/src/sdmmc/mod.rs index debe26c88..ed344c412 100644 --- a/embassy-stm32/src/sdmmc/mod.rs +++ b/embassy-stm32/src/sdmmc/mod.rs @@ -13,11 +13,12 @@ use embassy_sync::waitqueue::AtomicWaker; use sdio_host::{BusWidth, CardCapacity, CardStatus, CurrentState, SDStatus, CID, CSD, OCR, SCR}; use crate::dma::NoDma; -use crate::gpio::sealed::{AFType, Pin}; -use crate::gpio::{AnyPin, Pull, Speed}; +#[cfg(gpio_v2)] +use crate::gpio::Pull; +use crate::gpio::{AfType, AnyPin, OutputType, SealedPin, Speed}; use crate::interrupt::typelevel::Interrupt; use crate::pac::sdmmc::Sdmmc as RegBlock; -use crate::rcc::RccPeripheral; +use crate::rcc::{self, RccPeripheral}; use crate::time::Hertz; use crate::{interrupt, peripherals, Peripheral}; @@ -93,6 +94,34 @@ impl DerefMut for DataBlock { } } +/// Command Block buffer for SDMMC command transfers. +/// +/// This is a 16-word array, exposed so that DMA commpatible memory can be used if required. +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct CmdBlock(pub [u32; 16]); + +impl CmdBlock { + /// Creates a new instance of CmdBlock + pub const fn new() -> Self { + Self([0u32; 16]) + } +} + +impl Deref for CmdBlock { + type Target = [u32; 16]; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for CmdBlock { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + /// Errors #[non_exhaustive] #[derive(Debug, Copy, Clone, PartialEq, Eq)] @@ -228,10 +257,10 @@ fn clk_div(ker_ck: Hertz, sdmmc_ck: u32) -> Result<(bool, u16, Hertz), Error> { } #[cfg(sdmmc_v1)] -type Transfer<'a, C> = crate::dma::Transfer<'a, C>; +type Transfer<'a> = crate::dma::Transfer<'a>; #[cfg(sdmmc_v2)] -struct Transfer<'a, C> { - _dummy: core::marker::PhantomData<&'a mut C>, +struct Transfer<'a> { + _dummy: PhantomData<&'a ()>, } #[cfg(all(sdmmc_v1, dma))] @@ -240,12 +269,14 @@ const DMA_TRANSFER_OPTIONS: crate::dma::TransferOptions = crate::dma::TransferOp mburst: crate::dma::Burst::Incr4, flow_ctrl: crate::dma::FlowControl::Peripheral, fifo_threshold: Some(crate::dma::FifoThreshold::Full), + priority: crate::dma::Priority::VeryHigh, circular: false, half_transfer_ir: false, complete_transfer_ir: true, }; #[cfg(all(sdmmc_v1, not(dma)))] const DMA_TRANSFER_OPTIONS: crate::dma::TransferOptions = crate::dma::TransferOptions { + priority: crate::dma::Priority::VeryHigh, circular: false, half_transfer_ir: false, complete_transfer_ir: true, @@ -289,8 +320,19 @@ pub struct Sdmmc<'d, T: Instance, Dma: SdmmcDma = NoDma> { signalling: Signalling, /// Card card: Option, + + /// An optional buffer to be used for commands + /// This should be used if there are special memory location requirements for dma + cmd_block: Option<&'d mut CmdBlock>, } +const CLK_AF: AfType = AfType::output(OutputType::PushPull, Speed::VeryHigh); +#[cfg(gpio_v1)] +const CMD_AF: AfType = AfType::output(OutputType::PushPull, Speed::VeryHigh); +#[cfg(gpio_v2)] +const CMD_AF: AfType = AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up); +const DATA_AF: AfType = CMD_AF; + #[cfg(sdmmc_v1)] impl<'d, T: Instance, Dma: SdmmcDma> Sdmmc<'d, T, Dma> { /// Create a new SDMMC driver, with 1 data lane. @@ -306,13 +348,9 @@ impl<'d, T: Instance, Dma: SdmmcDma> Sdmmc<'d, T, Dma> { into_ref!(clk, cmd, d0); critical_section::with(|_| { - clk.set_as_af_pull(clk.af_num(), AFType::OutputPushPull, Pull::None); - cmd.set_as_af_pull(cmd.af_num(), AFType::OutputPushPull, Pull::Up); - d0.set_as_af_pull(d0.af_num(), AFType::OutputPushPull, Pull::Up); - - clk.set_speed(Speed::VeryHigh); - cmd.set_speed(Speed::VeryHigh); - d0.set_speed(Speed::VeryHigh); + clk.set_as_af(clk.af_num(), CLK_AF); + cmd.set_as_af(cmd.af_num(), CMD_AF); + d0.set_as_af(d0.af_num(), DATA_AF); }); Self::new_inner( @@ -344,19 +382,12 @@ impl<'d, T: Instance, Dma: SdmmcDma> Sdmmc<'d, T, Dma> { into_ref!(clk, cmd, d0, d1, d2, d3); critical_section::with(|_| { - clk.set_as_af_pull(clk.af_num(), AFType::OutputPushPull, Pull::None); - cmd.set_as_af_pull(cmd.af_num(), AFType::OutputPushPull, Pull::Up); - d0.set_as_af_pull(d0.af_num(), AFType::OutputPushPull, Pull::Up); - d1.set_as_af_pull(d1.af_num(), AFType::OutputPushPull, Pull::Up); - d2.set_as_af_pull(d2.af_num(), AFType::OutputPushPull, Pull::Up); - d3.set_as_af_pull(d3.af_num(), AFType::OutputPushPull, Pull::Up); - - clk.set_speed(Speed::VeryHigh); - cmd.set_speed(Speed::VeryHigh); - d0.set_speed(Speed::VeryHigh); - d1.set_speed(Speed::VeryHigh); - d2.set_speed(Speed::VeryHigh); - d3.set_speed(Speed::VeryHigh); + clk.set_as_af(clk.af_num(), CLK_AF); + cmd.set_as_af(cmd.af_num(), CMD_AF); + d0.set_as_af(d0.af_num(), DATA_AF); + d1.set_as_af(d1.af_num(), DATA_AF); + d2.set_as_af(d2.af_num(), DATA_AF); + d3.set_as_af(d3.af_num(), DATA_AF); }); Self::new_inner( @@ -387,13 +418,9 @@ impl<'d, T: Instance> Sdmmc<'d, T, NoDma> { into_ref!(clk, cmd, d0); critical_section::with(|_| { - clk.set_as_af_pull(clk.af_num(), AFType::OutputPushPull, Pull::None); - cmd.set_as_af_pull(cmd.af_num(), AFType::OutputPushPull, Pull::Up); - d0.set_as_af_pull(d0.af_num(), AFType::OutputPushPull, Pull::Up); - - clk.set_speed(Speed::VeryHigh); - cmd.set_speed(Speed::VeryHigh); - d0.set_speed(Speed::VeryHigh); + clk.set_as_af(clk.af_num(), CLK_AF); + cmd.set_as_af(cmd.af_num(), CMD_AF); + d0.set_as_af(d0.af_num(), DATA_AF); }); Self::new_inner( @@ -424,19 +451,12 @@ impl<'d, T: Instance> Sdmmc<'d, T, NoDma> { into_ref!(clk, cmd, d0, d1, d2, d3); critical_section::with(|_| { - clk.set_as_af_pull(clk.af_num(), AFType::OutputPushPull, Pull::None); - cmd.set_as_af_pull(cmd.af_num(), AFType::OutputPushPull, Pull::Up); - d0.set_as_af_pull(d0.af_num(), AFType::OutputPushPull, Pull::Up); - d1.set_as_af_pull(d1.af_num(), AFType::OutputPushPull, Pull::Up); - d2.set_as_af_pull(d2.af_num(), AFType::OutputPushPull, Pull::Up); - d3.set_as_af_pull(d3.af_num(), AFType::OutputPushPull, Pull::Up); - - clk.set_speed(Speed::VeryHigh); - cmd.set_speed(Speed::VeryHigh); - d0.set_speed(Speed::VeryHigh); - d1.set_speed(Speed::VeryHigh); - d2.set_speed(Speed::VeryHigh); - d3.set_speed(Speed::VeryHigh); + clk.set_as_af(clk.af_num(), CLK_AF); + cmd.set_as_af(cmd.af_num(), CMD_AF); + d0.set_as_af(d0.af_num(), DATA_AF); + d1.set_as_af(d1.af_num(), DATA_AF); + d2.set_as_af(d2.af_num(), DATA_AF); + d3.set_as_af(d3.af_num(), DATA_AF); }); Self::new_inner( @@ -467,7 +487,7 @@ impl<'d, T: Instance, Dma: SdmmcDma + 'd> Sdmmc<'d, T, Dma> { ) -> Self { into_ref!(sdmmc, dma); - T::enable_and_reset(); + rcc::enable_and_reset::(); T::Interrupt::unpend(); unsafe { T::Interrupt::enable() }; @@ -507,6 +527,7 @@ impl<'d, T: Instance, Dma: SdmmcDma + 'd> Sdmmc<'d, T, Dma> { clock: SD_INIT_FREQ, signalling: Default::default(), card: None, + cmd_block: None, } } @@ -543,12 +564,14 @@ impl<'d, T: Instance, Dma: SdmmcDma + 'd> Sdmmc<'d, T, Dma> { /// # Safety /// /// `buffer` must be valid for the whole transfer and word aligned + #[allow(unused_variables)] fn prepare_datapath_read<'a>( - &'a mut self, + config: &Config, + dma: &'a mut PeripheralRef<'d, Dma>, buffer: &'a mut [u32], length_bytes: u32, block_size: u8, - ) -> Transfer<'a, Dma> { + ) -> Transfer<'a> { assert!(block_size <= 14, "Block size up to 2^14 bytes"); let regs = T::regs(); @@ -556,15 +579,14 @@ impl<'d, T: Instance, Dma: SdmmcDma + 'd> Sdmmc<'d, T, Dma> { Self::wait_idle(); Self::clear_interrupt_flags(); - regs.dtimer() - .write(|w| w.set_datatime(self.config.data_transfer_timeout)); + regs.dtimer().write(|w| w.set_datatime(config.data_transfer_timeout)); regs.dlenr().write(|w| w.set_datalength(length_bytes)); #[cfg(sdmmc_v1)] let transfer = unsafe { - let request = self.dma.request(); + let request = dma.request(); Transfer::new_read( - &mut self.dma, + dma, request, regs.fifor().as_ptr() as *mut u32, buffer, @@ -596,12 +618,7 @@ impl<'d, T: Instance, Dma: SdmmcDma + 'd> Sdmmc<'d, T, Dma> { /// # Safety /// /// `buffer` must be valid for the whole transfer and word aligned - fn prepare_datapath_write<'a>( - &'a mut self, - buffer: &'a [u32], - length_bytes: u32, - block_size: u8, - ) -> Transfer<'a, Dma> { + fn prepare_datapath_write<'a>(&'a mut self, buffer: &'a [u32], length_bytes: u32, block_size: u8) -> Transfer<'a> { assert!(block_size <= 14, "Block size up to 2^14 bytes"); let regs = T::regs(); @@ -670,7 +687,7 @@ impl<'d, T: Instance, Dma: SdmmcDma + 'd> Sdmmc<'d, T, Dma> { _ => panic!("Invalid Bus Width"), }; - let ker_ck = T::kernel_clk(); + let ker_ck = T::frequency(); let (_bypass, clkdiv, new_clock) = clk_div(ker_ck, freq)?; // Enforce AHB and SDMMC_CK clock relation. See RM0433 Rev 7 @@ -709,13 +726,16 @@ impl<'d, T: Instance, Dma: SdmmcDma + 'd> Sdmmc<'d, T, Dma> { Signalling::SDR12 => 0xFF_FF00, }; - let mut status = [0u32; 16]; + let status = match self.cmd_block.as_deref_mut() { + Some(x) => x, + None => &mut CmdBlock::new(), + }; // Arm `OnDrop` after the buffer, so it will be dropped first let regs = T::regs(); let on_drop = OnDrop::new(|| Self::on_drop()); - let transfer = self.prepare_datapath_read(&mut status, 64, 6); + let transfer = Self::prepare_datapath_read(&self.config, &mut self.dma, status.as_mut(), 64, 6); InterruptHandler::::data_interrupts(true); Self::cmd(Cmd::cmd6(set_function), true)?; // CMD6 @@ -787,16 +807,21 @@ impl<'d, T: Instance, Dma: SdmmcDma + 'd> Sdmmc<'d, T, Dma> { let card = self.card.as_mut().ok_or(Error::NoCard)?; let rca = card.rca; + let cmd_block = match self.cmd_block.as_deref_mut() { + Some(x) => x, + None => &mut CmdBlock::new(), + }; + Self::cmd(Cmd::set_block_length(64), false)?; // CMD16 Self::cmd(Cmd::app_cmd(rca << 16), false)?; // APP - let mut status = [0u32; 16]; + let status = cmd_block; // Arm `OnDrop` after the buffer, so it will be dropped first let regs = T::regs(); let on_drop = OnDrop::new(|| Self::on_drop()); - let transfer = self.prepare_datapath_read(&mut status, 64, 6); + let transfer = Self::prepare_datapath_read(&self.config, &mut self.dma, status.as_mut(), 64, 6); InterruptHandler::::data_interrupts(true); Self::cmd(Cmd::card_status(0), true)?; @@ -830,7 +855,7 @@ impl<'d, T: Instance, Dma: SdmmcDma + 'd> Sdmmc<'d, T, Dma> { for byte in status.iter_mut() { *byte = u32::from_be(*byte); } - self.card.as_mut().unwrap().status = status.into(); + self.card.as_mut().unwrap().status = status.0.into(); } res } @@ -889,13 +914,17 @@ impl<'d, T: Instance, Dma: SdmmcDma + 'd> Sdmmc<'d, T, Dma> { Self::cmd(Cmd::set_block_length(8), false)?; // CMD16 Self::cmd(Cmd::app_cmd(card.rca << 16), false)?; - let mut scr = [0u32; 2]; + let cmd_block = match self.cmd_block.as_deref_mut() { + Some(x) => x, + None => &mut CmdBlock::new(), + }; + let scr = &mut cmd_block.0[..2]; // Arm `OnDrop` after the buffer, so it will be dropped first let regs = T::regs(); let on_drop = OnDrop::new(|| Self::on_drop()); - let transfer = self.prepare_datapath_read(&mut scr[..], 8, 3); + let transfer = Self::prepare_datapath_read(&self.config, &mut self.dma, scr, 8, 3); InterruptHandler::::data_interrupts(true); Self::cmd(Cmd::cmd51(), true)?; @@ -927,7 +956,7 @@ impl<'d, T: Instance, Dma: SdmmcDma + 'd> Sdmmc<'d, T, Dma> { drop(transfer); unsafe { - let scr_bytes = &*(&scr as *const [u32; 2] as *const [u8; 8]); + let scr_bytes = &*(&scr as *const _ as *const [u8; 8]); card.scr = SCR(u64::from_be_bytes(*scr_bytes)); } } @@ -1019,11 +1048,10 @@ impl<'d, T: Instance, Dma: SdmmcDma + 'd> Sdmmc<'d, T, Dma> { Self::stop_datapath(); } - /// Initializes card (if present) and sets the bus at the - /// specified frequency. + /// Initializes card (if present) and sets the bus at the specified frequency. pub async fn init_card(&mut self, freq: Hertz) -> Result<(), Error> { let regs = T::regs(); - let ker_ck = T::kernel_clk(); + let ker_ck = T::frequency(); let bus_width = match self.d3.is_some() { true => BusWidth::Four, @@ -1160,6 +1188,7 @@ impl<'d, T: Instance, Dma: SdmmcDma + 'd> Sdmmc<'d, T, Dma> { } } } + // Read status after signalling change self.read_sd_status().await?; @@ -1185,7 +1214,7 @@ impl<'d, T: Instance, Dma: SdmmcDma + 'd> Sdmmc<'d, T, Dma> { let regs = T::regs(); let on_drop = OnDrop::new(|| Self::on_drop()); - let transfer = self.prepare_datapath_read(buffer, 512, 9); + let transfer = Self::prepare_datapath_read(&self.config, &mut self.dma, buffer, 512, 9); InterruptHandler::::data_interrupts(true); Self::cmd(Cmd::read_single_block(address), true)?; @@ -1308,6 +1337,14 @@ impl<'d, T: Instance, Dma: SdmmcDma + 'd> Sdmmc<'d, T, Dma> { pub fn clock(&self) -> Hertz { self.clock } + + /// Set a specific cmd buffer rather than using the default stack allocated one. + /// This is required if stack RAM cannot be used with DMA and usually manifests + /// itself as an indefinite wait on a dma transfer because the dma peripheral + /// cannot access the memory. + pub fn set_cmd_block(&mut self, cmd_block: &'d mut CmdBlock) { + self.cmd_block = Some(cmd_block) + } } impl<'d, T: Instance, Dma: SdmmcDma + 'd> Drop for Sdmmc<'d, T, Dma> { @@ -1421,22 +1458,17 @@ impl Cmd { ////////////////////////////////////////////////////// -pub(crate) mod sealed { - use super::*; - - pub trait Instance { - type Interrupt: interrupt::typelevel::Interrupt; - - fn regs() -> RegBlock; - fn state() -> &'static AtomicWaker; - fn kernel_clk() -> Hertz; - } - - pub trait Pins {} +trait SealedInstance { + fn regs() -> RegBlock; + fn state() -> &'static AtomicWaker; } /// SDMMC instance trait. -pub trait Instance: sealed::Instance + RccPeripheral + 'static {} +#[allow(private_bounds)] +pub trait Instance: SealedInstance + RccPeripheral + 'static { + /// Interrupt for this instance. + type Interrupt: interrupt::typelevel::Interrupt; +} pin_trait!(CkPin, Instance); pin_trait!(CmdPin, Instance); @@ -1461,66 +1493,9 @@ pub trait SdmmcDma {} #[cfg(sdmmc_v2)] impl SdmmcDma for NoDma {} -cfg_if::cfg_if! { - // TODO, these could not be implemented, because required clocks are not exposed in RCC: - // - H7 uses pll1_q_ck or pll2_r_ck depending on SDMMCSEL - // - L1 uses pll48 - // - L4 uses clk48(pll48) - // - L4+, L5, U5 uses clk48(pll48) or PLLSAI3CLK(PLLP) depending on SDMMCSEL - if #[cfg(stm32f1)] { - // F1 uses AHB1(HCLK), which is correct in PAC - macro_rules! kernel_clk { - ($inst:ident) => { - ::frequency() - } - } - } else if #[cfg(any(stm32f2, stm32f4))] { - // F2, F4 always use pll48 - macro_rules! kernel_clk { - ($inst:ident) => { - critical_section::with(|_| unsafe { - unwrap!(crate::rcc::get_freqs().pll1_q) - }) - } - } - } else if #[cfg(stm32f7)] { - macro_rules! kernel_clk { - (SDMMC1) => { - critical_section::with(|_| unsafe { - let sdmmcsel = crate::pac::RCC.dckcfgr2().read().sdmmc1sel(); - if sdmmcsel == crate::pac::rcc::vals::Sdmmcsel::SYS { - crate::rcc::get_freqs().sys - } else { - unwrap!(crate::rcc::get_freqs().pll1_q) - } - }) - }; - (SDMMC2) => { - critical_section::with(|_| unsafe { - let sdmmcsel = crate::pac::RCC.dckcfgr2().read().sdmmc2sel(); - if sdmmcsel == crate::pac::rcc::vals::Sdmmcsel::SYS { - crate::rcc::get_freqs().sys - } else { - unwrap!(crate::rcc::get_freqs().pll1_q) - } - }) - }; - } - } else { - // Use default peripheral clock and hope it works - macro_rules! kernel_clk { - ($inst:ident) => { - ::frequency() - } - } - } -} - foreach_peripheral!( (sdmmc, $inst:ident) => { - impl sealed::Instance for peripherals::$inst { - type Interrupt = crate::interrupt::typelevel::$inst; - + impl SealedInstance for peripherals::$inst { fn regs() -> RegBlock { crate::pac::$inst } @@ -1529,12 +1504,51 @@ foreach_peripheral!( static WAKER: ::embassy_sync::waitqueue::AtomicWaker = ::embassy_sync::waitqueue::AtomicWaker::new(); &WAKER } - - fn kernel_clk() -> Hertz { - kernel_clk!($inst) - } } - impl Instance for peripherals::$inst {} + impl Instance for peripherals::$inst { + type Interrupt = crate::interrupt::typelevel::$inst; + } }; ); + +impl<'d, T: Instance, Dma: SdmmcDma + 'd> block_device_driver::BlockDevice<512> for Sdmmc<'d, T, Dma> { + type Error = Error; + type Align = aligned::A4; + + async fn read( + &mut self, + mut block_address: u32, + buf: &mut [aligned::Aligned], + ) -> Result<(), Self::Error> { + // FIXME/TODO because of missing read_blocks multiple we have to do this one block at a time + for block in buf.iter_mut() { + // safety aligned by block device + let block = unsafe { &mut *(block as *mut _ as *mut crate::sdmmc::DataBlock) }; + self.read_block(block_address, block).await?; + block_address += 1; + } + + Ok(()) + } + + async fn write( + &mut self, + mut block_address: u32, + buf: &[aligned::Aligned], + ) -> Result<(), Self::Error> { + // FIXME/TODO because of missing read_blocks multiple we have to do this one block at a time + for block in buf.iter() { + // safety aligned by block device + let block = unsafe { &*(block as *const _ as *const crate::sdmmc::DataBlock) }; + self.write_block(block_address, block).await?; + block_address += 1; + } + + Ok(()) + } + + async fn size(&mut self) -> Result { + Ok(self.card()?.size()) + } +} diff --git a/embassy-stm32/src/spi/mod.rs b/embassy-stm32/src/spi/mod.rs index 23f027e70..a65b0cc64 100644 --- a/embassy-stm32/src/spi/mod.rs +++ b/embassy-stm32/src/spi/mod.rs @@ -1,23 +1,24 @@ //! Serial Peripheral Interface (SPI) #![macro_use] +use core::marker::PhantomData; use core::ptr; use embassy_embedded_hal::SetConfig; use embassy_futures::join::join; -use embassy_hal_internal::{into_ref, PeripheralRef}; +use embassy_hal_internal::PeripheralRef; pub use embedded_hal_02::spi::{Mode, Phase, Polarity, MODE_0, MODE_1, MODE_2, MODE_3}; -use crate::dma::{slice_ptr_parts, word, Transfer}; -use crate::gpio::sealed::{AFType, Pin as _}; -use crate::gpio::{AnyPin, Pull}; +use crate::dma::{word, ChannelAndRequest}; +use crate::gpio::{AfType, AnyPin, OutputType, Pull, SealedPin as _, Speed}; +use crate::mode::{Async, Blocking, Mode as PeriMode}; use crate::pac::spi::{regs, vals, Spi as Regs}; -use crate::rcc::RccPeripheral; +use crate::rcc::{RccInfo, SealedRccPeripheral}; use crate::time::Hertz; -use crate::{peripherals, Peripheral}; +use crate::Peripheral; /// SPI error. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Error { /// Invalid framing. @@ -49,6 +50,11 @@ pub struct Config { pub bit_order: BitOrder, /// Clock frequency. pub frequency: Hertz, + /// Enable internal pullup on MISO. + /// + /// There are some ICs that require a pull-up on the MISO pin for some applications. + /// If you are unsure, you probably don't need this. + pub miso_pull: Pull, } impl Default for Config { @@ -57,6 +63,7 @@ impl Default for Config { mode: MODE_0, bit_order: BitOrder::MsbFirst, frequency: Hertz(1_000_000), + miso_pull: Pull::None, } } } @@ -82,181 +89,77 @@ impl Config { BitOrder::MsbFirst => vals::Lsbfirst::MSBFIRST, } } -} + #[cfg(gpio_v1)] + fn sck_af(&self) -> AfType { + AfType::output(OutputType::PushPull, Speed::VeryHigh) + } + + #[cfg(gpio_v2)] + fn sck_af(&self) -> AfType { + AfType::output_pull( + OutputType::PushPull, + Speed::VeryHigh, + match self.mode.polarity { + Polarity::IdleLow => Pull::Down, + Polarity::IdleHigh => Pull::Up, + }, + ) + } +} /// SPI driver. -pub struct Spi<'d, T: Instance, Tx, Rx> { - _peri: PeripheralRef<'d, T>, +pub struct Spi<'d, M: PeriMode> { + pub(crate) info: &'static Info, + kernel_clock: Hertz, sck: Option>, mosi: Option>, miso: Option>, - txdma: PeripheralRef<'d, Tx>, - rxdma: PeripheralRef<'d, Rx>, + tx_dma: Option>, + rx_dma: Option>, + _phantom: PhantomData, current_word_size: word_impl::Config, } -impl<'d, T: Instance, Tx, Rx> Spi<'d, T, Tx, Rx> { - /// Create a new SPI driver. - pub fn new( - peri: impl Peripheral

+ 'd, - sck: impl Peripheral

> + 'd, - mosi: impl Peripheral

> + 'd, - miso: impl Peripheral

> + 'd, - txdma: impl Peripheral

+ 'd, - rxdma: impl Peripheral

+ 'd, - config: Config, - ) -> Self { - into_ref!(peri, sck, mosi, miso); - - let sck_pull_mode = match config.mode.polarity { - Polarity::IdleLow => Pull::Down, - Polarity::IdleHigh => Pull::Up, - }; - - sck.set_as_af_pull(sck.af_num(), AFType::OutputPushPull, sck_pull_mode); - sck.set_speed(crate::gpio::Speed::VeryHigh); - mosi.set_as_af(mosi.af_num(), AFType::OutputPushPull); - mosi.set_speed(crate::gpio::Speed::VeryHigh); - miso.set_as_af(miso.af_num(), AFType::Input); - miso.set_speed(crate::gpio::Speed::VeryHigh); - - Self::new_inner( - peri, - Some(sck.map_into()), - Some(mosi.map_into()), - Some(miso.map_into()), - txdma, - rxdma, - config, - ) - } - - /// Create a new SPI driver, in RX-only mode (only MISO pin, no MOSI). - pub fn new_rxonly( - peri: impl Peripheral

+ 'd, - sck: impl Peripheral

> + 'd, - miso: impl Peripheral

> + 'd, - txdma: impl Peripheral

+ 'd, // TODO remove - rxdma: impl Peripheral

+ 'd, - config: Config, - ) -> Self { - into_ref!(sck, miso); - sck.set_as_af(sck.af_num(), AFType::OutputPushPull); - sck.set_speed(crate::gpio::Speed::VeryHigh); - miso.set_as_af(miso.af_num(), AFType::Input); - miso.set_speed(crate::gpio::Speed::VeryHigh); - - Self::new_inner( - peri, - Some(sck.map_into()), - None, - Some(miso.map_into()), - txdma, - rxdma, - config, - ) - } - - /// Create a new SPI driver, in TX-only mode (only MOSI pin, no MISO). - pub fn new_txonly( - peri: impl Peripheral

+ 'd, - sck: impl Peripheral

> + 'd, - mosi: impl Peripheral

> + 'd, - txdma: impl Peripheral

+ 'd, - rxdma: impl Peripheral

+ 'd, // TODO remove - config: Config, - ) -> Self { - into_ref!(sck, mosi); - sck.set_as_af(sck.af_num(), AFType::OutputPushPull); - sck.set_speed(crate::gpio::Speed::VeryHigh); - mosi.set_as_af(mosi.af_num(), AFType::OutputPushPull); - mosi.set_speed(crate::gpio::Speed::VeryHigh); - - Self::new_inner( - peri, - Some(sck.map_into()), - Some(mosi.map_into()), - None, - txdma, - rxdma, - config, - ) - } - - /// Create a new SPI driver, in TX-only mode, without SCK pin. - /// - /// This can be useful for bit-banging non-SPI protocols. - pub fn new_txonly_nosck( - peri: impl Peripheral

+ 'd, - mosi: impl Peripheral

> + 'd, - txdma: impl Peripheral

+ 'd, - rxdma: impl Peripheral

+ 'd, // TODO: remove - config: Config, - ) -> Self { - into_ref!(mosi); - mosi.set_as_af_pull(mosi.af_num(), AFType::OutputPushPull, Pull::Down); - mosi.set_speed(crate::gpio::Speed::Medium); - - Self::new_inner(peri, None, Some(mosi.map_into()), None, txdma, rxdma, config) - } - - #[cfg(stm32wl)] - /// Useful for on chip peripherals like SUBGHZ which are hardwired. - pub fn new_subghz( - peri: impl Peripheral

+ 'd, - txdma: impl Peripheral

+ 'd, - rxdma: impl Peripheral

+ 'd, - ) -> Self { - // see RM0453 rev 1 section 7.2.13 page 291 - // The SUBGHZSPI_SCK frequency is obtained by PCLK3 divided by two. - // The SUBGHZSPI_SCK clock maximum speed must not exceed 16 MHz. - let pclk3_freq = ::frequency().0; - let freq = Hertz(core::cmp::min(pclk3_freq / 2, 16_000_000)); - let mut config = Config::default(); - config.mode = MODE_0; - config.bit_order = BitOrder::MsbFirst; - config.frequency = freq; - Self::new_inner(peri, None, None, None, txdma, rxdma, config) - } - - #[allow(dead_code)] - pub(crate) fn new_internal( - peri: impl Peripheral

+ 'd, - txdma: impl Peripheral

+ 'd, - rxdma: impl Peripheral

+ 'd, - config: Config, - ) -> Self { - Self::new_inner(peri, None, None, None, txdma, rxdma, config) - } - - fn new_inner( - peri: impl Peripheral

+ 'd, +impl<'d, M: PeriMode> Spi<'d, M> { + fn new_inner( + _peri: impl Peripheral

+ 'd, sck: Option>, mosi: Option>, miso: Option>, - txdma: impl Peripheral

+ 'd, - rxdma: impl Peripheral

+ 'd, + tx_dma: Option>, + rx_dma: Option>, config: Config, ) -> Self { - into_ref!(peri, txdma, rxdma); - - let pclk = T::frequency(); - let freq = config.frequency; - let br = compute_baud_rate(pclk, freq); + let mut this = Self { + info: T::info(), + kernel_clock: T::frequency(), + sck, + mosi, + miso, + tx_dma, + rx_dma, + current_word_size: ::CONFIG, + _phantom: PhantomData, + }; + this.enable_and_init(config); + this + } + fn enable_and_init(&mut self, config: Config) { + let br = compute_baud_rate(self.kernel_clock, config.frequency); let cpha = config.raw_phase(); let cpol = config.raw_polarity(); - let lsbfirst = config.raw_byte_order(); - T::enable_and_reset(); + self.info.rcc.enable_and_reset(); + let regs = self.info.regs; #[cfg(any(spi_v1, spi_f1))] { - T::REGS.cr2().modify(|w| { + regs.cr2().modify(|w| { w.set_ssoe(false); }); - T::REGS.cr1().modify(|w| { + regs.cr1().modify(|w| { w.set_cpha(cpha); w.set_cpol(cpol); @@ -268,21 +171,22 @@ impl<'d, T: Instance, Tx, Rx> Spi<'d, T, Tx, Rx> { w.set_ssm(true); w.set_crcen(false); w.set_bidimode(vals::Bidimode::UNIDIRECTIONAL); - if mosi.is_none() { - w.set_rxonly(vals::Rxonly::OUTPUTDISABLED); - } - w.set_dff(::CONFIG) + // we're doing "fake rxonly", by actually writing one + // byte to TXDR for each byte we want to receive. if we + // set OUTPUTDISABLED here, this hangs. + w.set_rxonly(vals::Rxonly::FULLDUPLEX); + w.set_dff(::CONFIG) }); } #[cfg(spi_v2)] { - T::REGS.cr2().modify(|w| { - let (ds, frxth) = ::CONFIG; + regs.cr2().modify(|w| { + let (ds, frxth) = ::CONFIG; w.set_frxth(frxth); w.set_ds(ds); w.set_ssoe(false); }); - T::REGS.cr1().modify(|w| { + regs.cr1().modify(|w| { w.set_cpha(cpha); w.set_cpol(cpol); @@ -298,8 +202,8 @@ impl<'d, T: Instance, Tx, Rx> Spi<'d, T, Tx, Rx> { } #[cfg(any(spi_v3, spi_v4, spi_v5))] { - T::REGS.ifcr().write(|w| w.0 = 0xffff_ffff); - T::REGS.cfg2().modify(|w| { + regs.ifcr().write(|w| w.0 = 0xffff_ffff); + regs.cfg2().modify(|w| { //w.set_ssoe(true); w.set_ssoe(false); w.set_cpha(cpha); @@ -314,30 +218,20 @@ impl<'d, T: Instance, Tx, Rx> Spi<'d, T, Tx, Rx> { w.set_afcntr(true); w.set_ssiop(vals::Ssiop::ACTIVEHIGH); }); - T::REGS.cfg1().modify(|w| { + regs.cfg1().modify(|w| { w.set_crcen(false); w.set_mbr(br); - w.set_dsize(::CONFIG); + w.set_dsize(::CONFIG); w.set_fthlv(vals::Fthlv::ONEFRAME); }); - T::REGS.cr2().modify(|w| { + regs.cr2().modify(|w| { w.set_tsize(0); }); - T::REGS.cr1().modify(|w| { + regs.cr1().modify(|w| { w.set_ssi(false); w.set_spe(true); }); } - - Self { - _peri: peri, - sck, - mosi, - miso, - txdma, - rxdma, - current_word_size: ::CONFIG, - } } /// Reconfigures it with the supplied config. @@ -347,12 +241,10 @@ impl<'d, T: Instance, Tx, Rx> Spi<'d, T, Tx, Rx> { let lsbfirst = config.raw_byte_order(); - let pclk = T::frequency(); - let freq = config.frequency; - let br = compute_baud_rate(pclk, freq); + let br = compute_baud_rate(self.kernel_clock, config.frequency); #[cfg(any(spi_v1, spi_f1, spi_v2))] - T::REGS.cr1().modify(|w| { + self.info.regs.cr1().modify(|w| { w.set_cpha(cpha); w.set_cpol(cpol); w.set_br(br); @@ -361,12 +253,12 @@ impl<'d, T: Instance, Tx, Rx> Spi<'d, T, Tx, Rx> { #[cfg(any(spi_v3, spi_v4, spi_v5))] { - T::REGS.cfg2().modify(|w| { + self.info.regs.cfg2().modify(|w| { w.set_cpha(cpha); w.set_cpol(cpol); w.set_lsbfirst(lsbfirst); }); - T::REGS.cfg1().modify(|w| { + self.info.regs.cfg1().modify(|w| { w.set_mbr(br); }); } @@ -376,11 +268,11 @@ impl<'d, T: Instance, Tx, Rx> Spi<'d, T, Tx, Rx> { /// Get current SPI configuration. pub fn get_current_config(&self) -> Config { #[cfg(any(spi_v1, spi_f1, spi_v2))] - let cfg = T::REGS.cr1().read(); + let cfg = self.info.regs.cr1().read(); #[cfg(any(spi_v3, spi_v4, spi_v5))] - let cfg = T::REGS.cfg2().read(); + let cfg = self.info.regs.cfg2().read(); #[cfg(any(spi_v3, spi_v4, spi_v5))] - let cfg1 = T::REGS.cfg1().read(); + let cfg1 = self.info.regs.cfg1().read(); let polarity = if cfg.cpol() == vals::Cpol::IDLELOW { Polarity::IdleLow @@ -399,251 +291,99 @@ impl<'d, T: Instance, Tx, Rx> Spi<'d, T, Tx, Rx> { BitOrder::MsbFirst }; + let miso_pull = match &self.miso { + None => Pull::None, + Some(pin) => pin.pull(), + }; + #[cfg(any(spi_v1, spi_f1, spi_v2))] let br = cfg.br(); #[cfg(any(spi_v3, spi_v4, spi_v5))] let br = cfg1.mbr(); - let pclk = T::frequency(); - let frequency = compute_frequency(pclk, br); + let frequency = compute_frequency(self.kernel_clock, br); Config { mode: Mode { polarity, phase }, bit_order, frequency, + miso_pull, } } - fn set_word_size(&mut self, word_size: word_impl::Config) { + pub(crate) fn set_word_size(&mut self, word_size: word_impl::Config) { if self.current_word_size == word_size { return; } + self.info.regs.cr1().modify(|w| { + w.set_spe(false); + }); + #[cfg(any(spi_v1, spi_f1))] - { - T::REGS.cr1().modify(|reg| { - reg.set_spe(false); - reg.set_dff(word_size) - }); - T::REGS.cr1().modify(|reg| { - reg.set_spe(true); - }); - } + self.info.regs.cr1().modify(|reg| { + reg.set_dff(word_size); + }); #[cfg(spi_v2)] - { - T::REGS.cr1().modify(|w| { - w.set_spe(false); - }); - T::REGS.cr2().modify(|w| { - w.set_frxth(word_size.1); - w.set_ds(word_size.0); - }); - T::REGS.cr1().modify(|w| { - w.set_spe(true); - }); - } + self.info.regs.cr2().modify(|w| { + w.set_frxth(word_size.1); + w.set_ds(word_size.0); + }); #[cfg(any(spi_v3, spi_v4, spi_v5))] - { - T::REGS.cr1().modify(|w| { - w.set_csusp(true); - }); - while T::REGS.sr().read().eot() {} - T::REGS.cr1().modify(|w| { - w.set_spe(false); - }); - T::REGS.cfg1().modify(|w| { - w.set_dsize(word_size); - }); - T::REGS.cr1().modify(|w| { - w.set_csusp(false); - w.set_spe(true); - }); - } + self.info.regs.cfg1().modify(|w| { + w.set_dsize(word_size); + }); self.current_word_size = word_size; } - /// SPI write, using DMA. - pub async fn write(&mut self, data: &[W]) -> Result<(), Error> - where - Tx: TxDma, - { - if data.is_empty() { - return Ok(()); - } - - self.set_word_size(W::CONFIG); - T::REGS.cr1().modify(|w| { - w.set_spe(false); - }); - - let tx_request = self.txdma.request(); - let tx_dst = T::REGS.tx_ptr(); - let tx_f = unsafe { Transfer::new_write(&mut self.txdma, tx_request, data, tx_dst, Default::default()) }; - - set_txdmaen(T::REGS, true); - T::REGS.cr1().modify(|w| { - w.set_spe(true); - }); - #[cfg(any(spi_v3, spi_v4, spi_v5))] - T::REGS.cr1().modify(|w| { - w.set_cstart(true); - }); - - tx_f.await; - - finish_dma(T::REGS); - - Ok(()) - } - - /// SPI read, using DMA. - pub async fn read(&mut self, data: &mut [W]) -> Result<(), Error> - where - Tx: TxDma, - Rx: RxDma, - { - if data.is_empty() { - return Ok(()); - } - - self.set_word_size(W::CONFIG); - T::REGS.cr1().modify(|w| { - w.set_spe(false); - }); - - // SPIv3 clears rxfifo on SPE=0 - #[cfg(not(any(spi_v3, spi_v4, spi_v5)))] - flush_rx_fifo(T::REGS); - - set_rxdmaen(T::REGS, true); - - let clock_byte_count = data.len(); - - let rx_request = self.rxdma.request(); - let rx_src = T::REGS.rx_ptr(); - let rx_f = unsafe { Transfer::new_read(&mut self.rxdma, rx_request, rx_src, data, Default::default()) }; - - let tx_request = self.txdma.request(); - let tx_dst = T::REGS.tx_ptr(); - let clock_byte = 0x00u8; - let tx_f = unsafe { - Transfer::new_write_repeated( - &mut self.txdma, - tx_request, - &clock_byte, - clock_byte_count, - tx_dst, - Default::default(), - ) - }; - - set_txdmaen(T::REGS, true); - T::REGS.cr1().modify(|w| { - w.set_spe(true); - }); - #[cfg(any(spi_v3, spi_v4, spi_v5))] - T::REGS.cr1().modify(|w| { - w.set_cstart(true); - }); - - join(tx_f, rx_f).await; - - finish_dma(T::REGS); - - Ok(()) - } - - async fn transfer_inner(&mut self, read: *mut [W], write: *const [W]) -> Result<(), Error> - where - Tx: TxDma, - Rx: RxDma, - { - let (_, rx_len) = slice_ptr_parts(read); - let (_, tx_len) = slice_ptr_parts(write); - assert_eq!(rx_len, tx_len); - if rx_len == 0 { - return Ok(()); - } - - self.set_word_size(W::CONFIG); - T::REGS.cr1().modify(|w| { - w.set_spe(false); - }); - - // SPIv3 clears rxfifo on SPE=0 - #[cfg(not(any(spi_v3, spi_v4, spi_v5)))] - flush_rx_fifo(T::REGS); - - set_rxdmaen(T::REGS, true); - - let rx_request = self.rxdma.request(); - let rx_src = T::REGS.rx_ptr(); - let rx_f = unsafe { Transfer::new_read_raw(&mut self.rxdma, rx_request, rx_src, read, Default::default()) }; - - let tx_request = self.txdma.request(); - let tx_dst = T::REGS.tx_ptr(); - let tx_f = unsafe { Transfer::new_write_raw(&mut self.txdma, tx_request, write, tx_dst, Default::default()) }; - - set_txdmaen(T::REGS, true); - T::REGS.cr1().modify(|w| { - w.set_spe(true); - }); - #[cfg(any(spi_v3, spi_v4, spi_v5))] - T::REGS.cr1().modify(|w| { - w.set_cstart(true); - }); - - join(tx_f, rx_f).await; - - finish_dma(T::REGS); - - Ok(()) - } - - /// Bidirectional transfer, using DMA. - /// - /// This transfers both buffers at the same time, so it is NOT equivalent to `write` followed by `read`. - /// - /// The transfer runs for `max(read.len(), write.len())` bytes. If `read` is shorter extra bytes are ignored. - /// If `write` is shorter it is padded with zero bytes. - pub async fn transfer(&mut self, read: &mut [W], write: &[W]) -> Result<(), Error> - where - Tx: TxDma, - Rx: RxDma, - { - self.transfer_inner(read, write).await - } - - /// In-place bidirectional transfer, using DMA. - /// - /// This writes the contents of `data` on MOSI, and puts the received data on MISO in `data`, at the same time. - pub async fn transfer_in_place(&mut self, data: &mut [W]) -> Result<(), Error> - where - Tx: TxDma, - Rx: RxDma, - { - self.transfer_inner(data, data).await - } - /// Blocking write. pub fn blocking_write(&mut self, words: &[W]) -> Result<(), Error> { - T::REGS.cr1().modify(|w| w.set_spe(true)); - flush_rx_fifo(T::REGS); + // needed in v3+ to avoid overrun causing the SPI RX state machine to get stuck...? + #[cfg(any(spi_v3, spi_v4, spi_v5))] + self.info.regs.cr1().modify(|w| w.set_spe(false)); self.set_word_size(W::CONFIG); + self.info.regs.cr1().modify(|w| w.set_spe(true)); + flush_rx_fifo(self.info.regs); for word in words.iter() { - let _ = transfer_word(T::REGS, *word)?; + // this cannot use `transfer_word` because on SPIv2 and higher, + // the SPI RX state machine hangs if no physical pin is connected to the SCK AF. + // This is the case when the SPI has been created with `new_(blocking_?)txonly_nosck`. + // See https://github.com/embassy-rs/embassy/issues/2902 + // This is not documented as an errata by ST, and I've been unable to find anything online... + #[cfg(not(any(spi_v1, spi_f1)))] + write_word(self.info.regs, *word)?; + + // if we're doing tx only, after writing the last byte to FIFO we have to wait + // until it's actually sent. On SPIv1 you're supposed to use the BSY flag for this + // but apparently it's broken, it clears too soon. Workaround is to wait for RXNE: + // when it gets set you know the transfer is done, even if you don't care about rx. + // Luckily this doesn't affect SPIv2+. + // See http://efton.sk/STM32/gotcha/g68.html + // ST doesn't seem to document this in errata sheets (?) + #[cfg(any(spi_v1, spi_f1))] + transfer_word(self.info.regs, *word)?; } + + // wait until last word is transmitted. (except on v1, see above) + #[cfg(not(any(spi_v1, spi_f1, spi_v2)))] + while !self.info.regs.sr().read().txc() {} + #[cfg(spi_v2)] + while self.info.regs.sr().read().bsy() {} + Ok(()) } /// Blocking read. pub fn blocking_read(&mut self, words: &mut [W]) -> Result<(), Error> { - T::REGS.cr1().modify(|w| w.set_spe(true)); - flush_rx_fifo(T::REGS); + // needed in v3+ to avoid overrun causing the SPI RX state machine to get stuck...? + #[cfg(any(spi_v3, spi_v4, spi_v5))] + self.info.regs.cr1().modify(|w| w.set_spe(false)); self.set_word_size(W::CONFIG); + self.info.regs.cr1().modify(|w| w.set_spe(true)); + flush_rx_fifo(self.info.regs); for word in words.iter_mut() { - *word = transfer_word(T::REGS, W::default())?; + *word = transfer_word(self.info.regs, W::default())?; } Ok(()) } @@ -652,11 +392,14 @@ impl<'d, T: Instance, Tx, Rx> Spi<'d, T, Tx, Rx> { /// /// This writes the contents of `data` on MOSI, and puts the received data on MISO in `data`, at the same time. pub fn blocking_transfer_in_place(&mut self, words: &mut [W]) -> Result<(), Error> { - T::REGS.cr1().modify(|w| w.set_spe(true)); - flush_rx_fifo(T::REGS); + // needed in v3+ to avoid overrun causing the SPI RX state machine to get stuck...? + #[cfg(any(spi_v3, spi_v4, spi_v5))] + self.info.regs.cr1().modify(|w| w.set_spe(false)); self.set_word_size(W::CONFIG); + self.info.regs.cr1().modify(|w| w.set_spe(true)); + flush_rx_fifo(self.info.regs); for word in words.iter_mut() { - *word = transfer_word(T::REGS, *word)?; + *word = transfer_word(self.info.regs, *word)?; } Ok(()) } @@ -668,13 +411,16 @@ impl<'d, T: Instance, Tx, Rx> Spi<'d, T, Tx, Rx> { /// The transfer runs for `max(read.len(), write.len())` bytes. If `read` is shorter extra bytes are ignored. /// If `write` is shorter it is padded with zero bytes. pub fn blocking_transfer(&mut self, read: &mut [W], write: &[W]) -> Result<(), Error> { - T::REGS.cr1().modify(|w| w.set_spe(true)); - flush_rx_fifo(T::REGS); + // needed in v3+ to avoid overrun causing the SPI RX state machine to get stuck...? + #[cfg(any(spi_v3, spi_v4, spi_v5))] + self.info.regs.cr1().modify(|w| w.set_spe(false)); self.set_word_size(W::CONFIG); + self.info.regs.cr1().modify(|w| w.set_spe(true)); + flush_rx_fifo(self.info.regs); let len = read.len().max(write.len()); for i in 0..len { let wb = write.get(i).copied().unwrap_or_default(); - let rb = transfer_word(T::REGS, wb)?; + let rb = transfer_word(self.info.regs, wb)?; if let Some(r) = read.get_mut(i) { *r = rb; } @@ -683,13 +429,432 @@ impl<'d, T: Instance, Tx, Rx> Spi<'d, T, Tx, Rx> { } } -impl<'d, T: Instance, Tx, Rx> Drop for Spi<'d, T, Tx, Rx> { +impl<'d> Spi<'d, Blocking> { + /// Create a new blocking SPI driver. + pub fn new_blocking( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + mosi: impl Peripheral

> + 'd, + miso: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(sck, config.sck_af()), + new_pin!(mosi, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(miso, AfType::input(config.miso_pull)), + None, + None, + config, + ) + } + + /// Create a new blocking SPI driver, in RX-only mode (only MISO pin, no MOSI). + pub fn new_blocking_rxonly( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + miso: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(sck, config.sck_af()), + None, + new_pin!(miso, AfType::input(config.miso_pull)), + None, + None, + config, + ) + } + + /// Create a new blocking SPI driver, in TX-only mode (only MOSI pin, no MISO). + pub fn new_blocking_txonly( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + mosi: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(sck, config.sck_af()), + new_pin!(mosi, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + None, + None, + None, + config, + ) + } + + /// Create a new SPI driver, in TX-only mode, without SCK pin. + /// + /// This can be useful for bit-banging non-SPI protocols. + pub fn new_blocking_txonly_nosck( + peri: impl Peripheral

+ 'd, + mosi: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + None, + new_pin!(mosi, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + None, + None, + None, + config, + ) + } +} + +impl<'d> Spi<'d, Async> { + /// Create a new SPI driver. + pub fn new( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + mosi: impl Peripheral

> + 'd, + miso: impl Peripheral

> + 'd, + tx_dma: impl Peripheral

> + 'd, + rx_dma: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(sck, config.sck_af()), + new_pin!(mosi, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + new_pin!(miso, AfType::input(config.miso_pull)), + new_dma!(tx_dma), + new_dma!(rx_dma), + config, + ) + } + + /// Create a new SPI driver, in RX-only mode (only MISO pin, no MOSI). + pub fn new_rxonly( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + miso: impl Peripheral

> + 'd, + #[cfg(any(spi_v1, spi_f1, spi_v2))] tx_dma: impl Peripheral

> + 'd, + rx_dma: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(sck, config.sck_af()), + None, + new_pin!(miso, AfType::input(config.miso_pull)), + #[cfg(any(spi_v1, spi_f1, spi_v2))] + new_dma!(tx_dma), + #[cfg(any(spi_v3, spi_v4, spi_v5))] + None, + new_dma!(rx_dma), + config, + ) + } + + /// Create a new SPI driver, in TX-only mode (only MOSI pin, no MISO). + pub fn new_txonly( + peri: impl Peripheral

+ 'd, + sck: impl Peripheral

> + 'd, + mosi: impl Peripheral

> + 'd, + tx_dma: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + new_pin!(sck, config.sck_af()), + new_pin!(mosi, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + None, + new_dma!(tx_dma), + None, + config, + ) + } + + /// Create a new SPI driver, in TX-only mode, without SCK pin. + /// + /// This can be useful for bit-banging non-SPI protocols. + pub fn new_txonly_nosck( + peri: impl Peripheral

+ 'd, + mosi: impl Peripheral

> + 'd, + tx_dma: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + Self::new_inner( + peri, + None, + new_pin!(mosi, AfType::output(OutputType::PushPull, Speed::VeryHigh)), + None, + new_dma!(tx_dma), + None, + config, + ) + } + + #[cfg(stm32wl)] + /// Useful for on chip peripherals like SUBGHZ which are hardwired. + pub fn new_subghz( + peri: impl Peripheral

+ 'd, + tx_dma: impl Peripheral

> + 'd, + rx_dma: impl Peripheral

> + 'd, + ) -> Self { + // see RM0453 rev 1 section 7.2.13 page 291 + // The SUBGHZSPI_SCK frequency is obtained by PCLK3 divided by two. + // The SUBGHZSPI_SCK clock maximum speed must not exceed 16 MHz. + let pclk3_freq = ::frequency().0; + let freq = Hertz(core::cmp::min(pclk3_freq / 2, 16_000_000)); + let mut config = Config::default(); + config.mode = MODE_0; + config.bit_order = BitOrder::MsbFirst; + config.frequency = freq; + + Self::new_inner(peri, None, None, None, new_dma!(tx_dma), new_dma!(rx_dma), config) + } + + #[allow(dead_code)] + pub(crate) fn new_internal( + peri: impl Peripheral

+ 'd, + tx_dma: Option>, + rx_dma: Option>, + config: Config, + ) -> Self { + Self::new_inner(peri, None, None, None, tx_dma, rx_dma, config) + } + + /// SPI write, using DMA. + pub async fn write(&mut self, data: &[W]) -> Result<(), Error> { + if data.is_empty() { + return Ok(()); + } + + self.info.regs.cr1().modify(|w| { + w.set_spe(false); + }); + self.set_word_size(W::CONFIG); + + let tx_dst = self.info.regs.tx_ptr(); + let tx_f = unsafe { self.tx_dma.as_mut().unwrap().write(data, tx_dst, Default::default()) }; + + set_txdmaen(self.info.regs, true); + self.info.regs.cr1().modify(|w| { + w.set_spe(true); + }); + #[cfg(any(spi_v3, spi_v4, spi_v5))] + self.info.regs.cr1().modify(|w| { + w.set_cstart(true); + }); + + tx_f.await; + + finish_dma(self.info.regs); + + Ok(()) + } + + /// SPI read, using DMA. + #[cfg(any(spi_v3, spi_v4, spi_v5))] + pub async fn read(&mut self, data: &mut [W]) -> Result<(), Error> { + if data.is_empty() { + return Ok(()); + } + + let regs = self.info.regs; + + regs.cr1().modify(|w| { + w.set_spe(false); + }); + + self.set_word_size(W::CONFIG); + + let comm = regs.cfg2().modify(|w| { + let prev = w.comm(); + w.set_comm(vals::Comm::RECEIVER); + prev + }); + + #[cfg(spi_v3)] + let i2scfg = regs.i2scfgr().modify(|w| { + w.i2smod().then(|| { + let prev = w.i2scfg(); + w.set_i2scfg(match prev { + vals::I2scfg::SLAVERX | vals::I2scfg::SLAVEFULLDUPLEX => vals::I2scfg::SLAVERX, + vals::I2scfg::MASTERRX | vals::I2scfg::MASTERFULLDUPLEX => vals::I2scfg::MASTERRX, + _ => panic!("unsupported configuration"), + }); + prev + }) + }); + + let rx_src = regs.rx_ptr(); + + for mut chunk in data.chunks_mut(u16::max_value().into()) { + set_rxdmaen(regs, true); + + let tsize = chunk.len(); + + let transfer = unsafe { + self.rx_dma + .as_mut() + .unwrap() + .read(rx_src, &mut chunk, Default::default()) + }; + + regs.cr2().modify(|w| { + w.set_tsize(tsize as u16); + }); + + regs.cr1().modify(|w| { + w.set_spe(true); + }); + + regs.cr1().modify(|w| { + w.set_cstart(true); + }); + + transfer.await; + + finish_dma(regs); + } + + regs.cr1().modify(|w| { + w.set_spe(false); + }); + + regs.cfg2().modify(|w| { + w.set_comm(comm); + }); + + regs.cr2().modify(|w| { + w.set_tsize(0); + }); + + #[cfg(spi_v3)] + if let Some(i2scfg) = i2scfg { + regs.i2scfgr().modify(|w| { + w.set_i2scfg(i2scfg); + }); + } + + Ok(()) + } + + /// SPI read, using DMA. + #[cfg(any(spi_v1, spi_f1, spi_v2))] + pub async fn read(&mut self, data: &mut [W]) -> Result<(), Error> { + if data.is_empty() { + return Ok(()); + } + + self.info.regs.cr1().modify(|w| { + w.set_spe(false); + }); + + self.set_word_size(W::CONFIG); + + // SPIv3 clears rxfifo on SPE=0 + #[cfg(not(any(spi_v3, spi_v4, spi_v5)))] + flush_rx_fifo(self.info.regs); + + set_rxdmaen(self.info.regs, true); + + let clock_byte_count = data.len(); + + let rx_src = self.info.regs.rx_ptr(); + let rx_f = unsafe { self.rx_dma.as_mut().unwrap().read(rx_src, data, Default::default()) }; + + let tx_dst = self.info.regs.tx_ptr(); + let clock_byte = W::default(); + let tx_f = unsafe { + self.tx_dma + .as_mut() + .unwrap() + .write_repeated(&clock_byte, clock_byte_count, tx_dst, Default::default()) + }; + + set_txdmaen(self.info.regs, true); + self.info.regs.cr1().modify(|w| { + w.set_spe(true); + }); + #[cfg(any(spi_v3, spi_v4, spi_v5))] + self.info.regs.cr1().modify(|w| { + w.set_cstart(true); + }); + + join(tx_f, rx_f).await; + + finish_dma(self.info.regs); + + Ok(()) + } + + async fn transfer_inner(&mut self, read: *mut [W], write: *const [W]) -> Result<(), Error> { + assert_eq!(read.len(), write.len()); + if read.len() == 0 { + return Ok(()); + } + + self.info.regs.cr1().modify(|w| { + w.set_spe(false); + }); + + self.set_word_size(W::CONFIG); + + // SPIv3 clears rxfifo on SPE=0 + #[cfg(not(any(spi_v3, spi_v4, spi_v5)))] + flush_rx_fifo(self.info.regs); + + set_rxdmaen(self.info.regs, true); + + let rx_src = self.info.regs.rx_ptr(); + let rx_f = unsafe { self.rx_dma.as_mut().unwrap().read_raw(rx_src, read, Default::default()) }; + + let tx_dst = self.info.regs.tx_ptr(); + let tx_f = unsafe { + self.tx_dma + .as_mut() + .unwrap() + .write_raw(write, tx_dst, Default::default()) + }; + + set_txdmaen(self.info.regs, true); + self.info.regs.cr1().modify(|w| { + w.set_spe(true); + }); + #[cfg(any(spi_v3, spi_v4, spi_v5))] + self.info.regs.cr1().modify(|w| { + w.set_cstart(true); + }); + + join(tx_f, rx_f).await; + + finish_dma(self.info.regs); + + Ok(()) + } + + /// Bidirectional transfer, using DMA. + /// + /// This transfers both buffers at the same time, so it is NOT equivalent to `write` followed by `read`. + /// + /// The transfer runs for `max(read.len(), write.len())` bytes. If `read` is shorter extra bytes are ignored. + /// If `write` is shorter it is padded with zero bytes. + pub async fn transfer(&mut self, read: &mut [W], write: &[W]) -> Result<(), Error> { + self.transfer_inner(read, write).await + } + + /// In-place bidirectional transfer, using DMA. + /// + /// This writes the contents of `data` on MOSI, and puts the received data on MISO in `data`, at the same time. + pub async fn transfer_in_place(&mut self, data: &mut [W]) -> Result<(), Error> { + self.transfer_inner(data, data).await + } +} + +impl<'d, M: PeriMode> Drop for Spi<'d, M> { fn drop(&mut self) { self.sck.as_ref().map(|x| x.set_as_disconnected()); self.mosi.as_ref().map(|x| x.set_as_disconnected()); self.miso.as_ref().map(|x| x.set_as_disconnected()); - T::disable(); + self.info.rcc.disable(); } } @@ -698,9 +863,9 @@ use vals::Br; #[cfg(any(spi_v3, spi_v4, spi_v5))] use vals::Mbr as Br; -fn compute_baud_rate(clocks: Hertz, freq: Hertz) -> Br { - let val = match clocks.0 / freq.0 { - 0 => unreachable!(), +fn compute_baud_rate(kernel_clock: Hertz, freq: Hertz) -> Br { + let val = match kernel_clock.0 / freq.0 { + 0 => panic!("You are trying to reach a frequency higher than the clock"), 1..=2 => 0b000, 3..=5 => 0b001, 6..=11 => 0b010, @@ -714,7 +879,7 @@ fn compute_baud_rate(clocks: Hertz, freq: Hertz) -> Br { Br::from_bits(val) } -fn compute_frequency(clocks: Hertz, br: Br) -> Hertz { +fn compute_frequency(kernel_clock: Hertz, br: Br) -> Hertz { let div: u16 = match br { Br::DIV2 => 2, Br::DIV4 => 4, @@ -726,34 +891,38 @@ fn compute_frequency(clocks: Hertz, br: Br) -> Hertz { Br::DIV256 => 256, }; - clocks / div + kernel_clock / div } -trait RegsExt { +pub(crate) trait RegsExt { fn tx_ptr(&self) -> *mut W; fn rx_ptr(&self) -> *mut W; } impl RegsExt for Regs { fn tx_ptr(&self) -> *mut W { - #[cfg(not(any(spi_v3, spi_v4, spi_v5)))] + #[cfg(any(spi_v1, spi_f1))] let dr = self.dr(); + #[cfg(spi_v2)] + let dr = self.dr16(); #[cfg(any(spi_v3, spi_v4, spi_v5))] - let dr = self.txdr(); + let dr = self.txdr32(); dr.as_ptr() as *mut W } fn rx_ptr(&self) -> *mut W { - #[cfg(not(any(spi_v3, spi_v4, spi_v5)))] + #[cfg(any(spi_v1, spi_f1))] let dr = self.dr(); + #[cfg(spi_v2)] + let dr = self.dr16(); #[cfg(any(spi_v3, spi_v4, spi_v5))] - let dr = self.rxdr(); + let dr = self.rxdr32(); dr.as_ptr() as *mut W } } -fn check_error_flags(sr: regs::Sr) -> Result<(), Error> { - if sr.ovr() { +fn check_error_flags(sr: regs::Sr, ovr: bool) -> Result<(), Error> { + if sr.ovr() && ovr { return Err(Error::Overrun); } #[cfg(not(any(spi_f1, spi_v3, spi_v4, spi_v5)))] @@ -779,11 +948,11 @@ fn check_error_flags(sr: regs::Sr) -> Result<(), Error> { Ok(()) } -fn spin_until_tx_ready(regs: Regs) -> Result<(), Error> { +fn spin_until_tx_ready(regs: Regs, ovr: bool) -> Result<(), Error> { loop { let sr = regs.sr().read(); - check_error_flags(sr)?; + check_error_flags(sr, ovr)?; #[cfg(not(any(spi_v3, spi_v4, spi_v5)))] if sr.txe() { @@ -800,7 +969,7 @@ fn spin_until_rx_ready(regs: Regs) -> Result<(), Error> { loop { let sr = regs.sr().read(); - check_error_flags(sr)?; + check_error_flags(sr, true)?; #[cfg(not(any(spi_v3, spi_v4, spi_v5)))] if sr.rxne() { @@ -813,18 +982,21 @@ fn spin_until_rx_ready(regs: Regs) -> Result<(), Error> { } } -fn flush_rx_fifo(regs: Regs) { +pub(crate) fn flush_rx_fifo(regs: Regs) { #[cfg(not(any(spi_v3, spi_v4, spi_v5)))] while regs.sr().read().rxne() { + #[cfg(not(spi_v2))] let _ = regs.dr().read(); + #[cfg(spi_v2)] + let _ = regs.dr16().read(); } #[cfg(any(spi_v3, spi_v4, spi_v5))] while regs.sr().read().rxp() { - let _ = regs.rxdr().read(); + let _ = regs.rxdr32().read(); } } -fn set_txdmaen(regs: Regs, val: bool) { +pub(crate) fn set_txdmaen(regs: Regs, val: bool) { #[cfg(not(any(spi_v3, spi_v4, spi_v5)))] regs.cr2().modify(|reg| { reg.set_txdmaen(val); @@ -835,7 +1007,7 @@ fn set_txdmaen(regs: Regs, val: bool) { }); } -fn set_rxdmaen(regs: Regs, val: bool) { +pub(crate) fn set_rxdmaen(regs: Regs, val: bool) { #[cfg(not(any(spi_v3, spi_v4, spi_v5)))] regs.cr2().modify(|reg| { reg.set_rxdmaen(val); @@ -851,7 +1023,13 @@ fn finish_dma(regs: Regs) { while regs.sr().read().ftlvl().to_bits() > 0 {} #[cfg(any(spi_v3, spi_v4, spi_v5))] - while !regs.sr().read().txc() {} + { + if regs.cr2().read().tsize() == 0 { + while !regs.sr().read().txc() {} + } else { + while !regs.sr().read().eot() {} + } + } #[cfg(not(any(spi_v3, spi_v4, spi_v5)))] while regs.sr().read().bsy() {} @@ -875,7 +1053,7 @@ fn finish_dma(regs: Regs) { } fn transfer_word(regs: Regs, tx_word: W) -> Result { - spin_until_tx_ready(regs)?; + spin_until_tx_ready(regs, true)?; unsafe { ptr::write_volatile(regs.tx_ptr(), tx_word); @@ -890,11 +1068,26 @@ fn transfer_word(regs: Regs, tx_word: W) -> Result { Ok(rx_word) } +#[allow(unused)] // unused in SPIv1 +fn write_word(regs: Regs, tx_word: W) -> Result<(), Error> { + // for write, we intentionally ignore the rx fifo, which will cause + // overrun errors that we have to ignore. + spin_until_tx_ready(regs, false)?; + + unsafe { + ptr::write_volatile(regs.tx_ptr(), tx_word); + + #[cfg(any(spi_v3, spi_v4, spi_v5))] + regs.cr1().modify(|reg| reg.set_cstart(true)); + } + Ok(()) +} + // Note: It is not possible to impl these traits generically in embedded-hal 0.2 due to a conflict with // some marker traits. For details, see https://github.com/rust-embedded/embedded-hal/pull/289 macro_rules! impl_blocking { ($w:ident) => { - impl<'d, T: Instance, Tx, Rx> embedded_hal_02::blocking::spi::Write<$w> for Spi<'d, T, Tx, Rx> { + impl<'d, M: PeriMode> embedded_hal_02::blocking::spi::Write<$w> for Spi<'d, M> { type Error = Error; fn write(&mut self, words: &[$w]) -> Result<(), Self::Error> { @@ -902,7 +1095,7 @@ macro_rules! impl_blocking { } } - impl<'d, T: Instance, Tx, Rx> embedded_hal_02::blocking::spi::Transfer<$w> for Spi<'d, T, Tx, Rx> { + impl<'d, M: PeriMode> embedded_hal_02::blocking::spi::Transfer<$w> for Spi<'d, M> { type Error = Error; fn transfer<'w>(&mut self, words: &'w mut [$w]) -> Result<&'w [$w], Self::Error> { @@ -916,11 +1109,11 @@ macro_rules! impl_blocking { impl_blocking!(u8); impl_blocking!(u16); -impl<'d, T: Instance, Tx, Rx> embedded_hal_1::spi::ErrorType for Spi<'d, T, Tx, Rx> { +impl<'d, M: PeriMode> embedded_hal_1::spi::ErrorType for Spi<'d, M> { type Error = Error; } -impl<'d, T: Instance, W: Word, Tx, Rx> embedded_hal_1::spi::SpiBus for Spi<'d, T, Tx, Rx> { +impl<'d, W: Word, M: PeriMode> embedded_hal_1::spi::SpiBus for Spi<'d, M> { fn flush(&mut self) -> Result<(), Self::Error> { Ok(()) } @@ -953,7 +1146,7 @@ impl embedded_hal_1::spi::Error for Error { } } -impl<'d, T: Instance, Tx: TxDma, Rx: RxDma, W: Word> embedded_hal_async::spi::SpiBus for Spi<'d, T, Tx, Rx> { +impl<'d, W: Word> embedded_hal_async::spi::SpiBus for Spi<'d, Async> { async fn flush(&mut self) -> Result<(), Self::Error> { Ok(()) } @@ -975,24 +1168,17 @@ impl<'d, T: Instance, Tx: TxDma, Rx: RxDma, W: Word> embedded_hal_async::s } } -pub(crate) mod sealed { - use super::*; - - pub trait Instance { - const REGS: Regs; - } - - pub trait Word { - const CONFIG: word_impl::Config; - } +pub(crate) trait SealedWord { + const CONFIG: word_impl::Config; } /// Word sizes usable for SPI. -pub trait Word: word::Word + sealed::Word {} +#[allow(private_bounds)] +pub trait Word: word::Word + SealedWord + Default {} macro_rules! impl_word { ($T:ty, $config:expr) => { - impl sealed::Word for $T { + impl SealedWord for $T { const CONFIG: Config = $config; } impl Word for $T {} @@ -1005,8 +1191,8 @@ mod word_impl { pub type Config = vals::Dff; - impl_word!(u8, vals::Dff::EIGHTBIT); - impl_word!(u16, vals::Dff::SIXTEENBIT); + impl_word!(u8, vals::Dff::BITS8); + impl_word!(u16, vals::Dff::BITS16); } #[cfg(spi_v2)] @@ -1015,19 +1201,19 @@ mod word_impl { pub type Config = (vals::Ds, vals::Frxth); - impl_word!(word::U4, (vals::Ds::FOURBIT, vals::Frxth::QUARTER)); - impl_word!(word::U5, (vals::Ds::FIVEBIT, vals::Frxth::QUARTER)); - impl_word!(word::U6, (vals::Ds::SIXBIT, vals::Frxth::QUARTER)); - impl_word!(word::U7, (vals::Ds::SEVENBIT, vals::Frxth::QUARTER)); - impl_word!(u8, (vals::Ds::EIGHTBIT, vals::Frxth::QUARTER)); - impl_word!(word::U9, (vals::Ds::NINEBIT, vals::Frxth::HALF)); - impl_word!(word::U10, (vals::Ds::TENBIT, vals::Frxth::HALF)); - impl_word!(word::U11, (vals::Ds::ELEVENBIT, vals::Frxth::HALF)); - impl_word!(word::U12, (vals::Ds::TWELVEBIT, vals::Frxth::HALF)); - impl_word!(word::U13, (vals::Ds::THIRTEENBIT, vals::Frxth::HALF)); - impl_word!(word::U14, (vals::Ds::FOURTEENBIT, vals::Frxth::HALF)); - impl_word!(word::U15, (vals::Ds::FIFTEENBIT, vals::Frxth::HALF)); - impl_word!(u16, (vals::Ds::SIXTEENBIT, vals::Frxth::HALF)); + impl_word!(word::U4, (vals::Ds::BITS4, vals::Frxth::QUARTER)); + impl_word!(word::U5, (vals::Ds::BITS5, vals::Frxth::QUARTER)); + impl_word!(word::U6, (vals::Ds::BITS6, vals::Frxth::QUARTER)); + impl_word!(word::U7, (vals::Ds::BITS7, vals::Frxth::QUARTER)); + impl_word!(u8, (vals::Ds::BITS8, vals::Frxth::QUARTER)); + impl_word!(word::U9, (vals::Ds::BITS9, vals::Frxth::HALF)); + impl_word!(word::U10, (vals::Ds::BITS10, vals::Frxth::HALF)); + impl_word!(word::U11, (vals::Ds::BITS11, vals::Frxth::HALF)); + impl_word!(word::U12, (vals::Ds::BITS12, vals::Frxth::HALF)); + impl_word!(word::U13, (vals::Ds::BITS13, vals::Frxth::HALF)); + impl_word!(word::U14, (vals::Ds::BITS14, vals::Frxth::HALF)); + impl_word!(word::U15, (vals::Ds::BITS15, vals::Frxth::HALF)); + impl_word!(u16, (vals::Ds::BITS16, vals::Frxth::HALF)); } #[cfg(any(spi_v3, spi_v4, spi_v5))] @@ -1067,8 +1253,21 @@ mod word_impl { impl_word!(u32, 32 - 1); } -/// SPI instance trait. -pub trait Instance: Peripheral

+ sealed::Instance + RccPeripheral {} +pub(crate) struct Info { + pub(crate) regs: Regs, + pub(crate) rcc: RccInfo, +} + +struct State {} + +impl State { + #[allow(unused)] + const fn new() -> Self { + Self {} + } +} + +peri_trait!(); pin_trait!(SckPin, Instance); pin_trait!(MosiPin, Instance); @@ -1082,15 +1281,14 @@ dma_trait!(TxDma, Instance); foreach_peripheral!( (spi, $inst:ident) => { - impl sealed::Instance for peripherals::$inst { - const REGS: Regs = crate::pac::$inst; - } - - impl Instance for peripherals::$inst {} + peri_trait_impl!($inst, Info { + regs: crate::pac::$inst, + rcc: crate::peripherals::$inst::RCC_INFO, + }); }; ); -impl<'d, T: Instance, Tx, Rx> SetConfig for Spi<'d, T, Tx, Rx> { +impl<'d, M: PeriMode> SetConfig for Spi<'d, M> { type Config = Config; type ConfigError = (); fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> { diff --git a/embassy-stm32/src/time.rs b/embassy-stm32/src/time.rs index 17690aefc..802ff41ce 100644 --- a/embassy-stm32/src/time.rs +++ b/embassy-stm32/src/time.rs @@ -87,3 +87,39 @@ impl Div for Hertz { self.0 / rhs.0 } } + +#[repr(C)] +#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug, Default)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +/// A variant on [Hertz] that acts as an `Option` that is smaller and repr C. +/// +/// An `Option` can be `.into()`'d into this type and back. +/// The only restriction is that that [Hertz] cannot have the value 0 since that's +/// seen as the `None` variant. +pub struct MaybeHertz(u32); + +impl MaybeHertz { + /// Same as calling the `.into()` function, but without type inference. + pub fn to_hertz(self) -> Option { + self.into() + } +} + +impl From> for MaybeHertz { + fn from(value: Option) -> Self { + match value { + Some(Hertz(0)) => panic!("Hertz cannot be 0"), + Some(Hertz(val)) => Self(val), + None => Self(0), + } + } +} + +impl From for Option { + fn from(value: MaybeHertz) -> Self { + match value { + MaybeHertz(0) => None, + MaybeHertz(val) => Some(Hertz(val)), + } + } +} diff --git a/embassy-stm32/src/time_driver.rs b/embassy-stm32/src/time_driver.rs index 320b29ddb..f8041bf1e 100644 --- a/embassy-stm32/src/time_driver.rs +++ b/embassy-stm32/src/time_driver.rs @@ -1,5 +1,6 @@ +#![allow(non_snake_case)] + use core::cell::Cell; -use core::convert::TryInto; use core::sync::atomic::{compiler_fence, AtomicU32, AtomicU8, Ordering}; use core::{mem, ptr}; @@ -7,14 +8,14 @@ use critical_section::CriticalSection; use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; use embassy_sync::blocking_mutex::Mutex; use embassy_time_driver::{AlarmHandle, Driver, TICK_HZ}; -use stm32_metapac::timer::regs; +use stm32_metapac::timer::{regs, TimGp16}; use crate::interrupt::typelevel::Interrupt; use crate::pac::timer::vals; -use crate::rcc::sealed::RccPeripheral; +use crate::rcc::{self, SealedRccPeripheral}; #[cfg(feature = "low-power")] use crate::rtc::Rtc; -use crate::timer::sealed::{Basic16bitInstance as BasicInstance, GeneralPurpose16bitInstance as Instance}; +use crate::timer::{CoreInstance, GeneralInstance1Channel}; use crate::{interrupt, peripherals}; // NOTE regarding ALARM_COUNT: @@ -22,18 +23,22 @@ use crate::{interrupt, peripherals}; // As of 2023-12-04, this driver is implemented using CC1 as the halfway rollover interrupt, and any // additional CC capabilities to provide timer alarms to embassy-time. embassy-time requires AT LEAST // one alarm to be allocatable, which means timers that only have CC1, such as TIM16/TIM17, are not -// candidates for use as an embassy-time driver provider. +// candidates for use as an embassy-time driver provider. (a.k.a 1CH and 1CH_CMP are not, others are good.) // // The values of ALARM_COUNT below are not the TOTAL CC registers available, but rather the number // available after reserving CC1 for regular time keeping. For example, TIM2 has four CC registers: // CC1, CC2, CC3, and CC4, so it can provide ALARM_COUNT = 3. -#[cfg(not(any(time_driver_tim12, time_driver_tim15, time_driver_tim21, time_driver_tim22)))] -const ALARM_COUNT: usize = 3; - -#[cfg(any(time_driver_tim12, time_driver_tim15, time_driver_tim21, time_driver_tim22))] -const ALARM_COUNT: usize = 1; +cfg_if::cfg_if! { + if #[cfg(any(time_driver_tim9, time_driver_tim12, time_driver_tim15, time_driver_tim21, time_driver_tim22))] { + const ALARM_COUNT: usize = 1; + } else { + const ALARM_COUNT: usize = 3; + } +} +#[cfg(time_driver_tim1)] +type T = peripherals::TIM1; #[cfg(time_driver_tim2)] type T = peripherals::TIM2; #[cfg(time_driver_tim3)] @@ -42,21 +47,43 @@ type T = peripherals::TIM3; type T = peripherals::TIM4; #[cfg(time_driver_tim5)] type T = peripherals::TIM5; +#[cfg(time_driver_tim8)] +type T = peripherals::TIM8; #[cfg(time_driver_tim9)] type T = peripherals::TIM9; -#[cfg(time_driver_tim11)] -type T = peripherals::TIM11; #[cfg(time_driver_tim12)] type T = peripherals::TIM12; #[cfg(time_driver_tim15)] type T = peripherals::TIM15; +#[cfg(time_driver_tim20)] +type T = peripherals::TIM20; #[cfg(time_driver_tim21)] type T = peripherals::TIM21; #[cfg(time_driver_tim22)] type T = peripherals::TIM22; +#[cfg(time_driver_tim23)] +type T = peripherals::TIM23; +#[cfg(time_driver_tim24)] +type T = peripherals::TIM24; foreach_interrupt! { - (TIM2, timer, $block:ident, UP, $irq:ident) => { + (TIM1, timer, $block:ident, CC, $irq:ident) => { + #[cfg(time_driver_tim1)] + #[cfg(feature = "rt")] + #[interrupt] + fn $irq() { + DRIVER.on_interrupt() + } + }; + (TIM1, timer, $block:ident, CC, $irq:ident) => { + #[cfg(time_driver_tim1)] + #[cfg(feature = "rt")] + #[interrupt] + fn $irq() { + DRIVER.on_interrupt() + } + }; + (TIM2, timer, $block:ident, CC, $irq:ident) => { #[cfg(time_driver_tim2)] #[cfg(feature = "rt")] #[interrupt] @@ -64,7 +91,7 @@ foreach_interrupt! { DRIVER.on_interrupt() } }; - (TIM3, timer, $block:ident, UP, $irq:ident) => { + (TIM3, timer, $block:ident, CC, $irq:ident) => { #[cfg(time_driver_tim3)] #[cfg(feature = "rt")] #[interrupt] @@ -72,7 +99,7 @@ foreach_interrupt! { DRIVER.on_interrupt() } }; - (TIM4, timer, $block:ident, UP, $irq:ident) => { + (TIM4, timer, $block:ident, CC, $irq:ident) => { #[cfg(time_driver_tim4)] #[cfg(feature = "rt")] #[interrupt] @@ -80,7 +107,7 @@ foreach_interrupt! { DRIVER.on_interrupt() } }; - (TIM5, timer, $block:ident, UP, $irq:ident) => { + (TIM5, timer, $block:ident, CC, $irq:ident) => { #[cfg(time_driver_tim5)] #[cfg(feature = "rt")] #[interrupt] @@ -88,7 +115,23 @@ foreach_interrupt! { DRIVER.on_interrupt() } }; - (TIM9, timer, $block:ident, UP, $irq:ident) => { + (TIM8, timer, $block:ident, CC, $irq:ident) => { + #[cfg(time_driver_tim8)] + #[cfg(feature = "rt")] + #[interrupt] + fn $irq() { + DRIVER.on_interrupt() + } + }; + (TIM8, timer, $block:ident, CC, $irq:ident) => { + #[cfg(time_driver_tim8)] + #[cfg(feature = "rt")] + #[interrupt] + fn $irq() { + DRIVER.on_interrupt() + } + }; + (TIM9, timer, $block:ident, CC, $irq:ident) => { #[cfg(time_driver_tim9)] #[cfg(feature = "rt")] #[interrupt] @@ -96,15 +139,7 @@ foreach_interrupt! { DRIVER.on_interrupt() } }; - (TIM11, timer, $block:ident, UP, $irq:ident) => { - #[cfg(time_driver_tim11)] - #[cfg(feature = "rt")] - #[interrupt] - fn $irq() { - DRIVER.on_interrupt() - } - }; - (TIM12, timer, $block:ident, UP, $irq:ident) => { + (TIM12, timer, $block:ident, CC, $irq:ident) => { #[cfg(time_driver_tim12)] #[cfg(feature = "rt")] #[interrupt] @@ -112,7 +147,7 @@ foreach_interrupt! { DRIVER.on_interrupt() } }; - (TIM15, timer, $block:ident, UP, $irq:ident) => { + (TIM15, timer, $block:ident, CC, $irq:ident) => { #[cfg(time_driver_tim15)] #[cfg(feature = "rt")] #[interrupt] @@ -120,7 +155,23 @@ foreach_interrupt! { DRIVER.on_interrupt() } }; - (TIM21, timer, $block:ident, UP, $irq:ident) => { + (TIM20, timer, $block:ident, CC, $irq:ident) => { + #[cfg(time_driver_tim20)] + #[cfg(feature = "rt")] + #[interrupt] + fn $irq() { + DRIVER.on_interrupt() + } + }; + (TIM20, timer, $block:ident, CC, $irq:ident) => { + #[cfg(time_driver_tim20)] + #[cfg(feature = "rt")] + #[interrupt] + fn $irq() { + DRIVER.on_interrupt() + } + }; + (TIM21, timer, $block:ident, CC, $irq:ident) => { #[cfg(time_driver_tim21)] #[cfg(feature = "rt")] #[interrupt] @@ -128,7 +179,7 @@ foreach_interrupt! { DRIVER.on_interrupt() } }; - (TIM22, timer, $block:ident, UP, $irq:ident) => { + (TIM22, timer, $block:ident, CC, $irq:ident) => { #[cfg(time_driver_tim22)] #[cfg(feature = "rt")] #[interrupt] @@ -136,6 +187,26 @@ foreach_interrupt! { DRIVER.on_interrupt() } }; + (TIM23, timer, $block:ident, CC, $irq:ident) => { + #[cfg(time_driver_tim23)] + #[cfg(feature = "rt")] + #[interrupt] + fn $irq() { + DRIVER.on_interrupt() + } + }; + (TIM24, timer, $block:ident, CC, $irq:ident) => { + #[cfg(time_driver_tim24)] + #[cfg(feature = "rt")] + #[interrupt] + fn $irq() { + DRIVER.on_interrupt() + } + }; +} + +fn regs_gp16() -> TimGp16 { + unsafe { TimGp16::from_ptr(T::regs()) } } // Clock timekeeping works with something we call "periods", which are time intervals @@ -190,6 +261,7 @@ pub(crate) struct RtcDriver { rtc: Mutex>>, } +#[allow(clippy::declare_interior_mutable_const)] const ALARM_STATE_NEW: AlarmState = AlarmState::new(); embassy_time_driver::time_driver_impl!(static DRIVER: RtcDriver = RtcDriver { @@ -202,9 +274,9 @@ embassy_time_driver::time_driver_impl!(static DRIVER: RtcDriver = RtcDriver { impl RtcDriver { fn init(&'static self, cs: critical_section::CriticalSection) { - let r = T::regs_gp16(); + let r = regs_gp16(); - ::enable_and_reset_with_cs(cs); + rcc::enable_and_reset_with_cs::(cs); let timer_freq = T::frequency(); @@ -217,7 +289,7 @@ impl RtcDriver { Ok(n) => n, }; - r.psc().write(|w| w.set_psc(psc)); + r.psc().write_value(psc); r.arr().write(|w| w.set_arr(u16::MAX)); // Set URS, generate update and clear URS @@ -234,14 +306,14 @@ impl RtcDriver { w.set_ccie(0, true); }); - ::Interrupt::unpend(); - unsafe { ::Interrupt::enable() }; + ::CaptureCompareInterrupt::unpend(); + unsafe { ::CaptureCompareInterrupt::enable() }; r.cr1().modify(|w| w.set_cen(true)); } fn on_interrupt(&self) { - let r = T::regs_gp16(); + let r = regs_gp16(); // XXX: reduce the size of this critical section ? critical_section::with(|cs| { @@ -251,7 +323,7 @@ impl RtcDriver { // Clear all interrupt flags. Bits in SR are "write 0 to clear", so write the bitwise NOT. // Other approaches such as writing all zeros, or RMWing won't work, they can // miss interrupts. - r.sr().write_value(regs::SrGp(!sr.0)); + r.sr().write_value(regs::SrGp16(!sr.0)); // Overflow if sr.uif() { @@ -272,7 +344,7 @@ impl RtcDriver { } fn next_period(&self) { - let r = T::regs_gp16(); + let r = regs_gp16(); // We only modify the period from the timer interrupt, so we know this can't race. let period = self.period.load(Ordering::Relaxed) + 1; @@ -336,7 +408,7 @@ impl RtcDriver { /// Add the given offset to the current time fn add_time(&self, offset: embassy_time::Duration, cs: CriticalSection) { let offset = offset.as_ticks(); - let cnt = T::regs_gp16().cnt().read().cnt() as u32; + let cnt = regs_gp16().cnt().read().cnt() as u32; let period = self.period.load(Ordering::SeqCst); // Correct the race, if it exists @@ -362,7 +434,7 @@ impl RtcDriver { let period = if cnt > u16::MAX as u32 / 2 { period + 1 } else { period }; self.period.store(period, Ordering::SeqCst); - T::regs_gp16().cnt().write(|w| w.set_cnt(cnt as u16)); + regs_gp16().cnt().write(|w| w.set_cnt(cnt as u16)); // Now, recompute all alarms for i in 0..ALARM_COUNT { @@ -419,7 +491,7 @@ impl RtcDriver { .unwrap() .start_wakeup_alarm(time_until_next_alarm, cs); - T::regs_gp16().cr1().modify(|w| w.set_cen(false)); + regs_gp16().cr1().modify(|w| w.set_cen(false)); Ok(()) } @@ -429,7 +501,7 @@ impl RtcDriver { #[cfg(feature = "low-power")] /// Resume the timer with the given offset pub(crate) fn resume_time(&self) { - if T::regs_gp16().cr1().read().cen() { + if regs_gp16().cr1().read().cen() { // Time isn't currently stopped return; @@ -438,14 +510,14 @@ impl RtcDriver { critical_section::with(|cs| { self.stop_wakeup_alarm(cs); - T::regs_gp16().cr1().modify(|w| w.set_cen(true)); + regs_gp16().cr1().modify(|w| w.set_cen(true)); }) } } impl Driver for RtcDriver { fn now(&self) -> u64 { - let r = T::regs_gp16(); + let r = regs_gp16(); let period = self.period.load(Ordering::Relaxed); compiler_fence(Ordering::Acquire); @@ -476,7 +548,7 @@ impl Driver for RtcDriver { fn set_alarm(&self, alarm: AlarmHandle, timestamp: u64) -> bool { critical_section::with(|cs| { - let r = T::regs_gp16(); + let r = regs_gp16(); let n = alarm.id() as usize; let alarm = self.get_alarm(cs, alarm); diff --git a/embassy-stm32/src/timer/complementary_pwm.rs b/embassy-stm32/src/timer/complementary_pwm.rs index eddce0404..46ccbf3df 100644 --- a/embassy-stm32/src/timer/complementary_pwm.rs +++ b/embassy-stm32/src/timer/complementary_pwm.rs @@ -5,12 +5,15 @@ use core::marker::PhantomData; use embassy_hal_internal::{into_ref, PeripheralRef}; use stm32_metapac::timer::vals::Ckd; -use super::simple_pwm::*; -use super::*; -#[allow(unused_imports)] -use crate::gpio::sealed::{AFType, Pin}; +use super::low_level::{CountingMode, OutputPolarity, Timer}; +use super::simple_pwm::{Ch1, Ch2, Ch3, Ch4, PwmPin}; +use super::{ + AdvancedInstance4Channel, Channel, Channel1ComplementaryPin, Channel2ComplementaryPin, Channel3ComplementaryPin, + Channel4ComplementaryPin, +}; use crate::gpio::{AnyPin, OutputType}; use crate::time::Hertz; +use crate::timer::low_level::OutputCompareMode; use crate::Peripheral; /// Complementary PWM pin wrapper. @@ -23,15 +26,16 @@ pub struct ComplementaryPwmPin<'d, T, C> { macro_rules! complementary_channel_impl { ($new_chx:ident, $channel:ident, $pin_trait:ident) => { - impl<'d, T: CaptureCompare16bitInstance> ComplementaryPwmPin<'d, T, $channel> { + impl<'d, T: AdvancedInstance4Channel> ComplementaryPwmPin<'d, T, $channel> { #[doc = concat!("Create a new ", stringify!($channel), " complementary PWM pin instance.")] pub fn $new_chx(pin: impl Peripheral

> + 'd, output_type: OutputType) -> Self { into_ref!(pin); critical_section::with(|_| { pin.set_low(); - pin.set_as_af(pin.af_num(), output_type.into()); - #[cfg(gpio_v2)] - pin.set_speed(crate::gpio::Speed::VeryHigh); + pin.set_as_af( + pin.af_num(), + crate::gpio::AfType::output(output_type, crate::gpio::Speed::VeryHigh), + ); }); ComplementaryPwmPin { _pin: pin.map_into(), @@ -48,11 +52,11 @@ complementary_channel_impl!(new_ch3, Ch3, Channel3ComplementaryPin); complementary_channel_impl!(new_ch4, Ch4, Channel4ComplementaryPin); /// PWM driver with support for standard and complementary outputs. -pub struct ComplementaryPwm<'d, T> { - inner: PeripheralRef<'d, T>, +pub struct ComplementaryPwm<'d, T: AdvancedInstance4Channel> { + inner: Timer<'d, T>, } -impl<'d, T: ComplementaryCaptureCompare16bitInstance> ComplementaryPwm<'d, T> { +impl<'d, T: AdvancedInstance4Channel> ComplementaryPwm<'d, T> { /// Create a new complementary PWM driver. #[allow(clippy::too_many_arguments)] pub fn new( @@ -72,11 +76,7 @@ impl<'d, T: ComplementaryCaptureCompare16bitInstance> ComplementaryPwm<'d, T> { } fn new_inner(tim: impl Peripheral

+ 'd, freq: Hertz, counting_mode: CountingMode) -> Self { - into_ref!(tim); - - T::enable_and_reset(); - - let mut this = Self { inner: tim }; + let mut this = Self { inner: Timer::new(tim) }; this.inner.set_counting_mode(counting_mode); this.set_frequency(freq); @@ -84,14 +84,13 @@ impl<'d, T: ComplementaryCaptureCompare16bitInstance> ComplementaryPwm<'d, T> { this.inner.enable_outputs(); - this.inner - .set_output_compare_mode(Channel::Ch1, OutputCompareMode::PwmMode1); - this.inner - .set_output_compare_mode(Channel::Ch2, OutputCompareMode::PwmMode1); - this.inner - .set_output_compare_mode(Channel::Ch3, OutputCompareMode::PwmMode1); - this.inner - .set_output_compare_mode(Channel::Ch4, OutputCompareMode::PwmMode1); + [Channel::Ch1, Channel::Ch2, Channel::Ch3, Channel::Ch4] + .iter() + .for_each(|&channel| { + this.inner.set_output_compare_mode(channel, OutputCompareMode::PwmMode1); + this.inner.set_output_compare_preload(channel, true); + }); + this } @@ -124,7 +123,7 @@ impl<'d, T: ComplementaryCaptureCompare16bitInstance> ComplementaryPwm<'d, T> { /// /// This value depends on the configured frequency and the timer's clock rate from RCC. pub fn get_max_duty(&self) -> u16 { - self.inner.get_max_compare_value() + 1 + self.inner.get_max_compare_value() as u16 + 1 } /// Set the duty for a given channel. @@ -132,7 +131,7 @@ impl<'d, T: ComplementaryCaptureCompare16bitInstance> ComplementaryPwm<'d, T> { /// The value ranges from 0 for 0% duty, to [`get_max_duty`](Self::get_max_duty) for 100% duty, both included. pub fn set_duty(&mut self, channel: Channel, duty: u16) { assert!(duty <= self.get_max_duty()); - self.inner.set_compare_value(channel, duty) + self.inner.set_compare_value(channel, duty as _) } /// Set the output polarity for a given channel. @@ -150,7 +149,7 @@ impl<'d, T: ComplementaryCaptureCompare16bitInstance> ComplementaryPwm<'d, T> { } } -impl<'d, T: ComplementaryCaptureCompare16bitInstance> embedded_hal_02::Pwm for ComplementaryPwm<'d, T> { +impl<'d, T: AdvancedInstance4Channel> embedded_hal_02::Pwm for ComplementaryPwm<'d, T> { type Channel = Channel; type Time = Hertz; type Duty = u16; @@ -170,16 +169,16 @@ impl<'d, T: ComplementaryCaptureCompare16bitInstance> embedded_hal_02::Pwm for C } fn get_duty(&self, channel: Self::Channel) -> Self::Duty { - self.inner.get_compare_value(channel) + self.inner.get_compare_value(channel) as u16 } fn get_max_duty(&self) -> Self::Duty { - self.inner.get_max_compare_value() + 1 + self.inner.get_max_compare_value() as u16 + 1 } fn set_duty(&mut self, channel: Self::Channel, duty: Self::Duty) { assert!(duty <= self.get_max_duty()); - self.inner.set_compare_value(channel, duty) + self.inner.set_compare_value(channel, duty as u32) } fn set_period

(&mut self, period: P) diff --git a/embassy-stm32/src/timer/input_capture.rs b/embassy-stm32/src/timer/input_capture.rs new file mode 100644 index 000000000..341ac2c04 --- /dev/null +++ b/embassy-stm32/src/timer/input_capture.rs @@ -0,0 +1,214 @@ +//! Input capture driver. + +use core::future::Future; +use core::marker::PhantomData; +use core::pin::Pin; +use core::task::{Context, Poll}; + +use embassy_hal_internal::{into_ref, PeripheralRef}; + +use super::low_level::{CountingMode, FilterValue, InputCaptureMode, InputTISelection, Timer}; +use super::{ + CaptureCompareInterruptHandler, Channel, Channel1Pin, Channel2Pin, Channel3Pin, Channel4Pin, + GeneralInstance4Channel, +}; +use crate::gpio::{AfType, AnyPin, Pull}; +use crate::interrupt::typelevel::{Binding, Interrupt}; +use crate::time::Hertz; +use crate::Peripheral; + +/// Channel 1 marker type. +pub enum Ch1 {} +/// Channel 2 marker type. +pub enum Ch2 {} +/// Channel 3 marker type. +pub enum Ch3 {} +/// Channel 4 marker type. +pub enum Ch4 {} + +/// Capture pin wrapper. +/// +/// This wraps a pin to make it usable with capture. +pub struct CapturePin<'d, T, C> { + _pin: PeripheralRef<'d, AnyPin>, + phantom: PhantomData<(T, C)>, +} + +macro_rules! channel_impl { + ($new_chx:ident, $channel:ident, $pin_trait:ident) => { + impl<'d, T: GeneralInstance4Channel> CapturePin<'d, T, $channel> { + #[doc = concat!("Create a new ", stringify!($channel), " capture pin instance.")] + pub fn $new_chx(pin: impl Peripheral

> + 'd, pull: Pull) -> Self { + into_ref!(pin); + pin.set_as_af(pin.af_num(), AfType::input(pull)); + CapturePin { + _pin: pin.map_into(), + phantom: PhantomData, + } + } + } + }; +} + +channel_impl!(new_ch1, Ch1, Channel1Pin); +channel_impl!(new_ch2, Ch2, Channel2Pin); +channel_impl!(new_ch3, Ch3, Channel3Pin); +channel_impl!(new_ch4, Ch4, Channel4Pin); + +/// Input capture driver. +pub struct InputCapture<'d, T: GeneralInstance4Channel> { + inner: Timer<'d, T>, +} + +impl<'d, T: GeneralInstance4Channel> InputCapture<'d, T> { + /// Create a new input capture driver. + pub fn new( + tim: impl Peripheral

+ 'd, + _ch1: Option>, + _ch2: Option>, + _ch3: Option>, + _ch4: Option>, + _irq: impl Binding> + 'd, + freq: Hertz, + counting_mode: CountingMode, + ) -> Self { + Self::new_inner(tim, freq, counting_mode) + } + + fn new_inner(tim: impl Peripheral

+ 'd, freq: Hertz, counting_mode: CountingMode) -> Self { + let mut this = Self { inner: Timer::new(tim) }; + + this.inner.set_counting_mode(counting_mode); + this.inner.set_tick_freq(freq); + this.inner.enable_outputs(); // Required for advanced timers, see GeneralInstance4Channel for details + this.inner.start(); + + // enable NVIC interrupt + T::CaptureCompareInterrupt::unpend(); + unsafe { T::CaptureCompareInterrupt::enable() }; + + this + } + + /// Enable the given channel. + pub fn enable(&mut self, channel: Channel) { + self.inner.enable_channel(channel, true); + } + + /// Disable the given channel. + pub fn disable(&mut self, channel: Channel) { + self.inner.enable_channel(channel, false); + } + + /// Check whether given channel is enabled + pub fn is_enabled(&self, channel: Channel) -> bool { + self.inner.get_channel_enable_state(channel) + } + + /// Set the input capture mode for a given channel. + pub fn set_input_capture_mode(&mut self, channel: Channel, mode: InputCaptureMode) { + self.inner.set_input_capture_mode(channel, mode); + } + + /// Set input TI selection. + pub fn set_input_ti_selection(&mut self, channel: Channel, tisel: InputTISelection) { + self.inner.set_input_ti_selection(channel, tisel) + } + + /// Get capture value for a channel. + pub fn get_capture_value(&self, channel: Channel) -> u32 { + self.inner.get_capture_value(channel) + } + + /// Get input interrupt. + pub fn get_input_interrupt(&self, channel: Channel) -> bool { + self.inner.get_input_interrupt(channel) + } + + fn new_future(&self, channel: Channel, mode: InputCaptureMode, tisel: InputTISelection) -> InputCaptureFuture { + // Configuration steps from ST RM0390 (STM32F446) chapter 17.3.5 + // or ST RM0008 (STM32F103) chapter 15.3.5 Input capture mode + self.inner.set_input_ti_selection(channel, tisel); + self.inner.set_input_capture_filter(channel, FilterValue::NOFILTER); + self.inner.set_input_capture_mode(channel, mode); + self.inner.set_input_capture_prescaler(channel, 0); + self.inner.enable_channel(channel, true); + self.inner.enable_input_interrupt(channel, true); + + InputCaptureFuture { + channel, + phantom: PhantomData, + } + } + + /// Asynchronously wait until the pin sees a rising edge. + pub async fn wait_for_rising_edge(&mut self, channel: Channel) -> u32 { + self.new_future(channel, InputCaptureMode::Rising, InputTISelection::Normal) + .await + } + + /// Asynchronously wait until the pin sees a falling edge. + pub async fn wait_for_falling_edge(&mut self, channel: Channel) -> u32 { + self.new_future(channel, InputCaptureMode::Falling, InputTISelection::Normal) + .await + } + + /// Asynchronously wait until the pin sees any edge. + pub async fn wait_for_any_edge(&mut self, channel: Channel) -> u32 { + self.new_future(channel, InputCaptureMode::BothEdges, InputTISelection::Normal) + .await + } + + /// Asynchronously wait until the (alternate) pin sees a rising edge. + pub async fn wait_for_rising_edge_alternate(&mut self, channel: Channel) -> u32 { + self.new_future(channel, InputCaptureMode::Rising, InputTISelection::Alternate) + .await + } + + /// Asynchronously wait until the (alternate) pin sees a falling edge. + pub async fn wait_for_falling_edge_alternate(&mut self, channel: Channel) -> u32 { + self.new_future(channel, InputCaptureMode::Falling, InputTISelection::Alternate) + .await + } + + /// Asynchronously wait until the (alternate) pin sees any edge. + pub async fn wait_for_any_edge_alternate(&mut self, channel: Channel) -> u32 { + self.new_future(channel, InputCaptureMode::BothEdges, InputTISelection::Alternate) + .await + } +} + +#[must_use = "futures do nothing unless you `.await` or poll them"] +struct InputCaptureFuture { + channel: Channel, + phantom: PhantomData, +} + +impl Drop for InputCaptureFuture { + fn drop(&mut self) { + critical_section::with(|_| { + let regs = unsafe { crate::pac::timer::TimGp16::from_ptr(T::regs()) }; + + // disable interrupt enable + regs.dier().modify(|w| w.set_ccie(self.channel.index(), false)); + }); + } +} + +impl Future for InputCaptureFuture { + type Output = u32; + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + T::state().cc_waker[self.channel.index()].register(cx.waker()); + + let regs = unsafe { crate::pac::timer::TimGp16::from_ptr(T::regs()) }; + + let dier = regs.dier().read(); + if !dier.ccie(self.channel.index()) { + let val = regs.ccr(self.channel.index()).read().0; + Poll::Ready(val) + } else { + Poll::Pending + } + } +} diff --git a/embassy-stm32/src/timer/low_level.rs b/embassy-stm32/src/timer/low_level.rs new file mode 100644 index 000000000..3136ea4e9 --- /dev/null +++ b/embassy-stm32/src/timer/low_level.rs @@ -0,0 +1,687 @@ +//! Low-level timer driver. +//! +//! This is an unopinionated, very low-level driver for all STM32 timers. It allows direct register +//! manipulation with the `regs_*()` methods, and has utility functions that are thin wrappers +//! over the registers. +//! +//! The available functionality depends on the timer type. + +use core::mem::ManuallyDrop; + +use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef}; +// Re-export useful enums +pub use stm32_metapac::timer::vals::{FilterValue, Sms as SlaveMode, Ts as TriggerSource}; + +use super::*; +use crate::pac::timer::vals; +use crate::rcc; +use crate::time::Hertz; + +/// Input capture mode. +#[derive(Clone, Copy)] +pub enum InputCaptureMode { + /// Rising edge only. + Rising, + /// Falling edge only. + Falling, + /// Both rising or falling edges. + BothEdges, +} + +/// Input TI selection. +#[derive(Clone, Copy)] +pub enum InputTISelection { + /// Normal + Normal, + /// Alternate + Alternate, + /// TRC + TRC, +} + +impl From for stm32_metapac::timer::vals::CcmrInputCcs { + fn from(tisel: InputTISelection) -> Self { + match tisel { + InputTISelection::Normal => stm32_metapac::timer::vals::CcmrInputCcs::TI4, + InputTISelection::Alternate => stm32_metapac::timer::vals::CcmrInputCcs::TI3, + InputTISelection::TRC => stm32_metapac::timer::vals::CcmrInputCcs::TRC, + } + } +} + +/// Timer counting mode. +#[repr(u8)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum CountingMode { + #[default] + /// The timer counts up to the reload value and then resets back to 0. + EdgeAlignedUp, + /// The timer counts down to 0 and then resets back to the reload value. + EdgeAlignedDown, + /// The timer counts up to the reload value and then counts back to 0. + /// + /// The output compare interrupt flags of channels configured in output are + /// set when the counter is counting down. + CenterAlignedDownInterrupts, + /// The timer counts up to the reload value and then counts back to 0. + /// + /// The output compare interrupt flags of channels configured in output are + /// set when the counter is counting up. + CenterAlignedUpInterrupts, + /// The timer counts up to the reload value and then counts back to 0. + /// + /// The output compare interrupt flags of channels configured in output are + /// set when the counter is counting both up or down. + CenterAlignedBothInterrupts, +} + +impl CountingMode { + /// Return whether this mode is edge-aligned (up or down). + pub fn is_edge_aligned(&self) -> bool { + matches!(self, CountingMode::EdgeAlignedUp | CountingMode::EdgeAlignedDown) + } + + /// Return whether this mode is center-aligned. + pub fn is_center_aligned(&self) -> bool { + matches!( + self, + CountingMode::CenterAlignedDownInterrupts + | CountingMode::CenterAlignedUpInterrupts + | CountingMode::CenterAlignedBothInterrupts + ) + } +} + +impl From for (vals::Cms, vals::Dir) { + fn from(value: CountingMode) -> Self { + match value { + CountingMode::EdgeAlignedUp => (vals::Cms::EDGEALIGNED, vals::Dir::UP), + CountingMode::EdgeAlignedDown => (vals::Cms::EDGEALIGNED, vals::Dir::DOWN), + CountingMode::CenterAlignedDownInterrupts => (vals::Cms::CENTERALIGNED1, vals::Dir::UP), + CountingMode::CenterAlignedUpInterrupts => (vals::Cms::CENTERALIGNED2, vals::Dir::UP), + CountingMode::CenterAlignedBothInterrupts => (vals::Cms::CENTERALIGNED3, vals::Dir::UP), + } + } +} + +impl From<(vals::Cms, vals::Dir)> for CountingMode { + fn from(value: (vals::Cms, vals::Dir)) -> Self { + match value { + (vals::Cms::EDGEALIGNED, vals::Dir::UP) => CountingMode::EdgeAlignedUp, + (vals::Cms::EDGEALIGNED, vals::Dir::DOWN) => CountingMode::EdgeAlignedDown, + (vals::Cms::CENTERALIGNED1, _) => CountingMode::CenterAlignedDownInterrupts, + (vals::Cms::CENTERALIGNED2, _) => CountingMode::CenterAlignedUpInterrupts, + (vals::Cms::CENTERALIGNED3, _) => CountingMode::CenterAlignedBothInterrupts, + } + } +} + +/// Output compare mode. +#[derive(Clone, Copy)] +pub enum OutputCompareMode { + /// The comparison between the output compare register TIMx_CCRx and + /// the counter TIMx_CNT has no effect on the outputs. + /// (this mode is used to generate a timing base). + Frozen, + /// Set channel to active level on match. OCxREF signal is forced high when the + /// counter TIMx_CNT matches the capture/compare register x (TIMx_CCRx). + ActiveOnMatch, + /// Set channel to inactive level on match. OCxREF signal is forced low when the + /// counter TIMx_CNT matches the capture/compare register x (TIMx_CCRx). + InactiveOnMatch, + /// Toggle - OCxREF toggles when TIMx_CNT=TIMx_CCRx. + Toggle, + /// Force inactive level - OCxREF is forced low. + ForceInactive, + /// Force active level - OCxREF is forced high. + ForceActive, + /// PWM mode 1 - In upcounting, channel is active as long as TIMx_CNTTIMx_CCRx else active (OCxREF=1). + PwmMode1, + /// PWM mode 2 - In upcounting, channel is inactive as long as + /// TIMx_CNTTIMx_CCRx else inactive. + PwmMode2, + // TODO: there's more modes here depending on the chip family. +} + +impl From for stm32_metapac::timer::vals::Ocm { + fn from(mode: OutputCompareMode) -> Self { + match mode { + OutputCompareMode::Frozen => stm32_metapac::timer::vals::Ocm::FROZEN, + OutputCompareMode::ActiveOnMatch => stm32_metapac::timer::vals::Ocm::ACTIVEONMATCH, + OutputCompareMode::InactiveOnMatch => stm32_metapac::timer::vals::Ocm::INACTIVEONMATCH, + OutputCompareMode::Toggle => stm32_metapac::timer::vals::Ocm::TOGGLE, + OutputCompareMode::ForceInactive => stm32_metapac::timer::vals::Ocm::FORCEINACTIVE, + OutputCompareMode::ForceActive => stm32_metapac::timer::vals::Ocm::FORCEACTIVE, + OutputCompareMode::PwmMode1 => stm32_metapac::timer::vals::Ocm::PWMMODE1, + OutputCompareMode::PwmMode2 => stm32_metapac::timer::vals::Ocm::PWMMODE2, + } + } +} + +/// Timer output pin polarity. +#[derive(Clone, Copy)] +pub enum OutputPolarity { + /// Active high (higher duty value makes the pin spend more time high). + ActiveHigh, + /// Active low (higher duty value makes the pin spend more time low). + ActiveLow, +} + +impl From for bool { + fn from(mode: OutputPolarity) -> Self { + match mode { + OutputPolarity::ActiveHigh => false, + OutputPolarity::ActiveLow => true, + } + } +} + +/// Low-level timer driver. +pub struct Timer<'d, T: CoreInstance> { + tim: PeripheralRef<'d, T>, +} + +impl<'d, T: CoreInstance> Drop for Timer<'d, T> { + fn drop(&mut self) { + rcc::disable::(); + } +} + +impl<'d, T: CoreInstance> Timer<'d, T> { + /// Create a new timer driver. + pub fn new(tim: impl Peripheral

+ 'd) -> Self { + into_ref!(tim); + + rcc::enable_and_reset::(); + + Self { tim } + } + + pub(crate) unsafe fn clone_unchecked(&self) -> ManuallyDrop { + let tim = unsafe { self.tim.clone_unchecked() }; + ManuallyDrop::new(Self { tim }) + } + + /// Get access to the virutal core 16bit timer registers. + /// + /// Note: This works even if the timer is more capable, because registers + /// for the less capable timers are a subset. This allows writing a driver + /// for a given set of capabilities, and having it transparently work with + /// more capable timers. + pub fn regs_core(&self) -> crate::pac::timer::TimCore { + unsafe { crate::pac::timer::TimCore::from_ptr(T::regs()) } + } + + #[cfg(not(stm32l0))] + fn regs_gp32_unchecked(&self) -> crate::pac::timer::TimGp32 { + unsafe { crate::pac::timer::TimGp32::from_ptr(T::regs()) } + } + + /// Start the timer. + pub fn start(&self) { + self.regs_core().cr1().modify(|r| r.set_cen(true)); + } + + /// Stop the timer. + pub fn stop(&self) { + self.regs_core().cr1().modify(|r| r.set_cen(false)); + } + + /// Reset the counter value to 0 + pub fn reset(&self) { + self.regs_core().cnt().write(|r| r.set_cnt(0)); + } + + /// Set the frequency of how many times per second the timer counts up to the max value or down to 0. + /// + /// This means that in the default edge-aligned mode, + /// the timer counter will wrap around at the same frequency as is being set. + /// In center-aligned mode (which not all timers support), the wrap-around frequency is effectively halved + /// because it needs to count up and down. + pub fn set_frequency(&self, frequency: Hertz) { + let f = frequency.0; + assert!(f > 0); + let timer_f = T::frequency().0; + + match T::BITS { + TimerBits::Bits16 => { + let pclk_ticks_per_timer_period = timer_f / f; + let psc: u16 = unwrap!(((pclk_ticks_per_timer_period - 1) / (1 << 16)).try_into()); + let divide_by = pclk_ticks_per_timer_period / (u32::from(psc) + 1); + + // the timer counts `0..=arr`, we want it to count `0..divide_by` + let arr = unwrap!(u16::try_from(divide_by - 1)); + + let regs = self.regs_core(); + regs.psc().write_value(psc); + regs.arr().write(|r| r.set_arr(arr)); + + regs.cr1().modify(|r| r.set_urs(vals::Urs::COUNTERONLY)); + regs.egr().write(|r| r.set_ug(true)); + regs.cr1().modify(|r| r.set_urs(vals::Urs::ANYEVENT)); + } + #[cfg(not(stm32l0))] + TimerBits::Bits32 => { + let pclk_ticks_per_timer_period = (timer_f / f) as u64; + let psc: u16 = unwrap!(((pclk_ticks_per_timer_period - 1) / (1 << 32)).try_into()); + let divide_by = pclk_ticks_per_timer_period / (u64::from(psc) + 1); + + // the timer counts `0..=arr`, we want it to count `0..divide_by` + let arr: u32 = unwrap!(u32::try_from(divide_by - 1)); + + let regs = self.regs_gp32_unchecked(); + regs.psc().write_value(psc); + regs.arr().write_value(arr); + + regs.cr1().modify(|r| r.set_urs(vals::Urs::COUNTERONLY)); + regs.egr().write(|r| r.set_ug(true)); + regs.cr1().modify(|r| r.set_urs(vals::Urs::ANYEVENT)); + } + } + } + + /// Set tick frequency. + pub fn set_tick_freq(&mut self, freq: Hertz) { + let f = freq; + assert!(f.0 > 0); + let timer_f = self.get_clock_frequency(); + + let pclk_ticks_per_timer_period = timer_f / f; + let psc: u16 = unwrap!((pclk_ticks_per_timer_period - 1).try_into()); + + let regs = self.regs_core(); + regs.psc().write_value(psc); + + // Generate an Update Request + regs.egr().write(|r| r.set_ug(true)); + } + + /// Clear update interrupt. + /// + /// Returns whether the update interrupt flag was set. + pub fn clear_update_interrupt(&self) -> bool { + let regs = self.regs_core(); + let sr = regs.sr().read(); + if sr.uif() { + regs.sr().modify(|r| { + r.set_uif(false); + }); + true + } else { + false + } + } + + /// Enable/disable the update interrupt. + pub fn enable_update_interrupt(&self, enable: bool) { + self.regs_core().dier().modify(|r| r.set_uie(enable)); + } + + /// Enable/disable autoreload preload. + pub fn set_autoreload_preload(&self, enable: bool) { + self.regs_core().cr1().modify(|r| r.set_arpe(enable)); + } + + /// Get the timer frequency. + pub fn get_frequency(&self) -> Hertz { + let timer_f = T::frequency(); + + match T::BITS { + TimerBits::Bits16 => { + let regs = self.regs_core(); + let arr = regs.arr().read().arr(); + let psc = regs.psc().read(); + + timer_f / arr / (psc + 1) + } + #[cfg(not(stm32l0))] + TimerBits::Bits32 => { + let regs = self.regs_gp32_unchecked(); + let arr = regs.arr().read(); + let psc = regs.psc().read(); + + timer_f / arr / (psc + 1) + } + } + } + + /// Get the clock frequency of the timer (before prescaler is applied). + pub fn get_clock_frequency(&self) -> Hertz { + T::frequency() + } +} + +impl<'d, T: BasicNoCr2Instance> Timer<'d, T> { + /// Get access to the Baisc 16bit timer registers. + /// + /// Note: This works even if the timer is more capable, because registers + /// for the less capable timers are a subset. This allows writing a driver + /// for a given set of capabilities, and having it transparently work with + /// more capable timers. + pub fn regs_basic_no_cr2(&self) -> crate::pac::timer::TimBasicNoCr2 { + unsafe { crate::pac::timer::TimBasicNoCr2::from_ptr(T::regs()) } + } + + /// Enable/disable the update dma. + pub fn enable_update_dma(&self, enable: bool) { + self.regs_basic_no_cr2().dier().modify(|r| r.set_ude(enable)); + } + + /// Get the update dma enable/disable state. + pub fn get_update_dma_state(&self) -> bool { + self.regs_basic_no_cr2().dier().read().ude() + } +} + +impl<'d, T: BasicInstance> Timer<'d, T> { + /// Get access to the Baisc 16bit timer registers. + /// + /// Note: This works even if the timer is more capable, because registers + /// for the less capable timers are a subset. This allows writing a driver + /// for a given set of capabilities, and having it transparently work with + /// more capable timers. + pub fn regs_basic(&self) -> crate::pac::timer::TimBasic { + unsafe { crate::pac::timer::TimBasic::from_ptr(T::regs()) } + } +} + +impl<'d, T: GeneralInstance1Channel> Timer<'d, T> { + /// Get access to the general purpose 1 channel 16bit timer registers. + /// + /// Note: This works even if the timer is more capable, because registers + /// for the less capable timers are a subset. This allows writing a driver + /// for a given set of capabilities, and having it transparently work with + /// more capable timers. + pub fn regs_1ch(&self) -> crate::pac::timer::Tim1ch { + unsafe { crate::pac::timer::Tim1ch::from_ptr(T::regs()) } + } + + /// Set clock divider. + pub fn set_clock_division(&self, ckd: vals::Ckd) { + self.regs_1ch().cr1().modify(|r| r.set_ckd(ckd)); + } + + /// Get max compare value. This depends on the timer frequency and the clock frequency from RCC. + pub fn get_max_compare_value(&self) -> u32 { + match T::BITS { + TimerBits::Bits16 => self.regs_1ch().arr().read().arr() as u32, + #[cfg(not(stm32l0))] + TimerBits::Bits32 => self.regs_gp32_unchecked().arr().read(), + } + } +} + +impl<'d, T: GeneralInstance2Channel> Timer<'d, T> { + /// Get access to the general purpose 2 channel 16bit timer registers. + /// + /// Note: This works even if the timer is more capable, because registers + /// for the less capable timers are a subset. This allows writing a driver + /// for a given set of capabilities, and having it transparently work with + /// more capable timers. + pub fn regs_2ch(&self) -> crate::pac::timer::Tim2ch { + unsafe { crate::pac::timer::Tim2ch::from_ptr(T::regs()) } + } +} + +impl<'d, T: GeneralInstance4Channel> Timer<'d, T> { + /// Get access to the general purpose 16bit timer registers. + /// + /// Note: This works even if the timer is more capable, because registers + /// for the less capable timers are a subset. This allows writing a driver + /// for a given set of capabilities, and having it transparently work with + /// more capable timers. + pub fn regs_gp16(&self) -> crate::pac::timer::TimGp16 { + unsafe { crate::pac::timer::TimGp16::from_ptr(T::regs()) } + } + + /// Enable timer outputs. + pub fn enable_outputs(&self) { + self.tim.enable_outputs() + } + + /// Set counting mode. + pub fn set_counting_mode(&self, mode: CountingMode) { + let (cms, dir) = mode.into(); + + let timer_enabled = self.regs_core().cr1().read().cen(); + // Changing from edge aligned to center aligned (and vice versa) is not allowed while the timer is running. + // Changing direction is discouraged while the timer is running. + assert!(!timer_enabled); + + self.regs_gp16().cr1().modify(|r| r.set_dir(dir)); + self.regs_gp16().cr1().modify(|r| r.set_cms(cms)) + } + + /// Get counting mode. + pub fn get_counting_mode(&self) -> CountingMode { + let cr1 = self.regs_gp16().cr1().read(); + (cr1.cms(), cr1.dir()).into() + } + + /// Set input capture filter. + pub fn set_input_capture_filter(&self, channel: Channel, icf: vals::FilterValue) { + let raw_channel = channel.index(); + self.regs_gp16() + .ccmr_input(raw_channel / 2) + .modify(|r| r.set_icf(raw_channel % 2, icf)); + } + + /// Clear input interrupt. + pub fn clear_input_interrupt(&self, channel: Channel) { + self.regs_gp16().sr().modify(|r| r.set_ccif(channel.index(), false)); + } + + /// Get input interrupt. + pub fn get_input_interrupt(&self, channel: Channel) -> bool { + self.regs_gp16().sr().read().ccif(channel.index()) + } + + /// Enable input interrupt. + pub fn enable_input_interrupt(&self, channel: Channel, enable: bool) { + self.regs_gp16().dier().modify(|r| r.set_ccie(channel.index(), enable)); + } + + /// Set input capture prescaler. + pub fn set_input_capture_prescaler(&self, channel: Channel, factor: u8) { + let raw_channel = channel.index(); + self.regs_gp16() + .ccmr_input(raw_channel / 2) + .modify(|r| r.set_icpsc(raw_channel % 2, factor)); + } + + /// Set input TI selection. + pub fn set_input_ti_selection(&self, channel: Channel, tisel: InputTISelection) { + let raw_channel = channel.index(); + self.regs_gp16() + .ccmr_input(raw_channel / 2) + .modify(|r| r.set_ccs(raw_channel % 2, tisel.into())); + } + + /// Set input capture mode. + pub fn set_input_capture_mode(&self, channel: Channel, mode: InputCaptureMode) { + self.regs_gp16().ccer().modify(|r| match mode { + InputCaptureMode::Rising => { + r.set_ccnp(channel.index(), false); + r.set_ccp(channel.index(), false); + } + InputCaptureMode::Falling => { + r.set_ccnp(channel.index(), false); + r.set_ccp(channel.index(), true); + } + InputCaptureMode::BothEdges => { + r.set_ccnp(channel.index(), true); + r.set_ccp(channel.index(), true); + } + }); + } + + /// Set output compare mode. + pub fn set_output_compare_mode(&self, channel: Channel, mode: OutputCompareMode) { + let raw_channel: usize = channel.index(); + self.regs_gp16() + .ccmr_output(raw_channel / 2) + .modify(|w| w.set_ocm(raw_channel % 2, mode.into())); + } + + /// Set output polarity. + pub fn set_output_polarity(&self, channel: Channel, polarity: OutputPolarity) { + self.regs_gp16() + .ccer() + .modify(|w| w.set_ccp(channel.index(), polarity.into())); + } + + /// Enable/disable a channel. + pub fn enable_channel(&self, channel: Channel, enable: bool) { + self.regs_gp16().ccer().modify(|w| w.set_cce(channel.index(), enable)); + } + + /// Get enable/disable state of a channel + pub fn get_channel_enable_state(&self, channel: Channel) -> bool { + self.regs_gp16().ccer().read().cce(channel.index()) + } + + /// Set compare value for a channel. + pub fn set_compare_value(&self, channel: Channel, value: u32) { + match T::BITS { + TimerBits::Bits16 => { + let value = unwrap!(u16::try_from(value)); + self.regs_gp16().ccr(channel.index()).modify(|w| w.set_ccr(value)); + } + #[cfg(not(stm32l0))] + TimerBits::Bits32 => { + self.regs_gp32_unchecked().ccr(channel.index()).write_value(value); + } + } + } + + /// Get compare value for a channel. + pub fn get_compare_value(&self, channel: Channel) -> u32 { + match T::BITS { + TimerBits::Bits16 => self.regs_gp16().ccr(channel.index()).read().ccr() as u32, + #[cfg(not(stm32l0))] + TimerBits::Bits32 => self.regs_gp32_unchecked().ccr(channel.index()).read(), + } + } + + /// Get capture value for a channel. + pub fn get_capture_value(&self, channel: Channel) -> u32 { + self.get_compare_value(channel) + } + + /// Set output compare preload. + pub fn set_output_compare_preload(&self, channel: Channel, preload: bool) { + let channel_index = channel.index(); + self.regs_gp16() + .ccmr_output(channel_index / 2) + .modify(|w| w.set_ocpe(channel_index % 2, preload)); + } + + /// Get capture compare DMA selection + pub fn get_cc_dma_selection(&self) -> vals::Ccds { + self.regs_gp16().cr2().read().ccds() + } + + /// Set capture compare DMA selection + pub fn set_cc_dma_selection(&self, ccds: vals::Ccds) { + self.regs_gp16().cr2().modify(|w| w.set_ccds(ccds)) + } + + /// Get capture compare DMA enable state + pub fn get_cc_dma_enable_state(&self, channel: Channel) -> bool { + self.regs_gp16().dier().read().ccde(channel.index()) + } + + /// Set capture compare DMA enable state + pub fn set_cc_dma_enable_state(&self, channel: Channel, ccde: bool) { + self.regs_gp16().dier().modify(|w| w.set_ccde(channel.index(), ccde)) + } + + /// Set Timer Slave Mode + pub fn set_slave_mode(&self, sms: SlaveMode) { + self.regs_gp16().smcr().modify(|r| r.set_sms(sms)); + } + + /// Set Timer Trigger Source + pub fn set_trigger_source(&self, ts: TriggerSource) { + self.regs_gp16().smcr().modify(|r| r.set_ts(ts)); + } +} + +#[cfg(not(stm32l0))] +impl<'d, T: GeneralInstance32bit4Channel> Timer<'d, T> { + /// Get access to the general purpose 32bit timer registers. + /// + /// Note: This works even if the timer is more capable, because registers + /// for the less capable timers are a subset. This allows writing a driver + /// for a given set of capabilities, and having it transparently work with + /// more capable timers. + pub fn regs_gp32(&self) -> crate::pac::timer::TimGp32 { + unsafe { crate::pac::timer::TimGp32::from_ptr(T::regs()) } + } +} + +#[cfg(not(stm32l0))] +impl<'d, T: AdvancedInstance1Channel> Timer<'d, T> { + /// Get access to the general purpose 1 channel with one complementary 16bit timer registers. + /// + /// Note: This works even if the timer is more capable, because registers + /// for the less capable timers are a subset. This allows writing a driver + /// for a given set of capabilities, and having it transparently work with + /// more capable timers. + pub fn regs_1ch_cmp(&self) -> crate::pac::timer::Tim1chCmp { + unsafe { crate::pac::timer::Tim1chCmp::from_ptr(T::regs()) } + } + + /// Set clock divider for the dead time. + pub fn set_dead_time_clock_division(&self, value: vals::Ckd) { + self.regs_1ch_cmp().cr1().modify(|w| w.set_ckd(value)); + } + + /// Set dead time, as a fraction of the max duty value. + pub fn set_dead_time_value(&self, value: u8) { + self.regs_1ch_cmp().bdtr().modify(|w| w.set_dtg(value)); + } + + /// Set state of MOE-bit in BDTR register to en-/disable output + pub fn set_moe(&self, enable: bool) { + self.regs_1ch_cmp().bdtr().modify(|w| w.set_moe(enable)); + } +} + +#[cfg(not(stm32l0))] +impl<'d, T: AdvancedInstance2Channel> Timer<'d, T> { + /// Get access to the general purpose 2 channel with one complementary 16bit timer registers. + /// + /// Note: This works even if the timer is more capable, because registers + /// for the less capable timers are a subset. This allows writing a driver + /// for a given set of capabilities, and having it transparently work with + /// more capable timers. + pub fn regs_2ch_cmp(&self) -> crate::pac::timer::Tim2chCmp { + unsafe { crate::pac::timer::Tim2chCmp::from_ptr(T::regs()) } + } +} + +#[cfg(not(stm32l0))] +impl<'d, T: AdvancedInstance4Channel> Timer<'d, T> { + /// Get access to the advanced timer registers. + pub fn regs_advanced(&self) -> crate::pac::timer::TimAdv { + unsafe { crate::pac::timer::TimAdv::from_ptr(T::regs()) } + } + + /// Set complementary output polarity. + pub fn set_complementary_output_polarity(&self, channel: Channel, polarity: OutputPolarity) { + self.regs_advanced() + .ccer() + .modify(|w| w.set_ccnp(channel.index(), polarity.into())); + } + + /// Enable/disable a complementary channel. + pub fn enable_complementary_channel(&self, channel: Channel, enable: bool) { + self.regs_advanced() + .ccer() + .modify(|w| w.set_ccne(channel.index(), enable)); + } +} diff --git a/embassy-stm32/src/timer/mod.rs b/embassy-stm32/src/timer/mod.rs index 210bf7153..aa9dd91d9 100644 --- a/embassy-stm32/src/timer/mod.rs +++ b/embassy-stm32/src/timer/mod.rs @@ -1,388 +1,20 @@ //! Timers, PWM, quadrature decoder. +use core::marker::PhantomData; + +use embassy_hal_internal::Peripheral; +use embassy_sync::waitqueue::AtomicWaker; + +#[cfg(not(stm32l0))] pub mod complementary_pwm; +pub mod input_capture; +pub mod low_level; +pub mod pwm_input; pub mod qei; pub mod simple_pwm; -use stm32_metapac::timer::vals; - use crate::interrupt; use crate::rcc::RccPeripheral; -use crate::time::Hertz; - -/// Low-level timer access. -#[cfg(feature = "unstable-pac")] -pub mod low_level { - pub use super::sealed::*; -} - -pub(crate) mod sealed { - use super::*; - - /// Basic 16-bit timer instance. - pub trait Basic16bitInstance: RccPeripheral { - /// Interrupt for this timer. - type Interrupt: interrupt::typelevel::Interrupt; - - /// Get access to the basic 16bit timer registers. - /// - /// Note: This works even if the timer is more capable, because registers - /// for the less capable timers are a subset. This allows writing a driver - /// for a given set of capabilities, and having it transparently work with - /// more capable timers. - fn regs() -> crate::pac::timer::TimBasic; - - /// Start the timer. - fn start(&mut self) { - Self::regs().cr1().modify(|r| r.set_cen(true)); - } - - /// Stop the timer. - fn stop(&mut self) { - Self::regs().cr1().modify(|r| r.set_cen(false)); - } - - /// Reset the counter value to 0 - fn reset(&mut self) { - Self::regs().cnt().write(|r| r.set_cnt(0)); - } - - /// Set the frequency of how many times per second the timer counts up to the max value or down to 0. - /// - /// This means that in the default edge-aligned mode, - /// the timer counter will wrap around at the same frequency as is being set. - /// In center-aligned mode (which not all timers support), the wrap-around frequency is effectively halved - /// because it needs to count up and down. - fn set_frequency(&mut self, frequency: Hertz) { - let f = frequency.0; - let timer_f = Self::frequency().0; - assert!(f > 0); - let pclk_ticks_per_timer_period = timer_f / f; - let psc: u16 = unwrap!(((pclk_ticks_per_timer_period - 1) / (1 << 16)).try_into()); - let divide_by = pclk_ticks_per_timer_period / (u32::from(psc) + 1); - - // the timer counts `0..=arr`, we want it to count `0..divide_by` - let arr = unwrap!(u16::try_from(divide_by - 1)); - - let regs = Self::regs(); - regs.psc().write(|r| r.set_psc(psc)); - regs.arr().write(|r| r.set_arr(arr)); - - regs.cr1().modify(|r| r.set_urs(vals::Urs::COUNTERONLY)); - regs.egr().write(|r| r.set_ug(true)); - regs.cr1().modify(|r| r.set_urs(vals::Urs::ANYEVENT)); - } - - /// Clear update interrupt. - /// - /// Returns whether the update interrupt flag was set. - fn clear_update_interrupt(&mut self) -> bool { - let regs = Self::regs(); - let sr = regs.sr().read(); - if sr.uif() { - regs.sr().modify(|r| { - r.set_uif(false); - }); - true - } else { - false - } - } - - /// Enable/disable the update interrupt. - fn enable_update_interrupt(&mut self, enable: bool) { - Self::regs().dier().modify(|r| r.set_uie(enable)); - } - - /// Enable/disable the update dma. - fn enable_update_dma(&mut self, enable: bool) { - Self::regs().dier().modify(|r| r.set_ude(enable)); - } - - /// Get the update dma enable/disable state. - fn get_update_dma_state(&self) -> bool { - Self::regs().dier().read().ude() - } - - /// Enable/disable autoreload preload. - fn set_autoreload_preload(&mut self, enable: bool) { - Self::regs().cr1().modify(|r| r.set_arpe(enable)); - } - - /// Get the timer frequency. - fn get_frequency(&self) -> Hertz { - let timer_f = Self::frequency(); - - let regs = Self::regs(); - let arr = regs.arr().read().arr(); - let psc = regs.psc().read().psc(); - - timer_f / arr / (psc + 1) - } - } - - /// Gneral-purpose 16-bit timer instance. - pub trait GeneralPurpose16bitInstance: Basic16bitInstance { - /// Get access to the general purpose 16bit timer registers. - /// - /// Note: This works even if the timer is more capable, because registers - /// for the less capable timers are a subset. This allows writing a driver - /// for a given set of capabilities, and having it transparently work with - /// more capable timers. - fn regs_gp16() -> crate::pac::timer::TimGp16; - - /// Set counting mode. - fn set_counting_mode(&mut self, mode: CountingMode) { - let (cms, dir) = mode.into(); - - let timer_enabled = Self::regs().cr1().read().cen(); - // Changing from edge aligned to center aligned (and vice versa) is not allowed while the timer is running. - // Changing direction is discouraged while the timer is running. - assert!(!timer_enabled); - - Self::regs_gp16().cr1().modify(|r| r.set_dir(dir)); - Self::regs_gp16().cr1().modify(|r| r.set_cms(cms)) - } - - /// Get counting mode. - fn get_counting_mode(&self) -> CountingMode { - let cr1 = Self::regs_gp16().cr1().read(); - (cr1.cms(), cr1.dir()).into() - } - - /// Set clock divider. - fn set_clock_division(&mut self, ckd: vals::Ckd) { - Self::regs_gp16().cr1().modify(|r| r.set_ckd(ckd)); - } - } - - /// Gneral-purpose 32-bit timer instance. - pub trait GeneralPurpose32bitInstance: GeneralPurpose16bitInstance { - /// Get access to the general purpose 32bit timer registers. - /// - /// Note: This works even if the timer is more capable, because registers - /// for the less capable timers are a subset. This allows writing a driver - /// for a given set of capabilities, and having it transparently work with - /// more capable timers. - fn regs_gp32() -> crate::pac::timer::TimGp32; - - /// Set timer frequency. - fn set_frequency(&mut self, frequency: Hertz) { - let f = frequency.0; - assert!(f > 0); - let timer_f = Self::frequency().0; - let pclk_ticks_per_timer_period = (timer_f / f) as u64; - let psc: u16 = unwrap!(((pclk_ticks_per_timer_period - 1) / (1 << 32)).try_into()); - let arr: u32 = unwrap!((pclk_ticks_per_timer_period / (psc as u64 + 1)).try_into()); - - let regs = Self::regs_gp32(); - regs.psc().write(|r| r.set_psc(psc)); - regs.arr().write(|r| r.set_arr(arr)); - - regs.cr1().modify(|r| r.set_urs(vals::Urs::COUNTERONLY)); - regs.egr().write(|r| r.set_ug(true)); - regs.cr1().modify(|r| r.set_urs(vals::Urs::ANYEVENT)); - } - - /// Get timer frequency. - fn get_frequency(&self) -> Hertz { - let timer_f = Self::frequency(); - - let regs = Self::regs_gp32(); - let arr = regs.arr().read().arr(); - let psc = regs.psc().read().psc(); - - timer_f / arr / (psc + 1) - } - } - - /// Advanced control timer instance. - pub trait AdvancedControlInstance: GeneralPurpose16bitInstance { - /// Get access to the advanced timer registers. - fn regs_advanced() -> crate::pac::timer::TimAdv; - } - - /// Capture/Compare 16-bit timer instance. - pub trait CaptureCompare16bitInstance: GeneralPurpose16bitInstance { - /// Set input capture filter. - fn set_input_capture_filter(&mut self, channel: Channel, icf: vals::Icf) { - let raw_channel = channel.index(); - Self::regs_gp16() - .ccmr_input(raw_channel / 2) - .modify(|r| r.set_icf(raw_channel % 2, icf)); - } - - /// Clear input interrupt. - fn clear_input_interrupt(&mut self, channel: Channel) { - Self::regs_gp16().sr().modify(|r| r.set_ccif(channel.index(), false)); - } - - /// Enable input interrupt. - fn enable_input_interrupt(&mut self, channel: Channel, enable: bool) { - Self::regs_gp16().dier().modify(|r| r.set_ccie(channel.index(), enable)); - } - - /// Set input capture prescaler. - fn set_input_capture_prescaler(&mut self, channel: Channel, factor: u8) { - let raw_channel = channel.index(); - Self::regs_gp16() - .ccmr_input(raw_channel / 2) - .modify(|r| r.set_icpsc(raw_channel % 2, factor)); - } - - /// Set input TI selection. - fn set_input_ti_selection(&mut self, channel: Channel, tisel: InputTISelection) { - let raw_channel = channel.index(); - Self::regs_gp16() - .ccmr_input(raw_channel / 2) - .modify(|r| r.set_ccs(raw_channel % 2, tisel.into())); - } - - /// Set input capture mode. - fn set_input_capture_mode(&mut self, channel: Channel, mode: InputCaptureMode) { - Self::regs_gp16().ccer().modify(|r| match mode { - InputCaptureMode::Rising => { - r.set_ccnp(channel.index(), false); - r.set_ccp(channel.index(), false); - } - InputCaptureMode::Falling => { - r.set_ccnp(channel.index(), false); - r.set_ccp(channel.index(), true); - } - InputCaptureMode::BothEdges => { - r.set_ccnp(channel.index(), true); - r.set_ccp(channel.index(), true); - } - }); - } - - /// Enable timer outputs. - fn enable_outputs(&mut self); - - /// Set output compare mode. - fn set_output_compare_mode(&mut self, channel: Channel, mode: OutputCompareMode) { - let r = Self::regs_gp16(); - let raw_channel: usize = channel.index(); - r.ccmr_output(raw_channel / 2) - .modify(|w| w.set_ocm(raw_channel % 2, mode.into())); - } - - /// Set output polarity. - fn set_output_polarity(&mut self, channel: Channel, polarity: OutputPolarity) { - Self::regs_gp16() - .ccer() - .modify(|w| w.set_ccp(channel.index(), polarity.into())); - } - - /// Enable/disable a channel. - fn enable_channel(&mut self, channel: Channel, enable: bool) { - Self::regs_gp16().ccer().modify(|w| w.set_cce(channel.index(), enable)); - } - - /// Get enable/disable state of a channel - fn get_channel_enable_state(&self, channel: Channel) -> bool { - Self::regs_gp16().ccer().read().cce(channel.index()) - } - - /// Set compare value for a channel. - fn set_compare_value(&mut self, channel: Channel, value: u16) { - Self::regs_gp16().ccr(channel.index()).modify(|w| w.set_ccr(value)); - } - - /// Get capture value for a channel. - fn get_capture_value(&mut self, channel: Channel) -> u16 { - Self::regs_gp16().ccr(channel.index()).read().ccr() - } - - /// Get max compare value. This depends on the timer frequency and the clock frequency from RCC. - fn get_max_compare_value(&self) -> u16 { - Self::regs_gp16().arr().read().arr() - } - - /// Get compare value for a channel. - fn get_compare_value(&self, channel: Channel) -> u16 { - Self::regs_gp16().ccr(channel.index()).read().ccr() - } - - /// Set output compare preload. - fn set_output_compare_preload(&mut self, channel: Channel, preload: bool) { - let channel_index = channel.index(); - Self::regs_gp16() - .ccmr_output(channel_index / 2) - .modify(|w| w.set_ocpe(channel_index % 2, preload)); - } - - /// Get capture compare DMA selection - fn get_cc_dma_selection(&self) -> super::vals::Ccds { - Self::regs_gp16().cr2().read().ccds() - } - - /// Set capture compare DMA selection - fn set_cc_dma_selection(&mut self, ccds: super::vals::Ccds) { - Self::regs_gp16().cr2().modify(|w| w.set_ccds(ccds)) - } - - /// Get capture compare DMA enable state - fn get_cc_dma_enable_state(&self, channel: Channel) -> bool { - Self::regs_gp16().dier().read().ccde(channel.index()) - } - - /// Set capture compare DMA enable state - fn set_cc_dma_enable_state(&mut self, channel: Channel, ccde: bool) { - Self::regs_gp16().dier().modify(|w| w.set_ccde(channel.index(), ccde)) - } - } - - /// Capture/Compare 16-bit timer instance with complementary pin support. - pub trait ComplementaryCaptureCompare16bitInstance: CaptureCompare16bitInstance + AdvancedControlInstance { - /// Set complementary output polarity. - fn set_complementary_output_polarity(&mut self, channel: Channel, polarity: OutputPolarity) { - Self::regs_advanced() - .ccer() - .modify(|w| w.set_ccnp(channel.index(), polarity.into())); - } - - /// Set clock divider for the dead time. - fn set_dead_time_clock_division(&mut self, value: vals::Ckd) { - Self::regs_advanced().cr1().modify(|w| w.set_ckd(value)); - } - - /// Set dead time, as a fraction of the max duty value. - fn set_dead_time_value(&mut self, value: u8) { - Self::regs_advanced().bdtr().modify(|w| w.set_dtg(value)); - } - - /// Enable/disable a complementary channel. - fn enable_complementary_channel(&mut self, channel: Channel, enable: bool) { - Self::regs_advanced() - .ccer() - .modify(|w| w.set_ccne(channel.index(), enable)); - } - } - - /// Capture/Compare 32-bit timer instance. - pub trait CaptureCompare32bitInstance: GeneralPurpose32bitInstance + CaptureCompare16bitInstance { - /// Set comapre value for a channel. - fn set_compare_value(&mut self, channel: Channel, value: u32) { - Self::regs_gp32().ccr(channel.index()).modify(|w| w.set_ccr(value)); - } - - /// Get capture value for a channel. - fn get_capture_value(&mut self, channel: Channel) -> u32 { - Self::regs_gp32().ccr(channel.index()).read().ccr() - } - - /// Get max compare value. This depends on the timer frequency and the clock frequency from RCC. - fn get_max_compare_value(&self) -> u32 { - Self::regs_gp32().arr().read().arr() - } - - /// Get compare value for a channel. - fn get_compare_value(&self, channel: Channel) -> u32 { - Self::regs_gp32().ccr(channel.index()).read().ccr() - } - } -} /// Timer channel. #[derive(Clone, Copy)] @@ -409,321 +41,342 @@ impl Channel { } } -/// Input capture mode. -#[derive(Clone, Copy)] -pub enum InputCaptureMode { - /// Rising edge only. - Rising, - /// Falling edge only. - Falling, - /// Both rising or falling edges. - BothEdges, +/// Amount of bits of a timer. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum TimerBits { + /// 16 bits. + Bits16, + /// 32 bits. + #[cfg(not(stm32l0))] + Bits32, } -/// Input TI selection. -#[derive(Clone, Copy)] -pub enum InputTISelection { - /// Normal - Normal, - /// Alternate - Alternate, - /// TRC - TRC, +struct State { + up_waker: AtomicWaker, + cc_waker: [AtomicWaker; 4], } -impl From for stm32_metapac::timer::vals::CcmrInputCcs { - fn from(tisel: InputTISelection) -> Self { - match tisel { - InputTISelection::Normal => stm32_metapac::timer::vals::CcmrInputCcs::TI4, - InputTISelection::Alternate => stm32_metapac::timer::vals::CcmrInputCcs::TI3, - InputTISelection::TRC => stm32_metapac::timer::vals::CcmrInputCcs::TRC, +impl State { + const fn new() -> Self { + const NEW_AW: AtomicWaker = AtomicWaker::new(); + Self { + up_waker: NEW_AW, + cc_waker: [NEW_AW; 4], } } } -/// Timer counting mode. -#[repr(u8)] -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum CountingMode { - #[default] - /// The timer counts up to the reload value and then resets back to 0. - EdgeAlignedUp, - /// The timer counts down to 0 and then resets back to the reload value. - EdgeAlignedDown, - /// The timer counts up to the reload value and then counts back to 0. +trait SealedInstance: RccPeripheral + Peripheral

{ + /// Async state for this timer + fn state() -> &'static State; +} + +/// Core timer instance. +#[allow(private_bounds)] +pub trait CoreInstance: SealedInstance + 'static { + /// Update Interrupt for this timer. + type UpdateInterrupt: interrupt::typelevel::Interrupt; + + /// Amount of bits this timer has. + const BITS: TimerBits; + + /// Registers for this timer. /// - /// The output compare interrupt flags of channels configured in output are - /// set when the counter is counting down. - CenterAlignedDownInterrupts, - /// The timer counts up to the reload value and then counts back to 0. - /// - /// The output compare interrupt flags of channels configured in output are - /// set when the counter is counting up. - CenterAlignedUpInterrupts, - /// The timer counts up to the reload value and then counts back to 0. - /// - /// The output compare interrupt flags of channels configured in output are - /// set when the counter is counting both up or down. - CenterAlignedBothInterrupts, + /// This is a raw pointer to the register block. The actual register block layout varies depending on the timer type. + fn regs() -> *mut (); +} +/// Cut-down basic timer instance. +pub trait BasicNoCr2Instance: CoreInstance {} +/// Basic timer instance. +pub trait BasicInstance: BasicNoCr2Instance {} + +/// General-purpose 16-bit timer with 1 channel instance. +pub trait GeneralInstance1Channel: CoreInstance { + /// Capture compare interrupt for this timer. + type CaptureCompareInterrupt: interrupt::typelevel::Interrupt; } -impl CountingMode { - /// Return whether this mode is edge-aligned (up or down). - pub fn is_edge_aligned(&self) -> bool { - matches!(self, CountingMode::EdgeAlignedUp | CountingMode::EdgeAlignedDown) - } - - /// Return whether this mode is center-aligned. - pub fn is_center_aligned(&self) -> bool { - matches!( - self, - CountingMode::CenterAlignedDownInterrupts - | CountingMode::CenterAlignedUpInterrupts - | CountingMode::CenterAlignedBothInterrupts - ) - } +/// General-purpose 16-bit timer with 2 channels instance. +pub trait GeneralInstance2Channel: GeneralInstance1Channel { + /// Trigger event interrupt for this timer. + type TriggerInterrupt: interrupt::typelevel::Interrupt; } -impl From for (vals::Cms, vals::Dir) { - fn from(value: CountingMode) -> Self { - match value { - CountingMode::EdgeAlignedUp => (vals::Cms::EDGEALIGNED, vals::Dir::UP), - CountingMode::EdgeAlignedDown => (vals::Cms::EDGEALIGNED, vals::Dir::DOWN), - CountingMode::CenterAlignedDownInterrupts => (vals::Cms::CENTERALIGNED1, vals::Dir::UP), - CountingMode::CenterAlignedUpInterrupts => (vals::Cms::CENTERALIGNED2, vals::Dir::UP), - CountingMode::CenterAlignedBothInterrupts => (vals::Cms::CENTERALIGNED3, vals::Dir::UP), - } - } +// This trait add *extra* methods to GeneralInstance4Channel, +// that GeneralInstance4Channel doesn't use, but the "AdvancedInstance"s need. +// And it's a private trait, so it's content won't leak to outer namespace. +// +// If you want to add a new method to it, please leave a detail comment to explain it. +trait General4ChBlankSealed { + // SimplePwm<'d, T> is implemented for T: GeneralInstance4Channel + // Advanced timers implement this trait, but the output needs to be + // enabled explicitly. + // To support general-purpose and advanced timers, this function is added + // here defaulting to noop and overwritten for advanced timers. + // + // Enable timer outputs. + fn enable_outputs(&self) {} } -impl From<(vals::Cms, vals::Dir)> for CountingMode { - fn from(value: (vals::Cms, vals::Dir)) -> Self { - match value { - (vals::Cms::EDGEALIGNED, vals::Dir::UP) => CountingMode::EdgeAlignedUp, - (vals::Cms::EDGEALIGNED, vals::Dir::DOWN) => CountingMode::EdgeAlignedDown, - (vals::Cms::CENTERALIGNED1, _) => CountingMode::CenterAlignedDownInterrupts, - (vals::Cms::CENTERALIGNED2, _) => CountingMode::CenterAlignedUpInterrupts, - (vals::Cms::CENTERALIGNED3, _) => CountingMode::CenterAlignedBothInterrupts, - } - } +/// General-purpose 16-bit timer with 4 channels instance. +#[allow(private_bounds)] +pub trait GeneralInstance4Channel: BasicInstance + GeneralInstance2Channel + General4ChBlankSealed {} + +/// General-purpose 32-bit timer with 4 channels instance. +pub trait GeneralInstance32bit4Channel: GeneralInstance4Channel {} + +/// Advanced 16-bit timer with 1 channel instance. +pub trait AdvancedInstance1Channel: BasicNoCr2Instance + GeneralInstance1Channel { + /// Communication interrupt for this timer. + type CommunicationInterrupt: interrupt::typelevel::Interrupt; + /// Break input interrupt for this timer. + type BreakInputInterrupt: interrupt::typelevel::Interrupt; } +/// Advanced 16-bit timer with 2 channels instance. -/// Output compare mode. -#[derive(Clone, Copy)] -pub enum OutputCompareMode { - /// The comparison between the output compare register TIMx_CCRx and - /// the counter TIMx_CNT has no effect on the outputs. - /// (this mode is used to generate a timing base). - Frozen, - /// Set channel to active level on match. OCxREF signal is forced high when the - /// counter TIMx_CNT matches the capture/compare register x (TIMx_CCRx). - ActiveOnMatch, - /// Set channel to inactive level on match. OCxREF signal is forced low when the - /// counter TIMx_CNT matches the capture/compare register x (TIMx_CCRx). - InactiveOnMatch, - /// Toggle - OCxREF toggles when TIMx_CNT=TIMx_CCRx. - Toggle, - /// Force inactive level - OCxREF is forced low. - ForceInactive, - /// Force active level - OCxREF is forced high. - ForceActive, - /// PWM mode 1 - In upcounting, channel is active as long as TIMx_CNTTIMx_CCRx else active (OCxREF=1). - PwmMode1, - /// PWM mode 2 - In upcounting, channel is inactive as long as - /// TIMx_CNTTIMx_CCRx else inactive. - PwmMode2, - // TODO: there's more modes here depending on the chip family. -} +pub trait AdvancedInstance2Channel: BasicInstance + GeneralInstance2Channel + AdvancedInstance1Channel {} -impl From for stm32_metapac::timer::vals::Ocm { - fn from(mode: OutputCompareMode) -> Self { - match mode { - OutputCompareMode::Frozen => stm32_metapac::timer::vals::Ocm::FROZEN, - OutputCompareMode::ActiveOnMatch => stm32_metapac::timer::vals::Ocm::ACTIVEONMATCH, - OutputCompareMode::InactiveOnMatch => stm32_metapac::timer::vals::Ocm::INACTIVEONMATCH, - OutputCompareMode::Toggle => stm32_metapac::timer::vals::Ocm::TOGGLE, - OutputCompareMode::ForceInactive => stm32_metapac::timer::vals::Ocm::FORCEINACTIVE, - OutputCompareMode::ForceActive => stm32_metapac::timer::vals::Ocm::FORCEACTIVE, - OutputCompareMode::PwmMode1 => stm32_metapac::timer::vals::Ocm::PWMMODE1, - OutputCompareMode::PwmMode2 => stm32_metapac::timer::vals::Ocm::PWMMODE2, - } - } -} +/// Advanced 16-bit timer with 4 channels instance. +pub trait AdvancedInstance4Channel: AdvancedInstance2Channel + GeneralInstance4Channel {} -/// Timer output pin polarity. -#[derive(Clone, Copy)] -pub enum OutputPolarity { - /// Active high (higher duty value makes the pin spend more time high). - ActiveHigh, - /// Active low (higher duty value makes the pin spend more time low). - ActiveLow, -} +pin_trait!(Channel1Pin, GeneralInstance4Channel); +pin_trait!(Channel2Pin, GeneralInstance4Channel); +pin_trait!(Channel3Pin, GeneralInstance4Channel); +pin_trait!(Channel4Pin, GeneralInstance4Channel); +pin_trait!(ExternalTriggerPin, GeneralInstance4Channel); -impl From for bool { - fn from(mode: OutputPolarity) -> Self { - match mode { - OutputPolarity::ActiveHigh => false, - OutputPolarity::ActiveLow => true, - } - } -} +pin_trait!(Channel1ComplementaryPin, AdvancedInstance4Channel); +pin_trait!(Channel2ComplementaryPin, AdvancedInstance4Channel); +pin_trait!(Channel3ComplementaryPin, AdvancedInstance4Channel); +pin_trait!(Channel4ComplementaryPin, AdvancedInstance4Channel); -/// Basic 16-bit timer instance. -pub trait Basic16bitInstance: sealed::Basic16bitInstance + 'static {} +pin_trait!(BreakInputPin, AdvancedInstance4Channel); +pin_trait!(BreakInput2Pin, AdvancedInstance4Channel); -/// Gneral-purpose 16-bit timer instance. -pub trait GeneralPurpose16bitInstance: sealed::GeneralPurpose16bitInstance + Basic16bitInstance + 'static {} +pin_trait!(BreakInputComparator1Pin, AdvancedInstance4Channel); +pin_trait!(BreakInputComparator2Pin, AdvancedInstance4Channel); -/// Gneral-purpose 32-bit timer instance. -pub trait GeneralPurpose32bitInstance: - sealed::GeneralPurpose32bitInstance + GeneralPurpose16bitInstance + 'static -{ -} +pin_trait!(BreakInput2Comparator1Pin, AdvancedInstance4Channel); +pin_trait!(BreakInput2Comparator2Pin, AdvancedInstance4Channel); -/// Advanced control timer instance. -pub trait AdvancedControlInstance: sealed::AdvancedControlInstance + GeneralPurpose16bitInstance + 'static {} +// Update Event trigger DMA for every timer +dma_trait!(UpDma, BasicInstance); -/// Capture/Compare 16-bit timer instance. -pub trait CaptureCompare16bitInstance: - sealed::CaptureCompare16bitInstance + GeneralPurpose16bitInstance + 'static -{ -} - -/// Capture/Compare 16-bit timer instance with complementary pin support. -pub trait ComplementaryCaptureCompare16bitInstance: - sealed::ComplementaryCaptureCompare16bitInstance + CaptureCompare16bitInstance + AdvancedControlInstance + 'static -{ -} - -/// Capture/Compare 32-bit timer instance. -pub trait CaptureCompare32bitInstance: - sealed::CaptureCompare32bitInstance + CaptureCompare16bitInstance + GeneralPurpose32bitInstance + 'static -{ -} - -pin_trait!(Channel1Pin, CaptureCompare16bitInstance); -pin_trait!(Channel1ComplementaryPin, CaptureCompare16bitInstance); -pin_trait!(Channel2Pin, CaptureCompare16bitInstance); -pin_trait!(Channel2ComplementaryPin, CaptureCompare16bitInstance); -pin_trait!(Channel3Pin, CaptureCompare16bitInstance); -pin_trait!(Channel3ComplementaryPin, CaptureCompare16bitInstance); -pin_trait!(Channel4Pin, CaptureCompare16bitInstance); -pin_trait!(Channel4ComplementaryPin, CaptureCompare16bitInstance); -pin_trait!(ExternalTriggerPin, CaptureCompare16bitInstance); -pin_trait!(BreakInputPin, CaptureCompare16bitInstance); -pin_trait!(BreakInputComparator1Pin, CaptureCompare16bitInstance); -pin_trait!(BreakInputComparator2Pin, CaptureCompare16bitInstance); -pin_trait!(BreakInput2Pin, CaptureCompare16bitInstance); -pin_trait!(BreakInput2Comparator1Pin, CaptureCompare16bitInstance); -pin_trait!(BreakInput2Comparator2Pin, CaptureCompare16bitInstance); +dma_trait!(Ch1Dma, GeneralInstance4Channel); +dma_trait!(Ch2Dma, GeneralInstance4Channel); +dma_trait!(Ch3Dma, GeneralInstance4Channel); +dma_trait!(Ch4Dma, GeneralInstance4Channel); #[allow(unused)] -macro_rules! impl_basic_16bit_timer { - ($inst:ident, $irq:ident) => { - impl sealed::Basic16bitInstance for crate::peripherals::$inst { - type Interrupt = crate::interrupt::typelevel::$irq; +macro_rules! impl_core_timer { + ($inst:ident, $bits:expr) => { + impl SealedInstance for crate::peripherals::$inst { + fn state() -> &'static State { + static STATE: State = State::new(); + &STATE + } + } - fn regs() -> crate::pac::timer::TimBasic { - unsafe { crate::pac::timer::TimBasic::from_ptr(crate::pac::$inst.as_ptr()) } + impl CoreInstance for crate::peripherals::$inst { + type UpdateInterrupt = crate::_generated::peripheral_interrupts::$inst::UP; + + const BITS: TimerBits = $bits; + + fn regs() -> *mut () { + crate::pac::$inst.as_ptr() } } }; } #[allow(unused)] -macro_rules! impl_32bit_timer { +macro_rules! impl_general_1ch { ($inst:ident) => { - impl sealed::GeneralPurpose32bitInstance for crate::peripherals::$inst { - fn regs_gp32() -> crate::pac::timer::TimGp32 { - crate::pac::$inst - } + impl GeneralInstance1Channel for crate::peripherals::$inst { + type CaptureCompareInterrupt = crate::_generated::peripheral_interrupts::$inst::CC; } }; } #[allow(unused)] -macro_rules! impl_compare_capable_16bit { +macro_rules! impl_general_2ch { ($inst:ident) => { - impl sealed::CaptureCompare16bitInstance for crate::peripherals::$inst { - fn enable_outputs(&mut self) {} + impl GeneralInstance2Channel for crate::peripherals::$inst { + type TriggerInterrupt = crate::_generated::peripheral_interrupts::$inst::TRG; + } + }; +} + +#[allow(unused)] +macro_rules! impl_advanced_1ch { + ($inst:ident) => { + impl AdvancedInstance1Channel for crate::peripherals::$inst { + type CommunicationInterrupt = crate::_generated::peripheral_interrupts::$inst::COM; + type BreakInputInterrupt = crate::_generated::peripheral_interrupts::$inst::BRK; + } + }; +} + +// This macro only apply to "AdvancedInstance(s)", +// not "GeneralInstance4Channel" itself. +#[allow(unused)] +macro_rules! impl_general_4ch_blank_sealed { + ($inst:ident) => { + impl General4ChBlankSealed for crate::peripherals::$inst { + fn enable_outputs(&self) { + unsafe { crate::pac::timer::Tim1chCmp::from_ptr(Self::regs()) } + .bdtr() + .modify(|w| w.set_moe(true)); + } } }; } foreach_interrupt! { ($inst:ident, timer, TIM_BASIC, UP, $irq:ident) => { - impl_basic_16bit_timer!($inst, $irq); - impl Basic16bitInstance for crate::peripherals::$inst {} + impl_core_timer!($inst, TimerBits::Bits16); + impl BasicNoCr2Instance for crate::peripherals::$inst {} + impl BasicInstance for crate::peripherals::$inst {} }; - ($inst:ident, timer, TIM_GP16, UP, $irq:ident) => { - impl_basic_16bit_timer!($inst, $irq); - impl_compare_capable_16bit!($inst); - impl Basic16bitInstance for crate::peripherals::$inst {} - impl GeneralPurpose16bitInstance for crate::peripherals::$inst {} - impl CaptureCompare16bitInstance for crate::peripherals::$inst {} - impl sealed::GeneralPurpose16bitInstance for crate::peripherals::$inst { - fn regs_gp16() -> crate::pac::timer::TimGp16 { - crate::pac::$inst - } - } + ($inst:ident, timer, TIM_1CH, UP, $irq:ident) => { + impl_core_timer!($inst, TimerBits::Bits16); + impl BasicNoCr2Instance for crate::peripherals::$inst {} + impl BasicInstance for crate::peripherals::$inst {} + impl_general_1ch!($inst); + impl_general_2ch!($inst); + impl GeneralInstance4Channel for crate::peripherals::$inst {} + impl General4ChBlankSealed for crate::peripherals::$inst {} + }; + + ($inst:ident, timer, TIM_2CH, UP, $irq:ident) => { + impl_core_timer!($inst, TimerBits::Bits16); + impl BasicNoCr2Instance for crate::peripherals::$inst {} + impl BasicInstance for crate::peripherals::$inst {} + impl_general_1ch!($inst); + impl_general_2ch!($inst); + impl GeneralInstance4Channel for crate::peripherals::$inst {} + impl General4ChBlankSealed for crate::peripherals::$inst {} + }; + + ($inst:ident, timer, TIM_GP16, UP, $irq:ident) => { + impl_core_timer!($inst, TimerBits::Bits16); + impl BasicNoCr2Instance for crate::peripherals::$inst {} + impl BasicInstance for crate::peripherals::$inst {} + impl_general_1ch!($inst); + impl_general_2ch!($inst); + impl GeneralInstance4Channel for crate::peripherals::$inst {} + impl General4ChBlankSealed for crate::peripherals::$inst {} }; ($inst:ident, timer, TIM_GP32, UP, $irq:ident) => { - impl_basic_16bit_timer!($inst, $irq); - impl_32bit_timer!($inst); - impl_compare_capable_16bit!($inst); - impl Basic16bitInstance for crate::peripherals::$inst {} - impl CaptureCompare16bitInstance for crate::peripherals::$inst {} - impl CaptureCompare32bitInstance for crate::peripherals::$inst {} - impl GeneralPurpose16bitInstance for crate::peripherals::$inst {} - impl GeneralPurpose32bitInstance for crate::peripherals::$inst {} - impl sealed::CaptureCompare32bitInstance for crate::peripherals::$inst {} + impl_core_timer!($inst, TimerBits::Bits32); + impl BasicNoCr2Instance for crate::peripherals::$inst {} + impl BasicInstance for crate::peripherals::$inst {} + impl_general_1ch!($inst); + impl_general_2ch!($inst); + impl GeneralInstance4Channel for crate::peripherals::$inst {} + impl GeneralInstance32bit4Channel for crate::peripherals::$inst {} + impl General4ChBlankSealed for crate::peripherals::$inst {} + }; - impl sealed::GeneralPurpose16bitInstance for crate::peripherals::$inst { - fn regs_gp16() -> crate::pac::timer::TimGp16 { - unsafe { crate::pac::timer::TimGp16::from_ptr(crate::pac::$inst.as_ptr()) } - } - } + ($inst:ident, timer, TIM_1CH_CMP, UP, $irq:ident) => { + impl_core_timer!($inst, TimerBits::Bits16); + impl BasicNoCr2Instance for crate::peripherals::$inst {} + impl BasicInstance for crate::peripherals::$inst {} + impl_general_1ch!($inst); + impl_general_2ch!($inst); + impl GeneralInstance4Channel for crate::peripherals::$inst {} + impl_general_4ch_blank_sealed!($inst); + impl_advanced_1ch!($inst); + impl AdvancedInstance2Channel for crate::peripherals::$inst {} + impl AdvancedInstance4Channel for crate::peripherals::$inst {} + }; + + ($inst:ident, timer, TIM_2CH_CMP, UP, $irq:ident) => { + impl_core_timer!($inst, TimerBits::Bits16); + impl BasicNoCr2Instance for crate::peripherals::$inst {} + impl BasicInstance for crate::peripherals::$inst {} + impl_general_1ch!($inst); + impl_general_2ch!($inst); + impl GeneralInstance4Channel for crate::peripherals::$inst {} + impl_general_4ch_blank_sealed!($inst); + impl_advanced_1ch!($inst); + impl AdvancedInstance2Channel for crate::peripherals::$inst {} + impl AdvancedInstance4Channel for crate::peripherals::$inst {} }; ($inst:ident, timer, TIM_ADV, UP, $irq:ident) => { - impl_basic_16bit_timer!($inst, $irq); - - impl Basic16bitInstance for crate::peripherals::$inst {} - impl GeneralPurpose16bitInstance for crate::peripherals::$inst {} - impl CaptureCompare16bitInstance for crate::peripherals::$inst {} - impl ComplementaryCaptureCompare16bitInstance for crate::peripherals::$inst {} - impl AdvancedControlInstance for crate::peripherals::$inst {} - impl sealed::CaptureCompare16bitInstance for crate::peripherals::$inst { - fn enable_outputs(&mut self) { - use crate::timer::sealed::AdvancedControlInstance; - let r = Self::regs_advanced(); - r.bdtr().modify(|w| w.set_moe(true)); - } - } - impl sealed::ComplementaryCaptureCompare16bitInstance for crate::peripherals::$inst {} - impl sealed::GeneralPurpose16bitInstance for crate::peripherals::$inst { - fn regs_gp16() -> crate::pac::timer::TimGp16 { - unsafe { crate::pac::timer::TimGp16::from_ptr(crate::pac::$inst.as_ptr()) } - } - } - - impl sealed::AdvancedControlInstance for crate::peripherals::$inst { - fn regs_advanced() -> crate::pac::timer::TimAdv { - crate::pac::$inst - } - } + impl_core_timer!($inst, TimerBits::Bits16); + impl BasicNoCr2Instance for crate::peripherals::$inst {} + impl BasicInstance for crate::peripherals::$inst {} + impl_general_1ch!($inst); + impl_general_2ch!($inst); + impl GeneralInstance4Channel for crate::peripherals::$inst {} + impl_general_4ch_blank_sealed!($inst); + impl_advanced_1ch!($inst); + impl AdvancedInstance2Channel for crate::peripherals::$inst {} + impl AdvancedInstance4Channel for crate::peripherals::$inst {} }; } -// Update Event trigger DMA for every timer -dma_trait!(UpDma, Basic16bitInstance); +/// Update interrupt handler. +pub struct UpdateInterruptHandler { + _phantom: PhantomData, +} -dma_trait!(Ch1Dma, CaptureCompare16bitInstance); -dma_trait!(Ch2Dma, CaptureCompare16bitInstance); -dma_trait!(Ch3Dma, CaptureCompare16bitInstance); -dma_trait!(Ch4Dma, CaptureCompare16bitInstance); +impl interrupt::typelevel::Handler for UpdateInterruptHandler { + unsafe fn on_interrupt() { + #[cfg(feature = "low-power")] + crate::low_power::on_wakeup_irq(); + + let regs = crate::pac::timer::TimCore::from_ptr(T::regs()); + + // Read TIM interrupt flags. + let sr = regs.sr().read(); + + // Mask relevant interrupts (UIE). + let bits = sr.0 & 0x00000001; + + // Mask all the channels that fired. + regs.dier().modify(|w| w.0 &= !bits); + + // Wake the tasks + if sr.uif() { + T::state().up_waker.wake(); + } + } +} + +/// Capture/Compare interrupt handler. +pub struct CaptureCompareInterruptHandler { + _phantom: PhantomData, +} + +impl interrupt::typelevel::Handler + for CaptureCompareInterruptHandler +{ + unsafe fn on_interrupt() { + #[cfg(feature = "low-power")] + crate::low_power::on_wakeup_irq(); + + let regs = crate::pac::timer::TimGp16::from_ptr(T::regs()); + + // Read TIM interrupt flags. + let sr = regs.sr().read(); + + // Mask relevant interrupts (CCIE). + let bits = sr.0 & 0x0000001E; + + // Mask all the channels that fired. + regs.dier().modify(|w| w.0 &= !bits); + + // Wake the tasks + for ch in 0..4 { + if sr.ccif(ch) { + T::state().cc_waker[ch].wake(); + } + } + } +} diff --git a/embassy-stm32/src/timer/pwm_input.rs b/embassy-stm32/src/timer/pwm_input.rs new file mode 100644 index 000000000..e3eb6042a --- /dev/null +++ b/embassy-stm32/src/timer/pwm_input.rs @@ -0,0 +1,114 @@ +//! PWM Input driver. + +use embassy_hal_internal::into_ref; + +use super::low_level::{CountingMode, InputCaptureMode, InputTISelection, SlaveMode, Timer, TriggerSource}; +use super::{Channel, Channel1Pin, Channel2Pin, GeneralInstance4Channel}; +use crate::gpio::{AfType, Pull}; +use crate::time::Hertz; +use crate::Peripheral; + +/// PWM Input driver. +pub struct PwmInput<'d, T: GeneralInstance4Channel> { + channel: Channel, + inner: Timer<'d, T>, +} + +impl<'d, T: GeneralInstance4Channel> PwmInput<'d, T> { + /// Create a new PWM input driver. + pub fn new( + tim: impl Peripheral

+ 'd, + pin: impl Peripheral

> + 'd, + pull: Pull, + freq: Hertz, + ) -> Self { + into_ref!(pin); + + pin.set_as_af(pin.af_num(), AfType::input(pull)); + + Self::new_inner(tim, freq, Channel::Ch1, Channel::Ch2) + } + + /// Create a new PWM input driver. + pub fn new_alt( + tim: impl Peripheral

+ 'd, + pin: impl Peripheral

> + 'd, + pull: Pull, + freq: Hertz, + ) -> Self { + into_ref!(pin); + + pin.set_as_af(pin.af_num(), AfType::input(pull)); + + Self::new_inner(tim, freq, Channel::Ch2, Channel::Ch1) + } + + fn new_inner(tim: impl Peripheral

+ 'd, freq: Hertz, ch1: Channel, ch2: Channel) -> Self { + let mut inner = Timer::new(tim); + + inner.set_counting_mode(CountingMode::EdgeAlignedUp); + inner.set_tick_freq(freq); + inner.enable_outputs(); // Required for advanced timers, see GeneralInstance4Channel for details + inner.start(); + + // Configuration steps from ST RM0390 (STM32F446) chapter 17.3.6 + // or ST RM0008 (STM32F103) chapter 15.3.6 Input capture mode + inner.set_input_ti_selection(ch1, InputTISelection::Normal); + inner.set_input_capture_mode(ch1, InputCaptureMode::Rising); + + inner.set_input_ti_selection(ch2, InputTISelection::Alternate); + inner.set_input_capture_mode(ch2, InputCaptureMode::Falling); + + inner.set_trigger_source(match ch1 { + Channel::Ch1 => TriggerSource::TI1FP1, + Channel::Ch2 => TriggerSource::TI2FP2, + _ => panic!("Invalid channel for PWM input"), + }); + + inner.set_slave_mode(SlaveMode::RESET_MODE); + + // Must call the `enable` function after + + Self { channel: ch1, inner } + } + + /// Enable the given channel. + pub fn enable(&mut self) { + self.inner.enable_channel(Channel::Ch1, true); + self.inner.enable_channel(Channel::Ch2, true); + } + + /// Disable the given channel. + pub fn disable(&mut self) { + self.inner.enable_channel(Channel::Ch1, false); + self.inner.enable_channel(Channel::Ch2, false); + } + + /// Check whether given channel is enabled + pub fn is_enabled(&self) -> bool { + self.inner.get_channel_enable_state(Channel::Ch1) + } + + /// Get the period tick count + pub fn get_period_ticks(&self) -> u32 { + self.inner.get_capture_value(self.channel) + } + + /// Get the pulse width tick count + pub fn get_width_ticks(&self) -> u32 { + self.inner.get_capture_value(match self.channel { + Channel::Ch1 => Channel::Ch2, + Channel::Ch2 => Channel::Ch1, + _ => panic!("Invalid channel for PWM input"), + }) + } + + /// Get the duty cycle in 100% + pub fn get_duty_cycle(&self) -> f32 { + let period = self.get_period_ticks(); + if period == 0 { + return 0.; + } + 100. * (self.get_width_ticks() as f32) / (period as f32) + } +} diff --git a/embassy-stm32/src/timer/qei.rs b/embassy-stm32/src/timer/qei.rs index 59efb72ba..fc5835414 100644 --- a/embassy-stm32/src/timer/qei.rs +++ b/embassy-stm32/src/timer/qei.rs @@ -3,10 +3,11 @@ use core::marker::PhantomData; use embassy_hal_internal::{into_ref, PeripheralRef}; +use stm32_metapac::timer::vals; -use super::*; -use crate::gpio::sealed::AFType; -use crate::gpio::AnyPin; +use super::low_level::Timer; +use super::{Channel1Pin, Channel2Pin, GeneralInstance4Channel}; +use crate::gpio::{AfType, AnyPin, Pull}; use crate::Peripheral; /// Counting direction @@ -30,15 +31,13 @@ pub struct QeiPin<'d, T, Channel> { macro_rules! channel_impl { ($new_chx:ident, $channel:ident, $pin_trait:ident) => { - impl<'d, T: CaptureCompare16bitInstance> QeiPin<'d, T, $channel> { + impl<'d, T: GeneralInstance4Channel> QeiPin<'d, T, $channel> { #[doc = concat!("Create a new ", stringify!($channel), " QEI pin instance.")] pub fn $new_chx(pin: impl Peripheral

> + 'd) -> Self { into_ref!(pin); critical_section::with(|_| { pin.set_low(); - pin.set_as_af(pin.af_num(), AFType::Input); - #[cfg(gpio_v2)] - pin.set_speed(crate::gpio::Speed::VeryHigh); + pin.set_as_af(pin.af_num(), AfType::input(Pull::None)); }); QeiPin { _pin: pin.map_into(), @@ -53,29 +52,28 @@ channel_impl!(new_ch1, Ch1, Channel1Pin); channel_impl!(new_ch2, Ch2, Channel2Pin); /// Quadrature decoder driver. -pub struct Qei<'d, T> { - _inner: PeripheralRef<'d, T>, +pub struct Qei<'d, T: GeneralInstance4Channel> { + inner: Timer<'d, T>, } -impl<'d, T: CaptureCompare16bitInstance> Qei<'d, T> { +impl<'d, T: GeneralInstance4Channel> Qei<'d, T> { /// Create a new quadrature decoder driver. pub fn new(tim: impl Peripheral

+ 'd, _ch1: QeiPin<'d, T, Ch1>, _ch2: QeiPin<'d, T, Ch2>) -> Self { Self::new_inner(tim) } fn new_inner(tim: impl Peripheral

+ 'd) -> Self { - into_ref!(tim); - - T::enable_and_reset(); + let inner = Timer::new(tim); + let r = inner.regs_gp16(); // Configure TxC1 and TxC2 as captures - T::regs_gp16().ccmr_input(0).modify(|w| { + r.ccmr_input(0).modify(|w| { w.set_ccs(0, vals::CcmrInputCcs::TI4); w.set_ccs(1, vals::CcmrInputCcs::TI4); }); // enable and configure to capture on rising edge - T::regs_gp16().ccer().modify(|w| { + r.ccer().modify(|w| { w.set_cce(0, true); w.set_cce(1, true); @@ -83,19 +81,19 @@ impl<'d, T: CaptureCompare16bitInstance> Qei<'d, T> { w.set_ccp(1, false); }); - T::regs_gp16().smcr().modify(|w| { + r.smcr().modify(|w| { w.set_sms(vals::Sms::ENCODER_MODE_3); }); - T::regs_gp16().arr().modify(|w| w.set_arr(u16::MAX)); - T::regs_gp16().cr1().modify(|w| w.set_cen(true)); + r.arr().modify(|w| w.set_arr(u16::MAX)); + r.cr1().modify(|w| w.set_cen(true)); - Self { _inner: tim } + Self { inner } } /// Get direction. pub fn read_direction(&self) -> Direction { - match T::regs_gp16().cr1().read().dir() { + match self.inner.regs_gp16().cr1().read().dir() { vals::Dir::DOWN => Direction::Downcounting, vals::Dir::UP => Direction::Upcounting, } @@ -103,6 +101,6 @@ impl<'d, T: CaptureCompare16bitInstance> Qei<'d, T> { /// Get count. pub fn count(&self) -> u16 { - T::regs_gp16().cnt().read().cnt() + self.inner.regs_gp16().cnt().read().cnt() } } diff --git a/embassy-stm32/src/timer/simple_pwm.rs b/embassy-stm32/src/timer/simple_pwm.rs index 0b4c1225f..9e4a09095 100644 --- a/embassy-stm32/src/timer/simple_pwm.rs +++ b/embassy-stm32/src/timer/simple_pwm.rs @@ -1,13 +1,13 @@ //! Simple PWM driver. use core::marker::PhantomData; +use core::mem::ManuallyDrop; use embassy_hal_internal::{into_ref, PeripheralRef}; -use super::*; -#[allow(unused_imports)] -use crate::gpio::sealed::{AFType, Pin}; -use crate::gpio::{AnyPin, OutputType}; +use super::low_level::{CountingMode, OutputCompareMode, OutputPolarity, Timer}; +use super::{Channel, Channel1Pin, Channel2Pin, Channel3Pin, Channel4Pin, GeneralInstance4Channel}; +use crate::gpio::{AfType, AnyPin, OutputType, Speed}; use crate::time::Hertz; use crate::Peripheral; @@ -30,15 +30,13 @@ pub struct PwmPin<'d, T, C> { macro_rules! channel_impl { ($new_chx:ident, $channel:ident, $pin_trait:ident) => { - impl<'d, T: CaptureCompare16bitInstance> PwmPin<'d, T, $channel> { + impl<'d, T: GeneralInstance4Channel> PwmPin<'d, T, $channel> { #[doc = concat!("Create a new ", stringify!($channel), " PWM pin instance.")] pub fn $new_chx(pin: impl Peripheral

> + 'd, output_type: OutputType) -> Self { into_ref!(pin); critical_section::with(|_| { pin.set_low(); - pin.set_as_af(pin.af_num(), output_type.into()); - #[cfg(gpio_v2)] - pin.set_speed(crate::gpio::Speed::VeryHigh); + pin.set_as_af(pin.af_num(), AfType::output(output_type, Speed::VeryHigh)); }); PwmPin { _pin: pin.map_into(), @@ -54,12 +52,117 @@ channel_impl!(new_ch2, Ch2, Channel2Pin); channel_impl!(new_ch3, Ch3, Channel3Pin); channel_impl!(new_ch4, Ch4, Channel4Pin); -/// Simple PWM driver. -pub struct SimplePwm<'d, T> { - inner: PeripheralRef<'d, T>, +/// A single channel of a pwm, obtained from [`SimplePwm::split`], +/// [`SimplePwm::channel`], [`SimplePwm::ch1`], etc. +/// +/// It is not possible to change the pwm frequency because +/// the frequency configuration is shared with all four channels. +pub struct SimplePwmChannel<'d, T: GeneralInstance4Channel> { + timer: ManuallyDrop>, + channel: Channel, } -impl<'d, T: CaptureCompare16bitInstance> SimplePwm<'d, T> { +// TODO: check for RMW races +impl<'d, T: GeneralInstance4Channel> SimplePwmChannel<'d, T> { + /// Enable the given channel. + pub fn enable(&mut self) { + self.timer.enable_channel(self.channel, true); + } + + /// Disable the given channel. + pub fn disable(&mut self) { + self.timer.enable_channel(self.channel, false); + } + + /// Check whether given channel is enabled + pub fn is_enabled(&self) -> bool { + self.timer.get_channel_enable_state(self.channel) + } + + /// Get max duty value. + /// + /// This value depends on the configured frequency and the timer's clock rate from RCC. + pub fn max_duty_cycle(&self) -> u16 { + let max = self.timer.get_max_compare_value(); + assert!(max < u16::MAX as u32); + max as u16 + 1 + } + + /// Set the duty for a given channel. + /// + /// The value ranges from 0 for 0% duty, to [`max_duty_cycle`](Self::max_duty_cycle) for 100% duty, both included. + pub fn set_duty_cycle(&mut self, duty: u16) { + assert!(duty <= (*self).max_duty_cycle()); + self.timer.set_compare_value(self.channel, duty.into()) + } + + /// Set the duty cycle to 0%, or always inactive. + pub fn set_duty_cycle_fully_off(&mut self) { + self.set_duty_cycle(0); + } + + /// Set the duty cycle to 100%, or always active. + pub fn set_duty_cycle_fully_on(&mut self) { + self.set_duty_cycle((*self).max_duty_cycle()); + } + + /// Set the duty cycle to `num / denom`. + /// + /// The caller is responsible for ensuring that `num` is less than or equal to `denom`, + /// and that `denom` is not zero. + pub fn set_duty_cycle_fraction(&mut self, num: u16, denom: u16) { + assert!(denom != 0); + assert!(num <= denom); + let duty = u32::from(num) * u32::from(self.max_duty_cycle()) / u32::from(denom); + + // This is safe because we know that `num <= denom`, so `duty <= self.max_duty_cycle()` (u16) + #[allow(clippy::cast_possible_truncation)] + self.set_duty_cycle(duty as u16); + } + + /// Set the duty cycle to `percent / 100` + /// + /// The caller is responsible for ensuring that `percent` is less than or equal to 100. + pub fn set_duty_cycle_percent(&mut self, percent: u8) { + self.set_duty_cycle_fraction(u16::from(percent), 100) + } + + /// Get the duty for a given channel. + /// + /// The value ranges from 0 for 0% duty, to [`max_duty_cycle`](Self::max_duty_cycle) for 100% duty, both included. + pub fn current_duty_cycle(&self) -> u16 { + unwrap!(self.timer.get_compare_value(self.channel).try_into()) + } + + /// Set the output polarity for a given channel. + pub fn set_polarity(&mut self, polarity: OutputPolarity) { + self.timer.set_output_polarity(self.channel, polarity); + } + + /// Set the output compare mode for a given channel. + pub fn set_output_compare_mode(&mut self, mode: OutputCompareMode) { + self.timer.set_output_compare_mode(self.channel, mode); + } +} + +/// A group of four [`SimplePwmChannel`]s, obtained from [`SimplePwm::split`]. +pub struct SimplePwmChannels<'d, T: GeneralInstance4Channel> { + /// Channel 1 + pub ch1: SimplePwmChannel<'d, T>, + /// Channel 2 + pub ch2: SimplePwmChannel<'d, T>, + /// Channel 3 + pub ch3: SimplePwmChannel<'d, T>, + /// Channel 4 + pub ch4: SimplePwmChannel<'d, T>, +} + +/// Simple PWM driver. +pub struct SimplePwm<'d, T: GeneralInstance4Channel> { + inner: Timer<'d, T>, +} + +impl<'d, T: GeneralInstance4Channel> SimplePwm<'d, T> { /// Create a new simple PWM driver. pub fn new( tim: impl Peripheral

+ 'd, @@ -74,41 +177,94 @@ impl<'d, T: CaptureCompare16bitInstance> SimplePwm<'d, T> { } fn new_inner(tim: impl Peripheral

+ 'd, freq: Hertz, counting_mode: CountingMode) -> Self { - into_ref!(tim); - - T::enable_and_reset(); - - let mut this = Self { inner: tim }; + let mut this = Self { inner: Timer::new(tim) }; this.inner.set_counting_mode(counting_mode); this.set_frequency(freq); + this.inner.enable_outputs(); // Required for advanced timers, see GeneralInstance4Channel for details this.inner.start(); - this.inner.enable_outputs(); - [Channel::Ch1, Channel::Ch2, Channel::Ch3, Channel::Ch4] .iter() .for_each(|&channel| { this.inner.set_output_compare_mode(channel, OutputCompareMode::PwmMode1); - this.inner.set_output_compare_preload(channel, true) + + this.inner.set_output_compare_preload(channel, true); }); this } - /// Enable the given channel. - pub fn enable(&mut self, channel: Channel) { - self.inner.enable_channel(channel, true); + /// Get a single channel + /// + /// If you need to use multiple channels, use [`Self::split`]. + pub fn channel(&mut self, channel: Channel) -> SimplePwmChannel<'_, T> { + SimplePwmChannel { + timer: unsafe { self.inner.clone_unchecked() }, + channel, + } } - /// Disable the given channel. - pub fn disable(&mut self, channel: Channel) { - self.inner.enable_channel(channel, false); + /// Channel 1 + /// + /// This is just a convenience wrapper around [`Self::channel`]. + /// + /// If you need to use multiple channels, use [`Self::split`]. + pub fn ch1(&mut self) -> SimplePwmChannel<'_, T> { + self.channel(Channel::Ch1) } - /// Check whether given channel is enabled - pub fn is_enabled(&self, channel: Channel) -> bool { - self.inner.get_channel_enable_state(channel) + /// Channel 2 + /// + /// This is just a convenience wrapper around [`Self::channel`]. + /// + /// If you need to use multiple channels, use [`Self::split`]. + pub fn ch2(&mut self) -> SimplePwmChannel<'_, T> { + self.channel(Channel::Ch2) + } + + /// Channel 3 + /// + /// This is just a convenience wrapper around [`Self::channel`]. + /// + /// If you need to use multiple channels, use [`Self::split`]. + pub fn ch3(&mut self) -> SimplePwmChannel<'_, T> { + self.channel(Channel::Ch3) + } + + /// Channel 4 + /// + /// This is just a convenience wrapper around [`Self::channel`]. + /// + /// If you need to use multiple channels, use [`Self::split`]. + pub fn ch4(&mut self) -> SimplePwmChannel<'_, T> { + self.channel(Channel::Ch4) + } + + /// Splits a [`SimplePwm`] into four pwm channels. + /// + /// This returns all four channels, including channels that + /// aren't configured with a [`PwmPin`]. + // TODO: I hate the name "split" + pub fn split(self) -> SimplePwmChannels<'static, T> + where + // must be static because the timer will never be dropped/disabled + 'd: 'static, + { + // without this, the timer would be disabled at the end of this function + let timer = ManuallyDrop::new(self.inner); + + let ch = |channel| SimplePwmChannel { + timer: unsafe { timer.clone_unchecked() }, + channel, + }; + + SimplePwmChannels { + ch1: ch(Channel::Ch1), + ch2: ch(Channel::Ch2), + ch3: ch(Channel::Ch3), + ch4: ch(Channel::Ch4), + } } /// Set PWM frequency. @@ -116,6 +272,7 @@ impl<'d, T: CaptureCompare16bitInstance> SimplePwm<'d, T> { /// Note: when you call this, the max duty value changes, so you will have to /// call `set_duty` on all channels with the duty calculated based on the new max duty. pub fn set_frequency(&mut self, freq: Hertz) { + // TODO: prevent ARR = u16::MAX? let multiplier = if self.inner.get_counting_mode().is_center_aligned() { 2u8 } else { @@ -127,33 +284,10 @@ impl<'d, T: CaptureCompare16bitInstance> SimplePwm<'d, T> { /// Get max duty value. /// /// This value depends on the configured frequency and the timer's clock rate from RCC. - pub fn get_max_duty(&self) -> u16 { - self.inner.get_max_compare_value() + 1 - } - - /// Set the duty for a given channel. - /// - /// The value ranges from 0 for 0% duty, to [`get_max_duty`](Self::get_max_duty) for 100% duty, both included. - pub fn set_duty(&mut self, channel: Channel, duty: u16) { - assert!(duty <= self.get_max_duty()); - self.inner.set_compare_value(channel, duty) - } - - /// Get the duty for a given channel. - /// - /// The value ranges from 0 for 0% duty, to [`get_max_duty`](Self::get_max_duty) for 100% duty, both included. - pub fn get_duty(&self, channel: Channel) -> u16 { - self.inner.get_compare_value(channel) - } - - /// Set the output polarity for a given channel. - pub fn set_polarity(&mut self, channel: Channel, polarity: OutputPolarity) { - self.inner.set_output_polarity(channel, polarity); - } - - /// Set the output compare mode for a given channel. - pub fn set_output_compare_mode(&mut self, channel: Channel, mode: OutputCompareMode) { - self.inner.set_output_compare_mode(channel, mode); + pub fn max_duty_cycle(&self) -> u16 { + let max = self.inner.get_max_compare_value(); + assert!(max < u16::MAX as u32); + max as u16 + 1 } /// Generate a sequence of PWM waveform @@ -166,15 +300,13 @@ impl<'d, T: CaptureCompare16bitInstance> SimplePwm<'d, T> { channel: Channel, duty: &[u16], ) { - assert!(duty.iter().all(|v| *v <= self.get_max_duty())); - into_ref!(dma); #[allow(clippy::let_unit_value)] // eg. stm32f334 let req = dma.request(); - let original_duty_state = self.get_duty(channel); - let original_enable_state = self.is_enabled(channel); + let original_duty_state = self.channel(channel).current_duty_cycle(); + let original_enable_state = self.channel(channel).is_enabled(); let original_update_dma_state = self.inner.get_update_dma_state(); if !original_update_dma_state { @@ -182,7 +314,7 @@ impl<'d, T: CaptureCompare16bitInstance> SimplePwm<'d, T> { } if !original_enable_state { - self.enable(channel); + self.channel(channel).enable(); } unsafe { @@ -202,7 +334,7 @@ impl<'d, T: CaptureCompare16bitInstance> SimplePwm<'d, T> { &mut dma, req, duty, - T::regs_gp16().ccr(channel.index()).as_ptr() as *mut _, + self.inner.regs_1ch().ccr(channel.index()).as_ptr() as *mut _, dma_transfer_option, ) .await @@ -210,10 +342,10 @@ impl<'d, T: CaptureCompare16bitInstance> SimplePwm<'d, T> { // restore output compare state if !original_enable_state { - self.disable(channel); + self.channel(channel).disable(); } - self.set_duty(channel, original_duty_state); + self.channel(channel).set_duty_cycle(original_duty_state); // Since DMA is closed before timer update event trigger DMA is turn off, // this can almost always trigger a DMA FIFO error. @@ -228,25 +360,23 @@ impl<'d, T: CaptureCompare16bitInstance> SimplePwm<'d, T> { macro_rules! impl_waveform_chx { ($fn_name:ident, $dma_ch:ident, $cc_ch:ident) => { - impl<'d, T: CaptureCompare16bitInstance> SimplePwm<'d, T> { + impl<'d, T: GeneralInstance4Channel> SimplePwm<'d, T> { /// Generate a sequence of PWM waveform /// /// Note: /// you will need to provide corresponding TIMx_CHy DMA channel to use this method. pub async fn $fn_name(&mut self, dma: impl Peripheral

>, duty: &[u16]) { - use super::vals::Ccds; - - assert!(duty.iter().all(|v| *v <= self.get_max_duty())); + use crate::pac::timer::vals::Ccds; into_ref!(dma); #[allow(clippy::let_unit_value)] // eg. stm32f334 let req = dma.request(); - let cc_channel = super::Channel::$cc_ch; + let cc_channel = Channel::$cc_ch; - let original_duty_state = self.get_duty(cc_channel); - let original_enable_state = self.is_enabled(cc_channel); + let original_duty_state = self.channel(cc_channel).current_duty_cycle(); + let original_enable_state = self.channel(cc_channel).is_enabled(); let original_cc_dma_on_update = self.inner.get_cc_dma_selection() == Ccds::ONUPDATE; let original_cc_dma_enabled = self.inner.get_cc_dma_enable_state(cc_channel); @@ -260,7 +390,7 @@ macro_rules! impl_waveform_chx { } if !original_enable_state { - self.enable(cc_channel); + self.channel(cc_channel).enable(); } unsafe { @@ -280,7 +410,7 @@ macro_rules! impl_waveform_chx { &mut dma, req, duty, - T::regs_gp16().ccr(cc_channel.index()).as_ptr() as *mut _, + self.inner.regs_gp16().ccr(cc_channel.index()).as_ptr() as *mut _, dma_transfer_option, ) .await @@ -288,10 +418,10 @@ macro_rules! impl_waveform_chx { // restore output compare state if !original_enable_state { - self.disable(cc_channel); + self.channel(cc_channel).disable(); } - self.set_duty(cc_channel, original_duty_state); + self.channel(cc_channel).set_duty_cycle(original_duty_state); // Since DMA is closed before timer Capture Compare Event trigger DMA is turn off, // this can almost always trigger a DMA FIFO error. @@ -315,10 +445,45 @@ impl_waveform_chx!(waveform_ch2, Ch2Dma, Ch2); impl_waveform_chx!(waveform_ch3, Ch3Dma, Ch3); impl_waveform_chx!(waveform_ch4, Ch4Dma, Ch4); -impl<'d, T: CaptureCompare16bitInstance> embedded_hal_02::Pwm for SimplePwm<'d, T> { +impl<'d, T: GeneralInstance4Channel> embedded_hal_1::pwm::ErrorType for SimplePwmChannel<'d, T> { + type Error = core::convert::Infallible; +} + +impl<'d, T: GeneralInstance4Channel> embedded_hal_1::pwm::SetDutyCycle for SimplePwmChannel<'d, T> { + fn max_duty_cycle(&self) -> u16 { + self.max_duty_cycle() + } + + fn set_duty_cycle(&mut self, duty: u16) -> Result<(), Self::Error> { + self.set_duty_cycle(duty); + Ok(()) + } + + fn set_duty_cycle_fully_off(&mut self) -> Result<(), Self::Error> { + self.set_duty_cycle_fully_off(); + Ok(()) + } + + fn set_duty_cycle_fully_on(&mut self) -> Result<(), Self::Error> { + self.set_duty_cycle_fully_on(); + Ok(()) + } + + fn set_duty_cycle_fraction(&mut self, num: u16, denom: u16) -> Result<(), Self::Error> { + self.set_duty_cycle_fraction(num, denom); + Ok(()) + } + + fn set_duty_cycle_percent(&mut self, percent: u8) -> Result<(), Self::Error> { + self.set_duty_cycle_percent(percent); + Ok(()) + } +} + +impl<'d, T: GeneralInstance4Channel> embedded_hal_02::Pwm for SimplePwm<'d, T> { type Channel = Channel; type Time = Hertz; - type Duty = u16; + type Duty = u32; fn disable(&mut self, channel: Self::Channel) { self.inner.enable_channel(channel, false); @@ -341,7 +506,7 @@ impl<'d, T: CaptureCompare16bitInstance> embedded_hal_02::Pwm for SimplePwm<'d, } fn set_duty(&mut self, channel: Self::Channel, duty: Self::Duty) { - assert!(duty <= self.get_max_duty()); + assert!(duty <= self.max_duty_cycle() as u32); self.inner.set_compare_value(channel, duty) } diff --git a/embassy-stm32/src/tsc/enums.rs b/embassy-stm32/src/tsc/enums.rs new file mode 100644 index 000000000..0d34a43ec --- /dev/null +++ b/embassy-stm32/src/tsc/enums.rs @@ -0,0 +1,238 @@ +use core::ops::BitOr; + +/// Pin defines +#[allow(missing_docs)] +pub enum TscIOPin { + Group1Io1, + Group1Io2, + Group1Io3, + Group1Io4, + Group2Io1, + Group2Io2, + Group2Io3, + Group2Io4, + Group3Io1, + Group3Io2, + Group3Io3, + Group3Io4, + Group4Io1, + Group4Io2, + Group4Io3, + Group4Io4, + Group5Io1, + Group5Io2, + Group5Io3, + Group5Io4, + Group6Io1, + Group6Io2, + Group6Io3, + Group6Io4, + #[cfg(any(tsc_v2, tsc_v3))] + Group7Io1, + #[cfg(any(tsc_v2, tsc_v3))] + Group7Io2, + #[cfg(any(tsc_v2, tsc_v3))] + Group7Io3, + #[cfg(any(tsc_v2, tsc_v3))] + Group7Io4, + #[cfg(tsc_v3)] + Group8Io1, + #[cfg(tsc_v3)] + Group8Io2, + #[cfg(tsc_v3)] + Group8Io3, + #[cfg(tsc_v3)] + Group8Io4, +} + +impl BitOr for u32 { + type Output = u32; + fn bitor(self, rhs: TscIOPin) -> Self::Output { + let rhs: u32 = rhs.into(); + self | rhs + } +} + +impl BitOr for TscIOPin { + type Output = u32; + fn bitor(self, rhs: u32) -> Self::Output { + let val: u32 = self.into(); + val | rhs + } +} + +impl BitOr for TscIOPin { + type Output = u32; + fn bitor(self, rhs: Self) -> Self::Output { + let val: u32 = self.into(); + let rhs: u32 = rhs.into(); + val | rhs + } +} + +impl Into for TscIOPin { + fn into(self) -> u32 { + match self { + TscIOPin::Group1Io1 => 0x00000001, + TscIOPin::Group1Io2 => 0x00000002, + TscIOPin::Group1Io3 => 0x00000004, + TscIOPin::Group1Io4 => 0x00000008, + TscIOPin::Group2Io1 => 0x00000010, + TscIOPin::Group2Io2 => 0x00000020, + TscIOPin::Group2Io3 => 0x00000040, + TscIOPin::Group2Io4 => 0x00000080, + TscIOPin::Group3Io1 => 0x00000100, + TscIOPin::Group3Io2 => 0x00000200, + TscIOPin::Group3Io3 => 0x00000400, + TscIOPin::Group3Io4 => 0x00000800, + TscIOPin::Group4Io1 => 0x00001000, + TscIOPin::Group4Io2 => 0x00002000, + TscIOPin::Group4Io3 => 0x00004000, + TscIOPin::Group4Io4 => 0x00008000, + TscIOPin::Group5Io1 => 0x00010000, + TscIOPin::Group5Io2 => 0x00020000, + TscIOPin::Group5Io3 => 0x00040000, + TscIOPin::Group5Io4 => 0x00080000, + TscIOPin::Group6Io1 => 0x00100000, + TscIOPin::Group6Io2 => 0x00200000, + TscIOPin::Group6Io3 => 0x00400000, + TscIOPin::Group6Io4 => 0x00800000, + #[cfg(any(tsc_v2, tsc_v3))] + TscIOPin::Group7Io1 => 0x01000000, + #[cfg(any(tsc_v2, tsc_v3))] + TscIOPin::Group7Io2 => 0x02000000, + #[cfg(any(tsc_v2, tsc_v3))] + TscIOPin::Group7Io3 => 0x04000000, + #[cfg(any(tsc_v2, tsc_v3))] + TscIOPin::Group7Io4 => 0x08000000, + #[cfg(tsc_v3)] + TscIOPin::Group8Io1 => 0x10000000, + #[cfg(tsc_v3)] + TscIOPin::Group8Io2 => 0x20000000, + #[cfg(tsc_v3)] + TscIOPin::Group8Io3 => 0x40000000, + #[cfg(tsc_v3)] + TscIOPin::Group8Io4 => 0x80000000, + } + } +} + +/// Spread Spectrum Deviation +#[derive(Copy, Clone)] +pub struct SSDeviation(u8); +impl SSDeviation { + /// Create new deviation value, acceptable inputs are 1-128 + pub fn new(val: u8) -> Result { + if val == 0 || val > 128 { + return Err(()); + } + Ok(Self(val - 1)) + } +} + +impl Into for SSDeviation { + fn into(self) -> u8 { + self.0 + } +} + +/// Charge transfer pulse cycles +#[allow(missing_docs)] +#[derive(Copy, Clone, PartialEq)] +pub enum ChargeTransferPulseCycle { + _1, + _2, + _3, + _4, + _5, + _6, + _7, + _8, + _9, + _10, + _11, + _12, + _13, + _14, + _15, + _16, +} + +impl Into for ChargeTransferPulseCycle { + fn into(self) -> u8 { + match self { + ChargeTransferPulseCycle::_1 => 0, + ChargeTransferPulseCycle::_2 => 1, + ChargeTransferPulseCycle::_3 => 2, + ChargeTransferPulseCycle::_4 => 3, + ChargeTransferPulseCycle::_5 => 4, + ChargeTransferPulseCycle::_6 => 5, + ChargeTransferPulseCycle::_7 => 6, + ChargeTransferPulseCycle::_8 => 7, + ChargeTransferPulseCycle::_9 => 8, + ChargeTransferPulseCycle::_10 => 9, + ChargeTransferPulseCycle::_11 => 10, + ChargeTransferPulseCycle::_12 => 11, + ChargeTransferPulseCycle::_13 => 12, + ChargeTransferPulseCycle::_14 => 13, + ChargeTransferPulseCycle::_15 => 14, + ChargeTransferPulseCycle::_16 => 15, + } + } +} + +/// Prescaler divider +#[allow(missing_docs)] +#[derive(Copy, Clone, PartialEq)] +pub enum PGPrescalerDivider { + _1, + _2, + _4, + _8, + _16, + _32, + _64, + _128, +} + +impl Into for PGPrescalerDivider { + fn into(self) -> u8 { + match self { + PGPrescalerDivider::_1 => 0, + PGPrescalerDivider::_2 => 1, + PGPrescalerDivider::_4 => 2, + PGPrescalerDivider::_8 => 3, + PGPrescalerDivider::_16 => 4, + PGPrescalerDivider::_32 => 5, + PGPrescalerDivider::_64 => 6, + PGPrescalerDivider::_128 => 7, + } + } +} + +/// Max count +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum MaxCount { + _255, + _511, + _1023, + _2047, + _4095, + _8191, + _16383, +} + +impl Into for MaxCount { + fn into(self) -> u8 { + match self { + MaxCount::_255 => 0, + MaxCount::_511 => 1, + MaxCount::_1023 => 2, + MaxCount::_2047 => 3, + MaxCount::_4095 => 4, + MaxCount::_8191 => 5, + MaxCount::_16383 => 6, + } + } +} diff --git a/embassy-stm32/src/tsc/mod.rs b/embassy-stm32/src/tsc/mod.rs new file mode 100644 index 000000000..17240e6bc --- /dev/null +++ b/embassy-stm32/src/tsc/mod.rs @@ -0,0 +1,1023 @@ +//! TSC Peripheral Interface +//! +//! +//! # Example (stm32) +//! ``` rust, ignore +//! +//! let mut device_config = embassy_stm32::Config::default(); +//! { +//! device_config.rcc.mux = ClockSrc::MSI(Msirange::RANGE_4MHZ); +//! } +//! +//! let context = embassy_stm32::init(device_config); +//! +//! let config = tsc::Config { +//! ct_pulse_high_length: ChargeTransferPulseCycle::_2, +//! ct_pulse_low_length: ChargeTransferPulseCycle::_2, +//! spread_spectrum: false, +//! spread_spectrum_deviation: SSDeviation::new(2).unwrap(), +//! spread_spectrum_prescaler: false, +//! pulse_generator_prescaler: PGPrescalerDivider::_4, +//! max_count_value: MaxCount::_8191, +//! io_default_mode: false, +//! synchro_pin_polarity: false, +//! acquisition_mode: false, +//! max_count_interrupt: false, +//! channel_ios: TscIOPin::Group2Io2 | TscIOPin::Group7Io3, +//! shield_ios: TscIOPin::Group1Io3.into(), +//! sampling_ios: TscIOPin::Group1Io2 | TscIOPin::Group2Io1 | TscIOPin::Group7Io2, +//! }; +//! +//! let mut g1: PinGroup = PinGroup::new(); +//! g1.set_io2(context.PB13, PinType::Sample); +//! g1.set_io3(context.PB14, PinType::Shield); +//! +//! let mut g2: PinGroup = PinGroup::new(); +//! g2.set_io1(context.PB4, PinType::Sample); +//! g2.set_io2(context.PB5, PinType::Channel); +//! +//! let mut g7: PinGroup = PinGroup::new(); +//! g7.set_io2(context.PE3, PinType::Sample); +//! g7.set_io3(context.PE4, PinType::Channel); +//! +//! let mut touch_controller = tsc::Tsc::new_blocking( +//! context.TSC, +//! Some(g1), +//! Some(g2), +//! None, +//! None, +//! None, +//! None, +//! Some(g7), +//! None, +//! config, +//! ); +//! +//! touch_controller.discharge_io(true); +//! Timer::after_millis(1).await; +//! +//! touch_controller.start(); +//! +//! ``` + +#![macro_use] + +/// Enums defined for peripheral parameters +pub mod enums; + +use core::future::poll_fn; +use core::marker::PhantomData; +use core::task::Poll; + +use embassy_hal_internal::{into_ref, PeripheralRef}; +use embassy_sync::waitqueue::AtomicWaker; +pub use enums::*; + +use crate::gpio::{AfType, AnyPin, OutputType, Speed}; +use crate::interrupt::typelevel::Interrupt; +use crate::mode::{Async, Blocking, Mode as PeriMode}; +use crate::rcc::{self, RccPeripheral}; +use crate::{interrupt, peripherals, Peripheral}; + +#[cfg(tsc_v1)] +const TSC_NUM_GROUPS: u32 = 6; +#[cfg(tsc_v2)] +const TSC_NUM_GROUPS: u32 = 7; +#[cfg(tsc_v3)] +const TSC_NUM_GROUPS: u32 = 8; + +/// Error type defined for TSC +#[derive(Debug, Clone, Copy)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Error { + /// Test error for TSC + Test, +} + +/// TSC interrupt handler. +pub struct InterruptHandler { + _phantom: PhantomData, +} + +impl interrupt::typelevel::Handler for InterruptHandler { + unsafe fn on_interrupt() { + T::regs().ier().write(|w| w.set_eoaie(false)); + T::waker().wake(); + } +} + +/// Pin type definition to control IO parameters +pub enum PinType { + /// Sensing channel pin connected to an electrode + Channel, + /// Sampling capacitor pin, one required for every pin group + Sample, + /// Shield pin connected to capacitive sensing shield + Shield, +} + +/// Peripheral state +#[derive(PartialEq, Clone, Copy)] +pub enum State { + /// Peripheral is being setup or reconfigured + Reset, + /// Ready to start acquisition + Ready, + /// In process of sensor acquisition + Busy, + /// Error occured during acquisition + Error, +} + +/// Individual group status checked after acquisition reported as complete +/// For groups with multiple channel pins, may take longer because acquisitions +/// are done sequentially. Check this status before pulling count for each +/// sampled channel +#[derive(PartialEq)] +pub enum GroupStatus { + /// Acquisition for channel still in progress + Ongoing, + /// Acquisition either not started or complete + Complete, +} + +/// Group identifier used to interrogate status +#[allow(missing_docs)] +pub enum Group { + One, + Two, + Three, + Four, + Five, + Six, + #[cfg(any(tsc_v2, tsc_v3))] + Seven, + #[cfg(tsc_v3)] + Eight, +} + +impl Into for Group { + fn into(self) -> usize { + match self { + Group::One => 0, + Group::Two => 1, + Group::Three => 2, + Group::Four => 3, + Group::Five => 4, + Group::Six => 5, + #[cfg(any(tsc_v2, tsc_v3))] + Group::Seven => 6, + #[cfg(tsc_v3)] + Group::Eight => 7, + } + } +} + +/// Peripheral configuration +#[derive(Clone, Copy)] +pub struct Config { + /// Duration of high state of the charge transfer pulse + pub ct_pulse_high_length: ChargeTransferPulseCycle, + /// Duration of the low state of the charge transfer pulse + pub ct_pulse_low_length: ChargeTransferPulseCycle, + /// Enable/disable of spread spectrum feature + pub spread_spectrum: bool, + /// Adds variable number of periods of the SS clk to pulse high state + pub spread_spectrum_deviation: SSDeviation, + /// Selects AHB clock divider used to generate SS clk + pub spread_spectrum_prescaler: bool, + /// Selects AHB clock divider used to generate pulse generator clk + pub pulse_generator_prescaler: PGPrescalerDivider, + /// Maximum number of charge transfer pulses that can be generated before error + pub max_count_value: MaxCount, + /// Defines config of all IOs when no ongoing acquisition + pub io_default_mode: bool, + /// Polarity of sync input pin + pub synchro_pin_polarity: bool, + /// Acquisition starts when start bit is set or with sync pin input + pub acquisition_mode: bool, + /// Enable max count interrupt + pub max_count_interrupt: bool, + /// Channel IO mask + pub channel_ios: u32, + /// Shield IO mask + pub shield_ios: u32, + /// Sampling IO mask + pub sampling_ios: u32, +} + +impl Default for Config { + fn default() -> Self { + Self { + ct_pulse_high_length: ChargeTransferPulseCycle::_1, + ct_pulse_low_length: ChargeTransferPulseCycle::_1, + spread_spectrum: false, + spread_spectrum_deviation: SSDeviation::new(1).unwrap(), + spread_spectrum_prescaler: false, + pulse_generator_prescaler: PGPrescalerDivider::_1, + max_count_value: MaxCount::_255, + io_default_mode: false, + synchro_pin_polarity: false, + acquisition_mode: false, + max_count_interrupt: false, + channel_ios: 0, + shield_ios: 0, + sampling_ios: 0, + } + } +} + +/// Pin struct that maintains usage +#[allow(missing_docs)] +pub struct TscPin<'d, T, C> { + _pin: PeripheralRef<'d, AnyPin>, + role: PinType, + phantom: PhantomData<(T, C)>, +} + +enum GroupError { + NoSample, + ChannelShield, +} + +/// Pin group definition +/// Pins are organized into groups of four IOs, all groups with a +/// sampling channel must also have a sampling capacitor channel. +#[allow(missing_docs)] +#[derive(Default)] +pub struct PinGroup<'d, T, C> { + d1: Option>, + d2: Option>, + d3: Option>, + d4: Option>, +} + +impl<'d, T: Instance, C> PinGroup<'d, T, C> { + /// Create new sensing group + pub fn new() -> Self { + Self { + d1: None, + d2: None, + d3: None, + d4: None, + } + } + + fn contains_shield(&self) -> bool { + let mut shield_count = 0; + + if let Some(pin) = &self.d1 { + if let PinType::Shield = pin.role { + shield_count += 1; + } + } + + if let Some(pin) = &self.d2 { + if let PinType::Shield = pin.role { + shield_count += 1; + } + } + + if let Some(pin) = &self.d3 { + if let PinType::Shield = pin.role { + shield_count += 1; + } + } + + if let Some(pin) = &self.d4 { + if let PinType::Shield = pin.role { + shield_count += 1; + } + } + + shield_count == 1 + } + + fn check_group(&self) -> Result<(), GroupError> { + let mut channel_count = 0; + let mut shield_count = 0; + let mut sample_count = 0; + if let Some(pin) = &self.d1 { + match pin.role { + PinType::Channel => { + channel_count += 1; + } + PinType::Shield => { + shield_count += 1; + } + PinType::Sample => { + sample_count += 1; + } + } + } + + if let Some(pin) = &self.d2 { + match pin.role { + PinType::Channel => { + channel_count += 1; + } + PinType::Shield => { + shield_count += 1; + } + PinType::Sample => { + sample_count += 1; + } + } + } + + if let Some(pin) = &self.d3 { + match pin.role { + PinType::Channel => { + channel_count += 1; + } + PinType::Shield => { + shield_count += 1; + } + PinType::Sample => { + sample_count += 1; + } + } + } + + if let Some(pin) = &self.d4 { + match pin.role { + PinType::Channel => { + channel_count += 1; + } + PinType::Shield => { + shield_count += 1; + } + PinType::Sample => { + sample_count += 1; + } + } + } + + // Every group requires one sampling capacitor + if sample_count != 1 { + return Err(GroupError::NoSample); + } + + // Each group must have at least one shield or channel IO + if shield_count == 0 && channel_count == 0 { + return Err(GroupError::ChannelShield); + } + + // Any group can either contain channel ios or a shield IO + if shield_count != 0 && channel_count != 0 { + return Err(GroupError::ChannelShield); + } + + // No more than one shield IO is allow per group and amongst all groups + if shield_count > 1 { + return Err(GroupError::ChannelShield); + } + + Ok(()) + } +} + +macro_rules! group_impl { + ($group:ident, $trait1:ident, $trait2:ident, $trait3:ident, $trait4:ident) => { + impl<'d, T: Instance> PinGroup<'d, T, $group> { + #[doc = concat!("Create a new pin1 for ", stringify!($group), " TSC group instance.")] + pub fn set_io1(&mut self, pin: impl Peripheral

> + 'd, role: PinType) { + into_ref!(pin); + critical_section::with(|_| { + pin.set_low(); + pin.set_as_af( + pin.af_num(), + AfType::output( + match role { + PinType::Channel => OutputType::PushPull, + PinType::Sample => OutputType::OpenDrain, + PinType::Shield => OutputType::PushPull, + }, + Speed::VeryHigh, + ), + ); + self.d1 = Some(TscPin { + _pin: pin.map_into(), + role: role, + phantom: PhantomData, + }) + }) + } + + #[doc = concat!("Create a new pin2 for ", stringify!($group), " TSC group instance.")] + pub fn set_io2(&mut self, pin: impl Peripheral

> + 'd, role: PinType) { + into_ref!(pin); + critical_section::with(|_| { + pin.set_low(); + pin.set_as_af( + pin.af_num(), + AfType::output( + match role { + PinType::Channel => OutputType::PushPull, + PinType::Sample => OutputType::OpenDrain, + PinType::Shield => OutputType::PushPull, + }, + Speed::VeryHigh, + ), + ); + self.d2 = Some(TscPin { + _pin: pin.map_into(), + role: role, + phantom: PhantomData, + }) + }) + } + + #[doc = concat!("Create a new pin3 for ", stringify!($group), " TSC group instance.")] + pub fn set_io3(&mut self, pin: impl Peripheral

> + 'd, role: PinType) { + into_ref!(pin); + critical_section::with(|_| { + pin.set_low(); + pin.set_as_af( + pin.af_num(), + AfType::output( + match role { + PinType::Channel => OutputType::PushPull, + PinType::Sample => OutputType::OpenDrain, + PinType::Shield => OutputType::PushPull, + }, + Speed::VeryHigh, + ), + ); + self.d3 = Some(TscPin { + _pin: pin.map_into(), + role: role, + phantom: PhantomData, + }) + }) + } + + #[doc = concat!("Create a new pin4 for ", stringify!($group), " TSC group instance.")] + pub fn set_io4(&mut self, pin: impl Peripheral

> + 'd, role: PinType) { + into_ref!(pin); + critical_section::with(|_| { + pin.set_low(); + pin.set_as_af( + pin.af_num(), + AfType::output( + match role { + PinType::Channel => OutputType::PushPull, + PinType::Sample => OutputType::OpenDrain, + PinType::Shield => OutputType::PushPull, + }, + Speed::VeryHigh, + ), + ); + self.d4 = Some(TscPin { + _pin: pin.map_into(), + role: role, + phantom: PhantomData, + }) + }) + } + } + }; +} + +group_impl!(G1, G1IO1Pin, G1IO2Pin, G1IO3Pin, G1IO4Pin); +group_impl!(G2, G2IO1Pin, G2IO2Pin, G2IO3Pin, G2IO4Pin); +group_impl!(G3, G3IO1Pin, G3IO2Pin, G3IO3Pin, G3IO4Pin); +group_impl!(G4, G4IO1Pin, G4IO2Pin, G4IO3Pin, G4IO4Pin); +group_impl!(G5, G5IO1Pin, G5IO2Pin, G5IO3Pin, G5IO4Pin); +group_impl!(G6, G6IO1Pin, G6IO2Pin, G6IO3Pin, G6IO4Pin); +group_impl!(G7, G7IO1Pin, G7IO2Pin, G7IO3Pin, G7IO4Pin); +group_impl!(G8, G8IO1Pin, G8IO2Pin, G8IO3Pin, G8IO4Pin); + +/// Group 1 marker type. +pub enum G1 {} +/// Group 2 marker type. +pub enum G2 {} +/// Group 3 marker type. +pub enum G3 {} +/// Group 4 marker type. +pub enum G4 {} +/// Group 5 marker type. +pub enum G5 {} +/// Group 6 marker type. +pub enum G6 {} +/// Group 7 marker type. +pub enum G7 {} +/// Group 8 marker type. +pub enum G8 {} + +/// TSC driver +pub struct Tsc<'d, T: Instance, K: PeriMode> { + _peri: PeripheralRef<'d, T>, + _g1: Option>, + _g2: Option>, + _g3: Option>, + _g4: Option>, + _g5: Option>, + _g6: Option>, + #[cfg(any(tsc_v2, tsc_v3))] + _g7: Option>, + #[cfg(tsc_v3)] + _g8: Option>, + state: State, + config: Config, + _kind: PhantomData, +} + +impl<'d, T: Instance> Tsc<'d, T, Async> { + /// Create a Tsc instance that can be awaited for completion + pub fn new_async( + peri: impl Peripheral

+ 'd, + g1: Option>, + g2: Option>, + g3: Option>, + g4: Option>, + g5: Option>, + g6: Option>, + #[cfg(any(tsc_v2, tsc_v3))] g7: Option>, + #[cfg(tsc_v3)] g8: Option>, + config: Config, + _irq: impl interrupt::typelevel::Binding> + 'd, + ) -> Self { + // Need to check valid pin configuration input + let g1 = g1.filter(|b| b.check_group().is_ok()); + let g2 = g2.filter(|b| b.check_group().is_ok()); + let g3 = g3.filter(|b| b.check_group().is_ok()); + let g4 = g4.filter(|b| b.check_group().is_ok()); + let g5 = g5.filter(|b| b.check_group().is_ok()); + let g6 = g6.filter(|b| b.check_group().is_ok()); + #[cfg(any(tsc_v2, tsc_v3))] + let g7 = g7.filter(|b| b.check_group().is_ok()); + #[cfg(tsc_v3)] + let g8 = g8.filter(|b| b.check_group().is_ok()); + + match Self::check_shields( + &g1, + &g2, + &g3, + &g4, + &g5, + &g6, + #[cfg(any(tsc_v2, tsc_v3))] + &g7, + #[cfg(tsc_v3)] + &g8, + ) { + Ok(()) => Self::new_inner( + peri, + g1, + g2, + g3, + g4, + g5, + g6, + #[cfg(any(tsc_v2, tsc_v3))] + g7, + #[cfg(tsc_v3)] + g8, + config, + ), + Err(_) => Self::new_inner( + peri, + None, + None, + None, + None, + None, + None, + #[cfg(any(tsc_v2, tsc_v3))] + None, + #[cfg(tsc_v3)] + None, + config, + ), + } + } + /// Asyncronously wait for the end of an acquisition + pub async fn pend_for_acquisition(&mut self) { + poll_fn(|cx| match self.get_state() { + State::Busy => { + T::waker().register(cx.waker()); + T::regs().ier().write(|w| w.set_eoaie(true)); + if self.get_state() != State::Busy { + T::regs().ier().write(|w| w.set_eoaie(false)); + return Poll::Ready(()); + } + Poll::Pending + } + _ => { + T::regs().ier().write(|w| w.set_eoaie(false)); + Poll::Ready(()) + } + }) + .await; + } +} + +impl<'d, T: Instance> Tsc<'d, T, Blocking> { + /// Create a Tsc instance that must be polled for completion + pub fn new_blocking( + peri: impl Peripheral

+ 'd, + g1: Option>, + g2: Option>, + g3: Option>, + g4: Option>, + g5: Option>, + g6: Option>, + #[cfg(any(tsc_v2, tsc_v3))] g7: Option>, + #[cfg(tsc_v3)] g8: Option>, + config: Config, + ) -> Self { + // Need to check valid pin configuration input + let g1 = g1.filter(|b| b.check_group().is_ok()); + let g2 = g2.filter(|b| b.check_group().is_ok()); + let g3 = g3.filter(|b| b.check_group().is_ok()); + let g4 = g4.filter(|b| b.check_group().is_ok()); + let g5 = g5.filter(|b| b.check_group().is_ok()); + let g6 = g6.filter(|b| b.check_group().is_ok()); + #[cfg(any(tsc_v2, tsc_v3))] + let g7 = g7.filter(|b| b.check_group().is_ok()); + #[cfg(tsc_v3)] + let g8 = g8.filter(|b| b.check_group().is_ok()); + + match Self::check_shields( + &g1, + &g2, + &g3, + &g4, + &g5, + &g6, + #[cfg(any(tsc_v2, tsc_v3))] + &g7, + #[cfg(tsc_v3)] + &g8, + ) { + Ok(()) => Self::new_inner( + peri, + g1, + g2, + g3, + g4, + g5, + g6, + #[cfg(any(tsc_v2, tsc_v3))] + g7, + #[cfg(tsc_v3)] + g8, + config, + ), + Err(_) => Self::new_inner( + peri, + None, + None, + None, + None, + None, + None, + #[cfg(any(tsc_v2, tsc_v3))] + None, + #[cfg(tsc_v3)] + None, + config, + ), + } + } + /// Wait for end of acquisition + pub fn poll_for_acquisition(&mut self) { + while self.get_state() == State::Busy {} + } +} + +impl<'d, T: Instance, K: PeriMode> Tsc<'d, T, K> { + /// Create new TSC driver + fn check_shields( + g1: &Option>, + g2: &Option>, + g3: &Option>, + g4: &Option>, + g5: &Option>, + g6: &Option>, + #[cfg(any(tsc_v2, tsc_v3))] g7: &Option>, + #[cfg(tsc_v3)] g8: &Option>, + ) -> Result<(), GroupError> { + let mut shield_count = 0; + + if let Some(pin_group) = g1 { + if pin_group.contains_shield() { + shield_count += 1; + } + }; + if let Some(pin_group) = g2 { + if pin_group.contains_shield() { + shield_count += 1; + } + }; + if let Some(pin_group) = g3 { + if pin_group.contains_shield() { + shield_count += 1; + } + }; + if let Some(pin_group) = g4 { + if pin_group.contains_shield() { + shield_count += 1; + } + }; + if let Some(pin_group) = g5 { + if pin_group.contains_shield() { + shield_count += 1; + } + }; + if let Some(pin_group) = g6 { + if pin_group.contains_shield() { + shield_count += 1; + } + }; + #[cfg(any(tsc_v2, tsc_v3))] + if let Some(pin_group) = g7 { + if pin_group.contains_shield() { + shield_count += 1; + } + }; + #[cfg(tsc_v3)] + if let Some(pin_group) = g8 { + if pin_group.contains_shield() { + shield_count += 1; + } + }; + + if shield_count > 1 { + return Err(GroupError::ChannelShield); + } + + Ok(()) + } + + fn extract_groups(io_mask: u32) -> u32 { + let mut groups: u32 = 0; + for idx in 0..TSC_NUM_GROUPS { + if io_mask & (0x0F << idx * 4) != 0 { + groups |= 1 << idx + } + } + groups + } + + fn new_inner( + peri: impl Peripheral

+ 'd, + g1: Option>, + g2: Option>, + g3: Option>, + g4: Option>, + g5: Option>, + g6: Option>, + #[cfg(any(tsc_v2, tsc_v3))] g7: Option>, + #[cfg(tsc_v3)] g8: Option>, + config: Config, + ) -> Self { + into_ref!(peri); + + rcc::enable_and_reset::(); + + T::regs().cr().modify(|w| { + w.set_tsce(true); + w.set_ctph(config.ct_pulse_high_length.into()); + w.set_ctpl(config.ct_pulse_low_length.into()); + w.set_sse(config.spread_spectrum); + // Prevent invalid configuration for pulse generator prescaler + if config.ct_pulse_low_length == ChargeTransferPulseCycle::_1 + && (config.pulse_generator_prescaler == PGPrescalerDivider::_1 + || config.pulse_generator_prescaler == PGPrescalerDivider::_2) + { + w.set_pgpsc(PGPrescalerDivider::_4.into()); + } else if config.ct_pulse_low_length == ChargeTransferPulseCycle::_2 + && config.pulse_generator_prescaler == PGPrescalerDivider::_1 + { + w.set_pgpsc(PGPrescalerDivider::_2.into()); + } else { + w.set_pgpsc(config.pulse_generator_prescaler.into()); + } + w.set_ssd(config.spread_spectrum_deviation.into()); + w.set_sspsc(config.spread_spectrum_prescaler); + + w.set_mcv(config.max_count_value.into()); + w.set_syncpol(config.synchro_pin_polarity); + w.set_am(config.acquisition_mode); + }); + + // Set IO configuration + // Disable Schmitt trigger hysteresis on all used TSC IOs + T::regs() + .iohcr() + .write(|w| w.0 = !(config.channel_ios | config.shield_ios | config.sampling_ios)); + + // Set channel and shield IOs + T::regs() + .ioccr() + .write(|w| w.0 = config.channel_ios | config.shield_ios); + + // Set sampling IOs + T::regs().ioscr().write(|w| w.0 = config.sampling_ios); + + // Set the groups to be acquired + T::regs() + .iogcsr() + .write(|w| w.0 = Self::extract_groups(config.channel_ios)); + + // Disable interrupts + T::regs().ier().modify(|w| { + w.set_eoaie(false); + w.set_mceie(false); + }); + + // Clear flags + T::regs().icr().modify(|w| { + w.set_eoaic(true); + w.set_mceic(true); + }); + + unsafe { + T::Interrupt::enable(); + } + + Self { + _peri: peri, + _g1: g1, + _g2: g2, + _g3: g3, + _g4: g4, + _g5: g5, + _g6: g6, + #[cfg(any(tsc_v2, tsc_v3))] + _g7: g7, + #[cfg(tsc_v3)] + _g8: g8, + state: State::Ready, + config, + _kind: PhantomData, + } + } + + /// Start charge transfer acquisition + pub fn start(&mut self) { + self.state = State::Busy; + + // Disable interrupts + T::regs().ier().modify(|w| { + w.set_eoaie(false); + w.set_mceie(false); + }); + + // Clear flags + T::regs().icr().modify(|w| { + w.set_eoaic(true); + w.set_mceic(true); + }); + + // Set the touch sensing IOs not acquired to the default mode + T::regs().cr().modify(|w| { + w.set_iodef(self.config.io_default_mode); + }); + + // Start the acquisition + T::regs().cr().modify(|w| { + w.set_start(true); + }); + } + + /// Stop charge transfer acquisition + pub fn stop(&mut self) { + T::regs().cr().modify(|w| { + w.set_start(false); + }); + + // Set the touch sensing IOs in low power mode + T::regs().cr().modify(|w| { + w.set_iodef(false); + }); + + // Clear flags + T::regs().icr().modify(|w| { + w.set_eoaic(true); + w.set_mceic(true); + }); + + self.state = State::Ready; + } + + /// Get current state of acquisition + pub fn get_state(&mut self) -> State { + if self.state == State::Busy { + if T::regs().isr().read().eoaf() { + if T::regs().isr().read().mcef() { + self.state = State::Error + } else { + self.state = State::Ready + } + } + } + self.state + } + + /// Get the individual group status to check acquisition complete + pub fn group_get_status(&mut self, index: Group) -> GroupStatus { + // Status bits are set by hardware when the acquisition on the corresponding + // enabled analog IO group is complete, cleared when new acquisition is started + let status = match index { + Group::One => T::regs().iogcsr().read().g1s(), + Group::Two => T::regs().iogcsr().read().g2s(), + Group::Three => T::regs().iogcsr().read().g3s(), + Group::Four => T::regs().iogcsr().read().g4s(), + Group::Five => T::regs().iogcsr().read().g5s(), + Group::Six => T::regs().iogcsr().read().g6s(), + #[cfg(any(tsc_v2, tsc_v3))] + Group::Seven => T::regs().iogcsr().read().g7s(), + #[cfg(tsc_v3)] + Group::Eight => T::regs().iogcsr().read().g8s(), + }; + match status { + true => GroupStatus::Complete, + false => GroupStatus::Ongoing, + } + } + + /// Get the count for the acquisiton, valid once group status is set + pub fn group_get_value(&mut self, index: Group) -> u16 { + T::regs().iogcr(index.into()).read().cnt() + } + + /// Discharge the IOs for subsequent acquisition + pub fn discharge_io(&mut self, status: bool) { + // Set the touch sensing IOs in low power mode + T::regs().cr().modify(|w| { + w.set_iodef(!status); + }); + } +} + +impl<'d, T: Instance, K: PeriMode> Drop for Tsc<'d, T, K> { + fn drop(&mut self) { + rcc::disable::(); + } +} + +pub(crate) trait SealedInstance { + fn regs() -> crate::pac::tsc::Tsc; + fn waker() -> &'static AtomicWaker; +} + +/// TSC instance trait +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + RccPeripheral { + /// Interrupt for this TSC instance + type Interrupt: interrupt::typelevel::Interrupt; +} + +foreach_interrupt!( + ($inst:ident, tsc, TSC, GLOBAL, $irq:ident) => { + impl Instance for peripherals::$inst { + type Interrupt = crate::interrupt::typelevel::$irq; + } + + impl SealedInstance for peripherals::$inst { + fn regs() -> crate::pac::tsc::Tsc { + crate::pac::$inst + } + fn waker() -> &'static AtomicWaker { + static WAKER: AtomicWaker = AtomicWaker::new(); + &WAKER + } + } + }; +); + +pin_trait!(G1IO1Pin, Instance); +pin_trait!(G1IO2Pin, Instance); +pin_trait!(G1IO3Pin, Instance); +pin_trait!(G1IO4Pin, Instance); +pin_trait!(G2IO1Pin, Instance); +pin_trait!(G2IO2Pin, Instance); +pin_trait!(G2IO3Pin, Instance); +pin_trait!(G2IO4Pin, Instance); +pin_trait!(G3IO1Pin, Instance); +pin_trait!(G3IO2Pin, Instance); +pin_trait!(G3IO3Pin, Instance); +pin_trait!(G3IO4Pin, Instance); +pin_trait!(G4IO1Pin, Instance); +pin_trait!(G4IO2Pin, Instance); +pin_trait!(G4IO3Pin, Instance); +pin_trait!(G4IO4Pin, Instance); +pin_trait!(G5IO1Pin, Instance); +pin_trait!(G5IO2Pin, Instance); +pin_trait!(G5IO3Pin, Instance); +pin_trait!(G5IO4Pin, Instance); +pin_trait!(G6IO1Pin, Instance); +pin_trait!(G6IO2Pin, Instance); +pin_trait!(G6IO3Pin, Instance); +pin_trait!(G6IO4Pin, Instance); +pin_trait!(G7IO1Pin, Instance); +pin_trait!(G7IO2Pin, Instance); +pin_trait!(G7IO3Pin, Instance); +pin_trait!(G7IO4Pin, Instance); +pin_trait!(G8IO1Pin, Instance); +pin_trait!(G8IO2Pin, Instance); +pin_trait!(G8IO3Pin, Instance); +pin_trait!(G8IO4Pin, Instance); diff --git a/embassy-stm32/src/ucpd.rs b/embassy-stm32/src/ucpd.rs new file mode 100644 index 000000000..ee0a2c7c1 --- /dev/null +++ b/embassy-stm32/src/ucpd.rs @@ -0,0 +1,669 @@ +//! USB Type-C/USB Power Delivery Interface (UCPD) + +// Implementation Notes +// +// As of Feb. 2024 the UCPD peripheral is availalbe on: G0, G4, H5, L5, U5 +// +// Cube HAL LL Driver (g0): +// https://github.com/STMicroelectronics/stm32g0xx_hal_driver/blob/v1.4.6/Inc/stm32g0xx_ll_ucpd.h +// https://github.com/STMicroelectronics/stm32g0xx_hal_driver/blob/v1.4.6/Src/stm32g0xx_ll_ucpd.c +// Except for a the `LL_UCPD_RxAnalogFilterEnable/Disable()` functions the Cube HAL implementation of +// all families is the same. +// +// Dead battery pull-down resistors functionality is enabled by default on startup and must +// be disabled by setting a bit in PWR/SYSCFG registers. The exact name and location for that +// bit is different for each familily. + +use core::future::poll_fn; +use core::marker::PhantomData; +use core::sync::atomic::{AtomicBool, Ordering}; +use core::task::Poll; + +use embassy_hal_internal::drop::OnDrop; +use embassy_hal_internal::{into_ref, Peripheral}; +use embassy_sync::waitqueue::AtomicWaker; + +use crate::dma::{ChannelAndRequest, TransferOptions}; +use crate::interrupt; +use crate::interrupt::typelevel::Interrupt; +use crate::pac::ucpd::vals::{Anamode, Ccenable, PscUsbpdclk, Txmode}; +pub use crate::pac::ucpd::vals::{Phyccsel as CcSel, Rxordset, TypecVstateCc as CcVState}; +use crate::rcc::{self, RccPeripheral}; + +pub(crate) fn init( + _cs: critical_section::CriticalSection, + #[cfg(peri_ucpd1)] ucpd1_db_enable: bool, + #[cfg(peri_ucpd2)] ucpd2_db_enable: bool, +) { + #[cfg(stm32g0x1)] + { + // according to RM0444 (STM32G0x1) section 8.1.1: + // when UCPD is disabled setting the strobe will disable dead battery + // (which is enabled after reset) but if UCPD is enabled, setting the + // strobe will apply the CC pin configuration from the control register + // (which is why we need to be careful about when we call this) + crate::pac::SYSCFG.cfgr1().modify(|w| { + w.set_ucpd1_strobe(!ucpd1_db_enable); + w.set_ucpd2_strobe(!ucpd2_db_enable); + }); + } + + #[cfg(any(stm32g4, stm32l5))] + { + crate::pac::PWR.cr3().modify(|w| { + #[cfg(stm32g4)] + w.set_ucpd1_dbdis(!ucpd1_db_enable); + #[cfg(stm32l5)] + w.set_ucpd_dbdis(!ucpd1_db_enable); + }) + } + + #[cfg(any(stm32h5, stm32u5, stm32h7rs))] + { + crate::pac::PWR.ucpdr().modify(|w| { + w.set_ucpd_dbdis(!ucpd1_db_enable); + }) + } +} + +/// Pull-up or Pull-down resistor state of both CC lines. +#[derive(Debug, Clone, Copy, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum CcPull { + /// Analog PHY for CC pin disabled. + Disabled, + + /// Rd=5.1k pull-down resistor. + Sink, + + /// Rp=56k pull-up resistor to indicate default USB power. + SourceDefaultUsb, + + /// Rp=22k pull-up resistor to indicate support for up to 1.5A. + Source1_5A, + + /// Rp=10k pull-up resistor to indicate support for up to 3.0A. + Source3_0A, +} + +/// UCPD configuration +#[non_exhaustive] +#[derive(Copy, Clone, Debug)] +pub struct Config { + /// Receive SOP packets + pub sop: bool, + /// Receive SOP' packets + pub sop_prime: bool, + /// Receive SOP'' packets + pub sop_double_prime: bool, + /// Receive SOP'_Debug packets + pub sop_prime_debug: bool, + /// Receive SOP''_Debug packets + pub sop_double_prime_debug: bool, +} + +impl Default for Config { + fn default() -> Self { + Self { + sop: true, + sop_prime: false, + sop_double_prime: false, + sop_prime_debug: false, + sop_double_prime_debug: false, + } + } +} + +/// UCPD driver. +pub struct Ucpd<'d, T: Instance> { + cc_phy: CcPhy<'d, T>, +} + +impl<'d, T: Instance> Ucpd<'d, T> { + /// Creates a new UCPD driver instance. + pub fn new( + _peri: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + cc1: impl Peripheral

> + 'd, + cc2: impl Peripheral

> + 'd, + config: Config, + ) -> Self { + into_ref!(cc1, cc2); + cc1.set_as_analog(); + cc2.set_as_analog(); + + rcc::enable_and_reset::(); + T::Interrupt::unpend(); + unsafe { T::Interrupt::enable() }; + + let r = T::REGS; + r.cfgr1().write(|w| { + // "The receiver is designed to work in the clock frequency range from 6 to 18 MHz. + // However, the optimum performance is ensured in the range from 6 to 12 MHz" + // UCPD is driven by HSI16 (16MHz internal oscillator), which we need to divide by 2. + w.set_psc_usbpdclk(PscUsbpdclk::DIV2); + + // Prescaler to produce a target half-bit frequency of 600kHz which is required + // to produce transmit with a nominal nominal bit rate of 300Kbps+-10% using + // biphase mark coding (BMC, aka differential manchester coding). + // A divider of 13 gives the target frequency closest to spec (~615kHz, 1.625us). + w.set_hbitclkdiv(13 - 1); + + // Time window for detecting non-idle (12-20us). + // 1.75us * 8 = 14us. + w.set_transwin(8 - 1); + + // Time from the end of last bit of a Frame until the start of the first bit of the + // next Preamble (min 25us). + // 1.75us * 17 = ~30us + w.set_ifrgap(17 - 1); + + // UNDOCUMENTED: This register can only be written while UCPDEN=0 (found by testing). + let rxordset = (config.sop as u16) << 0 + | (config.sop_prime as u16) << 1 + | (config.sop_double_prime as u16) << 2 + // Hard reset + | 0x1 << 3 + | (config.sop_prime_debug as u16) << 4 + | (config.sop_double_prime_debug as u16) << 5; + w.set_rxordseten(rxordset); + + // Enable DMA + w.set_txdmaen(true); + w.set_rxdmaen(true); + + w.set_ucpden(true); + }); + + Self { + cc_phy: CcPhy { _lifetime: PhantomData }, + } + } + + /// Returns the TypeC CC PHY. + pub fn cc_phy(&mut self) -> &mut CcPhy<'d, T> { + &mut self.cc_phy + } + + /// Splits the UCPD driver into a TypeC PHY to control and monitor CC voltage + /// and a Power Delivery (PD) PHY with receiver and transmitter. + pub fn split_pd_phy( + self, + rx_dma: impl Peripheral

> + 'd, + tx_dma: impl Peripheral

> + 'd, + cc_sel: CcSel, + ) -> (CcPhy<'d, T>, PdPhy<'d, T>) { + let r = T::REGS; + + // TODO: Currently only SOP messages are supported. + r.tx_ordsetr().write(|w| w.set_txordset(0b10001_11000_11000_11000)); + + // Enable the receiver on one of the two CC lines. + r.cr().modify(|w| w.set_phyccsel(cc_sel)); + + // Enable hard reset receive interrupt. + r.imr().modify(|w| w.set_rxhrstdetie(true)); + + // Enable PD packet reception + r.cr().modify(|w| w.set_phyrxen(true)); + + // Both parts must be dropped before the peripheral can be disabled. + T::state().drop_not_ready.store(true, Ordering::Relaxed); + + into_ref!(rx_dma, tx_dma); + let rx_dma_req = rx_dma.request(); + let tx_dma_req = tx_dma.request(); + ( + self.cc_phy, + PdPhy { + _lifetime: PhantomData, + rx_dma: ChannelAndRequest { + channel: rx_dma.map_into(), + request: rx_dma_req, + }, + tx_dma: ChannelAndRequest { + channel: tx_dma.map_into(), + request: tx_dma_req, + }, + }, + ) + } +} + +/// Control and monitoring of TypeC CC pin functionailty. +pub struct CcPhy<'d, T: Instance> { + _lifetime: PhantomData<&'d mut T>, +} + +impl<'d, T: Instance> Drop for CcPhy<'d, T> { + fn drop(&mut self) { + let r = T::REGS; + r.cr().modify(|w| { + w.set_cc1tcdis(true); + w.set_cc2tcdis(true); + w.set_ccenable(Ccenable::DISABLED); + }); + + // Check if the PdPhy part was dropped already. + let drop_not_ready = &T::state().drop_not_ready; + if drop_not_ready.load(Ordering::Relaxed) { + drop_not_ready.store(true, Ordering::Relaxed); + } else { + r.cfgr1().write(|w| w.set_ucpden(false)); + rcc::disable::(); + T::Interrupt::disable(); + } + } +} + +impl<'d, T: Instance> CcPhy<'d, T> { + /// Sets the pull-up/pull-down resistor values exposed on the CC pins. + pub fn set_pull(&mut self, cc_pull: CcPull) { + T::REGS.cr().modify(|w| { + w.set_anamode(if cc_pull == CcPull::Sink { + Anamode::SINK + } else { + Anamode::SOURCE + }); + w.set_anasubmode(match cc_pull { + CcPull::SourceDefaultUsb => 1, + CcPull::Source1_5A => 2, + CcPull::Source3_0A => 3, + _ => 0, + }); + w.set_ccenable(if cc_pull == CcPull::Disabled { + Ccenable::DISABLED + } else { + Ccenable::BOTH + }); + }); + + // Disable dead-battery pull-down resistors which are enabled by default on boot. + critical_section::with(|cs| { + init( + cs, + false, + #[cfg(peri_ucpd2)] + false, + ); + }); + } + + /// Returns the current voltage level of CC1 and CC2 pin as tuple. + /// + /// Interpretation of the voltage levels depends on the configured CC line + /// pull-up/pull-down resistance. + pub fn vstate(&self) -> (CcVState, CcVState) { + let sr = T::REGS.sr().read(); + (sr.typec_vstate_cc1(), sr.typec_vstate_cc2()) + } + + /// Waits for a change in voltage state on either CC line. + pub async fn wait_for_vstate_change(&self) -> (CcVState, CcVState) { + let _on_drop = OnDrop::new(|| self.enable_cc_interrupts(false)); + let prev_vstate = self.vstate(); + poll_fn(|cx| { + let vstate = self.vstate(); + if vstate != prev_vstate { + Poll::Ready(vstate) + } else { + T::state().waker.register(cx.waker()); + self.enable_cc_interrupts(true); + Poll::Pending + } + }) + .await + } + + fn enable_cc_interrupts(&self, enable: bool) { + T::REGS.imr().modify(|w| { + w.set_typecevt1ie(enable); + w.set_typecevt2ie(enable); + }); + } +} + +/// Receive SOP. +#[derive(Debug, Clone, Copy)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Sop { + /// SOP + Sop, + /// SOP' + SopPrime, + /// SOP'' + SopDoublePrime, + /// SOP'_Debug + SopPrimeDebug, + /// SOP''_Debug + SopDoublePrimeDebug, +} + +/// Receive Error. +#[derive(Debug, Clone, Copy)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum RxError { + /// Incorrect CRC or truncated message (a line becoming static before EOP is met). + Crc, + + /// Provided buffer was too small for the received message. + Overrun, + + /// Hard Reset received before or during reception. + HardReset, +} + +/// Transmit Error. +#[derive(Debug, Clone, Copy)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum TxError { + /// Concurrent receive in progress or excessive noise on the line. + Discarded, + + /// Hard Reset received before or during transmission. + HardReset, +} + +/// Power Delivery (PD) PHY. +pub struct PdPhy<'d, T: Instance> { + _lifetime: PhantomData<&'d mut T>, + rx_dma: ChannelAndRequest<'d>, + tx_dma: ChannelAndRequest<'d>, +} + +impl<'d, T: Instance> Drop for PdPhy<'d, T> { + fn drop(&mut self) { + T::REGS.cr().modify(|w| w.set_phyrxen(false)); + // Check if the Type-C part was dropped already. + let drop_not_ready = &T::state().drop_not_ready; + if drop_not_ready.load(Ordering::Relaxed) { + drop_not_ready.store(true, Ordering::Relaxed); + } else { + T::REGS.cfgr1().write(|w| w.set_ucpden(false)); + rcc::disable::(); + T::Interrupt::disable(); + } + } +} + +impl<'d, T: Instance> PdPhy<'d, T> { + /// Receives a PD message into the provided buffer. + /// + /// Returns the number of received bytes or an error. + pub async fn receive(&mut self, buf: &mut [u8]) -> Result { + self.receive_with_sop(buf).await.map(|(_sop, size)| size) + } + + /// Receives SOP and a PD message into the provided buffer. + /// + /// Returns the start of packet type and number of received bytes or an error. + pub async fn receive_with_sop(&mut self, buf: &mut [u8]) -> Result<(Sop, usize), RxError> { + let r = T::REGS; + + let dma = unsafe { + self.rx_dma + .read(r.rxdr().as_ptr() as *mut u8, buf, TransferOptions::default()) + }; + + let _on_drop = OnDrop::new(|| { + Self::enable_rx_interrupt(false); + // Clear interrupt flags + r.icr().write(|w| { + w.set_rxorddetcf(true); + w.set_rxovrcf(true); + w.set_rxmsgendcf(true); + }); + }); + + poll_fn(|cx| { + let sr = r.sr().read(); + if sr.rxhrstdet() { + // Clean and re-enable hard reset receive interrupt. + r.icr().write(|w| w.set_rxhrstdetcf(true)); + r.imr().modify(|w| w.set_rxhrstdetie(true)); + Poll::Ready(Err(RxError::HardReset)) + } else if sr.rxmsgend() { + let ret = if sr.rxovr() { + Err(RxError::Overrun) + } else if sr.rxerr() { + Err(RxError::Crc) + } else { + Ok(()) + }; + Poll::Ready(ret) + } else { + T::state().waker.register(cx.waker()); + Self::enable_rx_interrupt(true); + Poll::Pending + } + }) + .await?; + + // Make sure that the last byte was fetched by DMA. + while r.sr().read().rxne() { + if dma.get_remaining_transfers() == 0 { + return Err(RxError::Overrun); + } + } + + let sop = match r.rx_ordsetr().read().rxordset() { + Rxordset::SOP => Sop::Sop, + Rxordset::SOPPRIME => Sop::SopPrime, + Rxordset::SOPDOUBLEPRIME => Sop::SopDoublePrime, + Rxordset::SOPPRIMEDEBUG => Sop::SopPrimeDebug, + Rxordset::SOPDOUBLEPRIMEDEBUG => Sop::SopDoublePrimeDebug, + Rxordset::CABLERESET => return Err(RxError::HardReset), + // Extension headers are not supported + _ => unreachable!(), + }; + + Ok((sop, r.rx_payszr().read().rxpaysz().into())) + } + + fn enable_rx_interrupt(enable: bool) { + T::REGS.imr().modify(|w| w.set_rxmsgendie(enable)); + } + + /// Transmits a PD message. + pub async fn transmit(&mut self, buf: &[u8]) -> Result<(), TxError> { + let r = T::REGS; + + // When a previous transmission was dropped before it had finished it + // might still be running because there is no way to abort an ongoing + // message transmission. Wait for it to finish but ignore errors. + if r.cr().read().txsend() { + if let Err(TxError::HardReset) = Self::wait_tx_done().await { + return Err(TxError::HardReset); + } + } + + // Clear the TX interrupt flags. + T::REGS.icr().write(|w| { + w.set_txmsgdisccf(true); + w.set_txmsgsentcf(true); + }); + + // Start the DMA and let it do its thing in the background. + let _dma = unsafe { + self.tx_dma + .write(buf, r.txdr().as_ptr() as *mut u8, TransferOptions::default()) + }; + + // Configure and start the transmission. + r.tx_payszr().write(|w| w.set_txpaysz(buf.len() as _)); + r.cr().modify(|w| { + w.set_txmode(Txmode::PACKET); + w.set_txsend(true); + }); + + Self::wait_tx_done().await + } + + async fn wait_tx_done() -> Result<(), TxError> { + let _on_drop = OnDrop::new(|| Self::enable_tx_interrupts(false)); + poll_fn(|cx| { + let r = T::REGS; + let sr = r.sr().read(); + if sr.rxhrstdet() { + // Clean and re-enable hard reset receive interrupt. + r.icr().write(|w| w.set_rxhrstdetcf(true)); + r.imr().modify(|w| w.set_rxhrstdetie(true)); + Poll::Ready(Err(TxError::HardReset)) + } else if sr.txmsgdisc() { + Poll::Ready(Err(TxError::Discarded)) + } else if sr.txmsgsent() { + Poll::Ready(Ok(())) + } else { + T::state().waker.register(cx.waker()); + Self::enable_tx_interrupts(true); + Poll::Pending + } + }) + .await + } + + fn enable_tx_interrupts(enable: bool) { + T::REGS.imr().modify(|w| { + w.set_txmsgdiscie(enable); + w.set_txmsgsentie(enable); + }); + } + + /// Transmit a hard reset. + pub async fn transmit_hardreset(&mut self) -> Result<(), TxError> { + let r = T::REGS; + + // Clear the hardreset interrupt flags. + T::REGS.icr().write(|w| { + w.set_hrstdisccf(true); + w.set_hrstsentcf(true); + }); + + // Trigger hard reset transmission. + r.cr().modify(|w| { + w.set_txhrst(true); + }); + + let _on_drop = OnDrop::new(|| self.enable_hardreset_interrupts(false)); + poll_fn(|cx| { + let r = T::REGS; + let sr = r.sr().read(); + if sr.rxhrstdet() { + // Clean and re-enable hard reset receive interrupt. + r.icr().write(|w| w.set_rxhrstdetcf(true)); + r.imr().modify(|w| w.set_rxhrstdetie(true)); + Poll::Ready(Err(TxError::HardReset)) + } else if sr.hrstdisc() { + Poll::Ready(Err(TxError::Discarded)) + } else if sr.hrstsent() { + Poll::Ready(Ok(())) + } else { + T::state().waker.register(cx.waker()); + self.enable_hardreset_interrupts(true); + Poll::Pending + } + }) + .await + } + + fn enable_hardreset_interrupts(&self, enable: bool) { + T::REGS.imr().modify(|w| { + w.set_hrstdiscie(enable); + w.set_hrstsentie(enable); + }); + } +} + +/// Interrupt handler. +pub struct InterruptHandler { + _phantom: PhantomData, +} + +impl interrupt::typelevel::Handler for InterruptHandler { + unsafe fn on_interrupt() { + let r = T::REGS; + let sr = r.sr().read(); + + if sr.typecevt1() || sr.typecevt2() { + r.icr().write(|w| { + w.set_typecevt1cf(true); + w.set_typecevt2cf(true); + }); + } + + if sr.rxhrstdet() { + r.imr().modify(|w| w.set_rxhrstdetie(false)); + } + + if sr.rxmsgend() { + r.imr().modify(|w| w.set_rxmsgendie(false)); + } + + if sr.txmsgdisc() || sr.txmsgsent() { + r.imr().modify(|w| { + w.set_txmsgdiscie(false); + w.set_txmsgsentie(false); + }); + } + + if sr.hrstdisc() || sr.hrstsent() { + r.imr().modify(|w| { + w.set_hrstdiscie(false); + w.set_hrstsentie(false); + }); + } + + // Wake the task to clear and re-enabled interrupts. + T::state().waker.wake(); + } +} + +struct State { + waker: AtomicWaker, + // Inverted logic for a default state of 0 so that the data goes into the .bss section. + drop_not_ready: AtomicBool, +} + +impl State { + pub const fn new() -> Self { + Self { + waker: AtomicWaker::new(), + drop_not_ready: AtomicBool::new(false), + } + } +} + +trait SealedInstance { + const REGS: crate::pac::ucpd::Ucpd; + fn state() -> &'static State; +} + +/// UCPD instance trait. +#[allow(private_bounds)] +pub trait Instance: SealedInstance + RccPeripheral { + /// Interrupt for this instance. + type Interrupt: crate::interrupt::typelevel::Interrupt; +} + +foreach_interrupt!( + ($inst:ident, ucpd, UCPD, GLOBAL, $irq:ident) => { + impl SealedInstance for crate::peripherals::$inst { + const REGS: crate::pac::ucpd::Ucpd = crate::pac::$inst; + + fn state() -> &'static State { + static STATE: State = State::new(); + &STATE + } + } + + impl Instance for crate::peripherals::$inst { + type Interrupt = crate::interrupt::typelevel::$irq; + } + }; +); + +pin_trait!(Cc1Pin, Instance); +pin_trait!(Cc2Pin, Instance); + +dma_trait!(TxDma, Instance); +dma_trait!(RxDma, Instance); diff --git a/embassy-stm32/src/uid.rs b/embassy-stm32/src/uid.rs index aa13586f8..5e38532bd 100644 --- a/embassy-stm32/src/uid.rs +++ b/embassy-stm32/src/uid.rs @@ -27,5 +27,5 @@ pub fn uid_hex_bytes() -> &'static [u8; 24] { LOADED = true; } }); - unsafe { &UID_HEX } + unsafe { &*core::ptr::addr_of!(UID_HEX) } } diff --git a/embassy-stm32/src/usart/buffered.rs b/embassy-stm32/src/usart/buffered.rs index c78752883..f7b2bf4b4 100644 --- a/embassy-stm32/src/usart/buffered.rs +++ b/embassy-stm32/src/usart/buffered.rs @@ -1,155 +1,178 @@ use core::future::poll_fn; +use core::marker::PhantomData; use core::slice; -use core::sync::atomic::{AtomicBool, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU8, Ordering}; use core::task::Poll; +use embassy_embedded_hal::SetConfig; use embassy_hal_internal::atomic_ring_buffer::RingBuffer; +use embassy_hal_internal::{Peripheral, PeripheralRef}; use embassy_sync::waitqueue::AtomicWaker; -use super::*; -use crate::interrupt::typelevel::Interrupt; +#[cfg(not(any(usart_v1, usart_v2)))] +use super::DePin; +use super::{ + clear_interrupt_flags, configure, rdr, reconfigure, send_break, sr, tdr, Config, ConfigError, CtsPin, Error, Info, + Instance, Regs, RtsPin, RxPin, TxPin, +}; +use crate::gpio::{AfType, AnyPin, OutputType, Pull, SealedPin as _, Speed}; +use crate::interrupt::{self, InterruptExt}; +use crate::time::Hertz; /// Interrupt handler. -pub struct InterruptHandler { +pub struct InterruptHandler { _phantom: PhantomData, } -impl interrupt::typelevel::Handler for InterruptHandler { +impl interrupt::typelevel::Handler for InterruptHandler { unsafe fn on_interrupt() { - let r = T::regs(); - let state = T::buffered_state(); + on_interrupt(T::info().regs, T::buffered_state()) + } +} - // RX - let sr_val = sr(r).read(); - // On v1 & v2, reading DR clears the rxne, error and idle interrupt - // flags. Keep this close to the SR read to reduce the chance of a - // flag being set in-between. - let dr = if sr_val.rxne() || cfg!(any(usart_v1, usart_v2)) && (sr_val.ore() || sr_val.idle()) { - Some(rdr(r).read_volatile()) +unsafe fn on_interrupt(r: Regs, state: &'static State) { + // RX + let sr_val = sr(r).read(); + // On v1 & v2, reading DR clears the rxne, error and idle interrupt + // flags. Keep this close to the SR read to reduce the chance of a + // flag being set in-between. + let dr = if sr_val.rxne() || cfg!(any(usart_v1, usart_v2)) && (sr_val.ore() || sr_val.idle()) { + Some(rdr(r).read_volatile()) + } else { + None + }; + clear_interrupt_flags(r, sr_val); + + if sr_val.pe() { + warn!("Parity error"); + } + if sr_val.fe() { + warn!("Framing error"); + } + if sr_val.ne() { + warn!("Noise error"); + } + if sr_val.ore() { + warn!("Overrun error"); + } + if sr_val.rxne() { + let mut rx_writer = state.rx_buf.writer(); + let buf = rx_writer.push_slice(); + if !buf.is_empty() { + if let Some(byte) = dr { + buf[0] = byte; + rx_writer.push_done(1); + } } else { - None - }; - clear_interrupt_flags(r, sr_val); - - if sr_val.pe() { - warn!("Parity error"); - } - if sr_val.fe() { - warn!("Framing error"); - } - if sr_val.ne() { - warn!("Noise error"); - } - if sr_val.ore() { - warn!("Overrun error"); - } - if sr_val.rxne() { - let mut rx_writer = state.rx_buf.writer(); - let buf = rx_writer.push_slice(); - if !buf.is_empty() { - if let Some(byte) = dr { - buf[0] = byte; - rx_writer.push_done(1); - } - } else { - // FIXME: Should we disable any further RX interrupts when the buffer becomes full. - } - - if state.rx_buf.is_full() { - state.rx_waker.wake(); - } + // FIXME: Should we disable any further RX interrupts when the buffer becomes full. } - if sr_val.idle() { + if !state.rx_buf.is_empty() { state.rx_waker.wake(); } + } - // With `usart_v4` hardware FIFO is enabled and Transmission complete (TC) - // indicates that all bytes are pushed out from the FIFO. - // For other usart variants it shows that last byte from the buffer was just sent. - if sr_val.tc() { - // For others it is cleared above with `clear_interrupt_flags`. - #[cfg(any(usart_v1, usart_v2))] - sr(r).modify(|w| w.set_tc(false)); + if sr_val.idle() { + state.rx_waker.wake(); + } + // With `usart_v4` hardware FIFO is enabled and Transmission complete (TC) + // indicates that all bytes are pushed out from the FIFO. + // For other usart variants it shows that last byte from the buffer was just sent. + if sr_val.tc() { + // For others it is cleared above with `clear_interrupt_flags`. + #[cfg(any(usart_v1, usart_v2))] + sr(r).modify(|w| w.set_tc(false)); + + r.cr1().modify(|w| { + w.set_tcie(false); + }); + + state.tx_done.store(true, Ordering::Release); + state.tx_waker.wake(); + } + + // TX + if sr(r).read().txe() { + let mut tx_reader = state.tx_buf.reader(); + let buf = tx_reader.pop_slice(); + if !buf.is_empty() { r.cr1().modify(|w| { - w.set_tcie(false); + w.set_txeie(true); }); - state.tx_done.store(true, Ordering::Release); - state.tx_waker.wake(); - } - - // TX - if sr(r).read().txe() { - let mut tx_reader = state.tx_buf.reader(); - let buf = tx_reader.pop_slice(); - if !buf.is_empty() { + // Enable transmission complete interrupt when last byte is going to be sent out. + if buf.len() == 1 { r.cr1().modify(|w| { - w.set_txeie(true); - }); - - // Enable transmission complete interrupt when last byte is going to be sent out. - if buf.len() == 1 { - r.cr1().modify(|w| { - w.set_tcie(true); - }); - } - - tdr(r).write_volatile(buf[0].into()); - tx_reader.pop_done(1); - } else { - // Disable interrupt until we have something to transmit again. - r.cr1().modify(|w| { - w.set_txeie(false); + w.set_tcie(true); }); } + + tdr(r).write_volatile(buf[0].into()); + tx_reader.pop_done(1); + } else { + // Disable interrupt until we have something to transmit again. + r.cr1().modify(|w| { + w.set_txeie(false); + }); } } } -pub(crate) use sealed::State; -pub(crate) mod sealed { - use super::*; - pub struct State { - pub(crate) rx_waker: AtomicWaker, - pub(crate) rx_buf: RingBuffer, - pub(crate) tx_waker: AtomicWaker, - pub(crate) tx_buf: RingBuffer, - pub(crate) tx_done: AtomicBool, - } +pub(super) struct State { + rx_waker: AtomicWaker, + rx_buf: RingBuffer, + tx_waker: AtomicWaker, + tx_buf: RingBuffer, + tx_done: AtomicBool, + tx_rx_refcount: AtomicU8, +} - impl State { - /// Create new state - pub const fn new() -> Self { - Self { - rx_buf: RingBuffer::new(), - tx_buf: RingBuffer::new(), - rx_waker: AtomicWaker::new(), - tx_waker: AtomicWaker::new(), - tx_done: AtomicBool::new(true), - } +impl State { + pub(super) const fn new() -> Self { + Self { + rx_buf: RingBuffer::new(), + tx_buf: RingBuffer::new(), + rx_waker: AtomicWaker::new(), + tx_waker: AtomicWaker::new(), + tx_done: AtomicBool::new(true), + tx_rx_refcount: AtomicU8::new(0), } } } /// Bidirectional buffered UART -pub struct BufferedUart<'d, T: BasicInstance> { - rx: BufferedUartRx<'d, T>, - tx: BufferedUartTx<'d, T>, +pub struct BufferedUart<'d> { + rx: BufferedUartRx<'d>, + tx: BufferedUartTx<'d>, } /// Tx-only buffered UART -pub struct BufferedUartTx<'d, T: BasicInstance> { - phantom: PhantomData<&'d mut T>, +/// +/// Created with [BufferedUart::split] +pub struct BufferedUartTx<'d> { + info: &'static Info, + state: &'static State, + kernel_clock: Hertz, + tx: Option>, + cts: Option>, + de: Option>, + is_borrowed: bool, } /// Rx-only buffered UART -pub struct BufferedUartRx<'d, T: BasicInstance> { - phantom: PhantomData<&'d mut T>, +/// +/// Created with [BufferedUart::split] +pub struct BufferedUartRx<'d> { + info: &'static Info, + state: &'static State, + kernel_clock: Hertz, + rx: Option>, + rts: Option>, + is_borrowed: bool, } -impl<'d, T: BasicInstance> SetConfig for BufferedUart<'d, T> { +impl<'d> SetConfig for BufferedUart<'d> { type Config = Config; type ConfigError = ConfigError; @@ -158,7 +181,7 @@ impl<'d, T: BasicInstance> SetConfig for BufferedUart<'d, T> { } } -impl<'d, T: BasicInstance> SetConfig for BufferedUartRx<'d, T> { +impl<'d> SetConfig for BufferedUartRx<'d> { type Config = Config; type ConfigError = ConfigError; @@ -167,7 +190,7 @@ impl<'d, T: BasicInstance> SetConfig for BufferedUartRx<'d, T> { } } -impl<'d, T: BasicInstance> SetConfig for BufferedUartTx<'d, T> { +impl<'d> SetConfig for BufferedUartTx<'d> { type Config = Config; type ConfigError = ConfigError; @@ -176,9 +199,9 @@ impl<'d, T: BasicInstance> SetConfig for BufferedUartTx<'d, T> { } } -impl<'d, T: BasicInstance> BufferedUart<'d, T> { +impl<'d> BufferedUart<'d> { /// Create a new bidirectional buffered UART driver - pub fn new( + pub fn new( peri: impl Peripheral

+ 'd, _irq: impl interrupt::typelevel::Binding> + 'd, rx: impl Peripheral

> + 'd, @@ -187,15 +210,21 @@ impl<'d, T: BasicInstance> BufferedUart<'d, T> { rx_buffer: &'d mut [u8], config: Config, ) -> Result { - // UartRx and UartTx have one refcount ea. - T::enable_and_reset(); - T::enable_and_reset(); - - Self::new_inner(peri, rx, tx, tx_buffer, rx_buffer, config) + Self::new_inner( + peri, + new_pin!(rx, AfType::input(config.rx_pull)), + new_pin!(tx, AfType::output(OutputType::PushPull, Speed::Medium)), + None, + None, + None, + tx_buffer, + rx_buffer, + config, + ) } /// Create a new bidirectional buffered UART driver with request-to-send and clear-to-send pins - pub fn new_with_rtscts( + pub fn new_with_rtscts( peri: impl Peripheral

+ 'd, _irq: impl interrupt::typelevel::Binding> + 'd, rx: impl Peripheral

> + 'd, @@ -206,25 +235,70 @@ impl<'d, T: BasicInstance> BufferedUart<'d, T> { rx_buffer: &'d mut [u8], config: Config, ) -> Result { - into_ref!(cts, rts); + Self::new_inner( + peri, + new_pin!(rx, AfType::input(Pull::None)), + new_pin!(tx, AfType::output(OutputType::PushPull, Speed::Medium)), + new_pin!(rts, AfType::output(OutputType::PushPull, Speed::Medium)), + new_pin!(cts, AfType::input(Pull::None)), + None, + tx_buffer, + rx_buffer, + config, + ) + } - // UartRx and UartTx have one refcount ea. - T::enable_and_reset(); - T::enable_and_reset(); + /// Create a new bidirectional buffered UART driver with only the RTS pin as the DE pin + pub fn new_with_rts_as_de( + peri: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + rx: impl Peripheral

> + 'd, + tx: impl Peripheral

> + 'd, + rts: impl Peripheral

> + 'd, + tx_buffer: &'d mut [u8], + rx_buffer: &'d mut [u8], + config: Config, + ) -> Result { + Self::new_inner( + peri, + new_pin!(rx, AfType::input(Pull::None)), + new_pin!(tx, AfType::output(OutputType::PushPull, Speed::Medium)), + None, + None, + new_pin!(rts, AfType::input(Pull::None)), // RTS mapped used as DE + tx_buffer, + rx_buffer, + config, + ) + } - rts.set_as_af(rts.af_num(), AFType::OutputPushPull); - cts.set_as_af(cts.af_num(), AFType::Input); - T::regs().cr3().write(|w| { - w.set_rtse(true); - w.set_ctse(true); - }); - - Self::new_inner(peri, rx, tx, tx_buffer, rx_buffer, config) + /// Create a new bidirectional buffered UART driver with only the request-to-send pin + pub fn new_with_rts( + peri: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + rx: impl Peripheral

> + 'd, + tx: impl Peripheral

> + 'd, + rts: impl Peripheral

> + 'd, + tx_buffer: &'d mut [u8], + rx_buffer: &'d mut [u8], + config: Config, + ) -> Result { + Self::new_inner( + peri, + new_pin!(rx, AfType::input(Pull::None)), + new_pin!(tx, AfType::output(OutputType::PushPull, Speed::Medium)), + new_pin!(rts, AfType::input(Pull::None)), + None, // no CTS + None, // no DE + tx_buffer, + rx_buffer, + config, + ) } /// Create a new bidirectional buffered UART driver with a driver-enable pin #[cfg(not(any(usart_v1, usart_v2)))] - pub fn new_with_de( + pub fn new_with_de( peri: impl Peripheral

+ 'd, _irq: impl interrupt::typelevel::Binding> + 'd, rx: impl Peripheral

> + 'd, @@ -234,78 +308,145 @@ impl<'d, T: BasicInstance> BufferedUart<'d, T> { rx_buffer: &'d mut [u8], config: Config, ) -> Result { - into_ref!(de); - - // UartRx and UartTx have one refcount ea. - T::enable_and_reset(); - T::enable_and_reset(); - - de.set_as_af(de.af_num(), AFType::OutputPushPull); - T::regs().cr3().write(|w| { - w.set_dem(true); - }); - - Self::new_inner(peri, rx, tx, tx_buffer, rx_buffer, config) + Self::new_inner( + peri, + new_pin!(rx, AfType::input(config.rx_pull)), + new_pin!(tx, AfType::output(OutputType::PushPull, Speed::Medium)), + None, + None, + new_pin!(de, AfType::output(OutputType::PushPull, Speed::Medium)), + tx_buffer, + rx_buffer, + config, + ) } - fn new_inner( + fn new_inner( _peri: impl Peripheral

+ 'd, - rx: impl Peripheral

> + 'd, - tx: impl Peripheral

> + 'd, + rx: Option>, + tx: Option>, + rts: Option>, + cts: Option>, + de: Option>, tx_buffer: &'d mut [u8], rx_buffer: &'d mut [u8], config: Config, ) -> Result { - into_ref!(_peri, rx, tx); - + let info = T::info(); let state = T::buffered_state(); + let kernel_clock = T::frequency(); + + let mut this = Self { + rx: BufferedUartRx { + info, + state, + kernel_clock, + rx, + rts, + is_borrowed: false, + }, + tx: BufferedUartTx { + info, + state, + kernel_clock, + tx, + cts, + de, + is_borrowed: false, + }, + }; + this.enable_and_configure(tx_buffer, rx_buffer, &config)?; + Ok(this) + } + + fn enable_and_configure( + &mut self, + tx_buffer: &'d mut [u8], + rx_buffer: &'d mut [u8], + config: &Config, + ) -> Result<(), ConfigError> { + let info = self.rx.info; + let state = self.rx.state; + state.tx_rx_refcount.store(2, Ordering::Relaxed); + + info.rcc.enable_and_reset(); + let len = tx_buffer.len(); unsafe { state.tx_buf.init(tx_buffer.as_mut_ptr(), len) }; let len = rx_buffer.len(); unsafe { state.rx_buf.init(rx_buffer.as_mut_ptr(), len) }; - let r = T::regs(); - rx.set_as_af(rx.af_num(), AFType::Input); - tx.set_as_af(tx.af_num(), AFType::OutputPushPull); + info.regs.cr3().write(|w| { + w.set_rtse(self.rx.rts.is_some()); + w.set_ctse(self.tx.cts.is_some()); + #[cfg(not(any(usart_v1, usart_v2)))] + w.set_dem(self.tx.de.is_some()); + }); + configure(info, self.rx.kernel_clock, &config, true, true)?; - configure(r, &config, T::frequency(), T::KIND, true, true)?; - - r.cr1().modify(|w| { + info.regs.cr1().modify(|w| { w.set_rxneie(true); w.set_idleie(true); }); - T::Interrupt::unpend(); - unsafe { T::Interrupt::enable() }; + info.interrupt.unpend(); + unsafe { info.interrupt.enable() }; - Ok(Self { - rx: BufferedUartRx { phantom: PhantomData }, - tx: BufferedUartTx { phantom: PhantomData }, - }) + Ok(()) } /// Split the driver into a Tx and Rx part (useful for sending to separate tasks) - pub fn split(self) -> (BufferedUartTx<'d, T>, BufferedUartRx<'d, T>) { + pub fn split(self) -> (BufferedUartTx<'d>, BufferedUartRx<'d>) { (self.tx, self.rx) } + /// Split the Uart into a transmitter and receiver, + /// which is particularly useful when having two tasks correlating to + /// transmitting and receiving. + pub fn split_ref(&mut self) -> (BufferedUartTx<'_>, BufferedUartRx<'_>) { + ( + BufferedUartTx { + info: self.tx.info, + state: self.tx.state, + kernel_clock: self.tx.kernel_clock, + tx: self.tx.tx.as_mut().map(PeripheralRef::reborrow), + cts: self.tx.cts.as_mut().map(PeripheralRef::reborrow), + de: self.tx.de.as_mut().map(PeripheralRef::reborrow), + is_borrowed: true, + }, + BufferedUartRx { + info: self.rx.info, + state: self.rx.state, + kernel_clock: self.rx.kernel_clock, + rx: self.rx.rx.as_mut().map(PeripheralRef::reborrow), + rts: self.rx.rts.as_mut().map(PeripheralRef::reborrow), + is_borrowed: true, + }, + ) + } + /// Reconfigure the driver pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> { - reconfigure::(config)?; + reconfigure(self.rx.info, self.rx.kernel_clock, config)?; - T::regs().cr1().modify(|w| { + self.rx.info.regs.cr1().modify(|w| { w.set_rxneie(true); w.set_idleie(true); }); Ok(()) } + + /// Send break character + pub fn send_break(&self) { + self.tx.send_break() + } } -impl<'d, T: BasicInstance> BufferedUartRx<'d, T> { +impl<'d> BufferedUartRx<'d> { async fn read(&self, buf: &mut [u8]) -> Result { poll_fn(move |cx| { - let state = T::buffered_state(); + let state = self.state; let mut rx_reader = unsafe { state.rx_buf.reader() }; let data = rx_reader.pop_slice(); @@ -317,7 +458,7 @@ impl<'d, T: BasicInstance> BufferedUartRx<'d, T> { rx_reader.pop_done(len); if do_pend { - T::Interrupt::pend(); + self.info.interrupt.pend(); } return Poll::Ready(Ok(len)); @@ -331,7 +472,7 @@ impl<'d, T: BasicInstance> BufferedUartRx<'d, T> { fn blocking_read(&self, buf: &mut [u8]) -> Result { loop { - let state = T::buffered_state(); + let state = self.state; let mut rx_reader = unsafe { state.rx_buf.reader() }; let data = rx_reader.pop_slice(); @@ -343,7 +484,7 @@ impl<'d, T: BasicInstance> BufferedUartRx<'d, T> { rx_reader.pop_done(len); if do_pend { - T::Interrupt::pend(); + self.info.interrupt.pend(); } return Ok(len); @@ -353,7 +494,7 @@ impl<'d, T: BasicInstance> BufferedUartRx<'d, T> { async fn fill_buf(&self) -> Result<&[u8], Error> { poll_fn(move |cx| { - let state = T::buffered_state(); + let state = self.state; let mut rx_reader = unsafe { state.rx_buf.reader() }; let (p, n) = rx_reader.pop_buf(); if n == 0 { @@ -368,20 +509,26 @@ impl<'d, T: BasicInstance> BufferedUartRx<'d, T> { } fn consume(&self, amt: usize) { - let state = T::buffered_state(); + let state = self.state; let mut rx_reader = unsafe { state.rx_buf.reader() }; let full = state.rx_buf.is_full(); rx_reader.pop_done(amt); if full { - T::Interrupt::pend(); + self.info.interrupt.pend(); } } + /// we are ready to read if there is data in the buffer + fn read_ready(&mut self) -> Result { + let state = self.state; + Ok(!state.rx_buf.is_empty()) + } + /// Reconfigure the driver pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> { - reconfigure::(config)?; + reconfigure(self.info, self.kernel_clock, config)?; - T::regs().cr1().modify(|w| { + self.info.regs.cr1().modify(|w| { w.set_rxneie(true); w.set_idleie(true); }); @@ -390,10 +537,10 @@ impl<'d, T: BasicInstance> BufferedUartRx<'d, T> { } } -impl<'d, T: BasicInstance> BufferedUartTx<'d, T> { +impl<'d> BufferedUartTx<'d> { async fn write(&self, buf: &[u8]) -> Result { poll_fn(move |cx| { - let state = T::buffered_state(); + let state = self.state; state.tx_done.store(false, Ordering::Release); let empty = state.tx_buf.is_empty(); @@ -410,7 +557,7 @@ impl<'d, T: BasicInstance> BufferedUartTx<'d, T> { tx_writer.push_done(n); if empty { - T::Interrupt::pend(); + self.info.interrupt.pend(); } Poll::Ready(Ok(n)) @@ -420,7 +567,7 @@ impl<'d, T: BasicInstance> BufferedUartTx<'d, T> { async fn flush(&self) -> Result<(), Error> { poll_fn(move |cx| { - let state = T::buffered_state(); + let state = self.state; if !state.tx_done.load(Ordering::Acquire) { state.tx_waker.register(cx.waker()); @@ -434,7 +581,7 @@ impl<'d, T: BasicInstance> BufferedUartTx<'d, T> { fn blocking_write(&self, buf: &[u8]) -> Result { loop { - let state = T::buffered_state(); + let state = self.state; let empty = state.tx_buf.is_empty(); let mut tx_writer = unsafe { state.tx_buf.writer() }; @@ -445,7 +592,7 @@ impl<'d, T: BasicInstance> BufferedUartTx<'d, T> { tx_writer.push_done(n); if empty { - T::Interrupt::pend(); + self.info.interrupt.pend(); } return Ok(n); @@ -455,7 +602,7 @@ impl<'d, T: BasicInstance> BufferedUartTx<'d, T> { fn blocking_flush(&self) -> Result<(), Error> { loop { - let state = T::buffered_state(); + let state = self.state; if state.tx_buf.is_empty() { return Ok(()); } @@ -464,76 +611,115 @@ impl<'d, T: BasicInstance> BufferedUartTx<'d, T> { /// Reconfigure the driver pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> { - reconfigure::(config)?; + reconfigure(self.info, self.kernel_clock, config)?; - T::regs().cr1().modify(|w| { + self.info.regs.cr1().modify(|w| { w.set_rxneie(true); w.set_idleie(true); }); Ok(()) } -} -impl<'d, T: BasicInstance> Drop for BufferedUartRx<'d, T> { - fn drop(&mut self) { - let state = T::buffered_state(); - unsafe { - state.rx_buf.deinit(); - - // TX is inactive if the the buffer is not available. - // We can now unregister the interrupt handler - if state.tx_buf.len() == 0 { - T::Interrupt::disable(); - } - } - - T::disable(); + /// Send break character + pub fn send_break(&self) { + send_break(&self.info.regs); } } -impl<'d, T: BasicInstance> Drop for BufferedUartTx<'d, T> { +impl<'d> Drop for BufferedUartRx<'d> { fn drop(&mut self) { - let state = T::buffered_state(); - unsafe { - state.tx_buf.deinit(); + if !self.is_borrowed { + let state = self.state; + unsafe { + state.rx_buf.deinit(); - // RX is inactive if the the buffer is not available. - // We can now unregister the interrupt handler - if state.rx_buf.len() == 0 { - T::Interrupt::disable(); + // TX is inactive if the the buffer is not available. + // We can now unregister the interrupt handler + if state.tx_buf.len() == 0 { + self.info.interrupt.disable(); + } } - } - T::disable(); + self.rx.as_ref().map(|x| x.set_as_disconnected()); + self.rts.as_ref().map(|x| x.set_as_disconnected()); + drop_tx_rx(self.info, state); + } } } -impl<'d, T: BasicInstance> embedded_io_async::ErrorType for BufferedUart<'d, T> { +impl<'d> Drop for BufferedUartTx<'d> { + fn drop(&mut self) { + if !self.is_borrowed { + let state = self.state; + unsafe { + state.tx_buf.deinit(); + + // RX is inactive if the the buffer is not available. + // We can now unregister the interrupt handler + if state.rx_buf.len() == 0 { + self.info.interrupt.disable(); + } + } + + self.tx.as_ref().map(|x| x.set_as_disconnected()); + self.cts.as_ref().map(|x| x.set_as_disconnected()); + self.de.as_ref().map(|x| x.set_as_disconnected()); + drop_tx_rx(self.info, state); + } + } +} + +fn drop_tx_rx(info: &Info, state: &State) { + // We cannot use atomic subtraction here, because it's not supported for all targets + let is_last_drop = critical_section::with(|_| { + let refcount = state.tx_rx_refcount.load(Ordering::Relaxed); + assert!(refcount >= 1); + state.tx_rx_refcount.store(refcount - 1, Ordering::Relaxed); + refcount == 1 + }); + if is_last_drop { + info.rcc.disable(); + } +} + +impl<'d> embedded_io_async::ErrorType for BufferedUart<'d> { type Error = Error; } -impl<'d, T: BasicInstance> embedded_io_async::ErrorType for BufferedUartRx<'d, T> { +impl<'d> embedded_io_async::ErrorType for BufferedUartRx<'d> { type Error = Error; } -impl<'d, T: BasicInstance> embedded_io_async::ErrorType for BufferedUartTx<'d, T> { +impl<'d> embedded_io_async::ErrorType for BufferedUartTx<'d> { type Error = Error; } -impl<'d, T: BasicInstance> embedded_io_async::Read for BufferedUart<'d, T> { +impl<'d> embedded_io_async::Read for BufferedUart<'d> { async fn read(&mut self, buf: &mut [u8]) -> Result { self.rx.read(buf).await } } -impl<'d, T: BasicInstance> embedded_io_async::Read for BufferedUartRx<'d, T> { +impl<'d> embedded_io_async::Read for BufferedUartRx<'d> { async fn read(&mut self, buf: &mut [u8]) -> Result { Self::read(self, buf).await } } -impl<'d, T: BasicInstance> embedded_io_async::BufRead for BufferedUart<'d, T> { +impl<'d> embedded_io_async::ReadReady for BufferedUart<'d> { + fn read_ready(&mut self) -> Result { + BufferedUartRx::<'d>::read_ready(&mut self.rx) + } +} + +impl<'d> embedded_io_async::ReadReady for BufferedUartRx<'d> { + fn read_ready(&mut self) -> Result { + Self::read_ready(self) + } +} + +impl<'d> embedded_io_async::BufRead for BufferedUart<'d> { async fn fill_buf(&mut self) -> Result<&[u8], Self::Error> { self.rx.fill_buf().await } @@ -543,7 +729,7 @@ impl<'d, T: BasicInstance> embedded_io_async::BufRead for BufferedUart<'d, T> { } } -impl<'d, T: BasicInstance> embedded_io_async::BufRead for BufferedUartRx<'d, T> { +impl<'d> embedded_io_async::BufRead for BufferedUartRx<'d> { async fn fill_buf(&mut self) -> Result<&[u8], Self::Error> { Self::fill_buf(self).await } @@ -553,7 +739,7 @@ impl<'d, T: BasicInstance> embedded_io_async::BufRead for BufferedUartRx<'d, T> } } -impl<'d, T: BasicInstance> embedded_io_async::Write for BufferedUart<'d, T> { +impl<'d> embedded_io_async::Write for BufferedUart<'d> { async fn write(&mut self, buf: &[u8]) -> Result { self.tx.write(buf).await } @@ -563,7 +749,7 @@ impl<'d, T: BasicInstance> embedded_io_async::Write for BufferedUart<'d, T> { } } -impl<'d, T: BasicInstance> embedded_io_async::Write for BufferedUartTx<'d, T> { +impl<'d> embedded_io_async::Write for BufferedUartTx<'d> { async fn write(&mut self, buf: &[u8]) -> Result { Self::write(self, buf).await } @@ -573,19 +759,19 @@ impl<'d, T: BasicInstance> embedded_io_async::Write for BufferedUartTx<'d, T> { } } -impl<'d, T: BasicInstance> embedded_io::Read for BufferedUart<'d, T> { +impl<'d> embedded_io::Read for BufferedUart<'d> { fn read(&mut self, buf: &mut [u8]) -> Result { self.rx.blocking_read(buf) } } -impl<'d, T: BasicInstance> embedded_io::Read for BufferedUartRx<'d, T> { +impl<'d> embedded_io::Read for BufferedUartRx<'d> { fn read(&mut self, buf: &mut [u8]) -> Result { self.blocking_read(buf) } } -impl<'d, T: BasicInstance> embedded_io::Write for BufferedUart<'d, T> { +impl<'d> embedded_io::Write for BufferedUart<'d> { fn write(&mut self, buf: &[u8]) -> Result { self.tx.blocking_write(buf) } @@ -595,7 +781,7 @@ impl<'d, T: BasicInstance> embedded_io::Write for BufferedUart<'d, T> { } } -impl<'d, T: BasicInstance> embedded_io::Write for BufferedUartTx<'d, T> { +impl<'d> embedded_io::Write for BufferedUartTx<'d> { fn write(&mut self, buf: &[u8]) -> Result { Self::blocking_write(self, buf) } @@ -605,11 +791,11 @@ impl<'d, T: BasicInstance> embedded_io::Write for BufferedUartTx<'d, T> { } } -impl<'d, T: BasicInstance> embedded_hal_02::serial::Read for BufferedUartRx<'d, T> { +impl<'d> embedded_hal_02::serial::Read for BufferedUartRx<'d> { type Error = Error; fn read(&mut self) -> Result> { - let r = T::regs(); + let r = self.info.regs; unsafe { let sr = sr(r).read(); if sr.pe() { @@ -633,7 +819,7 @@ impl<'d, T: BasicInstance> embedded_hal_02::serial::Read for BufferedUartRx< } } -impl<'d, T: BasicInstance> embedded_hal_02::blocking::serial::Write for BufferedUartTx<'d, T> { +impl<'d> embedded_hal_02::blocking::serial::Write for BufferedUartTx<'d> { type Error = Error; fn bwrite_all(&mut self, mut buffer: &[u8]) -> Result<(), Self::Error> { @@ -652,7 +838,7 @@ impl<'d, T: BasicInstance> embedded_hal_02::blocking::serial::Write for Buff } } -impl<'d, T: BasicInstance> embedded_hal_02::serial::Read for BufferedUart<'d, T> { +impl<'d> embedded_hal_02::serial::Read for BufferedUart<'d> { type Error = Error; fn read(&mut self) -> Result> { @@ -660,7 +846,7 @@ impl<'d, T: BasicInstance> embedded_hal_02::serial::Read for BufferedUart<'d } } -impl<'d, T: BasicInstance> embedded_hal_02::blocking::serial::Write for BufferedUart<'d, T> { +impl<'d> embedded_hal_02::blocking::serial::Write for BufferedUart<'d> { type Error = Error; fn bwrite_all(&mut self, mut buffer: &[u8]) -> Result<(), Self::Error> { @@ -679,25 +865,25 @@ impl<'d, T: BasicInstance> embedded_hal_02::blocking::serial::Write for Buff } } -impl<'d, T: BasicInstance> embedded_hal_nb::serial::ErrorType for BufferedUart<'d, T> { +impl<'d> embedded_hal_nb::serial::ErrorType for BufferedUart<'d> { type Error = Error; } -impl<'d, T: BasicInstance> embedded_hal_nb::serial::ErrorType for BufferedUartTx<'d, T> { +impl<'d> embedded_hal_nb::serial::ErrorType for BufferedUartTx<'d> { type Error = Error; } -impl<'d, T: BasicInstance> embedded_hal_nb::serial::ErrorType for BufferedUartRx<'d, T> { +impl<'d> embedded_hal_nb::serial::ErrorType for BufferedUartRx<'d> { type Error = Error; } -impl<'d, T: BasicInstance> embedded_hal_nb::serial::Read for BufferedUartRx<'d, T> { +impl<'d> embedded_hal_nb::serial::Read for BufferedUartRx<'d> { fn read(&mut self) -> nb::Result { embedded_hal_02::serial::Read::read(self) } } -impl<'d, T: BasicInstance> embedded_hal_nb::serial::Write for BufferedUartTx<'d, T> { +impl<'d> embedded_hal_nb::serial::Write for BufferedUartTx<'d> { fn write(&mut self, char: u8) -> nb::Result<(), Self::Error> { self.blocking_write(&[char]).map(drop).map_err(nb::Error::Other) } @@ -707,13 +893,13 @@ impl<'d, T: BasicInstance> embedded_hal_nb::serial::Write for BufferedUartTx<'d, } } -impl<'d, T: BasicInstance> embedded_hal_nb::serial::Read for BufferedUart<'d, T> { +impl<'d> embedded_hal_nb::serial::Read for BufferedUart<'d> { fn read(&mut self) -> Result> { embedded_hal_02::serial::Read::read(&mut self.rx) } } -impl<'d, T: BasicInstance> embedded_hal_nb::serial::Write for BufferedUart<'d, T> { +impl<'d> embedded_hal_nb::serial::Write for BufferedUart<'d> { fn write(&mut self, char: u8) -> nb::Result<(), Self::Error> { self.tx.blocking_write(&[char]).map(drop).map_err(nb::Error::Other) } diff --git a/embassy-stm32/src/usart/mod.rs b/embassy-stm32/src/usart/mod.rs index ea727b010..8152fc560 100644 --- a/embassy-stm32/src/usart/mod.rs +++ b/embassy-stm32/src/usart/mod.rs @@ -4,17 +4,20 @@ use core::future::poll_fn; use core::marker::PhantomData; -use core::sync::atomic::{compiler_fence, Ordering}; +use core::sync::atomic::{compiler_fence, AtomicU8, Ordering}; use core::task::Poll; use embassy_embedded_hal::SetConfig; use embassy_hal_internal::drop::OnDrop; -use embassy_hal_internal::{into_ref, PeripheralRef}; -use futures::future::{select, Either}; +use embassy_hal_internal::PeripheralRef; +use embassy_sync::waitqueue::AtomicWaker; +use futures_util::future::{select, Either}; -use crate::dma::{NoDma, Transfer}; -use crate::gpio::sealed::AFType; -use crate::interrupt::typelevel::Interrupt; +use crate::dma::ChannelAndRequest; +use crate::gpio::{self, AfType, AnyPin, OutputType, Pull, SealedPin as _, Speed}; +use crate::interrupt::typelevel::Interrupt as _; +use crate::interrupt::{self, Interrupt, InterruptExt}; +use crate::mode::{Async, Blocking, Mode}; #[allow(unused_imports)] #[cfg(not(any(usart_v1, usart_v2)))] use crate::pac::usart::regs::Isr as Sr; @@ -25,57 +28,65 @@ use crate::pac::usart::Lpuart as Regs; #[cfg(any(usart_v1, usart_v2))] use crate::pac::usart::Usart as Regs; use crate::pac::usart::{regs, vals}; +use crate::rcc::{RccInfo, SealedRccPeripheral}; use crate::time::Hertz; -use crate::{interrupt, peripherals, Peripheral}; +use crate::Peripheral; /// Interrupt handler. -pub struct InterruptHandler { +pub struct InterruptHandler { _phantom: PhantomData, } -impl interrupt::typelevel::Handler for InterruptHandler { +impl interrupt::typelevel::Handler for InterruptHandler { unsafe fn on_interrupt() { - let r = T::regs(); - let s = T::state(); - - let (sr, cr1, cr3) = (sr(r).read(), r.cr1().read(), r.cr3().read()); - - let has_errors = (sr.pe() && cr1.peie()) || ((sr.fe() || sr.ne() || sr.ore()) && cr3.eie()); - if has_errors { - // clear all interrupts and DMA Rx Request - r.cr1().modify(|w| { - // disable RXNE interrupt - w.set_rxneie(false); - // disable parity interrupt - w.set_peie(false); - // disable idle line interrupt - w.set_idleie(false); - }); - r.cr3().modify(|w| { - // disable Error Interrupt: (Frame error, Noise error, Overrun error) - w.set_eie(false); - // disable DMA Rx Request - w.set_dmar(false); - }); - } else if cr1.idleie() && sr.idle() { - // IDLE detected: no more data will come - r.cr1().modify(|w| { - // disable idle line detection - w.set_idleie(false); - }); - } else if cr1.rxneie() { - // We cannot check the RXNE flag as it is auto-cleared by the DMA controller - - // It is up to the listener to determine if this in fact was a RX event and disable the RXNE detection - } else { - return; - } - - compiler_fence(Ordering::SeqCst); - s.rx_waker.wake(); + on_interrupt(T::info().regs, T::state()) } } +unsafe fn on_interrupt(r: Regs, s: &'static State) { + let (sr, cr1, cr3) = (sr(r).read(), r.cr1().read(), r.cr3().read()); + + let has_errors = (sr.pe() && cr1.peie()) || ((sr.fe() || sr.ne() || sr.ore()) && cr3.eie()); + if has_errors { + // clear all interrupts and DMA Rx Request + r.cr1().modify(|w| { + // disable RXNE interrupt + w.set_rxneie(false); + // disable parity interrupt + w.set_peie(false); + // disable idle line interrupt + w.set_idleie(false); + }); + r.cr3().modify(|w| { + // disable Error Interrupt: (Frame error, Noise error, Overrun error) + w.set_eie(false); + // disable DMA Rx Request + w.set_dmar(false); + }); + } else if cr1.idleie() && sr.idle() { + // IDLE detected: no more data will come + r.cr1().modify(|w| { + // disable idle line detection + w.set_idleie(false); + }); + } else if cr1.tcie() && sr.tc() { + // Transmission complete detected + r.cr1().modify(|w| { + // disable Transmission complete interrupt + w.set_tcie(false); + }); + } else if cr1.rxneie() { + // We cannot check the RXNE flag as it is auto-cleared by the DMA controller + + // It is up to the listener to determine if this in fact was a RX event and disable the RXNE detection + } else { + return; + } + + compiler_fence(Ordering::SeqCst); + s.rx_waker.wake(); +} + #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] /// Number of data bits @@ -154,13 +165,37 @@ pub struct Config { #[cfg(any(usart_v3, usart_v4))] pub swap_rx_tx: bool, - /// Set this to true to invert TX pin signal values (VDD =0/mark, Gnd = 1/idle). + /// Set this to true to invert TX pin signal values (VDD = 0/mark, Gnd = 1/idle). #[cfg(any(usart_v3, usart_v4))] pub invert_tx: bool, - /// Set this to true to invert RX pin signal values (VDD =0/mark, Gnd = 1/idle). + /// Set this to true to invert RX pin signal values (VDD = 0/mark, Gnd = 1/idle). #[cfg(any(usart_v3, usart_v4))] pub invert_rx: bool, + + /// Set the pull configuration for the RX pin. + pub rx_pull: Pull, + + // private: set by new_half_duplex, not by the user. + half_duplex: bool, +} + +impl Config { + fn tx_af(&self) -> AfType { + #[cfg(any(usart_v3, usart_v4))] + if self.swap_rx_tx { + return AfType::input(self.rx_pull); + }; + AfType::output(OutputType::PushPull, Speed::Medium) + } + + fn rx_af(&self) -> AfType { + #[cfg(any(usart_v3, usart_v4))] + if self.swap_rx_tx { + return AfType::output(OutputType::PushPull, Speed::Medium); + }; + AfType::input(self.rx_pull) + } } impl Default for Config { @@ -180,6 +215,32 @@ impl Default for Config { invert_tx: false, #[cfg(any(usart_v3, usart_v4))] invert_rx: false, + rx_pull: Pull::None, + half_duplex: false, + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +/// Half duplex IO mode +pub enum HalfDuplexConfig { + /// Push pull allows for faster baudrates, may require series resistor + PushPull, + /// Open drain output using external pull up resistor + OpenDrainExternal, + #[cfg(not(gpio_v1))] + /// Open drain output using internal pull up resistor + OpenDrainInternal, +} + +impl HalfDuplexConfig { + fn af_type(self) -> gpio::AfType { + match self { + HalfDuplexConfig::PushPull => AfType::output(OutputType::PushPull, Speed::Medium), + HalfDuplexConfig::OpenDrainExternal => AfType::output(OutputType::OpenDrain, Speed::Medium), + #[cfg(not(gpio_v1))] + HalfDuplexConfig::OpenDrainInternal => AfType::output_pull(OutputType::OpenDrain, Speed::Medium, Pull::Up), } } } @@ -208,13 +269,20 @@ enum ReadCompletionEvent { Idle(usize), } -/// Bidirectional UART Driver -pub struct Uart<'d, T: BasicInstance, TxDma = NoDma, RxDma = NoDma> { - tx: UartTx<'d, T, TxDma>, - rx: UartRx<'d, T, RxDma>, +/// Bidirectional UART Driver, which acts as a combination of [`UartTx`] and [`UartRx`]. +/// +/// ### Notes on [`embedded_io::Read`] +/// +/// `embedded_io::Read` requires guarantees that the base [`UartRx`] cannot provide. +/// +/// See [`UartRx`] for more details, and see [`BufferedUart`] and [`RingBufferedUartRx`] +/// as alternatives that do provide the necessary guarantees for `embedded_io::Read`. +pub struct Uart<'d, M: Mode> { + tx: UartTx<'d, M>, + rx: UartRx<'d, M>, } -impl<'d, T: BasicInstance, TxDma, RxDma> SetConfig for Uart<'d, T, TxDma, RxDma> { +impl<'d, M: Mode> SetConfig for Uart<'d, M> { type Config = Config; type ConfigError = ConfigError; @@ -224,13 +292,22 @@ impl<'d, T: BasicInstance, TxDma, RxDma> SetConfig for Uart<'d, T, TxDma, RxDma> } } -/// Tx-only UART Driver -pub struct UartTx<'d, T: BasicInstance, TxDma = NoDma> { - phantom: PhantomData<&'d mut T>, - tx_dma: PeripheralRef<'d, TxDma>, +/// Tx-only UART Driver. +/// +/// Can be obtained from [`Uart::split`], or can be constructed independently, +/// if you do not need the receiving half of the driver. +pub struct UartTx<'d, M: Mode> { + info: &'static Info, + state: &'static State, + kernel_clock: Hertz, + tx: Option>, + cts: Option>, + de: Option>, + tx_dma: Option>, + _phantom: PhantomData, } -impl<'d, T: BasicInstance, TxDma> SetConfig for UartTx<'d, T, TxDma> { +impl<'d, M: Mode> SetConfig for UartTx<'d, M> { type Config = Config; type ConfigError = ConfigError; @@ -239,16 +316,49 @@ impl<'d, T: BasicInstance, TxDma> SetConfig for UartTx<'d, T, TxDma> { } } -/// Rx-only UART Driver -pub struct UartRx<'d, T: BasicInstance, RxDma = NoDma> { - _peri: PeripheralRef<'d, T>, - rx_dma: PeripheralRef<'d, RxDma>, +/// Rx-only UART Driver. +/// +/// Can be obtained from [`Uart::split`], or can be constructed independently, +/// if you do not need the transmitting half of the driver. +/// +/// ### Notes on [`embedded_io::Read`] +/// +/// `embedded_io::Read` requires guarantees that this struct cannot provide: +/// +/// - Any data received between calls to [`UartRx::read`] or [`UartRx::blocking_read`] +/// will be thrown away, as `UartRx` is unbuffered. +/// Users of `embedded_io::Read` are likely to not expect this behavior +/// (for instance if they read multiple small chunks in a row). +/// - [`UartRx::read`] and [`UartRx::blocking_read`] only return once the entire buffer has been +/// filled, whereas `embedded_io::Read` requires us to fill the buffer with what we already +/// received, and only block/wait until the first byte arrived. +///
+/// While [`UartRx::read_until_idle`] does return early, it will still eagerly wait for data until +/// the buffer is full or no data has been transmitted in a while, +/// which may not be what users of `embedded_io::Read` expect. +/// +/// [`UartRx::into_ring_buffered`] can be called to equip `UartRx` with a buffer, +/// that it can then use to store data received between calls to `read`, +/// provided you are using DMA already. +/// +/// Alternatively, you can use [`BufferedUartRx`], which is interrupt-based and which can also +/// store data received between calls. +/// +/// Also see [this github comment](https://github.com/embassy-rs/embassy/pull/2185#issuecomment-1810047043). +pub struct UartRx<'d, M: Mode> { + info: &'static Info, + state: &'static State, + kernel_clock: Hertz, + rx: Option>, + rts: Option>, + rx_dma: Option>, detect_previous_overrun: bool, #[cfg(any(usart_v1, usart_v2))] buffered_sr: stm32_metapac::usart::regs::Sr, + _phantom: PhantomData, } -impl<'d, T: BasicInstance, RxDma> SetConfig for UartRx<'d, T, RxDma> { +impl<'d, M: Mode> SetConfig for UartRx<'d, M> { type Config = Config; type ConfigError = ConfigError; @@ -257,86 +367,158 @@ impl<'d, T: BasicInstance, RxDma> SetConfig for UartRx<'d, T, RxDma> { } } -impl<'d, T: BasicInstance, TxDma> UartTx<'d, T, TxDma> { +impl<'d> UartTx<'d, Async> { /// Useful if you only want Uart Tx. It saves 1 pin and consumes a little less power. - pub fn new( + pub fn new( peri: impl Peripheral

+ 'd, tx: impl Peripheral

> + 'd, - tx_dma: impl Peripheral

+ 'd, + tx_dma: impl Peripheral

> + 'd, config: Config, ) -> Result { - T::enable_and_reset(); - - Self::new_inner(peri, tx, tx_dma, config) + Self::new_inner( + peri, + new_pin!(tx, AfType::output(OutputType::PushPull, Speed::Medium)), + None, + new_dma!(tx_dma), + config, + ) } /// Create a new tx-only UART with a clear-to-send pin - pub fn new_with_cts( + pub fn new_with_cts( peri: impl Peripheral

+ 'd, tx: impl Peripheral

> + 'd, cts: impl Peripheral

> + 'd, - tx_dma: impl Peripheral

+ 'd, + tx_dma: impl Peripheral

> + 'd, config: Config, ) -> Result { - into_ref!(cts); - - T::enable_and_reset(); - - cts.set_as_af(cts.af_num(), AFType::Input); - T::regs().cr3().write(|w| { - w.set_ctse(true); - }); - Self::new_inner(peri, tx, tx_dma, config) - } - - fn new_inner( - _peri: impl Peripheral

+ 'd, - tx: impl Peripheral

> + 'd, - tx_dma: impl Peripheral

+ 'd, - config: Config, - ) -> Result { - into_ref!(_peri, tx, tx_dma); - - let r = T::regs(); - - tx.set_as_af(tx.af_num(), AFType::OutputPushPull); - - configure(r, &config, T::frequency(), T::KIND, false, true)?; - - // create state once! - let _s = T::state(); - - Ok(Self { - tx_dma, - phantom: PhantomData, - }) - } - - /// Reconfigure the driver - pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> { - reconfigure::(config) + Self::new_inner( + peri, + new_pin!(tx, AfType::output(OutputType::PushPull, Speed::Medium)), + new_pin!(cts, AfType::input(Pull::None)), + new_dma!(tx_dma), + config, + ) } /// Initiate an asynchronous UART write - pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> - where - TxDma: crate::usart::TxDma, - { - let ch = &mut self.tx_dma; - let request = ch.request(); - T::regs().cr3().modify(|reg| { + pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> { + let r = self.info.regs; + + // Enable Transmitter and disable Receiver for Half-Duplex mode + let mut cr1 = r.cr1().read(); + if r.cr3().read().hdsel() && !cr1.te() { + cr1.set_te(true); + cr1.set_re(false); + r.cr1().write_value(cr1); + } + + let ch = self.tx_dma.as_mut().unwrap(); + r.cr3().modify(|reg| { reg.set_dmat(true); }); // If we don't assign future to a variable, the data register pointer // is held across an await and makes the future non-Send. - let transfer = unsafe { Transfer::new_write(ch, request, buffer, tdr(T::regs()), Default::default()) }; + let transfer = unsafe { ch.write(buffer, tdr(r), Default::default()) }; transfer.await; Ok(()) } + /// Wait until transmission complete + pub async fn flush(&mut self) -> Result<(), Error> { + flush(&self.info, &self.state).await + } +} + +impl<'d> UartTx<'d, Blocking> { + /// Create a new blocking tx-only UART with no hardware flow control. + /// + /// Useful if you only want Uart Tx. It saves 1 pin and consumes a little less power. + pub fn new_blocking( + peri: impl Peripheral

+ 'd, + tx: impl Peripheral

> + 'd, + config: Config, + ) -> Result { + Self::new_inner( + peri, + new_pin!(tx, AfType::output(OutputType::PushPull, Speed::Medium)), + None, + None, + config, + ) + } + + /// Create a new blocking tx-only UART with a clear-to-send pin + pub fn new_blocking_with_cts( + peri: impl Peripheral

+ 'd, + tx: impl Peripheral

> + 'd, + cts: impl Peripheral

> + 'd, + config: Config, + ) -> Result { + Self::new_inner( + peri, + new_pin!(tx, AfType::output(OutputType::PushPull, Speed::Medium)), + new_pin!(cts, AfType::input(config.rx_pull)), + None, + config, + ) + } +} + +impl<'d, M: Mode> UartTx<'d, M> { + fn new_inner( + _peri: impl Peripheral

+ 'd, + tx: Option>, + cts: Option>, + tx_dma: Option>, + config: Config, + ) -> Result { + let mut this = Self { + info: T::info(), + state: T::state(), + kernel_clock: T::frequency(), + tx, + cts, + de: None, + tx_dma, + _phantom: PhantomData, + }; + this.enable_and_configure(&config)?; + Ok(this) + } + + fn enable_and_configure(&mut self, config: &Config) -> Result<(), ConfigError> { + let info = self.info; + let state = self.state; + state.tx_rx_refcount.store(1, Ordering::Relaxed); + + info.rcc.enable_and_reset(); + + info.regs.cr3().modify(|w| { + w.set_ctse(self.cts.is_some()); + }); + configure(info, self.kernel_clock, config, false, true)?; + + Ok(()) + } + + /// Reconfigure the driver + pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> { + reconfigure(self.info, self.kernel_clock, config) + } + /// Perform a blocking UART write pub fn blocking_write(&mut self, buffer: &[u8]) -> Result<(), Error> { - let r = T::regs(); + let r = self.info.regs; + + // Enable Transmitter and disable Receiver for Half-Duplex mode + let mut cr1 = r.cr1().read(); + if r.cr3().read().hdsel() && !cr1.te() { + cr1.set_te(true); + cr1.set_re(false); + r.cr1().write_value(cr1); + } + for &b in buffer { while !sr(r).read().txe() {} unsafe { tdr(r).write_volatile(b) }; @@ -346,169 +528,116 @@ impl<'d, T: BasicInstance, TxDma> UartTx<'d, T, TxDma> { /// Block until transmission complete pub fn blocking_flush(&mut self) -> Result<(), Error> { - let r = T::regs(); - while !sr(r).read().tc() {} - Ok(()) + blocking_flush(self.info) + } + + /// Send break character + pub fn send_break(&self) { + send_break(&self.info.regs); } } -impl<'d, T: BasicInstance, RxDma> UartRx<'d, T, RxDma> { +/// Wait until transmission complete +async fn flush(info: &Info, state: &State) -> Result<(), Error> { + let r = info.regs; + if r.cr1().read().te() && !sr(r).read().tc() { + r.cr1().modify(|w| { + // enable Transmission Complete interrupt + w.set_tcie(true); + }); + + compiler_fence(Ordering::SeqCst); + + // future which completes when Transmission complete is detected + let abort = poll_fn(move |cx| { + state.rx_waker.register(cx.waker()); + + let sr = sr(r).read(); + if sr.tc() { + // Transmission complete detected + return Poll::Ready(()); + } + + Poll::Pending + }); + + abort.await; + } + + Ok(()) +} + +fn blocking_flush(info: &Info) -> Result<(), Error> { + let r = info.regs; + if r.cr1().read().te() { + while !sr(r).read().tc() {} + } + + Ok(()) +} + +/// Send break character +pub fn send_break(regs: &Regs) { + // Busy wait until previous break has been sent + #[cfg(any(usart_v1, usart_v2))] + while regs.cr1().read().sbk() {} + #[cfg(any(usart_v3, usart_v4))] + while regs.isr().read().sbkf() {} + + // Send break right after completing the current character transmission + #[cfg(any(usart_v1, usart_v2))] + regs.cr1().modify(|w| w.set_sbk(true)); + #[cfg(any(usart_v3, usart_v4))] + regs.rqr().write(|w| w.set_sbkrq(true)); +} + +impl<'d> UartRx<'d, Async> { + /// Create a new rx-only UART with no hardware flow control. + /// /// Useful if you only want Uart Rx. It saves 1 pin and consumes a little less power. - pub fn new( + pub fn new( peri: impl Peripheral

+ 'd, _irq: impl interrupt::typelevel::Binding> + 'd, rx: impl Peripheral

> + 'd, - rx_dma: impl Peripheral

+ 'd, + rx_dma: impl Peripheral

> + 'd, config: Config, ) -> Result { - T::enable_and_reset(); - - Self::new_inner(peri, rx, rx_dma, config) + Self::new_inner( + peri, + new_pin!(rx, AfType::input(config.rx_pull)), + None, + new_dma!(rx_dma), + config, + ) } /// Create a new rx-only UART with a request-to-send pin - pub fn new_with_rts( + pub fn new_with_rts( peri: impl Peripheral

+ 'd, _irq: impl interrupt::typelevel::Binding> + 'd, rx: impl Peripheral

> + 'd, rts: impl Peripheral

> + 'd, - rx_dma: impl Peripheral

+ 'd, + rx_dma: impl Peripheral

> + 'd, config: Config, ) -> Result { - into_ref!(rts); - - T::enable_and_reset(); - - rts.set_as_af(rts.af_num(), AFType::OutputPushPull); - T::regs().cr3().write(|w| { - w.set_rtse(true); - }); - - Self::new_inner(peri, rx, rx_dma, config) - } - - fn new_inner( - peri: impl Peripheral

+ 'd, - rx: impl Peripheral

> + 'd, - rx_dma: impl Peripheral

+ 'd, - config: Config, - ) -> Result { - into_ref!(peri, rx, rx_dma); - - let r = T::regs(); - - rx.set_as_af(rx.af_num(), AFType::Input); - - configure(r, &config, T::frequency(), T::KIND, true, false)?; - - T::Interrupt::unpend(); - unsafe { T::Interrupt::enable() }; - - // create state once! - let _s = T::state(); - - Ok(Self { - _peri: peri, - rx_dma, - detect_previous_overrun: config.detect_previous_overrun, - #[cfg(any(usart_v1, usart_v2))] - buffered_sr: stm32_metapac::usart::regs::Sr(0), - }) - } - - /// Reconfigure the driver - pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> { - reconfigure::(config) - } - - #[cfg(any(usart_v1, usart_v2))] - fn check_rx_flags(&mut self) -> Result { - let r = T::regs(); - loop { - // Handle all buffered error flags. - if self.buffered_sr.pe() { - self.buffered_sr.set_pe(false); - return Err(Error::Parity); - } else if self.buffered_sr.fe() { - self.buffered_sr.set_fe(false); - return Err(Error::Framing); - } else if self.buffered_sr.ne() { - self.buffered_sr.set_ne(false); - return Err(Error::Noise); - } else if self.buffered_sr.ore() { - self.buffered_sr.set_ore(false); - return Err(Error::Overrun); - } else if self.buffered_sr.rxne() { - self.buffered_sr.set_rxne(false); - return Ok(true); - } else { - // No error flags from previous iterations were set: Check the actual status register - let sr = r.sr().read(); - if !sr.rxne() { - return Ok(false); - } - - // Buffer the status register and let the loop handle the error flags. - self.buffered_sr = sr; - } - } - } - - #[cfg(any(usart_v3, usart_v4))] - fn check_rx_flags(&mut self) -> Result { - let r = T::regs(); - let sr = r.isr().read(); - if sr.pe() { - r.icr().write(|w| w.set_pe(true)); - return Err(Error::Parity); - } else if sr.fe() { - r.icr().write(|w| w.set_fe(true)); - return Err(Error::Framing); - } else if sr.ne() { - r.icr().write(|w| w.set_ne(true)); - return Err(Error::Noise); - } else if sr.ore() { - r.icr().write(|w| w.set_ore(true)); - return Err(Error::Overrun); - } - Ok(sr.rxne()) + Self::new_inner( + peri, + new_pin!(rx, AfType::input(config.rx_pull)), + new_pin!(rts, AfType::output(OutputType::PushPull, Speed::Medium)), + new_dma!(rx_dma), + config, + ) } /// Initiate an asynchronous UART read - pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> - where - RxDma: crate::usart::RxDma, - { + pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> { self.inner_read(buffer, false).await?; Ok(()) } - /// Read a single u8 if there is one available, otherwise return WouldBlock - pub fn nb_read(&mut self) -> Result> { - let r = T::regs(); - if self.check_rx_flags()? { - Ok(unsafe { rdr(r).read_volatile() }) - } else { - Err(nb::Error::WouldBlock) - } - } - - /// Perform a blocking read into `buffer` - pub fn blocking_read(&mut self, buffer: &mut [u8]) -> Result<(), Error> { - let r = T::regs(); - for b in buffer { - while !self.check_rx_flags()? {} - unsafe { *b = rdr(r).read_volatile() } - } - Ok(()) - } - /// Initiate an asynchronous read with idle line detection enabled - pub async fn read_until_idle(&mut self, buffer: &mut [u8]) -> Result - where - RxDma: crate::usart::RxDma, - { + pub async fn read_until_idle(&mut self, buffer: &mut [u8]) -> Result { self.inner_read(buffer, true).await } @@ -516,11 +645,20 @@ impl<'d, T: BasicInstance, RxDma> UartRx<'d, T, RxDma> { &mut self, buffer: &mut [u8], enable_idle_line_detection: bool, - ) -> Result - where - RxDma: crate::usart::RxDma, - { - let r = T::regs(); + ) -> Result { + let r = self.info.regs; + + // Call flush for Half-Duplex mode if some bytes were written and flush was not called. + // It prevents reading of bytes which have just been written. + if r.cr3().read().hdsel() && r.cr1().read().te() { + flush(&self.info, &self.state).await?; + + // Disable Transmitter and enable Receiver after flush + r.cr1().modify(|reg| { + reg.set_re(true); + reg.set_te(false); + }); + } // make sure USART state is restored to neutral state when this future is dropped let on_drop = OnDrop::new(move || { @@ -542,15 +680,14 @@ impl<'d, T: BasicInstance, RxDma> UartRx<'d, T, RxDma> { }); }); - let ch = &mut self.rx_dma; - let request = ch.request(); + let ch = self.rx_dma.as_mut().unwrap(); let buffer_len = buffer.len(); // Start USART DMA // will not do anything yet because DMAR is not yet set // future which will complete when DMA Read request completes - let transfer = unsafe { Transfer::new_read(ch, request, rdr(T::regs()), buffer, Default::default()) }; + let transfer = unsafe { ch.read(rdr(r), buffer, Default::default()) }; // clear ORE flag just before enabling DMA Rx Request: can be mandatory for the second transfer if !self.detect_previous_overrun { @@ -625,9 +762,8 @@ impl<'d, T: BasicInstance, RxDma> UartRx<'d, T, RxDma> { compiler_fence(Ordering::SeqCst); // future which completes when idle line or error is detected + let s = self.state; let abort = poll_fn(move |cx| { - let s = T::state(); - s.rx_waker.register(cx.waker()); let sr = sr(r).read(); @@ -693,10 +829,7 @@ impl<'d, T: BasicInstance, RxDma> UartRx<'d, T, RxDma> { r } - async fn inner_read(&mut self, buffer: &mut [u8], enable_idle_line_detection: bool) -> Result - where - RxDma: crate::usart::RxDma, - { + async fn inner_read(&mut self, buffer: &mut [u8], enable_idle_line_detection: bool) -> Result { if buffer.is_empty() { return Ok(0); } else if buffer.len() > 0xFFFF { @@ -716,119 +849,311 @@ impl<'d, T: BasicInstance, RxDma> UartRx<'d, T, RxDma> { } } -impl<'d, T: BasicInstance, TxDma> Drop for UartTx<'d, T, TxDma> { - fn drop(&mut self) { - T::disable(); +impl<'d> UartRx<'d, Blocking> { + /// Create a new rx-only UART with no hardware flow control. + /// + /// Useful if you only want Uart Rx. It saves 1 pin and consumes a little less power. + pub fn new_blocking( + peri: impl Peripheral

+ 'd, + rx: impl Peripheral

> + 'd, + config: Config, + ) -> Result { + Self::new_inner(peri, new_pin!(rx, AfType::input(config.rx_pull)), None, None, config) + } + + /// Create a new rx-only UART with a request-to-send pin + pub fn new_blocking_with_rts( + peri: impl Peripheral

+ 'd, + rx: impl Peripheral

> + 'd, + rts: impl Peripheral

> + 'd, + config: Config, + ) -> Result { + Self::new_inner( + peri, + new_pin!(rx, AfType::input(config.rx_pull)), + new_pin!(rts, AfType::output(OutputType::PushPull, Speed::Medium)), + None, + config, + ) } } -impl<'d, T: BasicInstance, TxDma> Drop for UartRx<'d, T, TxDma> { - fn drop(&mut self) { - T::disable(); +impl<'d, M: Mode> UartRx<'d, M> { + fn new_inner( + _peri: impl Peripheral

+ 'd, + rx: Option>, + rts: Option>, + rx_dma: Option>, + config: Config, + ) -> Result { + let mut this = Self { + _phantom: PhantomData, + info: T::info(), + state: T::state(), + kernel_clock: T::frequency(), + rx, + rts, + rx_dma, + detect_previous_overrun: config.detect_previous_overrun, + #[cfg(any(usart_v1, usart_v2))] + buffered_sr: stm32_metapac::usart::regs::Sr(0), + }; + this.enable_and_configure(&config)?; + Ok(this) + } + + fn enable_and_configure(&mut self, config: &Config) -> Result<(), ConfigError> { + let info = self.info; + let state = self.state; + state.tx_rx_refcount.store(1, Ordering::Relaxed); + + info.rcc.enable_and_reset(); + + info.regs.cr3().write(|w| { + w.set_rtse(self.rts.is_some()); + }); + configure(info, self.kernel_clock, &config, true, false)?; + + info.interrupt.unpend(); + unsafe { info.interrupt.enable() }; + + Ok(()) + } + + /// Reconfigure the driver + pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> { + reconfigure(self.info, self.kernel_clock, config) + } + + #[cfg(any(usart_v1, usart_v2))] + fn check_rx_flags(&mut self) -> Result { + let r = self.info.regs; + loop { + // Handle all buffered error flags. + if self.buffered_sr.pe() { + self.buffered_sr.set_pe(false); + return Err(Error::Parity); + } else if self.buffered_sr.fe() { + self.buffered_sr.set_fe(false); + return Err(Error::Framing); + } else if self.buffered_sr.ne() { + self.buffered_sr.set_ne(false); + return Err(Error::Noise); + } else if self.buffered_sr.ore() { + self.buffered_sr.set_ore(false); + return Err(Error::Overrun); + } else if self.buffered_sr.rxne() { + self.buffered_sr.set_rxne(false); + return Ok(true); + } else { + // No error flags from previous iterations were set: Check the actual status register + let sr = r.sr().read(); + if !sr.rxne() { + return Ok(false); + } + + // Buffer the status register and let the loop handle the error flags. + self.buffered_sr = sr; + } + } + } + + #[cfg(any(usart_v3, usart_v4))] + fn check_rx_flags(&mut self) -> Result { + let r = self.info.regs; + let sr = r.isr().read(); + if sr.pe() { + r.icr().write(|w| w.set_pe(true)); + return Err(Error::Parity); + } else if sr.fe() { + r.icr().write(|w| w.set_fe(true)); + return Err(Error::Framing); + } else if sr.ne() { + r.icr().write(|w| w.set_ne(true)); + return Err(Error::Noise); + } else if sr.ore() { + r.icr().write(|w| w.set_ore(true)); + return Err(Error::Overrun); + } + Ok(sr.rxne()) + } + + /// Read a single u8 if there is one available, otherwise return WouldBlock + pub(crate) fn nb_read(&mut self) -> Result> { + let r = self.info.regs; + if self.check_rx_flags()? { + Ok(unsafe { rdr(r).read_volatile() }) + } else { + Err(nb::Error::WouldBlock) + } + } + + /// Perform a blocking read into `buffer` + pub fn blocking_read(&mut self, buffer: &mut [u8]) -> Result<(), Error> { + let r = self.info.regs; + + // Call flush for Half-Duplex mode if some bytes were written and flush was not called. + // It prevents reading of bytes which have just been written. + if r.cr3().read().hdsel() && r.cr1().read().te() { + blocking_flush(self.info)?; + + // Disable Transmitter and enable Receiver after flush + r.cr1().modify(|reg| { + reg.set_re(true); + reg.set_te(false); + }); + } + + for b in buffer { + while !self.check_rx_flags()? {} + unsafe { *b = rdr(r).read_volatile() } + } + Ok(()) } } -impl<'d, T: BasicInstance, TxDma, RxDma> Uart<'d, T, TxDma, RxDma> { +impl<'d, M: Mode> Drop for UartTx<'d, M> { + fn drop(&mut self) { + self.tx.as_ref().map(|x| x.set_as_disconnected()); + self.cts.as_ref().map(|x| x.set_as_disconnected()); + self.de.as_ref().map(|x| x.set_as_disconnected()); + drop_tx_rx(self.info, self.state); + } +} + +impl<'d, M: Mode> Drop for UartRx<'d, M> { + fn drop(&mut self) { + self.rx.as_ref().map(|x| x.set_as_disconnected()); + self.rts.as_ref().map(|x| x.set_as_disconnected()); + drop_tx_rx(self.info, self.state); + } +} + +fn drop_tx_rx(info: &Info, state: &State) { + // We cannot use atomic subtraction here, because it's not supported for all targets + let is_last_drop = critical_section::with(|_| { + let refcount = state.tx_rx_refcount.load(Ordering::Relaxed); + assert!(refcount >= 1); + state.tx_rx_refcount.store(refcount - 1, Ordering::Relaxed); + refcount == 1 + }); + if is_last_drop { + info.rcc.disable(); + } +} + +impl<'d> Uart<'d, Async> { /// Create a new bidirectional UART - pub fn new( + pub fn new( peri: impl Peripheral

+ 'd, rx: impl Peripheral

> + 'd, tx: impl Peripheral

> + 'd, _irq: impl interrupt::typelevel::Binding> + 'd, - tx_dma: impl Peripheral

+ 'd, - rx_dma: impl Peripheral

+ 'd, + tx_dma: impl Peripheral

> + 'd, + rx_dma: impl Peripheral

> + 'd, config: Config, ) -> Result { - // UartRx and UartTx have one refcount ea. - T::enable_and_reset(); - T::enable_and_reset(); - - Self::new_inner_configure(peri, rx, tx, tx_dma, rx_dma, config) + Self::new_inner( + peri, + new_pin!(rx, config.rx_af()), + new_pin!(tx, config.tx_af()), + None, + None, + None, + new_dma!(tx_dma), + new_dma!(rx_dma), + config, + ) } /// Create a new bidirectional UART with request-to-send and clear-to-send pins - pub fn new_with_rtscts( + pub fn new_with_rtscts( peri: impl Peripheral

+ 'd, rx: impl Peripheral

> + 'd, tx: impl Peripheral

> + 'd, _irq: impl interrupt::typelevel::Binding> + 'd, rts: impl Peripheral

> + 'd, cts: impl Peripheral

> + 'd, - tx_dma: impl Peripheral

+ 'd, - rx_dma: impl Peripheral

+ 'd, + tx_dma: impl Peripheral

> + 'd, + rx_dma: impl Peripheral

> + 'd, config: Config, ) -> Result { - into_ref!(cts, rts); - - // UartRx and UartTx have one refcount ea. - T::enable_and_reset(); - T::enable_and_reset(); - - rts.set_as_af(rts.af_num(), AFType::OutputPushPull); - cts.set_as_af(cts.af_num(), AFType::Input); - T::regs().cr3().write(|w| { - w.set_rtse(true); - w.set_ctse(true); - }); - Self::new_inner_configure(peri, rx, tx, tx_dma, rx_dma, config) + Self::new_inner( + peri, + new_pin!(rx, config.rx_af()), + new_pin!(tx, config.tx_af()), + new_pin!(rts, AfType::output(OutputType::PushPull, Speed::Medium)), + new_pin!(cts, AfType::input(Pull::None)), + None, + new_dma!(tx_dma), + new_dma!(rx_dma), + config, + ) } #[cfg(not(any(usart_v1, usart_v2)))] /// Create a new bidirectional UART with a driver-enable pin - pub fn new_with_de( + pub fn new_with_de( peri: impl Peripheral

+ 'd, rx: impl Peripheral

> + 'd, tx: impl Peripheral

> + 'd, _irq: impl interrupt::typelevel::Binding> + 'd, de: impl Peripheral

> + 'd, - tx_dma: impl Peripheral

+ 'd, - rx_dma: impl Peripheral

+ 'd, + tx_dma: impl Peripheral

> + 'd, + rx_dma: impl Peripheral

> + 'd, config: Config, ) -> Result { - into_ref!(de); - - // UartRx and UartTx have one refcount ea. - T::enable_and_reset(); - T::enable_and_reset(); - - de.set_as_af(de.af_num(), AFType::OutputPushPull); - T::regs().cr3().write(|w| { - w.set_dem(true); - }); - Self::new_inner_configure(peri, rx, tx, tx_dma, rx_dma, config) + Self::new_inner( + peri, + new_pin!(rx, config.rx_af()), + new_pin!(tx, config.tx_af()), + None, + None, + new_pin!(de, AfType::output(OutputType::PushPull, Speed::Medium)), + new_dma!(tx_dma), + new_dma!(rx_dma), + config, + ) } /// Create a single-wire half-duplex Uart transceiver on a single Tx pin. /// - /// See [`new_half_duplex_on_rx`][`Self::new_half_duplex_on_rx`] if you would prefer to use an Rx pin. - /// There is no functional difference between these methods, as both allow bidirectional communication. + /// See [`new_half_duplex_on_rx`][`Self::new_half_duplex_on_rx`] if you would prefer to use an Rx pin + /// (when it is available for your chip). There is no functional difference between these methods, as both + /// allow bidirectional communication. /// - /// The pin is always released when no data is transmitted. Thus, it acts as a standard - /// I/O in idle or in reception. + /// The TX pin is always released when no data is transmitted. Thus, it acts as a standard + /// I/O in idle or in reception. It means that the I/O must be configured so that TX is + /// configured as alternate function open-drain with an external pull-up /// Apart from this, the communication protocol is similar to normal USART mode. Any conflict /// on the line must be managed by software (for instance by using a centralized arbiter). - #[cfg(not(any(usart_v1, usart_v2)))] #[doc(alias("HDSEL"))] - pub fn new_half_duplex( + pub fn new_half_duplex( peri: impl Peripheral

+ 'd, tx: impl Peripheral

> + 'd, _irq: impl interrupt::typelevel::Binding> + 'd, - tx_dma: impl Peripheral

+ 'd, - rx_dma: impl Peripheral

+ 'd, + tx_dma: impl Peripheral

> + 'd, + rx_dma: impl Peripheral

> + 'd, mut config: Config, + half_duplex: HalfDuplexConfig, ) -> Result { - // UartRx and UartTx have one refcount ea. - T::enable_and_reset(); - T::enable_and_reset(); + #[cfg(not(any(usart_v1, usart_v2)))] + { + config.swap_rx_tx = false; + } + config.half_duplex = true; - config.swap_rx_tx = false; - - into_ref!(peri, tx, tx_dma, rx_dma); - - T::regs().cr3().write(|w| w.set_hdsel(true)); - tx.set_as_af(tx.af_num(), AFType::OutputPushPull); - - Self::new_inner(peri, tx_dma, rx_dma, config) + Self::new_inner( + peri, + None, + new_pin!(tx, half_duplex.af_type()), + None, + None, + None, + new_dma!(tx_dma), + new_dma!(rx_dma), + config, + ) } /// Create a single-wire half-duplex Uart transceiver on a single Rx pin. @@ -842,95 +1167,250 @@ impl<'d, T: BasicInstance, TxDma, RxDma> Uart<'d, T, TxDma, RxDma> { /// on the line must be managed by software (for instance by using a centralized arbiter). #[cfg(not(any(usart_v1, usart_v2)))] #[doc(alias("HDSEL"))] - pub fn new_half_duplex_on_rx( + pub fn new_half_duplex_on_rx( peri: impl Peripheral

+ 'd, rx: impl Peripheral

> + 'd, _irq: impl interrupt::typelevel::Binding> + 'd, - tx_dma: impl Peripheral

+ 'd, - rx_dma: impl Peripheral

+ 'd, + tx_dma: impl Peripheral

> + 'd, + rx_dma: impl Peripheral

> + 'd, mut config: Config, + half_duplex: HalfDuplexConfig, ) -> Result { - // UartRx and UartTx have one refcount ea. - T::enable_and_reset(); - T::enable_and_reset(); - config.swap_rx_tx = true; + config.half_duplex = true; - into_ref!(peri, rx, tx_dma, rx_dma); - - T::regs().cr3().write(|w| w.set_hdsel(true)); - rx.set_as_af(rx.af_num(), AFType::OutputPushPull); - - Self::new_inner(peri, tx_dma, rx_dma, config) + Self::new_inner( + peri, + None, + None, + new_pin!(rx, half_duplex.af_type()), + None, + None, + new_dma!(tx_dma), + new_dma!(rx_dma), + config, + ) } - fn new_inner_configure( + /// Perform an asynchronous write + pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> { + self.tx.write(buffer).await + } + + /// Wait until transmission complete + pub async fn flush(&mut self) -> Result<(), Error> { + self.tx.flush().await + } + + /// Perform an asynchronous read into `buffer` + pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> { + self.rx.read(buffer).await + } + + /// Perform an an asynchronous read with idle line detection enabled + pub async fn read_until_idle(&mut self, buffer: &mut [u8]) -> Result { + self.rx.read_until_idle(buffer).await + } +} + +impl<'d> Uart<'d, Blocking> { + /// Create a new blocking bidirectional UART. + pub fn new_blocking( peri: impl Peripheral

+ 'd, rx: impl Peripheral

> + 'd, tx: impl Peripheral

> + 'd, - tx_dma: impl Peripheral

+ 'd, - rx_dma: impl Peripheral

+ 'd, config: Config, ) -> Result { - into_ref!(peri, rx, tx, tx_dma, rx_dma); - - // Some chips do not have swap_rx_tx bit - cfg_if::cfg_if! { - if #[cfg(any(usart_v3, usart_v4))] { - if config.swap_rx_tx { - let (rx, tx) = (tx, rx); - rx.set_as_af(rx.af_num(), AFType::Input); - tx.set_as_af(tx.af_num(), AFType::OutputPushPull); - } else { - rx.set_as_af(rx.af_num(), AFType::Input); - tx.set_as_af(tx.af_num(), AFType::OutputPushPull); - } - } else { - rx.set_as_af(rx.af_num(), AFType::Input); - tx.set_as_af(tx.af_num(), AFType::OutputPushPull); - } - } - - Self::new_inner(peri, tx_dma, rx_dma, config) + Self::new_inner( + peri, + new_pin!(rx, config.rx_af()), + new_pin!(tx, config.tx_af()), + None, + None, + None, + None, + None, + config, + ) } - fn new_inner( - peri: PeripheralRef<'d, T>, - tx_dma: PeripheralRef<'d, TxDma>, - rx_dma: PeripheralRef<'d, RxDma>, + /// Create a new bidirectional UART with request-to-send and clear-to-send pins + pub fn new_blocking_with_rtscts( + peri: impl Peripheral

+ 'd, + rx: impl Peripheral

> + 'd, + tx: impl Peripheral

> + 'd, + rts: impl Peripheral

> + 'd, + cts: impl Peripheral

> + 'd, config: Config, ) -> Result { - let r = T::regs(); + Self::new_inner( + peri, + new_pin!(rx, config.rx_af()), + new_pin!(tx, config.tx_af()), + new_pin!(rts, AfType::output(OutputType::PushPull, Speed::Medium)), + new_pin!(cts, AfType::input(Pull::None)), + None, + None, + None, + config, + ) + } - configure(r, &config, T::frequency(), T::KIND, true, true)?; + #[cfg(not(any(usart_v1, usart_v2)))] + /// Create a new bidirectional UART with a driver-enable pin + pub fn new_blocking_with_de( + peri: impl Peripheral

+ 'd, + rx: impl Peripheral

> + 'd, + tx: impl Peripheral

> + 'd, + de: impl Peripheral

> + 'd, + config: Config, + ) -> Result { + Self::new_inner( + peri, + new_pin!(rx, config.rx_af()), + new_pin!(tx, config.tx_af()), + None, + None, + new_pin!(de, AfType::output(OutputType::PushPull, Speed::Medium)), + None, + None, + config, + ) + } - T::Interrupt::unpend(); - unsafe { T::Interrupt::enable() }; + /// Create a single-wire half-duplex Uart transceiver on a single Tx pin. + /// + /// See [`new_half_duplex_on_rx`][`Self::new_half_duplex_on_rx`] if you would prefer to use an Rx pin + /// (when it is available for your chip). There is no functional difference between these methods, as both + /// allow bidirectional communication. + /// + /// The pin is always released when no data is transmitted. Thus, it acts as a standard + /// I/O in idle or in reception. + /// Apart from this, the communication protocol is similar to normal USART mode. Any conflict + /// on the line must be managed by software (for instance by using a centralized arbiter). + #[doc(alias("HDSEL"))] + pub fn new_blocking_half_duplex( + peri: impl Peripheral

+ 'd, + tx: impl Peripheral

> + 'd, + mut config: Config, + half_duplex: HalfDuplexConfig, + ) -> Result { + #[cfg(not(any(usart_v1, usart_v2)))] + { + config.swap_rx_tx = false; + } + config.half_duplex = true; - // create state once! - let _s = T::state(); + Self::new_inner( + peri, + None, + new_pin!(tx, half_duplex.af_type()), + None, + None, + None, + None, + None, + config, + ) + } - Ok(Self { + /// Create a single-wire half-duplex Uart transceiver on a single Rx pin. + /// + /// See [`new_half_duplex`][`Self::new_half_duplex`] if you would prefer to use an Tx pin. + /// There is no functional difference between these methods, as both allow bidirectional communication. + /// + /// The pin is always released when no data is transmitted. Thus, it acts as a standard + /// I/O in idle or in reception. + /// Apart from this, the communication protocol is similar to normal USART mode. Any conflict + /// on the line must be managed by software (for instance by using a centralized arbiter). + #[cfg(not(any(usart_v1, usart_v2)))] + #[doc(alias("HDSEL"))] + pub fn new_blocking_half_duplex_on_rx( + peri: impl Peripheral

+ 'd, + rx: impl Peripheral

> + 'd, + mut config: Config, + half_duplex: HalfDuplexConfig, + ) -> Result { + config.swap_rx_tx = true; + config.half_duplex = true; + + Self::new_inner( + peri, + None, + None, + new_pin!(rx, half_duplex.af_type()), + None, + None, + None, + None, + config, + ) + } +} + +impl<'d, M: Mode> Uart<'d, M> { + fn new_inner( + _peri: impl Peripheral

+ 'd, + rx: Option>, + tx: Option>, + rts: Option>, + cts: Option>, + de: Option>, + tx_dma: Option>, + rx_dma: Option>, + config: Config, + ) -> Result { + let info = T::info(); + let state = T::state(); + let kernel_clock = T::frequency(); + + let mut this = Self { tx: UartTx { + _phantom: PhantomData, + info, + state, + kernel_clock, + tx, + cts, + de, tx_dma, - phantom: PhantomData, }, rx: UartRx { - _peri: peri, + _phantom: PhantomData, + info, + state, + kernel_clock, + rx, + rts, rx_dma, detect_previous_overrun: config.detect_previous_overrun, #[cfg(any(usart_v1, usart_v2))] buffered_sr: stm32_metapac::usart::regs::Sr(0), }, - }) + }; + this.enable_and_configure(&config)?; + Ok(this) } - /// Initiate an asynchronous write - pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> - where - TxDma: crate::usart::TxDma, - { - self.tx.write(buffer).await + fn enable_and_configure(&mut self, config: &Config) -> Result<(), ConfigError> { + let info = self.rx.info; + let state = self.rx.state; + state.tx_rx_refcount.store(2, Ordering::Relaxed); + + info.rcc.enable_and_reset(); + + info.regs.cr3().write(|w| { + w.set_rtse(self.rx.rts.is_some()); + w.set_ctse(self.tx.cts.is_some()); + #[cfg(not(any(usart_v1, usart_v2)))] + w.set_dem(self.tx.de.is_some()); + }); + configure(info, self.rx.kernel_clock, config, true, true)?; + + info.interrupt.unpend(); + unsafe { info.interrupt.enable() }; + + Ok(()) } /// Perform a blocking write @@ -943,16 +1423,8 @@ impl<'d, T: BasicInstance, TxDma, RxDma> Uart<'d, T, TxDma, RxDma> { self.tx.blocking_flush() } - /// Initiate an asynchronous read into `buffer` - pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> - where - RxDma: crate::usart::RxDma, - { - self.rx.read(buffer).await - } - /// Read a single `u8` or return `WouldBlock` - pub fn nb_read(&mut self) -> Result> { + pub(crate) fn nb_read(&mut self) -> Result> { self.rx.nb_read() } @@ -961,43 +1433,49 @@ impl<'d, T: BasicInstance, TxDma, RxDma> Uart<'d, T, TxDma, RxDma> { self.rx.blocking_read(buffer) } - /// Initiate an an asynchronous read with idle line detection enabled - pub async fn read_until_idle(&mut self, buffer: &mut [u8]) -> Result - where - RxDma: crate::usart::RxDma, - { - self.rx.read_until_idle(buffer).await - } - /// Split the Uart into a transmitter and receiver, which is /// particularly useful when having two tasks correlating to /// transmitting and receiving. - pub fn split(self) -> (UartTx<'d, T, TxDma>, UartRx<'d, T, RxDma>) { + pub fn split(self) -> (UartTx<'d, M>, UartRx<'d, M>) { (self.tx, self.rx) } + + /// Split the Uart into a transmitter and receiver by mutable reference, + /// which is particularly useful when having two tasks correlating to + /// transmitting and receiving. + pub fn split_ref(&mut self) -> (&mut UartTx<'d, M>, &mut UartRx<'d, M>) { + (&mut self.tx, &mut self.rx) + } + + /// Send break character + pub fn send_break(&self) { + self.tx.send_break(); + } } -fn reconfigure(config: &Config) -> Result<(), ConfigError> { - T::Interrupt::disable(); - let r = T::regs(); +fn reconfigure(info: &Info, kernel_clock: Hertz, config: &Config) -> Result<(), ConfigError> { + info.interrupt.disable(); + let r = info.regs; let cr = r.cr1().read(); - configure(r, config, T::frequency(), T::KIND, cr.re(), cr.te())?; + configure(info, kernel_clock, config, cr.re(), cr.te())?; - T::Interrupt::unpend(); - unsafe { T::Interrupt::enable() }; + info.interrupt.unpend(); + unsafe { info.interrupt.enable() }; Ok(()) } fn configure( - r: Regs, + info: &Info, + kernel_clock: Hertz, config: &Config, - pclk_freq: Hertz, - kind: Kind, enable_rx: bool, enable_tx: bool, ) -> Result<(), ConfigError> { + let r = info.regs; + let kind = info.kind; + if !enable_rx && !enable_tx { return Err(ConfigError::RxOrTxNotEnabled); } @@ -1023,8 +1501,14 @@ fn configure( let (mul, brr_min, brr_max) = match kind { #[cfg(any(usart_v3, usart_v4))] - Kind::Lpuart => (256, 0x300, 0x10_0000), - Kind::Uart => (1, 0x10, 0x1_0000), + Kind::Lpuart => { + trace!("USART: Kind::Lpuart"); + (256, 0x300, 0x10_0000) + } + Kind::Uart => { + trace!("USART: Kind::Uart"); + (1, 0x10, 0x1_0000) + } }; fn calculate_brr(baud: u32, pclk: u32, presc: u32, mul: u32) -> u32 { @@ -1051,7 +1535,7 @@ fn configure( let mut over8 = false; let mut found_brr = None; for &(presc, _presc_val) in &DIVS { - let brr = calculate_brr(config.baudrate, pclk_freq.0, presc as u32, mul); + let brr = calculate_brr(config.baudrate, kernel_clock.0, presc as u32, mul); trace!( "USART: presc={}, div=0x{:08x} (mantissa = {}, fraction = {})", presc, @@ -1092,7 +1576,7 @@ fn configure( "Using {} oversampling, desired baudrate: {}, actual baudrate: {}", oversampling, config.baudrate, - pclk_freq.0 / brr * mul + kernel_clock.0 / brr * mul ); r.cr2().write(|w| { @@ -1111,49 +1595,73 @@ fn configure( } }); - #[cfg(not(usart_v1))] r.cr3().modify(|w| { + #[cfg(not(usart_v1))] w.set_onebit(config.assume_noise_free); + w.set_hdsel(config.half_duplex); }); r.cr1().write(|w| { // enable uart w.set_ue(true); - // enable transceiver - w.set_te(enable_tx); - // enable receiver - w.set_re(enable_rx); + + if config.half_duplex { + // The te and re bits will be set by write, read and flush methods. + // Receiver should be enabled by default for Half-Duplex. + w.set_te(false); + w.set_re(true); + } else { + // enable transceiver + w.set_te(enable_tx); + // enable receiver + w.set_re(enable_rx); + } + // configure word size // if using odd or even parity it must be configured to 9bits w.set_m0(if config.parity != Parity::ParityNone { + trace!("USART: m0: vals::M0::BIT9"); vals::M0::BIT9 } else { + trace!("USART: m0: vals::M0::BIT8"); vals::M0::BIT8 }); // configure parity w.set_pce(config.parity != Parity::ParityNone); w.set_ps(match config.parity { - Parity::ParityOdd => vals::Ps::ODD, - Parity::ParityEven => vals::Ps::EVEN, - _ => vals::Ps::EVEN, + Parity::ParityOdd => { + trace!("USART: set_ps: vals::Ps::ODD"); + vals::Ps::ODD + } + Parity::ParityEven => { + trace!("USART: set_ps: vals::Ps::EVEN"); + vals::Ps::EVEN + } + _ => { + trace!("USART: set_ps: vals::Ps::EVEN"); + vals::Ps::EVEN + } }); #[cfg(not(usart_v1))] w.set_over8(vals::Over8::from_bits(over8 as _)); #[cfg(usart_v4)] - w.set_fifoen(true); + { + trace!("USART: set_fifoen: true (usart_v4)"); + w.set_fifoen(true); + } }); Ok(()) } -impl<'d, T: BasicInstance, RxDma> embedded_hal_02::serial::Read for UartRx<'d, T, RxDma> { +impl<'d, M: Mode> embedded_hal_02::serial::Read for UartRx<'d, M> { type Error = Error; fn read(&mut self) -> Result> { self.nb_read() } } -impl<'d, T: BasicInstance, TxDma> embedded_hal_02::blocking::serial::Write for UartTx<'d, T, TxDma> { +impl<'d, M: Mode> embedded_hal_02::blocking::serial::Write for UartTx<'d, M> { type Error = Error; fn bwrite_all(&mut self, buffer: &[u8]) -> Result<(), Self::Error> { self.blocking_write(buffer) @@ -1163,14 +1671,14 @@ impl<'d, T: BasicInstance, TxDma> embedded_hal_02::blocking::serial::Write f } } -impl<'d, T: BasicInstance, TxDma, RxDma> embedded_hal_02::serial::Read for Uart<'d, T, TxDma, RxDma> { +impl<'d, M: Mode> embedded_hal_02::serial::Read for Uart<'d, M> { type Error = Error; fn read(&mut self) -> Result> { self.nb_read() } } -impl<'d, T: BasicInstance, TxDma, RxDma> embedded_hal_02::blocking::serial::Write for Uart<'d, T, TxDma, RxDma> { +impl<'d, M: Mode> embedded_hal_02::blocking::serial::Write for Uart<'d, M> { type Error = Error; fn bwrite_all(&mut self, buffer: &[u8]) -> Result<(), Self::Error> { self.blocking_write(buffer) @@ -1192,25 +1700,25 @@ impl embedded_hal_nb::serial::Error for Error { } } -impl<'d, T: BasicInstance, TxDma, RxDma> embedded_hal_nb::serial::ErrorType for Uart<'d, T, TxDma, RxDma> { +impl<'d, M: Mode> embedded_hal_nb::serial::ErrorType for Uart<'d, M> { type Error = Error; } -impl<'d, T: BasicInstance, TxDma> embedded_hal_nb::serial::ErrorType for UartTx<'d, T, TxDma> { +impl<'d, M: Mode> embedded_hal_nb::serial::ErrorType for UartTx<'d, M> { type Error = Error; } -impl<'d, T: BasicInstance, RxDma> embedded_hal_nb::serial::ErrorType for UartRx<'d, T, RxDma> { +impl<'d, M: Mode> embedded_hal_nb::serial::ErrorType for UartRx<'d, M> { type Error = Error; } -impl<'d, T: BasicInstance, RxDma> embedded_hal_nb::serial::Read for UartRx<'d, T, RxDma> { +impl<'d, M: Mode> embedded_hal_nb::serial::Read for UartRx<'d, M> { fn read(&mut self) -> nb::Result { self.nb_read() } } -impl<'d, T: BasicInstance, TxDma> embedded_hal_nb::serial::Write for UartTx<'d, T, TxDma> { +impl<'d, M: Mode> embedded_hal_nb::serial::Write for UartTx<'d, M> { fn write(&mut self, char: u8) -> nb::Result<(), Self::Error> { self.blocking_write(&[char]).map_err(nb::Error::Other) } @@ -1220,13 +1728,13 @@ impl<'d, T: BasicInstance, TxDma> embedded_hal_nb::serial::Write for UartTx<'d, } } -impl<'d, T: BasicInstance, TxDma, RxDma> embedded_hal_nb::serial::Read for Uart<'d, T, TxDma, RxDma> { +impl<'d, M: Mode> embedded_hal_nb::serial::Read for Uart<'d, M> { fn read(&mut self) -> Result> { self.nb_read() } } -impl<'d, T: BasicInstance, TxDma, RxDma> embedded_hal_nb::serial::Write for Uart<'d, T, TxDma, RxDma> { +impl<'d, M: Mode> embedded_hal_nb::serial::Write for Uart<'d, M> { fn write(&mut self, char: u8) -> nb::Result<(), Self::Error> { self.blocking_write(&[char]).map_err(nb::Error::Other) } @@ -1242,25 +1750,15 @@ impl embedded_io::Error for Error { } } -impl embedded_io::ErrorType for Uart<'_, T, TxDma, RxDma> -where - T: BasicInstance, -{ +impl embedded_io::ErrorType for Uart<'_, M> { type Error = Error; } -impl embedded_io::ErrorType for UartTx<'_, T, TxDma> -where - T: BasicInstance, -{ +impl embedded_io::ErrorType for UartTx<'_, M> { type Error = Error; } -impl embedded_io::Write for Uart<'_, T, TxDma, RxDma> -where - T: BasicInstance, - TxDma: crate::usart::TxDma, -{ +impl embedded_io::Write for Uart<'_, M> { fn write(&mut self, buf: &[u8]) -> Result { self.blocking_write(buf)?; Ok(buf.len()) @@ -1271,11 +1769,7 @@ where } } -impl embedded_io::Write for UartTx<'_, T, TxDma> -where - T: BasicInstance, - TxDma: crate::usart::TxDma, -{ +impl embedded_io::Write for UartTx<'_, M> { fn write(&mut self, buf: &[u8]) -> Result { self.blocking_write(buf)?; Ok(buf.len()) @@ -1286,33 +1780,25 @@ where } } -impl embedded_io_async::Write for Uart<'_, T, TxDma, RxDma> -where - T: BasicInstance, - TxDma: self::TxDma, -{ +impl embedded_io_async::Write for Uart<'_, Async> { async fn write(&mut self, buf: &[u8]) -> Result { self.write(buf).await?; Ok(buf.len()) } async fn flush(&mut self) -> Result<(), Self::Error> { - self.blocking_flush() + self.flush().await } } -impl embedded_io_async::Write for UartTx<'_, T, TxDma> -where - T: BasicInstance, - TxDma: self::TxDma, -{ +impl embedded_io_async::Write for UartTx<'_, Async> { async fn write(&mut self, buf: &[u8]) -> Result { self.write(buf).await?; Ok(buf.len()) } async fn flush(&mut self) -> Result<(), Self::Error> { - self.blocking_flush() + self.flush().await } } @@ -1326,8 +1812,6 @@ mod ringbuffered; #[cfg(not(gpdma))] pub use ringbuffered::RingBufferedUartRx; -use self::sealed::Kind; - #[cfg(any(usart_v1, usart_v2))] fn tdr(r: crate::pac::usart::Usart) -> *mut u8 { r.dr().as_ptr() as _ @@ -1370,85 +1854,87 @@ fn clear_interrupt_flags(r: Regs, sr: regs::Isr) { r.icr().write(|w| *w = regs::Icr(sr.0)); } -pub(crate) mod sealed { - use embassy_sync::waitqueue::AtomicWaker; +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + Uart, + #[cfg(any(usart_v3, usart_v4))] + #[allow(unused)] + Lpuart, +} - use super::*; +struct State { + rx_waker: AtomicWaker, + tx_rx_refcount: AtomicU8, +} - #[derive(Clone, Copy, PartialEq, Eq)] - pub enum Kind { - Uart, - #[cfg(any(usart_v3, usart_v4))] - Lpuart, - } - - pub struct State { - pub rx_waker: AtomicWaker, - pub tx_waker: AtomicWaker, - } - - impl State { - pub const fn new() -> Self { - Self { - rx_waker: AtomicWaker::new(), - tx_waker: AtomicWaker::new(), - } +impl State { + const fn new() -> Self { + Self { + rx_waker: AtomicWaker::new(), + tx_rx_refcount: AtomicU8::new(0), } } - - pub trait BasicInstance: crate::rcc::RccPeripheral { - const KIND: Kind; - type Interrupt: interrupt::typelevel::Interrupt; - - fn regs() -> Regs; - fn state() -> &'static State; - - fn buffered_state() -> &'static buffered::State; - } - - pub trait FullInstance: BasicInstance { - fn regs_uart() -> crate::pac::usart::Usart; - } } -/// Basic UART driver instance -pub trait BasicInstance: Peripheral

+ sealed::BasicInstance + 'static + Send {} +struct Info { + regs: Regs, + rcc: RccInfo, + interrupt: Interrupt, + kind: Kind, +} -/// Full UART driver instance -pub trait FullInstance: sealed::FullInstance {} +#[allow(private_interfaces)] +pub(crate) trait SealedInstance: crate::rcc::RccPeripheral { + fn info() -> &'static Info; + fn state() -> &'static State; + fn buffered_state() -> &'static buffered::State; +} -pin_trait!(RxPin, BasicInstance); -pin_trait!(TxPin, BasicInstance); -pin_trait!(CtsPin, BasicInstance); -pin_trait!(RtsPin, BasicInstance); -pin_trait!(CkPin, BasicInstance); -pin_trait!(DePin, BasicInstance); +/// USART peripheral instance trait. +#[allow(private_bounds)] +pub trait Instance: Peripheral

+ SealedInstance + 'static + Send { + /// Interrupt for this peripheral. + type Interrupt: interrupt::typelevel::Interrupt; +} -dma_trait!(TxDma, BasicInstance); -dma_trait!(RxDma, BasicInstance); +pin_trait!(RxPin, Instance); +pin_trait!(TxPin, Instance); +pin_trait!(CtsPin, Instance); +pin_trait!(RtsPin, Instance); +pin_trait!(CkPin, Instance); +pin_trait!(DePin, Instance); + +dma_trait!(TxDma, Instance); +dma_trait!(RxDma, Instance); macro_rules! impl_usart { ($inst:ident, $irq:ident, $kind:expr) => { - impl sealed::BasicInstance for crate::peripherals::$inst { - const KIND: Kind = $kind; - type Interrupt = crate::interrupt::typelevel::$irq; - - fn regs() -> Regs { - unsafe { Regs::from_ptr(crate::pac::$inst.as_ptr()) } + #[allow(private_interfaces)] + impl SealedInstance for crate::peripherals::$inst { + fn info() -> &'static Info { + static INFO: Info = Info { + regs: unsafe { Regs::from_ptr(crate::pac::$inst.as_ptr()) }, + rcc: crate::peripherals::$inst::RCC_INFO, + interrupt: crate::interrupt::typelevel::$irq::IRQ, + kind: $kind, + }; + &INFO } - fn state() -> &'static crate::usart::sealed::State { - static STATE: crate::usart::sealed::State = crate::usart::sealed::State::new(); + fn state() -> &'static State { + static STATE: State = State::new(); &STATE } fn buffered_state() -> &'static buffered::State { - static STATE: buffered::State = buffered::State::new(); - &STATE + static BUFFERED_STATE: buffered::State = buffered::State::new(); + &BUFFERED_STATE } } - impl BasicInstance for peripherals::$inst {} + impl Instance for crate::peripherals::$inst { + type Interrupt = crate::interrupt::typelevel::$irq; + } }; } @@ -1456,16 +1942,7 @@ foreach_interrupt!( ($inst:ident, usart, LPUART, $signal_name:ident, $irq:ident) => { impl_usart!($inst, $irq, Kind::Lpuart); }; - ($inst:ident, usart, $block:ident, $signal_name:ident, $irq:ident) => { impl_usart!($inst, $irq, Kind::Uart); - - impl sealed::FullInstance for peripherals::$inst { - fn regs_uart() -> crate::pac::usart::Usart { - crate::pac::$inst - } - } - - impl FullInstance for peripherals::$inst {} }; ); diff --git a/embassy-stm32/src/usart/ringbuffered.rs b/embassy-stm32/src/usart/ringbuffered.rs index 4391bfef7..a791ac2a9 100644 --- a/embassy-stm32/src/usart/ringbuffered.rs +++ b/embassy-stm32/src/usart/ringbuffered.rs @@ -5,19 +5,29 @@ use core::task::Poll; use embassy_embedded_hal::SetConfig; use embassy_hal_internal::PeripheralRef; -use futures::future::{select, Either}; +use embedded_io_async::ReadReady; +use futures_util::future::{select, Either}; -use super::{clear_interrupt_flags, rdr, reconfigure, sr, BasicInstance, Config, ConfigError, Error, RxDma, UartRx}; +use super::{clear_interrupt_flags, rdr, reconfigure, sr, Config, ConfigError, Error, Info, State, UartRx}; use crate::dma::ReadableRingBuffer; +use crate::gpio::{AnyPin, SealedPin as _}; +use crate::mode::Async; +use crate::time::Hertz; use crate::usart::{Regs, Sr}; /// Rx-only Ring-buffered UART Driver -pub struct RingBufferedUartRx<'d, T: BasicInstance, RxDma: super::RxDma> { - _peri: PeripheralRef<'d, T>, - ring_buf: ReadableRingBuffer<'d, RxDma, u8>, +/// +/// Created with [UartRx::into_ring_buffered] +pub struct RingBufferedUartRx<'d> { + info: &'static Info, + state: &'static State, + kernel_clock: Hertz, + rx: Option>, + rts: Option>, + ring_buf: ReadableRingBuffer<'d, u8>, } -impl<'d, T: BasicInstance, RxDma: super::RxDma> SetConfig for RingBufferedUartRx<'d, T, RxDma> { +impl<'d> SetConfig for RingBufferedUartRx<'d> { type Config = Config; type ConfigError = ConfigError; @@ -26,61 +36,56 @@ impl<'d, T: BasicInstance, RxDma: super::RxDma> SetConfig for RingBufferedUar } } -impl<'d, T: BasicInstance, RxDma: super::RxDma> UartRx<'d, T, RxDma> { +impl<'d> UartRx<'d, Async> { /// Turn the `UartRx` into a buffered uart which can continously receive in the background /// without the possibility of losing bytes. The `dma_buf` is a buffer registered to the /// DMA controller, and must be large enough to prevent overflows. - pub fn into_ring_buffered(self, dma_buf: &'d mut [u8]) -> RingBufferedUartRx<'d, T, RxDma> { + pub fn into_ring_buffered(mut self, dma_buf: &'d mut [u8]) -> RingBufferedUartRx<'d> { assert!(!dma_buf.is_empty() && dma_buf.len() <= 0xFFFF); - let request = self.rx_dma.request(); let opts = Default::default(); // Safety: we forget the struct before this function returns. - let rx_dma = unsafe { self.rx_dma.clone_unchecked() }; - let _peri = unsafe { self._peri.clone_unchecked() }; + let rx_dma = self.rx_dma.as_mut().unwrap(); + let request = rx_dma.request; + let rx_dma = unsafe { rx_dma.channel.clone_unchecked() }; - let ring_buf = unsafe { ReadableRingBuffer::new(rx_dma, request, rdr(T::regs()), dma_buf, opts) }; + let info = self.info; + let state = self.state; + let kernel_clock = self.kernel_clock; + let ring_buf = unsafe { ReadableRingBuffer::new(rx_dma, request, rdr(info.regs), dma_buf, opts) }; + let rx = unsafe { self.rx.as_ref().map(|x| x.clone_unchecked()) }; + let rts = unsafe { self.rts.as_ref().map(|x| x.clone_unchecked()) }; // Don't disable the clock mem::forget(self); - RingBufferedUartRx { _peri, ring_buf } + RingBufferedUartRx { + info, + state, + kernel_clock, + rx, + rts, + ring_buf, + } } } -impl<'d, T: BasicInstance, RxDma: super::RxDma> RingBufferedUartRx<'d, T, RxDma> { - /// Clear the ring buffer and start receiving in the background - pub fn start(&mut self) -> Result<(), Error> { - // Clear the ring buffer so that it is ready to receive data - self.ring_buf.clear(); - - self.setup_uart(); - - Ok(()) - } - - fn stop(&mut self, err: Error) -> Result { - self.teardown_uart(); - - Err(err) - } - - /// Cleanly stop and reconfigure the driver +impl<'d> RingBufferedUartRx<'d> { + /// Reconfigure the driver pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> { - self.teardown_uart(); - reconfigure::(config) + reconfigure(self.info, self.kernel_clock, config) } - /// Start uart background receive - fn setup_uart(&mut self) { - // fence before starting DMA. + /// Configure and start the DMA backed UART receiver + /// + /// Note: This is also done automatically by [`read()`] if required. + pub fn start_uart(&mut self) { + // Clear the buffer so that it is ready to receive data compiler_fence(Ordering::SeqCst); - - // start the dma controller self.ring_buf.start(); - let r = T::regs(); + let r = self.info.regs; // clear all interrupts and DMA Rx Request r.cr1().modify(|w| { // disable RXNE interrupt @@ -98,11 +103,11 @@ impl<'d, T: BasicInstance, RxDma: super::RxDma> RingBufferedUartRx<'d, T, RxD }); } - /// Stop uart background receive - fn teardown_uart(&mut self) { - self.ring_buf.request_stop(); + /// Stop DMA backed UART receiver + fn stop_uart(&mut self) { + self.ring_buf.request_pause(); - let r = T::regs(); + let r = self.info.regs; // clear all interrupts and DMA Rx Request r.cr1().modify(|w| { // disable RXNE interrupt @@ -131,15 +136,17 @@ impl<'d, T: BasicInstance, RxDma: super::RxDma> RingBufferedUartRx<'d, T, RxD /// Receive in the background is terminated if an error is returned. /// It must then manually be started again by calling `start()` or by re-calling `read()`. pub async fn read(&mut self, buf: &mut [u8]) -> Result { - let r = T::regs(); + let r = self.info.regs; - // Start background receive if it was not already started + // Start DMA and Uart if it was not already started, + // otherwise check for errors in status register. + let sr = clear_idle_flag(r); if !r.cr3().read().dmar() { - self.start()?; + self.start_uart(); + } else { + check_for_errors(sr)?; } - check_for_errors(clear_idle_flag(T::regs()))?; - loop { match self.ring_buf.read(buf) { Ok((0, _)) => {} @@ -147,14 +154,16 @@ impl<'d, T: BasicInstance, RxDma: super::RxDma> RingBufferedUartRx<'d, T, RxD return Ok(len); } Err(_) => { - return self.stop(Error::Overrun); + self.stop_uart(); + return Err(Error::Overrun); } } match self.wait_for_data_or_idle().await { Ok(_) => {} Err(err) => { - return self.stop(err); + self.stop_uart(); + return Err(err); } } } @@ -164,6 +173,27 @@ impl<'d, T: BasicInstance, RxDma: super::RxDma> RingBufferedUartRx<'d, T, RxD async fn wait_for_data_or_idle(&mut self) -> Result<(), Error> { compiler_fence(Ordering::SeqCst); + // Future which completes when idle line is detected + let s = self.state; + let uart = poll_fn(|cx| { + s.rx_waker.register(cx.waker()); + + compiler_fence(Ordering::SeqCst); + + // Critical section is needed so that IDLE isn't set after + // our read but before we clear it. + let sr = critical_section::with(|_| clear_idle_flag(self.info.regs)); + + check_for_errors(sr)?; + + if sr.idle() { + // Idle line is detected + Poll::Ready(Ok(())) + } else { + Poll::Pending + } + }); + let mut dma_init = false; // Future which completes when there is dma is half full or full let dma = poll_fn(|cx| { @@ -178,41 +208,22 @@ impl<'d, T: BasicInstance, RxDma: super::RxDma> RingBufferedUartRx<'d, T, RxD status }); - // Future which completes when idle line is detected - let uart = poll_fn(|cx| { - let s = T::state(); - s.rx_waker.register(cx.waker()); - - compiler_fence(Ordering::SeqCst); - - // Critical section is needed so that IDLE isn't set after - // our read but before we clear it. - let sr = critical_section::with(|_| clear_idle_flag(T::regs())); - - check_for_errors(sr)?; - - if sr.idle() { - // Idle line is detected - Poll::Ready(Ok(())) - } else { - Poll::Pending - } - }); - - match select(dma, uart).await { - Either::Left(((), _)) => Ok(()), - Either::Right((result, _)) => result, + match select(uart, dma).await { + Either::Left((result, _)) => result, + Either::Right(((), _)) => Ok(()), } } } -impl> Drop for RingBufferedUartRx<'_, T, RxDma> { +impl Drop for RingBufferedUartRx<'_> { fn drop(&mut self) { - self.teardown_uart(); - - T::disable(); + self.stop_uart(); + self.rx.as_ref().map(|x| x.set_as_disconnected()); + self.rts.as_ref().map(|x| x.set_as_disconnected()); + super::drop_tx_rx(self.info, self.state); } } + /// Return an error result if the Sr register has errors fn check_for_errors(s: Sr) -> Result<(), Error> { if s.pe() { @@ -243,20 +254,29 @@ fn clear_idle_flag(r: Regs) -> Sr { sr } -impl embedded_io_async::ErrorType for RingBufferedUartRx<'_, T, Rx> -where - T: BasicInstance, - Rx: RxDma, -{ +impl embedded_io_async::ErrorType for RingBufferedUartRx<'_> { type Error = Error; } -impl embedded_io_async::Read for RingBufferedUartRx<'_, T, Rx> -where - T: BasicInstance, - Rx: RxDma, -{ +impl embedded_io_async::Read for RingBufferedUartRx<'_> { async fn read(&mut self, buf: &mut [u8]) -> Result { self.read(buf).await } } + +impl ReadReady for RingBufferedUartRx<'_> { + fn read_ready(&mut self) -> Result { + let len = self.ring_buf.len().map_err(|e| match e { + crate::dma::ringbuffer::Error::Overrun => Self::Error::Overrun, + crate::dma::ringbuffer::Error::DmaUnsynced => { + error!( + "Ringbuffer error: DmaUNsynced, driver implementation is + probably bugged please open an issue" + ); + // we report this as overrun since its recoverable in the same way + Self::Error::Overrun + } + })?; + Ok(len > 0) + } +} diff --git a/embassy-stm32/src/usb/mod.rs b/embassy-stm32/src/usb/mod.rs index 4debd4e54..a473285bf 100644 --- a/embassy-stm32/src/usb/mod.rs +++ b/embassy-stm32/src/usb/mod.rs @@ -1,37 +1,99 @@ //! Universal Serial Bus (USB) -use crate::interrupt; -use crate::rcc::RccPeripheral; +#[cfg_attr(usb, path = "usb.rs")] +#[cfg_attr(otg, path = "otg.rs")] +mod _version; +pub use _version::*; -mod usb; -pub use usb::*; +use crate::interrupt::typelevel::Interrupt; +use crate::rcc; -pub(crate) mod sealed { - pub trait Instance { - fn regs() -> crate::pac::usb::Usb; +/// clock, power initialization stuff that's common for USB and OTG. +fn common_init() { + // Check the USB clock is enabled and running at exactly 48 MHz. + // frequency() will panic if not enabled + let freq = T::frequency(); + + // On the H7RS, the USBPHYC embeds a PLL accepting one of the input frequencies listed below and providing 48MHz to OTG_FS and 60MHz to OTG_HS internally + #[cfg(stm32h7rs)] + if ![16_000_000, 19_200_000, 20_000_000, 24_000_000, 26_000_000, 32_000_000].contains(&freq.0) { + panic!( + "USB clock should be one of 16, 19.2, 20, 24, 26, 32Mhz but is {} Hz. Please double-check your RCC settings.", + freq.0 + ) } + // Check frequency is within the 0.25% tolerance allowed by the spec. + // Clock might not be exact 48Mhz due to rounding errors in PLL calculation, or if the user + // has tight clock restrictions due to something else (like audio). + #[cfg(not(stm32h7rs))] + if freq.0.abs_diff(48_000_000) > 120_000 { + panic!( + "USB clock should be 48Mhz but is {} Hz. Please double-check your RCC settings.", + freq.0 + ) + } + + #[cfg(any(stm32l4, stm32l5, stm32wb, stm32u0))] + critical_section::with(|_| crate::pac::PWR.cr2().modify(|w| w.set_usv(true))); + + #[cfg(pwr_h5)] + critical_section::with(|_| crate::pac::PWR.usbscr().modify(|w| w.set_usb33sv(true))); + + #[cfg(stm32h7)] + { + // If true, VDD33USB is generated by internal regulator from VDD50USB + // If false, VDD33USB and VDD50USB must be suplied directly with 3.3V (default on nucleo) + // TODO: unhardcode + let internal_regulator = false; + + // Enable USB power + critical_section::with(|_| { + crate::pac::PWR.cr3().modify(|w| { + w.set_usb33den(true); + w.set_usbregen(internal_regulator); + }) + }); + + // Wait for USB power to stabilize + while !crate::pac::PWR.cr3().read().usb33rdy() {} + } + + #[cfg(stm32h7rs)] + { + // If true, VDD33USB is generated by internal regulator from VDD50USB + // If false, VDD33USB and VDD50USB must be suplied directly with 3.3V (default on nucleo) + // TODO: unhardcode + let internal_regulator = false; + + // Enable USB power + critical_section::with(|_| { + crate::pac::PWR.csr2().modify(|w| { + w.set_usbregen(internal_regulator); + w.set_usb33den(true); + w.set_usbhsregen(true); + }) + }); + + // Wait for USB power to stabilize + while !crate::pac::PWR.csr2().read().usb33rdy() {} + } + + #[cfg(stm32u5)] + { + // Enable USB power + critical_section::with(|_| { + crate::pac::PWR.svmcr().modify(|w| { + w.set_usv(true); + w.set_uvmen(true); + }) + }); + + // Wait for USB power to stabilize + while !crate::pac::PWR.svmsr().read().vddusbrdy() {} + } + + T::Interrupt::unpend(); + unsafe { T::Interrupt::enable() }; + + rcc::enable_and_reset::(); } - -/// USB instance trait. -pub trait Instance: sealed::Instance + RccPeripheral + 'static { - /// Interrupt for this USB instance. - type Interrupt: interrupt::typelevel::Interrupt; -} - -// Internal PHY pins -pin_trait!(DpPin, Instance); -pin_trait!(DmPin, Instance); - -foreach_interrupt!( - ($inst:ident, usb, $block:ident, LP, $irq:ident) => { - impl sealed::Instance for crate::peripherals::$inst { - fn regs() -> crate::pac::usb::Usb { - crate::pac::$inst - } - } - - impl Instance for crate::peripherals::$inst { - type Interrupt = crate::interrupt::typelevel::$irq; - } - }; -); diff --git a/embassy-stm32/src/usb/otg.rs b/embassy-stm32/src/usb/otg.rs new file mode 100644 index 000000000..00cafe6e4 --- /dev/null +++ b/embassy-stm32/src/usb/otg.rs @@ -0,0 +1,585 @@ +use core::marker::PhantomData; + +use embassy_hal_internal::{into_ref, Peripheral}; +use embassy_usb_driver::{EndpointAddress, EndpointAllocError, EndpointType, Event, Unsupported}; +use embassy_usb_synopsys_otg::otg_v1::vals::Dspd; +use embassy_usb_synopsys_otg::otg_v1::Otg; +pub use embassy_usb_synopsys_otg::Config; +use embassy_usb_synopsys_otg::{ + on_interrupt as on_interrupt_impl, Bus as OtgBus, ControlPipe, Driver as OtgDriver, Endpoint, In, OtgInstance, Out, + PhyType, State, +}; + +use crate::gpio::{AfType, OutputType, Speed}; +use crate::interrupt; +use crate::interrupt::typelevel::Interrupt; +use crate::rcc::{self, RccPeripheral}; + +const MAX_EP_COUNT: usize = 9; + +/// Interrupt handler. +pub struct InterruptHandler { + _phantom: PhantomData, +} + +impl interrupt::typelevel::Handler for InterruptHandler { + unsafe fn on_interrupt() { + trace!("irq"); + let r = T::regs(); + let state = T::state(); + + let setup_late_cnak = quirk_setup_late_cnak(r); + + on_interrupt_impl(r, state, T::ENDPOINT_COUNT, setup_late_cnak); + } +} + +macro_rules! config_ulpi_pins { + ($($pin:ident),*) => { + into_ref!($($pin),*); + critical_section::with(|_| { + $( + $pin.set_as_af($pin.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); + )* + }) + }; +} + +// From `synopsys-usb-otg` crate: +// This calculation doesn't correspond to one in a Reference Manual. +// In fact, the required number of words is higher than indicated in RM. +// The following numbers are pessimistic and were figured out empirically. +const RX_FIFO_EXTRA_SIZE_WORDS: u16 = 30; + +/// USB driver. +pub struct Driver<'d, T: Instance> { + phantom: PhantomData<&'d mut T>, + inner: OtgDriver<'d, MAX_EP_COUNT>, +} + +impl<'d, T: Instance> Driver<'d, T> { + /// Initializes USB OTG peripheral with internal Full-Speed PHY. + /// + /// # Arguments + /// + /// * `ep_out_buffer` - An internal buffer used to temporarily store received packets. + /// Must be large enough to fit all OUT endpoint max packet sizes. + /// Endpoint allocation will fail if it is too small. + pub fn new_fs( + _peri: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + dp: impl Peripheral

> + 'd, + dm: impl Peripheral

> + 'd, + ep_out_buffer: &'d mut [u8], + config: Config, + ) -> Self { + into_ref!(dp, dm); + + dp.set_as_af(dp.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); + dm.set_as_af(dm.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); + + let regs = T::regs(); + + let instance = OtgInstance { + regs, + state: T::state(), + fifo_depth_words: T::FIFO_DEPTH_WORDS, + extra_rx_fifo_words: RX_FIFO_EXTRA_SIZE_WORDS, + endpoint_count: T::ENDPOINT_COUNT, + phy_type: PhyType::InternalFullSpeed, + quirk_setup_late_cnak: quirk_setup_late_cnak(regs), + calculate_trdt_fn: calculate_trdt::, + }; + + Self { + inner: OtgDriver::new(ep_out_buffer, instance, config), + phantom: PhantomData, + } + } + + /// Initializes USB OTG peripheral with internal High-Speed PHY. + /// + /// # Arguments + /// + /// * `ep_out_buffer` - An internal buffer used to temporarily store received packets. + /// Must be large enough to fit all OUT endpoint max packet sizes. + /// Endpoint allocation will fail if it is too small. + pub fn new_hs( + _peri: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + dp: impl Peripheral

> + 'd, + dm: impl Peripheral

> + 'd, + ep_out_buffer: &'d mut [u8], + config: Config, + ) -> Self { + into_ref!(dp, dm); + + dp.set_as_af(dp.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); + dm.set_as_af(dm.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); + + let regs = T::regs(); + + let instance = OtgInstance { + regs, + state: T::state(), + fifo_depth_words: T::FIFO_DEPTH_WORDS, + extra_rx_fifo_words: RX_FIFO_EXTRA_SIZE_WORDS, + endpoint_count: T::ENDPOINT_COUNT, + phy_type: PhyType::InternalHighSpeed, + quirk_setup_late_cnak: quirk_setup_late_cnak(regs), + calculate_trdt_fn: calculate_trdt::, + }; + + Self { + inner: OtgDriver::new(ep_out_buffer, instance, config), + phantom: PhantomData, + } + } + + /// Initializes USB OTG peripheral with external Full-speed PHY (usually, a High-speed PHY in Full-speed mode). + /// + /// # Arguments + /// + /// * `ep_out_buffer` - An internal buffer used to temporarily store received packets. + /// Must be large enough to fit all OUT endpoint max packet sizes. + /// Endpoint allocation will fail if it is too small. + pub fn new_fs_ulpi( + _peri: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + ulpi_clk: impl Peripheral

> + 'd, + ulpi_dir: impl Peripheral

> + 'd, + ulpi_nxt: impl Peripheral

> + 'd, + ulpi_stp: impl Peripheral

> + 'd, + ulpi_d0: impl Peripheral

> + 'd, + ulpi_d1: impl Peripheral

> + 'd, + ulpi_d2: impl Peripheral

> + 'd, + ulpi_d3: impl Peripheral

> + 'd, + ulpi_d4: impl Peripheral

> + 'd, + ulpi_d5: impl Peripheral

> + 'd, + ulpi_d6: impl Peripheral

> + 'd, + ulpi_d7: impl Peripheral

> + 'd, + ep_out_buffer: &'d mut [u8], + config: Config, + ) -> Self { + config_ulpi_pins!( + ulpi_clk, ulpi_dir, ulpi_nxt, ulpi_stp, ulpi_d0, ulpi_d1, ulpi_d2, ulpi_d3, ulpi_d4, ulpi_d5, ulpi_d6, + ulpi_d7 + ); + + let regs = T::regs(); + + let instance = OtgInstance { + regs: T::regs(), + state: T::state(), + fifo_depth_words: T::FIFO_DEPTH_WORDS, + extra_rx_fifo_words: RX_FIFO_EXTRA_SIZE_WORDS, + endpoint_count: T::ENDPOINT_COUNT, + phy_type: PhyType::ExternalFullSpeed, + quirk_setup_late_cnak: quirk_setup_late_cnak(regs), + calculate_trdt_fn: calculate_trdt::, + }; + + Self { + inner: OtgDriver::new(ep_out_buffer, instance, config), + phantom: PhantomData, + } + } + + /// Initializes USB OTG peripheral with external High-Speed PHY. + /// + /// # Arguments + /// + /// * `ep_out_buffer` - An internal buffer used to temporarily store received packets. + /// Must be large enough to fit all OUT endpoint max packet sizes. + /// Endpoint allocation will fail if it is too small. + pub fn new_hs_ulpi( + _peri: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + ulpi_clk: impl Peripheral

> + 'd, + ulpi_dir: impl Peripheral

> + 'd, + ulpi_nxt: impl Peripheral

> + 'd, + ulpi_stp: impl Peripheral

> + 'd, + ulpi_d0: impl Peripheral

> + 'd, + ulpi_d1: impl Peripheral

> + 'd, + ulpi_d2: impl Peripheral

> + 'd, + ulpi_d3: impl Peripheral

> + 'd, + ulpi_d4: impl Peripheral

> + 'd, + ulpi_d5: impl Peripheral

> + 'd, + ulpi_d6: impl Peripheral

> + 'd, + ulpi_d7: impl Peripheral

> + 'd, + ep_out_buffer: &'d mut [u8], + config: Config, + ) -> Self { + assert!(T::HIGH_SPEED == true, "Peripheral is not capable of high-speed USB"); + + config_ulpi_pins!( + ulpi_clk, ulpi_dir, ulpi_nxt, ulpi_stp, ulpi_d0, ulpi_d1, ulpi_d2, ulpi_d3, ulpi_d4, ulpi_d5, ulpi_d6, + ulpi_d7 + ); + + let regs = T::regs(); + + let instance = OtgInstance { + regs: T::regs(), + state: T::state(), + fifo_depth_words: T::FIFO_DEPTH_WORDS, + extra_rx_fifo_words: RX_FIFO_EXTRA_SIZE_WORDS, + endpoint_count: T::ENDPOINT_COUNT, + phy_type: PhyType::ExternalHighSpeed, + quirk_setup_late_cnak: quirk_setup_late_cnak(regs), + calculate_trdt_fn: calculate_trdt::, + }; + + Self { + inner: OtgDriver::new(ep_out_buffer, instance, config), + phantom: PhantomData, + } + } +} + +impl<'d, T: Instance> embassy_usb_driver::Driver<'d> for Driver<'d, T> { + type EndpointOut = Endpoint<'d, Out>; + type EndpointIn = Endpoint<'d, In>; + type ControlPipe = ControlPipe<'d>; + type Bus = Bus<'d, T>; + + fn alloc_endpoint_in( + &mut self, + ep_type: EndpointType, + max_packet_size: u16, + interval_ms: u8, + ) -> Result { + self.inner.alloc_endpoint_in(ep_type, max_packet_size, interval_ms) + } + + fn alloc_endpoint_out( + &mut self, + ep_type: EndpointType, + max_packet_size: u16, + interval_ms: u8, + ) -> Result { + self.inner.alloc_endpoint_out(ep_type, max_packet_size, interval_ms) + } + + fn start(self, control_max_packet_size: u16) -> (Self::Bus, Self::ControlPipe) { + let (bus, cp) = self.inner.start(control_max_packet_size); + + ( + Bus { + phantom: PhantomData, + inner: bus, + inited: false, + }, + cp, + ) + } +} + +/// USB bus. +pub struct Bus<'d, T: Instance> { + phantom: PhantomData<&'d mut T>, + inner: OtgBus<'d, MAX_EP_COUNT>, + inited: bool, +} + +impl<'d, T: Instance> Bus<'d, T> { + fn init(&mut self) { + super::common_init::(); + + // Enable ULPI clock if external PHY is used + let phy_type = self.inner.phy_type(); + let _ulpien = !phy_type.internal(); + + #[cfg(any(stm32f2, stm32f4, stm32f7))] + if T::HIGH_SPEED { + critical_section::with(|_| { + let rcc = crate::pac::RCC; + rcc.ahb1enr().modify(|w| w.set_usb_otg_hsulpien(_ulpien)); + rcc.ahb1lpenr().modify(|w| w.set_usb_otg_hsulpilpen(_ulpien)); + }); + } + + #[cfg(stm32h7)] + critical_section::with(|_| { + let rcc = crate::pac::RCC; + if T::HIGH_SPEED { + rcc.ahb1enr().modify(|w| w.set_usb_otg_hs_ulpien(_ulpien)); + rcc.ahb1lpenr().modify(|w| w.set_usb_otg_hs_ulpilpen(_ulpien)); + } else { + rcc.ahb1enr().modify(|w| w.set_usb_otg_fs_ulpien(_ulpien)); + rcc.ahb1lpenr().modify(|w| w.set_usb_otg_fs_ulpilpen(_ulpien)); + } + }); + + #[cfg(stm32h7rs)] + critical_section::with(|_| { + let rcc = crate::pac::RCC; + rcc.ahb1enr().modify(|w| { + w.set_usbphycen(true); + w.set_usb_otg_hsen(true); + }); + rcc.ahb1lpenr().modify(|w| { + w.set_usbphyclpen(true); + w.set_usb_otg_hslpen(true); + }); + }); + + let r = T::regs(); + let core_id = r.cid().read().0; + trace!("Core id {:08x}", core_id); + + // Wait for AHB ready. + while !r.grstctl().read().ahbidl() {} + + // Configure as device. + self.inner.configure_as_device(); + + // Configuring Vbus sense and SOF output + match core_id { + 0x0000_1200 | 0x0000_1100 => self.inner.config_v1(), + 0x0000_2000 | 0x0000_2100 | 0x0000_2300 | 0x0000_3000 | 0x0000_3100 => self.inner.config_v2v3(), + 0x0000_5000 => self.inner.config_v5(), + _ => unimplemented!("Unknown USB core id {:X}", core_id), + } + } + + fn disable(&mut self) { + T::Interrupt::disable(); + + rcc::disable::(); + self.inited = false; + + #[cfg(stm32l4)] + crate::pac::PWR.cr2().modify(|w| w.set_usv(false)); + // Cannot disable PWR, because other peripherals might be using it + } +} + +impl<'d, T: Instance> embassy_usb_driver::Bus for Bus<'d, T> { + async fn poll(&mut self) -> Event { + if !self.inited { + self.init(); + self.inited = true; + } + + self.inner.poll().await + } + + fn endpoint_set_stalled(&mut self, ep_addr: EndpointAddress, stalled: bool) { + self.inner.endpoint_set_stalled(ep_addr, stalled) + } + + fn endpoint_is_stalled(&mut self, ep_addr: EndpointAddress) -> bool { + self.inner.endpoint_is_stalled(ep_addr) + } + + fn endpoint_set_enabled(&mut self, ep_addr: EndpointAddress, enabled: bool) { + self.inner.endpoint_set_enabled(ep_addr, enabled) + } + + async fn enable(&mut self) { + self.inner.enable().await + } + + async fn disable(&mut self) { + // NOTE: inner call is a no-op + self.inner.disable().await + } + + async fn remote_wakeup(&mut self) -> Result<(), Unsupported> { + self.inner.remote_wakeup().await + } +} + +impl<'d, T: Instance> Drop for Bus<'d, T> { + fn drop(&mut self) { + Bus::disable(self); + } +} + +trait SealedInstance { + const HIGH_SPEED: bool; + const FIFO_DEPTH_WORDS: u16; + const ENDPOINT_COUNT: usize; + + fn regs() -> Otg; + fn state() -> &'static State<{ MAX_EP_COUNT }>; +} + +/// USB instance trait. +#[allow(private_bounds)] +pub trait Instance: SealedInstance + RccPeripheral + 'static { + /// Interrupt for this USB instance. + type Interrupt: interrupt::typelevel::Interrupt; +} + +// Internal PHY pins +pin_trait!(DpPin, Instance); +pin_trait!(DmPin, Instance); + +// External PHY pins +pin_trait!(UlpiClkPin, Instance); +pin_trait!(UlpiDirPin, Instance); +pin_trait!(UlpiNxtPin, Instance); +pin_trait!(UlpiStpPin, Instance); +pin_trait!(UlpiD0Pin, Instance); +pin_trait!(UlpiD1Pin, Instance); +pin_trait!(UlpiD2Pin, Instance); +pin_trait!(UlpiD3Pin, Instance); +pin_trait!(UlpiD4Pin, Instance); +pin_trait!(UlpiD5Pin, Instance); +pin_trait!(UlpiD6Pin, Instance); +pin_trait!(UlpiD7Pin, Instance); + +foreach_interrupt!( + (USB_OTG_FS, otg, $block:ident, GLOBAL, $irq:ident) => { + impl SealedInstance for crate::peripherals::USB_OTG_FS { + const HIGH_SPEED: bool = false; + + cfg_if::cfg_if! { + if #[cfg(stm32f1)] { + const FIFO_DEPTH_WORDS: u16 = 128; + const ENDPOINT_COUNT: usize = 8; + } else if #[cfg(any( + stm32f2, + stm32f401, + stm32f405, + stm32f407, + stm32f411, + stm32f415, + stm32f417, + stm32f427, + stm32f429, + stm32f437, + stm32f439, + ))] { + const FIFO_DEPTH_WORDS: u16 = 320; + const ENDPOINT_COUNT: usize = 4; + } else if #[cfg(any( + stm32f412, + stm32f413, + stm32f423, + stm32f446, + stm32f469, + stm32f479, + stm32f7, + stm32l4, + stm32u5, + ))] { + const FIFO_DEPTH_WORDS: u16 = 320; + const ENDPOINT_COUNT: usize = 6; + } else if #[cfg(stm32g0x1)] { + const FIFO_DEPTH_WORDS: u16 = 512; + const ENDPOINT_COUNT: usize = 8; + } else if #[cfg(any(stm32h7, stm32h7rs))] { + const FIFO_DEPTH_WORDS: u16 = 1024; + const ENDPOINT_COUNT: usize = 9; + } else if #[cfg(stm32u5)] { + const FIFO_DEPTH_WORDS: u16 = 320; + const ENDPOINT_COUNT: usize = 6; + } else { + compile_error!("USB_OTG_FS peripheral is not supported by this chip."); + } + } + + fn regs() -> Otg { + unsafe { Otg::from_ptr(crate::pac::USB_OTG_FS.as_ptr()) } + } + + fn state() -> &'static State { + static STATE: State = State::new(); + &STATE + } + } + + impl Instance for crate::peripherals::USB_OTG_FS { + type Interrupt = crate::interrupt::typelevel::$irq; + } + }; + + (USB_OTG_HS, otg, $block:ident, GLOBAL, $irq:ident) => { + impl SealedInstance for crate::peripherals::USB_OTG_HS { + const HIGH_SPEED: bool = true; + + cfg_if::cfg_if! { + if #[cfg(any( + stm32f2, + stm32f405, + stm32f407, + stm32f415, + stm32f417, + stm32f427, + stm32f429, + stm32f437, + stm32f439, + ))] { + const FIFO_DEPTH_WORDS: u16 = 1024; + const ENDPOINT_COUNT: usize = 6; + } else if #[cfg(any( + stm32f446, + stm32f469, + stm32f479, + stm32f7, + stm32h7, stm32h7rs, + ))] { + const FIFO_DEPTH_WORDS: u16 = 1024; + const ENDPOINT_COUNT: usize = 9; + } else if #[cfg(stm32u5)] { + const FIFO_DEPTH_WORDS: u16 = 1024; + const ENDPOINT_COUNT: usize = 9; + } else { + compile_error!("USB_OTG_HS peripheral is not supported by this chip."); + } + } + + fn regs() -> Otg { + // OTG HS registers are a superset of FS registers + unsafe { Otg::from_ptr(crate::pac::USB_OTG_HS.as_ptr()) } + } + + fn state() -> &'static State { + static STATE: State = State::new(); + &STATE + } + } + + impl Instance for crate::peripherals::USB_OTG_HS { + type Interrupt = crate::interrupt::typelevel::$irq; + } + }; +); + +fn calculate_trdt(speed: Dspd) -> u8 { + let ahb_freq = T::frequency().0; + match speed { + Dspd::HIGH_SPEED => { + // From RM0431 (F72xx), RM0090 (F429), RM0390 (F446) + if ahb_freq >= 30_000_000 || cfg!(stm32h7rs) { + 0x9 + } else { + panic!("AHB frequency is too low") + } + } + Dspd::FULL_SPEED_EXTERNAL | Dspd::FULL_SPEED_INTERNAL => { + // From RM0431 (F72xx), RM0090 (F429) + match ahb_freq { + 0..=14_199_999 => panic!("AHB frequency is too low"), + 14_200_000..=14_999_999 => 0xF, + 15_000_000..=15_999_999 => 0xE, + 16_000_000..=17_199_999 => 0xD, + 17_200_000..=18_499_999 => 0xC, + 18_500_000..=19_999_999 => 0xB, + 20_000_000..=21_799_999 => 0xA, + 21_800_000..=23_999_999 => 0x9, + 24_000_000..=27_499_999 => 0x8, + 27_500_000..=31_999_999 => 0x7, // 27.7..32 in code from CubeIDE + 32_000_000..=u32::MAX => 0x6, + } + } + _ => unimplemented!(), + } +} + +fn quirk_setup_late_cnak(r: Otg) -> bool { + r.cid().read().0 & 0xf000 == 0x1000 +} diff --git a/embassy-stm32/src/usb/usb.rs b/embassy-stm32/src/usb/usb.rs index f39915906..0ab2306c8 100644 --- a/embassy-stm32/src/usb/usb.rs +++ b/embassy-stm32/src/usb/usb.rs @@ -12,12 +12,10 @@ use embassy_usb_driver::{ Direction, EndpointAddress, EndpointAllocError, EndpointError, EndpointInfo, EndpointType, Event, Unsupported, }; -use super::{DmPin, DpPin, Instance}; -use crate::interrupt::typelevel::Interrupt; use crate::pac::usb::regs; use crate::pac::usb::vals::{EpType, Stat}; use crate::pac::USBRAM; -use crate::rcc::sealed::RccPeripheral; +use crate::rcc::RccPeripheral; use crate::{interrupt, Peripheral}; /// Interrupt handler. @@ -82,6 +80,8 @@ impl interrupt::typelevel::Handler for InterruptHandl if istr.ctr() { let index = istr.ep_id() as usize; + CTR_TRIGGERED[index].store(true, Ordering::Relaxed); + let mut epr = regs.epr(index).read(); if epr.ctr_rx() { if index == 0 && epr.setup() { @@ -109,19 +109,23 @@ const EP_COUNT: usize = 8; #[cfg(any(usbram_16x1_512, usbram_16x2_512))] const USBRAM_SIZE: usize = 512; -#[cfg(usbram_16x2_1024)] +#[cfg(any(usbram_16x2_1024, usbram_32_1024))] const USBRAM_SIZE: usize = 1024; #[cfg(usbram_32_2048)] const USBRAM_SIZE: usize = 2048; -#[cfg(not(usbram_32_2048))] +#[cfg(not(any(usbram_32_2048, usbram_32_1024)))] const USBRAM_ALIGN: usize = 2; -#[cfg(usbram_32_2048)] +#[cfg(any(usbram_32_2048, usbram_32_1024))] const USBRAM_ALIGN: usize = 4; const NEW_AW: AtomicWaker = AtomicWaker::new(); static BUS_WAKER: AtomicWaker = NEW_AW; static EP0_SETUP: AtomicBool = AtomicBool::new(false); + +const NEW_CTR_TRIGGERED: AtomicBool = AtomicBool::new(false); +static CTR_TRIGGERED: [AtomicBool; EP_COUNT] = [NEW_CTR_TRIGGERED; EP_COUNT]; + static EP_IN_WAKERS: [AtomicWaker; EP_COUNT] = [NEW_AW; EP_COUNT]; static EP_OUT_WAKERS: [AtomicWaker; EP_COUNT] = [NEW_AW; EP_COUNT]; static IRQ_RESET: AtomicBool = AtomicBool::new(false); @@ -161,44 +165,79 @@ fn calc_out_len(len: u16) -> (u16, u16) { } } -#[cfg(not(usbram_32_2048))] +#[cfg(not(any(usbram_32_2048, usbram_32_1024)))] mod btable { use super::*; - pub(super) fn write_in(index: usize, addr: u16) { + pub(super) fn write_in_tx(index: usize, addr: u16) { USBRAM.mem(index * 4 + 0).write_value(addr); } - pub(super) fn write_in_len(index: usize, _addr: u16, len: u16) { + pub(super) fn write_in_rx(index: usize, addr: u16) { + USBRAM.mem(index * 4 + 2).write_value(addr); + } + + pub(super) fn write_in_len_rx(index: usize, _addr: u16, len: u16) { + USBRAM.mem(index * 4 + 3).write_value(len); + } + + pub(super) fn write_in_len_tx(index: usize, _addr: u16, len: u16) { USBRAM.mem(index * 4 + 1).write_value(len); } - pub(super) fn write_out(index: usize, addr: u16, max_len_bits: u16) { + pub(super) fn write_out_rx(index: usize, addr: u16, max_len_bits: u16) { USBRAM.mem(index * 4 + 2).write_value(addr); USBRAM.mem(index * 4 + 3).write_value(max_len_bits); } - pub(super) fn read_out_len(index: usize) -> u16 { + pub(super) fn write_out_tx(index: usize, addr: u16, max_len_bits: u16) { + USBRAM.mem(index * 4 + 0).write_value(addr); + USBRAM.mem(index * 4 + 1).write_value(max_len_bits); + } + + pub(super) fn read_out_len_tx(index: usize) -> u16 { + USBRAM.mem(index * 4 + 1).read() + } + + pub(super) fn read_out_len_rx(index: usize) -> u16 { USBRAM.mem(index * 4 + 3).read() } } -#[cfg(usbram_32_2048)] +#[cfg(any(usbram_32_2048, usbram_32_1024))] mod btable { use super::*; - pub(super) fn write_in(_index: usize, _addr: u16) {} + pub(super) fn write_in_tx(_index: usize, _addr: u16) {} - pub(super) fn write_in_len(index: usize, addr: u16, len: u16) { + pub(super) fn write_in_rx(_index: usize, _addr: u16) {} + + pub(super) fn write_in_len_tx(index: usize, addr: u16, len: u16) { USBRAM.mem(index * 2).write_value((addr as u32) | ((len as u32) << 16)); } - pub(super) fn write_out(index: usize, addr: u16, max_len_bits: u16) { + pub(super) fn write_in_len_rx(index: usize, addr: u16, len: u16) { + USBRAM + .mem(index * 2 + 1) + .write_value((addr as u32) | ((len as u32) << 16)); + } + + pub(super) fn write_out_tx(index: usize, addr: u16, max_len_bits: u16) { + USBRAM + .mem(index * 2) + .write_value((addr as u32) | ((max_len_bits as u32) << 16)); + } + + pub(super) fn write_out_rx(index: usize, addr: u16, max_len_bits: u16) { USBRAM .mem(index * 2 + 1) .write_value((addr as u32) | ((max_len_bits as u32) << 16)); } - pub(super) fn read_out_len(index: usize) -> u16 { + pub(super) fn read_out_len_tx(index: usize) -> u16 { + (USBRAM.mem(index * 2).read() >> 16) as u16 + } + + pub(super) fn read_out_len_rx(index: usize) -> u16 { (USBRAM.mem(index * 2 + 1).read() >> 16) as u16 } } @@ -226,9 +265,9 @@ impl EndpointBuffer { let n = USBRAM_ALIGN.min(buf.len() - i * USBRAM_ALIGN); val[..n].copy_from_slice(&buf[i * USBRAM_ALIGN..][..n]); - #[cfg(not(usbram_32_2048))] + #[cfg(not(any(usbram_32_2048, usbram_32_1024)))] let val = u16::from_le_bytes(val); - #[cfg(usbram_32_2048)] + #[cfg(any(usbram_32_2048, usbram_32_1024))] let val = u32::from_le_bytes(val); USBRAM.mem(self.addr as usize / USBRAM_ALIGN + i).write_value(val); } @@ -259,36 +298,29 @@ impl<'d, T: Instance> Driver<'d, T> { dm: impl Peripheral

> + 'd, ) -> Self { into_ref!(dp, dm); - T::Interrupt::unpend(); - unsafe { T::Interrupt::enable() }; + + super::common_init::(); let regs = T::regs(); - #[cfg(any(stm32l5, stm32wb))] - crate::pac::PWR.cr2().modify(|w| w.set_usv(true)); - - #[cfg(pwr_h5)] - crate::pac::PWR.usbscr().modify(|w| w.set_usb33sv(true)); - - ::enable_and_reset(); - regs.cntr().write(|w| { w.set_pdwn(false); w.set_fres(true); }); - #[cfg(time)] + #[cfg(feature = "time")] embassy_time::block_for(embassy_time::Duration::from_millis(100)); - #[cfg(not(time))] - cortex_m::asm::delay(unsafe { crate::rcc::get_freqs() }.sys.0 / 10); + #[cfg(not(feature = "time"))] + cortex_m::asm::delay(unsafe { crate::rcc::get_freqs() }.sys.to_hertz().unwrap().0 / 10); #[cfg(not(usb_v4))] regs.btable().write(|w| w.set_btable(0)); #[cfg(not(stm32l1))] { - dp.set_as_af(dp.af_num(), crate::gpio::sealed::AFType::OutputPushPull); - dm.set_as_af(dm.af_num(), crate::gpio::sealed::AFType::OutputPushPull); + use crate::gpio::{AfType, OutputType, Speed}; + dp.set_as_af(dp.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); + dm.set_as_af(dm.af_num(), AfType::output(OutputType::PushPull, Speed::VeryHigh)); } #[cfg(stm32l1)] let _ = (dp, dm); // suppress "unused" warnings. @@ -336,6 +368,13 @@ impl<'d, T: Instance> Driver<'d, T> { return false; // reserved for control pipe } let used = ep.used_out || ep.used_in; + if used && (ep.ep_type == EndpointType::Isochronous || ep.ep_type == EndpointType::Bulk) { + // Isochronous and bulk endpoints are double-buffered. + // Their corresponding endpoint/channel registers are forced to be unidirectional. + // Do not reuse this index. + return false; + } + let used_dir = match D::dir() { Direction::Out => ep.used_out, Direction::In => ep.used_in, @@ -359,7 +398,11 @@ impl<'d, T: Instance> Driver<'d, T> { let addr = self.alloc_ep_mem(len); trace!(" len_bits = {:04x}", len_bits); - btable::write_out::(index, addr, len_bits); + btable::write_out_rx::(index, addr, len_bits); + + if ep_type == EndpointType::Isochronous { + btable::write_out_tx::(index, addr, len_bits); + } EndpointBuffer { addr, @@ -375,7 +418,11 @@ impl<'d, T: Instance> Driver<'d, T> { let addr = self.alloc_ep_mem(len); // ep_in_len is written when actually TXing packets. - btable::write_in::(index, addr); + btable::write_in_tx::(index, addr); + + if ep_type == EndpointType::Isochronous { + btable::write_in_rx::(index, addr); + } EndpointBuffer { addr, @@ -647,7 +694,6 @@ impl<'d, T: Instance> driver::Bus for Bus<'d, T> { trait Dir { fn dir() -> Direction; - fn waker(i: usize) -> &'static AtomicWaker; } /// Marker type for the "IN" direction. @@ -656,11 +702,6 @@ impl Dir for In { fn dir() -> Direction { Direction::In } - - #[inline] - fn waker(i: usize) -> &'static AtomicWaker { - &EP_IN_WAKERS[i] - } } /// Marker type for the "OUT" direction. @@ -669,11 +710,18 @@ impl Dir for Out { fn dir() -> Direction { Direction::Out } +} - #[inline] - fn waker(i: usize) -> &'static AtomicWaker { - &EP_OUT_WAKERS[i] - } +/// Selects the packet buffer. +/// +/// For double-buffered endpoints, both the `Rx` and `Tx` buffer from a channel are used for the same +/// direction of transfer. This is opposed to single-buffered endpoints, where one channel can serve +/// two directions at the same time. +enum PacketBuffer { + /// The RX buffer - must be used for single-buffered OUT endpoints + Rx, + /// The TX buffer - must be used for single-buffered IN endpoints + Tx, } /// USB endpoint. @@ -684,15 +732,46 @@ pub struct Endpoint<'d, T: Instance, D> { } impl<'d, T: Instance, D> Endpoint<'d, T, D> { - fn write_data(&mut self, buf: &[u8]) { + /// Write to a double-buffered endpoint. + /// + /// For double-buffered endpoints, the data buffers overlap, but we still need to write to the right counter field. + /// The DTOG_TX bit indicates the buffer that is currently in use by the USB peripheral, that is, the buffer in + /// which the next transmit packet will be stored, so we need to write the counter of the OTHER buffer, which is + /// where the last transmitted packet was stored. + fn write_data_double_buffered(&mut self, buf: &[u8], packet_buffer: PacketBuffer) { let index = self.info.addr.index(); self.buf.write(buf); - btable::write_in_len::(index, self.buf.addr, buf.len() as _); + + match packet_buffer { + PacketBuffer::Rx => btable::write_in_len_rx::(index, self.buf.addr, buf.len() as _), + PacketBuffer::Tx => btable::write_in_len_tx::(index, self.buf.addr, buf.len() as _), + } } - fn read_data(&mut self, buf: &mut [u8]) -> Result { + /// Write to a single-buffered endpoint. + fn write_data(&mut self, buf: &[u8]) { + self.write_data_double_buffered(buf, PacketBuffer::Tx); + } + + /// Read from a double-buffered endpoint. + /// + /// For double-buffered endpoints, the data buffers overlap, but we still need to read from the right counter field. + /// The DTOG_RX bit indicates the buffer that is currently in use by the USB peripheral, that is, the buffer in + /// which the next received packet will be stored, so we need to read the counter of the OTHER buffer, which is + /// where the last received packet was stored. + fn read_data_double_buffered( + &mut self, + buf: &mut [u8], + packet_buffer: PacketBuffer, + ) -> Result { let index = self.info.addr.index(); - let rx_len = btable::read_out_len::(index) as usize & 0x3FF; + + let rx_len = match packet_buffer { + PacketBuffer::Rx => btable::read_out_len_rx::(index), + PacketBuffer::Tx => btable::read_out_len_tx::(index), + } as usize + & 0x3FF; + trace!("READ DONE, rx_len = {}", rx_len); if rx_len > buf.len() { return Err(EndpointError::BufferOverflow); @@ -700,6 +779,11 @@ impl<'d, T: Instance, D> Endpoint<'d, T, D> { self.buf.read(&mut buf[..rx_len]); Ok(rx_len) } + + /// Read from a single-buffered endpoint. + fn read_data(&mut self, buf: &mut [u8]) -> Result { + self.read_data_double_buffered(buf, PacketBuffer::Rx) + } } impl<'d, T: Instance> driver::Endpoint for Endpoint<'d, T, In> { @@ -754,25 +838,53 @@ impl<'d, T: Instance> driver::EndpointOut for Endpoint<'d, T, Out> { EP_OUT_WAKERS[index].register(cx.waker()); let regs = T::regs(); let stat = regs.epr(index).read().stat_rx(); - if matches!(stat, Stat::NAK | Stat::DISABLED) { - Poll::Ready(stat) + if self.info.ep_type == EndpointType::Isochronous { + // The isochronous endpoint does not change its `STAT_RX` field to `NAK` when receiving a packet. + // Therefore, this instead waits until the `CTR` interrupt was triggered. + if matches!(stat, Stat::DISABLED) || CTR_TRIGGERED[index].load(Ordering::Relaxed) { + Poll::Ready(stat) + } else { + Poll::Pending + } } else { - Poll::Pending + if matches!(stat, Stat::NAK | Stat::DISABLED) { + Poll::Ready(stat) + } else { + Poll::Pending + } } }) .await; + CTR_TRIGGERED[index].store(false, Ordering::Relaxed); + if stat == Stat::DISABLED { return Err(EndpointError::Disabled); } - let rx_len = self.read_data(buf)?; - let regs = T::regs(); + + let packet_buffer = if self.info.ep_type == EndpointType::Isochronous { + // Find the buffer, which is currently in use. Read from the OTHER buffer. + if regs.epr(index).read().dtog_rx() { + PacketBuffer::Rx + } else { + PacketBuffer::Tx + } + } else { + PacketBuffer::Rx + }; + + let rx_len = self.read_data_double_buffered(buf, packet_buffer)?; + regs.epr(index).write(|w| { w.set_ep_type(convert_type(self.info.ep_type)); w.set_ea(self.info.addr.index() as _); - w.set_stat_rx(Stat::from_bits(Stat::NAK.to_bits() ^ Stat::VALID.to_bits())); + if self.info.ep_type == EndpointType::Isochronous { + w.set_stat_rx(Stat::from_bits(0)); // STAT_RX remains `VALID`. + } else { + w.set_stat_rx(Stat::from_bits(Stat::NAK.to_bits() ^ Stat::VALID.to_bits())); + } w.set_stat_tx(Stat::from_bits(0)); w.set_ctr_rx(true); // don't clear w.set_ctr_tx(true); // don't clear @@ -796,25 +908,54 @@ impl<'d, T: Instance> driver::EndpointIn for Endpoint<'d, T, In> { EP_IN_WAKERS[index].register(cx.waker()); let regs = T::regs(); let stat = regs.epr(index).read().stat_tx(); - if matches!(stat, Stat::NAK | Stat::DISABLED) { - Poll::Ready(stat) + if self.info.ep_type == EndpointType::Isochronous { + // The isochronous endpoint does not change its `STAT_RX` field to `NAK` when receiving a packet. + // Therefore, this instead waits until the `CTR` interrupt was triggered. + if matches!(stat, Stat::DISABLED) || CTR_TRIGGERED[index].load(Ordering::Relaxed) { + Poll::Ready(stat) + } else { + Poll::Pending + } } else { - Poll::Pending + if matches!(stat, Stat::NAK | Stat::DISABLED) { + Poll::Ready(stat) + } else { + Poll::Pending + } } }) .await; + CTR_TRIGGERED[index].store(false, Ordering::Relaxed); + if stat == Stat::DISABLED { return Err(EndpointError::Disabled); } - self.write_data(buf); + let regs = T::regs(); + + let packet_buffer = if self.info.ep_type == EndpointType::Isochronous { + // Find the buffer, which is currently in use. Write to the OTHER buffer. + if regs.epr(index).read().dtog_tx() { + PacketBuffer::Tx + } else { + PacketBuffer::Rx + } + } else { + PacketBuffer::Tx + }; + + self.write_data_double_buffered(buf, packet_buffer); let regs = T::regs(); regs.epr(index).write(|w| { w.set_ep_type(convert_type(self.info.ep_type)); w.set_ea(self.info.addr.index() as _); - w.set_stat_tx(Stat::from_bits(Stat::NAK.to_bits() ^ Stat::VALID.to_bits())); + if self.info.ep_type == EndpointType::Isochronous { + w.set_stat_tx(Stat::from_bits(0)); // STAT_TX remains `VALID`. + } else { + w.set_stat_tx(Stat::from_bits(Stat::NAK.to_bits() ^ Stat::VALID.to_bits())); + } w.set_stat_rx(Stat::from_bits(0)); w.set_ctr_rx(true); // don't clear w.set_ctr_tx(true); // don't clear @@ -1057,3 +1198,32 @@ impl<'d, T: Instance> driver::ControlPipe for ControlPipe<'d, T> { }); } } + +trait SealedInstance { + fn regs() -> crate::pac::usb::Usb; +} + +/// USB instance trait. +#[allow(private_bounds)] +pub trait Instance: SealedInstance + RccPeripheral + 'static { + /// Interrupt for this USB instance. + type Interrupt: interrupt::typelevel::Interrupt; +} + +// Internal PHY pins +pin_trait!(DpPin, Instance); +pin_trait!(DmPin, Instance); + +foreach_interrupt!( + ($inst:ident, usb, $block:ident, LP, $irq:ident) => { + impl SealedInstance for crate::peripherals::$inst { + fn regs() -> crate::pac::usb::Usb { + crate::pac::$inst + } + } + + impl Instance for crate::peripherals::$inst { + type Interrupt = crate::interrupt::typelevel::$irq; + } + }; +); diff --git a/embassy-stm32/src/usb_otg/mod.rs b/embassy-stm32/src/usb_otg/mod.rs deleted file mode 100644 index 0649e684b..000000000 --- a/embassy-stm32/src/usb_otg/mod.rs +++ /dev/null @@ -1,163 +0,0 @@ -//! USB On The Go (OTG) - -use crate::rcc::RccPeripheral; -use crate::{interrupt, peripherals}; - -mod usb; -pub use usb::*; - -// Using Instance::ENDPOINT_COUNT requires feature(const_generic_expr) so just define maximum eps -const MAX_EP_COUNT: usize = 9; - -pub(crate) mod sealed { - pub trait Instance { - const HIGH_SPEED: bool; - const FIFO_DEPTH_WORDS: u16; - const ENDPOINT_COUNT: usize; - - fn regs() -> crate::pac::otg::Otg; - fn state() -> &'static super::State<{ super::MAX_EP_COUNT }>; - } -} - -/// USB OTG instance. -pub trait Instance: sealed::Instance + RccPeripheral { - /// Interrupt for this USB OTG instance. - type Interrupt: interrupt::typelevel::Interrupt; -} - -// Internal PHY pins -pin_trait!(DpPin, Instance); -pin_trait!(DmPin, Instance); - -// External PHY pins -pin_trait!(UlpiClkPin, Instance); -pin_trait!(UlpiDirPin, Instance); -pin_trait!(UlpiNxtPin, Instance); -pin_trait!(UlpiStpPin, Instance); -pin_trait!(UlpiD0Pin, Instance); -pin_trait!(UlpiD1Pin, Instance); -pin_trait!(UlpiD2Pin, Instance); -pin_trait!(UlpiD3Pin, Instance); -pin_trait!(UlpiD4Pin, Instance); -pin_trait!(UlpiD5Pin, Instance); -pin_trait!(UlpiD6Pin, Instance); -pin_trait!(UlpiD7Pin, Instance); - -foreach_interrupt!( - (USB_OTG_FS, otg, $block:ident, GLOBAL, $irq:ident) => { - impl sealed::Instance for peripherals::USB_OTG_FS { - const HIGH_SPEED: bool = false; - - cfg_if::cfg_if! { - if #[cfg(stm32f1)] { - const FIFO_DEPTH_WORDS: u16 = 128; - const ENDPOINT_COUNT: usize = 8; - } else if #[cfg(any( - stm32f2, - stm32f401, - stm32f405, - stm32f407, - stm32f411, - stm32f415, - stm32f417, - stm32f427, - stm32f429, - stm32f437, - stm32f439, - ))] { - const FIFO_DEPTH_WORDS: u16 = 320; - const ENDPOINT_COUNT: usize = 4; - } else if #[cfg(any( - stm32f412, - stm32f413, - stm32f423, - stm32f446, - stm32f469, - stm32f479, - stm32f7, - stm32l4, - stm32u5, - ))] { - const FIFO_DEPTH_WORDS: u16 = 320; - const ENDPOINT_COUNT: usize = 6; - } else if #[cfg(stm32g0x1)] { - const FIFO_DEPTH_WORDS: u16 = 512; - const ENDPOINT_COUNT: usize = 8; - } else if #[cfg(stm32h7)] { - const FIFO_DEPTH_WORDS: u16 = 1024; - const ENDPOINT_COUNT: usize = 9; - } else if #[cfg(stm32u5)] { - const FIFO_DEPTH_WORDS: u16 = 320; - const ENDPOINT_COUNT: usize = 6; - } else { - compile_error!("USB_OTG_FS peripheral is not supported by this chip."); - } - } - - fn regs() -> crate::pac::otg::Otg { - crate::pac::USB_OTG_FS - } - - fn state() -> &'static State { - static STATE: State = State::new(); - &STATE - } - } - - impl Instance for peripherals::USB_OTG_FS { - type Interrupt = crate::interrupt::typelevel::$irq; - } - }; - - (USB_OTG_HS, otg, $block:ident, GLOBAL, $irq:ident) => { - impl sealed::Instance for peripherals::USB_OTG_HS { - const HIGH_SPEED: bool = true; - - cfg_if::cfg_if! { - if #[cfg(any( - stm32f2, - stm32f405, - stm32f407, - stm32f415, - stm32f417, - stm32f427, - stm32f429, - stm32f437, - stm32f439, - ))] { - const FIFO_DEPTH_WORDS: u16 = 1024; - const ENDPOINT_COUNT: usize = 6; - } else if #[cfg(any( - stm32f446, - stm32f469, - stm32f479, - stm32f7, - stm32h7, - ))] { - const FIFO_DEPTH_WORDS: u16 = 1024; - const ENDPOINT_COUNT: usize = 9; - } else if #[cfg(stm32u5)] { - const FIFO_DEPTH_WORDS: u16 = 1024; - const ENDPOINT_COUNT: usize = 9; - } else { - compile_error!("USB_OTG_HS peripheral is not supported by this chip."); - } - } - - fn regs() -> crate::pac::otg::Otg { - // OTG HS registers are a superset of FS registers - unsafe { crate::pac::otg::Otg::from_ptr(crate::pac::USB_OTG_HS.as_ptr()) } - } - - fn state() -> &'static State { - static STATE: State = State::new(); - &STATE - } - } - - impl Instance for peripherals::USB_OTG_HS { - type Interrupt = crate::interrupt::typelevel::$irq; - } - }; -); diff --git a/embassy-stm32/src/wdg/mod.rs b/embassy-stm32/src/wdg/mod.rs index dc701ef64..ab21c4b6b 100644 --- a/embassy-stm32/src/wdg/mod.rs +++ b/embassy-stm32/src/wdg/mod.rs @@ -42,9 +42,13 @@ impl<'d, T: Instance> IndependentWatchdog<'d, T> { // Prescaler value let psc = 2u16.pow(psc_power); + #[cfg(not(iwdg_v3))] + assert!(psc <= 256, "IWDG prescaler should be no more than 256"); + #[cfg(iwdg_v3)] // H5, U5, WBA + assert!(psc <= 1024, "IWDG prescaler should be no more than 1024"); + // Convert prescaler power to PR register value let pr = psc_power as u8 - 2; - assert!(pr <= 0b110); // Reload value let rl = reload_value(psc, timeout_us); @@ -76,18 +80,17 @@ impl<'d, T: Instance> IndependentWatchdog<'d, T> { } } -mod sealed { - pub trait Instance { - fn regs() -> crate::pac::iwdg::Iwdg; - } +trait SealedInstance { + fn regs() -> crate::pac::iwdg::Iwdg; } /// IWDG instance trait. -pub trait Instance: sealed::Instance {} +#[allow(private_bounds)] +pub trait Instance: SealedInstance {} foreach_peripheral!( (iwdg, $inst:ident) => { - impl sealed::Instance for crate::peripherals::$inst { + impl SealedInstance for crate::peripherals::$inst { fn regs() -> crate::pac::iwdg::Iwdg { crate::pac::$inst } diff --git a/embassy-sync/CHANGELOG.md b/embassy-sync/CHANGELOG.md index e7db97ef7..a7dd6f66e 100644 --- a/embassy-sync/CHANGELOG.md +++ b/embassy-sync/CHANGELOG.md @@ -5,16 +5,35 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + +- Add `LazyLock` sync primitive. +- Add `Watch` sync primitive. +- Add `clear`, `len`, `is_empty` and `is_full` functions to `zerocopy_channel`. +- Add `capacity`, `free_capacity`, `clear`, `len`, `is_empty` and `is_full` functions to `channel::{Sender, Receiver}`. +- Add `capacity`, `free_capacity`, `clear`, `len`, `is_empty` and `is_full` functions to `priority_channel::{Sender, Receiver}`. + +## 0.6.0 - 2024-05-29 + +- Add `capacity`, `free_capacity`, `clear`, `len`, `is_empty` and `is_full` functions to `Channel`. +- Add `capacity`, `free_capacity`, `clear`, `len`, `is_empty` and `is_full` functions to `PriorityChannel`. +- Add `capacity`, `free_capacity`, `clear`, `len`, `is_empty` and `is_full` functions to `PubSubChannel`. +- Made `PubSubBehavior` sealed + - If you called `.publish_immediate(...)` on the queue directly before, then now call `.immediate_publisher().publish_immediate(...)` +- Add `OnceLock` sync primitive. +- Add constructor for `DynamicChannel` +- Add ready_to_receive functions to `Channel` and `Receiver`. + ## 0.5.0 - 2023-12-04 -- Add a PriorityChannel. -- Remove nightly and unstable-traits features in preparation for 1.75. -- Upgrade heapless to 0.8. -- Upgrade static-cell to 2.0. +- Add a `PriorityChannel`. +- Remove `nightly` and `unstable-traits` features in preparation for 1.75. +- Upgrade `heapless` to 0.8. +- Upgrade `static-cell` to 2.0. ## 0.4.0 - 2023-10-31 -- Re-add impl_trait_projections +- Re-add `impl_trait_projections` - switch to `embedded-io 0.6` ## 0.3.0 - 2023-09-14 @@ -35,7 +54,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Remove unnecessary uses of `atomic-polyfill` - Add `#[must_use]` to all futures. - ## 0.1.0 - 2022-08-26 - First release diff --git a/embassy-sync/Cargo.toml b/embassy-sync/Cargo.toml index 85673026c..2f049b6bc 100644 --- a/embassy-sync/Cargo.toml +++ b/embassy-sync/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "embassy-sync" -version = "0.5.0" +version = "0.6.0" edition = "2021" description = "no-std, no-alloc synchronization primitives with async support" repository = "https://github.com/embassy-rs/embassy" @@ -20,13 +20,14 @@ src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/embassy-sync/ target = "thumbv7em-none-eabi" [features] -std = [] +std = ["critical-section/std"] turbowakers = [] [dependencies] defmt = { version = "0.3", optional = true } log = { version = "0.4.14", optional = true } +futures-sink = { version = "0.3", default-features = false, features = [] } futures-util = { version = "0.3.17", default-features = false } critical-section = "1.1" heapless = "0.8" @@ -37,7 +38,7 @@ embedded-io-async = { version = "0.6.1" } futures-executor = { version = "0.3.17", features = [ "thread-pool" ] } futures-test = "0.3.17" futures-timer = "3.0.2" -futures-util = { version = "0.3.17", features = [ "channel" ] } +futures-util = { version = "0.3.17", features = [ "channel", "sink" ] } # Enable critical-section implementation for std, for tests critical-section = { version = "1.1", features = ["std"] } diff --git a/embassy-sync/README.md b/embassy-sync/README.md index c2e13799e..6871bcabc 100644 --- a/embassy-sync/README.md +++ b/embassy-sync/README.md @@ -5,14 +5,16 @@ An [Embassy](https://embassy.dev) project. Synchronization primitives and data structures with async support: - [`Channel`](channel::Channel) - A Multiple Producer Multiple Consumer (MPMC) channel. Each message is only received by a single consumer. -- [`PriorityChannel`](channel::priority::PriorityChannel) - A Multiple Producer Multiple Consumer (MPMC) channel. Each message is only received by a single consumer. Higher priority items are sifted to the front of the channel. +- [`PriorityChannel`](priority_channel::PriorityChannel) - A Multiple Producer Multiple Consumer (MPMC) channel. Each message is only received by a single consumer. Higher priority items are shifted to the front of the channel. - [`PubSubChannel`](pubsub::PubSubChannel) - A broadcast channel (publish-subscribe) channel. Each message is received by all consumers. - [`Signal`](signal::Signal) - Signalling latest value to a single consumer. +- [`Watch`](watch::Watch) - Signalling latest value to multiple consumers. - [`Mutex`](mutex::Mutex) - Mutex for synchronizing state between asynchronous tasks. - [`Pipe`](pipe::Pipe) - Byte stream implementing `embedded_io` traits. - [`WakerRegistration`](waitqueue::WakerRegistration) - Utility to register and wake a `Waker`. - [`AtomicWaker`](waitqueue::AtomicWaker) - A variant of `WakerRegistration` accessible using a non-mut API. - [`MultiWakerRegistration`](waitqueue::MultiWakerRegistration) - Utility registering and waking multiple `Waker`'s. +- [`LazyLock`](lazy_lock::LazyLock) - A value which is initialized on the first access ## Interoperability diff --git a/embassy-sync/build.rs b/embassy-sync/build.rs index afd76dad1..ecd2c0c9f 100644 --- a/embassy-sync/build.rs +++ b/embassy-sync/build.rs @@ -1,31 +1,7 @@ -use std::env; +#[path = "./build_common.rs"] +mod common; fn main() { - println!("cargo:rerun-if-changed=build.rs"); - - let target = env::var("TARGET").unwrap(); - - if target.starts_with("thumbv6m-") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv6m"); - } else if target.starts_with("thumbv7m-") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv7m"); - } else if target.starts_with("thumbv7em-") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv7m"); - println!("cargo:rustc-cfg=armv7em"); // (not currently used) - } else if target.starts_with("thumbv8m.base") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv8m"); - println!("cargo:rustc-cfg=armv8m_base"); - } else if target.starts_with("thumbv8m.main") { - println!("cargo:rustc-cfg=cortex_m"); - println!("cargo:rustc-cfg=armv8m"); - println!("cargo:rustc-cfg=armv8m_main"); - } - - if target.ends_with("-eabihf") { - println!("cargo:rustc-cfg=has_fpu"); - } + let mut cfgs = common::CfgSet::new(); + common::set_target_cfgs(&mut cfgs); } diff --git a/embassy-sync/build_common.rs b/embassy-sync/build_common.rs new file mode 100644 index 000000000..4f24e6d37 --- /dev/null +++ b/embassy-sync/build_common.rs @@ -0,0 +1,94 @@ +// NOTE: this file is copy-pasted between several Embassy crates, because there is no +// straightforward way to share this code: +// - it cannot be placed into the root of the repo and linked from each build.rs using `#[path = +// "../build_common.rs"]`, because `cargo publish` requires that all files published with a crate +// reside in the crate's directory, +// - it cannot be symlinked from `embassy-xxx/build_common.rs` to `../build_common.rs`, because +// symlinks don't work on Windows. + +use std::collections::HashSet; +use std::env; + +/// Helper for emitting cargo instruction for enabling configs (`cargo:rustc-cfg=X`) and declaring +/// them (`cargo:rust-check-cfg=cfg(X)`). +#[derive(Debug)] +pub struct CfgSet { + enabled: HashSet, + declared: HashSet, +} + +impl CfgSet { + pub fn new() -> Self { + Self { + enabled: HashSet::new(), + declared: HashSet::new(), + } + } + + /// Enable a config, which can then be used in `#[cfg(...)]` for conditional compilation. + /// + /// All configs that can potentially be enabled should be unconditionally declared using + /// [`Self::declare()`]. + pub fn enable(&mut self, cfg: impl AsRef) { + if self.enabled.insert(cfg.as_ref().to_owned()) { + println!("cargo:rustc-cfg={}", cfg.as_ref()); + } + } + + pub fn enable_all(&mut self, cfgs: &[impl AsRef]) { + for cfg in cfgs.iter() { + self.enable(cfg.as_ref()); + } + } + + /// Declare a valid config for conditional compilation, without enabling it. + /// + /// This enables rustc to check that the configs in `#[cfg(...)]` attributes are valid. + pub fn declare(&mut self, cfg: impl AsRef) { + if self.declared.insert(cfg.as_ref().to_owned()) { + println!("cargo:rustc-check-cfg=cfg({})", cfg.as_ref()); + } + } + + pub fn declare_all(&mut self, cfgs: &[impl AsRef]) { + for cfg in cfgs.iter() { + self.declare(cfg.as_ref()); + } + } + + pub fn set(&mut self, cfg: impl Into, enable: bool) { + let cfg = cfg.into(); + if enable { + self.enable(cfg.clone()); + } + self.declare(cfg); + } +} + +/// Sets configs that describe the target platform. +pub fn set_target_cfgs(cfgs: &mut CfgSet) { + let target = env::var("TARGET").unwrap(); + + if target.starts_with("thumbv6m-") { + cfgs.enable_all(&["cortex_m", "armv6m"]); + } else if target.starts_with("thumbv7m-") { + cfgs.enable_all(&["cortex_m", "armv7m"]); + } else if target.starts_with("thumbv7em-") { + cfgs.enable_all(&["cortex_m", "armv7m", "armv7em"]); + } else if target.starts_with("thumbv8m.base") { + cfgs.enable_all(&["cortex_m", "armv8m", "armv8m_base"]); + } else if target.starts_with("thumbv8m.main") { + cfgs.enable_all(&["cortex_m", "armv8m", "armv8m_main"]); + } + cfgs.declare_all(&[ + "cortex_m", + "armv6m", + "armv7m", + "armv7em", + "armv8m", + "armv8m_base", + "armv8m_main", + ]); + + cfgs.set("has_fpu", target.ends_with("-eabihf")); +} diff --git a/embassy-sync/src/blocking_mutex/mod.rs b/embassy-sync/src/blocking_mutex/mod.rs index 8a4a4c642..beafdb43d 100644 --- a/embassy-sync/src/blocking_mutex/mod.rs +++ b/embassy-sync/src/blocking_mutex/mod.rs @@ -104,6 +104,7 @@ impl Mutex { impl Mutex { /// Borrows the data + #[allow(clippy::should_implement_trait)] pub fn borrow(&self) -> &T { let ptr = self.data.get() as *const T; unsafe { &*ptr } diff --git a/embassy-sync/src/channel.rs b/embassy-sync/src/channel.rs index ff7129303..18b053111 100644 --- a/embassy-sync/src/channel.rs +++ b/embassy-sync/src/channel.rs @@ -42,7 +42,7 @@ where M: RawMutex, { fn clone(&self) -> Self { - Sender { channel: self.channel } + *self } } @@ -72,6 +72,48 @@ where pub fn poll_ready_to_send(&self, cx: &mut Context<'_>) -> Poll<()> { self.channel.poll_ready_to_send(cx) } + + /// Returns the maximum number of elements the channel can hold. + /// + /// See [`Channel::capacity()`] + pub const fn capacity(&self) -> usize { + self.channel.capacity() + } + + /// Returns the free capacity of the channel. + /// + /// See [`Channel::free_capacity()`] + pub fn free_capacity(&self) -> usize { + self.channel.free_capacity() + } + + /// Clears all elements in the channel. + /// + /// See [`Channel::clear()`] + pub fn clear(&self) { + self.channel.clear(); + } + + /// Returns the number of elements currently in the channel. + /// + /// See [`Channel::len()`] + pub fn len(&self) -> usize { + self.channel.len() + } + + /// Returns whether the channel is empty. + /// + /// See [`Channel::is_empty()`] + pub fn is_empty(&self) -> bool { + self.channel.is_empty() + } + + /// Returns whether the channel is full. + /// + /// See [`Channel::is_full()`] + pub fn is_full(&self) -> bool { + self.channel.is_full() + } } /// Send-only access to a [`Channel`] without knowing channel size. @@ -81,7 +123,7 @@ pub struct DynamicSender<'ch, T> { impl<'ch, T> Clone for DynamicSender<'ch, T> { fn clone(&self) -> Self { - DynamicSender { channel: self.channel } + *self } } @@ -135,7 +177,7 @@ where M: RawMutex, { fn clone(&self) -> Self { - Receiver { channel: self.channel } + *self } } @@ -152,6 +194,13 @@ where self.channel.receive() } + /// Is a value ready to be received in the channel + /// + /// See [`Channel::ready_to_receive()`]. + pub fn ready_to_receive(&self) -> ReceiveReadyFuture<'_, M, T, N> { + self.channel.ready_to_receive() + } + /// Attempt to immediately receive the next value. /// /// See [`Channel::try_receive()`] @@ -172,6 +221,48 @@ where pub fn poll_receive(&self, cx: &mut Context<'_>) -> Poll { self.channel.poll_receive(cx) } + + /// Returns the maximum number of elements the channel can hold. + /// + /// See [`Channel::capacity()`] + pub const fn capacity(&self) -> usize { + self.channel.capacity() + } + + /// Returns the free capacity of the channel. + /// + /// See [`Channel::free_capacity()`] + pub fn free_capacity(&self) -> usize { + self.channel.free_capacity() + } + + /// Clears all elements in the channel. + /// + /// See [`Channel::clear()`] + pub fn clear(&self) { + self.channel.clear(); + } + + /// Returns the number of elements currently in the channel. + /// + /// See [`Channel::len()`] + pub fn len(&self) -> usize { + self.channel.len() + } + + /// Returns whether the channel is empty. + /// + /// See [`Channel::is_empty()`] + pub fn is_empty(&self) -> bool { + self.channel.is_empty() + } + + /// Returns whether the channel is full. + /// + /// See [`Channel::is_full()`] + pub fn is_full(&self) -> bool { + self.channel.is_full() + } } /// Receive-only access to a [`Channel`] without knowing channel size. @@ -181,7 +272,7 @@ pub struct DynamicReceiver<'ch, T> { impl<'ch, T> Clone for DynamicReceiver<'ch, T> { fn clone(&self) -> Self { - DynamicReceiver { channel: self.channel } + *self } } @@ -246,6 +337,26 @@ where } } +/// Future returned by [`Channel::ready_to_receive`] and [`Receiver::ready_to_receive`]. +#[must_use = "futures do nothing unless you `.await` or poll them"] +pub struct ReceiveReadyFuture<'ch, M, T, const N: usize> +where + M: RawMutex, +{ + channel: &'ch Channel, +} + +impl<'ch, M, T, const N: usize> Future for ReceiveReadyFuture<'ch, M, T, N> +where + M: RawMutex, +{ + type Output = (); + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { + self.channel.poll_ready_to_receive(cx) + } +} + /// Future returned by [`DynamicReceiver::receive`]. #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct DynamicReceiveFuture<'ch, T> { @@ -263,6 +374,12 @@ impl<'ch, T> Future for DynamicReceiveFuture<'ch, T> { } } +impl<'ch, M: RawMutex, T, const N: usize> From> for DynamicReceiveFuture<'ch, T> { + fn from(value: ReceiveFuture<'ch, M, T, N>) -> Self { + Self { channel: value.channel } + } +} + /// Future returned by [`Channel::send`] and [`Sender::send`]. #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct SendFuture<'ch, M, T, const N: usize> @@ -321,6 +438,15 @@ impl<'ch, T> Future for DynamicSendFuture<'ch, T> { impl<'ch, T> Unpin for DynamicSendFuture<'ch, T> {} +impl<'ch, M: RawMutex, T, const N: usize> From> for DynamicSendFuture<'ch, T> { + fn from(value: SendFuture<'ch, M, T, N>) -> Self { + Self { + channel: value.channel, + message: value.message, + } + } +} + pub(crate) trait DynamicChannel { fn try_send_with_context(&self, message: T, cx: Option<&mut Context<'_>>) -> Result<(), TrySendError>; @@ -434,6 +560,22 @@ impl ChannelState { Poll::Pending } } + + fn clear(&mut self) { + self.queue.clear(); + } + + fn len(&self) -> usize { + self.queue.len() + } + + fn is_empty(&self) -> bool { + self.queue.is_empty() + } + + fn is_full(&self) -> bool { + self.queue.is_full() + } } /// A bounded channel for communicating between asynchronous tasks @@ -507,6 +649,16 @@ where Receiver { channel: self } } + /// Get a sender for this channel using dynamic dispatch. + pub fn dyn_sender(&self) -> DynamicSender<'_, T> { + DynamicSender { channel: self } + } + + /// Get a receiver for this channel using dynamic dispatch. + pub fn dyn_receiver(&self) -> DynamicReceiver<'_, T> { + DynamicReceiver { channel: self } + } + /// Send a value, waiting until there is capacity. /// /// Sending completes when the value has been pushed to the channel's queue. @@ -540,6 +692,14 @@ where ReceiveFuture { channel: self } } + /// Is a value ready to be received in the channel + /// + /// If there are no messages in the channel's buffer, this method will + /// wait until there is at least one + pub fn ready_to_receive(&self) -> ReceiveReadyFuture<'_, M, T, N> { + ReceiveReadyFuture { channel: self } + } + /// Attempt to immediately receive a message. /// /// This method will either receive a message from the channel immediately or return an error @@ -547,6 +707,38 @@ where pub fn try_receive(&self) -> Result { self.lock(|c| c.try_receive()) } + + /// Returns the maximum number of elements the channel can hold. + pub const fn capacity(&self) -> usize { + N + } + + /// Returns the free capacity of the channel. + /// + /// This is equivalent to `capacity() - len()` + pub fn free_capacity(&self) -> usize { + N - self.len() + } + + /// Clears all elements in the channel. + pub fn clear(&self) { + self.lock(|c| c.clear()); + } + + /// Returns the number of elements currently in the channel. + pub fn len(&self) -> usize { + self.lock(|c| c.len()) + } + + /// Returns whether the channel is empty. + pub fn is_empty(&self) -> bool { + self.lock(|c| c.is_empty()) + } + + /// Returns whether the channel is full. + pub fn is_full(&self) -> bool { + self.lock(|c| c.is_full()) + } } /// Implements the DynamicChannel to allow creating types that are unaware of the queue size with the @@ -648,7 +840,7 @@ mod tests { } #[test] - fn dynamic_dispatch() { + fn dynamic_dispatch_into() { let c = Channel::::new(); let s: DynamicSender<'_, u32> = c.sender().into(); let r: DynamicReceiver<'_, u32> = c.receiver().into(); @@ -657,6 +849,16 @@ mod tests { assert_eq!(r.try_receive().unwrap(), 1); } + #[test] + fn dynamic_dispatch_constructor() { + let c = Channel::::new(); + let s = c.dyn_sender(); + let r = c.dyn_receiver(); + + assert!(s.try_send(1).is_ok()); + assert_eq!(r.try_receive().unwrap(), 1); + } + #[futures_test::test] async fn receiver_receives_given_try_send_async() { let executor = ThreadPool::new().unwrap(); diff --git a/embassy-sync/src/fmt.rs b/embassy-sync/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-sync/src/fmt.rs +++ b/embassy-sync/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-sync/src/lazy_lock.rs b/embassy-sync/src/lazy_lock.rs new file mode 100644 index 000000000..18e3c2019 --- /dev/null +++ b/embassy-sync/src/lazy_lock.rs @@ -0,0 +1,152 @@ +//! Synchronization primitive for initializing a value once, allowing others to get a reference to the value. + +use core::cell::UnsafeCell; +use core::mem::ManuallyDrop; +use core::sync::atomic::{AtomicBool, Ordering}; + +/// The `LazyLock` is a synchronization primitive that allows for +/// initializing a value once, and allowing others to obtain a +/// reference to the value. This is useful for lazy initialization of +/// a static value. +/// +/// # Example +/// ``` +/// use futures_executor::block_on; +/// use embassy_sync::lazy_lock::LazyLock; +/// +/// // Define a static value that will be lazily initialized +/// // at runtime at the first access. +/// static VALUE: LazyLock = LazyLock::new(|| 20); +/// +/// let reference = VALUE.get(); +/// assert_eq!(reference, &20); +/// ``` +pub struct LazyLock T> { + init: AtomicBool, + data: UnsafeCell>, +} + +union Data { + value: ManuallyDrop, + f: ManuallyDrop, +} + +unsafe impl Sync for LazyLock {} + +impl T> LazyLock { + /// Create a new uninitialized `StaticLock`. + pub const fn new(init_fn: F) -> Self { + Self { + init: AtomicBool::new(false), + data: UnsafeCell::new(Data { + f: ManuallyDrop::new(init_fn), + }), + } + } + + /// Get a reference to the underlying value, initializing it if it + /// has not been done already. + #[inline] + pub fn get(&self) -> &T { + self.ensure_init_fast(); + unsafe { &(*self.data.get()).value } + } + + /// Consume the `LazyLock`, returning the underlying value. The + /// initialization function will be called if it has not been + /// already. + #[inline] + pub fn into_inner(self) -> T { + self.ensure_init_fast(); + let this = ManuallyDrop::new(self); + let data = unsafe { core::ptr::read(&this.data) }.into_inner(); + + ManuallyDrop::into_inner(unsafe { data.value }) + } + + /// Initialize the `LazyLock` if it has not been initialized yet. + /// This function is a fast track to [`Self::ensure_init`] + /// which does not require a critical section in most cases when + /// the value has been initialized already. + /// When this function returns, `self.data` is guaranteed to be + /// initialized and visible on the current core. + #[inline] + fn ensure_init_fast(&self) { + if !self.init.load(Ordering::Acquire) { + self.ensure_init(); + } + } + + /// Initialize the `LazyLock` if it has not been initialized yet. + /// When this function returns, `self.data` is guaranteed to be + /// initialized and visible on the current core. + fn ensure_init(&self) { + critical_section::with(|_| { + if !self.init.load(Ordering::Acquire) { + let data = unsafe { &mut *self.data.get() }; + let f = unsafe { ManuallyDrop::take(&mut data.f) }; + let value = f(); + data.value = ManuallyDrop::new(value); + + self.init.store(true, Ordering::Release); + } + }); + } +} + +impl Drop for LazyLock { + fn drop(&mut self) { + if self.init.load(Ordering::Acquire) { + unsafe { ManuallyDrop::drop(&mut self.data.get_mut().value) }; + } else { + unsafe { ManuallyDrop::drop(&mut self.data.get_mut().f) }; + } + } +} + +#[cfg(test)] +mod tests { + use core::sync::atomic::{AtomicU32, Ordering}; + + use super::*; + + #[test] + fn test_lazy_lock() { + static VALUE: LazyLock = LazyLock::new(|| 20); + let reference = VALUE.get(); + assert_eq!(reference, &20); + } + #[test] + fn test_lazy_lock_into_inner() { + let lazy: LazyLock = LazyLock::new(|| 20); + let value = lazy.into_inner(); + assert_eq!(value, 20); + } + + static DROP_CHECKER: AtomicU32 = AtomicU32::new(0); + struct DropCheck; + + impl Drop for DropCheck { + fn drop(&mut self) { + DROP_CHECKER.fetch_add(1, Ordering::Acquire); + } + } + + #[test] + fn test_lazy_drop() { + let lazy: LazyLock = LazyLock::new(|| DropCheck); + assert_eq!(DROP_CHECKER.load(Ordering::Acquire), 0); + lazy.get(); + drop(lazy); + assert_eq!(DROP_CHECKER.load(Ordering::Acquire), 1); + + let dropper = DropCheck; + let lazy_fn: LazyLock = LazyLock::new(move || { + let _a = dropper; + 20 + }); + assert_eq!(DROP_CHECKER.load(Ordering::Acquire), 1); + drop(lazy_fn); + assert_eq!(DROP_CHECKER.load(Ordering::Acquire), 2); + } +} diff --git a/embassy-sync/src/lib.rs b/embassy-sync/src/lib.rs index d88c76db5..df0f5e815 100644 --- a/embassy-sync/src/lib.rs +++ b/embassy-sync/src/lib.rs @@ -1,4 +1,4 @@ -#![cfg_attr(not(any(feature = "std", feature = "wasm")), no_std)] +#![cfg_attr(not(feature = "std"), no_std)] #![allow(async_fn_in_trait)] #![allow(clippy::new_without_default)] #![doc = include_str!("../README.md")] @@ -12,10 +12,14 @@ mod ring_buffer; pub mod blocking_mutex; pub mod channel; +pub mod lazy_lock; pub mod mutex; +pub mod once_lock; pub mod pipe; pub mod priority_channel; pub mod pubsub; +pub mod semaphore; pub mod signal; pub mod waitqueue; +pub mod watch; pub mod zerocopy_channel; diff --git a/embassy-sync/src/mutex.rs b/embassy-sync/src/mutex.rs index 72459d660..08f66e374 100644 --- a/embassy-sync/src/mutex.rs +++ b/embassy-sync/src/mutex.rs @@ -5,6 +5,7 @@ use core::cell::{RefCell, UnsafeCell}; use core::future::poll_fn; use core::ops::{Deref, DerefMut}; use core::task::Poll; +use core::{fmt, mem}; use crate::blocking_mutex::raw::RawMutex; use crate::blocking_mutex::Mutex as BlockingMutex; @@ -128,12 +129,49 @@ where } } +impl From for Mutex { + fn from(from: T) -> Self { + Self::new(from) + } +} + +impl Default for Mutex +where + M: RawMutex, + T: Default, +{ + fn default() -> Self { + Self::new(Default::default()) + } +} + +impl fmt::Debug for Mutex +where + M: RawMutex, + T: ?Sized + fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut d = f.debug_struct("Mutex"); + match self.try_lock() { + Ok(value) => { + d.field("inner", &&*value); + } + Err(TryLockError) => { + d.field("inner", &format_args!("")); + } + } + + d.finish_non_exhaustive() + } +} + /// Async mutex guard. /// /// Owning an instance of this type indicates having /// successfully locked the mutex, and grants access to the contents. /// /// Dropping it unlocks the mutex. +#[clippy::has_significant_drop] pub struct MutexGuard<'a, M, T> where M: RawMutex, @@ -142,6 +180,25 @@ where mutex: &'a Mutex, } +impl<'a, M, T> MutexGuard<'a, M, T> +where + M: RawMutex, + T: ?Sized, +{ + /// Returns a locked view over a portion of the locked data. + pub fn map(this: Self, fun: impl FnOnce(&mut T) -> &mut U) -> MappedMutexGuard<'a, M, U> { + let mutex = this.mutex; + let value = fun(unsafe { &mut *this.mutex.inner.get() }); + // Don't run the `drop` method for MutexGuard. The ownership of the underlying + // locked state is being moved to the returned MappedMutexGuard. + mem::forget(this); + MappedMutexGuard { + state: &mutex.state, + value, + } + } +} + impl<'a, M, T> Drop for MutexGuard<'a, M, T> where M: RawMutex, @@ -180,3 +237,155 @@ where unsafe { &mut *(self.mutex.inner.get()) } } } + +impl<'a, M, T> fmt::Debug for MutexGuard<'a, M, T> +where + M: RawMutex, + T: ?Sized + fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, M, T> fmt::Display for MutexGuard<'a, M, T> +where + M: RawMutex, + T: ?Sized + fmt::Display, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +/// A handle to a held `Mutex` that has had a function applied to it via [`MutexGuard::map`] or +/// [`MappedMutexGuard::map`]. +/// +/// This can be used to hold a subfield of the protected data. +#[clippy::has_significant_drop] +pub struct MappedMutexGuard<'a, M, T> +where + M: RawMutex, + T: ?Sized, +{ + state: &'a BlockingMutex>, + value: *mut T, +} + +impl<'a, M, T> MappedMutexGuard<'a, M, T> +where + M: RawMutex, + T: ?Sized, +{ + /// Returns a locked view over a portion of the locked data. + pub fn map(this: Self, fun: impl FnOnce(&mut T) -> &mut U) -> MappedMutexGuard<'a, M, U> { + let state = this.state; + let value = fun(unsafe { &mut *this.value }); + // Don't run the `drop` method for MutexGuard. The ownership of the underlying + // locked state is being moved to the returned MappedMutexGuard. + mem::forget(this); + MappedMutexGuard { state, value } + } +} + +impl<'a, M, T> Deref for MappedMutexGuard<'a, M, T> +where + M: RawMutex, + T: ?Sized, +{ + type Target = T; + fn deref(&self) -> &Self::Target { + // Safety: the MutexGuard represents exclusive access to the contents + // of the mutex, so it's OK to get it. + unsafe { &*self.value } + } +} + +impl<'a, M, T> DerefMut for MappedMutexGuard<'a, M, T> +where + M: RawMutex, + T: ?Sized, +{ + fn deref_mut(&mut self) -> &mut Self::Target { + // Safety: the MutexGuard represents exclusive access to the contents + // of the mutex, so it's OK to get it. + unsafe { &mut *self.value } + } +} + +impl<'a, M, T> Drop for MappedMutexGuard<'a, M, T> +where + M: RawMutex, + T: ?Sized, +{ + fn drop(&mut self) { + self.state.lock(|s| { + let mut s = unwrap!(s.try_borrow_mut()); + s.locked = false; + s.waker.wake(); + }) + } +} + +unsafe impl Send for MappedMutexGuard<'_, M, T> +where + M: RawMutex + Sync, + T: Send + ?Sized, +{ +} + +unsafe impl Sync for MappedMutexGuard<'_, M, T> +where + M: RawMutex + Sync, + T: Sync + ?Sized, +{ +} + +impl<'a, M, T> fmt::Debug for MappedMutexGuard<'a, M, T> +where + M: RawMutex, + T: ?Sized + fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, M, T> fmt::Display for MappedMutexGuard<'a, M, T> +where + M: RawMutex, + T: ?Sized + fmt::Display, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[cfg(test)] +mod tests { + use crate::blocking_mutex::raw::NoopRawMutex; + use crate::mutex::{Mutex, MutexGuard}; + + #[futures_test::test] + async fn mapped_guard_releases_lock_when_dropped() { + let mutex: Mutex = Mutex::new([0, 1]); + + { + let guard = mutex.lock().await; + assert_eq!(*guard, [0, 1]); + let mut mapped = MutexGuard::map(guard, |this| &mut this[1]); + assert_eq!(*mapped, 1); + *mapped = 2; + } + + { + let guard = mutex.lock().await; + assert_eq!(*guard, [0, 2]); + let mut mapped = MutexGuard::map(guard, |this| &mut this[1]); + assert_eq!(*mapped, 2); + *mapped = 3; + } + + assert_eq!(*mutex.lock().await, [0, 3]); + } +} diff --git a/embassy-sync/src/once_lock.rs b/embassy-sync/src/once_lock.rs new file mode 100644 index 000000000..55608ba32 --- /dev/null +++ b/embassy-sync/src/once_lock.rs @@ -0,0 +1,236 @@ +//! Synchronization primitive for initializing a value once, allowing others to await a reference to the value. + +use core::cell::Cell; +use core::future::poll_fn; +use core::mem::MaybeUninit; +use core::sync::atomic::{AtomicBool, Ordering}; +use core::task::Poll; + +/// The `OnceLock` is a synchronization primitive that allows for +/// initializing a value once, and allowing others to `.await` a +/// reference to the value. This is useful for lazy initialization of +/// a static value. +/// +/// **Note**: this implementation uses a busy loop to poll the value, +/// which is not as efficient as registering a dedicated `Waker`. +/// However, if the usecase for it is to initialize a static variable +/// relatively early in the program life cycle, it should be fine. +/// +/// # Example +/// ``` +/// use futures_executor::block_on; +/// use embassy_sync::once_lock::OnceLock; +/// +/// // Define a static value that will be lazily initialized +/// static VALUE: OnceLock = OnceLock::new(); +/// +/// let f = async { +/// +/// // Initialize the value +/// let reference = VALUE.get_or_init(|| 20); +/// assert_eq!(reference, &20); +/// +/// // Wait for the value to be initialized +/// // and get a static reference it +/// assert_eq!(VALUE.get().await, &20); +/// +/// }; +/// block_on(f) +/// ``` +pub struct OnceLock { + init: AtomicBool, + data: Cell>, +} + +unsafe impl Sync for OnceLock {} + +impl OnceLock { + /// Create a new uninitialized `OnceLock`. + pub const fn new() -> Self { + Self { + init: AtomicBool::new(false), + data: Cell::new(MaybeUninit::zeroed()), + } + } + + /// Get a reference to the underlying value, waiting for it to be set. + /// If the value is already set, this will return immediately. + pub async fn get(&self) -> &T { + poll_fn(|cx| match self.try_get() { + Some(data) => Poll::Ready(data), + None => { + cx.waker().wake_by_ref(); + Poll::Pending + } + }) + .await + } + + /// Try to get a reference to the underlying value if it exists. + pub fn try_get(&self) -> Option<&T> { + if self.init.load(Ordering::Relaxed) { + Some(unsafe { self.get_ref_unchecked() }) + } else { + None + } + } + + /// Set the underlying value. If the value is already set, this will return an error with the given value. + pub fn init(&self, value: T) -> Result<(), T> { + // Critical section is required to ensure that the value is + // not simultaneously initialized elsewhere at the same time. + critical_section::with(|_| { + // If the value is not set, set it and return Ok. + if !self.init.load(Ordering::Relaxed) { + self.data.set(MaybeUninit::new(value)); + self.init.store(true, Ordering::Relaxed); + Ok(()) + + // Otherwise return an error with the given value. + } else { + Err(value) + } + }) + } + + /// Get a reference to the underlying value, initializing it if it does not exist. + pub fn get_or_init(&self, f: F) -> &T + where + F: FnOnce() -> T, + { + // Critical section is required to ensure that the value is + // not simultaneously initialized elsewhere at the same time. + critical_section::with(|_| { + // If the value is not set, set it. + if !self.init.load(Ordering::Relaxed) { + self.data.set(MaybeUninit::new(f())); + self.init.store(true, Ordering::Relaxed); + } + }); + + // Return a reference to the value. + unsafe { self.get_ref_unchecked() } + } + + /// Consume the `OnceLock`, returning the underlying value if it was initialized. + pub fn into_inner(self) -> Option { + if self.init.load(Ordering::Relaxed) { + Some(unsafe { self.data.into_inner().assume_init() }) + } else { + None + } + } + + /// Take the underlying value if it was initialized, uninitializing the `OnceLock` in the process. + pub fn take(&mut self) -> Option { + // If the value is set, uninitialize the lock and return the value. + critical_section::with(|_| { + if self.init.load(Ordering::Relaxed) { + let val = unsafe { self.data.replace(MaybeUninit::zeroed()).assume_init() }; + self.init.store(false, Ordering::Relaxed); + Some(val) + + // Otherwise return None. + } else { + None + } + }) + } + + /// Check if the value has been set. + pub fn is_set(&self) -> bool { + self.init.load(Ordering::Relaxed) + } + + /// Get a reference to the underlying value. + /// # Safety + /// Must only be used if a value has been set. + unsafe fn get_ref_unchecked(&self) -> &T { + (*self.data.as_ptr()).assume_init_ref() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn once_lock() { + let lock = OnceLock::new(); + assert_eq!(lock.try_get(), None); + assert_eq!(lock.is_set(), false); + + let v = 42; + assert_eq!(lock.init(v), Ok(())); + assert_eq!(lock.is_set(), true); + assert_eq!(lock.try_get(), Some(&v)); + assert_eq!(lock.try_get(), Some(&v)); + + let v = 43; + assert_eq!(lock.init(v), Err(v)); + assert_eq!(lock.is_set(), true); + assert_eq!(lock.try_get(), Some(&42)); + } + + #[test] + fn once_lock_get_or_init() { + let lock = OnceLock::new(); + assert_eq!(lock.try_get(), None); + assert_eq!(lock.is_set(), false); + + let v = lock.get_or_init(|| 42); + assert_eq!(v, &42); + assert_eq!(lock.is_set(), true); + assert_eq!(lock.try_get(), Some(&42)); + + let v = lock.get_or_init(|| 43); + assert_eq!(v, &42); + assert_eq!(lock.is_set(), true); + assert_eq!(lock.try_get(), Some(&42)); + } + + #[test] + fn once_lock_static() { + static LOCK: OnceLock = OnceLock::new(); + + let v: &'static i32 = LOCK.get_or_init(|| 42); + assert_eq!(v, &42); + + let v: &'static i32 = LOCK.get_or_init(|| 43); + assert_eq!(v, &42); + } + + #[futures_test::test] + async fn once_lock_async() { + static LOCK: OnceLock = OnceLock::new(); + + assert!(LOCK.init(42).is_ok()); + + let v: &'static i32 = LOCK.get().await; + assert_eq!(v, &42); + } + + #[test] + fn once_lock_into_inner() { + let lock: OnceLock = OnceLock::new(); + + let v = lock.get_or_init(|| 42); + assert_eq!(v, &42); + + assert_eq!(lock.into_inner(), Some(42)); + } + + #[test] + fn once_lock_take_init() { + let mut lock: OnceLock = OnceLock::new(); + + assert_eq!(lock.get_or_init(|| 42), &42); + assert_eq!(lock.is_set(), true); + + assert_eq!(lock.take(), Some(42)); + assert_eq!(lock.is_set(), false); + + assert_eq!(lock.get_or_init(|| 43), &43); + assert_eq!(lock.is_set(), true); + } +} diff --git a/embassy-sync/src/pipe.rs b/embassy-sync/src/pipe.rs index 42fe8ebd0..cd5b8ed75 100644 --- a/embassy-sync/src/pipe.rs +++ b/embassy-sync/src/pipe.rs @@ -25,7 +25,7 @@ where M: RawMutex, { fn clone(&self) -> Self { - Writer { pipe: self.pipe } + *self } } diff --git a/embassy-sync/src/priority_channel.rs b/embassy-sync/src/priority_channel.rs index bd75c0135..1f4d8667c 100644 --- a/embassy-sync/src/priority_channel.rs +++ b/embassy-sync/src/priority_channel.rs @@ -33,7 +33,7 @@ where M: RawMutex, { fn clone(&self) -> Self { - Sender { channel: self.channel } + *self } } @@ -71,6 +71,48 @@ where pub fn poll_ready_to_send(&self, cx: &mut Context<'_>) -> Poll<()> { self.channel.poll_ready_to_send(cx) } + + /// Returns the maximum number of elements the channel can hold. + /// + /// See [`PriorityChannel::capacity()`] + pub const fn capacity(&self) -> usize { + self.channel.capacity() + } + + /// Returns the free capacity of the channel. + /// + /// See [`PriorityChannel::free_capacity()`] + pub fn free_capacity(&self) -> usize { + self.channel.free_capacity() + } + + /// Clears all elements in the channel. + /// + /// See [`PriorityChannel::clear()`] + pub fn clear(&self) { + self.channel.clear(); + } + + /// Returns the number of elements currently in the channel. + /// + /// See [`PriorityChannel::len()`] + pub fn len(&self) -> usize { + self.channel.len() + } + + /// Returns whether the channel is empty. + /// + /// See [`PriorityChannel::is_empty()`] + pub fn is_empty(&self) -> bool { + self.channel.is_empty() + } + + /// Returns whether the channel is full. + /// + /// See [`PriorityChannel::is_full()`] + pub fn is_full(&self) -> bool { + self.channel.is_full() + } } impl<'ch, M, T, K, const N: usize> From> for DynamicSender<'ch, T> @@ -101,7 +143,7 @@ where M: RawMutex, { fn clone(&self) -> Self { - Receiver { channel: self.channel } + *self } } @@ -146,6 +188,48 @@ where pub fn poll_receive(&self, cx: &mut Context<'_>) -> Poll { self.channel.poll_receive(cx) } + + /// Returns the maximum number of elements the channel can hold. + /// + /// See [`PriorityChannel::capacity()`] + pub const fn capacity(&self) -> usize { + self.channel.capacity() + } + + /// Returns the free capacity of the channel. + /// + /// See [`PriorityChannel::free_capacity()`] + pub fn free_capacity(&self) -> usize { + self.channel.free_capacity() + } + + /// Clears all elements in the channel. + /// + /// See [`PriorityChannel::clear()`] + pub fn clear(&self) { + self.channel.clear(); + } + + /// Returns the number of elements currently in the channel. + /// + /// See [`PriorityChannel::len()`] + pub fn len(&self) -> usize { + self.channel.len() + } + + /// Returns whether the channel is empty. + /// + /// See [`PriorityChannel::is_empty()`] + pub fn is_empty(&self) -> bool { + self.channel.is_empty() + } + + /// Returns whether the channel is full. + /// + /// See [`PriorityChannel::is_full()`] + pub fn is_full(&self) -> bool { + self.channel.is_full() + } } impl<'ch, M, T, K, const N: usize> From> for DynamicReceiver<'ch, T> @@ -314,6 +398,22 @@ where Poll::Pending } } + + fn clear(&mut self) { + self.queue.clear(); + } + + fn len(&self) -> usize { + self.queue.len() + } + + fn is_empty(&self) -> bool { + self.queue.is_empty() + } + + fn is_full(&self) -> bool { + self.queue.len() == self.queue.capacity() + } } /// A bounded channel for communicating between asynchronous tasks @@ -323,9 +423,9 @@ where /// buffer is full, attempts to `send` new messages will wait until a message is /// received from the channel. /// -/// Sent data may be reordered based on their priorty within the channel. +/// Sent data may be reordered based on their priority within the channel. /// For example, in a [`Max`](heapless::binary_heap::Max) [`PriorityChannel`] -/// containing `u32`'s, data sent in the following order `[1, 2, 3]` will be recieved as `[3, 2, 1]`. +/// containing `u32`'s, data sent in the following order `[1, 2, 3]` will be received as `[3, 2, 1]`. pub struct PriorityChannel where T: Ord, @@ -433,6 +533,38 @@ where pub fn try_receive(&self) -> Result { self.lock(|c| c.try_receive()) } + + /// Returns the maximum number of elements the channel can hold. + pub const fn capacity(&self) -> usize { + N + } + + /// Returns the free capacity of the channel. + /// + /// This is equivalent to `capacity() - len()` + pub fn free_capacity(&self) -> usize { + N - self.len() + } + + /// Clears all elements in the channel. + pub fn clear(&self) { + self.lock(|c| c.clear()); + } + + /// Returns the number of elements currently in the channel. + pub fn len(&self) -> usize { + self.lock(|c| c.len()) + } + + /// Returns whether the channel is empty. + pub fn is_empty(&self) -> bool { + self.lock(|c| c.is_empty()) + } + + /// Returns whether the channel is full. + pub fn is_full(&self) -> bool { + self.lock(|c| c.is_full()) + } } /// Implements the DynamicChannel to allow creating types that are unaware of the queue size with the diff --git a/embassy-sync/src/pubsub/mod.rs b/embassy-sync/src/pubsub/mod.rs index 6afd54af5..a2360a1d8 100644 --- a/embassy-sync/src/pubsub/mod.rs +++ b/embassy-sync/src/pubsub/mod.rs @@ -27,8 +27,8 @@ pub use subscriber::{DynSubscriber, Subscriber}; /// /// - With [Pub::publish()] the publisher has to wait until there is space in the internal message queue. /// - With [Pub::publish_immediate()] the publisher doesn't await and instead lets the oldest message -/// in the queue drop if necessary. This will cause any [Subscriber] that missed the message to receive -/// an error to indicate that it has lagged. +/// in the queue drop if necessary. This will cause any [Subscriber] that missed the message to receive +/// an error to indicate that it has lagged. /// /// ## Example /// @@ -160,9 +160,60 @@ impl DynImmediatePublisher { DynImmediatePublisher(ImmediatePub::new(self)) } + + /// Returns the maximum number of elements the channel can hold. + pub const fn capacity(&self) -> usize { + CAP + } + + /// Returns the free capacity of the channel. + /// + /// This is equivalent to `capacity() - len()` + pub fn free_capacity(&self) -> usize { + CAP - self.len() + } + + /// Clears all elements in the channel. + pub fn clear(&self) { + self.inner.lock(|inner| inner.borrow_mut().clear()); + } + + /// Returns the number of elements currently in the channel. + pub fn len(&self) -> usize { + self.inner.lock(|inner| inner.borrow().len()) + } + + /// Returns whether the channel is empty. + pub fn is_empty(&self) -> bool { + self.inner.lock(|inner| inner.borrow().is_empty()) + } + + /// Returns whether the channel is full. + pub fn is_full(&self) -> bool { + self.inner.lock(|inner| inner.borrow().is_full()) + } } -impl PubSubBehavior +impl crate::pubsub::PubSubBehavior + for PubSubChannel +{ + fn publish_immediate(&self, message: T) { + self.inner.lock(|s| { + let mut s = s.borrow_mut(); + s.publish_immediate(message) + }) + } + + fn capacity(&self) -> usize { + self.capacity() + } + + fn is_full(&self) -> bool { + self.is_full() + } +} + +impl SealedPubSubBehavior for PubSubChannel { fn get_message_with_context(&self, next_message_id: &mut u64, cx: Option<&mut Context<'_>>) -> Poll> { @@ -214,20 +265,6 @@ impl usize { - self.inner.lock(|s| { - let s = s.borrow(); - s.queue.capacity() - s.queue.len() - }) - } - fn unregister_subscriber(&self, subscriber_next_message_id: u64) { self.inner.lock(|s| { let mut s = s.borrow_mut(); @@ -241,6 +278,22 @@ impl usize { + self.free_capacity() + } + + fn clear(&self) { + self.clear(); + } + + fn len(&self) -> usize { + self.len() + } + + fn is_empty(&self) -> bool { + self.is_empty() + } } /// Internal state for the PubSub channel @@ -366,10 +419,26 @@ impl PubSubSta fn unregister_publisher(&mut self) { self.publisher_count -= 1; } + + fn clear(&mut self) { + self.queue.clear(); + } + + fn len(&self) -> usize { + self.queue.len() + } + + fn is_empty(&self) -> bool { + self.queue.is_empty() + } + + fn is_full(&self) -> bool { + self.queue.is_full() + } } /// Error type for the [PubSubChannel] -#[derive(Debug, PartialEq, Eq, Clone)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Error { /// All subscriber slots are used. To add another subscriber, first another subscriber must be dropped or @@ -380,12 +449,10 @@ pub enum Error { MaximumPublishersReached, } -/// 'Middle level' behaviour of the pubsub channel. -/// This trait is used so that Sub and Pub can be generic over the channel. -pub trait PubSubBehavior { +trait SealedPubSubBehavior { /// Try to get a message from the queue with the given message id. /// - /// If the message is not yet present and a context is given, then its waker is registered in the subsriber wakers. + /// If the message is not yet present and a context is given, then its waker is registered in the subscriber wakers. fn get_message_with_context(&self, next_message_id: &mut u64, cx: Option<&mut Context<'_>>) -> Poll>; /// Get the amount of messages that are between the given the next_message_id and the most recent message. @@ -397,11 +464,19 @@ pub trait PubSubBehavior { /// If the queue is full and a context is given, then its waker is registered in the publisher wakers. fn publish_with_context(&self, message: T, cx: Option<&mut Context<'_>>) -> Result<(), T>; - /// Publish a message immediately - fn publish_immediate(&self, message: T); + /// Returns the free capacity of the channel. + /// + /// This is equivalent to `capacity() - len()` + fn free_capacity(&self) -> usize; - /// The amount of messages that can still be published without having to wait or without having to lag the subscribers - fn space(&self) -> usize; + /// Clears all elements in the channel. + fn clear(&self); + + /// Returns the number of elements currently in the channel. + fn len(&self) -> usize; + + /// Returns whether the channel is empty. + fn is_empty(&self) -> bool; /// Let the channel know that a subscriber has dropped fn unregister_subscriber(&self, subscriber_next_message_id: u64); @@ -410,6 +485,20 @@ pub trait PubSubBehavior { fn unregister_publisher(&self); } +/// 'Middle level' behaviour of the pubsub channel. +/// This trait is used so that Sub and Pub can be generic over the channel. +#[allow(private_bounds)] +pub trait PubSubBehavior: SealedPubSubBehavior { + /// Publish a message immediately + fn publish_immediate(&self, message: T); + + /// Returns the maximum number of elements the channel can hold. + fn capacity(&self) -> usize; + + /// Returns whether the channel is full. + fn is_full(&self) -> bool; +} + /// The result of the subscriber wait procedure #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -542,6 +631,7 @@ mod tests { assert_eq!(pub0.try_publish(0), Ok(())); assert_eq!(pub0.try_publish(0), Ok(())); assert_eq!(pub0.try_publish(0), Ok(())); + assert!(pub0.is_full()); assert_eq!(pub0.try_publish(0), Err(0)); drop(sub0); @@ -574,32 +664,42 @@ mod tests { } #[futures_test::test] - async fn correct_space() { + async fn correct_len() { let channel = PubSubChannel::::new(); let mut sub0 = channel.subscriber().unwrap(); let mut sub1 = channel.subscriber().unwrap(); let pub0 = channel.publisher().unwrap(); - assert_eq!(pub0.space(), 4); + assert!(sub0.is_empty()); + assert!(sub1.is_empty()); + assert!(pub0.is_empty()); + assert_eq!(pub0.free_capacity(), 4); + assert_eq!(pub0.len(), 0); pub0.publish(42).await; - assert_eq!(pub0.space(), 3); + assert_eq!(pub0.free_capacity(), 3); + assert_eq!(pub0.len(), 1); pub0.publish(42).await; - assert_eq!(pub0.space(), 2); + assert_eq!(pub0.free_capacity(), 2); + assert_eq!(pub0.len(), 2); sub0.next_message().await; sub0.next_message().await; - assert_eq!(pub0.space(), 2); + assert_eq!(pub0.free_capacity(), 2); + assert_eq!(pub0.len(), 2); sub1.next_message().await; - assert_eq!(pub0.space(), 3); + assert_eq!(pub0.free_capacity(), 3); + assert_eq!(pub0.len(), 1); + sub1.next_message().await; - assert_eq!(pub0.space(), 4); + assert_eq!(pub0.free_capacity(), 4); + assert_eq!(pub0.len(), 0); } #[futures_test::test] @@ -610,29 +710,29 @@ mod tests { let mut sub0 = channel.subscriber().unwrap(); let mut sub1 = channel.subscriber().unwrap(); - assert_eq!(4, pub0.space()); + assert_eq!(4, pub0.free_capacity()); pub0.publish(1).await; pub0.publish(2).await; - assert_eq!(2, channel.space()); + assert_eq!(2, channel.free_capacity()); assert_eq!(1, sub0.try_next_message_pure().unwrap()); assert_eq!(2, sub0.try_next_message_pure().unwrap()); - assert_eq!(2, channel.space()); + assert_eq!(2, channel.free_capacity()); drop(sub0); - assert_eq!(2, channel.space()); + assert_eq!(2, channel.free_capacity()); assert_eq!(1, sub1.try_next_message_pure().unwrap()); - assert_eq!(3, channel.space()); + assert_eq!(3, channel.free_capacity()); drop(sub1); - assert_eq!(4, channel.space()); + assert_eq!(4, channel.free_capacity()); } struct CloneCallCounter(usize); @@ -655,4 +755,30 @@ mod tests { assert_eq!(1, sub0.try_next_message_pure().unwrap().0); assert_eq!(0, sub1.try_next_message_pure().unwrap().0); } + + #[futures_test::test] + async fn publisher_sink() { + use futures_util::{SinkExt, StreamExt}; + + let channel = PubSubChannel::::new(); + + let mut sub = channel.subscriber().unwrap(); + + let publ = channel.publisher().unwrap(); + let mut sink = publ.sink(); + + sink.send(0).await.unwrap(); + assert_eq!(0, sub.try_next_message_pure().unwrap()); + + sink.send(1).await.unwrap(); + assert_eq!(1, sub.try_next_message_pure().unwrap()); + + sink.send_all(&mut futures_util::stream::iter(0..4).map(Ok)) + .await + .unwrap(); + assert_eq!(0, sub.try_next_message_pure().unwrap()); + assert_eq!(1, sub.try_next_message_pure().unwrap()); + assert_eq!(2, sub.try_next_message_pure().unwrap()); + assert_eq!(3, sub.try_next_message_pure().unwrap()); + } } diff --git a/embassy-sync/src/pubsub/publisher.rs b/embassy-sync/src/pubsub/publisher.rs index e1edc9eb9..7a1ab66de 100644 --- a/embassy-sync/src/pubsub/publisher.rs +++ b/embassy-sync/src/pubsub/publisher.rs @@ -43,12 +43,42 @@ impl<'a, PSB: PubSubBehavior + ?Sized, T: Clone> Pub<'a, PSB, T> { self.channel.publish_with_context(message, None) } - /// The amount of messages that can still be published without having to wait or without having to lag the subscribers + /// Returns the maximum number of elements the ***channel*** can hold. + pub fn capacity(&self) -> usize { + self.channel.capacity() + } + + /// Returns the free capacity of the ***channel***. /// - /// *Note: In the time between checking this and a publish action, other publishers may have had time to publish something. - /// So checking doesn't give any guarantees.* - pub fn space(&self) -> usize { - self.channel.space() + /// This is equivalent to `capacity() - len()` + pub fn free_capacity(&self) -> usize { + self.channel.free_capacity() + } + + /// Clears all elements in the ***channel***. + pub fn clear(&self) { + self.channel.clear(); + } + + /// Returns the number of elements currently in the ***channel***. + pub fn len(&self) -> usize { + self.channel.len() + } + + /// Returns whether the ***channel*** is empty. + pub fn is_empty(&self) -> bool { + self.channel.is_empty() + } + + /// Returns whether the ***channel*** is full. + pub fn is_full(&self) -> bool { + self.channel.is_full() + } + + /// Create a [`futures::Sink`] adapter for this publisher. + #[inline] + pub const fn sink(&self) -> PubSink<'a, '_, PSB, T> { + PubSink { publ: self, fut: None } } } @@ -124,12 +154,36 @@ impl<'a, PSB: PubSubBehavior + ?Sized, T: Clone> ImmediatePub<'a, PSB, T> { self.channel.publish_with_context(message, None) } - /// The amount of messages that can still be published without having to wait or without having to lag the subscribers + /// Returns the maximum number of elements the ***channel*** can hold. + pub fn capacity(&self) -> usize { + self.channel.capacity() + } + + /// Returns the free capacity of the ***channel***. /// - /// *Note: In the time between checking this and a publish action, other publishers may have had time to publish something. - /// So checking doesn't give any guarantees.* - pub fn space(&self) -> usize { - self.channel.space() + /// This is equivalent to `capacity() - len()` + pub fn free_capacity(&self) -> usize { + self.channel.free_capacity() + } + + /// Clears all elements in the ***channel***. + pub fn clear(&self) { + self.channel.clear(); + } + + /// Returns the number of elements currently in the ***channel***. + pub fn len(&self) -> usize { + self.channel.len() + } + + /// Returns whether the ***channel*** is empty. + pub fn is_empty(&self) -> bool { + self.channel.is_empty() + } + + /// Returns whether the ***channel*** is full. + pub fn is_full(&self) -> bool { + self.channel.is_full() } } @@ -173,6 +227,67 @@ impl<'a, M: RawMutex, T: Clone, const CAP: usize, const SUBS: usize, const PUBS: } } +#[must_use = "Sinks do nothing unless polled"] +/// [`futures_sink::Sink`] adapter for [`Pub`]. +pub struct PubSink<'a, 'p, PSB, T> +where + T: Clone, + PSB: PubSubBehavior + ?Sized, +{ + publ: &'p Pub<'a, PSB, T>, + fut: Option>, +} + +impl<'a, 'p, PSB, T> PubSink<'a, 'p, PSB, T> +where + PSB: PubSubBehavior + ?Sized, + T: Clone, +{ + /// Try to make progress on the pending future if we have one. + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { + let Some(mut fut) = self.fut.take() else { + return Poll::Ready(()); + }; + + if Pin::new(&mut fut).poll(cx).is_pending() { + self.fut = Some(fut); + return Poll::Pending; + } + + Poll::Ready(()) + } +} + +impl<'a, 'p, PSB, T> futures_sink::Sink for PubSink<'a, 'p, PSB, T> +where + PSB: PubSubBehavior + ?Sized, + T: Clone, +{ + type Error = core::convert::Infallible; + + #[inline] + fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.poll(cx).map(Ok) + } + + #[inline] + fn start_send(mut self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> { + self.fut = Some(self.publ.publish(item)); + + Ok(()) + } + + #[inline] + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.poll(cx).map(Ok) + } + + #[inline] + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.poll(cx).map(Ok) + } +} + /// Future for the publisher wait action #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct PublisherWaitFuture<'s, 'a, PSB: PubSubBehavior + ?Sized, T: Clone> { diff --git a/embassy-sync/src/pubsub/subscriber.rs b/embassy-sync/src/pubsub/subscriber.rs index f420a75f0..6ad660cb3 100644 --- a/embassy-sync/src/pubsub/subscriber.rs +++ b/embassy-sync/src/pubsub/subscriber.rs @@ -65,10 +65,44 @@ impl<'a, PSB: PubSubBehavior + ?Sized, T: Clone> Sub<'a, PSB, T> { } } - /// The amount of messages this subscriber hasn't received yet + /// The amount of messages this subscriber hasn't received yet. This is like [Self::len] but specifically + /// for this subscriber. pub fn available(&self) -> u64 { self.channel.available(self.next_message_id) } + + /// Returns the maximum number of elements the ***channel*** can hold. + pub fn capacity(&self) -> usize { + self.channel.capacity() + } + + /// Returns the free capacity of the ***channel***. + /// + /// This is equivalent to `capacity() - len()` + pub fn free_capacity(&self) -> usize { + self.channel.free_capacity() + } + + /// Clears all elements in the ***channel***. + pub fn clear(&self) { + self.channel.clear(); + } + + /// Returns the number of elements currently in the ***channel***. + /// See [Self::available] for how many messages are available for this subscriber. + pub fn len(&self) -> usize { + self.channel.len() + } + + /// Returns whether the ***channel*** is empty. + pub fn is_empty(&self) -> bool { + self.channel.is_empty() + } + + /// Returns whether the ***channel*** is full. + pub fn is_full(&self) -> bool { + self.channel.is_full() + } } impl<'a, PSB: PubSubBehavior + ?Sized, T: Clone> Drop for Sub<'a, PSB, T> { diff --git a/embassy-sync/src/semaphore.rs b/embassy-sync/src/semaphore.rs new file mode 100644 index 000000000..d30eee30b --- /dev/null +++ b/embassy-sync/src/semaphore.rs @@ -0,0 +1,772 @@ +//! A synchronization primitive for controlling access to a pool of resources. +use core::cell::{Cell, RefCell}; +use core::convert::Infallible; +use core::future::{poll_fn, Future}; +use core::task::{Poll, Waker}; + +use heapless::Deque; + +use crate::blocking_mutex::raw::RawMutex; +use crate::blocking_mutex::Mutex; +use crate::waitqueue::WakerRegistration; + +/// An asynchronous semaphore. +/// +/// A semaphore tracks a number of permits, typically representing a pool of shared resources. +/// Users can acquire permits to synchronize access to those resources. The semaphore does not +/// contain the resources themselves, only the count of available permits. +pub trait Semaphore: Sized { + /// The error returned when the semaphore is unable to acquire the requested permits. + type Error; + + /// Asynchronously acquire one or more permits from the semaphore. + async fn acquire(&self, permits: usize) -> Result, Self::Error>; + + /// Try to immediately acquire one or more permits from the semaphore. + fn try_acquire(&self, permits: usize) -> Option>; + + /// Asynchronously acquire all permits controlled by the semaphore. + /// + /// This method will wait until at least `min` permits are available, then acquire all available permits + /// from the semaphore. Note that other tasks may have already acquired some permits which could be released + /// back to the semaphore at any time. The number of permits actually acquired may be determined by calling + /// [`SemaphoreReleaser::permits`]. + async fn acquire_all(&self, min: usize) -> Result, Self::Error>; + + /// Try to immediately acquire all available permits from the semaphore, if at least `min` permits are available. + fn try_acquire_all(&self, min: usize) -> Option>; + + /// Release `permits` back to the semaphore, making them available to be acquired. + fn release(&self, permits: usize); + + /// Reset the number of available permints in the semaphore to `permits`. + fn set(&self, permits: usize); +} + +/// A representation of a number of acquired permits. +/// +/// The acquired permits will be released back to the [`Semaphore`] when this is dropped. +pub struct SemaphoreReleaser<'a, S: Semaphore> { + semaphore: &'a S, + permits: usize, +} + +impl<'a, S: Semaphore> Drop for SemaphoreReleaser<'a, S> { + fn drop(&mut self) { + self.semaphore.release(self.permits); + } +} + +impl<'a, S: Semaphore> SemaphoreReleaser<'a, S> { + /// The number of acquired permits. + pub fn permits(&self) -> usize { + self.permits + } + + /// Prevent the acquired permits from being released on drop. + /// + /// Returns the number of acquired permits. + pub fn disarm(self) -> usize { + let permits = self.permits; + core::mem::forget(self); + permits + } +} + +/// A greedy [`Semaphore`] implementation. +/// +/// Tasks can acquire permits as soon as they become available, even if another task +/// is waiting on a larger number of permits. +pub struct GreedySemaphore { + state: Mutex>, +} + +impl Default for GreedySemaphore { + fn default() -> Self { + Self::new(0) + } +} + +impl GreedySemaphore { + /// Create a new `Semaphore`. + pub const fn new(permits: usize) -> Self { + Self { + state: Mutex::new(Cell::new(SemaphoreState { + permits, + waker: WakerRegistration::new(), + })), + } + } + + #[cfg(test)] + fn permits(&self) -> usize { + self.state.lock(|cell| { + let state = cell.replace(SemaphoreState::EMPTY); + let permits = state.permits; + cell.replace(state); + permits + }) + } + + fn poll_acquire( + &self, + permits: usize, + acquire_all: bool, + waker: Option<&Waker>, + ) -> Poll, Infallible>> { + self.state.lock(|cell| { + let mut state = cell.replace(SemaphoreState::EMPTY); + if let Some(permits) = state.take(permits, acquire_all) { + cell.set(state); + Poll::Ready(Ok(SemaphoreReleaser { + semaphore: self, + permits, + })) + } else { + if let Some(waker) = waker { + state.register(waker); + } + cell.set(state); + Poll::Pending + } + }) + } +} + +impl Semaphore for GreedySemaphore { + type Error = Infallible; + + async fn acquire(&self, permits: usize) -> Result, Self::Error> { + poll_fn(|cx| self.poll_acquire(permits, false, Some(cx.waker()))).await + } + + fn try_acquire(&self, permits: usize) -> Option> { + match self.poll_acquire(permits, false, None) { + Poll::Ready(Ok(n)) => Some(n), + _ => None, + } + } + + async fn acquire_all(&self, min: usize) -> Result, Self::Error> { + poll_fn(|cx| self.poll_acquire(min, true, Some(cx.waker()))).await + } + + fn try_acquire_all(&self, min: usize) -> Option> { + match self.poll_acquire(min, true, None) { + Poll::Ready(Ok(n)) => Some(n), + _ => None, + } + } + + fn release(&self, permits: usize) { + if permits > 0 { + self.state.lock(|cell| { + let mut state = cell.replace(SemaphoreState::EMPTY); + state.permits += permits; + state.wake(); + cell.set(state); + }); + } + } + + fn set(&self, permits: usize) { + self.state.lock(|cell| { + let mut state = cell.replace(SemaphoreState::EMPTY); + if permits > state.permits { + state.wake(); + } + state.permits = permits; + cell.set(state); + }); + } +} + +struct SemaphoreState { + permits: usize, + waker: WakerRegistration, +} + +impl SemaphoreState { + const EMPTY: SemaphoreState = SemaphoreState { + permits: 0, + waker: WakerRegistration::new(), + }; + + fn register(&mut self, w: &Waker) { + self.waker.register(w); + } + + fn take(&mut self, mut permits: usize, acquire_all: bool) -> Option { + if self.permits < permits { + None + } else { + if acquire_all { + permits = self.permits; + } + self.permits -= permits; + Some(permits) + } + } + + fn wake(&mut self) { + self.waker.wake(); + } +} + +/// A fair [`Semaphore`] implementation. +/// +/// Tasks are allowed to acquire permits in FIFO order. A task waiting to acquire +/// a large number of permits will prevent other tasks from acquiring any permits +/// until its request is satisfied. +/// +/// Up to `N` tasks may attempt to acquire permits concurrently. If additional +/// tasks attempt to acquire a permit, a [`WaitQueueFull`] error will be returned. +pub struct FairSemaphore +where + M: RawMutex, +{ + state: Mutex>>, +} + +impl Default for FairSemaphore +where + M: RawMutex, +{ + fn default() -> Self { + Self::new(0) + } +} + +impl FairSemaphore +where + M: RawMutex, +{ + /// Create a new `FairSemaphore`. + pub const fn new(permits: usize) -> Self { + Self { + state: Mutex::new(RefCell::new(FairSemaphoreState::new(permits))), + } + } + + #[cfg(test)] + fn permits(&self) -> usize { + self.state.lock(|cell| cell.borrow().permits) + } + + fn poll_acquire( + &self, + permits: usize, + acquire_all: bool, + cx: Option<(&mut Option, &Waker)>, + ) -> Poll, WaitQueueFull>> { + let ticket = cx.as_ref().map(|(x, _)| **x).unwrap_or(None); + self.state.lock(|cell| { + let mut state = cell.borrow_mut(); + if let Some(permits) = state.take(ticket, permits, acquire_all) { + Poll::Ready(Ok(SemaphoreReleaser { + semaphore: self, + permits, + })) + } else if let Some((ticket_ref, waker)) = cx { + match state.register(ticket, waker) { + Ok(ticket) => { + *ticket_ref = Some(ticket); + Poll::Pending + } + Err(err) => Poll::Ready(Err(err)), + } + } else { + Poll::Pending + } + }) + } +} + +/// An error indicating the [`FairSemaphore`]'s wait queue is full. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct WaitQueueFull; + +impl Semaphore for FairSemaphore { + type Error = WaitQueueFull; + + fn acquire(&self, permits: usize) -> impl Future, Self::Error>> { + FairAcquire { + sema: self, + permits, + ticket: None, + } + } + + fn try_acquire(&self, permits: usize) -> Option> { + match self.poll_acquire(permits, false, None) { + Poll::Ready(Ok(x)) => Some(x), + _ => None, + } + } + + fn acquire_all(&self, min: usize) -> impl Future, Self::Error>> { + FairAcquireAll { + sema: self, + min, + ticket: None, + } + } + + fn try_acquire_all(&self, min: usize) -> Option> { + match self.poll_acquire(min, true, None) { + Poll::Ready(Ok(x)) => Some(x), + _ => None, + } + } + + fn release(&self, permits: usize) { + if permits > 0 { + self.state.lock(|cell| { + let mut state = cell.borrow_mut(); + state.permits += permits; + state.wake(); + }); + } + } + + fn set(&self, permits: usize) { + self.state.lock(|cell| { + let mut state = cell.borrow_mut(); + if permits > state.permits { + state.wake(); + } + state.permits = permits; + }); + } +} + +struct FairAcquire<'a, M: RawMutex, const N: usize> { + sema: &'a FairSemaphore, + permits: usize, + ticket: Option, +} + +impl<'a, M: RawMutex, const N: usize> Drop for FairAcquire<'a, M, N> { + fn drop(&mut self) { + self.sema + .state + .lock(|cell| cell.borrow_mut().cancel(self.ticket.take())); + } +} + +impl<'a, M: RawMutex, const N: usize> core::future::Future for FairAcquire<'a, M, N> { + type Output = Result>, WaitQueueFull>; + + fn poll(mut self: core::pin::Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll { + self.sema + .poll_acquire(self.permits, false, Some((&mut self.ticket, cx.waker()))) + } +} + +struct FairAcquireAll<'a, M: RawMutex, const N: usize> { + sema: &'a FairSemaphore, + min: usize, + ticket: Option, +} + +impl<'a, M: RawMutex, const N: usize> Drop for FairAcquireAll<'a, M, N> { + fn drop(&mut self) { + self.sema + .state + .lock(|cell| cell.borrow_mut().cancel(self.ticket.take())); + } +} + +impl<'a, M: RawMutex, const N: usize> core::future::Future for FairAcquireAll<'a, M, N> { + type Output = Result>, WaitQueueFull>; + + fn poll(mut self: core::pin::Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll { + self.sema + .poll_acquire(self.min, true, Some((&mut self.ticket, cx.waker()))) + } +} + +struct FairSemaphoreState { + permits: usize, + next_ticket: usize, + wakers: Deque, N>, +} + +impl FairSemaphoreState { + /// Create a new empty instance + const fn new(permits: usize) -> Self { + Self { + permits, + next_ticket: 0, + wakers: Deque::new(), + } + } + + /// Register a waker. If the queue is full the function returns an error + fn register(&mut self, ticket: Option, w: &Waker) -> Result { + self.pop_canceled(); + + match ticket { + None => { + let ticket = self.next_ticket.wrapping_add(self.wakers.len()); + self.wakers.push_back(Some(w.clone())).or(Err(WaitQueueFull))?; + Ok(ticket) + } + Some(ticket) => { + self.set_waker(ticket, Some(w.clone())); + Ok(ticket) + } + } + } + + fn cancel(&mut self, ticket: Option) { + if let Some(ticket) = ticket { + self.set_waker(ticket, None); + } + } + + fn set_waker(&mut self, ticket: usize, waker: Option) { + let i = ticket.wrapping_sub(self.next_ticket); + if i < self.wakers.len() { + let (a, b) = self.wakers.as_mut_slices(); + let x = if i < a.len() { &mut a[i] } else { &mut b[i - a.len()] }; + *x = waker; + } + } + + fn take(&mut self, ticket: Option, mut permits: usize, acquire_all: bool) -> Option { + self.pop_canceled(); + + if permits > self.permits { + return None; + } + + match ticket { + Some(n) if n != self.next_ticket => return None, + None if !self.wakers.is_empty() => return None, + _ => (), + } + + if acquire_all { + permits = self.permits; + } + self.permits -= permits; + + if ticket.is_some() { + self.pop(); + if self.permits > 0 { + self.wake(); + } + } + + Some(permits) + } + + fn pop_canceled(&mut self) { + while let Some(None) = self.wakers.front() { + self.pop(); + } + } + + /// Panics if `self.wakers` is empty + fn pop(&mut self) { + self.wakers.pop_front().unwrap(); + self.next_ticket = self.next_ticket.wrapping_add(1); + } + + fn wake(&mut self) { + self.pop_canceled(); + + if let Some(Some(waker)) = self.wakers.front() { + waker.wake_by_ref(); + } + } +} + +#[cfg(test)] +mod tests { + mod greedy { + use core::pin::pin; + + use futures_util::poll; + + use super::super::*; + use crate::blocking_mutex::raw::NoopRawMutex; + + #[test] + fn try_acquire() { + let semaphore = GreedySemaphore::::new(3); + + let a = semaphore.try_acquire(1).unwrap(); + assert_eq!(a.permits(), 1); + assert_eq!(semaphore.permits(), 2); + + core::mem::drop(a); + assert_eq!(semaphore.permits(), 3); + } + + #[test] + fn disarm() { + let semaphore = GreedySemaphore::::new(3); + + let a = semaphore.try_acquire(1).unwrap(); + assert_eq!(a.disarm(), 1); + assert_eq!(semaphore.permits(), 2); + } + + #[futures_test::test] + async fn acquire() { + let semaphore = GreedySemaphore::::new(3); + + let a = semaphore.acquire(1).await.unwrap(); + assert_eq!(a.permits(), 1); + assert_eq!(semaphore.permits(), 2); + + core::mem::drop(a); + assert_eq!(semaphore.permits(), 3); + } + + #[test] + fn try_acquire_all() { + let semaphore = GreedySemaphore::::new(3); + + let a = semaphore.try_acquire_all(1).unwrap(); + assert_eq!(a.permits(), 3); + assert_eq!(semaphore.permits(), 0); + } + + #[futures_test::test] + async fn acquire_all() { + let semaphore = GreedySemaphore::::new(3); + + let a = semaphore.acquire_all(1).await.unwrap(); + assert_eq!(a.permits(), 3); + assert_eq!(semaphore.permits(), 0); + } + + #[test] + fn release() { + let semaphore = GreedySemaphore::::new(3); + assert_eq!(semaphore.permits(), 3); + semaphore.release(2); + assert_eq!(semaphore.permits(), 5); + } + + #[test] + fn set() { + let semaphore = GreedySemaphore::::new(3); + assert_eq!(semaphore.permits(), 3); + semaphore.set(2); + assert_eq!(semaphore.permits(), 2); + } + + #[test] + fn contested() { + let semaphore = GreedySemaphore::::new(3); + + let a = semaphore.try_acquire(1).unwrap(); + let b = semaphore.try_acquire(3); + assert!(b.is_none()); + + core::mem::drop(a); + + let b = semaphore.try_acquire(3); + assert!(b.is_some()); + } + + #[futures_test::test] + async fn greedy() { + let semaphore = GreedySemaphore::::new(3); + + let a = semaphore.try_acquire(1).unwrap(); + + let b_fut = semaphore.acquire(3); + let mut b_fut = pin!(b_fut); + let b = poll!(b_fut.as_mut()); + assert!(b.is_pending()); + + // Succeed even through `b` is waiting + let c = semaphore.try_acquire(1); + assert!(c.is_some()); + + let b = poll!(b_fut.as_mut()); + assert!(b.is_pending()); + + core::mem::drop(a); + + let b = poll!(b_fut.as_mut()); + assert!(b.is_pending()); + + core::mem::drop(c); + + let b = poll!(b_fut.as_mut()); + assert!(b.is_ready()); + } + } + + mod fair { + use core::pin::pin; + use core::time::Duration; + + use futures_executor::ThreadPool; + use futures_timer::Delay; + use futures_util::poll; + use futures_util::task::SpawnExt; + use static_cell::StaticCell; + + use super::super::*; + use crate::blocking_mutex::raw::{CriticalSectionRawMutex, NoopRawMutex}; + + #[test] + fn try_acquire() { + let semaphore = FairSemaphore::::new(3); + + let a = semaphore.try_acquire(1).unwrap(); + assert_eq!(a.permits(), 1); + assert_eq!(semaphore.permits(), 2); + + core::mem::drop(a); + assert_eq!(semaphore.permits(), 3); + } + + #[test] + fn disarm() { + let semaphore = FairSemaphore::::new(3); + + let a = semaphore.try_acquire(1).unwrap(); + assert_eq!(a.disarm(), 1); + assert_eq!(semaphore.permits(), 2); + } + + #[futures_test::test] + async fn acquire() { + let semaphore = FairSemaphore::::new(3); + + let a = semaphore.acquire(1).await.unwrap(); + assert_eq!(a.permits(), 1); + assert_eq!(semaphore.permits(), 2); + + core::mem::drop(a); + assert_eq!(semaphore.permits(), 3); + } + + #[test] + fn try_acquire_all() { + let semaphore = FairSemaphore::::new(3); + + let a = semaphore.try_acquire_all(1).unwrap(); + assert_eq!(a.permits(), 3); + assert_eq!(semaphore.permits(), 0); + } + + #[futures_test::test] + async fn acquire_all() { + let semaphore = FairSemaphore::::new(3); + + let a = semaphore.acquire_all(1).await.unwrap(); + assert_eq!(a.permits(), 3); + assert_eq!(semaphore.permits(), 0); + } + + #[test] + fn release() { + let semaphore = FairSemaphore::::new(3); + assert_eq!(semaphore.permits(), 3); + semaphore.release(2); + assert_eq!(semaphore.permits(), 5); + } + + #[test] + fn set() { + let semaphore = FairSemaphore::::new(3); + assert_eq!(semaphore.permits(), 3); + semaphore.set(2); + assert_eq!(semaphore.permits(), 2); + } + + #[test] + fn contested() { + let semaphore = FairSemaphore::::new(3); + + let a = semaphore.try_acquire(1).unwrap(); + let b = semaphore.try_acquire(3); + assert!(b.is_none()); + + core::mem::drop(a); + + let b = semaphore.try_acquire(3); + assert!(b.is_some()); + } + + #[futures_test::test] + async fn fairness() { + let semaphore = FairSemaphore::::new(3); + + let a = semaphore.try_acquire(1); + assert!(a.is_some()); + + let b_fut = semaphore.acquire(3); + let mut b_fut = pin!(b_fut); + let b = poll!(b_fut.as_mut()); // Poll `b_fut` once so it is registered + assert!(b.is_pending()); + + let c = semaphore.try_acquire(1); + assert!(c.is_none()); + + let c_fut = semaphore.acquire(1); + let mut c_fut = pin!(c_fut); + let c = poll!(c_fut.as_mut()); // Poll `c_fut` once so it is registered + assert!(c.is_pending()); // `c` is blocked behind `b` + + let d = semaphore.acquire(1).await; + assert!(matches!(d, Err(WaitQueueFull))); + + core::mem::drop(a); + + let c = poll!(c_fut.as_mut()); + assert!(c.is_pending()); // `c` is still blocked behind `b` + + let b = poll!(b_fut.as_mut()); + assert!(b.is_ready()); + + let c = poll!(c_fut.as_mut()); + assert!(c.is_pending()); // `c` is still blocked behind `b` + + core::mem::drop(b); + + let c = poll!(c_fut.as_mut()); + assert!(c.is_ready()); + } + + #[futures_test::test] + async fn wakers() { + let executor = ThreadPool::new().unwrap(); + + static SEMAPHORE: StaticCell> = StaticCell::new(); + let semaphore = &*SEMAPHORE.init(FairSemaphore::new(3)); + + let a = semaphore.try_acquire(2); + assert!(a.is_some()); + + let b_task = executor + .spawn_with_handle(async move { semaphore.acquire(2).await }) + .unwrap(); + while semaphore.state.lock(|x| x.borrow().wakers.is_empty()) { + Delay::new(Duration::from_millis(50)).await; + } + + let c_task = executor + .spawn_with_handle(async move { semaphore.acquire(1).await }) + .unwrap(); + + core::mem::drop(a); + + let b = b_task.await.unwrap(); + assert_eq!(b.permits(), 2); + + let c = c_task.await.unwrap(); + assert_eq!(c.permits(), 1); + } + } +} diff --git a/embassy-sync/src/signal.rs b/embassy-sync/src/signal.rs index d75750ce7..a0f4b5a74 100644 --- a/embassy-sync/src/signal.rs +++ b/embassy-sync/src/signal.rs @@ -65,7 +65,7 @@ where } } -impl Signal +impl Signal where M: RawMutex, { @@ -125,7 +125,7 @@ where }) } - /// non-blocking method to check whether this signal has been signaled. + /// non-blocking method to check whether this signal has been signaled. This does not clear the signal. pub fn signaled(&self) -> bool { self.state.lock(|cell| { let state = cell.replace(State::None); diff --git a/embassy-sync/src/waitqueue/multi_waker.rs b/embassy-sync/src/waitqueue/multi_waker.rs index 824d192da..0e520bf40 100644 --- a/embassy-sync/src/waitqueue/multi_waker.rs +++ b/embassy-sync/src/waitqueue/multi_waker.rs @@ -14,7 +14,7 @@ impl MultiWakerRegistration { } /// Register a waker. If the buffer is full the function returns it in the error - pub fn register<'a>(&mut self, w: &'a Waker) { + pub fn register(&mut self, w: &Waker) { // If we already have some waker that wakes the same task as `w`, do nothing. // This avoids cloning wakers, and avoids unnecessary mass-wakes. for w2 in &self.wakers { diff --git a/embassy-sync/src/watch.rs b/embassy-sync/src/watch.rs new file mode 100644 index 000000000..404e31714 --- /dev/null +++ b/embassy-sync/src/watch.rs @@ -0,0 +1,1121 @@ +//! A synchronization primitive for passing the latest value to **multiple** receivers. + +use core::cell::RefCell; +use core::future::poll_fn; +use core::marker::PhantomData; +use core::ops::{Deref, DerefMut}; +use core::task::{Context, Poll}; + +use crate::blocking_mutex::raw::RawMutex; +use crate::blocking_mutex::Mutex; +use crate::waitqueue::MultiWakerRegistration; + +/// The `Watch` is a single-slot signaling primitive that allows multiple receivers to concurrently await +/// changes to the value. Unlike a [`Signal`](crate::signal::Signal), `Watch` supports multiple receivers, +/// and unlike a [`PubSubChannel`](crate::pubsub::PubSubChannel), `Watch` immediately overwrites the previous +/// value when a new one is sent, without waiting for all receivers to read the previous value. +/// +/// This makes `Watch` particularly useful when a single task updates a value or "state", and multiple other tasks +/// need to be notified about changes to this value asynchronously. Receivers may "lose" stale values, as they are +/// always provided with the latest value. +/// +/// Typically, `Watch` instances are declared as `static`, and a [`Sender`] and [`Receiver`] +/// (or [`DynSender`] and/or [`DynReceiver`]) are obtained where relevant. An [`AnonReceiver`] +/// and [`DynAnonReceiver`] are also available, which do not increase the receiver count for the +/// channel, and unwrapping is therefore not required, but it is not possible to `.await` the channel. +/// ``` +/// +/// use futures_executor::block_on; +/// use embassy_sync::watch::Watch; +/// use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +/// +/// let f = async { +/// +/// static WATCH: Watch = Watch::new(); +/// +/// // Obtain receivers and sender +/// let mut rcv0 = WATCH.receiver().unwrap(); +/// let mut rcv1 = WATCH.dyn_receiver().unwrap(); +/// let mut snd = WATCH.sender(); +/// +/// // No more receivers, and no update +/// assert!(WATCH.receiver().is_none()); +/// assert_eq!(rcv1.try_changed(), None); +/// +/// snd.send(10); +/// +/// // Receive the new value (async or try) +/// assert_eq!(rcv0.changed().await, 10); +/// assert_eq!(rcv1.try_changed(), Some(10)); +/// +/// // No update +/// assert_eq!(rcv0.try_changed(), None); +/// assert_eq!(rcv1.try_changed(), None); +/// +/// snd.send(20); +/// +/// // Using `get` marks the value as seen +/// assert_eq!(rcv1.get().await, 20); +/// assert_eq!(rcv1.try_changed(), None); +/// +/// // But `get` also returns when unchanged +/// assert_eq!(rcv1.get().await, 20); +/// assert_eq!(rcv1.get().await, 20); +/// +/// }; +/// block_on(f); +/// ``` +pub struct Watch { + mutex: Mutex>>, +} + +struct WatchState { + data: Option, + current_id: u64, + wakers: MultiWakerRegistration, + receiver_count: usize, +} + +trait SealedWatchBehavior { + /// Poll the `Watch` for the current value, making it as seen. + fn poll_get(&self, id: &mut u64, cx: &mut Context<'_>) -> Poll; + + /// Poll the `Watch` for the value if it matches the predicate function + /// `f`, making it as seen. + fn poll_get_and(&self, id: &mut u64, f: &mut dyn Fn(&T) -> bool, cx: &mut Context<'_>) -> Poll; + + /// Poll the `Watch` for a changed value, marking it as seen, if an id is given. + fn poll_changed(&self, id: &mut u64, cx: &mut Context<'_>) -> Poll; + + /// Tries to retrieve the value of the `Watch` if it has changed, marking it as seen. + fn try_changed(&self, id: &mut u64) -> Option; + + /// Poll the `Watch` for a changed value that matches the predicate function + /// `f`, marking it as seen. + fn poll_changed_and(&self, id: &mut u64, f: &mut dyn Fn(&T) -> bool, cx: &mut Context<'_>) -> Poll; + + /// Tries to retrieve the value of the `Watch` if it has changed and matches the + /// predicate function `f`, marking it as seen. + fn try_changed_and(&self, id: &mut u64, f: &mut dyn Fn(&T) -> bool) -> Option; + + /// Used when a receiver is dropped to decrement the receiver count. + /// + /// ## This method should not be called by the user. + fn drop_receiver(&self); + + /// Clears the value of the `Watch`. + fn clear(&self); + + /// Sends a new value to the `Watch`. + fn send(&self, val: T); + + /// Modify the value of the `Watch` using a closure. Returns `false` if the + /// `Watch` does not already contain a value. + fn send_modify(&self, f: &mut dyn Fn(&mut Option)); + + /// Modify the value of the `Watch` using a closure. Returns `false` if the + /// `Watch` does not already contain a value. + fn send_if_modified(&self, f: &mut dyn Fn(&mut Option) -> bool); +} + +/// A trait representing the 'inner' behavior of the `Watch`. +#[allow(private_bounds)] +pub trait WatchBehavior: SealedWatchBehavior { + /// Tries to get the value of the `Watch`, marking it as seen, if an id is given. + fn try_get(&self, id: Option<&mut u64>) -> Option; + + /// Tries to get the value of the `Watch` if it matches the predicate function + /// `f`, marking it as seen. + fn try_get_and(&self, id: Option<&mut u64>, f: &mut dyn Fn(&T) -> bool) -> Option; + + /// Checks if the `Watch` is been initialized with a value. + fn contains_value(&self) -> bool; +} + +impl SealedWatchBehavior for Watch { + fn poll_get(&self, id: &mut u64, cx: &mut Context<'_>) -> Poll { + self.mutex.lock(|state| { + let mut s = state.borrow_mut(); + match &s.data { + Some(data) => { + *id = s.current_id; + Poll::Ready(data.clone()) + } + None => { + s.wakers.register(cx.waker()); + Poll::Pending + } + } + }) + } + + fn poll_get_and(&self, id: &mut u64, f: &mut dyn Fn(&T) -> bool, cx: &mut Context<'_>) -> Poll { + self.mutex.lock(|state| { + let mut s = state.borrow_mut(); + match s.data { + Some(ref data) if f(data) => { + *id = s.current_id; + Poll::Ready(data.clone()) + } + _ => { + s.wakers.register(cx.waker()); + Poll::Pending + } + } + }) + } + + fn poll_changed(&self, id: &mut u64, cx: &mut Context<'_>) -> Poll { + self.mutex.lock(|state| { + let mut s = state.borrow_mut(); + match (&s.data, s.current_id > *id) { + (Some(data), true) => { + *id = s.current_id; + Poll::Ready(data.clone()) + } + _ => { + s.wakers.register(cx.waker()); + Poll::Pending + } + } + }) + } + + fn try_changed(&self, id: &mut u64) -> Option { + self.mutex.lock(|state| { + let s = state.borrow(); + match s.current_id > *id { + true => { + *id = s.current_id; + s.data.clone() + } + false => None, + } + }) + } + + fn poll_changed_and(&self, id: &mut u64, f: &mut dyn Fn(&T) -> bool, cx: &mut Context<'_>) -> Poll { + self.mutex.lock(|state| { + let mut s = state.borrow_mut(); + match (&s.data, s.current_id > *id) { + (Some(data), true) if f(data) => { + *id = s.current_id; + Poll::Ready(data.clone()) + } + _ => { + s.wakers.register(cx.waker()); + Poll::Pending + } + } + }) + } + + fn try_changed_and(&self, id: &mut u64, f: &mut dyn Fn(&T) -> bool) -> Option { + self.mutex.lock(|state| { + let s = state.borrow(); + match (&s.data, s.current_id > *id) { + (Some(data), true) if f(data) => { + *id = s.current_id; + s.data.clone() + } + _ => None, + } + }) + } + + fn drop_receiver(&self) { + self.mutex.lock(|state| { + let mut s = state.borrow_mut(); + s.receiver_count -= 1; + }) + } + + fn clear(&self) { + self.mutex.lock(|state| { + let mut s = state.borrow_mut(); + s.data = None; + }) + } + + fn send(&self, val: T) { + self.mutex.lock(|state| { + let mut s = state.borrow_mut(); + s.data = Some(val); + s.current_id += 1; + s.wakers.wake(); + }) + } + + fn send_modify(&self, f: &mut dyn Fn(&mut Option)) { + self.mutex.lock(|state| { + let mut s = state.borrow_mut(); + f(&mut s.data); + s.current_id += 1; + s.wakers.wake(); + }) + } + + fn send_if_modified(&self, f: &mut dyn Fn(&mut Option) -> bool) { + self.mutex.lock(|state| { + let mut s = state.borrow_mut(); + if f(&mut s.data) { + s.current_id += 1; + s.wakers.wake(); + } + }) + } +} + +impl WatchBehavior for Watch { + fn try_get(&self, id: Option<&mut u64>) -> Option { + self.mutex.lock(|state| { + let s = state.borrow(); + if let Some(id) = id { + *id = s.current_id; + } + s.data.clone() + }) + } + + fn try_get_and(&self, id: Option<&mut u64>, f: &mut dyn Fn(&T) -> bool) -> Option { + self.mutex.lock(|state| { + let s = state.borrow(); + match s.data { + Some(ref data) if f(data) => { + if let Some(id) = id { + *id = s.current_id; + } + Some(data.clone()) + } + _ => None, + } + }) + } + + fn contains_value(&self) -> bool { + self.mutex.lock(|state| state.borrow().data.is_some()) + } +} + +impl Watch { + /// Create a new `Watch` channel. + pub const fn new() -> Self { + Self { + mutex: Mutex::new(RefCell::new(WatchState { + data: None, + current_id: 0, + wakers: MultiWakerRegistration::new(), + receiver_count: 0, + })), + } + } + + /// Create a new `Watch` channel with default data. + pub const fn new_with(data: T) -> Self { + Self { + mutex: Mutex::new(RefCell::new(WatchState { + data: Some(data), + current_id: 0, + wakers: MultiWakerRegistration::new(), + receiver_count: 0, + })), + } + } + + /// Create a new [`Sender`] for the `Watch`. + pub fn sender(&self) -> Sender<'_, M, T, N> { + Sender(Snd::new(self)) + } + + /// Create a new [`DynSender`] for the `Watch`. + pub fn dyn_sender(&self) -> DynSender<'_, T> { + DynSender(Snd::new(self)) + } + + /// Try to create a new [`Receiver`] for the `Watch`. If the + /// maximum number of receivers has been reached, `None` is returned. + pub fn receiver(&self) -> Option> { + self.mutex.lock(|state| { + let mut s = state.borrow_mut(); + if s.receiver_count < N { + s.receiver_count += 1; + Some(Receiver(Rcv::new(self, 0))) + } else { + None + } + }) + } + + /// Try to create a new [`DynReceiver`] for the `Watch`. If the + /// maximum number of receivers has been reached, `None` is returned. + pub fn dyn_receiver(&self) -> Option> { + self.mutex.lock(|state| { + let mut s = state.borrow_mut(); + if s.receiver_count < N { + s.receiver_count += 1; + Some(DynReceiver(Rcv::new(self, 0))) + } else { + None + } + }) + } + + /// Try to create a new [`AnonReceiver`] for the `Watch`. + pub fn anon_receiver(&self) -> AnonReceiver<'_, M, T, N> { + AnonReceiver(AnonRcv::new(self, 0)) + } + + /// Try to create a new [`DynAnonReceiver`] for the `Watch`. + pub fn dyn_anon_receiver(&self) -> DynAnonReceiver<'_, T> { + DynAnonReceiver(AnonRcv::new(self, 0)) + } + + /// Returns the message ID of the latest message sent to the `Watch`. + /// + /// This counter is monotonic, and is incremented every time a new message is sent. + pub fn get_msg_id(&self) -> u64 { + self.mutex.lock(|state| state.borrow().current_id) + } + + /// Tries to get the value of the `Watch`. + pub fn try_get(&self) -> Option { + WatchBehavior::try_get(self, None) + } + + /// Tries to get the value of the `Watch` if it matches the predicate function `f`. + pub fn try_get_and(&self, mut f: F) -> Option + where + F: Fn(&T) -> bool, + { + WatchBehavior::try_get_and(self, None, &mut f) + } +} + +/// A receiver can `.await` a change in the `Watch` value. +pub struct Snd<'a, T: Clone, W: WatchBehavior + ?Sized> { + watch: &'a W, + _phantom: PhantomData, +} + +impl<'a, T: Clone, W: WatchBehavior + ?Sized> Clone for Snd<'a, T, W> { + fn clone(&self) -> Self { + Self { + watch: self.watch, + _phantom: PhantomData, + } + } +} + +impl<'a, T: Clone, W: WatchBehavior + ?Sized> Snd<'a, T, W> { + /// Creates a new `Receiver` with a reference to the `Watch`. + fn new(watch: &'a W) -> Self { + Self { + watch, + _phantom: PhantomData, + } + } + + /// Sends a new value to the `Watch`. + pub fn send(&self, val: T) { + self.watch.send(val) + } + + /// Clears the value of the `Watch`. + /// This will cause calls to [`Rcv::get`] to be pending. + pub fn clear(&self) { + self.watch.clear() + } + + /// Tries to retrieve the value of the `Watch`. + pub fn try_get(&self) -> Option { + self.watch.try_get(None) + } + + /// Tries to peek the current value of the `Watch` if it matches the predicate + /// function `f`. + pub fn try_get_and(&self, mut f: F) -> Option + where + F: Fn(&T) -> bool, + { + self.watch.try_get_and(None, &mut f) + } + + /// Returns true if the `Watch` contains a value. + pub fn contains_value(&self) -> bool { + self.watch.contains_value() + } + + /// Modify the value of the `Watch` using a closure. + pub fn send_modify(&self, mut f: F) + where + F: Fn(&mut Option), + { + self.watch.send_modify(&mut f) + } + + /// Modify the value of the `Watch` using a closure. The closure must return + /// `true` if the value was modified, which notifies all receivers. + pub fn send_if_modified(&self, mut f: F) + where + F: Fn(&mut Option) -> bool, + { + self.watch.send_if_modified(&mut f) + } +} + +/// A sender of a `Watch` channel. +/// +/// For a simpler type definition, consider [`DynSender`] at the expense of +/// some runtime performance due to dynamic dispatch. +pub struct Sender<'a, M: RawMutex, T: Clone, const N: usize>(Snd<'a, T, Watch>); + +impl<'a, M: RawMutex, T: Clone, const N: usize> Clone for Sender<'a, M, T, N> { + fn clone(&self) -> Self { + Self(self.0.clone()) + } +} + +impl<'a, M: RawMutex, T: Clone, const N: usize> Sender<'a, M, T, N> { + /// Converts the `Sender` into a [`DynSender`]. + pub fn as_dyn(self) -> DynSender<'a, T> { + DynSender(Snd::new(self.watch)) + } +} + +impl<'a, M: RawMutex, T: Clone, const N: usize> Into> for Sender<'a, M, T, N> { + fn into(self) -> DynSender<'a, T> { + self.as_dyn() + } +} + +impl<'a, M: RawMutex, T: Clone, const N: usize> Deref for Sender<'a, M, T, N> { + type Target = Snd<'a, T, Watch>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl<'a, M: RawMutex, T: Clone, const N: usize> DerefMut for Sender<'a, M, T, N> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/// A sender which holds a **dynamic** reference to a `Watch` channel. +/// +/// This is an alternative to [`Sender`] with a simpler type definition, +pub struct DynSender<'a, T: Clone>(Snd<'a, T, dyn WatchBehavior + 'a>); + +impl<'a, T: Clone> Clone for DynSender<'a, T> { + fn clone(&self) -> Self { + Self(self.0.clone()) + } +} + +impl<'a, T: Clone> Deref for DynSender<'a, T> { + type Target = Snd<'a, T, dyn WatchBehavior + 'a>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl<'a, T: Clone> DerefMut for DynSender<'a, T> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/// A receiver can `.await` a change in the `Watch` value. +pub struct Rcv<'a, T: Clone, W: WatchBehavior + ?Sized> { + watch: &'a W, + at_id: u64, + _phantom: PhantomData, +} + +impl<'a, T: Clone, W: WatchBehavior + ?Sized> Rcv<'a, T, W> { + /// Creates a new `Receiver` with a reference to the `Watch`. + fn new(watch: &'a W, at_id: u64) -> Self { + Self { + watch, + at_id, + _phantom: PhantomData, + } + } + + /// Returns the current value of the `Watch` once it is initialized, marking it as seen. + /// + /// **Note**: Futures do nothing unless you `.await` or poll them. + pub async fn get(&mut self) -> T { + poll_fn(|cx| self.watch.poll_get(&mut self.at_id, cx)).await + } + + /// Tries to get the current value of the `Watch` without waiting, marking it as seen. + pub fn try_get(&mut self) -> Option { + self.watch.try_get(Some(&mut self.at_id)) + } + + /// Returns the value of the `Watch` if it matches the predicate function `f`, + /// or waits for it to match, marking it as seen. + /// + /// **Note**: Futures do nothing unless you `.await` or poll them. + pub async fn get_and(&mut self, mut f: F) -> T + where + F: Fn(&T) -> bool, + { + poll_fn(|cx| self.watch.poll_get_and(&mut self.at_id, &mut f, cx)).await + } + + /// Tries to get the current value of the `Watch` if it matches the predicate + /// function `f` without waiting, marking it as seen. + pub fn try_get_and(&mut self, mut f: F) -> Option + where + F: Fn(&T) -> bool, + { + self.watch.try_get_and(Some(&mut self.at_id), &mut f) + } + + /// Waits for the `Watch` to change and returns the new value, marking it as seen. + /// + /// **Note**: Futures do nothing unless you `.await` or poll them. + pub async fn changed(&mut self) -> T { + poll_fn(|cx| self.watch.poll_changed(&mut self.at_id, cx)).await + } + + /// Tries to get the new value of the watch without waiting, marking it as seen. + pub fn try_changed(&mut self) -> Option { + self.watch.try_changed(&mut self.at_id) + } + + /// Waits for the `Watch` to change to a value which satisfies the predicate + /// function `f` and returns the new value, marking it as seen. + /// + /// **Note**: Futures do nothing unless you `.await` or poll them. + pub async fn changed_and(&mut self, mut f: F) -> T + where + F: Fn(&T) -> bool, + { + poll_fn(|cx| self.watch.poll_changed_and(&mut self.at_id, &mut f, cx)).await + } + + /// Tries to get the new value of the watch which satisfies the predicate + /// function `f` and returns the new value without waiting, marking it as seen. + pub fn try_changed_and(&mut self, mut f: F) -> Option + where + F: Fn(&T) -> bool, + { + self.watch.try_changed_and(&mut self.at_id, &mut f) + } + + /// Checks if the `Watch` contains a value. If this returns true, + /// then awaiting [`Rcv::get`] will return immediately. + pub fn contains_value(&self) -> bool { + self.watch.contains_value() + } +} + +impl<'a, T: Clone, W: WatchBehavior + ?Sized> Drop for Rcv<'a, T, W> { + fn drop(&mut self) { + self.watch.drop_receiver(); + } +} + +/// A anonymous receiver can NOT `.await` a change in the `Watch` value. +pub struct AnonRcv<'a, T: Clone, W: WatchBehavior + ?Sized> { + watch: &'a W, + at_id: u64, + _phantom: PhantomData, +} + +impl<'a, T: Clone, W: WatchBehavior + ?Sized> AnonRcv<'a, T, W> { + /// Creates a new `Receiver` with a reference to the `Watch`. + fn new(watch: &'a W, at_id: u64) -> Self { + Self { + watch, + at_id, + _phantom: PhantomData, + } + } + + /// Tries to get the current value of the `Watch` without waiting, marking it as seen. + pub fn try_get(&mut self) -> Option { + self.watch.try_get(Some(&mut self.at_id)) + } + + /// Tries to get the current value of the `Watch` if it matches the predicate + /// function `f` without waiting, marking it as seen. + pub fn try_get_and(&mut self, mut f: F) -> Option + where + F: Fn(&T) -> bool, + { + self.watch.try_get_and(Some(&mut self.at_id), &mut f) + } + + /// Tries to get the new value of the watch without waiting, marking it as seen. + pub fn try_changed(&mut self) -> Option { + self.watch.try_changed(&mut self.at_id) + } + + /// Tries to get the new value of the watch which satisfies the predicate + /// function `f` and returns the new value without waiting, marking it as seen. + pub fn try_changed_and(&mut self, mut f: F) -> Option + where + F: Fn(&T) -> bool, + { + self.watch.try_changed_and(&mut self.at_id, &mut f) + } + + /// Checks if the `Watch` contains a value. If this returns true, + /// then awaiting [`Rcv::get`] will return immediately. + pub fn contains_value(&self) -> bool { + self.watch.contains_value() + } +} + +/// A receiver of a `Watch` channel. +pub struct Receiver<'a, M: RawMutex, T: Clone, const N: usize>(Rcv<'a, T, Watch>); + +impl<'a, M: RawMutex, T: Clone, const N: usize> Receiver<'a, M, T, N> { + /// Converts the `Receiver` into a [`DynReceiver`]. + pub fn as_dyn(self) -> DynReceiver<'a, T> { + let rcv = DynReceiver(Rcv::new(self.0.watch, self.at_id)); + core::mem::forget(self); // Ensures the destructor is not called + rcv + } +} + +impl<'a, M: RawMutex, T: Clone, const N: usize> Into> for Receiver<'a, M, T, N> { + fn into(self) -> DynReceiver<'a, T> { + self.as_dyn() + } +} + +impl<'a, M: RawMutex, T: Clone, const N: usize> Deref for Receiver<'a, M, T, N> { + type Target = Rcv<'a, T, Watch>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl<'a, M: RawMutex, T: Clone, const N: usize> DerefMut for Receiver<'a, M, T, N> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/// A receiver which holds a **dynamic** reference to a `Watch` channel. +/// +/// This is an alternative to [`Receiver`] with a simpler type definition, at the expense of +/// some runtime performance due to dynamic dispatch. +pub struct DynReceiver<'a, T: Clone>(Rcv<'a, T, dyn WatchBehavior + 'a>); + +impl<'a, T: Clone> Deref for DynReceiver<'a, T> { + type Target = Rcv<'a, T, dyn WatchBehavior + 'a>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl<'a, T: Clone> DerefMut for DynReceiver<'a, T> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/// A receiver of a `Watch` channel that cannot `.await` values. +pub struct AnonReceiver<'a, M: RawMutex, T: Clone, const N: usize>(AnonRcv<'a, T, Watch>); + +impl<'a, M: RawMutex, T: Clone, const N: usize> AnonReceiver<'a, M, T, N> { + /// Converts the `Receiver` into a [`DynReceiver`]. + pub fn as_dyn(self) -> DynAnonReceiver<'a, T> { + let rcv = DynAnonReceiver(AnonRcv::new(self.0.watch, self.at_id)); + core::mem::forget(self); // Ensures the destructor is not called + rcv + } +} + +impl<'a, M: RawMutex, T: Clone, const N: usize> Into> for AnonReceiver<'a, M, T, N> { + fn into(self) -> DynAnonReceiver<'a, T> { + self.as_dyn() + } +} + +impl<'a, M: RawMutex, T: Clone, const N: usize> Deref for AnonReceiver<'a, M, T, N> { + type Target = AnonRcv<'a, T, Watch>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl<'a, M: RawMutex, T: Clone, const N: usize> DerefMut for AnonReceiver<'a, M, T, N> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/// A receiver that cannot `.await` value, which holds a **dynamic** reference to a `Watch` channel. +/// +/// This is an alternative to [`AnonReceiver`] with a simpler type definition, at the expense of +/// some runtime performance due to dynamic dispatch. +pub struct DynAnonReceiver<'a, T: Clone>(AnonRcv<'a, T, dyn WatchBehavior + 'a>); + +impl<'a, T: Clone> Deref for DynAnonReceiver<'a, T> { + type Target = AnonRcv<'a, T, dyn WatchBehavior + 'a>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl<'a, T: Clone> DerefMut for DynAnonReceiver<'a, T> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +#[cfg(test)] +mod tests { + use futures_executor::block_on; + + use super::Watch; + use crate::blocking_mutex::raw::CriticalSectionRawMutex; + + #[test] + fn multiple_sends() { + let f = async { + static WATCH: Watch = Watch::new(); + + // Obtain receiver and sender + let mut rcv = WATCH.receiver().unwrap(); + let snd = WATCH.sender(); + + // Not initialized + assert_eq!(rcv.try_changed(), None); + + // Receive the new value + snd.send(10); + assert_eq!(rcv.changed().await, 10); + + // Receive another value + snd.send(20); + assert_eq!(rcv.try_changed(), Some(20)); + + // No update + assert_eq!(rcv.try_changed(), None); + }; + block_on(f); + } + + #[test] + fn all_try_get() { + let f = async { + static WATCH: Watch = Watch::new(); + + // Obtain receiver and sender + let mut rcv = WATCH.receiver().unwrap(); + let snd = WATCH.sender(); + + // Not initialized + assert_eq!(WATCH.try_get(), None); + assert_eq!(rcv.try_get(), None); + assert_eq!(snd.try_get(), None); + + // Receive the new value + snd.send(10); + assert_eq!(WATCH.try_get(), Some(10)); + assert_eq!(rcv.try_get(), Some(10)); + assert_eq!(snd.try_get(), Some(10)); + + assert_eq!(WATCH.try_get_and(|x| x > &5), Some(10)); + assert_eq!(rcv.try_get_and(|x| x > &5), Some(10)); + assert_eq!(snd.try_get_and(|x| x > &5), Some(10)); + + assert_eq!(WATCH.try_get_and(|x| x < &5), None); + assert_eq!(rcv.try_get_and(|x| x < &5), None); + assert_eq!(snd.try_get_and(|x| x < &5), None); + }; + block_on(f); + } + + #[test] + fn once_lock_like() { + let f = async { + static CONFIG0: u8 = 10; + static CONFIG1: u8 = 20; + + static WATCH: Watch = Watch::new(); + + // Obtain receiver and sender + let mut rcv = WATCH.receiver().unwrap(); + let snd = WATCH.sender(); + + // Not initialized + assert_eq!(rcv.try_changed(), None); + + // Receive the new value + snd.send(&CONFIG0); + let rcv0 = rcv.changed().await; + assert_eq!(rcv0, &10); + + // Receive another value + snd.send(&CONFIG1); + let rcv1 = rcv.try_changed(); + assert_eq!(rcv1, Some(&20)); + + // No update + assert_eq!(rcv.try_changed(), None); + + // Ensure similarity with original static + assert_eq!(rcv0, &CONFIG0); + assert_eq!(rcv1, Some(&CONFIG1)); + }; + block_on(f); + } + + #[test] + fn sender_modify() { + let f = async { + static WATCH: Watch = Watch::new(); + + // Obtain receiver and sender + let mut rcv = WATCH.receiver().unwrap(); + let snd = WATCH.sender(); + + // Receive the new value + snd.send(10); + assert_eq!(rcv.try_changed(), Some(10)); + + // Modify the value inplace + snd.send_modify(|opt| { + if let Some(inner) = opt { + *inner += 5; + } + }); + + // Get the modified value + assert_eq!(rcv.try_changed(), Some(15)); + assert_eq!(rcv.try_changed(), None); + }; + block_on(f); + } + + #[test] + fn predicate_fn() { + let f = async { + static WATCH: Watch = Watch::new(); + + // Obtain receiver and sender + let mut rcv = WATCH.receiver().unwrap(); + let snd = WATCH.sender(); + + snd.send(15); + assert_eq!(rcv.try_get_and(|x| x > &5), Some(15)); + assert_eq!(rcv.try_get_and(|x| x < &5), None); + assert!(rcv.try_changed().is_none()); + + snd.send(20); + assert_eq!(rcv.try_changed_and(|x| x > &5), Some(20)); + assert_eq!(rcv.try_changed_and(|x| x > &5), None); + + snd.send(25); + assert_eq!(rcv.try_changed_and(|x| x < &5), None); + assert_eq!(rcv.try_changed(), Some(25)); + + snd.send(30); + assert_eq!(rcv.changed_and(|x| x > &5).await, 30); + assert_eq!(rcv.get_and(|x| x > &5).await, 30); + }; + block_on(f); + } + + #[test] + fn receive_after_create() { + let f = async { + static WATCH: Watch = Watch::new(); + + // Obtain sender and send value + let snd = WATCH.sender(); + snd.send(10); + + // Obtain receiver and receive value + let mut rcv = WATCH.receiver().unwrap(); + assert_eq!(rcv.try_changed(), Some(10)); + }; + block_on(f); + } + + #[test] + fn max_receivers_drop() { + let f = async { + static WATCH: Watch = Watch::new(); + + // Try to create 3 receivers (only 2 can exist at once) + let rcv0 = WATCH.receiver(); + let rcv1 = WATCH.receiver(); + let rcv2 = WATCH.receiver(); + + // Ensure the first two are successful and the third is not + assert!(rcv0.is_some()); + assert!(rcv1.is_some()); + assert!(rcv2.is_none()); + + // Drop the first receiver + drop(rcv0); + + // Create another receiver and ensure it is successful + let rcv3 = WATCH.receiver(); + assert!(rcv3.is_some()); + }; + block_on(f); + } + + #[test] + fn multiple_receivers() { + let f = async { + static WATCH: Watch = Watch::new(); + + // Obtain receivers and sender + let mut rcv0 = WATCH.receiver().unwrap(); + let mut rcv1 = WATCH.anon_receiver(); + let snd = WATCH.sender(); + + // No update for both + assert_eq!(rcv0.try_changed(), None); + assert_eq!(rcv1.try_changed(), None); + + // Send a new value + snd.send(0); + + // Both receivers receive the new value + assert_eq!(rcv0.try_changed(), Some(0)); + assert_eq!(rcv1.try_changed(), Some(0)); + }; + block_on(f); + } + + #[test] + fn clone_senders() { + let f = async { + // Obtain different ways to send + static WATCH: Watch = Watch::new(); + let snd0 = WATCH.sender(); + let snd1 = snd0.clone(); + + // Obtain Receiver + let mut rcv = WATCH.receiver().unwrap().as_dyn(); + + // Send a value from first sender + snd0.send(10); + assert_eq!(rcv.try_changed(), Some(10)); + + // Send a value from second sender + snd1.send(20); + assert_eq!(rcv.try_changed(), Some(20)); + }; + block_on(f); + } + + #[test] + fn use_dynamics() { + let f = async { + static WATCH: Watch = Watch::new(); + + // Obtain receiver and sender + let mut anon_rcv = WATCH.dyn_anon_receiver(); + let mut dyn_rcv = WATCH.dyn_receiver().unwrap(); + let dyn_snd = WATCH.dyn_sender(); + + // Send a value + dyn_snd.send(10); + + // Ensure the dynamic receiver receives the value + assert_eq!(anon_rcv.try_changed(), Some(10)); + assert_eq!(dyn_rcv.try_changed(), Some(10)); + assert_eq!(dyn_rcv.try_changed(), None); + }; + block_on(f); + } + + #[test] + fn convert_to_dyn() { + let f = async { + static WATCH: Watch = Watch::new(); + + // Obtain receiver and sender + let anon_rcv = WATCH.anon_receiver(); + let rcv = WATCH.receiver().unwrap(); + let snd = WATCH.sender(); + + // Convert to dynamic + let mut dyn_anon_rcv = anon_rcv.as_dyn(); + let mut dyn_rcv = rcv.as_dyn(); + let dyn_snd = snd.as_dyn(); + + // Send a value + dyn_snd.send(10); + + // Ensure the dynamic receiver receives the value + assert_eq!(dyn_anon_rcv.try_changed(), Some(10)); + assert_eq!(dyn_rcv.try_changed(), Some(10)); + assert_eq!(dyn_rcv.try_changed(), None); + }; + block_on(f); + } + + #[test] + fn dynamic_receiver_count() { + let f = async { + static WATCH: Watch = Watch::new(); + + // Obtain receiver and sender + let rcv0 = WATCH.receiver(); + let rcv1 = WATCH.receiver(); + let rcv2 = WATCH.receiver(); + + // Ensure the first two are successful and the third is not + assert!(rcv0.is_some()); + assert!(rcv1.is_some()); + assert!(rcv2.is_none()); + + // Convert to dynamic + let dyn_rcv0 = rcv0.unwrap().as_dyn(); + + // Drop the (now dynamic) receiver + drop(dyn_rcv0); + + // Create another receiver and ensure it is successful + let rcv3 = WATCH.receiver(); + let rcv4 = WATCH.receiver(); + assert!(rcv3.is_some()); + assert!(rcv4.is_none()); + }; + block_on(f); + } + + #[test] + fn contains_value() { + let f = async { + static WATCH: Watch = Watch::new(); + + // Obtain receiver and sender + let rcv = WATCH.receiver().unwrap(); + let snd = WATCH.sender(); + + // check if the watch contains a value + assert_eq!(rcv.contains_value(), false); + assert_eq!(snd.contains_value(), false); + + // Send a value + snd.send(10); + + // check if the watch contains a value + assert_eq!(rcv.contains_value(), true); + assert_eq!(snd.contains_value(), true); + }; + block_on(f); + } +} diff --git a/embassy-sync/src/zerocopy_channel.rs b/embassy-sync/src/zerocopy_channel.rs index f704cbd5d..fabb69bf6 100644 --- a/embassy-sync/src/zerocopy_channel.rs +++ b/embassy-sync/src/zerocopy_channel.rs @@ -1,10 +1,7 @@ //! A zero-copy queue for sending values between asynchronous tasks. //! -//! It can be used concurrently by multiple producers (senders) and multiple -//! consumers (receivers), i.e. it is an "MPMC channel". -//! -//! Receivers are competing for messages. So a message that is received by -//! one receiver is not received by any other. +//! It can be used concurrently by a producer (sender) and a +//! consumer (receiver), i.e. it is an "SPSC channel". //! //! This queue takes a Mutex type so that various //! targets can be attained. For example, a ThreadModeMutex can be used @@ -56,7 +53,7 @@ impl<'a, M: RawMutex, T> Channel<'a, M, T> { buf: buf.as_mut_ptr(), phantom: PhantomData, state: Mutex::new(RefCell::new(State { - len, + capacity: len, front: 0, back: 0, full: false, @@ -73,6 +70,28 @@ impl<'a, M: RawMutex, T> Channel<'a, M, T> { pub fn split(&mut self) -> (Sender<'_, M, T>, Receiver<'_, M, T>) { (Sender { channel: self }, Receiver { channel: self }) } + + /// Clears all elements in the channel. + pub fn clear(&mut self) { + self.state.lock(|s| { + s.borrow_mut().clear(); + }); + } + + /// Returns the number of elements currently in the channel. + pub fn len(&self) -> usize { + self.state.lock(|s| s.borrow().len()) + } + + /// Returns whether the channel is empty. + pub fn is_empty(&self) -> bool { + self.state.lock(|s| s.borrow().is_empty()) + } + + /// Returns whether the channel is full. + pub fn is_full(&self) -> bool { + self.state.lock(|s| s.borrow().is_full()) + } } /// Send-only access to a [`Channel`]. @@ -133,6 +152,28 @@ impl<'a, M: RawMutex, T> Sender<'a, M, T> { pub fn send_done(&mut self) { self.channel.state.lock(|s| s.borrow_mut().push_done()) } + + /// Clears all elements in the channel. + pub fn clear(&mut self) { + self.channel.state.lock(|s| { + s.borrow_mut().clear(); + }); + } + + /// Returns the number of elements currently in the channel. + pub fn len(&self) -> usize { + self.channel.state.lock(|s| s.borrow().len()) + } + + /// Returns whether the channel is empty. + pub fn is_empty(&self) -> bool { + self.channel.state.lock(|s| s.borrow().is_empty()) + } + + /// Returns whether the channel is full. + pub fn is_full(&self) -> bool { + self.channel.state.lock(|s| s.borrow().is_full()) + } } /// Receive-only access to a [`Channel`]. @@ -193,10 +234,33 @@ impl<'a, M: RawMutex, T> Receiver<'a, M, T> { pub fn receive_done(&mut self) { self.channel.state.lock(|s| s.borrow_mut().pop_done()) } + + /// Clears all elements in the channel. + pub fn clear(&mut self) { + self.channel.state.lock(|s| { + s.borrow_mut().clear(); + }); + } + + /// Returns the number of elements currently in the channel. + pub fn len(&self) -> usize { + self.channel.state.lock(|s| s.borrow().len()) + } + + /// Returns whether the channel is empty. + pub fn is_empty(&self) -> bool { + self.channel.state.lock(|s| s.borrow().is_empty()) + } + + /// Returns whether the channel is full. + pub fn is_full(&self) -> bool { + self.channel.state.lock(|s| s.borrow().is_full()) + } } struct State { - len: usize, + /// Maximum number of elements the channel can hold. + capacity: usize, /// Front index. Always 0..=(N-1) front: usize, @@ -213,13 +277,31 @@ struct State { impl State { fn increment(&self, i: usize) -> usize { - if i + 1 == self.len { + if i + 1 == self.capacity { 0 } else { i + 1 } } + fn clear(&mut self) { + self.front = 0; + self.back = 0; + self.full = false; + } + + fn len(&self) -> usize { + if !self.full { + if self.back >= self.front { + self.back - self.front + } else { + self.capacity + self.back - self.front + } + } else { + self.capacity + } + } + fn is_full(&self) -> bool { self.full } diff --git a/embassy-time-driver/src/lib.rs b/embassy-time-driver/src/lib.rs index 565597935..12f40b9b9 100644 --- a/embassy-time-driver/src/lib.rs +++ b/embassy-time-driver/src/lib.rs @@ -98,7 +98,7 @@ pub trait Driver: Send + Sync + 'static { /// /// Implementations MUST ensure that: /// - This is guaranteed to be monotonic, i.e. a call to now() will always return - /// a greater or equal value than earler calls. Time can't "roll backwards". + /// a greater or equal value than earlier calls. Time can't "roll backwards". /// - It "never" overflows. It must not overflow in a sufficiently long time frame, say /// in 10_000 years (Human civilization is likely to already have self-destructed /// 10_000 years from now.). This means if your hardware only has 16bit/32bit timers @@ -109,28 +109,64 @@ pub trait Driver: Send + Sync + 'static { /// Try allocating an alarm handle. Returns None if no alarms left. /// Initially the alarm has no callback set, and a null `ctx` pointer. /// + /// The allocated alarm is a reusable resource and can be used multiple times. + /// Once the alarm has fired, it remains allocated and can be set again without needing + /// to be reallocated. + /// /// # Safety /// It is UB to make the alarm fire before setting a callback. unsafe fn allocate_alarm(&self) -> Option; - /// Sets the callback function to be called when the alarm triggers. + /// Set the callback function to be called when the alarm triggers. /// The callback may be called from any context (interrupt or thread mode). + /// + /// The callback is maintained after the alarm has fired. Callers do not need + /// to set a callback again before setting another alarm, unless they want to + /// change the callback function or context. fn set_alarm_callback(&self, alarm: AlarmHandle, callback: fn(*mut ()), ctx: *mut ()); - /// Sets an alarm at the given timestamp. When the current timestamp reaches the alarm - /// timestamp, the provided callback function will be called. + /// Set an alarm at the given timestamp. /// - /// The `Driver` implementation should guarantee that the alarm callback is never called synchronously from `set_alarm`. - /// Rather - if `timestamp` is already in the past - `false` should be returned and alarm should not be set, - /// or alternatively, the driver should return `true` and arrange to call the alarm callback as soon as possible, but not synchronously. - /// There is a rare third possibility that the alarm was barely in the future, and by the time it was enabled, it had slipped into the - /// past. This is can be detected by double-checking that the alarm is still in the future after enabling it; if it isn't, `false` - /// should also be returned to indicate that the callback may have been called already by the alarm, but it is not guaranteed, so the - /// caller should also call the callback, just like in the more common `false` case. (Note: This requires idempotency of the callback.) + /// ## Behavior /// - /// When callback is called, it is guaranteed that now() will return a value greater or equal than timestamp. + /// If `timestamp` is in the future, `set_alarm` schedules calling the callback function + /// at that time, and returns `true`. /// - /// Only one alarm can be active at a time for each AlarmHandle. This overwrites any previously-set alarm if any. + /// If `timestamp` is in the past, `set_alarm` has two allowed behaviors. Implementations can pick whether to: + /// + /// - Schedule calling the callback function "immediately", as if the requested timestamp was "now+epsilon" and return `true`, or + /// - Not schedule the callback, and return `false`. + /// + /// Callers must ensure to behave correctly with either behavior. + /// + /// When callback is called, it is guaranteed that `now()` will return a value greater than or equal to `timestamp`. + /// + /// ## Reentrancy + /// + /// Calling the callback from `set_alarm` synchronously is not allowed. If the implementation chooses the first option above, + /// it must still call the callback from another context (i.e. an interrupt handler or background thread), it's not allowed + /// to call it synchronously in the context `set_alarm` is running. + /// + /// The reason for the above is callers are explicitly permitted to do both of: + /// - Lock a mutex in the alarm callback. + /// - Call `set_alarm` while having that mutex locked. + /// + /// If `set_alarm` called the callback synchronously, it'd cause a deadlock or panic because it'd cause the + /// mutex to be locked twice reentrantly in the same context. + /// + /// ## Overwriting alarms + /// + /// Only one alarm can be active at a time for each `AlarmHandle`. This overwrites any previously-set alarm if any. + /// + /// ## Unsetting the alarm + /// + /// There is no `unset_alarm` API. Instead, callers can call `set_alarm` with `timestamp` set to `u64::MAX`. + /// + /// This allows for more efficient implementations, since they don't need to distinguish between the "alarm set" and + /// "alarm not set" cases, thanks to the fact "Alarm set for u64::MAX" is effectively equivalent for "alarm not set". + /// + /// This means implementations need to be careful to avoid timestamp overflows. The recommendation is to make `timestamp` + /// be in the same units as hardware ticks to avoid any conversions, which makes avoiding overflow easier. fn set_alarm(&self, alarm: AlarmHandle, timestamp: u64) -> bool; } diff --git a/embassy-time-queue-driver/README.md b/embassy-time-queue-driver/README.md index 8852b0358..b9fb12d94 100644 --- a/embassy-time-queue-driver/README.md +++ b/embassy-time-queue-driver/README.md @@ -4,5 +4,5 @@ This crate contains the driver trait used by the [`embassy-time`](https://crates You should rarely need to use this crate directly. Only use it when implementing your own timer queue. -There is two timer queue implementations, one in `embassy-time` enabled by the `generic-queue` feature, and +There is two timer queue implementations, one in `embassy-time` enabled by the `generic-queue` feature, and another in `embassy-executor` enabled by the `integrated-timers` feature. diff --git a/embassy-time/CHANGELOG.md b/embassy-time/CHANGELOG.md index df093949f..3b4d93387 100644 --- a/embassy-time/CHANGELOG.md +++ b/embassy-time/CHANGELOG.md @@ -5,6 +5,20 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + +## 0.3.2 - 2024-08-05 + +- Implement with_timeout()/with_deadline() method style call on Future +- Add collapse_debuginfo to fmt.rs macros. + +## 0.3.1 - 2024-01-11 + +- Add with\_deadline convenience function and example +- Implement Clone for Delay +- Make Ticker::next Send+Sync +- Add timestamp features + ## 0.3.0 - 2024-01-11 - Update `embedded-hal-async` to `1.0.0` diff --git a/embassy-time/Cargo.toml b/embassy-time/Cargo.toml index 6b0a0f22d..0e61434f1 100644 --- a/embassy-time/Cargo.toml +++ b/embassy-time/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "embassy-time" -version = "0.3.0" +version = "0.3.2" edition = "2021" description = "Instant and Duration for embedded no-std systems, with async timer support" repository = "https://github.com/embassy-rs/embassy" @@ -27,9 +27,17 @@ features = ["defmt", "std"] std = ["tick-hz-1_000_000", "critical-section/std"] wasm = ["dep:wasm-bindgen", "dep:js-sys", "dep:wasm-timer", "tick-hz-1_000_000"] -## Display a timestamp of the number of seconds since startup next to defmt log messages +## Display the time since startup next to defmt log messages. +## At most 1 `defmt-timestamp-uptime-*` feature can be used. +## `defmt-timestamp-uptime` is provided for backwards compatibility (provides the same format as `uptime-us`). ## To use this you must have a time driver provided. defmt-timestamp-uptime = ["defmt"] +defmt-timestamp-uptime-s = ["defmt"] +defmt-timestamp-uptime-ms = ["defmt"] +defmt-timestamp-uptime-us = ["defmt"] +defmt-timestamp-uptime-ts = ["defmt"] +defmt-timestamp-uptime-tms = ["defmt"] +defmt-timestamp-uptime-tus = ["defmt"] ## Create a `MockDriver` that can be manually advanced for testing purposes. mock-driver = ["tick-hz-1_000_000"] @@ -42,7 +50,7 @@ generic-queue = [] #! The following features set how many timers are used for the generic queue. At most one #! `generic-queue-*` feature can be enabled. If none is enabled, a default of 64 timers is used. -#! +#! #! When using embassy-time from libraries, you should *not* enable any `generic-queue-*` feature, to allow the #! end user to pick. @@ -60,7 +68,7 @@ generic-queue-128 = ["generic-queue"] #! ### Tick Rate #! #! At most 1 `tick-*` feature can be enabled. If none is enabled, a default of 1MHz is used. -#! +#! #! If the time driver in use supports using arbitrary tick rates, you can enable one `tick-*` #! feature from your binary crate to set the tick rate. The driver will use configured tick rate. #! If the time driver supports a fixed tick rate, it will enable one feature itself, so you should @@ -71,7 +79,7 @@ generic-queue-128 = ["generic-queue"] #!

#! Available tick rates: #! -#! +#! # BEGIN TICKS # Generated by gen_tick.py. DO NOT EDIT. @@ -423,4 +431,4 @@ wasm-timer = { version = "0.2.5", optional = true } [dev-dependencies] serial_test = "0.9" critical-section = { version = "1.1", features = ["std"] } -embassy-executor = { version = "0.5.0", path = "../embassy-executor" } +embassy-executor = { version = "0.6.2", path = "../embassy-executor" } diff --git a/embassy-time/README.md b/embassy-time/README.md index f5d46df7b..6a4b049b4 100644 --- a/embassy-time/README.md +++ b/embassy-time/README.md @@ -5,7 +5,7 @@ Timekeeping, delays and timeouts. Timekeeping is done with elapsed time since system boot. Time is represented in ticks, where the tick rate is defined either by the driver (in the case of a fixed-rate tick) or chosen by the user with a [tick rate](#tick-rate) feature. The chosen -tick rate applies to everything in `embassy-time` and thus determines the maximum +tick rate applies to everything in `embassy-time` and thus determines the maximum timing resolution of (1 / tick_rate) seconds. Tick counts are 64 bits. The default tick rate of 1Mhz supports diff --git a/embassy-time/src/delay.rs b/embassy-time/src/delay.rs index 7ef5961f0..f77859d4a 100644 --- a/embassy-time/src/delay.rs +++ b/embassy-time/src/delay.rs @@ -13,6 +13,7 @@ pub fn block_for(duration: Duration) { /// the amount provided, but accuracy can be affected by many factors, including interrupt usage. /// Make sure to use a suitable tick rate for your use case. The tick rate is defined by the currently /// active driver. +#[derive(Clone)] pub struct Delay; impl embedded_hal_1::delay::DelayNs for Delay { diff --git a/embassy-time/src/fmt.rs b/embassy-time/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-time/src/fmt.rs +++ b/embassy-time/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-time/src/lib.rs b/embassy-time/src/lib.rs index 3c8575ee9..8d0648ce5 100644 --- a/embassy-time/src/lib.rs +++ b/embassy-time/src/lib.rs @@ -32,7 +32,7 @@ pub use delay::{block_for, Delay}; pub use duration::Duration; pub use embassy_time_driver::TICK_HZ; pub use instant::Instant; -pub use timer::{with_deadline, with_timeout, Ticker, TimeoutError, Timer}; +pub use timer::{with_deadline, with_timeout, Ticker, TimeoutError, Timer, WithTimeout}; const fn gcd(a: u64, b: u64) -> u64 { if b == 0 { @@ -46,5 +46,20 @@ pub(crate) const GCD_1K: u64 = gcd(TICK_HZ, 1_000); pub(crate) const GCD_1M: u64 = gcd(TICK_HZ, 1_000_000); pub(crate) const GCD_1G: u64 = gcd(TICK_HZ, 1_000_000_000); -#[cfg(feature = "defmt-timestamp-uptime")] +#[cfg(feature = "defmt-timestamp-uptime-s")] +defmt::timestamp! {"{=u64}", Instant::now().as_secs() } + +#[cfg(feature = "defmt-timestamp-uptime-ms")] +defmt::timestamp! {"{=u64:ms}", Instant::now().as_millis() } + +#[cfg(any(feature = "defmt-timestamp-uptime", feature = "defmt-timestamp-uptime-us"))] defmt::timestamp! {"{=u64:us}", Instant::now().as_micros() } + +#[cfg(feature = "defmt-timestamp-uptime-ts")] +defmt::timestamp! {"{=u64:ts}", Instant::now().as_secs() } + +#[cfg(feature = "defmt-timestamp-uptime-tms")] +defmt::timestamp! {"{=u64:tms}", Instant::now().as_millis() } + +#[cfg(feature = "defmt-timestamp-uptime-tus")] +defmt::timestamp! {"{=u64:tus}", Instant::now().as_micros() } diff --git a/embassy-time/src/queue_generic.rs b/embassy-time/src/queue_generic.rs index cf7a986d5..4882afd3e 100644 --- a/embassy-time/src/queue_generic.rs +++ b/embassy-time/src/queue_generic.rs @@ -177,9 +177,10 @@ embassy_time_queue_driver::timer_queue_impl!(static QUEUE: Queue = Queue::new()) #[cfg(test)] #[cfg(feature = "mock-driver")] mod tests { - use core::cell::Cell; - use core::task::{RawWaker, RawWakerVTable, Waker}; - use std::rc::Rc; + use core::sync::atomic::{AtomicBool, Ordering}; + use core::task::Waker; + use std::sync::Arc; + use std::task::Wake; use serial_test::serial; @@ -188,42 +189,26 @@ mod tests { use crate::{Duration, Instant}; struct TestWaker { - pub awoken: Rc>, - pub waker: Waker, + pub awoken: AtomicBool, } - impl TestWaker { - fn new() -> Self { - let flag = Rc::new(Cell::new(false)); - - const VTABLE: RawWakerVTable = RawWakerVTable::new( - |data: *const ()| { - unsafe { - Rc::increment_strong_count(data as *const Cell); - } - - RawWaker::new(data as _, &VTABLE) - }, - |data: *const ()| unsafe { - let data = data as *const Cell; - data.as_ref().unwrap().set(true); - Rc::decrement_strong_count(data); - }, - |data: *const ()| unsafe { - (data as *const Cell).as_ref().unwrap().set(true); - }, - |data: *const ()| unsafe { - Rc::decrement_strong_count(data); - }, - ); - - let raw = RawWaker::new(Rc::into_raw(flag.clone()) as _, &VTABLE); - - Self { - awoken: flag.clone(), - waker: unsafe { Waker::from_raw(raw) }, - } + impl Wake for TestWaker { + fn wake(self: Arc) { + self.awoken.store(true, Ordering::Relaxed); } + + fn wake_by_ref(self: &Arc) { + self.awoken.store(true, Ordering::Relaxed); + } + } + + fn test_waker() -> (Arc, Waker) { + let arc = Arc::new(TestWaker { + awoken: AtomicBool::new(false), + }); + let waker = Waker::from(arc.clone()); + + (arc, waker) } fn setup() { @@ -249,11 +234,11 @@ mod tests { assert_eq!(queue_len(), 0); - let waker = TestWaker::new(); + let (flag, waker) = test_waker(); - QUEUE.schedule_wake(Instant::from_secs(1), &waker.waker); + QUEUE.schedule_wake(Instant::from_secs(1), &waker); - assert!(!waker.awoken.get()); + assert!(!flag.awoken.load(Ordering::Relaxed)); assert_eq!(queue_len(), 1); } @@ -262,23 +247,23 @@ mod tests { fn test_schedule_same() { setup(); - let waker = TestWaker::new(); + let (_flag, waker) = test_waker(); - QUEUE.schedule_wake(Instant::from_secs(1), &waker.waker); + QUEUE.schedule_wake(Instant::from_secs(1), &waker); assert_eq!(queue_len(), 1); - QUEUE.schedule_wake(Instant::from_secs(1), &waker.waker); + QUEUE.schedule_wake(Instant::from_secs(1), &waker); assert_eq!(queue_len(), 1); - QUEUE.schedule_wake(Instant::from_secs(100), &waker.waker); + QUEUE.schedule_wake(Instant::from_secs(100), &waker); assert_eq!(queue_len(), 1); - let waker2 = TestWaker::new(); + let (_flag2, waker2) = test_waker(); - QUEUE.schedule_wake(Instant::from_secs(100), &waker2.waker); + QUEUE.schedule_wake(Instant::from_secs(100), &waker2); assert_eq!(queue_len(), 2); } @@ -288,21 +273,21 @@ mod tests { fn test_trigger() { setup(); - let waker = TestWaker::new(); + let (flag, waker) = test_waker(); - QUEUE.schedule_wake(Instant::from_secs(100), &waker.waker); + QUEUE.schedule_wake(Instant::from_secs(100), &waker); - assert!(!waker.awoken.get()); + assert!(!flag.awoken.load(Ordering::Relaxed)); MockDriver::get().advance(Duration::from_secs(99)); - assert!(!waker.awoken.get()); + assert!(!flag.awoken.load(Ordering::Relaxed)); assert_eq!(queue_len(), 1); MockDriver::get().advance(Duration::from_secs(1)); - assert!(waker.awoken.get()); + assert!(flag.awoken.load(Ordering::Relaxed)); assert_eq!(queue_len(), 0); } @@ -312,18 +297,18 @@ mod tests { fn test_immediate_trigger() { setup(); - let waker = TestWaker::new(); + let (flag, waker) = test_waker(); - QUEUE.schedule_wake(Instant::from_secs(100), &waker.waker); + QUEUE.schedule_wake(Instant::from_secs(100), &waker); MockDriver::get().advance(Duration::from_secs(50)); - let waker2 = TestWaker::new(); + let (flag2, waker2) = test_waker(); - QUEUE.schedule_wake(Instant::from_secs(40), &waker2.waker); + QUEUE.schedule_wake(Instant::from_secs(40), &waker2); - assert!(!waker.awoken.get()); - assert!(waker2.awoken.get()); + assert!(!flag.awoken.load(Ordering::Relaxed)); + assert!(flag2.awoken.load(Ordering::Relaxed)); assert_eq!(queue_len(), 1); } @@ -333,30 +318,31 @@ mod tests { setup(); for i in 1..super::QUEUE_SIZE { - let waker = TestWaker::new(); + let (flag, waker) = test_waker(); - QUEUE.schedule_wake(Instant::from_secs(310), &waker.waker); + QUEUE.schedule_wake(Instant::from_secs(310), &waker); assert_eq!(queue_len(), i); - assert!(!waker.awoken.get()); + assert!(!flag.awoken.load(Ordering::Relaxed)); } - let first_waker = TestWaker::new(); + let (flag, waker) = test_waker(); - QUEUE.schedule_wake(Instant::from_secs(300), &first_waker.waker); + QUEUE.schedule_wake(Instant::from_secs(300), &waker); assert_eq!(queue_len(), super::QUEUE_SIZE); - assert!(!first_waker.awoken.get()); + assert!(!flag.awoken.load(Ordering::Relaxed)); - let second_waker = TestWaker::new(); + let (flag2, waker2) = test_waker(); - QUEUE.schedule_wake(Instant::from_secs(305), &second_waker.waker); + QUEUE.schedule_wake(Instant::from_secs(305), &waker2); assert_eq!(queue_len(), super::QUEUE_SIZE); - assert!(first_waker.awoken.get()); + assert!(flag.awoken.load(Ordering::Relaxed)); - QUEUE.schedule_wake(Instant::from_secs(320), &TestWaker::new().waker); + let (_flag3, waker3) = test_waker(); + QUEUE.schedule_wake(Instant::from_secs(320), &waker3); assert_eq!(queue_len(), super::QUEUE_SIZE); - assert!(second_waker.awoken.get()); + assert!(flag2.awoken.load(Ordering::Relaxed)); } } diff --git a/embassy-time/src/timer.rs b/embassy-time/src/timer.rs index daa4c1699..4d7194b20 100644 --- a/embassy-time/src/timer.rs +++ b/embassy-time/src/timer.rs @@ -1,10 +1,10 @@ use core::future::{poll_fn, Future}; -use core::pin::Pin; +use core::pin::{pin, Pin}; use core::task::{Context, Poll}; use futures_util::future::{select, Either}; use futures_util::stream::FusedStream; -use futures_util::{pin_mut, Stream}; +use futures_util::Stream; use crate::{Duration, Instant}; @@ -19,8 +19,7 @@ pub struct TimeoutError; /// work on the future is stopped (`poll` is no longer called), the future is dropped and `Err(TimeoutError)` is returned. pub async fn with_timeout(timeout: Duration, fut: F) -> Result { let timeout_fut = Timer::after(timeout); - pin_mut!(fut); - match select(fut, timeout_fut).await { + match select(pin!(fut), timeout_fut).await { Either::Left((r, _)) => Ok(r), Either::Right(_) => Err(TimeoutError), } @@ -32,13 +31,42 @@ pub async fn with_timeout(timeout: Duration, fut: F) -> Result(at: Instant, fut: F) -> Result { let timeout_fut = Timer::at(at); - pin_mut!(fut); - match select(fut, timeout_fut).await { + match select(pin!(fut), timeout_fut).await { Either::Left((r, _)) => Ok(r), Either::Right(_) => Err(TimeoutError), } } +/// Provides functions to run a given future with a timeout or a deadline. +pub trait WithTimeout { + /// Output type of the future. + type Output; + + /// Runs a given future with a timeout. + /// + /// If the future completes before the timeout, its output is returned. Otherwise, on timeout, + /// work on the future is stopped (`poll` is no longer called), the future is dropped and `Err(TimeoutError)` is returned. + async fn with_timeout(self, timeout: Duration) -> Result; + + /// Runs a given future with a deadline time. + /// + /// If the future completes before the deadline, its output is returned. Otherwise, on timeout, + /// work on the future is stopped (`poll` is no longer called), the future is dropped and `Err(TimeoutError)` is returned. + async fn with_deadline(self, at: Instant) -> Result; +} + +impl WithTimeout for F { + type Output = F::Output; + + async fn with_timeout(self, timeout: Duration) -> Result { + with_timeout(timeout, self).await + } + + async fn with_deadline(self, at: Instant) -> Result { + with_deadline(at, self).await + } +} + /// A future that completes at a specified [Instant](struct.Instant.html). #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Timer { @@ -190,8 +218,20 @@ impl Ticker { self.expires_at = Instant::now() + self.duration; } + /// Reset the ticker at the deadline. + /// If the deadline is in the past, the ticker will fire instantly. + pub fn reset_at(&mut self, deadline: Instant) { + self.expires_at = deadline + self.duration; + } + + /// Resets the ticker, after the specified duration has passed. + /// If the specified duration is zero, the next tick will be after the duration of the ticker. + pub fn reset_after(&mut self, after: Duration) { + self.expires_at = Instant::now() + after + self.duration; + } + /// Waits for the next tick. - pub fn next(&mut self) -> impl Future + '_ { + pub fn next(&mut self) -> impl Future + Send + Sync + '_ { poll_fn(|cx| { if self.expires_at <= Instant::now() { let dur = self.duration; diff --git a/embassy-usb-dfu/Cargo.toml b/embassy-usb-dfu/Cargo.toml index 4d6ffeb5f..481b2699a 100644 --- a/embassy-usb-dfu/Cargo.toml +++ b/embassy-usb-dfu/Cargo.toml @@ -26,14 +26,16 @@ flavors = [ features = ["defmt", "cortex-m", "dfu"] [dependencies] +defmt = { version = "0.3.5", optional = true } +log = { version = "0.4.17", optional = true } + bitflags = "2.4.1" cortex-m = { version = "0.7.7", features = ["inline-asm"], optional = true } -defmt = { version = "0.3.5", optional = true } -embassy-boot = { version = "0.2.0", path = "../embassy-boot" } +embassy-boot = { version = "0.3.0", path = "../embassy-boot" } embassy-futures = { version = "0.1.1", path = "../embassy-futures" } -embassy-sync = { version = "0.5.0", path = "../embassy-sync" } -embassy-time = { version = "0.3.0", path = "../embassy-time" } -embassy-usb = { version = "0.1.0", path = "../embassy-usb", default-features = false } +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } +embassy-time = { version = "0.3.2", path = "../embassy-time" } +embassy-usb = { version = "0.3.0", path = "../embassy-usb", default-features = false } embedded-storage = { version = "0.3.1" } esp32c3-hal = { version = "0.13.0", optional = true, default-features = false } diff --git a/embassy-usb-dfu/src/fmt.rs b/embassy-usb-dfu/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-usb-dfu/src/fmt.rs +++ b/embassy-usb-dfu/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-usb-driver/Cargo.toml b/embassy-usb-driver/Cargo.toml index 837878621..41493f00d 100644 --- a/embassy-usb-driver/Cargo.toml +++ b/embassy-usb-driver/Cargo.toml @@ -9,10 +9,8 @@ categories = ["embedded", "hardware-support", "no-std", "asynchronous"] repository = "https://github.com/embassy-rs/embassy" documentation = "https://docs.embassy.dev/embassy-usb-driver" -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - [package.metadata.embassy_docs] -src_base = "https://github.com/embassy-rs/embassy/blob/embassy-usb-driver-v$VERSION/embassy-usb/src/" +src_base = "https://github.com/embassy-rs/embassy/blob/embassy-usb-driver-v$VERSION/embassy-usb-driver/src/" src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/embassy-usb-driver/src/" features = ["defmt"] target = "thumbv7em-none-eabi" diff --git a/embassy-usb-logger/CHANGELOG.md b/embassy-usb-logger/CHANGELOG.md new file mode 100644 index 000000000..4cd84b8be --- /dev/null +++ b/embassy-usb-logger/CHANGELOG.md @@ -0,0 +1,28 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## Unreleased + +## 0.2.0 - 2024-05-20 + +### Added + +- [#2414](https://github.com/embassy-rs/embassy/pull/2414) USB logger can now use an existing USB device (@JomerDev) + +### Changed + +- Update `embassy-usb` to 0.2.0 + +### Fixed + +- No more data loss at `Pipe` wraparound +- [#2414](https://github.com/embassy-rs/embassy/pull/2414) Messages that are exactly `MAX_PACKET_SIZE` long are no +longer delayed (@JomerDev) + +## 0.1.0 - 2024-01-14 + +- Initial Release diff --git a/embassy-usb-logger/Cargo.toml b/embassy-usb-logger/Cargo.toml index cb23fed1b..d796e5d8e 100644 --- a/embassy-usb-logger/Cargo.toml +++ b/embassy-usb-logger/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "embassy-usb-logger" -version = "0.1.0" +version = "0.2.0" edition = "2021" license = "MIT OR Apache-2.0" description = "`log` implementation for USB serial using `embassy-usb`." @@ -15,7 +15,7 @@ src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/embassy-usb-l target = "thumbv7em-none-eabi" [dependencies] -embassy-usb = { version = "0.1.0", path = "../embassy-usb" } -embassy-sync = { version = "0.5.0", path = "../embassy-sync" } +embassy-usb = { version = "0.3.0", path = "../embassy-usb" } +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } embassy-futures = { version = "0.1.0", path = "../embassy-futures" } log = "0.4" diff --git a/embassy-usb-logger/src/lib.rs b/embassy-usb-logger/src/lib.rs index 45d780bf8..29c102f10 100644 --- a/embassy-usb-logger/src/lib.rs +++ b/embassy-usb-logger/src/lib.rs @@ -3,20 +3,39 @@ #![warn(missing_docs)] use core::fmt::Write as _; +use core::future::Future; use embassy_futures::join::join; use embassy_sync::pipe::Pipe; -use embassy_usb::class::cdc_acm::{CdcAcmClass, State}; +use embassy_usb::class::cdc_acm::{CdcAcmClass, Receiver, Sender, State}; use embassy_usb::driver::Driver; use embassy_usb::{Builder, Config}; use log::{Metadata, Record}; type CS = embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +/// A trait that can be implemented and then passed to the +pub trait ReceiverHandler { + /// Data comes in from the serial port with each command and runs this function + fn handle_data(&self, data: &[u8]) -> impl Future + Send; + + /// Create a new instance of the Handler + fn new() -> Self; +} + +/// Use this Handler if you don't wish to use any handler +pub struct DummyHandler; + +impl ReceiverHandler for DummyHandler { + async fn handle_data(&self, _data: &[u8]) {} + fn new() -> Self { + Self {} + } +} + /// The logger state containing buffers that must live as long as the USB peripheral. pub struct LoggerState<'d> { state: State<'d>, - device_descriptor: [u8; 32], config_descriptor: [u8; 128], bos_descriptor: [u8; 16], msos_descriptor: [u8; 256], @@ -28,7 +47,6 @@ impl<'d> LoggerState<'d> { pub fn new() -> Self { Self { state: State::new(), - device_descriptor: [0; 32], config_descriptor: [0; 128], bos_descriptor: [0; 16], msos_descriptor: [0; 256], @@ -37,15 +55,38 @@ impl<'d> LoggerState<'d> { } } +/// The packet size used in the usb logger, to be used with `create_future_from_class` +pub const MAX_PACKET_SIZE: u8 = 64; + /// The logger handle, which contains a pipe with configurable size for buffering log messages. -pub struct UsbLogger { +pub struct UsbLogger { buffer: Pipe, + custom_style: Option) -> ()>, + recieve_handler: Option, } -impl UsbLogger { +impl UsbLogger { /// Create a new logger instance. pub const fn new() -> Self { - Self { buffer: Pipe::new() } + Self { + buffer: Pipe::new(), + custom_style: None, + recieve_handler: None, + } + } + + /// Create a new logger instance with a custom formatter. + pub const fn with_custom_style(custom_style: fn(&Record, &mut Writer<'_, N>) -> ()) -> Self { + Self { + buffer: Pipe::new(), + custom_style: Some(custom_style), + recieve_handler: None, + } + } + + /// Add a command handler to the logger + pub fn with_handler(&mut self, handler: T) { + self.recieve_handler = Some(handler); } /// Run the USB logger using the state and USB driver. Never returns. @@ -54,7 +95,6 @@ impl UsbLogger { D: Driver<'d>, Self: 'd, { - const MAX_PACKET_SIZE: u8 = 64; let mut config = Config::new(0xc0de, 0xcafe); config.manufacturer = Some("Embassy"); config.product = Some("USB-serial logger"); @@ -72,7 +112,6 @@ impl UsbLogger { let mut builder = Builder::new( driver, config, - &mut state.device_descriptor, &mut state.config_descriptor, &mut state.bos_descriptor, &mut state.msos_descriptor, @@ -87,52 +126,98 @@ impl UsbLogger { let mut device = builder.build(); loop { let run_fut = device.run(); - let log_fut = async { - let mut rx: [u8; MAX_PACKET_SIZE as usize] = [0; MAX_PACKET_SIZE as usize]; - sender.wait_connection().await; - loop { - let len = self.buffer.read(&mut rx[..]).await; - let _ = sender.write_packet(&rx[..len]).await; + let class_fut = self.run_logger_class(&mut sender, &mut receiver); + join(run_fut, class_fut).await; + } + } + + async fn run_logger_class<'d, D>(&self, sender: &mut Sender<'d, D>, receiver: &mut Receiver<'d, D>) + where + D: Driver<'d>, + { + let log_fut = async { + let mut rx: [u8; MAX_PACKET_SIZE as usize] = [0; MAX_PACKET_SIZE as usize]; + sender.wait_connection().await; + loop { + let len = self.buffer.read(&mut rx[..]).await; + let _ = sender.write_packet(&rx[..len]).await; + if len as u8 == MAX_PACKET_SIZE { + let _ = sender.write_packet(&[]).await; } - }; - let discard_fut = async { - let mut discard_buf: [u8; MAX_PACKET_SIZE as usize] = [0; MAX_PACKET_SIZE as usize]; - receiver.wait_connection().await; - loop { - let _ = receiver.read_packet(&mut discard_buf).await; + } + }; + let reciever_fut = async { + let mut reciever_buf: [u8; MAX_PACKET_SIZE as usize] = [0; MAX_PACKET_SIZE as usize]; + receiver.wait_connection().await; + loop { + let n = receiver.read_packet(&mut reciever_buf).await.unwrap(); + match &self.recieve_handler { + Some(handler) => { + let data = &reciever_buf[..n]; + handler.handle_data(data).await; + } + None => (), } - }; - join(run_fut, join(log_fut, discard_fut)).await; + } + }; + + join(log_fut, reciever_fut).await; + } + + /// Creates the futures needed for the logger from a given class + /// This can be used in cases where the usb device is already in use for another connection + pub async fn create_future_from_class<'d, D>(&'d self, class: CdcAcmClass<'d, D>) + where + D: Driver<'d>, + { + let (mut sender, mut receiver) = class.split(); + loop { + self.run_logger_class(&mut sender, &mut receiver).await; } } } -impl log::Log for UsbLogger { +impl log::Log for UsbLogger { fn enabled(&self, _metadata: &Metadata) -> bool { true } fn log(&self, record: &Record) { if self.enabled(record.metadata()) { - let _ = write!(Writer(&self.buffer), "{}\r\n", record.args()); + if let Some(custom_style) = self.custom_style { + custom_style(record, &mut Writer(&self.buffer)); + } else { + let _ = write!(Writer(&self.buffer), "{}\r\n", record.args()); + } } } fn flush(&self) {} } -struct Writer<'d, const N: usize>(&'d Pipe); +/// A writer that writes to the USB logger buffer. +pub struct Writer<'d, const N: usize>(&'d Pipe); impl<'d, const N: usize> core::fmt::Write for Writer<'d, N> { fn write_str(&mut self, s: &str) -> Result<(), core::fmt::Error> { - let _ = self.0.try_write(s.as_bytes()); + // The Pipe is implemented in such way that we cannot + // write across the wraparound discontinuity. + let b = s.as_bytes(); + if let Ok(n) = self.0.try_write(b) { + if n < b.len() { + // We wrote some data but not all, attempt again + // as the reason might be a wraparound in the + // ring buffer, which resolves on second attempt. + let _ = self.0.try_write(&b[n..]); + } + } Ok(()) } } /// Initialize and run the USB serial logger, never returns. /// -/// Arguments specify the buffer size, log level and the USB driver, respectively. +/// Arguments specify the buffer size, log level and the USB driver, respectively. You can optionally add a RecieverHandler. /// /// # Usage /// @@ -146,10 +231,95 @@ impl<'d, const N: usize> core::fmt::Write for Writer<'d, N> { #[macro_export] macro_rules! run { ( $x:expr, $l:expr, $p:ident ) => { - static LOGGER: ::embassy_usb_logger::UsbLogger<$x> = ::embassy_usb_logger::UsbLogger::new(); + static LOGGER: ::embassy_usb_logger::UsbLogger<$x, ::embassy_usb_logger::DummyHandler> = + ::embassy_usb_logger::UsbLogger::new(); unsafe { let _ = ::log::set_logger_racy(&LOGGER).map(|()| log::set_max_level_racy($l)); } let _ = LOGGER.run(&mut ::embassy_usb_logger::LoggerState::new(), $p).await; }; + + ( $x:expr, $l:expr, $p:ident, $h:ty ) => { + unsafe { + static mut LOGGER: ::embassy_usb_logger::UsbLogger<$x, $h> = ::embassy_usb_logger::UsbLogger::new(); + LOGGER.with_handler(<$h>::new()); + let _ = ::log::set_logger_racy(&LOGGER).map(|()| log::set_max_level_racy($l)); + let _ = LOGGER.run(&mut ::embassy_usb_logger::LoggerState::new(), $p).await; + } + }; +} + +/// Initialize the USB serial logger from a serial class and return the future to run it. +/// +/// Arguments specify the buffer size, log level and the serial class, respectively. You can optionally add a RecieverHandler. +/// +/// # Usage +/// +/// ``` +/// embassy_usb_logger::with_class!(1024, log::LevelFilter::Info, class); +/// ``` +/// +/// # Safety +/// +/// This macro should only be invoked only once since it is setting the global logging state of the application. +#[macro_export] +macro_rules! with_class { + ( $x:expr, $l:expr, $p:ident ) => {{ + static LOGGER: ::embassy_usb_logger::UsbLogger<$x, ::embassy_usb_logger::DummyHandler> = + ::embassy_usb_logger::UsbLogger::new(); + unsafe { + let _ = ::log::set_logger_racy(&LOGGER).map(|()| log::set_max_level_racy($l)); + } + LOGGER.create_future_from_class($p) + }}; + + ( $x:expr, $l:expr, $p:ident, $h:ty ) => {{ + unsafe { + static mut LOGGER: ::embassy_usb_logger::UsbLogger<$x, $h> = ::embassy_usb_logger::UsbLogger::new(); + LOGGER.with_handler(<$h>::new()); + let _ = ::log::set_logger_racy(&LOGGER).map(|()| log::set_max_level_racy($l)); + LOGGER.create_future_from_class($p) + } + }}; +} + +/// Initialize the USB serial logger from a serial class and return the future to run it. +/// This version of the macro allows for a custom style function to be passed in. +/// The custom style function will be called for each log record and is responsible for writing the log message to the buffer. +/// +/// Arguments specify the buffer size, log level, the serial class and the custom style function, respectively. You can optionally add a RecieverHandler. +/// +/// # Usage +/// +/// ``` +/// let log_fut = embassy_usb_logger::with_custom_style!(1024, log::LevelFilter::Info, logger_class, |record, writer| { +/// use core::fmt::Write; +/// let level = record.level().as_str(); +/// write!(writer, "[{level}] {}\r\n", record.args()).unwrap(); +/// }); +/// ``` +/// +/// # Safety +/// +/// This macro should only be invoked only once since it is setting the global logging state of the application. +#[macro_export] +macro_rules! with_custom_style { + ( $x:expr, $l:expr, $p:ident, $s:expr ) => {{ + static LOGGER: ::embassy_usb_logger::UsbLogger<$x, ::embassy_usb_logger::DummyHandler> = + ::embassy_usb_logger::UsbLogger::with_custom_style($s); + unsafe { + let _ = ::log::set_logger_racy(&LOGGER).map(|()| log::set_max_level_racy($l)); + } + LOGGER.create_future_from_class($p) + }}; + + ( $x:expr, $l:expr, $p:ident, $s:expr, $h:ty ) => {{ + unsafe { + static mut LOGGER: ::embassy_usb_logger::UsbLogger<$x, $h> = + ::embassy_usb_logger::UsbLogger::with_custom_style($s); + LOGGER.with_handler(<$h>::new()); + let _ = ::log::set_logger_racy(&LOGGER).map(|()| log::set_max_level_racy($l)); + LOGGER.create_future_from_class($p) + } + }}; } diff --git a/embassy-usb-synopsys-otg/Cargo.toml b/embassy-usb-synopsys-otg/Cargo.toml new file mode 100644 index 000000000..68ab0415f --- /dev/null +++ b/embassy-usb-synopsys-otg/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "embassy-usb-synopsys-otg" +version = "0.1.0" +edition = "2021" +license = "MIT OR Apache-2.0" +description = "`embassy-usb-driver` implementation for Synopsys OTG USB controllers" +keywords = ["embedded", "async", "usb", "hal", "embedded-hal"] +categories = ["embedded", "hardware-support", "no-std", "asynchronous"] +repository = "https://github.com/embassy-rs/embassy" +documentation = "https://docs.embassy.dev/embassy-usb-synopsys-otg" + +[package.metadata.embassy_docs] +src_base = "https://github.com/embassy-rs/embassy/blob/embassy-usb-synopsys-otg-v$VERSION/embassy-usb-synopsys-otg/src/" +src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/embassy-usb-synopsys-otg/src/" +features = ["defmt"] +target = "thumbv7em-none-eabi" + +[dependencies] +critical-section = "1.1" + +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } +embassy-usb-driver = {version = "0.1.0", path = "../embassy-usb-driver" } + +defmt = { version = "0.3", optional = true } +log = { version = "0.4.14", optional = true } diff --git a/embassy-usb-synopsys-otg/README.md b/embassy-usb-synopsys-otg/README.md new file mode 100644 index 000000000..5354f07bf --- /dev/null +++ b/embassy-usb-synopsys-otg/README.md @@ -0,0 +1,16 @@ +# Embassy USB driver for the Synopsys USB OTG core + +This crate implements [`embassy-usb-driver`](https://crates.io/crates/embassy-usb-driver) for Synopsys USB OTG devices. + +It contains the "core" of the driver that is common across all chips using +the Synopsys OTG IP, but it doesn't contain chip-specific initialization such +as clock setup and GPIO muxing. You most likely don't want to use this crate +directly, but use it through a HAL that does the initialization for you. + +List of HALs integrating this driver: + +- [`embassy-stm32`](https://crates.io/crates/embassy-stm32), for STMicroelectronics STM32 chips. +- [`esp-hal`](https://crates.io/crates/esp-hal), for Espressif ESP32 chips. + +If you wish to integrate this crate into your device's HAL, you will need to add the +device-specific initialization. See the above crates for examples on how to do it. \ No newline at end of file diff --git a/embassy-usb-synopsys-otg/src/fmt.rs b/embassy-usb-synopsys-otg/src/fmt.rs new file mode 100644 index 000000000..8ca61bc39 --- /dev/null +++ b/embassy-usb-synopsys-otg/src/fmt.rs @@ -0,0 +1,270 @@ +#![macro_use] +#![allow(unused)] + +use core::fmt::{Debug, Display, LowerHex}; + +#[cfg(all(feature = "defmt", feature = "log"))] +compile_error!("You may not enable both `defmt` and `log` features."); + +#[collapse_debuginfo(yes)] +macro_rules! assert { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::assert!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::assert!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! assert_eq { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::assert_eq!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::assert_eq!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! assert_ne { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::assert_ne!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::assert_ne!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! debug_assert { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::debug_assert!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::debug_assert!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! debug_assert_eq { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::debug_assert_eq!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::debug_assert_eq!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! debug_assert_ne { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::debug_assert_ne!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::debug_assert_ne!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! todo { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::todo!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::todo!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! unreachable { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! panic { + ($($x:tt)*) => { + { + #[cfg(not(feature = "defmt"))] + ::core::panic!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::panic!($($x)*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! trace { + ($s:literal $(, $x:expr)* $(,)?) => { + { + #[cfg(feature = "log")] + ::log::trace!($s $(, $x)*); + #[cfg(feature = "defmt")] + ::defmt::trace!($s $(, $x)*); + #[cfg(not(any(feature = "log", feature="defmt")))] + let _ = ($( & $x ),*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! debug { + ($s:literal $(, $x:expr)* $(,)?) => { + { + #[cfg(feature = "log")] + ::log::debug!($s $(, $x)*); + #[cfg(feature = "defmt")] + ::defmt::debug!($s $(, $x)*); + #[cfg(not(any(feature = "log", feature="defmt")))] + let _ = ($( & $x ),*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! info { + ($s:literal $(, $x:expr)* $(,)?) => { + { + #[cfg(feature = "log")] + ::log::info!($s $(, $x)*); + #[cfg(feature = "defmt")] + ::defmt::info!($s $(, $x)*); + #[cfg(not(any(feature = "log", feature="defmt")))] + let _ = ($( & $x ),*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! warn { + ($s:literal $(, $x:expr)* $(,)?) => { + { + #[cfg(feature = "log")] + ::log::warn!($s $(, $x)*); + #[cfg(feature = "defmt")] + ::defmt::warn!($s $(, $x)*); + #[cfg(not(any(feature = "log", feature="defmt")))] + let _ = ($( & $x ),*); + } + }; +} + +#[collapse_debuginfo(yes)] +macro_rules! error { + ($s:literal $(, $x:expr)* $(,)?) => { + { + #[cfg(feature = "log")] + ::log::error!($s $(, $x)*); + #[cfg(feature = "defmt")] + ::defmt::error!($s $(, $x)*); + #[cfg(not(any(feature = "log", feature="defmt")))] + let _ = ($( & $x ),*); + } + }; +} + +#[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] +macro_rules! unwrap { + ($($x:tt)*) => { + ::defmt::unwrap!($($x)*) + }; +} + +#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] +macro_rules! unwrap { + ($arg:expr) => { + match $crate::fmt::Try::into_result($arg) { + ::core::result::Result::Ok(t) => t, + ::core::result::Result::Err(e) => { + ::core::panic!("unwrap of `{}` failed: {:?}", ::core::stringify!($arg), e); + } + } + }; + ($arg:expr, $($msg:expr),+ $(,)? ) => { + match $crate::fmt::Try::into_result($arg) { + ::core::result::Result::Ok(t) => t, + ::core::result::Result::Err(e) => { + ::core::panic!("unwrap of `{}` failed: {}: {:?}", ::core::stringify!($arg), ::core::format_args!($($msg,)*), e); + } + } + } +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub struct NoneError; + +pub trait Try { + type Ok; + type Error; + fn into_result(self) -> Result; +} + +impl Try for Option { + type Ok = T; + type Error = NoneError; + + #[inline] + fn into_result(self) -> Result { + self.ok_or(NoneError) + } +} + +impl Try for Result { + type Ok = T; + type Error = E; + + #[inline] + fn into_result(self) -> Self { + self + } +} + +pub(crate) struct Bytes<'a>(pub &'a [u8]); + +impl<'a> Debug for Bytes<'a> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{:#02x?}", self.0) + } +} + +impl<'a> Display for Bytes<'a> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{:#02x?}", self.0) + } +} + +impl<'a> LowerHex for Bytes<'a> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{:#02x?}", self.0) + } +} + +#[cfg(feature = "defmt")] +impl<'a> defmt::Format for Bytes<'a> { + fn format(&self, fmt: defmt::Formatter) { + defmt::write!(fmt, "{:02x}", self.0) + } +} diff --git a/embassy-stm32/src/usb_otg/usb.rs b/embassy-usb-synopsys-otg/src/lib.rs similarity index 50% rename from embassy-stm32/src/usb_otg/usb.rs rename to embassy-usb-synopsys-otg/src/lib.rs index 190fb274f..f90403936 100644 --- a/embassy-stm32/src/usb_otg/usb.rs +++ b/embassy-usb-synopsys-otg/src/lib.rs @@ -1,192 +1,172 @@ +#![cfg_attr(not(test), no_std)] +#![allow(async_fn_in_trait)] +#![doc = include_str!("../README.md")] +#![warn(missing_docs)] + +// This must go FIRST so that all the other modules see its macros. +mod fmt; + use core::cell::UnsafeCell; +use core::future::poll_fn; use core::marker::PhantomData; use core::sync::atomic::{AtomicBool, AtomicU16, Ordering}; use core::task::Poll; -use embassy_hal_internal::{into_ref, Peripheral}; use embassy_sync::waitqueue::AtomicWaker; use embassy_usb_driver::{ - self, Bus as _, Direction, EndpointAddress, EndpointAllocError, EndpointError, EndpointIn, EndpointInfo, - EndpointOut, EndpointType, Event, Unsupported, + Bus as _, Direction, EndpointAddress, EndpointAllocError, EndpointError, EndpointIn, EndpointInfo, EndpointOut, + EndpointType, Event, Unsupported, }; -use futures::future::poll_fn; -use super::*; -use crate::gpio::sealed::AFType; -use crate::interrupt; -use crate::interrupt::typelevel::Interrupt; -use crate::pac::otg::{regs, vals}; -use crate::rcc::sealed::RccPeripheral; -use crate::time::Hertz; +pub mod otg_v1; -/// Interrupt handler. -pub struct InterruptHandler { - _phantom: PhantomData, -} +use otg_v1::{regs, vals, Otg}; -impl interrupt::typelevel::Handler for InterruptHandler { - unsafe fn on_interrupt() { - trace!("irq"); - let r = T::regs(); - let state = T::state(); - - let ints = r.gintsts().read(); - if ints.wkupint() || ints.usbsusp() || ints.usbrst() || ints.enumdne() || ints.otgint() || ints.srqint() { - // Mask interrupts and notify `Bus` to process them - r.gintmsk().write(|_| {}); - T::state().bus_waker.wake(); - } - - // Handle RX - while r.gintsts().read().rxflvl() { - let status = r.grxstsp().read(); - trace!("=== status {:08x}", status.0); - let ep_num = status.epnum() as usize; - let len = status.bcnt() as usize; - - assert!(ep_num < T::ENDPOINT_COUNT); - - match status.pktstsd() { - vals::Pktstsd::SETUP_DATA_RX => { - trace!("SETUP_DATA_RX"); - assert!(len == 8, "invalid SETUP packet length={}", len); - assert!(ep_num == 0, "invalid SETUP packet endpoint={}", ep_num); - - // flushing TX if something stuck in control endpoint - if r.dieptsiz(ep_num).read().pktcnt() != 0 { - r.grstctl().modify(|w| { - w.set_txfnum(ep_num as _); - w.set_txfflsh(true); - }); - while r.grstctl().read().txfflsh() {} - } - - if state.ep0_setup_ready.load(Ordering::Relaxed) == false { - // SAFETY: exclusive access ensured by atomic bool - let data = unsafe { &mut *state.ep0_setup_data.get() }; - data[0..4].copy_from_slice(&r.fifo(0).read().0.to_ne_bytes()); - data[4..8].copy_from_slice(&r.fifo(0).read().0.to_ne_bytes()); - state.ep0_setup_ready.store(true, Ordering::Release); - state.ep_out_wakers[0].wake(); - } else { - error!("received SETUP before previous finished processing"); - // discard FIFO - r.fifo(0).read(); - r.fifo(0).read(); - } - } - vals::Pktstsd::OUT_DATA_RX => { - trace!("OUT_DATA_RX ep={} len={}", ep_num, len); - - if state.ep_out_size[ep_num].load(Ordering::Acquire) == EP_OUT_BUFFER_EMPTY { - // SAFETY: Buffer size is allocated to be equal to endpoint's maximum packet size - // We trust the peripheral to not exceed its configured MPSIZ - let buf = unsafe { core::slice::from_raw_parts_mut(*state.ep_out_buffers[ep_num].get(), len) }; - - for chunk in buf.chunks_mut(4) { - // RX FIFO is shared so always read from fifo(0) - let data = r.fifo(0).read().0; - chunk.copy_from_slice(&data.to_ne_bytes()[0..chunk.len()]); - } - - state.ep_out_size[ep_num].store(len as u16, Ordering::Release); - state.ep_out_wakers[ep_num].wake(); - } else { - error!("ep_out buffer overflow index={}", ep_num); - - // discard FIFO data - let len_words = (len + 3) / 4; - for _ in 0..len_words { - r.fifo(0).read().data(); - } - } - } - vals::Pktstsd::OUT_DATA_DONE => { - trace!("OUT_DATA_DONE ep={}", ep_num); - } - vals::Pktstsd::SETUP_DATA_DONE => { - trace!("SETUP_DATA_DONE ep={}", ep_num); - - if quirk_setup_late_cnak(r) { - // Clear NAK to indicate we are ready to receive more data - r.doepctl(ep_num).modify(|w| w.set_cnak(true)); - } - } - x => trace!("unknown PKTSTS: {}", x.to_bits()), - } - } - - // IN endpoint interrupt - if ints.iepint() { - let mut ep_mask = r.daint().read().iepint(); - let mut ep_num = 0; - - // Iterate over endpoints while there are non-zero bits in the mask - while ep_mask != 0 { - if ep_mask & 1 != 0 { - let ep_ints = r.diepint(ep_num).read(); - - // clear all - r.diepint(ep_num).write_value(ep_ints); - - // TXFE is cleared in DIEPEMPMSK - if ep_ints.txfe() { - critical_section::with(|_| { - r.diepempmsk().modify(|w| { - w.set_ineptxfem(w.ineptxfem() & !(1 << ep_num)); - }); - }); - } - - state.ep_in_wakers[ep_num].wake(); - trace!("in ep={} irq val={:08x}", ep_num, ep_ints.0); - } - - ep_mask >>= 1; - ep_num += 1; - } - } - - // not needed? reception handled in rxflvl - // OUT endpoint interrupt - // if ints.oepint() { - // let mut ep_mask = r.daint().read().oepint(); - // let mut ep_num = 0; - - // while ep_mask != 0 { - // if ep_mask & 1 != 0 { - // let ep_ints = r.doepint(ep_num).read(); - // // clear all - // r.doepint(ep_num).write_value(ep_ints); - // state.ep_out_wakers[ep_num].wake(); - // trace!("out ep={} irq val={:08x}", ep_num, ep_ints.0); - // } - - // ep_mask >>= 1; - // ep_num += 1; - // } - // } +/// Handle interrupts. +pub unsafe fn on_interrupt( + r: Otg, + state: &State, + ep_count: usize, + quirk_setup_late_cnak: bool, +) { + let ints = r.gintsts().read(); + if ints.wkupint() || ints.usbsusp() || ints.usbrst() || ints.enumdne() || ints.otgint() || ints.srqint() { + // Mask interrupts and notify `Bus` to process them + r.gintmsk().write(|_| {}); + state.bus_waker.wake(); } -} -macro_rules! config_ulpi_pins { - ($($pin:ident),*) => { - into_ref!($($pin),*); - critical_section::with(|_| { - $( - $pin.set_as_af($pin.af_num(), AFType::OutputPushPull); - #[cfg(gpio_v2)] - $pin.set_speed(crate::gpio::Speed::VeryHigh); - )* - }) - }; -} + // Handle RX + while r.gintsts().read().rxflvl() { + let status = r.grxstsp().read(); + trace!("=== status {:08x}", status.0); + let ep_num = status.epnum() as usize; + let len = status.bcnt() as usize; -// From `synopsys-usb-otg` crate: -// This calculation doesn't correspond to one in a Reference Manual. -// In fact, the required number of words is higher than indicated in RM. -// The following numbers are pessimistic and were figured out empirically. -const RX_FIFO_EXTRA_SIZE_WORDS: u16 = 30; + assert!(ep_num < ep_count); + + match status.pktstsd() { + vals::Pktstsd::SETUP_DATA_RX => { + trace!("SETUP_DATA_RX"); + assert!(len == 8, "invalid SETUP packet length={}", len); + assert!(ep_num == 0, "invalid SETUP packet endpoint={}", ep_num); + + // flushing TX if something stuck in control endpoint + if r.dieptsiz(ep_num).read().pktcnt() != 0 { + r.grstctl().modify(|w| { + w.set_txfnum(ep_num as _); + w.set_txfflsh(true); + }); + while r.grstctl().read().txfflsh() {} + } + + if state.cp_state.setup_ready.load(Ordering::Relaxed) == false { + // SAFETY: exclusive access ensured by atomic bool + let data = unsafe { &mut *state.cp_state.setup_data.get() }; + data[0..4].copy_from_slice(&r.fifo(0).read().0.to_ne_bytes()); + data[4..8].copy_from_slice(&r.fifo(0).read().0.to_ne_bytes()); + state.cp_state.setup_ready.store(true, Ordering::Release); + state.ep_states[0].out_waker.wake(); + } else { + error!("received SETUP before previous finished processing"); + // discard FIFO + r.fifo(0).read(); + r.fifo(0).read(); + } + } + vals::Pktstsd::OUT_DATA_RX => { + trace!("OUT_DATA_RX ep={} len={}", ep_num, len); + + if state.ep_states[ep_num].out_size.load(Ordering::Acquire) == EP_OUT_BUFFER_EMPTY { + // SAFETY: Buffer size is allocated to be equal to endpoint's maximum packet size + // We trust the peripheral to not exceed its configured MPSIZ + let buf = + unsafe { core::slice::from_raw_parts_mut(*state.ep_states[ep_num].out_buffer.get(), len) }; + + for chunk in buf.chunks_mut(4) { + // RX FIFO is shared so always read from fifo(0) + let data = r.fifo(0).read().0; + chunk.copy_from_slice(&data.to_ne_bytes()[0..chunk.len()]); + } + + state.ep_states[ep_num].out_size.store(len as u16, Ordering::Release); + state.ep_states[ep_num].out_waker.wake(); + } else { + error!("ep_out buffer overflow index={}", ep_num); + + // discard FIFO data + let len_words = (len + 3) / 4; + for _ in 0..len_words { + r.fifo(0).read().data(); + } + } + } + vals::Pktstsd::OUT_DATA_DONE => { + trace!("OUT_DATA_DONE ep={}", ep_num); + } + vals::Pktstsd::SETUP_DATA_DONE => { + trace!("SETUP_DATA_DONE ep={}", ep_num); + + if quirk_setup_late_cnak { + // Clear NAK to indicate we are ready to receive more data + r.doepctl(ep_num).modify(|w| w.set_cnak(true)); + } + } + x => trace!("unknown PKTSTS: {}", x.to_bits()), + } + } + + // IN endpoint interrupt + if ints.iepint() { + let mut ep_mask = r.daint().read().iepint(); + let mut ep_num = 0; + + // Iterate over endpoints while there are non-zero bits in the mask + while ep_mask != 0 { + if ep_mask & 1 != 0 { + let ep_ints = r.diepint(ep_num).read(); + + // clear all + r.diepint(ep_num).write_value(ep_ints); + + // TXFE is cleared in DIEPEMPMSK + if ep_ints.txfe() { + critical_section::with(|_| { + r.diepempmsk().modify(|w| { + w.set_ineptxfem(w.ineptxfem() & !(1 << ep_num)); + }); + }); + } + + state.ep_states[ep_num].in_waker.wake(); + trace!("in ep={} irq val={:08x}", ep_num, ep_ints.0); + } + + ep_mask >>= 1; + ep_num += 1; + } + } + + // not needed? reception handled in rxflvl + // OUT endpoint interrupt + // if ints.oepint() { + // let mut ep_mask = r.daint().read().oepint(); + // let mut ep_num = 0; + + // while ep_mask != 0 { + // if ep_mask & 1 != 0 { + // let ep_ints = r.doepint(ep_num).read(); + // // clear all + // r.doepint(ep_num).write_value(ep_ints); + // state.ep_out_wakers[ep_num].wake(); + // trace!("out ep={} irq val={:08x}", ep_num, ep_ints.0); + // } + + // ep_mask >>= 1; + // ep_num += 1; + // } + // } +} /// USB PHY type #[derive(Copy, Clone, Debug, Eq, PartialEq)] @@ -199,6 +179,8 @@ pub enum PhyType { /// /// Available on a few STM32 chips. InternalHighSpeed, + /// External ULPI Full-Speed PHY (or High-Speed PHY in Full-Speed mode) + ExternalFullSpeed, /// External ULPI High-Speed PHY ExternalHighSpeed, } @@ -208,14 +190,14 @@ impl PhyType { pub fn internal(&self) -> bool { match self { PhyType::InternalFullSpeed | PhyType::InternalHighSpeed => true, - PhyType::ExternalHighSpeed => false, + PhyType::ExternalHighSpeed | PhyType::ExternalFullSpeed => false, } } /// Get whether this PHY is any of the high-speed types. pub fn high_speed(&self) -> bool { match self { - PhyType::InternalFullSpeed => false, + PhyType::InternalFullSpeed | PhyType::ExternalFullSpeed => false, PhyType::ExternalHighSpeed | PhyType::InternalHighSpeed => true, } } @@ -224,6 +206,7 @@ impl PhyType { match self { PhyType::InternalFullSpeed => vals::Dspd::FULL_SPEED_INTERNAL, PhyType::InternalHighSpeed => vals::Dspd::HIGH_SPEED, + PhyType::ExternalFullSpeed => vals::Dspd::FULL_SPEED_EXTERNAL, PhyType::ExternalHighSpeed => vals::Dspd::HIGH_SPEED, } } @@ -232,17 +215,31 @@ impl PhyType { /// Indicates that [State::ep_out_buffers] is empty. const EP_OUT_BUFFER_EMPTY: u16 = u16::MAX; -/// USB OTG driver state. -pub struct State { - /// Holds received SETUP packets. Available if [State::ep0_setup_ready] is true. - ep0_setup_data: UnsafeCell<[u8; 8]>, - ep0_setup_ready: AtomicBool, - ep_in_wakers: [AtomicWaker; EP_COUNT], - ep_out_wakers: [AtomicWaker; EP_COUNT], +struct EpState { + in_waker: AtomicWaker, + out_waker: AtomicWaker, /// RX FIFO is shared so extra buffers are needed to dequeue all data without waiting on each endpoint. /// Buffers are ready when associated [State::ep_out_size] != [EP_OUT_BUFFER_EMPTY]. - ep_out_buffers: [UnsafeCell<*mut u8>; EP_COUNT], - ep_out_size: [AtomicU16; EP_COUNT], + out_buffer: UnsafeCell<*mut u8>, + out_size: AtomicU16, +} + +// SAFETY: The EndpointAllocator ensures that the buffer points to valid memory exclusive for each endpoint and is +// large enough to hold the maximum packet size. Access to the buffer is synchronized between the USB interrupt and the +// EndpointOut impl using the out_size atomic variable. +unsafe impl Send for EpState {} +unsafe impl Sync for EpState {} + +struct ControlPipeSetupState { + /// Holds received SETUP packets. Available if [Ep0State::setup_ready] is true. + setup_data: UnsafeCell<[u8; 8]>, + setup_ready: AtomicBool, +} + +/// USB OTG driver state. +pub struct State { + cp_state: ControlPipeSetupState, + ep_states: [EpState; EP_COUNT], bus_waker: AtomicWaker, } @@ -255,14 +252,19 @@ impl State { const NEW_AW: AtomicWaker = AtomicWaker::new(); const NEW_BUF: UnsafeCell<*mut u8> = UnsafeCell::new(0 as _); const NEW_SIZE: AtomicU16 = AtomicU16::new(EP_OUT_BUFFER_EMPTY); + const NEW_EP_STATE: EpState = EpState { + in_waker: NEW_AW, + out_waker: NEW_AW, + out_buffer: NEW_BUF, + out_size: NEW_SIZE, + }; Self { - ep0_setup_data: UnsafeCell::new([0u8; 8]), - ep0_setup_ready: AtomicBool::new(false), - ep_in_wakers: [NEW_AW; EP_COUNT], - ep_out_wakers: [NEW_AW; EP_COUNT], - ep_out_buffers: [NEW_BUF; EP_COUNT], - ep_out_size: [NEW_SIZE; EP_COUNT], + cp_state: ControlPipeSetupState { + setup_data: UnsafeCell::new([0u8; 8]), + setup_ready: AtomicBool::new(false), + }, + ep_states: [NEW_EP_STATE; EP_COUNT], bus_waker: NEW_AW, } } @@ -282,10 +284,10 @@ pub struct Config { /// Enable VBUS detection. /// /// The USB spec requires USB devices monitor for USB cable plug/unplug and react accordingly. - /// This is done by checkihg whether there is 5V on the VBUS pin or not. + /// This is done by checking whether there is 5V on the VBUS pin or not. /// /// If your device is bus-powered (powers itself from the USB host via VBUS), then this is optional. - /// (if there's no power in VBUS your device would be off anyway, so it's fine to always assume + /// (If there's no power in VBUS your device would be off anyway, so it's fine to always assume /// there's power in VBUS, i.e. the USB cable is always plugged in.) /// /// If your device is self-powered (i.e. it gets power from a source other than the USB cable, and @@ -294,111 +296,68 @@ pub struct Config { /// If you set this to true, you must connect VBUS to PA9 for FS, PB13 for HS, possibly with a /// voltage divider. See ST application note AN4879 and the reference manual for more details. pub vbus_detection: bool, + + /// Enable transceiver delay. + /// + /// Some ULPI PHYs like the Microchip USB334x series require a delay between the ULPI register write that initiates + /// the HS Chirp and the subsequent transmit command, otherwise the HS Chirp does not get executed and the deivce + /// enumerates in FS mode. Some USB Link IP like those in the STM32H7 series support adding this delay to work with + /// the affected PHYs. + pub xcvrdly: bool, } impl Default for Config { fn default() -> Self { - Self { vbus_detection: true } + Self { + vbus_detection: false, + xcvrdly: false, + } } } -/// USB driver. -pub struct Driver<'d, T: Instance> { +/// USB OTG driver. +pub struct Driver<'d, const MAX_EP_COUNT: usize> { config: Config, - phantom: PhantomData<&'d mut T>, ep_in: [Option; MAX_EP_COUNT], ep_out: [Option; MAX_EP_COUNT], ep_out_buffer: &'d mut [u8], ep_out_buffer_offset: usize, - phy_type: PhyType, + instance: OtgInstance<'d, MAX_EP_COUNT>, } -impl<'d, T: Instance> Driver<'d, T> { - /// Initializes USB OTG peripheral with internal Full-Speed PHY. +impl<'d, const MAX_EP_COUNT: usize> Driver<'d, MAX_EP_COUNT> { + /// Initializes the USB OTG peripheral. /// /// # Arguments /// - /// * `ep_out_buffer` - An internal buffer used to temporarily store recevied packets. + /// * `ep_out_buffer` - An internal buffer used to temporarily store received packets. /// Must be large enough to fit all OUT endpoint max packet sizes. /// Endpoint allocation will fail if it is too small. - pub fn new_fs( - _peri: impl Peripheral

+ 'd, - _irq: impl interrupt::typelevel::Binding> + 'd, - dp: impl Peripheral

> + 'd, - dm: impl Peripheral

> + 'd, - ep_out_buffer: &'d mut [u8], - config: Config, - ) -> Self { - into_ref!(dp, dm); - - dp.set_as_af(dp.af_num(), AFType::OutputPushPull); - dm.set_as_af(dm.af_num(), AFType::OutputPushPull); - + /// * `instance` - The USB OTG peripheral instance and its configuration. + /// * `config` - The USB driver configuration. + pub fn new(ep_out_buffer: &'d mut [u8], instance: OtgInstance<'d, MAX_EP_COUNT>, config: Config) -> Self { Self { config, - phantom: PhantomData, ep_in: [None; MAX_EP_COUNT], ep_out: [None; MAX_EP_COUNT], ep_out_buffer, ep_out_buffer_offset: 0, - phy_type: PhyType::InternalFullSpeed, + instance, } } - /// Initializes USB OTG peripheral with external High-Speed PHY. - /// - /// # Arguments - /// - /// * `ep_out_buffer` - An internal buffer used to temporarily store recevied packets. - /// Must be large enough to fit all OUT endpoint max packet sizes. - /// Endpoint allocation will fail if it is too small. - pub fn new_hs_ulpi( - _peri: impl Peripheral

+ 'd, - _irq: impl interrupt::typelevel::Binding> + 'd, - ulpi_clk: impl Peripheral

> + 'd, - ulpi_dir: impl Peripheral

> + 'd, - ulpi_nxt: impl Peripheral

> + 'd, - ulpi_stp: impl Peripheral

> + 'd, - ulpi_d0: impl Peripheral

> + 'd, - ulpi_d1: impl Peripheral

> + 'd, - ulpi_d2: impl Peripheral

> + 'd, - ulpi_d3: impl Peripheral

> + 'd, - ulpi_d4: impl Peripheral

> + 'd, - ulpi_d5: impl Peripheral

> + 'd, - ulpi_d6: impl Peripheral

> + 'd, - ulpi_d7: impl Peripheral

> + 'd, - ep_out_buffer: &'d mut [u8], - config: Config, - ) -> Self { - assert!(T::HIGH_SPEED == true, "Peripheral is not capable of high-speed USB"); - - config_ulpi_pins!( - ulpi_clk, ulpi_dir, ulpi_nxt, ulpi_stp, ulpi_d0, ulpi_d1, ulpi_d2, ulpi_d3, ulpi_d4, ulpi_d5, ulpi_d6, - ulpi_d7 - ); - - Self { - config, - phantom: PhantomData, - ep_in: [None; MAX_EP_COUNT], - ep_out: [None; MAX_EP_COUNT], - ep_out_buffer, - ep_out_buffer_offset: 0, - phy_type: PhyType::ExternalHighSpeed, - } - } - - // Returns total amount of words (u32) allocated in dedicated FIFO + /// Returns the total amount of words (u32) allocated in dedicated FIFO. fn allocated_fifo_words(&self) -> u16 { - RX_FIFO_EXTRA_SIZE_WORDS + ep_fifo_size(&self.ep_out) + ep_fifo_size(&self.ep_in) + self.instance.extra_rx_fifo_words + ep_fifo_size(&self.ep_out) + ep_fifo_size(&self.ep_in) } + /// Creates an [`Endpoint`] with the given parameters. fn alloc_endpoint( &mut self, ep_type: EndpointType, max_packet_size: u16, interval_ms: u8, - ) -> Result, EndpointAllocError> { + ) -> Result, EndpointAllocError> { trace!( "allocating type={:?} mps={:?} interval_ms={}, dir={:?}", ep_type, @@ -420,14 +379,14 @@ impl<'d, T: Instance> Driver<'d, T> { Direction::In => u16::max((max_packet_size + 3) / 4, 16), }; - if fifo_size_words + self.allocated_fifo_words() > T::FIFO_DEPTH_WORDS { + if fifo_size_words + self.allocated_fifo_words() > self.instance.fifo_depth_words { error!("Not enough FIFO capacity"); return Err(EndpointAllocError); } let eps = match D::dir() { - Direction::Out => &mut self.ep_out, - Direction::In => &mut self.ep_in, + Direction::Out => &mut self.ep_out[..self.instance.endpoint_count], + Direction::In => &mut self.ep_in[..self.instance.endpoint_count], }; // Find free endpoint slot @@ -457,17 +416,19 @@ impl<'d, T: Instance> Driver<'d, T> { trace!(" index={}", index); + let state = &self.instance.state.ep_states[index]; if D::dir() == Direction::Out { // Buffer capacity check was done above, now allocation cannot fail unsafe { - *T::state().ep_out_buffers[index].get() = - self.ep_out_buffer.as_mut_ptr().offset(self.ep_out_buffer_offset as _); + *state.out_buffer.get() = self.ep_out_buffer.as_mut_ptr().offset(self.ep_out_buffer_offset as _); } self.ep_out_buffer_offset += max_packet_size as usize; } Ok(Endpoint { _phantom: PhantomData, + regs: self.instance.regs, + state, info: EndpointInfo { addr: EndpointAddress::from_parts(index, D::dir()), ep_type, @@ -478,11 +439,11 @@ impl<'d, T: Instance> Driver<'d, T> { } } -impl<'d, T: Instance> embassy_usb_driver::Driver<'d> for Driver<'d, T> { - type EndpointOut = Endpoint<'d, T, Out>; - type EndpointIn = Endpoint<'d, T, In>; - type ControlPipe = ControlPipe<'d, T>; - type Bus = Bus<'d, T>; +impl<'d, const MAX_EP_COUNT: usize> embassy_usb_driver::Driver<'d> for Driver<'d, MAX_EP_COUNT> { + type EndpointOut = Endpoint<'d, Out>; + type EndpointIn = Endpoint<'d, In>; + type ControlPipe = ControlPipe<'d>; + type Bus = Bus<'d, MAX_EP_COUNT>; fn alloc_endpoint_in( &mut self, @@ -514,38 +475,41 @@ impl<'d, T: Instance> embassy_usb_driver::Driver<'d> for Driver<'d, T> { trace!("start"); + let regs = self.instance.regs; + let quirk_setup_late_cnak = self.instance.quirk_setup_late_cnak; + let cp_setup_state = &self.instance.state.cp_state; ( Bus { config: self.config, - phantom: PhantomData, ep_in: self.ep_in, ep_out: self.ep_out, - phy_type: self.phy_type, inited: false, + instance: self.instance, }, ControlPipe { - _phantom: PhantomData, max_packet_size: control_max_packet_size, + setup_state: cp_setup_state, ep_out, ep_in, + regs, + quirk_setup_late_cnak, }, ) } } /// USB bus. -pub struct Bus<'d, T: Instance> { +pub struct Bus<'d, const MAX_EP_COUNT: usize> { config: Config, - phantom: PhantomData<&'d mut T>, ep_in: [Option; MAX_EP_COUNT], ep_out: [Option; MAX_EP_COUNT], - phy_type: PhyType, + instance: OtgInstance<'d, MAX_EP_COUNT>, inited: bool, } -impl<'d, T: Instance> Bus<'d, T> { - fn restore_irqs() { - T::regs().gintmsk().write(|w| { +impl<'d, const MAX_EP_COUNT: usize> Bus<'d, MAX_EP_COUNT> { + fn restore_irqs(&mut self) { + self.instance.regs.gintmsk().write(|w| { w.set_usbrst(true); w.set_enumdnem(true); w.set_usbsuspm(true); @@ -557,161 +521,95 @@ impl<'d, T: Instance> Bus<'d, T> { w.set_otgint(true); }); } -} -impl<'d, T: Instance> Bus<'d, T> { - fn init(&mut self) { - #[cfg(stm32l4)] - critical_section::with(|_| crate::pac::PWR.cr2().modify(|w| w.set_usv(true))); + /// Returns the PHY type. + pub fn phy_type(&self) -> PhyType { + self.instance.phy_type + } - #[cfg(stm32f7)] - { - // Enable ULPI clock if external PHY is used - let ulpien = !self.phy_type.internal(); - critical_section::with(|_| { - crate::pac::RCC.ahb1enr().modify(|w| { - if T::HIGH_SPEED { - w.set_usb_otg_hsulpien(ulpien); - } else { - w.set_usb_otg_hsen(ulpien); - } - }); - - // Low power mode - crate::pac::RCC.ahb1lpenr().modify(|w| { - if T::HIGH_SPEED { - w.set_usb_otg_hsulpilpen(ulpien); - } else { - w.set_usb_otg_hslpen(ulpien); - } - }); - }); - } - - #[cfg(stm32h7)] - { - // If true, VDD33USB is generated by internal regulator from VDD50USB - // If false, VDD33USB and VDD50USB must be suplied directly with 3.3V (default on nucleo) - // TODO: unhardcode - let internal_regulator = false; - - // Enable USB power - critical_section::with(|_| { - crate::pac::PWR.cr3().modify(|w| { - w.set_usb33den(true); - w.set_usbregen(internal_regulator); - }) - }); - - // Wait for USB power to stabilize - while !crate::pac::PWR.cr3().read().usb33rdy() {} - - // Use internal 48MHz HSI clock. Should be enabled in RCC by default. - critical_section::with(|_| { - crate::pac::RCC - .d2ccip2r() - .modify(|w| w.set_usbsel(crate::pac::rcc::vals::Usbsel::HSI48)) - }); - - // Enable ULPI clock if external PHY is used - let ulpien = !self.phy_type.internal(); - critical_section::with(|_| { - crate::pac::RCC.ahb1enr().modify(|w| { - if T::HIGH_SPEED { - w.set_usb_otg_hs_ulpien(ulpien); - } else { - w.set_usb_otg_fs_ulpien(ulpien); - } - }); - crate::pac::RCC.ahb1lpenr().modify(|w| { - if T::HIGH_SPEED { - w.set_usb_otg_hs_ulpilpen(ulpien); - } else { - w.set_usb_otg_fs_ulpilpen(ulpien); - } - }); - }); - } - - #[cfg(stm32u5)] - { - // Enable USB power - critical_section::with(|_| { - crate::pac::PWR.svmcr().modify(|w| { - w.set_usv(true); - w.set_uvmen(true); - }) - }); - - // Wait for USB power to stabilize - while !crate::pac::PWR.svmsr().read().vddusbrdy() {} - - // Select HSI48 as USB clock source. - critical_section::with(|_| { - crate::pac::RCC.ccipr1().modify(|w| { - w.set_iclksel(crate::pac::rcc::vals::Iclksel::HSI48); - }) - }); - } - - ::enable_and_reset(); - - T::Interrupt::unpend(); - unsafe { T::Interrupt::enable() }; - - let r = T::regs(); - let core_id = r.cid().read().0; - trace!("Core id {:08x}", core_id); - - // Wait for AHB ready. - while !r.grstctl().read().ahbidl() {} - - // Configure as device. + /// Configures the PHY as a device. + pub fn configure_as_device(&mut self) { + let r = self.instance.regs; + let phy_type = self.instance.phy_type; r.gusbcfg().write(|w| { // Force device mode w.set_fdmod(true); // Enable internal full-speed PHY - w.set_physel(self.phy_type.internal() && !self.phy_type.high_speed()); + w.set_physel(phy_type.internal() && !phy_type.high_speed()); + }); + } + + /// Applies configuration specific to + /// Core ID 0x0000_1100 and 0x0000_1200 + pub fn config_v1(&mut self) { + let r = self.instance.regs; + let phy_type = self.instance.phy_type; + assert!(phy_type != PhyType::InternalHighSpeed); + + r.gccfg_v1().modify(|w| { + // Enable internal full-speed PHY, logic is inverted + w.set_pwrdwn(phy_type.internal()); }); - // Configuring Vbus sense and SOF output - match core_id { - 0x0000_1200 | 0x0000_1100 => { - assert!(self.phy_type != PhyType::InternalHighSpeed); + // F429-like chips have the GCCFG.NOVBUSSENS bit + r.gccfg_v1().modify(|w| { + w.set_novbussens(!self.config.vbus_detection); + w.set_vbusasen(false); + w.set_vbusbsen(self.config.vbus_detection); + w.set_sofouten(false); + }); + } - r.gccfg_v1().modify(|w| { - // Enable internal full-speed PHY, logic is inverted - w.set_pwrdwn(self.phy_type.internal()); - }); + /// Applies configuration specific to + /// Core ID 0x0000_2000, 0x0000_2100, 0x0000_2300, 0x0000_3000 and 0x0000_3100 + pub fn config_v2v3(&mut self) { + let r = self.instance.regs; + let phy_type = self.instance.phy_type; - // F429-like chips have the GCCFG.NOVBUSSENS bit - r.gccfg_v1().modify(|w| { - w.set_novbussens(!self.config.vbus_detection); - w.set_vbusasen(false); - w.set_vbusbsen(self.config.vbus_detection); - w.set_sofouten(false); - }); - } - 0x0000_2000 | 0x0000_2100 | 0x0000_2300 | 0x0000_3000 | 0x0000_3100 => { - // F446-like chips have the GCCFG.VBDEN bit with the opposite meaning - r.gccfg_v2().modify(|w| { - // Enable internal full-speed PHY, logic is inverted - w.set_pwrdwn(self.phy_type.internal() && !self.phy_type.high_speed()); - w.set_phyhsen(self.phy_type.internal() && self.phy_type.high_speed()); - }); + // F446-like chips have the GCCFG.VBDEN bit with the opposite meaning + r.gccfg_v2().modify(|w| { + // Enable internal full-speed PHY, logic is inverted + w.set_pwrdwn(phy_type.internal() && !phy_type.high_speed()); + w.set_phyhsen(phy_type.internal() && phy_type.high_speed()); + }); - r.gccfg_v2().modify(|w| { - w.set_vbden(self.config.vbus_detection); - }); + r.gccfg_v2().modify(|w| { + w.set_vbden(self.config.vbus_detection); + }); - // Force B-peripheral session - r.gotgctl().modify(|w| { - w.set_bvaloen(!self.config.vbus_detection); - w.set_bvaloval(true); - }); - } - _ => unimplemented!("Unknown USB core id {:X}", core_id), + // Force B-peripheral session + r.gotgctl().modify(|w| { + w.set_bvaloen(!self.config.vbus_detection); + w.set_bvaloval(true); + }); + } + + /// Applies configuration specific to + /// Core ID 0x0000_5000 + pub fn config_v5(&mut self) { + let r = self.instance.regs; + let phy_type = self.instance.phy_type; + + if phy_type == PhyType::InternalHighSpeed { + r.gccfg_v3().modify(|w| { + w.set_vbvaloven(!self.config.vbus_detection); + w.set_vbvaloval(!self.config.vbus_detection); + w.set_vbden(self.config.vbus_detection); + }); + } else { + r.gotgctl().modify(|w| { + w.set_bvaloen(!self.config.vbus_detection); + w.set_bvaloval(!self.config.vbus_detection); + }); + r.gccfg_v3().modify(|w| { + w.set_vbden(self.config.vbus_detection); + }); } + } + + fn init(&mut self) { + let r = self.instance.regs; + let phy_type = self.instance.phy_type; // Soft disconnect. r.dctl().write(|w| w.set_sdis(true)); @@ -719,7 +617,10 @@ impl<'d, T: Instance> Bus<'d, T> { // Set speed. r.dcfg().write(|w| { w.set_pfivl(vals::Pfivl::FRAME_INTERVAL_80); - w.set_dspd(self.phy_type.to_dspd()); + w.set_dspd(phy_type.to_dspd()); + if self.config.xcvrdly { + w.set_xcvrdly(true); + } }); // Unmask transfer complete EP interrupt @@ -728,7 +629,7 @@ impl<'d, T: Instance> Bus<'d, T> { }); // Unmask and clear core interrupts - Bus::::restore_irqs(); + self.restore_irqs(); r.gintsts().write_value(regs::Gintsts(0xFFFF_FFFF)); // Unmask global interrupt @@ -743,49 +644,54 @@ impl<'d, T: Instance> Bus<'d, T> { fn init_fifo(&mut self) { trace!("init_fifo"); - let r = T::regs(); + let regs = self.instance.regs; + // ERRATA NOTE: Don't interrupt FIFOs being written to. The interrupt + // handler COULD interrupt us here and do FIFO operations, so ensure + // the interrupt does not occur. + critical_section::with(|_| { + // Configure RX fifo size. All endpoints share the same FIFO area. + let rx_fifo_size_words = self.instance.extra_rx_fifo_words + ep_fifo_size(&self.ep_out); + trace!("configuring rx fifo size={}", rx_fifo_size_words); - // Configure RX fifo size. All endpoints share the same FIFO area. - let rx_fifo_size_words = RX_FIFO_EXTRA_SIZE_WORDS + ep_fifo_size(&self.ep_out); - trace!("configuring rx fifo size={}", rx_fifo_size_words); + regs.grxfsiz().modify(|w| w.set_rxfd(rx_fifo_size_words)); - r.grxfsiz().modify(|w| w.set_rxfd(rx_fifo_size_words)); + // Configure TX (USB in direction) fifo size for each endpoint + let mut fifo_top = rx_fifo_size_words; + for i in 0..self.instance.endpoint_count { + if let Some(ep) = self.ep_in[i] { + trace!( + "configuring tx fifo ep={}, offset={}, size={}", + i, + fifo_top, + ep.fifo_size_words + ); - // Configure TX (USB in direction) fifo size for each endpoint - let mut fifo_top = rx_fifo_size_words; - for i in 0..T::ENDPOINT_COUNT { - if let Some(ep) = self.ep_in[i] { - trace!( - "configuring tx fifo ep={}, offset={}, size={}", - i, - fifo_top, - ep.fifo_size_words - ); + let dieptxf = if i == 0 { regs.dieptxf0() } else { regs.dieptxf(i - 1) }; - let dieptxf = if i == 0 { r.dieptxf0() } else { r.dieptxf(i - 1) }; + dieptxf.write(|w| { + w.set_fd(ep.fifo_size_words); + w.set_sa(fifo_top); + }); - dieptxf.write(|w| { - w.set_fd(ep.fifo_size_words); - w.set_sa(fifo_top); - }); - - fifo_top += ep.fifo_size_words; + fifo_top += ep.fifo_size_words; + } } - } - assert!( - fifo_top <= T::FIFO_DEPTH_WORDS, - "FIFO allocations exceeded maximum capacity" - ); + assert!( + fifo_top <= self.instance.fifo_depth_words, + "FIFO allocations exceeded maximum capacity" + ); - // Flush fifos - r.grstctl().write(|w| { - w.set_rxfflsh(true); - w.set_txfflsh(true); - w.set_txfnum(0x10); + // Flush fifos + regs.grstctl().write(|w| { + w.set_rxfflsh(true); + w.set_txfflsh(true); + w.set_txfnum(0x10); + }); }); + loop { - let x = r.grstctl().read(); + let x = regs.grstctl().read(); if !x.rxfflsh() && !x.txfflsh() { break; } @@ -795,13 +701,13 @@ impl<'d, T: Instance> Bus<'d, T> { fn configure_endpoints(&mut self) { trace!("configure_endpoints"); - let r = T::regs(); + let regs = self.instance.regs; // Configure IN endpoints for (index, ep) in self.ep_in.iter().enumerate() { if let Some(ep) = ep { critical_section::with(|_| { - r.diepctl(index).write(|w| { + regs.diepctl(index).write(|w| { if index == 0 { w.set_mpsiz(ep0_mpsiz(ep.max_packet_size)); } else { @@ -820,7 +726,7 @@ impl<'d, T: Instance> Bus<'d, T> { for (index, ep) in self.ep_out.iter().enumerate() { if let Some(ep) = ep { critical_section::with(|_| { - r.doepctl(index).write(|w| { + regs.doepctl(index).write(|w| { if index == 0 { w.set_mpsiz(ep0_mpsiz(ep.max_packet_size)); } else { @@ -830,7 +736,7 @@ impl<'d, T: Instance> Bus<'d, T> { } }); - r.doeptsiz(index).modify(|w| { + regs.doeptsiz(index).modify(|w| { w.set_xfrsiz(ep.max_packet_size as _); if index == 0 { w.set_rxdpid_stupcnt(1); @@ -843,7 +749,7 @@ impl<'d, T: Instance> Bus<'d, T> { } // Enable IRQs for allocated endpoints - r.daintmsk().modify(|w| { + regs.daintmsk().modify(|w| { w.set_iepm(ep_irq_mask(&self.ep_in)); // OUT interrupts not used, handled in RXFLVL // w.set_oepm(ep_irq_mask(&self.ep_out)); @@ -851,24 +757,14 @@ impl<'d, T: Instance> Bus<'d, T> { } fn disable_all_endpoints(&mut self) { - for i in 0..T::ENDPOINT_COUNT { + for i in 0..self.instance.endpoint_count { self.endpoint_set_enabled(EndpointAddress::from_parts(i, Direction::In), false); self.endpoint_set_enabled(EndpointAddress::from_parts(i, Direction::Out), false); } } - - fn disable(&mut self) { - T::Interrupt::disable(); - - ::disable(); - - #[cfg(stm32l4)] - crate::pac::PWR.cr2().modify(|w| w.set_usv(false)); - // Cannot disable PWR, because other peripherals might be using it - } } -impl<'d, T: Instance> embassy_usb_driver::Bus for Bus<'d, T> { +impl<'d, const MAX_EP_COUNT: usize> embassy_usb_driver::Bus for Bus<'d, MAX_EP_COUNT> { async fn poll(&mut self) -> Event { poll_fn(move |cx| { if !self.inited { @@ -881,17 +777,16 @@ impl<'d, T: Instance> embassy_usb_driver::Bus for Bus<'d, T> { } } - let r = T::regs(); + let regs = self.instance.regs; + self.instance.state.bus_waker.register(cx.waker()); - T::state().bus_waker.register(cx.waker()); - - let ints = r.gintsts().read(); + let ints = regs.gintsts().read(); if ints.srqint() { trace!("vbus detected"); - r.gintsts().write(|w| w.set_srqint(true)); // clear - Self::restore_irqs(); + regs.gintsts().write(|w| w.set_srqint(true)); // clear + self.restore_irqs(); if self.config.vbus_detection { return Poll::Ready(Event::PowerDetected); @@ -899,9 +794,9 @@ impl<'d, T: Instance> embassy_usb_driver::Bus for Bus<'d, T> { } if ints.otgint() { - let otgints = r.gotgint().read(); - r.gotgint().write_value(otgints); // clear all - Self::restore_irqs(); + let otgints = regs.gotgint().read(); + regs.gotgint().write_value(otgints); // clear all + self.restore_irqs(); if otgints.sedet() { trace!("vbus removed"); @@ -920,40 +815,40 @@ impl<'d, T: Instance> embassy_usb_driver::Bus for Bus<'d, T> { // Reset address critical_section::with(|_| { - r.dcfg().modify(|w| { + regs.dcfg().modify(|w| { w.set_dad(0); }); }); - r.gintsts().write(|w| w.set_usbrst(true)); // clear - Self::restore_irqs(); + regs.gintsts().write(|w| w.set_usbrst(true)); // clear + self.restore_irqs(); } if ints.enumdne() { trace!("enumdne"); - let speed = r.dsts().read().enumspd(); - let trdt = calculate_trdt(speed, T::frequency()); + let speed = regs.dsts().read().enumspd(); + let trdt = (self.instance.calculate_trdt_fn)(speed); trace!(" speed={} trdt={}", speed.to_bits(), trdt); - r.gusbcfg().modify(|w| w.set_trdt(trdt)); + regs.gusbcfg().modify(|w| w.set_trdt(trdt)); - r.gintsts().write(|w| w.set_enumdne(true)); // clear - Self::restore_irqs(); + regs.gintsts().write(|w| w.set_enumdne(true)); // clear + self.restore_irqs(); return Poll::Ready(Event::Reset); } if ints.usbsusp() { trace!("suspend"); - r.gintsts().write(|w| w.set_usbsusp(true)); // clear - Self::restore_irqs(); + regs.gintsts().write(|w| w.set_usbsusp(true)); // clear + self.restore_irqs(); return Poll::Ready(Event::Suspend); } if ints.wkupint() { trace!("resume"); - r.gintsts().write(|w| w.set_wkupint(true)); // clear - Self::restore_irqs(); + regs.gintsts().write(|w| w.set_wkupint(true)); // clear + self.restore_irqs(); return Poll::Ready(Event::Resume); } @@ -966,12 +861,13 @@ impl<'d, T: Instance> embassy_usb_driver::Bus for Bus<'d, T> { trace!("endpoint_set_stalled ep={:?} en={}", ep_addr, stalled); assert!( - ep_addr.index() < T::ENDPOINT_COUNT, + ep_addr.index() < self.instance.endpoint_count, "endpoint_set_stalled index {} out of range", ep_addr.index() ); - let regs = T::regs(); + let regs = self.instance.regs; + let state = self.instance.state; match ep_addr.direction() { Direction::Out => { critical_section::with(|_| { @@ -980,7 +876,7 @@ impl<'d, T: Instance> embassy_usb_driver::Bus for Bus<'d, T> { }); }); - T::state().ep_out_wakers[ep_addr.index()].wake(); + state.ep_states[ep_addr.index()].out_waker.wake(); } Direction::In => { critical_section::with(|_| { @@ -989,20 +885,19 @@ impl<'d, T: Instance> embassy_usb_driver::Bus for Bus<'d, T> { }); }); - T::state().ep_in_wakers[ep_addr.index()].wake(); + state.ep_states[ep_addr.index()].in_waker.wake(); } } } fn endpoint_is_stalled(&mut self, ep_addr: EndpointAddress) -> bool { assert!( - ep_addr.index() < T::ENDPOINT_COUNT, + ep_addr.index() < self.instance.endpoint_count, "endpoint_is_stalled index {} out of range", ep_addr.index() ); - let regs = T::regs(); - + let regs = self.instance.regs; match ep_addr.direction() { Direction::Out => regs.doepctl(ep_addr.index()).read().stall(), Direction::In => regs.diepctl(ep_addr.index()).read().stall(), @@ -1013,34 +908,35 @@ impl<'d, T: Instance> embassy_usb_driver::Bus for Bus<'d, T> { trace!("endpoint_set_enabled ep={:?} en={}", ep_addr, enabled); assert!( - ep_addr.index() < T::ENDPOINT_COUNT, + ep_addr.index() < self.instance.endpoint_count, "endpoint_set_enabled index {} out of range", ep_addr.index() ); - let r = T::regs(); + let regs = self.instance.regs; + let state = self.instance.state; match ep_addr.direction() { Direction::Out => { critical_section::with(|_| { // cancel transfer if active - if !enabled && r.doepctl(ep_addr.index()).read().epena() { - r.doepctl(ep_addr.index()).modify(|w| { + if !enabled && regs.doepctl(ep_addr.index()).read().epena() { + regs.doepctl(ep_addr.index()).modify(|w| { w.set_snak(true); w.set_epdis(true); }) } - r.doepctl(ep_addr.index()).modify(|w| { + regs.doepctl(ep_addr.index()).modify(|w| { w.set_usbaep(enabled); }); // Flush tx fifo - r.grstctl().write(|w| { + regs.grstctl().write(|w| { w.set_txfflsh(true); w.set_txfnum(ep_addr.index() as _); }); loop { - let x = r.grstctl().read(); + let x = regs.grstctl().read(); if !x.txfflsh() { break; } @@ -1048,26 +944,26 @@ impl<'d, T: Instance> embassy_usb_driver::Bus for Bus<'d, T> { }); // Wake `Endpoint::wait_enabled()` - T::state().ep_out_wakers[ep_addr.index()].wake(); + state.ep_states[ep_addr.index()].out_waker.wake(); } Direction::In => { critical_section::with(|_| { // cancel transfer if active - if !enabled && r.diepctl(ep_addr.index()).read().epena() { - r.diepctl(ep_addr.index()).modify(|w| { + if !enabled && regs.diepctl(ep_addr.index()).read().epena() { + regs.diepctl(ep_addr.index()).modify(|w| { w.set_snak(true); // set NAK w.set_epdis(true); }) } - r.diepctl(ep_addr.index()).modify(|w| { + regs.diepctl(ep_addr.index()).modify(|w| { w.set_usbaep(enabled); w.set_cnak(enabled); // clear NAK that might've been set by SNAK above. }) }); // Wake `Endpoint::wait_enabled()` - T::state().ep_in_wakers[ep_addr.index()].wake(); + state.ep_states[ep_addr.index()].in_waker.wake(); } } } @@ -1089,13 +985,9 @@ impl<'d, T: Instance> embassy_usb_driver::Bus for Bus<'d, T> { } } -impl<'d, T: Instance> Drop for Bus<'d, T> { - fn drop(&mut self) { - Bus::disable(self); - } -} - +/// USB endpoint direction. trait Dir { + /// Returns the direction value. fn dir() -> Direction; } @@ -1116,12 +1008,14 @@ impl Dir for Out { } /// USB endpoint. -pub struct Endpoint<'d, T: Instance, D> { - _phantom: PhantomData<(&'d mut T, D)>, +pub struct Endpoint<'d, D> { + _phantom: PhantomData, + regs: Otg, info: EndpointInfo, + state: &'d EpState, } -impl<'d, T: Instance> embassy_usb_driver::Endpoint for Endpoint<'d, T, In> { +impl<'d> embassy_usb_driver::Endpoint for Endpoint<'d, In> { fn info(&self) -> &EndpointInfo { &self.info } @@ -1130,9 +1024,9 @@ impl<'d, T: Instance> embassy_usb_driver::Endpoint for Endpoint<'d, T, In> { poll_fn(|cx| { let ep_index = self.info.addr.index(); - T::state().ep_in_wakers[ep_index].register(cx.waker()); + self.state.in_waker.register(cx.waker()); - if T::regs().diepctl(ep_index).read().usbaep() { + if self.regs.diepctl(ep_index).read().usbaep() { Poll::Ready(()) } else { Poll::Pending @@ -1142,7 +1036,7 @@ impl<'d, T: Instance> embassy_usb_driver::Endpoint for Endpoint<'d, T, In> { } } -impl<'d, T: Instance> embassy_usb_driver::Endpoint for Endpoint<'d, T, Out> { +impl<'d> embassy_usb_driver::Endpoint for Endpoint<'d, Out> { fn info(&self) -> &EndpointInfo { &self.info } @@ -1151,9 +1045,9 @@ impl<'d, T: Instance> embassy_usb_driver::Endpoint for Endpoint<'d, T, Out> { poll_fn(|cx| { let ep_index = self.info.addr.index(); - T::state().ep_out_wakers[ep_index].register(cx.waker()); + self.state.out_waker.register(cx.waker()); - if T::regs().doepctl(ep_index).read().usbaep() { + if self.regs.doepctl(ep_index).read().usbaep() { Poll::Ready(()) } else { Poll::Pending @@ -1163,25 +1057,22 @@ impl<'d, T: Instance> embassy_usb_driver::Endpoint for Endpoint<'d, T, Out> { } } -impl<'d, T: Instance> embassy_usb_driver::EndpointOut for Endpoint<'d, T, Out> { +impl<'d> embassy_usb_driver::EndpointOut for Endpoint<'d, Out> { async fn read(&mut self, buf: &mut [u8]) -> Result { trace!("read start len={}", buf.len()); poll_fn(|cx| { - let r = T::regs(); let index = self.info.addr.index(); - let state = T::state(); + self.state.out_waker.register(cx.waker()); - state.ep_out_wakers[index].register(cx.waker()); - - let doepctl = r.doepctl(index).read(); + let doepctl = self.regs.doepctl(index).read(); trace!("read ep={:?}: doepctl {:08x}", self.info.addr, doepctl.0,); if !doepctl.usbaep() { trace!("read ep={:?} error disabled", self.info.addr); return Poll::Ready(Err(EndpointError::Disabled)); } - let len = state.ep_out_size[index].load(Ordering::Relaxed); + let len = self.state.out_size.load(Ordering::Relaxed); if len != EP_OUT_BUFFER_EMPTY { trace!("read ep={:?} done len={}", self.info.addr, len); @@ -1189,22 +1080,37 @@ impl<'d, T: Instance> embassy_usb_driver::EndpointOut for Endpoint<'d, T, Out> { return Poll::Ready(Err(EndpointError::BufferOverflow)); } - // SAFETY: exclusive access ensured by `ep_out_size` atomic variable - let data = unsafe { core::slice::from_raw_parts(*state.ep_out_buffers[index].get(), len as usize) }; + // SAFETY: exclusive access ensured by `out_size` atomic variable + let data = unsafe { core::slice::from_raw_parts(*self.state.out_buffer.get(), len as usize) }; buf[..len as usize].copy_from_slice(data); // Release buffer - state.ep_out_size[index].store(EP_OUT_BUFFER_EMPTY, Ordering::Release); + self.state.out_size.store(EP_OUT_BUFFER_EMPTY, Ordering::Release); critical_section::with(|_| { // Receive 1 packet - T::regs().doeptsiz(index).modify(|w| { + self.regs.doeptsiz(index).modify(|w| { w.set_xfrsiz(self.info.max_packet_size as _); w.set_pktcnt(1); }); + if self.info.ep_type == EndpointType::Isochronous { + // Isochronous endpoints must set the correct even/odd frame bit to + // correspond with the next frame's number. + let frame_number = self.regs.dsts().read().fnsof(); + let frame_is_odd = frame_number & 0x01 == 1; + + self.regs.doepctl(index).modify(|r| { + if frame_is_odd { + r.set_sd0pid_sevnfrm(true); + } else { + r.set_sd1pid_soddfrm(true); + } + }); + } + // Clear NAK to indicate we are ready to receive more data - T::regs().doepctl(index).modify(|w| { + self.regs.doepctl(index).modify(|w| { w.set_cnak(true); }); }); @@ -1218,7 +1124,7 @@ impl<'d, T: Instance> embassy_usb_driver::EndpointOut for Endpoint<'d, T, Out> { } } -impl<'d, T: Instance> embassy_usb_driver::EndpointIn for Endpoint<'d, T, In> { +impl<'d> embassy_usb_driver::EndpointIn for Endpoint<'d, In> { async fn write(&mut self, buf: &[u8]) -> Result<(), EndpointError> { trace!("write ep={:?} data={:?}", self.info.addr, buf); @@ -1226,16 +1132,13 @@ impl<'d, T: Instance> embassy_usb_driver::EndpointIn for Endpoint<'d, T, In> { return Err(EndpointError::BufferOverflow); } - let r = T::regs(); let index = self.info.addr.index(); - let state = T::state(); - // Wait for previous transfer to complete and check if endpoint is disabled poll_fn(|cx| { - state.ep_in_wakers[index].register(cx.waker()); + self.state.in_waker.register(cx.waker()); - let diepctl = r.diepctl(index).read(); - let dtxfsts = r.dtxfsts(index).read(); + let diepctl = self.regs.diepctl(index).read(); + let dtxfsts = self.regs.dtxfsts(index).read(); trace!( "write ep={:?}: diepctl {:08x} ftxfsts {:08x}", self.info.addr, @@ -1257,15 +1160,15 @@ impl<'d, T: Instance> embassy_usb_driver::EndpointIn for Endpoint<'d, T, In> { if buf.len() > 0 { poll_fn(|cx| { - state.ep_in_wakers[index].register(cx.waker()); + self.state.in_waker.register(cx.waker()); let size_words = (buf.len() + 3) / 4; - let fifo_space = r.dtxfsts(index).read().ineptfsav() as usize; + let fifo_space = self.regs.dtxfsts(index).read().ineptfsav() as usize; if size_words > fifo_space { // Not enough space in fifo, enable tx fifo empty interrupt critical_section::with(|_| { - r.diepempmsk().modify(|w| { + self.regs.diepempmsk().modify(|w| { w.set_ineptxfem(w.ineptxfem() | (1 << index)); }); }); @@ -1281,27 +1184,46 @@ impl<'d, T: Instance> embassy_usb_driver::EndpointIn for Endpoint<'d, T, In> { .await } - // Setup transfer size - r.dieptsiz(index).write(|w| { - w.set_mcnt(1); - w.set_pktcnt(1); - w.set_xfrsiz(buf.len() as _); - }); - + // ERRATA: Transmit data FIFO is corrupted when a write sequence to the FIFO is interrupted with + // accesses to certain OTG_FS registers. + // + // Prevent the interrupt (which might poke FIFOs) from executing while copying data to FIFOs. critical_section::with(|_| { + // Setup transfer size + self.regs.dieptsiz(index).write(|w| { + w.set_mcnt(1); + w.set_pktcnt(1); + w.set_xfrsiz(buf.len() as _); + }); + + if self.info.ep_type == EndpointType::Isochronous { + // Isochronous endpoints must set the correct even/odd frame bit to + // correspond with the next frame's number. + let frame_number = self.regs.dsts().read().fnsof(); + let frame_is_odd = frame_number & 0x01 == 1; + + self.regs.diepctl(index).modify(|r| { + if frame_is_odd { + r.set_sd0pid_sevnfrm(true); + } else { + r.set_sd1pid_soddfrm(true); + } + }); + } + // Enable endpoint - r.diepctl(index).modify(|w| { + self.regs.diepctl(index).modify(|w| { w.set_cnak(true); w.set_epena(true); }); - }); - // Write data to FIFO - for chunk in buf.chunks(4) { - let mut tmp = [0u8; 4]; - tmp[0..chunk.len()].copy_from_slice(chunk); - r.fifo(index).write_value(regs::Fifo(u32::from_ne_bytes(tmp))); - } + // Write data to FIFO + for chunk in buf.chunks(4) { + let mut tmp = [0u8; 4]; + tmp[0..chunk.len()].copy_from_slice(chunk); + self.regs.fifo(index).write_value(regs::Fifo(u32::from_ne_bytes(tmp))); + } + }); trace!("write done ep={:?}", self.info.addr); @@ -1310,39 +1232,39 @@ impl<'d, T: Instance> embassy_usb_driver::EndpointIn for Endpoint<'d, T, In> { } /// USB control pipe. -pub struct ControlPipe<'d, T: Instance> { - _phantom: PhantomData<&'d mut T>, +pub struct ControlPipe<'d> { max_packet_size: u16, - ep_in: Endpoint<'d, T, In>, - ep_out: Endpoint<'d, T, Out>, + regs: Otg, + setup_state: &'d ControlPipeSetupState, + ep_in: Endpoint<'d, In>, + ep_out: Endpoint<'d, Out>, + quirk_setup_late_cnak: bool, } -impl<'d, T: Instance> embassy_usb_driver::ControlPipe for ControlPipe<'d, T> { +impl<'d> embassy_usb_driver::ControlPipe for ControlPipe<'d> { fn max_packet_size(&self) -> usize { usize::from(self.max_packet_size) } async fn setup(&mut self) -> [u8; 8] { poll_fn(|cx| { - let state = T::state(); + self.ep_out.state.out_waker.register(cx.waker()); - state.ep_out_wakers[0].register(cx.waker()); - - let r = T::regs(); - - if state.ep0_setup_ready.load(Ordering::Relaxed) { - let data = unsafe { *state.ep0_setup_data.get() }; - state.ep0_setup_ready.store(false, Ordering::Release); + if self.setup_state.setup_ready.load(Ordering::Relaxed) { + let data = unsafe { *self.setup_state.setup_data.get() }; + self.setup_state.setup_ready.store(false, Ordering::Release); // EP0 should not be controlled by `Bus` so this RMW does not need a critical section // Receive 1 SETUP packet - r.doeptsiz(self.ep_out.info.addr.index()).modify(|w| { + self.regs.doeptsiz(self.ep_out.info.addr.index()).modify(|w| { w.set_rxdpid_stupcnt(1); }); // Clear NAK to indicate we are ready to receive more data - if !quirk_setup_late_cnak(r) { - r.doepctl(self.ep_out.info.addr.index()).modify(|w| w.set_cnak(true)); + if !self.quirk_setup_late_cnak { + self.regs + .doepctl(self.ep_out.info.addr.index()) + .modify(|w| w.set_cnak(true)); } trace!("SETUP received: {:?}", data); @@ -1388,11 +1310,10 @@ impl<'d, T: Instance> embassy_usb_driver::ControlPipe for ControlPipe<'d, T> { trace!("control: reject"); // EP0 should not be controlled by `Bus` so this RMW does not need a critical section - let regs = T::regs(); - regs.diepctl(self.ep_in.info.addr.index()).modify(|w| { + self.regs.diepctl(self.ep_in.info.addr.index()).modify(|w| { w.set_stall(true); }); - regs.doepctl(self.ep_out.info.addr.index()).modify(|w| { + self.regs.doepctl(self.ep_out.info.addr.index()).modify(|w| { w.set_stall(true); }); } @@ -1400,7 +1321,7 @@ impl<'d, T: Instance> embassy_usb_driver::ControlPipe for ControlPipe<'d, T> { async fn accept_set_address(&mut self, addr: u8) { trace!("setting addr: {}", addr); critical_section::with(|_| { - T::regs().dcfg().modify(|w| { + self.regs.dcfg().modify(|w| { w.set_dad(addr); }); }); @@ -1450,36 +1371,22 @@ fn ep0_mpsiz(max_packet_size: u16) -> u16 { } } -fn calculate_trdt(speed: vals::Dspd, ahb_freq: Hertz) -> u8 { - match speed { - vals::Dspd::HIGH_SPEED => { - // From RM0431 (F72xx), RM0090 (F429), RM0390 (F446) - if ahb_freq.0 >= 30_000_000 { - 0x9 - } else { - panic!("AHB frequency is too low") - } - } - vals::Dspd::FULL_SPEED_EXTERNAL | vals::Dspd::FULL_SPEED_INTERNAL => { - // From RM0431 (F72xx), RM0090 (F429) - match ahb_freq.0 { - 0..=14_199_999 => panic!("AHB frequency is too low"), - 14_200_000..=14_999_999 => 0xF, - 15_000_000..=15_999_999 => 0xE, - 16_000_000..=17_199_999 => 0xD, - 17_200_000..=18_499_999 => 0xC, - 18_500_000..=19_999_999 => 0xB, - 20_000_000..=21_799_999 => 0xA, - 21_800_000..=23_999_999 => 0x9, - 24_000_000..=27_499_999 => 0x8, - 27_500_000..=31_999_999 => 0x7, // 27.7..32 in code from CubeIDE - 32_000_000..=u32::MAX => 0x6, - } - } - _ => unimplemented!(), - } -} - -fn quirk_setup_late_cnak(r: crate::pac::otg::Otg) -> bool { - r.cid().read().0 & 0xf000 == 0x1000 +/// Hardware-dependent USB IP configuration. +pub struct OtgInstance<'d, const MAX_EP_COUNT: usize> { + /// The USB peripheral. + pub regs: Otg, + /// The USB state. + pub state: &'d State, + /// FIFO depth in words. + pub fifo_depth_words: u16, + /// Number of used endpoints. + pub endpoint_count: usize, + /// The PHY type. + pub phy_type: PhyType, + /// Extra RX FIFO words needed by some implementations. + pub extra_rx_fifo_words: u16, + /// Whether to set up late cnak + pub quirk_setup_late_cnak: bool, + /// Function to calculate TRDT value based on some internal clock speed. + pub calculate_trdt_fn: fn(speed: vals::Dspd) -> u8, } diff --git a/embassy-usb-synopsys-otg/src/otg_v1.rs b/embassy-usb-synopsys-otg/src/otg_v1.rs new file mode 100644 index 000000000..18e760fd1 --- /dev/null +++ b/embassy-usb-synopsys-otg/src/otg_v1.rs @@ -0,0 +1,4665 @@ +//! Register definitions for Synopsys DesignWare USB OTG core + +#![allow(missing_docs)] + +use core::marker::PhantomData; + +#[derive(Copy, Clone, PartialEq, Eq)] +pub struct RW; +#[derive(Copy, Clone, PartialEq, Eq)] +pub struct R; +#[derive(Copy, Clone, PartialEq, Eq)] +pub struct W; + +mod sealed { + use super::*; + pub trait Access {} + impl Access for R {} + impl Access for W {} + impl Access for RW {} +} + +pub trait Access: sealed::Access + Copy {} +impl Access for R {} +impl Access for W {} +impl Access for RW {} + +pub trait Read: Access {} +impl Read for RW {} +impl Read for R {} + +pub trait Write: Access {} +impl Write for RW {} +impl Write for W {} + +#[derive(Copy, Clone, PartialEq, Eq)] +pub struct Reg { + ptr: *mut u8, + phantom: PhantomData<*mut (T, A)>, +} +unsafe impl Send for Reg {} +unsafe impl Sync for Reg {} + +impl Reg { + #[allow(clippy::missing_safety_doc)] + #[inline(always)] + pub const unsafe fn from_ptr(ptr: *mut T) -> Self { + Self { + ptr: ptr as _, + phantom: PhantomData, + } + } + + #[inline(always)] + pub const fn as_ptr(&self) -> *mut T { + self.ptr as _ + } +} + +impl Reg { + #[inline(always)] + pub fn read(&self) -> T { + unsafe { (self.ptr as *mut T).read_volatile() } + } +} + +impl Reg { + #[inline(always)] + pub fn write_value(&self, val: T) { + unsafe { (self.ptr as *mut T).write_volatile(val) } + } +} + +impl Reg { + #[inline(always)] + pub fn write(&self, f: impl FnOnce(&mut T) -> R) -> R { + let mut val = Default::default(); + let res = f(&mut val); + self.write_value(val); + res + } +} + +impl Reg { + #[inline(always)] + pub fn modify(&self, f: impl FnOnce(&mut T) -> R) -> R { + let mut val = self.read(); + let res = f(&mut val); + self.write_value(val); + res + } +} + +#[doc = "USB on the go"] +#[derive(Copy, Clone, Eq, PartialEq)] +pub struct Otg { + ptr: *mut u8, +} +unsafe impl Send for Otg {} +unsafe impl Sync for Otg {} +impl Otg { + #[inline(always)] + pub const unsafe fn from_ptr(ptr: *mut ()) -> Self { + Self { ptr: ptr as _ } + } + #[inline(always)] + pub const fn as_ptr(&self) -> *mut () { + self.ptr as _ + } + #[doc = "Control and status register"] + #[inline(always)] + pub const fn gotgctl(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0usize) as _) } + } + #[doc = "Interrupt register"] + #[inline(always)] + pub const fn gotgint(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x04usize) as _) } + } + #[doc = "AHB configuration register"] + #[inline(always)] + pub const fn gahbcfg(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x08usize) as _) } + } + #[doc = "USB configuration register"] + #[inline(always)] + pub const fn gusbcfg(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0cusize) as _) } + } + #[doc = "Reset register"] + #[inline(always)] + pub const fn grstctl(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x10usize) as _) } + } + #[doc = "Core interrupt register"] + #[inline(always)] + pub const fn gintsts(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x14usize) as _) } + } + #[doc = "Interrupt mask register"] + #[inline(always)] + pub const fn gintmsk(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x18usize) as _) } + } + #[doc = "Receive status debug read register"] + #[inline(always)] + pub const fn grxstsr(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x1cusize) as _) } + } + #[doc = "Status read and pop register"] + #[inline(always)] + pub const fn grxstsp(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x20usize) as _) } + } + #[doc = "Receive FIFO size register"] + #[inline(always)] + pub const fn grxfsiz(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x24usize) as _) } + } + #[doc = "Endpoint 0 transmit FIFO size register (device mode)"] + #[inline(always)] + pub const fn dieptxf0(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x28usize) as _) } + } + #[doc = "Non-periodic transmit FIFO size register (host mode)"] + #[inline(always)] + pub const fn hnptxfsiz(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x28usize) as _) } + } + #[doc = "Non-periodic transmit FIFO/queue status register (host mode)"] + #[inline(always)] + pub const fn hnptxsts(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x2cusize) as _) } + } + #[doc = "OTG I2C access register"] + #[inline(always)] + pub const fn gi2cctl(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x30usize) as _) } + } + #[doc = "General core configuration register, for core_id 0x0000_1xxx"] + #[inline(always)] + pub const fn gccfg_v1(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x38usize) as _) } + } + #[doc = "General core configuration register, for core_id 0x0000_\\[23\\]xxx"] + #[inline(always)] + pub const fn gccfg_v2(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x38usize) as _) } + } + #[doc = "General core configuration register, for core_id 0x0000_5xxx"] + #[inline(always)] + pub const fn gccfg_v3(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x38usize) as _) } + } + #[doc = "Core ID register"] + #[inline(always)] + pub const fn cid(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x3cusize) as _) } + } + #[doc = "OTG core LPM configuration register"] + #[inline(always)] + pub const fn glpmcfg(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x54usize) as _) } + } + #[doc = "Host periodic transmit FIFO size register"] + #[inline(always)] + pub const fn hptxfsiz(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0100usize) as _) } + } + #[doc = "Device IN endpoint transmit FIFO size register"] + #[inline(always)] + pub const fn dieptxf(self, n: usize) -> Reg { + assert!(n < 7usize); + unsafe { Reg::from_ptr(self.ptr.add(0x0104usize + n * 4usize) as _) } + } + #[doc = "Host configuration register"] + #[inline(always)] + pub const fn hcfg(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0400usize) as _) } + } + #[doc = "Host frame interval register"] + #[inline(always)] + pub const fn hfir(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0404usize) as _) } + } + #[doc = "Host frame number/frame time remaining register"] + #[inline(always)] + pub const fn hfnum(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0408usize) as _) } + } + #[doc = "Periodic transmit FIFO/queue status register"] + #[inline(always)] + pub const fn hptxsts(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0410usize) as _) } + } + #[doc = "Host all channels interrupt register"] + #[inline(always)] + pub const fn haint(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0414usize) as _) } + } + #[doc = "Host all channels interrupt mask register"] + #[inline(always)] + pub const fn haintmsk(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0418usize) as _) } + } + #[doc = "Host port control and status register"] + #[inline(always)] + pub const fn hprt(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0440usize) as _) } + } + #[doc = "Host channel characteristics register"] + #[inline(always)] + pub const fn hcchar(self, n: usize) -> Reg { + assert!(n < 12usize); + unsafe { Reg::from_ptr(self.ptr.add(0x0500usize + n * 32usize) as _) } + } + #[doc = "Host channel split control register"] + #[inline(always)] + pub const fn hcsplt(self, n: usize) -> Reg { + assert!(n < 12usize); + unsafe { Reg::from_ptr(self.ptr.add(0x0504usize + n * 32usize) as _) } + } + #[doc = "Host channel interrupt register"] + #[inline(always)] + pub const fn hcint(self, n: usize) -> Reg { + assert!(n < 12usize); + unsafe { Reg::from_ptr(self.ptr.add(0x0508usize + n * 32usize) as _) } + } + #[doc = "Host channel mask register"] + #[inline(always)] + pub const fn hcintmsk(self, n: usize) -> Reg { + assert!(n < 12usize); + unsafe { Reg::from_ptr(self.ptr.add(0x050cusize + n * 32usize) as _) } + } + #[doc = "Host channel transfer size register"] + #[inline(always)] + pub const fn hctsiz(self, n: usize) -> Reg { + assert!(n < 12usize); + unsafe { Reg::from_ptr(self.ptr.add(0x0510usize + n * 32usize) as _) } + } + #[doc = "Host channel DMA address register"] + #[inline(always)] + pub const fn hcdma(self, n: usize) -> Reg { + assert!(n < 12usize); + unsafe { Reg::from_ptr(self.ptr.add(0x0514usize + n * 32usize) as _) } + } + #[doc = "Device configuration register"] + #[inline(always)] + pub const fn dcfg(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0800usize) as _) } + } + #[doc = "Device control register"] + #[inline(always)] + pub const fn dctl(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0804usize) as _) } + } + #[doc = "Device status register"] + #[inline(always)] + pub const fn dsts(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0808usize) as _) } + } + #[doc = "Device IN endpoint common interrupt mask register"] + #[inline(always)] + pub const fn diepmsk(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0810usize) as _) } + } + #[doc = "Device OUT endpoint common interrupt mask register"] + #[inline(always)] + pub const fn doepmsk(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0814usize) as _) } + } + #[doc = "Device all endpoints interrupt register"] + #[inline(always)] + pub const fn daint(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0818usize) as _) } + } + #[doc = "All endpoints interrupt mask register"] + #[inline(always)] + pub const fn daintmsk(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x081cusize) as _) } + } + #[doc = "Device VBUS discharge time register"] + #[inline(always)] + pub const fn dvbusdis(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0828usize) as _) } + } + #[doc = "Device VBUS pulsing time register"] + #[inline(always)] + pub const fn dvbuspulse(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x082cusize) as _) } + } + #[doc = "Device IN endpoint FIFO empty interrupt mask register"] + #[inline(always)] + pub const fn diepempmsk(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0834usize) as _) } + } + #[doc = "Device IN endpoint control register"] + #[inline(always)] + pub const fn diepctl(self, n: usize) -> Reg { + assert!(n < 16usize); + unsafe { Reg::from_ptr(self.ptr.add(0x0900usize + n * 32usize) as _) } + } + #[doc = "Device IN endpoint interrupt register"] + #[inline(always)] + pub const fn diepint(self, n: usize) -> Reg { + assert!(n < 16usize); + unsafe { Reg::from_ptr(self.ptr.add(0x0908usize + n * 32usize) as _) } + } + #[doc = "Device IN endpoint transfer size register"] + #[inline(always)] + pub const fn dieptsiz(self, n: usize) -> Reg { + assert!(n < 16usize); + unsafe { Reg::from_ptr(self.ptr.add(0x0910usize + n * 32usize) as _) } + } + #[doc = "Device IN endpoint transmit FIFO status register"] + #[inline(always)] + pub const fn dtxfsts(self, n: usize) -> Reg { + assert!(n < 16usize); + unsafe { Reg::from_ptr(self.ptr.add(0x0918usize + n * 32usize) as _) } + } + #[doc = "Device OUT endpoint control register"] + #[inline(always)] + pub const fn doepctl(self, n: usize) -> Reg { + assert!(n < 16usize); + unsafe { Reg::from_ptr(self.ptr.add(0x0b00usize + n * 32usize) as _) } + } + #[doc = "Device OUT endpoint interrupt register"] + #[inline(always)] + pub const fn doepint(self, n: usize) -> Reg { + assert!(n < 16usize); + unsafe { Reg::from_ptr(self.ptr.add(0x0b08usize + n * 32usize) as _) } + } + #[doc = "Device OUT endpoint transfer size register"] + #[inline(always)] + pub const fn doeptsiz(self, n: usize) -> Reg { + assert!(n < 16usize); + unsafe { Reg::from_ptr(self.ptr.add(0x0b10usize + n * 32usize) as _) } + } + #[doc = "Device OUT/IN endpoint DMA address register"] + #[inline(always)] + pub const fn doepdma(self, n: usize) -> Reg { + assert!(n < 16usize); + unsafe { Reg::from_ptr(self.ptr.add(0x0b14usize + n * 32usize) as _) } + } + #[doc = "Power and clock gating control register"] + #[inline(always)] + pub const fn pcgcctl(self) -> Reg { + unsafe { Reg::from_ptr(self.ptr.add(0x0e00usize) as _) } + } + #[doc = "Device endpoint / host channel FIFO register"] + #[inline(always)] + pub const fn fifo(self, n: usize) -> Reg { + assert!(n < 16usize); + unsafe { Reg::from_ptr(self.ptr.add(0x1000usize + n * 4096usize) as _) } + } +} +pub mod regs { + #[doc = "Core ID register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Cid(pub u32); + impl Cid { + #[doc = "Product ID field"] + #[inline(always)] + pub const fn product_id(&self) -> u32 { + let val = (self.0 >> 0usize) & 0xffff_ffff; + val as u32 + } + #[doc = "Product ID field"] + #[inline(always)] + pub fn set_product_id(&mut self, val: u32) { + self.0 = (self.0 & !(0xffff_ffff << 0usize)) | (((val as u32) & 0xffff_ffff) << 0usize); + } + } + impl Default for Cid { + #[inline(always)] + fn default() -> Cid { + Cid(0) + } + } + #[doc = "Device all endpoints interrupt register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Daint(pub u32); + impl Daint { + #[doc = "IN endpoint interrupt bits"] + #[inline(always)] + pub const fn iepint(&self) -> u16 { + let val = (self.0 >> 0usize) & 0xffff; + val as u16 + } + #[doc = "IN endpoint interrupt bits"] + #[inline(always)] + pub fn set_iepint(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 0usize)) | (((val as u32) & 0xffff) << 0usize); + } + #[doc = "OUT endpoint interrupt bits"] + #[inline(always)] + pub const fn oepint(&self) -> u16 { + let val = (self.0 >> 16usize) & 0xffff; + val as u16 + } + #[doc = "OUT endpoint interrupt bits"] + #[inline(always)] + pub fn set_oepint(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 16usize)) | (((val as u32) & 0xffff) << 16usize); + } + } + impl Default for Daint { + #[inline(always)] + fn default() -> Daint { + Daint(0) + } + } + #[doc = "All endpoints interrupt mask register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Daintmsk(pub u32); + impl Daintmsk { + #[doc = "IN EP interrupt mask bits"] + #[inline(always)] + pub const fn iepm(&self) -> u16 { + let val = (self.0 >> 0usize) & 0xffff; + val as u16 + } + #[doc = "IN EP interrupt mask bits"] + #[inline(always)] + pub fn set_iepm(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 0usize)) | (((val as u32) & 0xffff) << 0usize); + } + #[doc = "OUT EP interrupt mask bits"] + #[inline(always)] + pub const fn oepm(&self) -> u16 { + let val = (self.0 >> 16usize) & 0xffff; + val as u16 + } + #[doc = "OUT EP interrupt mask bits"] + #[inline(always)] + pub fn set_oepm(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 16usize)) | (((val as u32) & 0xffff) << 16usize); + } + } + impl Default for Daintmsk { + #[inline(always)] + fn default() -> Daintmsk { + Daintmsk(0) + } + } + #[doc = "Device configuration register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Dcfg(pub u32); + impl Dcfg { + #[doc = "Device speed"] + #[inline(always)] + pub const fn dspd(&self) -> super::vals::Dspd { + let val = (self.0 >> 0usize) & 0x03; + super::vals::Dspd::from_bits(val as u8) + } + #[doc = "Device speed"] + #[inline(always)] + pub fn set_dspd(&mut self, val: super::vals::Dspd) { + self.0 = (self.0 & !(0x03 << 0usize)) | (((val.to_bits() as u32) & 0x03) << 0usize); + } + #[doc = "Non-zero-length status OUT handshake"] + #[inline(always)] + pub const fn nzlsohsk(&self) -> bool { + let val = (self.0 >> 2usize) & 0x01; + val != 0 + } + #[doc = "Non-zero-length status OUT handshake"] + #[inline(always)] + pub fn set_nzlsohsk(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 2usize)) | (((val as u32) & 0x01) << 2usize); + } + #[doc = "Device address"] + #[inline(always)] + pub const fn dad(&self) -> u8 { + let val = (self.0 >> 4usize) & 0x7f; + val as u8 + } + #[doc = "Device address"] + #[inline(always)] + pub fn set_dad(&mut self, val: u8) { + self.0 = (self.0 & !(0x7f << 4usize)) | (((val as u32) & 0x7f) << 4usize); + } + #[doc = "Periodic frame interval"] + #[inline(always)] + pub const fn pfivl(&self) -> super::vals::Pfivl { + let val = (self.0 >> 11usize) & 0x03; + super::vals::Pfivl::from_bits(val as u8) + } + #[doc = "Periodic frame interval"] + #[inline(always)] + pub fn set_pfivl(&mut self, val: super::vals::Pfivl) { + self.0 = (self.0 & !(0x03 << 11usize)) | (((val.to_bits() as u32) & 0x03) << 11usize); + } + #[doc = "Transceiver delay"] + #[inline(always)] + pub const fn xcvrdly(&self) -> bool { + let val = (self.0 >> 14usize) & 0x01; + val != 0 + } + #[doc = "Transceiver delay"] + #[inline(always)] + pub fn set_xcvrdly(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 14usize)) | (((val as u32) & 0x01) << 14usize); + } + } + impl Default for Dcfg { + #[inline(always)] + fn default() -> Dcfg { + Dcfg(0) + } + } + #[doc = "Device control register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Dctl(pub u32); + impl Dctl { + #[doc = "Remote wakeup signaling"] + #[inline(always)] + pub const fn rwusig(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "Remote wakeup signaling"] + #[inline(always)] + pub fn set_rwusig(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "Soft disconnect"] + #[inline(always)] + pub const fn sdis(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "Soft disconnect"] + #[inline(always)] + pub fn set_sdis(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "Global IN NAK status"] + #[inline(always)] + pub const fn ginsts(&self) -> bool { + let val = (self.0 >> 2usize) & 0x01; + val != 0 + } + #[doc = "Global IN NAK status"] + #[inline(always)] + pub fn set_ginsts(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 2usize)) | (((val as u32) & 0x01) << 2usize); + } + #[doc = "Global OUT NAK status"] + #[inline(always)] + pub const fn gonsts(&self) -> bool { + let val = (self.0 >> 3usize) & 0x01; + val != 0 + } + #[doc = "Global OUT NAK status"] + #[inline(always)] + pub fn set_gonsts(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 3usize)) | (((val as u32) & 0x01) << 3usize); + } + #[doc = "Test control"] + #[inline(always)] + pub const fn tctl(&self) -> u8 { + let val = (self.0 >> 4usize) & 0x07; + val as u8 + } + #[doc = "Test control"] + #[inline(always)] + pub fn set_tctl(&mut self, val: u8) { + self.0 = (self.0 & !(0x07 << 4usize)) | (((val as u32) & 0x07) << 4usize); + } + #[doc = "Set global IN NAK"] + #[inline(always)] + pub const fn sginak(&self) -> bool { + let val = (self.0 >> 7usize) & 0x01; + val != 0 + } + #[doc = "Set global IN NAK"] + #[inline(always)] + pub fn set_sginak(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 7usize)) | (((val as u32) & 0x01) << 7usize); + } + #[doc = "Clear global IN NAK"] + #[inline(always)] + pub const fn cginak(&self) -> bool { + let val = (self.0 >> 8usize) & 0x01; + val != 0 + } + #[doc = "Clear global IN NAK"] + #[inline(always)] + pub fn set_cginak(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 8usize)) | (((val as u32) & 0x01) << 8usize); + } + #[doc = "Set global OUT NAK"] + #[inline(always)] + pub const fn sgonak(&self) -> bool { + let val = (self.0 >> 9usize) & 0x01; + val != 0 + } + #[doc = "Set global OUT NAK"] + #[inline(always)] + pub fn set_sgonak(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 9usize)) | (((val as u32) & 0x01) << 9usize); + } + #[doc = "Clear global OUT NAK"] + #[inline(always)] + pub const fn cgonak(&self) -> bool { + let val = (self.0 >> 10usize) & 0x01; + val != 0 + } + #[doc = "Clear global OUT NAK"] + #[inline(always)] + pub fn set_cgonak(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 10usize)) | (((val as u32) & 0x01) << 10usize); + } + #[doc = "Power-on programming done"] + #[inline(always)] + pub const fn poprgdne(&self) -> bool { + let val = (self.0 >> 11usize) & 0x01; + val != 0 + } + #[doc = "Power-on programming done"] + #[inline(always)] + pub fn set_poprgdne(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 11usize)) | (((val as u32) & 0x01) << 11usize); + } + } + impl Default for Dctl { + #[inline(always)] + fn default() -> Dctl { + Dctl(0) + } + } + #[doc = "Device endpoint control register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Diepctl(pub u32); + impl Diepctl { + #[doc = "MPSIZ"] + #[inline(always)] + pub const fn mpsiz(&self) -> u16 { + let val = (self.0 >> 0usize) & 0x07ff; + val as u16 + } + #[doc = "MPSIZ"] + #[inline(always)] + pub fn set_mpsiz(&mut self, val: u16) { + self.0 = (self.0 & !(0x07ff << 0usize)) | (((val as u32) & 0x07ff) << 0usize); + } + #[doc = "USBAEP"] + #[inline(always)] + pub const fn usbaep(&self) -> bool { + let val = (self.0 >> 15usize) & 0x01; + val != 0 + } + #[doc = "USBAEP"] + #[inline(always)] + pub fn set_usbaep(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 15usize)) | (((val as u32) & 0x01) << 15usize); + } + #[doc = "EONUM/DPID"] + #[inline(always)] + pub const fn eonum_dpid(&self) -> bool { + let val = (self.0 >> 16usize) & 0x01; + val != 0 + } + #[doc = "EONUM/DPID"] + #[inline(always)] + pub fn set_eonum_dpid(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 16usize)) | (((val as u32) & 0x01) << 16usize); + } + #[doc = "NAKSTS"] + #[inline(always)] + pub const fn naksts(&self) -> bool { + let val = (self.0 >> 17usize) & 0x01; + val != 0 + } + #[doc = "NAKSTS"] + #[inline(always)] + pub fn set_naksts(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 17usize)) | (((val as u32) & 0x01) << 17usize); + } + #[doc = "EPTYP"] + #[inline(always)] + pub const fn eptyp(&self) -> super::vals::Eptyp { + let val = (self.0 >> 18usize) & 0x03; + super::vals::Eptyp::from_bits(val as u8) + } + #[doc = "EPTYP"] + #[inline(always)] + pub fn set_eptyp(&mut self, val: super::vals::Eptyp) { + self.0 = (self.0 & !(0x03 << 18usize)) | (((val.to_bits() as u32) & 0x03) << 18usize); + } + #[doc = "SNPM"] + #[inline(always)] + pub const fn snpm(&self) -> bool { + let val = (self.0 >> 20usize) & 0x01; + val != 0 + } + #[doc = "SNPM"] + #[inline(always)] + pub fn set_snpm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 20usize)) | (((val as u32) & 0x01) << 20usize); + } + #[doc = "STALL"] + #[inline(always)] + pub const fn stall(&self) -> bool { + let val = (self.0 >> 21usize) & 0x01; + val != 0 + } + #[doc = "STALL"] + #[inline(always)] + pub fn set_stall(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 21usize)) | (((val as u32) & 0x01) << 21usize); + } + #[doc = "TXFNUM"] + #[inline(always)] + pub const fn txfnum(&self) -> u8 { + let val = (self.0 >> 22usize) & 0x0f; + val as u8 + } + #[doc = "TXFNUM"] + #[inline(always)] + pub fn set_txfnum(&mut self, val: u8) { + self.0 = (self.0 & !(0x0f << 22usize)) | (((val as u32) & 0x0f) << 22usize); + } + #[doc = "CNAK"] + #[inline(always)] + pub const fn cnak(&self) -> bool { + let val = (self.0 >> 26usize) & 0x01; + val != 0 + } + #[doc = "CNAK"] + #[inline(always)] + pub fn set_cnak(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 26usize)) | (((val as u32) & 0x01) << 26usize); + } + #[doc = "SNAK"] + #[inline(always)] + pub const fn snak(&self) -> bool { + let val = (self.0 >> 27usize) & 0x01; + val != 0 + } + #[doc = "SNAK"] + #[inline(always)] + pub fn set_snak(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 27usize)) | (((val as u32) & 0x01) << 27usize); + } + #[doc = "SD0PID/SEVNFRM"] + #[inline(always)] + pub const fn sd0pid_sevnfrm(&self) -> bool { + let val = (self.0 >> 28usize) & 0x01; + val != 0 + } + #[doc = "SD0PID/SEVNFRM"] + #[inline(always)] + pub fn set_sd0pid_sevnfrm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 28usize)) | (((val as u32) & 0x01) << 28usize); + } + #[doc = "SD1PID/SODDFRM"] + #[inline(always)] + pub const fn sd1pid_soddfrm(&self) -> bool { + let val = (self.0 >> 29usize) & 0x01; + val != 0 + } + #[doc = "SD1PID/SODDFRM"] + #[inline(always)] + pub fn set_sd1pid_soddfrm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 29usize)) | (((val as u32) & 0x01) << 29usize); + } + #[doc = "EPDIS"] + #[inline(always)] + pub const fn epdis(&self) -> bool { + let val = (self.0 >> 30usize) & 0x01; + val != 0 + } + #[doc = "EPDIS"] + #[inline(always)] + pub fn set_epdis(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 30usize)) | (((val as u32) & 0x01) << 30usize); + } + #[doc = "EPENA"] + #[inline(always)] + pub const fn epena(&self) -> bool { + let val = (self.0 >> 31usize) & 0x01; + val != 0 + } + #[doc = "EPENA"] + #[inline(always)] + pub fn set_epena(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 31usize)) | (((val as u32) & 0x01) << 31usize); + } + } + impl Default for Diepctl { + #[inline(always)] + fn default() -> Diepctl { + Diepctl(0) + } + } + #[doc = "Device IN endpoint FIFO empty interrupt mask register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Diepempmsk(pub u32); + impl Diepempmsk { + #[doc = "IN EP Tx FIFO empty interrupt mask bits"] + #[inline(always)] + pub const fn ineptxfem(&self) -> u16 { + let val = (self.0 >> 0usize) & 0xffff; + val as u16 + } + #[doc = "IN EP Tx FIFO empty interrupt mask bits"] + #[inline(always)] + pub fn set_ineptxfem(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 0usize)) | (((val as u32) & 0xffff) << 0usize); + } + } + impl Default for Diepempmsk { + #[inline(always)] + fn default() -> Diepempmsk { + Diepempmsk(0) + } + } + #[doc = "Device endpoint interrupt register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Diepint(pub u32); + impl Diepint { + #[doc = "XFRC"] + #[inline(always)] + pub const fn xfrc(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "XFRC"] + #[inline(always)] + pub fn set_xfrc(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "EPDISD"] + #[inline(always)] + pub const fn epdisd(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "EPDISD"] + #[inline(always)] + pub fn set_epdisd(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "TOC"] + #[inline(always)] + pub const fn toc(&self) -> bool { + let val = (self.0 >> 3usize) & 0x01; + val != 0 + } + #[doc = "TOC"] + #[inline(always)] + pub fn set_toc(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 3usize)) | (((val as u32) & 0x01) << 3usize); + } + #[doc = "ITTXFE"] + #[inline(always)] + pub const fn ittxfe(&self) -> bool { + let val = (self.0 >> 4usize) & 0x01; + val != 0 + } + #[doc = "ITTXFE"] + #[inline(always)] + pub fn set_ittxfe(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 4usize)) | (((val as u32) & 0x01) << 4usize); + } + #[doc = "INEPNE"] + #[inline(always)] + pub const fn inepne(&self) -> bool { + let val = (self.0 >> 6usize) & 0x01; + val != 0 + } + #[doc = "INEPNE"] + #[inline(always)] + pub fn set_inepne(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 6usize)) | (((val as u32) & 0x01) << 6usize); + } + #[doc = "TXFE"] + #[inline(always)] + pub const fn txfe(&self) -> bool { + let val = (self.0 >> 7usize) & 0x01; + val != 0 + } + #[doc = "TXFE"] + #[inline(always)] + pub fn set_txfe(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 7usize)) | (((val as u32) & 0x01) << 7usize); + } + } + impl Default for Diepint { + #[inline(always)] + fn default() -> Diepint { + Diepint(0) + } + } + #[doc = "Device IN endpoint common interrupt mask register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Diepmsk(pub u32); + impl Diepmsk { + #[doc = "Transfer completed interrupt mask"] + #[inline(always)] + pub const fn xfrcm(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "Transfer completed interrupt mask"] + #[inline(always)] + pub fn set_xfrcm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "Endpoint disabled interrupt mask"] + #[inline(always)] + pub const fn epdm(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "Endpoint disabled interrupt mask"] + #[inline(always)] + pub fn set_epdm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "Timeout condition mask (Non-isochronous endpoints)"] + #[inline(always)] + pub const fn tom(&self) -> bool { + let val = (self.0 >> 3usize) & 0x01; + val != 0 + } + #[doc = "Timeout condition mask (Non-isochronous endpoints)"] + #[inline(always)] + pub fn set_tom(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 3usize)) | (((val as u32) & 0x01) << 3usize); + } + #[doc = "IN token received when TxFIFO empty mask"] + #[inline(always)] + pub const fn ittxfemsk(&self) -> bool { + let val = (self.0 >> 4usize) & 0x01; + val != 0 + } + #[doc = "IN token received when TxFIFO empty mask"] + #[inline(always)] + pub fn set_ittxfemsk(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 4usize)) | (((val as u32) & 0x01) << 4usize); + } + #[doc = "IN token received with EP mismatch mask"] + #[inline(always)] + pub const fn inepnmm(&self) -> bool { + let val = (self.0 >> 5usize) & 0x01; + val != 0 + } + #[doc = "IN token received with EP mismatch mask"] + #[inline(always)] + pub fn set_inepnmm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 5usize)) | (((val as u32) & 0x01) << 5usize); + } + #[doc = "IN endpoint NAK effective mask"] + #[inline(always)] + pub const fn inepnem(&self) -> bool { + let val = (self.0 >> 6usize) & 0x01; + val != 0 + } + #[doc = "IN endpoint NAK effective mask"] + #[inline(always)] + pub fn set_inepnem(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 6usize)) | (((val as u32) & 0x01) << 6usize); + } + } + impl Default for Diepmsk { + #[inline(always)] + fn default() -> Diepmsk { + Diepmsk(0) + } + } + #[doc = "Device endpoint transfer size register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Dieptsiz(pub u32); + impl Dieptsiz { + #[doc = "Transfer size"] + #[inline(always)] + pub const fn xfrsiz(&self) -> u32 { + let val = (self.0 >> 0usize) & 0x0007_ffff; + val as u32 + } + #[doc = "Transfer size"] + #[inline(always)] + pub fn set_xfrsiz(&mut self, val: u32) { + self.0 = (self.0 & !(0x0007_ffff << 0usize)) | (((val as u32) & 0x0007_ffff) << 0usize); + } + #[doc = "Packet count"] + #[inline(always)] + pub const fn pktcnt(&self) -> u16 { + let val = (self.0 >> 19usize) & 0x03ff; + val as u16 + } + #[doc = "Packet count"] + #[inline(always)] + pub fn set_pktcnt(&mut self, val: u16) { + self.0 = (self.0 & !(0x03ff << 19usize)) | (((val as u32) & 0x03ff) << 19usize); + } + #[doc = "Multi count"] + #[inline(always)] + pub const fn mcnt(&self) -> u8 { + let val = (self.0 >> 29usize) & 0x03; + val as u8 + } + #[doc = "Multi count"] + #[inline(always)] + pub fn set_mcnt(&mut self, val: u8) { + self.0 = (self.0 & !(0x03 << 29usize)) | (((val as u32) & 0x03) << 29usize); + } + } + impl Default for Dieptsiz { + #[inline(always)] + fn default() -> Dieptsiz { + Dieptsiz(0) + } + } + #[doc = "Device endpoint control register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Doepctl(pub u32); + impl Doepctl { + #[doc = "MPSIZ"] + #[inline(always)] + pub const fn mpsiz(&self) -> u16 { + let val = (self.0 >> 0usize) & 0x07ff; + val as u16 + } + #[doc = "MPSIZ"] + #[inline(always)] + pub fn set_mpsiz(&mut self, val: u16) { + self.0 = (self.0 & !(0x07ff << 0usize)) | (((val as u32) & 0x07ff) << 0usize); + } + #[doc = "USBAEP"] + #[inline(always)] + pub const fn usbaep(&self) -> bool { + let val = (self.0 >> 15usize) & 0x01; + val != 0 + } + #[doc = "USBAEP"] + #[inline(always)] + pub fn set_usbaep(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 15usize)) | (((val as u32) & 0x01) << 15usize); + } + #[doc = "EONUM/DPID"] + #[inline(always)] + pub const fn eonum_dpid(&self) -> bool { + let val = (self.0 >> 16usize) & 0x01; + val != 0 + } + #[doc = "EONUM/DPID"] + #[inline(always)] + pub fn set_eonum_dpid(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 16usize)) | (((val as u32) & 0x01) << 16usize); + } + #[doc = "NAKSTS"] + #[inline(always)] + pub const fn naksts(&self) -> bool { + let val = (self.0 >> 17usize) & 0x01; + val != 0 + } + #[doc = "NAKSTS"] + #[inline(always)] + pub fn set_naksts(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 17usize)) | (((val as u32) & 0x01) << 17usize); + } + #[doc = "EPTYP"] + #[inline(always)] + pub const fn eptyp(&self) -> super::vals::Eptyp { + let val = (self.0 >> 18usize) & 0x03; + super::vals::Eptyp::from_bits(val as u8) + } + #[doc = "EPTYP"] + #[inline(always)] + pub fn set_eptyp(&mut self, val: super::vals::Eptyp) { + self.0 = (self.0 & !(0x03 << 18usize)) | (((val.to_bits() as u32) & 0x03) << 18usize); + } + #[doc = "SNPM"] + #[inline(always)] + pub const fn snpm(&self) -> bool { + let val = (self.0 >> 20usize) & 0x01; + val != 0 + } + #[doc = "SNPM"] + #[inline(always)] + pub fn set_snpm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 20usize)) | (((val as u32) & 0x01) << 20usize); + } + #[doc = "STALL"] + #[inline(always)] + pub const fn stall(&self) -> bool { + let val = (self.0 >> 21usize) & 0x01; + val != 0 + } + #[doc = "STALL"] + #[inline(always)] + pub fn set_stall(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 21usize)) | (((val as u32) & 0x01) << 21usize); + } + #[doc = "CNAK"] + #[inline(always)] + pub const fn cnak(&self) -> bool { + let val = (self.0 >> 26usize) & 0x01; + val != 0 + } + #[doc = "CNAK"] + #[inline(always)] + pub fn set_cnak(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 26usize)) | (((val as u32) & 0x01) << 26usize); + } + #[doc = "SNAK"] + #[inline(always)] + pub const fn snak(&self) -> bool { + let val = (self.0 >> 27usize) & 0x01; + val != 0 + } + #[doc = "SNAK"] + #[inline(always)] + pub fn set_snak(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 27usize)) | (((val as u32) & 0x01) << 27usize); + } + #[doc = "SD0PID/SEVNFRM"] + #[inline(always)] + pub const fn sd0pid_sevnfrm(&self) -> bool { + let val = (self.0 >> 28usize) & 0x01; + val != 0 + } + #[doc = "SD0PID/SEVNFRM"] + #[inline(always)] + pub fn set_sd0pid_sevnfrm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 28usize)) | (((val as u32) & 0x01) << 28usize); + } + #[doc = "SD1PID/SODDFRM"] + #[inline(always)] + pub const fn sd1pid_soddfrm(&self) -> bool { + let val = (self.0 >> 29usize) & 0x01; + val != 0 + } + #[doc = "SD1PID/SODDFRM"] + #[inline(always)] + pub fn set_sd1pid_soddfrm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 29usize)) | (((val as u32) & 0x01) << 29usize); + } + #[doc = "EPDIS"] + #[inline(always)] + pub const fn epdis(&self) -> bool { + let val = (self.0 >> 30usize) & 0x01; + val != 0 + } + #[doc = "EPDIS"] + #[inline(always)] + pub fn set_epdis(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 30usize)) | (((val as u32) & 0x01) << 30usize); + } + #[doc = "EPENA"] + #[inline(always)] + pub const fn epena(&self) -> bool { + let val = (self.0 >> 31usize) & 0x01; + val != 0 + } + #[doc = "EPENA"] + #[inline(always)] + pub fn set_epena(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 31usize)) | (((val as u32) & 0x01) << 31usize); + } + } + impl Default for Doepctl { + #[inline(always)] + fn default() -> Doepctl { + Doepctl(0) + } + } + #[doc = "Device endpoint interrupt register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Doepint(pub u32); + impl Doepint { + #[doc = "XFRC"] + #[inline(always)] + pub const fn xfrc(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "XFRC"] + #[inline(always)] + pub fn set_xfrc(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "EPDISD"] + #[inline(always)] + pub const fn epdisd(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "EPDISD"] + #[inline(always)] + pub fn set_epdisd(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "STUP"] + #[inline(always)] + pub const fn stup(&self) -> bool { + let val = (self.0 >> 3usize) & 0x01; + val != 0 + } + #[doc = "STUP"] + #[inline(always)] + pub fn set_stup(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 3usize)) | (((val as u32) & 0x01) << 3usize); + } + #[doc = "OTEPDIS"] + #[inline(always)] + pub const fn otepdis(&self) -> bool { + let val = (self.0 >> 4usize) & 0x01; + val != 0 + } + #[doc = "OTEPDIS"] + #[inline(always)] + pub fn set_otepdis(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 4usize)) | (((val as u32) & 0x01) << 4usize); + } + #[doc = "B2BSTUP"] + #[inline(always)] + pub const fn b2bstup(&self) -> bool { + let val = (self.0 >> 6usize) & 0x01; + val != 0 + } + #[doc = "B2BSTUP"] + #[inline(always)] + pub fn set_b2bstup(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 6usize)) | (((val as u32) & 0x01) << 6usize); + } + } + impl Default for Doepint { + #[inline(always)] + fn default() -> Doepint { + Doepint(0) + } + } + #[doc = "Device OUT endpoint common interrupt mask register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Doepmsk(pub u32); + impl Doepmsk { + #[doc = "Transfer completed interrupt mask"] + #[inline(always)] + pub const fn xfrcm(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "Transfer completed interrupt mask"] + #[inline(always)] + pub fn set_xfrcm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "Endpoint disabled interrupt mask"] + #[inline(always)] + pub const fn epdm(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "Endpoint disabled interrupt mask"] + #[inline(always)] + pub fn set_epdm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "SETUP phase done mask"] + #[inline(always)] + pub const fn stupm(&self) -> bool { + let val = (self.0 >> 3usize) & 0x01; + val != 0 + } + #[doc = "SETUP phase done mask"] + #[inline(always)] + pub fn set_stupm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 3usize)) | (((val as u32) & 0x01) << 3usize); + } + #[doc = "OUT token received when endpoint disabled mask"] + #[inline(always)] + pub const fn otepdm(&self) -> bool { + let val = (self.0 >> 4usize) & 0x01; + val != 0 + } + #[doc = "OUT token received when endpoint disabled mask"] + #[inline(always)] + pub fn set_otepdm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 4usize)) | (((val as u32) & 0x01) << 4usize); + } + } + impl Default for Doepmsk { + #[inline(always)] + fn default() -> Doepmsk { + Doepmsk(0) + } + } + #[doc = "Device OUT endpoint transfer size register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Doeptsiz(pub u32); + impl Doeptsiz { + #[doc = "Transfer size"] + #[inline(always)] + pub const fn xfrsiz(&self) -> u32 { + let val = (self.0 >> 0usize) & 0x0007_ffff; + val as u32 + } + #[doc = "Transfer size"] + #[inline(always)] + pub fn set_xfrsiz(&mut self, val: u32) { + self.0 = (self.0 & !(0x0007_ffff << 0usize)) | (((val as u32) & 0x0007_ffff) << 0usize); + } + #[doc = "Packet count"] + #[inline(always)] + pub const fn pktcnt(&self) -> u16 { + let val = (self.0 >> 19usize) & 0x03ff; + val as u16 + } + #[doc = "Packet count"] + #[inline(always)] + pub fn set_pktcnt(&mut self, val: u16) { + self.0 = (self.0 & !(0x03ff << 19usize)) | (((val as u32) & 0x03ff) << 19usize); + } + #[doc = "Received data PID/SETUP packet count"] + #[inline(always)] + pub const fn rxdpid_stupcnt(&self) -> u8 { + let val = (self.0 >> 29usize) & 0x03; + val as u8 + } + #[doc = "Received data PID/SETUP packet count"] + #[inline(always)] + pub fn set_rxdpid_stupcnt(&mut self, val: u8) { + self.0 = (self.0 & !(0x03 << 29usize)) | (((val as u32) & 0x03) << 29usize); + } + } + impl Default for Doeptsiz { + #[inline(always)] + fn default() -> Doeptsiz { + Doeptsiz(0) + } + } + #[doc = "Device status register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Dsts(pub u32); + impl Dsts { + #[doc = "Suspend status"] + #[inline(always)] + pub const fn suspsts(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "Suspend status"] + #[inline(always)] + pub fn set_suspsts(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "Enumerated speed"] + #[inline(always)] + pub const fn enumspd(&self) -> super::vals::Dspd { + let val = (self.0 >> 1usize) & 0x03; + super::vals::Dspd::from_bits(val as u8) + } + #[doc = "Enumerated speed"] + #[inline(always)] + pub fn set_enumspd(&mut self, val: super::vals::Dspd) { + self.0 = (self.0 & !(0x03 << 1usize)) | (((val.to_bits() as u32) & 0x03) << 1usize); + } + #[doc = "Erratic error"] + #[inline(always)] + pub const fn eerr(&self) -> bool { + let val = (self.0 >> 3usize) & 0x01; + val != 0 + } + #[doc = "Erratic error"] + #[inline(always)] + pub fn set_eerr(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 3usize)) | (((val as u32) & 0x01) << 3usize); + } + #[doc = "Frame number of the received SOF"] + #[inline(always)] + pub const fn fnsof(&self) -> u16 { + let val = (self.0 >> 8usize) & 0x3fff; + val as u16 + } + #[doc = "Frame number of the received SOF"] + #[inline(always)] + pub fn set_fnsof(&mut self, val: u16) { + self.0 = (self.0 & !(0x3fff << 8usize)) | (((val as u32) & 0x3fff) << 8usize); + } + } + impl Default for Dsts { + #[inline(always)] + fn default() -> Dsts { + Dsts(0) + } + } + #[doc = "Device IN endpoint transmit FIFO status register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Dtxfsts(pub u32); + impl Dtxfsts { + #[doc = "IN endpoint TxFIFO space available"] + #[inline(always)] + pub const fn ineptfsav(&self) -> u16 { + let val = (self.0 >> 0usize) & 0xffff; + val as u16 + } + #[doc = "IN endpoint TxFIFO space available"] + #[inline(always)] + pub fn set_ineptfsav(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 0usize)) | (((val as u32) & 0xffff) << 0usize); + } + } + impl Default for Dtxfsts { + #[inline(always)] + fn default() -> Dtxfsts { + Dtxfsts(0) + } + } + #[doc = "Device VBUS discharge time register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Dvbusdis(pub u32); + impl Dvbusdis { + #[doc = "Device VBUS discharge time"] + #[inline(always)] + pub const fn vbusdt(&self) -> u16 { + let val = (self.0 >> 0usize) & 0xffff; + val as u16 + } + #[doc = "Device VBUS discharge time"] + #[inline(always)] + pub fn set_vbusdt(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 0usize)) | (((val as u32) & 0xffff) << 0usize); + } + } + impl Default for Dvbusdis { + #[inline(always)] + fn default() -> Dvbusdis { + Dvbusdis(0) + } + } + #[doc = "Device VBUS pulsing time register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Dvbuspulse(pub u32); + impl Dvbuspulse { + #[doc = "Device VBUS pulsing time"] + #[inline(always)] + pub const fn dvbusp(&self) -> u16 { + let val = (self.0 >> 0usize) & 0x0fff; + val as u16 + } + #[doc = "Device VBUS pulsing time"] + #[inline(always)] + pub fn set_dvbusp(&mut self, val: u16) { + self.0 = (self.0 & !(0x0fff << 0usize)) | (((val as u32) & 0x0fff) << 0usize); + } + } + impl Default for Dvbuspulse { + #[inline(always)] + fn default() -> Dvbuspulse { + Dvbuspulse(0) + } + } + #[doc = "FIFO register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Fifo(pub u32); + impl Fifo { + #[doc = "Data"] + #[inline(always)] + pub const fn data(&self) -> u32 { + let val = (self.0 >> 0usize) & 0xffff_ffff; + val as u32 + } + #[doc = "Data"] + #[inline(always)] + pub fn set_data(&mut self, val: u32) { + self.0 = (self.0 & !(0xffff_ffff << 0usize)) | (((val as u32) & 0xffff_ffff) << 0usize); + } + } + impl Default for Fifo { + #[inline(always)] + fn default() -> Fifo { + Fifo(0) + } + } + #[doc = "FIFO size register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Fsiz(pub u32); + impl Fsiz { + #[doc = "RAM start address"] + #[inline(always)] + pub const fn sa(&self) -> u16 { + let val = (self.0 >> 0usize) & 0xffff; + val as u16 + } + #[doc = "RAM start address"] + #[inline(always)] + pub fn set_sa(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 0usize)) | (((val as u32) & 0xffff) << 0usize); + } + #[doc = "FIFO depth"] + #[inline(always)] + pub const fn fd(&self) -> u16 { + let val = (self.0 >> 16usize) & 0xffff; + val as u16 + } + #[doc = "FIFO depth"] + #[inline(always)] + pub fn set_fd(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 16usize)) | (((val as u32) & 0xffff) << 16usize); + } + } + impl Default for Fsiz { + #[inline(always)] + fn default() -> Fsiz { + Fsiz(0) + } + } + #[doc = "AHB configuration register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Gahbcfg(pub u32); + impl Gahbcfg { + #[doc = "Global interrupt mask"] + #[inline(always)] + pub const fn gint(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "Global interrupt mask"] + #[inline(always)] + pub fn set_gint(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "Burst length/type"] + #[inline(always)] + pub const fn hbstlen(&self) -> u8 { + let val = (self.0 >> 1usize) & 0x0f; + val as u8 + } + #[doc = "Burst length/type"] + #[inline(always)] + pub fn set_hbstlen(&mut self, val: u8) { + self.0 = (self.0 & !(0x0f << 1usize)) | (((val as u32) & 0x0f) << 1usize); + } + #[doc = "DMA enable"] + #[inline(always)] + pub const fn dmaen(&self) -> bool { + let val = (self.0 >> 5usize) & 0x01; + val != 0 + } + #[doc = "DMA enable"] + #[inline(always)] + pub fn set_dmaen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 5usize)) | (((val as u32) & 0x01) << 5usize); + } + #[doc = "TxFIFO empty level"] + #[inline(always)] + pub const fn txfelvl(&self) -> bool { + let val = (self.0 >> 7usize) & 0x01; + val != 0 + } + #[doc = "TxFIFO empty level"] + #[inline(always)] + pub fn set_txfelvl(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 7usize)) | (((val as u32) & 0x01) << 7usize); + } + #[doc = "Periodic TxFIFO empty level"] + #[inline(always)] + pub const fn ptxfelvl(&self) -> bool { + let val = (self.0 >> 8usize) & 0x01; + val != 0 + } + #[doc = "Periodic TxFIFO empty level"] + #[inline(always)] + pub fn set_ptxfelvl(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 8usize)) | (((val as u32) & 0x01) << 8usize); + } + } + impl Default for Gahbcfg { + #[inline(always)] + fn default() -> Gahbcfg { + Gahbcfg(0) + } + } + #[doc = "General core configuration register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct GccfgV1(pub u32); + impl GccfgV1 { + #[doc = "Power down"] + #[inline(always)] + pub const fn pwrdwn(&self) -> bool { + let val = (self.0 >> 16usize) & 0x01; + val != 0 + } + #[doc = "Power down"] + #[inline(always)] + pub fn set_pwrdwn(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 16usize)) | (((val as u32) & 0x01) << 16usize); + } + #[doc = "Enable the VBUS \"A\" sensing device"] + #[inline(always)] + pub const fn vbusasen(&self) -> bool { + let val = (self.0 >> 18usize) & 0x01; + val != 0 + } + #[doc = "Enable the VBUS \"A\" sensing device"] + #[inline(always)] + pub fn set_vbusasen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 18usize)) | (((val as u32) & 0x01) << 18usize); + } + #[doc = "Enable the VBUS \"B\" sensing device"] + #[inline(always)] + pub const fn vbusbsen(&self) -> bool { + let val = (self.0 >> 19usize) & 0x01; + val != 0 + } + #[doc = "Enable the VBUS \"B\" sensing device"] + #[inline(always)] + pub fn set_vbusbsen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 19usize)) | (((val as u32) & 0x01) << 19usize); + } + #[doc = "SOF output enable"] + #[inline(always)] + pub const fn sofouten(&self) -> bool { + let val = (self.0 >> 20usize) & 0x01; + val != 0 + } + #[doc = "SOF output enable"] + #[inline(always)] + pub fn set_sofouten(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 20usize)) | (((val as u32) & 0x01) << 20usize); + } + #[doc = "VBUS sensing disable"] + #[inline(always)] + pub const fn novbussens(&self) -> bool { + let val = (self.0 >> 21usize) & 0x01; + val != 0 + } + #[doc = "VBUS sensing disable"] + #[inline(always)] + pub fn set_novbussens(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 21usize)) | (((val as u32) & 0x01) << 21usize); + } + } + impl Default for GccfgV1 { + #[inline(always)] + fn default() -> GccfgV1 { + GccfgV1(0) + } + } + #[doc = "General core configuration register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct GccfgV2(pub u32); + impl GccfgV2 { + #[doc = "Data contact detection (DCD) status"] + #[inline(always)] + pub const fn dcdet(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "Data contact detection (DCD) status"] + #[inline(always)] + pub fn set_dcdet(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "Primary detection (PD) status"] + #[inline(always)] + pub const fn pdet(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "Primary detection (PD) status"] + #[inline(always)] + pub fn set_pdet(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "Secondary detection (SD) status"] + #[inline(always)] + pub const fn sdet(&self) -> bool { + let val = (self.0 >> 2usize) & 0x01; + val != 0 + } + #[doc = "Secondary detection (SD) status"] + #[inline(always)] + pub fn set_sdet(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 2usize)) | (((val as u32) & 0x01) << 2usize); + } + #[doc = "DM pull-up detection status"] + #[inline(always)] + pub const fn ps2det(&self) -> bool { + let val = (self.0 >> 3usize) & 0x01; + val != 0 + } + #[doc = "DM pull-up detection status"] + #[inline(always)] + pub fn set_ps2det(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 3usize)) | (((val as u32) & 0x01) << 3usize); + } + #[doc = "Power down"] + #[inline(always)] + pub const fn pwrdwn(&self) -> bool { + let val = (self.0 >> 16usize) & 0x01; + val != 0 + } + #[doc = "Power down"] + #[inline(always)] + pub fn set_pwrdwn(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 16usize)) | (((val as u32) & 0x01) << 16usize); + } + #[doc = "Battery charging detector (BCD) enable"] + #[inline(always)] + pub const fn bcden(&self) -> bool { + let val = (self.0 >> 17usize) & 0x01; + val != 0 + } + #[doc = "Battery charging detector (BCD) enable"] + #[inline(always)] + pub fn set_bcden(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 17usize)) | (((val as u32) & 0x01) << 17usize); + } + #[doc = "Data contact detection (DCD) mode enable"] + #[inline(always)] + pub const fn dcden(&self) -> bool { + let val = (self.0 >> 18usize) & 0x01; + val != 0 + } + #[doc = "Data contact detection (DCD) mode enable"] + #[inline(always)] + pub fn set_dcden(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 18usize)) | (((val as u32) & 0x01) << 18usize); + } + #[doc = "Primary detection (PD) mode enable"] + #[inline(always)] + pub const fn pden(&self) -> bool { + let val = (self.0 >> 19usize) & 0x01; + val != 0 + } + #[doc = "Primary detection (PD) mode enable"] + #[inline(always)] + pub fn set_pden(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 19usize)) | (((val as u32) & 0x01) << 19usize); + } + #[doc = "Secondary detection (SD) mode enable"] + #[inline(always)] + pub const fn sden(&self) -> bool { + let val = (self.0 >> 20usize) & 0x01; + val != 0 + } + #[doc = "Secondary detection (SD) mode enable"] + #[inline(always)] + pub fn set_sden(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 20usize)) | (((val as u32) & 0x01) << 20usize); + } + #[doc = "USB VBUS detection enable"] + #[inline(always)] + pub const fn vbden(&self) -> bool { + let val = (self.0 >> 21usize) & 0x01; + val != 0 + } + #[doc = "USB VBUS detection enable"] + #[inline(always)] + pub fn set_vbden(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 21usize)) | (((val as u32) & 0x01) << 21usize); + } + #[doc = "Internal high-speed PHY enable."] + #[inline(always)] + pub const fn phyhsen(&self) -> bool { + let val = (self.0 >> 23usize) & 0x01; + val != 0 + } + #[doc = "Internal high-speed PHY enable."] + #[inline(always)] + pub fn set_phyhsen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 23usize)) | (((val as u32) & 0x01) << 23usize); + } + } + impl Default for GccfgV2 { + #[inline(always)] + fn default() -> GccfgV2 { + GccfgV2(0) + } + } + #[doc = "OTG general core configuration register."] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct GccfgV3(pub u32); + impl GccfgV3 { + #[doc = "Charger detection, result of the current mode (primary or secondary)."] + #[inline(always)] + pub const fn chgdet(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "Charger detection, result of the current mode (primary or secondary)."] + #[inline(always)] + pub fn set_chgdet(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "Single-Ended DP indicator This bit gives the voltage level on DP (also result of the comparison with VLGC threshold as defined in BC v1.2 standard)."] + #[inline(always)] + pub const fn fsvplus(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "Single-Ended DP indicator This bit gives the voltage level on DP (also result of the comparison with VLGC threshold as defined in BC v1.2 standard)."] + #[inline(always)] + pub fn set_fsvplus(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "Single-Ended DM indicator This bit gives the voltage level on DM (also result of the comparison with VLGC threshold as defined in BC v1.2 standard)."] + #[inline(always)] + pub const fn fsvminus(&self) -> bool { + let val = (self.0 >> 2usize) & 0x01; + val != 0 + } + #[doc = "Single-Ended DM indicator This bit gives the voltage level on DM (also result of the comparison with VLGC threshold as defined in BC v1.2 standard)."] + #[inline(always)] + pub fn set_fsvminus(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 2usize)) | (((val as u32) & 0x01) << 2usize); + } + #[doc = "VBUS session indicator Indicates if VBUS is above VBUS session threshold."] + #[inline(always)] + pub const fn sessvld(&self) -> bool { + let val = (self.0 >> 3usize) & 0x01; + val != 0 + } + #[doc = "VBUS session indicator Indicates if VBUS is above VBUS session threshold."] + #[inline(always)] + pub fn set_sessvld(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 3usize)) | (((val as u32) & 0x01) << 3usize); + } + #[doc = "Host CDP behavior enable."] + #[inline(always)] + pub const fn hcdpen(&self) -> bool { + let val = (self.0 >> 16usize) & 0x01; + val != 0 + } + #[doc = "Host CDP behavior enable."] + #[inline(always)] + pub fn set_hcdpen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 16usize)) | (((val as u32) & 0x01) << 16usize); + } + #[doc = "Host CDP port voltage detector enable on DP."] + #[inline(always)] + pub const fn hcdpdeten(&self) -> bool { + let val = (self.0 >> 17usize) & 0x01; + val != 0 + } + #[doc = "Host CDP port voltage detector enable on DP."] + #[inline(always)] + pub fn set_hcdpdeten(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 17usize)) | (((val as u32) & 0x01) << 17usize); + } + #[doc = "Host CDP port Voltage source enable on DM."] + #[inline(always)] + pub const fn hvdmsrcen(&self) -> bool { + let val = (self.0 >> 18usize) & 0x01; + val != 0 + } + #[doc = "Host CDP port Voltage source enable on DM."] + #[inline(always)] + pub fn set_hvdmsrcen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 18usize)) | (((val as u32) & 0x01) << 18usize); + } + #[doc = "Data Contact Detection enable."] + #[inline(always)] + pub const fn dcden(&self) -> bool { + let val = (self.0 >> 19usize) & 0x01; + val != 0 + } + #[doc = "Data Contact Detection enable."] + #[inline(always)] + pub fn set_dcden(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 19usize)) | (((val as u32) & 0x01) << 19usize); + } + #[doc = "Primary detection enable."] + #[inline(always)] + pub const fn pden(&self) -> bool { + let val = (self.0 >> 20usize) & 0x01; + val != 0 + } + #[doc = "Primary detection enable."] + #[inline(always)] + pub fn set_pden(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 20usize)) | (((val as u32) & 0x01) << 20usize); + } + #[doc = "VBUS detection enable Enables VBUS Sensing Comparators in order to detect VBUS presence and/or perform OTG operation."] + #[inline(always)] + pub const fn vbden(&self) -> bool { + let val = (self.0 >> 21usize) & 0x01; + val != 0 + } + #[doc = "VBUS detection enable Enables VBUS Sensing Comparators in order to detect VBUS presence and/or perform OTG operation."] + #[inline(always)] + pub fn set_vbden(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 21usize)) | (((val as u32) & 0x01) << 21usize); + } + #[doc = "Secondary detection enable."] + #[inline(always)] + pub const fn sden(&self) -> bool { + let val = (self.0 >> 22usize) & 0x01; + val != 0 + } + #[doc = "Secondary detection enable."] + #[inline(always)] + pub fn set_sden(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 22usize)) | (((val as u32) & 0x01) << 22usize); + } + #[doc = "Software override value of the VBUS B-session detection."] + #[inline(always)] + pub const fn vbvaloval(&self) -> bool { + let val = (self.0 >> 23usize) & 0x01; + val != 0 + } + #[doc = "Software override value of the VBUS B-session detection."] + #[inline(always)] + pub fn set_vbvaloval(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 23usize)) | (((val as u32) & 0x01) << 23usize); + } + #[doc = "Enables a software override of the VBUS B-session detection."] + #[inline(always)] + pub const fn vbvaloven(&self) -> bool { + let val = (self.0 >> 24usize) & 0x01; + val != 0 + } + #[doc = "Enables a software override of the VBUS B-session detection."] + #[inline(always)] + pub fn set_vbvaloven(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 24usize)) | (((val as u32) & 0x01) << 24usize); + } + #[doc = "Force host mode pull-downs If the ID pin functions are enabled, the host mode pull-downs on DP and DM activate automatically. However, whenever that is not the case, yet host mode is required, this bit must be used to force the pull-downs active."] + #[inline(always)] + pub const fn forcehostpd(&self) -> bool { + let val = (self.0 >> 25usize) & 0x01; + val != 0 + } + #[doc = "Force host mode pull-downs If the ID pin functions are enabled, the host mode pull-downs on DP and DM activate automatically. However, whenever that is not the case, yet host mode is required, this bit must be used to force the pull-downs active."] + #[inline(always)] + pub fn set_forcehostpd(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 25usize)) | (((val as u32) & 0x01) << 25usize); + } + } + impl Default for GccfgV3 { + #[inline(always)] + fn default() -> GccfgV3 { + GccfgV3(0) + } + } + #[doc = "I2C access register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Gi2cctl(pub u32); + impl Gi2cctl { + #[doc = "I2C Read/Write Data"] + #[inline(always)] + pub const fn rwdata(&self) -> u8 { + let val = (self.0 >> 0usize) & 0xff; + val as u8 + } + #[doc = "I2C Read/Write Data"] + #[inline(always)] + pub fn set_rwdata(&mut self, val: u8) { + self.0 = (self.0 & !(0xff << 0usize)) | (((val as u32) & 0xff) << 0usize); + } + #[doc = "I2C Register Address"] + #[inline(always)] + pub const fn regaddr(&self) -> u8 { + let val = (self.0 >> 8usize) & 0xff; + val as u8 + } + #[doc = "I2C Register Address"] + #[inline(always)] + pub fn set_regaddr(&mut self, val: u8) { + self.0 = (self.0 & !(0xff << 8usize)) | (((val as u32) & 0xff) << 8usize); + } + #[doc = "I2C Address"] + #[inline(always)] + pub const fn addr(&self) -> u8 { + let val = (self.0 >> 16usize) & 0x7f; + val as u8 + } + #[doc = "I2C Address"] + #[inline(always)] + pub fn set_addr(&mut self, val: u8) { + self.0 = (self.0 & !(0x7f << 16usize)) | (((val as u32) & 0x7f) << 16usize); + } + #[doc = "I2C Enable"] + #[inline(always)] + pub const fn i2cen(&self) -> bool { + let val = (self.0 >> 23usize) & 0x01; + val != 0 + } + #[doc = "I2C Enable"] + #[inline(always)] + pub fn set_i2cen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 23usize)) | (((val as u32) & 0x01) << 23usize); + } + #[doc = "I2C ACK"] + #[inline(always)] + pub const fn ack(&self) -> bool { + let val = (self.0 >> 24usize) & 0x01; + val != 0 + } + #[doc = "I2C ACK"] + #[inline(always)] + pub fn set_ack(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 24usize)) | (((val as u32) & 0x01) << 24usize); + } + #[doc = "I2C Device Address"] + #[inline(always)] + pub const fn i2cdevadr(&self) -> u8 { + let val = (self.0 >> 26usize) & 0x03; + val as u8 + } + #[doc = "I2C Device Address"] + #[inline(always)] + pub fn set_i2cdevadr(&mut self, val: u8) { + self.0 = (self.0 & !(0x03 << 26usize)) | (((val as u32) & 0x03) << 26usize); + } + #[doc = "I2C DatSe0 USB mode"] + #[inline(always)] + pub const fn i2cdatse0(&self) -> bool { + let val = (self.0 >> 28usize) & 0x01; + val != 0 + } + #[doc = "I2C DatSe0 USB mode"] + #[inline(always)] + pub fn set_i2cdatse0(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 28usize)) | (((val as u32) & 0x01) << 28usize); + } + #[doc = "Read/Write Indicator"] + #[inline(always)] + pub const fn rw(&self) -> bool { + let val = (self.0 >> 30usize) & 0x01; + val != 0 + } + #[doc = "Read/Write Indicator"] + #[inline(always)] + pub fn set_rw(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 30usize)) | (((val as u32) & 0x01) << 30usize); + } + #[doc = "I2C Busy/Done"] + #[inline(always)] + pub const fn bsydne(&self) -> bool { + let val = (self.0 >> 31usize) & 0x01; + val != 0 + } + #[doc = "I2C Busy/Done"] + #[inline(always)] + pub fn set_bsydne(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 31usize)) | (((val as u32) & 0x01) << 31usize); + } + } + impl Default for Gi2cctl { + #[inline(always)] + fn default() -> Gi2cctl { + Gi2cctl(0) + } + } + #[doc = "Interrupt mask register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Gintmsk(pub u32); + impl Gintmsk { + #[doc = "Mode mismatch interrupt mask"] + #[inline(always)] + pub const fn mmism(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "Mode mismatch interrupt mask"] + #[inline(always)] + pub fn set_mmism(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "OTG interrupt mask"] + #[inline(always)] + pub const fn otgint(&self) -> bool { + let val = (self.0 >> 2usize) & 0x01; + val != 0 + } + #[doc = "OTG interrupt mask"] + #[inline(always)] + pub fn set_otgint(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 2usize)) | (((val as u32) & 0x01) << 2usize); + } + #[doc = "Start of frame mask"] + #[inline(always)] + pub const fn sofm(&self) -> bool { + let val = (self.0 >> 3usize) & 0x01; + val != 0 + } + #[doc = "Start of frame mask"] + #[inline(always)] + pub fn set_sofm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 3usize)) | (((val as u32) & 0x01) << 3usize); + } + #[doc = "Receive FIFO non-empty mask"] + #[inline(always)] + pub const fn rxflvlm(&self) -> bool { + let val = (self.0 >> 4usize) & 0x01; + val != 0 + } + #[doc = "Receive FIFO non-empty mask"] + #[inline(always)] + pub fn set_rxflvlm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 4usize)) | (((val as u32) & 0x01) << 4usize); + } + #[doc = "Non-periodic TxFIFO empty mask"] + #[inline(always)] + pub const fn nptxfem(&self) -> bool { + let val = (self.0 >> 5usize) & 0x01; + val != 0 + } + #[doc = "Non-periodic TxFIFO empty mask"] + #[inline(always)] + pub fn set_nptxfem(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 5usize)) | (((val as u32) & 0x01) << 5usize); + } + #[doc = "Global non-periodic IN NAK effective mask"] + #[inline(always)] + pub const fn ginakeffm(&self) -> bool { + let val = (self.0 >> 6usize) & 0x01; + val != 0 + } + #[doc = "Global non-periodic IN NAK effective mask"] + #[inline(always)] + pub fn set_ginakeffm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 6usize)) | (((val as u32) & 0x01) << 6usize); + } + #[doc = "Global OUT NAK effective mask"] + #[inline(always)] + pub const fn gonakeffm(&self) -> bool { + let val = (self.0 >> 7usize) & 0x01; + val != 0 + } + #[doc = "Global OUT NAK effective mask"] + #[inline(always)] + pub fn set_gonakeffm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 7usize)) | (((val as u32) & 0x01) << 7usize); + } + #[doc = "Early suspend mask"] + #[inline(always)] + pub const fn esuspm(&self) -> bool { + let val = (self.0 >> 10usize) & 0x01; + val != 0 + } + #[doc = "Early suspend mask"] + #[inline(always)] + pub fn set_esuspm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 10usize)) | (((val as u32) & 0x01) << 10usize); + } + #[doc = "USB suspend mask"] + #[inline(always)] + pub const fn usbsuspm(&self) -> bool { + let val = (self.0 >> 11usize) & 0x01; + val != 0 + } + #[doc = "USB suspend mask"] + #[inline(always)] + pub fn set_usbsuspm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 11usize)) | (((val as u32) & 0x01) << 11usize); + } + #[doc = "USB reset mask"] + #[inline(always)] + pub const fn usbrst(&self) -> bool { + let val = (self.0 >> 12usize) & 0x01; + val != 0 + } + #[doc = "USB reset mask"] + #[inline(always)] + pub fn set_usbrst(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 12usize)) | (((val as u32) & 0x01) << 12usize); + } + #[doc = "Enumeration done mask"] + #[inline(always)] + pub const fn enumdnem(&self) -> bool { + let val = (self.0 >> 13usize) & 0x01; + val != 0 + } + #[doc = "Enumeration done mask"] + #[inline(always)] + pub fn set_enumdnem(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 13usize)) | (((val as u32) & 0x01) << 13usize); + } + #[doc = "Isochronous OUT packet dropped interrupt mask"] + #[inline(always)] + pub const fn isoodrpm(&self) -> bool { + let val = (self.0 >> 14usize) & 0x01; + val != 0 + } + #[doc = "Isochronous OUT packet dropped interrupt mask"] + #[inline(always)] + pub fn set_isoodrpm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 14usize)) | (((val as u32) & 0x01) << 14usize); + } + #[doc = "End of periodic frame interrupt mask"] + #[inline(always)] + pub const fn eopfm(&self) -> bool { + let val = (self.0 >> 15usize) & 0x01; + val != 0 + } + #[doc = "End of periodic frame interrupt mask"] + #[inline(always)] + pub fn set_eopfm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 15usize)) | (((val as u32) & 0x01) << 15usize); + } + #[doc = "Endpoint mismatch interrupt mask"] + #[inline(always)] + pub const fn epmism(&self) -> bool { + let val = (self.0 >> 17usize) & 0x01; + val != 0 + } + #[doc = "Endpoint mismatch interrupt mask"] + #[inline(always)] + pub fn set_epmism(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 17usize)) | (((val as u32) & 0x01) << 17usize); + } + #[doc = "IN endpoints interrupt mask"] + #[inline(always)] + pub const fn iepint(&self) -> bool { + let val = (self.0 >> 18usize) & 0x01; + val != 0 + } + #[doc = "IN endpoints interrupt mask"] + #[inline(always)] + pub fn set_iepint(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 18usize)) | (((val as u32) & 0x01) << 18usize); + } + #[doc = "OUT endpoints interrupt mask"] + #[inline(always)] + pub const fn oepint(&self) -> bool { + let val = (self.0 >> 19usize) & 0x01; + val != 0 + } + #[doc = "OUT endpoints interrupt mask"] + #[inline(always)] + pub fn set_oepint(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 19usize)) | (((val as u32) & 0x01) << 19usize); + } + #[doc = "Incomplete isochronous IN transfer mask"] + #[inline(always)] + pub const fn iisoixfrm(&self) -> bool { + let val = (self.0 >> 20usize) & 0x01; + val != 0 + } + #[doc = "Incomplete isochronous IN transfer mask"] + #[inline(always)] + pub fn set_iisoixfrm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 20usize)) | (((val as u32) & 0x01) << 20usize); + } + #[doc = "Incomplete periodic transfer mask (host mode) / Incomplete isochronous OUT transfer mask (device mode)"] + #[inline(always)] + pub const fn ipxfrm_iisooxfrm(&self) -> bool { + let val = (self.0 >> 21usize) & 0x01; + val != 0 + } + #[doc = "Incomplete periodic transfer mask (host mode) / Incomplete isochronous OUT transfer mask (device mode)"] + #[inline(always)] + pub fn set_ipxfrm_iisooxfrm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 21usize)) | (((val as u32) & 0x01) << 21usize); + } + #[doc = "Data fetch suspended mask"] + #[inline(always)] + pub const fn fsuspm(&self) -> bool { + let val = (self.0 >> 22usize) & 0x01; + val != 0 + } + #[doc = "Data fetch suspended mask"] + #[inline(always)] + pub fn set_fsuspm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 22usize)) | (((val as u32) & 0x01) << 22usize); + } + #[doc = "Reset detected interrupt mask"] + #[inline(always)] + pub const fn rstde(&self) -> bool { + let val = (self.0 >> 23usize) & 0x01; + val != 0 + } + #[doc = "Reset detected interrupt mask"] + #[inline(always)] + pub fn set_rstde(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 23usize)) | (((val as u32) & 0x01) << 23usize); + } + #[doc = "Host port interrupt mask"] + #[inline(always)] + pub const fn prtim(&self) -> bool { + let val = (self.0 >> 24usize) & 0x01; + val != 0 + } + #[doc = "Host port interrupt mask"] + #[inline(always)] + pub fn set_prtim(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 24usize)) | (((val as u32) & 0x01) << 24usize); + } + #[doc = "Host channels interrupt mask"] + #[inline(always)] + pub const fn hcim(&self) -> bool { + let val = (self.0 >> 25usize) & 0x01; + val != 0 + } + #[doc = "Host channels interrupt mask"] + #[inline(always)] + pub fn set_hcim(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 25usize)) | (((val as u32) & 0x01) << 25usize); + } + #[doc = "Periodic TxFIFO empty mask"] + #[inline(always)] + pub const fn ptxfem(&self) -> bool { + let val = (self.0 >> 26usize) & 0x01; + val != 0 + } + #[doc = "Periodic TxFIFO empty mask"] + #[inline(always)] + pub fn set_ptxfem(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 26usize)) | (((val as u32) & 0x01) << 26usize); + } + #[doc = "LPM interrupt mask"] + #[inline(always)] + pub const fn lpmintm(&self) -> bool { + let val = (self.0 >> 27usize) & 0x01; + val != 0 + } + #[doc = "LPM interrupt mask"] + #[inline(always)] + pub fn set_lpmintm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 27usize)) | (((val as u32) & 0x01) << 27usize); + } + #[doc = "Connector ID status change mask"] + #[inline(always)] + pub const fn cidschgm(&self) -> bool { + let val = (self.0 >> 28usize) & 0x01; + val != 0 + } + #[doc = "Connector ID status change mask"] + #[inline(always)] + pub fn set_cidschgm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 28usize)) | (((val as u32) & 0x01) << 28usize); + } + #[doc = "Disconnect detected interrupt mask"] + #[inline(always)] + pub const fn discint(&self) -> bool { + let val = (self.0 >> 29usize) & 0x01; + val != 0 + } + #[doc = "Disconnect detected interrupt mask"] + #[inline(always)] + pub fn set_discint(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 29usize)) | (((val as u32) & 0x01) << 29usize); + } + #[doc = "Session request/new session detected interrupt mask"] + #[inline(always)] + pub const fn srqim(&self) -> bool { + let val = (self.0 >> 30usize) & 0x01; + val != 0 + } + #[doc = "Session request/new session detected interrupt mask"] + #[inline(always)] + pub fn set_srqim(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 30usize)) | (((val as u32) & 0x01) << 30usize); + } + #[doc = "Resume/remote wakeup detected interrupt mask"] + #[inline(always)] + pub const fn wuim(&self) -> bool { + let val = (self.0 >> 31usize) & 0x01; + val != 0 + } + #[doc = "Resume/remote wakeup detected interrupt mask"] + #[inline(always)] + pub fn set_wuim(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 31usize)) | (((val as u32) & 0x01) << 31usize); + } + } + impl Default for Gintmsk { + #[inline(always)] + fn default() -> Gintmsk { + Gintmsk(0) + } + } + #[doc = "Core interrupt register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Gintsts(pub u32); + impl Gintsts { + #[doc = "Current mode of operation"] + #[inline(always)] + pub const fn cmod(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "Current mode of operation"] + #[inline(always)] + pub fn set_cmod(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "Mode mismatch interrupt"] + #[inline(always)] + pub const fn mmis(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "Mode mismatch interrupt"] + #[inline(always)] + pub fn set_mmis(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "OTG interrupt"] + #[inline(always)] + pub const fn otgint(&self) -> bool { + let val = (self.0 >> 2usize) & 0x01; + val != 0 + } + #[doc = "OTG interrupt"] + #[inline(always)] + pub fn set_otgint(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 2usize)) | (((val as u32) & 0x01) << 2usize); + } + #[doc = "Start of frame"] + #[inline(always)] + pub const fn sof(&self) -> bool { + let val = (self.0 >> 3usize) & 0x01; + val != 0 + } + #[doc = "Start of frame"] + #[inline(always)] + pub fn set_sof(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 3usize)) | (((val as u32) & 0x01) << 3usize); + } + #[doc = "RxFIFO non-empty"] + #[inline(always)] + pub const fn rxflvl(&self) -> bool { + let val = (self.0 >> 4usize) & 0x01; + val != 0 + } + #[doc = "RxFIFO non-empty"] + #[inline(always)] + pub fn set_rxflvl(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 4usize)) | (((val as u32) & 0x01) << 4usize); + } + #[doc = "Non-periodic TxFIFO empty"] + #[inline(always)] + pub const fn nptxfe(&self) -> bool { + let val = (self.0 >> 5usize) & 0x01; + val != 0 + } + #[doc = "Non-periodic TxFIFO empty"] + #[inline(always)] + pub fn set_nptxfe(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 5usize)) | (((val as u32) & 0x01) << 5usize); + } + #[doc = "Global IN non-periodic NAK effective"] + #[inline(always)] + pub const fn ginakeff(&self) -> bool { + let val = (self.0 >> 6usize) & 0x01; + val != 0 + } + #[doc = "Global IN non-periodic NAK effective"] + #[inline(always)] + pub fn set_ginakeff(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 6usize)) | (((val as u32) & 0x01) << 6usize); + } + #[doc = "Global OUT NAK effective"] + #[inline(always)] + pub const fn goutnakeff(&self) -> bool { + let val = (self.0 >> 7usize) & 0x01; + val != 0 + } + #[doc = "Global OUT NAK effective"] + #[inline(always)] + pub fn set_goutnakeff(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 7usize)) | (((val as u32) & 0x01) << 7usize); + } + #[doc = "Early suspend"] + #[inline(always)] + pub const fn esusp(&self) -> bool { + let val = (self.0 >> 10usize) & 0x01; + val != 0 + } + #[doc = "Early suspend"] + #[inline(always)] + pub fn set_esusp(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 10usize)) | (((val as u32) & 0x01) << 10usize); + } + #[doc = "USB suspend"] + #[inline(always)] + pub const fn usbsusp(&self) -> bool { + let val = (self.0 >> 11usize) & 0x01; + val != 0 + } + #[doc = "USB suspend"] + #[inline(always)] + pub fn set_usbsusp(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 11usize)) | (((val as u32) & 0x01) << 11usize); + } + #[doc = "USB reset"] + #[inline(always)] + pub const fn usbrst(&self) -> bool { + let val = (self.0 >> 12usize) & 0x01; + val != 0 + } + #[doc = "USB reset"] + #[inline(always)] + pub fn set_usbrst(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 12usize)) | (((val as u32) & 0x01) << 12usize); + } + #[doc = "Enumeration done"] + #[inline(always)] + pub const fn enumdne(&self) -> bool { + let val = (self.0 >> 13usize) & 0x01; + val != 0 + } + #[doc = "Enumeration done"] + #[inline(always)] + pub fn set_enumdne(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 13usize)) | (((val as u32) & 0x01) << 13usize); + } + #[doc = "Isochronous OUT packet dropped interrupt"] + #[inline(always)] + pub const fn isoodrp(&self) -> bool { + let val = (self.0 >> 14usize) & 0x01; + val != 0 + } + #[doc = "Isochronous OUT packet dropped interrupt"] + #[inline(always)] + pub fn set_isoodrp(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 14usize)) | (((val as u32) & 0x01) << 14usize); + } + #[doc = "End of periodic frame interrupt"] + #[inline(always)] + pub const fn eopf(&self) -> bool { + let val = (self.0 >> 15usize) & 0x01; + val != 0 + } + #[doc = "End of periodic frame interrupt"] + #[inline(always)] + pub fn set_eopf(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 15usize)) | (((val as u32) & 0x01) << 15usize); + } + #[doc = "IN endpoint interrupt"] + #[inline(always)] + pub const fn iepint(&self) -> bool { + let val = (self.0 >> 18usize) & 0x01; + val != 0 + } + #[doc = "IN endpoint interrupt"] + #[inline(always)] + pub fn set_iepint(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 18usize)) | (((val as u32) & 0x01) << 18usize); + } + #[doc = "OUT endpoint interrupt"] + #[inline(always)] + pub const fn oepint(&self) -> bool { + let val = (self.0 >> 19usize) & 0x01; + val != 0 + } + #[doc = "OUT endpoint interrupt"] + #[inline(always)] + pub fn set_oepint(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 19usize)) | (((val as u32) & 0x01) << 19usize); + } + #[doc = "Incomplete isochronous IN transfer"] + #[inline(always)] + pub const fn iisoixfr(&self) -> bool { + let val = (self.0 >> 20usize) & 0x01; + val != 0 + } + #[doc = "Incomplete isochronous IN transfer"] + #[inline(always)] + pub fn set_iisoixfr(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 20usize)) | (((val as u32) & 0x01) << 20usize); + } + #[doc = "Incomplete periodic transfer (host mode) / Incomplete isochronous OUT transfer (device mode)"] + #[inline(always)] + pub const fn ipxfr_incompisoout(&self) -> bool { + let val = (self.0 >> 21usize) & 0x01; + val != 0 + } + #[doc = "Incomplete periodic transfer (host mode) / Incomplete isochronous OUT transfer (device mode)"] + #[inline(always)] + pub fn set_ipxfr_incompisoout(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 21usize)) | (((val as u32) & 0x01) << 21usize); + } + #[doc = "Data fetch suspended"] + #[inline(always)] + pub const fn datafsusp(&self) -> bool { + let val = (self.0 >> 22usize) & 0x01; + val != 0 + } + #[doc = "Data fetch suspended"] + #[inline(always)] + pub fn set_datafsusp(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 22usize)) | (((val as u32) & 0x01) << 22usize); + } + #[doc = "Host port interrupt"] + #[inline(always)] + pub const fn hprtint(&self) -> bool { + let val = (self.0 >> 24usize) & 0x01; + val != 0 + } + #[doc = "Host port interrupt"] + #[inline(always)] + pub fn set_hprtint(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 24usize)) | (((val as u32) & 0x01) << 24usize); + } + #[doc = "Host channels interrupt"] + #[inline(always)] + pub const fn hcint(&self) -> bool { + let val = (self.0 >> 25usize) & 0x01; + val != 0 + } + #[doc = "Host channels interrupt"] + #[inline(always)] + pub fn set_hcint(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 25usize)) | (((val as u32) & 0x01) << 25usize); + } + #[doc = "Periodic TxFIFO empty"] + #[inline(always)] + pub const fn ptxfe(&self) -> bool { + let val = (self.0 >> 26usize) & 0x01; + val != 0 + } + #[doc = "Periodic TxFIFO empty"] + #[inline(always)] + pub fn set_ptxfe(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 26usize)) | (((val as u32) & 0x01) << 26usize); + } + #[doc = "Connector ID status change"] + #[inline(always)] + pub const fn cidschg(&self) -> bool { + let val = (self.0 >> 28usize) & 0x01; + val != 0 + } + #[doc = "Connector ID status change"] + #[inline(always)] + pub fn set_cidschg(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 28usize)) | (((val as u32) & 0x01) << 28usize); + } + #[doc = "Disconnect detected interrupt"] + #[inline(always)] + pub const fn discint(&self) -> bool { + let val = (self.0 >> 29usize) & 0x01; + val != 0 + } + #[doc = "Disconnect detected interrupt"] + #[inline(always)] + pub fn set_discint(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 29usize)) | (((val as u32) & 0x01) << 29usize); + } + #[doc = "Session request/new session detected interrupt"] + #[inline(always)] + pub const fn srqint(&self) -> bool { + let val = (self.0 >> 30usize) & 0x01; + val != 0 + } + #[doc = "Session request/new session detected interrupt"] + #[inline(always)] + pub fn set_srqint(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 30usize)) | (((val as u32) & 0x01) << 30usize); + } + #[doc = "Resume/remote wakeup detected interrupt"] + #[inline(always)] + pub const fn wkupint(&self) -> bool { + let val = (self.0 >> 31usize) & 0x01; + val != 0 + } + #[doc = "Resume/remote wakeup detected interrupt"] + #[inline(always)] + pub fn set_wkupint(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 31usize)) | (((val as u32) & 0x01) << 31usize); + } + } + impl Default for Gintsts { + #[inline(always)] + fn default() -> Gintsts { + Gintsts(0) + } + } + #[doc = "Core LPM configuration register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Glpmcfg(pub u32); + impl Glpmcfg { + #[doc = "LPM support enable"] + #[inline(always)] + pub const fn lpmen(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "LPM support enable"] + #[inline(always)] + pub fn set_lpmen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "LPM token acknowledge enable"] + #[inline(always)] + pub const fn lpmack(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "LPM token acknowledge enable"] + #[inline(always)] + pub fn set_lpmack(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "Best effort service latency"] + #[inline(always)] + pub const fn besl(&self) -> u8 { + let val = (self.0 >> 2usize) & 0x0f; + val as u8 + } + #[doc = "Best effort service latency"] + #[inline(always)] + pub fn set_besl(&mut self, val: u8) { + self.0 = (self.0 & !(0x0f << 2usize)) | (((val as u32) & 0x0f) << 2usize); + } + #[doc = "bRemoteWake value"] + #[inline(always)] + pub const fn remwake(&self) -> bool { + let val = (self.0 >> 6usize) & 0x01; + val != 0 + } + #[doc = "bRemoteWake value"] + #[inline(always)] + pub fn set_remwake(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 6usize)) | (((val as u32) & 0x01) << 6usize); + } + #[doc = "L1 Shallow Sleep enable"] + #[inline(always)] + pub const fn l1ssen(&self) -> bool { + let val = (self.0 >> 7usize) & 0x01; + val != 0 + } + #[doc = "L1 Shallow Sleep enable"] + #[inline(always)] + pub fn set_l1ssen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 7usize)) | (((val as u32) & 0x01) << 7usize); + } + #[doc = "BESL threshold"] + #[inline(always)] + pub const fn beslthrs(&self) -> u8 { + let val = (self.0 >> 8usize) & 0x0f; + val as u8 + } + #[doc = "BESL threshold"] + #[inline(always)] + pub fn set_beslthrs(&mut self, val: u8) { + self.0 = (self.0 & !(0x0f << 8usize)) | (((val as u32) & 0x0f) << 8usize); + } + #[doc = "L1 deep sleep enable"] + #[inline(always)] + pub const fn l1dsen(&self) -> bool { + let val = (self.0 >> 12usize) & 0x01; + val != 0 + } + #[doc = "L1 deep sleep enable"] + #[inline(always)] + pub fn set_l1dsen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 12usize)) | (((val as u32) & 0x01) << 12usize); + } + #[doc = "LPM response"] + #[inline(always)] + pub const fn lpmrst(&self) -> u8 { + let val = (self.0 >> 13usize) & 0x03; + val as u8 + } + #[doc = "LPM response"] + #[inline(always)] + pub fn set_lpmrst(&mut self, val: u8) { + self.0 = (self.0 & !(0x03 << 13usize)) | (((val as u32) & 0x03) << 13usize); + } + #[doc = "Port sleep status"] + #[inline(always)] + pub const fn slpsts(&self) -> bool { + let val = (self.0 >> 15usize) & 0x01; + val != 0 + } + #[doc = "Port sleep status"] + #[inline(always)] + pub fn set_slpsts(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 15usize)) | (((val as u32) & 0x01) << 15usize); + } + #[doc = "Sleep State Resume OK"] + #[inline(always)] + pub const fn l1rsmok(&self) -> bool { + let val = (self.0 >> 16usize) & 0x01; + val != 0 + } + #[doc = "Sleep State Resume OK"] + #[inline(always)] + pub fn set_l1rsmok(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 16usize)) | (((val as u32) & 0x01) << 16usize); + } + #[doc = "LPM Channel Index"] + #[inline(always)] + pub const fn lpmchidx(&self) -> u8 { + let val = (self.0 >> 17usize) & 0x0f; + val as u8 + } + #[doc = "LPM Channel Index"] + #[inline(always)] + pub fn set_lpmchidx(&mut self, val: u8) { + self.0 = (self.0 & !(0x0f << 17usize)) | (((val as u32) & 0x0f) << 17usize); + } + #[doc = "LPM retry count"] + #[inline(always)] + pub const fn lpmrcnt(&self) -> u8 { + let val = (self.0 >> 21usize) & 0x07; + val as u8 + } + #[doc = "LPM retry count"] + #[inline(always)] + pub fn set_lpmrcnt(&mut self, val: u8) { + self.0 = (self.0 & !(0x07 << 21usize)) | (((val as u32) & 0x07) << 21usize); + } + #[doc = "Send LPM transaction"] + #[inline(always)] + pub const fn sndlpm(&self) -> bool { + let val = (self.0 >> 24usize) & 0x01; + val != 0 + } + #[doc = "Send LPM transaction"] + #[inline(always)] + pub fn set_sndlpm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 24usize)) | (((val as u32) & 0x01) << 24usize); + } + #[doc = "LPM retry count status"] + #[inline(always)] + pub const fn lpmrcntsts(&self) -> u8 { + let val = (self.0 >> 25usize) & 0x07; + val as u8 + } + #[doc = "LPM retry count status"] + #[inline(always)] + pub fn set_lpmrcntsts(&mut self, val: u8) { + self.0 = (self.0 & !(0x07 << 25usize)) | (((val as u32) & 0x07) << 25usize); + } + #[doc = "Enable best effort service latency"] + #[inline(always)] + pub const fn enbesl(&self) -> bool { + let val = (self.0 >> 28usize) & 0x01; + val != 0 + } + #[doc = "Enable best effort service latency"] + #[inline(always)] + pub fn set_enbesl(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 28usize)) | (((val as u32) & 0x01) << 28usize); + } + } + impl Default for Glpmcfg { + #[inline(always)] + fn default() -> Glpmcfg { + Glpmcfg(0) + } + } + #[doc = "Control and status register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Gotgctl(pub u32); + impl Gotgctl { + #[doc = "Session request success"] + #[inline(always)] + pub const fn srqscs(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "Session request success"] + #[inline(always)] + pub fn set_srqscs(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "Session request"] + #[inline(always)] + pub const fn srq(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "Session request"] + #[inline(always)] + pub fn set_srq(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "VBUS valid override enable"] + #[inline(always)] + pub const fn vbvaloen(&self) -> bool { + let val = (self.0 >> 2usize) & 0x01; + val != 0 + } + #[doc = "VBUS valid override enable"] + #[inline(always)] + pub fn set_vbvaloen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 2usize)) | (((val as u32) & 0x01) << 2usize); + } + #[doc = "VBUS valid override value"] + #[inline(always)] + pub const fn vbvaloval(&self) -> bool { + let val = (self.0 >> 3usize) & 0x01; + val != 0 + } + #[doc = "VBUS valid override value"] + #[inline(always)] + pub fn set_vbvaloval(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 3usize)) | (((val as u32) & 0x01) << 3usize); + } + #[doc = "A-peripheral session valid override enable"] + #[inline(always)] + pub const fn avaloen(&self) -> bool { + let val = (self.0 >> 4usize) & 0x01; + val != 0 + } + #[doc = "A-peripheral session valid override enable"] + #[inline(always)] + pub fn set_avaloen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 4usize)) | (((val as u32) & 0x01) << 4usize); + } + #[doc = "A-peripheral session valid override value"] + #[inline(always)] + pub const fn avaloval(&self) -> bool { + let val = (self.0 >> 5usize) & 0x01; + val != 0 + } + #[doc = "A-peripheral session valid override value"] + #[inline(always)] + pub fn set_avaloval(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 5usize)) | (((val as u32) & 0x01) << 5usize); + } + #[doc = "B-peripheral session valid override enable"] + #[inline(always)] + pub const fn bvaloen(&self) -> bool { + let val = (self.0 >> 6usize) & 0x01; + val != 0 + } + #[doc = "B-peripheral session valid override enable"] + #[inline(always)] + pub fn set_bvaloen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 6usize)) | (((val as u32) & 0x01) << 6usize); + } + #[doc = "B-peripheral session valid override value"] + #[inline(always)] + pub const fn bvaloval(&self) -> bool { + let val = (self.0 >> 7usize) & 0x01; + val != 0 + } + #[doc = "B-peripheral session valid override value"] + #[inline(always)] + pub fn set_bvaloval(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 7usize)) | (((val as u32) & 0x01) << 7usize); + } + #[doc = "Host negotiation success"] + #[inline(always)] + pub const fn hngscs(&self) -> bool { + let val = (self.0 >> 8usize) & 0x01; + val != 0 + } + #[doc = "Host negotiation success"] + #[inline(always)] + pub fn set_hngscs(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 8usize)) | (((val as u32) & 0x01) << 8usize); + } + #[doc = "HNP request"] + #[inline(always)] + pub const fn hnprq(&self) -> bool { + let val = (self.0 >> 9usize) & 0x01; + val != 0 + } + #[doc = "HNP request"] + #[inline(always)] + pub fn set_hnprq(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 9usize)) | (((val as u32) & 0x01) << 9usize); + } + #[doc = "Host set HNP enable"] + #[inline(always)] + pub const fn hshnpen(&self) -> bool { + let val = (self.0 >> 10usize) & 0x01; + val != 0 + } + #[doc = "Host set HNP enable"] + #[inline(always)] + pub fn set_hshnpen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 10usize)) | (((val as u32) & 0x01) << 10usize); + } + #[doc = "Device HNP enabled"] + #[inline(always)] + pub const fn dhnpen(&self) -> bool { + let val = (self.0 >> 11usize) & 0x01; + val != 0 + } + #[doc = "Device HNP enabled"] + #[inline(always)] + pub fn set_dhnpen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 11usize)) | (((val as u32) & 0x01) << 11usize); + } + #[doc = "Embedded host enable"] + #[inline(always)] + pub const fn ehen(&self) -> bool { + let val = (self.0 >> 12usize) & 0x01; + val != 0 + } + #[doc = "Embedded host enable"] + #[inline(always)] + pub fn set_ehen(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 12usize)) | (((val as u32) & 0x01) << 12usize); + } + #[doc = "Connector ID status"] + #[inline(always)] + pub const fn cidsts(&self) -> bool { + let val = (self.0 >> 16usize) & 0x01; + val != 0 + } + #[doc = "Connector ID status"] + #[inline(always)] + pub fn set_cidsts(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 16usize)) | (((val as u32) & 0x01) << 16usize); + } + #[doc = "Long/short debounce time"] + #[inline(always)] + pub const fn dbct(&self) -> bool { + let val = (self.0 >> 17usize) & 0x01; + val != 0 + } + #[doc = "Long/short debounce time"] + #[inline(always)] + pub fn set_dbct(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 17usize)) | (((val as u32) & 0x01) << 17usize); + } + #[doc = "A-session valid"] + #[inline(always)] + pub const fn asvld(&self) -> bool { + let val = (self.0 >> 18usize) & 0x01; + val != 0 + } + #[doc = "A-session valid"] + #[inline(always)] + pub fn set_asvld(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 18usize)) | (((val as u32) & 0x01) << 18usize); + } + #[doc = "B-session valid"] + #[inline(always)] + pub const fn bsvld(&self) -> bool { + let val = (self.0 >> 19usize) & 0x01; + val != 0 + } + #[doc = "B-session valid"] + #[inline(always)] + pub fn set_bsvld(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 19usize)) | (((val as u32) & 0x01) << 19usize); + } + } + impl Default for Gotgctl { + #[inline(always)] + fn default() -> Gotgctl { + Gotgctl(0) + } + } + #[doc = "Interrupt register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Gotgint(pub u32); + impl Gotgint { + #[doc = "Session end detected"] + #[inline(always)] + pub const fn sedet(&self) -> bool { + let val = (self.0 >> 2usize) & 0x01; + val != 0 + } + #[doc = "Session end detected"] + #[inline(always)] + pub fn set_sedet(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 2usize)) | (((val as u32) & 0x01) << 2usize); + } + #[doc = "Session request success status change"] + #[inline(always)] + pub const fn srsschg(&self) -> bool { + let val = (self.0 >> 8usize) & 0x01; + val != 0 + } + #[doc = "Session request success status change"] + #[inline(always)] + pub fn set_srsschg(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 8usize)) | (((val as u32) & 0x01) << 8usize); + } + #[doc = "Host negotiation success status change"] + #[inline(always)] + pub const fn hnsschg(&self) -> bool { + let val = (self.0 >> 9usize) & 0x01; + val != 0 + } + #[doc = "Host negotiation success status change"] + #[inline(always)] + pub fn set_hnsschg(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 9usize)) | (((val as u32) & 0x01) << 9usize); + } + #[doc = "Host negotiation detected"] + #[inline(always)] + pub const fn hngdet(&self) -> bool { + let val = (self.0 >> 17usize) & 0x01; + val != 0 + } + #[doc = "Host negotiation detected"] + #[inline(always)] + pub fn set_hngdet(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 17usize)) | (((val as u32) & 0x01) << 17usize); + } + #[doc = "A-device timeout change"] + #[inline(always)] + pub const fn adtochg(&self) -> bool { + let val = (self.0 >> 18usize) & 0x01; + val != 0 + } + #[doc = "A-device timeout change"] + #[inline(always)] + pub fn set_adtochg(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 18usize)) | (((val as u32) & 0x01) << 18usize); + } + #[doc = "Debounce done"] + #[inline(always)] + pub const fn dbcdne(&self) -> bool { + let val = (self.0 >> 19usize) & 0x01; + val != 0 + } + #[doc = "Debounce done"] + #[inline(always)] + pub fn set_dbcdne(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 19usize)) | (((val as u32) & 0x01) << 19usize); + } + #[doc = "ID input pin changed"] + #[inline(always)] + pub const fn idchng(&self) -> bool { + let val = (self.0 >> 20usize) & 0x01; + val != 0 + } + #[doc = "ID input pin changed"] + #[inline(always)] + pub fn set_idchng(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 20usize)) | (((val as u32) & 0x01) << 20usize); + } + } + impl Default for Gotgint { + #[inline(always)] + fn default() -> Gotgint { + Gotgint(0) + } + } + #[doc = "Reset register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Grstctl(pub u32); + impl Grstctl { + #[doc = "Core soft reset"] + #[inline(always)] + pub const fn csrst(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "Core soft reset"] + #[inline(always)] + pub fn set_csrst(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "HCLK soft reset"] + #[inline(always)] + pub const fn hsrst(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "HCLK soft reset"] + #[inline(always)] + pub fn set_hsrst(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "Host frame counter reset"] + #[inline(always)] + pub const fn fcrst(&self) -> bool { + let val = (self.0 >> 2usize) & 0x01; + val != 0 + } + #[doc = "Host frame counter reset"] + #[inline(always)] + pub fn set_fcrst(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 2usize)) | (((val as u32) & 0x01) << 2usize); + } + #[doc = "RxFIFO flush"] + #[inline(always)] + pub const fn rxfflsh(&self) -> bool { + let val = (self.0 >> 4usize) & 0x01; + val != 0 + } + #[doc = "RxFIFO flush"] + #[inline(always)] + pub fn set_rxfflsh(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 4usize)) | (((val as u32) & 0x01) << 4usize); + } + #[doc = "TxFIFO flush"] + #[inline(always)] + pub const fn txfflsh(&self) -> bool { + let val = (self.0 >> 5usize) & 0x01; + val != 0 + } + #[doc = "TxFIFO flush"] + #[inline(always)] + pub fn set_txfflsh(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 5usize)) | (((val as u32) & 0x01) << 5usize); + } + #[doc = "TxFIFO number"] + #[inline(always)] + pub const fn txfnum(&self) -> u8 { + let val = (self.0 >> 6usize) & 0x1f; + val as u8 + } + #[doc = "TxFIFO number"] + #[inline(always)] + pub fn set_txfnum(&mut self, val: u8) { + self.0 = (self.0 & !(0x1f << 6usize)) | (((val as u32) & 0x1f) << 6usize); + } + #[doc = "DMA request signal enabled for USB OTG HS"] + #[inline(always)] + pub const fn dmareq(&self) -> bool { + let val = (self.0 >> 30usize) & 0x01; + val != 0 + } + #[doc = "DMA request signal enabled for USB OTG HS"] + #[inline(always)] + pub fn set_dmareq(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 30usize)) | (((val as u32) & 0x01) << 30usize); + } + #[doc = "AHB master idle"] + #[inline(always)] + pub const fn ahbidl(&self) -> bool { + let val = (self.0 >> 31usize) & 0x01; + val != 0 + } + #[doc = "AHB master idle"] + #[inline(always)] + pub fn set_ahbidl(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 31usize)) | (((val as u32) & 0x01) << 31usize); + } + } + impl Default for Grstctl { + #[inline(always)] + fn default() -> Grstctl { + Grstctl(0) + } + } + #[doc = "Receive FIFO size register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Grxfsiz(pub u32); + impl Grxfsiz { + #[doc = "RxFIFO depth"] + #[inline(always)] + pub const fn rxfd(&self) -> u16 { + let val = (self.0 >> 0usize) & 0xffff; + val as u16 + } + #[doc = "RxFIFO depth"] + #[inline(always)] + pub fn set_rxfd(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 0usize)) | (((val as u32) & 0xffff) << 0usize); + } + } + impl Default for Grxfsiz { + #[inline(always)] + fn default() -> Grxfsiz { + Grxfsiz(0) + } + } + #[doc = "Status read and pop register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Grxsts(pub u32); + impl Grxsts { + #[doc = "Endpoint number (device mode) / Channel number (host mode)"] + #[inline(always)] + pub const fn epnum(&self) -> u8 { + let val = (self.0 >> 0usize) & 0x0f; + val as u8 + } + #[doc = "Endpoint number (device mode) / Channel number (host mode)"] + #[inline(always)] + pub fn set_epnum(&mut self, val: u8) { + self.0 = (self.0 & !(0x0f << 0usize)) | (((val as u32) & 0x0f) << 0usize); + } + #[doc = "Byte count"] + #[inline(always)] + pub const fn bcnt(&self) -> u16 { + let val = (self.0 >> 4usize) & 0x07ff; + val as u16 + } + #[doc = "Byte count"] + #[inline(always)] + pub fn set_bcnt(&mut self, val: u16) { + self.0 = (self.0 & !(0x07ff << 4usize)) | (((val as u32) & 0x07ff) << 4usize); + } + #[doc = "Data PID"] + #[inline(always)] + pub const fn dpid(&self) -> super::vals::Dpid { + let val = (self.0 >> 15usize) & 0x03; + super::vals::Dpid::from_bits(val as u8) + } + #[doc = "Data PID"] + #[inline(always)] + pub fn set_dpid(&mut self, val: super::vals::Dpid) { + self.0 = (self.0 & !(0x03 << 15usize)) | (((val.to_bits() as u32) & 0x03) << 15usize); + } + #[doc = "Packet status (device mode)"] + #[inline(always)] + pub const fn pktstsd(&self) -> super::vals::Pktstsd { + let val = (self.0 >> 17usize) & 0x0f; + super::vals::Pktstsd::from_bits(val as u8) + } + #[doc = "Packet status (device mode)"] + #[inline(always)] + pub fn set_pktstsd(&mut self, val: super::vals::Pktstsd) { + self.0 = (self.0 & !(0x0f << 17usize)) | (((val.to_bits() as u32) & 0x0f) << 17usize); + } + #[doc = "Packet status (host mode)"] + #[inline(always)] + pub const fn pktstsh(&self) -> super::vals::Pktstsh { + let val = (self.0 >> 17usize) & 0x0f; + super::vals::Pktstsh::from_bits(val as u8) + } + #[doc = "Packet status (host mode)"] + #[inline(always)] + pub fn set_pktstsh(&mut self, val: super::vals::Pktstsh) { + self.0 = (self.0 & !(0x0f << 17usize)) | (((val.to_bits() as u32) & 0x0f) << 17usize); + } + #[doc = "Frame number (device mode)"] + #[inline(always)] + pub const fn frmnum(&self) -> u8 { + let val = (self.0 >> 21usize) & 0x0f; + val as u8 + } + #[doc = "Frame number (device mode)"] + #[inline(always)] + pub fn set_frmnum(&mut self, val: u8) { + self.0 = (self.0 & !(0x0f << 21usize)) | (((val as u32) & 0x0f) << 21usize); + } + } + impl Default for Grxsts { + #[inline(always)] + fn default() -> Grxsts { + Grxsts(0) + } + } + #[doc = "USB configuration register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Gusbcfg(pub u32); + impl Gusbcfg { + #[doc = "FS timeout calibration"] + #[inline(always)] + pub const fn tocal(&self) -> u8 { + let val = (self.0 >> 0usize) & 0x07; + val as u8 + } + #[doc = "FS timeout calibration"] + #[inline(always)] + pub fn set_tocal(&mut self, val: u8) { + self.0 = (self.0 & !(0x07 << 0usize)) | (((val as u32) & 0x07) << 0usize); + } + #[doc = "Full-speed internal serial transceiver enable"] + #[inline(always)] + pub const fn physel(&self) -> bool { + let val = (self.0 >> 6usize) & 0x01; + val != 0 + } + #[doc = "Full-speed internal serial transceiver enable"] + #[inline(always)] + pub fn set_physel(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 6usize)) | (((val as u32) & 0x01) << 6usize); + } + #[doc = "SRP-capable"] + #[inline(always)] + pub const fn srpcap(&self) -> bool { + let val = (self.0 >> 8usize) & 0x01; + val != 0 + } + #[doc = "SRP-capable"] + #[inline(always)] + pub fn set_srpcap(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 8usize)) | (((val as u32) & 0x01) << 8usize); + } + #[doc = "HNP-capable"] + #[inline(always)] + pub const fn hnpcap(&self) -> bool { + let val = (self.0 >> 9usize) & 0x01; + val != 0 + } + #[doc = "HNP-capable"] + #[inline(always)] + pub fn set_hnpcap(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 9usize)) | (((val as u32) & 0x01) << 9usize); + } + #[doc = "USB turnaround time"] + #[inline(always)] + pub const fn trdt(&self) -> u8 { + let val = (self.0 >> 10usize) & 0x0f; + val as u8 + } + #[doc = "USB turnaround time"] + #[inline(always)] + pub fn set_trdt(&mut self, val: u8) { + self.0 = (self.0 & !(0x0f << 10usize)) | (((val as u32) & 0x0f) << 10usize); + } + #[doc = "PHY Low-power clock select"] + #[inline(always)] + pub const fn phylpcs(&self) -> bool { + let val = (self.0 >> 15usize) & 0x01; + val != 0 + } + #[doc = "PHY Low-power clock select"] + #[inline(always)] + pub fn set_phylpcs(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 15usize)) | (((val as u32) & 0x01) << 15usize); + } + #[doc = "ULPI FS/LS select"] + #[inline(always)] + pub const fn ulpifsls(&self) -> bool { + let val = (self.0 >> 17usize) & 0x01; + val != 0 + } + #[doc = "ULPI FS/LS select"] + #[inline(always)] + pub fn set_ulpifsls(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 17usize)) | (((val as u32) & 0x01) << 17usize); + } + #[doc = "ULPI Auto-resume"] + #[inline(always)] + pub const fn ulpiar(&self) -> bool { + let val = (self.0 >> 18usize) & 0x01; + val != 0 + } + #[doc = "ULPI Auto-resume"] + #[inline(always)] + pub fn set_ulpiar(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 18usize)) | (((val as u32) & 0x01) << 18usize); + } + #[doc = "ULPI Clock SuspendM"] + #[inline(always)] + pub const fn ulpicsm(&self) -> bool { + let val = (self.0 >> 19usize) & 0x01; + val != 0 + } + #[doc = "ULPI Clock SuspendM"] + #[inline(always)] + pub fn set_ulpicsm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 19usize)) | (((val as u32) & 0x01) << 19usize); + } + #[doc = "ULPI External VBUS Drive"] + #[inline(always)] + pub const fn ulpievbusd(&self) -> bool { + let val = (self.0 >> 20usize) & 0x01; + val != 0 + } + #[doc = "ULPI External VBUS Drive"] + #[inline(always)] + pub fn set_ulpievbusd(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 20usize)) | (((val as u32) & 0x01) << 20usize); + } + #[doc = "ULPI external VBUS indicator"] + #[inline(always)] + pub const fn ulpievbusi(&self) -> bool { + let val = (self.0 >> 21usize) & 0x01; + val != 0 + } + #[doc = "ULPI external VBUS indicator"] + #[inline(always)] + pub fn set_ulpievbusi(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 21usize)) | (((val as u32) & 0x01) << 21usize); + } + #[doc = "TermSel DLine pulsing selection"] + #[inline(always)] + pub const fn tsdps(&self) -> bool { + let val = (self.0 >> 22usize) & 0x01; + val != 0 + } + #[doc = "TermSel DLine pulsing selection"] + #[inline(always)] + pub fn set_tsdps(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 22usize)) | (((val as u32) & 0x01) << 22usize); + } + #[doc = "Indicator complement"] + #[inline(always)] + pub const fn pcci(&self) -> bool { + let val = (self.0 >> 23usize) & 0x01; + val != 0 + } + #[doc = "Indicator complement"] + #[inline(always)] + pub fn set_pcci(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 23usize)) | (((val as u32) & 0x01) << 23usize); + } + #[doc = "Indicator pass through"] + #[inline(always)] + pub const fn ptci(&self) -> bool { + let val = (self.0 >> 24usize) & 0x01; + val != 0 + } + #[doc = "Indicator pass through"] + #[inline(always)] + pub fn set_ptci(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 24usize)) | (((val as u32) & 0x01) << 24usize); + } + #[doc = "ULPI interface protect disable"] + #[inline(always)] + pub const fn ulpiipd(&self) -> bool { + let val = (self.0 >> 25usize) & 0x01; + val != 0 + } + #[doc = "ULPI interface protect disable"] + #[inline(always)] + pub fn set_ulpiipd(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 25usize)) | (((val as u32) & 0x01) << 25usize); + } + #[doc = "Force host mode"] + #[inline(always)] + pub const fn fhmod(&self) -> bool { + let val = (self.0 >> 29usize) & 0x01; + val != 0 + } + #[doc = "Force host mode"] + #[inline(always)] + pub fn set_fhmod(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 29usize)) | (((val as u32) & 0x01) << 29usize); + } + #[doc = "Force device mode"] + #[inline(always)] + pub const fn fdmod(&self) -> bool { + let val = (self.0 >> 30usize) & 0x01; + val != 0 + } + #[doc = "Force device mode"] + #[inline(always)] + pub fn set_fdmod(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 30usize)) | (((val as u32) & 0x01) << 30usize); + } + #[doc = "Corrupt Tx packet"] + #[inline(always)] + pub const fn ctxpkt(&self) -> bool { + let val = (self.0 >> 31usize) & 0x01; + val != 0 + } + #[doc = "Corrupt Tx packet"] + #[inline(always)] + pub fn set_ctxpkt(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 31usize)) | (((val as u32) & 0x01) << 31usize); + } + } + impl Default for Gusbcfg { + #[inline(always)] + fn default() -> Gusbcfg { + Gusbcfg(0) + } + } + #[doc = "Host all channels interrupt register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Haint(pub u32); + impl Haint { + #[doc = "Channel interrupts"] + #[inline(always)] + pub const fn haint(&self) -> u16 { + let val = (self.0 >> 0usize) & 0xffff; + val as u16 + } + #[doc = "Channel interrupts"] + #[inline(always)] + pub fn set_haint(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 0usize)) | (((val as u32) & 0xffff) << 0usize); + } + } + impl Default for Haint { + #[inline(always)] + fn default() -> Haint { + Haint(0) + } + } + #[doc = "Host all channels interrupt mask register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Haintmsk(pub u32); + impl Haintmsk { + #[doc = "Channel interrupt mask"] + #[inline(always)] + pub const fn haintm(&self) -> u16 { + let val = (self.0 >> 0usize) & 0xffff; + val as u16 + } + #[doc = "Channel interrupt mask"] + #[inline(always)] + pub fn set_haintm(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 0usize)) | (((val as u32) & 0xffff) << 0usize); + } + } + impl Default for Haintmsk { + #[inline(always)] + fn default() -> Haintmsk { + Haintmsk(0) + } + } + #[doc = "Host channel characteristics register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Hcchar(pub u32); + impl Hcchar { + #[doc = "Maximum packet size"] + #[inline(always)] + pub const fn mpsiz(&self) -> u16 { + let val = (self.0 >> 0usize) & 0x07ff; + val as u16 + } + #[doc = "Maximum packet size"] + #[inline(always)] + pub fn set_mpsiz(&mut self, val: u16) { + self.0 = (self.0 & !(0x07ff << 0usize)) | (((val as u32) & 0x07ff) << 0usize); + } + #[doc = "Endpoint number"] + #[inline(always)] + pub const fn epnum(&self) -> u8 { + let val = (self.0 >> 11usize) & 0x0f; + val as u8 + } + #[doc = "Endpoint number"] + #[inline(always)] + pub fn set_epnum(&mut self, val: u8) { + self.0 = (self.0 & !(0x0f << 11usize)) | (((val as u32) & 0x0f) << 11usize); + } + #[doc = "Endpoint direction"] + #[inline(always)] + pub const fn epdir(&self) -> bool { + let val = (self.0 >> 15usize) & 0x01; + val != 0 + } + #[doc = "Endpoint direction"] + #[inline(always)] + pub fn set_epdir(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 15usize)) | (((val as u32) & 0x01) << 15usize); + } + #[doc = "Low-speed device"] + #[inline(always)] + pub const fn lsdev(&self) -> bool { + let val = (self.0 >> 17usize) & 0x01; + val != 0 + } + #[doc = "Low-speed device"] + #[inline(always)] + pub fn set_lsdev(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 17usize)) | (((val as u32) & 0x01) << 17usize); + } + #[doc = "Endpoint type"] + #[inline(always)] + pub const fn eptyp(&self) -> super::vals::Eptyp { + let val = (self.0 >> 18usize) & 0x03; + super::vals::Eptyp::from_bits(val as u8) + } + #[doc = "Endpoint type"] + #[inline(always)] + pub fn set_eptyp(&mut self, val: super::vals::Eptyp) { + self.0 = (self.0 & !(0x03 << 18usize)) | (((val.to_bits() as u32) & 0x03) << 18usize); + } + #[doc = "Multicount"] + #[inline(always)] + pub const fn mcnt(&self) -> u8 { + let val = (self.0 >> 20usize) & 0x03; + val as u8 + } + #[doc = "Multicount"] + #[inline(always)] + pub fn set_mcnt(&mut self, val: u8) { + self.0 = (self.0 & !(0x03 << 20usize)) | (((val as u32) & 0x03) << 20usize); + } + #[doc = "Device address"] + #[inline(always)] + pub const fn dad(&self) -> u8 { + let val = (self.0 >> 22usize) & 0x7f; + val as u8 + } + #[doc = "Device address"] + #[inline(always)] + pub fn set_dad(&mut self, val: u8) { + self.0 = (self.0 & !(0x7f << 22usize)) | (((val as u32) & 0x7f) << 22usize); + } + #[doc = "Odd frame"] + #[inline(always)] + pub const fn oddfrm(&self) -> bool { + let val = (self.0 >> 29usize) & 0x01; + val != 0 + } + #[doc = "Odd frame"] + #[inline(always)] + pub fn set_oddfrm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 29usize)) | (((val as u32) & 0x01) << 29usize); + } + #[doc = "Channel disable"] + #[inline(always)] + pub const fn chdis(&self) -> bool { + let val = (self.0 >> 30usize) & 0x01; + val != 0 + } + #[doc = "Channel disable"] + #[inline(always)] + pub fn set_chdis(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 30usize)) | (((val as u32) & 0x01) << 30usize); + } + #[doc = "Channel enable"] + #[inline(always)] + pub const fn chena(&self) -> bool { + let val = (self.0 >> 31usize) & 0x01; + val != 0 + } + #[doc = "Channel enable"] + #[inline(always)] + pub fn set_chena(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 31usize)) | (((val as u32) & 0x01) << 31usize); + } + } + impl Default for Hcchar { + #[inline(always)] + fn default() -> Hcchar { + Hcchar(0) + } + } + #[doc = "Host configuration register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Hcfg(pub u32); + impl Hcfg { + #[doc = "FS/LS PHY clock select"] + #[inline(always)] + pub const fn fslspcs(&self) -> u8 { + let val = (self.0 >> 0usize) & 0x03; + val as u8 + } + #[doc = "FS/LS PHY clock select"] + #[inline(always)] + pub fn set_fslspcs(&mut self, val: u8) { + self.0 = (self.0 & !(0x03 << 0usize)) | (((val as u32) & 0x03) << 0usize); + } + #[doc = "FS- and LS-only support"] + #[inline(always)] + pub const fn fslss(&self) -> bool { + let val = (self.0 >> 2usize) & 0x01; + val != 0 + } + #[doc = "FS- and LS-only support"] + #[inline(always)] + pub fn set_fslss(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 2usize)) | (((val as u32) & 0x01) << 2usize); + } + } + impl Default for Hcfg { + #[inline(always)] + fn default() -> Hcfg { + Hcfg(0) + } + } + #[doc = "Host channel interrupt register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Hcint(pub u32); + impl Hcint { + #[doc = "Transfer completed"] + #[inline(always)] + pub const fn xfrc(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "Transfer completed"] + #[inline(always)] + pub fn set_xfrc(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "Channel halted"] + #[inline(always)] + pub const fn chh(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "Channel halted"] + #[inline(always)] + pub fn set_chh(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "STALL response received interrupt"] + #[inline(always)] + pub const fn stall(&self) -> bool { + let val = (self.0 >> 3usize) & 0x01; + val != 0 + } + #[doc = "STALL response received interrupt"] + #[inline(always)] + pub fn set_stall(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 3usize)) | (((val as u32) & 0x01) << 3usize); + } + #[doc = "NAK response received interrupt"] + #[inline(always)] + pub const fn nak(&self) -> bool { + let val = (self.0 >> 4usize) & 0x01; + val != 0 + } + #[doc = "NAK response received interrupt"] + #[inline(always)] + pub fn set_nak(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 4usize)) | (((val as u32) & 0x01) << 4usize); + } + #[doc = "ACK response received/transmitted interrupt"] + #[inline(always)] + pub const fn ack(&self) -> bool { + let val = (self.0 >> 5usize) & 0x01; + val != 0 + } + #[doc = "ACK response received/transmitted interrupt"] + #[inline(always)] + pub fn set_ack(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 5usize)) | (((val as u32) & 0x01) << 5usize); + } + #[doc = "Transaction error"] + #[inline(always)] + pub const fn txerr(&self) -> bool { + let val = (self.0 >> 7usize) & 0x01; + val != 0 + } + #[doc = "Transaction error"] + #[inline(always)] + pub fn set_txerr(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 7usize)) | (((val as u32) & 0x01) << 7usize); + } + #[doc = "Babble error"] + #[inline(always)] + pub const fn bberr(&self) -> bool { + let val = (self.0 >> 8usize) & 0x01; + val != 0 + } + #[doc = "Babble error"] + #[inline(always)] + pub fn set_bberr(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 8usize)) | (((val as u32) & 0x01) << 8usize); + } + #[doc = "Frame overrun"] + #[inline(always)] + pub const fn frmor(&self) -> bool { + let val = (self.0 >> 9usize) & 0x01; + val != 0 + } + #[doc = "Frame overrun"] + #[inline(always)] + pub fn set_frmor(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 9usize)) | (((val as u32) & 0x01) << 9usize); + } + #[doc = "Data toggle error"] + #[inline(always)] + pub const fn dterr(&self) -> bool { + let val = (self.0 >> 10usize) & 0x01; + val != 0 + } + #[doc = "Data toggle error"] + #[inline(always)] + pub fn set_dterr(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 10usize)) | (((val as u32) & 0x01) << 10usize); + } + } + impl Default for Hcint { + #[inline(always)] + fn default() -> Hcint { + Hcint(0) + } + } + #[doc = "Host channel mask register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Hcintmsk(pub u32); + impl Hcintmsk { + #[doc = "Transfer completed mask"] + #[inline(always)] + pub const fn xfrcm(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "Transfer completed mask"] + #[inline(always)] + pub fn set_xfrcm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "Channel halted mask"] + #[inline(always)] + pub const fn chhm(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "Channel halted mask"] + #[inline(always)] + pub fn set_chhm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "STALL response received interrupt mask"] + #[inline(always)] + pub const fn stallm(&self) -> bool { + let val = (self.0 >> 3usize) & 0x01; + val != 0 + } + #[doc = "STALL response received interrupt mask"] + #[inline(always)] + pub fn set_stallm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 3usize)) | (((val as u32) & 0x01) << 3usize); + } + #[doc = "NAK response received interrupt mask"] + #[inline(always)] + pub const fn nakm(&self) -> bool { + let val = (self.0 >> 4usize) & 0x01; + val != 0 + } + #[doc = "NAK response received interrupt mask"] + #[inline(always)] + pub fn set_nakm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 4usize)) | (((val as u32) & 0x01) << 4usize); + } + #[doc = "ACK response received/transmitted interrupt mask"] + #[inline(always)] + pub const fn ackm(&self) -> bool { + let val = (self.0 >> 5usize) & 0x01; + val != 0 + } + #[doc = "ACK response received/transmitted interrupt mask"] + #[inline(always)] + pub fn set_ackm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 5usize)) | (((val as u32) & 0x01) << 5usize); + } + #[doc = "Response received interrupt mask"] + #[inline(always)] + pub const fn nyet(&self) -> bool { + let val = (self.0 >> 6usize) & 0x01; + val != 0 + } + #[doc = "Response received interrupt mask"] + #[inline(always)] + pub fn set_nyet(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 6usize)) | (((val as u32) & 0x01) << 6usize); + } + #[doc = "Transaction error mask"] + #[inline(always)] + pub const fn txerrm(&self) -> bool { + let val = (self.0 >> 7usize) & 0x01; + val != 0 + } + #[doc = "Transaction error mask"] + #[inline(always)] + pub fn set_txerrm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 7usize)) | (((val as u32) & 0x01) << 7usize); + } + #[doc = "Babble error mask"] + #[inline(always)] + pub const fn bberrm(&self) -> bool { + let val = (self.0 >> 8usize) & 0x01; + val != 0 + } + #[doc = "Babble error mask"] + #[inline(always)] + pub fn set_bberrm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 8usize)) | (((val as u32) & 0x01) << 8usize); + } + #[doc = "Frame overrun mask"] + #[inline(always)] + pub const fn frmorm(&self) -> bool { + let val = (self.0 >> 9usize) & 0x01; + val != 0 + } + #[doc = "Frame overrun mask"] + #[inline(always)] + pub fn set_frmorm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 9usize)) | (((val as u32) & 0x01) << 9usize); + } + #[doc = "Data toggle error mask"] + #[inline(always)] + pub const fn dterrm(&self) -> bool { + let val = (self.0 >> 10usize) & 0x01; + val != 0 + } + #[doc = "Data toggle error mask"] + #[inline(always)] + pub fn set_dterrm(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 10usize)) | (((val as u32) & 0x01) << 10usize); + } + } + impl Default for Hcintmsk { + #[inline(always)] + fn default() -> Hcintmsk { + Hcintmsk(0) + } + } + #[doc = "Host channel transfer size register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Hctsiz(pub u32); + impl Hctsiz { + #[doc = "Transfer size"] + #[inline(always)] + pub const fn xfrsiz(&self) -> u32 { + let val = (self.0 >> 0usize) & 0x0007_ffff; + val as u32 + } + #[doc = "Transfer size"] + #[inline(always)] + pub fn set_xfrsiz(&mut self, val: u32) { + self.0 = (self.0 & !(0x0007_ffff << 0usize)) | (((val as u32) & 0x0007_ffff) << 0usize); + } + #[doc = "Packet count"] + #[inline(always)] + pub const fn pktcnt(&self) -> u16 { + let val = (self.0 >> 19usize) & 0x03ff; + val as u16 + } + #[doc = "Packet count"] + #[inline(always)] + pub fn set_pktcnt(&mut self, val: u16) { + self.0 = (self.0 & !(0x03ff << 19usize)) | (((val as u32) & 0x03ff) << 19usize); + } + #[doc = "Data PID"] + #[inline(always)] + pub const fn dpid(&self) -> u8 { + let val = (self.0 >> 29usize) & 0x03; + val as u8 + } + #[doc = "Data PID"] + #[inline(always)] + pub fn set_dpid(&mut self, val: u8) { + self.0 = (self.0 & !(0x03 << 29usize)) | (((val as u32) & 0x03) << 29usize); + } + } + impl Default for Hctsiz { + #[inline(always)] + fn default() -> Hctsiz { + Hctsiz(0) + } + } + #[doc = "Host frame interval register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Hfir(pub u32); + impl Hfir { + #[doc = "Frame interval"] + #[inline(always)] + pub const fn frivl(&self) -> u16 { + let val = (self.0 >> 0usize) & 0xffff; + val as u16 + } + #[doc = "Frame interval"] + #[inline(always)] + pub fn set_frivl(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 0usize)) | (((val as u32) & 0xffff) << 0usize); + } + } + impl Default for Hfir { + #[inline(always)] + fn default() -> Hfir { + Hfir(0) + } + } + #[doc = "Host frame number/frame time remaining register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Hfnum(pub u32); + impl Hfnum { + #[doc = "Frame number"] + #[inline(always)] + pub const fn frnum(&self) -> u16 { + let val = (self.0 >> 0usize) & 0xffff; + val as u16 + } + #[doc = "Frame number"] + #[inline(always)] + pub fn set_frnum(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 0usize)) | (((val as u32) & 0xffff) << 0usize); + } + #[doc = "Frame time remaining"] + #[inline(always)] + pub const fn ftrem(&self) -> u16 { + let val = (self.0 >> 16usize) & 0xffff; + val as u16 + } + #[doc = "Frame time remaining"] + #[inline(always)] + pub fn set_ftrem(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 16usize)) | (((val as u32) & 0xffff) << 16usize); + } + } + impl Default for Hfnum { + #[inline(always)] + fn default() -> Hfnum { + Hfnum(0) + } + } + #[doc = "Non-periodic transmit FIFO/queue status register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Hnptxsts(pub u32); + impl Hnptxsts { + #[doc = "Non-periodic TxFIFO space available"] + #[inline(always)] + pub const fn nptxfsav(&self) -> u16 { + let val = (self.0 >> 0usize) & 0xffff; + val as u16 + } + #[doc = "Non-periodic TxFIFO space available"] + #[inline(always)] + pub fn set_nptxfsav(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 0usize)) | (((val as u32) & 0xffff) << 0usize); + } + #[doc = "Non-periodic transmit request queue space available"] + #[inline(always)] + pub const fn nptqxsav(&self) -> u8 { + let val = (self.0 >> 16usize) & 0xff; + val as u8 + } + #[doc = "Non-periodic transmit request queue space available"] + #[inline(always)] + pub fn set_nptqxsav(&mut self, val: u8) { + self.0 = (self.0 & !(0xff << 16usize)) | (((val as u32) & 0xff) << 16usize); + } + #[doc = "Top of the non-periodic transmit request queue"] + #[inline(always)] + pub const fn nptxqtop(&self) -> u8 { + let val = (self.0 >> 24usize) & 0x7f; + val as u8 + } + #[doc = "Top of the non-periodic transmit request queue"] + #[inline(always)] + pub fn set_nptxqtop(&mut self, val: u8) { + self.0 = (self.0 & !(0x7f << 24usize)) | (((val as u32) & 0x7f) << 24usize); + } + } + impl Default for Hnptxsts { + #[inline(always)] + fn default() -> Hnptxsts { + Hnptxsts(0) + } + } + #[doc = "Host port control and status register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Hprt(pub u32); + impl Hprt { + #[doc = "Port connect status"] + #[inline(always)] + pub const fn pcsts(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "Port connect status"] + #[inline(always)] + pub fn set_pcsts(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "Port connect detected"] + #[inline(always)] + pub const fn pcdet(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "Port connect detected"] + #[inline(always)] + pub fn set_pcdet(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "Port enable"] + #[inline(always)] + pub const fn pena(&self) -> bool { + let val = (self.0 >> 2usize) & 0x01; + val != 0 + } + #[doc = "Port enable"] + #[inline(always)] + pub fn set_pena(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 2usize)) | (((val as u32) & 0x01) << 2usize); + } + #[doc = "Port enable/disable change"] + #[inline(always)] + pub const fn penchng(&self) -> bool { + let val = (self.0 >> 3usize) & 0x01; + val != 0 + } + #[doc = "Port enable/disable change"] + #[inline(always)] + pub fn set_penchng(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 3usize)) | (((val as u32) & 0x01) << 3usize); + } + #[doc = "Port overcurrent active"] + #[inline(always)] + pub const fn poca(&self) -> bool { + let val = (self.0 >> 4usize) & 0x01; + val != 0 + } + #[doc = "Port overcurrent active"] + #[inline(always)] + pub fn set_poca(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 4usize)) | (((val as u32) & 0x01) << 4usize); + } + #[doc = "Port overcurrent change"] + #[inline(always)] + pub const fn pocchng(&self) -> bool { + let val = (self.0 >> 5usize) & 0x01; + val != 0 + } + #[doc = "Port overcurrent change"] + #[inline(always)] + pub fn set_pocchng(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 5usize)) | (((val as u32) & 0x01) << 5usize); + } + #[doc = "Port resume"] + #[inline(always)] + pub const fn pres(&self) -> bool { + let val = (self.0 >> 6usize) & 0x01; + val != 0 + } + #[doc = "Port resume"] + #[inline(always)] + pub fn set_pres(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 6usize)) | (((val as u32) & 0x01) << 6usize); + } + #[doc = "Port suspend"] + #[inline(always)] + pub const fn psusp(&self) -> bool { + let val = (self.0 >> 7usize) & 0x01; + val != 0 + } + #[doc = "Port suspend"] + #[inline(always)] + pub fn set_psusp(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 7usize)) | (((val as u32) & 0x01) << 7usize); + } + #[doc = "Port reset"] + #[inline(always)] + pub const fn prst(&self) -> bool { + let val = (self.0 >> 8usize) & 0x01; + val != 0 + } + #[doc = "Port reset"] + #[inline(always)] + pub fn set_prst(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 8usize)) | (((val as u32) & 0x01) << 8usize); + } + #[doc = "Port line status"] + #[inline(always)] + pub const fn plsts(&self) -> u8 { + let val = (self.0 >> 10usize) & 0x03; + val as u8 + } + #[doc = "Port line status"] + #[inline(always)] + pub fn set_plsts(&mut self, val: u8) { + self.0 = (self.0 & !(0x03 << 10usize)) | (((val as u32) & 0x03) << 10usize); + } + #[doc = "Port power"] + #[inline(always)] + pub const fn ppwr(&self) -> bool { + let val = (self.0 >> 12usize) & 0x01; + val != 0 + } + #[doc = "Port power"] + #[inline(always)] + pub fn set_ppwr(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 12usize)) | (((val as u32) & 0x01) << 12usize); + } + #[doc = "Port test control"] + #[inline(always)] + pub const fn ptctl(&self) -> u8 { + let val = (self.0 >> 13usize) & 0x0f; + val as u8 + } + #[doc = "Port test control"] + #[inline(always)] + pub fn set_ptctl(&mut self, val: u8) { + self.0 = (self.0 & !(0x0f << 13usize)) | (((val as u32) & 0x0f) << 13usize); + } + #[doc = "Port speed"] + #[inline(always)] + pub const fn pspd(&self) -> u8 { + let val = (self.0 >> 17usize) & 0x03; + val as u8 + } + #[doc = "Port speed"] + #[inline(always)] + pub fn set_pspd(&mut self, val: u8) { + self.0 = (self.0 & !(0x03 << 17usize)) | (((val as u32) & 0x03) << 17usize); + } + } + impl Default for Hprt { + #[inline(always)] + fn default() -> Hprt { + Hprt(0) + } + } + #[doc = "Periodic transmit FIFO/queue status register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Hptxsts(pub u32); + impl Hptxsts { + #[doc = "Periodic transmit data FIFO space available"] + #[inline(always)] + pub const fn ptxfsavl(&self) -> u16 { + let val = (self.0 >> 0usize) & 0xffff; + val as u16 + } + #[doc = "Periodic transmit data FIFO space available"] + #[inline(always)] + pub fn set_ptxfsavl(&mut self, val: u16) { + self.0 = (self.0 & !(0xffff << 0usize)) | (((val as u32) & 0xffff) << 0usize); + } + #[doc = "Periodic transmit request queue space available"] + #[inline(always)] + pub const fn ptxqsav(&self) -> u8 { + let val = (self.0 >> 16usize) & 0xff; + val as u8 + } + #[doc = "Periodic transmit request queue space available"] + #[inline(always)] + pub fn set_ptxqsav(&mut self, val: u8) { + self.0 = (self.0 & !(0xff << 16usize)) | (((val as u32) & 0xff) << 16usize); + } + #[doc = "Top of the periodic transmit request queue"] + #[inline(always)] + pub const fn ptxqtop(&self) -> u8 { + let val = (self.0 >> 24usize) & 0xff; + val as u8 + } + #[doc = "Top of the periodic transmit request queue"] + #[inline(always)] + pub fn set_ptxqtop(&mut self, val: u8) { + self.0 = (self.0 & !(0xff << 24usize)) | (((val as u32) & 0xff) << 24usize); + } + } + impl Default for Hptxsts { + #[inline(always)] + fn default() -> Hptxsts { + Hptxsts(0) + } + } + #[doc = "Power and clock gating control register"] + #[repr(transparent)] + #[derive(Copy, Clone, Eq, PartialEq)] + pub struct Pcgcctl(pub u32); + impl Pcgcctl { + #[doc = "Stop PHY clock"] + #[inline(always)] + pub const fn stppclk(&self) -> bool { + let val = (self.0 >> 0usize) & 0x01; + val != 0 + } + #[doc = "Stop PHY clock"] + #[inline(always)] + pub fn set_stppclk(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 0usize)) | (((val as u32) & 0x01) << 0usize); + } + #[doc = "Gate HCLK"] + #[inline(always)] + pub const fn gatehclk(&self) -> bool { + let val = (self.0 >> 1usize) & 0x01; + val != 0 + } + #[doc = "Gate HCLK"] + #[inline(always)] + pub fn set_gatehclk(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 1usize)) | (((val as u32) & 0x01) << 1usize); + } + #[doc = "PHY Suspended"] + #[inline(always)] + pub const fn physusp(&self) -> bool { + let val = (self.0 >> 4usize) & 0x01; + val != 0 + } + #[doc = "PHY Suspended"] + #[inline(always)] + pub fn set_physusp(&mut self, val: bool) { + self.0 = (self.0 & !(0x01 << 4usize)) | (((val as u32) & 0x01) << 4usize); + } + } + impl Default for Pcgcctl { + #[inline(always)] + fn default() -> Pcgcctl { + Pcgcctl(0) + } + } +} +pub mod vals { + #[repr(u8)] + #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] + #[allow(non_camel_case_types)] + pub enum Dpid { + DATA0 = 0x0, + DATA2 = 0x01, + DATA1 = 0x02, + MDATA = 0x03, + } + impl Dpid { + #[inline(always)] + pub const fn from_bits(val: u8) -> Dpid { + unsafe { core::mem::transmute(val & 0x03) } + } + #[inline(always)] + pub const fn to_bits(self) -> u8 { + unsafe { core::mem::transmute(self) } + } + } + impl From for Dpid { + #[inline(always)] + fn from(val: u8) -> Dpid { + Dpid::from_bits(val) + } + } + impl From for u8 { + #[inline(always)] + fn from(val: Dpid) -> u8 { + Dpid::to_bits(val) + } + } + #[repr(u8)] + #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] + #[allow(non_camel_case_types)] + pub enum Dspd { + #[doc = "High speed"] + HIGH_SPEED = 0x0, + #[doc = "Full speed using external ULPI PHY"] + FULL_SPEED_EXTERNAL = 0x01, + _RESERVED_2 = 0x02, + #[doc = "Full speed using internal embedded PHY"] + FULL_SPEED_INTERNAL = 0x03, + } + impl Dspd { + #[inline(always)] + pub const fn from_bits(val: u8) -> Dspd { + unsafe { core::mem::transmute(val & 0x03) } + } + #[inline(always)] + pub const fn to_bits(self) -> u8 { + unsafe { core::mem::transmute(self) } + } + } + impl From for Dspd { + #[inline(always)] + fn from(val: u8) -> Dspd { + Dspd::from_bits(val) + } + } + impl From for u8 { + #[inline(always)] + fn from(val: Dspd) -> u8 { + Dspd::to_bits(val) + } + } + #[repr(u8)] + #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] + #[allow(non_camel_case_types)] + pub enum Eptyp { + CONTROL = 0x0, + ISOCHRONOUS = 0x01, + BULK = 0x02, + INTERRUPT = 0x03, + } + impl Eptyp { + #[inline(always)] + pub const fn from_bits(val: u8) -> Eptyp { + unsafe { core::mem::transmute(val & 0x03) } + } + #[inline(always)] + pub const fn to_bits(self) -> u8 { + unsafe { core::mem::transmute(self) } + } + } + impl From for Eptyp { + #[inline(always)] + fn from(val: u8) -> Eptyp { + Eptyp::from_bits(val) + } + } + impl From for u8 { + #[inline(always)] + fn from(val: Eptyp) -> u8 { + Eptyp::to_bits(val) + } + } + #[repr(u8)] + #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] + #[allow(non_camel_case_types)] + pub enum Pfivl { + #[doc = "80% of the frame interval"] + FRAME_INTERVAL_80 = 0x0, + #[doc = "85% of the frame interval"] + FRAME_INTERVAL_85 = 0x01, + #[doc = "90% of the frame interval"] + FRAME_INTERVAL_90 = 0x02, + #[doc = "95% of the frame interval"] + FRAME_INTERVAL_95 = 0x03, + } + impl Pfivl { + #[inline(always)] + pub const fn from_bits(val: u8) -> Pfivl { + unsafe { core::mem::transmute(val & 0x03) } + } + #[inline(always)] + pub const fn to_bits(self) -> u8 { + unsafe { core::mem::transmute(self) } + } + } + impl From for Pfivl { + #[inline(always)] + fn from(val: u8) -> Pfivl { + Pfivl::from_bits(val) + } + } + impl From for u8 { + #[inline(always)] + fn from(val: Pfivl) -> u8 { + Pfivl::to_bits(val) + } + } + #[repr(u8)] + #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] + #[allow(non_camel_case_types)] + pub enum Pktstsd { + _RESERVED_0 = 0x0, + #[doc = "Global OUT NAK (triggers an interrupt)"] + OUT_NAK = 0x01, + #[doc = "OUT data packet received"] + OUT_DATA_RX = 0x02, + #[doc = "OUT transfer completed (triggers an interrupt)"] + OUT_DATA_DONE = 0x03, + #[doc = "SETUP transaction completed (triggers an interrupt)"] + SETUP_DATA_DONE = 0x04, + _RESERVED_5 = 0x05, + #[doc = "SETUP data packet received"] + SETUP_DATA_RX = 0x06, + _RESERVED_7 = 0x07, + _RESERVED_8 = 0x08, + _RESERVED_9 = 0x09, + _RESERVED_a = 0x0a, + _RESERVED_b = 0x0b, + _RESERVED_c = 0x0c, + _RESERVED_d = 0x0d, + _RESERVED_e = 0x0e, + _RESERVED_f = 0x0f, + } + impl Pktstsd { + #[inline(always)] + pub const fn from_bits(val: u8) -> Pktstsd { + unsafe { core::mem::transmute(val & 0x0f) } + } + #[inline(always)] + pub const fn to_bits(self) -> u8 { + unsafe { core::mem::transmute(self) } + } + } + impl From for Pktstsd { + #[inline(always)] + fn from(val: u8) -> Pktstsd { + Pktstsd::from_bits(val) + } + } + impl From for u8 { + #[inline(always)] + fn from(val: Pktstsd) -> u8 { + Pktstsd::to_bits(val) + } + } + #[repr(u8)] + #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] + #[allow(non_camel_case_types)] + pub enum Pktstsh { + _RESERVED_0 = 0x0, + _RESERVED_1 = 0x01, + #[doc = "IN data packet received"] + IN_DATA_RX = 0x02, + #[doc = "IN transfer completed (triggers an interrupt)"] + IN_DATA_DONE = 0x03, + _RESERVED_4 = 0x04, + #[doc = "Data toggle error (triggers an interrupt)"] + DATA_TOGGLE_ERR = 0x05, + _RESERVED_6 = 0x06, + #[doc = "Channel halted (triggers an interrupt)"] + CHANNEL_HALTED = 0x07, + _RESERVED_8 = 0x08, + _RESERVED_9 = 0x09, + _RESERVED_a = 0x0a, + _RESERVED_b = 0x0b, + _RESERVED_c = 0x0c, + _RESERVED_d = 0x0d, + _RESERVED_e = 0x0e, + _RESERVED_f = 0x0f, + } + impl Pktstsh { + #[inline(always)] + pub const fn from_bits(val: u8) -> Pktstsh { + unsafe { core::mem::transmute(val & 0x0f) } + } + #[inline(always)] + pub const fn to_bits(self) -> u8 { + unsafe { core::mem::transmute(self) } + } + } + impl From for Pktstsh { + #[inline(always)] + fn from(val: u8) -> Pktstsh { + Pktstsh::from_bits(val) + } + } + impl From for u8 { + #[inline(always)] + fn from(val: Pktstsh) -> u8 { + Pktstsh::to_bits(val) + } + } +} diff --git a/embassy-usb/CHANGELOG.md b/embassy-usb/CHANGELOG.md new file mode 100644 index 000000000..efdda96fb --- /dev/null +++ b/embassy-usb/CHANGELOG.md @@ -0,0 +1,23 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## Unreleased + +## 0.3.0 - 2024-08-05 + +- bump usbd-hid from 0.7.0 to 0.8.1 +- Add collapse_debuginfo to fmt.rs macros. +- update embassy-sync dependency + +## 0.2.0 - 2024-05-20 + +- [#2862](https://github.com/embassy-rs/embassy/pull/2862) WebUSB implementation by @chmanie +- Removed dynamically sized `device_descriptor` fields + +## 0.1.0 - 2024-01-11 + +- Initial Release diff --git a/embassy-usb/Cargo.toml b/embassy-usb/Cargo.toml index 1b31b6145..e310d8bae 100644 --- a/embassy-usb/Cargo.toml +++ b/embassy-usb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "embassy-usb" -version = "0.1.0" +version = "0.3.0" edition = "2021" license = "MIT OR Apache-2.0" description = "Async USB device stack for embedded devices in Rust." @@ -48,13 +48,13 @@ max-handler-count-8 = [] [dependencies] embassy-futures = { version = "0.1.0", path = "../embassy-futures" } embassy-usb-driver = { version = "0.1.0", path = "../embassy-usb-driver" } -embassy-sync = { version = "0.5.0", path = "../embassy-sync" } -embassy-net-driver-channel = { version = "0.2.0", path = "../embassy-net-driver-channel" } +embassy-sync = { version = "0.6.0", path = "../embassy-sync" } +embassy-net-driver-channel = { version = "0.3.0", path = "../embassy-net-driver-channel" } defmt = { version = "0.3", optional = true } log = { version = "0.4.14", optional = true } heapless = "0.8" # for HID -usbd-hid = { version = "0.6.0", optional = true } +usbd-hid = { version = "0.8.1", optional = true } ssmarshal = { version = "1.0", default-features = false, optional = true } diff --git a/embassy-usb/README.md b/embassy-usb/README.md index d2adae4f5..400fc6695 100644 --- a/embassy-usb/README.md +++ b/embassy-usb/README.md @@ -34,8 +34,8 @@ They can be set in two ways: - Via Cargo features: enable a feature like `-`. `name` must be in lowercase and use dashes instead of underscores. For example. `max-interface-count-3`. Only a selection of values is available, check `Cargo.toml` for the list. -- Via environment variables at build time: set the variable named `EMBASSY_USB_`. For example -`EMBASSY_USB_MAX_INTERFACE_COUNT=3 cargo build`. You can also set them in the `[env]` section of `.cargo/config.toml`. +- Via environment variables at build time: set the variable named `EMBASSY_USB_`. For example +`EMBASSY_USB_MAX_INTERFACE_COUNT=3 cargo build`. You can also set them in the `[env]` section of `.cargo/config.toml`. Any value can be set, unlike with Cargo features. Environment variables take precedence over Cargo features. If two Cargo features are enabled for the same setting diff --git a/embassy-usb/src/builder.rs b/embassy-usb/src/builder.rs index c4705d041..e1bf8041f 100644 --- a/embassy-usb/src/builder.rs +++ b/embassy-usb/src/builder.rs @@ -1,8 +1,8 @@ use heapless::Vec; use crate::config::MAX_HANDLER_COUNT; -use crate::descriptor::{BosWriter, DescriptorWriter}; -use crate::driver::{Driver, Endpoint, EndpointType}; +use crate::descriptor::{BosWriter, DescriptorWriter, SynchronizationType, UsageType}; +use crate::driver::{Driver, Endpoint, EndpointInfo, EndpointType}; use crate::msos::{DeviceLevelDescriptor, FunctionLevelDescriptor, MsOsDescriptorWriter}; use crate::types::{InterfaceNumber, StringIndex}; use crate::{Handler, Interface, UsbDevice, MAX_INTERFACE_COUNT, STRING_INDEX_CUSTOM_START}; @@ -38,11 +38,12 @@ pub struct Config<'a> { /// Maximum packet size in bytes for the control endpoint 0. /// - /// Valid values are 8, 16, 32 and 64. There's generally no need to change this from the default - /// value of 8 bytes unless a class uses control transfers for sending large amounts of data, in - /// which case using a larger packet size may be more efficient. + /// Valid values depend on the speed at which the bus is enumerated. + /// - low speed: 8 + /// - full speed: 8, 16, 32, or 64 + /// - high speed: 64 /// - /// Default: 8 bytes + /// Default: 64 bytes pub max_packet_size_0: u8, /// Manufacturer name string descriptor. @@ -128,7 +129,6 @@ pub struct Builder<'d, D: Driver<'d>> { driver: D, next_string_index: u8, - device_descriptor: DescriptorWriter<'d>, config_descriptor: DescriptorWriter<'d>, bos_descriptor: BosWriter<'d>, @@ -144,7 +144,6 @@ impl<'d, D: Driver<'d>> Builder<'d, D> { pub fn new( driver: D, config: Config<'d>, - device_descriptor_buf: &'d mut [u8], config_descriptor_buf: &'d mut [u8], bos_descriptor_buf: &'d mut [u8], msos_descriptor_buf: &'d mut [u8], @@ -167,11 +166,9 @@ impl<'d, D: Driver<'d>> Builder<'d, D> { _ => panic!("invalid max_packet_size_0, the allowed values are 8, 16, 32 or 64"), } - let mut device_descriptor = DescriptorWriter::new(device_descriptor_buf); let mut config_descriptor = DescriptorWriter::new(config_descriptor_buf); let mut bos_descriptor = BosWriter::new(DescriptorWriter::new(bos_descriptor_buf)); - device_descriptor.device(&config); config_descriptor.configuration(&config); bos_descriptor.bos(); @@ -183,7 +180,6 @@ impl<'d, D: Driver<'d>> Builder<'d, D> { control_buf, next_string_index: STRING_INDEX_CUSTOM_START, - device_descriptor, config_descriptor, bos_descriptor, @@ -199,7 +195,6 @@ impl<'d, D: Driver<'d>> Builder<'d, D> { self.bos_descriptor.end_bos(); // Log the number of allocator bytes actually used in descriptor buffers - info!("USB: device_descriptor used: {}", self.device_descriptor.position()); info!("USB: config_descriptor used: {}", self.config_descriptor.position()); info!("USB: bos_descriptor used: {}", self.bos_descriptor.writer.position()); info!("USB: msos_descriptor used: {}", msos_descriptor.len()); @@ -209,7 +204,6 @@ impl<'d, D: Driver<'d>> Builder<'d, D> { self.driver, self.config, self.handlers, - self.device_descriptor.into_buf(), self.config_descriptor.into_buf(), self.bos_descriptor.writer.into_buf(), msos_descriptor, @@ -420,29 +414,88 @@ impl<'a, 'd, D: Driver<'d>> InterfaceAltBuilder<'a, 'd, D> { /// Descriptors are written in the order builder functions are called. Note that some /// classes care about the order. pub fn descriptor(&mut self, descriptor_type: u8, descriptor: &[u8]) { - self.builder.config_descriptor.write(descriptor_type, descriptor); + self.builder.config_descriptor.write(descriptor_type, descriptor, &[]); } - fn endpoint_in(&mut self, ep_type: EndpointType, max_packet_size: u16, interval_ms: u8) -> D::EndpointIn { + /// Add a custom Binary Object Store (BOS) descriptor to this alternate setting. + pub fn bos_capability(&mut self, capability_type: u8, capability: &[u8]) { + self.builder.bos_descriptor.capability(capability_type, capability); + } + + /// Write a custom endpoint descriptor for a certain endpoint. + /// + /// This can be necessary, if the endpoint descriptors can only be written + /// after the endpoint was created. As an example, an endpoint descriptor + /// may contain the address of an endpoint that was allocated earlier. + pub fn endpoint_descriptor( + &mut self, + endpoint: &EndpointInfo, + synchronization_type: SynchronizationType, + usage_type: UsageType, + extra_fields: &[u8], + ) { + self.builder + .config_descriptor + .endpoint(endpoint, synchronization_type, usage_type, extra_fields); + } + + /// Allocate an IN endpoint, without writing its descriptor. + /// + /// Used for granular control over the order of endpoint and descriptor creation. + pub fn alloc_endpoint_in(&mut self, ep_type: EndpointType, max_packet_size: u16, interval_ms: u8) -> D::EndpointIn { let ep = self .builder .driver .alloc_endpoint_in(ep_type, max_packet_size, interval_ms) .expect("alloc_endpoint_in failed"); - self.builder.config_descriptor.endpoint(ep.info()); + ep + } + + fn endpoint_in( + &mut self, + ep_type: EndpointType, + max_packet_size: u16, + interval_ms: u8, + synchronization_type: SynchronizationType, + usage_type: UsageType, + extra_fields: &[u8], + ) -> D::EndpointIn { + let ep = self.alloc_endpoint_in(ep_type, max_packet_size, interval_ms); + self.endpoint_descriptor(ep.info(), synchronization_type, usage_type, extra_fields); ep } - fn endpoint_out(&mut self, ep_type: EndpointType, max_packet_size: u16, interval_ms: u8) -> D::EndpointOut { + /// Allocate an OUT endpoint, without writing its descriptor. + /// + /// Use for granular control over the order of endpoint and descriptor creation. + pub fn alloc_endpoint_out( + &mut self, + ep_type: EndpointType, + max_packet_size: u16, + interval_ms: u8, + ) -> D::EndpointOut { let ep = self .builder .driver .alloc_endpoint_out(ep_type, max_packet_size, interval_ms) .expect("alloc_endpoint_out failed"); - self.builder.config_descriptor.endpoint(ep.info()); + ep + } + + fn endpoint_out( + &mut self, + ep_type: EndpointType, + max_packet_size: u16, + interval_ms: u8, + synchronization_type: SynchronizationType, + usage_type: UsageType, + extra_fields: &[u8], + ) -> D::EndpointOut { + let ep = self.alloc_endpoint_out(ep_type, max_packet_size, interval_ms); + self.endpoint_descriptor(ep.info(), synchronization_type, usage_type, extra_fields); ep } @@ -452,7 +505,14 @@ impl<'a, 'd, D: Driver<'d>> InterfaceAltBuilder<'a, 'd, D> { /// Descriptors are written in the order builder functions are called. Note that some /// classes care about the order. pub fn endpoint_bulk_in(&mut self, max_packet_size: u16) -> D::EndpointIn { - self.endpoint_in(EndpointType::Bulk, max_packet_size, 0) + self.endpoint_in( + EndpointType::Bulk, + max_packet_size, + 0, + SynchronizationType::NoSynchronization, + UsageType::DataEndpoint, + &[], + ) } /// Allocate a BULK OUT endpoint and write its descriptor. @@ -460,7 +520,14 @@ impl<'a, 'd, D: Driver<'d>> InterfaceAltBuilder<'a, 'd, D> { /// Descriptors are written in the order builder functions are called. Note that some /// classes care about the order. pub fn endpoint_bulk_out(&mut self, max_packet_size: u16) -> D::EndpointOut { - self.endpoint_out(EndpointType::Bulk, max_packet_size, 0) + self.endpoint_out( + EndpointType::Bulk, + max_packet_size, + 0, + SynchronizationType::NoSynchronization, + UsageType::DataEndpoint, + &[], + ) } /// Allocate a INTERRUPT IN endpoint and write its descriptor. @@ -468,24 +535,66 @@ impl<'a, 'd, D: Driver<'d>> InterfaceAltBuilder<'a, 'd, D> { /// Descriptors are written in the order builder functions are called. Note that some /// classes care about the order. pub fn endpoint_interrupt_in(&mut self, max_packet_size: u16, interval_ms: u8) -> D::EndpointIn { - self.endpoint_in(EndpointType::Interrupt, max_packet_size, interval_ms) + self.endpoint_in( + EndpointType::Interrupt, + max_packet_size, + interval_ms, + SynchronizationType::NoSynchronization, + UsageType::DataEndpoint, + &[], + ) } /// Allocate a INTERRUPT OUT endpoint and write its descriptor. pub fn endpoint_interrupt_out(&mut self, max_packet_size: u16, interval_ms: u8) -> D::EndpointOut { - self.endpoint_out(EndpointType::Interrupt, max_packet_size, interval_ms) + self.endpoint_out( + EndpointType::Interrupt, + max_packet_size, + interval_ms, + SynchronizationType::NoSynchronization, + UsageType::DataEndpoint, + &[], + ) } /// Allocate a ISOCHRONOUS IN endpoint and write its descriptor. /// /// Descriptors are written in the order builder functions are called. Note that some /// classes care about the order. - pub fn endpoint_isochronous_in(&mut self, max_packet_size: u16, interval_ms: u8) -> D::EndpointIn { - self.endpoint_in(EndpointType::Isochronous, max_packet_size, interval_ms) + pub fn endpoint_isochronous_in( + &mut self, + max_packet_size: u16, + interval_ms: u8, + synchronization_type: SynchronizationType, + usage_type: UsageType, + extra_fields: &[u8], + ) -> D::EndpointIn { + self.endpoint_in( + EndpointType::Isochronous, + max_packet_size, + interval_ms, + synchronization_type, + usage_type, + extra_fields, + ) } /// Allocate a ISOCHRONOUS OUT endpoint and write its descriptor. - pub fn endpoint_isochronous_out(&mut self, max_packet_size: u16, interval_ms: u8) -> D::EndpointOut { - self.endpoint_out(EndpointType::Isochronous, max_packet_size, interval_ms) + pub fn endpoint_isochronous_out( + &mut self, + max_packet_size: u16, + interval_ms: u8, + synchronization_type: SynchronizationType, + usage_type: UsageType, + extra_fields: &[u8], + ) -> D::EndpointOut { + self.endpoint_out( + EndpointType::Isochronous, + max_packet_size, + interval_ms, + synchronization_type, + usage_type, + extra_fields, + ) } } diff --git a/embassy-usb/src/class/hid.rs b/embassy-usb/src/class/hid.rs index 0000b5b2b..6d9e0aced 100644 --- a/embassy-usb/src/class/hid.rs +++ b/embassy-usb/src/class/hid.rs @@ -37,7 +37,7 @@ pub struct Config<'d> { pub report_descriptor: &'d [u8], /// Handler for control requests. - pub request_handler: Option<&'d dyn RequestHandler>, + pub request_handler: Option<&'d mut dyn RequestHandler>, /// Configures how frequently the host should poll for reading/writing HID reports. /// @@ -299,7 +299,7 @@ impl<'d, D: Driver<'d>, const N: usize> HidReader<'d, D, N> { /// /// If `use_report_ids` is true, the first byte of the report will be used as /// the `ReportId` value. Otherwise the `ReportId` value will be 0. - pub async fn run(mut self, use_report_ids: bool, handler: &T) -> ! { + pub async fn run(mut self, use_report_ids: bool, handler: &mut T) -> ! { let offset = self.offset.load(Ordering::Acquire); assert!(offset == 0); let mut buf = [0; N]; @@ -378,13 +378,13 @@ pub trait RequestHandler { /// Reads the value of report `id` into `buf` returning the size. /// /// Returns `None` if `id` is invalid or no data is available. - fn get_report(&self, id: ReportId, buf: &mut [u8]) -> Option { + fn get_report(&mut self, id: ReportId, buf: &mut [u8]) -> Option { let _ = (id, buf); None } /// Sets the value of report `id` to `data`. - fn set_report(&self, id: ReportId, data: &[u8]) -> OutResponse { + fn set_report(&mut self, id: ReportId, data: &[u8]) -> OutResponse { let _ = (id, data); OutResponse::Rejected } @@ -394,7 +394,7 @@ pub trait RequestHandler { /// If `id` is `None`, get the idle rate for all reports. Returning `None` /// will reject the control request. Any duration at or above 1.024 seconds /// or below 4ms will be returned as an indefinite idle rate. - fn get_idle_ms(&self, id: Option) -> Option { + fn get_idle_ms(&mut self, id: Option) -> Option { let _ = id; None } @@ -403,7 +403,7 @@ pub trait RequestHandler { /// /// If `id` is `None`, set the idle rate of all input reports to `dur`. If /// an indefinite duration is requested, `dur` will be set to `u32::MAX`. - fn set_idle_ms(&self, id: Option, duration_ms: u32) { + fn set_idle_ms(&mut self, id: Option, duration_ms: u32) { let _ = (id, duration_ms); } } @@ -411,7 +411,7 @@ pub trait RequestHandler { struct Control<'d> { if_num: InterfaceNumber, report_descriptor: &'d [u8], - request_handler: Option<&'d dyn RequestHandler>, + request_handler: Option<&'d mut dyn RequestHandler>, out_report_offset: &'d AtomicUsize, hid_descriptor: [u8; 9], } @@ -420,7 +420,7 @@ impl<'d> Control<'d> { fn new( if_num: InterfaceNumber, report_descriptor: &'d [u8], - request_handler: Option<&'d dyn RequestHandler>, + request_handler: Option<&'d mut dyn RequestHandler>, out_report_offset: &'d AtomicUsize, ) -> Self { Control { @@ -468,7 +468,7 @@ impl<'d> Handler for Control<'d> { trace!("HID control_out {:?} {=[u8]:x}", req, data); match req.request { HID_REQ_SET_IDLE => { - if let Some(handler) = self.request_handler { + if let Some(handler) = self.request_handler.as_mut() { let id = req.value as u8; let id = (id != 0).then_some(ReportId::In(id)); let dur = u32::from(req.value >> 8); @@ -477,7 +477,7 @@ impl<'d> Handler for Control<'d> { } Some(OutResponse::Accepted) } - HID_REQ_SET_REPORT => match (ReportId::try_from(req.value), self.request_handler) { + HID_REQ_SET_REPORT => match (ReportId::try_from(req.value), self.request_handler.as_mut()) { (Ok(id), Some(handler)) => Some(handler.set_report(id, data)), _ => Some(OutResponse::Rejected), }, @@ -513,7 +513,7 @@ impl<'d> Handler for Control<'d> { match req.request { HID_REQ_GET_REPORT => { let size = match ReportId::try_from(req.value) { - Ok(id) => self.request_handler.and_then(|x| x.get_report(id, buf)), + Ok(id) => self.request_handler.as_mut().and_then(|x| x.get_report(id, buf)), Err(_) => None, }; @@ -524,7 +524,7 @@ impl<'d> Handler for Control<'d> { } } HID_REQ_GET_IDLE => { - if let Some(handler) = self.request_handler { + if let Some(handler) = self.request_handler.as_mut() { let id = req.value as u8; let id = (id != 0).then_some(ReportId::In(id)); if let Some(dur) = handler.get_idle_ms(id) { diff --git a/embassy-usb/src/class/mod.rs b/embassy-usb/src/class/mod.rs index 452eedf17..b883ed4e5 100644 --- a/embassy-usb/src/class/mod.rs +++ b/embassy-usb/src/class/mod.rs @@ -3,3 +3,4 @@ pub mod cdc_acm; pub mod cdc_ncm; pub mod hid; pub mod midi; +pub mod web_usb; diff --git a/embassy-usb/src/class/web_usb.rs b/embassy-usb/src/class/web_usb.rs new file mode 100644 index 000000000..10ebf318d --- /dev/null +++ b/embassy-usb/src/class/web_usb.rs @@ -0,0 +1,186 @@ +//! WebUSB API capability implementation. +//! +//! See https://wicg.github.io/webusb + +use core::mem::MaybeUninit; + +use crate::control::{InResponse, Recipient, Request, RequestType}; +use crate::descriptor::capability_type; +use crate::driver::Driver; +use crate::{Builder, Handler}; + +const USB_CLASS_VENDOR: u8 = 0xff; +const USB_SUBCLASS_NONE: u8 = 0x00; +const USB_PROTOCOL_NONE: u8 = 0x00; + +const WEB_USB_REQUEST_GET_URL: u16 = 0x02; +const WEB_USB_DESCRIPTOR_TYPE_URL: u8 = 0x03; + +/// URL descriptor for WebUSB landing page. +/// +/// An ecoded URL descriptor to point to a website that is suggested to the user when the device is connected. +pub struct Url<'d>(&'d str, u8); + +impl<'d> Url<'d> { + /// Create a new WebUSB URL descriptor. + pub fn new(url: &'d str) -> Self { + let (prefix, stripped_url) = if let Some(stripped) = url.strip_prefix("https://") { + (1, stripped) + } else if let Some(stripped) = url.strip_prefix("http://") { + (0, stripped) + } else { + (255, url) + }; + assert!( + stripped_url.len() <= 252, + "URL too long. ({} bytes). Maximum length is 252 bytes.", + stripped_url.len() + ); + Self(stripped_url, prefix) + } + + fn as_bytes(&self) -> &[u8] { + self.0.as_bytes() + } + + fn scheme(&self) -> u8 { + self.1 + } +} + +/// Configuration for WebUSB. +pub struct Config<'d> { + /// Maximum packet size in bytes for the data endpoints. + /// + /// Valid values depend on the speed at which the bus is enumerated. + /// - low speed: 8 + /// - full speed: 8, 16, 32, or 64 + /// - high speed: 64 + pub max_packet_size: u16, + /// URL to navigate to when the device is connected. + /// + /// If defined, shows a landing page which the device manufacturer would like the user to visit in order to control their device. + pub landing_url: Option>, + /// Vendor code for the WebUSB request. + /// + /// This value defines the request id (bRequest) the device expects the host to use when issuing control transfers these requests. This can be an arbitrary u8 and is not to be confused with the USB Vendor ID. + pub vendor_code: u8, +} + +struct Control<'d> { + ep_buf: [u8; 128], + vendor_code: u8, + landing_url: Option<&'d Url<'d>>, +} + +impl<'d> Control<'d> { + fn new(config: &'d Config<'d>) -> Self { + Control { + ep_buf: [0u8; 128], + vendor_code: config.vendor_code, + landing_url: config.landing_url.as_ref(), + } + } +} + +impl<'d> Handler for Control<'d> { + fn control_in(&mut self, req: Request, _data: &mut [u8]) -> Option { + let landing_value = if self.landing_url.is_some() { 1 } else { 0 }; + if req.request_type == RequestType::Vendor + && req.recipient == Recipient::Device + && req.request == self.vendor_code + && req.value == landing_value + && req.index == WEB_USB_REQUEST_GET_URL + { + if let Some(url) = self.landing_url { + let url_bytes = url.as_bytes(); + let len = url_bytes.len(); + + self.ep_buf[0] = len as u8 + 3; + self.ep_buf[1] = WEB_USB_DESCRIPTOR_TYPE_URL; + self.ep_buf[2] = url.scheme(); + self.ep_buf[3..3 + len].copy_from_slice(url_bytes); + + return Some(InResponse::Accepted(&self.ep_buf[..3 + len])); + } + } + None + } +} + +/// Internal state for WebUSB +pub struct State<'d> { + control: MaybeUninit>, +} + +impl<'d> Default for State<'d> { + fn default() -> Self { + Self::new() + } +} + +impl<'d> State<'d> { + /// Create a new `State`. + pub const fn new() -> Self { + State { + control: MaybeUninit::uninit(), + } + } +} + +/// WebUSB capability implementation. +/// +/// WebUSB is a W3C standard that allows a web page to communicate with USB devices. +/// See See https://wicg.github.io/webusb for more information and the browser API. +/// This implementation provides one read and one write endpoint. +pub struct WebUsb<'d, D: Driver<'d>> { + _driver: core::marker::PhantomData<&'d D>, +} + +impl<'d, D: Driver<'d>> WebUsb<'d, D> { + /// Builder for the WebUSB capability implementation. + /// + /// Pass in a USB `Builder`, a `State`, which holds the the control endpoint state, and a `Config` for the WebUSB configuration. + pub fn configure(builder: &mut Builder<'d, D>, state: &'d mut State<'d>, config: &'d Config<'d>) { + let mut func = builder.function(USB_CLASS_VENDOR, USB_SUBCLASS_NONE, USB_PROTOCOL_NONE); + let mut iface = func.interface(); + let mut alt = iface.alt_setting(USB_CLASS_VENDOR, USB_SUBCLASS_NONE, USB_PROTOCOL_NONE, None); + + alt.bos_capability( + capability_type::PLATFORM, + &[ + // PlatformCapabilityUUID (3408b638-09a9-47a0-8bfd-a0768815b665) + 0x0, + 0x38, + 0xb6, + 0x08, + 0x34, + 0xa9, + 0x09, + 0xa0, + 0x47, + 0x8b, + 0xfd, + 0xa0, + 0x76, + 0x88, + 0x15, + 0xb6, + 0x65, + // bcdVersion of WebUSB (1.0) + 0x00, + 0x01, + // bVendorCode + config.vendor_code, + // iLandingPage + if config.landing_url.is_some() { 1 } else { 0 }, + ], + ); + + let control = state.control.write(Control::new(config)); + + drop(func); + + builder.handler(control); + } +} diff --git a/embassy-usb/src/descriptor.rs b/embassy-usb/src/descriptor.rs index fa83ef583..06ebe0481 100644 --- a/embassy-usb/src/descriptor.rs +++ b/embassy-usb/src/descriptor.rs @@ -1,4 +1,5 @@ //! Utilities for writing USB descriptors. +use embassy_usb_driver::EndpointType; use crate::builder::Config; use crate::driver::EndpointInfo; @@ -13,6 +14,8 @@ pub mod descriptor_type { pub const STRING: u8 = 3; pub const INTERFACE: u8 = 4; pub const ENDPOINT: u8 = 5; + pub const DEVICE_QUALIFIER: u8 = 6; + pub const OTHER_SPEED_CONFIGURATION: u8 = 7; pub const IAD: u8 = 11; pub const BOS: u8 = 15; pub const CAPABILITY: u8 = 16; @@ -36,6 +39,40 @@ pub mod capability_type { pub const PLATFORM: u8 = 5; } +/// USB endpoint synchronization type. The values of this enum can be directly +/// cast into `u8` to get the bmAttributes synchronization type bits. +/// Values other than `NoSynchronization` are only allowed on isochronous endpoints. +#[repr(u8)] +#[derive(Copy, Clone, Eq, PartialEq, Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum SynchronizationType { + /// No synchronization is used. + NoSynchronization = 0b00, + /// Unsynchronized, although sinks provide data rate feedback. + Asynchronous = 0b01, + /// Synchronized using feedback or feedforward data rate information. + Adaptive = 0b10, + /// Synchronized to the USB’s SOF. + Synchronous = 0b11, +} + +/// USB endpoint usage type. The values of this enum can be directly cast into +/// `u8` to get the bmAttributes usage type bits. +/// Values other than `DataEndpoint` are only allowed on isochronous endpoints. +#[repr(u8)] +#[derive(Copy, Clone, Eq, PartialEq, Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum UsageType { + /// Use the endpoint for regular data transfer. + DataEndpoint = 0b00, + /// Endpoint conveys explicit feedback information for one or more data endpoints. + FeedbackEndpoint = 0b01, + /// A data endpoint that also serves as an implicit feedback endpoint for one or more data endpoints. + ImplicitFeedbackDataEndpoint = 0b10, + /// Reserved usage type. + Reserved = 0b11, +} + /// A writer for USB descriptors. pub(crate) struct DescriptorWriter<'a> { pub buf: &'a mut [u8], @@ -63,47 +100,26 @@ impl<'a> DescriptorWriter<'a> { self.position } - /// Writes an arbitrary (usually class-specific) descriptor. - pub fn write(&mut self, descriptor_type: u8, descriptor: &[u8]) { - let length = descriptor.len(); + /// Writes an arbitrary (usually class-specific) descriptor with optional extra fields. + pub fn write(&mut self, descriptor_type: u8, descriptor: &[u8], extra_fields: &[u8]) { + let descriptor_length = descriptor.len(); + let extra_fields_length = extra_fields.len(); + let total_length = descriptor_length + extra_fields_length; assert!( - (self.position + 2 + length) <= self.buf.len() && (length + 2) <= 255, + (self.position + 2 + total_length) <= self.buf.len() && (total_length + 2) <= 255, "Descriptor buffer full" ); - self.buf[self.position] = (length + 2) as u8; + self.buf[self.position] = (total_length + 2) as u8; self.buf[self.position + 1] = descriptor_type; let start = self.position + 2; - self.buf[start..start + length].copy_from_slice(descriptor); + self.buf[start..start + descriptor_length].copy_from_slice(descriptor); + self.buf[start + descriptor_length..start + total_length].copy_from_slice(extra_fields); - self.position = start + length; - } - - pub(crate) fn device(&mut self, config: &Config) { - self.write( - descriptor_type::DEVICE, - &[ - 0x10, - 0x02, // bcdUSB 2.1 - config.device_class, // bDeviceClass - config.device_sub_class, // bDeviceSubClass - config.device_protocol, // bDeviceProtocol - config.max_packet_size_0, // bMaxPacketSize0 - config.vendor_id as u8, - (config.vendor_id >> 8) as u8, // idVendor - config.product_id as u8, - (config.product_id >> 8) as u8, // idProduct - config.device_release as u8, - (config.device_release >> 8) as u8, // bcdDevice - config.manufacturer.map_or(0, |_| 1), // iManufacturer - config.product.map_or(0, |_| 2), // iProduct - config.serial_number.map_or(0, |_| 3), // iSerialNumber - 1, // bNumConfigurations - ], - ); + self.position = start + total_length; } pub(crate) fn configuration(&mut self, config: &Config) { @@ -121,6 +137,7 @@ impl<'a> DescriptorWriter<'a> { | if config.supports_remote_wakeup { 0x20 } else { 0x00 }, // bmAttributes (config.max_power / 2) as u8, // bMaxPower ], + &[], ); } @@ -167,6 +184,7 @@ impl<'a> DescriptorWriter<'a> { function_protocol, 0, ], + &[], ); } @@ -217,6 +235,7 @@ impl<'a> DescriptorWriter<'a> { interface_protocol, // bInterfaceProtocol str_index, // iInterface ], + &[], ); } @@ -226,21 +245,50 @@ impl<'a> DescriptorWriter<'a> { /// /// * `endpoint` - Endpoint previously allocated with /// [`UsbDeviceBuilder`](crate::bus::UsbDeviceBuilder). - pub fn endpoint(&mut self, endpoint: &EndpointInfo) { + /// * `synchronization_type` - The synchronization type of the endpoint. + /// * `usage_type` - The usage type of the endpoint. + /// * `extra_fields` - Additional, class-specific entries at the end of the endpoint descriptor. + pub fn endpoint( + &mut self, + endpoint: &EndpointInfo, + synchronization_type: SynchronizationType, + usage_type: UsageType, + extra_fields: &[u8], + ) { match self.num_endpoints_mark { Some(mark) => self.buf[mark] += 1, None => panic!("you can only call `endpoint` after `interface/interface_alt`."), }; + let mut bm_attributes = endpoint.ep_type as u8; + + // Synchronization types other than `NoSynchronization`, + // and usage types other than `DataEndpoint` + // are only allowed for isochronous endpoints. + if endpoint.ep_type != EndpointType::Isochronous { + assert_eq!(synchronization_type, SynchronizationType::NoSynchronization); + assert_eq!(usage_type, UsageType::DataEndpoint); + } else { + if usage_type == UsageType::FeedbackEndpoint { + assert_eq!(synchronization_type, SynchronizationType::NoSynchronization) + } + + let synchronization_bm_attibutes: u8 = (synchronization_type as u8) << 2; + let usage_bm_attibutes: u8 = (usage_type as u8) << 4; + + bm_attributes |= usage_bm_attibutes | synchronization_bm_attibutes; + } + self.write( descriptor_type::ENDPOINT, &[ - endpoint.addr.into(), // bEndpointAddress - endpoint.ep_type as u8, // bmAttributes + endpoint.addr.into(), // bEndpointAddress + bm_attributes, // bmAttributes endpoint.max_packet_size as u8, (endpoint.max_packet_size >> 8) as u8, // wMaxPacketSize endpoint.interval_ms, // bInterval ], + extra_fields, ); } @@ -269,6 +317,52 @@ impl<'a> DescriptorWriter<'a> { } } +/// Create a new Device Descriptor array. +/// +/// All device descriptors are always 18 bytes, so there's no need for +/// a variable-length buffer or DescriptorWriter. +pub(crate) fn device_descriptor(config: &Config) -> [u8; 18] { + [ + 18, // bLength + 0x01, // bDescriptorType + 0x10, + 0x02, // bcdUSB 2.1 + config.device_class, // bDeviceClass + config.device_sub_class, // bDeviceSubClass + config.device_protocol, // bDeviceProtocol + config.max_packet_size_0, // bMaxPacketSize0 + config.vendor_id as u8, + (config.vendor_id >> 8) as u8, // idVendor + config.product_id as u8, + (config.product_id >> 8) as u8, // idProduct + config.device_release as u8, + (config.device_release >> 8) as u8, // bcdDevice + config.manufacturer.map_or(0, |_| 1), // iManufacturer + config.product.map_or(0, |_| 2), // iProduct + config.serial_number.map_or(0, |_| 3), // iSerialNumber + 1, // bNumConfigurations + ] +} + +/// Create a new Device Qualifier Descriptor array. +/// +/// All device qualifier descriptors are always 10 bytes, so there's no need for +/// a variable-length buffer or DescriptorWriter. +pub(crate) fn device_qualifier_descriptor(config: &Config) -> [u8; 10] { + [ + 10, // bLength + 0x06, // bDescriptorType + 0x10, + 0x02, // bcdUSB 2.1 + config.device_class, // bDeviceClass + config.device_sub_class, // bDeviceSubClass + config.device_protocol, // bDeviceProtocol + config.max_packet_size_0, // bMaxPacketSize0 + 1, // bNumConfigurations + 0, // Reserved + ] +} + /// A writer for Binary Object Store descriptor. pub struct BosWriter<'a> { pub(crate) writer: DescriptorWriter<'a>, @@ -284,6 +378,9 @@ impl<'a> BosWriter<'a> { } pub(crate) fn bos(&mut self) { + if (self.writer.buf.len() - self.writer.position) < 5 { + return; + } self.num_caps_mark = Some(self.writer.position + 4); self.writer.write( descriptor_type::BOS, @@ -291,6 +388,7 @@ impl<'a> BosWriter<'a> { 0x00, 0x00, // wTotalLength 0x00, // bNumDeviceCaps ], + &[], ); self.capability(capability_type::USB_2_0_EXTENSION, &[0; 4]); @@ -326,6 +424,9 @@ impl<'a> BosWriter<'a> { } pub(crate) fn end_bos(&mut self) { + if self.writer.position == 0 { + return; + } self.num_caps_mark = None; let position = self.writer.position as u16; self.writer.buf[2..4].copy_from_slice(&position.to_le_bytes()); diff --git a/embassy-usb/src/fmt.rs b/embassy-usb/src/fmt.rs index 78e583c1c..8ca61bc39 100644 --- a/embassy-usb/src/fmt.rs +++ b/embassy-usb/src/fmt.rs @@ -1,11 +1,12 @@ #![macro_use] -#![allow(unused_macros)] +#![allow(unused)] use core::fmt::{Debug, Display, LowerHex}; #[cfg(all(feature = "defmt", feature = "log"))] compile_error!("You may not enable both `defmt` and `log` features."); +#[collapse_debuginfo(yes)] macro_rules! assert { ($($x:tt)*) => { { @@ -17,6 +18,7 @@ macro_rules! assert { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_eq { ($($x:tt)*) => { { @@ -28,6 +30,7 @@ macro_rules! assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! assert_ne { ($($x:tt)*) => { { @@ -39,6 +42,7 @@ macro_rules! assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert { ($($x:tt)*) => { { @@ -50,6 +54,7 @@ macro_rules! debug_assert { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_eq { ($($x:tt)*) => { { @@ -61,6 +66,7 @@ macro_rules! debug_assert_eq { }; } +#[collapse_debuginfo(yes)] macro_rules! debug_assert_ne { ($($x:tt)*) => { { @@ -72,6 +78,7 @@ macro_rules! debug_assert_ne { }; } +#[collapse_debuginfo(yes)] macro_rules! todo { ($($x:tt)*) => { { @@ -83,20 +90,19 @@ macro_rules! todo { }; } -#[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unreachable { ($($x:tt)*) => { - ::core::unreachable!($($x)*) - }; -} - -#[cfg(feature = "defmt")] -macro_rules! unreachable { - ($($x:tt)*) => { - ::defmt::unreachable!($($x)*) + { + #[cfg(not(feature = "defmt"))] + ::core::unreachable!($($x)*); + #[cfg(feature = "defmt")] + ::defmt::unreachable!($($x)*); + } }; } +#[collapse_debuginfo(yes)] macro_rules! panic { ($($x:tt)*) => { { @@ -108,6 +114,7 @@ macro_rules! panic { }; } +#[collapse_debuginfo(yes)] macro_rules! trace { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -121,6 +128,7 @@ macro_rules! trace { }; } +#[collapse_debuginfo(yes)] macro_rules! debug { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -134,6 +142,7 @@ macro_rules! debug { }; } +#[collapse_debuginfo(yes)] macro_rules! info { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -147,6 +156,7 @@ macro_rules! info { }; } +#[collapse_debuginfo(yes)] macro_rules! warn { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -160,6 +170,7 @@ macro_rules! warn { }; } +#[collapse_debuginfo(yes)] macro_rules! error { ($s:literal $(, $x:expr)* $(,)?) => { { @@ -174,6 +185,7 @@ macro_rules! error { } #[cfg(feature = "defmt")] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($($x:tt)*) => { ::defmt::unwrap!($($x)*) @@ -181,6 +193,7 @@ macro_rules! unwrap { } #[cfg(not(feature = "defmt"))] +#[collapse_debuginfo(yes)] macro_rules! unwrap { ($arg:expr) => { match $crate::fmt::Try::into_result($arg) { @@ -229,7 +242,6 @@ impl Try for Result { } } -#[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); impl<'a> Debug for Bytes<'a> { diff --git a/embassy-usb/src/lib.rs b/embassy-usb/src/lib.rs index 241e33a78..a5478ca0e 100644 --- a/embassy-usb/src/lib.rs +++ b/embassy-usb/src/lib.rs @@ -168,8 +168,6 @@ struct Interface { #[derive(PartialEq, Eq, Copy, Clone, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct UsbBufferReport { - /// Number of device descriptor bytes used - pub device_descriptor_used: usize, /// Number of config descriptor bytes used pub config_descriptor_used: usize, /// Number of bos descriptor bytes used @@ -191,7 +189,8 @@ struct Inner<'d, D: Driver<'d>> { bus: D::Bus, config: Config<'d>, - device_descriptor: &'d [u8], + device_descriptor: [u8; 18], + device_qualifier_descriptor: [u8; 10], config_descriptor: &'d [u8], bos_descriptor: &'d [u8], msos_descriptor: crate::msos::MsOsDescriptorSet<'d>, @@ -217,7 +216,6 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> { driver: D, config: Config<'d>, handlers: Vec<&'d mut dyn Handler, MAX_HANDLER_COUNT>, - device_descriptor: &'d [u8], config_descriptor: &'d [u8], bos_descriptor: &'d [u8], msos_descriptor: crate::msos::MsOsDescriptorSet<'d>, @@ -227,6 +225,8 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> { // Start the USB bus. // This prevent further allocation by consuming the driver. let (bus, control) = driver.start(config.max_packet_size_0 as u16); + let device_descriptor = descriptor::device_descriptor(&config); + let device_qualifier_descriptor = descriptor::device_qualifier_descriptor(&config); Self { control_buf, @@ -235,6 +235,7 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> { bus, config, device_descriptor, + device_qualifier_descriptor, config_descriptor, bos_descriptor, msos_descriptor, @@ -256,7 +257,6 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> { /// Useful for tuning buffer sizes for actual usage pub fn buffer_usage(&self) -> UsbBufferReport { UsbBufferReport { - device_descriptor_used: self.inner.device_descriptor.len(), config_descriptor_used: self.inner.config_descriptor.len(), bos_descriptor_used: self.inner.bos_descriptor.len(), msos_descriptor_used: self.inner.msos_descriptor.len(), @@ -720,7 +720,7 @@ impl<'d, D: Driver<'d>> Inner<'d, D> { match dtype { descriptor_type::BOS => InResponse::Accepted(self.bos_descriptor), - descriptor_type::DEVICE => InResponse::Accepted(self.device_descriptor), + descriptor_type::DEVICE => InResponse::Accepted(&self.device_descriptor), descriptor_type::CONFIGURATION => InResponse::Accepted(self.config_descriptor), descriptor_type::STRING => { if index == 0 { @@ -767,6 +767,7 @@ impl<'d, D: Driver<'d>> Inner<'d, D> { } } } + descriptor_type::DEVICE_QUALIFIER => InResponse::Accepted(&self.device_qualifier_descriptor), _ => InResponse::Rejected, } } diff --git a/embassy-usb/src/msos.rs b/embassy-usb/src/msos.rs index 3858c0f51..9f4e1a57b 100644 --- a/embassy-usb/src/msos.rs +++ b/embassy-usb/src/msos.rs @@ -226,27 +226,21 @@ pub mod windows_version { pub const WIN10: u32 = 0x0A000000; } -mod sealed { - use core::mem::size_of; +/// A trait for descriptors +trait Descriptor: Sized { + const TYPE: DescriptorType; - /// A trait for descriptors - pub trait Descriptor: Sized { - const TYPE: super::DescriptorType; - - /// The size of the descriptor's header. - fn size(&self) -> usize { - size_of::() - } - - fn write_to(&self, buf: &mut [u8]); + /// The size of the descriptor's header. + fn size(&self) -> usize { + size_of::() } - pub trait DescriptorSet: Descriptor { - const LENGTH_OFFSET: usize; - } + fn write_to(&self, buf: &mut [u8]); } -use sealed::*; +trait DescriptorSet: Descriptor { + const LENGTH_OFFSET: usize; +} /// Copies the data of `t` into `buf`. /// @@ -255,7 +249,7 @@ use sealed::*; unsafe fn transmute_write_to(t: &T, buf: &mut [u8]) { let bytes = core::slice::from_raw_parts((t as *const T) as *const u8, size_of::()); assert!(buf.len() >= bytes.len(), "MS OS descriptor buffer full"); - (&mut buf[..bytes.len()]).copy_from_slice(bytes); + buf[..bytes.len()].copy_from_slice(bytes); } /// Table 9. Microsoft OS 2.0 descriptor wDescriptorType values. @@ -284,6 +278,7 @@ pub enum DescriptorType { /// Table 5. Descriptor set information structure. #[allow(non_snake_case)] +#[allow(unused)] #[repr(C, packed(1))] pub struct DescriptorSetInformation { dwWindowsVersion: u32, @@ -294,6 +289,7 @@ pub struct DescriptorSetInformation { /// Table 4. Microsoft OS 2.0 platform capability descriptor header. #[allow(non_snake_case)] +#[allow(unused)] #[repr(C, packed(1))] pub struct PlatformDescriptor { bLength: u8, @@ -412,9 +408,11 @@ impl DescriptorSet for FunctionSubsetHeader { // Feature Descriptors /// A marker trait for feature descriptors that are valid at the device level. +#[allow(private_bounds)] pub trait DeviceLevelDescriptor: Descriptor {} /// A marker trait for feature descriptors that are valid at the function level. +#[allow(private_bounds)] pub trait FunctionLevelDescriptor: Descriptor {} /// Table 13. Microsoft OS 2.0 compatible ID descriptor. @@ -444,9 +442,9 @@ impl CompatibleIdFeatureDescriptor { pub fn new(compatible_id: &str, sub_compatible_id: &str) -> Self { assert!(compatible_id.len() <= 8 && sub_compatible_id.len() <= 8); let mut cid = [0u8; 8]; - (&mut cid[..compatible_id.len()]).copy_from_slice(compatible_id.as_bytes()); + cid[..compatible_id.len()].copy_from_slice(compatible_id.as_bytes()); let mut scid = [0u8; 8]; - (&mut scid[..sub_compatible_id.len()]).copy_from_slice(sub_compatible_id.as_bytes()); + scid[..sub_compatible_id.len()].copy_from_slice(sub_compatible_id.as_bytes()); Self::new_raw(cid, scid) } diff --git a/examples/boot/application/nrf/Cargo.toml b/examples/boot/application/nrf/Cargo.toml index 86f6676cb..e2ae240ae 100644 --- a/examples/boot/application/nrf/Cargo.toml +++ b/examples/boot/application/nrf/Cargo.toml @@ -5,13 +5,13 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" } -embassy-executor = { version = "0.5.0", path = "../../../../embassy-executor", features = ["task-arena-size-16384", "arch-cortex-m", "executor-thread", "integrated-timers", "arch-cortex-m", "executor-thread"] } -embassy-time = { version = "0.3.0", path = "../../../../embassy-time", features = [] } -embassy-nrf = { version = "0.1.0", path = "../../../../embassy-nrf", features = ["time-driver-rtc1", "gpiote", ] } -embassy-boot = { version = "0.2.0", path = "../../../../embassy-boot", features = [] } -embassy-boot-nrf = { version = "0.2.0", path = "../../../../embassy-boot-nrf", features = [] } -embassy-embedded-hal = { version = "0.1.0", path = "../../../../embassy-embedded-hal" } +embassy-sync = { version = "0.6.0", path = "../../../../embassy-sync" } +embassy-executor = { version = "0.6.2", path = "../../../../embassy-executor", features = ["task-arena-size-16384", "arch-cortex-m", "executor-thread", "integrated-timers", "arch-cortex-m", "executor-thread"] } +embassy-time = { version = "0.3.2", path = "../../../../embassy-time", features = [] } +embassy-nrf = { version = "0.2.0", path = "../../../../embassy-nrf", features = ["time-driver-rtc1", "gpiote", ] } +embassy-boot = { version = "0.3.0", path = "../../../../embassy-boot", features = [] } +embassy-boot-nrf = { version = "0.3.0", path = "../../../../embassy-boot-nrf", features = [] } +embassy-embedded-hal = { version = "0.2.0", path = "../../../../embassy-embedded-hal" } defmt = { version = "0.3", optional = true } defmt-rtt = { version = "0.4", optional = true } @@ -25,3 +25,10 @@ cortex-m-rt = "0.7.0" ed25519-dalek = ["embassy-boot/ed25519-dalek"] ed25519-salty = ["embassy-boot/ed25519-salty"] skip-include = [] +defmt = [ + "dep:defmt", + "dep:defmt-rtt", + "embassy-nrf/defmt", + "embassy-boot-nrf/defmt", + "embassy-sync/defmt", +] diff --git a/examples/boot/application/nrf/build.rs b/examples/boot/application/nrf/build.rs index cd1a264c4..e1da69328 100644 --- a/examples/boot/application/nrf/build.rs +++ b/examples/boot/application/nrf/build.rs @@ -31,4 +31,7 @@ fn main() { println!("cargo:rustc-link-arg-bins=--nmagic"); println!("cargo:rustc-link-arg-bins=-Tlink.x"); + if env::var("CARGO_FEATURE_DEFMT").is_ok() { + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); + } } diff --git a/examples/boot/application/nrf/src/bin/a.rs b/examples/boot/application/nrf/src/bin/a.rs index f3abfddbc..2c1d1a7bb 100644 --- a/examples/boot/application/nrf/src/bin/a.rs +++ b/examples/boot/application/nrf/src/bin/a.rs @@ -2,6 +2,9 @@ #![no_main] #![macro_use] +#[cfg(feature = "defmt")] +use defmt_rtt as _; +use embassy_boot::State; use embassy_boot_nrf::{FirmwareUpdater, FirmwareUpdaterConfig}; use embassy_embedded_hal::adapter::BlockingAsync; use embassy_executor::Spawner; @@ -22,6 +25,7 @@ async fn main(_spawner: Spawner) { let mut button = Input::new(p.P0_11, Pull::Up); let mut led = Output::new(p.P0_13, Level::Low, OutputDrive::Standard); + let mut led_reverted = Output::new(p.P0_14, Level::High, OutputDrive::Standard); //let mut led = Output::new(p.P1_10, Level::Low, OutputDrive::Standard); //let mut button = Input::new(p.P1_02, Pull::Up); @@ -50,9 +54,16 @@ async fn main(_spawner: Spawner) { let nvmc = Nvmc::new(p.NVMC); let nvmc = Mutex::new(BlockingAsync::new(nvmc)); - let config = FirmwareUpdaterConfig::from_linkerfile(&nvmc); + let config = FirmwareUpdaterConfig::from_linkerfile(&nvmc, &nvmc); let mut magic = [0; 4]; let mut updater = FirmwareUpdater::new(config, &mut magic); + let state = updater.get_state().await.unwrap(); + if state == State::Revert { + led_reverted.set_low(); + } else { + led_reverted.set_high(); + } + loop { led.set_low(); button.wait_for_any_edge().await; diff --git a/examples/boot/application/rp/Cargo.toml b/examples/boot/application/rp/Cargo.toml index 70741a0ce..f61ac3fd9 100644 --- a/examples/boot/application/rp/Cargo.toml +++ b/examples/boot/application/rp/Cargo.toml @@ -5,12 +5,12 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" } -embassy-executor = { version = "0.5.0", path = "../../../../embassy-executor", features = ["task-arena-size-16384", "arch-cortex-m", "executor-thread", "integrated-timers", "arch-cortex-m", "executor-thread"] } -embassy-time = { version = "0.3.0", path = "../../../../embassy-time", features = [] } -embassy-rp = { version = "0.1.0", path = "../../../../embassy-rp", features = ["time-driver", ] } -embassy-boot-rp = { version = "0.2.0", path = "../../../../embassy-boot-rp", features = [] } -embassy-embedded-hal = { version = "0.1.0", path = "../../../../embassy-embedded-hal" } +embassy-sync = { version = "0.6.0", path = "../../../../embassy-sync" } +embassy-executor = { version = "0.6.2", path = "../../../../embassy-executor", features = ["task-arena-size-16384", "arch-cortex-m", "executor-thread", "integrated-timers", "arch-cortex-m", "executor-thread"] } +embassy-time = { version = "0.3.2", path = "../../../../embassy-time", features = [] } +embassy-rp = { version = "0.2.0", path = "../../../../embassy-rp", features = ["time-driver", "rp2040"] } +embassy-boot-rp = { version = "0.3.0", path = "../../../../embassy-boot-rp", features = [] } +embassy-embedded-hal = { version = "0.2.0", path = "../../../../embassy-embedded-hal" } defmt = "0.3" defmt-rtt = "0.4" diff --git a/examples/boot/application/rp/src/bin/a.rs b/examples/boot/application/rp/src/bin/a.rs index 3f0bf90e2..ede0c07da 100644 --- a/examples/boot/application/rp/src/bin/a.rs +++ b/examples/boot/application/rp/src/bin/a.rs @@ -36,7 +36,7 @@ async fn main(_s: Spawner) { let flash = Flash::<_, _, FLASH_SIZE>::new_blocking(p.FLASH); let flash = Mutex::new(RefCell::new(flash)); - let config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash); + let config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash, &flash); let mut aligned = AlignedBuffer([0; 1]); let mut updater = BlockingFirmwareUpdater::new(config, &mut aligned.0); diff --git a/examples/boot/application/stm32f3/Cargo.toml b/examples/boot/application/stm32f3/Cargo.toml index 1cb143820..dd20d2e0d 100644 --- a/examples/boot/application/stm32f3/Cargo.toml +++ b/examples/boot/application/stm32f3/Cargo.toml @@ -5,12 +5,12 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" } -embassy-executor = { version = "0.5.0", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } +embassy-sync = { version = "0.6.0", path = "../../../../embassy-sync" } +embassy-executor = { version = "0.6.2", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } embassy-stm32 = { version = "0.1.0", path = "../../../../embassy-stm32", features = ["stm32f303re", "time-driver-any", "exti"] } embassy-boot-stm32 = { version = "0.2.0", path = "../../../../embassy-boot-stm32" } -embassy-embedded-hal = { version = "0.1.0", path = "../../../../embassy-embedded-hal" } +embassy-embedded-hal = { version = "0.2.0", path = "../../../../embassy-embedded-hal" } defmt = { version = "0.3", optional = true } defmt-rtt = { version = "0.4", optional = true } @@ -23,6 +23,7 @@ cortex-m-rt = "0.7.0" [features] defmt = [ "dep:defmt", + "dep:defmt-rtt", "embassy-stm32/defmt", "embassy-boot-stm32/defmt", "embassy-sync/defmt", diff --git a/examples/boot/application/stm32f3/memory.x b/examples/boot/application/stm32f3/memory.x index f51875766..02ebe3ecf 100644 --- a/examples/boot/application/stm32f3/memory.x +++ b/examples/boot/application/stm32f3/memory.x @@ -3,8 +3,8 @@ MEMORY /* NOTE 1 K = 1 KiBi = 1024 bytes */ BOOTLOADER : ORIGIN = 0x08000000, LENGTH = 24K BOOTLOADER_STATE : ORIGIN = 0x08006000, LENGTH = 4K - FLASH : ORIGIN = 0x08008000, LENGTH = 32K - DFU : ORIGIN = 0x08010000, LENGTH = 36K + FLASH : ORIGIN = 0x08008000, LENGTH = 64K + DFU : ORIGIN = 0x08018000, LENGTH = 66K RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 32K } diff --git a/examples/boot/application/stm32f3/src/bin/a.rs b/examples/boot/application/stm32f3/src/bin/a.rs index 3f9ebe5c8..b608b2e01 100644 --- a/examples/boot/application/stm32f3/src/bin/a.rs +++ b/examples/boot/application/stm32f3/src/bin/a.rs @@ -1,7 +1,7 @@ #![no_std] #![no_main] -#[cfg(feature = "defmt-rtt")] +#[cfg(feature = "defmt")] use defmt_rtt::*; use embassy_boot_stm32::{AlignedBuffer, FirmwareUpdater, FirmwareUpdaterConfig}; use embassy_embedded_hal::adapter::BlockingAsync; @@ -28,7 +28,7 @@ async fn main(_spawner: Spawner) { let mut led = Output::new(p.PA5, Level::Low, Speed::Low); led.set_high(); - let config = FirmwareUpdaterConfig::from_linkerfile(&flash); + let config = FirmwareUpdaterConfig::from_linkerfile(&flash, &flash); let mut magic = AlignedBuffer([0; WRITE_SIZE]); let mut updater = FirmwareUpdater::new(config, &mut magic.0); button.wait_for_falling_edge().await; diff --git a/examples/boot/application/stm32f3/src/bin/b.rs b/examples/boot/application/stm32f3/src/bin/b.rs index 22ba82d5e..b1a505631 100644 --- a/examples/boot/application/stm32f3/src/bin/b.rs +++ b/examples/boot/application/stm32f3/src/bin/b.rs @@ -1,7 +1,7 @@ #![no_std] #![no_main] -#[cfg(feature = "defmt-rtt")] +#[cfg(feature = "defmt")] use defmt_rtt::*; use embassy_executor::Spawner; use embassy_stm32::gpio::{Level, Output, Speed}; diff --git a/examples/boot/application/stm32f7/Cargo.toml b/examples/boot/application/stm32f7/Cargo.toml index c4ae461a5..ce38e9ab9 100644 --- a/examples/boot/application/stm32f7/Cargo.toml +++ b/examples/boot/application/stm32f7/Cargo.toml @@ -5,12 +5,12 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" } -embassy-executor = { version = "0.5.0", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } +embassy-sync = { version = "0.6.0", path = "../../../../embassy-sync" } +embassy-executor = { version = "0.6.2", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } embassy-stm32 = { version = "0.1.0", path = "../../../../embassy-stm32", features = ["stm32f767zi", "time-driver-any", "exti"] } embassy-boot-stm32 = { version = "0.2.0", path = "../../../../embassy-boot-stm32", features = [] } -embassy-embedded-hal = { version = "0.1.0", path = "../../../../embassy-embedded-hal" } +embassy-embedded-hal = { version = "0.2.0", path = "../../../../embassy-embedded-hal" } defmt = { version = "0.3", optional = true } defmt-rtt = { version = "0.4", optional = true } @@ -24,6 +24,7 @@ cortex-m-rt = "0.7.0" [features] defmt = [ "dep:defmt", + "dep:defmt-rtt", "embassy-stm32/defmt", "embassy-boot-stm32/defmt", "embassy-sync/defmt", diff --git a/examples/boot/application/stm32f7/src/bin/a.rs b/examples/boot/application/stm32f7/src/bin/a.rs index c57c29263..172b4c235 100644 --- a/examples/boot/application/stm32f7/src/bin/a.rs +++ b/examples/boot/application/stm32f7/src/bin/a.rs @@ -3,7 +3,7 @@ use core::cell::RefCell; -#[cfg(feature = "defmt-rtt")] +#[cfg(feature = "defmt")] use defmt_rtt::*; use embassy_boot_stm32::{AlignedBuffer, BlockingFirmwareUpdater, FirmwareUpdaterConfig}; use embassy_executor::Spawner; @@ -30,7 +30,7 @@ async fn main(_spawner: Spawner) { let mut led = Output::new(p.PB7, Level::Low, Speed::Low); led.set_high(); - let config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash); + let config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash, &flash); let mut magic = AlignedBuffer([0; WRITE_SIZE]); let mut updater = BlockingFirmwareUpdater::new(config, &mut magic.0); let writer = updater.prepare_update().unwrap(); diff --git a/examples/boot/application/stm32f7/src/bin/b.rs b/examples/boot/application/stm32f7/src/bin/b.rs index 190477204..6bc9c9ab8 100644 --- a/examples/boot/application/stm32f7/src/bin/b.rs +++ b/examples/boot/application/stm32f7/src/bin/b.rs @@ -1,7 +1,7 @@ #![no_std] #![no_main] -#[cfg(feature = "defmt-rtt")] +#[cfg(feature = "defmt")] use defmt_rtt::*; use embassy_executor::Spawner; use embassy_stm32::gpio::{Level, Output, Speed}; diff --git a/examples/boot/application/stm32h7/Cargo.toml b/examples/boot/application/stm32h7/Cargo.toml index 995487cdd..841075627 100644 --- a/examples/boot/application/stm32h7/Cargo.toml +++ b/examples/boot/application/stm32h7/Cargo.toml @@ -5,12 +5,12 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" } -embassy-executor = { version = "0.5.0", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } +embassy-sync = { version = "0.6.0", path = "../../../../embassy-sync" } +embassy-executor = { version = "0.6.2", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } embassy-stm32 = { version = "0.1.0", path = "../../../../embassy-stm32", features = ["stm32h743zi", "time-driver-any", "exti"] } embassy-boot-stm32 = { version = "0.2.0", path = "../../../../embassy-boot-stm32", features = [] } -embassy-embedded-hal = { version = "0.1.0", path = "../../../../embassy-embedded-hal" } +embassy-embedded-hal = { version = "0.2.0", path = "../../../../embassy-embedded-hal" } defmt = { version = "0.3", optional = true } defmt-rtt = { version = "0.4", optional = true } @@ -24,6 +24,7 @@ cortex-m-rt = "0.7.0" [features] defmt = [ "dep:defmt", + "dep:defmt-rtt", "embassy-stm32/defmt", "embassy-boot-stm32/defmt", "embassy-sync/defmt", diff --git a/examples/boot/application/stm32h7/src/bin/a.rs b/examples/boot/application/stm32h7/src/bin/a.rs index a00d17408..c1b1a267a 100644 --- a/examples/boot/application/stm32h7/src/bin/a.rs +++ b/examples/boot/application/stm32h7/src/bin/a.rs @@ -3,7 +3,7 @@ use core::cell::RefCell; -#[cfg(feature = "defmt-rtt")] +#[cfg(feature = "defmt")] use defmt_rtt::*; use embassy_boot_stm32::{AlignedBuffer, BlockingFirmwareUpdater, FirmwareUpdaterConfig}; use embassy_executor::Spawner; @@ -30,7 +30,7 @@ async fn main(_spawner: Spawner) { let mut led = Output::new(p.PB14, Level::Low, Speed::Low); led.set_high(); - let config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash); + let config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash, &flash); let mut magic = AlignedBuffer([0; WRITE_SIZE]); let mut updater = BlockingFirmwareUpdater::new(config, &mut magic.0); let writer = updater.prepare_update().unwrap(); diff --git a/examples/boot/application/stm32h7/src/bin/b.rs b/examples/boot/application/stm32h7/src/bin/b.rs index 5f3f35207..13bdae1f1 100644 --- a/examples/boot/application/stm32h7/src/bin/b.rs +++ b/examples/boot/application/stm32h7/src/bin/b.rs @@ -1,7 +1,7 @@ #![no_std] #![no_main] -#[cfg(feature = "defmt-rtt")] +#[cfg(feature = "defmt")] use defmt_rtt::*; use embassy_executor::Spawner; use embassy_stm32::gpio::{Level, Output, Speed}; diff --git a/examples/boot/application/stm32l0/Cargo.toml b/examples/boot/application/stm32l0/Cargo.toml index b2abc005c..1a92517db 100644 --- a/examples/boot/application/stm32l0/Cargo.toml +++ b/examples/boot/application/stm32l0/Cargo.toml @@ -5,12 +5,12 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" } -embassy-executor = { version = "0.5.0", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } +embassy-sync = { version = "0.6.0", path = "../../../../embassy-sync" } +embassy-executor = { version = "0.6.2", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } embassy-stm32 = { version = "0.1.0", path = "../../../../embassy-stm32", features = ["stm32l072cz", "time-driver-any", "exti", "memory-x"] } embassy-boot-stm32 = { version = "0.2.0", path = "../../../../embassy-boot-stm32", features = [] } -embassy-embedded-hal = { version = "0.1.0", path = "../../../../embassy-embedded-hal" } +embassy-embedded-hal = { version = "0.2.0", path = "../../../../embassy-embedded-hal" } defmt = { version = "0.3", optional = true } defmt-rtt = { version = "0.4", optional = true } @@ -23,6 +23,7 @@ cortex-m-rt = "0.7.0" [features] defmt = [ "dep:defmt", + "dep:defmt-rtt", "embassy-stm32/defmt", "embassy-boot-stm32/defmt", "embassy-sync/defmt", diff --git a/examples/boot/application/stm32l0/memory.x b/examples/boot/application/stm32l0/memory.x index a99330145..8866506a8 100644 --- a/examples/boot/application/stm32l0/memory.x +++ b/examples/boot/application/stm32l0/memory.x @@ -3,8 +3,8 @@ MEMORY /* NOTE 1 K = 1 KiBi = 1024 bytes */ BOOTLOADER : ORIGIN = 0x08000000, LENGTH = 24K BOOTLOADER_STATE : ORIGIN = 0x08006000, LENGTH = 4K - FLASH : ORIGIN = 0x08008000, LENGTH = 32K - DFU : ORIGIN = 0x08010000, LENGTH = 36K + FLASH : ORIGIN = 0x08008000, LENGTH = 64K + DFU : ORIGIN = 0x08018000, LENGTH = 66K RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 16K } diff --git a/examples/boot/application/stm32l0/src/bin/a.rs b/examples/boot/application/stm32l0/src/bin/a.rs index dbec49d44..dcc10e5c6 100644 --- a/examples/boot/application/stm32l0/src/bin/a.rs +++ b/examples/boot/application/stm32l0/src/bin/a.rs @@ -1,7 +1,7 @@ #![no_std] #![no_main] -#[cfg(feature = "defmt-rtt")] +#[cfg(feature = "defmt")] use defmt_rtt::*; use embassy_boot_stm32::{AlignedBuffer, FirmwareUpdater, FirmwareUpdaterConfig}; use embassy_embedded_hal::adapter::BlockingAsync; @@ -30,7 +30,7 @@ async fn main(_spawner: Spawner) { led.set_high(); - let config = FirmwareUpdaterConfig::from_linkerfile(&flash); + let config = FirmwareUpdaterConfig::from_linkerfile(&flash, &flash); let mut magic = AlignedBuffer([0; WRITE_SIZE]); let mut updater = FirmwareUpdater::new(config, &mut magic.0); button.wait_for_falling_edge().await; diff --git a/examples/boot/application/stm32l0/src/bin/b.rs b/examples/boot/application/stm32l0/src/bin/b.rs index 6bf00f41a..a59c6f540 100644 --- a/examples/boot/application/stm32l0/src/bin/b.rs +++ b/examples/boot/application/stm32l0/src/bin/b.rs @@ -1,7 +1,7 @@ #![no_std] #![no_main] -#[cfg(feature = "defmt-rtt")] +#[cfg(feature = "defmt")] use defmt_rtt::*; use embassy_executor::Spawner; use embassy_stm32::gpio::{Level, Output, Speed}; diff --git a/examples/boot/application/stm32l1/Cargo.toml b/examples/boot/application/stm32l1/Cargo.toml index 7203e6350..57eeb07a1 100644 --- a/examples/boot/application/stm32l1/Cargo.toml +++ b/examples/boot/application/stm32l1/Cargo.toml @@ -5,12 +5,12 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" } -embassy-executor = { version = "0.5.0", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } +embassy-sync = { version = "0.6.0", path = "../../../../embassy-sync" } +embassy-executor = { version = "0.6.2", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } embassy-stm32 = { version = "0.1.0", path = "../../../../embassy-stm32", features = ["stm32l151cb-a", "time-driver-any", "exti"] } embassy-boot-stm32 = { version = "0.2.0", path = "../../../../embassy-boot-stm32", features = [] } -embassy-embedded-hal = { version = "0.1.0", path = "../../../../embassy-embedded-hal" } +embassy-embedded-hal = { version = "0.2.0", path = "../../../../embassy-embedded-hal" } defmt = { version = "0.3", optional = true } defmt-rtt = { version = "0.4", optional = true } @@ -23,6 +23,7 @@ cortex-m-rt = "0.7.0" [features] defmt = [ "dep:defmt", + "dep:defmt-rtt", "embassy-stm32/defmt", "embassy-boot-stm32/defmt", "embassy-sync/defmt", diff --git a/examples/boot/application/stm32l1/memory.x b/examples/boot/application/stm32l1/memory.x index a99330145..caa525278 100644 --- a/examples/boot/application/stm32l1/memory.x +++ b/examples/boot/application/stm32l1/memory.x @@ -3,8 +3,8 @@ MEMORY /* NOTE 1 K = 1 KiBi = 1024 bytes */ BOOTLOADER : ORIGIN = 0x08000000, LENGTH = 24K BOOTLOADER_STATE : ORIGIN = 0x08006000, LENGTH = 4K - FLASH : ORIGIN = 0x08008000, LENGTH = 32K - DFU : ORIGIN = 0x08010000, LENGTH = 36K + FLASH : ORIGIN = 0x08008000, LENGTH = 46K + DFU : ORIGIN = 0x08013800, LENGTH = 54K RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 16K } diff --git a/examples/boot/application/stm32l1/src/bin/a.rs b/examples/boot/application/stm32l1/src/bin/a.rs index dbec49d44..dcc10e5c6 100644 --- a/examples/boot/application/stm32l1/src/bin/a.rs +++ b/examples/boot/application/stm32l1/src/bin/a.rs @@ -1,7 +1,7 @@ #![no_std] #![no_main] -#[cfg(feature = "defmt-rtt")] +#[cfg(feature = "defmt")] use defmt_rtt::*; use embassy_boot_stm32::{AlignedBuffer, FirmwareUpdater, FirmwareUpdaterConfig}; use embassy_embedded_hal::adapter::BlockingAsync; @@ -30,7 +30,7 @@ async fn main(_spawner: Spawner) { led.set_high(); - let config = FirmwareUpdaterConfig::from_linkerfile(&flash); + let config = FirmwareUpdaterConfig::from_linkerfile(&flash, &flash); let mut magic = AlignedBuffer([0; WRITE_SIZE]); let mut updater = FirmwareUpdater::new(config, &mut magic.0); button.wait_for_falling_edge().await; diff --git a/examples/boot/application/stm32l1/src/bin/b.rs b/examples/boot/application/stm32l1/src/bin/b.rs index 6bf00f41a..a59c6f540 100644 --- a/examples/boot/application/stm32l1/src/bin/b.rs +++ b/examples/boot/application/stm32l1/src/bin/b.rs @@ -1,7 +1,7 @@ #![no_std] #![no_main] -#[cfg(feature = "defmt-rtt")] +#[cfg(feature = "defmt")] use defmt_rtt::*; use embassy_executor::Spawner; use embassy_stm32::gpio::{Level, Output, Speed}; diff --git a/examples/boot/application/stm32l4/Cargo.toml b/examples/boot/application/stm32l4/Cargo.toml index ec134f394..f51ca29e1 100644 --- a/examples/boot/application/stm32l4/Cargo.toml +++ b/examples/boot/application/stm32l4/Cargo.toml @@ -5,12 +5,12 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" } -embassy-executor = { version = "0.5.0", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } +embassy-sync = { version = "0.6.0", path = "../../../../embassy-sync" } +embassy-executor = { version = "0.6.2", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } embassy-stm32 = { version = "0.1.0", path = "../../../../embassy-stm32", features = ["stm32l475vg", "time-driver-any", "exti"] } embassy-boot-stm32 = { version = "0.2.0", path = "../../../../embassy-boot-stm32", features = [] } -embassy-embedded-hal = { version = "0.1.0", path = "../../../../embassy-embedded-hal" } +embassy-embedded-hal = { version = "0.2.0", path = "../../../../embassy-embedded-hal" } defmt = { version = "0.3", optional = true } defmt-rtt = { version = "0.4", optional = true } @@ -23,6 +23,7 @@ cortex-m-rt = "0.7.0" [features] defmt = [ "dep:defmt", + "dep:defmt-rtt", "embassy-stm32/defmt", "embassy-boot-stm32/defmt", "embassy-sync/defmt", diff --git a/examples/boot/application/stm32l4/memory.x b/examples/boot/application/stm32l4/memory.x index f51875766..e1d4e7fa8 100644 --- a/examples/boot/application/stm32l4/memory.x +++ b/examples/boot/application/stm32l4/memory.x @@ -3,8 +3,8 @@ MEMORY /* NOTE 1 K = 1 KiBi = 1024 bytes */ BOOTLOADER : ORIGIN = 0x08000000, LENGTH = 24K BOOTLOADER_STATE : ORIGIN = 0x08006000, LENGTH = 4K - FLASH : ORIGIN = 0x08008000, LENGTH = 32K - DFU : ORIGIN = 0x08010000, LENGTH = 36K + FLASH : ORIGIN = 0x08008000, LENGTH = 64K + DFU : ORIGIN = 0x08018000, LENGTH = 68K RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 32K } diff --git a/examples/boot/application/stm32l4/src/bin/a.rs b/examples/boot/application/stm32l4/src/bin/a.rs index e946c3cdf..7f8015c04 100644 --- a/examples/boot/application/stm32l4/src/bin/a.rs +++ b/examples/boot/application/stm32l4/src/bin/a.rs @@ -1,7 +1,7 @@ #![no_std] #![no_main] -#[cfg(feature = "defmt-rtt")] +#[cfg(feature = "defmt")] use defmt_rtt::*; use embassy_boot_stm32::{AlignedBuffer, FirmwareUpdater, FirmwareUpdaterConfig}; use embassy_embedded_hal::adapter::BlockingAsync; @@ -28,7 +28,7 @@ async fn main(_spawner: Spawner) { let mut led = Output::new(p.PB14, Level::Low, Speed::Low); led.set_high(); - let config = FirmwareUpdaterConfig::from_linkerfile(&flash); + let config = FirmwareUpdaterConfig::from_linkerfile(&flash, &flash); let mut magic = AlignedBuffer([0; WRITE_SIZE]); let mut updater = FirmwareUpdater::new(config, &mut magic.0); button.wait_for_falling_edge().await; diff --git a/examples/boot/application/stm32l4/src/bin/b.rs b/examples/boot/application/stm32l4/src/bin/b.rs index 22ba82d5e..b1a505631 100644 --- a/examples/boot/application/stm32l4/src/bin/b.rs +++ b/examples/boot/application/stm32l4/src/bin/b.rs @@ -1,7 +1,7 @@ #![no_std] #![no_main] -#[cfg(feature = "defmt-rtt")] +#[cfg(feature = "defmt")] use defmt_rtt::*; use embassy_executor::Spawner; use embassy_stm32::gpio::{Level, Output, Speed}; diff --git a/examples/boot/application/stm32wb-dfu/Cargo.toml b/examples/boot/application/stm32wb-dfu/Cargo.toml index 0bdf94331..112de92f1 100644 --- a/examples/boot/application/stm32wb-dfu/Cargo.toml +++ b/examples/boot/application/stm32wb-dfu/Cargo.toml @@ -5,13 +5,13 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" } -embassy-executor = { version = "0.5.0", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } +embassy-sync = { version = "0.6.0", path = "../../../../embassy-sync" } +embassy-executor = { version = "0.6.2", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } embassy-stm32 = { version = "0.1.0", path = "../../../../embassy-stm32", features = ["stm32wb55rg", "time-driver-any", "exti"] } embassy-boot-stm32 = { version = "0.2.0", path = "../../../../embassy-boot-stm32", features = [] } -embassy-embedded-hal = { version = "0.1.0", path = "../../../../embassy-embedded-hal" } -embassy-usb = { version = "0.1.0", path = "../../../../embassy-usb" } +embassy-embedded-hal = { version = "0.2.0", path = "../../../../embassy-embedded-hal" } +embassy-usb = { version = "0.3.0", path = "../../../../embassy-usb" } embassy-usb-dfu = { version = "0.1.0", path = "../../../../embassy-usb-dfu", features = ["application", "cortex-m"] } defmt = { version = "0.3", optional = true } diff --git a/examples/boot/application/stm32wb-dfu/README.md b/examples/boot/application/stm32wb-dfu/README.md index c8dce0387..7f656cde6 100644 --- a/examples/boot/application/stm32wb-dfu/README.md +++ b/examples/boot/application/stm32wb-dfu/README.md @@ -1,29 +1,9 @@ # Examples using bootloader -Example for STM32WL demonstrating the bootloader. The example consists of application binaries, 'a' -which allows you to press a button to start the DFU process, and 'b' which is the updated -application. - - -## Prerequisites - -* `cargo-binutils` -* `cargo-flash` -* `embassy-boot-stm32` +Example for STM32WB demonstrating the USB DFU application. ## Usage ``` -# Flash bootloader -cargo flash --manifest-path ../../bootloader/stm32/Cargo.toml --release --features embassy-stm32/stm32wl55jc-cm4 --chip STM32WLE5JCIx -# Build 'b' -cargo build --release --bin b -# Generate binary for 'b' -cargo objcopy --release --bin b -- -O binary b.bin -``` - -# Flash `a` (which includes b.bin) - -``` -cargo flash --release --bin a --chip STM32WLE5JCIx +cargo flash --release --chip STM32WB55RGVx ``` diff --git a/examples/boot/application/stm32wb-dfu/src/main.rs b/examples/boot/application/stm32wb-dfu/src/main.rs index b2ccb9e1a..0ab99ff90 100644 --- a/examples/boot/application/stm32wb-dfu/src/main.rs +++ b/examples/boot/application/stm32wb-dfu/src/main.rs @@ -3,7 +3,7 @@ use core::cell::RefCell; -#[cfg(feature = "defmt-rtt")] +#[cfg(feature = "defmt")] use defmt_rtt::*; use embassy_boot_stm32::{AlignedBuffer, BlockingFirmwareState, FirmwareUpdaterConfig}; use embassy_executor::Spawner; @@ -30,7 +30,7 @@ async fn main(_spawner: Spawner) { let flash = Flash::new_blocking(p.FLASH); let flash = Mutex::new(RefCell::new(flash)); - let config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash); + let config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash, &flash); let mut magic = AlignedBuffer([0; WRITE_SIZE]); let mut firmware_state = BlockingFirmwareState::from_config(config, &mut magic.0); firmware_state.mark_booted().expect("Failed to mark booted"); @@ -41,7 +41,6 @@ async fn main(_spawner: Spawner) { config.product = Some("USB-DFU Runtime example"); config.serial_number = Some("1235678"); - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 64]; @@ -49,7 +48,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], diff --git a/examples/boot/application/stm32wl/Cargo.toml b/examples/boot/application/stm32wl/Cargo.toml index e38e9f3af..e2c42ce20 100644 --- a/examples/boot/application/stm32wl/Cargo.toml +++ b/examples/boot/application/stm32wl/Cargo.toml @@ -5,12 +5,12 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" } -embassy-executor = { version = "0.5.0", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } +embassy-sync = { version = "0.6.0", path = "../../../../embassy-sync" } +embassy-executor = { version = "0.6.2", path = "../../../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] } embassy-stm32 = { version = "0.1.0", path = "../../../../embassy-stm32", features = ["stm32wl55jc-cm4", "time-driver-any", "exti"] } embassy-boot-stm32 = { version = "0.2.0", path = "../../../../embassy-boot-stm32", features = [] } -embassy-embedded-hal = { version = "0.1.0", path = "../../../../embassy-embedded-hal" } +embassy-embedded-hal = { version = "0.2.0", path = "../../../../embassy-embedded-hal" } defmt = { version = "0.3", optional = true } defmt-rtt = { version = "0.4", optional = true } @@ -23,6 +23,7 @@ cortex-m-rt = "0.7.0" [features] defmt = [ "dep:defmt", + "dep:defmt-rtt", "embassy-stm32/defmt", "embassy-boot-stm32/defmt", "embassy-sync/defmt", diff --git a/examples/boot/application/stm32wl/memory.x b/examples/boot/application/stm32wl/memory.x index f51875766..20109e37e 100644 --- a/examples/boot/application/stm32wl/memory.x +++ b/examples/boot/application/stm32wl/memory.x @@ -3,9 +3,10 @@ MEMORY /* NOTE 1 K = 1 KiBi = 1024 bytes */ BOOTLOADER : ORIGIN = 0x08000000, LENGTH = 24K BOOTLOADER_STATE : ORIGIN = 0x08006000, LENGTH = 4K - FLASH : ORIGIN = 0x08008000, LENGTH = 32K - DFU : ORIGIN = 0x08010000, LENGTH = 36K - RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 32K + FLASH : ORIGIN = 0x08008000, LENGTH = 64K + DFU : ORIGIN = 0x08018000, LENGTH = 68K + SHARED_RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 128 + RAM (rwx) : ORIGIN = 0x20000080, LENGTH = 32K - 128 } __bootloader_state_start = ORIGIN(BOOTLOADER_STATE) - ORIGIN(BOOTLOADER); @@ -13,3 +14,11 @@ __bootloader_state_end = ORIGIN(BOOTLOADER_STATE) + LENGTH(BOOTLOADER_STATE) - O __bootloader_dfu_start = ORIGIN(DFU) - ORIGIN(BOOTLOADER); __bootloader_dfu_end = ORIGIN(DFU) + LENGTH(DFU) - ORIGIN(BOOTLOADER); + +SECTIONS +{ + .shared_data : + { + *(.shared_data) + } > SHARED_RAM +} diff --git a/examples/boot/application/stm32wl/src/bin/a.rs b/examples/boot/application/stm32wl/src/bin/a.rs index b582d8b25..127de0237 100644 --- a/examples/boot/application/stm32wl/src/bin/a.rs +++ b/examples/boot/application/stm32wl/src/bin/a.rs @@ -1,7 +1,9 @@ #![no_std] #![no_main] -#[cfg(feature = "defmt-rtt")] +use core::mem::MaybeUninit; + +#[cfg(feature = "defmt")] use defmt_rtt::*; use embassy_boot_stm32::{AlignedBuffer, FirmwareUpdater, FirmwareUpdaterConfig}; use embassy_embedded_hal::adapter::BlockingAsync; @@ -9,6 +11,7 @@ use embassy_executor::Spawner; use embassy_stm32::exti::ExtiInput; use embassy_stm32::flash::{Flash, WRITE_SIZE}; use embassy_stm32::gpio::{Level, Output, Pull, Speed}; +use embassy_stm32::SharedData; use embassy_sync::mutex::Mutex; use panic_reset as _; @@ -17,9 +20,12 @@ static APP_B: &[u8] = &[0, 1, 2, 3]; #[cfg(not(feature = "skip-include"))] static APP_B: &[u8] = include_bytes!("../../b.bin"); +#[link_section = ".shared_data"] +static SHARED_DATA: MaybeUninit = MaybeUninit::uninit(); + #[embassy_executor::main] async fn main(_spawner: Spawner) { - let p = embassy_stm32::init(Default::default()); + let p = embassy_stm32::init_primary(Default::default(), &SHARED_DATA); let flash = Flash::new_blocking(p.FLASH); let flash = Mutex::new(BlockingAsync::new(flash)); @@ -28,7 +34,7 @@ async fn main(_spawner: Spawner) { let mut led = Output::new(p.PB9, Level::Low, Speed::Low); led.set_high(); - let config = FirmwareUpdaterConfig::from_linkerfile(&flash); + let config = FirmwareUpdaterConfig::from_linkerfile(&flash, &flash); let mut magic = AlignedBuffer([0; WRITE_SIZE]); let mut updater = FirmwareUpdater::new(config, &mut magic.0); button.wait_for_falling_edge().await; diff --git a/examples/boot/application/stm32wl/src/bin/b.rs b/examples/boot/application/stm32wl/src/bin/b.rs index 8dd15d8cd..768dadf8b 100644 --- a/examples/boot/application/stm32wl/src/bin/b.rs +++ b/examples/boot/application/stm32wl/src/bin/b.rs @@ -1,16 +1,22 @@ #![no_std] #![no_main] -#[cfg(feature = "defmt-rtt")] +use core::mem::MaybeUninit; + +#[cfg(feature = "defmt")] use defmt_rtt::*; use embassy_executor::Spawner; use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::SharedData; use embassy_time::Timer; use panic_reset as _; +#[link_section = ".shared_data"] +static SHARED_DATA: MaybeUninit = MaybeUninit::uninit(); + #[embassy_executor::main] async fn main(_spawner: Spawner) { - let p = embassy_stm32::init(Default::default()); + let p = embassy_stm32::init_primary(Default::default(), &SHARED_DATA); let mut led = Output::new(p.PB15, Level::High, Speed::Low); loop { diff --git a/examples/boot/bootloader/nrf/Cargo.toml b/examples/boot/bootloader/nrf/Cargo.toml index 3e41d1479..9d5d51a13 100644 --- a/examples/boot/bootloader/nrf/Cargo.toml +++ b/examples/boot/bootloader/nrf/Cargo.toml @@ -12,20 +12,20 @@ defmt-rtt = { version = "0.4", optional = true } embassy-nrf = { path = "../../../../embassy-nrf", features = [] } embassy-boot-nrf = { path = "../../../../embassy-boot-nrf" } cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } -embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" } +embassy-sync = { version = "0.6.0", path = "../../../../embassy-sync" } cortex-m-rt = { version = "0.7" } cfg-if = "1.0.0" [features] defmt = [ "dep:defmt", + "dep:defmt-rtt", "embassy-boot-nrf/defmt", "embassy-nrf/defmt", ] softdevice = [ "embassy-boot-nrf/softdevice", ] -debug = ["defmt-rtt", "defmt"] [profile.dev] debug = 2 diff --git a/examples/boot/bootloader/nrf/src/main.rs b/examples/boot/bootloader/nrf/src/main.rs index 74e2e293f..b849a0df3 100644 --- a/examples/boot/bootloader/nrf/src/main.rs +++ b/examples/boot/bootloader/nrf/src/main.rs @@ -8,7 +8,7 @@ use cortex_m_rt::{entry, exception}; use defmt_rtt as _; use embassy_boot_nrf::*; use embassy_nrf::nvmc::Nvmc; -use embassy_nrf::wdt; +use embassy_nrf::wdt::{self, HaltConfig, SleepConfig}; use embassy_sync::blocking_mutex::Mutex; #[entry] @@ -25,13 +25,13 @@ fn main() -> ! { let mut wdt_config = wdt::Config::default(); wdt_config.timeout_ticks = 32768 * 5; // timeout seconds - wdt_config.run_during_sleep = true; - wdt_config.run_during_debug_halt = false; + wdt_config.action_during_sleep = SleepConfig::RUN; + wdt_config.action_during_debug_halt = HaltConfig::PAUSE; let flash = WatchdogFlash::start(Nvmc::new(p.NVMC), p.WDT, wdt_config); let flash = Mutex::new(RefCell::new(flash)); - let config = BootLoaderConfig::from_linkerfile_blocking(&flash); + let config = BootLoaderConfig::from_linkerfile_blocking(&flash, &flash, &flash); let active_offset = config.active.offset(); let bl: BootLoader = BootLoader::prepare(config); diff --git a/examples/boot/bootloader/rp/Cargo.toml b/examples/boot/bootloader/rp/Cargo.toml index 3cf61a002..9df396e5e 100644 --- a/examples/boot/bootloader/rp/Cargo.toml +++ b/examples/boot/bootloader/rp/Cargo.toml @@ -9,9 +9,9 @@ license = "MIT OR Apache-2.0" defmt = { version = "0.3", optional = true } defmt-rtt = { version = "0.4", optional = true } -embassy-rp = { path = "../../../../embassy-rp", features = [] } +embassy-rp = { path = "../../../../embassy-rp", features = ["rp2040"] } embassy-boot-rp = { path = "../../../../embassy-boot-rp" } -embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" } +embassy-sync = { version = "0.6.0", path = "../../../../embassy-sync" } embassy-time = { path = "../../../../embassy-time", features = [] } cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } @@ -23,10 +23,10 @@ cfg-if = "1.0.0" [features] defmt = [ "dep:defmt", + "dep:defmt-rtt", "embassy-boot-rp/defmt", "embassy-rp/defmt", ] -debug = ["defmt-rtt", "defmt"] [profile.release] debug = true diff --git a/examples/boot/bootloader/rp/memory.x b/examples/boot/bootloader/rp/memory.x index c3b54976e..88b5bbb15 100644 --- a/examples/boot/bootloader/rp/memory.x +++ b/examples/boot/bootloader/rp/memory.x @@ -2,7 +2,7 @@ MEMORY { /* NOTE 1 K = 1 KiBi = 1024 bytes */ BOOT2 : ORIGIN = 0x10000000, LENGTH = 0x100 - FLASH : ORIGIN = 0x10000100, LENGTH = 24K + FLASH : ORIGIN = 0x10000100, LENGTH = 24K - 0x100 BOOTLOADER_STATE : ORIGIN = 0x10006000, LENGTH = 4K ACTIVE : ORIGIN = 0x10007000, LENGTH = 512K DFU : ORIGIN = 0x10087000, LENGTH = 516K diff --git a/examples/boot/bootloader/rp/src/main.rs b/examples/boot/bootloader/rp/src/main.rs index c0e75d1ea..25b1657b8 100644 --- a/examples/boot/bootloader/rp/src/main.rs +++ b/examples/boot/bootloader/rp/src/main.rs @@ -27,7 +27,7 @@ fn main() -> ! { let flash = WatchdogFlash::::start(p.FLASH, p.WATCHDOG, Duration::from_secs(8)); let flash = Mutex::new(RefCell::new(flash)); - let config = BootLoaderConfig::from_linkerfile_blocking(&flash); + let config = BootLoaderConfig::from_linkerfile_blocking(&flash, &flash, &flash); let active_offset = config.active.offset(); let bl: BootLoader = BootLoader::prepare(config); diff --git a/examples/boot/bootloader/stm32-dual-bank/Cargo.toml b/examples/boot/bootloader/stm32-dual-bank/Cargo.toml new file mode 100644 index 000000000..b91b05412 --- /dev/null +++ b/examples/boot/bootloader/stm32-dual-bank/Cargo.toml @@ -0,0 +1,56 @@ +[package] +edition = "2021" +name = "stm32-bootloader-dual-bank-flash-example" +version = "0.1.0" +description = "Example bootloader for dual-bank flash STM32 chips" +license = "MIT OR Apache-2.0" + +[dependencies] +defmt = { version = "0.3", optional = true } +defmt-rtt = { version = "0.4", optional = true } + +embassy-stm32 = { path = "../../../../embassy-stm32", features = [] } +embassy-boot-stm32 = { path = "../../../../embassy-boot-stm32" } +cortex-m = { version = "0.7.6", features = [ + "inline-asm", + "critical-section-single-core", +] } +embassy-sync = { version = "0.6.0", path = "../../../../embassy-sync" } +cortex-m-rt = { version = "0.7" } +embedded-storage = "0.3.1" +embedded-storage-async = "0.4.0" +cfg-if = "1.0.0" + +[features] +defmt = ["dep:defmt", "dep:defmt-rtt", "embassy-boot-stm32/defmt", "embassy-stm32/defmt"] + +[profile.dev] +debug = 2 +debug-assertions = true +incremental = false +opt-level = 'z' +overflow-checks = true + +[profile.release] +codegen-units = 1 +debug = 2 +debug-assertions = false +incremental = false +lto = 'fat' +opt-level = 'z' +overflow-checks = false + +# do not optimize proc-macro crates = faster builds from scratch +[profile.dev.build-override] +codegen-units = 8 +debug = false +debug-assertions = false +opt-level = 0 +overflow-checks = false + +[profile.release.build-override] +codegen-units = 8 +debug = false +debug-assertions = false +opt-level = 0 +overflow-checks = false diff --git a/examples/boot/bootloader/stm32-dual-bank/README.md b/examples/boot/bootloader/stm32-dual-bank/README.md new file mode 100644 index 000000000..cd6c0bc84 --- /dev/null +++ b/examples/boot/bootloader/stm32-dual-bank/README.md @@ -0,0 +1,44 @@ +# STM32 dual-bank flash Bootloader + +## Overview + +This bootloader leverages `embassy-boot` to interact with the flash. +This example targets STM32 devices with dual-bank flash memory, with a primary focus on the STM32H747XI series. +Users must modify the `memory.x` configuration file to match with the memory layout of their specific STM32 device. + +Additionally, this example can be extended to utilize external flash memory, such as QSPI, for storing partitions. + +## Memory Configuration + +In this example's `memory.x` file, various symbols are defined to assist in effective memory management within the bootloader environment. +For dual-bank STM32 devices, it's crucial to assign these symbols correctly to their respective memory banks. + +### Symbol Definitions + +The bootloader's state and active symbols are anchored to the flash origin of **bank 1**: + +- `__bootloader_state_start` and `__bootloader_state_end` +- `__bootloader_active_start` and `__bootloader_active_end` + +In contrast, the Device Firmware Upgrade (DFU) symbols are aligned with the DFU flash origin in **bank 2**: + +- `__bootloader_dfu_start` and `__bootloader_dfu_end` + +```rust +__bootloader_state_start = ORIGIN(BOOTLOADER_STATE) - ORIGIN(**FLASH**); +__bootloader_state_end = ORIGIN(BOOTLOADER_STATE) + LENGTH(BOOTLOADER_STATE) - ORIGIN(**FLASH**); + +__bootloader_active_start = ORIGIN(ACTIVE) - ORIGIN(**FLASH**); +__bootloader_active_end = ORIGIN(ACTIVE) + LENGTH(ACTIVE) - ORIGIN(**FLASH**); + +__bootloader_dfu_start = ORIGIN(DFU) - ORIGIN(**DFU**); +__bootloader_dfu_end = ORIGIN(DFU) + LENGTH(DFU) - ORIGIN(**DFU**); +``` + +## Flashing the Bootloader + +To flash the bootloader onto your STM32H747XI device, use the following command: + +```bash +cargo flash --features embassy-stm32/stm32h747xi-cm7 --release --chip STM32H747XIHx +``` diff --git a/examples/boot/bootloader/stm32-dual-bank/build.rs b/examples/boot/bootloader/stm32-dual-bank/build.rs new file mode 100644 index 000000000..fd605991f --- /dev/null +++ b/examples/boot/bootloader/stm32-dual-bank/build.rs @@ -0,0 +1,27 @@ +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; + +fn main() { + // Put `memory.x` in our output directory and ensure it's + // on the linker search path. + let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); + File::create(out.join("memory.x")) + .unwrap() + .write_all(include_bytes!("memory.x")) + .unwrap(); + println!("cargo:rustc-link-search={}", out.display()); + + // By default, Cargo will re-run a build script whenever + // any file in the project changes. By specifying `memory.x` + // here, we ensure the build script is only re-run when + // `memory.x` is changed. + println!("cargo:rerun-if-changed=memory.x"); + + println!("cargo:rustc-link-arg-bins=--nmagic"); + println!("cargo:rustc-link-arg-bins=-Tlink.x"); + if env::var("CARGO_FEATURE_DEFMT").is_ok() { + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); + } +} diff --git a/examples/boot/bootloader/stm32-dual-bank/memory.x b/examples/boot/bootloader/stm32-dual-bank/memory.x new file mode 100644 index 000000000..665da7139 --- /dev/null +++ b/examples/boot/bootloader/stm32-dual-bank/memory.x @@ -0,0 +1,18 @@ +MEMORY +{ + /* NOTE 1 K = 1 KiBi = 1024 bytes */ + FLASH : ORIGIN = 0x08000000, LENGTH = 128K + BOOTLOADER_STATE : ORIGIN = 0x08020000, LENGTH = 128K + ACTIVE : ORIGIN = 0x08040000, LENGTH = 512K + DFU : ORIGIN = 0x08100000, LENGTH = 640K + RAM (rwx) : ORIGIN = 0x24000000, LENGTH = 512K +} + +__bootloader_state_start = ORIGIN(BOOTLOADER_STATE) - ORIGIN(FLASH); +__bootloader_state_end = ORIGIN(BOOTLOADER_STATE) + LENGTH(BOOTLOADER_STATE) - ORIGIN(FLASH); + +__bootloader_active_start = ORIGIN(ACTIVE) - ORIGIN(FLASH); +__bootloader_active_end = ORIGIN(ACTIVE) + LENGTH(ACTIVE) - ORIGIN(FLASH); + +__bootloader_dfu_start = ORIGIN(DFU) - ORIGIN(DFU); +__bootloader_dfu_end = ORIGIN(DFU) + LENGTH(DFU) - ORIGIN(DFU); diff --git a/examples/boot/bootloader/stm32-dual-bank/src/main.rs b/examples/boot/bootloader/stm32-dual-bank/src/main.rs new file mode 100644 index 000000000..4d2e82d26 --- /dev/null +++ b/examples/boot/bootloader/stm32-dual-bank/src/main.rs @@ -0,0 +1,53 @@ +#![no_std] +#![no_main] + +use core::cell::RefCell; + +use cortex_m_rt::{entry, exception}; +#[cfg(feature = "defmt")] +use defmt_rtt as _; +use embassy_boot_stm32::*; +use embassy_stm32::flash::{Flash, BANK1_REGION}; +use embassy_sync::blocking_mutex::Mutex; + +#[entry] +fn main() -> ! { + let p = embassy_stm32::init(Default::default()); + + // Uncomment this if you are debugging the bootloader with debugger/RTT attached, + // as it prevents a hard fault when accessing flash 'too early' after boot. + /* + for i in 0..10000000 { + cortex_m::asm::nop(); + } + */ + + let layout = Flash::new_blocking(p.FLASH).into_blocking_regions(); + let flash_bank1 = Mutex::new(RefCell::new(layout.bank1_region)); + let flash_bank2 = Mutex::new(RefCell::new(layout.bank2_region)); + + let config = BootLoaderConfig::from_linkerfile_blocking(&flash_bank1, &flash_bank2, &flash_bank1); + let active_offset = config.active.offset(); + let bl = BootLoader::prepare::<_, _, _, 2048>(config); + + unsafe { bl.load(BANK1_REGION.base + active_offset) } +} + +#[no_mangle] +#[cfg_attr(target_os = "none", link_section = ".HardFault.user")] +unsafe extern "C" fn HardFault() { + cortex_m::peripheral::SCB::sys_reset(); +} + +#[exception] +unsafe fn DefaultHandler(_: i16) -> ! { + const SCB_ICSR: *const u32 = 0xE000_ED04 as *const u32; + let irqn = core::ptr::read_volatile(SCB_ICSR) as u8 as i16 - 16; + + panic!("DefaultHandler #{:?}", irqn); +} + +#[panic_handler] +fn panic(_info: &core::panic::PanicInfo) -> ! { + cortex_m::asm::udf(); +} diff --git a/examples/boot/bootloader/stm32/Cargo.toml b/examples/boot/bootloader/stm32/Cargo.toml index 74c01b0f4..541186949 100644 --- a/examples/boot/bootloader/stm32/Cargo.toml +++ b/examples/boot/bootloader/stm32/Cargo.toml @@ -12,7 +12,7 @@ defmt-rtt = { version = "0.4", optional = true } embassy-stm32 = { path = "../../../../embassy-stm32", features = [] } embassy-boot-stm32 = { path = "../../../../embassy-boot-stm32" } cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } -embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" } +embassy-sync = { version = "0.6.0", path = "../../../../embassy-sync" } cortex-m-rt = { version = "0.7" } embedded-storage = "0.3.1" embedded-storage-async = "0.4.0" @@ -21,10 +21,10 @@ cfg-if = "1.0.0" [features] defmt = [ "dep:defmt", + "dep:defmt-rtt", "embassy-boot-stm32/defmt", "embassy-stm32/defmt", ] -debug = ["defmt-rtt", "defmt"] [profile.dev] debug = 2 diff --git a/examples/boot/bootloader/stm32/memory.x b/examples/boot/bootloader/stm32/memory.x index b6f185ef7..198290520 100644 --- a/examples/boot/bootloader/stm32/memory.x +++ b/examples/boot/bootloader/stm32/memory.x @@ -2,7 +2,7 @@ MEMORY { /* NOTE 1 K = 1 KiBi = 1024 bytes */ FLASH : ORIGIN = 0x08000000, LENGTH = 24K - BOOTLOADER_STATE : ORIGIN = 0x08006000, LENGTH = 4K + BOOTLOADER_STATE : ORIGIN = 0x08006000, LENGTH = 8K ACTIVE : ORIGIN = 0x08008000, LENGTH = 32K DFU : ORIGIN = 0x08010000, LENGTH = 36K RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 16K diff --git a/examples/boot/bootloader/stm32/src/main.rs b/examples/boot/bootloader/stm32/src/main.rs index 5fd9ea588..99a7a6a6b 100644 --- a/examples/boot/bootloader/stm32/src/main.rs +++ b/examples/boot/bootloader/stm32/src/main.rs @@ -25,7 +25,7 @@ fn main() -> ! { let layout = Flash::new_blocking(p.FLASH).into_blocking_regions(); let flash = Mutex::new(RefCell::new(layout.bank1_region)); - let config = BootLoaderConfig::from_linkerfile_blocking(&flash); + let config = BootLoaderConfig::from_linkerfile_blocking(&flash, &flash, &flash); let active_offset = config.active.offset(); let bl = BootLoader::prepare::<_, _, _, 2048>(config); diff --git a/examples/boot/bootloader/stm32wb-dfu/Cargo.toml b/examples/boot/bootloader/stm32wb-dfu/Cargo.toml index 96635afa2..050b672ce 100644 --- a/examples/boot/bootloader/stm32wb-dfu/Cargo.toml +++ b/examples/boot/bootloader/stm32wb-dfu/Cargo.toml @@ -9,27 +9,27 @@ license = "MIT OR Apache-2.0" defmt = { version = "0.3", optional = true } defmt-rtt = { version = "0.4", optional = true } -embassy-stm32 = { path = "../../../../embassy-stm32", features = ["stm32wb55rg"] } +embassy-stm32 = { path = "../../../../embassy-stm32", features = [] } embassy-boot-stm32 = { path = "../../../../embassy-boot-stm32" } cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } -embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" } +embassy-sync = { version = "0.6.0", path = "../../../../embassy-sync" } cortex-m-rt = { version = "0.7" } embedded-storage = "0.3.1" embedded-storage-async = "0.4.0" cfg-if = "1.0.0" embassy-usb-dfu = { version = "0.1.0", path = "../../../../embassy-usb-dfu", features = ["dfu", "cortex-m"] } -embassy-usb = { version = "0.1.0", path = "../../../../embassy-usb", default-features = false } +embassy-usb = { version = "0.3.0", path = "../../../../embassy-usb", default-features = false } embassy-futures = { version = "0.1.1", path = "../../../../embassy-futures" } [features] defmt = [ "dep:defmt", + "dep:defmt-rtt", "embassy-boot-stm32/defmt", "embassy-stm32/defmt", "embassy-usb/defmt", "embassy-usb-dfu/defmt" ] -debug = ["defmt-rtt", "defmt"] [profile.dev] debug = 2 diff --git a/examples/boot/bootloader/stm32wb-dfu/README.md b/examples/boot/bootloader/stm32wb-dfu/README.md index a82b730b9..d5c6ea57c 100644 --- a/examples/boot/bootloader/stm32wb-dfu/README.md +++ b/examples/boot/bootloader/stm32wb-dfu/README.md @@ -7,5 +7,5 @@ The bootloader uses `embassy-boot` to interact with the flash. Flash the bootloader ``` -cargo flash --features embassy-stm32/stm32wl55jc-cm4 --release --chip STM32WLE5JCIx +cargo flash --features embassy-stm32/stm32wb55rg --release --chip STM32WB55RGVx ``` diff --git a/examples/boot/bootloader/stm32wb-dfu/src/main.rs b/examples/boot/bootloader/stm32wb-dfu/src/main.rs index a7ab813b6..093b39f9d 100644 --- a/examples/boot/bootloader/stm32wb-dfu/src/main.rs +++ b/examples/boot/bootloader/stm32wb-dfu/src/main.rs @@ -35,7 +35,7 @@ fn main() -> ! { let layout = Flash::new_blocking(p.FLASH).into_blocking_regions(); let flash = Mutex::new(RefCell::new(layout.bank1_region)); - let config = BootLoaderConfig::from_linkerfile_blocking(&flash); + let config = BootLoaderConfig::from_linkerfile_blocking(&flash, &flash, &flash); let active_offset = config.active.offset(); let bl = BootLoader::prepare::<_, _, _, 2048>(config); if bl.state == State::DfuDetach { @@ -45,11 +45,10 @@ fn main() -> ! { config.product = Some("USB-DFU Bootloader example"); config.serial_number = Some("1235678"); - let fw_config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash); + let fw_config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash, &flash); let mut buffer = AlignedBuffer([0; WRITE_SIZE]); let updater = BlockingFirmwareUpdater::new(fw_config, &mut buffer.0[..]); - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 4096]; @@ -57,7 +56,6 @@ fn main() -> ! { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], diff --git a/examples/lpc55s69/.cargo/config.toml b/examples/lpc55s69/.cargo/config.toml new file mode 100644 index 000000000..9556de72f --- /dev/null +++ b/examples/lpc55s69/.cargo/config.toml @@ -0,0 +1,8 @@ +[target.'cfg(all(target_arch = "arm", target_os = "none"))'] +runner = "probe-rs run --chip LPC55S69JBD100" + +[build] +target = "thumbv8m.main-none-eabihf" + +[env] +DEFMT_LOG = "debug" diff --git a/examples/lpc55s69/Cargo.toml b/examples/lpc55s69/Cargo.toml new file mode 100644 index 000000000..a18b29f2e --- /dev/null +++ b/examples/lpc55s69/Cargo.toml @@ -0,0 +1,22 @@ +[package] +edition = "2021" +name = "embassy-nxp-lpc55s69-examples" +version = "0.1.0" +license = "MIT OR Apache-2.0" + + +[dependencies] +embassy-nxp = { version = "0.1.0", path = "../../embassy-nxp", features = ["rt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt"] } +panic-halt = "0.2.0" +cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } +cortex-m-rt = {version = "0.7.0"} +defmt = "0.3" +defmt-rtt = "0.4" +panic-probe = { version = "0.3.2", features = ["print-defmt"] } +panic-semihosting = "0.6.0" + +[profile.release] +debug = 2 diff --git a/examples/lpc55s69/build.rs b/examples/lpc55s69/build.rs new file mode 100644 index 000000000..30691aa97 --- /dev/null +++ b/examples/lpc55s69/build.rs @@ -0,0 +1,35 @@ +//! This build script copies the `memory.x` file from the crate root into +//! a directory where the linker can always find it at build time. +//! For many projects this is optional, as the linker always searches the +//! project root directory -- wherever `Cargo.toml` is. However, if you +//! are using a workspace or have a more complicated build setup, this +//! build script becomes required. Additionally, by requesting that +//! Cargo re-run the build script whenever `memory.x` is changed, +//! updating `memory.x` ensures a rebuild of the application with the +//! new memory settings. + +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; + +fn main() { + // Put `memory.x` in our output directory and ensure it's + // on the linker search path. + let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); + File::create(out.join("memory.x")) + .unwrap() + .write_all(include_bytes!("memory.x")) + .unwrap(); + println!("cargo:rustc-link-search={}", out.display()); + + // By default, Cargo will re-run a build script whenever + // any file in the project changes. By specifying `memory.x` + // here, we ensure the build script is only re-run when + // `memory.x` is changed. + println!("cargo:rerun-if-changed=memory.x"); + + println!("cargo:rustc-link-arg-bins=--nmagic"); + println!("cargo:rustc-link-arg-bins=-Tlink.x"); + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); +} diff --git a/examples/lpc55s69/memory.x b/examples/lpc55s69/memory.x new file mode 100644 index 000000000..1483b2fad --- /dev/null +++ b/examples/lpc55s69/memory.x @@ -0,0 +1,28 @@ +/* File originally from lpc55-hal repo: https://github.com/lpc55/lpc55-hal/blob/main/memory.x */ +MEMORY +{ + FLASH : ORIGIN = 0x00000000, LENGTH = 512K + + /* for use with standard link.x */ + RAM : ORIGIN = 0x20000000, LENGTH = 256K + + /* would be used with proper link.x */ + /* needs changes to r0 (initialization code) */ + /* SRAM0 : ORIGIN = 0x20000000, LENGTH = 64K */ + /* SRAM1 : ORIGIN = 0x20010000, LENGTH = 64K */ + /* SRAM2 : ORIGIN = 0x20020000, LENGTH = 64K */ + /* SRAM3 : ORIGIN = 0x20030000, LENGTH = 64K */ + + /* CASPER SRAM regions */ + /* SRAMX0: ORIGIN = 0x1400_0000, LENGTH = 4K /1* to 0x1400_0FFF *1/ */ + /* SRAMX1: ORIGIN = 0x1400_4000, LENGTH = 4K /1* to 0x1400_4FFF *1/ */ + + /* USB1 SRAM regin */ + /* USB1_SRAM : ORIGIN = 0x40100000, LENGTH = 16K */ + + /* To define our own USB RAM section in one regular */ + /* RAM, probably easiest to shorten length of RAM */ + /* above, and use this freed RAM section */ + +} + diff --git a/examples/lpc55s69/src/bin/blinky_nop.rs b/examples/lpc55s69/src/bin/blinky_nop.rs new file mode 100644 index 000000000..58e2d9808 --- /dev/null +++ b/examples/lpc55s69/src/bin/blinky_nop.rs @@ -0,0 +1,33 @@ +//! This example has been made with the LPCXpresso55S69 board in mind, which has a built-in LED on PIO1_6. + +#![no_std] +#![no_main] + +use cortex_m::asm::nop; +use defmt::*; +use embassy_executor::Spawner; +use embassy_nxp::gpio::{Level, Output}; +use {defmt_rtt as _, panic_halt as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_nxp::init(Default::default()); + + let mut led = Output::new(p.PIO1_6, Level::Low); + + loop { + info!("led off!"); + led.set_high(); + + for _ in 0..200_000 { + nop(); + } + + info!("led on!"); + led.set_low(); + + for _ in 0..200_000 { + nop(); + } + } +} diff --git a/examples/lpc55s69/src/bin/button_executor.rs b/examples/lpc55s69/src/bin/button_executor.rs new file mode 100644 index 000000000..836b1c9eb --- /dev/null +++ b/examples/lpc55s69/src/bin/button_executor.rs @@ -0,0 +1,25 @@ +//! This example has been made with the LPCXpresso55S69 board in mind, which has a built-in LED on +//! PIO1_6 and a button (labeled "user") on PIO1_9. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_nxp::gpio::{Input, Level, Output, Pull}; +use {defmt_rtt as _, panic_halt as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) -> ! { + let p = embassy_nxp::init(Default::default()); + + let mut led = Output::new(p.PIO1_6, Level::Low); + let mut button = Input::new(p.PIO1_9, Pull::Up); + + info!("Entered main loop"); + loop { + button.wait_for_rising_edge().await; + info!("Button pressed"); + led.toggle(); + } +} diff --git a/examples/nrf-rtos-trace/Cargo.toml b/examples/nrf-rtos-trace/Cargo.toml index 17210994b..fbdd2744c 100644 --- a/examples/nrf-rtos-trace/Cargo.toml +++ b/examples/nrf-rtos-trace/Cargo.toml @@ -15,15 +15,14 @@ log = [ ] [dependencies] -embassy-sync = { version = "0.5.0", path = "../../embassy-sync" } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "rtos-trace", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time" } -embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync" } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "rtos-trace", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time" } +embassy-nrf = { version = "0.2.0", path = "../../embassy-nrf", features = ["nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac"] } cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } cortex-m-rt = "0.7.0" panic-probe = { version = "0.3" } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } rand = { version = "0.8.4", default-features = false } serde = { version = "1.0.136", default-features = false } rtos-trace = "0.1.3" diff --git a/examples/nrf51/Cargo.toml b/examples/nrf51/Cargo.toml index d1e919a33..3799a87cc 100644 --- a/examples/nrf51/Cargo.toml +++ b/examples/nrf51/Cargo.toml @@ -5,9 +5,9 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-4096", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } -embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nrf51", "time-driver-rtc1", "unstable-pac", "time", "rt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-4096", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } +embassy-nrf = { version = "0.2.0", path = "../../embassy-nrf", features = ["defmt", "nrf51", "gpiote", "time-driver-rtc1", "unstable-pac", "time", "rt"] } defmt = "0.3" defmt-rtt = "0.4" diff --git a/examples/nrf52810/.cargo/config.toml b/examples/nrf52810/.cargo/config.toml new file mode 100644 index 000000000..917a5364a --- /dev/null +++ b/examples/nrf52810/.cargo/config.toml @@ -0,0 +1,9 @@ +[target.'cfg(all(target_arch = "arm", target_os = "none"))'] +# replace nRF82810_xxAA with your chip as listed in `probe-rs chip list` +runner = "probe-rs run --chip nRF52810_xxAA" + +[build] +target = "thumbv7em-none-eabi" + +[env] +DEFMT_LOG = "trace" diff --git a/examples/nrf52810/Cargo.toml b/examples/nrf52810/Cargo.toml new file mode 100644 index 000000000..e3045bdba --- /dev/null +++ b/examples/nrf52810/Cargo.toml @@ -0,0 +1,24 @@ +[package] +edition = "2021" +name = "embassy-nrf52810-examples" +version = "0.1.0" +license = "MIT OR Apache-2.0" + +[dependencies] +embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-8192", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } +embassy-nrf = { version = "0.2.0", path = "../../embassy-nrf", features = ["defmt", "nrf52810", "time-driver-rtc1", "gpiote", "unstable-pac", "time"] } + +defmt = "0.3" +defmt-rtt = "0.4" + +fixed = "1.10.0" +static_cell = { version = "2" } +cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } +cortex-m-rt = "0.7.0" +panic-probe = { version = "0.3", features = ["print-defmt"] } + +[profile.release] +debug = 2 diff --git a/examples/nrf52810/build.rs b/examples/nrf52810/build.rs new file mode 100644 index 000000000..30691aa97 --- /dev/null +++ b/examples/nrf52810/build.rs @@ -0,0 +1,35 @@ +//! This build script copies the `memory.x` file from the crate root into +//! a directory where the linker can always find it at build time. +//! For many projects this is optional, as the linker always searches the +//! project root directory -- wherever `Cargo.toml` is. However, if you +//! are using a workspace or have a more complicated build setup, this +//! build script becomes required. Additionally, by requesting that +//! Cargo re-run the build script whenever `memory.x` is changed, +//! updating `memory.x` ensures a rebuild of the application with the +//! new memory settings. + +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; + +fn main() { + // Put `memory.x` in our output directory and ensure it's + // on the linker search path. + let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); + File::create(out.join("memory.x")) + .unwrap() + .write_all(include_bytes!("memory.x")) + .unwrap(); + println!("cargo:rustc-link-search={}", out.display()); + + // By default, Cargo will re-run a build script whenever + // any file in the project changes. By specifying `memory.x` + // here, we ensure the build script is only re-run when + // `memory.x` is changed. + println!("cargo:rerun-if-changed=memory.x"); + + println!("cargo:rustc-link-arg-bins=--nmagic"); + println!("cargo:rustc-link-arg-bins=-Tlink.x"); + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); +} diff --git a/examples/nrf52810/memory.x b/examples/nrf52810/memory.x new file mode 100644 index 000000000..7cf560e44 --- /dev/null +++ b/examples/nrf52810/memory.x @@ -0,0 +1,7 @@ +MEMORY +{ + /* NOTE 1 K = 1 KiBi = 1024 bytes */ + FLASH : ORIGIN = 0x00000000, LENGTH = 256K + RAM : ORIGIN = 0x20000000, LENGTH = 24K + +} diff --git a/examples/nrf52810/src/bin/blinky.rs b/examples/nrf52810/src/bin/blinky.rs new file mode 100644 index 000000000..1da039f7d --- /dev/null +++ b/examples/nrf52810/src/bin/blinky.rs @@ -0,0 +1,20 @@ +#![no_std] +#![no_main] + +use embassy_executor::Spawner; +use embassy_nrf::gpio::{Level, Output, OutputDrive}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_nrf::init(Default::default()); + let mut led = Output::new(p.P0_18, Level::Low, OutputDrive::Standard); + + loop { + led.set_high(); + Timer::after_millis(300).await; + led.set_low(); + Timer::after_millis(300).await; + } +} diff --git a/examples/nrf52840-rtic/Cargo.toml b/examples/nrf52840-rtic/Cargo.toml index d91f58d0e..7fae7aefc 100644 --- a/examples/nrf52840-rtic/Cargo.toml +++ b/examples/nrf52840-rtic/Cargo.toml @@ -8,9 +8,9 @@ license = "MIT OR Apache-2.0" rtic = { version = "2", features = ["thumbv7-backend"] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = [ "defmt", "defmt-timestamp-uptime", "generic-queue"] } -embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = [ "defmt", "nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac", "time"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = [ "defmt", "defmt-timestamp-uptime", "generic-queue"] } +embassy-nrf = { version = "0.2.0", path = "../../embassy-nrf", features = [ "defmt", "nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac", "time"] } defmt = "0.3" defmt-rtt = "0.4" @@ -18,7 +18,6 @@ defmt-rtt = "0.4" cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } cortex-m-rt = "0.7.0" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } [profile.release] debug = 2 diff --git a/examples/nrf52840/Cargo.toml b/examples/nrf52840/Cargo.toml index abb995be6..e0a27c628 100644 --- a/examples/nrf52840/Cargo.toml +++ b/examples/nrf52840/Cargo.toml @@ -6,12 +6,12 @@ license = "MIT OR Apache-2.0" [dependencies] embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } -embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac", "time"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } +embassy-nrf = { version = "0.2.0", path = "../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac", "time"] } embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet"] } -embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } embedded-io = { version = "0.6.0", features = ["defmt-03"] } embedded-io-async = { version = "0.6.1", features = ["defmt-03"] } embassy-net-esp-hosted = { version = "0.1.0", path = "../../embassy-net-esp-hosted", features = ["defmt"] } @@ -25,10 +25,9 @@ static_cell = { version = "2" } cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } cortex-m-rt = "0.7.0" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } rand = { version = "0.8.4", default-features = false } embedded-storage = "0.3.1" -usbd-hid = "0.6.0" +usbd-hid = "0.8.1" serde = { version = "1.0.136", default-features = false } embedded-hal = { version = "1.0" } embedded-hal-async = { version = "1.0" } diff --git a/examples/nrf52840/src/bin/channel.rs b/examples/nrf52840/src/bin/channel.rs index 7fcea9dbd..e06ba1c73 100644 --- a/examples/nrf52840/src/bin/channel.rs +++ b/examples/nrf52840/src/bin/channel.rs @@ -35,8 +35,8 @@ async fn main(spawner: Spawner) { loop { match CHANNEL.receive().await { - LedState::On => led.set_high(), - LedState::Off => led.set_low(), + LedState::On => led.set_low(), + LedState::Off => led.set_high(), } } } diff --git a/examples/nrf52840/src/bin/channel_sender_receiver.rs b/examples/nrf52840/src/bin/channel_sender_receiver.rs index 3095a04ec..29f70f91c 100644 --- a/examples/nrf52840/src/bin/channel_sender_receiver.rs +++ b/examples/nrf52840/src/bin/channel_sender_receiver.rs @@ -33,8 +33,8 @@ async fn recv_task(led: AnyPin, receiver: Receiver<'static, NoopRawMutex, LedSta loop { match receiver.receive().await { - LedState::On => led.set_high(), - LedState::Off => led.set_low(), + LedState::On => led.set_low(), + LedState::Off => led.set_high(), } } } diff --git a/examples/nrf52840/src/bin/egu.rs b/examples/nrf52840/src/bin/egu.rs new file mode 100644 index 000000000..8bf712697 --- /dev/null +++ b/examples/nrf52840/src/bin/egu.rs @@ -0,0 +1,43 @@ +//! This example shows the use of the EGU peripheral combined with PPI. +//! +//! It chains events from button -> egu0-trigger0 -> egu0-trigger1 -> led +#![no_std] +#![no_main] + +use embassy_executor::Spawner; +use embassy_nrf::egu::{Egu, TriggerNumber}; +use embassy_nrf::gpio::{Input, Level, Output, OutputDrive, Pull}; +use embassy_nrf::gpiote::{InputChannel, InputChannelPolarity, OutputChannel, OutputChannelPolarity}; +use embassy_nrf::peripherals::{PPI_CH0, PPI_CH1, PPI_CH2}; +use embassy_nrf::ppi::Ppi; +use embassy_time::{Duration, Timer}; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_nrf::init(Default::default()); + + let led1 = Output::new(p.P0_13, Level::High, OutputDrive::Standard); + let btn1 = Input::new(p.P0_11, Pull::Up); + + let mut egu1 = Egu::new(p.EGU0); + let led1 = OutputChannel::new(p.GPIOTE_CH0, led1, OutputChannelPolarity::Toggle); + let btn1 = InputChannel::new(p.GPIOTE_CH1, btn1, InputChannelPolarity::LoToHi); + + let trigger0 = egu1.trigger(TriggerNumber::Trigger0); + let trigger1 = egu1.trigger(TriggerNumber::Trigger1); + + let mut ppi1: Ppi = Ppi::new_one_to_one(p.PPI_CH0, btn1.event_in(), trigger0.task()); + ppi1.enable(); + + let mut ppi2: Ppi = Ppi::new_one_to_one(p.PPI_CH1, trigger0.event(), trigger1.task()); + ppi2.enable(); + + let mut ppi3: Ppi = Ppi::new_one_to_one(p.PPI_CH2, trigger1.event(), led1.task_out()); + ppi3.enable(); + + defmt::info!("Push the button to toggle the LED"); + loop { + Timer::after(Duration::from_secs(60)).await; + } +} diff --git a/examples/nrf52840/src/bin/ethernet_enc28j60.rs b/examples/nrf52840/src/bin/ethernet_enc28j60.rs index 279f32edc..0946492fe 100644 --- a/examples/nrf52840/src/bin/ethernet_enc28j60.rs +++ b/examples/nrf52840/src/bin/ethernet_enc28j60.rs @@ -4,7 +4,7 @@ use defmt::*; use embassy_executor::Spawner; use embassy_net::tcp::TcpSocket; -use embassy_net::{Stack, StackResources}; +use embassy_net::StackResources; use embassy_net_enc28j60::Enc28j60; use embassy_nrf::gpio::{Level, Output, OutputDrive}; use embassy_nrf::rng::Rng; @@ -23,11 +23,12 @@ bind_interrupts!(struct Irqs { #[embassy_executor::task] async fn net_task( - stack: &'static Stack< + mut runner: embassy_net::Runner< + 'static, Enc28j60, Output<'static>, Delay>, Output<'static>>, >, ) -> ! { - stack.run().await + runner.run().await } #[embassy_executor::main] @@ -66,18 +67,10 @@ async fn main(spawner: Spawner) { let seed = u64::from_le_bytes(seed); // Init network stack - static RESOURCES: StaticCell> = StaticCell::new(); - static STACK: StaticCell< - Stack, Output<'static>, Delay>, Output<'static>>>, - > = StaticCell::new(); - let stack = STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<2>::new()), - seed, - )); + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); // And now we can use it! diff --git a/examples/nrf52840/src/bin/gpiote_channel.rs b/examples/nrf52840/src/bin/gpiote_channel.rs index e254d613d..dcfe7723a 100644 --- a/examples/nrf52840/src/bin/gpiote_channel.rs +++ b/examples/nrf52840/src/bin/gpiote_channel.rs @@ -61,5 +61,5 @@ async fn main(_spawner: Spawner) { } }; - futures::join!(button1, button2, button3, button4); + embassy_futures::join::join4(button1, button2, button3, button4).await; } diff --git a/examples/nrf52840/src/bin/multiprio.rs b/examples/nrf52840/src/bin/multiprio.rs index b634d8569..797be93a7 100644 --- a/examples/nrf52840/src/bin/multiprio.rs +++ b/examples/nrf52840/src/bin/multiprio.rs @@ -80,7 +80,7 @@ async fn run_med() { info!(" [med] Starting long computation"); // Spin-wait to simulate a long CPU computation - cortex_m::asm::delay(32_000_000); // ~1 second + embassy_time::block_for(embassy_time::Duration::from_secs(1)); // ~1 second let end = Instant::now(); let ms = end.duration_since(start).as_ticks() / 33; @@ -97,7 +97,7 @@ async fn run_low() { info!("[low] Starting long computation"); // Spin-wait to simulate a long CPU computation - cortex_m::asm::delay(64_000_000); // ~2 seconds + embassy_time::block_for(embassy_time::Duration::from_secs(2)); // ~2 seconds let end = Instant::now(); let ms = end.duration_since(start).as_ticks() / 33; diff --git a/examples/nrf52840/src/bin/usb_ethernet.rs b/examples/nrf52840/src/bin/usb_ethernet.rs index 3469c6e5f..82364ded8 100644 --- a/examples/nrf52840/src/bin/usb_ethernet.rs +++ b/examples/nrf52840/src/bin/usb_ethernet.rs @@ -1,12 +1,10 @@ #![no_std] #![no_main] -use core::mem; - use defmt::*; use embassy_executor::Spawner; use embassy_net::tcp::TcpSocket; -use embassy_net::{Stack, StackResources}; +use embassy_net::StackResources; use embassy_nrf::rng::Rng; use embassy_nrf::usb::vbus_detect::HardwareVbusDetect; use embassy_nrf::usb::Driver; @@ -39,18 +37,17 @@ async fn usb_ncm_task(class: Runner<'static, MyDriver, MTU>) -> ! { } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static, MTU>>) -> ! { + runner.run().await } #[embassy_executor::main] async fn main(spawner: Spawner) { let p = embassy_nrf::init(Default::default()); - let clock: pac::CLOCK = unsafe { mem::transmute(()) }; info!("Enabling ext hfosc..."); - clock.tasks_hfclkstart.write(|w| unsafe { w.bits(1) }); - while clock.events_hfclkstarted.read().bits() != 1 {} + pac::CLOCK.tasks_hfclkstart().write_value(1); + while pac::CLOCK.events_hfclkstarted().read() != 1 {} // Create the driver, from the HAL. let driver = Driver::new(p.USBD, Irqs, HardwareVbusDetect::new(Irqs)); @@ -70,7 +67,6 @@ async fn main(spawner: Spawner) { config.device_protocol = 0x01; // Create embassy-usb DeviceBuilder using the driver and config. - static DEVICE_DESC: StaticCell<[u8; 256]> = StaticCell::new(); static CONFIG_DESC: StaticCell<[u8; 256]> = StaticCell::new(); static BOS_DESC: StaticCell<[u8; 256]> = StaticCell::new(); static MSOS_DESC: StaticCell<[u8; 128]> = StaticCell::new(); @@ -78,7 +74,6 @@ async fn main(spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut DEVICE_DESC.init([0; 256])[..], &mut CONFIG_DESC.init([0; 256])[..], &mut BOS_DESC.init([0; 256])[..], &mut MSOS_DESC.init([0; 128])[..], @@ -117,11 +112,10 @@ async fn main(spawner: Spawner) { let seed = u64::from_le_bytes(seed); // Init network stack - static RESOURCES: StaticCell> = StaticCell::new(); - static STACK: StaticCell>> = StaticCell::new(); - let stack = &*STACK.init(Stack::new(device, config, RESOURCES.init(StackResources::new()), seed)); + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); // And now we can use it! diff --git a/examples/nrf52840/src/bin/usb_hid_keyboard.rs b/examples/nrf52840/src/bin/usb_hid_keyboard.rs index 3e86590c4..3b752fd16 100644 --- a/examples/nrf52840/src/bin/usb_hid_keyboard.rs +++ b/examples/nrf52840/src/bin/usb_hid_keyboard.rs @@ -1,7 +1,6 @@ #![no_std] #![no_main] -use core::mem; use core::sync::atomic::{AtomicBool, Ordering}; use defmt::*; @@ -30,11 +29,10 @@ static SUSPENDED: AtomicBool = AtomicBool::new(false); #[embassy_executor::main] async fn main(_spawner: Spawner) { let p = embassy_nrf::init(Default::default()); - let clock: pac::CLOCK = unsafe { mem::transmute(()) }; info!("Enabling ext hfosc..."); - clock.tasks_hfclkstart.write(|w| unsafe { w.bits(1) }); - while clock.events_hfclkstarted.read().bits() != 1 {} + pac::CLOCK.tasks_hfclkstart().write_value(1); + while pac::CLOCK.events_hfclkstarted().read() != 1 {} // Create the driver, from the HAL. let driver = Driver::new(p.USBD, Irqs, HardwareVbusDetect::new(Irqs)); @@ -50,12 +48,11 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut msos_descriptor = [0; 256]; let mut control_buf = [0; 64]; - let request_handler = MyRequestHandler {}; + let mut request_handler = MyRequestHandler {}; let mut device_handler = MyDeviceHandler::new(); let mut state = State::new(); @@ -63,7 +60,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut msos_descriptor, @@ -75,7 +71,7 @@ async fn main(_spawner: Spawner) { // Create classes on the builder. let config = embassy_usb::class::hid::Config { report_descriptor: KeyboardReport::desc(), - request_handler: Some(&request_handler), + request_handler: None, poll_ms: 60, max_packet_size: 64, }; @@ -139,7 +135,7 @@ async fn main(_spawner: Spawner) { }; let out_fut = async { - reader.run(false, &request_handler).await; + reader.run(false, &mut request_handler).await; }; // Run everything concurrently. @@ -150,21 +146,21 @@ async fn main(_spawner: Spawner) { struct MyRequestHandler {} impl RequestHandler for MyRequestHandler { - fn get_report(&self, id: ReportId, _buf: &mut [u8]) -> Option { + fn get_report(&mut self, id: ReportId, _buf: &mut [u8]) -> Option { info!("Get report for {:?}", id); None } - fn set_report(&self, id: ReportId, data: &[u8]) -> OutResponse { + fn set_report(&mut self, id: ReportId, data: &[u8]) -> OutResponse { info!("Set report for {:?}: {=[u8]}", id, data); OutResponse::Accepted } - fn set_idle_ms(&self, id: Option, dur: u32) { + fn set_idle_ms(&mut self, id: Option, dur: u32) { info!("Set idle rate for {:?} to {:?}", id, dur); } - fn get_idle_ms(&self, id: Option) -> Option { + fn get_idle_ms(&mut self, id: Option) -> Option { info!("Get idle rate for {:?}", id); None } diff --git a/examples/nrf52840/src/bin/usb_hid_mouse.rs b/examples/nrf52840/src/bin/usb_hid_mouse.rs index 04ad841b7..3f13a014e 100644 --- a/examples/nrf52840/src/bin/usb_hid_mouse.rs +++ b/examples/nrf52840/src/bin/usb_hid_mouse.rs @@ -1,8 +1,6 @@ #![no_std] #![no_main] -use core::mem; - use defmt::*; use embassy_executor::Spawner; use embassy_futures::join::join; @@ -24,11 +22,10 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) { let p = embassy_nrf::init(Default::default()); - let clock: pac::CLOCK = unsafe { mem::transmute(()) }; info!("Enabling ext hfosc..."); - clock.tasks_hfclkstart.write(|w| unsafe { w.bits(1) }); - while clock.events_hfclkstarted.read().bits() != 1 {} + pac::CLOCK.tasks_hfclkstart().write_value(1); + while pac::CLOCK.events_hfclkstarted().read() != 1 {} // Create the driver, from the HAL. let driver = Driver::new(p.USBD, Irqs, HardwareVbusDetect::new(Irqs)); @@ -43,19 +40,17 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut msos_descriptor = [0; 256]; let mut control_buf = [0; 64]; - let request_handler = MyRequestHandler {}; + let mut request_handler = MyRequestHandler {}; let mut state = State::new(); let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut msos_descriptor, @@ -65,7 +60,7 @@ async fn main(_spawner: Spawner) { // Create classes on the builder. let config = embassy_usb::class::hid::Config { report_descriptor: MouseReport::desc(), - request_handler: Some(&request_handler), + request_handler: Some(&mut request_handler), poll_ms: 60, max_packet_size: 8, }; @@ -107,21 +102,21 @@ async fn main(_spawner: Spawner) { struct MyRequestHandler {} impl RequestHandler for MyRequestHandler { - fn get_report(&self, id: ReportId, _buf: &mut [u8]) -> Option { + fn get_report(&mut self, id: ReportId, _buf: &mut [u8]) -> Option { info!("Get report for {:?}", id); None } - fn set_report(&self, id: ReportId, data: &[u8]) -> OutResponse { + fn set_report(&mut self, id: ReportId, data: &[u8]) -> OutResponse { info!("Set report for {:?}: {=[u8]}", id, data); OutResponse::Accepted } - fn set_idle_ms(&self, id: Option, dur: u32) { + fn set_idle_ms(&mut self, id: Option, dur: u32) { info!("Set idle rate for {:?} to {:?}", id, dur); } - fn get_idle_ms(&self, id: Option) -> Option { + fn get_idle_ms(&mut self, id: Option) -> Option { info!("Get idle rate for {:?}", id); None } diff --git a/examples/nrf52840/src/bin/usb_serial.rs b/examples/nrf52840/src/bin/usb_serial.rs index aff539b1b..30fe103ad 100644 --- a/examples/nrf52840/src/bin/usb_serial.rs +++ b/examples/nrf52840/src/bin/usb_serial.rs @@ -1,8 +1,6 @@ #![no_std] #![no_main] -use core::mem; - use defmt::{info, panic}; use embassy_executor::Spawner; use embassy_futures::join::join; @@ -22,11 +20,10 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) { let p = embassy_nrf::init(Default::default()); - let clock: pac::CLOCK = unsafe { mem::transmute(()) }; info!("Enabling ext hfosc..."); - clock.tasks_hfclkstart.write(|w| unsafe { w.bits(1) }); - while clock.events_hfclkstarted.read().bits() != 1 {} + pac::CLOCK.tasks_hfclkstart().write_value(1); + while pac::CLOCK.events_hfclkstarted().read() != 1 {} // Create the driver, from the HAL. let driver = Driver::new(p.USBD, Irqs, HardwareVbusDetect::new(Irqs)); @@ -48,7 +45,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut msos_descriptor = [0; 256]; @@ -59,7 +55,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut msos_descriptor, diff --git a/examples/nrf52840/src/bin/usb_serial_multitask.rs b/examples/nrf52840/src/bin/usb_serial_multitask.rs index 4e8118fb8..05b5f0ec9 100644 --- a/examples/nrf52840/src/bin/usb_serial_multitask.rs +++ b/examples/nrf52840/src/bin/usb_serial_multitask.rs @@ -1,8 +1,6 @@ #![no_std] #![no_main] -use core::mem; - use defmt::{info, panic, unwrap}; use embassy_executor::Spawner; use embassy_nrf::usb::vbus_detect::HardwareVbusDetect; @@ -39,11 +37,10 @@ async fn echo_task(mut class: CdcAcmClass<'static, MyDriver>) { #[embassy_executor::main] async fn main(spawner: Spawner) { let p = embassy_nrf::init(Default::default()); - let clock: pac::CLOCK = unsafe { mem::transmute(()) }; info!("Enabling ext hfosc..."); - clock.tasks_hfclkstart.write(|w| unsafe { w.bits(1) }); - while clock.events_hfclkstarted.read().bits() != 1 {} + pac::CLOCK.tasks_hfclkstart().write_value(1); + while pac::CLOCK.events_hfclkstarted().read() != 1 {} // Create the driver, from the HAL. let driver = Driver::new(p.USBD, Irqs, HardwareVbusDetect::new(Irqs)); @@ -67,7 +64,6 @@ async fn main(spawner: Spawner) { let state = STATE.init(State::new()); // Create embassy-usb DeviceBuilder using the driver and config. - static DEVICE_DESC: StaticCell<[u8; 256]> = StaticCell::new(); static CONFIG_DESC: StaticCell<[u8; 256]> = StaticCell::new(); static BOS_DESC: StaticCell<[u8; 256]> = StaticCell::new(); static MSOS_DESC: StaticCell<[u8; 128]> = StaticCell::new(); @@ -75,7 +71,6 @@ async fn main(spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut DEVICE_DESC.init([0; 256])[..], &mut CONFIG_DESC.init([0; 256])[..], &mut BOS_DESC.init([0; 256])[..], &mut MSOS_DESC.init([0; 128])[..], diff --git a/examples/nrf52840/src/bin/usb_serial_winusb.rs b/examples/nrf52840/src/bin/usb_serial_winusb.rs index 060f9ba94..7c07158e0 100644 --- a/examples/nrf52840/src/bin/usb_serial_winusb.rs +++ b/examples/nrf52840/src/bin/usb_serial_winusb.rs @@ -1,8 +1,6 @@ #![no_std] #![no_main] -use core::mem; - use defmt::{info, panic}; use embassy_executor::Spawner; use embassy_futures::join::join; @@ -27,11 +25,10 @@ const DEVICE_INTERFACE_GUIDS: &[&str] = &["{EAA9A5DC-30BA-44BC-9232-606CDC875321 #[embassy_executor::main] async fn main(_spawner: Spawner) { let p = embassy_nrf::init(Default::default()); - let clock: pac::CLOCK = unsafe { mem::transmute(()) }; info!("Enabling ext hfosc..."); - clock.tasks_hfclkstart.write(|w| unsafe { w.bits(1) }); - while clock.events_hfclkstarted.read().bits() != 1 {} + pac::CLOCK.tasks_hfclkstart().write_value(1); + while pac::CLOCK.events_hfclkstarted().read() != 1 {} // Create the driver, from the HAL. let driver = Driver::new(p.USBD, Irqs, HardwareVbusDetect::new(Irqs)); @@ -53,7 +50,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut msos_descriptor = [0; 256]; @@ -64,7 +60,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut msos_descriptor, diff --git a/examples/nrf52840/src/bin/wdt.rs b/examples/nrf52840/src/bin/wdt.rs index ede88cc26..0d9ee3cf8 100644 --- a/examples/nrf52840/src/bin/wdt.rs +++ b/examples/nrf52840/src/bin/wdt.rs @@ -4,7 +4,7 @@ use defmt::*; use embassy_executor::Spawner; use embassy_nrf::gpio::{Input, Pull}; -use embassy_nrf::wdt::{Config, Watchdog}; +use embassy_nrf::wdt::{Config, HaltConfig, Watchdog}; use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] @@ -17,7 +17,7 @@ async fn main(_spawner: Spawner) { // This is needed for `probe-rs run` to be able to catch the panic message // in the WDT interrupt. The core resets 2 ticks after firing the interrupt. - config.run_during_debug_halt = false; + config.action_during_debug_halt = HaltConfig::PAUSE; let (_wdt, [mut handle]) = match Watchdog::try_new(p.WDT, config) { Ok(x) => x, diff --git a/examples/nrf52840/src/bin/wifi_esp_hosted.rs b/examples/nrf52840/src/bin/wifi_esp_hosted.rs index 00bd50081..26eaf485e 100644 --- a/examples/nrf52840/src/bin/wifi_esp_hosted.rs +++ b/examples/nrf52840/src/bin/wifi_esp_hosted.rs @@ -4,7 +4,7 @@ use defmt::{info, unwrap, warn}; use embassy_executor::Spawner; use embassy_net::tcp::TcpSocket; -use embassy_net::{Stack, StackResources}; +use embassy_net::StackResources; use embassy_nrf::gpio::{Input, Level, Output, OutputDrive, Pull}; use embassy_nrf::rng::Rng; use embassy_nrf::spim::{self, Spim}; @@ -36,8 +36,8 @@ async fn wifi_task( } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, hosted::NetDriver<'static>>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -89,16 +89,10 @@ async fn main(spawner: Spawner) { let seed = u64::from_le_bytes(seed); // Init network stack - static RESOURCES: StaticCell> = StaticCell::new(); - static STACK: StaticCell>> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<2>::new()), - seed, - )); + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); // And now we can use it! diff --git a/examples/nrf5340/Cargo.toml b/examples/nrf5340/Cargo.toml index 56b9c8018..2a4e78b7c 100644 --- a/examples/nrf5340/Cargo.toml +++ b/examples/nrf5340/Cargo.toml @@ -6,12 +6,12 @@ license = "MIT OR Apache-2.0" [dependencies] embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } -embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nrf5340-app-s", "time-driver-rtc1", "gpiote", "unstable-pac"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } +embassy-nrf = { version = "0.2.0", path = "../../embassy-nrf", features = ["defmt", "nrf5340-app-s", "time-driver-rtc1", "gpiote", "unstable-pac"] } embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet"] } -embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } embedded-io-async = { version = "0.6.1" } defmt = "0.3" @@ -21,10 +21,9 @@ static_cell = "2" cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } cortex-m-rt = "0.7.0" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } rand = { version = "0.8.4", default-features = false } embedded-storage = "0.3.1" -usbd-hid = "0.6.0" +usbd-hid = "0.8.1" serde = { version = "1.0.136", default-features = false } [profile.release] diff --git a/examples/nrf5340/src/bin/gpiote_channel.rs b/examples/nrf5340/src/bin/gpiote_channel.rs index c0a55142f..23f6fca98 100644 --- a/examples/nrf5340/src/bin/gpiote_channel.rs +++ b/examples/nrf5340/src/bin/gpiote_channel.rs @@ -61,5 +61,5 @@ async fn main(_spawner: Spawner) { } }; - futures::join!(button1, button2, button3, button4); + embassy_futures::join::join4(button1, button2, button3, button4).await; } diff --git a/examples/nrf9151/ns/.cargo/config.toml b/examples/nrf9151/ns/.cargo/config.toml new file mode 100644 index 000000000..1444b0cd1 --- /dev/null +++ b/examples/nrf9151/ns/.cargo/config.toml @@ -0,0 +1,9 @@ +[target.'cfg(all(target_arch = "arm", target_os = "none"))'] +# replace nRF82840_xxAA with your chip as listed in `probe-rs chip list` +runner = "probe-rs run --chip nRF9160_xxAA" + +[build] +target = "thumbv8m.main-none-eabihf" + +[env] +DEFMT_LOG = "trace" diff --git a/examples/nrf9151/ns/Cargo.toml b/examples/nrf9151/ns/Cargo.toml new file mode 100644 index 000000000..679331716 --- /dev/null +++ b/examples/nrf9151/ns/Cargo.toml @@ -0,0 +1,20 @@ +[package] +edition = "2021" +name = "embassy-nrf9151-non-secure-examples" +version = "0.1.0" +license = "MIT OR Apache-2.0" + +[dependencies] +embassy-executor = { version = "0.6.2", path = "../../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } +embassy-nrf = { version = "0.2.0", path = "../../../embassy-nrf", features = ["defmt", "nrf9120-ns", "time-driver-rtc1", "gpiote", "unstable-pac", "time"] } + +defmt = "0.3" +defmt-rtt = "0.4" + +cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } +cortex-m-rt = "0.7.0" +panic-probe = { version = "0.3", features = ["print-defmt"] } + +[profile.release] +debug = 2 diff --git a/examples/nrf9151/ns/README.md b/examples/nrf9151/ns/README.md new file mode 100644 index 000000000..a3f81d24e --- /dev/null +++ b/examples/nrf9151/ns/README.md @@ -0,0 +1,4 @@ +You must flash the TFM before running any non-secure examples. The TFM +configures the secure and non-secure execution environments and then loads the +non-secure application. A reference TFM is included, and you can use the +provided helper script to flash it. diff --git a/examples/nrf9151/ns/build.rs b/examples/nrf9151/ns/build.rs new file mode 100644 index 000000000..30691aa97 --- /dev/null +++ b/examples/nrf9151/ns/build.rs @@ -0,0 +1,35 @@ +//! This build script copies the `memory.x` file from the crate root into +//! a directory where the linker can always find it at build time. +//! For many projects this is optional, as the linker always searches the +//! project root directory -- wherever `Cargo.toml` is. However, if you +//! are using a workspace or have a more complicated build setup, this +//! build script becomes required. Additionally, by requesting that +//! Cargo re-run the build script whenever `memory.x` is changed, +//! updating `memory.x` ensures a rebuild of the application with the +//! new memory settings. + +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; + +fn main() { + // Put `memory.x` in our output directory and ensure it's + // on the linker search path. + let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); + File::create(out.join("memory.x")) + .unwrap() + .write_all(include_bytes!("memory.x")) + .unwrap(); + println!("cargo:rustc-link-search={}", out.display()); + + // By default, Cargo will re-run a build script whenever + // any file in the project changes. By specifying `memory.x` + // here, we ensure the build script is only re-run when + // `memory.x` is changed. + println!("cargo:rerun-if-changed=memory.x"); + + println!("cargo:rustc-link-arg-bins=--nmagic"); + println!("cargo:rustc-link-arg-bins=-Tlink.x"); + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); +} diff --git a/examples/nrf9151/ns/flash_tfm.sh b/examples/nrf9151/ns/flash_tfm.sh new file mode 100644 index 000000000..29e4e0ed5 --- /dev/null +++ b/examples/nrf9151/ns/flash_tfm.sh @@ -0,0 +1,2 @@ +nrfjprog --family NRF91 --recover +nrfjprog --family NRF91 --chiperase --verify --program tfm.hex diff --git a/examples/nrf9151/ns/memory.x b/examples/nrf9151/ns/memory.x new file mode 100644 index 000000000..8d7b66fcc --- /dev/null +++ b/examples/nrf9151/ns/memory.x @@ -0,0 +1,7 @@ +MEMORY +{ + /* Trusted Firmware-M (TF-M) is flashed at the start */ + FLASH : ORIGIN = 0x00008000, LENGTH = 0xf8000 + RAM (rwx) : ORIGIN = 0x2000C568, LENGTH = 0x33a98 +} + diff --git a/examples/nrf9151/ns/src/bin/blinky.rs b/examples/nrf9151/ns/src/bin/blinky.rs new file mode 100644 index 000000000..7457a95a3 --- /dev/null +++ b/examples/nrf9151/ns/src/bin/blinky.rs @@ -0,0 +1,22 @@ +#![no_std] +#![no_main] + +use embassy_executor::Spawner; +use embassy_nrf::gpio::{Level, Output, OutputDrive}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_nrf::init(Default::default()); + let mut led = Output::new(p.P0_00, Level::Low, OutputDrive::Standard); + + loop { + led.set_high(); + defmt::info!("high"); + Timer::after_millis(500).await; + led.set_low(); + defmt::info!("low"); + Timer::after_millis(1000).await; + } +} diff --git a/examples/nrf9151/ns/src/bin/uart.rs b/examples/nrf9151/ns/src/bin/uart.rs new file mode 100644 index 000000000..2220dccfb --- /dev/null +++ b/examples/nrf9151/ns/src/bin/uart.rs @@ -0,0 +1,37 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_nrf::{bind_interrupts, peripherals, uarte}; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + SPIM0_SPIS0_TWIM0_TWIS0_UARTE0 => uarte::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_nrf::init(Default::default()); + let mut config = uarte::Config::default(); + config.parity = uarte::Parity::EXCLUDED; + config.baudrate = uarte::Baudrate::BAUD115200; + + let mut uart = uarte::Uarte::new(p.SERIAL0, Irqs, p.P0_26, p.P0_27, config); + + info!("uarte initialized!"); + + // Message must be in SRAM + let mut buf = [0; 8]; + buf.copy_from_slice(b"Hello!\r\n"); + + unwrap!(uart.write(&buf).await); + info!("wrote hello in uart!"); + + loop { + info!("reading..."); + unwrap!(uart.read(&mut buf).await); + info!("writing..."); + unwrap!(uart.write(&buf).await); + } +} diff --git a/examples/nrf9151/ns/tfm.hex b/examples/nrf9151/ns/tfm.hex new file mode 100644 index 000000000..9864a1849 --- /dev/null +++ b/examples/nrf9151/ns/tfm.hex @@ -0,0 +1,1543 @@ +:10000000F80B0020690600000D070000255A0000CB +:10001000455A0000655A0000A55A0000855A0000A4 +:100020000000000000000000000000001D2700008C +:100030000D070000000000000D0700000D07000084 +:10004000000000000000000000000000F13200008D +:10005000000000000D07000000000000000000008C +:100060000D0700000D0700000D0700000D07000040 +:10007000000000000D0700000D0700000D07000044 +:100080000D0700000D070000000000000000000048 +:100090000D0700000D070000000000000000000038 +:1000A0000D07000000000000000000000D07000028 +:1000B0000D0700000D0700000D0700000D070000F0 +:1000C0000D0700000D0700000D0700000D070000E0 +:1000D0000D070000000000000D07000000000000F8 +:1000E0000D070000000000000D07000000000000E8 +:1000F0000D070000000000000000000000000000EC +:10010000000000000D0700000000000000000000DB +:1001100000000000000000000000000000000000DF +:10012000000000000D0700000000000000000000BB +:1001300000000000000000000000000000000000BF +:100140000D07000000015F5F00000000FE0B0000D3 +:10015000F9270000800600000000000000000000F9 +:10016000000000000000000000000000401200201D +:100170000000000001015F5F030100001F0100009B +:1001800085040000000000000000000001000000E5 +:10019000010000000000000000000000000000005E +:1001A0000000000070000000CC5E00008000000035 +:1001B000000F000001000000D102000001015F5F9C +:1001C000040100001F010000F30500000000000012 +:1001D000000000000000000001000000000000001E +:1001E000000000000000000000000000D75E0000DA +:1001F000400000000507000001000000DF040000CF +:1002000038B50025054C29462046D4F80024C4F80A +:10021000045405F0B0FCC4F8005438BD200C002094 +:1002200013B511460022CDE9002242680346382A60 +:10023000046844D194F82820022A19D01AB900F091 +:1002400047F902B010BD21482468D0F80404013AEF +:10025000CDE90040082A35D8DFE802F0050A0E1380 +:10026000181D22272C006A46184600F02EF9E8E7F0 +:10027000184600F018F9E4E76A46184600F016F947 +:10028000DFE76A46184600F00BF9DAE76A461846D7 +:1002900000F00FF9D5E76A46184600F00DF9D0E7EF +:1002A0006A46184600F00BF9CBE76A46184600F09C +:1002B00009F9C6E76A46184600F00EF9C1E76FF083 +:1002C0008000BEE76FF08500BBE700BF200C002078 +:1002D0002DE9F04F05680446A1B0002D40F0AA803A +:1002E0002022294602A805F046FC12AF202229460A +:1002F0000AA805F040FC38222946384605F03BFCA8 +:10030000E26904F11C039846B2B10426E26A04F1E2 +:100310002C03EAB10425EEB96FF08306304621B014 +:10032000BDE8F08F002EF1D053F8041D3246013E97 +:100330000029F7D01646E9E70326F5E7002DEAD0B5 +:1003400053F8041D2A46013D0029F7D01546E2E77F +:100350000325F5E738233A460021606805F048FC9C +:100360003828D9D14FF00109CDE90270334F0DF192 +:10037000080A04F1100B4E45D7F800141CD10DF1FA +:1003800028094B46002008EB850EC64533D108B13D +:10039000C7F80014A3683146C7F804340AAA2B46EC +:1003A00002A8FFF73DFF00270646BD4209F10809F4 +:1003B00038D1FFF725FFB1E75BF8043FC1F5806254 +:1003C000D81C20F00300904204D9FFF719FF6FF00A +:1003D0008C06A3E70844CA19C7F8000449466068B8 +:1003E000019205F005FC019ACAF80C0009F1010917 +:1003F0004AF8082FBFE758F804CFC1F5806A0CF11E +:10040000030222F00302524503F1080305D87818CD +:1004100043E9020C11440120B7E70028D5D0C7F802 +:100420000014D2E7394659E90223606805F0F5FB6C +:100430000137BAE76FF0850670E700BF200C002097 +:1004400008B528220021024805F095FB002008BDD0 +:100450002810002010B5044C0F222046034905F057 +:1004600065FB204610BD00BF51100020F6050000BE +:1004700008B50121024803F011FB002008BD00BFB0 +:100480005010002008B5FFF7DBFF40B9FFF7E2FF8F +:10049000FFF7EEFF18B9BDE8084003F06DBB08BDDB +:1004A0006FF0850070476FF0850070476FF0850032 +:1004B00070476FF0850070476FF0850070476FF0F0 +:1004C000850070476FF0850070476FF085007047BA +:1004D000D1E9000103F030BB6FF085007047F0B543 +:1004E00003680546B3F57D7FA7B007D040F2F5322B +:1004F000934207D06FF0850027B0F0BD01F08EFC6D +:100500000020F9E700243C22214607A8CDE9024457 +:10051000CDE90444069405F02EFB3C22214617A8A1 +:10052000169405F028FBEA69019405F11C0302B357 +:100530000426EA6A05F12C033AB30424731E012B46 +:1005400052D8012C50D80423002168680DEB030217 +:1005500005F04EFB04281AD06FF08000CCE7002E87 +:10056000E7D053F8041D3246013E0029F7D0164665 +:10057000DFE70326F5E7002CE0D053F8041D224600 +:10058000013C0029F7D01446D8E70324F5E7022EF2 +:1005900016D16E69402E29D806AF33463A4601215E +:1005A000686805F025FB8642D6D1CDE9027602A91E +:1005B00044B92246019801F01AFE044620469BE702 +:1005C0000021F5E72B6A402BC6D816AACDE90423F3 +:1005D000019804AA01F00BFEDDE904230446002182 +:1005E000686805F01AFBE9E7012085E76FF08900EC +:1005F00082E7002070474D62656420544C532033DD +:100600002E352E3000000000000000000000000029 +:1006100000000000000000000000000000000000DA +:100620005431000001000000407C000080100020D8 +:100630004A000000407C0000200C00200000000068 +:10064000407C0000000C002000000000A8110020E9 +:10065000C4050000200C002018010000000C002040 +:100660000800000002F07ABC08B572B61E4A1F4BA3 +:100670009A601F4B83F309881E4B83F30A8883F328 +:100680000B881D4B16A1D1E90001C3E9000100F060 +:1006900089F81A4B1A498B4212D30020194B1A4978 +:1006A0008B4218D303F06AF8186850F82240586853 +:1006B00040F82240013298688242F5D30C33EAE7D1 +:1006C0000022F8E71C6844F8220001325C68A2426C +:1006D000F8D30833E4E70022F8E700BFAFF3008067 +:1006E000A5EDF5FEA5EDF5FE0000000000ED00E033 +:1006F000F80B002000040020F80B00202806000062 +:100700004C0600004C06000064060000EFF3088071 +:10071000EFF309812DE9F00F6B46724600F038F9CE +:1007200008B0FFF79FFFFEE708B5EFF31083012B3A +:100730000C4A07D1126ABFF34F8F511C4A424A41FB +:10074000104608BD01F0BEFB00B172B6126ABFF3DD +:100750004F8F531C5A425A4101F0B4FB0028EFD08E +:1007600062B6EDE70080FF0008B5EFF31083012BC0 +:100770000B4A06D1D269BFF34F8F02F00102104637 +:1007800008BD01F09FFB00B172B6D269BFF34F8F75 +:1007900002F0010201F096FB0028F0D062B6EEE70D +:1007A0000080FF006F4A10B5D2F8D03043F002034A +:1007B000C2F8D03001F086FB30B14FF05023002258 +:1007C000C3F81421C3F8182101F08BFB28B10122D2 +:1007D000654BC3F8382AC3F878254FF47F02D2F866 +:1007E0003031D2F83421BFF34F8FC3F30B03092B01 +:1007F00005D1012A1EBF01225B4BC3F8782501F009 +:1008000070FB18B10E22594BC3F8E42E01F05AFBCD +:1008100030B10022544BC3F80C270122C3F8102733 +:100820000022D30003F57F03D3F80013BFF34F8FEB +:10083000013108D0D3F800130132D3F80433B2F5F4 +:10084000807F0B60EDD1EFF31084FFF78DFF002860 +:100850004DD0BFF34F8F464BD3F80024012AFBD174 +:10086000C3F80425D3F80024012AFBD1012C03D0BE +:1008700001F028FB00B172B6FFF776FF58B13D4A90 +:10088000D36923F00103D361BFF34F8F384AD2F805 +:100890000034012BFBD1FFF747FF68B1354A136ADB +:1008A00023F0FF0343F020031362BFF34F8F304A5E +:1008B000D2F80034012BFBD1012C03D001F002FB54 +:1008C00000B162B600222A4BC3F80425D3F80024F5 +:1008D000012AFBD1BFF34F8F2249274BCA6802F48C +:1008E000E0621343CB60BFF34F8F00BFFDE7FFF71C +:1008F0001BFF0028ADD11B4AD2F88C3043F4406373 +:10090000C2F88C304FF47F03D3F83021D3F8343160 +:10091000BFF34F8FC2F30B02092A16D1013B022B02 +:1009200002D8164AD35C83B1124815490368104AAD +:100930008B420CBF5A230023C2F8103EC36A8B427D +:100940000CBF5A230023C2F8003E064AD2F8883072 +:1009500043F47003C2F88830BFF34F8FBFF36F8F3B +:1009600010BD00BF00ED00E00040005000A00350AB +:10097000009003500080FF000400FA05C43300001B +:10098000FA50FA507C22014905F0D0B8DC1800205A +:1009900038B51D46374B384C5B68C3F308032360FA +:1009A000EFF30383C4E901206365C2F3801302F00F +:1009B0000C020C2AE16038D10BB9EFF389812022B7 +:1009C0002E48216105F0B2F825B1202229462C4895 +:1009D00005F0ACF8274B9A6AA265D96AE165986B75 +:1009E000206602F400406066586BA06602F080004A +:1009F000E0669A62D962D3F8E4202267D3F8E8105F +:100A0000616702F04001A167C3F8E42000F06AF8D2 +:100A10000E211C4801F077FA2268D31E042B1CD843 +:100A2000DFE803F0090F1215180013B9EFF38881FE +:100A3000C5E70146C3E70C211348BDE8384001F083 +:100A400062BA12211148F8E70B211148F5E70D2190 +:100A50001048F2E70E211048EFE70F2A98BF142143 +:100A6000BDE8384089BF25210C480D48103A01F0F7 +:100A7000F5BB00BF00ED00E0DC180020F0180020FE +:100A800010190020C7330000D5330000E133000007 +:100A9000F3330000FE3300000B3400001934000073 +:100AA0002D3400002DE9F34106460F460C4DD5F8D4 +:100AB0002C80C04710F00104FBD1394630466B69E9 +:100AC000984740B9C047C307FCD42B6A019302B0D2 +:100AD000BDE8F0411847204602B0BDE8F08100BFF4 +:100AE0005434000010B5094C0020A36898472369CE +:100AF00002209847A46A4FF4E1310120A047234621 +:100B0000BDE8104001211520184700BF54340000F3 +:100B100010B5044C002023699847E368BDE81040F5 +:100B2000184700BF54340000064B82B018680023F9 +:100B300082B262F30F03000C60F31F43184602B049 +:100B4000704700BF9C340000014B1869704700BF1C +:100B500084100020014B5869704700BF84100020AA +:100B600038B50C4D0C4695F8203013B94FF0FF30D6 +:100B700038BD0A460146284600F06CFF064B9842F5 +:100B800005D00B3B9842F1D100206C61F0E76FF08B +:100B90000100EDE7841000200B00AD0BF0B51B4EFB +:100BA000054696F820300C4691B01BB94FF0FF3047 +:100BB00011B0F0BD00F06043B3F1005F21D100231C +:100BC0000A460146304600F031FC114B98421AD0DB +:100BD0000B3B9842EAD1346111E0A71B402F28BF9C +:100BE0004027A9193A46684604F0A0FF39466846EE +:100BF000FFF7D4FF0028DBD14036B442EDD8002007 +:100C0000D6E70026F9E76FF00100D1E78410002055 +:100C10000B00AD0BC3B2012B10B540F096804DF622 +:100C2000C023994270D028D8B1F5615F6FD011D838 +:100C3000B1F5965F6DD008D8B1F5966F6BD0B1F570 +:100C4000166F6BD06FF007005DE0B1F5165FF9D15C +:100C5000454B33E047F61223994262D007D8B1F5ED +:100C6000964F61D0B1F5E14FECD1404B26E0B1F5A4 +:100C7000164FE7D14FF41D0320E03D4B994255D06C +:100C800011D8B1F5E13F54D007D8B1F5614F53D039 +:100C9000B1F5963FD6D1374B10E0B1F5613FD1D1D8 +:100CA0004FF06C730AE0B1F5612F48D0324B994296 +:100CB00048D0B1F5E12FC5D14FF0E86310F4E06FF3 +:100CC00046D110F4404103D0B1F5804F43D11021FB +:100CD00010F4405203D0B2F5805F3FD10E2210F4E1 +:100CE000403003D0B0F5403F3BD10120234C20766B +:100CF0006276E361A1760A4324681043C4F8243580 +:100D0000C4F86C05002010BD4FF46503D6E71C4BFA +:100D1000D4E71C4BD2E74FF49E23CFE74FF41D23BB +:100D2000CCE74FF40003C9E7174BC7E74FF08063E8 +:100D3000C4E74FF0EB73C1E74FF46B03BEE74FF02E +:100D40007063BBE74FF08053B8E76FF00300DAE75A +:100D50006FF00800D7E76FF00A00D4E76FF00900E2 +:100D6000D1E76FF00B00CEE70050270000C0750000 +:100D700090D0030000903A0140420F008410002000 +:100D800000F03A0000B0130000A04E0010B5114C66 +:100D9000204600F0D5FD0021206884F8201000F0E6 +:100DA00047FF226842F30732002A11DB0121530971 +:100DB0009B0003F1604303F56143D3F8800202F026 +:100DC0001F0201FA02F20243C3F88022D3F88032F4 +:100DD000002010BD8410002010B5264C0021206892 +:100DE0008EB000F017FF226842F30732002A12DBB0 +:100DF000012053099B0003F1604303F56143D3F8DD +:100E0000801202F01F0200FA02F221EA0202C3F885 +:100E10008022D3F880322422002105A804F0ABFE02 +:100E2000D4E902124FF0FF33CDE90133CDE90333AA +:100E30004FF0EB730B93072301A88DF8363001F0C8 +:100E400080F8014600220B4800F03AFA0A4B98421B +:100E50000DD10C9B002023831B0CA3760B9BC4E9B4 +:100E60000400E361012384F820300EB010BD6FF060 +:100E70000100FAE7841000200000AD0B7FB50025CB +:100E80000C46C0F808511646D0F80821D0F80022C8 +:100E900022F02002C0F80022104AC0F8082301F016 +:100EA000A0F8A560256104F14C03D3E8EF1F21F4FD +:100EB0007F0121F47041C3E8E21F002AF5D110221E +:100EC0002946684604F057FE042368468DF8003032 +:100ED0000196D4E90013984704B070BD10020A00CF +:100EE00000F01F03400909D1074A02EB8303D3F83E +:100EF0000012064A0A40C3F80022704700228033DD +:100F000052F82330FFDE00BF00258450F0F8FCFFCC +:100F10002DE9F04F804690F804A05020664F0E4611 +:100F200000FB0A70416885B049B113F0020304D098 +:100F3000836B002B00F0B2800123009300E000914E +:100F40004FF0500909FB0A73DB6CD90600F1A6804B +:100F50004FF0010BB3180293029BB34200F0A7803D +:100F600006F06043039398F80450D8F8004009FB5A +:100F700005739A6B9AB9039BB3F1005F40F09980B7 +:100F8000019200F0A1FD09FB0572D16C204601F031 +:100F9000010100F0F4FF28B900F09EFDE3E7012312 +:100FA0000193EEE7516C33460029BCBFD4F84C15D1 +:100FB0005164019A42B109FB05713078D1E90E23E1 +:100FC000D054D1E90E3213441BB1C4F84435C4F8EF +:100FD00048B50022C4F82021D4F82011C4F85821C3 +:100FE000D4F85811C4F85021D4F850210822C4F87C +:100FF0000025009AE2B14FF48003C4F80433C4F82A +:1010000008B000F069FD502303FB0A725168002903 +:101010004BD1D26C120748D503FB0A734C33D3E88B +:10102000EF1F21F00801C3E8E21F002A36D0F6E7DF +:10103000C4F808B0019300F04FFD09FB0572D16CB4 +:10104000019B01F001012046019300F098FF8446C6 +:10105000019BD4F84C05D4F84425BCF1000F0DD108 +:101060009342F0D005EB850507EB0515D1B100F0F3 +:101070002BFD2946204600F0F9FFC2E705EB850568 +:10108000934207EB0515F1D10028EFD100F01CFDCC +:101090002946204600F0EAFF00F01EFD074805B093 +:1010A000BDE8F08FC4F80CB0E1E7013654E704481E +:1010B000F5E70448F3E700BF581900200800AD0B1E +:1010C0000000AD0B0400AD0B430904D10123034A1A +:1010D00083409360704700239B60FFDE00258450AF +:1010E00000F01F0340090BD1084A02EB8302D2F83B +:1010F0000012074B0B4043F00303C2F80032704765 +:101100000022803352F82330FFDE00BF00258450D8 +:10111000F0F8FCFF2DE9F84391F8303005460C4615 +:1011200090F804800F6853BB5023DFF85091781C6F +:1011300003FB0893DE6C46F00072DA6404D0384694 +:10114000FFF7C2FFFFF7CCFF6068411C01D0FFF73B +:10115000C7FE94F82C30012B11D1502303FB0893C8 +:10116000E06846F02066421CDE6401D0FFF7B8FE5E +:10117000A068431C03D0FFF7A7FFFFF7B1FF94F867 +:101180002F0038B950223D4B02FB0833DA6C42F095 +:101190008072DA6494F82CC094F82D1094F82EE044 +:1011A000A26A2B6841EA0C01E668D4E90198C3F809 +:1011B00024254EEA0102C3F86C2550B9BCF1010F99 +:1011C000C3F80C75C3F8149504BFC3F80885C3F8B9 +:1011D0001065D3F8682503F26458012A08BFDA6065 +:1011E000D3F86425012A13D1082149F64046244F3B +:1011F000C3F8001547F001075A60D8F800309BBBD0 +:101200002B68D3F88024C3F880240022C3F800257B +:1012100000212B6894F83220C3F81011D3F8100184 +:10122000C3F82011D3F82001C3F82411D3F8240106 +:10123000C3F84411D3F84401C3F85811D3F8581136 +:1012400043F307335201002BD2B212DB0D49C81809 +:1012500080F800230122580903F01F0302FA03F368 +:1012600041F82030BDE8F8834020B847013EC4D1A2 +:10127000C6E7054903F00F03CA54F3E758190020E5 +:10128000A034000000E100E014ED00E000F01F03D6 +:1012900040090BD1084A02EB8302D2F80012074B37 +:1012A0000B4043F00203C2F8003270470022803343 +:1012B00052F82330FFDE00BF00258450F0F8FCFF19 +:1012C0002DE9F3479046502290F80490514C02FBD0 +:1012D00009FA04EB0A070D4697F84810064600295C +:1012E00040F0858009EB890004EB001004F043FC1A +:1012F0002B69AA6944F80A306B69BB6302B1013AF1 +:10130000502303FB0943DA632A6A042A81BFEA698E +:101310009A610022DA6195F83130B8F1000F37D0C8 +:1013200083F001073F0233B1502303FB0943DA6C1A +:1013300042F00102DA64502303FB09440123C4F89C +:10134000048084F848303468D4F84C2112BB294614 +:101350003046FFF7DFFE0822002334688DF807309F +:10136000C4F800250DF10702C4F84425C4F8483537 +:1013700001230A25A360E360D4F85831002B38D14B +:10138000254B402043F001039847013DF4D128E06C +:101390004746C8E708224FF06409C4F80025636097 +:1013A0001D4B43F0010AD4F84431F3B9D4F8243189 +:1013B000DBB94FF42070D047B9F10109F3D14B46A6 +:1013C0000022C4F84C21D4F84C11C4F81021D4F8F0 +:1013D0001011C4F84421D4F84411C4F80025002B9E +:1013E000B5D10E4802B0BDE8F0870123E8E70C480C +:1013F000F8E70023C4F820319845D4F82021C4F838 +:101400000035084B08BF00231F4333680648C3F864 +:101410000473E7E758190020A03400000100AD0B69 +:101420000C00AD0B10020A000000AD0B2DE9F047D7 +:1014300084460F469E4616460579002A51D04FF045 +:10144000500ADFF8BC80D0F800900AFB058ADAF871 +:10145000044074B96BB9DAF82C50002D43D1CAF8A6 +:101460002C20FFF755FD0446CAF82C502046BDE855 +:10147000F0871EF0030F07D0734632463946BDE8A9 +:10148000F0476046FFF744BD07F06043B3F1005FEB +:101490004FF0500414D104FB058400F015FBE26A00 +:1014A0001AB1134C00F018FBE0E7C4E90A7605EB2B +:1014B0008505484608EB051100F0E3FD0D4CF1E70A +:1014C00004FB0584A36B83B100F0FEFAE36A002BF2 +:1014D000E7D1E36C012243F00203C4E90A76E36436 +:1014E000E5E7054CC2E7024CC0E7044CBEE700BF8D +:1014F0000B00AD0B0000AD0B0600AD0B0A00AD0BF1 +:10150000581900202DE9F84350230679284D046826 +:1015100003FB0653D4F80473DA6AC4F8087322B9DB +:101520002448C4F80473BDE8F88306EB860005F18F +:101530004C024FEA001802EB0012D2E8EFCF4CF059 +:10154000080CC2E8E0CF0028F7D10122E26031B3F5 +:10155000D96C01EA02094946204600F010FD002836 +:10156000FAD000F0B1FAB9F1000F1CD1D4F8203153 +:1015700053B10123E360D4F85831002BFBD020464F +:1015800005EB080100F072FD00F0A6FA0023C4F894 +:101590002031D4F82021502202FB0655EB62064888 +:1015A000C4F80473BFE7D4F85831002BE7D1EBE758 +:1015B000581900200500AD0B0000AD0B2DE9F843D4 +:1015C00090F80480484F08EB8806360106F14C0578 +:1015D00004683D44D5E8EF3F43F48052C5E8E02F6E +:1015E0000028F7D1DB047BD4480705D5502303FB43 +:1015F00008739B69002B75D03C4B3E44C4F80833FC +:101600000823C4F800350023C4F81031D4F81021A1 +:10161000C4F84C31D4F84C21C4F844310A03D4F84E +:1016200044318B0303F4804302F400524903134313 +:1016300001F400410B43D5E8EF2F1A43C5E8E12F31 +:101640000029F8D14FF0500909FB0879D9F8083082 +:10165000BBB9D9F8043063B9D5E8EF3F23F47F0371 +:1016600023F47043C5E8E23F002AF5D12048BDE8E5 +:10167000F8830321304600F08FFCD9F80830002BA6 +:10168000EAD0D4F80433590713D5502303FB087369 +:101690005A6872B1DB6C1A030BD5D5E8EF3F23F41F +:1016A0000023C5E8E23F002AF7D10621304600F0CA +:1016B00073FC502303FB0873DB6CDB0401D40D487F +:1016C000D5E7D4F84C310BB901232360502303FB39 +:1016D00008735B68002BF2D0044BC4F80433EEE7C8 +:1016E0000548C4E70548C2E75819002010020A005F +:1016F0000200AD0B0000AD0B0B00AD0B0800AD0BF5 +:101700002DE9F84F056801F06043D5F804A3B3F163 +:10171000005F90F804B089461746C5F808A37CD14D +:101720005023404E03FB0B639A6852B15B68002B59 +:101730005ED1D5F81021002A5AD0C5F81031D5F85D +:101740001031502404FB0B64E269C4E90297002ABB +:101750003CD00BEB8B0897424FEA081824D24FF08D +:10176000000B3A46A1694846C4E902BB04F0DEF921 +:10177000E269A069D21BC119E26104F0A1F96368B2 +:101780006BB1B04449463A46404600F016FCE36C63 +:10179000990404D55A4641462846FFF76FFB224874 +:1017A000C5F804A3BDE8F88F4846A16904F0BEF966 +:1017B000E36963620023E3611C4B9844D8E8EF3F80 +:1017C00043F40023C8E8E23F002AF7D1502303FB8B +:1017D0000B63586ADA689968DB6C121A0144C5F821 +:1017E0003415C5F83825DA04D9D501232B60D6E79E +:1017F000502303FB0B6633698BB9F36CC5F8349542 +:101800005B04C6E90497C5F83875C8D5D5F8003229 +:1018100043F02003C5F80032C1E70548C0E705489A +:10182000BEE700BF581900200000AD0BA41900202E +:101830000A00AD0B0B00AD0B50232DE9F0413C4DE0 +:1018400090F80480046803FB0853DB6CD4F80002B2 +:1018500003F48223B3F5805F68D1D4F80463C4F83D +:10186000086309B9830656D4D4F8003223F0200364 +:10187000C4F800324FF4842308EB8801090101F118 +:101880004C072F44D7E8EF0F1843C7E8EC0FBCF123 +:10189000000FF7D12AB9502303FB08535B68002BD4 +:1018A00041D1244BC4F8083301236360D4F8443198 +:1018B000002BFBD00023C4F84C31D4F84C21C4F8E1 +:1018C0001031D4F81021C4F84431D4F844315023F5 +:1018D00003FB0853DA6C12F400421FD1DA61204690 +:1018E00000F07FFB502303FB08550023AB602B6106 +:1018F000D7E8EF3F23F47F0323F47043C7E8E23FC8 +:10190000002AF5D126F4202626F404760A48C4F8E5 +:101910000463BDE8F0814FF48033ADE720462944ED +:1019200000F071FBDBE701236360EFE70348F0E7BA +:101930005819002010020A000000AD0B0500AD0B85 +:101940002DE9F8432F4A03680679C3F8082343F3C7 +:101950000733002B04460DDB01215A0903F01F0356 +:10196000994002F12003284A42F82310BFF34F8F19 +:10197000BFF36F8F012220461146FFF75DFF012163 +:101980002046FFF7BFFD50212279204D236801FB3F +:101990000252D46CD3F80C05E201D3F81495D3F8B5 +:1019A0000875D3F8108509D54FF0FF32C3F80C2520 +:1019B000C3F81425C3F80825C3F81025A30116D5CC +:1019C000411C01D0FFF762FCB9F1FF3F02D048464D +:1019D000FFF75CFC22010AD5B8F1FF3F02D0404678 +:1019E000FFF754FC7B1C02D03846FFF74FFC502316 +:1019F000002203FB0653DA6483F848205A60BDE8EE +:101A0000F88300BF10034A0000E100E058190020ED +:101A100010B5502402790B4B04FB02335B686BB9A1 +:101A20000368D3F810211AB9D3F80025082A07D083 +:101A300011B1D3F83C350B60034810BD0348FCE7F7 +:101A40000348FAE7581900200000AD0B0800AD0B61 +:101A50000B00AD0BF7B505461646FFF751FE164BCA +:101A60000446984222D1032128462F79FFF7A6FD8C +:101A7000124B984201D0A0421BD15022104B02FBC6 +:101A800007335B6893B90C4C284601A9FFF7C0FFE8 +:101A9000A042F9D1019BB34207D301222846114647 +:101AA00003B0BDE8F040FFF7C7BE064C204603B0C8 +:101AB000F0BD0446FAE700BF0000AD0B0B00AD0B14 +:101AC000581900200800AD0B72B6024A13680133A2 +:101AD00013607047A8190020034A1368013B136084 +:101AE00003B962B6704700BFA81900200722024B55 +:101AF000C3F80423704700BF00300050084BD3F8F0 +:101B00000801D3F80021003818BF012080000AB175 +:101B100040F00100D3F804310BB140F002007047EF +:101B2000003000500022074BC3F80021D3F8001109 +:101B3000C3F80421D3F80411C3F80821D3F80831FD +:101B4000704700BF0030005000231720094A03F5FA +:101B5000C0710133202B42F82100F8D10023172057 +:101B6000044A03F5E0710133202B42F82100F8D13B +:101B7000704700BF0030005010B59DF80840C00B02 +:101B800043EA0423064CC90B43EA0213884200D9F6 +:101B900010BDC2B202F5C07244F822300130F5E740 +:101BA0000030005010B59DF8084000F1604043EA55 +:101BB000042301F16041074C400B490B43EA021337 +:101BC000884200D910BDC2B202F5E07244F822305A +:101BD0000130F5E700300050C0F30E03C3F50043B9 +:101BE000B3FA83F3C3F11B03064AC0F3C730DBB279 +:101BF00040F4807043F48073C2F80005C2F80435E5 +:101C0000704700BF0030005043030148184470473C +:101C1000FF1FF81F054BC0F30730090241F03001E8 +:101C200000F5007043F82010704700BF00300050EE +:101C3000044BC0F30730090200F5007043F8201090 +:101C4000704700BF00300050003A18BF0122003931 +:101C500018BF012103688900074841EA420118635F +:101C600059605A6842F001025A60BFF34F8FBFF3C8 +:101C70006F8F0020704700BF04AAFF0008B5FFF770 +:101C80003DFF044B162118600348BDE8084000F0F2 +:101C90003AB900BFEC1F0020A63400000C22014915 +:101CA00003F044BFEC1F002010B501F006FB044612 +:101CB00090B901F097FF044680B90A4A2E21D368F3 +:101CC000094823F008031B041B0C43F0BF6343F4D3 +:101CD0000033D36000F017F9204610BD45F22354BD +:101CE000FAE700BF00ED00E0BC340000024B1860D2 +:101CF000024B002019607047FC1F0020F81F0020D5 +:101D00001FB5374C426923685A6282699A62C26978 +:101D1000DA62026A1A63426A5A63826A9A63C26A20 +:101D2000DA63026B1A64426B5A60826B9A60C26B10 +:101D3000DA60026C1A61426C5A61826C9A61C26C00 +:101D4000DA61026D1A62826D5A65C26D9A65026F20 +:101D5000DA65026E1A66826E5A66426F9A66EFF311 +:101D600088825A64EFF389829A644268DA64EFF3F6 +:101D700094821A65026801A81A67FFF78FFF23682B +:101D8000019ADA6601221A70164B1C686408640016 +:101D90002046214622462346B7EE000AF7EE000A07 +:101DA000B7EE001AF7EE001AB7EE002AF7EE002A97 +:101DB000B7EE003AF7EE003AB7EE004AF7EE004A07 +:101DC000B7EE005AF7EE005AB7EE006AF7EE006A77 +:101DD000B7EE007AF7EE007A03F081FF04B010BD91 +:101DE000FC1F0020F81F002000B5A1B001A8FEF7DD +:101DF000C9FD029B63B15B060AD4019B23F0020379 +:101E0000052B05D1044B1B6813B101A8FFF778FF20 +:101E100021B05DF804FB00BFF81F0020BFF34F8F17 +:101E20000549064BCA6802F4E0621343CB60BFF376 +:101E30004F8F00BFFDE700BF00ED00E00400FA0592 +:101E400038B543680C2B30D14B68042B2DD14FF0A3 +:101E5000FF3304680D6821682B6031B3A26822B398 +:101E60000623012001F081F9F8B96168104B99420D +:101E70000DD9A2680F485318834202D9F43883421F +:101E800010D8206803F052FE0020286038BD0A4BAD +:101E900099420AD9A26809488B188342F1D90730C0 +:101EA000814202D906488342EBD90220EEE700BF07 +:101EB000FF01FF002C02FF002F01FF003801FF008F +:101EC0004C01FF004FF47F03D3F83001D3F83431D5 +:101ED000BFF34F8FC0F30B00A0F1090358425841E4 +:101EE00070474FF47F02D2F83031D2F83401BFF39B +:101EF0004F8FC3F30B03092B03D1431E58425841A4 +:101F0000704700207047FEF7CDBD012070476FF08D +:101F100003007047002382B00193019802B070471C +:101F20006FF003007047002382B00193019802B064 +:101F30007047022814BF6FF0030000207047FEF7BF +:101F40002DBE30B501EB8202914200D130BD51F877 +:101F5000044B04F07F037F2B4FEA144408BF4FF07B +:101F6000FF33032CF0D8DFE804F002040608036016 +:101F7000EAE74360E8E78360E6E7C360E4E7034637 +:101F8000D0F8580130B931B9D3F82001003818BF62 +:101F9000012070470120704730B504460D4685B0DA +:101FA00010220021684603F0E6FDD4E900136846DC +:101FB0008DF80050984705B030BD7FB504460E46F9 +:101FC000154600211022684603F0D5FD012368461E +:101FD0008DF80030CDE90165D4E90013984704B0CD +:101FE00070BD10B50446FFF76FFDD4F8583133B11A +:101FF000D4F8043313F4800308BFC4F80035BDE8F7 +:102000001040FFF769BD70B50D4604460522AA21B0 +:10201000D0F83C65A86903F0AEFD0522AB69C4F8B1 +:102020003435C4F838250022C4F81021D4F8101132 +:102030000121E162D4F810110029FBD0C4F84C2131 +:10204000D4F84C11C4F81021D4F81021D4F83C2550 +:102050009642EA6109D15A1E043312F8011FAA29D7 +:1020600003D19A42F9D10023EB6170BDD0F8583109 +:1020700033B1CB6CC3F30032DB0458BFC0F800258A +:10208000704770B5CE6C0D4606F001010446FFF7AF +:1020900076FF38B94FF4800346F00406EE64C4F8C6 +:1020A000043370BDD5E90A365AB1296CEA6B761A49 +:1020B000964228BF164619443246A86B03F036FDF7 +:1020C000AB6B4FF0FF326A641BB1C4F84435C4F8FF +:1020D00048650023C4F82031D4F82021C4F85831D1 +:1020E000D4F85821C4F85031D4F850310823C4F83A +:1020F00000354FF48003C4F804330123A360D0E714 +:10210000C0037047C00300F5FF407F3070470020D8 +:1021100070471F2070474FF40040704700F57F4024 +:10212000C03040037047402070475F2070474FF435 +:10213000005070474B6830B513F01F052DD1026871 +:102140000C681068C0F30720844226D2506855609E +:1021500094600C7C23F01F0304F001041C438B7C6F +:10216000DB0003F018031C434B7C5B0003F0060309 +:102170002343D3608B68013B23F01F04CB685B00D3 +:1021800003F00E03234343F0010313615060BFF3D8 +:102190004F8FBFF36F8F284630BD0120FCE70368E7 +:1021A00000205A68C9B258609960D86018615A60B6 +:1021B000704770B50546002403681E68C6F30726FD +:1021C000B44201D1002070BD21462846FFF7E7FF49 +:1021D0000134F5E70020704708B5FFF705FE72B639 +:1021E00020BFFDE7002070470020704770470B4676 +:1021F00070B5114618B1032806D0032070BD1846EB +:10220000BDE87040FFF71CBE5A68082A01D00220C2 +:10221000F4E74C68042CFAD11D684FF0FF330E68C8 +:10222000296833600029F2D06B68002BEFD0262399 +:102230007422012000F099FF0028E8D122462323D0 +:102240000120696800F091FF04460028DFD1D5E93C +:102250000001FFF74BFD30602046CFE730B50C465C +:10226000154685B038B139B1FFF74DFE041E03DACB +:10227000204605B030BD044640F60D23ADF80E30C3 +:1022800009230B4901A805F00F028A5C2D091A5495 +:10229000013B012BF7D147F630030C21ADF8043098 +:1022A000FFF731FE0028B4BF04462418E0E700BF62 +:1022B000EA34000008B5194B83F30A88184800F087 +:1022C000E7FF40BBFFF7F0FC28BBFFF783FF10BB25 +:1022D000FFF788FFD8B9FFF789FF00F067FA3521CB +:1022E0001048FFF710FE17210F48FFF70CFE1821CA +:1022F0000E48FFF708FE00F03FFC21210C48FFF7D5 +:1023000002FE00F03FFA00F0CDFE002008BDFFF70E +:102310006BFF0028DFD000F021FEEEE70004002074 +:10232000AC190020FA3400002F35000046350000BB +:102330005E3500002DE9F04F93B00093574B814676 +:10234000D3F800B00BB2002B0D461646C1F302685D +:10235000C1F3024A04DA6FF0800013B0BDE8F08FD9 +:102360008B42C36001D10020F7E708EB0A03042B7E +:10237000F1D8CC0F64014FEAC80731463A46DBF882 +:10238000080044F0020300F0F0FE01460028E2D10C +:10239000202202A803F0EFFB3A46314602A84FEA9A +:1023A000CA0603F0C3FB32460099DBF8080044F08C +:1023B000060300F0DAFE07460028CCD101462022B1 +:1023C0000AA803F0D8FB324600990AA802AE03F02F +:1023D000ADFB33460137B84514D91A46BC460DE06B +:1023E000D2F808E0D16818687144884203D259686D +:1023F00008448645AFD30CF1010C0832C445EFD137 +:102400000833E7E715F0006F18BF202409F118071B +:1024100007EB880844F00203474513D1202C26D14E +:10242000002D02DBC5F3C0456C0109F128050AAE99 +:1024300005EB8A0A44F0060455451AD1009BC9F8F9 +:102440007C3090E77268DBF8080056F8081B0193AF +:1024500000F08BFE00287FF47EAF56F8042C019B21 +:1024600047F8042F56F8082C38633A62D4E7002462 +:10247000DBE77268234656F8081BDBF8080000F01B +:1024800074FE00287FF467AF56F8043C45F8043F1B +:1024900056F8083C28642B63CEE700BFB019002033 +:1024A0002DE9F0411F461A4B0D461646D3F8008021 +:1024B00000F051FF044608B900F050FDE368002B1E +:1024C00001DA00F04BFD032D01D900F047FD04EBCC +:1024D0008504E569E36CED1A16D006233A463146C9 +:1024E000D8F8080000F041FE08B100F037FDBD4209 +:1024F00028BF3D46E36CE16B2A461944304603F0A1 +:1025000015FBE36C2B44E3642846BDE8F08100BF73 +:10251000B01900202DE9F0411D461A4B0F46164612 +:10252000D3F8008000F017FF044608B900F016FD4C +:10253000E368002B01DA00F011FD032F01D900F050 +:102540000DFD04EB8704E36AE26E9B1AAB4201D2F5 +:1025500000F004FD02232A463146D8F8080000F0B6 +:1025600004FE08B100F0FAFCE36EE06D2A46314645 +:10257000184403F0DBFAE36E00202B44E366BDE869 +:10258000F08100BFB01900202DE9F04105464FF061 +:1025900001080E4E0E4B37685C681CB92846376040 +:1025A000BDE8F0812268936813F400700CD1A36930 +:1025B000012B09D0D368346023B19847002801DA91 +:1025C00000F0CCFCC4F81880246AE6E7B0190020BB +:1025D000B419002038B5044610B96FF0800038BD3A +:1025E0008368002BF9D01A68002AF6D05D68002DA8 +:1025F000F3D00B4BE861A8691D6020B92B68DB683C +:1026000053B90123AB61A36804F10C001B681B697B +:10261000984701232360E2E798470028F1DADCE7D6 +:10262000B01900204268024B08461A60704700BF8C +:10263000B0190020002330B505680446AA68C0E937 +:10264000063312F4406F85B01CD012F4006202D041 +:1026500000F0C2F90246A96A2B6968460B440731AB +:1026600023F0070321F00701CDE9021300930023B3 +:1026700005490193EB6800F09FFA684600F04EFEB2 +:10268000024B1C6005B030BD89250000B019002048 +:1026900001F00C0370B50C2B0CBF154605464A061D +:1026A0000C461ED58B0658BF2835AB6913F8026C53 +:1026B00084F00803C3F3C003C6F38012934201D031 +:1026C00000F04CFC16F0A00F1ED176B1032E17D0EF +:1026D00032461C210E48FFF7C1FD6FF083032B60CB +:1026E0000CE000F03BFC2026E2E700F03BFB044658 +:1026F000FEF70EFA2146074800F00AFE204670BD9C +:10270000284600F03FFAF9E732461F210248E2E787 +:102710007F350000F80B00209B350000EFF30880A8 +:102720007146EFF30982EFF30B830CB406B4FFF7A5 +:10273000AFFF8646009900F0080001F00801401A3A +:1027400002DC12DB04B070471EF020031CBF2DE931 +:10275000F00FBDF1080D0A4C254626462746A04637 +:10276000A146A246A34630B4704704B030BC1EF068 +:1027700020031CBF1DF1080DBDE8F00F04B0704729 +:10278000A5EDF5FE084BDA6882F07F4282F47F0205 +:1027900042F48042DA6000221A765A76DA76DA77E4 +:1027A000602283F82220704700ED00E0114BD3F83F +:1027B000882042F47002C3F88820BFF34F8FBFF324 +:1027C0006F8FD3F88C2042F44062C3F88C20D3F88A +:1027D000342242F08042C3F83422D3F8342242F04B +:1027E0003C42C3F834224FF0E022D36843F4200384 +:1027F000D360704700ED00E0009A164B9A4227D153 +:1028000001229043014641EC100B41EC110B41ECCD +:10281000120B41EC130B41EC140B41EC150B41EC8A +:10282000160B41EC170BEFF3148222F0040282F333 +:102830001488BFF36F8F02460346044605460646DA +:10284000074680468146824683468446864604473C +:10285000FEE70000A5EDF5FE2DE9F041044618B9AC +:1028600043F6DA30BDE8F0810029F9D0836800250D +:1028700013F4406F14BF01230023134F43F00203EE +:10288000DFF848800B6000F13006236AAB4201D8C4 +:102890000020E7E71421A369E26906EB830301FB4B +:1028A00002330C226A4399188968090709D59B5895 +:1028B000BB4201D04345D3D1186810B10121FFF7C5 +:1028C000A9F90135E1E700BFB4100020AC100020E9 +:1028D00070B5324C86B03248FFF76BFC2368012597 +:1028E0005A1C01932F4B2260DA681B694FF4407623 +:1028F000039300232A4801A902920495ADF81460BD +:102900008DF81630FFF716FC18B143F6DA3006B032 +:1029100070BD23688DF816005A1C0193224B204885 +:102920000293224B01A9CDE903352260ADF8146072 +:10293000FFF700FC0028E8D123688DF816005A1C28 +:1029400001931B4B164802931A4B01A9CDE903359D +:102950002260ADF81460FFF7EDFB0028D5D12368A5 +:102960008DF816005A1C0193134B0D480293134B1C +:1029700001A903930223049340F201132260ADF8EE +:102980001430FFF7D7FB04460028BED12A4629465B +:102990000348FFF759F92046B9E700BFBC190020EA +:1029A000A81000202C36000060360000005F0000F8 +:1029B0002006000020060000000C0020200C002053 +:1029C000014B1868704700BF2C360000014B1B6894 +:1029D000186870472C360000014B1B685868704718 +:1029E0002C36000008B5FFF749F9FFF79BF80A4BB2 +:1029F0005A68103AD3B2120609D401215A0903F0D9 +:102A00001F03994002F16003044A42F82310BDE815 +:102A1000084000F0A3BA00BF00ED00E000E100E0D4 +:102A20000020034BD8765A6A42F470225A627047EB +:102A300000ED00E00349044BCA68002092B2134342 +:102A4000CB60704700ED00E00800FA0500224FF06F +:102A5000FF300D4B02F1A0010132102A43F8210092 +:102A6000F8D1D3F88022002022F00802C3F8802297 +:102A7000D3F88022D3F8802222F40072C3F8802297 +:102A8000D3F88032704700BF00E100E008B5FFF7DF +:102A90002DF80822024BC3F880211A60002008BDDF +:102AA00000E100E0064BD3F8D02022F00102C3F889 +:102AB000D020D3F8D02042F00202C3F8D0207047D3 +:102AC00000ED00E037B50124FFF73EF8134D224634 +:102AD000052347F6FF7100200094FFF74DF82246CA +:102AE00007234FF000500E490094FFF75BF8D5E93B +:102AF0000101072300220094FFF73EF8072300227C +:102B0000084909480094FFF74DF82969E868013938 +:102B1000FFF762F8002003B030BD00BF2C36000084 +:102B2000FF7F0020FFFF03200080002038B5002435 +:102B30000E4D002155F8040B0134FFF779F81C2CD9 +:102B4000F7D10020012240F20111094BC3F88004A3 +:102B5000C3F88424C3F8C004C3F8C424054AC2F8E7 +:102B600040154FF48072C3F8402438BDBC350000D6 +:102B700000300050009003500122014B1A60704752 +:102B8000C019002010B50446094B228918686168F5 +:102B90000623806800F0E9FA28B9064B1B68012B70 +:102BA00001D100F087F86FF08603236010BD00BFED +:102BB000B0190020C01900202DE9F84305461E4633 +:102BC0000068134B9046AA68A0F1080440E902335C +:102BD000503890420F4601D200F0C0F9A4F14809E4 +:102BE00048220021484602F0C6FF002344E907338B +:102BF00044F8143C4FF0807344F8043C6FF0020337 +:102C000044E9036744F8208CC5E90093BDE8F883E4 +:102C1000A5EDF5FE30B5094C024661680023084673 +:102C200040B105686D68954205D11BB1826860604E +:102C30009A60816030BD03468068F1E7441A002045 +:102C400038B504462AB10B689B68DB0512D5002015 +:102C500038BD0B4B1D680DB900F080F900222B68C0 +:102C600099692C338A4203D053F8040FA04204D14F +:102C70009142ECD16FF0FC00EAE70132F2E700BFCD +:102C8000B019002070B504460E46154600213022CA +:102C90000C3002F070FF064B20461B68A660636094 +:102CA000656100F001FA00232061236070BD00BF60 +:102CB000B0190020044B1B681BB11B680BB158688E +:102CC00070474FF0FF307047B0190020064B10B529 +:102CD0001C680CB900F042F923689B6813F4406F3C +:102CE00014BF0120002010BDB01900202DE9F843C9 +:102CF000904607460C46FFF7E9FF024624B96FF0FD +:102D000080042046BDE8F8836300F8D5144B04F036 +:102D10001F0153F82150002DF1D02B682946586827 +:102D2000FFF78EFFB0B9C4F30721284600F001FB7E +:102D300004460028E3D1EFF3108972B600F0C1F920 +:102D4000064689F3108840B142462946FFF79AFFAC +:102D50003E60D6E76FF08104D3E76FF08204D0E7DE +:102D6000C41900202DE9F04100F0AAF90023134E08 +:102D7000134F73607B6000F0E5F8DFF84880304661 +:102D800000F022F80446A8B139468023424600F0FC +:102D90007FF80546204600F011FB206804F1080189 +:102DA000FFF75AFD08B100F0D9F829462046FFF791 +:102DB00041FCE4E7BDE8F04100F071B9B41900202E +:102DC000441A0020C4190020F8B5054608B900F0DF +:102DD000C5F82A4E346814F1290F4CD8284B1968CD +:102DE00004F128038B4246D2236AA26903EB430312 +:102DF0000C321344606AE269024402EB820213441B +:102E00009B00E31801D2994201D200F0A7F8236891 +:102E10001C4A1B0C1B04934201D000F09FF823882E +:102E2000B3F5817F01D300F099F86368002B01DAD4 +:102E300000F094F8144A176807F124031360134A4A +:102E40001268934201D900F089F8236AA26903EB62 +:102E500043030C32616A1344E2693C600A4402EBAA +:102E600082021344326802EB83026B6832603B6279 +:102E70006F603846F8BD0027FBE700BFC410002094 +:102E80004836000000005F5FC0100020443600009C +:102E90002DE9F74F0F4690460646009300B109B959 +:102EA00000F05CF8D6F800A0DAF818200AF1300338 +:102EB00003EB820BDAF81C40204B1D6854B10C2246 +:102EC00002FB04541C601E4B1B689C4201D900F09D +:102ED00045F82C4625464FF00009DAF81C204A45F3 +:102EE00000D91CB9002003B0BDE8F08F142303FB08 +:102EF00009B20023C5E900269268AB60930516D598 +:102F0000B8F1000F02D0009B802B03D0019200F09B +:102F100025F8019A12F0E00FD0B202D158F8202023 +:102F20001AB1019000F01AF8019848F820507A6818 +:102F300009F10109AA607D600C35CEE7BC100020C4 +:102F40004036000008B5FFF73BFD034B9860FFF7E4 +:102F50003DFD80F3888808BD00ED02E0FFF73CB935 +:102F60008230012808B506D8FFF7B0FE18B9BDE8D1 +:102F70000840FFF7F3BF08BDF8B506460D4600F060 +:102F8000EAF9044608B9FFF7E9FFA7680FB9FFF7A8 +:102F9000E5FFE368991C20D05A1C21D1A5B315F197 +:102FA000820F13D102232360EFF3108672B62946F5 +:102FB0002046FFF737FB054686F310882368022B6F +:102FC00024D1204600F086F82846F8BD15F1830F7D +:102FD000EAD0FFF7C3FF0025E6E702232360FAE704 +:102FE000002BF6DB204600F0DAF93B689B689B0576 +:102FF00001D50223236015F1810FD5D16369002B20 +:10300000D2DBFFF7ABFFCFE73546F4E700232360C1 +:10301000DAE708B5FFF7E0F86FF0830008BD2DE9A7 +:10302000F3410E46174698460546FFF74FFE00F05F +:10303000A6F92946024601A8FFF758FE044660B9E2 +:1030400043463A4631460198FFF774F9044640B1C9 +:103050006B0002D5019800F03DF8204602B0BDE8B3 +:10306000F0810198FFF7B6FA0446F6E740F2011046 +:10307000704770B50546FFF729FE06462846FFF75C +:10308000C9FD044608B9002070BD014632462846F5 +:10309000FFF7D6FD0028F6D12368D868F4E76FF073 +:1030A0000200704700DF70474FF480507047B0F562 +:1030B000805F03D1EFF30B808038704700207047AA +:1030C0007047EFF30B8000F1800383F30B887047A8 +:1030D00000207047EFF30B83803B83F30B8870472E +:1030E00080EA0000E1EE100A00EE100A00EE900AFD +:1030F00001EE100A01EE900A02EE100A02EE900AAA +:1031000003EE100A03EE900A04EE100A04EE900A91 +:1031100005EE100A05EE900A06EE100A06EE900A79 +:1031200007EE100A07EE900A08EE100A08EE900A61 +:1031300009EE100A09EE900A0AEE100A0AEE900A49 +:103140000BEE100A0BEE900A0CEE100A0CEE900A31 +:103150000DEE100A0DEE900A0EEE100A0EEE900A19 +:103160000FEE100A0FEE900A70472DE9F0410E465F +:103170001546002A4AD0C4074BD480F00204C4F399 +:103180004004A40003F00602062A4AD144F00104D8 +:1031900022462946304602F077FBB8BB46E800F2EB +:1031A00005EB0608100E120208F1FF3747E800F39E +:1031B0004FEA136166D51B0264D5884262D046E8A7 +:1031C00000F547E800F7FEF7A2FF2D0E85424FEA13 +:1031D000176734D3FEF79DFF874230D82846FEF7A5 +:1031E00091FF2246C6F101010144304602F04CFB3A +:1031F000002847D00135AF4218D83846FEF780FF87 +:103200002246A8EB000102F03FFBD8B30020BDE846 +:10321000F081EFF39484A40004F0040444F0120459 +:10322000B0E7990731D544F00804B1E72846FEF726 +:1032300067FF0646FEF76FFF22460146D5E7FEF719 +:1032400072FF85421ED3FEF770FF87421AD82846C8 +:10325000FEF7DAFC2246C6F101010144304602F0D5 +:1032600013FB78B10135AF4203D83846FEF756FF5D +:10327000C6E72846FEF752FF0646FEF758FF2246ED +:103280000146EBE76FF07F00C1E74CF2DA20BEE7C2 +:1032900010B50446FFF706FCFFF714FC10B143F627 +:1032A000DA3010BDFFF742FC0028F8D1FFF710FB21 +:1032B0000028F4D102232360F3E708B5FFF7B0FB41 +:1032C00010B143F6DA3008BDFFF7B4FB0028F8D19F +:1032D00000F01CF80028F4D162B6FDF703FCFFF7FC +:1032E000B5FB0028EDD1FFF7D1FB0028EBD0E8E7D4 +:1032F000EFF30880EFF309812DE9F00F6B4672467A +:10330000FDF746FB08B0FFF76DFBFEE700207047B6 +:1033100004460D46FFF7E4FEA54628470368283318 +:1033200083F30988836883F30B88BFF36F8F40684A +:10333000704703689A68DB6812F4806F05D18B428E +:103340002CBF00206FF0FA0070478B420CBF0020AA +:103350006FF0FA00704710B5FFF7A9FE0446FFF7BB +:10336000B7FE50B9FFF7A6FCA3685B681B685B68F3 +:10337000834218BF0024204610BD0024FBE738B567 +:10338000054648B100F01BF8B5EBD07F044601D0EC +:10339000FFF7E4FD204638BDFFF78CFCF4E700237F +:1033A00010B500F1280252F8041F19B1C16F146C56 +:1033B00019444C600833202BF5D110BD70474FF0F5 +:1033C000FF307047000001464154414C20455252A5 +:1033D0004F523A2000486172644661756C740D0A60 +:1033E000004D656D4D616E616765206661756C7439 +:1033F0000D0A004275734661756C740D0A005573B1 +:103400006167654661756C740D0A0053656375727A +:10341000654661756C740D0A005265736572766558 +:103420006420457863657074696F6E2000506C612C +:1034300074666F726D2065787465726E616C206958 +:103440006E7465727275707420284952516E293AF3 +:1034500020000000290B00000B1F0000D90D000008 +:103460008D0D0000331F00003F1F0000610B0000A6 +:103470000F1F0000490B0000550B0000150C000049 +:10348000151F0000211F0000271F00001D00000065 +:10349000100004001C0002001100060003020202DA +:1034A0000338FDD87047506C6174666F726D2045AB +:1034B0007863657074696F6E3A0D0A00416C6C2018 +:1034C00070696E732068617665206265656E206341 +:1034D0006F6E66696775726564206173206E6F6ECA +:1034E0002D7365637572650D0A00303132333435E2 +:1034F000363738394142434445461B5B313B333410 +:103500006D5B536563205468726561645D2053652B +:103510006375726520696D61676520696E6974699C +:10352000616C697A696E67211B5B306D0D0A00540E +:10353000462D4D20466C6F6174204142493A204827 +:103540006172640D0A004C617A7920737461636B57 +:10355000696E6720656E61626C65640D0A001B5BB5 +:10356000313B33346D426F6F74696E672054462D62 +:103570004D2076322E302E301B5B306D0D0A0055FB +:103580006E6B6E6F776E2053504D205356432072F2 +:1035900065717565737465643A2000556E6B6E6F66 +:1035A000776E20535643206E756D6265722072658A +:1035B000717565737465643A200000000040005026 +:1035C000005000500080005000A0005000B000509B +:1035D00000E0005000F000500000015000100150C9 +:1035E0000040015000500150007001500080015017 +:1035F00000B0015000C0015000D0015000E0015067 +:1036000000F0015000000250001002500020025053 +:103610000030025000400250006002500080025012 +:1036200000A002500090035000258450008000004C +:1036300000800000FFFF0F00007C00000080000001 +:0C3640002C1200201412002000020000D8 +:10366000009A204B9A4208D110B502F0A7FA02F056 +:10367000A9F906BC96460C46744702F0E3FA009A94 +:10368000184B9A4208D110B502F0A4FA02F09AF948 +:1036900006BC96460C46744702F0D4FA0CB4029A63 +:1036A000104B9A420CD14FF0004319430CBC10B59B +:1036B00000F09EF802F086F906BC96460C46744768 +:1036C00002F0C0FA009A074B9A4202D106490868F4 +:1036D000744702F0B7FA009A024B9A4200D174473D +:1036E00002F0B0FAA5EDF5FE801000200348044B6F +:1036F000834202D0034B03B118477047A811002042 +:10370000A8110020000000000548064B1B1AD90F25 +:1037100001EBA301491002D0034B03B118477047D6 +:10372000A8110020A81100200000000010B5064CD0 +:10373000237843B9FFF7DAFF044B13B10448AFF322 +:1037400000800123237010BDC0180020000000007D +:10375000EC5E000008B5044B1BB104490448AFF30C +:103760000080BDE80840CFE700000000C41800203A +:10377000EC5E0000A3F5803A704700BF174B002BAA +:1037800008BF134B9D46FFF7F5FF00218B460F4600 +:103790001348144A121A02F0EEF90E4B002B00D017 +:1037A00098470D4B002B00D09847002000210400C3 +:1037B0000D000D48002802D00C48AFF3008002F045 +:1037C000DBF820002900FEF775FD02F0C1F800BF0C +:1037D000000008000000000000000000F80B0020BE +:1037E000A8110020B8280020000000000000000000 +:1037F0002DE9F84304460D4616461F46EFF30583B0 +:10380000C3F308030BB1FFF7A9FBDFF834903B4685 +:10381000204632462946D9F80080FFF700FCD9F847 +:1038200000300446984506D0DB6901461869BDE8BA +:10383000F843FFF7A1BBFFF793FB2046BDE8F883F1 +:10384000B019002001680E4A0346914215D1C169A2 +:10385000A2F11022A2F1EF1291420ED18268012A48 +:103860000BD8C26812B101698A4206D0586928B1E2 +:103870009B691B1A5842584170470120704700BF8E +:1038800055AA00FF0D4B70B59E68A6B13046FFF7F4 +:10389000D9FF044678B9F3686BB935690DB920468C +:1038A00070BD2846FFF7CEFF28B9EB68B34202D1BE +:1038B0002E462D69F2E70124F1E700BF4C1A0020E3 +:1038C0002DE9F041394E3468F368D4B1B468C4B11D +:1038D000002861D000295FD001FB00F5B5FBF0F0B6 +:1038E000884259D1291D57D8AA070DD025F00302C7 +:1038F00004321C4603E0616891424FD2A469002C57 +:10390000F9D12046BDE8F0812A46F2E7891A232939 +:1039100004F12007D4E9050C1AD80123A360A0B153 +:10392000C0F818C0A36903B158610023C4E9053386 +:103930003369DB0702D5FFF7A5FFA0BB2A460021AC +:1039400038463C4602F017F9DBE7C6F80CC0E9E759 +:1039500002F1200804EB08032039C3E9011E2169A4 +:10396000DFF84CE0DC60196144F808E0AEF1102E9D +:10397000AEF1EF1EC3F81CE001B1CB60C3E9050C4A +:1039800040B18361996901B14B6101212361C4E9AF +:103990000121CAE7F360F5E70024B2E7D4F808E0B4 +:1039A000BEF1000FB2D0012001F0D2FF4C1A00206E +:1039B00055AA00FFF8B5054600283AD0364E3368C0 +:1039C000002B36D0B268002A33D0834203D8726805 +:1039D0001344984202D3012001F0BAFFA0F1200461 +:1039E0002046FFF72FFF0028F5D155F8183C012B92 +:1039F000F1D145F8180C55E90570DFB1BB68CBB9BA +:103A000055F81C2C7B68203213447B60386100B170 +:103A1000C76020220021204602F0ADF8386908B1C5 +:103A200083682BB333699B0703D5FFF72BFF00286F +:103A3000D1D1F8BD40B3836833BB42686368134497 +:103A4000203363600369D4E90521236192B9B9B9D0 +:103A5000426981696261A161A2B19461A26902B106 +:103A6000546103B1DC602022002102F084F8D9E720 +:103A70003C46E2E79161A1690029E9D04A61E7E7A4 +:103A8000F160F8E7F460E9E7F36845F8083C03B152 +:103A90005C61F460C6E700BF4C1A002038B50D46E3 +:103AA000142200210446124802F065F81149124818 +:103AB00000F02CF8232D1AD914F003031FBF043D86 +:103AC000ED18C3F10403E4182A460021204602F051 +:103AD00052F8074B094AC3E900459C602260A2F1F5 +:103AE0001022203DA2F1EF126560E261DC6038BD7A +:103AF0004C1A0020B5390000C138000055AA00FF5B +:103B0000014B1B68184700BFC8100020024B18600B +:103B1000024B002019607047CC100020C810002014 +:103B200010B50A46044619B1024B00211B6898479C +:103B300010BD00BFD0100020054B0A46197819B1FE +:103B40000146181D02F0B8B86FF08800704700BF3A +:103B5000601A002010B5074C00F032F8204602F041 +:103B6000BCF8201F0821FFF7DBFFBDE8104002F082 +:103B7000A0B800BF641A002070B50C4D2B787BB93B +:103B800002F095F8044670B90126281D6E7002F007 +:103B900091F8044638B900F00BF8044618B92E70B5 +:103BA0000024204670BDFFF7D5FFFAE7601A002019 +:103BB0000122024B002083F880257047681A0020FC +:103BC000F8B5074C2025264601272046276202F03B +:103BD0005DF8013D04F12C04F7D186F88055F8BD5D +:103BE000681A002010B50C4C236813B10B4B1B68EE +:103BF0002BB900F089FC30B90122084B1A6001236F +:103C00002360002010BD0138062801D9044810BDEA +:103C1000044B53F8200010BD042000200020002099 +:103C2000FE8FFFFF545D0000144B2DE9F043002888 +:103C300014BF04461C46124F236883B0BB4219D000 +:103C400016460D4620464FF4147104F1040900F0A5 +:103C500047F804F58E78484600F0CEF8404600F06C +:103C600019FA2B464A4640460649009600F034FBB6 +:103C700008B92760002003B0BDE8F08308200020C9 +:103C8000A5BCC95A7D3E000070B50D4C1D460028EC +:103C900014BF064626460B4B306882B098420DD1C1 +:103CA00006F58E70002633460096144600F03EFB63 +:103CB000002818BF34462C6002B070BD0248FBE7F4 +:103CC00008200020A5BCC95AE88FFFFF38B131B1E8 +:103CD000002201440346013081421A70FAD1704734 +:103CE00038B131B1002201440346013088421A70D4 +:103CF000FAD170472DE9F043202B1D460646884631 +:103D000091468BB026D8DBB202AF8DF80480B04666 +:103D100058F8041B8DF8053021B9404601F038F9F8 +:103D2000044640B9012302224046336001A901F054 +:103D300043F9044638B138462021FFF7D1FF204629 +:103D40000BB0BDE8F0832A464946404601F034F9FD +:103D50000446F0E702AF1946104600233A4601F048 +:103D6000B1FA04460028E6D12023B9461D46CCE727 +:103D70002DE9F041D0F8F830A6B0002BD8BF02AE44 +:103D800031DD05460027D0F80C4102AEA4F1010850 +:103D90009022D5F8FC403146D0F8000101AB0197E4 +:103DA000B8FA88F8A0474FEA5818044620B9019B92 +:103DB00053B9B8F1000F16D030469021FFF790FFAD +:103DC000204626B0BDE8F081014632462846FFF77E +:103DD00091FF58B9D5F80431019A1344C5F804315C +:103DE000B8F1000FE8D16FF03C04E5E70446204647 +:103DF00026B0BDE8F08100BF70B50025044614224E +:103E000004F588762946C0F8F850FC3001F0B3FE7E +:103E100008222946304601F0AEFE144B30461B689E +:103E20009847204640F8045B01F098F8104B304664 +:103E30001B689847C8B9D4F8F830AB420FDC03EBE5 +:103E4000830204EB82022021C2F800010120C2E9B2 +:103E5000421008490133C2F8FC10C4F8F830064B90 +:103E60003046BDE870401B68184770BDF010002058 +:103E7000EC100020614E0000E81000202DE9F04712 +:103E8000202A88B07AD83F4B00F5887904461B6811 +:103E900048461746884698470546F8B940F2011645 +:103EA000D4F8F830002B65D02046FFF761FF0546B7 +:103EB00038B9D4F8F830002B14DC013EF2D16FF0A1 +:103EC0003B056E4620213046FFF70AFF2E4B484641 +:103ED0001B689847002818BF6FF01D05284608B0DA +:103EE000BDE8F087D4E94132934203D3D4F80C21E2 +:103EF000012A02D0013ED7D1E1E71F2BFAD96E4645 +:103F000001462022304604F1040A01F034FE314615 +:103F1000504601F07BF805460028D3D1504601F009 +:103F200031F8504601F01AF82946504601F030F8B1 +:103F300005460028C6D150462022314601F03CF803 +:103F400005460028BED1034632462021304601F006 +:103F5000B9F905460028B5D1D4F8F8303A46002B17 +:103F6000C8BF002340463146C8BFC4F8043101F041 +:103F7000DDFDA7E76FF03F056E46A3E76FF03B0559 +:103F8000ACE700BFEC100020E810002070B590B046 +:103F900000287AD03E4C0D46402236210646204667 +:103FA00001F0E9FD40225C21A01801F0E4FD2B1D89 +:103FB000A34203D904F144039D4252D32B682268E3 +:103FC000534023602B68226C534023646B68626803 +:103FD000534063606B68626C53406364AB68A26873 +:103FE0005340A360AB68A26C5340A364EB68E268E3 +:103FF0005340E360EB68E26C5340E3642B69226951 +:1040000053402361226D2B695340236562696B69BC +:10401000534063616B69626D53406365AB69A2692C +:104020005340A361AB69A26D5340A365EB69E2699C +:104030005340E361EB69E26D5340E3650021304694 +:1040400000F0A6FF044628B940223046104900F08F +:10405000B3FF044640216846FFF742FE204610B0F9 +:1040600070BD631E04F13F01013D1F3415F8010FBF +:1040700013F8012F42401A7011F8012F2878A3423B +:1040800082EA00020A70F1D1D8E76FF07304E5E725 +:104090005822002010B54FF49A720021044601F016 +:1040A0006AFD42F21072044BC4F8202104F59670A8 +:1040B0001B68BDE810401847F01000202DE9F04FB4 +:1040C00004468846914695B0002900F0A780002A52 +:1040D0000CBF0126022600238DF80C30002C00F0C6 +:1040E0009F80DFF844A104AF0AF1400B0021204675 +:1040F00000F04EFF034648B1384620210193FFF7F8 +:10410000EFFD019B184615B0BDE8F08F40225146E7 +:10411000204600F051FF03460028EDD104F1F405DC +:1041200020222946204600F047FF03460028E3D11D +:104130000122204603A900F03FFF03460028DBD1FF +:10414000022E62D020460CA900F060FF0346002832 +:10415000D2D10146204600F01BFF03460028CBD1F8 +:1041600040225946204600F027FF03460028C3D1CD +:10417000202220460CA900F01FFF03460028BBD1D7 +:104180003946204600F042FF03460028B4D13946A4 +:104190002046FFF7FBFE03460028ADD1202229462A +:1041A000204600F009FF03460028A5D120460CA9AF +:1041B00000F02CFF034600289ED10146204600F067 +:1041C000E7FE0346002897D140225946204600F0DA +:1041D000F3FE034600288FD1202220460CA900F0D0 +:1041E000EBFE0346002887D12946204600F00EFF4B +:1041F0000346002880D19DF80C200132D2B2B24291 +:104200008DF80C20FFF472AF76E74A46414620460F +:1042100000F0D2FE0346002894D06DE701265AE74D +:104220006FF0730304AF67E7582200202DE9F041D7 +:104230000446884615461F46D0F81801E0B013B171 +:1042400000EB40004008B5F5807F3ED82844B0F52B +:10425000C07F3AD84FF4C0720021684601F08BFC51 +:104260006946D4F82431D4F81821D4F828019847A5 +:1042700070BBD4F8186157B1D4E9493072080DEB1E +:104280000601984720BBD4F8183106EB5306B8F165 +:10429000000F00D08DB9324669462046FFF70EFF69 +:1042A000054610B90123C4F8143131466846FFF7BA +:1042B00017FD284660B0BDE8F0810DEB06004146D1 +:1042C0002A462E4401F032FCE5E76FF00405F0E7E2 +:1042D0006FF00805EDE700BF2DE9F047044604F153 +:1042E000F4050F4691461E46DDF8208000F036FEAC +:1042F00029462046FFF74AFE08B1BDE8F087284668 +:104300002022012101F037FCD4F81831C4F82471BF +:10431000C4F8289113B92023C4F818314246314615 +:104320002046BDE8F0470123FFF780BFB2F5806F5C +:1043300000F295802DE9F04F89B09A46129BB3F5B3 +:10434000807F00F29080D0F82431164604460F4654 +:104350004BB3D0F81C31012B05D0D0F81421D0F884 +:1043600020319A421FDD514600232046129AFFF762 +:104370005DFF014698B900231293002E5ED0DFF84E +:10438000EC9009F1400B0021204600F001FE202EA8 +:104390003546014628BF202504F1F40890B10846AF +:1043A00009B0BDE8F08FBAF1000FE6D0129B002BE8 +:1043B000E1D051461A462046FFF780FE014600280C +:1043C000DBD0ECE749464022204600F0F5FD0146EF +:1043D0000028E4D141462022204600F0EDFD0146B0 +:1043E0000028DCD16946204600F010FE0146002876 +:1043F000D5D1204600F0CCFD01460028CFD159464A +:104400004022204600F0D8FD01460028C7D1694669 +:104410002022204600F0D0FD01460028BFD14146B1 +:10442000204600F0F3FD01460028B8D138462A4660 +:10443000414601F07BFB761B2F44A4D15146204618 +:10444000129AFFF73BFE01460028A8D10846D4F88F +:1044500014310133C4F8143109B0BDE8F08F6FF0A6 +:104460000201084670476FF0040198E758220020C7 +:10447000002130B58DB0282202A8019101F07BFB0C +:1044800002A800F047FF044610B120460DB030BD31 +:10449000174D4FF0FF31286800F042F9044620B173 +:1044A000144800F0D3F9012C18D0002000F068F96E +:1044B000D0B9114A02A901A800F0C4FC04460120A9 +:1044C00000F05EF960B9286800F032F90028DCD00D +:1044D0000A4800F0BBF920460DB030BD0524F2E7D4 +:1044E000074800F0B3F9EEE7064800F0AFF9E0E75F +:1044F000D4100020705D0000D8220020C85D0000AC +:10450000A85D0000885D000030B583B000F05CF865 +:1045100028B100F0ABF80324204603B030BD00F012 +:1045200077F8D8B900F02CF9E0B9224CD4F8283942 +:104530001B0EF02B0AD1D4F8242A1F4B9A4231D0FB +:1045400000F044F8072400F091F8E5E7062400F0B5 +:104550003DF800F08BF8204603B030BD042420461F +:1045600003B030BD00F032F800F080F8FFF780FFB4 +:10457000044698B9114D2B68002BCDD10246014657 +:10458000FFF752FB50B968220D4901ABFFF77CFBE6 +:1045900020B920460B4B2B6003B030BD05242046CC +:1045A00003B030BD012000F0EBF80028DAD1C4F8E8 +:1045B0000C0ADBE7001084500000E020F824002003 +:1045C000FC2400205AEA5A5A002070470020704705 +:1045D000430504D54FF0FF32034BC3F80821024BCB +:1045E000C3F8080A704700BF00108450014BC3F89D +:1045F000040A70470010845008B100F06BB84FF403 +:104600007500704708B100F04FB84FF4750070475F +:1046100010B5114800F070F800B110BD0F4800F05F +:104620006BF80028F9D10E4C204600F065F8002800 +:10463000F3D10C4B0C481C6000F05EF801460028DA +:10464000EBD100F02DF8044608B1204610BD00F073 +:1046500079F82046FAE700BFE4100020E0100020BF +:10466000DC100020D4100020D810002008B5084825 +:1046700000F04CF8074800F049F8074800F046F809 +:10468000064800F043F8BDE8084000F00BB800BF52 +:10469000E4100020E0100020DC100020D8100020E2 +:1046A00000207047704700BF024610B4084CD4F891 +:1046B000003A1342FBD021B1D4F804310B60C4F8A6 +:1046C0000831034B0020C3F8082A5DF8044B7047FB +:1046D00000108450044AD2F8003A1842FBD0C2F8C5 +:1046E000080A0020704700BF0010845001F0E8B9AC +:1046F0000A46002101F03FBA08B5034B02681B6867 +:1047000010689847002008BD1011002008B5034B21 +:1047100002685B6810689847002008BD10110020EF +:10472000024B02689B681068184700BF10110020F8 +:1047300008B5034B0268DB6810689847002008BD85 +:104740001011002070B5094C094D2069AB689847DD +:1047500018B1084B08485B6898470021074AEB6886 +:1047600011602069BDE87040184700BFFC100020B0 +:1047700010110020F4100020E05D000064250020EE +:10478000F8B51A4D1A4E0446B26828699047E8B940 +:10479000184F3B684CB1A3B1012B19D0013B3B60D2 +:1047A0002869F36898470020F8BD43B90121124AEF +:1047B000C2F800151149D1F81029002AFBD10133A4 +:1047C0003B60F368286998470020F8BD0C48F8BDA5 +:1047D0000A4AD2F81039002BFBD1074A6FF07E400D +:1047E000C2F80035FFF702FF3B68D7E7FC10002056 +:1047F0001011002064250020000084500010845017 +:10480000E98FFFFF014B1B68184700BF1011002004 +:10481000014B9B68184700BF10110020014BDB685B +:10482000184700BF10110020BFF34F8F0549064BFA +:10483000CA6802F4E0621343CB60BFF34F8F00BF3E +:10484000FDE700BF00ED00E00400FA0530B44FF0D2 +:10485000FE320025074B084C08494968C3F800247C +:10486000C3F80424C3F80824C3F80C24C4F8005582 +:1048700030BC08470010845000008450F410002021 +:1048800010B5044650B1636813F0685F05D0064A5E +:10489000934202D000236260236010BD034B0448A2 +:1048A0005B689847EFE700BF2C5F5CA9F41000201D +:1048B000005E0000C8B143680D4A934213D013F064 +:1048C000685F0ED0012350E8002F194640E8001C15 +:1048D0009CF0000FF7D1012AF5D0BFF35F8F0020C5 +:1048E000704704487047044870476FF4E0407047D1 +:1048F0002C5F5CA9E98FFFFFEA8FFFFF034680B1C1 +:10490000426809498A420AD012F0685F05D0BFF3B5 +:104910005F8F002210461A607047044870470448B1 +:1049200070476FF4E04070472C5F5CA9E98FFFFF90 +:10493000EA8FFFFF10B5044620B10023034A23602D +:10494000626010BD0248FFF781FFF6E73A00003AC7 +:10495000285E00002DE9F047002878D00C46002999 +:1049600075D01D46002B72D007461AB101220023D4 +:104970002A6003602B68002B64D02946204600F093 +:10498000B7FD804600285FD12146286800F096FDDB +:104990008046002858D12B68082B6CD0042B6DD092 +:1049A000A3F10209B9FA89F94FEA59190121354EE3 +:1049B000C6F8C411C6F84011C6F8C411636AC6F837 +:1049C0003031D6F830219342F6D14FF0000A4FF043 +:1049D000FF30C6F82CA1FFF7FBFD6FF01B0350461C +:1049E000C6F80031FFF702FEC6F80C91D6F8040AAB +:1049F00040F48060FFF7FAFD0A23C6F83831089BBF +:104A0000012B29D02369204AA2FB03231B09626AD8 +:104A1000404602FB03F303EB43031A4ADB039B0903 +:104A2000C2F8D8310123C2F82C313B682A6823F040 +:104A30007F4343EA02633B602A6843EA02233B6008 +:104A4000BDE8F087DFF844804046BDE8F087DFF836 +:104A500040804046BDE8F0874FF47F03D3F80C2C2C +:104A6000013206D0D3F80C3C074AA2FB03231B09F2 +:104A7000CDE71623CBE74FF0030997E74FF0020984 +:104A800094E700BF00108450ABAAAAAA310CF10031 +:104A9000350CF10058B34B1EB3F5047F27D230B567 +:104AA0004FF0000ECD00744671464B0901F01F0C0B +:104AB00050F82330BCF11F0F23FA0CF306D003F09B +:104AC000010319B901211C468E46EEE79C4201F113 +:104AD000010106D01C464FF0010EA942E5D100208D +:104AE00030BD0EF1010E9645F7D1024830BD0148A8 +:104AF000704700BF360CF100C0B32DE9F0434C1EE7 +:104B0000B4F5047F1DD2E3B1DAB100252E46A846E4 +:104B10002C46CF0003F1FF394FEA541C04F01F0E5E +:104B200050F82C10BEF11F0F21FA0EFC0CD00CF027 +:104B3000010C4CB90126E04634463546ECE7964276 +:104B400016D90C48BDE8F083AB420BD0C44508BF72 +:104B50000136A945F3D001350134BC42DCD1002037 +:104B6000BDE8F0830125E0462E46F5E70148704791 +:104B70001D46F1E7370CF1002DE9F04F91B0834667 +:104B8000DDE91B460D46002E6ED10F691C60002327 +:104B90001A990B60002A00F02F819D4B6A6AD3F8A6 +:104BA0003811D3F830319A4269D10A2967D19BF87C +:104BB0000330089304F10803079304230593954BEE +:104BC000934CA3FB07239B0803EB4303A7EB43038F +:104BD000039306971A9B069E1E60002E00F0EA8043 +:104BE00000F096FC00230993BBF1000F00F0D58084 +:104BF00098464FF0010ADDF81C90002D00F0CD80A2 +:104C0000089B002B3DD0284608A900F071FC002825 +:104C100039D0814B984220D0089B082B00F0E480CB +:104C200000225B000893294608AB58460092FFF724 +:104C300091FE7A4B984200F0D38070B9DBF80020E7 +:104C4000130A03F47F03134323F07F43CBF80030B0 +:104C5000059B013B0593BDD10020039000F058FC5B +:104C6000039811B0BDE8F08F4FF47F01D1F80C0C20 +:104C700001300CBF4FF40477D1F80C7C86E768480C +:104C8000EBE76648C5E72946089800F017FC0028BE +:104C9000BFD1089B082B00F0A980042B00F0A9804D +:104CA000A3F10203B3FA83F35B090493C4F8C4A12C +:104CB000C4F840A1C4F8C4A16B6AC4F83031D4F878 +:104CC00030219342F6D100234FF0FF30C4F82C314D +:104CD000FFF77EFC002318466FF01B03C4F8003179 +:104CE000FFF784FC049B4B4FC4F80C31D4F8040A42 +:104CF00040F48060FFF77AFC0A23C4F838312B694E +:104D000009A8A7FB03236A6A1B0902FB03F303EB51 +:104D10004303DB039B09C4F8D831C4F82CA1DBF8AA +:104D20000030089923F07F420B0243EA01631343EA +:104D3000CBF8003000F0B2FB099B03F01A030343E9 +:104D40007FF46AAFA7FB0637D4F81431B8EB970F9E +:104D50000A93D4F818310B93D4F81C310C93D4F87F +:104D600020310D93D4F824310E93D4F828310F93C9 +:104D700001D1039B9BB9484618220AA9183EFFF7A8 +:104D8000B5FC09F1180908F101089EB100F0C0FB5B +:104D900000230993002D7FF433AF224839E74846BA +:104DA0001A46F61A0AA9994408F10108FFF79EFC71 +:104DB000002EEBD1069F079E6A6939463046FFF701 +:104DC00069FEAA6940B94FF4806339463046FFF75F +:104DD00093FE00283FF440AF00231A9A136018E7AF +:104DE0002B6A002B3FF439AF0F4836E703230493B7 +:104DF0005CE70223049359E70122294658460096AE +:104E000008ABFFF7A7FD00283FF4D4AE25E700BFAD +:104E100000108450ABAAAAAA020CF100310CF100D8 +:104E2000300CF100350CF100320CF10030B4DDE94A +:104E3000023402940024049DCDE9035430BCFFF7F2 +:104E40009BBE00BF30B51546012487B005AB00936B +:104E50000022CDE9015404ABFFF78EFE07B030BD50 +:104E6000F0B587B0002966D01E46002B63D01446EB +:104E7000002A60D0314F0D4638684FF0FF31FFF700 +:104E80004FFC00284DD10020FFF77AFC002844D1C8 +:104E90002B4800F03FFAD8B101204FF0FF35FFF763 +:104EA0006FFC002835D14FF408712648FEF70EFF3D +:104EB00004212548FEF70AFF21482821FEF706FFB6 +:104EC0003868FFF735FC00282FD1284607B0F0BD21 +:104ED0001C4A0346029205AA019204AA039000927A +:104EE000174902461848FFF7A1FF03460028D3D10F +:104EF00028461D46059B22469C4228BF1A46049917 +:104F000032600831FFF7F2FB0120FFF739FC00287F +:104F1000C9D00E48FFF79AFCC5E70D48FFF796FC8D +:104F2000B6E70C48FFF792FCADE70B48FFF78EFCA5 +:104F3000284607B0F0BD4FF0FF35C6E7D41000207B +:104F40007C250020A425002078250020A85D0000F5 +:104F5000885D0000705D00004C5E000010B50446E6 +:104F600028B12046BDE81040F421FFF7C1BB04483A +:104F7000FFF76CFC2046BDE81040F421FFF7B8BBFA +:104F8000645E000010B1F421FEF7A0BE704700BFC0 +:104F900008B521B1012908D06FF0360008BD012104 +:104FA00000F058F80028F7D108BD022100F052F8AF +:104FB0000028F9D0F0E700BF30B505468818B0F5F5 +:104FC000801F0B461446A1B001D8802A0CD9B3F536 +:104FD000801F17D922461946284600F07DF804465E +:104FE00084B9204621B030BD6846FFF77FFB2246DA +:104FF0006946284600F070F8802104466846FFF7AD +:1050000077FBEDE76FF03604EBE700BF70B5E8B172 +:105010000E46D9B1044600F031F80546B0B9236810 +:10502000012B0BD0022B01D0284670BD1C2230462C +:1050300004F10801FFF75AFB284670BD20223046D4 +:1050400004F10801FFF752FB284670BD6FF03605EA +:10505000EAE700BF78B138B50D46F0210446FFF706 +:1050600047FB402320462560E36500F091FA0038B5 +:1050700018BF012038BD0120704700BFF0B5056E94 +:10508000A5B0044604AEE5B90023012701933046DC +:105090006760294602AA009300F046FA10B1012089 +:1050A00025B0F0BD2A46204602A900F099FA002852 +:1050B000F5D1204600F0AAFB0028F0D1206625B0EB +:1050C000F0BD802D2A46304628BF802204F16401BD +:1050D000FFF70CFB256ED7E7002800F0AE802DE926 +:1050E000F04F1446A5B0002A3DD00F46002949D004 +:1050F000B2F5803F0546006E20D34FF6FF7805F1EC +:10510000640AEB6D1A1AB2FBF3F103FB1122002AB9 +:1051100065D18342B9464FF6FF7672D0B6FBF3FBFA +:1051200003FB0BFBBBF1000F30D1002E45D1A4F5E2 +:105130007F44FF3CB4F5803F4744E2D2EA6D161A43 +:10514000B6FBF2F302FB1366A64228BF2646002EEA +:1051500075D1824200F08D80B4FBF2F602FB06F6B8 +:105160002EB9002C79D1002025B0BDE8F08F0023A6 +:1051700031463846CDE9003302AA00F0D5F90028BF +:1051800000F09580012025B0BDE8F08F002359463E +:105190004846CDE9003302AA00F0C6F90028F1D153 +:1051A0005A46284602A900F01BFA0028EAD1A6EBCD +:1051B0000B06286ED944002EB9D019304946324624 +:1051C00005EB8000FFF792FAA4F57F44286EFF3CC0 +:1051D0003044B4F5803F4744286692D2AEE742455A +:1051E00028BF4246164639465044FFF77FFA286EDC +:1051F000EB6D3044834207EB06092866A8EB0606F0 +:105200008CD1802B28BF802351461A4604A8FFF773 +:105210006DFA0023E96D02AACDE9003304A800F07D +:1052200083F90028AED12846EA6D02A900F0D8F92A +:105230000028A7D1EB6D286670E70120704705F1C3 +:105240006403394632461844FFF750FA286EEA6D77 +:105250003044A41B374428667BE72B6E2246193363 +:1052600005EB83003946FFF741FA2B6E23442B668A +:1052700079E7802A28BF802205F1640104A8FFF79E +:1052800035FA0023E96D04A8CDE9003302AA00F045 +:105290004BF900287FF476AF2846EA6D02A900F0AA +:1052A0009FF900287FF46EAFEA6D286654E7324616 +:1052B000284602A900F094F900287FF463AF374430 +:1052C000A41B4EE7F8B51C460546114816460F4686 +:1052D000FFF744FE21460E48FFF75AFE044620B170 +:1052E0000B48FFF74FFE2046F8BD3A4629460848CE +:1052F000FFF762FE04460028F2D131460448FFF76A +:1053000085FE04460248FFF73DFE2046F8BD00BF7B +:10531000C42700201C2370B582B001A90546019363 +:1053200000F032F8044638B9019B1C2B07D0144C0E +:105330001C212846FFF7DCF9204602B070BDD5E9F4 +:105340000112131E18BF0123003918BF01210126C5 +:1053500028689B00EA6843EA4103002818BF43F02D +:105360000103EE612AB9C5E90834002BE4D1054CEC +:10537000DEE7204643F00803C5E9083402B070BDFB +:10538000370CF0000E0CF0000346002866D0002910 +:1053900064D00A681C2A61D14FF47F023B49D2F8DD +:1053A000100C88425CD0D2F8101C013158D0D2F8D1 +:1053B000101C4FF47F021960D2F8140C3449884253 +:1053C00060D0D2F8141C01315CD0D2F8141C4FF418 +:1053D0007F025960D2F8181C11F5947F4FD0D2F893 +:1053E000181C01314BD0D2F8181C4FF47F02996081 +:1053F000D2F81C0C274988423ED0D2F81C1C01313F +:105400003AD0D2F81C1C4FF47F02D960D2F8001CAD +:1054100070312FD0D2F8001C01312BD0D2F8001CF3 +:105420004FF47F021961D2F8041CAF3120D0D2F8BA +:10543000041C01311CD0D2F8041C4FF47F025961C6 +:10544000D2F8080C144988420DD0D2F8081C01315A +:1054500009D0D2F8082C00209A61704701207047CB +:1054600040F6FC01A5E740F2373200209A61704710 +:105470005121E2E79021D3E742F60411C3E740F659 +:10548000D861B2E742F2D001A1E700BFFCF8FFFF0C +:10549000D020FFFF0429FFFF37F3FFFF014608B5C7 +:1054A0004FF48060FFF7AEF80022034BC3F8C82129 +:1054B000C3F82C2108BD00BF001084500138072814 +:1054C00005D8DFE800F0100E040A040404060748BB +:1054D0007047CB6800204B6270478B6800204B629E +:1054E00070474B68F6E70B68F4E700BF310CF1003A +:1054F0000B6802E0082B0B6006D8026A13424FEAE1 +:105500004303F7D00020704700487047310CF1008A +:105510000022044B4FF48060C3F82C21C3F8C4214F +:10552000FFF756B800108450F0B5002483B0B0F1F6 +:10553000005F8DF8074025D38C468444BCF1804F32 +:1055400004461FD817461D4601220DF1070300F03F +:1055500097F90646B0B99DF80730099A3C603B714F +:1055600092B14DB10246089928460DF1070300F0AB +:1055700087F938B99DF807303046099A15601371DC +:1055800003B0F0BD4FF47506304603B0F0BD00BF68 +:10559000D8B108B50368012B04D0022B0FD043B15A +:1055A0000B4808BD20220B490830FFF79FF8002068 +:1055B00008BD142208490830FFF798F8F7E72022C1 +:1055C00006490830FFF792F8F1E74FF4730070478F +:1055D0000100F300745E0000B45E0000945E000001 +:1055E0002DE9F843002900F0F9800446002800F076 +:1055F000F98003680F469046002B00F0C380013B02 +:10560000012B00F2D7804FF0FF3178484FF00209AC +:10561000FFF786F8002840F0BF800020FFF7B0F8C1 +:105620000646002840F0C280714AD2F81C39002B8F +:10563000FBD16F4DD5F8203C002BFBD14FF0FF3054 +:10564000FEF7C6FFD5F8040A20F04000FEF7CEFFB3 +:1056500001230722C5F81838C5F80029C5F8C43752 +:10566000A36CC5F8CC37E36CC5F8D037C5F8C09744 +:1056700023685BB1013B012B18D8636AC5F85C361F +:10568000236AC5F85836E369C5F85436A269584B01 +:10569000C3F850266269C3F84C262269C3F848262D +:1056A000E268C3F84426A268C3F84026504AD2F8FC +:1056B0001039002BFBD1B8F1000F5FD06368402098 +:1056C000012B08BFC2F884363A68494BC3F8282C2E +:1056D000C3F82C8CFEF790FF0646454AD2F81039E5 +:1056E000002BFBD1424AD2F8203C002BFBD123688F +:1056F0005BB1013B012B18D8D2F85C366362D2F85B +:1057000058362362D2F85436E361394BD3F8502629 +:10571000A261D3F84C266261D3F848262261D3F8FF +:105720004426E260D3F84036A36000230121304ACA +:10573000D2F8CC07A064D2F8D007E064C2F8C4174E +:10574000C2F88436C2F8C837D2F81039002BFBD122 +:10575000C2F81838002E3BD1254BD3F8040A40F08C +:105760004000FEF743FF0120FFF70AF860BB1F4827 +:10577000FEF7DEFF10BB3046BDE8F8830423C2F815 +:10578000C837AAE74FF0FF3118484FF00109FEF77C +:10579000C7FF00283FF441AF1648FFF757F8002035 +:1057A000FEF7EEFF064600283FF43EAF1248FFF733 +:1057B0004DF839E7114E3046BDE8F8831048FFF741 +:1057C00045F83046BDE8F8830E48FFF73FF8CEE7CE +:1057D000102104F10800FEF78BFFBDE70A4E3046AA +:1057E000BDE8F8834FF47306C5E700BFE41000205E +:1057F00000108450705D0000885D00000100F3001F +:10580000C85D0000A85D00000300F300A0B30346DC +:1058100070B4D0E90240D3E9041226BA05BA0CBA32 +:1058200010BAC3E90440D3E90612986A09BAC3E979 +:10583000026512BA996100BAD3E9084125BA0CBAD7 +:10584000C3E90725D3E90B12C3E9094009BAD86BAC +:1058500012BAD962D3E90D4125BAC3E90C250CBAB5 +:1058600000BAD3E9101209BA12BAC3E90E4019649A +:1058700000205A6470BC70474FF47300704700BF3B +:1058800000201870704700BF431810B501D21F2ABE +:1058900001D9002010BD013902F014030144102B7E +:1058A00080EA01043CD009DC8BB1042BF1D11F2C20 +:1058B00040E840F315D941E840F10EE0142BE8D15F +:1058C0001F2C40E8C0F30CD941E8C0F105E01F2CC3 +:1058D00040E800F305D941E800F11C460B468C4234 +:1058E000D7D122F01402013A0A2AD2D801A151F8E4 +:1058F00022F000BF435900003D5900002F5900001D +:1059000093580000935800009358000093580000EB +:105910004959000043590000375900002F59000031 +:105920001F2C40E880F3DCD941E880F1D5E713F47F +:10593000001FAFD1ADE713F4801FFAE75B02A9D5D2 +:10594000A7E713F4002FF4E713F4802FF1E700BF6B +:1059500008B5074B044613B10021AFF30080054B97 +:105960001868836A03B19847204600F029F800BF01 +:1059700000000000C85E000070B50D4D00260D4C03 +:10598000641BA410A64209D10B4D00260B4C00F05D +:10599000D5F9641BA410A64205D170BD55F8043B8F +:1059A00001369847EEE755F8043B01369847F2E791 +:1059B000A0110020A0110020A0110020A41100209F +:1059C000FEE700BFB7EE000AF7EE000AB7EE001AD6 +:1059D000F7EE001AB7EE002AF7EE002AB7EE003A0B +:1059E000F7EE003AB7EE004AF7EE004AB7EE005A7B +:1059F000F7EE005AB7EE006AF7EE006AB7EE007AEB +:105A0000F7EE007AF1EE10CA40F29F01CFF20001EA +:105A10003CEA010CE1EE10CA002383F300887047D2 +:105A2000FDF79CBAEFF30880EFF309812DE9F00F41 +:105A30006B467246FAF7ACFF08B0FFF7F1FFFEE7DE +:105A4000FDF78CBAEFF30880EFF309812DE9F00F31 +:105A50006B467246FAF79CFF08B0FFF7F1FFFEE7CE +:105A6000FDF77CBAEFF30880EFF309812DE9F00F21 +:105A70006B467246FAF78CFF08B0FFF7F1FFFEE7BE +:105A8000FDF76CBAEFF30880EFF309812DE9F00F11 +:105A90006B467246FAF77CFF08B0FFF7F1FFFEE7AE +:105AA000FDF75CBAEFF30880EFF309812DE9F00F01 +:105AB0006B467246FAF76CFF08B0FFF7F1FFFEE79E +:105AC000814270B40546144602D370BC00F02EB873 +:105AD000821821443CB141EA020313F003030FD1C1 +:105AE000E018032812D86FF00300A30843430020F6 +:105AF00019441A442344984210D1284670BC704778 +:105B000011F8013D013C02F8013DE3E7581850F857 +:105B1000046C981840F8046C043BE1E70C1A14F884 +:105B2000016C141A04F8016C0130E4E770B5044606 +:105B30003AB141EA040313F003030CD1D518032D45 +:105B40000FD822F003031C441944002302F003027F +:105B500093420CD170BD11F8013B013A04F8013BAE +:105B6000E6E7CD1A2E68E51A2E60043BE6E75D5C99 +:105B7000E5540133ECE7F0B5044662B922F00303C3 +:105B8000234402F003021A44934214D1F0BD04F8F6 +:105B9000011B013AF1E7A307F9D115460B0443EACB +:105BA00001630B4343EA01231619032DE6D9771B42 +:105BB0003B60043DF9E703F8011BE5E708B5EFF3A7 +:105BC0000583C3F308030BB1FDF7C8F9BDE808402E +:105BD000FDF74CBA10B50446EFF30583C3F3080391 +:105BE0000BB1FDF7BBF92046BDE81040FDF741BA07 +:105BF0002DE9F04104460D4616461F46EFF3058396 +:105C0000C3F308030BB1FDF7A9F93B463246294619 +:105C10002046BDE8F041FCF743BC2DE9F0410446C5 +:105C20000D4616461F46EFF30583C3F308030BB179 +:105C3000FDF794F93B46324629462046BDE8F0413F +:105C4000FCF768BC08B5EFF30583C3F308030BB199 +:105C5000FDF784F9BDE80840FDF7DBB90020704787 +:105C6000704710B5044608B1FDF75AFF2046BDE85D +:105C70001040FDF745BF10B50446406A10B1A16A57 +:105C8000FFF7EFFF0020C4E9090010BD38B5044656 +:105C9000FFF7F1FF236A2C22012B0CBF05466FF0A2 +:105CA000960500212046FFF766FF284638BD0020F4 +:105CB000704770470020704713B5002001AB1446B1 +:105CC000FDF7E2FF30B9019BA34218BF6FF09300CC +:105CD00002B010BD6FF09200FAE7002070472DE986 +:105CE000E04F2746A046A146A246A346A4462DED76 +:105CF000108B4FF0000545EC185B45EC195A45EC4C +:105D00001A5A45EC1B5A45EC1C5A45EC1D5A45ECF9 +:105D10001E5A45EC1F5AF1EE105A4FF66076C0F647 +:105D2000FF763540E1EE105A84F30088254626467A +:105D3000A447BDEC108BBDE8E08F0000F8B500BFB4 +:105D4000F8BC08BC9E467047F8B500BFF8BC08BC5C +:105D50009E467047FF8FFFFFFF8FFFFFFE8FFFFF05 +:105D6000FE8FFFFFFD8FFFFFFC8FFFFFFC8FFFFF0C +:105D70004661696C20746F2061637175697265207A +:105D80006D757465780A00004661696C20746F2037 +:105D9000696E63726561736520504D20636F756E27 +:105DA0007465720A000000004661696C20746F20FF +:105DB000646563726561736520504D20636F756E15 +:105DC0007465720A000000004661696C20746F20DF +:105DD00072656C65617365206D757465780A000085 +:105DE000436F756C64206E6F74206C6F636B2070F2 +:105DF0006F7765722073617665206D7574657800C4 +:105E00006D757465785F667265652063616C6C653D +:105E1000642077697468204E554C4C207061726123 +:105E20006D6574657200000043616E277420696EB1 +:105E3000697469616C697A65206D757465782C2068 +:105E4000776173204E554C4C0D0A00004661696C19 +:105E500020746F20756E6C6F636B206D7574657840 +:105E60000A0000000A637478206973204E554C4C78 +:105E70000A00000067E6096A85AE67BB72F36E3CF4 +:105E80003AF54FA57F520E518C68059BABD9831F05 +:105E900019CDE05BD89E05C107D57C3617DD703083 +:105EA00039590EF7310BC0FF11155868A78FF964E7 +:105EB000A44FFABE0123456789ABCDEFFEDCBA984B +:105EC00076543210F0E1D2C34011002054464D5FA9 +:105ED00043525950544F0054464D5F504C41544624 +:105EE0004F524D5F53455256494345000000000054 +:105EF00000000000000000000000000000000000A2 +:107C00007FE97FE9FBF72CBD7FE97FE9FBF737BD13 +:107C10007FE97FE9FBF75FBD7FE97FE9FBF752BDB5 +:107C20007FE97FE9FBF73ABD00000000000000009B +:107C30000000000000000000000000000000000044 +:107C40007AFFFFFF00900050000000008C3400001D +:107C50000400000000000000000000000000000020 +:107C6000000000000000000090ED00E000A00350C4 +:107C70007FA60350009000506F9500501412002012 +:107C8000A811002044010000615C00005D5C000060 +:107C9000775B0000DC1000200C1100200411002094 +:107CA00000110020FC1000201D48000011480000B9 +:107CB000054800000000000029480000381100209D +:107CC00030110020281100200000000020110020A9 +:107CD0003549000081480000B5480000FD4800001B +:107CE000682500203A00003A6C2500203A00003A4E +:107CF000702500203A00003A742500203A00003A2E +:107D00000000000000000000000000000000000073 +:107D10000000000000000000000000000000000063 +:107D20000000000000000000000000000000000053 +:107D30000000000000000000000000000000000043 +:107D40000000000000000000000000000000000033 +:107D50000000000000000000000000000000000023 +:087D6000553700002D3700002B +:00000001FF diff --git a/examples/nrf9151/s/.cargo/config.toml b/examples/nrf9151/s/.cargo/config.toml new file mode 100644 index 000000000..f64c63966 --- /dev/null +++ b/examples/nrf9151/s/.cargo/config.toml @@ -0,0 +1,8 @@ +[target.'cfg(all(target_arch = "arm", target_os = "none"))'] +runner = "probe-rs run --chip nRF9160_xxAA" + +[build] +target = "thumbv8m.main-none-eabihf" + +[env] +DEFMT_LOG = "trace" diff --git a/examples/nrf9151/s/Cargo.toml b/examples/nrf9151/s/Cargo.toml new file mode 100644 index 000000000..63114478b --- /dev/null +++ b/examples/nrf9151/s/Cargo.toml @@ -0,0 +1,20 @@ +[package] +edition = "2021" +name = "embassy-nrf9151-secure-examples" +version = "0.1.0" +license = "MIT OR Apache-2.0" + +[dependencies] +embassy-executor = { version = "0.6.2", path = "../../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } +embassy-nrf = { version = "0.2.0", path = "../../../embassy-nrf", features = ["defmt", "nrf9120-s", "time-driver-rtc1", "gpiote", "unstable-pac", "time"] } + +defmt = "0.3" +defmt-rtt = "0.4" + +cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } +cortex-m-rt = "0.7.0" +panic-probe = { version = "0.3", features = ["print-defmt"] } + +[profile.release] +debug = 2 diff --git a/examples/nrf9151/s/build.rs b/examples/nrf9151/s/build.rs new file mode 100644 index 000000000..30691aa97 --- /dev/null +++ b/examples/nrf9151/s/build.rs @@ -0,0 +1,35 @@ +//! This build script copies the `memory.x` file from the crate root into +//! a directory where the linker can always find it at build time. +//! For many projects this is optional, as the linker always searches the +//! project root directory -- wherever `Cargo.toml` is. However, if you +//! are using a workspace or have a more complicated build setup, this +//! build script becomes required. Additionally, by requesting that +//! Cargo re-run the build script whenever `memory.x` is changed, +//! updating `memory.x` ensures a rebuild of the application with the +//! new memory settings. + +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; + +fn main() { + // Put `memory.x` in our output directory and ensure it's + // on the linker search path. + let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); + File::create(out.join("memory.x")) + .unwrap() + .write_all(include_bytes!("memory.x")) + .unwrap(); + println!("cargo:rustc-link-search={}", out.display()); + + // By default, Cargo will re-run a build script whenever + // any file in the project changes. By specifying `memory.x` + // here, we ensure the build script is only re-run when + // `memory.x` is changed. + println!("cargo:rerun-if-changed=memory.x"); + + println!("cargo:rustc-link-arg-bins=--nmagic"); + println!("cargo:rustc-link-arg-bins=-Tlink.x"); + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); +} diff --git a/examples/nrf9151/s/memory.x b/examples/nrf9151/s/memory.x new file mode 100644 index 000000000..4c7d4ebf0 --- /dev/null +++ b/examples/nrf9151/s/memory.x @@ -0,0 +1,5 @@ +MEMORY +{ + FLASH : ORIGIN = 0x00000000, LENGTH = 1024K + RAM : ORIGIN = 0x20018000, LENGTH = 160K +} diff --git a/examples/nrf9151/s/src/bin/blinky.rs b/examples/nrf9151/s/src/bin/blinky.rs new file mode 100644 index 000000000..7457a95a3 --- /dev/null +++ b/examples/nrf9151/s/src/bin/blinky.rs @@ -0,0 +1,22 @@ +#![no_std] +#![no_main] + +use embassy_executor::Spawner; +use embassy_nrf::gpio::{Level, Output, OutputDrive}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_nrf::init(Default::default()); + let mut led = Output::new(p.P0_00, Level::Low, OutputDrive::Standard); + + loop { + led.set_high(); + defmt::info!("high"); + Timer::after_millis(500).await; + led.set_low(); + defmt::info!("low"); + Timer::after_millis(1000).await; + } +} diff --git a/examples/nrf9160/.cargo/config.toml b/examples/nrf9160/.cargo/config.toml index 1444b0cd1..6072b8595 100644 --- a/examples/nrf9160/.cargo/config.toml +++ b/examples/nrf9160/.cargo/config.toml @@ -1,6 +1,6 @@ [target.'cfg(all(target_arch = "arm", target_os = "none"))'] -# replace nRF82840_xxAA with your chip as listed in `probe-rs chip list` -runner = "probe-rs run --chip nRF9160_xxAA" +# runner = "probe-rs run --chip nRF9160_xxAA" +runner = [ "probe-rs", "run", "--chip=nRF9160_xxAA", "--always-print-stacktrace", "--log-format={t} {[{L}]%bold} {s} {{c} {ff}:{l:1}%dimmed}" ] [build] target = "thumbv8m.main-none-eabihf" diff --git a/examples/nrf9160/Cargo.toml b/examples/nrf9160/Cargo.toml index af2385960..d5b0f0a41 100644 --- a/examples/nrf9160/Cargo.toml +++ b/examples/nrf9160/Cargo.toml @@ -5,16 +5,22 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } -embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nrf9160-s", "time-driver-rtc1", "gpiote", "unstable-pac", "time"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } +embassy-nrf = { version = "0.2.0", path = "../../embassy-nrf", features = ["defmt", "nrf9160-s", "time-driver-rtc1", "gpiote", "unstable-pac", "time"] } +embassy-net-nrf91 = { version = "0.1.0", path = "../../embassy-net-nrf91", features = ["defmt"] } +embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "proto-ipv4", "medium-ip"] } defmt = "0.3" defmt-rtt = "0.4" +heapless = "0.8" cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } cortex-m-rt = "0.7.0" panic-probe = { version = "0.3", features = ["print-defmt"] } +static_cell = { version = "2" } +embedded-io = "0.6.1" +embedded-io-async = { version = "0.6.1", features = ["defmt-03"] } [profile.release] debug = 2 diff --git a/examples/nrf9160/memory.x b/examples/nrf9160/memory.x index 4c7d4ebf0..e33498773 100644 --- a/examples/nrf9160/memory.x +++ b/examples/nrf9160/memory.x @@ -1,5 +1,9 @@ MEMORY { - FLASH : ORIGIN = 0x00000000, LENGTH = 1024K - RAM : ORIGIN = 0x20018000, LENGTH = 160K + FLASH : ORIGIN = 0x00000000, LENGTH = 1024K + RAM : ORIGIN = 0x20010000, LENGTH = 192K + IPC : ORIGIN = 0x20000000, LENGTH = 64K } + +PROVIDE(__start_ipc = ORIGIN(IPC)); +PROVIDE(__end_ipc = ORIGIN(IPC) + LENGTH(IPC)); diff --git a/examples/nrf9160/src/bin/modem_tcp_client.rs b/examples/nrf9160/src/bin/modem_tcp_client.rs new file mode 100644 index 000000000..067ec4276 --- /dev/null +++ b/examples/nrf9160/src/bin/modem_tcp_client.rs @@ -0,0 +1,197 @@ +#![no_std] +#![no_main] + +use core::mem::MaybeUninit; +use core::net::IpAddr; +use core::ptr::addr_of_mut; +use core::slice; +use core::str::FromStr; + +use defmt::{info, unwrap, warn}; +use embassy_executor::Spawner; +use embassy_net::{Ipv4Cidr, Stack, StackResources}; +use embassy_net_nrf91::context::Status; +use embassy_net_nrf91::{context, Runner, State, TraceBuffer, TraceReader}; +use embassy_nrf::buffered_uarte::{self, BufferedUarteTx}; +use embassy_nrf::gpio::{AnyPin, Level, Output, OutputDrive, Pin}; +use embassy_nrf::uarte::Baudrate; +use embassy_nrf::{bind_interrupts, interrupt, peripherals, uarte}; +use embassy_time::{Duration, Timer}; +use embedded_io_async::Write; +use heapless::Vec; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[interrupt] +fn IPC() { + embassy_net_nrf91::on_ipc_irq(); +} + +bind_interrupts!(struct Irqs { + UARTE0_SPIM0_SPIS0_TWIM0_TWIS0 => buffered_uarte::InterruptHandler; +}); + +#[embassy_executor::task] +async fn trace_task(mut uart: BufferedUarteTx<'static, peripherals::SERIAL0>, reader: TraceReader<'static>) -> ! { + let mut rx = [0u8; 1024]; + loop { + let n = reader.read(&mut rx[..]).await; + unwrap!(uart.write_all(&rx[..n]).await); + } +} + +#[embassy_executor::task] +async fn modem_task(runner: Runner<'static>) -> ! { + runner.run().await +} + +#[embassy_executor::task] +async fn net_task(mut runner: embassy_net::Runner<'static, embassy_net_nrf91::NetDriver<'static>>) -> ! { + runner.run().await +} + +#[embassy_executor::task] +async fn control_task( + control: &'static context::Control<'static>, + config: context::Config<'static>, + stack: Stack<'static>, +) { + unwrap!(control.configure(&config).await); + unwrap!( + control + .run(|status| { + stack.set_config_v4(status_to_config(status)); + }) + .await + ); +} + +fn status_to_config(status: &Status) -> embassy_net::ConfigV4 { + let Some(IpAddr::V4(addr)) = status.ip else { + panic!("Unexpected IP address"); + }; + + let gateway = match status.gateway { + Some(IpAddr::V4(addr)) => Some(addr), + _ => None, + }; + + let mut dns_servers = Vec::new(); + for dns in status.dns.iter() { + if let IpAddr::V4(ip) = dns { + unwrap!(dns_servers.push(*ip)); + } + } + + embassy_net::ConfigV4::Static(embassy_net::StaticConfigV4 { + address: Ipv4Cidr::new(addr, 32), + gateway, + dns_servers, + }) +} + +#[embassy_executor::task] +async fn blink_task(pin: AnyPin) { + let mut led = Output::new(pin, Level::Low, OutputDrive::Standard); + loop { + led.set_high(); + Timer::after_millis(1000).await; + led.set_low(); + Timer::after_millis(1000).await; + } +} + +extern "C" { + static __start_ipc: u8; + static __end_ipc: u8; +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_nrf::init(Default::default()); + + info!("Hello World!"); + + unwrap!(spawner.spawn(blink_task(p.P0_02.degrade()))); + + let ipc_mem = unsafe { + let ipc_start = &__start_ipc as *const u8 as *mut MaybeUninit; + let ipc_end = &__end_ipc as *const u8 as *mut MaybeUninit; + let ipc_len = ipc_end.offset_from(ipc_start) as usize; + slice::from_raw_parts_mut(ipc_start, ipc_len) + }; + + static mut TRACE_BUF: [u8; 4096] = [0u8; 4096]; + let mut config = uarte::Config::default(); + config.baudrate = Baudrate::BAUD1M; + let uart = BufferedUarteTx::new( + //let trace_uart = BufferedUarteTx::new( + unsafe { peripherals::SERIAL0::steal() }, + Irqs, + unsafe { peripherals::P0_01::steal() }, + //unsafe { peripherals::P0_14::steal() }, + config, + unsafe { &mut *addr_of_mut!(TRACE_BUF) }, + ); + + static STATE: StaticCell = StaticCell::new(); + static TRACE: StaticCell = StaticCell::new(); + let (device, control, runner, tracer) = + embassy_net_nrf91::new_with_trace(STATE.init(State::new()), ipc_mem, TRACE.init(TraceBuffer::new())).await; + unwrap!(spawner.spawn(modem_task(runner))); + unwrap!(spawner.spawn(trace_task(uart, tracer))); + + let config = embassy_net::Config::default(); + + // Generate "random" seed. nRF91 has no RNG, TODO figure out something... + let seed = 123456; + + // Init network stack + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::<2>::new()), seed); + + unwrap!(spawner.spawn(net_task(runner))); + + static CONTROL: StaticCell> = StaticCell::new(); + let control = CONTROL.init(context::Control::new(control, 0).await); + + unwrap!(spawner.spawn(control_task( + control, + context::Config { + apn: b"iot.nat.es", + auth_prot: context::AuthProt::Pap, + auth: Some((b"orange", b"orange")), + pin: None, + }, + stack + ))); + + stack.wait_config_up().await; + + let mut rx_buffer = [0; 4096]; + let mut tx_buffer = [0; 4096]; + loop { + let mut socket = embassy_net::tcp::TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer); + socket.set_timeout(Some(Duration::from_secs(10))); + + info!("Connecting..."); + let host_addr = embassy_net::Ipv4Address::from_str("45.79.112.203").unwrap(); + if let Err(e) = socket.connect((host_addr, 4242)).await { + warn!("connect error: {:?}", e); + Timer::after_secs(10).await; + continue; + } + info!("Connected to {:?}", socket.remote_endpoint()); + + let msg = b"Hello world!\n"; + for _ in 0..10 { + if let Err(e) = socket.write_all(msg).await { + warn!("write error: {:?}", e); + break; + } + info!("txd: {}", core::str::from_utf8(msg).unwrap()); + Timer::after_secs(1).await; + } + Timer::after_secs(4).await; + } +} diff --git a/examples/rp/Cargo.toml b/examples/rp/Cargo.toml index e1092dba4..b45f5040a 100644 --- a/examples/rp/Cargo.toml +++ b/examples/rp/Cargo.toml @@ -6,49 +6,77 @@ license = "MIT OR Apache-2.0" [dependencies] -embassy-embedded-hal = { version = "0.1.0", path = "../../embassy-embedded-hal", features = ["defmt"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } -embassy-rp = { version = "0.1.0", path = "../../embassy-rp", features = ["defmt", "unstable-pac", "time-driver", "critical-section-impl"] } -embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } -embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "udp", "dhcpv4", "medium-ethernet"] } +embassy-embedded-hal = { version = "0.2.0", path = "../../embassy-embedded-hal", features = ["defmt"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-98304", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } +embassy-rp = { version = "0.2.0", path = "../../embassy-rp", features = ["defmt", "unstable-pac", "time-driver", "critical-section-impl", "rp2040"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "udp", "raw", "dhcpv4", "medium-ethernet", "dns", "proto-ipv4", "proto-ipv6", "multicast"] } embassy-net-wiznet = { version = "0.1.0", path = "../../embassy-net-wiznet", features = ["defmt"] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } -embassy-usb-logger = { version = "0.1.0", path = "../../embassy-usb-logger" } -cyw43 = { version = "0.1.0", path = "../../cyw43", features = ["defmt", "firmware-logs"] } -cyw43-pio = { version = "0.1.0", path = "../../cyw43-pio", features = ["defmt", "overclock"] } +embassy-usb-logger = { version = "0.2.0", path = "../../embassy-usb-logger" } +cyw43 = { version = "0.2.0", path = "../../cyw43", features = ["defmt", "firmware-logs", "bluetooth"] } +cyw43-pio = { version = "0.2.0", path = "../../cyw43-pio", features = ["defmt"] } defmt = "0.3" defmt-rtt = "0.4" fixed = "1.23.1" fixed-macro = "1.2" +# for web request example +reqwless = { version = "0.13.0", features = ["defmt"] } +serde = { version = "1.0.203", default-features = false, features = ["derive"] } +serde-json-core = "0.5.1" + +# for assign resources example +assign-resources = { git = "https://github.com/adamgreig/assign-resources", rev = "94ad10e2729afdf0fd5a77cd12e68409a982f58a" } + #cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] } cortex-m = { version = "0.7.6", features = ["inline-asm"] } cortex-m-rt = "0.7.0" +critical-section = "1.1" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await", "cfg-target-has-atomic", "unstable"] } -display-interface-spi = "0.4.1" -embedded-graphics = "0.7.1" -st7789 = "0.6.1" -display-interface = "0.4.1" +display-interface-spi = "0.5.0" +embedded-graphics = "0.8.1" +mipidsi = "0.8.0" +display-interface = "0.5.0" byte-slice-cast = { version = "1.2.0", default-features = false } -smart-leds = "0.3.0" +smart-leds = "0.4.0" heapless = "0.8" -usbd-hid = "0.6.1" +usbd-hid = "0.8.1" embedded-hal-1 = { package = "embedded-hal", version = "1.0" } embedded-hal-async = "1.0" embedded-hal-bus = { version = "0.1", features = ["async"] } embedded-io-async = { version = "0.6.1", features = ["defmt-03"] } embedded-storage = { version = "0.3" } -static_cell = "2" +static_cell = "2.1" portable-atomic = { version = "1.5", features = ["critical-section"] } log = "0.4" pio-proc = "0.2" pio = "0.2.1" rand = { version = "0.8.5", default-features = false } +embedded-sdmmc = "0.7.0" + +bt-hci = { version = "0.1.0", default-features = false, features = ["defmt"] } +trouble-host = { version = "0.1.0", features = ["defmt", "gatt"] } [profile.release] debug = 2 +lto = true +opt-level = 'z' + +[profile.dev] +debug = 2 +lto = true +opt-level = "z" + +[patch.crates-io] +trouble-host = { git = "https://github.com/embassy-rs/trouble.git", rev = "4b8c0f499b34e46ca23a56e2d1640ede371722cf" } +embassy-executor = { path = "../../embassy-executor" } +embassy-sync = { path = "../../embassy-sync" } +embassy-futures = { path = "../../embassy-futures" } +embassy-time = { path = "../../embassy-time" } +embassy-time-driver = { path = "../../embassy-time-driver" } +embassy-embedded-hal = { path = "../../embassy-embedded-hal" } diff --git a/examples/rp/src/bin/adc_dma.rs b/examples/rp/src/bin/adc_dma.rs new file mode 100644 index 000000000..f755cf5bf --- /dev/null +++ b/examples/rp/src/bin/adc_dma.rs @@ -0,0 +1,54 @@ +//! This example shows how to use the RP2040 ADC with DMA, both single- and multichannel reads. +//! For multichannel, the samples are interleaved in the buffer: +//! `[ch1, ch2, ch3, ch4, ch1, ch2, ch3, ch4, ...]` +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::adc::{Adc, Channel, Config, InterruptHandler}; +use embassy_rp::bind_interrupts; +use embassy_rp::gpio::Pull; +use embassy_time::{Duration, Ticker}; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + ADC_IRQ_FIFO => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + info!("Here we go!"); + + let mut adc = Adc::new(p.ADC, Irqs, Config::default()); + let mut dma = p.DMA_CH0; + let mut pin = Channel::new_pin(p.PIN_26, Pull::Up); + let mut pins = [ + Channel::new_pin(p.PIN_27, Pull::Down), + Channel::new_pin(p.PIN_28, Pull::None), + Channel::new_pin(p.PIN_29, Pull::Up), + Channel::new_temp_sensor(p.ADC_TEMP_SENSOR), + ]; + + const BLOCK_SIZE: usize = 100; + const NUM_CHANNELS: usize = 4; + let mut ticker = Ticker::every(Duration::from_secs(1)); + loop { + // Read 100 samples from a single channel + let mut buf = [0_u16; BLOCK_SIZE]; + let div = 479; // 100kHz sample rate (48Mhz / 100kHz - 1) + adc.read_many(&mut pin, &mut buf, div, &mut dma).await.unwrap(); + info!("single: {:?} ...etc", buf[..8]); + + // Read 100 samples from 4 channels interleaved + let mut buf = [0_u16; { BLOCK_SIZE * NUM_CHANNELS }]; + let div = 119; // 100kHz sample rate (48Mhz / 100kHz * 4ch - 1) + adc.read_many_multichannel(&mut pins, &mut buf, div, &mut dma) + .await + .unwrap(); + info!("multi: {:?} ...etc", buf[..NUM_CHANNELS * 2]); + + ticker.next().await; + } +} diff --git a/examples/rp/src/bin/assign_resources.rs b/examples/rp/src/bin/assign_resources.rs new file mode 100644 index 000000000..ff6eff4a2 --- /dev/null +++ b/examples/rp/src/bin/assign_resources.rs @@ -0,0 +1,79 @@ +//! This example demonstrates how to assign resources to multiple tasks by splitting up the peripherals. +//! It is not about sharing the same resources between tasks, see sharing.rs for that or head to https://embassy.dev/book/#_sharing_peripherals_between_tasks) +//! Of course splitting up resources and sharing resources can be combined, yet this example is only about splitting up resources. +//! +//! There are basically two ways we demonstrate here: +//! 1) Assigning resources to a task by passing parts of the peripherals +//! 2) Assigning resources to a task by passing a struct with the split up peripherals, using the assign-resources macro +//! +//! using four LEDs on Pins 10, 11, 20 and 21 + +#![no_std] +#![no_main] + +use assign_resources::assign_resources; +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::gpio::{Level, Output}; +use embassy_rp::peripherals::{self, PIN_20, PIN_21}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + // initialize the peripherals + let p = embassy_rp::init(Default::default()); + + // 1) Assigning a resource to a task by passing parts of the peripherals. + spawner + .spawn(double_blinky_manually_assigned(spawner, p.PIN_20, p.PIN_21)) + .unwrap(); + + // 2) Using the assign-resources macro to assign resources to a task. + // we perform the split, see further below for the definition of the resources struct + let r = split_resources!(p); + // and then we can use them + spawner.spawn(double_blinky_macro_assigned(spawner, r.leds)).unwrap(); +} + +// 1) Assigning a resource to a task by passing parts of the peripherals. +#[embassy_executor::task] +async fn double_blinky_manually_assigned(_spawner: Spawner, pin_20: PIN_20, pin_21: PIN_21) { + let mut led_20 = Output::new(pin_20, Level::Low); + let mut led_21 = Output::new(pin_21, Level::High); + + loop { + info!("toggling leds"); + led_20.toggle(); + led_21.toggle(); + Timer::after_secs(1).await; + } +} + +// 2) Using the assign-resources macro to assign resources to a task. +// first we define the resources we want to assign to the task using the assign_resources! macro +// basically this will split up the peripherals struct into smaller structs, that we define here +// naming is up to you, make sure your future self understands what you did here +assign_resources! { + leds: Leds{ + led_10: PIN_10, + led_11: PIN_11, + } + // add more resources to more structs if needed, for example defining one struct for each task +} +// this could be done in another file and imported here, but for the sake of simplicity we do it here +// see https://github.com/adamgreig/assign-resources for more information + +// 2) Using the split resources in a task +#[embassy_executor::task] +async fn double_blinky_macro_assigned(_spawner: Spawner, r: Leds) { + let mut led_10 = Output::new(r.led_10, Level::Low); + let mut led_11 = Output::new(r.led_11, Level::High); + + loop { + info!("toggling leds"); + led_10.toggle(); + led_11.toggle(); + Timer::after_secs(1).await; + } +} diff --git a/examples/rp/src/bin/bluetooth.rs b/examples/rp/src/bin/bluetooth.rs new file mode 100644 index 000000000..7524e7929 --- /dev/null +++ b/examples/rp/src/bin/bluetooth.rs @@ -0,0 +1,150 @@ +//! This example test the RP Pico W on board LED. +//! +//! It does not work with the RP Pico board. See blinky.rs. + +#![no_std] +#![no_main] + +use bt_hci::controller::ExternalController; +use cyw43_pio::PioSpi; +use defmt::*; +use embassy_executor::Spawner; +use embassy_futures::join::join3; +use embassy_rp::bind_interrupts; +use embassy_rp::gpio::{Level, Output}; +use embassy_rp::peripherals::{DMA_CH0, PIO0}; +use embassy_rp::pio::{InterruptHandler, Pio}; +use embassy_sync::blocking_mutex::raw::NoopRawMutex; +use embassy_time::{Duration, Timer}; +use static_cell::StaticCell; +use trouble_host::advertise::{AdStructure, Advertisement, BR_EDR_NOT_SUPPORTED, LE_GENERAL_DISCOVERABLE}; +use trouble_host::attribute::{AttributeTable, CharacteristicProp, Service, Uuid}; +use trouble_host::gatt::GattEvent; +use trouble_host::{Address, BleHost, BleHostResources, PacketQos}; +use {defmt_rtt as _, embassy_time as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +#[embassy_executor::task] +async fn cyw43_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'static, PIO0, 0, DMA_CH0>>) -> ! { + runner.run().await +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let fw = include_bytes!("../../../../cyw43-firmware/43439A0.bin"); + let clm = include_bytes!("../../../../cyw43-firmware/43439A0_clm.bin"); + let btfw = include_bytes!("../../../../cyw43-firmware/43439A0_btfw.bin"); + + // To make flashing faster for development, you may want to flash the firmwares independently + // at hardcoded addresses, instead of baking them into the program with `include_bytes!`: + // probe-rs download 43439A0.bin --format bin --chip RP2040 --base-address 0x10100000 + // probe-rs download 43439A0_clm.bin --format bin --chip RP2040 --base-address 0x10140000 + // probe-rs download 43439A0_btfw.bin --format bin --chip RP2040 --base-address 0x10141400 + //let fw = unsafe { core::slice::from_raw_parts(0x10100000 as *const u8, 224190) }; + //let clm = unsafe { core::slice::from_raw_parts(0x10140000 as *const u8, 4752) }; + //let btfw = unsafe { core::slice::from_raw_parts(0x10141400 as *const u8, 6164) }; + + let pwr = Output::new(p.PIN_23, Level::Low); + let cs = Output::new(p.PIN_25, Level::High); + let mut pio = Pio::new(p.PIO0, Irqs); + let spi = PioSpi::new(&mut pio.common, pio.sm0, pio.irq0, cs, p.PIN_24, p.PIN_29, p.DMA_CH0); + + static STATE: StaticCell = StaticCell::new(); + let state = STATE.init(cyw43::State::new()); + let (_net_device, bt_device, mut control, runner) = cyw43::new_with_bluetooth(state, pwr, spi, fw, btfw).await; + unwrap!(spawner.spawn(cyw43_task(runner))); + control.init(clm).await; + + let controller: ExternalController<_, 10> = ExternalController::new(bt_device); + static HOST_RESOURCES: StaticCell> = StaticCell::new(); + let host_resources = HOST_RESOURCES.init(BleHostResources::new(PacketQos::None)); + + let mut ble: BleHost<'_, _> = BleHost::new(controller, host_resources); + + ble.set_random_address(Address::random([0xff, 0x9f, 0x1a, 0x05, 0xe4, 0xff])); + let mut table: AttributeTable<'_, NoopRawMutex, 10> = AttributeTable::new(); + + // Generic Access Service (mandatory) + let id = b"Pico W Bluetooth"; + let appearance = [0x80, 0x07]; + let mut bat_level = [0; 1]; + let handle = { + let mut svc = table.add_service(Service::new(0x1800)); + let _ = svc.add_characteristic_ro(0x2a00, id); + let _ = svc.add_characteristic_ro(0x2a01, &appearance[..]); + svc.build(); + + // Generic attribute service (mandatory) + table.add_service(Service::new(0x1801)); + + // Battery service + let mut svc = table.add_service(Service::new(0x180f)); + + svc.add_characteristic( + 0x2a19, + &[CharacteristicProp::Read, CharacteristicProp::Notify], + &mut bat_level, + ) + .build() + }; + + let mut adv_data = [0; 31]; + AdStructure::encode_slice( + &[ + AdStructure::Flags(LE_GENERAL_DISCOVERABLE | BR_EDR_NOT_SUPPORTED), + AdStructure::ServiceUuids16(&[Uuid::Uuid16([0x0f, 0x18])]), + AdStructure::CompleteLocalName(b"Pico W Bluetooth"), + ], + &mut adv_data[..], + ) + .unwrap(); + + let server = ble.gatt_server(&table); + + info!("Starting advertising and GATT service"); + let _ = join3( + ble.run(), + async { + loop { + match server.next().await { + Ok(GattEvent::Write { handle, connection: _ }) => { + let _ = table.get(handle, |value| { + info!("Write event. Value written: {:?}", value); + }); + } + Ok(GattEvent::Read { .. }) => { + info!("Read event"); + } + Err(e) => { + error!("Error processing GATT events: {:?}", e); + } + } + } + }, + async { + let mut advertiser = ble + .advertise( + &Default::default(), + Advertisement::ConnectableScannableUndirected { + adv_data: &adv_data[..], + scan_data: &[], + }, + ) + .await + .unwrap(); + let conn = advertiser.accept().await.unwrap(); + // Keep connection alive + let mut tick: u8 = 0; + loop { + Timer::after(Duration::from_secs(10)).await; + tick += 1; + server.notify(handle, &conn, &[tick]).await.unwrap(); + } + }, + ) + .await; +} diff --git a/examples/rp/src/bin/ethernet_w5500_multisocket.rs b/examples/rp/src/bin/ethernet_w5500_multisocket.rs index bd52cadca..12003adbe 100644 --- a/examples/rp/src/bin/ethernet_w5500_multisocket.rs +++ b/examples/rp/src/bin/ethernet_w5500_multisocket.rs @@ -36,8 +36,8 @@ async fn ethernet_task( } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static>>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -63,24 +63,24 @@ async fn main(spawner: Spawner) { w5500_int, w5500_reset, ) - .await; + .await + .unwrap(); unwrap!(spawner.spawn(ethernet_task(runner))); // Generate random seed let seed = rng.next_u64(); // Init network stack - static STACK: StaticCell>> = StaticCell::new(); static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( + let (stack, runner) = embassy_net::new( device, embassy_net::Config::dhcpv4(Default::default()), - RESOURCES.init(StackResources::<3>::new()), + RESOURCES.init(StackResources::new()), seed, - )); + ); // Launch network task - unwrap!(spawner.spawn(net_task(&stack))); + unwrap!(spawner.spawn(net_task(runner))); info!("Waiting for DHCP..."); let cfg = wait_for_config(stack).await; @@ -88,12 +88,12 @@ async fn main(spawner: Spawner) { info!("IP address: {:?}", local_addr); // Create two sockets listening to the same port, to handle simultaneous connections - unwrap!(spawner.spawn(listen_task(&stack, 0, 1234))); - unwrap!(spawner.spawn(listen_task(&stack, 1, 1234))); + unwrap!(spawner.spawn(listen_task(stack, 0, 1234))); + unwrap!(spawner.spawn(listen_task(stack, 1, 1234))); } #[embassy_executor::task(pool_size = 2)] -async fn listen_task(stack: &'static Stack>, id: u8, port: u16) { +async fn listen_task(stack: Stack<'static>, id: u8, port: u16) { let mut rx_buffer = [0; 4096]; let mut tx_buffer = [0; 4096]; let mut buf = [0; 4096]; @@ -130,7 +130,7 @@ async fn listen_task(stack: &'static Stack>, id: u8, port: u16) } } -async fn wait_for_config(stack: &'static Stack>) -> embassy_net::StaticConfigV4 { +async fn wait_for_config(stack: Stack<'static>) -> embassy_net::StaticConfigV4 { loop { if let Some(config) = stack.config_v4() { return config.clone(); diff --git a/examples/rp/src/bin/ethernet_w5500_tcp_client.rs b/examples/rp/src/bin/ethernet_w5500_tcp_client.rs index 3e4fbd2e6..d66a43a88 100644 --- a/examples/rp/src/bin/ethernet_w5500_tcp_client.rs +++ b/examples/rp/src/bin/ethernet_w5500_tcp_client.rs @@ -38,8 +38,8 @@ async fn ethernet_task( } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static>>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -66,24 +66,24 @@ async fn main(spawner: Spawner) { w5500_int, w5500_reset, ) - .await; + .await + .unwrap(); unwrap!(spawner.spawn(ethernet_task(runner))); // Generate random seed let seed = rng.next_u64(); // Init network stack - static STACK: StaticCell>> = StaticCell::new(); - static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new( device, embassy_net::Config::dhcpv4(Default::default()), - RESOURCES.init(StackResources::<2>::new()), + RESOURCES.init(StackResources::new()), seed, - )); + ); // Launch network task - unwrap!(spawner.spawn(net_task(&stack))); + unwrap!(spawner.spawn(net_task(runner))); info!("Waiting for DHCP..."); let cfg = wait_for_config(stack).await; @@ -118,7 +118,7 @@ async fn main(spawner: Spawner) { } } -async fn wait_for_config(stack: &'static Stack>) -> embassy_net::StaticConfigV4 { +async fn wait_for_config(stack: Stack<'static>) -> embassy_net::StaticConfigV4 { loop { if let Some(config) = stack.config_v4() { return config.clone(); diff --git a/examples/rp/src/bin/ethernet_w5500_tcp_server.rs b/examples/rp/src/bin/ethernet_w5500_tcp_server.rs index 5532851f3..97d9bd4c9 100644 --- a/examples/rp/src/bin/ethernet_w5500_tcp_server.rs +++ b/examples/rp/src/bin/ethernet_w5500_tcp_server.rs @@ -37,8 +37,8 @@ async fn ethernet_task( } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static>>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -65,24 +65,24 @@ async fn main(spawner: Spawner) { w5500_int, w5500_reset, ) - .await; + .await + .unwrap(); unwrap!(spawner.spawn(ethernet_task(runner))); // Generate random seed let seed = rng.next_u64(); // Init network stack - static STACK: StaticCell>> = StaticCell::new(); - static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new( device, embassy_net::Config::dhcpv4(Default::default()), - RESOURCES.init(StackResources::<2>::new()), + RESOURCES.init(StackResources::new()), seed, - )); + ); // Launch network task - unwrap!(spawner.spawn(net_task(&stack))); + unwrap!(spawner.spawn(net_task(runner))); info!("Waiting for DHCP..."); let cfg = wait_for_config(stack).await; @@ -127,7 +127,7 @@ async fn main(spawner: Spawner) { } } -async fn wait_for_config(stack: &'static Stack>) -> embassy_net::StaticConfigV4 { +async fn wait_for_config(stack: Stack<'static>) -> embassy_net::StaticConfigV4 { loop { if let Some(config) = stack.config_v4() { return config.clone(); diff --git a/examples/rp/src/bin/ethernet_w5500_udp.rs b/examples/rp/src/bin/ethernet_w5500_udp.rs index adb1d8941..b1b5f9758 100644 --- a/examples/rp/src/bin/ethernet_w5500_udp.rs +++ b/examples/rp/src/bin/ethernet_w5500_udp.rs @@ -36,8 +36,8 @@ async fn ethernet_task( } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static>>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -63,24 +63,24 @@ async fn main(spawner: Spawner) { w5500_int, w5500_reset, ) - .await; + .await + .unwrap(); unwrap!(spawner.spawn(ethernet_task(runner))); // Generate random seed let seed = rng.next_u64(); // Init network stack - static STACK: StaticCell>> = StaticCell::new(); - static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new( device, embassy_net::Config::dhcpv4(Default::default()), - RESOURCES.init(StackResources::<2>::new()), + RESOURCES.init(StackResources::new()), seed, - )); + ); // Launch network task - unwrap!(spawner.spawn(net_task(&stack))); + unwrap!(spawner.spawn(net_task(runner))); info!("Waiting for DHCP..."); let cfg = wait_for_config(stack).await; @@ -107,7 +107,7 @@ async fn main(spawner: Spawner) { } } -async fn wait_for_config(stack: &'static Stack>) -> embassy_net::StaticConfigV4 { +async fn wait_for_config(stack: Stack<'static>) -> embassy_net::StaticConfigV4 { loop { if let Some(config) = stack.config_v4() { return config.clone(); diff --git a/examples/rp/src/bin/i2c_async_embassy.rs b/examples/rp/src/bin/i2c_async_embassy.rs new file mode 100644 index 000000000..a65b71b9f --- /dev/null +++ b/examples/rp/src/bin/i2c_async_embassy.rs @@ -0,0 +1,85 @@ +//! This example shows how to communicate asynchronous using i2c with external chip. +//! +//! It's using embassy's functions directly instead of traits from embedded_hal_async::i2c::I2c. +//! While most of i2c devices are addressed using 7 bits, an extension allows 10 bits too. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_rp::i2c::InterruptHandler; +use {defmt_rtt as _, panic_probe as _}; + +// Our anonymous hypotetical temperature sensor could be: +// a 12-bit sensor, with 100ms startup time, range of -40*C - 125*C, and precision 0.25*C +// It requires no configuration or calibration, works with all i2c bus speeds, +// never stretches clock or does anything complicated. Replies with one u16. +// It requires only one write to take it out of suspend mode, and stays on. +// Often result would be just on 12 bits, but here we'll simplify it to 16. + +enum UncomplicatedSensorId { + A(UncomplicatedSensorU8), + B(UncomplicatedSensorU16), +} +enum UncomplicatedSensorU8 { + First = 0x48, +} +enum UncomplicatedSensorU16 { + Other = 0x0049, +} + +impl Into for UncomplicatedSensorU16 { + fn into(self) -> u16 { + self as u16 + } +} +impl Into for UncomplicatedSensorU8 { + fn into(self) -> u16 { + 0x48 + } +} +impl From for u16 { + fn from(t: UncomplicatedSensorId) -> Self { + match t { + UncomplicatedSensorId::A(x) => x.into(), + UncomplicatedSensorId::B(x) => x.into(), + } + } +} + +embassy_rp::bind_interrupts!(struct Irqs { + I2C1_IRQ => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_task_spawner: embassy_executor::Spawner) { + let p = embassy_rp::init(Default::default()); + let sda = p.PIN_14; + let scl = p.PIN_15; + let config = embassy_rp::i2c::Config::default(); + let mut bus = embassy_rp::i2c::I2c::new_async(p.I2C1, scl, sda, Irqs, config); + + const WAKEYWAKEY: u16 = 0xBABE; + let mut result: [u8; 2] = [0, 0]; + // wait for sensors to initialize + embassy_time::Timer::after(embassy_time::Duration::from_millis(100)).await; + + let _res_1 = bus + .write_async(UncomplicatedSensorU8::First, WAKEYWAKEY.to_be_bytes()) + .await; + let _res_2 = bus + .write_async(UncomplicatedSensorU16::Other, WAKEYWAKEY.to_be_bytes()) + .await; + + loop { + let s1 = UncomplicatedSensorId::A(UncomplicatedSensorU8::First); + let s2 = UncomplicatedSensorId::B(UncomplicatedSensorU16::Other); + let sensors = [s1, s2]; + for sensor in sensors { + if bus.read_async(sensor, &mut result).await.is_ok() { + info!("Result {}", u16::from_be_bytes(result.into())); + } + } + embassy_time::Timer::after(embassy_time::Duration::from_millis(200)).await; + } +} diff --git a/examples/rp/src/bin/i2c_slave.rs b/examples/rp/src/bin/i2c_slave.rs index 479f9a16a..9fffb4646 100644 --- a/examples/rp/src/bin/i2c_slave.rs +++ b/examples/rp/src/bin/i2c_slave.rs @@ -26,7 +26,7 @@ async fn device_task(mut dev: i2c_slave::I2cSlave<'static, I2C1>) -> ! { loop { let mut buf = [0u8; 128]; match dev.listen(&mut buf).await { - Ok(i2c_slave::Command::GeneralCall(len)) => info!("Device recieved general call write: {}", buf[..len]), + Ok(i2c_slave::Command::GeneralCall(len)) => info!("Device received general call write: {}", buf[..len]), Ok(i2c_slave::Command::Read) => loop { match dev.respond_to_read(&[state]).await { Ok(x) => match x { @@ -40,9 +40,9 @@ async fn device_task(mut dev: i2c_slave::I2cSlave<'static, I2C1>) -> ! { Err(e) => error!("error while responding {}", e), } }, - Ok(i2c_slave::Command::Write(len)) => info!("Device recieved write: {}", buf[..len]), + Ok(i2c_slave::Command::Write(len)) => info!("Device received write: {}", buf[..len]), Ok(i2c_slave::Command::WriteRead(len)) => { - info!("device recieved write read: {:x}", buf[..len]); + info!("device received write read: {:x}", buf[..len]); match buf[0] { // Set the state 0xC2 => { @@ -110,7 +110,7 @@ async fn main(spawner: Spawner) { let c_sda = p.PIN_1; let c_scl = p.PIN_0; let mut config = i2c::Config::default(); - config.frequency = 5_000; + config.frequency = 1_000_000; let controller = i2c::I2c::new_async(p.I2C0, c_sda, c_scl, Irqs, config); unwrap!(spawner.spawn(controller_task(controller))); diff --git a/examples/rp/src/bin/interrupt.rs b/examples/rp/src/bin/interrupt.rs new file mode 100644 index 000000000..5b9d7027e --- /dev/null +++ b/examples/rp/src/bin/interrupt.rs @@ -0,0 +1,94 @@ +//! This example shows how you can use raw interrupt handlers alongside embassy. +//! The example also showcases some of the options available for sharing resources/data. +//! +//! In the example, an ADC reading is triggered every time the PWM wraps around. +//! The sample data is sent down a channel, to be processed inside a low priority task. +//! The processed data is then used to adjust the PWM duty cycle, once every second. + +#![no_std] +#![no_main] + +use core::cell::{Cell, RefCell}; + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::adc::{self, Adc, Blocking}; +use embassy_rp::gpio::Pull; +use embassy_rp::interrupt; +use embassy_rp::pwm::{Config, Pwm}; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +use embassy_sync::blocking_mutex::Mutex; +use embassy_sync::channel::Channel; +use embassy_time::{Duration, Ticker}; +use portable_atomic::{AtomicU32, Ordering}; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +static COUNTER: AtomicU32 = AtomicU32::new(0); +static PWM: Mutex>> = Mutex::new(RefCell::new(None)); +static ADC: Mutex, adc::Channel)>>> = + Mutex::new(RefCell::new(None)); +static ADC_VALUES: Channel = Channel::new(); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + embassy_rp::pac::SIO.spinlock(31).write_value(1); + let p = embassy_rp::init(Default::default()); + + let adc = Adc::new_blocking(p.ADC, Default::default()); + let p26 = adc::Channel::new_pin(p.PIN_26, Pull::None); + ADC.lock(|a| a.borrow_mut().replace((adc, p26))); + + let pwm = Pwm::new_output_b(p.PWM_SLICE4, p.PIN_25, Default::default()); + PWM.lock(|p| p.borrow_mut().replace(pwm)); + + // Enable the interrupt for pwm slice 4 + embassy_rp::pac::PWM.inte().modify(|w| w.set_ch4(true)); + unsafe { + cortex_m::peripheral::NVIC::unmask(interrupt::PWM_IRQ_WRAP); + } + + // Tasks require their resources to have 'static lifetime + // No Mutex needed when sharing within the same executor/prio level + static AVG: StaticCell> = StaticCell::new(); + let avg = AVG.init(Default::default()); + spawner.must_spawn(processing(avg)); + + let mut ticker = Ticker::every(Duration::from_secs(1)); + loop { + ticker.next().await; + let freq = COUNTER.swap(0, Ordering::Relaxed); + info!("pwm freq: {:?} Hz", freq); + info!("adc average: {:?}", avg.get()); + + // Update the pwm duty cycle, based on the averaged adc reading + let mut config = Config::default(); + config.compare_b = ((avg.get() as f32 / 4095.0) * config.top as f32) as _; + PWM.lock(|p| p.borrow_mut().as_mut().unwrap().set_config(&config)); + } +} + +#[embassy_executor::task] +async fn processing(avg: &'static Cell) { + let mut buffer: heapless::HistoryBuffer = Default::default(); + loop { + let val = ADC_VALUES.receive().await; + buffer.write(val); + let sum: u32 = buffer.iter().map(|x| *x as u32).sum(); + avg.set(sum / buffer.len() as u32); + } +} + +#[interrupt] +fn PWM_IRQ_WRAP() { + critical_section::with(|cs| { + let mut adc = ADC.borrow(cs).borrow_mut(); + let (adc, p26) = adc.as_mut().unwrap(); + let val = adc.blocking_read(p26).unwrap(); + ADC_VALUES.try_send(val).ok(); + + // Clear the interrupt, so we don't immediately re-enter this irq handler + PWM.borrow(cs).borrow_mut().as_mut().unwrap().clear_wrapped(); + }); + COUNTER.fetch_add(1, Ordering::Relaxed); +} diff --git a/examples/rp/src/bin/multicore.rs b/examples/rp/src/bin/multicore.rs index c7b087476..7cb546c91 100644 --- a/examples/rp/src/bin/multicore.rs +++ b/examples/rp/src/bin/multicore.rs @@ -30,10 +30,14 @@ fn main() -> ! { let p = embassy_rp::init(Default::default()); let led = Output::new(p.PIN_25, Level::Low); - spawn_core1(p.CORE1, unsafe { &mut CORE1_STACK }, move || { - let executor1 = EXECUTOR1.init(Executor::new()); - executor1.run(|spawner| unwrap!(spawner.spawn(core1_task(led)))); - }); + spawn_core1( + p.CORE1, + unsafe { &mut *core::ptr::addr_of_mut!(CORE1_STACK) }, + move || { + let executor1 = EXECUTOR1.init(Executor::new()); + executor1.run(|spawner| unwrap!(spawner.spawn(core1_task(led)))); + }, + ); let executor0 = EXECUTOR0.init(Executor::new()); executor0.run(|spawner| unwrap!(spawner.spawn(core0_task()))); diff --git a/examples/rp/src/bin/multiprio.rs b/examples/rp/src/bin/multiprio.rs index 26b80c11d..2b397f97d 100644 --- a/examples/rp/src/bin/multiprio.rs +++ b/examples/rp/src/bin/multiprio.rs @@ -80,7 +80,7 @@ async fn run_med() { info!(" [med] Starting long computation"); // Spin-wait to simulate a long CPU computation - cortex_m::asm::delay(125_000_000); // ~1 second + embassy_time::block_for(embassy_time::Duration::from_secs(1)); // ~1 second let end = Instant::now(); let ms = end.duration_since(start).as_ticks() * 1000 / TICK_HZ; @@ -97,7 +97,7 @@ async fn run_low() { info!("[low] Starting long computation"); // Spin-wait to simulate a long CPU computation - cortex_m::asm::delay(250_000_000); // ~2 seconds + embassy_time::block_for(embassy_time::Duration::from_secs(2)); // ~2 seconds let end = Instant::now(); let ms = end.duration_since(start).as_ticks() * 1000 / TICK_HZ; diff --git a/examples/rp/src/bin/orchestrate_tasks.rs b/examples/rp/src/bin/orchestrate_tasks.rs new file mode 100644 index 000000000..0e21d5833 --- /dev/null +++ b/examples/rp/src/bin/orchestrate_tasks.rs @@ -0,0 +1,318 @@ +//! This example demonstrates some approaches to communicate between tasks in order to orchestrate the state of the system. +//! +//! We demonstrate how to: +//! - use a channel to send messages between tasks, in this case here in order to have one task control the state of the system. +//! - use a signal to terminate a task. +//! - use command channels to send commands to another task. +//! - use different ways to receive messages, from a straightforwar awaiting on one channel to a more complex awaiting on multiple futures. +//! +//! There are more patterns to orchestrate tasks, this is just one example. +//! +//! We will use these tasks to generate example "state information": +//! - a task that generates random numbers in intervals of 60s +//! - a task that generates random numbers in intervals of 30s +//! - a task that generates random numbers in intervals of 90s +//! - a task that notifies about being attached/disattached from usb power +//! - a task that measures vsys voltage in intervals of 30s +//! - a task that consumes the state information and reacts to it + +#![no_std] +#![no_main] + +use assign_resources::assign_resources; +use defmt::*; +use embassy_executor::Spawner; +use embassy_futures::select::{select, Either}; +use embassy_rp::adc::{Adc, Channel, Config, InterruptHandler}; +use embassy_rp::clocks::RoscRng; +use embassy_rp::gpio::{Input, Pull}; +use embassy_rp::{bind_interrupts, peripherals}; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +use embassy_sync::{channel, signal}; +use embassy_time::{Duration, Timer}; +use rand::RngCore; +use {defmt_rtt as _, panic_probe as _}; + +// This is just some preparation, see example `assign_resources.rs` for more information on this. We prep the rresources that we will be using in different tasks. +// **Note**: This will not work with a board that has a wifi chip, because the wifi chip uses pins 24 and 29 for its own purposes. A way around this in software +// is not trivial, at least if you intend to use wifi, too. Workaround is to wire from vsys and vbus pins to appropriate pins on the board through a voltage divider. Then use those pins. +// For this example it will not matter much, the concept of what we are showing remains valid. +assign_resources! { + vsys: Vsys { + adc: ADC, + pin_29: PIN_29, + }, + vbus: Vbus { + pin_24: PIN_24, + }, +} + +bind_interrupts!(struct Irqs { + ADC_IRQ_FIFO => InterruptHandler; +}); + +/// This is the type of Events that we will send from the worker tasks to the orchestrating task. +enum Events { + UsbPowered(bool), + VsysVoltage(f32), + FirstRandomSeed(u32), + SecondRandomSeed(u32), + ThirdRandomSeed(u32), + ResetFirstRandomSeed, +} + +/// This is the type of Commands that we will send from the orchestrating task to the worker tasks. +/// Note that we are lazy here and only have one command, you might want to have more. +enum Commands { + /// This command will stop the appropriate worker task + Stop, +} + +/// This is the state of the system, we will use this to orchestrate the system. This is a simple example, in a real world application this would be more complex. +#[derive(Default, Debug, Clone, Format)] +struct State { + usb_powered: bool, + vsys_voltage: f32, + first_random_seed: u32, + second_random_seed: u32, + third_random_seed: u32, + times_we_got_first_random_seed: u8, + maximum_times_we_want_first_random_seed: u8, +} + +impl State { + fn new() -> Self { + Self { + usb_powered: false, + vsys_voltage: 0.0, + first_random_seed: 0, + second_random_seed: 0, + third_random_seed: 0, + times_we_got_first_random_seed: 0, + maximum_times_we_want_first_random_seed: 3, + } + } +} + +/// Channel for the events that we want the orchestrator to react to, all state events are of the type Enum Events. +/// We use a channel with an arbitrary size of 10, the precise size of the queue depends on your use case. This depends on how many events we +/// expect to be generated in a given time frame and how fast the orchestrator can react to them. And then if we rather want the senders to wait for +/// new slots in the queue or if we want the orchestrator to have a backlog of events to process. In this case here we expect to always be enough slots +/// in the queue, so the worker tasks can in all nominal cases send their events and continue with their work without waiting. +/// For the events we - in this case here - do not want to loose any events, so a channel is a good choice. See embassy_sync docs for other options. +static EVENT_CHANNEL: channel::Channel = channel::Channel::new(); + +/// Signal for stopping the first random signal task. We use a signal here, because we need no queue. It is suffiient to have one signal active. +static STOP_FIRST_RANDOM_SIGNAL: signal::Signal = signal::Signal::new(); + +/// Channel for the state that we want the consumer task to react to. We use a channel here, because we want to have a queue of state changes, although +/// we want the queue to be of size 1, because we want to finish rwacting to the state change before the next one comes in. This is just a design choice +/// and depends on your use case. +static CONSUMER_CHANNEL: channel::Channel = channel::Channel::new(); + +// And now we can put all this into use + +/// This is the main task, that will not do very much besides spawning the other tasks. This is a design choice, you could do the +/// orchestrating here. This is to show that we do not need a main loop here, the system will run indefinitely as long as at least one task is running. +#[embassy_executor::main] +async fn main(spawner: Spawner) { + // initialize the peripherals + let p = embassy_rp::init(Default::default()); + // split the resources, for convenience - see above + let r = split_resources! {p}; + + // spawn the tasks + spawner.spawn(orchestrate(spawner)).unwrap(); + spawner.spawn(random_60s(spawner)).unwrap(); + spawner.spawn(random_90s(spawner)).unwrap(); + spawner.spawn(usb_power(spawner, r.vbus)).unwrap(); + spawner.spawn(vsys_voltage(spawner, r.vsys)).unwrap(); + spawner.spawn(consumer(spawner)).unwrap(); +} + +/// This is the task handling the system state and orchestrating the other tasks. WEe can regard this as the "main loop" of the system. +#[embassy_executor::task] +async fn orchestrate(_spawner: Spawner) { + let mut state = State::new(); + + // we need to have a receiver for the events + let receiver = EVENT_CHANNEL.receiver(); + + // and we need a sender for the consumer task + let state_sender = CONSUMER_CHANNEL.sender(); + + loop { + // we await on the receiver, this will block until a new event is available + // as an alternative to this, we could also await on multiple channels, this would block until at least one of the channels has an event + // see the embassy_futures docs: https://docs.embassy.dev/embassy-futures/git/default/select/index.html + // The task random_30s does a select, if you want to have a look at that. + // Another reason to use select may also be that we want to have a timeout, so we can react to the absence of events within a time frame. + // We keep it simple here. + let event = receiver.receive().await; + + // react to the events + match event { + Events::UsbPowered(usb_powered) => { + // update the state and/or react to the event here + state.usb_powered = usb_powered; + info!("Usb powered: {}", usb_powered); + } + Events::VsysVoltage(voltage) => { + // update the state and/or react to the event here + state.vsys_voltage = voltage; + info!("Vsys voltage: {}", voltage); + } + Events::FirstRandomSeed(seed) => { + // update the state and/or react to the event here + state.first_random_seed = seed; + // here we change some meta state, we count how many times we got the first random seed + state.times_we_got_first_random_seed += 1; + info!( + "First random seed: {}, and that was iteration {} of receiving this.", + seed, &state.times_we_got_first_random_seed + ); + } + Events::SecondRandomSeed(seed) => { + // update the state and/or react to the event here + state.second_random_seed = seed; + info!("Second random seed: {}", seed); + } + Events::ThirdRandomSeed(seed) => { + // update the state and/or react to the event here + state.third_random_seed = seed; + info!("Third random seed: {}", seed); + } + Events::ResetFirstRandomSeed => { + // update the state and/or react to the event here + state.times_we_got_first_random_seed = 0; + state.first_random_seed = 0; + info!("Resetting the first random seed counter"); + } + } + // we now have an altered state + // there is a crate for detecting field changes on crates.io (https://crates.io/crates/fieldset) that might be useful here + // for now we just keep it simple + + // we send the state to the consumer task + // since the channel has a size of 1, this will block until the consumer task has received the state, which is what we want here in this example + // **Note:** It is bad design to send too much data between tasks, with no clear definition of what "too much" is. In this example we send the + // whole state, in a real world application you might want to send only the data, that is relevant to the consumer task AND only when it has changed. + // We keep it simple here. + state_sender.send(state.clone()).await; + } +} + +/// This task will consume the state information and react to it. This is a simple example, in a real world application this would be more complex +/// and we could have multiple consumer tasks, each reacting to different parts of the state. +#[embassy_executor::task] +async fn consumer(spawner: Spawner) { + // we need to have a receiver for the state + let receiver = CONSUMER_CHANNEL.receiver(); + let sender = EVENT_CHANNEL.sender(); + loop { + // we await on the receiver, this will block until a new state is available + let state = receiver.receive().await; + // react to the state, in this case here we just log it + info!("The consumer has reveived this state: {:?}", &state); + + // here we react to the state, in this case here we want to start or stop the first random signal task depending on the state of the system + match state.times_we_got_first_random_seed { + max if max == state.maximum_times_we_want_first_random_seed => { + info!("Stopping the first random signal task"); + // we send a command to the task + STOP_FIRST_RANDOM_SIGNAL.signal(Commands::Stop); + // we notify the orchestrator that we have sent the command + sender.send(Events::ResetFirstRandomSeed).await; + } + 0 => { + // we start the task, which presents us with an interesting problem, because we may return here before the task has started + // here we just try and log if the task has started, in a real world application you might want to handle this more gracefully + info!("Starting the first random signal task"); + match spawner.spawn(random_30s(spawner)) { + Ok(_) => info!("Successfully spawned random_30s task"), + Err(e) => info!("Failed to spawn random_30s task: {:?}", e), + } + } + _ => {} + } + } +} + +/// This task will generate random numbers in intervals of 30s +/// The task will terminate after it has received a command signal to stop, see the orchestrate task for that. +/// Note that we are not spawning this task from main, as we will show how such a task can be spawned and closed dynamically. +#[embassy_executor::task] +async fn random_30s(_spawner: Spawner) { + let mut rng = RoscRng; + let sender = EVENT_CHANNEL.sender(); + loop { + // we either await on the timer or the signal, whichever comes first. + let futures = select(Timer::after(Duration::from_secs(30)), STOP_FIRST_RANDOM_SIGNAL.wait()).await; + match futures { + Either::First(_) => { + // we received are operating on the timer + info!("30s are up, generating random number"); + let random_number = rng.next_u32(); + sender.send(Events::FirstRandomSeed(random_number)).await; + } + Either::Second(_) => { + // we received the signal to stop + info!("Received signal to stop, goodbye!"); + break; + } + } + } +} + +/// This task will generate random numbers in intervals of 60s +#[embassy_executor::task] +async fn random_60s(_spawner: Spawner) { + let mut rng = RoscRng; + let sender = EVENT_CHANNEL.sender(); + loop { + Timer::after(Duration::from_secs(60)).await; + let random_number = rng.next_u32(); + sender.send(Events::SecondRandomSeed(random_number)).await; + } +} + +/// This task will generate random numbers in intervals of 90s +#[embassy_executor::task] +async fn random_90s(_spawner: Spawner) { + let mut rng = RoscRng; + let sender = EVENT_CHANNEL.sender(); + loop { + Timer::after(Duration::from_secs(90)).await; + let random_number = rng.next_u32(); + sender.send(Events::ThirdRandomSeed(random_number)).await; + } +} + +/// This task will notify if we are connected to usb power +#[embassy_executor::task] +pub async fn usb_power(_spawner: Spawner, r: Vbus) { + let mut vbus_in = Input::new(r.pin_24, Pull::None); + let sender = EVENT_CHANNEL.sender(); + loop { + sender.send(Events::UsbPowered(vbus_in.is_high())).await; + vbus_in.wait_for_any_edge().await; + } +} + +/// This task will measure the vsys voltage in intervals of 30s +#[embassy_executor::task] +pub async fn vsys_voltage(_spawner: Spawner, r: Vsys) { + let mut adc = Adc::new(r.adc, Irqs, Config::default()); + let vsys_in = r.pin_29; + let mut channel = Channel::new_pin(vsys_in, Pull::None); + let sender = EVENT_CHANNEL.sender(); + loop { + // read the adc value + let adc_value = adc.read(&mut channel).await.unwrap(); + // convert the adc value to voltage. + // 3.3 is the reference voltage, 3.0 is the factor for the inbuilt voltage divider and 4096 is the resolution of the adc + let voltage = (adc_value as f32) * 3.3 * 3.0 / 4096.0; + sender.send(Events::VsysVoltage(voltage)).await; + Timer::after(Duration::from_secs(30)).await; + } +} diff --git a/examples/rp/src/bin/pio_hd44780.rs b/examples/rp/src/bin/pio_hd44780.rs index 3fab7b5f2..164e6f8d3 100644 --- a/examples/rp/src/bin/pio_hd44780.rs +++ b/examples/rp/src/bin/pio_hd44780.rs @@ -7,13 +7,11 @@ use core::fmt::Write; use embassy_executor::Spawner; -use embassy_rp::dma::{AnyChannel, Channel}; +use embassy_rp::bind_interrupts; use embassy_rp::peripherals::PIO0; -use embassy_rp::pio::{ - Config, Direction, FifoJoin, InterruptHandler, Pio, PioPin, ShiftConfig, ShiftDirection, StateMachine, -}; +use embassy_rp::pio::{InterruptHandler, Pio}; +use embassy_rp::pio_programs::hd44780::{PioHD44780, PioHD44780CommandSequenceProgram, PioHD44780CommandWordProgram}; use embassy_rp::pwm::{self, Pwm}; -use embassy_rp::{bind_interrupts, into_ref, Peripheral, PeripheralRef}; use embassy_time::{Instant, Timer}; use {defmt_rtt as _, panic_probe as _}; @@ -35,7 +33,7 @@ async fn main(_spawner: Spawner) { // allowing direct connection of the display to the RP2040 without level shifters. let p = embassy_rp::init(Default::default()); - let _pwm = Pwm::new_output_b(p.PWM_CH7, p.PIN_15, { + let _pwm = Pwm::new_output_b(p.PWM_SLICE7, p.PIN_15, { let mut c = pwm::Config::default(); c.divider = 125.into(); c.top = 100; @@ -43,8 +41,27 @@ async fn main(_spawner: Spawner) { c }); - let mut hd = HD44780::new( - p.PIO0, Irqs, p.DMA_CH3, p.PIN_0, p.PIN_1, p.PIN_2, p.PIN_3, p.PIN_4, p.PIN_5, p.PIN_6, + let Pio { + mut common, sm0, irq0, .. + } = Pio::new(p.PIO0, Irqs); + + let word_prg = PioHD44780CommandWordProgram::new(&mut common); + let seq_prg = PioHD44780CommandSequenceProgram::new(&mut common); + + let mut hd = PioHD44780::new( + &mut common, + sm0, + irq0, + p.DMA_CH3, + p.PIN_0, + p.PIN_1, + p.PIN_2, + p.PIN_3, + p.PIN_4, + p.PIN_5, + p.PIN_6, + &word_prg, + &seq_prg, ) .await; @@ -68,173 +85,3 @@ async fn main(_spawner: Spawner) { Timer::after_secs(1).await; } } - -pub struct HD44780<'l> { - dma: PeripheralRef<'l, AnyChannel>, - sm: StateMachine<'l, PIO0, 0>, - - buf: [u8; 40], -} - -impl<'l> HD44780<'l> { - pub async fn new( - pio: impl Peripheral

+ 'l, - irq: Irqs, - dma: impl Peripheral

+ 'l, - rs: impl PioPin, - rw: impl PioPin, - e: impl PioPin, - db4: impl PioPin, - db5: impl PioPin, - db6: impl PioPin, - db7: impl PioPin, - ) -> HD44780<'l> { - into_ref!(dma); - - let Pio { - mut common, - mut irq0, - mut sm0, - .. - } = Pio::new(pio, irq); - - // takes command words ( <0:4>) - let prg = pio_proc::pio_asm!( - r#" - .side_set 1 opt - .origin 20 - - loop: - out x, 24 - delay: - jmp x--, delay - out pins, 4 side 1 - out null, 4 side 0 - jmp !osre, loop - irq 0 - "#, - ); - - let rs = common.make_pio_pin(rs); - let rw = common.make_pio_pin(rw); - let e = common.make_pio_pin(e); - let db4 = common.make_pio_pin(db4); - let db5 = common.make_pio_pin(db5); - let db6 = common.make_pio_pin(db6); - let db7 = common.make_pio_pin(db7); - - sm0.set_pin_dirs(Direction::Out, &[&rs, &rw, &e, &db4, &db5, &db6, &db7]); - - let mut cfg = Config::default(); - cfg.use_program(&common.load_program(&prg.program), &[&e]); - cfg.clock_divider = 125u8.into(); - cfg.set_out_pins(&[&db4, &db5, &db6, &db7]); - cfg.shift_out = ShiftConfig { - auto_fill: true, - direction: ShiftDirection::Left, - threshold: 32, - }; - cfg.fifo_join = FifoJoin::TxOnly; - sm0.set_config(&cfg); - - sm0.set_enable(true); - // init to 8 bit thrice - sm0.tx().push((50000 << 8) | 0x30); - sm0.tx().push((5000 << 8) | 0x30); - sm0.tx().push((200 << 8) | 0x30); - // init 4 bit - sm0.tx().push((200 << 8) | 0x20); - // set font and lines - sm0.tx().push((50 << 8) | 0x20); - sm0.tx().push(0b1100_0000); - - irq0.wait().await; - sm0.set_enable(false); - - // takes command sequences ( , data...) - // many side sets are only there to free up a delay bit! - let prg = pio_proc::pio_asm!( - r#" - .origin 27 - .side_set 1 - - .wrap_target - pull side 0 - out x 1 side 0 ; !rs - out y 7 side 0 ; #data - 1 - - ; rs/rw to e: >= 60ns - ; e high time: >= 500ns - ; e low time: >= 500ns - ; read data valid after e falling: ~5ns - ; write data hold after e falling: ~10ns - - loop: - pull side 0 - jmp !x data side 0 - command: - set pins 0b00 side 0 - jmp shift side 0 - data: - set pins 0b01 side 0 - shift: - out pins 4 side 1 [9] - nop side 0 [9] - out pins 4 side 1 [9] - mov osr null side 0 [7] - out pindirs 4 side 0 - set pins 0b10 side 0 - busy: - nop side 1 [9] - jmp pin more side 0 [9] - mov osr ~osr side 1 [9] - nop side 0 [4] - out pindirs 4 side 0 - jmp y-- loop side 0 - .wrap - more: - nop side 1 [9] - jmp busy side 0 [9] - "# - ); - - let mut cfg = Config::default(); - cfg.use_program(&common.load_program(&prg.program), &[&e]); - cfg.clock_divider = 8u8.into(); // ~64ns/insn - cfg.set_jmp_pin(&db7); - cfg.set_set_pins(&[&rs, &rw]); - cfg.set_out_pins(&[&db4, &db5, &db6, &db7]); - cfg.shift_out.direction = ShiftDirection::Left; - cfg.fifo_join = FifoJoin::TxOnly; - sm0.set_config(&cfg); - - sm0.set_enable(true); - - // display on and cursor on and blinking, reset display - sm0.tx().dma_push(dma.reborrow(), &[0x81u8, 0x0f, 1]).await; - - Self { - dma: dma.map_into(), - sm: sm0, - buf: [0x20; 40], - } - } - - pub async fn add_line(&mut self, s: &[u8]) { - // move cursor to 0:0, prepare 16 characters - self.buf[..3].copy_from_slice(&[0x80, 0x80, 15]); - // move line 2 up - self.buf.copy_within(22..38, 3); - // move cursor to 1:0, prepare 16 characters - self.buf[19..22].copy_from_slice(&[0x80, 0xc0, 15]); - // file line 2 with spaces - self.buf[22..38].fill(0x20); - // copy input line - let len = s.len().min(16); - self.buf[22..22 + len].copy_from_slice(&s[0..len]); - // set cursor to 1:15 - self.buf[38..].copy_from_slice(&[0x80, 0xcf]); - - self.sm.tx().dma_push(self.dma.reborrow(), &self.buf).await; - } -} diff --git a/examples/rp/src/bin/pio_i2s.rs b/examples/rp/src/bin/pio_i2s.rs index cf60e5b30..447100ddf 100644 --- a/examples/rp/src/bin/pio_i2s.rs +++ b/examples/rp/src/bin/pio_i2s.rs @@ -13,10 +13,10 @@ use core::mem; use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; use embassy_rp::peripherals::PIO0; -use embassy_rp::pio::{Config, FifoJoin, InterruptHandler, Pio, ShiftConfig, ShiftDirection}; -use embassy_rp::{bind_interrupts, Peripheral}; -use fixed::traits::ToFixed; +use embassy_rp::pio::{InterruptHandler, Pio}; +use embassy_rp::pio_programs::i2s::{PioI2sOut, PioI2sOutProgram}; use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _}; @@ -25,61 +25,32 @@ bind_interrupts!(struct Irqs { }); const SAMPLE_RATE: u32 = 48_000; +const BIT_DEPTH: u32 = 16; +const CHANNELS: u32 = 2; #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut p = embassy_rp::init(Default::default()); // Setup pio state machine for i2s output - let mut pio = Pio::new(p.PIO0, Irqs); - - #[rustfmt::skip] - let pio_program = pio_proc::pio_asm!( - ".side_set 2", - " set x, 14 side 0b01", // side 0bWB - W = Word Clock, B = Bit Clock - "left_data:", - " out pins, 1 side 0b00", - " jmp x-- left_data side 0b01", - " out pins 1 side 0b10", - " set x, 14 side 0b11", - "right_data:", - " out pins 1 side 0b10", - " jmp x-- right_data side 0b11", - " out pins 1 side 0b00", - ); + let Pio { mut common, sm0, .. } = Pio::new(p.PIO0, Irqs); let bit_clock_pin = p.PIN_18; let left_right_clock_pin = p.PIN_19; let data_pin = p.PIN_20; - let data_pin = pio.common.make_pio_pin(data_pin); - let bit_clock_pin = pio.common.make_pio_pin(bit_clock_pin); - let left_right_clock_pin = pio.common.make_pio_pin(left_right_clock_pin); - - let cfg = { - let mut cfg = Config::default(); - cfg.use_program( - &pio.common.load_program(&pio_program.program), - &[&bit_clock_pin, &left_right_clock_pin], - ); - cfg.set_out_pins(&[&data_pin]); - const BIT_DEPTH: u32 = 16; - const CHANNELS: u32 = 2; - let clock_frequency = SAMPLE_RATE * BIT_DEPTH * CHANNELS; - cfg.clock_divider = (125_000_000. / clock_frequency as f64 / 2.).to_fixed(); - cfg.shift_out = ShiftConfig { - threshold: 32, - direction: ShiftDirection::Left, - auto_fill: true, - }; - // join fifos to have twice the time to start the next dma transfer - cfg.fifo_join = FifoJoin::TxOnly; - cfg - }; - pio.sm0.set_config(&cfg); - pio.sm0.set_pin_dirs( - embassy_rp::pio::Direction::Out, - &[&data_pin, &left_right_clock_pin, &bit_clock_pin], + let program = PioI2sOutProgram::new(&mut common); + let mut i2s = PioI2sOut::new( + &mut common, + sm0, + p.DMA_CH0, + data_pin, + bit_clock_pin, + left_right_clock_pin, + SAMPLE_RATE, + BIT_DEPTH, + CHANNELS, + &program, ); // create two audio buffers (back and front) which will take turns being @@ -90,17 +61,13 @@ async fn main(_spawner: Spawner) { let (mut back_buffer, mut front_buffer) = dma_buffer.split_at_mut(BUFFER_SIZE); // start pio state machine - pio.sm0.set_enable(true); - let tx = pio.sm0.tx(); - let mut dma_ref = p.DMA_CH0.into_ref(); - let mut fade_value: i32 = 0; let mut phase: i32 = 0; loop { // trigger transfer of front buffer data to the pio fifo // but don't await the returned future, yet - let dma_future = tx.dma_push(dma_ref.reborrow(), front_buffer); + let dma_future = i2s.write(front_buffer); // fade in audio when bootsel is pressed let fade_target = if p.BOOTSEL.is_pressed() { i32::MAX } else { 0 }; diff --git a/examples/rp/src/bin/pio_onewire.rs b/examples/rp/src/bin/pio_onewire.rs new file mode 100644 index 000000000..991510851 --- /dev/null +++ b/examples/rp/src/bin/pio_onewire.rs @@ -0,0 +1,83 @@ +//! This example shows how you can use PIO to read a `DS18B20` one-wire temperature sensor. + +#![no_std] +#![no_main] +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::peripherals::PIO0; +use embassy_rp::pio::{self, InterruptHandler, Pio}; +use embassy_rp::pio_programs::onewire::{PioOneWire, PioOneWireProgram}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let mut pio = Pio::new(p.PIO0, Irqs); + + let prg = PioOneWireProgram::new(&mut pio.common); + let onewire = PioOneWire::new(&mut pio.common, pio.sm0, p.PIN_2, &prg); + + let mut sensor = Ds18b20::new(onewire); + + loop { + sensor.start().await; // Start a new measurement + Timer::after_secs(1).await; // Allow 1s for the measurement to finish + match sensor.temperature().await { + Ok(temp) => info!("temp = {:?} deg C", temp), + _ => error!("sensor error"), + } + Timer::after_secs(1).await; + } +} + +/// DS18B20 temperature sensor driver +pub struct Ds18b20<'d, PIO: pio::Instance, const SM: usize> { + wire: PioOneWire<'d, PIO, SM>, +} + +impl<'d, PIO: pio::Instance, const SM: usize> Ds18b20<'d, PIO, SM> { + pub fn new(wire: PioOneWire<'d, PIO, SM>) -> Self { + Self { wire } + } + + /// Calculate CRC8 of the data + fn crc8(data: &[u8]) -> u8 { + let mut temp; + let mut data_byte; + let mut crc = 0; + for b in data { + data_byte = *b; + for _ in 0..8 { + temp = (crc ^ data_byte) & 0x01; + crc >>= 1; + if temp != 0 { + crc ^= 0x8C; + } + data_byte >>= 1; + } + } + crc + } + + /// Start a new measurement. Allow at least 1000ms before getting `temperature`. + pub async fn start(&mut self) { + self.wire.write_bytes(&[0xCC, 0x44]).await; + } + + /// Read the temperature. Ensure >1000ms has passed since `start` before calling this. + pub async fn temperature(&mut self) -> Result { + self.wire.write_bytes(&[0xCC, 0xBE]).await; + let mut data = [0; 9]; + self.wire.read_bytes(&mut data).await; + match Self::crc8(&data) == 0 { + true => Ok(((data[1] as u32) << 8 | data[0] as u32) as f32 / 16.), + false => Err(()), + } + } +} diff --git a/examples/rp/src/bin/pio_pwm.rs b/examples/rp/src/bin/pio_pwm.rs new file mode 100644 index 000000000..7eabb2289 --- /dev/null +++ b/examples/rp/src/bin/pio_pwm.rs @@ -0,0 +1,38 @@ +//! This example shows how to create a pwm using the PIO module in the RP2040 chip. + +#![no_std] +#![no_main] +use core::time::Duration; + +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::peripherals::PIO0; +use embassy_rp::pio::{InterruptHandler, Pio}; +use embassy_rp::pio_programs::pwm::{PioPwm, PioPwmProgram}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +const REFRESH_INTERVAL: u64 = 20000; + +bind_interrupts!(struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let Pio { mut common, sm0, .. } = Pio::new(p.PIO0, Irqs); + + // Note that PIN_25 is the led pin on the Pico + let prg = PioPwmProgram::new(&mut common); + let mut pwm_pio = PioPwm::new(&mut common, sm0, p.PIN_25, &prg); + pwm_pio.set_period(Duration::from_micros(REFRESH_INTERVAL)); + pwm_pio.start(); + + let mut duration = 0; + loop { + duration = (duration + 1) % 1000; + pwm_pio.write(Duration::from_micros(duration)); + Timer::after_millis(1).await; + } +} diff --git a/examples/rp/src/bin/pio_rotary_encoder.rs b/examples/rp/src/bin/pio_rotary_encoder.rs index 58bdadbc0..2750f61ae 100644 --- a/examples/rp/src/bin/pio_rotary_encoder.rs +++ b/examples/rp/src/bin/pio_rotary_encoder.rs @@ -5,70 +5,18 @@ use defmt::info; use embassy_executor::Spawner; -use embassy_rp::gpio::Pull; +use embassy_rp::bind_interrupts; use embassy_rp::peripherals::PIO0; -use embassy_rp::{bind_interrupts, pio}; -use fixed::traits::ToFixed; -use pio::{Common, Config, FifoJoin, Instance, InterruptHandler, Pio, PioPin, ShiftDirection, StateMachine}; +use embassy_rp::pio::{InterruptHandler, Pio}; +use embassy_rp::pio_programs::rotary_encoder::{Direction, PioEncoder, PioEncoderProgram}; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { PIO0_IRQ_0 => InterruptHandler; }); -pub struct PioEncoder<'d, T: Instance, const SM: usize> { - sm: StateMachine<'d, T, SM>, -} - -impl<'d, T: Instance, const SM: usize> PioEncoder<'d, T, SM> { - pub fn new( - pio: &mut Common<'d, T>, - mut sm: StateMachine<'d, T, SM>, - pin_a: impl PioPin, - pin_b: impl PioPin, - ) -> Self { - let mut pin_a = pio.make_pio_pin(pin_a); - let mut pin_b = pio.make_pio_pin(pin_b); - pin_a.set_pull(Pull::Up); - pin_b.set_pull(Pull::Up); - sm.set_pin_dirs(pio::Direction::In, &[&pin_a, &pin_b]); - - let prg = pio_proc::pio_asm!("wait 1 pin 1", "wait 0 pin 1", "in pins, 2", "push",); - - let mut cfg = Config::default(); - cfg.set_in_pins(&[&pin_a, &pin_b]); - cfg.fifo_join = FifoJoin::RxOnly; - cfg.shift_in.direction = ShiftDirection::Left; - cfg.clock_divider = 10_000.to_fixed(); - cfg.use_program(&pio.load_program(&prg.program), &[]); - sm.set_config(&cfg); - sm.set_enable(true); - Self { sm } - } - - pub async fn read(&mut self) -> Direction { - loop { - match self.sm.rx().wait_pull().await { - 0 => return Direction::CounterClockwise, - 1 => return Direction::Clockwise, - _ => {} - } - } - } -} - -pub enum Direction { - Clockwise, - CounterClockwise, -} - -#[embassy_executor::main] -async fn main(_spawner: Spawner) { - let p = embassy_rp::init(Default::default()); - let Pio { mut common, sm0, .. } = Pio::new(p.PIO0, Irqs); - - let mut encoder = PioEncoder::new(&mut common, sm0, p.PIN_4, p.PIN_5); - +#[embassy_executor::task] +async fn encoder_0(mut encoder: PioEncoder<'static, PIO0, 0>) { let mut count = 0; loop { info!("Count: {}", count); @@ -78,3 +26,30 @@ async fn main(_spawner: Spawner) { }; } } + +#[embassy_executor::task] +async fn encoder_1(mut encoder: PioEncoder<'static, PIO0, 1>) { + let mut count = 0; + loop { + info!("Count: {}", count); + count += match encoder.read().await { + Direction::Clockwise => 1, + Direction::CounterClockwise => -1, + }; + } +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let Pio { + mut common, sm0, sm1, .. + } = Pio::new(p.PIO0, Irqs); + + let prg = PioEncoderProgram::new(&mut common); + let encoder0 = PioEncoder::new(&mut common, sm0, p.PIN_4, p.PIN_5, &prg); + let encoder1 = PioEncoder::new(&mut common, sm1, p.PIN_6, p.PIN_7, &prg); + + spawner.must_spawn(encoder_0(encoder0)); + spawner.must_spawn(encoder_1(encoder1)); +} diff --git a/examples/rp/src/bin/pio_servo.rs b/examples/rp/src/bin/pio_servo.rs new file mode 100644 index 000000000..c52ee7492 --- /dev/null +++ b/examples/rp/src/bin/pio_servo.rs @@ -0,0 +1,128 @@ +//! This example shows how to create a pwm using the PIO module in the RP2040 chip. + +#![no_std] +#![no_main] +use core::time::Duration; + +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::peripherals::PIO0; +use embassy_rp::pio::{Instance, InterruptHandler, Pio}; +use embassy_rp::pio_programs::pwm::{PioPwm, PioPwmProgram}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +const DEFAULT_MIN_PULSE_WIDTH: u64 = 1000; // uncalibrated default, the shortest duty cycle sent to a servo +const DEFAULT_MAX_PULSE_WIDTH: u64 = 2000; // uncalibrated default, the longest duty cycle sent to a servo +const DEFAULT_MAX_DEGREE_ROTATION: u64 = 160; // 160 degrees is typical +const REFRESH_INTERVAL: u64 = 20000; // The period of each cycle + +bind_interrupts!(struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +pub struct ServoBuilder<'d, T: Instance, const SM: usize> { + pwm: PioPwm<'d, T, SM>, + period: Duration, + min_pulse_width: Duration, + max_pulse_width: Duration, + max_degree_rotation: u64, +} + +impl<'d, T: Instance, const SM: usize> ServoBuilder<'d, T, SM> { + pub fn new(pwm: PioPwm<'d, T, SM>) -> Self { + Self { + pwm, + period: Duration::from_micros(REFRESH_INTERVAL), + min_pulse_width: Duration::from_micros(DEFAULT_MIN_PULSE_WIDTH), + max_pulse_width: Duration::from_micros(DEFAULT_MAX_PULSE_WIDTH), + max_degree_rotation: DEFAULT_MAX_DEGREE_ROTATION, + } + } + + pub fn set_period(mut self, duration: Duration) -> Self { + self.period = duration; + self + } + + pub fn set_min_pulse_width(mut self, duration: Duration) -> Self { + self.min_pulse_width = duration; + self + } + + pub fn set_max_pulse_width(mut self, duration: Duration) -> Self { + self.max_pulse_width = duration; + self + } + + pub fn set_max_degree_rotation(mut self, degree: u64) -> Self { + self.max_degree_rotation = degree; + self + } + + pub fn build(mut self) -> Servo<'d, T, SM> { + self.pwm.set_period(self.period); + Servo { + pwm: self.pwm, + min_pulse_width: self.min_pulse_width, + max_pulse_width: self.max_pulse_width, + max_degree_rotation: self.max_degree_rotation, + } + } +} + +pub struct Servo<'d, T: Instance, const SM: usize> { + pwm: PioPwm<'d, T, SM>, + min_pulse_width: Duration, + max_pulse_width: Duration, + max_degree_rotation: u64, +} + +impl<'d, T: Instance, const SM: usize> Servo<'d, T, SM> { + pub fn start(&mut self) { + self.pwm.start(); + } + + pub fn stop(&mut self) { + self.pwm.stop(); + } + + pub fn write_time(&mut self, duration: Duration) { + self.pwm.write(duration); + } + + pub fn rotate(&mut self, degree: u64) { + let degree_per_nano_second = (self.max_pulse_width.as_nanos() as u64 - self.min_pulse_width.as_nanos() as u64) + / self.max_degree_rotation; + let mut duration = + Duration::from_nanos(degree * degree_per_nano_second + self.min_pulse_width.as_nanos() as u64); + if self.max_pulse_width < duration { + duration = self.max_pulse_width; + } + + self.pwm.write(duration); + } +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let Pio { mut common, sm0, .. } = Pio::new(p.PIO0, Irqs); + + let prg = PioPwmProgram::new(&mut common); + let pwm_pio = PioPwm::new(&mut common, sm0, p.PIN_1, &prg); + let mut servo = ServoBuilder::new(pwm_pio) + .set_max_degree_rotation(120) // Example of adjusting values for MG996R servo + .set_min_pulse_width(Duration::from_micros(350)) // This value was detemined by a rough experiment. + .set_max_pulse_width(Duration::from_micros(2600)) // Along with this value. + .build(); + + servo.start(); + + let mut degree = 0; + loop { + degree = (degree + 1) % 120; + servo.rotate(degree); + Timer::after_millis(50).await; + } +} diff --git a/examples/rp/src/bin/pio_stepper.rs b/examples/rp/src/bin/pio_stepper.rs index ab9ecf623..3862c248b 100644 --- a/examples/rp/src/bin/pio_stepper.rs +++ b/examples/rp/src/bin/pio_stepper.rs @@ -3,143 +3,20 @@ #![no_std] #![no_main] -use core::mem::{self, MaybeUninit}; use defmt::info; use embassy_executor::Spawner; use embassy_rp::bind_interrupts; use embassy_rp::peripherals::PIO0; -use embassy_rp::pio::{Common, Config, Direction, Instance, InterruptHandler, Irq, Pio, PioPin, StateMachine}; +use embassy_rp::pio::{InterruptHandler, Pio}; +use embassy_rp::pio_programs::stepper::{PioStepper, PioStepperProgram}; use embassy_time::{with_timeout, Duration, Timer}; -use fixed::traits::ToFixed; -use fixed::types::extra::U8; -use fixed::FixedU32; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { PIO0_IRQ_0 => InterruptHandler; }); -pub struct PioStepper<'d, T: Instance, const SM: usize> { - irq: Irq<'d, T, SM>, - sm: StateMachine<'d, T, SM>, -} - -impl<'d, T: Instance, const SM: usize> PioStepper<'d, T, SM> { - pub fn new( - pio: &mut Common<'d, T>, - mut sm: StateMachine<'d, T, SM>, - irq: Irq<'d, T, SM>, - pin0: impl PioPin, - pin1: impl PioPin, - pin2: impl PioPin, - pin3: impl PioPin, - ) -> Self { - let prg = pio_proc::pio_asm!( - "pull block", - "mov x, osr", - "pull block", - "mov y, osr", - "jmp !x end", - "loop:", - "jmp !osre step", - "mov osr, y", - "step:", - "out pins, 4 [31]" - "jmp x-- loop", - "end:", - "irq 0 rel" - ); - let pin0 = pio.make_pio_pin(pin0); - let pin1 = pio.make_pio_pin(pin1); - let pin2 = pio.make_pio_pin(pin2); - let pin3 = pio.make_pio_pin(pin3); - sm.set_pin_dirs(Direction::Out, &[&pin0, &pin1, &pin2, &pin3]); - let mut cfg = Config::default(); - cfg.set_out_pins(&[&pin0, &pin1, &pin2, &pin3]); - cfg.clock_divider = (125_000_000 / (100 * 136)).to_fixed(); - cfg.use_program(&pio.load_program(&prg.program), &[]); - sm.set_config(&cfg); - sm.set_enable(true); - Self { irq, sm } - } - - // Set pulse frequency - pub fn set_frequency(&mut self, freq: u32) { - let clock_divider: FixedU32 = (125_000_000 / (freq * 136)).to_fixed(); - assert!(clock_divider <= 65536, "clkdiv must be <= 65536"); - assert!(clock_divider >= 1, "clkdiv must be >= 1"); - T::PIO.sm(SM).clkdiv().write(|w| w.0 = clock_divider.to_bits() << 8); - self.sm.clkdiv_restart(); - } - - // Full step, one phase - pub async fn step(&mut self, steps: i32) { - if steps > 0 { - self.run(steps, 0b1000_0100_0010_0001_1000_0100_0010_0001).await - } else { - self.run(-steps, 0b0001_0010_0100_1000_0001_0010_0100_1000).await - } - } - - // Full step, two phase - pub async fn step2(&mut self, steps: i32) { - if steps > 0 { - self.run(steps, 0b1001_1100_0110_0011_1001_1100_0110_0011).await - } else { - self.run(-steps, 0b0011_0110_1100_1001_0011_0110_1100_1001).await - } - } - - // Half step - pub async fn step_half(&mut self, steps: i32) { - if steps > 0 { - self.run(steps, 0b1001_1000_1100_0100_0110_0010_0011_0001).await - } else { - self.run(-steps, 0b0001_0011_0010_0110_0100_1100_1000_1001).await - } - } - - async fn run(&mut self, steps: i32, pattern: u32) { - self.sm.tx().wait_push(steps as u32).await; - self.sm.tx().wait_push(pattern).await; - let drop = OnDrop::new(|| { - self.sm.clear_fifos(); - unsafe { - self.sm.exec_instr( - pio::InstructionOperands::JMP { - address: 0, - condition: pio::JmpCondition::Always, - } - .encode(), - ); - } - }); - self.irq.wait().await; - drop.defuse(); - } -} - -struct OnDrop { - f: MaybeUninit, -} - -impl OnDrop { - pub fn new(f: F) -> Self { - Self { f: MaybeUninit::new(f) } - } - - pub fn defuse(self) { - mem::forget(self) - } -} - -impl Drop for OnDrop { - fn drop(&mut self) { - unsafe { self.f.as_ptr().read()() } - } -} - #[embassy_executor::main] async fn main(_spawner: Spawner) { let p = embassy_rp::init(Default::default()); @@ -147,14 +24,18 @@ async fn main(_spawner: Spawner) { mut common, irq0, sm0, .. } = Pio::new(p.PIO0, Irqs); - let mut stepper = PioStepper::new(&mut common, sm0, irq0, p.PIN_4, p.PIN_5, p.PIN_6, p.PIN_7); + let prg = PioStepperProgram::new(&mut common); + let mut stepper = PioStepper::new(&mut common, sm0, irq0, p.PIN_4, p.PIN_5, p.PIN_6, p.PIN_7, &prg); stepper.set_frequency(120); loop { info!("CW full steps"); stepper.step(1000).await; info!("CCW full steps, drop after 1 sec"); - if let Err(_) = with_timeout(Duration::from_secs(1), stepper.step(i32::MIN)).await { + if with_timeout(Duration::from_secs(1), stepper.step(-i32::MAX)) + .await + .is_err() + { info!("Time's up!"); Timer::after(Duration::from_secs(1)).await; } diff --git a/examples/rp/src/bin/pio_uart.rs b/examples/rp/src/bin/pio_uart.rs index a07f1c180..aaf2a524f 100644 --- a/examples/rp/src/bin/pio_uart.rs +++ b/examples/rp/src/bin/pio_uart.rs @@ -13,10 +13,10 @@ use defmt::{info, panic, trace}; use embassy_executor::Spawner; use embassy_futures::join::{join, join3}; -use embassy_rp::bind_interrupts; use embassy_rp::peripherals::{PIO0, USB}; -use embassy_rp::pio::InterruptHandler as PioInterruptHandler; +use embassy_rp::pio_programs::uart::{PioUartRx, PioUartRxProgram, PioUartTx, PioUartTxProgram}; use embassy_rp::usb::{Driver, Instance, InterruptHandler}; +use embassy_rp::{bind_interrupts, pio}; use embassy_sync::blocking_mutex::raw::NoopRawMutex; use embassy_sync::pipe::Pipe; use embassy_usb::class::cdc_acm::{CdcAcmClass, Receiver, Sender, State}; @@ -25,13 +25,11 @@ use embassy_usb::{Builder, Config}; use embedded_io_async::{Read, Write}; use {defmt_rtt as _, panic_probe as _}; -use crate::uart::PioUart; -use crate::uart_rx::PioUartRx; -use crate::uart_tx::PioUartTx; +//use crate::uart::PioUart; bind_interrupts!(struct Irqs { USBCTRL_IRQ => InterruptHandler; - PIO0_IRQ_0 => PioInterruptHandler; + PIO0_IRQ_0 => pio::InterruptHandler; }); #[embassy_executor::main] @@ -60,7 +58,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 64]; @@ -70,7 +67,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], // no msos descriptors @@ -87,8 +83,15 @@ async fn main(_spawner: Spawner) { let usb_fut = usb.run(); // PIO UART setup - let uart = PioUart::new(9600, p.PIO0, p.PIN_4, p.PIN_5); - let (mut uart_tx, mut uart_rx) = uart.split(); + let pio::Pio { + mut common, sm0, sm1, .. + } = pio::Pio::new(p.PIO0, Irqs); + + let tx_program = PioUartTxProgram::new(&mut common); + let mut uart_tx = PioUartTx::new(9600, &mut common, sm0, p.PIN_4, &tx_program); + + let rx_program = PioUartRxProgram::new(&mut common); + let mut uart_rx = PioUartRx::new(9600, &mut common, sm1, p.PIN_5, &rx_program); // Pipe setup let mut usb_pipe: Pipe = Pipe::new(); @@ -165,8 +168,8 @@ async fn usb_write<'d, T: Instance + 'd>( } /// Read from the UART and write it to the USB TX pipe -async fn uart_read( - uart_rx: &mut PioUartRx<'_>, +async fn uart_read( + uart_rx: &mut PioUartRx<'_, PIO, SM>, usb_pipe_writer: &mut embassy_sync::pipe::Writer<'_, NoopRawMutex, 20>, ) -> ! { let mut buf = [0; 64]; @@ -182,8 +185,8 @@ async fn uart_read( } /// Read from the UART TX pipe and write it to the UART -async fn uart_write( - uart_tx: &mut PioUartTx<'_>, +async fn uart_write( + uart_tx: &mut PioUartTx<'_, PIO, SM>, uart_pipe_reader: &mut embassy_sync::pipe::Reader<'_, NoopRawMutex, 20>, ) -> ! { let mut buf = [0; 64]; @@ -194,197 +197,3 @@ async fn uart_write( let _ = uart_tx.write(&data).await; } } - -mod uart { - use embassy_rp::peripherals::PIO0; - use embassy_rp::pio::{Pio, PioPin}; - use embassy_rp::Peripheral; - - use crate::uart_rx::PioUartRx; - use crate::uart_tx::PioUartTx; - use crate::Irqs; - - pub struct PioUart<'a> { - tx: PioUartTx<'a>, - rx: PioUartRx<'a>, - } - - impl<'a> PioUart<'a> { - pub fn new( - baud: u64, - pio: impl Peripheral

+ 'a, - tx_pin: impl PioPin, - rx_pin: impl PioPin, - ) -> PioUart<'a> { - let Pio { - mut common, sm0, sm1, .. - } = Pio::new(pio, Irqs); - - let tx = PioUartTx::new(&mut common, sm0, tx_pin, baud); - let rx = PioUartRx::new(&mut common, sm1, rx_pin, baud); - - PioUart { tx, rx } - } - - pub fn split(self) -> (PioUartTx<'a>, PioUartRx<'a>) { - (self.tx, self.rx) - } - } -} - -mod uart_tx { - use core::convert::Infallible; - - use embassy_rp::gpio::Level; - use embassy_rp::peripherals::PIO0; - use embassy_rp::pio::{Common, Config, Direction, FifoJoin, PioPin, ShiftDirection, StateMachine}; - use embedded_io_async::{ErrorType, Write}; - use fixed::traits::ToFixed; - use fixed_macro::types::U56F8; - - pub struct PioUartTx<'a> { - sm_tx: StateMachine<'a, PIO0, 0>, - } - - impl<'a> PioUartTx<'a> { - pub fn new( - common: &mut Common<'a, PIO0>, - mut sm_tx: StateMachine<'a, PIO0, 0>, - tx_pin: impl PioPin, - baud: u64, - ) -> Self { - let prg = pio_proc::pio_asm!( - r#" - .side_set 1 opt - - ; An 8n1 UART transmit program. - ; OUT pin 0 and side-set pin 0 are both mapped to UART TX pin. - - pull side 1 [7] ; Assert stop bit, or stall with line in idle state - set x, 7 side 0 [7] ; Preload bit counter, assert start bit for 8 clocks - bitloop: ; This loop will run 8 times (8n1 UART) - out pins, 1 ; Shift 1 bit from OSR to the first OUT pin - jmp x-- bitloop [6] ; Each loop iteration is 8 cycles. - "# - ); - let tx_pin = common.make_pio_pin(tx_pin); - sm_tx.set_pins(Level::High, &[&tx_pin]); - sm_tx.set_pin_dirs(Direction::Out, &[&tx_pin]); - - let mut cfg = Config::default(); - - cfg.set_out_pins(&[&tx_pin]); - cfg.use_program(&common.load_program(&prg.program), &[&tx_pin]); - cfg.shift_out.auto_fill = false; - cfg.shift_out.direction = ShiftDirection::Right; - cfg.fifo_join = FifoJoin::TxOnly; - cfg.clock_divider = (U56F8!(125_000_000) / (8 * baud)).to_fixed(); - sm_tx.set_config(&cfg); - sm_tx.set_enable(true); - - Self { sm_tx } - } - - pub async fn write_u8(&mut self, data: u8) { - self.sm_tx.tx().wait_push(data as u32).await; - } - } - - impl ErrorType for PioUartTx<'_> { - type Error = Infallible; - } - - impl Write for PioUartTx<'_> { - async fn write(&mut self, buf: &[u8]) -> Result { - for byte in buf { - self.write_u8(*byte).await; - } - Ok(buf.len()) - } - } -} - -mod uart_rx { - use core::convert::Infallible; - - use embassy_rp::gpio::Level; - use embassy_rp::peripherals::PIO0; - use embassy_rp::pio::{Common, Config, Direction, FifoJoin, PioPin, ShiftDirection, StateMachine}; - use embedded_io_async::{ErrorType, Read}; - use fixed::traits::ToFixed; - use fixed_macro::types::U56F8; - - pub struct PioUartRx<'a> { - sm_rx: StateMachine<'a, PIO0, 1>, - } - - impl<'a> PioUartRx<'a> { - pub fn new( - common: &mut Common<'a, PIO0>, - mut sm_rx: StateMachine<'a, PIO0, 1>, - rx_pin: impl PioPin, - baud: u64, - ) -> Self { - let prg = pio_proc::pio_asm!( - r#" - ; Slightly more fleshed-out 8n1 UART receiver which handles framing errors and - ; break conditions more gracefully. - ; IN pin 0 and JMP pin are both mapped to the GPIO used as UART RX. - - start: - wait 0 pin 0 ; Stall until start bit is asserted - set x, 7 [10] ; Preload bit counter, then delay until halfway through - rx_bitloop: ; the first data bit (12 cycles incl wait, set). - in pins, 1 ; Shift data bit into ISR - jmp x-- rx_bitloop [6] ; Loop 8 times, each loop iteration is 8 cycles - jmp pin good_rx_stop ; Check stop bit (should be high) - - irq 4 rel ; Either a framing error or a break. Set a sticky flag, - wait 1 pin 0 ; and wait for line to return to idle state. - jmp start ; Don't push data if we didn't see good framing. - - good_rx_stop: ; No delay before returning to start; a little slack is - in null 24 - push ; important in case the TX clock is slightly too fast. - "# - ); - let mut cfg = Config::default(); - cfg.use_program(&common.load_program(&prg.program), &[]); - - let rx_pin = common.make_pio_pin(rx_pin); - sm_rx.set_pins(Level::High, &[&rx_pin]); - cfg.set_in_pins(&[&rx_pin]); - cfg.set_jmp_pin(&rx_pin); - sm_rx.set_pin_dirs(Direction::In, &[&rx_pin]); - - cfg.clock_divider = (U56F8!(125_000_000) / (8 * baud)).to_fixed(); - cfg.shift_in.auto_fill = false; - cfg.shift_in.direction = ShiftDirection::Right; - cfg.shift_in.threshold = 32; - cfg.fifo_join = FifoJoin::RxOnly; - sm_rx.set_config(&cfg); - sm_rx.set_enable(true); - - Self { sm_rx } - } - - pub async fn read_u8(&mut self) -> u8 { - self.sm_rx.rx().wait_pull().await as u8 - } - } - - impl ErrorType for PioUartRx<'_> { - type Error = Infallible; - } - - impl Read for PioUartRx<'_> { - async fn read(&mut self, buf: &mut [u8]) -> Result { - let mut i = 0; - while i < buf.len() { - buf[i] = self.read_u8().await; - i += 1; - } - Ok(i) - } - } -} diff --git a/examples/rp/src/bin/pio_ws2812.rs b/examples/rp/src/bin/pio_ws2812.rs index 9a97cb8a7..d1fcfc471 100644 --- a/examples/rp/src/bin/pio_ws2812.rs +++ b/examples/rp/src/bin/pio_ws2812.rs @@ -6,15 +6,11 @@ use defmt::*; use embassy_executor::Spawner; -use embassy_rp::dma::{AnyChannel, Channel}; +use embassy_rp::bind_interrupts; use embassy_rp::peripherals::PIO0; -use embassy_rp::pio::{ - Common, Config, FifoJoin, Instance, InterruptHandler, Pio, PioPin, ShiftConfig, ShiftDirection, StateMachine, -}; -use embassy_rp::{bind_interrupts, clocks, into_ref, Peripheral, PeripheralRef}; -use embassy_time::Timer; -use fixed::types::U24F8; -use fixed_macro::fixed; +use embassy_rp::pio::{InterruptHandler, Pio}; +use embassy_rp::pio_programs::ws2812::{PioWs2812, PioWs2812Program}; +use embassy_time::{Duration, Ticker}; use smart_leds::RGB8; use {defmt_rtt as _, panic_probe as _}; @@ -22,94 +18,6 @@ bind_interrupts!(struct Irqs { PIO0_IRQ_0 => InterruptHandler; }); -pub struct Ws2812<'d, P: Instance, const S: usize, const N: usize> { - dma: PeripheralRef<'d, AnyChannel>, - sm: StateMachine<'d, P, S>, -} - -impl<'d, P: Instance, const S: usize, const N: usize> Ws2812<'d, P, S, N> { - pub fn new( - pio: &mut Common<'d, P>, - mut sm: StateMachine<'d, P, S>, - dma: impl Peripheral

+ 'd, - pin: impl PioPin, - ) -> Self { - into_ref!(dma); - - // Setup sm0 - - // prepare the PIO program - let side_set = pio::SideSet::new(false, 1, false); - let mut a: pio::Assembler<32> = pio::Assembler::new_with_side_set(side_set); - - const T1: u8 = 2; // start bit - const T2: u8 = 5; // data bit - const T3: u8 = 3; // stop bit - const CYCLES_PER_BIT: u32 = (T1 + T2 + T3) as u32; - - let mut wrap_target = a.label(); - let mut wrap_source = a.label(); - let mut do_zero = a.label(); - a.set_with_side_set(pio::SetDestination::PINDIRS, 1, 0); - a.bind(&mut wrap_target); - // Do stop bit - a.out_with_delay_and_side_set(pio::OutDestination::X, 1, T3 - 1, 0); - // Do start bit - a.jmp_with_delay_and_side_set(pio::JmpCondition::XIsZero, &mut do_zero, T1 - 1, 1); - // Do data bit = 1 - a.jmp_with_delay_and_side_set(pio::JmpCondition::Always, &mut wrap_target, T2 - 1, 1); - a.bind(&mut do_zero); - // Do data bit = 0 - a.nop_with_delay_and_side_set(T2 - 1, 0); - a.bind(&mut wrap_source); - - let prg = a.assemble_with_wrap(wrap_source, wrap_target); - let mut cfg = Config::default(); - - // Pin config - let out_pin = pio.make_pio_pin(pin); - cfg.set_out_pins(&[&out_pin]); - cfg.set_set_pins(&[&out_pin]); - - cfg.use_program(&pio.load_program(&prg), &[&out_pin]); - - // Clock config, measured in kHz to avoid overflows - // TODO CLOCK_FREQ should come from embassy_rp - let clock_freq = U24F8::from_num(clocks::clk_sys_freq() / 1000); - let ws2812_freq = fixed!(800: U24F8); - let bit_freq = ws2812_freq * CYCLES_PER_BIT; - cfg.clock_divider = clock_freq / bit_freq; - - // FIFO config - cfg.fifo_join = FifoJoin::TxOnly; - cfg.shift_out = ShiftConfig { - auto_fill: true, - threshold: 24, - direction: ShiftDirection::Left, - }; - - sm.set_config(&cfg); - sm.set_enable(true); - - Self { - dma: dma.map_into(), - sm, - } - } - - pub async fn write(&mut self, colors: &[RGB8; N]) { - // Precompute the word bytes from the colors - let mut words = [0u32; N]; - for i in 0..N { - let word = (u32::from(colors[i].g) << 24) | (u32::from(colors[i].r) << 16) | (u32::from(colors[i].b) << 8); - words[i] = word; - } - - // DMA transfer - self.sm.tx().dma_push(self.dma.reborrow(), &words).await; - } -} - /// Input a value 0 to 255 to get a color value /// The colours are a transition r - g - b - back to r. fn wheel(mut wheel_pos: u8) -> RGB8 { @@ -140,9 +48,11 @@ async fn main(_spawner: Spawner) { // Common neopixel pins: // Thing plus: 8 // Adafruit Feather: 16; Adafruit Feather+RFM95: 4 - let mut ws2812 = Ws2812::new(&mut common, sm0, p.DMA_CH0, p.PIN_16); + let program = PioWs2812Program::new(&mut common); + let mut ws2812 = PioWs2812::new(&mut common, sm0, p.DMA_CH0, p.PIN_16, &program); // Loop forever making RGB values and pushing them out to the WS2812. + let mut ticker = Ticker::every(Duration::from_millis(10)); loop { for j in 0..(256 * 5) { debug!("New Colors:"); @@ -152,7 +62,7 @@ async fn main(_spawner: Spawner) { } ws2812.write(&data).await; - Timer::after_millis(10).await; + ticker.next().await; } } } diff --git a/examples/rp/src/bin/pwm.rs b/examples/rp/src/bin/pwm.rs index 4fb62546d..791b88b5b 100644 --- a/examples/rp/src/bin/pwm.rs +++ b/examples/rp/src/bin/pwm.rs @@ -1,24 +1,36 @@ //! This example shows how to use PWM (Pulse Width Modulation) in the RP2040 chip. //! -//! The LED on the RP Pico W board is connected differently. Add a LED and resistor to another pin. +//! We demonstrate two ways of using PWM: +//! 1. Via config +//! 2. Via setting a duty cycle #![no_std] #![no_main] use defmt::*; use embassy_executor::Spawner; -use embassy_rp::pwm::{Config, Pwm}; +use embassy_rp::peripherals::{PIN_25, PIN_4, PWM_SLICE2, PWM_SLICE4}; +use embassy_rp::pwm::{Config, Pwm, SetDutyCycle}; use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] -async fn main(_spawner: Spawner) { +async fn main(spawner: Spawner) { let p = embassy_rp::init(Default::default()); + spawner.spawn(pwm_set_config(p.PWM_SLICE4, p.PIN_25)).unwrap(); + spawner.spawn(pwm_set_dutycycle(p.PWM_SLICE2, p.PIN_4)).unwrap(); +} - let mut c: Config = Default::default(); - c.top = 0x8000; +/// Demonstrate PWM by modifying & applying the config +/// +/// Using the onboard led, if You are using a different Board than plain Pico2 (i.e. W variant) +/// you must use another slice & pin and an appropriate resistor. +#[embassy_executor::task] +async fn pwm_set_config(slice4: PWM_SLICE4, pin25: PIN_25) { + let mut c = Config::default(); + c.top = 32_768; c.compare_b = 8; - let mut pwm = Pwm::new_output_b(p.PWM_CH4, p.PIN_25, c.clone()); + let mut pwm = Pwm::new_output_b(slice4, pin25, c.clone()); loop { info!("current LED duty cycle: {}/32768", c.compare_b); @@ -27,3 +39,37 @@ async fn main(_spawner: Spawner) { pwm.set_config(&c); } } + +/// Demonstrate PWM by setting duty cycle +/// +/// Using GP4 in Slice2, make sure to use an appropriate resistor. +#[embassy_executor::task] +async fn pwm_set_dutycycle(slice2: PWM_SLICE2, pin4: PIN_4) { + // If we aim for a specific frequency, here is how we can calculate the top value. + // The top value sets the period of the PWM cycle, so a counter goes from 0 to top and then wraps around to 0. + // Every such wraparound is one PWM cycle. So here is how we get 25KHz: + let mut c = Config::default(); + let pwm_freq = 25_000; // Hz, our desired frequency + let clock_freq = embassy_rp::clocks::clk_sys_freq(); + c.top = (clock_freq / pwm_freq) as u16 - 1; + + let mut pwm = Pwm::new_output_a(slice2, pin4, c.clone()); + + loop { + // 100% duty cycle, fully on + pwm.set_duty_cycle_fully_on().unwrap(); + Timer::after_secs(1).await; + + // 66% duty cycle. Expressed as simple percentage. + pwm.set_duty_cycle_percent(66).unwrap(); + Timer::after_secs(1).await; + + // 25% duty cycle. Expressed as 32768/4 = 8192. + pwm.set_duty_cycle(c.top / 4).unwrap(); + Timer::after_secs(1).await; + + // 0% duty cycle, fully off. + pwm.set_duty_cycle_fully_off().unwrap(); + Timer::after_secs(1).await; + } +} diff --git a/examples/rp/src/bin/pwm_input.rs b/examples/rp/src/bin/pwm_input.rs index e7bcbfbd4..bf454a936 100644 --- a/examples/rp/src/bin/pwm_input.rs +++ b/examples/rp/src/bin/pwm_input.rs @@ -5,6 +5,7 @@ use defmt::*; use embassy_executor::Spawner; +use embassy_rp::gpio::Pull; use embassy_rp::pwm::{Config, InputMode, Pwm}; use embassy_time::{Duration, Ticker}; use {defmt_rtt as _, panic_probe as _}; @@ -14,7 +15,7 @@ async fn main(_spawner: Spawner) { let p = embassy_rp::init(Default::default()); let cfg: Config = Default::default(); - let pwm = Pwm::new_input(p.PWM_CH2, p.PIN_5, InputMode::RisingEdge, cfg); + let pwm = Pwm::new_input(p.PWM_SLICE2, p.PIN_5, Pull::None, InputMode::RisingEdge, cfg); let mut ticker = Ticker::every(Duration::from_secs(1)); loop { diff --git a/examples/rp/src/bin/shared_bus.rs b/examples/rp/src/bin/shared_bus.rs new file mode 100644 index 000000000..c6cb5d64c --- /dev/null +++ b/examples/rp/src/bin/shared_bus.rs @@ -0,0 +1,115 @@ +//! This example shows how to share (async) I2C and SPI buses between multiple devices. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_embedded_hal::shared_bus::asynch::i2c::I2cDevice; +use embassy_embedded_hal::shared_bus::asynch::spi::SpiDevice; +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::gpio::{AnyPin, Level, Output}; +use embassy_rp::i2c::{self, I2c, InterruptHandler}; +use embassy_rp::peripherals::{I2C1, SPI1}; +use embassy_rp::spi::{self, Spi}; +use embassy_sync::blocking_mutex::raw::NoopRawMutex; +use embassy_sync::mutex::Mutex; +use embassy_time::Timer; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +type Spi1Bus = Mutex>; +type I2c1Bus = Mutex>; + +bind_interrupts!(struct Irqs { + I2C1_IRQ => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + info!("Here we go!"); + + // Shared I2C bus + let i2c = I2c::new_async(p.I2C1, p.PIN_15, p.PIN_14, Irqs, i2c::Config::default()); + static I2C_BUS: StaticCell = StaticCell::new(); + let i2c_bus = I2C_BUS.init(Mutex::new(i2c)); + + spawner.must_spawn(i2c_task_a(i2c_bus)); + spawner.must_spawn(i2c_task_b(i2c_bus)); + + // Shared SPI bus + let spi_cfg = spi::Config::default(); + let spi = Spi::new(p.SPI1, p.PIN_10, p.PIN_11, p.PIN_12, p.DMA_CH0, p.DMA_CH1, spi_cfg); + static SPI_BUS: StaticCell = StaticCell::new(); + let spi_bus = SPI_BUS.init(Mutex::new(spi)); + + // Chip select pins for the SPI devices + let cs_a = Output::new(AnyPin::from(p.PIN_0), Level::High); + let cs_b = Output::new(AnyPin::from(p.PIN_1), Level::High); + + spawner.must_spawn(spi_task_a(spi_bus, cs_a)); + spawner.must_spawn(spi_task_b(spi_bus, cs_b)); +} + +#[embassy_executor::task] +async fn i2c_task_a(i2c_bus: &'static I2c1Bus) { + let i2c_dev = I2cDevice::new(i2c_bus); + let _sensor = DummyI2cDeviceDriver::new(i2c_dev, 0xC0); + loop { + info!("i2c task A"); + Timer::after_secs(1).await; + } +} + +#[embassy_executor::task] +async fn i2c_task_b(i2c_bus: &'static I2c1Bus) { + let i2c_dev = I2cDevice::new(i2c_bus); + let _sensor = DummyI2cDeviceDriver::new(i2c_dev, 0xDE); + loop { + info!("i2c task B"); + Timer::after_secs(1).await; + } +} + +#[embassy_executor::task] +async fn spi_task_a(spi_bus: &'static Spi1Bus, cs: Output<'static>) { + let spi_dev = SpiDevice::new(spi_bus, cs); + let _sensor = DummySpiDeviceDriver::new(spi_dev); + loop { + info!("spi task A"); + Timer::after_secs(1).await; + } +} + +#[embassy_executor::task] +async fn spi_task_b(spi_bus: &'static Spi1Bus, cs: Output<'static>) { + let spi_dev = SpiDevice::new(spi_bus, cs); + let _sensor = DummySpiDeviceDriver::new(spi_dev); + loop { + info!("spi task B"); + Timer::after_secs(1).await; + } +} + +// Dummy I2C device driver, using `embedded-hal-async` +struct DummyI2cDeviceDriver { + _i2c: I2C, +} + +impl DummyI2cDeviceDriver { + fn new(i2c_dev: I2C, _address: u8) -> Self { + Self { _i2c: i2c_dev } + } +} + +// Dummy SPI device driver, using `embedded-hal-async` +struct DummySpiDeviceDriver { + _spi: SPI, +} + +impl DummySpiDeviceDriver { + fn new(spi_dev: SPI) -> Self { + Self { _spi: spi_dev } + } +} diff --git a/examples/rp/src/bin/sharing.rs b/examples/rp/src/bin/sharing.rs new file mode 100644 index 000000000..5416e20ce --- /dev/null +++ b/examples/rp/src/bin/sharing.rs @@ -0,0 +1,150 @@ +//! This example shows some common strategies for sharing resources between tasks. +//! +//! We demonstrate five different ways of sharing, covering different use cases: +//! - Atomics: This method is used for simple values, such as bool and u8..u32 +//! - Blocking Mutex: This is used for sharing non-async things, using Cell/RefCell for interior mutability. +//! - Async Mutex: This is used for sharing async resources, where you need to hold the lock across await points. +//! The async Mutex has interior mutability built-in, so no RefCell is needed. +//! - Cell: For sharing Copy types between tasks running on the same executor. +//! - RefCell: When you want &mut access to a value shared between tasks running on the same executor. +//! +//! More information: https://embassy.dev/book/#_sharing_peripherals_between_tasks + +#![no_std] +#![no_main] + +use core::cell::{Cell, RefCell}; +use core::sync::atomic::{AtomicU32, Ordering}; + +use cortex_m_rt::entry; +use defmt::info; +use embassy_executor::{Executor, InterruptExecutor}; +use embassy_rp::clocks::RoscRng; +use embassy_rp::interrupt::{InterruptExt, Priority}; +use embassy_rp::peripherals::UART0; +use embassy_rp::uart::{self, InterruptHandler, UartTx}; +use embassy_rp::{bind_interrupts, interrupt}; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +use embassy_sync::{blocking_mutex, mutex}; +use embassy_time::{Duration, Ticker}; +use rand::RngCore; +use static_cell::{ConstStaticCell, StaticCell}; +use {defmt_rtt as _, panic_probe as _}; + +type UartAsyncMutex = mutex::Mutex>; + +struct MyType { + inner: u32, +} + +static EXECUTOR_HI: InterruptExecutor = InterruptExecutor::new(); +static EXECUTOR_LOW: StaticCell = StaticCell::new(); + +// Use Atomics for simple values +static ATOMIC: AtomicU32 = AtomicU32::new(0); + +// Use blocking Mutex with Cell/RefCell for sharing non-async things +static MUTEX_BLOCKING: blocking_mutex::Mutex> = + blocking_mutex::Mutex::new(RefCell::new(MyType { inner: 0 })); + +bind_interrupts!(struct Irqs { + UART0_IRQ => InterruptHandler; +}); + +#[interrupt] +unsafe fn SWI_IRQ_0() { + EXECUTOR_HI.on_interrupt() +} + +#[entry] +fn main() -> ! { + let p = embassy_rp::init(Default::default()); + info!("Here we go!"); + + let uart = UartTx::new(p.UART0, p.PIN_0, p.DMA_CH0, uart::Config::default()); + // Use the async Mutex for sharing async things (built-in interior mutability) + static UART: StaticCell = StaticCell::new(); + let uart = UART.init(mutex::Mutex::new(uart)); + + // High-priority executor: runs in interrupt mode + interrupt::SWI_IRQ_0.set_priority(Priority::P3); + let spawner = EXECUTOR_HI.start(interrupt::SWI_IRQ_0); + spawner.must_spawn(task_a(uart)); + + // Low priority executor: runs in thread mode + let executor = EXECUTOR_LOW.init(Executor::new()); + executor.run(|spawner| { + // No Mutex needed when sharing between tasks running on the same executor + + // Use Cell for Copy-types + static CELL: ConstStaticCell> = ConstStaticCell::new(Cell::new([0; 4])); + let cell = CELL.take(); + + // Use RefCell for &mut access + static REF_CELL: ConstStaticCell> = ConstStaticCell::new(RefCell::new(MyType { inner: 0 })); + let ref_cell = REF_CELL.take(); + + spawner.must_spawn(task_b(uart, cell, ref_cell)); + spawner.must_spawn(task_c(cell, ref_cell)); + }); +} + +#[embassy_executor::task] +async fn task_a(uart: &'static UartAsyncMutex) { + let mut ticker = Ticker::every(Duration::from_secs(1)); + loop { + let random = RoscRng.next_u32(); + + { + let mut uart = uart.lock().await; + uart.write(b"task a").await.unwrap(); + // The uart lock is released when it goes out of scope + } + + ATOMIC.store(random, Ordering::Relaxed); + + MUTEX_BLOCKING.lock(|x| x.borrow_mut().inner = random); + + ticker.next().await; + } +} + +#[embassy_executor::task] +async fn task_b(uart: &'static UartAsyncMutex, cell: &'static Cell<[u8; 4]>, ref_cell: &'static RefCell) { + let mut ticker = Ticker::every(Duration::from_secs(1)); + loop { + let random = RoscRng.next_u32(); + + uart.lock().await.write(b"task b").await.unwrap(); + + cell.set(random.to_be_bytes()); + + ref_cell.borrow_mut().inner = random; + + ticker.next().await; + } +} + +#[embassy_executor::task] +async fn task_c(cell: &'static Cell<[u8; 4]>, ref_cell: &'static RefCell) { + let mut ticker = Ticker::every(Duration::from_secs(1)); + loop { + info!("======================="); + + let atomic_val = ATOMIC.load(Ordering::Relaxed); + info!("atomic: {}", atomic_val); + + MUTEX_BLOCKING.lock(|x| { + let val = x.borrow().inner; + info!("blocking mutex: {}", val); + }); + + let cell_val = cell.get(); + info!("cell: {:?}", cell_val); + + let ref_cell_val = ref_cell.borrow().inner; + info!("ref_cell: {:?}", ref_cell_val); + + ticker.next().await; + } +} diff --git a/examples/rp/src/bin/spi_display.rs b/examples/rp/src/bin/spi_display.rs index e937b9d0a..dd114a4ae 100644 --- a/examples/rp/src/bin/spi_display.rs +++ b/examples/rp/src/bin/spi_display.rs @@ -9,11 +9,12 @@ use core::cell::RefCell; use defmt::*; +use display_interface_spi::SPIInterface; use embassy_embedded_hal::shared_bus::blocking::spi::SpiDeviceWithConfig; use embassy_executor::Spawner; use embassy_rp::gpio::{Level, Output}; use embassy_rp::spi; -use embassy_rp::spi::{Blocking, Spi}; +use embassy_rp::spi::Spi; use embassy_sync::blocking_mutex::raw::NoopRawMutex; use embassy_sync::blocking_mutex::Mutex; use embassy_time::Delay; @@ -24,10 +25,11 @@ use embedded_graphics::pixelcolor::Rgb565; use embedded_graphics::prelude::*; use embedded_graphics::primitives::{PrimitiveStyleBuilder, Rectangle}; use embedded_graphics::text::Text; -use st7789::{Orientation, ST7789}; +use mipidsi::models::ST7789; +use mipidsi::options::{Orientation, Rotation}; +use mipidsi::Builder; use {defmt_rtt as _, panic_probe as _}; -use crate::my_display_interface::SPIDeviceInterface; use crate::touch::Touch; const DISPLAY_FREQ: u32 = 64_000_000; @@ -58,7 +60,7 @@ async fn main(_spawner: Spawner) { touch_config.phase = spi::Phase::CaptureOnSecondTransition; touch_config.polarity = spi::Polarity::IdleHigh; - let spi: Spi<'_, _, Blocking> = Spi::new_blocking(p.SPI1, clk, mosi, miso, touch_config.clone()); + let spi = Spi::new_blocking(p.SPI1, clk, mosi, miso, touch_config.clone()); let spi_bus: Mutex = Mutex::new(RefCell::new(spi)); let display_spi = SpiDeviceWithConfig::new(&spi_bus, Output::new(display_cs, Level::High), display_config); @@ -74,17 +76,15 @@ async fn main(_spawner: Spawner) { let _bl = Output::new(bl, Level::High); // display interface abstraction from SPI and DC - let di = SPIDeviceInterface::new(display_spi, dcx); - - // create driver - let mut display = ST7789::new(di, rst, 240, 320); - - // initialize - display.init(&mut Delay).unwrap(); - - // set default orientation - display.set_orientation(Orientation::Landscape).unwrap(); + let di = SPIInterface::new(display_spi, dcx); + // Define the display from the display interface and initialize it + let mut display = Builder::new(ST7789, di) + .display_size(240, 320) + .reset_pin(rst) + .orientation(Orientation::new().rotate(Rotation::Deg90)) + .init(&mut Delay) + .unwrap(); display.clear(Rgb565::BLACK).unwrap(); let raw_image_data = ImageRawLE::new(include_bytes!("../../assets/ferris.raw"), 86); @@ -175,138 +175,3 @@ mod touch { } } } - -mod my_display_interface { - use display_interface::{DataFormat, DisplayError, WriteOnlyDataCommand}; - use embedded_hal_1::digital::OutputPin; - use embedded_hal_1::spi::SpiDevice; - - /// SPI display interface. - /// - /// This combines the SPI peripheral and a data/command pin - pub struct SPIDeviceInterface { - spi: SPI, - dc: DC, - } - - impl SPIDeviceInterface - where - SPI: SpiDevice, - DC: OutputPin, - { - /// Create new SPI interface for communciation with a display driver - pub fn new(spi: SPI, dc: DC) -> Self { - Self { spi, dc } - } - } - - impl WriteOnlyDataCommand for SPIDeviceInterface - where - SPI: SpiDevice, - DC: OutputPin, - { - fn send_commands(&mut self, cmds: DataFormat<'_>) -> Result<(), DisplayError> { - // 1 = data, 0 = command - self.dc.set_low().map_err(|_| DisplayError::DCError)?; - - send_u8(&mut self.spi, cmds).map_err(|_| DisplayError::BusWriteError)?; - Ok(()) - } - - fn send_data(&mut self, buf: DataFormat<'_>) -> Result<(), DisplayError> { - // 1 = data, 0 = command - self.dc.set_high().map_err(|_| DisplayError::DCError)?; - - send_u8(&mut self.spi, buf).map_err(|_| DisplayError::BusWriteError)?; - Ok(()) - } - } - - fn send_u8(spi: &mut T, words: DataFormat<'_>) -> Result<(), T::Error> { - match words { - DataFormat::U8(slice) => spi.write(slice), - DataFormat::U16(slice) => { - use byte_slice_cast::*; - spi.write(slice.as_byte_slice()) - } - DataFormat::U16LE(slice) => { - use byte_slice_cast::*; - for v in slice.as_mut() { - *v = v.to_le(); - } - spi.write(slice.as_byte_slice()) - } - DataFormat::U16BE(slice) => { - use byte_slice_cast::*; - for v in slice.as_mut() { - *v = v.to_be(); - } - spi.write(slice.as_byte_slice()) - } - DataFormat::U8Iter(iter) => { - let mut buf = [0; 32]; - let mut i = 0; - - for v in iter.into_iter() { - buf[i] = v; - i += 1; - - if i == buf.len() { - spi.write(&buf)?; - i = 0; - } - } - - if i > 0 { - spi.write(&buf[..i])?; - } - - Ok(()) - } - DataFormat::U16LEIter(iter) => { - use byte_slice_cast::*; - let mut buf = [0; 32]; - let mut i = 0; - - for v in iter.map(u16::to_le) { - buf[i] = v; - i += 1; - - if i == buf.len() { - spi.write(&buf.as_byte_slice())?; - i = 0; - } - } - - if i > 0 { - spi.write(&buf[..i].as_byte_slice())?; - } - - Ok(()) - } - DataFormat::U16BEIter(iter) => { - use byte_slice_cast::*; - let mut buf = [0; 64]; - let mut i = 0; - let len = buf.len(); - - for v in iter.map(u16::to_be) { - buf[i] = v; - i += 1; - - if i == len { - spi.write(&buf.as_byte_slice())?; - i = 0; - } - } - - if i > 0 { - spi.write(&buf[..i].as_byte_slice())?; - } - - Ok(()) - } - _ => unimplemented!(), - } - } -} diff --git a/examples/rp/src/bin/spi_sdmmc.rs b/examples/rp/src/bin/spi_sdmmc.rs new file mode 100644 index 000000000..4cbc82f7b --- /dev/null +++ b/examples/rp/src/bin/spi_sdmmc.rs @@ -0,0 +1,83 @@ +//! This example shows how to use `embedded-sdmmc` with the RP2040 chip, over SPI. +//! +//! The example will attempt to read a file `MY_FILE.TXT` from the root directory +//! of the SD card and print its contents. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_embedded_hal::SetConfig; +use embassy_executor::Spawner; +use embassy_rp::spi::Spi; +use embassy_rp::{gpio, spi}; +use embedded_hal_bus::spi::ExclusiveDevice; +use embedded_sdmmc::sdcard::{DummyCsPin, SdCard}; +use gpio::{Level, Output}; +use {defmt_rtt as _, panic_probe as _}; + +struct DummyTimesource(); + +impl embedded_sdmmc::TimeSource for DummyTimesource { + fn get_timestamp(&self) -> embedded_sdmmc::Timestamp { + embedded_sdmmc::Timestamp { + year_since_1970: 0, + zero_indexed_month: 0, + zero_indexed_day: 0, + hours: 0, + minutes: 0, + seconds: 0, + } + } +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + embassy_rp::pac::SIO.spinlock(31).write_value(1); + let p = embassy_rp::init(Default::default()); + + // SPI clock needs to be running at <= 400kHz during initialization + let mut config = spi::Config::default(); + config.frequency = 400_000; + let spi = Spi::new_blocking(p.SPI1, p.PIN_10, p.PIN_11, p.PIN_12, config); + // Use a dummy cs pin here, for embedded-hal SpiDevice compatibility reasons + let spi_dev = ExclusiveDevice::new_no_delay(spi, DummyCsPin); + // Real cs pin + let cs = Output::new(p.PIN_16, Level::High); + + let sdcard = SdCard::new(spi_dev, cs, embassy_time::Delay); + info!("Card size is {} bytes", sdcard.num_bytes().unwrap()); + + // Now that the card is initialized, the SPI clock can go faster + let mut config = spi::Config::default(); + config.frequency = 16_000_000; + sdcard.spi(|dev| dev.bus_mut().set_config(&config)).ok(); + + // Now let's look for volumes (also known as partitions) on our block device. + // To do this we need a Volume Manager. It will take ownership of the block device. + let mut volume_mgr = embedded_sdmmc::VolumeManager::new(sdcard, DummyTimesource()); + + // Try and access Volume 0 (i.e. the first partition). + // The volume object holds information about the filesystem on that volume. + let mut volume0 = volume_mgr.open_volume(embedded_sdmmc::VolumeIdx(0)).unwrap(); + info!("Volume 0: {:?}", defmt::Debug2Format(&volume0)); + + // Open the root directory (mutably borrows from the volume). + let mut root_dir = volume0.open_root_dir().unwrap(); + + // Open a file called "MY_FILE.TXT" in the root directory + // This mutably borrows the directory. + let mut my_file = root_dir + .open_file_in_dir("MY_FILE.TXT", embedded_sdmmc::Mode::ReadOnly) + .unwrap(); + + // Print the contents of the file + while !my_file.is_eof() { + let mut buf = [0u8; 32]; + if let Ok(n) = my_file.read(&mut buf) { + info!("{:a}", buf[..n]); + } + } + + loop {} +} diff --git a/examples/rp/src/bin/uart_buffered_split.rs b/examples/rp/src/bin/uart_buffered_split.rs index fac61aa04..468d2b61a 100644 --- a/examples/rp/src/bin/uart_buffered_split.rs +++ b/examples/rp/src/bin/uart_buffered_split.rs @@ -31,7 +31,7 @@ async fn main(spawner: Spawner) { static RX_BUF: StaticCell<[u8; 16]> = StaticCell::new(); let rx_buf = &mut RX_BUF.init([0; 16])[..]; let uart = BufferedUart::new(uart, Irqs, tx_pin, rx_pin, tx_buf, rx_buf, Config::default()); - let (rx, mut tx) = uart.split(); + let (mut tx, rx) = uart.split(); unwrap!(spawner.spawn(reader(rx))); diff --git a/examples/rp/src/bin/uart_r503.rs b/examples/rp/src/bin/uart_r503.rs new file mode 100644 index 000000000..085be280b --- /dev/null +++ b/examples/rp/src/bin/uart_r503.rs @@ -0,0 +1,158 @@ +#![no_std] +#![no_main] + +use defmt::{debug, error, info}; +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::peripherals::UART0; +use embassy_rp::uart::{Config, DataBits, InterruptHandler as UARTInterruptHandler, Parity, StopBits, Uart}; +use embassy_time::{with_timeout, Duration, Timer}; +use heapless::Vec; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(pub struct Irqs { + UART0_IRQ => UARTInterruptHandler; +}); + +const START: u16 = 0xEF01; +const ADDRESS: u32 = 0xFFFFFFFF; + +// ================================================================================ + +// Data package format +// Name Length Description +// ========================================================================================================== +// Start 2 bytes Fixed value of 0xEF01; High byte transferred first. +// Address 4 bytes Default value is 0xFFFFFFFF, which can be modified by command. +// High byte transferred first and at wrong adder value, module +// will reject to transfer. +// PID 1 byte 01H Command packet; +// 02H Data packet; Data packet shall not appear alone in executing +// processs, must follow command packet or acknowledge packet. +// 07H Acknowledge packet; +// 08H End of Data packet. +// LENGTH 2 bytes Refers to the length of package content (command packets and data packets) +// plus the length of Checksum (2 bytes). Unit is byte. Max length is 256 bytes. +// And high byte is transferred first. +// DATA - It can be commands, data, command’s parameters, acknowledge result, etc. +// (fingerprint character value, template are all deemed as data); +// SUM 2 bytes The arithmetic sum of package identifier, package length and all package +// contens. Overflowing bits are omitted. high byte is transferred first. + +// ================================================================================ + +// Checksum is calculated on 'length (2 bytes) + data (??)'. +fn compute_checksum(buf: Vec) -> u16 { + let mut checksum = 0u16; + + let check_end = buf.len(); + let checked_bytes = &buf[6..check_end]; + for byte in checked_bytes { + checksum += (*byte) as u16; + } + return checksum; +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + info!("Start"); + + let p = embassy_rp::init(Default::default()); + + // Initialize the fingerprint scanner. + let mut config = Config::default(); + config.baudrate = 57600; + config.stop_bits = StopBits::STOP1; + config.data_bits = DataBits::DataBits8; + config.parity = Parity::ParityNone; + + let (uart, tx_pin, tx_dma, rx_pin, rx_dma) = (p.UART0, p.PIN_16, p.DMA_CH0, p.PIN_17, p.DMA_CH1); + let uart = Uart::new(uart, tx_pin, rx_pin, Irqs, tx_dma, rx_dma, config); + let (mut tx, mut rx) = uart.split(); + + let mut vec_buf: Vec = heapless::Vec::new(); + let mut data: Vec = heapless::Vec::new(); + + let mut speeds: Vec = heapless::Vec::new(); + let _ = speeds.push(0xC8); // Slow + let _ = speeds.push(0x20); // Medium + let _ = speeds.push(0x02); // Fast + + // Cycle through the three colours Red, Blue and Purple forever. + loop { + for colour in 1..=3 { + for speed in &speeds { + // Set the data first, because the length is dependent on that. + // However, we write the length bits before we do the data. + data.clear(); + let _ = data.push(0x01); // ctrl=Breathing light + let _ = data.push(*speed); + let _ = data.push(colour as u8); // colour=Red, Blue, Purple + let _ = data.push(0x00); // times=Infinite + + // Clear buffers + vec_buf.clear(); + + // START + let _ = vec_buf.extend_from_slice(&START.to_be_bytes()[..]); + + // ADDRESS + let _ = vec_buf.extend_from_slice(&ADDRESS.to_be_bytes()[..]); + + // PID + let _ = vec_buf.extend_from_slice(&[0x01]); + + // LENGTH + let len: u16 = (1 + data.len() + 2).try_into().unwrap(); + let _ = vec_buf.extend_from_slice(&len.to_be_bytes()[..]); + + // COMMAND + let _ = vec_buf.push(0x35); // Command: AuraLedConfig + + // DATA + let _ = vec_buf.extend_from_slice(&data); + + // SUM + let chk = compute_checksum(vec_buf.clone()); + let _ = vec_buf.extend_from_slice(&chk.to_be_bytes()[..]); + + // ===== + + // Send command buffer. + let data_write: [u8; 16] = vec_buf.clone().into_array().unwrap(); + debug!(" write='{:?}'", data_write[..]); + match tx.write(&data_write).await { + Ok(..) => info!("Write successful."), + Err(e) => error!("Write error: {:?}", e), + } + + // ===== + + // Read command buffer. + let mut read_buf: [u8; 1] = [0; 1]; // Can only read one byte at a time! + let mut data_read: Vec = heapless::Vec::new(); // Save buffer. + + info!("Attempting read."); + loop { + // Some commands, like `Img2Tz()` needs longer, but we hard-code this to 200ms + // for this command. + match with_timeout(Duration::from_millis(200), rx.read(&mut read_buf)).await { + Ok(..) => { + // Extract and save read byte. + debug!(" r='{=u8:#04x}H' ({:03}D)", read_buf[0], read_buf[0]); + let _ = data_read.push(read_buf[0]).unwrap(); + } + Err(..) => break, // TimeoutError -> Ignore. + } + } + info!("Read successful"); + debug!(" read='{:?}'", data_read[..]); + + Timer::after_secs(3).await; + info!("Changing speed."); + } + + info!("Changing colour."); + } + } +} diff --git a/examples/rp/src/bin/usb_ethernet.rs b/examples/rp/src/bin/usb_ethernet.rs index 01f0d5967..9a15125d4 100644 --- a/examples/rp/src/bin/usb_ethernet.rs +++ b/examples/rp/src/bin/usb_ethernet.rs @@ -8,7 +8,8 @@ use defmt::*; use embassy_executor::Spawner; use embassy_net::tcp::TcpSocket; -use embassy_net::{Stack, StackResources}; +use embassy_net::StackResources; +use embassy_rp::clocks::RoscRng; use embassy_rp::peripherals::USB; use embassy_rp::usb::{Driver, InterruptHandler}; use embassy_rp::{bind_interrupts, peripherals}; @@ -16,6 +17,7 @@ use embassy_usb::class::cdc_ncm::embassy_net::{Device, Runner, State as NetState use embassy_usb::class::cdc_ncm::{CdcNcmClass, State}; use embassy_usb::{Builder, Config, UsbDevice}; use embedded_io_async::Write; +use rand::RngCore; use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _}; @@ -38,13 +40,14 @@ async fn usb_ncm_task(class: Runner<'static, MyDriver, MTU>) -> ! { } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static, MTU>>) -> ! { + runner.run().await } #[embassy_executor::main] async fn main(spawner: Spawner) { let p = embassy_rp::init(Default::default()); + let mut rng = RoscRng; // Create the driver, from the HAL. let driver = Driver::new(p.USB, Irqs); @@ -64,14 +67,12 @@ async fn main(spawner: Spawner) { config.device_protocol = 0x01; // Create embassy-usb DeviceBuilder using the driver and config. - static DEVICE_DESC: StaticCell<[u8; 256]> = StaticCell::new(); static CONFIG_DESC: StaticCell<[u8; 256]> = StaticCell::new(); static BOS_DESC: StaticCell<[u8; 256]> = StaticCell::new(); static CONTROL_BUF: StaticCell<[u8; 128]> = StaticCell::new(); let mut builder = Builder::new( driver, config, - &mut DEVICE_DESC.init([0; 256])[..], &mut CONFIG_DESC.init([0; 256])[..], &mut BOS_DESC.init([0; 256])[..], &mut [], // no msos descriptors @@ -104,19 +105,13 @@ async fn main(spawner: Spawner) { //}); // Generate random seed - let seed = 1234; // guaranteed random, chosen by a fair dice roll + let seed = rng.next_u64(); // Init network stack - static STACK: StaticCell>> = StaticCell::new(); - static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<2>::new()), - seed, - )); + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); // And now we can use it! diff --git a/examples/rp/src/bin/usb_hid_keyboard.rs b/examples/rp/src/bin/usb_hid_keyboard.rs index b5ac16245..a7cb322d8 100644 --- a/examples/rp/src/bin/usb_hid_keyboard.rs +++ b/examples/rp/src/bin/usb_hid_keyboard.rs @@ -36,13 +36,12 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; // You can also add a Microsoft OS descriptor. let mut msos_descriptor = [0; 256]; let mut control_buf = [0; 64]; - let request_handler = MyRequestHandler {}; + let mut request_handler = MyRequestHandler {}; let mut device_handler = MyDeviceHandler::new(); let mut state = State::new(); @@ -50,7 +49,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut msos_descriptor, @@ -62,7 +60,7 @@ async fn main(_spawner: Spawner) { // Create classes on the builder. let config = embassy_usb::class::hid::Config { report_descriptor: KeyboardReport::desc(), - request_handler: Some(&request_handler), + request_handler: None, poll_ms: 60, max_packet_size: 64, }; @@ -116,7 +114,7 @@ async fn main(_spawner: Spawner) { }; let out_fut = async { - reader.run(false, &request_handler).await; + reader.run(false, &mut request_handler).await; }; // Run everything concurrently. @@ -127,21 +125,21 @@ async fn main(_spawner: Spawner) { struct MyRequestHandler {} impl RequestHandler for MyRequestHandler { - fn get_report(&self, id: ReportId, _buf: &mut [u8]) -> Option { + fn get_report(&mut self, id: ReportId, _buf: &mut [u8]) -> Option { info!("Get report for {:?}", id); None } - fn set_report(&self, id: ReportId, data: &[u8]) -> OutResponse { + fn set_report(&mut self, id: ReportId, data: &[u8]) -> OutResponse { info!("Set report for {:?}: {=[u8]}", id, data); OutResponse::Accepted } - fn set_idle_ms(&self, id: Option, dur: u32) { + fn set_idle_ms(&mut self, id: Option, dur: u32) { info!("Set idle rate for {:?} to {:?}", id, dur); } - fn get_idle_ms(&self, id: Option) -> Option { + fn get_idle_ms(&mut self, id: Option) -> Option { info!("Get idle rate for {:?}", id); None } diff --git a/examples/rp/src/bin/usb_hid_mouse.rs b/examples/rp/src/bin/usb_hid_mouse.rs new file mode 100644 index 000000000..5ee650910 --- /dev/null +++ b/examples/rp/src/bin/usb_hid_mouse.rs @@ -0,0 +1,173 @@ +#![no_std] +#![no_main] + +use core::sync::atomic::{AtomicBool, Ordering}; + +use defmt::*; +use embassy_executor::Spawner; +use embassy_futures::join::join; +use embassy_rp::bind_interrupts; +use embassy_rp::clocks::RoscRng; +use embassy_rp::peripherals::USB; +use embassy_rp::usb::{Driver, InterruptHandler}; +use embassy_time::Timer; +use embassy_usb::class::hid::{HidReaderWriter, ReportId, RequestHandler, State}; +use embassy_usb::control::OutResponse; +use embassy_usb::{Builder, Config, Handler}; +use rand::Rng; +use usbd_hid::descriptor::{MouseReport, SerializedDescriptor}; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + USBCTRL_IRQ => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + // Create the driver, from the HAL. + let driver = Driver::new(p.USB, Irqs); + + // Create embassy-usb Config + let mut config = Config::new(0xc0de, 0xcafe); + config.manufacturer = Some("Embassy"); + config.product = Some("HID keyboard example"); + config.serial_number = Some("12345678"); + config.max_power = 100; + config.max_packet_size_0 = 64; + + // Create embassy-usb DeviceBuilder using the driver and config. + // It needs some buffers for building the descriptors. + let mut config_descriptor = [0; 256]; + let mut bos_descriptor = [0; 256]; + // You can also add a Microsoft OS descriptor. + let mut msos_descriptor = [0; 256]; + let mut control_buf = [0; 64]; + let mut request_handler = MyRequestHandler {}; + let mut device_handler = MyDeviceHandler::new(); + + let mut state = State::new(); + + let mut builder = Builder::new( + driver, + config, + &mut config_descriptor, + &mut bos_descriptor, + &mut msos_descriptor, + &mut control_buf, + ); + + builder.handler(&mut device_handler); + + // Create classes on the builder. + let config = embassy_usb::class::hid::Config { + report_descriptor: MouseReport::desc(), + request_handler: None, + poll_ms: 60, + max_packet_size: 64, + }; + let hid = HidReaderWriter::<_, 1, 8>::new(&mut builder, &mut state, config); + + // Build the builder. + let mut usb = builder.build(); + + // Run the USB device. + let usb_fut = usb.run(); + + let (reader, mut writer) = hid.split(); + + // Do stuff with the class! + let in_fut = async { + let mut rng = RoscRng; + + loop { + // every 1 second + _ = Timer::after_secs(1).await; + let report = MouseReport { + buttons: 0, + x: rng.gen_range(-100..100), // random small x movement + y: rng.gen_range(-100..100), // random small y movement + wheel: 0, + pan: 0, + }; + // Send the report. + match writer.write_serialize(&report).await { + Ok(()) => {} + Err(e) => warn!("Failed to send report: {:?}", e), + } + } + }; + + let out_fut = async { + reader.run(false, &mut request_handler).await; + }; + + // Run everything concurrently. + // If we had made everything `'static` above instead, we could do this using separate tasks instead. + join(usb_fut, join(in_fut, out_fut)).await; +} + +struct MyRequestHandler {} + +impl RequestHandler for MyRequestHandler { + fn get_report(&mut self, id: ReportId, _buf: &mut [u8]) -> Option { + info!("Get report for {:?}", id); + None + } + + fn set_report(&mut self, id: ReportId, data: &[u8]) -> OutResponse { + info!("Set report for {:?}: {=[u8]}", id, data); + OutResponse::Accepted + } + + fn set_idle_ms(&mut self, id: Option, dur: u32) { + info!("Set idle rate for {:?} to {:?}", id, dur); + } + + fn get_idle_ms(&mut self, id: Option) -> Option { + info!("Get idle rate for {:?}", id); + None + } +} + +struct MyDeviceHandler { + configured: AtomicBool, +} + +impl MyDeviceHandler { + fn new() -> Self { + MyDeviceHandler { + configured: AtomicBool::new(false), + } + } +} + +impl Handler for MyDeviceHandler { + fn enabled(&mut self, enabled: bool) { + self.configured.store(false, Ordering::Relaxed); + if enabled { + info!("Device enabled"); + } else { + info!("Device disabled"); + } + } + + fn reset(&mut self) { + self.configured.store(false, Ordering::Relaxed); + info!("Bus reset, the Vbus current limit is 100mA"); + } + + fn addressed(&mut self, addr: u8) { + self.configured.store(false, Ordering::Relaxed); + info!("USB address set to: {}", addr); + } + + fn configured(&mut self, configured: bool) { + self.configured.store(configured, Ordering::Relaxed); + if configured { + info!("Device configured, it may now draw up to the configured current limit from Vbus.") + } else { + info!("Device is no longer configured, the Vbus current limit is 100mA."); + } + } +} diff --git a/examples/rp/src/bin/usb_midi.rs b/examples/rp/src/bin/usb_midi.rs index 95306a35c..11db1b2e1 100644 --- a/examples/rp/src/bin/usb_midi.rs +++ b/examples/rp/src/bin/usb_midi.rs @@ -46,7 +46,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 64]; @@ -54,7 +53,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], // no msos descriptors diff --git a/examples/rp/src/bin/usb_raw.rs b/examples/rp/src/bin/usb_raw.rs index a6c8a5b2e..97e7e0244 100644 --- a/examples/rp/src/bin/usb_raw.rs +++ b/examples/rp/src/bin/usb_raw.rs @@ -93,7 +93,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut msos_descriptor = [0; 256]; @@ -106,7 +105,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut msos_descriptor, diff --git a/examples/rp/src/bin/usb_raw_bulk.rs b/examples/rp/src/bin/usb_raw_bulk.rs index 0dc8e9f72..331c3da4c 100644 --- a/examples/rp/src/bin/usb_raw_bulk.rs +++ b/examples/rp/src/bin/usb_raw_bulk.rs @@ -71,7 +71,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut msos_descriptor = [0; 256]; @@ -80,7 +79,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut msos_descriptor, diff --git a/examples/rp/src/bin/usb_serial.rs b/examples/rp/src/bin/usb_serial.rs index ab24a994c..4a802994a 100644 --- a/examples/rp/src/bin/usb_serial.rs +++ b/examples/rp/src/bin/usb_serial.rs @@ -5,15 +5,15 @@ #![no_std] #![no_main] -use defmt::{info, panic}; +use defmt::{info, panic, unwrap}; use embassy_executor::Spawner; -use embassy_futures::join::join; use embassy_rp::bind_interrupts; use embassy_rp::peripherals::USB; use embassy_rp::usb::{Driver, Instance, InterruptHandler}; use embassy_usb::class::cdc_acm::{CdcAcmClass, State}; use embassy_usb::driver::EndpointError; -use embassy_usb::{Builder, Config}; +use embassy_usb::UsbDevice; +use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { @@ -21,7 +21,7 @@ bind_interrupts!(struct Irqs { }); #[embassy_executor::main] -async fn main(_spawner: Spawner) { +async fn main(spawner: Spawner) { info!("Hello there!"); let p = embassy_rp::init(Default::default()); @@ -30,61 +30,69 @@ async fn main(_spawner: Spawner) { let driver = Driver::new(p.USB, Irqs); // Create embassy-usb Config - let mut config = Config::new(0xc0de, 0xcafe); - config.manufacturer = Some("Embassy"); - config.product = Some("USB-serial example"); - config.serial_number = Some("12345678"); - config.max_power = 100; - config.max_packet_size_0 = 64; + let config = { + let mut config = embassy_usb::Config::new(0xc0de, 0xcafe); + config.manufacturer = Some("Embassy"); + config.product = Some("USB-serial example"); + config.serial_number = Some("12345678"); + config.max_power = 100; + config.max_packet_size_0 = 64; - // Required for windows compatibility. - // https://developer.nordicsemi.com/nRF_Connect_SDK/doc/1.9.1/kconfig/CONFIG_CDC_ACM_IAD.html#help - config.device_class = 0xEF; - config.device_sub_class = 0x02; - config.device_protocol = 0x01; - config.composite_with_iads = true; + // Required for windows compatibility. + // https://developer.nordicsemi.com/nRF_Connect_SDK/doc/1.9.1/kconfig/CONFIG_CDC_ACM_IAD.html#help + config.device_class = 0xEF; + config.device_sub_class = 0x02; + config.device_protocol = 0x01; + config.composite_with_iads = true; + config + }; // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; - let mut config_descriptor = [0; 256]; - let mut bos_descriptor = [0; 256]; - let mut control_buf = [0; 64]; + let mut builder = { + static CONFIG_DESCRIPTOR: StaticCell<[u8; 256]> = StaticCell::new(); + static BOS_DESCRIPTOR: StaticCell<[u8; 256]> = StaticCell::new(); + static CONTROL_BUF: StaticCell<[u8; 64]> = StaticCell::new(); - let mut state = State::new(); - - let mut builder = Builder::new( - driver, - config, - &mut device_descriptor, - &mut config_descriptor, - &mut bos_descriptor, - &mut [], // no msos descriptors - &mut control_buf, - ); - - // Create classes on the builder. - let mut class = CdcAcmClass::new(&mut builder, &mut state, 64); - - // Build the builder. - let mut usb = builder.build(); - - // Run the USB device. - let usb_fut = usb.run(); - - // Do stuff with the class! - let echo_fut = async { - loop { - class.wait_connection().await; - info!("Connected"); - let _ = echo(&mut class).await; - info!("Disconnected"); - } + let builder = embassy_usb::Builder::new( + driver, + config, + CONFIG_DESCRIPTOR.init([0; 256]), + BOS_DESCRIPTOR.init([0; 256]), + &mut [], // no msos descriptors + CONTROL_BUF.init([0; 64]), + ); + builder }; - // Run everything concurrently. - // If we had made everything `'static` above instead, we could do this using separate tasks instead. - join(usb_fut, echo_fut).await; + // Create classes on the builder. + let mut class = { + static STATE: StaticCell = StaticCell::new(); + let state = STATE.init(State::new()); + CdcAcmClass::new(&mut builder, state, 64) + }; + + // Build the builder. + let usb = builder.build(); + + // Run the USB device. + unwrap!(spawner.spawn(usb_task(usb))); + + // Do stuff with the class! + loop { + class.wait_connection().await; + info!("Connected"); + let _ = echo(&mut class).await; + info!("Disconnected"); + } +} + +type MyUsbDriver = Driver<'static, USB>; +type MyUsbDevice = UsbDevice<'static, MyUsbDriver>; + +#[embassy_executor::task] +async fn usb_task(mut usb: MyUsbDevice) -> ! { + usb.run().await } struct Disconnected {} diff --git a/examples/rp/src/bin/usb_serial_with_handler.rs b/examples/rp/src/bin/usb_serial_with_handler.rs new file mode 100644 index 000000000..a9e65be70 --- /dev/null +++ b/examples/rp/src/bin/usb_serial_with_handler.rs @@ -0,0 +1,64 @@ +//! This example shows how to use USB (Universal Serial Bus) in the RP2040 chip. +//! +//! This creates the possibility to send log::info/warn/error/debug! to USB serial port. + +#![no_std] +#![no_main] + +use core::str; + +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::peripherals::USB; +use embassy_rp::rom_data::reset_to_usb_boot; +use embassy_rp::usb::{Driver, InterruptHandler}; +use embassy_time::Timer; +use embassy_usb_logger::ReceiverHandler; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + USBCTRL_IRQ => InterruptHandler; +}); + +struct Handler; + +impl ReceiverHandler for Handler { + async fn handle_data(&self, data: &[u8]) { + if let Ok(data) = str::from_utf8(data) { + let data = data.trim(); + + // If you are using elf2uf2-term with the '-t' flag, then when closing the serial monitor, + // this will automatically put the pico into boot mode + if data == "q" || data == "elf2uf2-term" { + reset_to_usb_boot(0, 0); // Restart the chip + } else if data.eq_ignore_ascii_case("hello") { + log::info!("World!"); + } else { + log::info!("Recieved: {:?}", data); + } + } + } + + fn new() -> Self { + Self + } +} + +#[embassy_executor::task] +async fn logger_task(driver: Driver<'static, USB>) { + embassy_usb_logger::run!(1024, log::LevelFilter::Info, driver, Handler); +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let driver = Driver::new(p.USB, Irqs); + spawner.spawn(logger_task(driver)).unwrap(); + + let mut counter = 0; + loop { + counter += 1; + log::info!("Tick {}", counter); + Timer::after_secs(1).await; + } +} diff --git a/examples/rp/src/bin/usb_serial_with_logger.rs b/examples/rp/src/bin/usb_serial_with_logger.rs new file mode 100644 index 000000000..f9cfdef94 --- /dev/null +++ b/examples/rp/src/bin/usb_serial_with_logger.rs @@ -0,0 +1,115 @@ +//! This example shows how to use USB (Universal Serial Bus) in the RP2040 chip as well as how to create multiple usb classes for one device +//! +//! This creates a USB serial port that echos. It will also print out logging information on a separate serial device + +#![no_std] +#![no_main] + +use defmt::{info, panic}; +use embassy_executor::Spawner; +use embassy_futures::join::join; +use embassy_rp::bind_interrupts; +use embassy_rp::peripherals::USB; +use embassy_rp::usb::{Driver, Instance, InterruptHandler}; +use embassy_usb::class::cdc_acm::{CdcAcmClass, State}; +use embassy_usb::driver::EndpointError; +use embassy_usb::{Builder, Config}; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + USBCTRL_IRQ => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + info!("Hello there!"); + + let p = embassy_rp::init(Default::default()); + + // Create the driver, from the HAL. + let driver = Driver::new(p.USB, Irqs); + + // Create embassy-usb Config + let mut config = Config::new(0xc0de, 0xcafe); + config.manufacturer = Some("Embassy"); + config.product = Some("USB-serial example"); + config.serial_number = Some("12345678"); + config.max_power = 100; + config.max_packet_size_0 = 64; + + // Required for windows compatibility. + // https://developer.nordicsemi.com/nRF_Connect_SDK/doc/1.9.1/kconfig/CONFIG_CDC_ACM_IAD.html#help + config.device_class = 0xEF; + config.device_sub_class = 0x02; + config.device_protocol = 0x01; + config.composite_with_iads = true; + + // Create embassy-usb DeviceBuilder using the driver and config. + // It needs some buffers for building the descriptors. + let mut config_descriptor = [0; 256]; + let mut bos_descriptor = [0; 256]; + let mut control_buf = [0; 64]; + + let mut state = State::new(); + let mut logger_state = State::new(); + + let mut builder = Builder::new( + driver, + config, + &mut config_descriptor, + &mut bos_descriptor, + &mut [], // no msos descriptors + &mut control_buf, + ); + + // Create classes on the builder. + let mut class = CdcAcmClass::new(&mut builder, &mut state, 64); + + // Create a class for the logger + let logger_class = CdcAcmClass::new(&mut builder, &mut logger_state, 64); + + // Creates the logger and returns the logger future + // Note: You'll need to use log::info! afterwards instead of info! for this to work (this also applies to all the other log::* macros) + let log_fut = embassy_usb_logger::with_class!(1024, log::LevelFilter::Info, logger_class); + + // Build the builder. + let mut usb = builder.build(); + + // Run the USB device. + let usb_fut = usb.run(); + + // Do stuff with the class! + let echo_fut = async { + loop { + class.wait_connection().await; + log::info!("Connected"); + let _ = echo(&mut class).await; + log::info!("Disconnected"); + } + }; + + // Run everything concurrently. + // If we had made everything `'static` above instead, we could do this using separate tasks instead. + join(usb_fut, join(echo_fut, log_fut)).await; +} + +struct Disconnected {} + +impl From for Disconnected { + fn from(val: EndpointError) -> Self { + match val { + EndpointError::BufferOverflow => panic!("Buffer overflow"), + EndpointError::Disabled => Disconnected {}, + } + } +} + +async fn echo<'d, T: Instance + 'd>(class: &mut CdcAcmClass<'d, Driver<'d, T>>) -> Result<(), Disconnected> { + let mut buf = [0; 64]; + loop { + let n = class.read_packet(&mut buf).await?; + let data = &buf[..n]; + info!("data: {:x}", data); + class.write_packet(data).await?; + } +} diff --git a/examples/rp/src/bin/usb_webusb.rs b/examples/rp/src/bin/usb_webusb.rs new file mode 100644 index 000000000..e73938ac9 --- /dev/null +++ b/examples/rp/src/bin/usb_webusb.rs @@ -0,0 +1,155 @@ +//! This example shows how to use USB (Universal Serial Bus) in the RP2040 chip. +//! +//! This creates a WebUSB capable device that echoes data back to the host. +//! +//! To test this in the browser (ideally host this on localhost:8080, to test the landing page +//! feature): +//! ```js +//! (async () => { +//! const device = await navigator.usb.requestDevice({ filters: [{ vendorId: 0xf569 }] }); +//! await device.open(); +//! await device.claimInterface(1); +//! device.transferIn(1, 64).then(data => console.log(data)); +//! await device.transferOut(1, new Uint8Array([1,2,3])); +//! })(); +//! ``` + +#![no_std] +#![no_main] + +use defmt::info; +use embassy_executor::Spawner; +use embassy_futures::join::join; +use embassy_rp::bind_interrupts; +use embassy_rp::peripherals::USB; +use embassy_rp::usb::{Driver as UsbDriver, InterruptHandler}; +use embassy_usb::class::web_usb::{Config as WebUsbConfig, State, Url, WebUsb}; +use embassy_usb::driver::{Driver, Endpoint, EndpointIn, EndpointOut}; +use embassy_usb::msos::{self, windows_version}; +use embassy_usb::{Builder, Config}; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + USBCTRL_IRQ => InterruptHandler; +}); + +// This is a randomly generated GUID to allow clients on Windows to find our device +const DEVICE_INTERFACE_GUIDS: &[&str] = &["{AFB9A6FB-30BA-44BC-9232-806CFC875321}"]; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + + // Create the driver, from the HAL. + let driver = UsbDriver::new(p.USB, Irqs); + + // Create embassy-usb Config + let mut config = Config::new(0xf569, 0x0001); + config.manufacturer = Some("Embassy"); + config.product = Some("WebUSB example"); + config.serial_number = Some("12345678"); + config.max_power = 100; + config.max_packet_size_0 = 64; + + // Required for windows compatibility. + // https://developer.nordicsemi.com/nRF_Connect_SDK/doc/1.9.1/kconfig/CONFIG_CDC_ACM_IAD.html#help + config.device_class = 0xff; + config.device_sub_class = 0x00; + config.device_protocol = 0x00; + + // Create embassy-usb DeviceBuilder using the driver and config. + // It needs some buffers for building the descriptors. + let mut config_descriptor = [0; 256]; + let mut bos_descriptor = [0; 256]; + let mut control_buf = [0; 64]; + let mut msos_descriptor = [0; 256]; + + let webusb_config = WebUsbConfig { + max_packet_size: 64, + vendor_code: 1, + // If defined, shows a landing page which the device manufacturer would like the user to visit in order to control their device. Suggest the user to navigate to this URL when the device is connected. + landing_url: Some(Url::new("http://localhost:8080")), + }; + + let mut state = State::new(); + + let mut builder = Builder::new( + driver, + config, + &mut config_descriptor, + &mut bos_descriptor, + &mut msos_descriptor, + &mut control_buf, + ); + + // Add the Microsoft OS Descriptor (MSOS/MOD) descriptor. + // We tell Windows that this entire device is compatible with the "WINUSB" feature, + // which causes it to use the built-in WinUSB driver automatically, which in turn + // can be used by libusb/rusb software without needing a custom driver or INF file. + // In principle you might want to call msos_feature() just on a specific function, + // if your device also has other functions that still use standard class drivers. + builder.msos_descriptor(windows_version::WIN8_1, 0); + builder.msos_feature(msos::CompatibleIdFeatureDescriptor::new("WINUSB", "")); + builder.msos_feature(msos::RegistryPropertyFeatureDescriptor::new( + "DeviceInterfaceGUIDs", + msos::PropertyData::RegMultiSz(DEVICE_INTERFACE_GUIDS), + )); + + // Create classes on the builder (WebUSB just needs some setup, but doesn't return anything) + WebUsb::configure(&mut builder, &mut state, &webusb_config); + // Create some USB bulk endpoints for testing. + let mut endpoints = WebEndpoints::new(&mut builder, &webusb_config); + + // Build the builder. + let mut usb = builder.build(); + + // Run the USB device. + let usb_fut = usb.run(); + + // Do some WebUSB transfers. + let webusb_fut = async { + loop { + endpoints.wait_connected().await; + info!("Connected"); + endpoints.echo().await; + } + }; + + // Run everything concurrently. + // If we had made everything `'static` above instead, we could do this using separate tasks instead. + join(usb_fut, webusb_fut).await; +} + +struct WebEndpoints<'d, D: Driver<'d>> { + write_ep: D::EndpointIn, + read_ep: D::EndpointOut, +} + +impl<'d, D: Driver<'d>> WebEndpoints<'d, D> { + fn new(builder: &mut Builder<'d, D>, config: &'d WebUsbConfig<'d>) -> Self { + let mut func = builder.function(0xff, 0x00, 0x00); + let mut iface = func.interface(); + let mut alt = iface.alt_setting(0xff, 0x00, 0x00, None); + + let write_ep = alt.endpoint_bulk_in(config.max_packet_size); + let read_ep = alt.endpoint_bulk_out(config.max_packet_size); + + WebEndpoints { write_ep, read_ep } + } + + // Wait until the device's endpoints are enabled. + async fn wait_connected(&mut self) { + self.read_ep.wait_enabled().await + } + + // Echo data back to the host. + async fn echo(&mut self) { + let mut buf = [0; 64]; + loop { + let n = self.read_ep.read(&mut buf).await.unwrap(); + let data = &buf[..n]; + info!("Data read: {:x}", data); + self.write_ep.write(data).await.unwrap(); + } + } +} diff --git a/examples/rp/src/bin/wifi_ap_tcp_server.rs b/examples/rp/src/bin/wifi_ap_tcp_server.rs index b60852359..4c9651433 100644 --- a/examples/rp/src/bin/wifi_ap_tcp_server.rs +++ b/examples/rp/src/bin/wifi_ap_tcp_server.rs @@ -11,13 +11,15 @@ use cyw43_pio::PioSpi; use defmt::*; use embassy_executor::Spawner; use embassy_net::tcp::TcpSocket; -use embassy_net::{Config, Stack, StackResources}; +use embassy_net::{Config, StackResources}; use embassy_rp::bind_interrupts; +use embassy_rp::clocks::RoscRng; use embassy_rp::gpio::{Level, Output}; use embassy_rp::peripherals::{DMA_CH0, PIO0}; use embassy_rp::pio::{InterruptHandler, Pio}; use embassy_time::Duration; use embedded_io_async::Write; +use rand::RngCore; use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _}; @@ -26,13 +28,13 @@ bind_interrupts!(struct Irqs { }); #[embassy_executor::task] -async fn wifi_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'static, PIO0, 0, DMA_CH0>>) -> ! { +async fn cyw43_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'static, PIO0, 0, DMA_CH0>>) -> ! { runner.run().await } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, cyw43::NetDriver<'static>>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -40,14 +42,15 @@ async fn main(spawner: Spawner) { info!("Hello World!"); let p = embassy_rp::init(Default::default()); + let mut rng = RoscRng; let fw = include_bytes!("../../../../cyw43-firmware/43439A0.bin"); let clm = include_bytes!("../../../../cyw43-firmware/43439A0_clm.bin"); // To make flashing faster for development, you may want to flash the firmwares independently // at hardcoded addresses, instead of baking them into the program with `include_bytes!`: - // probe-rs download 43439A0.bin --format bin --chip RP2040 --base-address 0x10100000 - // probe-rs download 43439A0_clm.bin --format bin --chip RP2040 --base-address 0x10140000 + // probe-rs download 43439A0.bin --binary-format bin --chip RP2040 --base-address 0x10100000 + // probe-rs download 43439A0_clm.bin --binary-format bin --chip RP2040 --base-address 0x10140000 //let fw = unsafe { core::slice::from_raw_parts(0x10100000 as *const u8, 230321) }; //let clm = unsafe { core::slice::from_raw_parts(0x10140000 as *const u8, 4752) }; @@ -59,7 +62,7 @@ async fn main(spawner: Spawner) { static STATE: StaticCell = StaticCell::new(); let state = STATE.init(cyw43::State::new()); let (net_device, mut control, runner) = cyw43::new(state, pwr, spi, fw).await; - unwrap!(spawner.spawn(wifi_task(runner))); + unwrap!(spawner.spawn(cyw43_task(runner))); control.init(clm).await; control @@ -74,19 +77,13 @@ async fn main(spawner: Spawner) { }); // Generate random seed - let seed = 0x0123_4567_89ab_cdef; // chosen by fair dice roll. guarenteed to be random. + let seed = rng.next_u64(); // Init network stack - static STACK: StaticCell>> = StaticCell::new(); - static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - net_device, - config, - RESOURCES.init(StackResources::<2>::new()), - seed, - )); + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new(net_device, config, RESOURCES.init(StackResources::new()), seed); - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); //control.start_ap_open("cyw43", 5).await; control.start_ap_wpa2("cyw43", "password", 5).await; diff --git a/examples/rp/src/bin/wifi_blinky.rs b/examples/rp/src/bin/wifi_blinky.rs index 18eefe41f..0107a2326 100644 --- a/examples/rp/src/bin/wifi_blinky.rs +++ b/examples/rp/src/bin/wifi_blinky.rs @@ -21,7 +21,7 @@ bind_interrupts!(struct Irqs { }); #[embassy_executor::task] -async fn wifi_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'static, PIO0, 0, DMA_CH0>>) -> ! { +async fn cyw43_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'static, PIO0, 0, DMA_CH0>>) -> ! { runner.run().await } @@ -33,8 +33,8 @@ async fn main(spawner: Spawner) { // To make flashing faster for development, you may want to flash the firmwares independently // at hardcoded addresses, instead of baking them into the program with `include_bytes!`: - // probe-rs download 43439A0.bin --format bin --chip RP2040 --base-address 0x10100000 - // probe-rs download 43439A0_clm.bin --format bin --chip RP2040 --base-address 0x10140000 + // probe-rs download ../../cyw43-firmware/43439A0.bin --binary-format bin --chip RP2040 --base-address 0x10100000 + // probe-rs download ../../cyw43-firmware/43439A0_clm.bin --binary-format bin --chip RP2040 --base-address 0x10140000 //let fw = unsafe { core::slice::from_raw_parts(0x10100000 as *const u8, 230321) }; //let clm = unsafe { core::slice::from_raw_parts(0x10140000 as *const u8, 4752) }; @@ -46,7 +46,7 @@ async fn main(spawner: Spawner) { static STATE: StaticCell = StaticCell::new(); let state = STATE.init(cyw43::State::new()); let (_net_device, mut control, runner) = cyw43::new(state, pwr, spi, fw).await; - unwrap!(spawner.spawn(wifi_task(runner))); + unwrap!(spawner.spawn(cyw43_task(runner))); control.init(clm).await; control diff --git a/examples/rp/src/bin/wifi_scan.rs b/examples/rp/src/bin/wifi_scan.rs index e0f85a6b0..434f0074c 100644 --- a/examples/rp/src/bin/wifi_scan.rs +++ b/examples/rp/src/bin/wifi_scan.rs @@ -10,7 +10,6 @@ use core::str; use cyw43_pio::PioSpi; use defmt::*; use embassy_executor::Spawner; -use embassy_net::Stack; use embassy_rp::bind_interrupts; use embassy_rp::gpio::{Level, Output}; use embassy_rp::peripherals::{DMA_CH0, PIO0}; @@ -23,13 +22,13 @@ bind_interrupts!(struct Irqs { }); #[embassy_executor::task] -async fn wifi_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'static, PIO0, 0, DMA_CH0>>) -> ! { +async fn cyw43_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'static, PIO0, 0, DMA_CH0>>) -> ! { runner.run().await } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, cyw43::NetDriver<'static>>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -43,8 +42,8 @@ async fn main(spawner: Spawner) { // To make flashing faster for development, you may want to flash the firmwares independently // at hardcoded addresses, instead of baking them into the program with `include_bytes!`: - // probe-rs download 43439A0.bin --format bin --chip RP2040 --base-address 0x10100000 - // probe-rs download 43439A0_clm.bin --format bin --chip RP2040 --base-address 0x10140000 + // probe-rs download 43439A0.bin --binary-format bin --chip RP2040 --base-address 0x10100000 + // probe-rs download 43439A0_clm.bin --binary-format bin --chip RP2040 --base-address 0x10140000 //let fw = unsafe { core::slice::from_raw_parts(0x10100000 as *const u8, 230321) }; //let clm = unsafe { core::slice::from_raw_parts(0x10140000 as *const u8, 4752) }; @@ -56,7 +55,7 @@ async fn main(spawner: Spawner) { static STATE: StaticCell = StaticCell::new(); let state = STATE.init(cyw43::State::new()); let (_net_device, mut control, runner) = cyw43::new(state, pwr, spi, fw).await; - unwrap!(spawner.spawn(wifi_task(runner))); + unwrap!(spawner.spawn(cyw43_task(runner))); control.init(clm).await; control diff --git a/examples/rp/src/bin/wifi_tcp_server.rs b/examples/rp/src/bin/wifi_tcp_server.rs index f1afc4a00..7bf546e01 100644 --- a/examples/rp/src/bin/wifi_tcp_server.rs +++ b/examples/rp/src/bin/wifi_tcp_server.rs @@ -7,17 +7,20 @@ use core::str::from_utf8; +use cyw43::JoinOptions; use cyw43_pio::PioSpi; use defmt::*; use embassy_executor::Spawner; use embassy_net::tcp::TcpSocket; -use embassy_net::{Config, Stack, StackResources}; +use embassy_net::{Config, StackResources}; use embassy_rp::bind_interrupts; +use embassy_rp::clocks::RoscRng; use embassy_rp::gpio::{Level, Output}; use embassy_rp::peripherals::{DMA_CH0, PIO0}; use embassy_rp::pio::{InterruptHandler, Pio}; use embassy_time::{Duration, Timer}; use embedded_io_async::Write; +use rand::RngCore; use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _}; @@ -25,17 +28,17 @@ bind_interrupts!(struct Irqs { PIO0_IRQ_0 => InterruptHandler; }); -const WIFI_NETWORK: &str = "EmbassyTest"; -const WIFI_PASSWORD: &str = "V8YxhKt5CdIAJFud"; +const WIFI_NETWORK: &str = "LadronDeWifi"; +const WIFI_PASSWORD: &str = "MBfcaedHmyRFE4kaQ1O5SsY8"; #[embassy_executor::task] -async fn wifi_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'static, PIO0, 0, DMA_CH0>>) -> ! { +async fn cyw43_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'static, PIO0, 0, DMA_CH0>>) -> ! { runner.run().await } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, cyw43::NetDriver<'static>>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -43,14 +46,15 @@ async fn main(spawner: Spawner) { info!("Hello World!"); let p = embassy_rp::init(Default::default()); + let mut rng = RoscRng; let fw = include_bytes!("../../../../cyw43-firmware/43439A0.bin"); let clm = include_bytes!("../../../../cyw43-firmware/43439A0_clm.bin"); // To make flashing faster for development, you may want to flash the firmwares independently // at hardcoded addresses, instead of baking them into the program with `include_bytes!`: - // probe-rs download 43439A0.bin --format bin --chip RP2040 --base-address 0x10100000 - // probe-rs download 43439A0_clm.bin --format bin --chip RP2040 --base-address 0x10140000 + // probe-rs download 43439A0.bin --binary-format bin --chip RP2040 --base-address 0x10100000 + // probe-rs download 43439A0_clm.bin --binary-format bin --chip RP2040 --base-address 0x10140000 //let fw = unsafe { core::slice::from_raw_parts(0x10100000 as *const u8, 230321) }; //let clm = unsafe { core::slice::from_raw_parts(0x10140000 as *const u8, 4752) }; @@ -62,7 +66,7 @@ async fn main(spawner: Spawner) { static STATE: StaticCell = StaticCell::new(); let state = STATE.init(cyw43::State::new()); let (net_device, mut control, runner) = cyw43::new(state, pwr, spi, fw).await; - unwrap!(spawner.spawn(wifi_task(runner))); + unwrap!(spawner.spawn(cyw43_task(runner))); control.init(clm).await; control @@ -77,23 +81,19 @@ async fn main(spawner: Spawner) { //}); // Generate random seed - let seed = 0x0123_4567_89ab_cdef; // chosen by fair dice roll. guarenteed to be random. + let seed = rng.next_u64(); // Init network stack - static STACK: StaticCell>> = StaticCell::new(); - static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - net_device, - config, - RESOURCES.init(StackResources::<2>::new()), - seed, - )); + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new(net_device, config, RESOURCES.init(StackResources::new()), seed); - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); loop { - //control.join_open(WIFI_NETWORK).await; - match control.join_wpa2(WIFI_NETWORK, WIFI_PASSWORD).await { + match control + .join(WIFI_NETWORK, JoinOptions::new(WIFI_PASSWORD.as_bytes())) + .await + { Ok(_) => break, Err(err) => { info!("join failed with status={}", err.status); diff --git a/examples/rp/src/bin/wifi_webrequest.rs b/examples/rp/src/bin/wifi_webrequest.rs new file mode 100644 index 000000000..1ae909917 --- /dev/null +++ b/examples/rp/src/bin/wifi_webrequest.rs @@ -0,0 +1,190 @@ +//! This example uses the RP Pico W board Wifi chip (cyw43). +//! Connects to Wifi network and makes a web request to get the current time. + +#![no_std] +#![no_main] +#![allow(async_fn_in_trait)] + +use core::str::from_utf8; + +use cyw43::JoinOptions; +use cyw43_pio::PioSpi; +use defmt::*; +use embassy_executor::Spawner; +use embassy_net::dns::DnsSocket; +use embassy_net::tcp::client::{TcpClient, TcpClientState}; +use embassy_net::{Config, StackResources}; +use embassy_rp::bind_interrupts; +use embassy_rp::clocks::RoscRng; +use embassy_rp::gpio::{Level, Output}; +use embassy_rp::peripherals::{DMA_CH0, PIO0}; +use embassy_rp::pio::{InterruptHandler, Pio}; +use embassy_time::{Duration, Timer}; +use rand::RngCore; +use reqwless::client::{HttpClient, TlsConfig, TlsVerify}; +use reqwless::request::Method; +use serde::Deserialize; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _, serde_json_core}; + +bind_interrupts!(struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +const WIFI_NETWORK: &str = "ssid"; // change to your network SSID +const WIFI_PASSWORD: &str = "pwd"; // change to your network password + +#[embassy_executor::task] +async fn cyw43_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'static, PIO0, 0, DMA_CH0>>) -> ! { + runner.run().await +} + +#[embassy_executor::task] +async fn net_task(mut runner: embassy_net::Runner<'static, cyw43::NetDriver<'static>>) -> ! { + runner.run().await +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + info!("Hello World!"); + + let p = embassy_rp::init(Default::default()); + let mut rng = RoscRng; + + let fw = include_bytes!("../../../../cyw43-firmware/43439A0.bin"); + let clm = include_bytes!("../../../../cyw43-firmware/43439A0_clm.bin"); + // To make flashing faster for development, you may want to flash the firmwares independently + // at hardcoded addresses, instead of baking them into the program with `include_bytes!`: + // probe-rs download 43439A0.bin --binary-format bin --chip RP2040 --base-address 0x10100000 + // probe-rs download 43439A0_clm.bin --binary-format bin --chip RP2040 --base-address 0x10140000 + // let fw = unsafe { core::slice::from_raw_parts(0x10100000 as *const u8, 230321) }; + // let clm = unsafe { core::slice::from_raw_parts(0x10140000 as *const u8, 4752) }; + + let pwr = Output::new(p.PIN_23, Level::Low); + let cs = Output::new(p.PIN_25, Level::High); + let mut pio = Pio::new(p.PIO0, Irqs); + let spi = PioSpi::new(&mut pio.common, pio.sm0, pio.irq0, cs, p.PIN_24, p.PIN_29, p.DMA_CH0); + + static STATE: StaticCell = StaticCell::new(); + let state = STATE.init(cyw43::State::new()); + let (net_device, mut control, runner) = cyw43::new(state, pwr, spi, fw).await; + unwrap!(spawner.spawn(cyw43_task(runner))); + + control.init(clm).await; + control + .set_power_management(cyw43::PowerManagementMode::PowerSave) + .await; + + let config = Config::dhcpv4(Default::default()); + // Use static IP configuration instead of DHCP + //let config = embassy_net::Config::ipv4_static(embassy_net::StaticConfigV4 { + // address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 69, 2), 24), + // dns_servers: Vec::new(), + // gateway: Some(Ipv4Address::new(192, 168, 69, 1)), + //}); + + // Generate random seed + let seed = rng.next_u64(); + + // Init network stack + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new(net_device, config, RESOURCES.init(StackResources::new()), seed); + + unwrap!(spawner.spawn(net_task(runner))); + + loop { + match control + .join(WIFI_NETWORK, JoinOptions::new(WIFI_PASSWORD.as_bytes())) + .await + { + Ok(_) => break, + Err(err) => { + info!("join failed with status={}", err.status); + } + } + } + + // Wait for DHCP, not necessary when using static IP + info!("waiting for DHCP..."); + while !stack.is_config_up() { + Timer::after_millis(100).await; + } + info!("DHCP is now up!"); + + info!("waiting for link up..."); + while !stack.is_link_up() { + Timer::after_millis(500).await; + } + info!("Link is up!"); + + info!("waiting for stack to be up..."); + stack.wait_config_up().await; + info!("Stack is up!"); + + // And now we can use it! + + loop { + let mut rx_buffer = [0; 8192]; + let mut tls_read_buffer = [0; 16640]; + let mut tls_write_buffer = [0; 16640]; + + let client_state = TcpClientState::<1, 1024, 1024>::new(); + let tcp_client = TcpClient::new(stack, &client_state); + let dns_client = DnsSocket::new(stack); + let tls_config = TlsConfig::new(seed, &mut tls_read_buffer, &mut tls_write_buffer, TlsVerify::None); + + let mut http_client = HttpClient::new_with_tls(&tcp_client, &dns_client, tls_config); + let url = "https://worldtimeapi.org/api/timezone/Europe/Berlin"; + // for non-TLS requests, use this instead: + // let mut http_client = HttpClient::new(&tcp_client, &dns_client); + // let url = "http://worldtimeapi.org/api/timezone/Europe/Berlin"; + + info!("connecting to {}", &url); + + let mut request = match http_client.request(Method::GET, &url).await { + Ok(req) => req, + Err(e) => { + error!("Failed to make HTTP request: {:?}", e); + return; // handle the error + } + }; + + let response = match request.send(&mut rx_buffer).await { + Ok(resp) => resp, + Err(_e) => { + error!("Failed to send HTTP request"); + return; // handle the error; + } + }; + + let body = match from_utf8(response.body().read_to_end().await.unwrap()) { + Ok(b) => b, + Err(_e) => { + error!("Failed to read response body"); + return; // handle the error + } + }; + info!("Response body: {:?}", &body); + + // parse the response body and update the RTC + + #[derive(Deserialize)] + struct ApiResponse<'a> { + datetime: &'a str, + // other fields as needed + } + + let bytes = body.as_bytes(); + match serde_json_core::de::from_slice::(bytes) { + Ok((output, _used)) => { + info!("Datetime: {:?}", output.datetime); + } + Err(_e) => { + error!("Failed to parse response body"); + return; // handle the error + } + } + + Timer::after(Duration::from_secs(5)).await; + } +} diff --git a/examples/rp/src/bin/zerocopy.rs b/examples/rp/src/bin/zerocopy.rs new file mode 100644 index 000000000..39f03c8e4 --- /dev/null +++ b/examples/rp/src/bin/zerocopy.rs @@ -0,0 +1,94 @@ +//! This example shows how to use `zerocopy_channel` from `embassy_sync` for +//! sending large values between two tasks without copying. +//! The example also shows how to use the RP2040 ADC with DMA. +#![no_std] +#![no_main] + +use core::sync::atomic::{AtomicU16, Ordering}; + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::adc::{self, Adc, Async, Config, InterruptHandler}; +use embassy_rp::bind_interrupts; +use embassy_rp::gpio::Pull; +use embassy_rp::peripherals::DMA_CH0; +use embassy_sync::blocking_mutex::raw::NoopRawMutex; +use embassy_sync::zerocopy_channel::{Channel, Receiver, Sender}; +use embassy_time::{Duration, Ticker, Timer}; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +type SampleBuffer = [u16; 512]; + +bind_interrupts!(struct Irqs { + ADC_IRQ_FIFO => InterruptHandler; +}); + +const BLOCK_SIZE: usize = 512; +const NUM_BLOCKS: usize = 2; +static MAX: AtomicU16 = AtomicU16::new(0); + +struct AdcParts { + adc: Adc<'static, Async>, + pin: adc::Channel<'static>, + dma: DMA_CH0, +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + info!("Here we go!"); + + let adc_parts = AdcParts { + adc: Adc::new(p.ADC, Irqs, Config::default()), + pin: adc::Channel::new_pin(p.PIN_29, Pull::None), + dma: p.DMA_CH0, + }; + + static BUF: StaticCell<[SampleBuffer; NUM_BLOCKS]> = StaticCell::new(); + let buf = BUF.init([[0; BLOCK_SIZE]; NUM_BLOCKS]); + + static CHANNEL: StaticCell> = StaticCell::new(); + let channel = CHANNEL.init(Channel::new(buf)); + let (sender, receiver) = channel.split(); + + spawner.must_spawn(consumer(receiver)); + spawner.must_spawn(producer(sender, adc_parts)); + + let mut ticker = Ticker::every(Duration::from_secs(1)); + loop { + ticker.next().await; + let max = MAX.load(Ordering::Relaxed); + info!("latest block's max value: {:?}", max); + } +} + +#[embassy_executor::task] +async fn producer(mut sender: Sender<'static, NoopRawMutex, SampleBuffer>, mut adc: AdcParts) { + loop { + // Obtain a free buffer from the channel + let buf = sender.send().await; + + // Fill it with data + adc.adc.read_many(&mut adc.pin, buf, 1, &mut adc.dma).await.unwrap(); + + // Notify the channel that the buffer is now ready to be received + sender.send_done(); + } +} + +#[embassy_executor::task] +async fn consumer(mut receiver: Receiver<'static, NoopRawMutex, SampleBuffer>) { + loop { + // Receive a buffer from the channel + let buf = receiver.receive().await; + + // Simulate using the data, while the producer is filling up the next buffer + Timer::after_micros(1000).await; + let max = buf.iter().max().unwrap(); + MAX.store(*max, Ordering::Relaxed); + + // Notify the channel that the buffer is now ready to be reused + receiver.receive_done(); + } +} diff --git a/examples/rp23/.cargo/config.toml b/examples/rp23/.cargo/config.toml new file mode 100644 index 000000000..9a92b1ce2 --- /dev/null +++ b/examples/rp23/.cargo/config.toml @@ -0,0 +1,10 @@ +[target.'cfg(all(target_arch = "arm", target_os = "none"))'] +#runner = "probe-rs run --chip RP2040" +#runner = "elf2uf2-rs -d" +runner = "picotool load -u -v -x -t elf" + +[build] +target = "thumbv8m.main-none-eabihf" + +[env] +DEFMT_LOG = "debug" diff --git a/examples/rp23/Cargo.toml b/examples/rp23/Cargo.toml new file mode 100644 index 000000000..99a75a67f --- /dev/null +++ b/examples/rp23/Cargo.toml @@ -0,0 +1,80 @@ +[package] +edition = "2021" +name = "embassy-rp2350-examples" +version = "0.1.0" +license = "MIT OR Apache-2.0" + + +[dependencies] +embassy-embedded-hal = { version = "0.2.0", path = "../../embassy-embedded-hal", features = ["defmt"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-98304", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } +embassy-rp = { version = "0.2.0", path = "../../embassy-rp", features = ["defmt", "unstable-pac", "time-driver", "critical-section-impl", "rp235xa", "binary-info"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "udp", "raw", "dhcpv4", "medium-ethernet", "dns"] } +embassy-net-wiznet = { version = "0.1.0", path = "../../embassy-net-wiznet", features = ["defmt"] } +embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } +embassy-usb-logger = { version = "0.2.0", path = "../../embassy-usb-logger" } +cyw43 = { version = "0.2.0", path = "../../cyw43", features = ["defmt", "firmware-logs", "bluetooth"] } +cyw43-pio = { version = "0.2.0", path = "../../cyw43-pio", features = ["defmt"] } + +defmt = "0.3" +defmt-rtt = "0.4" +fixed = "1.23.1" +fixed-macro = "1.2" + +serde = { version = "1.0.203", default-features = false, features = ["derive"] } +serde-json-core = "0.5.1" + +# for assign resources example +assign-resources = { git = "https://github.com/adamgreig/assign-resources", rev = "94ad10e2729afdf0fd5a77cd12e68409a982f58a" } + +# for TB6612FNG example +tb6612fng = "1.0.0" + +#cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] } +cortex-m = { version = "0.7.6", features = ["inline-asm"] } +cortex-m-rt = "0.7.0" +critical-section = "1.1" +panic-probe = { version = "0.3", features = ["print-defmt"] } +display-interface-spi = "0.5.0" +embedded-graphics = "0.8.1" +mipidsi = "0.8.0" +display-interface = "0.5.0" +byte-slice-cast = { version = "1.2.0", default-features = false } +smart-leds = "0.3.0" +heapless = "0.8" +usbd-hid = "0.8.1" + +embedded-hal-1 = { package = "embedded-hal", version = "1.0" } +embedded-hal-async = "1.0" +embedded-hal-bus = { version = "0.1", features = ["async"] } +embedded-io-async = { version = "0.6.1", features = ["defmt-03"] } +embedded-storage = { version = "0.3" } +static_cell = "2.1" +portable-atomic = { version = "1.5", features = ["critical-section"] } +log = "0.4" +pio-proc = "0.2" +pio = "0.2.1" +rand = { version = "0.8.5", default-features = false } +embedded-sdmmc = "0.7.0" + +bt-hci = { version = "0.1.0", default-features = false, features = ["defmt"] } +trouble-host = { version = "0.1.0", features = ["defmt", "gatt"] } + +[profile.release] +debug = 2 + +[profile.dev] +lto = true +opt-level = "z" + +[patch.crates-io] +trouble-host = { git = "https://github.com/embassy-rs/trouble.git", rev = "4b8c0f499b34e46ca23a56e2d1640ede371722cf" } +embassy-executor = { path = "../../embassy-executor" } +embassy-sync = { path = "../../embassy-sync" } +embassy-futures = { path = "../../embassy-futures" } +embassy-time = { path = "../../embassy-time" } +embassy-time-driver = { path = "../../embassy-time-driver" } +embassy-embedded-hal = { path = "../../embassy-embedded-hal" } diff --git a/examples/rp23/assets/ferris.raw b/examples/rp23/assets/ferris.raw new file mode 100644 index 000000000..9733889c5 Binary files /dev/null and b/examples/rp23/assets/ferris.raw differ diff --git a/examples/rp23/build.rs b/examples/rp23/build.rs new file mode 100644 index 000000000..30691aa97 --- /dev/null +++ b/examples/rp23/build.rs @@ -0,0 +1,35 @@ +//! This build script copies the `memory.x` file from the crate root into +//! a directory where the linker can always find it at build time. +//! For many projects this is optional, as the linker always searches the +//! project root directory -- wherever `Cargo.toml` is. However, if you +//! are using a workspace or have a more complicated build setup, this +//! build script becomes required. Additionally, by requesting that +//! Cargo re-run the build script whenever `memory.x` is changed, +//! updating `memory.x` ensures a rebuild of the application with the +//! new memory settings. + +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; + +fn main() { + // Put `memory.x` in our output directory and ensure it's + // on the linker search path. + let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); + File::create(out.join("memory.x")) + .unwrap() + .write_all(include_bytes!("memory.x")) + .unwrap(); + println!("cargo:rustc-link-search={}", out.display()); + + // By default, Cargo will re-run a build script whenever + // any file in the project changes. By specifying `memory.x` + // here, we ensure the build script is only re-run when + // `memory.x` is changed. + println!("cargo:rerun-if-changed=memory.x"); + + println!("cargo:rustc-link-arg-bins=--nmagic"); + println!("cargo:rustc-link-arg-bins=-Tlink.x"); + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); +} diff --git a/examples/rp23/memory.x b/examples/rp23/memory.x new file mode 100644 index 000000000..c803896f6 --- /dev/null +++ b/examples/rp23/memory.x @@ -0,0 +1,75 @@ +MEMORY { + /* + * The RP2350 has either external or internal flash. + * + * 2 MiB is a safe default here, although a Pico 2 has 4 MiB. + */ + FLASH : ORIGIN = 0x10000000, LENGTH = 2048K + /* + * RAM consists of 8 banks, SRAM0-SRAM7, with a striped mapping. + * This is usually good for performance, as it distributes load on + * those banks evenly. + */ + RAM : ORIGIN = 0x20000000, LENGTH = 512K + /* + * RAM banks 8 and 9 use a direct mapping. They can be used to have + * memory areas dedicated for some specific job, improving predictability + * of access times. + * Example: Separate stacks for core0 and core1. + */ + SRAM4 : ORIGIN = 0x20080000, LENGTH = 4K + SRAM5 : ORIGIN = 0x20081000, LENGTH = 4K +} + +SECTIONS { + /* ### Boot ROM info + * + * Goes after .vector_table, to keep it in the first 4K of flash + * where the Boot ROM (and picotool) can find it + */ + .start_block : ALIGN(4) + { + __start_block_addr = .; + KEEP(*(.start_block)); + KEEP(*(.boot_info)); + } > FLASH + +} INSERT AFTER .vector_table; + +/* move .text to start /after/ the boot info */ +_stext = ADDR(.start_block) + SIZEOF(.start_block); + +SECTIONS { + /* ### Picotool 'Binary Info' Entries + * + * Picotool looks through this block (as we have pointers to it in our + * header) to find interesting information. + */ + .bi_entries : ALIGN(4) + { + /* We put this in the header */ + __bi_entries_start = .; + /* Here are the entries */ + KEEP(*(.bi_entries)); + /* Keep this block a nice round size */ + . = ALIGN(4); + /* We put this in the header */ + __bi_entries_end = .; + } > FLASH +} INSERT AFTER .text; + +SECTIONS { + /* ### Boot ROM extra info + * + * Goes after everything in our program, so it can contain a signature. + */ + .end_block : ALIGN(4) + { + __end_block_addr = .; + KEEP(*(.end_block)); + } > FLASH + +} INSERT AFTER .uninit; + +PROVIDE(start_to_end = __end_block_addr - __start_block_addr); +PROVIDE(end_to_start = __start_block_addr - __end_block_addr); diff --git a/examples/rp23/src/bin/adc.rs b/examples/rp23/src/bin/adc.rs new file mode 100644 index 000000000..f7db9653a --- /dev/null +++ b/examples/rp23/src/bin/adc.rs @@ -0,0 +1,53 @@ +//! This example test the ADC (Analog to Digital Conversion) of the RP2350A pins 26, 27 and 28. +//! It also reads the temperature sensor in the chip. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::adc::{Adc, Channel, Config, InterruptHandler}; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio::Pull; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + ADC_IRQ_FIFO => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let mut adc = Adc::new(p.ADC, Irqs, Config::default()); + + let mut p26 = Channel::new_pin(p.PIN_26, Pull::None); + let mut p27 = Channel::new_pin(p.PIN_27, Pull::None); + let mut p28 = Channel::new_pin(p.PIN_28, Pull::None); + let mut ts = Channel::new_temp_sensor(p.ADC_TEMP_SENSOR); + + loop { + let level = adc.read(&mut p26).await.unwrap(); + info!("Pin 26 ADC: {}", level); + let level = adc.read(&mut p27).await.unwrap(); + info!("Pin 27 ADC: {}", level); + let level = adc.read(&mut p28).await.unwrap(); + info!("Pin 28 ADC: {}", level); + let temp = adc.read(&mut ts).await.unwrap(); + info!("Temp: {} degrees", convert_to_celsius(temp)); + Timer::after_secs(1).await; + } +} + +fn convert_to_celsius(raw_temp: u16) -> f32 { + // According to chapter 4.9.5. Temperature Sensor in RP2040 datasheet + let temp = 27.0 - (raw_temp as f32 * 3.3 / 4096.0 - 0.706) / 0.001721; + let sign = if temp < 0.0 { -1.0 } else { 1.0 }; + let rounded_temp_x10: i16 = ((temp * 10.0) + 0.5 * sign) as i16; + (rounded_temp_x10 as f32) / 10.0 +} diff --git a/examples/rp23/src/bin/adc_dma.rs b/examples/rp23/src/bin/adc_dma.rs new file mode 100644 index 000000000..a6814c23a --- /dev/null +++ b/examples/rp23/src/bin/adc_dma.rs @@ -0,0 +1,59 @@ +//! This example shows how to use the RP2040 ADC with DMA, both single- and multichannel reads. +//! For multichannel, the samples are interleaved in the buffer: +//! `[ch1, ch2, ch3, ch4, ch1, ch2, ch3, ch4, ...]` +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::adc::{Adc, Channel, Config, InterruptHandler}; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio::Pull; +use embassy_time::{Duration, Ticker}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + ADC_IRQ_FIFO => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + info!("Here we go!"); + + let mut adc = Adc::new(p.ADC, Irqs, Config::default()); + let mut dma = p.DMA_CH0; + let mut pin = Channel::new_pin(p.PIN_26, Pull::Up); + let mut pins = [ + Channel::new_pin(p.PIN_27, Pull::Down), + Channel::new_pin(p.PIN_28, Pull::None), + Channel::new_pin(p.PIN_29, Pull::Up), + Channel::new_temp_sensor(p.ADC_TEMP_SENSOR), + ]; + + const BLOCK_SIZE: usize = 100; + const NUM_CHANNELS: usize = 4; + let mut ticker = Ticker::every(Duration::from_secs(1)); + loop { + // Read 100 samples from a single channel + let mut buf = [0_u16; BLOCK_SIZE]; + let div = 479; // 100kHz sample rate (48Mhz / 100kHz - 1) + adc.read_many(&mut pin, &mut buf, div, &mut dma).await.unwrap(); + info!("single: {:?} ...etc", buf[..8]); + + // Read 100 samples from 4 channels interleaved + let mut buf = [0_u16; { BLOCK_SIZE * NUM_CHANNELS }]; + let div = 119; // 100kHz sample rate (48Mhz / 100kHz * 4ch - 1) + adc.read_many_multichannel(&mut pins, &mut buf, div, &mut dma) + .await + .unwrap(); + info!("multi: {:?} ...etc", buf[..NUM_CHANNELS * 2]); + + ticker.next().await; + } +} diff --git a/examples/rp23/src/bin/assign_resources.rs b/examples/rp23/src/bin/assign_resources.rs new file mode 100644 index 000000000..0d4ad8dc3 --- /dev/null +++ b/examples/rp23/src/bin/assign_resources.rs @@ -0,0 +1,84 @@ +//! This example demonstrates how to assign resources to multiple tasks by splitting up the peripherals. +//! It is not about sharing the same resources between tasks, see sharing.rs for that or head to https://embassy.dev/book/#_sharing_peripherals_between_tasks) +//! Of course splitting up resources and sharing resources can be combined, yet this example is only about splitting up resources. +//! +//! There are basically two ways we demonstrate here: +//! 1) Assigning resources to a task by passing parts of the peripherals +//! 2) Assigning resources to a task by passing a struct with the split up peripherals, using the assign-resources macro +//! +//! using four LEDs on Pins 10, 11, 20 and 21 + +#![no_std] +#![no_main] + +use assign_resources::assign_resources; +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio::{Level, Output}; +use embassy_rp::peripherals::{self, PIN_20, PIN_21}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + // initialize the peripherals + let p = embassy_rp::init(Default::default()); + + // 1) Assigning a resource to a task by passing parts of the peripherals. + spawner + .spawn(double_blinky_manually_assigned(spawner, p.PIN_20, p.PIN_21)) + .unwrap(); + + // 2) Using the assign-resources macro to assign resources to a task. + // we perform the split, see further below for the definition of the resources struct + let r = split_resources!(p); + // and then we can use them + spawner.spawn(double_blinky_macro_assigned(spawner, r.leds)).unwrap(); +} + +// 1) Assigning a resource to a task by passing parts of the peripherals. +#[embassy_executor::task] +async fn double_blinky_manually_assigned(_spawner: Spawner, pin_20: PIN_20, pin_21: PIN_21) { + let mut led_20 = Output::new(pin_20, Level::Low); + let mut led_21 = Output::new(pin_21, Level::High); + + loop { + info!("toggling leds"); + led_20.toggle(); + led_21.toggle(); + Timer::after_secs(1).await; + } +} + +// 2) Using the assign-resources macro to assign resources to a task. +// first we define the resources we want to assign to the task using the assign_resources! macro +// basically this will split up the peripherals struct into smaller structs, that we define here +// naming is up to you, make sure your future self understands what you did here +assign_resources! { + leds: Leds{ + led_10: PIN_10, + led_11: PIN_11, + } + // add more resources to more structs if needed, for example defining one struct for each task +} +// this could be done in another file and imported here, but for the sake of simplicity we do it here +// see https://github.com/adamgreig/assign-resources for more information + +// 2) Using the split resources in a task +#[embassy_executor::task] +async fn double_blinky_macro_assigned(_spawner: Spawner, r: Leds) { + let mut led_10 = Output::new(r.led_10, Level::Low); + let mut led_11 = Output::new(r.led_11, Level::High); + + loop { + info!("toggling leds"); + led_10.toggle(); + led_11.toggle(); + Timer::after_secs(1).await; + } +} diff --git a/examples/rp23/src/bin/blinky.rs b/examples/rp23/src/bin/blinky.rs new file mode 100644 index 000000000..c1ddbb7d2 --- /dev/null +++ b/examples/rp23/src/bin/blinky.rs @@ -0,0 +1,47 @@ +//! This example test the RP Pico on board LED. +//! +//! It does not work with the RP Pico W board. See wifi_blinky.rs. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio; +use embassy_time::Timer; +use gpio::{Level, Output}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +// Program metadata for `picotool info`. +// This isn't needed, but it's recomended to have these minimal entries. +#[link_section = ".bi_entries"] +#[used] +pub static PICOTOOL_ENTRIES: [embassy_rp::binary_info::EntryAddr; 4] = [ + embassy_rp::binary_info::rp_program_name!(c"Blinky Example"), + embassy_rp::binary_info::rp_program_description!( + c"This example tests the RP Pico on board LED, connected to gpio 25" + ), + embassy_rp::binary_info::rp_cargo_version!(), + embassy_rp::binary_info::rp_program_build_attribute!(), +]; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let mut led = Output::new(p.PIN_25, Level::Low); + + loop { + info!("led on!"); + led.set_high(); + Timer::after_millis(250).await; + + info!("led off!"); + led.set_low(); + Timer::after_millis(250).await; + } +} diff --git a/examples/rp23/src/bin/blinky_two_channels.rs b/examples/rp23/src/bin/blinky_two_channels.rs new file mode 100644 index 000000000..ce482858e --- /dev/null +++ b/examples/rp23/src/bin/blinky_two_channels.rs @@ -0,0 +1,55 @@ +#![no_std] +#![no_main] +/// This example demonstrates how to access a given pin from more than one embassy task +/// The on-board LED is toggled by two tasks with slightly different periods, leading to the +/// apparent duty cycle of the LED increasing, then decreasing, linearly. The phenomenon is similar +/// to interference and the 'beats' you can hear if you play two frequencies close to one another +/// [Link explaining it](https://www.physicsclassroom.com/class/sound/Lesson-3/Interference-and-Beats) +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio; +use embassy_sync::blocking_mutex::raw::ThreadModeRawMutex; +use embassy_sync::channel::{Channel, Sender}; +use embassy_time::{Duration, Ticker}; +use gpio::{AnyPin, Level, Output}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +enum LedState { + Toggle, +} +static CHANNEL: Channel = Channel::new(); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let mut led = Output::new(AnyPin::from(p.PIN_25), Level::High); + + let dt = 100 * 1_000_000; + let k = 1.003; + + unwrap!(spawner.spawn(toggle_led(CHANNEL.sender(), Duration::from_nanos(dt)))); + unwrap!(spawner.spawn(toggle_led( + CHANNEL.sender(), + Duration::from_nanos((dt as f64 * k) as u64) + ))); + + loop { + match CHANNEL.receive().await { + LedState::Toggle => led.toggle(), + } + } +} + +#[embassy_executor::task(pool_size = 2)] +async fn toggle_led(control: Sender<'static, ThreadModeRawMutex, LedState, 64>, delay: Duration) { + let mut ticker = Ticker::every(delay); + loop { + control.send(LedState::Toggle).await; + ticker.next().await; + } +} diff --git a/examples/rp23/src/bin/blinky_two_tasks.rs b/examples/rp23/src/bin/blinky_two_tasks.rs new file mode 100644 index 000000000..5dc62245d --- /dev/null +++ b/examples/rp23/src/bin/blinky_two_tasks.rs @@ -0,0 +1,54 @@ +#![no_std] +#![no_main] +/// This example demonstrates how to access a given pin from more than one embassy task +/// The on-board LED is toggled by two tasks with slightly different periods, leading to the +/// apparent duty cycle of the LED increasing, then decreasing, linearly. The phenomenon is similar +/// to interference and the 'beats' you can hear if you play two frequencies close to one another +/// [Link explaining it](https://www.physicsclassroom.com/class/sound/Lesson-3/Interference-and-Beats) +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio; +use embassy_sync::blocking_mutex::raw::ThreadModeRawMutex; +use embassy_sync::mutex::Mutex; +use embassy_time::{Duration, Ticker}; +use gpio::{AnyPin, Level, Output}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +type LedType = Mutex>>; +static LED: LedType = Mutex::new(None); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + // set the content of the global LED reference to the real LED pin + let led = Output::new(AnyPin::from(p.PIN_25), Level::High); + // inner scope is so that once the mutex is written to, the MutexGuard is dropped, thus the + // Mutex is released + { + *(LED.lock().await) = Some(led); + } + let dt = 100 * 1_000_000; + let k = 1.003; + + unwrap!(spawner.spawn(toggle_led(&LED, Duration::from_nanos(dt)))); + unwrap!(spawner.spawn(toggle_led(&LED, Duration::from_nanos((dt as f64 * k) as u64)))); +} + +#[embassy_executor::task(pool_size = 2)] +async fn toggle_led(led: &'static LedType, delay: Duration) { + let mut ticker = Ticker::every(delay); + loop { + { + let mut led_unlocked = led.lock().await; + if let Some(pin_ref) = led_unlocked.as_mut() { + pin_ref.toggle(); + } + } + ticker.next().await; + } +} diff --git a/examples/rp23/src/bin/button.rs b/examples/rp23/src/bin/button.rs new file mode 100644 index 000000000..85f1bcae3 --- /dev/null +++ b/examples/rp23/src/bin/button.rs @@ -0,0 +1,33 @@ +//! This example uses the RP Pico on board LED to test input pin 28. This is not the button on the board. +//! +//! It does not work with the RP Pico W board. Use wifi_blinky.rs and add input pin. + +#![no_std] +#![no_main] + +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio::{Input, Level, Output, Pull}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let mut led = Output::new(p.PIN_25, Level::Low); + + // Use PIN_28, Pin34 on J0 for RP Pico, as a input. + // You need to add your own button. + let button = Input::new(p.PIN_28, Pull::Up); + + loop { + if button.is_high() { + led.set_high(); + } else { + led.set_low(); + } + } +} diff --git a/examples/rp23/src/bin/debounce.rs b/examples/rp23/src/bin/debounce.rs new file mode 100644 index 000000000..4c8b80d92 --- /dev/null +++ b/examples/rp23/src/bin/debounce.rs @@ -0,0 +1,85 @@ +//! This example shows the ease of debouncing a button with async rust. +//! Hook up a button or switch between pin 9 and ground. + +#![no_std] +#![no_main] + +use defmt::info; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio::{Input, Level, Pull}; +use embassy_time::{with_deadline, Duration, Instant, Timer}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +pub struct Debouncer<'a> { + input: Input<'a>, + debounce: Duration, +} + +impl<'a> Debouncer<'a> { + pub fn new(input: Input<'a>, debounce: Duration) -> Self { + Self { input, debounce } + } + + pub async fn debounce(&mut self) -> Level { + loop { + let l1 = self.input.get_level(); + + self.input.wait_for_any_edge().await; + + Timer::after(self.debounce).await; + + let l2 = self.input.get_level(); + if l1 != l2 { + break l2; + } + } + } +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let mut btn = Debouncer::new(Input::new(p.PIN_9, Pull::Up), Duration::from_millis(20)); + + info!("Debounce Demo"); + + loop { + // button pressed + btn.debounce().await; + let start = Instant::now(); + info!("Button Press"); + + match with_deadline(start + Duration::from_secs(1), btn.debounce()).await { + // Button Released < 1s + Ok(_) => { + info!("Button pressed for: {}ms", start.elapsed().as_millis()); + continue; + } + // button held for > 1s + Err(_) => { + info!("Button Held"); + } + } + + match with_deadline(start + Duration::from_secs(5), btn.debounce()).await { + // Button released <5s + Ok(_) => { + info!("Button pressed for: {}ms", start.elapsed().as_millis()); + continue; + } + // button held for > >5s + Err(_) => { + info!("Button Long Held"); + } + } + + // wait for button release before handling another press + btn.debounce().await; + info!("Button pressed for: {}ms", start.elapsed().as_millis()); + } +} diff --git a/examples/rp23/src/bin/flash.rs b/examples/rp23/src/bin/flash.rs new file mode 100644 index 000000000..28dec24c9 --- /dev/null +++ b/examples/rp23/src/bin/flash.rs @@ -0,0 +1,130 @@ +//! This example test the flash connected to the RP2040 chip. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::flash::{Async, ERASE_SIZE, FLASH_BASE}; +use embassy_rp::peripherals::FLASH; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +const ADDR_OFFSET: u32 = 0x100000; +const FLASH_SIZE: usize = 2 * 1024 * 1024; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + info!("Hello World!"); + + // add some delay to give an attached debug probe time to parse the + // defmt RTT header. Reading that header might touch flash memory, which + // interferes with flash write operations. + // https://github.com/knurling-rs/defmt/pull/683 + Timer::after_millis(10).await; + + let mut flash = embassy_rp::flash::Flash::<_, Async, FLASH_SIZE>::new(p.FLASH, p.DMA_CH0); + + erase_write_sector(&mut flash, 0x00); + + multiwrite_bytes(&mut flash, ERASE_SIZE as u32); + + background_read(&mut flash, (ERASE_SIZE * 2) as u32).await; + + info!("Flash Works!"); +} + +fn multiwrite_bytes(flash: &mut embassy_rp::flash::Flash<'_, FLASH, Async, FLASH_SIZE>, offset: u32) { + info!(">>>> [multiwrite_bytes]"); + let mut read_buf = [0u8; ERASE_SIZE]; + defmt::unwrap!(flash.blocking_read(ADDR_OFFSET + offset, &mut read_buf)); + + info!("Addr of flash block is {:x}", ADDR_OFFSET + offset + FLASH_BASE as u32); + info!("Contents start with {=[u8]}", read_buf[0..4]); + + defmt::unwrap!(flash.blocking_erase(ADDR_OFFSET + offset, ADDR_OFFSET + offset + ERASE_SIZE as u32)); + + defmt::unwrap!(flash.blocking_read(ADDR_OFFSET + offset, &mut read_buf)); + info!("Contents after erase starts with {=[u8]}", read_buf[0..4]); + if read_buf.iter().any(|x| *x != 0xFF) { + defmt::panic!("unexpected"); + } + + defmt::unwrap!(flash.blocking_write(ADDR_OFFSET + offset, &[0x01])); + defmt::unwrap!(flash.blocking_write(ADDR_OFFSET + offset + 1, &[0x02])); + defmt::unwrap!(flash.blocking_write(ADDR_OFFSET + offset + 2, &[0x03])); + defmt::unwrap!(flash.blocking_write(ADDR_OFFSET + offset + 3, &[0x04])); + + defmt::unwrap!(flash.blocking_read(ADDR_OFFSET + offset, &mut read_buf)); + info!("Contents after write starts with {=[u8]}", read_buf[0..4]); + if read_buf[0..4] != [0x01, 0x02, 0x03, 0x04] { + defmt::panic!("unexpected"); + } +} + +fn erase_write_sector(flash: &mut embassy_rp::flash::Flash<'_, FLASH, Async, FLASH_SIZE>, offset: u32) { + info!(">>>> [erase_write_sector]"); + let mut buf = [0u8; ERASE_SIZE]; + defmt::unwrap!(flash.blocking_read(ADDR_OFFSET + offset, &mut buf)); + + info!("Addr of flash block is {:x}", ADDR_OFFSET + offset + FLASH_BASE as u32); + info!("Contents start with {=[u8]}", buf[0..4]); + + defmt::unwrap!(flash.blocking_erase(ADDR_OFFSET + offset, ADDR_OFFSET + offset + ERASE_SIZE as u32)); + + defmt::unwrap!(flash.blocking_read(ADDR_OFFSET + offset, &mut buf)); + info!("Contents after erase starts with {=[u8]}", buf[0..4]); + if buf.iter().any(|x| *x != 0xFF) { + defmt::panic!("unexpected"); + } + + for b in buf.iter_mut() { + *b = 0xDA; + } + + defmt::unwrap!(flash.blocking_write(ADDR_OFFSET + offset, &buf)); + + defmt::unwrap!(flash.blocking_read(ADDR_OFFSET + offset, &mut buf)); + info!("Contents after write starts with {=[u8]}", buf[0..4]); + if buf.iter().any(|x| *x != 0xDA) { + defmt::panic!("unexpected"); + } +} + +async fn background_read(flash: &mut embassy_rp::flash::Flash<'_, FLASH, Async, FLASH_SIZE>, offset: u32) { + info!(">>>> [background_read]"); + + let mut buf = [0u32; 8]; + defmt::unwrap!(flash.background_read(ADDR_OFFSET + offset, &mut buf)).await; + + info!("Addr of flash block is {:x}", ADDR_OFFSET + offset + FLASH_BASE as u32); + info!("Contents start with {=u32:x}", buf[0]); + + defmt::unwrap!(flash.blocking_erase(ADDR_OFFSET + offset, ADDR_OFFSET + offset + ERASE_SIZE as u32)); + + defmt::unwrap!(flash.background_read(ADDR_OFFSET + offset, &mut buf)).await; + info!("Contents after erase starts with {=u32:x}", buf[0]); + if buf.iter().any(|x| *x != 0xFFFFFFFF) { + defmt::panic!("unexpected"); + } + + for b in buf.iter_mut() { + *b = 0xDABA1234; + } + + defmt::unwrap!(flash.blocking_write(ADDR_OFFSET + offset, unsafe { + core::slice::from_raw_parts(buf.as_ptr() as *const u8, buf.len() * 4) + })); + + defmt::unwrap!(flash.background_read(ADDR_OFFSET + offset, &mut buf)).await; + info!("Contents after write starts with {=u32:x}", buf[0]); + if buf.iter().any(|x| *x != 0xDABA1234) { + defmt::panic!("unexpected"); + } +} diff --git a/examples/rp23/src/bin/gpio_async.rs b/examples/rp23/src/bin/gpio_async.rs new file mode 100644 index 000000000..bfb9a3f95 --- /dev/null +++ b/examples/rp23/src/bin/gpio_async.rs @@ -0,0 +1,45 @@ +//! This example shows how async gpio can be used with a RP2040. +//! +//! The LED on the RP Pico W board is connected differently. See wifi_blinky.rs. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio; +use embassy_time::Timer; +use gpio::{Input, Level, Output, Pull}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +/// It requires an external signal to be manually triggered on PIN 16. For +/// example, this could be accomplished using an external power source with a +/// button so that it is possible to toggle the signal from low to high. +/// +/// This example will begin with turning on the LED on the board and wait for a +/// high signal on PIN 16. Once the high event/signal occurs the program will +/// continue and turn off the LED, and then wait for 2 seconds before completing +/// the loop and starting over again. +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let mut led = Output::new(p.PIN_25, Level::Low); + let mut async_input = Input::new(p.PIN_16, Pull::None); + + loop { + info!("wait_for_high. Turn on LED"); + led.set_high(); + + async_input.wait_for_high().await; + + info!("done wait_for_high. Turn off LED"); + led.set_low(); + + Timer::after_secs(2).await; + } +} diff --git a/examples/rp23/src/bin/gpout.rs b/examples/rp23/src/bin/gpout.rs new file mode 100644 index 000000000..3cc2ea938 --- /dev/null +++ b/examples/rp23/src/bin/gpout.rs @@ -0,0 +1,42 @@ +//! This example shows how GPOUT (General purpose clock outputs) can toggle a output pin. +//! +//! The LED on the RP Pico W board is connected differently. Add a LED and resistor to another pin. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::clocks; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + + let gpout3 = clocks::Gpout::new(p.PIN_25); + gpout3.set_div(1000, 0); + gpout3.enable(); + + loop { + gpout3.set_src(clocks::GpoutSrc::Sys); + info!( + "Pin 25 is now outputing CLK_SYS/1000, should be toggling at {}", + gpout3.get_freq() + ); + Timer::after_secs(2).await; + + gpout3.set_src(clocks::GpoutSrc::Ref); + info!( + "Pin 25 is now outputing CLK_REF/1000, should be toggling at {}", + gpout3.get_freq() + ); + Timer::after_secs(2).await; + } +} diff --git a/examples/rp23/src/bin/i2c_async.rs b/examples/rp23/src/bin/i2c_async.rs new file mode 100644 index 000000000..b30088bae --- /dev/null +++ b/examples/rp23/src/bin/i2c_async.rs @@ -0,0 +1,115 @@ +//! This example shows how to communicate asynchronous using i2c with external chips. +//! +//! Example written for the [`MCP23017 16-Bit I2C I/O Expander with Serial Interface`] chip. +//! (https://www.microchip.com/en-us/product/mcp23017) + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::i2c::{self, Config, InterruptHandler}; +use embassy_rp::peripherals::I2C1; +use embassy_time::Timer; +use embedded_hal_async::i2c::I2c; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + I2C1_IRQ => InterruptHandler; +}); + +#[allow(dead_code)] +mod mcp23017 { + pub const ADDR: u8 = 0x20; // default addr + + macro_rules! mcpregs { + ($($name:ident : $val:expr),* $(,)?) => { + $( + pub const $name: u8 = $val; + )* + + pub fn regname(reg: u8) -> &'static str { + match reg { + $( + $val => stringify!($name), + )* + _ => panic!("bad reg"), + } + } + } + } + + // These are correct for IOCON.BANK=0 + mcpregs! { + IODIRA: 0x00, + IPOLA: 0x02, + GPINTENA: 0x04, + DEFVALA: 0x06, + INTCONA: 0x08, + IOCONA: 0x0A, + GPPUA: 0x0C, + INTFA: 0x0E, + INTCAPA: 0x10, + GPIOA: 0x12, + OLATA: 0x14, + IODIRB: 0x01, + IPOLB: 0x03, + GPINTENB: 0x05, + DEFVALB: 0x07, + INTCONB: 0x09, + IOCONB: 0x0B, + GPPUB: 0x0D, + INTFB: 0x0F, + INTCAPB: 0x11, + GPIOB: 0x13, + OLATB: 0x15, + } +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + + let sda = p.PIN_14; + let scl = p.PIN_15; + + info!("set up i2c "); + let mut i2c = i2c::I2c::new_async(p.I2C1, scl, sda, Irqs, Config::default()); + + use mcp23017::*; + + info!("init mcp23017 config for IxpandO"); + // init - a outputs, b inputs + i2c.write(ADDR, &[IODIRA, 0x00]).await.unwrap(); + i2c.write(ADDR, &[IODIRB, 0xff]).await.unwrap(); + i2c.write(ADDR, &[GPPUB, 0xff]).await.unwrap(); // pullups + + let mut val = 1; + loop { + let mut portb = [0]; + + i2c.write_read(mcp23017::ADDR, &[GPIOB], &mut portb).await.unwrap(); + info!("portb = {:02x}", portb[0]); + i2c.write(mcp23017::ADDR, &[GPIOA, val | portb[0]]).await.unwrap(); + val = val.rotate_left(1); + + // get a register dump + info!("getting register dump"); + let mut regs = [0; 22]; + i2c.write_read(ADDR, &[0], &mut regs).await.unwrap(); + // always get the regdump but only display it if portb'0 is set + if portb[0] & 1 != 0 { + for (idx, reg) in regs.into_iter().enumerate() { + info!("{} => {:02x}", regname(idx as u8), reg); + } + } + + Timer::after_millis(100).await; + } +} diff --git a/examples/rp23/src/bin/i2c_async_embassy.rs b/examples/rp23/src/bin/i2c_async_embassy.rs new file mode 100644 index 000000000..c783a80c5 --- /dev/null +++ b/examples/rp23/src/bin/i2c_async_embassy.rs @@ -0,0 +1,90 @@ +//! This example shows how to communicate asynchronous using i2c with external chip. +//! +//! It's using embassy's functions directly instead of traits from embedded_hal_async::i2c::I2c. +//! While most of i2c devices are addressed using 7 bits, an extension allows 10 bits too. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_rp::block::ImageDef; +use embassy_rp::i2c::InterruptHandler; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +// Our anonymous hypotetical temperature sensor could be: +// a 12-bit sensor, with 100ms startup time, range of -40*C - 125*C, and precision 0.25*C +// It requires no configuration or calibration, works with all i2c bus speeds, +// never stretches clock or does anything complicated. Replies with one u16. +// It requires only one write to take it out of suspend mode, and stays on. +// Often result would be just on 12 bits, but here we'll simplify it to 16. + +enum UncomplicatedSensorId { + A(UncomplicatedSensorU8), + B(UncomplicatedSensorU16), +} +enum UncomplicatedSensorU8 { + First = 0x48, +} +enum UncomplicatedSensorU16 { + Other = 0x0049, +} + +impl Into for UncomplicatedSensorU16 { + fn into(self) -> u16 { + self as u16 + } +} +impl Into for UncomplicatedSensorU8 { + fn into(self) -> u16 { + 0x48 + } +} +impl From for u16 { + fn from(t: UncomplicatedSensorId) -> Self { + match t { + UncomplicatedSensorId::A(x) => x.into(), + UncomplicatedSensorId::B(x) => x.into(), + } + } +} + +embassy_rp::bind_interrupts!(struct Irqs { + I2C1_IRQ => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_task_spawner: embassy_executor::Spawner) { + let p = embassy_rp::init(Default::default()); + let sda = p.PIN_14; + let scl = p.PIN_15; + let config = embassy_rp::i2c::Config::default(); + let mut bus = embassy_rp::i2c::I2c::new_async(p.I2C1, scl, sda, Irqs, config); + + const WAKEYWAKEY: u16 = 0xBABE; + let mut result: [u8; 2] = [0, 0]; + // wait for sensors to initialize + embassy_time::Timer::after(embassy_time::Duration::from_millis(100)).await; + + let _res_1 = bus + .write_async(UncomplicatedSensorU8::First, WAKEYWAKEY.to_be_bytes()) + .await; + let _res_2 = bus + .write_async(UncomplicatedSensorU16::Other, WAKEYWAKEY.to_be_bytes()) + .await; + + loop { + let s1 = UncomplicatedSensorId::A(UncomplicatedSensorU8::First); + let s2 = UncomplicatedSensorId::B(UncomplicatedSensorU16::Other); + let sensors = [s1, s2]; + for sensor in sensors { + if bus.read_async(sensor, &mut result).await.is_ok() { + info!("Result {}", u16::from_be_bytes(result.into())); + } + } + embassy_time::Timer::after(embassy_time::Duration::from_millis(200)).await; + } +} diff --git a/examples/rp23/src/bin/i2c_blocking.rs b/examples/rp23/src/bin/i2c_blocking.rs new file mode 100644 index 000000000..a68677311 --- /dev/null +++ b/examples/rp23/src/bin/i2c_blocking.rs @@ -0,0 +1,79 @@ +//! This example shows how to communicate using i2c with external chips. +//! +//! Example written for the [`MCP23017 16-Bit I2C I/O Expander with Serial Interface`] chip. +//! (https://www.microchip.com/en-us/product/mcp23017) + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::i2c::{self, Config}; +use embassy_time::Timer; +use embedded_hal_1::i2c::I2c; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +#[allow(dead_code)] +mod mcp23017 { + pub const ADDR: u8 = 0x20; // default addr + + pub const IODIRA: u8 = 0x00; + pub const IPOLA: u8 = 0x02; + pub const GPINTENA: u8 = 0x04; + pub const DEFVALA: u8 = 0x06; + pub const INTCONA: u8 = 0x08; + pub const IOCONA: u8 = 0x0A; + pub const GPPUA: u8 = 0x0C; + pub const INTFA: u8 = 0x0E; + pub const INTCAPA: u8 = 0x10; + pub const GPIOA: u8 = 0x12; + pub const OLATA: u8 = 0x14; + pub const IODIRB: u8 = 0x01; + pub const IPOLB: u8 = 0x03; + pub const GPINTENB: u8 = 0x05; + pub const DEFVALB: u8 = 0x07; + pub const INTCONB: u8 = 0x09; + pub const IOCONB: u8 = 0x0B; + pub const GPPUB: u8 = 0x0D; + pub const INTFB: u8 = 0x0F; + pub const INTCAPB: u8 = 0x11; + pub const GPIOB: u8 = 0x13; + pub const OLATB: u8 = 0x15; +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + + let sda = p.PIN_14; + let scl = p.PIN_15; + + info!("set up i2c "); + let mut i2c = i2c::I2c::new_blocking(p.I2C1, scl, sda, Config::default()); + + use mcp23017::*; + + info!("init mcp23017 config for IxpandO"); + // init - a outputs, b inputs + i2c.write(ADDR, &[IODIRA, 0x00]).unwrap(); + i2c.write(ADDR, &[IODIRB, 0xff]).unwrap(); + i2c.write(ADDR, &[GPPUB, 0xff]).unwrap(); // pullups + + let mut val = 0xaa; + loop { + let mut portb = [0]; + + i2c.write(mcp23017::ADDR, &[GPIOA, val]).unwrap(); + i2c.write_read(mcp23017::ADDR, &[GPIOB], &mut portb).unwrap(); + + info!("portb = {:02x}", portb[0]); + val = !val; + + Timer::after_secs(1).await; + } +} diff --git a/examples/rp23/src/bin/i2c_slave.rs b/examples/rp23/src/bin/i2c_slave.rs new file mode 100644 index 000000000..8817538c0 --- /dev/null +++ b/examples/rp23/src/bin/i2c_slave.rs @@ -0,0 +1,122 @@ +//! This example shows how to use the 2040 as an i2c slave. +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::{I2C0, I2C1}; +use embassy_rp::{bind_interrupts, i2c, i2c_slave}; +use embassy_time::Timer; +use embedded_hal_async::i2c::I2c; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + I2C0_IRQ => i2c::InterruptHandler; + I2C1_IRQ => i2c::InterruptHandler; +}); + +const DEV_ADDR: u8 = 0x42; + +#[embassy_executor::task] +async fn device_task(mut dev: i2c_slave::I2cSlave<'static, I2C1>) -> ! { + info!("Device start"); + + let mut state = 0; + + loop { + let mut buf = [0u8; 128]; + match dev.listen(&mut buf).await { + Ok(i2c_slave::Command::GeneralCall(len)) => info!("Device received general call write: {}", buf[..len]), + Ok(i2c_slave::Command::Read) => loop { + match dev.respond_to_read(&[state]).await { + Ok(x) => match x { + i2c_slave::ReadStatus::Done => break, + i2c_slave::ReadStatus::NeedMoreBytes => (), + i2c_slave::ReadStatus::LeftoverBytes(x) => { + info!("tried to write {} extra bytes", x); + break; + } + }, + Err(e) => error!("error while responding {}", e), + } + }, + Ok(i2c_slave::Command::Write(len)) => info!("Device received write: {}", buf[..len]), + Ok(i2c_slave::Command::WriteRead(len)) => { + info!("device received write read: {:x}", buf[..len]); + match buf[0] { + // Set the state + 0xC2 => { + state = buf[1]; + match dev.respond_and_fill(&[state], 0x00).await { + Ok(read_status) => info!("response read status {}", read_status), + Err(e) => error!("error while responding {}", e), + } + } + // Reset State + 0xC8 => { + state = 0; + match dev.respond_and_fill(&[state], 0x00).await { + Ok(read_status) => info!("response read status {}", read_status), + Err(e) => error!("error while responding {}", e), + } + } + x => error!("Invalid Write Read {:x}", x), + } + } + Err(e) => error!("{}", e), + } + } +} + +#[embassy_executor::task] +async fn controller_task(mut con: i2c::I2c<'static, I2C0, i2c::Async>) { + info!("Controller start"); + + loop { + let mut resp_buff = [0u8; 2]; + for i in 0..10 { + match con.write_read(DEV_ADDR, &[0xC2, i], &mut resp_buff).await { + Ok(_) => info!("write_read response: {}", resp_buff), + Err(e) => error!("Error writing {}", e), + } + + Timer::after_millis(100).await; + } + match con.read(DEV_ADDR, &mut resp_buff).await { + Ok(_) => info!("read response: {}", resp_buff), + Err(e) => error!("Error writing {}", e), + } + match con.write_read(DEV_ADDR, &[0xC8], &mut resp_buff).await { + Ok(_) => info!("write_read response: {}", resp_buff), + Err(e) => error!("Error writing {}", e), + } + Timer::after_millis(100).await; + } +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + info!("Hello World!"); + + let d_sda = p.PIN_3; + let d_scl = p.PIN_2; + let mut config = i2c_slave::Config::default(); + config.addr = DEV_ADDR as u16; + let device = i2c_slave::I2cSlave::new(p.I2C1, d_sda, d_scl, Irqs, config); + + unwrap!(spawner.spawn(device_task(device))); + + let c_sda = p.PIN_1; + let c_scl = p.PIN_0; + let mut config = i2c::Config::default(); + config.frequency = 1_000_000; + let controller = i2c::I2c::new_async(p.I2C0, c_sda, c_scl, Irqs, config); + + unwrap!(spawner.spawn(controller_task(controller))); +} diff --git a/examples/rp23/src/bin/interrupt.rs b/examples/rp23/src/bin/interrupt.rs new file mode 100644 index 000000000..d9b662253 --- /dev/null +++ b/examples/rp23/src/bin/interrupt.rs @@ -0,0 +1,99 @@ +//! This example shows how you can use raw interrupt handlers alongside embassy. +//! The example also showcases some of the options available for sharing resources/data. +//! +//! In the example, an ADC reading is triggered every time the PWM wraps around. +//! The sample data is sent down a channel, to be processed inside a low priority task. +//! The processed data is then used to adjust the PWM duty cycle, once every second. + +#![no_std] +#![no_main] + +use core::cell::{Cell, RefCell}; + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::adc::{self, Adc, Blocking}; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio::Pull; +use embassy_rp::interrupt; +use embassy_rp::pwm::{Config, Pwm}; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +use embassy_sync::blocking_mutex::Mutex; +use embassy_sync::channel::Channel; +use embassy_time::{Duration, Ticker}; +use portable_atomic::{AtomicU32, Ordering}; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +static COUNTER: AtomicU32 = AtomicU32::new(0); +static PWM: Mutex>> = Mutex::new(RefCell::new(None)); +static ADC: Mutex, adc::Channel)>>> = + Mutex::new(RefCell::new(None)); +static ADC_VALUES: Channel = Channel::new(); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + embassy_rp::pac::SIO.spinlock(31).write_value(1); + let p = embassy_rp::init(Default::default()); + + let adc = Adc::new_blocking(p.ADC, Default::default()); + let p26 = adc::Channel::new_pin(p.PIN_26, Pull::None); + ADC.lock(|a| a.borrow_mut().replace((adc, p26))); + + let pwm = Pwm::new_output_b(p.PWM_SLICE4, p.PIN_25, Default::default()); + PWM.lock(|p| p.borrow_mut().replace(pwm)); + + // Enable the interrupt for pwm slice 4 + embassy_rp::pac::PWM.irq0_inte().modify(|w| w.set_ch4(true)); + unsafe { + cortex_m::peripheral::NVIC::unmask(interrupt::PWM_IRQ_WRAP_0); + } + + // Tasks require their resources to have 'static lifetime + // No Mutex needed when sharing within the same executor/prio level + static AVG: StaticCell> = StaticCell::new(); + let avg = AVG.init(Default::default()); + spawner.must_spawn(processing(avg)); + + let mut ticker = Ticker::every(Duration::from_secs(1)); + loop { + ticker.next().await; + let freq = COUNTER.swap(0, Ordering::Relaxed); + info!("pwm freq: {:?} Hz", freq); + info!("adc average: {:?}", avg.get()); + + // Update the pwm duty cycle, based on the averaged adc reading + let mut config = Config::default(); + config.compare_b = ((avg.get() as f32 / 4095.0) * config.top as f32) as _; + PWM.lock(|p| p.borrow_mut().as_mut().unwrap().set_config(&config)); + } +} + +#[embassy_executor::task] +async fn processing(avg: &'static Cell) { + let mut buffer: heapless::HistoryBuffer = Default::default(); + loop { + let val = ADC_VALUES.receive().await; + buffer.write(val); + let sum: u32 = buffer.iter().map(|x| *x as u32).sum(); + avg.set(sum / buffer.len() as u32); + } +} + +#[interrupt] +fn PWM_IRQ_WRAP_0() { + critical_section::with(|cs| { + let mut adc = ADC.borrow(cs).borrow_mut(); + let (adc, p26) = adc.as_mut().unwrap(); + let val = adc.blocking_read(p26).unwrap(); + ADC_VALUES.try_send(val).ok(); + + // Clear the interrupt, so we don't immediately re-enter this irq handler + PWM.borrow(cs).borrow_mut().as_mut().unwrap().clear_wrapped(); + }); + COUNTER.fetch_add(1, Ordering::Relaxed); +} diff --git a/examples/rp23/src/bin/multicore.rs b/examples/rp23/src/bin/multicore.rs new file mode 100644 index 000000000..d4d470fa2 --- /dev/null +++ b/examples/rp23/src/bin/multicore.rs @@ -0,0 +1,71 @@ +//! This example shows how to send messages between the two cores in the RP2040 chip. +//! +//! The LED on the RP Pico W board is connected differently. See wifi_blinky.rs. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Executor; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio::{Level, Output}; +use embassy_rp::multicore::{spawn_core1, Stack}; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +use embassy_sync::channel::Channel; +use embassy_time::Timer; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +static mut CORE1_STACK: Stack<4096> = Stack::new(); +static EXECUTOR0: StaticCell = StaticCell::new(); +static EXECUTOR1: StaticCell = StaticCell::new(); +static CHANNEL: Channel = Channel::new(); + +enum LedState { + On, + Off, +} + +#[cortex_m_rt::entry] +fn main() -> ! { + let p = embassy_rp::init(Default::default()); + let led = Output::new(p.PIN_25, Level::Low); + + spawn_core1( + p.CORE1, + unsafe { &mut *core::ptr::addr_of_mut!(CORE1_STACK) }, + move || { + let executor1 = EXECUTOR1.init(Executor::new()); + executor1.run(|spawner| unwrap!(spawner.spawn(core1_task(led)))); + }, + ); + + let executor0 = EXECUTOR0.init(Executor::new()); + executor0.run(|spawner| unwrap!(spawner.spawn(core0_task()))); +} + +#[embassy_executor::task] +async fn core0_task() { + info!("Hello from core 0"); + loop { + CHANNEL.send(LedState::On).await; + Timer::after_millis(100).await; + CHANNEL.send(LedState::Off).await; + Timer::after_millis(400).await; + } +} + +#[embassy_executor::task] +async fn core1_task(mut led: Output<'static>) { + info!("Hello from core 1"); + loop { + match CHANNEL.receive().await { + LedState::On => led.set_high(), + LedState::Off => led.set_low(), + } + } +} diff --git a/examples/rp23/src/bin/multiprio.rs b/examples/rp23/src/bin/multiprio.rs new file mode 100644 index 000000000..787854aa9 --- /dev/null +++ b/examples/rp23/src/bin/multiprio.rs @@ -0,0 +1,150 @@ +//! This example showcases how to create multiple Executor instances to run tasks at +//! different priority levels. +//! +//! Low priority executor runs in thread mode (not interrupt), and uses `sev` for signaling +//! there's work in the queue, and `wfe` for waiting for work. +//! +//! Medium and high priority executors run in two interrupts with different priorities. +//! Signaling work is done by pending the interrupt. No "waiting" needs to be done explicitly, since +//! when there's work the interrupt will trigger and run the executor. +//! +//! Sample output below. Note that high priority ticks can interrupt everything else, and +//! medium priority computations can interrupt low priority computations, making them to appear +//! to take significantly longer time. +//! +//! ```not_rust +//! [med] Starting long computation +//! [med] done in 992 ms +//! [high] tick! +//! [low] Starting long computation +//! [med] Starting long computation +//! [high] tick! +//! [high] tick! +//! [med] done in 993 ms +//! [med] Starting long computation +//! [high] tick! +//! [high] tick! +//! [med] done in 993 ms +//! [low] done in 3972 ms +//! [med] Starting long computation +//! [high] tick! +//! [high] tick! +//! [med] done in 993 ms +//! ``` +//! +//! For comparison, try changing the code so all 3 tasks get spawned on the low priority executor. +//! You will get an output like the following. Note that no computation is ever interrupted. +//! +//! ```not_rust +//! [high] tick! +//! [med] Starting long computation +//! [med] done in 496 ms +//! [low] Starting long computation +//! [low] done in 992 ms +//! [med] Starting long computation +//! [med] done in 496 ms +//! [high] tick! +//! [low] Starting long computation +//! [low] done in 992 ms +//! [high] tick! +//! [med] Starting long computation +//! [med] done in 496 ms +//! [high] tick! +//! ``` +//! + +#![no_std] +#![no_main] + +use cortex_m_rt::entry; +use defmt::{info, unwrap}; +use embassy_executor::{Executor, InterruptExecutor}; +use embassy_rp::block::ImageDef; +use embassy_rp::interrupt; +use embassy_rp::interrupt::{InterruptExt, Priority}; +use embassy_time::{Instant, Timer, TICK_HZ}; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +#[embassy_executor::task] +async fn run_high() { + loop { + info!(" [high] tick!"); + Timer::after_ticks(673740).await; + } +} + +#[embassy_executor::task] +async fn run_med() { + loop { + let start = Instant::now(); + info!(" [med] Starting long computation"); + + // Spin-wait to simulate a long CPU computation + embassy_time::block_for(embassy_time::Duration::from_secs(1)); // ~1 second + + let end = Instant::now(); + let ms = end.duration_since(start).as_ticks() * 1000 / TICK_HZ; + info!(" [med] done in {} ms", ms); + + Timer::after_ticks(53421).await; + } +} + +#[embassy_executor::task] +async fn run_low() { + loop { + let start = Instant::now(); + info!("[low] Starting long computation"); + + // Spin-wait to simulate a long CPU computation + embassy_time::block_for(embassy_time::Duration::from_secs(2)); // ~2 seconds + + let end = Instant::now(); + let ms = end.duration_since(start).as_ticks() * 1000 / TICK_HZ; + info!("[low] done in {} ms", ms); + + Timer::after_ticks(82983).await; + } +} + +static EXECUTOR_HIGH: InterruptExecutor = InterruptExecutor::new(); +static EXECUTOR_MED: InterruptExecutor = InterruptExecutor::new(); +static EXECUTOR_LOW: StaticCell = StaticCell::new(); + +#[interrupt] +unsafe fn SWI_IRQ_1() { + EXECUTOR_HIGH.on_interrupt() +} + +#[interrupt] +unsafe fn SWI_IRQ_0() { + EXECUTOR_MED.on_interrupt() +} + +#[entry] +fn main() -> ! { + info!("Hello World!"); + + let _p = embassy_rp::init(Default::default()); + + // High-priority executor: SWI_IRQ_1, priority level 2 + interrupt::SWI_IRQ_1.set_priority(Priority::P2); + let spawner = EXECUTOR_HIGH.start(interrupt::SWI_IRQ_1); + unwrap!(spawner.spawn(run_high())); + + // Medium-priority executor: SWI_IRQ_0, priority level 3 + interrupt::SWI_IRQ_0.set_priority(Priority::P3); + let spawner = EXECUTOR_MED.start(interrupt::SWI_IRQ_0); + unwrap!(spawner.spawn(run_med())); + + // Low priority executor: runs in thread mode, using WFE/SEV + let executor = EXECUTOR_LOW.init(Executor::new()); + executor.run(|spawner| { + unwrap!(spawner.spawn(run_low())); + }); +} diff --git a/examples/rp23/src/bin/otp.rs b/examples/rp23/src/bin/otp.rs new file mode 100644 index 000000000..c67c9821a --- /dev/null +++ b/examples/rp23/src/bin/otp.rs @@ -0,0 +1,36 @@ +//! This example shows reading the OTP constants on the RP235x. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::otp; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let _ = embassy_rp::init(Default::default()); + // + // add some delay to give an attached debug probe time to parse the + // defmt RTT header. Reading that header might touch flash memory, which + // interferes with flash write operations. + // https://github.com/knurling-rs/defmt/pull/683 + Timer::after_millis(10).await; + + let chip_id = unwrap!(otp::get_chipid()); + info!("Unique id:{:X}", chip_id); + + let private_rand = unwrap!(otp::get_private_random_number()); + info!("Private Rand:{:X}", private_rand); + + loop { + Timer::after_secs(1).await; + } +} diff --git a/examples/rp23/src/bin/pio_async.rs b/examples/rp23/src/bin/pio_async.rs new file mode 100644 index 000000000..896447e28 --- /dev/null +++ b/examples/rp23/src/bin/pio_async.rs @@ -0,0 +1,135 @@ +//! This example shows powerful PIO module in the RP2040 chip. + +#![no_std] +#![no_main] +use defmt::info; +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::PIO0; +use embassy_rp::pio::{Common, Config, InterruptHandler, Irq, Pio, PioPin, ShiftDirection, StateMachine}; +use fixed::traits::ToFixed; +use fixed_macro::types::U56F8; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +fn setup_pio_task_sm0<'a>(pio: &mut Common<'a, PIO0>, sm: &mut StateMachine<'a, PIO0, 0>, pin: impl PioPin) { + // Setup sm0 + + // Send data serially to pin + let prg = pio_proc::pio_asm!( + ".origin 16", + "set pindirs, 1", + ".wrap_target", + "out pins,1 [19]", + ".wrap", + ); + + let mut cfg = Config::default(); + cfg.use_program(&pio.load_program(&prg.program), &[]); + let out_pin = pio.make_pio_pin(pin); + cfg.set_out_pins(&[&out_pin]); + cfg.set_set_pins(&[&out_pin]); + cfg.clock_divider = (U56F8!(125_000_000) / 20 / 200).to_fixed(); + cfg.shift_out.auto_fill = true; + sm.set_config(&cfg); +} + +#[embassy_executor::task] +async fn pio_task_sm0(mut sm: StateMachine<'static, PIO0, 0>) { + sm.set_enable(true); + + let mut v = 0x0f0caffa; + loop { + sm.tx().wait_push(v).await; + v ^= 0xffff; + info!("Pushed {:032b} to FIFO", v); + } +} + +fn setup_pio_task_sm1<'a>(pio: &mut Common<'a, PIO0>, sm: &mut StateMachine<'a, PIO0, 1>) { + // Setupm sm1 + + // Read 0b10101 repeatedly until ISR is full + let prg = pio_proc::pio_asm!( + // + ".origin 8", + "set x, 0x15", + ".wrap_target", + "in x, 5 [31]", + ".wrap", + ); + + let mut cfg = Config::default(); + cfg.use_program(&pio.load_program(&prg.program), &[]); + cfg.clock_divider = (U56F8!(125_000_000) / 2000).to_fixed(); + cfg.shift_in.auto_fill = true; + cfg.shift_in.direction = ShiftDirection::Right; + sm.set_config(&cfg); +} + +#[embassy_executor::task] +async fn pio_task_sm1(mut sm: StateMachine<'static, PIO0, 1>) { + sm.set_enable(true); + loop { + let rx = sm.rx().wait_pull().await; + info!("Pulled {:032b} from FIFO", rx); + } +} + +fn setup_pio_task_sm2<'a>(pio: &mut Common<'a, PIO0>, sm: &mut StateMachine<'a, PIO0, 2>) { + // Setup sm2 + + // Repeatedly trigger IRQ 3 + let prg = pio_proc::pio_asm!( + ".origin 0", + ".wrap_target", + "set x,10", + "delay:", + "jmp x-- delay [15]", + "irq 3 [15]", + ".wrap", + ); + let mut cfg = Config::default(); + cfg.use_program(&pio.load_program(&prg.program), &[]); + cfg.clock_divider = (U56F8!(125_000_000) / 2000).to_fixed(); + sm.set_config(&cfg); +} + +#[embassy_executor::task] +async fn pio_task_sm2(mut irq: Irq<'static, PIO0, 3>, mut sm: StateMachine<'static, PIO0, 2>) { + sm.set_enable(true); + loop { + irq.wait().await; + info!("IRQ trigged"); + } +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let pio = p.PIO0; + + let Pio { + mut common, + irq3, + mut sm0, + mut sm1, + mut sm2, + .. + } = Pio::new(pio, Irqs); + + setup_pio_task_sm0(&mut common, &mut sm0, p.PIN_0); + setup_pio_task_sm1(&mut common, &mut sm1); + setup_pio_task_sm2(&mut common, &mut sm2); + spawner.spawn(pio_task_sm0(sm0)).unwrap(); + spawner.spawn(pio_task_sm1(sm1)).unwrap(); + spawner.spawn(pio_task_sm2(irq3, sm2)).unwrap(); +} diff --git a/examples/rp23/src/bin/pio_dma.rs b/examples/rp23/src/bin/pio_dma.rs new file mode 100644 index 000000000..b5f754798 --- /dev/null +++ b/examples/rp23/src/bin/pio_dma.rs @@ -0,0 +1,88 @@ +//! This example shows powerful PIO module in the RP2040 chip. + +#![no_std] +#![no_main] +use defmt::info; +use embassy_executor::Spawner; +use embassy_futures::join::join; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::PIO0; +use embassy_rp::pio::{Config, InterruptHandler, Pio, ShiftConfig, ShiftDirection}; +use embassy_rp::{bind_interrupts, Peripheral}; +use fixed::traits::ToFixed; +use fixed_macro::types::U56F8; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +fn swap_nibbles(v: u32) -> u32 { + let v = (v & 0x0f0f_0f0f) << 4 | (v & 0xf0f0_f0f0) >> 4; + let v = (v & 0x00ff_00ff) << 8 | (v & 0xff00_ff00) >> 8; + (v & 0x0000_ffff) << 16 | (v & 0xffff_0000) >> 16 +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let pio = p.PIO0; + let Pio { + mut common, + sm0: mut sm, + .. + } = Pio::new(pio, Irqs); + + let prg = pio_proc::pio_asm!( + ".origin 0", + "set pindirs,1", + ".wrap_target", + "set y,7", + "loop:", + "out x,4", + "in x,4", + "jmp y--, loop", + ".wrap", + ); + + let mut cfg = Config::default(); + cfg.use_program(&common.load_program(&prg.program), &[]); + cfg.clock_divider = (U56F8!(125_000_000) / U56F8!(10_000)).to_fixed(); + cfg.shift_in = ShiftConfig { + auto_fill: true, + threshold: 32, + direction: ShiftDirection::Left, + }; + cfg.shift_out = ShiftConfig { + auto_fill: true, + threshold: 32, + direction: ShiftDirection::Right, + }; + + sm.set_config(&cfg); + sm.set_enable(true); + + let mut dma_out_ref = p.DMA_CH0.into_ref(); + let mut dma_in_ref = p.DMA_CH1.into_ref(); + let mut dout = [0x12345678u32; 29]; + for i in 1..dout.len() { + dout[i] = (dout[i - 1] & 0x0fff_ffff) * 13 + 7; + } + let mut din = [0u32; 29]; + loop { + let (rx, tx) = sm.rx_tx(); + join( + tx.dma_push(dma_out_ref.reborrow(), &dout), + rx.dma_pull(dma_in_ref.reborrow(), &mut din), + ) + .await; + for i in 0..din.len() { + assert_eq!(din[i], swap_nibbles(dout[i])); + } + info!("Swapped {} words", dout.len()); + } +} diff --git a/examples/rp23/src/bin/pio_hd44780.rs b/examples/rp23/src/bin/pio_hd44780.rs new file mode 100644 index 000000000..c6f5f6db0 --- /dev/null +++ b/examples/rp23/src/bin/pio_hd44780.rs @@ -0,0 +1,92 @@ +//! This example shows powerful PIO module in the RP2040 chip to communicate with a HD44780 display. +//! See (https://www.sparkfun.com/datasheets/LCD/HD44780.pdf) + +#![no_std] +#![no_main] + +use core::fmt::Write; + +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::PIO0; +use embassy_rp::pio::{InterruptHandler, Pio}; +use embassy_rp::pio_programs::hd44780::{PioHD44780, PioHD44780CommandSequenceProgram, PioHD44780CommandWordProgram}; +use embassy_rp::pwm::{self, Pwm}; +use embassy_time::{Instant, Timer}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(pub struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + // this test assumes a 2x16 HD44780 display attached as follow: + // rs = PIN0 + // rw = PIN1 + // e = PIN2 + // db4 = PIN3 + // db5 = PIN4 + // db6 = PIN5 + // db7 = PIN6 + // additionally a pwm signal for a bias voltage charge pump is provided on pin 15, + // allowing direct connection of the display to the RP2040 without level shifters. + let p = embassy_rp::init(Default::default()); + + let _pwm = Pwm::new_output_b(p.PWM_SLICE7, p.PIN_15, { + let mut c = pwm::Config::default(); + c.divider = 125.into(); + c.top = 100; + c.compare_b = 50; + c + }); + + let Pio { + mut common, sm0, irq0, .. + } = Pio::new(p.PIO0, Irqs); + + let word_prg = PioHD44780CommandWordProgram::new(&mut common); + let seq_prg = PioHD44780CommandSequenceProgram::new(&mut common); + + let mut hd = PioHD44780::new( + &mut common, + sm0, + irq0, + p.DMA_CH3, + p.PIN_0, + p.PIN_1, + p.PIN_2, + p.PIN_3, + p.PIN_4, + p.PIN_5, + p.PIN_6, + &word_prg, + &seq_prg, + ) + .await; + + loop { + struct Buf([u8; N], usize); + impl Write for Buf { + fn write_str(&mut self, s: &str) -> Result<(), core::fmt::Error> { + for b in s.as_bytes() { + if self.1 >= N { + return Err(core::fmt::Error); + } + self.0[self.1] = *b; + self.1 += 1; + } + Ok(()) + } + } + let mut buf = Buf([0; 16], 0); + write!(buf, "up {}s", Instant::now().as_micros() as f32 / 1e6).unwrap(); + hd.add_line(&buf.0[0..buf.1]).await; + Timer::after_secs(1).await; + } +} diff --git a/examples/rp23/src/bin/pio_i2s.rs b/examples/rp23/src/bin/pio_i2s.rs new file mode 100644 index 000000000..1fd34357b --- /dev/null +++ b/examples/rp23/src/bin/pio_i2s.rs @@ -0,0 +1,100 @@ +//! This example shows generating audio and sending it to a connected i2s DAC using the PIO +//! module of the RP2040. +//! +//! Connect the i2s DAC as follows: +//! bclk : GPIO 18 +//! lrc : GPIO 19 +//! din : GPIO 20 +//! Then hold down the boot select button to trigger a rising triangle waveform. + +#![no_std] +#![no_main] + +use core::mem; + +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio::{Input, Pull}; +use embassy_rp::peripherals::PIO0; +use embassy_rp::pio::{InterruptHandler, Pio}; +use embassy_rp::pio_programs::i2s::{PioI2sOut, PioI2sOutProgram}; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +const SAMPLE_RATE: u32 = 48_000; +const BIT_DEPTH: u32 = 16; +const CHANNELS: u32 = 2; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + + // Setup pio state machine for i2s output + let Pio { mut common, sm0, .. } = Pio::new(p.PIO0, Irqs); + + let bit_clock_pin = p.PIN_18; + let left_right_clock_pin = p.PIN_19; + let data_pin = p.PIN_20; + + let program = PioI2sOutProgram::new(&mut common); + let mut i2s = PioI2sOut::new( + &mut common, + sm0, + p.DMA_CH0, + data_pin, + bit_clock_pin, + left_right_clock_pin, + SAMPLE_RATE, + BIT_DEPTH, + CHANNELS, + &program, + ); + + let fade_input = Input::new(p.PIN_0, Pull::Up); + + // create two audio buffers (back and front) which will take turns being + // filled with new audio data and being sent to the pio fifo using dma + const BUFFER_SIZE: usize = 960; + static DMA_BUFFER: StaticCell<[u32; BUFFER_SIZE * 2]> = StaticCell::new(); + let dma_buffer = DMA_BUFFER.init_with(|| [0u32; BUFFER_SIZE * 2]); + let (mut back_buffer, mut front_buffer) = dma_buffer.split_at_mut(BUFFER_SIZE); + + // start pio state machine + let mut fade_value: i32 = 0; + let mut phase: i32 = 0; + + loop { + // trigger transfer of front buffer data to the pio fifo + // but don't await the returned future, yet + let dma_future = i2s.write(front_buffer); + + // fade in audio when bootsel is pressed + let fade_target = if fade_input.is_low() { i32::MAX } else { 0 }; + + // fill back buffer with fresh audio samples before awaiting the dma future + for s in back_buffer.iter_mut() { + // exponential approach of fade_value => fade_target + fade_value += (fade_target - fade_value) >> 14; + // generate triangle wave with amplitude and frequency based on fade value + phase = (phase + (fade_value >> 22)) & 0xffff; + let triangle_sample = (phase as i16 as i32).abs() - 16384; + let sample = (triangle_sample * (fade_value >> 15)) >> 16; + // duplicate mono sample into lower and upper half of dma word + *s = (sample as u16 as u32) * 0x10001; + } + + // now await the dma future. once the dma finishes, the next buffer needs to be queued + // within DMA_DEPTH / SAMPLE_RATE = 8 / 48000 seconds = 166us + dma_future.await; + mem::swap(&mut back_buffer, &mut front_buffer); + } +} diff --git a/examples/rp23/src/bin/pio_onewire.rs b/examples/rp23/src/bin/pio_onewire.rs new file mode 100644 index 000000000..7f227d04b --- /dev/null +++ b/examples/rp23/src/bin/pio_onewire.rs @@ -0,0 +1,88 @@ +//! This example shows how you can use PIO to read a `DS18B20` one-wire temperature sensor. + +#![no_std] +#![no_main] +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::PIO0; +use embassy_rp::pio::{self, InterruptHandler, Pio}; +use embassy_rp::pio_programs::onewire::{PioOneWire, PioOneWireProgram}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let mut pio = Pio::new(p.PIO0, Irqs); + + let prg = PioOneWireProgram::new(&mut pio.common); + let onewire = PioOneWire::new(&mut pio.common, pio.sm0, p.PIN_2, &prg); + + let mut sensor = Ds18b20::new(onewire); + + loop { + sensor.start().await; // Start a new measurement + Timer::after_secs(1).await; // Allow 1s for the measurement to finish + match sensor.temperature().await { + Ok(temp) => info!("temp = {:?} deg C", temp), + _ => error!("sensor error"), + } + Timer::after_secs(1).await; + } +} + +/// DS18B20 temperature sensor driver +pub struct Ds18b20<'d, PIO: pio::Instance, const SM: usize> { + wire: PioOneWire<'d, PIO, SM>, +} + +impl<'d, PIO: pio::Instance, const SM: usize> Ds18b20<'d, PIO, SM> { + pub fn new(wire: PioOneWire<'d, PIO, SM>) -> Self { + Self { wire } + } + + /// Calculate CRC8 of the data + fn crc8(data: &[u8]) -> u8 { + let mut temp; + let mut data_byte; + let mut crc = 0; + for b in data { + data_byte = *b; + for _ in 0..8 { + temp = (crc ^ data_byte) & 0x01; + crc >>= 1; + if temp != 0 { + crc ^= 0x8C; + } + data_byte >>= 1; + } + } + crc + } + + /// Start a new measurement. Allow at least 1000ms before getting `temperature`. + pub async fn start(&mut self) { + self.wire.write_bytes(&[0xCC, 0x44]).await; + } + + /// Read the temperature. Ensure >1000ms has passed since `start` before calling this. + pub async fn temperature(&mut self) -> Result { + self.wire.write_bytes(&[0xCC, 0xBE]).await; + let mut data = [0; 9]; + self.wire.read_bytes(&mut data).await; + match Self::crc8(&data) == 0 { + true => Ok(((data[1] as u32) << 8 | data[0] as u32) as f32 / 16.), + false => Err(()), + } + } +} diff --git a/examples/rp23/src/bin/pio_pwm.rs b/examples/rp23/src/bin/pio_pwm.rs new file mode 100644 index 000000000..11af62a7a --- /dev/null +++ b/examples/rp23/src/bin/pio_pwm.rs @@ -0,0 +1,43 @@ +//! This example shows how to create a pwm using the PIO module in the RP2040 chip. + +#![no_std] +#![no_main] +use core::time::Duration; + +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::PIO0; +use embassy_rp::pio::{InterruptHandler, Pio}; +use embassy_rp::pio_programs::pwm::{PioPwm, PioPwmProgram}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +const REFRESH_INTERVAL: u64 = 20000; + +bind_interrupts!(struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let Pio { mut common, sm0, .. } = Pio::new(p.PIO0, Irqs); + + // Note that PIN_25 is the led pin on the Pico + let prg = PioPwmProgram::new(&mut common); + let mut pwm_pio = PioPwm::new(&mut common, sm0, p.PIN_25, &prg); + pwm_pio.set_period(Duration::from_micros(REFRESH_INTERVAL)); + pwm_pio.start(); + + let mut duration = 0; + loop { + duration = (duration + 1) % 1000; + pwm_pio.write(Duration::from_micros(duration)); + Timer::after_millis(1).await; + } +} diff --git a/examples/rp23/src/bin/pio_rotary_encoder.rs b/examples/rp23/src/bin/pio_rotary_encoder.rs new file mode 100644 index 000000000..2bb0e67f9 --- /dev/null +++ b/examples/rp23/src/bin/pio_rotary_encoder.rs @@ -0,0 +1,60 @@ +//! This example shows how to use the PIO module in the RP2040 to read a quadrature rotary encoder. + +#![no_std] +#![no_main] + +use defmt::info; +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::PIO0; +use embassy_rp::pio::{InterruptHandler, Pio}; +use embassy_rp::pio_programs::rotary_encoder::{Direction, PioEncoder, PioEncoderProgram}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +#[embassy_executor::task] +async fn encoder_0(mut encoder: PioEncoder<'static, PIO0, 0>) { + let mut count = 0; + loop { + info!("Count: {}", count); + count += match encoder.read().await { + Direction::Clockwise => 1, + Direction::CounterClockwise => -1, + }; + } +} + +#[embassy_executor::task] +async fn encoder_1(mut encoder: PioEncoder<'static, PIO0, 1>) { + let mut count = 0; + loop { + info!("Count: {}", count); + count += match encoder.read().await { + Direction::Clockwise => 1, + Direction::CounterClockwise => -1, + }; + } +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let Pio { + mut common, sm0, sm1, .. + } = Pio::new(p.PIO0, Irqs); + + let prg = PioEncoderProgram::new(&mut common); + let encoder0 = PioEncoder::new(&mut common, sm0, p.PIN_4, p.PIN_5, &prg); + let encoder1 = PioEncoder::new(&mut common, sm1, p.PIN_6, p.PIN_7, &prg); + + spawner.must_spawn(encoder_0(encoder0)); + spawner.must_spawn(encoder_1(encoder1)); +} diff --git a/examples/rp23/src/bin/pio_servo.rs b/examples/rp23/src/bin/pio_servo.rs new file mode 100644 index 000000000..4e94103f1 --- /dev/null +++ b/examples/rp23/src/bin/pio_servo.rs @@ -0,0 +1,133 @@ +//! This example shows how to create a pwm using the PIO module in the RP2040 chip. + +#![no_std] +#![no_main] +use core::time::Duration; + +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::PIO0; +use embassy_rp::pio::{Instance, InterruptHandler, Pio}; +use embassy_rp::pio_programs::pwm::{PioPwm, PioPwmProgram}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +const DEFAULT_MIN_PULSE_WIDTH: u64 = 1000; // uncalibrated default, the shortest duty cycle sent to a servo +const DEFAULT_MAX_PULSE_WIDTH: u64 = 2000; // uncalibrated default, the longest duty cycle sent to a servo +const DEFAULT_MAX_DEGREE_ROTATION: u64 = 160; // 160 degrees is typical +const REFRESH_INTERVAL: u64 = 20000; // The period of each cycle + +bind_interrupts!(struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +pub struct ServoBuilder<'d, T: Instance, const SM: usize> { + pwm: PioPwm<'d, T, SM>, + period: Duration, + min_pulse_width: Duration, + max_pulse_width: Duration, + max_degree_rotation: u64, +} + +impl<'d, T: Instance, const SM: usize> ServoBuilder<'d, T, SM> { + pub fn new(pwm: PioPwm<'d, T, SM>) -> Self { + Self { + pwm, + period: Duration::from_micros(REFRESH_INTERVAL), + min_pulse_width: Duration::from_micros(DEFAULT_MIN_PULSE_WIDTH), + max_pulse_width: Duration::from_micros(DEFAULT_MAX_PULSE_WIDTH), + max_degree_rotation: DEFAULT_MAX_DEGREE_ROTATION, + } + } + + pub fn set_period(mut self, duration: Duration) -> Self { + self.period = duration; + self + } + + pub fn set_min_pulse_width(mut self, duration: Duration) -> Self { + self.min_pulse_width = duration; + self + } + + pub fn set_max_pulse_width(mut self, duration: Duration) -> Self { + self.max_pulse_width = duration; + self + } + + pub fn set_max_degree_rotation(mut self, degree: u64) -> Self { + self.max_degree_rotation = degree; + self + } + + pub fn build(mut self) -> Servo<'d, T, SM> { + self.pwm.set_period(self.period); + Servo { + pwm: self.pwm, + min_pulse_width: self.min_pulse_width, + max_pulse_width: self.max_pulse_width, + max_degree_rotation: self.max_degree_rotation, + } + } +} + +pub struct Servo<'d, T: Instance, const SM: usize> { + pwm: PioPwm<'d, T, SM>, + min_pulse_width: Duration, + max_pulse_width: Duration, + max_degree_rotation: u64, +} + +impl<'d, T: Instance, const SM: usize> Servo<'d, T, SM> { + pub fn start(&mut self) { + self.pwm.start(); + } + + pub fn stop(&mut self) { + self.pwm.stop(); + } + + pub fn write_time(&mut self, duration: Duration) { + self.pwm.write(duration); + } + + pub fn rotate(&mut self, degree: u64) { + let degree_per_nano_second = (self.max_pulse_width.as_nanos() as u64 - self.min_pulse_width.as_nanos() as u64) + / self.max_degree_rotation; + let mut duration = + Duration::from_nanos(degree * degree_per_nano_second + self.min_pulse_width.as_nanos() as u64); + if self.max_pulse_width < duration { + duration = self.max_pulse_width; + } + + self.pwm.write(duration); + } +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let Pio { mut common, sm0, .. } = Pio::new(p.PIO0, Irqs); + + let prg = PioPwmProgram::new(&mut common); + let pwm_pio = PioPwm::new(&mut common, sm0, p.PIN_1, &prg); + let mut servo = ServoBuilder::new(pwm_pio) + .set_max_degree_rotation(120) // Example of adjusting values for MG996R servo + .set_min_pulse_width(Duration::from_micros(350)) // This value was detemined by a rough experiment. + .set_max_pulse_width(Duration::from_micros(2600)) // Along with this value. + .build(); + + servo.start(); + + let mut degree = 0; + loop { + degree = (degree + 1) % 120; + servo.rotate(degree); + Timer::after_millis(50).await; + } +} diff --git a/examples/rp23/src/bin/pio_stepper.rs b/examples/rp23/src/bin/pio_stepper.rs new file mode 100644 index 000000000..4fabe78ca --- /dev/null +++ b/examples/rp23/src/bin/pio_stepper.rs @@ -0,0 +1,54 @@ +//! This example shows how to use the PIO module in the RP2040 to implement a stepper motor driver +//! for a 5-wire stepper such as the 28BYJ-48. You can halt an ongoing rotation by dropping the future. + +#![no_std] +#![no_main] + +use defmt::info; +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::PIO0; +use embassy_rp::pio::{InterruptHandler, Pio}; +use embassy_rp::pio_programs::stepper::{PioStepper, PioStepperProgram}; +use embassy_time::{with_timeout, Duration, Timer}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let Pio { + mut common, irq0, sm0, .. + } = Pio::new(p.PIO0, Irqs); + + let prg = PioStepperProgram::new(&mut common); + let mut stepper = PioStepper::new(&mut common, sm0, irq0, p.PIN_4, p.PIN_5, p.PIN_6, p.PIN_7, &prg); + stepper.set_frequency(120); + loop { + info!("CW full steps"); + stepper.step(1000).await; + + info!("CCW full steps, drop after 1 sec"); + if with_timeout(Duration::from_secs(1), stepper.step(-i32::MAX)) + .await + .is_err() + { + info!("Time's up!"); + Timer::after(Duration::from_secs(1)).await; + } + + info!("CW half steps"); + stepper.step_half(1000).await; + + info!("CCW half steps"); + stepper.step_half(-1000).await; + } +} diff --git a/examples/rp23/src/bin/pio_uart.rs b/examples/rp23/src/bin/pio_uart.rs new file mode 100644 index 000000000..f8398c22a --- /dev/null +++ b/examples/rp23/src/bin/pio_uart.rs @@ -0,0 +1,202 @@ +//! This example shows how to use the PIO module in the RP2040 chip to implement a duplex UART. +//! The PIO module is a very powerful peripheral that can be used to implement many different +//! protocols. It is a very flexible state machine that can be programmed to do almost anything. +//! +//! This example opens up a USB device that implements a CDC ACM serial port. It then uses the +//! PIO module to implement a UART that is connected to the USB serial port. This allows you to +//! communicate with a device connected to the RP2040 over USB serial. + +#![no_std] +#![no_main] +#![allow(async_fn_in_trait)] + +use defmt::{info, panic, trace}; +use embassy_executor::Spawner; +use embassy_futures::join::{join, join3}; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::{PIO0, USB}; +use embassy_rp::pio_programs::uart::{PioUartRx, PioUartRxProgram, PioUartTx, PioUartTxProgram}; +use embassy_rp::usb::{Driver, Instance, InterruptHandler}; +use embassy_rp::{bind_interrupts, pio}; +use embassy_sync::blocking_mutex::raw::NoopRawMutex; +use embassy_sync::pipe::Pipe; +use embassy_usb::class::cdc_acm::{CdcAcmClass, Receiver, Sender, State}; +use embassy_usb::driver::EndpointError; +use embassy_usb::{Builder, Config}; +use embedded_io_async::{Read, Write}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + USBCTRL_IRQ => InterruptHandler; + PIO0_IRQ_0 => pio::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + info!("Hello there!"); + + let p = embassy_rp::init(Default::default()); + + // Create the driver, from the HAL. + let driver = Driver::new(p.USB, Irqs); + + // Create embassy-usb Config + let mut config = Config::new(0xc0de, 0xcafe); + config.manufacturer = Some("Embassy"); + config.product = Some("PIO UART example"); + config.serial_number = Some("12345678"); + config.max_power = 100; + config.max_packet_size_0 = 64; + + // Required for windows compatibility. + // https://developer.nordicsemi.com/nRF_Connect_SDK/doc/1.9.1/kconfig/CONFIG_CDC_ACM_IAD.html#help + config.device_class = 0xEF; + config.device_sub_class = 0x02; + config.device_protocol = 0x01; + config.composite_with_iads = true; + + // Create embassy-usb DeviceBuilder using the driver and config. + // It needs some buffers for building the descriptors. + let mut config_descriptor = [0; 256]; + let mut bos_descriptor = [0; 256]; + let mut control_buf = [0; 64]; + + let mut state = State::new(); + + let mut builder = Builder::new( + driver, + config, + &mut config_descriptor, + &mut bos_descriptor, + &mut [], // no msos descriptors + &mut control_buf, + ); + + // Create classes on the builder. + let class = CdcAcmClass::new(&mut builder, &mut state, 64); + + // Build the builder. + let mut usb = builder.build(); + + // Run the USB device. + let usb_fut = usb.run(); + + // PIO UART setup + let pio::Pio { + mut common, sm0, sm1, .. + } = pio::Pio::new(p.PIO0, Irqs); + + let tx_program = PioUartTxProgram::new(&mut common); + let mut uart_tx = PioUartTx::new(9600, &mut common, sm0, p.PIN_4, &tx_program); + + let rx_program = PioUartRxProgram::new(&mut common); + let mut uart_rx = PioUartRx::new(9600, &mut common, sm1, p.PIN_5, &rx_program); + + // Pipe setup + let mut usb_pipe: Pipe = Pipe::new(); + let (mut usb_pipe_reader, mut usb_pipe_writer) = usb_pipe.split(); + + let mut uart_pipe: Pipe = Pipe::new(); + let (mut uart_pipe_reader, mut uart_pipe_writer) = uart_pipe.split(); + + let (mut usb_tx, mut usb_rx) = class.split(); + + // Read + write from USB + let usb_future = async { + loop { + info!("Wait for USB connection"); + usb_rx.wait_connection().await; + info!("Connected"); + let _ = join( + usb_read(&mut usb_rx, &mut uart_pipe_writer), + usb_write(&mut usb_tx, &mut usb_pipe_reader), + ) + .await; + info!("Disconnected"); + } + }; + + // Read + write from UART + let uart_future = join( + uart_read(&mut uart_rx, &mut usb_pipe_writer), + uart_write(&mut uart_tx, &mut uart_pipe_reader), + ); + + // Run everything concurrently. + // If we had made everything `'static` above instead, we could do this using separate tasks instead. + join3(usb_fut, usb_future, uart_future).await; +} + +struct Disconnected {} + +impl From for Disconnected { + fn from(val: EndpointError) -> Self { + match val { + EndpointError::BufferOverflow => panic!("Buffer overflow"), + EndpointError::Disabled => Disconnected {}, + } + } +} + +/// Read from the USB and write it to the UART TX pipe +async fn usb_read<'d, T: Instance + 'd>( + usb_rx: &mut Receiver<'d, Driver<'d, T>>, + uart_pipe_writer: &mut embassy_sync::pipe::Writer<'_, NoopRawMutex, 20>, +) -> Result<(), Disconnected> { + let mut buf = [0; 64]; + loop { + let n = usb_rx.read_packet(&mut buf).await?; + let data = &buf[..n]; + trace!("USB IN: {:x}", data); + (*uart_pipe_writer).write(data).await; + } +} + +/// Read from the USB TX pipe and write it to the USB +async fn usb_write<'d, T: Instance + 'd>( + usb_tx: &mut Sender<'d, Driver<'d, T>>, + usb_pipe_reader: &mut embassy_sync::pipe::Reader<'_, NoopRawMutex, 20>, +) -> Result<(), Disconnected> { + let mut buf = [0; 64]; + loop { + let n = (*usb_pipe_reader).read(&mut buf).await; + let data = &buf[..n]; + trace!("USB OUT: {:x}", data); + usb_tx.write_packet(&data).await?; + } +} + +/// Read from the UART and write it to the USB TX pipe +async fn uart_read( + uart_rx: &mut PioUartRx<'_, PIO, SM>, + usb_pipe_writer: &mut embassy_sync::pipe::Writer<'_, NoopRawMutex, 20>, +) -> ! { + let mut buf = [0; 64]; + loop { + let n = uart_rx.read(&mut buf).await.expect("UART read error"); + if n == 0 { + continue; + } + let data = &buf[..n]; + trace!("UART IN: {:x}", buf); + (*usb_pipe_writer).write(data).await; + } +} + +/// Read from the UART TX pipe and write it to the UART +async fn uart_write( + uart_tx: &mut PioUartTx<'_, PIO, SM>, + uart_pipe_reader: &mut embassy_sync::pipe::Reader<'_, NoopRawMutex, 20>, +) -> ! { + let mut buf = [0; 64]; + loop { + let n = (*uart_pipe_reader).read(&mut buf).await; + let data = &buf[..n]; + trace!("UART OUT: {:x}", data); + let _ = uart_tx.write(&data).await; + } +} diff --git a/examples/rp23/src/bin/pio_ws2812.rs b/examples/rp23/src/bin/pio_ws2812.rs new file mode 100644 index 000000000..4d258234e --- /dev/null +++ b/examples/rp23/src/bin/pio_ws2812.rs @@ -0,0 +1,73 @@ +//! This example shows powerful PIO module in the RP2040 chip to communicate with WS2812 LED modules. +//! See (https://www.sparkfun.com/categories/tags/ws2812) + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::PIO0; +use embassy_rp::pio::{InterruptHandler, Pio}; +use embassy_rp::pio_programs::ws2812::{PioWs2812, PioWs2812Program}; +use embassy_time::{Duration, Ticker}; +use smart_leds::RGB8; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +/// Input a value 0 to 255 to get a color value +/// The colours are a transition r - g - b - back to r. +fn wheel(mut wheel_pos: u8) -> RGB8 { + wheel_pos = 255 - wheel_pos; + if wheel_pos < 85 { + return (255 - wheel_pos * 3, 0, wheel_pos * 3).into(); + } + if wheel_pos < 170 { + wheel_pos -= 85; + return (0, wheel_pos * 3, 255 - wheel_pos * 3).into(); + } + wheel_pos -= 170; + (wheel_pos * 3, 255 - wheel_pos * 3, 0).into() +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + info!("Start"); + let p = embassy_rp::init(Default::default()); + + let Pio { mut common, sm0, .. } = Pio::new(p.PIO0, Irqs); + + // This is the number of leds in the string. Helpfully, the sparkfun thing plus and adafruit + // feather boards for the 2040 both have one built in. + const NUM_LEDS: usize = 1; + let mut data = [RGB8::default(); NUM_LEDS]; + + // Common neopixel pins: + // Thing plus: 8 + // Adafruit Feather: 16; Adafruit Feather+RFM95: 4 + let program = PioWs2812Program::new(&mut common); + let mut ws2812 = PioWs2812::new(&mut common, sm0, p.DMA_CH0, p.PIN_16, &program); + + // Loop forever making RGB values and pushing them out to the WS2812. + let mut ticker = Ticker::every(Duration::from_millis(10)); + loop { + for j in 0..(256 * 5) { + debug!("New Colors:"); + for i in 0..NUM_LEDS { + data[i] = wheel((((i * 256) as u16 / NUM_LEDS as u16 + j as u16) & 255) as u8); + debug!("R: {} G: {} B: {}", data[i].r, data[i].g, data[i].b); + } + ws2812.write(&data).await; + + ticker.next().await; + } + } +} diff --git a/examples/rp23/src/bin/pwm.rs b/examples/rp23/src/bin/pwm.rs new file mode 100644 index 000000000..5a4457158 --- /dev/null +++ b/examples/rp23/src/bin/pwm.rs @@ -0,0 +1,80 @@ +//! This example shows how to use PWM (Pulse Width Modulation) in the RP235x chip. +//! +//! We demonstrate two ways of using PWM: +//! 1. Via config +//! 2. Via setting a duty cycle + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::{PIN_25, PIN_4, PWM_SLICE2, PWM_SLICE4}; +use embassy_rp::pwm::{Config, Pwm, SetDutyCycle}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + spawner.spawn(pwm_set_config(p.PWM_SLICE4, p.PIN_25)).unwrap(); + spawner.spawn(pwm_set_dutycycle(p.PWM_SLICE2, p.PIN_4)).unwrap(); +} + +/// Demonstrate PWM by modifying & applying the config +/// +/// Using the onboard led, if You are using a different Board than plain Pico2 (i.e. W variant) +/// you must use another slice & pin and an appropriate resistor. +#[embassy_executor::task] +async fn pwm_set_config(slice4: PWM_SLICE4, pin25: PIN_25) { + let mut c = Config::default(); + c.top = 32_768; + c.compare_b = 8; + let mut pwm = Pwm::new_output_b(slice4, pin25, c.clone()); + + loop { + info!("current LED duty cycle: {}/32768", c.compare_b); + Timer::after_secs(1).await; + c.compare_b = c.compare_b.rotate_left(4); + pwm.set_config(&c); + } +} + +/// Demonstrate PWM by setting duty cycle +/// +/// Using GP4 in Slice2, make sure to use an appropriate resistor. +#[embassy_executor::task] +async fn pwm_set_dutycycle(slice2: PWM_SLICE2, pin4: PIN_4) { + // If we aim for a specific frequency, here is how we can calculate the top value. + // The top value sets the period of the PWM cycle, so a counter goes from 0 to top and then wraps around to 0. + // Every such wraparound is one PWM cycle. So here is how we get 25KHz: + let mut c = Config::default(); + let pwm_freq = 25_000; // Hz, our desired frequency + let clock_freq = embassy_rp::clocks::clk_sys_freq(); + c.top = (clock_freq / pwm_freq) as u16 - 1; + + let mut pwm = Pwm::new_output_a(slice2, pin4, c.clone()); + + loop { + // 100% duty cycle, fully on + pwm.set_duty_cycle_fully_on().unwrap(); + Timer::after_secs(1).await; + + // 66% duty cycle. Expressed as simple percentage. + pwm.set_duty_cycle_percent(66).unwrap(); + Timer::after_secs(1).await; + + // 25% duty cycle. Expressed as 32768/4 = 8192. + pwm.set_duty_cycle(c.top / 4).unwrap(); + Timer::after_secs(1).await; + + // 0% duty cycle, fully off. + pwm.set_duty_cycle_fully_off().unwrap(); + Timer::after_secs(1).await; + } +} diff --git a/examples/rp23/src/bin/pwm_input.rs b/examples/rp23/src/bin/pwm_input.rs new file mode 100644 index 000000000..ef87fe8b5 --- /dev/null +++ b/examples/rp23/src/bin/pwm_input.rs @@ -0,0 +1,31 @@ +//! This example shows how to use the PWM module to measure the frequency of an input signal. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio::Pull; +use embassy_rp::pwm::{Config, InputMode, Pwm}; +use embassy_time::{Duration, Ticker}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + + let cfg: Config = Default::default(); + let pwm = Pwm::new_input(p.PWM_SLICE2, p.PIN_5, Pull::None, InputMode::RisingEdge, cfg); + + let mut ticker = Ticker::every(Duration::from_secs(1)); + loop { + info!("Input frequency: {} Hz", pwm.counter()); + pwm.set_counter(0); + ticker.next().await; + } +} diff --git a/examples/rp23/src/bin/pwm_tb6612fng_motor_driver.rs b/examples/rp23/src/bin/pwm_tb6612fng_motor_driver.rs new file mode 100644 index 000000000..3fad2928c --- /dev/null +++ b/examples/rp23/src/bin/pwm_tb6612fng_motor_driver.rs @@ -0,0 +1,107 @@ +//! # PWM TB6612FNG motor driver +//! +//! This example shows the use of a TB6612FNG motor driver. The driver is built on top of embedded_hal and the example demonstrates how embassy_rp can be used to interact with ist. + +#![no_std] +#![no_main] + +use assign_resources::assign_resources; +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::config::Config; +use embassy_rp::gpio::Output; +use embassy_rp::{gpio, peripherals, pwm}; +use embassy_time::{Duration, Timer}; +use tb6612fng::{DriveCommand, Motor, Tb6612fng}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +assign_resources! { + motor: MotorResources { + standby_pin: PIN_22, + left_slice: PWM_SLICE6, + left_pwm_pin: PIN_28, + left_forward_pin: PIN_21, + left_backward_pin: PIN_20, + right_slice: PWM_SLICE5, + right_pwm_pin: PIN_27, + right_forward_pin: PIN_19, + right_backward_pin: PIN_18, + }, +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Config::default()); + let s = split_resources!(p); + let r = s.motor; + + // we want a PWM frequency of 1KHz, especially cheaper motors do not respond well to higher frequencies + let pwm_freq = 1_000; // Hz, our desired frequency + let clock_freq = embassy_rp::clocks::clk_sys_freq(); + let period = (clock_freq / pwm_freq) as u16 - 1; + + // we need a standby output and two motors to construct a full TB6612FNG + + // standby pin + let stby = Output::new(r.standby_pin, gpio::Level::Low); + + // motor A, here defined to be the left motor + let left_fwd = gpio::Output::new(r.left_forward_pin, gpio::Level::Low); + let left_bckw = gpio::Output::new(r.left_backward_pin, gpio::Level::Low); + let mut left_speed = pwm::Config::default(); + left_speed.top = period; + let left_pwm = pwm::Pwm::new_output_a(r.left_slice, r.left_pwm_pin, left_speed); + let left_motor = Motor::new(left_fwd, left_bckw, left_pwm).unwrap(); + + // motor B, here defined to be the right motor + let right_fwd = gpio::Output::new(r.right_forward_pin, gpio::Level::Low); + let right_bckw = gpio::Output::new(r.right_backward_pin, gpio::Level::Low); + let mut right_speed = pwm::Config::default(); + right_speed.top = period; + let right_pwm = pwm::Pwm::new_output_b(r.right_slice, r.right_pwm_pin, right_speed); + let right_motor = Motor::new(right_fwd, right_bckw, right_pwm).unwrap(); + + // construct the motor driver + let mut control = Tb6612fng::new(left_motor, right_motor, stby).unwrap(); + + loop { + // wake up the motor driver + info!("end standby"); + control.disable_standby().unwrap(); + Timer::after(Duration::from_millis(100)).await; + + // drive a straight line forward at 20% speed for 5s + info!("drive straight"); + control.motor_a.drive(DriveCommand::Forward(80)).unwrap(); + control.motor_b.drive(DriveCommand::Forward(80)).unwrap(); + Timer::after(Duration::from_secs(5)).await; + + // coast for 2s + info!("coast"); + control.motor_a.drive(DriveCommand::Stop).unwrap(); + control.motor_b.drive(DriveCommand::Stop).unwrap(); + Timer::after(Duration::from_secs(2)).await; + + // actively brake + info!("brake"); + control.motor_a.drive(DriveCommand::Brake).unwrap(); + control.motor_b.drive(DriveCommand::Brake).unwrap(); + Timer::after(Duration::from_secs(1)).await; + + // slowly turn for 3s + info!("turn"); + control.motor_a.drive(DriveCommand::Backward(50)).unwrap(); + control.motor_b.drive(DriveCommand::Forward(50)).unwrap(); + Timer::after(Duration::from_secs(3)).await; + + // and put the driver in standby mode and wait for 5s + info!("standby"); + control.enable_standby().unwrap(); + Timer::after(Duration::from_secs(5)).await; + } +} diff --git a/examples/rp23/src/bin/rosc.rs b/examples/rp23/src/bin/rosc.rs new file mode 100644 index 000000000..a096f0b7a --- /dev/null +++ b/examples/rp23/src/bin/rosc.rs @@ -0,0 +1,36 @@ +//! This example test the RP Pico on board LED. +//! +//! It does not work with the RP Pico W board. See wifi_blinky.rs. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::{clocks, gpio}; +use embassy_time::Timer; +use gpio::{Level, Output}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = embassy_rp::config::Config::default(); + config.clocks = clocks::ClockConfig::rosc(); + let p = embassy_rp::init(config); + let mut led = Output::new(p.PIN_25, Level::Low); + + loop { + info!("led on!"); + led.set_high(); + Timer::after_secs(1).await; + + info!("led off!"); + led.set_low(); + Timer::after_secs(1).await; + } +} diff --git a/examples/rp23/src/bin/shared_bus.rs b/examples/rp23/src/bin/shared_bus.rs new file mode 100644 index 000000000..2151ccb56 --- /dev/null +++ b/examples/rp23/src/bin/shared_bus.rs @@ -0,0 +1,120 @@ +//! This example shows how to share (async) I2C and SPI buses between multiple devices. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_embedded_hal::shared_bus::asynch::i2c::I2cDevice; +use embassy_embedded_hal::shared_bus::asynch::spi::SpiDevice; +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio::{AnyPin, Level, Output}; +use embassy_rp::i2c::{self, I2c, InterruptHandler}; +use embassy_rp::peripherals::{I2C1, SPI1}; +use embassy_rp::spi::{self, Spi}; +use embassy_sync::blocking_mutex::raw::NoopRawMutex; +use embassy_sync::mutex::Mutex; +use embassy_time::Timer; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +type Spi1Bus = Mutex>; +type I2c1Bus = Mutex>; + +bind_interrupts!(struct Irqs { + I2C1_IRQ => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + info!("Here we go!"); + + // Shared I2C bus + let i2c = I2c::new_async(p.I2C1, p.PIN_15, p.PIN_14, Irqs, i2c::Config::default()); + static I2C_BUS: StaticCell = StaticCell::new(); + let i2c_bus = I2C_BUS.init(Mutex::new(i2c)); + + spawner.must_spawn(i2c_task_a(i2c_bus)); + spawner.must_spawn(i2c_task_b(i2c_bus)); + + // Shared SPI bus + let spi_cfg = spi::Config::default(); + let spi = Spi::new(p.SPI1, p.PIN_10, p.PIN_11, p.PIN_12, p.DMA_CH0, p.DMA_CH1, spi_cfg); + static SPI_BUS: StaticCell = StaticCell::new(); + let spi_bus = SPI_BUS.init(Mutex::new(spi)); + + // Chip select pins for the SPI devices + let cs_a = Output::new(AnyPin::from(p.PIN_0), Level::High); + let cs_b = Output::new(AnyPin::from(p.PIN_1), Level::High); + + spawner.must_spawn(spi_task_a(spi_bus, cs_a)); + spawner.must_spawn(spi_task_b(spi_bus, cs_b)); +} + +#[embassy_executor::task] +async fn i2c_task_a(i2c_bus: &'static I2c1Bus) { + let i2c_dev = I2cDevice::new(i2c_bus); + let _sensor = DummyI2cDeviceDriver::new(i2c_dev, 0xC0); + loop { + info!("i2c task A"); + Timer::after_secs(1).await; + } +} + +#[embassy_executor::task] +async fn i2c_task_b(i2c_bus: &'static I2c1Bus) { + let i2c_dev = I2cDevice::new(i2c_bus); + let _sensor = DummyI2cDeviceDriver::new(i2c_dev, 0xDE); + loop { + info!("i2c task B"); + Timer::after_secs(1).await; + } +} + +#[embassy_executor::task] +async fn spi_task_a(spi_bus: &'static Spi1Bus, cs: Output<'static>) { + let spi_dev = SpiDevice::new(spi_bus, cs); + let _sensor = DummySpiDeviceDriver::new(spi_dev); + loop { + info!("spi task A"); + Timer::after_secs(1).await; + } +} + +#[embassy_executor::task] +async fn spi_task_b(spi_bus: &'static Spi1Bus, cs: Output<'static>) { + let spi_dev = SpiDevice::new(spi_bus, cs); + let _sensor = DummySpiDeviceDriver::new(spi_dev); + loop { + info!("spi task B"); + Timer::after_secs(1).await; + } +} + +// Dummy I2C device driver, using `embedded-hal-async` +struct DummyI2cDeviceDriver { + _i2c: I2C, +} + +impl DummyI2cDeviceDriver { + fn new(i2c_dev: I2C, _address: u8) -> Self { + Self { _i2c: i2c_dev } + } +} + +// Dummy SPI device driver, using `embedded-hal-async` +struct DummySpiDeviceDriver { + _spi: SPI, +} + +impl DummySpiDeviceDriver { + fn new(spi_dev: SPI) -> Self { + Self { _spi: spi_dev } + } +} diff --git a/examples/rp23/src/bin/sharing.rs b/examples/rp23/src/bin/sharing.rs new file mode 100644 index 000000000..68eb5d133 --- /dev/null +++ b/examples/rp23/src/bin/sharing.rs @@ -0,0 +1,155 @@ +//! This example shows some common strategies for sharing resources between tasks. +//! +//! We demonstrate five different ways of sharing, covering different use cases: +//! - Atomics: This method is used for simple values, such as bool and u8..u32 +//! - Blocking Mutex: This is used for sharing non-async things, using Cell/RefCell for interior mutability. +//! - Async Mutex: This is used for sharing async resources, where you need to hold the lock across await points. +//! The async Mutex has interior mutability built-in, so no RefCell is needed. +//! - Cell: For sharing Copy types between tasks running on the same executor. +//! - RefCell: When you want &mut access to a value shared between tasks running on the same executor. +//! +//! More information: https://embassy.dev/book/#_sharing_peripherals_between_tasks + +#![no_std] +#![no_main] + +use core::cell::{Cell, RefCell}; +use core::sync::atomic::{AtomicU32, Ordering}; + +use cortex_m_rt::entry; +use defmt::info; +use embassy_executor::{Executor, InterruptExecutor}; +use embassy_rp::block::ImageDef; +use embassy_rp::clocks::RoscRng; +use embassy_rp::interrupt::{InterruptExt, Priority}; +use embassy_rp::peripherals::UART0; +use embassy_rp::uart::{self, InterruptHandler, UartTx}; +use embassy_rp::{bind_interrupts, interrupt}; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +use embassy_sync::{blocking_mutex, mutex}; +use embassy_time::{Duration, Ticker}; +use rand::RngCore; +use static_cell::{ConstStaticCell, StaticCell}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +type UartAsyncMutex = mutex::Mutex>; + +struct MyType { + inner: u32, +} + +static EXECUTOR_HI: InterruptExecutor = InterruptExecutor::new(); +static EXECUTOR_LOW: StaticCell = StaticCell::new(); + +// Use Atomics for simple values +static ATOMIC: AtomicU32 = AtomicU32::new(0); + +// Use blocking Mutex with Cell/RefCell for sharing non-async things +static MUTEX_BLOCKING: blocking_mutex::Mutex> = + blocking_mutex::Mutex::new(RefCell::new(MyType { inner: 0 })); + +bind_interrupts!(struct Irqs { + UART0_IRQ => InterruptHandler; +}); + +#[interrupt] +unsafe fn SWI_IRQ_0() { + EXECUTOR_HI.on_interrupt() +} + +#[entry] +fn main() -> ! { + let p = embassy_rp::init(Default::default()); + info!("Here we go!"); + + let uart = UartTx::new(p.UART0, p.PIN_0, p.DMA_CH0, uart::Config::default()); + // Use the async Mutex for sharing async things (built-in interior mutability) + static UART: StaticCell = StaticCell::new(); + let uart = UART.init(mutex::Mutex::new(uart)); + + // High-priority executor: runs in interrupt mode + interrupt::SWI_IRQ_0.set_priority(Priority::P3); + let spawner = EXECUTOR_HI.start(interrupt::SWI_IRQ_0); + spawner.must_spawn(task_a(uart)); + + // Low priority executor: runs in thread mode + let executor = EXECUTOR_LOW.init(Executor::new()); + executor.run(|spawner| { + // No Mutex needed when sharing between tasks running on the same executor + + // Use Cell for Copy-types + static CELL: ConstStaticCell> = ConstStaticCell::new(Cell::new([0; 4])); + let cell = CELL.take(); + + // Use RefCell for &mut access + static REF_CELL: ConstStaticCell> = ConstStaticCell::new(RefCell::new(MyType { inner: 0 })); + let ref_cell = REF_CELL.take(); + + spawner.must_spawn(task_b(uart, cell, ref_cell)); + spawner.must_spawn(task_c(cell, ref_cell)); + }); +} + +#[embassy_executor::task] +async fn task_a(uart: &'static UartAsyncMutex) { + let mut ticker = Ticker::every(Duration::from_secs(1)); + loop { + let random = RoscRng.next_u32(); + + { + let mut uart = uart.lock().await; + uart.write(b"task a").await.unwrap(); + // The uart lock is released when it goes out of scope + } + + ATOMIC.store(random, Ordering::Relaxed); + + MUTEX_BLOCKING.lock(|x| x.borrow_mut().inner = random); + + ticker.next().await; + } +} + +#[embassy_executor::task] +async fn task_b(uart: &'static UartAsyncMutex, cell: &'static Cell<[u8; 4]>, ref_cell: &'static RefCell) { + let mut ticker = Ticker::every(Duration::from_secs(1)); + loop { + let random = RoscRng.next_u32(); + + uart.lock().await.write(b"task b").await.unwrap(); + + cell.set(random.to_be_bytes()); + + ref_cell.borrow_mut().inner = random; + + ticker.next().await; + } +} + +#[embassy_executor::task] +async fn task_c(cell: &'static Cell<[u8; 4]>, ref_cell: &'static RefCell) { + let mut ticker = Ticker::every(Duration::from_secs(1)); + loop { + info!("======================="); + + let atomic_val = ATOMIC.load(Ordering::Relaxed); + info!("atomic: {}", atomic_val); + + MUTEX_BLOCKING.lock(|x| { + let val = x.borrow().inner; + info!("blocking mutex: {}", val); + }); + + let cell_val = cell.get(); + info!("cell: {:?}", cell_val); + + let ref_cell_val = ref_cell.borrow().inner; + info!("ref_cell: {:?}", ref_cell_val); + + ticker.next().await; + } +} diff --git a/examples/rp23/src/bin/spi.rs b/examples/rp23/src/bin/spi.rs new file mode 100644 index 000000000..aacb8c7db --- /dev/null +++ b/examples/rp23/src/bin/spi.rs @@ -0,0 +1,51 @@ +//! This example shows how to use SPI (Serial Peripheral Interface) in the RP2040 chip. +//! +//! Example for resistive touch sensor in Waveshare Pico-ResTouch + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::spi::Spi; +use embassy_rp::{gpio, spi}; +use gpio::{Level, Output}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + info!("Hello World!"); + + // Example for resistive touch sensor in Waveshare Pico-ResTouch + + let miso = p.PIN_12; + let mosi = p.PIN_11; + let clk = p.PIN_10; + let touch_cs = p.PIN_16; + + // create SPI + let mut config = spi::Config::default(); + config.frequency = 2_000_000; + let mut spi = Spi::new_blocking(p.SPI1, clk, mosi, miso, config); + + // Configure CS + let mut cs = Output::new(touch_cs, Level::Low); + + loop { + cs.set_low(); + let mut buf = [0x90, 0x00, 0x00, 0xd0, 0x00, 0x00]; + spi.blocking_transfer_in_place(&mut buf).unwrap(); + cs.set_high(); + + let x = (buf[1] as u32) << 5 | (buf[2] as u32) >> 3; + let y = (buf[4] as u32) << 5 | (buf[5] as u32) >> 3; + + info!("touch: {=u32} {=u32}", x, y); + } +} diff --git a/examples/rp23/src/bin/spi_async.rs b/examples/rp23/src/bin/spi_async.rs new file mode 100644 index 000000000..ac7f02fa8 --- /dev/null +++ b/examples/rp23/src/bin/spi_async.rs @@ -0,0 +1,36 @@ +//! This example shows how to use SPI (Serial Peripheral Interface) in the RP2040 chip. +//! No specific hardware is specified in this example. If you connect pin 11 and 12 you should get the same data back. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::spi::{Config, Spi}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + info!("Hello World!"); + + let miso = p.PIN_12; + let mosi = p.PIN_11; + let clk = p.PIN_10; + + let mut spi = Spi::new(p.SPI1, clk, mosi, miso, p.DMA_CH0, p.DMA_CH1, Config::default()); + + loop { + let tx_buf = [1_u8, 2, 3, 4, 5, 6]; + let mut rx_buf = [0_u8; 6]; + spi.transfer(&mut rx_buf, &tx_buf).await.unwrap(); + info!("{:?}", rx_buf); + Timer::after_secs(1).await; + } +} diff --git a/examples/rp23/src/bin/spi_display.rs b/examples/rp23/src/bin/spi_display.rs new file mode 100644 index 000000000..6b7c0781f --- /dev/null +++ b/examples/rp23/src/bin/spi_display.rs @@ -0,0 +1,182 @@ +//! This example shows how to use SPI (Serial Peripheral Interface) in the RP2350 chip. +//! +//! Example written for a display using the ST7789 chip. Possibly the Waveshare Pico-ResTouch +//! (https://www.waveshare.com/wiki/Pico-ResTouch-LCD-2.8) + +#![no_std] +#![no_main] + +use core::cell::RefCell; + +use defmt::*; +use display_interface_spi::SPIInterface; +use embassy_embedded_hal::shared_bus::blocking::spi::SpiDeviceWithConfig; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio::{Level, Output}; +use embassy_rp::spi; +use embassy_rp::spi::{Blocking, Spi}; +use embassy_sync::blocking_mutex::raw::NoopRawMutex; +use embassy_sync::blocking_mutex::Mutex; +use embassy_time::Delay; +use embedded_graphics::image::{Image, ImageRawLE}; +use embedded_graphics::mono_font::ascii::FONT_10X20; +use embedded_graphics::mono_font::MonoTextStyle; +use embedded_graphics::pixelcolor::Rgb565; +use embedded_graphics::prelude::*; +use embedded_graphics::primitives::{PrimitiveStyleBuilder, Rectangle}; +use embedded_graphics::text::Text; +use mipidsi::models::ST7789; +use mipidsi::options::{Orientation, Rotation}; +use mipidsi::Builder; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +use crate::touch::Touch; + +const DISPLAY_FREQ: u32 = 64_000_000; +const TOUCH_FREQ: u32 = 200_000; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + info!("Hello World!"); + + let bl = p.PIN_13; + let rst = p.PIN_15; + let display_cs = p.PIN_9; + let dcx = p.PIN_8; + let miso = p.PIN_12; + let mosi = p.PIN_11; + let clk = p.PIN_10; + let touch_cs = p.PIN_16; + //let touch_irq = p.PIN_17; + + // create SPI + let mut display_config = spi::Config::default(); + display_config.frequency = DISPLAY_FREQ; + display_config.phase = spi::Phase::CaptureOnSecondTransition; + display_config.polarity = spi::Polarity::IdleHigh; + let mut touch_config = spi::Config::default(); + touch_config.frequency = TOUCH_FREQ; + touch_config.phase = spi::Phase::CaptureOnSecondTransition; + touch_config.polarity = spi::Polarity::IdleHigh; + + let spi: Spi<'_, _, Blocking> = Spi::new_blocking(p.SPI1, clk, mosi, miso, touch_config.clone()); + let spi_bus: Mutex = Mutex::new(RefCell::new(spi)); + + let display_spi = SpiDeviceWithConfig::new(&spi_bus, Output::new(display_cs, Level::High), display_config); + let touch_spi = SpiDeviceWithConfig::new(&spi_bus, Output::new(touch_cs, Level::High), touch_config); + + let mut touch = Touch::new(touch_spi); + + let dcx = Output::new(dcx, Level::Low); + let rst = Output::new(rst, Level::Low); + // dcx: 0 = command, 1 = data + + // Enable LCD backlight + let _bl = Output::new(bl, Level::High); + + // display interface abstraction from SPI and DC + let di = SPIInterface::new(display_spi, dcx); + + // Define the display from the display interface and initialize it + let mut display = Builder::new(ST7789, di) + .display_size(240, 320) + .reset_pin(rst) + .orientation(Orientation::new().rotate(Rotation::Deg90)) + .init(&mut Delay) + .unwrap(); + display.clear(Rgb565::BLACK).unwrap(); + + let raw_image_data = ImageRawLE::new(include_bytes!("../../assets/ferris.raw"), 86); + let ferris = Image::new(&raw_image_data, Point::new(34, 68)); + + // Display the image + ferris.draw(&mut display).unwrap(); + + let style = MonoTextStyle::new(&FONT_10X20, Rgb565::GREEN); + Text::new( + "Hello embedded_graphics \n + embassy + RP2040!", + Point::new(20, 200), + style, + ) + .draw(&mut display) + .unwrap(); + + loop { + if let Some((x, y)) = touch.read() { + let style = PrimitiveStyleBuilder::new().fill_color(Rgb565::BLUE).build(); + + Rectangle::new(Point::new(x - 1, y - 1), Size::new(3, 3)) + .into_styled(style) + .draw(&mut display) + .unwrap(); + } + } +} + +/// Driver for the XPT2046 resistive touchscreen sensor +mod touch { + use embedded_hal_1::spi::{Operation, SpiDevice}; + + struct Calibration { + x1: i32, + x2: i32, + y1: i32, + y2: i32, + sx: i32, + sy: i32, + } + + const CALIBRATION: Calibration = Calibration { + x1: 3880, + x2: 340, + y1: 262, + y2: 3850, + sx: 320, + sy: 240, + }; + + pub struct Touch { + spi: SPI, + } + + impl Touch + where + SPI: SpiDevice, + { + pub fn new(spi: SPI) -> Self { + Self { spi } + } + + pub fn read(&mut self) -> Option<(i32, i32)> { + let mut x = [0; 2]; + let mut y = [0; 2]; + self.spi + .transaction(&mut [ + Operation::Write(&[0x90]), + Operation::Read(&mut x), + Operation::Write(&[0xd0]), + Operation::Read(&mut y), + ]) + .unwrap(); + + let x = (u16::from_be_bytes(x) >> 3) as i32; + let y = (u16::from_be_bytes(y) >> 3) as i32; + + let cal = &CALIBRATION; + + let x = ((x - cal.x1) * cal.sx / (cal.x2 - cal.x1)).clamp(0, cal.sx); + let y = ((y - cal.y1) * cal.sy / (cal.y2 - cal.y1)).clamp(0, cal.sy); + if x == 0 && y == 0 { + None + } else { + Some((x, y)) + } + } + } +} diff --git a/examples/rp23/src/bin/spi_sdmmc.rs b/examples/rp23/src/bin/spi_sdmmc.rs new file mode 100644 index 000000000..aa6b44ffa --- /dev/null +++ b/examples/rp23/src/bin/spi_sdmmc.rs @@ -0,0 +1,88 @@ +//! This example shows how to use `embedded-sdmmc` with the RP2040 chip, over SPI. +//! +//! The example will attempt to read a file `MY_FILE.TXT` from the root directory +//! of the SD card and print its contents. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_embedded_hal::SetConfig; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::spi::Spi; +use embassy_rp::{gpio, spi}; +use embedded_hal_bus::spi::ExclusiveDevice; +use embedded_sdmmc::sdcard::{DummyCsPin, SdCard}; +use gpio::{Level, Output}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +struct DummyTimesource(); + +impl embedded_sdmmc::TimeSource for DummyTimesource { + fn get_timestamp(&self) -> embedded_sdmmc::Timestamp { + embedded_sdmmc::Timestamp { + year_since_1970: 0, + zero_indexed_month: 0, + zero_indexed_day: 0, + hours: 0, + minutes: 0, + seconds: 0, + } + } +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + embassy_rp::pac::SIO.spinlock(31).write_value(1); + let p = embassy_rp::init(Default::default()); + + // SPI clock needs to be running at <= 400kHz during initialization + let mut config = spi::Config::default(); + config.frequency = 400_000; + let spi = Spi::new_blocking(p.SPI1, p.PIN_10, p.PIN_11, p.PIN_12, config); + // Use a dummy cs pin here, for embedded-hal SpiDevice compatibility reasons + let spi_dev = ExclusiveDevice::new_no_delay(spi, DummyCsPin); + // Real cs pin + let cs = Output::new(p.PIN_16, Level::High); + + let sdcard = SdCard::new(spi_dev, cs, embassy_time::Delay); + info!("Card size is {} bytes", sdcard.num_bytes().unwrap()); + + // Now that the card is initialized, the SPI clock can go faster + let mut config = spi::Config::default(); + config.frequency = 16_000_000; + sdcard.spi(|dev| dev.bus_mut().set_config(&config)).ok(); + + // Now let's look for volumes (also known as partitions) on our block device. + // To do this we need a Volume Manager. It will take ownership of the block device. + let mut volume_mgr = embedded_sdmmc::VolumeManager::new(sdcard, DummyTimesource()); + + // Try and access Volume 0 (i.e. the first partition). + // The volume object holds information about the filesystem on that volume. + let mut volume0 = volume_mgr.open_volume(embedded_sdmmc::VolumeIdx(0)).unwrap(); + info!("Volume 0: {:?}", defmt::Debug2Format(&volume0)); + + // Open the root directory (mutably borrows from the volume). + let mut root_dir = volume0.open_root_dir().unwrap(); + + // Open a file called "MY_FILE.TXT" in the root directory + // This mutably borrows the directory. + let mut my_file = root_dir + .open_file_in_dir("MY_FILE.TXT", embedded_sdmmc::Mode::ReadOnly) + .unwrap(); + + // Print the contents of the file + while !my_file.is_eof() { + let mut buf = [0u8; 32]; + if let Ok(n) = my_file.read(&mut buf) { + info!("{:a}", buf[..n]); + } + } + + loop {} +} diff --git a/examples/rp23/src/bin/trng.rs b/examples/rp23/src/bin/trng.rs new file mode 100644 index 000000000..8251ebd8b --- /dev/null +++ b/examples/rp23/src/bin/trng.rs @@ -0,0 +1,54 @@ +//! This example shows TRNG usage + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio::{Level, Output}; +use embassy_rp::peripherals::TRNG; +use embassy_rp::trng::Trng; +use embassy_time::Timer; +use rand::RngCore; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + TRNG_IRQ => embassy_rp::trng::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let peripherals = embassy_rp::init(Default::default()); + + // Initialize the TRNG with default configuration + let mut trng = Trng::new(peripherals.TRNG, Irqs, embassy_rp::trng::Config::default()); + // A buffer to collect random bytes in. + let mut randomness = [0u8; 58]; + + let mut led = Output::new(peripherals.PIN_25, Level::Low); + + loop { + trng.fill_bytes(&mut randomness).await; + info!("Random bytes async {}", &randomness); + trng.blocking_fill_bytes(&mut randomness); + info!("Random bytes blocking {}", &randomness); + let random_u32 = trng.next_u32(); + let random_u64 = trng.next_u64(); + info!("Random u32 {} u64 {}", random_u32, random_u64); + // Random number of blinks between 0 and 31 + let blinks = random_u32 % 32; + for _ in 0..blinks { + led.set_high(); + Timer::after_millis(20).await; + led.set_low(); + Timer::after_millis(20).await; + } + Timer::after_millis(1000).await; + } +} diff --git a/examples/rp23/src/bin/uart.rs b/examples/rp23/src/bin/uart.rs new file mode 100644 index 000000000..fe28bb046 --- /dev/null +++ b/examples/rp23/src/bin/uart.rs @@ -0,0 +1,30 @@ +//! This example shows how to use UART (Universal asynchronous receiver-transmitter) in the RP2040 chip. +//! +//! No specific hardware is specified in this example. Only output on pin 0 is tested. +//! The Raspberry Pi Debug Probe (https://www.raspberrypi.com/products/debug-probe/) could be used +//! with its UART port. + +#![no_std] +#![no_main] + +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::uart; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let config = uart::Config::default(); + let mut uart = uart::Uart::new_blocking(p.UART1, p.PIN_4, p.PIN_5, config); + uart.blocking_write("Hello World!\r\n".as_bytes()).unwrap(); + + loop { + uart.blocking_write("hello there!\r\n".as_bytes()).unwrap(); + cortex_m::asm::delay(1_000_000); + } +} diff --git a/examples/rp23/src/bin/uart_buffered_split.rs b/examples/rp23/src/bin/uart_buffered_split.rs new file mode 100644 index 000000000..9ed130727 --- /dev/null +++ b/examples/rp23/src/bin/uart_buffered_split.rs @@ -0,0 +1,63 @@ +//! This example shows how to use UART (Universal asynchronous receiver-transmitter) in the RP2040 chip. +//! +//! No specific hardware is specified in this example. If you connect pin 0 and 1 you should get the same data back. +//! The Raspberry Pi Debug Probe (https://www.raspberrypi.com/products/debug-probe/) could be used +//! with its UART port. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::UART0; +use embassy_rp::uart::{BufferedInterruptHandler, BufferedUart, BufferedUartRx, Config}; +use embassy_time::Timer; +use embedded_io_async::{Read, Write}; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + UART0_IRQ => BufferedInterruptHandler; +}); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + let (tx_pin, rx_pin, uart) = (p.PIN_0, p.PIN_1, p.UART0); + + static TX_BUF: StaticCell<[u8; 16]> = StaticCell::new(); + let tx_buf = &mut TX_BUF.init([0; 16])[..]; + static RX_BUF: StaticCell<[u8; 16]> = StaticCell::new(); + let rx_buf = &mut RX_BUF.init([0; 16])[..]; + let uart = BufferedUart::new(uart, Irqs, tx_pin, rx_pin, tx_buf, rx_buf, Config::default()); + let (mut tx, rx) = uart.split(); + + unwrap!(spawner.spawn(reader(rx))); + + info!("Writing..."); + loop { + let data = [ + 1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, + 29, 30, 31, + ]; + info!("TX {:?}", data); + tx.write_all(&data).await.unwrap(); + Timer::after_secs(1).await; + } +} + +#[embassy_executor::task] +async fn reader(mut rx: BufferedUartRx<'static, UART0>) { + info!("Reading..."); + loop { + let mut buf = [0; 31]; + rx.read_exact(&mut buf).await.unwrap(); + info!("RX {:?}", buf); + } +} diff --git a/examples/rp23/src/bin/uart_r503.rs b/examples/rp23/src/bin/uart_r503.rs new file mode 100644 index 000000000..9aed42785 --- /dev/null +++ b/examples/rp23/src/bin/uart_r503.rs @@ -0,0 +1,163 @@ +#![no_std] +#![no_main] + +use defmt::{debug, error, info}; +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::UART0; +use embassy_rp::uart::{Config, DataBits, InterruptHandler as UARTInterruptHandler, Parity, StopBits, Uart}; +use embassy_time::{with_timeout, Duration, Timer}; +use heapless::Vec; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(pub struct Irqs { + UART0_IRQ => UARTInterruptHandler; +}); + +const START: u16 = 0xEF01; +const ADDRESS: u32 = 0xFFFFFFFF; + +// ================================================================================ + +// Data package format +// Name Length Description +// ========================================================================================================== +// Start 2 bytes Fixed value of 0xEF01; High byte transferred first. +// Address 4 bytes Default value is 0xFFFFFFFF, which can be modified by command. +// High byte transferred first and at wrong adder value, module +// will reject to transfer. +// PID 1 byte 01H Command packet; +// 02H Data packet; Data packet shall not appear alone in executing +// processs, must follow command packet or acknowledge packet. +// 07H Acknowledge packet; +// 08H End of Data packet. +// LENGTH 2 bytes Refers to the length of package content (command packets and data packets) +// plus the length of Checksum (2 bytes). Unit is byte. Max length is 256 bytes. +// And high byte is transferred first. +// DATA - It can be commands, data, command’s parameters, acknowledge result, etc. +// (fingerprint character value, template are all deemed as data); +// SUM 2 bytes The arithmetic sum of package identifier, package length and all package +// contens. Overflowing bits are omitted. high byte is transferred first. + +// ================================================================================ + +// Checksum is calculated on 'length (2 bytes) + data (??)'. +fn compute_checksum(buf: Vec) -> u16 { + let mut checksum = 0u16; + + let check_end = buf.len(); + let checked_bytes = &buf[6..check_end]; + for byte in checked_bytes { + checksum += (*byte) as u16; + } + return checksum; +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + info!("Start"); + + let p = embassy_rp::init(Default::default()); + + // Initialize the fingerprint scanner. + let mut config = Config::default(); + config.baudrate = 57600; + config.stop_bits = StopBits::STOP1; + config.data_bits = DataBits::DataBits8; + config.parity = Parity::ParityNone; + + let (uart, tx_pin, tx_dma, rx_pin, rx_dma) = (p.UART0, p.PIN_16, p.DMA_CH0, p.PIN_17, p.DMA_CH1); + let uart = Uart::new(uart, tx_pin, rx_pin, Irqs, tx_dma, rx_dma, config); + let (mut tx, mut rx) = uart.split(); + + let mut vec_buf: Vec = heapless::Vec::new(); + let mut data: Vec = heapless::Vec::new(); + + let mut speeds: Vec = heapless::Vec::new(); + let _ = speeds.push(0xC8); // Slow + let _ = speeds.push(0x20); // Medium + let _ = speeds.push(0x02); // Fast + + // Cycle through the three colours Red, Blue and Purple forever. + loop { + for colour in 1..=3 { + for speed in &speeds { + // Set the data first, because the length is dependent on that. + // However, we write the length bits before we do the data. + data.clear(); + let _ = data.push(0x01); // ctrl=Breathing light + let _ = data.push(*speed); + let _ = data.push(colour as u8); // colour=Red, Blue, Purple + let _ = data.push(0x00); // times=Infinite + + // Clear buffers + vec_buf.clear(); + + // START + let _ = vec_buf.extend_from_slice(&START.to_be_bytes()[..]); + + // ADDRESS + let _ = vec_buf.extend_from_slice(&ADDRESS.to_be_bytes()[..]); + + // PID + let _ = vec_buf.extend_from_slice(&[0x01]); + + // LENGTH + let len: u16 = (1 + data.len() + 2).try_into().unwrap(); + let _ = vec_buf.extend_from_slice(&len.to_be_bytes()[..]); + + // COMMAND + let _ = vec_buf.push(0x35); // Command: AuraLedConfig + + // DATA + let _ = vec_buf.extend_from_slice(&data); + + // SUM + let chk = compute_checksum(vec_buf.clone()); + let _ = vec_buf.extend_from_slice(&chk.to_be_bytes()[..]); + + // ===== + + // Send command buffer. + let data_write: [u8; 16] = vec_buf.clone().into_array().unwrap(); + debug!(" write='{:?}'", data_write[..]); + match tx.write(&data_write).await { + Ok(..) => info!("Write successful."), + Err(e) => error!("Write error: {:?}", e), + } + + // ===== + + // Read command buffer. + let mut read_buf: [u8; 1] = [0; 1]; // Can only read one byte at a time! + let mut data_read: Vec = heapless::Vec::new(); // Save buffer. + + info!("Attempting read."); + loop { + // Some commands, like `Img2Tz()` needs longer, but we hard-code this to 200ms + // for this command. + match with_timeout(Duration::from_millis(200), rx.read(&mut read_buf)).await { + Ok(..) => { + // Extract and save read byte. + debug!(" r='{=u8:#04x}H' ({:03}D)", read_buf[0], read_buf[0]); + let _ = data_read.push(read_buf[0]).unwrap(); + } + Err(..) => break, // TimeoutError -> Ignore. + } + } + info!("Read successful"); + debug!(" read='{:?}'", data_read[..]); + + Timer::after_secs(3).await; + info!("Changing speed."); + } + + info!("Changing colour."); + } + } +} diff --git a/examples/rp23/src/bin/uart_unidir.rs b/examples/rp23/src/bin/uart_unidir.rs new file mode 100644 index 000000000..12214c4c2 --- /dev/null +++ b/examples/rp23/src/bin/uart_unidir.rs @@ -0,0 +1,55 @@ +//! This example shows how to use UART (Universal asynchronous receiver-transmitter) in the RP2040 chip. +//! +//! Test TX-only and RX-only on two different UARTs. You need to connect GPIO0 to GPIO5 for +//! this to work +//! The Raspberry Pi Debug Probe (https://www.raspberrypi.com/products/debug-probe/) could be used +//! with its UART port. + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::UART1; +use embassy_rp::uart::{Async, Config, InterruptHandler, UartRx, UartTx}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + UART1_IRQ => InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + + let mut uart_tx = UartTx::new(p.UART0, p.PIN_0, p.DMA_CH0, Config::default()); + let uart_rx = UartRx::new(p.UART1, p.PIN_5, Irqs, p.DMA_CH1, Config::default()); + + unwrap!(spawner.spawn(reader(uart_rx))); + + info!("Writing..."); + loop { + let data = [1u8, 2, 3, 4, 5, 6, 7, 8]; + info!("TX {:?}", data); + uart_tx.write(&data).await.unwrap(); + Timer::after_secs(1).await; + } +} + +#[embassy_executor::task] +async fn reader(mut rx: UartRx<'static, UART1, Async>) { + info!("Reading..."); + loop { + // read a total of 4 transmissions (32 / 8) and then print the result + let mut buf = [0; 32]; + rx.read(&mut buf).await.unwrap(); + info!("RX {:?}", buf); + } +} diff --git a/examples/rp23/src/bin/usb_webusb.rs b/examples/rp23/src/bin/usb_webusb.rs new file mode 100644 index 000000000..15279cabc --- /dev/null +++ b/examples/rp23/src/bin/usb_webusb.rs @@ -0,0 +1,160 @@ +//! This example shows how to use USB (Universal Serial Bus) in the RP2040 chip. +//! +//! This creates a WebUSB capable device that echoes data back to the host. +//! +//! To test this in the browser (ideally host this on localhost:8080, to test the landing page +//! feature): +//! ```js +//! (async () => { +//! const device = await navigator.usb.requestDevice({ filters: [{ vendorId: 0xf569 }] }); +//! await device.open(); +//! await device.claimInterface(1); +//! device.transferIn(1, 64).then(data => console.log(data)); +//! await device.transferOut(1, new Uint8Array([1,2,3])); +//! })(); +//! ``` + +#![no_std] +#![no_main] + +use defmt::info; +use embassy_executor::Spawner; +use embassy_futures::join::join; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::peripherals::USB; +use embassy_rp::usb::{Driver as UsbDriver, InterruptHandler}; +use embassy_usb::class::web_usb::{Config as WebUsbConfig, State, Url, WebUsb}; +use embassy_usb::driver::{Driver, Endpoint, EndpointIn, EndpointOut}; +use embassy_usb::msos::{self, windows_version}; +use embassy_usb::{Builder, Config}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +bind_interrupts!(struct Irqs { + USBCTRL_IRQ => InterruptHandler; +}); + +// This is a randomly generated GUID to allow clients on Windows to find our device +const DEVICE_INTERFACE_GUIDS: &[&str] = &["{AFB9A6FB-30BA-44BC-9232-806CFC875321}"]; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + + // Create the driver, from the HAL. + let driver = UsbDriver::new(p.USB, Irqs); + + // Create embassy-usb Config + let mut config = Config::new(0xf569, 0x0001); + config.manufacturer = Some("Embassy"); + config.product = Some("WebUSB example"); + config.serial_number = Some("12345678"); + config.max_power = 100; + config.max_packet_size_0 = 64; + + // Required for windows compatibility. + // https://developer.nordicsemi.com/nRF_Connect_SDK/doc/1.9.1/kconfig/CONFIG_CDC_ACM_IAD.html#help + config.device_class = 0xff; + config.device_sub_class = 0x00; + config.device_protocol = 0x00; + + // Create embassy-usb DeviceBuilder using the driver and config. + // It needs some buffers for building the descriptors. + let mut config_descriptor = [0; 256]; + let mut bos_descriptor = [0; 256]; + let mut control_buf = [0; 64]; + let mut msos_descriptor = [0; 256]; + + let webusb_config = WebUsbConfig { + max_packet_size: 64, + vendor_code: 1, + // If defined, shows a landing page which the device manufacturer would like the user to visit in order to control their device. Suggest the user to navigate to this URL when the device is connected. + landing_url: Some(Url::new("http://localhost:8080")), + }; + + let mut state = State::new(); + + let mut builder = Builder::new( + driver, + config, + &mut config_descriptor, + &mut bos_descriptor, + &mut msos_descriptor, + &mut control_buf, + ); + + // Add the Microsoft OS Descriptor (MSOS/MOD) descriptor. + // We tell Windows that this entire device is compatible with the "WINUSB" feature, + // which causes it to use the built-in WinUSB driver automatically, which in turn + // can be used by libusb/rusb software without needing a custom driver or INF file. + // In principle you might want to call msos_feature() just on a specific function, + // if your device also has other functions that still use standard class drivers. + builder.msos_descriptor(windows_version::WIN8_1, 0); + builder.msos_feature(msos::CompatibleIdFeatureDescriptor::new("WINUSB", "")); + builder.msos_feature(msos::RegistryPropertyFeatureDescriptor::new( + "DeviceInterfaceGUIDs", + msos::PropertyData::RegMultiSz(DEVICE_INTERFACE_GUIDS), + )); + + // Create classes on the builder (WebUSB just needs some setup, but doesn't return anything) + WebUsb::configure(&mut builder, &mut state, &webusb_config); + // Create some USB bulk endpoints for testing. + let mut endpoints = WebEndpoints::new(&mut builder, &webusb_config); + + // Build the builder. + let mut usb = builder.build(); + + // Run the USB device. + let usb_fut = usb.run(); + + // Do some WebUSB transfers. + let webusb_fut = async { + loop { + endpoints.wait_connected().await; + info!("Connected"); + endpoints.echo().await; + } + }; + + // Run everything concurrently. + // If we had made everything `'static` above instead, we could do this using separate tasks instead. + join(usb_fut, webusb_fut).await; +} + +struct WebEndpoints<'d, D: Driver<'d>> { + write_ep: D::EndpointIn, + read_ep: D::EndpointOut, +} + +impl<'d, D: Driver<'d>> WebEndpoints<'d, D> { + fn new(builder: &mut Builder<'d, D>, config: &'d WebUsbConfig<'d>) -> Self { + let mut func = builder.function(0xff, 0x00, 0x00); + let mut iface = func.interface(); + let mut alt = iface.alt_setting(0xff, 0x00, 0x00, None); + + let write_ep = alt.endpoint_bulk_in(config.max_packet_size); + let read_ep = alt.endpoint_bulk_out(config.max_packet_size); + + WebEndpoints { write_ep, read_ep } + } + + // Wait until the device's endpoints are enabled. + async fn wait_connected(&mut self) { + self.read_ep.wait_enabled().await + } + + // Echo data back to the host. + async fn echo(&mut self) { + let mut buf = [0; 64]; + loop { + let n = self.read_ep.read(&mut buf).await.unwrap(); + let data = &buf[..n]; + info!("Data read: {:x}", data); + self.write_ep.write(data).await.unwrap(); + } + } +} diff --git a/examples/rp23/src/bin/watchdog.rs b/examples/rp23/src/bin/watchdog.rs new file mode 100644 index 000000000..efc24c4e3 --- /dev/null +++ b/examples/rp23/src/bin/watchdog.rs @@ -0,0 +1,56 @@ +//! This example shows how to use Watchdog in the RP2040 chip. +//! +//! It does not work with the RP Pico W board. See wifi_blinky.rs or connect external LED and resistor. + +#![no_std] +#![no_main] + +use defmt::info; +use embassy_executor::Spawner; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio; +use embassy_rp::watchdog::*; +use embassy_time::{Duration, Timer}; +use gpio::{Level, Output}; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + info!("Hello world!"); + + let mut watchdog = Watchdog::new(p.WATCHDOG); + let mut led = Output::new(p.PIN_25, Level::Low); + + // Set the LED high for 2 seconds so we know when we're about to start the watchdog + led.set_high(); + Timer::after_secs(2).await; + + // Set to watchdog to reset if it's not fed within 1.05 seconds, and start it + watchdog.start(Duration::from_millis(1_050)); + info!("Started the watchdog timer"); + + // Blink once a second for 5 seconds, feed the watchdog timer once a second to avoid a reset + for _ in 1..=5 { + led.set_low(); + Timer::after_millis(500).await; + led.set_high(); + Timer::after_millis(500).await; + info!("Feeding watchdog"); + watchdog.feed(); + } + + info!("Stopped feeding, device will reset in 1.05 seconds"); + // Blink 10 times per second, not feeding the watchdog. + // The processor should reset in 1.05 seconds. + loop { + led.set_low(); + Timer::after_millis(100).await; + led.set_high(); + Timer::after_millis(100).await; + } +} diff --git a/examples/rp23/src/bin/zerocopy.rs b/examples/rp23/src/bin/zerocopy.rs new file mode 100644 index 000000000..d317c4b56 --- /dev/null +++ b/examples/rp23/src/bin/zerocopy.rs @@ -0,0 +1,99 @@ +//! This example shows how to use `zerocopy_channel` from `embassy_sync` for +//! sending large values between two tasks without copying. +//! The example also shows how to use the RP2040 ADC with DMA. +#![no_std] +#![no_main] + +use core::sync::atomic::{AtomicU16, Ordering}; + +use defmt::*; +use embassy_executor::Spawner; +use embassy_rp::adc::{self, Adc, Async, Config, InterruptHandler}; +use embassy_rp::bind_interrupts; +use embassy_rp::block::ImageDef; +use embassy_rp::gpio::Pull; +use embassy_rp::peripherals::DMA_CH0; +use embassy_sync::blocking_mutex::raw::NoopRawMutex; +use embassy_sync::zerocopy_channel::{Channel, Receiver, Sender}; +use embassy_time::{Duration, Ticker, Timer}; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".start_block"] +#[used] +pub static IMAGE_DEF: ImageDef = ImageDef::secure_exe(); + +type SampleBuffer = [u16; 512]; + +bind_interrupts!(struct Irqs { + ADC_IRQ_FIFO => InterruptHandler; +}); + +const BLOCK_SIZE: usize = 512; +const NUM_BLOCKS: usize = 2; +static MAX: AtomicU16 = AtomicU16::new(0); + +struct AdcParts { + adc: Adc<'static, Async>, + pin: adc::Channel<'static>, + dma: DMA_CH0, +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + info!("Here we go!"); + + let adc_parts = AdcParts { + adc: Adc::new(p.ADC, Irqs, Config::default()), + pin: adc::Channel::new_pin(p.PIN_29, Pull::None), + dma: p.DMA_CH0, + }; + + static BUF: StaticCell<[SampleBuffer; NUM_BLOCKS]> = StaticCell::new(); + let buf = BUF.init([[0; BLOCK_SIZE]; NUM_BLOCKS]); + + static CHANNEL: StaticCell> = StaticCell::new(); + let channel = CHANNEL.init(Channel::new(buf)); + let (sender, receiver) = channel.split(); + + spawner.must_spawn(consumer(receiver)); + spawner.must_spawn(producer(sender, adc_parts)); + + let mut ticker = Ticker::every(Duration::from_secs(1)); + loop { + ticker.next().await; + let max = MAX.load(Ordering::Relaxed); + info!("latest block's max value: {:?}", max); + } +} + +#[embassy_executor::task] +async fn producer(mut sender: Sender<'static, NoopRawMutex, SampleBuffer>, mut adc: AdcParts) { + loop { + // Obtain a free buffer from the channel + let buf = sender.send().await; + + // Fill it with data + adc.adc.read_many(&mut adc.pin, buf, 1, &mut adc.dma).await.unwrap(); + + // Notify the channel that the buffer is now ready to be received + sender.send_done(); + } +} + +#[embassy_executor::task] +async fn consumer(mut receiver: Receiver<'static, NoopRawMutex, SampleBuffer>) { + loop { + // Receive a buffer from the channel + let buf = receiver.receive().await; + + // Simulate using the data, while the producer is filling up the next buffer + Timer::after_micros(1000).await; + let max = buf.iter().max().unwrap(); + MAX.store(*max, Ordering::Relaxed); + + // Notify the channel that the buffer is now ready to be reused + receiver.receive_done(); + } +} diff --git a/examples/std/Cargo.toml b/examples/std/Cargo.toml index f05565e84..fac180c0c 100644 --- a/examples/std/Cargo.toml +++ b/examples/std/Cargo.toml @@ -5,9 +5,9 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["log"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-std", "executor-thread", "log", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["log", "std", ] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["log"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-std", "executor-thread", "log", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["log", "std", ] } embassy-net = { version = "0.4.0", path = "../../embassy-net", features=[ "std", "log", "medium-ethernet", "medium-ip", "tcp", "udp", "dns", "dhcpv4", "proto-ipv6"] } embassy-net-tuntap = { version = "0.1.0", path = "../../embassy-net-tuntap" } embassy-net-ppp = { version = "0.1.0", path = "../../embassy-net-ppp", features = ["log"]} diff --git a/examples/std/src/bin/net.rs b/examples/std/src/bin/net.rs index dad93d0a1..cefa5448c 100644 --- a/examples/std/src/bin/net.rs +++ b/examples/std/src/bin/net.rs @@ -1,9 +1,7 @@ -use std::default::Default; - use clap::Parser; use embassy_executor::{Executor, Spawner}; use embassy_net::tcp::TcpSocket; -use embassy_net::{Config, Ipv4Address, Ipv4Cidr, Stack, StackResources}; +use embassy_net::{Config, Ipv4Address, Ipv4Cidr, StackResources}; use embassy_net_tuntap::TunTapDevice; use embassy_time::Duration; use embedded_io_async::Write; @@ -24,8 +22,8 @@ struct Opts { } #[embassy_executor::task] -async fn net_task(stack: &'static Stack) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, TunTapDevice>) -> ! { + runner.run().await } #[embassy_executor::task] @@ -52,17 +50,11 @@ async fn main_task(spawner: Spawner) { let seed = u64::from_le_bytes(seed); // Init network stack - static STACK: StaticCell> = StaticCell::new(); static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<3>::new()), - seed, - )); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); // Launch network task - spawner.spawn(net_task(stack)).unwrap(); + spawner.spawn(net_task(runner)).unwrap(); // Then we can use it! let mut rx_buffer = [0; 4096]; diff --git a/examples/std/src/bin/net_dns.rs b/examples/std/src/bin/net_dns.rs index fca1e076e..a42c5dbb7 100644 --- a/examples/std/src/bin/net_dns.rs +++ b/examples/std/src/bin/net_dns.rs @@ -1,9 +1,7 @@ -use std::default::Default; - use clap::Parser; use embassy_executor::{Executor, Spawner}; use embassy_net::dns::DnsQueryType; -use embassy_net::{Config, Ipv4Address, Ipv4Cidr, Stack, StackResources}; +use embassy_net::{Config, Ipv4Address, Ipv4Cidr, StackResources}; use embassy_net_tuntap::TunTapDevice; use heapless::Vec; use log::*; @@ -22,8 +20,8 @@ struct Opts { } #[embassy_executor::task] -async fn net_task(stack: &'static Stack) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, TunTapDevice>) -> ! { + runner.run().await } #[embassy_executor::task] @@ -51,17 +49,11 @@ async fn main_task(spawner: Spawner) { let seed = u64::from_le_bytes(seed); // Init network stack - static STACK: StaticCell> = StaticCell::new(); static RESOURCES: StaticCell> = StaticCell::new(); - let stack: &Stack<_> = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<3>::new()), - seed, - )); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); // Launch network task - spawner.spawn(net_task(stack)).unwrap(); + spawner.spawn(net_task(runner)).unwrap(); let host = "example.com"; info!("querying host {:?}...", host); diff --git a/examples/std/src/bin/net_ppp.rs b/examples/std/src/bin/net_ppp.rs index 9ec0ea91f..ea3fbebef 100644 --- a/examples/std/src/bin/net_ppp.rs +++ b/examples/std/src/bin/net_ppp.rs @@ -16,7 +16,7 @@ use async_io::Async; use clap::Parser; use embassy_executor::{Executor, Spawner}; use embassy_net::tcp::TcpSocket; -use embassy_net::{Config, ConfigV4, Ipv4Address, Ipv4Cidr, Stack, StackResources}; +use embassy_net::{Config, ConfigV4, Ipv4Cidr, Stack, StackResources}; use embassy_net_ppp::Runner; use embedded_io_async::Write; use futures::io::BufReader; @@ -37,16 +37,12 @@ struct Opts { } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, embassy_net_ppp::Device<'static>>) -> ! { + runner.run().await } #[embassy_executor::task] -async fn ppp_task( - stack: &'static Stack>, - mut runner: Runner<'static>, - port: SerialPort, -) -> ! { +async fn ppp_task(stack: Stack<'static>, mut runner: Runner<'static>, port: SerialPort) -> ! { let port = Async::new(port).unwrap(); let port = BufReader::new(port); let port = adapter::FromFutures::new(port); @@ -64,10 +60,10 @@ async fn ppp_task( }; let mut dns_servers = Vec::new(); for s in ipv4.dns_servers.iter().flatten() { - let _ = dns_servers.push(Ipv4Address::from_bytes(&s.0)); + let _ = dns_servers.push(*s); } let config = ConfigV4::Static(embassy_net::StaticConfigV4 { - address: Ipv4Cidr::new(Ipv4Address::from_bytes(&addr.0), 0), + address: Ipv4Cidr::new(addr, 0), gateway: None, dns_servers, }); @@ -97,17 +93,16 @@ async fn main_task(spawner: Spawner) { let seed = u64::from_le_bytes(seed); // Init network stack - static STACK: StaticCell>> = StaticCell::new(); static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( + let (stack, net_runner) = embassy_net::new( device, Config::default(), // don't configure IP yet - RESOURCES.init(StackResources::<3>::new()), + RESOURCES.init(StackResources::new()), seed, - )); + ); // Launch network task - spawner.spawn(net_task(stack)).unwrap(); + spawner.spawn(net_task(net_runner)).unwrap(); spawner.spawn(ppp_task(stack, runner, port)).unwrap(); // Then we can use it! diff --git a/examples/std/src/bin/net_udp.rs b/examples/std/src/bin/net_udp.rs index bee91990d..02d4d3efb 100644 --- a/examples/std/src/bin/net_udp.rs +++ b/examples/std/src/bin/net_udp.rs @@ -1,7 +1,7 @@ use clap::Parser; use embassy_executor::{Executor, Spawner}; use embassy_net::udp::{PacketMetadata, UdpSocket}; -use embassy_net::{Config, Ipv4Address, Ipv4Cidr, Stack, StackResources}; +use embassy_net::{Config, Ipv4Address, Ipv4Cidr, StackResources}; use embassy_net_tuntap::TunTapDevice; use heapless::Vec; use log::*; @@ -20,8 +20,8 @@ struct Opts { } #[embassy_executor::task] -async fn net_task(stack: &'static Stack) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, TunTapDevice>) -> ! { + runner.run().await } #[embassy_executor::task] @@ -48,17 +48,11 @@ async fn main_task(spawner: Spawner) { let seed = u64::from_le_bytes(seed); // Init network stack - static STACK: StaticCell> = StaticCell::new(); static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<3>::new()), - seed, - )); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); // Launch network task - spawner.spawn(net_task(stack)).unwrap(); + spawner.spawn(net_task(runner)).unwrap(); // Then we can use it! let mut rx_meta = [PacketMetadata::EMPTY; 16]; diff --git a/examples/std/src/bin/tcp_accept.rs b/examples/std/src/bin/tcp_accept.rs index 00ccd83a7..5d36b739d 100644 --- a/examples/std/src/bin/tcp_accept.rs +++ b/examples/std/src/bin/tcp_accept.rs @@ -1,10 +1,9 @@ use core::fmt::Write as _; -use std::default::Default; use clap::Parser; use embassy_executor::{Executor, Spawner}; use embassy_net::tcp::TcpSocket; -use embassy_net::{Config, Ipv4Address, Ipv4Cidr, Stack, StackResources}; +use embassy_net::{Config, Ipv4Address, Ipv4Cidr, StackResources}; use embassy_net_tuntap::TunTapDevice; use embassy_time::{Duration, Timer}; use embedded_io_async::Write as _; @@ -25,8 +24,8 @@ struct Opts { } #[embassy_executor::task] -async fn net_task(stack: &'static Stack) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, TunTapDevice>) -> ! { + runner.run().await } #[derive(Default)] @@ -63,17 +62,11 @@ async fn main_task(spawner: Spawner) { let seed = u64::from_le_bytes(seed); // Init network stack - static STACK: StaticCell> = StaticCell::new(); static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<3>::new()), - seed, - )); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); // Launch network task - spawner.spawn(net_task(stack)).unwrap(); + spawner.spawn(net_task(runner)).unwrap(); // Then we can use it! let mut rx_buffer = [0; 4096]; diff --git a/examples/stm32c0/Cargo.toml b/examples/stm32c0/Cargo.toml index 7a3e03b75..f8a845095 100644 --- a/examples/stm32c0/Cargo.toml +++ b/examples/stm32c0/Cargo.toml @@ -7,9 +7,9 @@ license = "MIT OR Apache-2.0" [dependencies] # Change stm32c031c6 to your chip name, if necessary. embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = [ "defmt", "time-driver-any", "stm32c031c6", "memory-x", "unstable-pac", "exti"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } defmt = "0.3" defmt-rtt = "0.4" @@ -18,7 +18,6 @@ cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] } cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } [profile.release] diff --git a/examples/stm32f0/Cargo.toml b/examples/stm32f0/Cargo.toml index 71b0eb683..6154fdc64 100644 --- a/examples/stm32f0/Cargo.toml +++ b/examples/stm32f0/Cargo.toml @@ -4,8 +4,6 @@ version = "0.1.0" edition = "2021" license = "MIT OR Apache-2.0" -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - [dependencies] # Change stm32f091rc to your chip name, if necessary. embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = [ "defmt", "memory-x", "stm32f091rc", "time-driver-any", "exti", "unstable-pac"] } @@ -13,10 +11,10 @@ cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-sing cortex-m-rt = "0.7.0" defmt = "0.3" defmt-rtt = "0.4" -panic-probe = "0.3" -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +panic-probe = { version = "0.3", features = ["print-defmt"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } static_cell = "2" portable-atomic = { version = "1.5", features = ["unsafe-assume-single-core"] } diff --git a/examples/stm32f0/src/bin/adc.rs b/examples/stm32f0/src/bin/adc.rs index 8fef062b3..8825e2687 100644 --- a/examples/stm32f0/src/bin/adc.rs +++ b/examples/stm32f0/src/bin/adc.rs @@ -4,13 +4,13 @@ use defmt::*; use embassy_executor::Spawner; use embassy_stm32::adc::{Adc, SampleTime}; -use embassy_stm32::peripherals::ADC; +use embassy_stm32::peripherals::ADC1; use embassy_stm32::{adc, bind_interrupts}; -use embassy_time::{Delay, Timer}; +use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { - ADC1_COMP => adc::InterruptHandler; + ADC1_COMP => adc::InterruptHandler; }); #[embassy_executor::main] @@ -18,11 +18,11 @@ async fn main(_spawner: Spawner) { let p = embassy_stm32::init(Default::default()); info!("Hello World!"); - let mut adc = Adc::new(p.ADC, Irqs, &mut Delay); - adc.set_sample_time(SampleTime::Cycles71_5); + let mut adc = Adc::new(p.ADC1, Irqs); + adc.set_sample_time(SampleTime::CYCLES71_5); let mut pin = p.PA1; - let mut vrefint = adc.enable_vref(&mut Delay); + let mut vrefint = adc.enable_vref(); let vrefint_sample = adc.read(&mut vrefint).await; let convert_to_millivolts = |sample| { // From https://www.st.com/resource/en/datasheet/stm32f031c6.pdf diff --git a/examples/stm32f0/src/bin/multiprio.rs b/examples/stm32f0/src/bin/multiprio.rs index e49951726..84e4077ef 100644 --- a/examples/stm32f0/src/bin/multiprio.rs +++ b/examples/stm32f0/src/bin/multiprio.rs @@ -80,7 +80,7 @@ async fn run_med() { info!(" [med] Starting long computation"); // Spin-wait to simulate a long CPU computation - cortex_m::asm::delay(8_000_000); // ~1 second + embassy_time::block_for(embassy_time::Duration::from_secs(1)); // ~1 second let end = Instant::now(); let ms = end.duration_since(start).as_ticks() / 33; @@ -97,7 +97,7 @@ async fn run_low() { info!("[low] Starting long computation"); // Spin-wait to simulate a long CPU computation - cortex_m::asm::delay(16_000_000); // ~2 seconds + embassy_time::block_for(embassy_time::Duration::from_secs(2)); // ~2 seconds let end = Instant::now(); let ms = end.duration_since(start).as_ticks() / 33; @@ -126,6 +126,11 @@ fn main() -> ! { // Initialize and create handle for devicer peripherals let _p = embassy_stm32::init(Default::default()); + // STM32s don’t have any interrupts exclusively for software use, but they can all be triggered by software as well as + // by the peripheral, so we can just use any free interrupt vectors which aren’t used by the rest of your application. + // In this case we’re using UART1 and UART2, but there’s nothing special about them. Any otherwise unused interrupt + // vector would work exactly the same. + // High-priority executor: USART1, priority level 6 interrupt::USART1.set_priority(Priority::P6); let spawner = EXECUTOR_HIGH.start(interrupt::USART1); diff --git a/examples/stm32f1/Cargo.toml b/examples/stm32f1/Cargo.toml index df5d32f70..c4836859e 100644 --- a/examples/stm32f1/Cargo.toml +++ b/examples/stm32f1/Cargo.toml @@ -7,10 +7,10 @@ license = "MIT OR Apache-2.0" [dependencies] # Change stm32f103c8 to your chip name, if necessary. embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = [ "defmt", "stm32f103c8", "unstable-pac", "memory-x", "time-driver-any" ] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } -embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } defmt = "0.3" @@ -20,9 +20,9 @@ cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-sing cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } nb = "1.0.0" +static_cell = "2.0.0" [profile.dev] opt-level = "s" diff --git a/examples/stm32f1/src/bin/adc.rs b/examples/stm32f1/src/bin/adc.rs index 1440460a9..541ff159e 100644 --- a/examples/stm32f1/src/bin/adc.rs +++ b/examples/stm32f1/src/bin/adc.rs @@ -6,7 +6,7 @@ use embassy_executor::Spawner; use embassy_stm32::adc::Adc; use embassy_stm32::peripherals::ADC1; use embassy_stm32::{adc, bind_interrupts}; -use embassy_time::{Delay, Timer}; +use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { @@ -18,10 +18,10 @@ async fn main(_spawner: Spawner) { let p = embassy_stm32::init(Default::default()); info!("Hello World!"); - let mut adc = Adc::new(p.ADC1, &mut Delay); + let mut adc = Adc::new(p.ADC1); let mut pin = p.PB1; - let mut vrefint = adc.enable_vref(&mut Delay); + let mut vrefint = adc.enable_vref(); let vrefint_sample = adc.read(&mut vrefint).await; let convert_to_millivolts = |sample| { // From http://www.st.com/resource/en/datasheet/CD00161566.pdf diff --git a/examples/stm32f1/src/bin/can.rs b/examples/stm32f1/src/bin/can.rs index c1c4f8359..ad0c8a5a5 100644 --- a/examples/stm32f1/src/bin/can.rs +++ b/examples/stm32f1/src/bin/can.rs @@ -3,11 +3,14 @@ use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::can::bxcan::filter::Mask32; -use embassy_stm32::can::bxcan::{Fifo, Frame, Id, StandardId}; -use embassy_stm32::can::{Can, Rx0InterruptHandler, Rx1InterruptHandler, SceInterruptHandler, TxInterruptHandler}; +use embassy_stm32::can::frame::Envelope; +use embassy_stm32::can::{ + filter, Can, Fifo, Frame, Id, Rx0InterruptHandler, Rx1InterruptHandler, SceInterruptHandler, StandardId, + TxInterruptHandler, +}; use embassy_stm32::peripherals::CAN; use embassy_stm32::{bind_interrupts, Config}; +use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { @@ -20,6 +23,27 @@ bind_interrupts!(struct Irqs { // This example is configured to work with real CAN transceivers on B8/B9. // See other examples for loopback. +fn handle_frame(env: Envelope, read_mode: &str) { + match env.frame.id() { + Id::Extended(id) => { + defmt::println!( + "{} Extended Frame id={:x} {:02x}", + read_mode, + id.as_raw(), + env.frame.data() + ); + } + Id::Standard(id) => { + defmt::println!( + "{} Standard Frame id={:x} {:02x}", + read_mode, + id.as_raw(), + env.frame.data() + ); + } + } +} + #[embassy_executor::main] async fn main(_spawner: Spawner) { let p = embassy_stm32::init(Config::default()); @@ -27,40 +51,90 @@ async fn main(_spawner: Spawner) { // Set alternate pin mapping to B8/B9 embassy_stm32::pac::AFIO.mapr().modify(|w| w.set_can1_remap(2)); + static RX_BUF: StaticCell> = StaticCell::new(); + static TX_BUF: StaticCell> = StaticCell::new(); + let mut can = Can::new(p.CAN, p.PB8, p.PB9, Irqs); - can.as_mut() - .modify_filters() - .enable_bank(0, Fifo::Fifo0, Mask32::accept_all()); + can.modify_filters() + .enable_bank(0, Fifo::Fifo0, filter::Mask32::accept_all()); - can.as_mut() - .modify_config() + can.modify_config() .set_loopback(false) .set_silent(false) - .leave_disabled(); - - can.set_bitrate(250_000); + .set_bitrate(250_000); can.enable().await; - let mut i: u8 = 0; - loop { - let tx_frame = Frame::new_data(unwrap!(StandardId::new(i as _)), [i]); - can.write(&tx_frame).await; - match can.read().await { - Ok(env) => match env.frame.id() { - Id::Extended(id) => { - defmt::println!("Extended Frame id={:x}", id.as_raw()); - } - Id::Standard(id) => { - defmt::println!("Standard Frame id={:x}", id.as_raw()); - } - }, + /* + // Example for using buffered Tx and Rx without needing to + // split first as is done below. + let mut can = can.buffered( + TX_BUF.init(embassy_stm32::can::TxBuf::<10>::new()), + RX_BUF.init(embassy_stm32::can::RxBuf::<10>::new())); + loop { + let tx_frame = Frame::new_data(unwrap!(StandardId::new(i as _)), &[i, 0, 1, 2, 3, 4, 5, 6]).unwrap(); + can.write(&tx_frame).await; + + match can.read().await { + Ok((frame, ts)) => { + handle_frame(Envelope { ts, frame }, "Buf"); + } + Err(err) => { + defmt::println!("Error {}", err); + } + } + i = i.wrapping_add(1); + } + + */ + let (mut tx, mut rx) = can.split(); + + // This example shows using the wait_not_empty API before try read + while i < 3 { + let tx_frame = Frame::new_data(unwrap!(StandardId::new(i as _)), &[i, 0, 1, 2, 3, 4, 5, 6]).unwrap(); + tx.write(&tx_frame).await; + + rx.wait_not_empty().await; + let env = rx.try_read().unwrap(); + handle_frame(env, "Wait"); + i += 1; + } + + // This example shows using the full async non-buffered API + while i < 6 { + let tx_frame = Frame::new_data(unwrap!(StandardId::new(i as _)), &[i, 0, 1, 2, 3, 4, 5, 6]).unwrap(); + tx.write(&tx_frame).await; + + match rx.read().await { + Ok(env) => { + handle_frame(env, "NoBuf"); + } Err(err) => { defmt::println!("Error {}", err); } } i += 1; } + + // This example shows using buffered RX and TX. User passes in desired buffer (size) + // It's possible this way to have just RX or TX buffered. + let mut rx = rx.buffered(RX_BUF.init(embassy_stm32::can::RxBuf::<10>::new())); + let mut tx = tx.buffered(TX_BUF.init(embassy_stm32::can::TxBuf::<10>::new())); + + loop { + let tx_frame = Frame::new_data(unwrap!(StandardId::new(i as _)), &[i, 0, 1, 2, 3, 4, 5, 6]).unwrap(); + tx.write(&tx_frame).await; + + match rx.read().await { + Ok(envelope) => { + handle_frame(envelope, "Buf"); + } + Err(err) => { + defmt::println!("Error {}", err); + } + } + i = i.wrapping_add(1); + } } diff --git a/examples/stm32f1/src/bin/hello.rs b/examples/stm32f1/src/bin/hello.rs index 7b761ecc1..3c295612c 100644 --- a/examples/stm32f1/src/bin/hello.rs +++ b/examples/stm32f1/src/bin/hello.rs @@ -3,15 +3,13 @@ use defmt::info; use embassy_executor::Spawner; -use embassy_stm32::time::Hertz; use embassy_stm32::Config; use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] async fn main(_spawner: Spawner) -> ! { - let mut config = Config::default(); - config.rcc.sys_ck = Some(Hertz(36_000_000)); + let config = Config::default(); let _p = embassy_stm32::init(config); loop { diff --git a/examples/stm32f1/src/bin/input_capture.rs b/examples/stm32f1/src/bin/input_capture.rs new file mode 100644 index 000000000..5e2dab9e6 --- /dev/null +++ b/examples/stm32f1/src/bin/input_capture.rs @@ -0,0 +1,52 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{Level, Output, Pull, Speed}; +use embassy_stm32::time::khz; +use embassy_stm32::timer::input_capture::{CapturePin, InputCapture}; +use embassy_stm32::timer::{self, Channel}; +use embassy_stm32::{bind_interrupts, peripherals}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +/// Connect PA2 and PC13 with a 1k Ohm resistor + +#[embassy_executor::task] +async fn blinky(led: peripherals::PC13) { + let mut led = Output::new(led, Level::High, Speed::Low); + + loop { + info!("high"); + led.set_high(); + Timer::after_millis(300).await; + + info!("low"); + led.set_low(); + Timer::after_millis(300).await; + } +} + +bind_interrupts!(struct Irqs { + TIM2 => timer::CaptureCompareInterruptHandler; +}); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + unwrap!(spawner.spawn(blinky(p.PC13))); + + let ch3 = CapturePin::new_ch3(p.PA2, Pull::None); + let mut ic = InputCapture::new(p.TIM2, None, None, Some(ch3), None, Irqs, khz(1000), Default::default()); + + loop { + info!("wait for rising edge"); + ic.wait_for_rising_edge(Channel::Ch3).await; + + let capture_value = ic.get_capture_value(Channel::Ch3); + info!("new capture! {}", capture_value); + } +} diff --git a/examples/stm32f1/src/bin/pwm_input.rs b/examples/stm32f1/src/bin/pwm_input.rs new file mode 100644 index 000000000..f74853d4e --- /dev/null +++ b/examples/stm32f1/src/bin/pwm_input.rs @@ -0,0 +1,54 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{Level, Output, Pull, Speed}; +use embassy_stm32::time::khz; +use embassy_stm32::timer::pwm_input::PwmInput; +use embassy_stm32::{bind_interrupts, peripherals, timer}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +/// Connect PA0 and PC13 with a 1k Ohm resistor + +#[embassy_executor::task] +async fn blinky(led: peripherals::PC13) { + let mut led = Output::new(led, Level::High, Speed::Low); + + loop { + info!("high"); + led.set_high(); + Timer::after_millis(300).await; + + info!("low"); + led.set_low(); + Timer::after_millis(300).await; + } +} + +bind_interrupts!(struct Irqs { + TIM2 => timer::CaptureCompareInterruptHandler; +}); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + unwrap!(spawner.spawn(blinky(p.PC13))); + + let mut pwm_input = PwmInput::new(p.TIM2, p.PA0, Pull::None, khz(10)); + pwm_input.enable(); + + loop { + Timer::after_millis(500).await; + let period = pwm_input.get_period_ticks(); + let width = pwm_input.get_width_ticks(); + let duty_cycle = pwm_input.get_duty_cycle(); + info!( + "period ticks: {} width ticks: {} duty cycle: {}", + period, width, duty_cycle + ); + } +} diff --git a/examples/stm32f1/src/bin/usb_serial.rs b/examples/stm32f1/src/bin/usb_serial.rs index e28381893..ee99acf41 100644 --- a/examples/stm32f1/src/bin/usb_serial.rs +++ b/examples/stm32f1/src/bin/usb_serial.rs @@ -21,9 +21,23 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut config = Config::default(); - config.rcc.hse = Some(Hertz(8_000_000)); - config.rcc.sys_ck = Some(Hertz(48_000_000)); - config.rcc.pclk1 = Some(Hertz(24_000_000)); + { + use embassy_stm32::rcc::*; + config.rcc.hse = Some(Hse { + freq: Hertz(8_000_000), + // Oscillator for bluepill, Bypass for nucleos. + mode: HseMode::Oscillator, + }); + config.rcc.pll = Some(Pll { + src: PllSource::HSE, + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL9, + }); + config.rcc.sys = Sysclk::PLL1_P; + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV2; + config.rcc.apb2_pre = APBPrescaler::DIV1; + } let mut p = embassy_stm32::init(config); info!("Hello World!"); @@ -46,7 +60,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 7]; @@ -56,7 +69,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], // no msos descriptors diff --git a/examples/stm32f2/Cargo.toml b/examples/stm32f2/Cargo.toml index 4cbf1dc84..0e4827e5d 100644 --- a/examples/stm32f2/Cargo.toml +++ b/examples/stm32f2/Cargo.toml @@ -7,9 +7,9 @@ license = "MIT OR Apache-2.0" [dependencies] # Change stm32f207zg to your chip name, if necessary. embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = [ "defmt", "stm32f207zg", "unstable-pac", "memory-x", "time-driver-any", "exti"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } defmt = "0.3" defmt-rtt = "0.4" @@ -18,7 +18,6 @@ cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-sing cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } nb = "1.0.0" diff --git a/examples/stm32f2/src/bin/pll.rs b/examples/stm32f2/src/bin/pll.rs index e32f283d1..e39e2daec 100644 --- a/examples/stm32f2/src/bin/pll.rs +++ b/examples/stm32f2/src/bin/pll.rs @@ -1,8 +1,6 @@ #![no_std] #![no_main] -use core::convert::TryFrom; - use defmt::*; use embassy_executor::Spawner; use embassy_stm32::time::Hertz; diff --git a/examples/stm32f3/Cargo.toml b/examples/stm32f3/Cargo.toml index 64bb2e560..08a921634 100644 --- a/examples/stm32f3/Cargo.toml +++ b/examples/stm32f3/Cargo.toml @@ -7,10 +7,10 @@ license = "MIT OR Apache-2.0" [dependencies] # Change stm32f303ze to your chip name, if necessary. embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = [ "defmt", "stm32f303ze", "unstable-pac", "memory-x", "time-driver-any", "exti"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } -embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } defmt = "0.3" @@ -20,7 +20,6 @@ cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-sing cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } nb = "1.0.0" embedded-storage = "0.3.1" diff --git a/examples/stm32f3/src/bin/blocking-tsc.rs b/examples/stm32f3/src/bin/blocking-tsc.rs new file mode 100644 index 000000000..5c8dac94f --- /dev/null +++ b/examples/stm32f3/src/bin/blocking-tsc.rs @@ -0,0 +1,98 @@ +// Example of polling TSC (Touch Sensing Controller) that lights an LED when touch is detected. +// +// Suggested physical setup on STM32F303ZE Nucleo board: +// - Connect a 1000pF capacitor between pin A0 and GND. This is your sampling capacitor. +// - Connect one end of a 1K resistor to pin A1 and leave the other end loose. +// The loose end will act as touch sensor which will register your touch. +// +// Troubleshooting the setup: +// - If no touch seems to be registered, then try to disconnect the sampling capacitor from GND momentarily, +// now the led should light up. Next try using a different value for the sampling capacitor. +// Also experiment with increasing the values for `ct_pulse_high_length`, `ct_pulse_low_length`, `pulse_generator_prescaler`, `max_count_value` and `discharge_delay`. +// +// All configuration values and sampling capacitor value have been determined experimentally. +// Suitable configuration and discharge delay values are highly dependent on the value of the sample capacitor. For example, a shorter discharge delay can be used with smaller capacitor values. +// +#![no_std] +#![no_main] + +use defmt::*; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::tsc::{self, *}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +/// This example is written for the nucleo-stm32f303ze, with a stm32f303ze chip. +/// +/// Make sure you check/update the following (whether you use the F303ZE or another board): +/// +/// * [ ] Update .cargo/config.toml with the correct `probe-rs run --chip STM32F303ZETx`chip name. +/// * [ ] Update Cargo.toml to have the correct `embassy-stm32` feature, for F303ZE it should be `stm32f303ze`. +/// * [ ] If your board has a special clock or power configuration, make sure that it is +/// set up appropriately. +/// * [ ] If your board has different pin mapping, update any pin numbers or peripherals +/// to match your schematic +/// +/// If you are unsure, please drop by the Embassy Matrix chat for support, and let us know: +/// +/// * Which example you are trying to run +/// * Which chip and board you are using +/// +/// Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org +#[embassy_executor::main] +async fn main(_spawner: embassy_executor::Spawner) { + let device_config = embassy_stm32::Config::default(); + let context = embassy_stm32::init(device_config); + + let tsc_conf = Config { + ct_pulse_high_length: ChargeTransferPulseCycle::_8, + ct_pulse_low_length: ChargeTransferPulseCycle::_8, + spread_spectrum: false, + spread_spectrum_deviation: SSDeviation::new(2).unwrap(), + spread_spectrum_prescaler: false, + pulse_generator_prescaler: PGPrescalerDivider::_32, + max_count_value: MaxCount::_255, + io_default_mode: false, + synchro_pin_polarity: false, + acquisition_mode: false, + max_count_interrupt: false, + channel_ios: TscIOPin::Group1Io1.into(), + shield_ios: 0, // no shield + sampling_ios: TscIOPin::Group1Io2.into(), + }; + + let mut g1: PinGroup = PinGroup::new(); + g1.set_io1(context.PA0, PinType::Sample); + g1.set_io2(context.PA1, PinType::Channel); + + let mut touch_controller = tsc::Tsc::new_blocking(context.TSC, Some(g1), None, None, None, None, None, tsc_conf); + + // LED2 on the STM32F303ZE nucleo-board + let mut led = Output::new(context.PB7, Level::High, Speed::Low); + + // smaller sample capacitor discharge faster and can be used with shorter delay. + let discharge_delay = 5; // ms + + // the interval at which the loop polls for new touch sensor values + let polling_interval = 100; // ms + + info!("polling for touch"); + loop { + touch_controller.start(); + touch_controller.poll_for_acquisition(); + touch_controller.discharge_io(true); + Timer::after_millis(discharge_delay).await; + + let grp1_status = touch_controller.group_get_status(Group::One); + match grp1_status { + GroupStatus::Complete => { + let group_one_val = touch_controller.group_get_value(Group::One); + info!("{}", group_one_val); + led.set_high(); + } + GroupStatus::Ongoing => led.set_low(), + } + + Timer::after_millis(polling_interval).await; + } +} diff --git a/examples/stm32f3/src/bin/hello.rs b/examples/stm32f3/src/bin/hello.rs index fd54da53d..3c295612c 100644 --- a/examples/stm32f3/src/bin/hello.rs +++ b/examples/stm32f3/src/bin/hello.rs @@ -3,16 +3,13 @@ use defmt::info; use embassy_executor::Spawner; -use embassy_stm32::time::Hertz; use embassy_stm32::Config; use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] async fn main(_spawner: Spawner) -> ! { - let mut config = Config::default(); - config.rcc.hse = Some(Hertz(8_000_000)); - config.rcc.sysclk = Some(Hertz(16_000_000)); + let config = Config::default(); let _p = embassy_stm32::init(config); loop { diff --git a/examples/stm32f3/src/bin/multiprio.rs b/examples/stm32f3/src/bin/multiprio.rs index 328447210..b4620888f 100644 --- a/examples/stm32f3/src/bin/multiprio.rs +++ b/examples/stm32f3/src/bin/multiprio.rs @@ -80,7 +80,7 @@ async fn run_med() { info!(" [med] Starting long computation"); // Spin-wait to simulate a long CPU computation - cortex_m::asm::delay(8_000_000); // ~1 second + embassy_time::block_for(embassy_time::Duration::from_secs(1)); // ~1 second let end = Instant::now(); let ms = end.duration_since(start).as_ticks() / 33; @@ -97,7 +97,7 @@ async fn run_low() { info!("[low] Starting long computation"); // Spin-wait to simulate a long CPU computation - cortex_m::asm::delay(16_000_000); // ~2 seconds + embassy_time::block_for(embassy_time::Duration::from_secs(2)); // ~2 seconds let end = Instant::now(); let ms = end.duration_since(start).as_ticks() / 33; @@ -127,6 +127,11 @@ fn main() -> ! { let _p = embassy_stm32::init(Default::default()); + // STM32s don’t have any interrupts exclusively for software use, but they can all be triggered by software as well as + // by the peripheral, so we can just use any free interrupt vectors which aren’t used by the rest of your application. + // In this case we’re using UART4 and UART5, but there’s nothing special about them. Any otherwise unused interrupt + // vector would work exactly the same. + // High-priority executor: UART4, priority level 6 interrupt::UART4.set_priority(Priority::P6); let spawner = EXECUTOR_HIGH.start(interrupt::UART4); diff --git a/examples/stm32f3/src/bin/usart_dma.rs b/examples/stm32f3/src/bin/usart_dma.rs index 5234e53b9..573a49f19 100644 --- a/examples/stm32f3/src/bin/usart_dma.rs +++ b/examples/stm32f3/src/bin/usart_dma.rs @@ -5,7 +5,6 @@ use core::fmt::Write; use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::dma::NoDma; use embassy_stm32::usart::{Config, Uart}; use embassy_stm32::{bind_interrupts, peripherals, usart}; use heapless::String; @@ -21,7 +20,7 @@ async fn main(_spawner: Spawner) { info!("Hello World!"); let config = Config::default(); - let mut usart = Uart::new(p.USART1, p.PE1, p.PE0, Irqs, p.DMA1_CH4, NoDma, config).unwrap(); + let mut usart = Uart::new(p.USART1, p.PE1, p.PE0, Irqs, p.DMA1_CH4, p.DMA1_CH5, config).unwrap(); for n in 0u32.. { let mut s: String<128> = String::new(); diff --git a/examples/stm32f3/src/bin/usb_serial.rs b/examples/stm32f3/src/bin/usb_serial.rs index cf9ecedfa..5760f2c1c 100644 --- a/examples/stm32f3/src/bin/usb_serial.rs +++ b/examples/stm32f3/src/bin/usb_serial.rs @@ -21,11 +21,22 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut config = Config::default(); - config.rcc.hse = Some(mhz(8)); - config.rcc.sysclk = Some(mhz(48)); - config.rcc.pclk1 = Some(mhz(24)); - config.rcc.pclk2 = Some(mhz(24)); - config.rcc.pll48 = true; + { + use embassy_stm32::rcc::*; + config.rcc.hse = Some(Hse { + freq: mhz(8), + mode: HseMode::Bypass, + }); + config.rcc.pll = Some(Pll { + src: PllSource::HSE, + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL9, + }); + config.rcc.sys = Sysclk::PLL1_P; + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV2; + config.rcc.apb2_pre = APBPrescaler::DIV1; + } let p = embassy_stm32::init(config); info!("Hello World!"); @@ -43,7 +54,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 7]; @@ -53,7 +63,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], // no msos descriptors diff --git a/examples/stm32f334/.cargo/config.toml b/examples/stm32f334/.cargo/config.toml index caf947be6..f38c90a31 100644 --- a/examples/stm32f334/.cargo/config.toml +++ b/examples/stm32f334/.cargo/config.toml @@ -1,6 +1,6 @@ [target.'cfg(all(target_arch = "arm", target_os = "none"))'] # replace STM32F429ZITx with your chip as listed in `probe-rs-cli chip list` -runner = "probe-run --chip STM32F334R8" +runner = "probe-rs run --chip STM32F334R8" [build] target = "thumbv7em-none-eabihf" diff --git a/examples/stm32f334/Cargo.toml b/examples/stm32f334/Cargo.toml index 3e5a7cc8c..cba83bf8c 100644 --- a/examples/stm32f334/Cargo.toml +++ b/examples/stm32f334/Cargo.toml @@ -5,11 +5,11 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = [ "defmt", "stm32f334r8", "unstable-pac", "memory-x", "time-driver-any", "exti"] } -embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } defmt = "0.3" @@ -19,7 +19,6 @@ cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-sing cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } nb = "1.0.0" embedded-storage = "0.3.1" diff --git a/examples/stm32f334/src/bin/adc.rs b/examples/stm32f334/src/bin/adc.rs index 063ee9dac..0528a9637 100644 --- a/examples/stm32f334/src/bin/adc.rs +++ b/examples/stm32f334/src/bin/adc.rs @@ -5,10 +5,9 @@ use defmt::info; use embassy_executor::Spawner; use embassy_stm32::adc::{Adc, SampleTime}; use embassy_stm32::peripherals::ADC1; -use embassy_stm32::rcc::{AdcClockSource, Adcpres}; use embassy_stm32::time::mhz; use embassy_stm32::{adc, bind_interrupts, Config}; -use embassy_time::{Delay, Timer}; +use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { @@ -18,23 +17,34 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) -> ! { let mut config = Config::default(); - config.rcc.sysclk = Some(mhz(64)); - config.rcc.hclk = Some(mhz(64)); - config.rcc.pclk1 = Some(mhz(32)); - config.rcc.pclk2 = Some(mhz(64)); - config.rcc.adc = Some(AdcClockSource::Pll(Adcpres::DIV1)); - + { + use embassy_stm32::rcc::*; + config.rcc.hse = Some(Hse { + freq: mhz(8), + mode: HseMode::Bypass, + }); + config.rcc.pll = Some(Pll { + src: PllSource::HSE, + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL9, + }); + config.rcc.sys = Sysclk::PLL1_P; + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV2; + config.rcc.apb2_pre = APBPrescaler::DIV1; + config.rcc.adc = AdcClockSource::Pll(AdcPllPrescaler::DIV1); + } let mut p = embassy_stm32::init(config); info!("create adc..."); - let mut adc = Adc::new(p.ADC1, Irqs, &mut Delay); + let mut adc = Adc::new(p.ADC1, Irqs); - adc.set_sample_time(SampleTime::Cycles601_5); + adc.set_sample_time(SampleTime::CYCLES601_5); info!("enable vrefint..."); - let mut vrefint = adc.enable_vref(&mut Delay); + let mut vrefint = adc.enable_vref(); let mut temperature = adc.enable_temperature(); loop { diff --git a/examples/stm32f334/src/bin/hello.rs b/examples/stm32f334/src/bin/hello.rs index fd54da53d..3c295612c 100644 --- a/examples/stm32f334/src/bin/hello.rs +++ b/examples/stm32f334/src/bin/hello.rs @@ -3,16 +3,13 @@ use defmt::info; use embassy_executor::Spawner; -use embassy_stm32::time::Hertz; use embassy_stm32::Config; use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] async fn main(_spawner: Spawner) -> ! { - let mut config = Config::default(); - config.rcc.hse = Some(Hertz(8_000_000)); - config.rcc.sysclk = Some(Hertz(16_000_000)); + let config = Config::default(); let _p = embassy_stm32::init(config); loop { diff --git a/examples/stm32f334/src/bin/opamp.rs b/examples/stm32f334/src/bin/opamp.rs index 850a0e335..2dbf1bdab 100644 --- a/examples/stm32f334/src/bin/opamp.rs +++ b/examples/stm32f334/src/bin/opamp.rs @@ -6,10 +6,9 @@ use embassy_executor::Spawner; use embassy_stm32::adc::{Adc, SampleTime}; use embassy_stm32::opamp::{OpAmp, OpAmpGain}; use embassy_stm32::peripherals::ADC2; -use embassy_stm32::rcc::{AdcClockSource, Adcpres}; use embassy_stm32::time::mhz; use embassy_stm32::{adc, bind_interrupts, Config}; -use embassy_time::{Delay, Timer}; +use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { @@ -19,24 +18,35 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) -> ! { let mut config = Config::default(); - config.rcc.sysclk = Some(mhz(64)); - config.rcc.hclk = Some(mhz(64)); - config.rcc.pclk1 = Some(mhz(32)); - config.rcc.pclk2 = Some(mhz(64)); - config.rcc.adc = Some(AdcClockSource::Pll(Adcpres::DIV1)); - + { + use embassy_stm32::rcc::*; + config.rcc.hse = Some(Hse { + freq: mhz(8), + mode: HseMode::Bypass, + }); + config.rcc.pll = Some(Pll { + src: PllSource::HSE, + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL9, + }); + config.rcc.sys = Sysclk::PLL1_P; + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV2; + config.rcc.apb2_pre = APBPrescaler::DIV1; + config.rcc.adc = AdcClockSource::Pll(AdcPllPrescaler::DIV1); + } let mut p = embassy_stm32::init(config); info!("create adc..."); - let mut adc = Adc::new(p.ADC2, Irqs, &mut Delay); + let mut adc = Adc::new(p.ADC2, Irqs); let mut opamp = OpAmp::new(p.OPAMP2); - adc.set_sample_time(SampleTime::Cycles601_5); + adc.set_sample_time(SampleTime::CYCLES601_5); info!("enable vrefint..."); - let mut vrefint = adc.enable_vref(&mut Delay); + let mut vrefint = adc.enable_vref(); let mut temperature = adc.enable_temperature(); let mut buffer = opamp.buffer_ext(&mut p.PA7, &mut p.PA6, OpAmpGain::Mul1); diff --git a/examples/stm32f334/src/bin/pwm.rs b/examples/stm32f334/src/bin/pwm.rs index c149cad92..e6d1a6c02 100644 --- a/examples/stm32f334/src/bin/pwm.rs +++ b/examples/stm32f334/src/bin/pwm.rs @@ -4,7 +4,6 @@ use defmt::*; use embassy_executor::Spawner; use embassy_stm32::hrtim::*; -use embassy_stm32::rcc::HrtimClockSource; use embassy_stm32::time::{khz, mhz}; use embassy_stm32::Config; use embassy_time::Timer; @@ -12,14 +11,27 @@ use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] async fn main(_spawner: Spawner) { - let mut config: Config = Default::default(); - config.rcc.sysclk = Some(mhz(64)); - config.rcc.hclk = Some(mhz(64)); - config.rcc.pclk1 = Some(mhz(32)); - config.rcc.pclk2 = Some(mhz(64)); - config.rcc.hrtim = HrtimClockSource::PllClk; + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.hse = Some(Hse { + freq: mhz(8), + mode: HseMode::Bypass, + }); + config.rcc.pll = Some(Pll { + src: PllSource::HSE, + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL9, + }); + config.rcc.sys = Sysclk::PLL1_P; + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV2; + config.rcc.apb2_pre = APBPrescaler::DIV1; + config.rcc.mux.hrtim1sw = embassy_stm32::rcc::mux::Timsw::PLL1_P; + } let p = embassy_stm32::init(config); + info!("Hello World!"); let ch1 = PwmPin::new_cha(p.PA8); diff --git a/examples/stm32f4/Cargo.toml b/examples/stm32f4/Cargo.toml index cd46fc85b..32fb845cb 100644 --- a/examples/stm32f4/Cargo.toml +++ b/examples/stm32f4/Cargo.toml @@ -6,12 +6,14 @@ license = "MIT OR Apache-2.0" [dependencies] # Change stm32f429zi to your chip name, if necessary. -embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32f429zi", "unstable-pac", "memory-x", "time-driver-any", "exti", "chrono"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } -embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt" ] } +embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32f429zi", "unstable-pac", "memory-x", "time-driver-any", "exti", "chrono"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt" ] } embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", ] } +embassy-net-wiznet = { version = "0.1.0", path = "../../embassy-net-wiznet", features = ["defmt"] } +embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } defmt = "0.3" defmt-rtt = "0.4" @@ -19,14 +21,16 @@ defmt-rtt = "0.4" cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" +embedded-hal-bus = { version = "0.2", features = ["async"] } embedded-io = { version = "0.6.0" } embedded-io-async = { version = "0.6.1" } panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } +futures-util = { version = "0.3.30", default-features = false } heapless = { version = "0.8", default-features = false } nb = "1.0.0" embedded-storage = "0.3.1" micromath = "2.0.0" +usbd-hid = "0.8.1" static_cell = "2" chrono = { version = "^0.4", default-features = false} diff --git a/examples/stm32f4/src/bin/adc.rs b/examples/stm32f4/src/bin/adc.rs index 699c29c05..423d29225 100644 --- a/examples/stm32f4/src/bin/adc.rs +++ b/examples/stm32f4/src/bin/adc.rs @@ -14,7 +14,7 @@ async fn main(_spawner: Spawner) { info!("Hello World!"); let mut delay = Delay; - let mut adc = Adc::new(p.ADC1, &mut delay); + let mut adc = Adc::new(p.ADC1); let mut pin = p.PC1; let mut vrefint = adc.enable_vrefint(); @@ -23,7 +23,7 @@ async fn main(_spawner: Spawner) { // Startup delay can be combined to the maximum of either delay.delay_us(Temperature::start_time_us().max(VrefInt::start_time_us())); - let vrefint_sample = adc.read(&mut vrefint); + let vrefint_sample = adc.blocking_read(&mut vrefint); let convert_to_millivolts = |sample| { // From http://www.st.com/resource/en/datasheet/DM00071990.pdf @@ -50,16 +50,16 @@ async fn main(_spawner: Spawner) { loop { // Read pin - let v = adc.read(&mut pin); + let v = adc.blocking_read(&mut pin); info!("PC1: {} ({} mV)", v, convert_to_millivolts(v)); // Read internal temperature - let v = adc.read(&mut temp); + let v = adc.blocking_read(&mut temp); let celcius = convert_to_celcius(v); info!("Internal temp: {} ({} C)", v, celcius); // Read internal voltage reference - let v = adc.read(&mut vrefint); + let v = adc.blocking_read(&mut vrefint); info!("VrefInt: {}", v); Timer::after_millis(100).await; diff --git a/examples/stm32f4/src/bin/adc_dma.rs b/examples/stm32f4/src/bin/adc_dma.rs new file mode 100644 index 000000000..43a761e6d --- /dev/null +++ b/examples/stm32f4/src/bin/adc_dma.rs @@ -0,0 +1,83 @@ +#![no_std] +#![no_main] +use cortex_m::singleton; +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::adc::{Adc, RingBufferedAdc, SampleTime, Sequence}; +use embassy_stm32::Peripherals; +use embassy_time::Instant; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + spawner.must_spawn(adc_task(p)); +} + +#[embassy_executor::task] +async fn adc_task(mut p: Peripherals) { + const ADC_BUF_SIZE: usize = 1024; + let adc_data: &mut [u16; ADC_BUF_SIZE] = singleton!(ADCDAT : [u16; ADC_BUF_SIZE] = [0u16; ADC_BUF_SIZE]).unwrap(); + let adc_data2: &mut [u16; ADC_BUF_SIZE] = singleton!(ADCDAT2 : [u16; ADC_BUF_SIZE] = [0u16; ADC_BUF_SIZE]).unwrap(); + + let adc = Adc::new(p.ADC1); + let adc2 = Adc::new(p.ADC2); + + let mut adc: RingBufferedAdc = adc.into_ring_buffered(p.DMA2_CH0, adc_data); + let mut adc2: RingBufferedAdc = adc2.into_ring_buffered(p.DMA2_CH2, adc_data2); + + adc.set_sample_sequence(Sequence::One, &mut p.PA0, SampleTime::CYCLES112); + adc.set_sample_sequence(Sequence::Two, &mut p.PA2, SampleTime::CYCLES112); + adc2.set_sample_sequence(Sequence::One, &mut p.PA1, SampleTime::CYCLES112); + adc2.set_sample_sequence(Sequence::Two, &mut p.PA3, SampleTime::CYCLES112); + + // Note that overrun is a big consideration in this implementation. Whatever task is running the adc.read() calls absolutely must circle back around + // to the adc.read() call before the DMA buffer is wrapped around > 1 time. At this point, the overrun is so significant that the context of + // what channel is at what index is lost. The buffer must be cleared and reset. This *is* handled here, but allowing this to happen will cause + // a reduction of performance as each time the buffer is reset, the adc & dma buffer must be restarted. + + // An interrupt executor with a higher priority than other tasks may be a good approach here, allowing this task to wake and read the buffer most + // frequently. + let mut tic = Instant::now(); + let mut buffer1 = [0u16; 512]; + let mut buffer2 = [0u16; 512]; + let _ = adc.start(); + let _ = adc2.start(); + loop { + match adc.read(&mut buffer1).await { + Ok(_data) => { + let toc = Instant::now(); + info!( + "\n adc1: {} dt = {}, n = {}", + buffer1[0..16], + (toc - tic).as_micros(), + _data + ); + tic = toc; + } + Err(e) => { + warn!("Error: {:?}", e); + buffer1 = [0u16; 512]; + let _ = adc.start(); + } + } + + match adc2.read(&mut buffer2).await { + Ok(_data) => { + let toc = Instant::now(); + info!( + "\n adc2: {} dt = {}, n = {}", + buffer2[0..16], + (toc - tic).as_micros(), + _data + ); + tic = toc; + } + Err(e) => { + warn!("Error: {:?}", e); + buffer2 = [0u16; 512]; + let _ = adc2.start(); + } + } + } +} diff --git a/examples/stm32f4/src/bin/can.rs b/examples/stm32f4/src/bin/can.rs index d074b4265..8e3beee24 100644 --- a/examples/stm32f4/src/bin/can.rs +++ b/examples/stm32f4/src/bin/can.rs @@ -4,9 +4,10 @@ use defmt::*; use embassy_executor::Spawner; use embassy_stm32::bind_interrupts; -use embassy_stm32::can::bxcan::filter::Mask32; -use embassy_stm32::can::bxcan::{Fifo, Frame, StandardId}; -use embassy_stm32::can::{Can, Rx0InterruptHandler, Rx1InterruptHandler, SceInterruptHandler, TxInterruptHandler}; +use embassy_stm32::can::filter::Mask32; +use embassy_stm32::can::{ + Can, Fifo, Frame, Rx0InterruptHandler, Rx1InterruptHandler, SceInterruptHandler, StandardId, TxInterruptHandler, +}; use embassy_stm32::gpio::{Input, Pull}; use embassy_stm32::peripherals::CAN1; use embassy_time::Instant; @@ -34,23 +35,18 @@ async fn main(_spawner: Spawner) { let mut can = Can::new(p.CAN1, p.PA11, p.PA12, Irqs); - can.as_mut() - .modify_filters() - .enable_bank(0, Fifo::Fifo0, Mask32::accept_all()); + can.modify_filters().enable_bank(0, Fifo::Fifo0, Mask32::accept_all()); - can.as_mut() - .modify_config() + can.modify_config() .set_loopback(true) // Receive own frames .set_silent(true) - .leave_disabled(); - - can.set_bitrate(1_000_000); + .set_bitrate(1_000_000); can.enable().await; let mut i: u8 = 0; loop { - let tx_frame = Frame::new_data(unwrap!(StandardId::new(i as _)), [i]); + let tx_frame = Frame::new_data(unwrap!(StandardId::new(i as _)), &[i]).unwrap(); let tx_ts = Instant::now(); can.write(&tx_frame).await; @@ -64,9 +60,9 @@ async fn main(_spawner: Spawner) { info!( "loopback frame {=u8}, latency: {} us", - unwrap!(envelope.frame.data())[0], + envelope.frame.data()[0], latency.as_micros() ); - i += 1; + i = i.wrapping_add(1); } } diff --git a/examples/stm32f4/src/bin/dac.rs b/examples/stm32f4/src/bin/dac.rs index 9c7754c4f..dd2a45718 100644 --- a/examples/stm32f4/src/bin/dac.rs +++ b/examples/stm32f4/src/bin/dac.rs @@ -12,7 +12,7 @@ async fn main(_spawner: Spawner) -> ! { let p = embassy_stm32::init(Default::default()); info!("Hello World, dude!"); - let mut dac = DacCh1::new(p.DAC, NoDma, p.PA4); + let mut dac = DacCh1::new(p.DAC1, NoDma, p.PA4); loop { for v in 0..=255 { diff --git a/examples/stm32f4/src/bin/eth.rs b/examples/stm32f4/src/bin/eth.rs index 7f5c8fdb1..baed96449 100644 --- a/examples/stm32f4/src/bin/eth.rs +++ b/examples/stm32f4/src/bin/eth.rs @@ -4,7 +4,7 @@ use defmt::*; use embassy_executor::Spawner; use embassy_net::tcp::TcpSocket; -use embassy_net::{Ipv4Address, Stack, StackResources}; +use embassy_net::{Ipv4Address, StackResources}; use embassy_stm32::eth::generic_smi::GenericSMI; use embassy_stm32::eth::{Ethernet, PacketQueue}; use embassy_stm32::peripherals::ETH; @@ -24,8 +24,8 @@ bind_interrupts!(struct Irqs { type Device = Ethernet<'static, ETH, GenericSMI>; #[embassy_executor::task] -async fn net_task(stack: &'static Stack) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -62,9 +62,9 @@ async fn main(spawner: Spawner) -> ! { let mac_addr = [0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF]; - static PACKETS: StaticCell> = StaticCell::new(); + static PACKETS: StaticCell> = StaticCell::new(); let device = Ethernet::new( - PACKETS.init(PacketQueue::<16, 16>::new()), + PACKETS.init(PacketQueue::<4, 4>::new()), p.ETH, Irqs, p.PA1, @@ -88,17 +88,11 @@ async fn main(spawner: Spawner) -> ! { //}); // Init network stack - static STACK: StaticCell> = StaticCell::new(); - static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<2>::new()), - seed, - )); + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); // Launch network task - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); // Ensure DHCP configuration is up before trying connect stack.wait_config_up().await; @@ -110,7 +104,7 @@ async fn main(spawner: Spawner) -> ! { let mut tx_buffer = [0; 4096]; loop { - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); + let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer); socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); diff --git a/examples/stm32f4/src/bin/eth_compliance_test.rs b/examples/stm32f4/src/bin/eth_compliance_test.rs new file mode 100644 index 000000000..5946fed79 --- /dev/null +++ b/examples/stm32f4/src/bin/eth_compliance_test.rs @@ -0,0 +1,77 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::eth::generic_smi::GenericSMI; +use embassy_stm32::eth::{Ethernet, PacketQueue, StationManagement}; +use embassy_stm32::time::Hertz; +use embassy_stm32::{bind_interrupts, eth, peripherals, rng, Config}; +use embassy_time::Timer; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + ETH => eth::InterruptHandler; + HASH_RNG => rng::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) -> ! { + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.hse = Some(Hse { + freq: Hertz(8_000_000), + mode: HseMode::Bypass, + }); + config.rcc.pll_src = PllSource::HSE; + config.rcc.pll = Some(Pll { + prediv: PllPreDiv::DIV4, + mul: PllMul::MUL180, + divp: Some(PllPDiv::DIV2), // 8mhz / 4 * 180 / 2 = 180Mhz. + divq: None, + divr: None, + }); + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV4; + config.rcc.apb2_pre = APBPrescaler::DIV2; + config.rcc.sys = Sysclk::PLL1_P; + } + let p = embassy_stm32::init(config); + + info!("Hello Compliance World!"); + + let mac_addr = [0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF]; + + const PHY_ADDR: u8 = 0; + static PACKETS: StaticCell> = StaticCell::new(); + let mut device = Ethernet::new( + PACKETS.init(PacketQueue::<4, 4>::new()), + p.ETH, + Irqs, + p.PA1, + p.PA2, + p.PC1, + p.PA7, + p.PC4, + p.PC5, + p.PG13, + p.PB13, + p.PG11, + GenericSMI::new(PHY_ADDR), + mac_addr, + ); + + let sm = unsafe { device.station_management() }; + + // Just an example. Exact register settings depend on the specific PHY and test. + sm.smi_write(PHY_ADDR, 0, 0x2100); + sm.smi_write(PHY_ADDR, 11, 0xA000); + + // NB: Remember to reset the PHY after testing before starting the networking stack + + loop { + Timer::after_secs(1).await; + } +} diff --git a/examples/stm32f4/src/bin/eth_w5500.rs b/examples/stm32f4/src/bin/eth_w5500.rs new file mode 100644 index 000000000..6e6bef08c --- /dev/null +++ b/examples/stm32f4/src/bin/eth_w5500.rs @@ -0,0 +1,134 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_net::tcp::TcpSocket; +use embassy_net::{Ipv4Address, StackResources}; +use embassy_net_wiznet::chip::W5500; +use embassy_net_wiznet::{Device, Runner, State}; +use embassy_stm32::exti::ExtiInput; +use embassy_stm32::gpio::{Level, Output, Pull, Speed}; +use embassy_stm32::mode::Async; +use embassy_stm32::rng::Rng; +use embassy_stm32::spi::Spi; +use embassy_stm32::time::Hertz; +use embassy_stm32::{bind_interrupts, peripherals, rng, spi, Config}; +use embassy_time::{Delay, Timer}; +use embedded_hal_bus::spi::ExclusiveDevice; +use embedded_io_async::Write; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + HASH_RNG => rng::InterruptHandler; +}); + +type EthernetSPI = ExclusiveDevice, Output<'static>, Delay>; +#[embassy_executor::task] +async fn ethernet_task(runner: Runner<'static, W5500, EthernetSPI, ExtiInput<'static>, Output<'static>>) -> ! { + runner.run().await +} + +#[embassy_executor::task] +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static>>) -> ! { + runner.run().await +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) -> ! { + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.hse = Some(Hse { + freq: Hertz(8_000_000), + mode: HseMode::Bypass, + }); + config.rcc.pll_src = PllSource::HSE; + config.rcc.pll = Some(Pll { + prediv: PllPreDiv::DIV4, + mul: PllMul::MUL180, + divp: Some(PllPDiv::DIV2), // 8mhz / 4 * 180 / 2 = 180Mhz. + divq: None, + divr: None, + }); + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV4; + config.rcc.apb2_pre = APBPrescaler::DIV2; + config.rcc.sys = Sysclk::PLL1_P; + } + let p = embassy_stm32::init(config); + + info!("Hello World!"); + + // Generate random seed + let mut rng = Rng::new(p.RNG, Irqs); + let mut seed = [0; 8]; + unwrap!(rng.async_fill_bytes(&mut seed).await); + let seed = u64::from_le_bytes(seed); + + let mut spi_cfg = spi::Config::default(); + spi_cfg.frequency = Hertz(50_000_000); // up to 50m works + let (miso, mosi, clk) = (p.PA6, p.PA7, p.PA5); + let spi = Spi::new(p.SPI1, clk, mosi, miso, p.DMA2_CH3, p.DMA2_CH0, spi_cfg); + let cs = Output::new(p.PA4, Level::High, Speed::VeryHigh); + let spi = unwrap!(ExclusiveDevice::new(spi, cs, Delay)); + + let w5500_int = ExtiInput::new(p.PB0, p.EXTI0, Pull::Up); + let w5500_reset = Output::new(p.PB1, Level::High, Speed::VeryHigh); + + let mac_addr = [0x02, 234, 3, 4, 82, 231]; + static STATE: StaticCell> = StaticCell::new(); + let state = STATE.init(State::<2, 2>::new()); + let (device, runner) = embassy_net_wiznet::new(mac_addr, state, spi, w5500_int, w5500_reset) + .await + .unwrap(); + unwrap!(spawner.spawn(ethernet_task(runner))); + + let config = embassy_net::Config::dhcpv4(Default::default()); + //let config = embassy_net::Config::ipv4_static(embassy_net::StaticConfigV4 { + // address: Ipv4Cidr::new(Ipv4Address::new(10, 42, 0, 61), 24), + // dns_servers: Vec::new(), + // gateway: Some(Ipv4Address::new(10, 42, 0, 1)), + //}); + + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); + + // Launch network task + unwrap!(spawner.spawn(net_task(runner))); + + // Ensure DHCP configuration is up before trying connect + stack.wait_config_up().await; + + info!("Network task initialized"); + + // Then we can use it! + let mut rx_buffer = [0; 1024]; + let mut tx_buffer = [0; 1024]; + + loop { + let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer); + + socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); + + let remote_endpoint = (Ipv4Address::new(10, 42, 0, 1), 8000); + info!("connecting..."); + let r = socket.connect(remote_endpoint).await; + if let Err(e) = r { + info!("connect error: {:?}", e); + Timer::after_secs(1).await; + continue; + } + info!("connected!"); + let buf = [0; 1024]; + loop { + let r = socket.write_all(&buf).await; + if let Err(e) = r { + info!("write error: {:?}", e); + break; + } + Timer::after_secs(1).await; + } + } +} diff --git a/examples/stm32f4/src/bin/i2c.rs b/examples/stm32f4/src/bin/i2c.rs index 4b5da774d..4a96357a4 100644 --- a/examples/stm32f4/src/bin/i2c.rs +++ b/examples/stm32f4/src/bin/i2c.rs @@ -3,35 +3,19 @@ use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::dma::NoDma; use embassy_stm32::i2c::{Error, I2c}; use embassy_stm32::time::Hertz; -use embassy_stm32::{bind_interrupts, i2c, peripherals}; use {defmt_rtt as _, panic_probe as _}; const ADDRESS: u8 = 0x5F; const WHOAMI: u8 = 0x0F; -bind_interrupts!(struct Irqs { - I2C2_EV => i2c::EventInterruptHandler; - I2C2_ER => i2c::ErrorInterruptHandler; -}); - #[embassy_executor::main] async fn main(_spawner: Spawner) { info!("Hello world!"); let p = embassy_stm32::init(Default::default()); - let mut i2c = I2c::new( - p.I2C2, - p.PB10, - p.PB11, - Irqs, - NoDma, - NoDma, - Hertz(100_000), - Default::default(), - ); + let mut i2c = I2c::new_blocking(p.I2C2, p.PB10, p.PB11, Hertz(100_000), Default::default()); let mut data = [0u8; 1]; diff --git a/examples/stm32f4/src/bin/i2c_comparison.rs b/examples/stm32f4/src/bin/i2c_comparison.rs index 30cfbdf57..55c4891e3 100644 --- a/examples/stm32f4/src/bin/i2c_comparison.rs +++ b/examples/stm32f4/src/bin/i2c_comparison.rs @@ -13,7 +13,7 @@ use embassy_stm32::i2c::I2c; use embassy_stm32::time::Hertz; use embassy_stm32::{bind_interrupts, i2c, peripherals}; use embassy_time::Instant; -use futures::future::try_join3; +use futures_util::future::try_join3; use {defmt_rtt as _, panic_probe as _}; const ADDRESS: u8 = 96; diff --git a/examples/stm32f4/src/bin/i2s_dma.rs b/examples/stm32f4/src/bin/i2s_dma.rs index 97a04b2aa..68392847b 100644 --- a/examples/stm32f4/src/bin/i2s_dma.rs +++ b/examples/stm32f4/src/bin/i2s_dma.rs @@ -1,13 +1,10 @@ #![no_std] #![no_main] -use core::fmt::Write; - use defmt::*; use embassy_executor::Spawner; use embassy_stm32::i2s::{Config, I2S}; use embassy_stm32::time::Hertz; -use heapless::String; use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] @@ -15,21 +12,22 @@ async fn main(_spawner: Spawner) { let p = embassy_stm32::init(Default::default()); info!("Hello World!"); - let mut i2s = I2S::new( + let mut dma_buffer = [0x00_u16; 128]; + + let mut i2s = I2S::new_txonly( p.SPI2, p.PC3, // sd p.PB12, // ws p.PB10, // ck p.PC6, // mck p.DMA1_CH4, - p.DMA1_CH3, + &mut dma_buffer, Hertz(1_000_000), Config::default(), ); - for n in 0u32.. { - let mut write: String<128> = String::new(); - core::write!(&mut write, "Hello DMA World {}!\r\n", n).unwrap(); - i2s.write(&mut write.as_bytes()).await.ok(); + for i in 0_u16.. { + i2s.write(&mut [i * 2; 64]).await.ok(); + i2s.write(&mut [i * 2 + 1; 64]).await.ok(); } } diff --git a/examples/stm32f4/src/bin/input_capture.rs b/examples/stm32f4/src/bin/input_capture.rs new file mode 100644 index 000000000..49de33d2b --- /dev/null +++ b/examples/stm32f4/src/bin/input_capture.rs @@ -0,0 +1,52 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{Level, Output, Pull, Speed}; +use embassy_stm32::time::khz; +use embassy_stm32::timer::input_capture::{CapturePin, InputCapture}; +use embassy_stm32::timer::{self, Channel}; +use embassy_stm32::{bind_interrupts, peripherals}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +/// Connect PB2 and PB10 with a 1k Ohm resistor + +#[embassy_executor::task] +async fn blinky(led: peripherals::PB2) { + let mut led = Output::new(led, Level::High, Speed::Low); + + loop { + info!("high"); + led.set_high(); + Timer::after_millis(300).await; + + info!("low"); + led.set_low(); + Timer::after_millis(300).await; + } +} + +bind_interrupts!(struct Irqs { + TIM2 => timer::CaptureCompareInterruptHandler; +}); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + unwrap!(spawner.spawn(blinky(p.PB2))); + + let ch3 = CapturePin::new_ch3(p.PB10, Pull::None); + let mut ic = InputCapture::new(p.TIM2, None, None, Some(ch3), None, Irqs, khz(1000), Default::default()); + + loop { + info!("wait for risign edge"); + ic.wait_for_rising_edge(Channel::Ch3).await; + + let capture_value = ic.get_capture_value(Channel::Ch3); + info!("new capture! {}", capture_value); + } +} diff --git a/examples/stm32f4/src/bin/multiprio.rs b/examples/stm32f4/src/bin/multiprio.rs index 328447210..b4620888f 100644 --- a/examples/stm32f4/src/bin/multiprio.rs +++ b/examples/stm32f4/src/bin/multiprio.rs @@ -80,7 +80,7 @@ async fn run_med() { info!(" [med] Starting long computation"); // Spin-wait to simulate a long CPU computation - cortex_m::asm::delay(8_000_000); // ~1 second + embassy_time::block_for(embassy_time::Duration::from_secs(1)); // ~1 second let end = Instant::now(); let ms = end.duration_since(start).as_ticks() / 33; @@ -97,7 +97,7 @@ async fn run_low() { info!("[low] Starting long computation"); // Spin-wait to simulate a long CPU computation - cortex_m::asm::delay(16_000_000); // ~2 seconds + embassy_time::block_for(embassy_time::Duration::from_secs(2)); // ~2 seconds let end = Instant::now(); let ms = end.duration_since(start).as_ticks() / 33; @@ -127,6 +127,11 @@ fn main() -> ! { let _p = embassy_stm32::init(Default::default()); + // STM32s don’t have any interrupts exclusively for software use, but they can all be triggered by software as well as + // by the peripheral, so we can just use any free interrupt vectors which aren’t used by the rest of your application. + // In this case we’re using UART4 and UART5, but there’s nothing special about them. Any otherwise unused interrupt + // vector would work exactly the same. + // High-priority executor: UART4, priority level 6 interrupt::UART4.set_priority(Priority::P6); let spawner = EXECUTOR_HIGH.start(interrupt::UART4); diff --git a/examples/stm32f4/src/bin/pwm.rs b/examples/stm32f4/src/bin/pwm.rs index 8844a9f0e..04811162b 100644 --- a/examples/stm32f4/src/bin/pwm.rs +++ b/examples/stm32f4/src/bin/pwm.rs @@ -6,7 +6,6 @@ use embassy_executor::Spawner; use embassy_stm32::gpio::OutputType; use embassy_stm32::time::khz; use embassy_stm32::timer::simple_pwm::{PwmPin, SimplePwm}; -use embassy_stm32::timer::Channel; use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; @@ -15,22 +14,22 @@ async fn main(_spawner: Spawner) { let p = embassy_stm32::init(Default::default()); info!("Hello World!"); - let ch1 = PwmPin::new_ch1(p.PE9, OutputType::PushPull); - let mut pwm = SimplePwm::new(p.TIM1, Some(ch1), None, None, None, khz(10), Default::default()); - let max = pwm.get_max_duty(); - pwm.enable(Channel::Ch1); + let ch1_pin = PwmPin::new_ch1(p.PE9, OutputType::PushPull); + let mut pwm = SimplePwm::new(p.TIM1, Some(ch1_pin), None, None, None, khz(10), Default::default()); + let mut ch1 = pwm.ch1(); + ch1.enable(); info!("PWM initialized"); - info!("PWM max duty {}", max); + info!("PWM max duty {}", ch1.max_duty_cycle()); loop { - pwm.set_duty(Channel::Ch1, 0); + ch1.set_duty_cycle_fully_off(); Timer::after_millis(300).await; - pwm.set_duty(Channel::Ch1, max / 4); + ch1.set_duty_cycle_fraction(1, 4); Timer::after_millis(300).await; - pwm.set_duty(Channel::Ch1, max / 2); + ch1.set_duty_cycle_fraction(1, 2); Timer::after_millis(300).await; - pwm.set_duty(Channel::Ch1, max - 1); + ch1.set_duty_cycle(ch1.max_duty_cycle() - 1); Timer::after_millis(300).await; } } diff --git a/examples/stm32f4/src/bin/pwm_input.rs b/examples/stm32f4/src/bin/pwm_input.rs new file mode 100644 index 000000000..ce200549d --- /dev/null +++ b/examples/stm32f4/src/bin/pwm_input.rs @@ -0,0 +1,54 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{Level, Output, Pull, Speed}; +use embassy_stm32::time::khz; +use embassy_stm32::timer::pwm_input::PwmInput; +use embassy_stm32::{bind_interrupts, peripherals, timer}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +/// Connect PB2 and PA6 with a 1k Ohm resistor + +#[embassy_executor::task] +async fn blinky(led: peripherals::PB2) { + let mut led = Output::new(led, Level::High, Speed::Low); + + loop { + info!("high"); + led.set_high(); + Timer::after_millis(300).await; + + info!("low"); + led.set_low(); + Timer::after_millis(300).await; + } +} + +bind_interrupts!(struct Irqs { + TIM2 => timer::CaptureCompareInterruptHandler; +}); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + unwrap!(spawner.spawn(blinky(p.PB2))); + + let mut pwm_input = PwmInput::new(p.TIM3, p.PA6, Pull::None, khz(10)); + pwm_input.enable(); + + loop { + Timer::after_millis(500).await; + let period = pwm_input.get_period_ticks(); + let width = pwm_input.get_width_ticks(); + let duty_cycle = pwm_input.get_duty_cycle(); + info!( + "period ticks: {} width ticks: {} duty cycle: {}", + period, width, duty_cycle + ); + } +} diff --git a/examples/stm32f4/src/bin/rtc.rs b/examples/stm32f4/src/bin/rtc.rs index abab07b6b..82d8a37ba 100644 --- a/examples/stm32f4/src/bin/rtc.rs +++ b/examples/stm32f4/src/bin/rtc.rs @@ -28,7 +28,7 @@ async fn main(_spawner: Spawner) { loop { let now: NaiveDateTime = rtc.now().unwrap().into(); - info!("{}", now.timestamp()); + info!("{}", now.and_utc().timestamp()); Timer::after_millis(1000).await; } diff --git a/examples/stm32f4/src/bin/spi.rs b/examples/stm32f4/src/bin/spi.rs index dc9141c62..970d819fc 100644 --- a/examples/stm32f4/src/bin/spi.rs +++ b/examples/stm32f4/src/bin/spi.rs @@ -3,7 +3,6 @@ use cortex_m_rt::entry; use defmt::*; -use embassy_stm32::dma::NoDma; use embassy_stm32::gpio::{Level, Output, Speed}; use embassy_stm32::spi::{Config, Spi}; use embassy_stm32::time::Hertz; @@ -18,7 +17,7 @@ fn main() -> ! { let mut spi_config = Config::default(); spi_config.frequency = Hertz(1_000_000); - let mut spi = Spi::new(p.SPI3, p.PC10, p.PC12, p.PC11, NoDma, NoDma, spi_config); + let mut spi = Spi::new_blocking(p.SPI3, p.PC10, p.PC12, p.PC11, spi_config); let mut cs = Output::new(p.PE0, Level::High, Speed::VeryHigh); diff --git a/examples/stm32f4/src/bin/usart.rs b/examples/stm32f4/src/bin/usart.rs index 40d9d70f1..991bf6673 100644 --- a/examples/stm32f4/src/bin/usart.rs +++ b/examples/stm32f4/src/bin/usart.rs @@ -3,7 +3,6 @@ use cortex_m_rt::entry; use defmt::*; -use embassy_stm32::dma::NoDma; use embassy_stm32::usart::{Config, Uart}; use embassy_stm32::{bind_interrupts, peripherals, usart}; use {defmt_rtt as _, panic_probe as _}; @@ -19,7 +18,7 @@ fn main() -> ! { let p = embassy_stm32::init(Default::default()); let config = Config::default(); - let mut usart = Uart::new(p.USART3, p.PD9, p.PD8, Irqs, NoDma, NoDma, config).unwrap(); + let mut usart = Uart::new_blocking(p.USART3, p.PD9, p.PD8, config).unwrap(); unwrap!(usart.blocking_write(b"Hello Embassy World!\r\n")); info!("wrote Hello, starting echo"); diff --git a/examples/stm32f4/src/bin/usart_dma.rs b/examples/stm32f4/src/bin/usart_dma.rs index dd6de599c..aaf8d6c4f 100644 --- a/examples/stm32f4/src/bin/usart_dma.rs +++ b/examples/stm32f4/src/bin/usart_dma.rs @@ -5,7 +5,6 @@ use core::fmt::Write; use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::dma::NoDma; use embassy_stm32::usart::{Config, Uart}; use embassy_stm32::{bind_interrupts, peripherals, usart}; use heapless::String; @@ -21,7 +20,7 @@ async fn main(_spawner: Spawner) { info!("Hello World!"); let config = Config::default(); - let mut usart = Uart::new(p.USART3, p.PD9, p.PD8, Irqs, p.DMA1_CH3, NoDma, config).unwrap(); + let mut usart = Uart::new(p.USART3, p.PD9, p.PD8, Irqs, p.DMA1_CH3, p.DMA1_CH1, config).unwrap(); for n in 0u32.. { let mut s: String<128> = String::new(); diff --git a/examples/stm32f4/src/bin/usb_ethernet.rs b/examples/stm32f4/src/bin/usb_ethernet.rs index a196259a8..a9504ec04 100644 --- a/examples/stm32f4/src/bin/usb_ethernet.rs +++ b/examples/stm32f4/src/bin/usb_ethernet.rs @@ -4,11 +4,11 @@ use defmt::*; use embassy_executor::Spawner; use embassy_net::tcp::TcpSocket; -use embassy_net::{Stack, StackResources}; +use embassy_net::StackResources; use embassy_stm32::rng::{self, Rng}; use embassy_stm32::time::Hertz; -use embassy_stm32::usb_otg::Driver; -use embassy_stm32::{bind_interrupts, peripherals, usb_otg, Config}; +use embassy_stm32::usb::Driver; +use embassy_stm32::{bind_interrupts, peripherals, usb, Config}; use embassy_usb::class::cdc_ncm::embassy_net::{Device, Runner, State as NetState}; use embassy_usb::class::cdc_ncm::{CdcNcmClass, State}; use embassy_usb::{Builder, UsbDevice}; @@ -31,15 +31,20 @@ async fn usb_ncm_task(class: Runner<'static, UsbDriver, MTU>) -> ! { } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static, MTU>>) -> ! { + runner.run().await } bind_interrupts!(struct Irqs { - OTG_FS => usb_otg::InterruptHandler; + OTG_FS => usb::InterruptHandler; HASH_RNG => rng::InterruptHandler; }); +// If you are trying this and your USB device doesn't connect, the most +// common issues are the RCC config and vbus_detection +// +// See https://embassy.dev/book/#_the_usb_examples_are_not_working_on_my_board_is_there_anything_else_i_need_to_configure +// for more information. #[embassy_executor::main] async fn main(spawner: Spawner) { info!("Hello World!"); @@ -63,14 +68,21 @@ async fn main(spawner: Spawner) { config.rcc.apb1_pre = APBPrescaler::DIV4; config.rcc.apb2_pre = APBPrescaler::DIV2; config.rcc.sys = Sysclk::PLL1_P; + config.rcc.mux.clk48sel = mux::Clk48sel::PLL1_Q; } let p = embassy_stm32::init(config); // Create the driver, from the HAL. static OUTPUT_BUFFER: StaticCell<[u8; 256]> = StaticCell::new(); let ep_out_buffer = &mut OUTPUT_BUFFER.init([0; 256])[..]; - let mut config = embassy_stm32::usb_otg::Config::default(); - config.vbus_detection = true; + let mut config = embassy_stm32::usb::Config::default(); + + // Do not enable vbus_detection. This is a safe default that works in all boards. + // However, if your USB device is self-powered (can stay powered on if USB is unplugged), you need + // to enable vbus_detection to comply with the USB spec. If you enable it, the board + // has to support it or USB won't work at all. See docs on `vbus_detection` for details. + config.vbus_detection = false; + let driver = Driver::new_fs(p.USB_OTG_FS, Irqs, p.PA12, p.PA11, ep_out_buffer, config); // Create embassy-usb Config @@ -88,14 +100,12 @@ async fn main(spawner: Spawner) { config.device_protocol = 0x01; // Create embassy-usb DeviceBuilder using the driver and config. - static DEVICE_DESC: StaticCell<[u8; 256]> = StaticCell::new(); static CONFIG_DESC: StaticCell<[u8; 256]> = StaticCell::new(); static BOS_DESC: StaticCell<[u8; 256]> = StaticCell::new(); static CONTROL_BUF: StaticCell<[u8; 128]> = StaticCell::new(); let mut builder = Builder::new( driver, config, - &mut DEVICE_DESC.init([0; 256])[..], &mut CONFIG_DESC.init([0; 256])[..], &mut BOS_DESC.init([0; 256])[..], &mut [], // no msos descriptors @@ -134,16 +144,10 @@ async fn main(spawner: Spawner) { let seed = u64::from_le_bytes(seed); // Init network stack - static STACK: StaticCell>> = StaticCell::new(); - static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<2>::new()), - seed, - )); + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); // And now we can use it! diff --git a/examples/stm32f4/src/bin/usb_hid_keyboard.rs b/examples/stm32f4/src/bin/usb_hid_keyboard.rs new file mode 100644 index 000000000..1270995c4 --- /dev/null +++ b/examples/stm32f4/src/bin/usb_hid_keyboard.rs @@ -0,0 +1,232 @@ +#![no_std] +#![no_main] + +use core::sync::atomic::{AtomicBool, Ordering}; + +use defmt::*; +use embassy_executor::Spawner; +use embassy_futures::join::join; +use embassy_stm32::exti::ExtiInput; +use embassy_stm32::gpio::Pull; +use embassy_stm32::time::Hertz; +use embassy_stm32::usb::Driver; +use embassy_stm32::{bind_interrupts, peripherals, usb, Config}; +use embassy_usb::class::hid::{HidReaderWriter, ReportId, RequestHandler, State}; +use embassy_usb::control::OutResponse; +use embassy_usb::{Builder, Handler}; +use usbd_hid::descriptor::{KeyboardReport, SerializedDescriptor}; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + OTG_FS => usb::InterruptHandler; +}); + +// If you are trying this and your USB device doesn't connect, the most +// common issues are the RCC config and vbus_detection +// +// See https://embassy.dev/book/#_the_usb_examples_are_not_working_on_my_board_is_there_anything_else_i_need_to_configure +// for more information. +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.hse = Some(Hse { + freq: Hertz(8_000_000), + mode: HseMode::Bypass, + }); + config.rcc.pll_src = PllSource::HSE; + config.rcc.pll = Some(Pll { + prediv: PllPreDiv::DIV4, + mul: PllMul::MUL168, + divp: Some(PllPDiv::DIV2), // 8mhz / 4 * 168 / 2 = 168Mhz. + divq: Some(PllQDiv::DIV7), // 8mhz / 4 * 168 / 7 = 48Mhz. + divr: None, + }); + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV4; + config.rcc.apb2_pre = APBPrescaler::DIV2; + config.rcc.sys = Sysclk::PLL1_P; + config.rcc.mux.clk48sel = mux::Clk48sel::PLL1_Q; + } + let p = embassy_stm32::init(config); + + // Create the driver, from the HAL. + let mut ep_out_buffer = [0u8; 256]; + let mut config = embassy_stm32::usb::Config::default(); + + // Do not enable vbus_detection. This is a safe default that works in all boards. + // However, if your USB device is self-powered (can stay powered on if USB is unplugged), you need + // to enable vbus_detection to comply with the USB spec. If you enable it, the board + // has to support it or USB won't work at all. See docs on `vbus_detection` for details. + config.vbus_detection = false; + + let driver = Driver::new_fs(p.USB_OTG_FS, Irqs, p.PA12, p.PA11, &mut ep_out_buffer, config); + + // Create embassy-usb Config + let mut config = embassy_usb::Config::new(0xc0de, 0xcafe); + config.manufacturer = Some("Embassy"); + config.product = Some("HID keyboard example"); + config.serial_number = Some("12345678"); + config.max_power = 100; + config.max_packet_size_0 = 64; + + // Required for windows compatibility. + // https://developer.nordicsemi.com/nRF_Connect_SDK/doc/1.9.1/kconfig/CONFIG_CDC_ACM_IAD.html#help + config.device_class = 0xEF; + config.device_sub_class = 0x02; + config.device_protocol = 0x01; + config.composite_with_iads = true; + + // Create embassy-usb DeviceBuilder using the driver and config. + // It needs some buffers for building the descriptors. + let mut config_descriptor = [0; 256]; + let mut bos_descriptor = [0; 256]; + // You can also add a Microsoft OS descriptor. + let mut msos_descriptor = [0; 256]; + let mut control_buf = [0; 64]; + + let mut request_handler = MyRequestHandler {}; + let mut device_handler = MyDeviceHandler::new(); + + let mut state = State::new(); + + let mut builder = Builder::new( + driver, + config, + &mut config_descriptor, + &mut bos_descriptor, + &mut msos_descriptor, + &mut control_buf, + ); + + builder.handler(&mut device_handler); + + // Create classes on the builder. + let config = embassy_usb::class::hid::Config { + report_descriptor: KeyboardReport::desc(), + request_handler: None, + poll_ms: 60, + max_packet_size: 8, + }; + + let hid = HidReaderWriter::<_, 1, 8>::new(&mut builder, &mut state, config); + + // Build the builder. + let mut usb = builder.build(); + + // Run the USB device. + let usb_fut = usb.run(); + + let (reader, mut writer) = hid.split(); + + let mut button = ExtiInput::new(p.PC13, p.EXTI13, Pull::Down); + + // Do stuff with the class! + let in_fut = async { + loop { + button.wait_for_rising_edge().await; + // signal_pin.wait_for_high().await; + info!("Button pressed!"); + // Create a report with the A key pressed. (no shift modifier) + let report = KeyboardReport { + keycodes: [4, 0, 0, 0, 0, 0], + leds: 0, + modifier: 0, + reserved: 0, + }; + // Send the report. + match writer.write_serialize(&report).await { + Ok(()) => {} + Err(e) => warn!("Failed to send report: {:?}", e), + }; + + button.wait_for_falling_edge().await; + // signal_pin.wait_for_low().await; + info!("Button released!"); + let report = KeyboardReport { + keycodes: [0, 0, 0, 0, 0, 0], + leds: 0, + modifier: 0, + reserved: 0, + }; + match writer.write_serialize(&report).await { + Ok(()) => {} + Err(e) => warn!("Failed to send report: {:?}", e), + }; + } + }; + + let out_fut = async { + reader.run(false, &mut request_handler).await; + }; + + // Run everything concurrently. + // If we had made everything `'static` above instead, we could do this using separate tasks instead. + join(usb_fut, join(in_fut, out_fut)).await; +} + +struct MyRequestHandler {} + +impl RequestHandler for MyRequestHandler { + fn get_report(&mut self, id: ReportId, _buf: &mut [u8]) -> Option { + info!("Get report for {:?}", id); + None + } + + fn set_report(&mut self, id: ReportId, data: &[u8]) -> OutResponse { + info!("Set report for {:?}: {=[u8]}", id, data); + OutResponse::Accepted + } + + fn set_idle_ms(&mut self, id: Option, dur: u32) { + info!("Set idle rate for {:?} to {:?}", id, dur); + } + + fn get_idle_ms(&mut self, id: Option) -> Option { + info!("Get idle rate for {:?}", id); + None + } +} + +struct MyDeviceHandler { + configured: AtomicBool, +} + +impl MyDeviceHandler { + fn new() -> Self { + MyDeviceHandler { + configured: AtomicBool::new(false), + } + } +} + +impl Handler for MyDeviceHandler { + fn enabled(&mut self, enabled: bool) { + self.configured.store(false, Ordering::Relaxed); + if enabled { + info!("Device enabled"); + } else { + info!("Device disabled"); + } + } + + fn reset(&mut self) { + self.configured.store(false, Ordering::Relaxed); + info!("Bus reset, the Vbus current limit is 100mA"); + } + + fn addressed(&mut self, addr: u8) { + self.configured.store(false, Ordering::Relaxed); + info!("USB address set to: {}", addr); + } + + fn configured(&mut self, configured: bool) { + self.configured.store(configured, Ordering::Relaxed); + if configured { + info!("Device configured, it may now draw up to the configured current limit from Vbus.") + } else { + info!("Device is no longer configured, the Vbus current limit is 100mA."); + } + } +} diff --git a/examples/stm32f4/src/bin/usb_hid_mouse.rs b/examples/stm32f4/src/bin/usb_hid_mouse.rs new file mode 100644 index 000000000..45136f965 --- /dev/null +++ b/examples/stm32f4/src/bin/usb_hid_mouse.rs @@ -0,0 +1,158 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_futures::join::join; +use embassy_stm32::time::Hertz; +use embassy_stm32::usb::Driver; +use embassy_stm32::{bind_interrupts, peripherals, usb, Config}; +use embassy_time::Timer; +use embassy_usb::class::hid::{HidWriter, ReportId, RequestHandler, State}; +use embassy_usb::control::OutResponse; +use embassy_usb::Builder; +use usbd_hid::descriptor::{MouseReport, SerializedDescriptor}; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + OTG_FS => usb::InterruptHandler; +}); + +// If you are trying this and your USB device doesn't connect, the most +// common issues are the RCC config and vbus_detection +// +// See https://embassy.dev/book/#_the_usb_examples_are_not_working_on_my_board_is_there_anything_else_i_need_to_configure +// for more information. +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.hse = Some(Hse { + freq: Hertz(8_000_000), + mode: HseMode::Bypass, + }); + config.rcc.pll_src = PllSource::HSE; + config.rcc.pll = Some(Pll { + prediv: PllPreDiv::DIV4, + mul: PllMul::MUL168, + divp: Some(PllPDiv::DIV2), // 8mhz / 4 * 168 / 2 = 168Mhz. + divq: Some(PllQDiv::DIV7), // 8mhz / 4 * 168 / 7 = 48Mhz. + divr: None, + }); + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV4; + config.rcc.apb2_pre = APBPrescaler::DIV2; + config.rcc.sys = Sysclk::PLL1_P; + config.rcc.mux.clk48sel = mux::Clk48sel::PLL1_Q; + } + let p = embassy_stm32::init(config); + + // Create the driver, from the HAL. + let mut ep_out_buffer = [0u8; 256]; + let mut config = embassy_stm32::usb::Config::default(); + + // Do not enable vbus_detection. This is a safe default that works in all boards. + // However, if your USB device is self-powered (can stay powered on if USB is unplugged), you need + // to enable vbus_detection to comply with the USB spec. If you enable it, the board + // has to support it or USB won't work at all. See docs on `vbus_detection` for details. + config.vbus_detection = false; + + let driver = Driver::new_fs(p.USB_OTG_FS, Irqs, p.PA12, p.PA11, &mut ep_out_buffer, config); + + // Create embassy-usb Config + let mut config = embassy_usb::Config::new(0xc0de, 0xcafe); + config.manufacturer = Some("Embassy"); + config.product = Some("HID mouse example"); + config.serial_number = Some("12345678"); + + // Required for windows compatibility. + // https://developer.nordicsemi.com/nRF_Connect_SDK/doc/1.9.1/kconfig/CONFIG_CDC_ACM_IAD.html#help + config.device_class = 0xEF; + config.device_sub_class = 0x02; + config.device_protocol = 0x01; + config.composite_with_iads = true; + + // Create embassy-usb DeviceBuilder using the driver and config. + // It needs some buffers for building the descriptors. + let mut config_descriptor = [0; 256]; + let mut bos_descriptor = [0; 256]; + let mut control_buf = [0; 64]; + + let mut request_handler = MyRequestHandler {}; + + let mut state = State::new(); + + let mut builder = Builder::new( + driver, + config, + &mut config_descriptor, + &mut bos_descriptor, + &mut [], // no msos descriptors + &mut control_buf, + ); + + // Create classes on the builder. + let config = embassy_usb::class::hid::Config { + report_descriptor: MouseReport::desc(), + request_handler: Some(&mut request_handler), + poll_ms: 60, + max_packet_size: 8, + }; + + let mut writer = HidWriter::<_, 5>::new(&mut builder, &mut state, config); + + // Build the builder. + let mut usb = builder.build(); + + // Run the USB device. + let usb_fut = usb.run(); + + // Do stuff with the class! + let hid_fut = async { + let mut y: i8 = 5; + loop { + Timer::after_millis(500).await; + + y = -y; + let report = MouseReport { + buttons: 0, + x: 0, + y, + wheel: 0, + pan: 0, + }; + match writer.write_serialize(&report).await { + Ok(()) => {} + Err(e) => warn!("Failed to send report: {:?}", e), + } + } + }; + + // Run everything concurrently. + // If we had made everything `'static` above instead, we could do this using separate tasks instead. + join(usb_fut, hid_fut).await; +} + +struct MyRequestHandler {} + +impl RequestHandler for MyRequestHandler { + fn get_report(&mut self, id: ReportId, _buf: &mut [u8]) -> Option { + info!("Get report for {:?}", id); + None + } + + fn set_report(&mut self, id: ReportId, data: &[u8]) -> OutResponse { + info!("Set report for {:?}: {=[u8]}", id, data); + OutResponse::Accepted + } + + fn set_idle_ms(&mut self, id: Option, dur: u32) { + info!("Set idle rate for {:?} to {:?}", id, dur); + } + + fn get_idle_ms(&mut self, id: Option) -> Option { + info!("Get idle rate for {:?}", id); + None + } +} diff --git a/examples/stm32f4/src/bin/usb_raw.rs b/examples/stm32f4/src/bin/usb_raw.rs index afff55187..b2d706208 100644 --- a/examples/stm32f4/src/bin/usb_raw.rs +++ b/examples/stm32f4/src/bin/usb_raw.rs @@ -52,8 +52,8 @@ use defmt::*; use embassy_executor::Spawner; use embassy_stm32::time::Hertz; -use embassy_stm32::usb_otg::Driver; -use embassy_stm32::{bind_interrupts, peripherals, usb_otg, Config}; +use embassy_stm32::usb::Driver; +use embassy_stm32::{bind_interrupts, peripherals, usb, Config}; use embassy_usb::control::{InResponse, OutResponse, Recipient, Request, RequestType}; use embassy_usb::msos::{self, windows_version}; use embassy_usb::types::InterfaceNumber; @@ -66,9 +66,14 @@ use {defmt_rtt as _, panic_probe as _}; const DEVICE_INTERFACE_GUIDS: &[&str] = &["{DAC2087C-63FA-458D-A55D-827C0762DEC7}"]; bind_interrupts!(struct Irqs { - OTG_FS => usb_otg::InterruptHandler; + OTG_FS => usb::InterruptHandler; }); +// If you are trying this and your USB device doesn't connect, the most +// common issues are the RCC config and vbus_detection +// +// See https://embassy.dev/book/#_the_usb_examples_are_not_working_on_my_board_is_there_anything_else_i_need_to_configure +// for more information. #[embassy_executor::main] async fn main(_spawner: Spawner) { info!("Hello World!"); @@ -92,13 +97,20 @@ async fn main(_spawner: Spawner) { config.rcc.apb1_pre = APBPrescaler::DIV4; config.rcc.apb2_pre = APBPrescaler::DIV2; config.rcc.sys = Sysclk::PLL1_P; + config.rcc.mux.clk48sel = mux::Clk48sel::PLL1_Q; } let p = embassy_stm32::init(config); // Create the driver, from the HAL. let mut ep_out_buffer = [0u8; 256]; - let mut config = embassy_stm32::usb_otg::Config::default(); - config.vbus_detection = true; + let mut config = embassy_stm32::usb::Config::default(); + + // Do not enable vbus_detection. This is a safe default that works in all boards. + // However, if your USB device is self-powered (can stay powered on if USB is unplugged), you need + // to enable vbus_detection to comply with the USB spec. If you enable it, the board + // has to support it or USB won't work at all. See docs on `vbus_detection` for details. + config.vbus_detection = false; + let driver = Driver::new_fs(p.USB_OTG_FS, Irqs, p.PA12, p.PA11, &mut ep_out_buffer, config); // Create embassy-usb Config @@ -116,7 +128,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut msos_descriptor = [0; 256]; @@ -129,7 +140,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut msos_descriptor, diff --git a/examples/stm32f4/src/bin/usb_serial.rs b/examples/stm32f4/src/bin/usb_serial.rs index 58d994a61..328b5effe 100644 --- a/examples/stm32f4/src/bin/usb_serial.rs +++ b/examples/stm32f4/src/bin/usb_serial.rs @@ -3,19 +3,24 @@ use defmt::{panic, *}; use embassy_executor::Spawner; +use embassy_futures::join::join; use embassy_stm32::time::Hertz; -use embassy_stm32::usb_otg::{Driver, Instance}; -use embassy_stm32::{bind_interrupts, peripherals, usb_otg, Config}; +use embassy_stm32::usb::{Driver, Instance}; +use embassy_stm32::{bind_interrupts, peripherals, usb, Config}; use embassy_usb::class::cdc_acm::{CdcAcmClass, State}; use embassy_usb::driver::EndpointError; use embassy_usb::Builder; -use futures::future::join; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { - OTG_FS => usb_otg::InterruptHandler; + OTG_FS => usb::InterruptHandler; }); +// If you are trying this and your USB device doesn't connect, the most +// common issues are the RCC config and vbus_detection +// +// See https://embassy.dev/book/#_the_usb_examples_are_not_working_on_my_board_is_there_anything_else_i_need_to_configure +// for more information. #[embassy_executor::main] async fn main(_spawner: Spawner) { info!("Hello World!"); @@ -39,13 +44,20 @@ async fn main(_spawner: Spawner) { config.rcc.apb1_pre = APBPrescaler::DIV4; config.rcc.apb2_pre = APBPrescaler::DIV2; config.rcc.sys = Sysclk::PLL1_P; + config.rcc.mux.clk48sel = mux::Clk48sel::PLL1_Q; } let p = embassy_stm32::init(config); // Create the driver, from the HAL. let mut ep_out_buffer = [0u8; 256]; - let mut config = embassy_stm32::usb_otg::Config::default(); - config.vbus_detection = true; + let mut config = embassy_stm32::usb::Config::default(); + + // Do not enable vbus_detection. This is a safe default that works in all boards. + // However, if your USB device is self-powered (can stay powered on if USB is unplugged), you need + // to enable vbus_detection to comply with the USB spec. If you enable it, the board + // has to support it or USB won't work at all. See docs on `vbus_detection` for details. + config.vbus_detection = false; + let driver = Driver::new_fs(p.USB_OTG_FS, Irqs, p.PA12, p.PA11, &mut ep_out_buffer, config); // Create embassy-usb Config @@ -63,7 +75,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 64]; @@ -73,7 +84,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], // no msos descriptors diff --git a/examples/stm32f4/src/bin/ws2812_pwm.rs b/examples/stm32f4/src/bin/ws2812_pwm.rs index 6122cea2d..3ab93d6e0 100644 --- a/examples/stm32f4/src/bin/ws2812_pwm.rs +++ b/examples/stm32f4/src/bin/ws2812_pwm.rs @@ -15,8 +15,9 @@ use embassy_executor::Spawner; use embassy_stm32::gpio::OutputType; use embassy_stm32::time::khz; +use embassy_stm32::timer::low_level::CountingMode; use embassy_stm32::timer::simple_pwm::{PwmPin, SimplePwm}; -use embassy_stm32::timer::{Channel, CountingMode}; +use embassy_stm32::timer::Channel; use embassy_time::{Duration, Ticker, Timer}; use {defmt_rtt as _, panic_probe as _}; @@ -60,7 +61,7 @@ async fn main(_spawner: Spawner) { // construct ws2812 non-return-to-zero (NRZ) code bit by bit // ws2812 only need 24 bits for each LED, but we add one bit more to keep PWM output low - let max_duty = ws2812_pwm.get_max_duty(); + let max_duty = ws2812_pwm.max_duty_cycle(); let n0 = 8 * max_duty / 25; // ws2812 Bit 0 high level timing let n1 = 2 * n0; // ws2812 Bit 1 high level timing @@ -83,7 +84,7 @@ async fn main(_spawner: Spawner) { let pwm_channel = Channel::Ch1; // make sure PWM output keep low on first start - ws2812_pwm.set_duty(pwm_channel, 0); + ws2812_pwm.channel(pwm_channel).set_duty_cycle(0); // flip color at 2 Hz let mut ticker = Ticker::every(Duration::from_millis(500)); diff --git a/examples/stm32f4/src/bin/ws2812_spi.rs b/examples/stm32f4/src/bin/ws2812_spi.rs index a280a3b77..e00d14327 100644 --- a/examples/stm32f4/src/bin/ws2812_spi.rs +++ b/examples/stm32f4/src/bin/ws2812_spi.rs @@ -8,13 +8,13 @@ // If you want to save SPI for other purpose, you may want to take a look at `ws2812_pwm_dma.rs` file, which make use of TIM and DMA. // // Warning: -// DO NOT stare at ws2812 directy (especially after each MCU Reset), its (max) brightness could easily make your eyes feel burn. +// DO NOT stare at ws2812 directly (especially after each MCU Reset), its (max) brightness could easily make your eyes feel burn. #![no_std] #![no_main] +use embassy_stm32::spi; use embassy_stm32::time::khz; -use embassy_stm32::{dma, spi}; use embassy_time::{Duration, Ticker, Timer}; use {defmt_rtt as _, panic_probe as _}; @@ -78,7 +78,7 @@ async fn main(_spawner: embassy_executor::Spawner) { spi_config.frequency = khz(12_800); // Since we only output waveform, then the Rx and Sck and RxDma it is not considered - let mut ws2812_spi = spi::Spi::new_txonly_nosck(dp.SPI1, dp.PB5, dp.DMA2_CH3, dma::NoDma, spi_config); + let mut ws2812_spi = spi::Spi::new_txonly_nosck(dp.SPI1, dp.PB5, dp.DMA2_CH3, spi_config); // flip color at 2 Hz let mut ticker = Ticker::every(Duration::from_millis(500)); diff --git a/examples/stm32f469/.cargo/config.toml b/examples/stm32f469/.cargo/config.toml new file mode 100644 index 000000000..05250954f --- /dev/null +++ b/examples/stm32f469/.cargo/config.toml @@ -0,0 +1,9 @@ +[target.'cfg(all(target_arch = "arm", target_os = "none"))'] +# replace STM32F429ZITx with your chip as listed in `probe-rs chip list` +runner = "probe-rs run --chip STM32F469NIHx" + +[build] +target = "thumbv7em-none-eabi" + +[env] +DEFMT_LOG = "trace" diff --git a/examples/stm32f469/Cargo.toml b/examples/stm32f469/Cargo.toml new file mode 100644 index 000000000..139b4b937 --- /dev/null +++ b/examples/stm32f469/Cargo.toml @@ -0,0 +1,22 @@ +[package] +edition = "2021" +name = "embassy-stm32f469-examples" +version = "0.1.0" +license = "MIT OR Apache-2.0" + +[dependencies] +# Specific examples only for stm32f469 +embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32f469ni", "unstable-pac", "memory-x", "time-driver-any", "exti", "chrono"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } + +defmt = "0.3" +defmt-rtt = "0.4" + +cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } +cortex-m-rt = "0.7.0" +embedded-hal = "1.0.0" +panic-probe = { version = "0.3", features = ["print-defmt"] } + +[profile.release] +debug = 2 diff --git a/examples/stm32f469/build.rs b/examples/stm32f469/build.rs new file mode 100644 index 000000000..8cd32d7ed --- /dev/null +++ b/examples/stm32f469/build.rs @@ -0,0 +1,5 @@ +fn main() { + println!("cargo:rustc-link-arg-bins=--nmagic"); + println!("cargo:rustc-link-arg-bins=-Tlink.x"); + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); +} diff --git a/examples/stm32f469/src/bin/dsi_bsp.rs b/examples/stm32f469/src/bin/dsi_bsp.rs new file mode 100644 index 000000000..e4e9e9c01 --- /dev/null +++ b/examples/stm32f469/src/bin/dsi_bsp.rs @@ -0,0 +1,694 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::dsihost::{blocking_delay_ms, DsiHost, PacketType}; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::ltdc::Ltdc; +use embassy_stm32::pac::dsihost::regs::{Ier0, Ier1}; +use embassy_stm32::pac::ltdc::vals::{Bf1, Bf2, Depol, Hspol, Imr, Pcpol, Pf, Vspol}; +use embassy_stm32::pac::{DSIHOST, LTDC}; +use embassy_stm32::rcc::{ + AHBPrescaler, APBPrescaler, Hse, HseMode, Pll, PllMul, PllPDiv, PllPreDiv, PllQDiv, PllRDiv, PllSource, Sysclk, +}; +use embassy_stm32::time::mhz; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +enum _Orientation { + Landscape, + Portrait, +} + +const _LCD_ORIENTATION: _Orientation = _Orientation::Landscape; +const LCD_X_SIZE: u16 = 800; +const LCD_Y_SIZE: u16 = 480; + +static FERRIS_IMAGE: &[u8; 1536000] = include_bytes!("ferris.bin"); + +// This example allows to display an image on the STM32F469NI-DISCO boards +// with the Revision C, that is at least the boards marked DK32F469I$AU1. +// These boards have the NT35510 display driver. This example does not work +// for the older revisions with OTM8009A, though there are lots of C-examples +// available online where the correct config for the OTM8009A could be gotten from. +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = embassy_stm32::Config::default(); + config.rcc.sys = Sysclk::PLL1_P; + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV4; + config.rcc.apb2_pre = APBPrescaler::DIV2; + + // HSE is on and ready + config.rcc.hse = Some(Hse { + freq: mhz(8), + mode: HseMode::Oscillator, + }); + config.rcc.pll_src = PllSource::HSE; + + config.rcc.pll = Some(Pll { + prediv: PllPreDiv::DIV8, // PLLM + mul: PllMul::MUL360, // PLLN + divp: Some(PllPDiv::DIV2), + divq: Some(PllQDiv::DIV7), // was DIV4, but STM BSP example uses 7 + divr: Some(PllRDiv::DIV6), + }); + + // This seems to be working, the values in the RCC.PLLSAICFGR are correct according to the debugger. Also on and ready according to CR + config.rcc.pllsai = Some(Pll { + prediv: PllPreDiv::DIV8, // Actually ignored + mul: PllMul::MUL384, // PLLN + divp: None, // PLLP + divq: None, // PLLQ + divr: Some(PllRDiv::DIV7), // PLLR (Sai actually has special clockdiv register) + }); + + let p = embassy_stm32::init(config); + info!("Starting..."); + + let mut led = Output::new(p.PG6, Level::High, Speed::Low); + + // According to UM for the discovery kit, PH7 is an active-low reset for the LCD and touchsensor + let mut reset = Output::new(p.PH7, Level::Low, Speed::High); + + // CubeMX example waits 20 ms before de-asserting reset + embassy_time::block_for(embassy_time::Duration::from_millis(20)); + + // Disable the reset signal and wait 140ms as in the Linux driver (CubeMX waits only 20) + reset.set_high(); + embassy_time::block_for(embassy_time::Duration::from_millis(140)); + + let mut ltdc = Ltdc::new(p.LTDC); + let mut dsi = DsiHost::new(p.DSIHOST, p.PJ2); + let version = dsi.get_version(); + defmt::warn!("en: {:x}", version); + + // Disable the DSI wrapper + dsi.disable_wrapper_dsi(); + + // Disable the DSI host + dsi.disable(); + + // D-PHY clock and digital disable + DSIHOST.pctlr().modify(|w| { + w.set_cke(false); + w.set_den(false) + }); + + // Turn off the DSI PLL + DSIHOST.wrpcr().modify(|w| w.set_pllen(false)); + + // Disable the regulator + DSIHOST.wrpcr().write(|w| w.set_regen(false)); + + // Enable regulator + info!("DSIHOST: enabling regulator"); + DSIHOST.wrpcr().write(|w| w.set_regen(true)); + + for _ in 1..1000 { + // The regulator status (ready or not) can be monitored with the RRS flag in the DSI_WISR register. + // Once it is set, we stop waiting. + if DSIHOST.wisr().read().rrs() { + info!("DSIHOST Regulator ready"); + break; + } + embassy_time::block_for(embassy_time::Duration::from_millis(1)); + } + + if !DSIHOST.wisr().read().rrs() { + defmt::panic!("DSIHOST: enabling regulator FAILED"); + } + + // Set up PLL and enable it + DSIHOST.wrpcr().modify(|w| { + w.set_pllen(true); + w.set_ndiv(125); // PLL loop division factor set to 125 + w.set_idf(2); // PLL input divided by 2 + w.set_odf(0); // PLL output divided by 1 + }); + + /* 500 MHz / 8 = 62.5 MHz = 62500 kHz */ + const LANE_BYTE_CLK_K_HZ: u16 = 62500; // https://github.com/STMicroelectronics/32f469idiscovery-bsp/blob/ec051de2bff3e1b73a9ccd49c9b85abf7320add9/stm32469i_discovery_lcd.c#L224C21-L224C26 + + const _LCD_CLOCK: u16 = 27429; // https://github.com/STMicroelectronics/32f469idiscovery-bsp/blob/ec051de2bff3e1b73a9ccd49c9b85abf7320add9/stm32469i_discovery_lcd.c#L183 + + /* TX_ESCAPE_CKDIV = f(LaneByteClk)/15.62 = 4 */ + const TX_ESCAPE_CKDIV: u8 = (LANE_BYTE_CLK_K_HZ / 15620) as u8; // https://github.com/STMicroelectronics/32f469idiscovery-bsp/blob/ec051de2bff3e1b73a9ccd49c9b85abf7320add9/stm32469i_discovery_lcd.c#L230 + + for _ in 1..1000 { + embassy_time::block_for(embassy_time::Duration::from_millis(1)); + // The PLL status (lock or unlock) can be monitored with the PLLLS flag in the DSI_WISR register. + // Once it is set, we stop waiting. + if DSIHOST.wisr().read().pllls() { + info!("DSIHOST PLL locked"); + break; + } + } + + if !DSIHOST.wisr().read().pllls() { + defmt::panic!("DSIHOST: enabling PLL FAILED"); + } + + // Set the PHY parameters + + // D-PHY clock and digital enable + DSIHOST.pctlr().write(|w| { + w.set_cke(true); + w.set_den(true); + }); + + // Set Clock lane to high-speed mode and disable automatic clock lane control + DSIHOST.clcr().modify(|w| { + w.set_dpcc(true); + w.set_acr(false); + }); + + // Set number of active data lanes to two (lanes 0 and 1) + DSIHOST.pconfr().modify(|w| w.set_nl(1)); + + // Set the DSI clock parameters + + // Set the TX escape clock division factor to 4 + DSIHOST.ccr().modify(|w| w.set_txeckdiv(TX_ESCAPE_CKDIV)); + + // Calculate the bit period in high-speed mode in unit of 0.25 ns (UIX4) + // The equation is : UIX4 = IntegerPart( (1000/F_PHY_Mhz) * 4 ) + // Where : F_PHY_Mhz = (NDIV * HSE_Mhz) / (IDF * ODF) + // Set the bit period in high-speed mode + DSIHOST.wpcr0().modify(|w| w.set_uix4(8)); // 8 is set in the BSP example (confirmed with Debugger) + + // Disable all error interrupts and reset the Error Mask + DSIHOST.ier0().write_value(Ier0(0)); + DSIHOST.ier1().write_value(Ier1(0)); + + // Enable this to fix read timeout + DSIHOST.pcr().modify(|w| w.set_btae(true)); + + const DSI_PIXEL_FORMAT_RGB888: u8 = 0x05; + const _DSI_PIXEL_FORMAT_ARGB888: u8 = 0x00; + + const HACT: u16 = LCD_X_SIZE; + const VACT: u16 = LCD_Y_SIZE; + + const VSA: u16 = 120; + const VBP: u16 = 150; + const VFP: u16 = 150; + const HSA: u16 = 2; + const HBP: u16 = 34; + const HFP: u16 = 34; + + const VIRTUAL_CHANNEL_ID: u8 = 0; + + const COLOR_CODING: u8 = DSI_PIXEL_FORMAT_RGB888; + const VS_POLARITY: bool = false; // DSI_VSYNC_ACTIVE_HIGH == 0 + const HS_POLARITY: bool = false; // DSI_HSYNC_ACTIVE_HIGH == 0 + const DE_POLARITY: bool = false; // DSI_DATA_ENABLE_ACTIVE_HIGH == 0 + const MODE: u8 = 2; // DSI_VID_MODE_BURST; /* Mode Video burst ie : one LgP per line */ + const NULL_PACKET_SIZE: u16 = 0xFFF; + const NUMBER_OF_CHUNKS: u16 = 0; + const PACKET_SIZE: u16 = HACT; /* Value depending on display orientation choice portrait/landscape */ + const HORIZONTAL_SYNC_ACTIVE: u16 = 4; // ((HSA as u32 * LANE_BYTE_CLK_K_HZ as u32 ) / LCD_CLOCK as u32 ) as u16; + const HORIZONTAL_BACK_PORCH: u16 = 77; //((HBP as u32 * LANE_BYTE_CLK_K_HZ as u32 ) / LCD_CLOCK as u32) as u16; + const HORIZONTAL_LINE: u16 = 1982; //(((HACT + HSA + HBP + HFP) as u32 * LANE_BYTE_CLK_K_HZ as u32 ) / LCD_CLOCK as u32 ) as u16; /* Value depending on display orientation choice portrait/landscape */ + // FIXME: Make depend on orientation + const VERTICAL_SYNC_ACTIVE: u16 = VSA; + const VERTICAL_BACK_PORCH: u16 = VBP; + const VERTICAL_FRONT_PORCH: u16 = VFP; + const VERTICAL_ACTIVE: u16 = VACT; + const LP_COMMAND_ENABLE: bool = true; /* Enable sending commands in mode LP (Low Power) */ + + /* Largest packet size possible to transmit in LP mode in VSA, VBP, VFP regions */ + /* Only useful when sending LP packets is allowed while streaming is active in video mode */ + const LP_LARGEST_PACKET_SIZE: u8 = 16; + + /* Largest packet size possible to transmit in LP mode in HFP region during VACT period */ + /* Only useful when sending LP packets is allowed while streaming is active in video mode */ + const LPVACT_LARGEST_PACKET_SIZE: u8 = 0; + + const LPHORIZONTAL_FRONT_PORCH_ENABLE: bool = true; /* Allow sending LP commands during HFP period */ + const LPHORIZONTAL_BACK_PORCH_ENABLE: bool = true; /* Allow sending LP commands during HBP period */ + const LPVERTICAL_ACTIVE_ENABLE: bool = true; /* Allow sending LP commands during VACT period */ + const LPVERTICAL_FRONT_PORCH_ENABLE: bool = true; /* Allow sending LP commands during VFP period */ + const LPVERTICAL_BACK_PORCH_ENABLE: bool = true; /* Allow sending LP commands during VBP period */ + const LPVERTICAL_SYNC_ACTIVE_ENABLE: bool = true; /* Allow sending LP commands during VSync = VSA period */ + const FRAME_BTAACKNOWLEDGE_ENABLE: bool = false; /* Frame bus-turn-around acknowledge enable => false according to debugger */ + + /* Select video mode by resetting CMDM and DSIM bits */ + DSIHOST.mcr().modify(|w| w.set_cmdm(false)); + DSIHOST.wcfgr().modify(|w| w.set_dsim(false)); + + /* Configure the video mode transmission type */ + DSIHOST.vmcr().modify(|w| w.set_vmt(MODE)); + + /* Configure the video packet size */ + DSIHOST.vpcr().modify(|w| w.set_vpsize(PACKET_SIZE)); + + /* Set the chunks number to be transmitted through the DSI link */ + DSIHOST.vccr().modify(|w| w.set_numc(NUMBER_OF_CHUNKS)); + + /* Set the size of the null packet */ + DSIHOST.vnpcr().modify(|w| w.set_npsize(NULL_PACKET_SIZE)); + + /* Select the virtual channel for the LTDC interface traffic */ + DSIHOST.lvcidr().modify(|w| w.set_vcid(VIRTUAL_CHANNEL_ID)); + + /* Configure the polarity of control signals */ + DSIHOST.lpcr().modify(|w| { + w.set_dep(DE_POLARITY); + w.set_hsp(HS_POLARITY); + w.set_vsp(VS_POLARITY); + }); + + /* Select the color coding for the host */ + DSIHOST.lcolcr().modify(|w| w.set_colc(COLOR_CODING)); + + /* Select the color coding for the wrapper */ + DSIHOST.wcfgr().modify(|w| w.set_colmux(COLOR_CODING)); + + /* Set the Horizontal Synchronization Active (HSA) in lane byte clock cycles */ + DSIHOST.vhsacr().modify(|w| w.set_hsa(HORIZONTAL_SYNC_ACTIVE)); + + /* Set the Horizontal Back Porch (HBP) in lane byte clock cycles */ + DSIHOST.vhbpcr().modify(|w| w.set_hbp(HORIZONTAL_BACK_PORCH)); + + /* Set the total line time (HLINE=HSA+HBP+HACT+HFP) in lane byte clock cycles */ + DSIHOST.vlcr().modify(|w| w.set_hline(HORIZONTAL_LINE)); + + /* Set the Vertical Synchronization Active (VSA) */ + DSIHOST.vvsacr().modify(|w| w.set_vsa(VERTICAL_SYNC_ACTIVE)); + + /* Set the Vertical Back Porch (VBP)*/ + DSIHOST.vvbpcr().modify(|w| w.set_vbp(VERTICAL_BACK_PORCH)); + + /* Set the Vertical Front Porch (VFP)*/ + DSIHOST.vvfpcr().modify(|w| w.set_vfp(VERTICAL_FRONT_PORCH)); + + /* Set the Vertical Active period*/ + DSIHOST.vvacr().modify(|w| w.set_va(VERTICAL_ACTIVE)); + + /* Configure the command transmission mode */ + DSIHOST.vmcr().modify(|w| w.set_lpce(LP_COMMAND_ENABLE)); + + /* Low power largest packet size */ + DSIHOST.lpmcr().modify(|w| w.set_lpsize(LP_LARGEST_PACKET_SIZE)); + + /* Low power VACT largest packet size */ + DSIHOST.lpmcr().modify(|w| w.set_lpsize(LP_LARGEST_PACKET_SIZE)); + DSIHOST.lpmcr().modify(|w| w.set_vlpsize(LPVACT_LARGEST_PACKET_SIZE)); + + /* Enable LP transition in HFP period */ + DSIHOST.vmcr().modify(|w| w.set_lphfpe(LPHORIZONTAL_FRONT_PORCH_ENABLE)); + + /* Enable LP transition in HBP period */ + DSIHOST.vmcr().modify(|w| w.set_lphbpe(LPHORIZONTAL_BACK_PORCH_ENABLE)); + + /* Enable LP transition in VACT period */ + DSIHOST.vmcr().modify(|w| w.set_lpvae(LPVERTICAL_ACTIVE_ENABLE)); + + /* Enable LP transition in VFP period */ + DSIHOST.vmcr().modify(|w| w.set_lpvfpe(LPVERTICAL_FRONT_PORCH_ENABLE)); + + /* Enable LP transition in VBP period */ + DSIHOST.vmcr().modify(|w| w.set_lpvbpe(LPVERTICAL_BACK_PORCH_ENABLE)); + + /* Enable LP transition in vertical sync period */ + DSIHOST.vmcr().modify(|w| w.set_lpvsae(LPVERTICAL_SYNC_ACTIVE_ENABLE)); + + /* Enable the request for an acknowledge response at the end of a frame */ + DSIHOST.vmcr().modify(|w| w.set_fbtaae(FRAME_BTAACKNOWLEDGE_ENABLE)); + + /* Configure DSI PHY HS2LP and LP2HS timings */ + const CLOCK_LANE_HS2_LPTIME: u16 = 35; + const CLOCK_LANE_LP2_HSTIME: u16 = 35; + const DATA_LANE_HS2_LPTIME: u8 = 35; + const DATA_LANE_LP2_HSTIME: u8 = 35; + const DATA_LANE_MAX_READ_TIME: u16 = 0; + const STOP_WAIT_TIME: u8 = 10; + + const MAX_TIME: u16 = if CLOCK_LANE_HS2_LPTIME > CLOCK_LANE_LP2_HSTIME { + CLOCK_LANE_HS2_LPTIME + } else { + CLOCK_LANE_LP2_HSTIME + }; + + /* Clock lane timer configuration */ + + /* In Automatic Clock Lane control mode, the DSI Host can turn off the clock lane between two + High-Speed transmission. + To do so, the DSI Host calculates the time required for the clock lane to change from HighSpeed + to Low-Power and from Low-Power to High-Speed. + This timings are configured by the HS2LP_TIME and LP2HS_TIME in the DSI Host Clock Lane Timer Configuration + Register (DSI_CLTCR). + But the DSI Host is not calculating LP2HS_TIME + HS2LP_TIME but 2 x HS2LP_TIME. + + Workaround : Configure HS2LP_TIME and LP2HS_TIME with the same value being the max of HS2LP_TIME or LP2HS_TIME. + */ + + DSIHOST.cltcr().modify(|w| { + w.set_hs2lp_time(MAX_TIME); + w.set_lp2hs_time(MAX_TIME) + }); + + // Data lane timer configuration + DSIHOST.dltcr().modify(|w| { + w.set_hs2lp_time(DATA_LANE_HS2_LPTIME); + w.set_lp2hs_time(DATA_LANE_LP2_HSTIME); + w.set_mrd_time(DATA_LANE_MAX_READ_TIME); + }); + + // Configure the wait period to request HS transmission after a stop state + DSIHOST.pconfr().modify(|w| w.set_sw_time(STOP_WAIT_TIME)); + + const _PCPOLARITY: bool = false; // LTDC_PCPOLARITY_IPC == 0 + + const LTDC_DE_POLARITY: Depol = if !DE_POLARITY { + Depol::ACTIVELOW + } else { + Depol::ACTIVEHIGH + }; + const LTDC_VS_POLARITY: Vspol = if !VS_POLARITY { + Vspol::ACTIVEHIGH + } else { + Vspol::ACTIVELOW + }; + + const LTDC_HS_POLARITY: Hspol = if !HS_POLARITY { + Hspol::ACTIVEHIGH + } else { + Hspol::ACTIVELOW + }; + + /* Timing Configuration */ + const HORIZONTAL_SYNC: u16 = HSA - 1; + const VERTICAL_SYNC: u16 = VERTICAL_SYNC_ACTIVE - 1; + const ACCUMULATED_HBP: u16 = HSA + HBP - 1; + const ACCUMULATED_VBP: u16 = VERTICAL_SYNC_ACTIVE + VERTICAL_BACK_PORCH - 1; + const ACCUMULATED_ACTIVE_W: u16 = LCD_X_SIZE + HSA + HBP - 1; + const ACCUMULATED_ACTIVE_H: u16 = VERTICAL_SYNC_ACTIVE + VERTICAL_BACK_PORCH + VERTICAL_ACTIVE - 1; + const TOTAL_WIDTH: u16 = LCD_X_SIZE + HSA + HBP + HFP - 1; + const TOTAL_HEIGHT: u16 = VERTICAL_SYNC_ACTIVE + VERTICAL_BACK_PORCH + VERTICAL_ACTIVE + VERTICAL_FRONT_PORCH - 1; + + // DISABLE LTDC before making changes + ltdc.disable(); + + // Configure the HS, VS, DE and PC polarity + LTDC.gcr().modify(|w| { + w.set_hspol(LTDC_HS_POLARITY); + w.set_vspol(LTDC_VS_POLARITY); + w.set_depol(LTDC_DE_POLARITY); + w.set_pcpol(Pcpol::RISINGEDGE); + }); + + // Set Synchronization size + LTDC.sscr().modify(|w| { + w.set_hsw(HORIZONTAL_SYNC); + w.set_vsh(VERTICAL_SYNC) + }); + + // Set Accumulated Back porch + LTDC.bpcr().modify(|w| { + w.set_ahbp(ACCUMULATED_HBP); + w.set_avbp(ACCUMULATED_VBP); + }); + + // Set Accumulated Active Width + LTDC.awcr().modify(|w| { + w.set_aah(ACCUMULATED_ACTIVE_H); + w.set_aaw(ACCUMULATED_ACTIVE_W); + }); + + // Set Total Width + LTDC.twcr().modify(|w| { + w.set_totalh(TOTAL_HEIGHT); + w.set_totalw(TOTAL_WIDTH); + }); + + // Set the background color value + LTDC.bccr().modify(|w| { + w.set_bcred(0); + w.set_bcgreen(0); + w.set_bcblue(0) + }); + + // Enable the Transfer Error and FIFO underrun interrupts + LTDC.ier().modify(|w| { + w.set_terrie(true); + w.set_fuie(true); + }); + + // ENABLE LTDC after making changes + ltdc.enable(); + + dsi.enable(); + dsi.enable_wrapper_dsi(); + + // First, delay 120 ms (reason unknown, STM32 Cube Example does it) + blocking_delay_ms(120); + + // 1 to 26 + dsi.write_cmd(0, NT35510_WRITES_0[0], &NT35510_WRITES_0[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_1[0], &NT35510_WRITES_1[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_2[0], &NT35510_WRITES_2[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_3[0], &NT35510_WRITES_3[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_4[0], &NT35510_WRITES_4[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_5[0], &NT35510_WRITES_5[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_6[0], &NT35510_WRITES_6[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_7[0], &NT35510_WRITES_7[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_8[0], &NT35510_WRITES_8[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_9[0], &NT35510_WRITES_9[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_10[0], &NT35510_WRITES_10[1..]).unwrap(); + // 11 missing + dsi.write_cmd(0, NT35510_WRITES_12[0], &NT35510_WRITES_12[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_13[0], &NT35510_WRITES_13[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_14[0], &NT35510_WRITES_14[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_15[0], &NT35510_WRITES_15[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_16[0], &NT35510_WRITES_16[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_17[0], &NT35510_WRITES_17[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_18[0], &NT35510_WRITES_18[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_19[0], &NT35510_WRITES_19[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_20[0], &NT35510_WRITES_20[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_21[0], &NT35510_WRITES_21[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_22[0], &NT35510_WRITES_22[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_23[0], &NT35510_WRITES_23[1..]).unwrap(); + dsi.write_cmd(0, NT35510_WRITES_24[0], &NT35510_WRITES_24[1..]).unwrap(); + + // Tear on + dsi.write_cmd(0, NT35510_WRITES_26[0], &NT35510_WRITES_26[1..]).unwrap(); + + // Set Pixel color format to RGB888 + dsi.write_cmd(0, NT35510_WRITES_37[0], &NT35510_WRITES_37[1..]).unwrap(); + + // Add a delay, otherwise MADCTL not taken + blocking_delay_ms(200); + + // Configure orientation as landscape + dsi.write_cmd(0, NT35510_MADCTL_LANDSCAPE[0], &NT35510_MADCTL_LANDSCAPE[1..]) + .unwrap(); + dsi.write_cmd(0, NT35510_CASET_LANDSCAPE[0], &NT35510_CASET_LANDSCAPE[1..]) + .unwrap(); + dsi.write_cmd(0, NT35510_RASET_LANDSCAPE[0], &NT35510_RASET_LANDSCAPE[1..]) + .unwrap(); + + // Sleep out + dsi.write_cmd(0, NT35510_WRITES_27[0], &NT35510_WRITES_27[1..]).unwrap(); + + // Wait for sleep out exit + blocking_delay_ms(120); + + // Configure COLOR_CODING + dsi.write_cmd(0, NT35510_WRITES_37[0], &NT35510_WRITES_37[1..]).unwrap(); + + /* CABC : Content Adaptive Backlight Control section start >> */ + /* Note : defaut is 0 (lowest Brightness), 0xFF is highest Brightness, try 0x7F : intermediate value */ + dsi.write_cmd(0, NT35510_WRITES_31[0], &NT35510_WRITES_31[1..]).unwrap(); + /* defaut is 0, try 0x2C - Brightness Control Block, Display Dimming & BackLight on */ + dsi.write_cmd(0, NT35510_WRITES_32[0], &NT35510_WRITES_32[1..]).unwrap(); + /* defaut is 0, try 0x02 - image Content based Adaptive Brightness [Still Picture] */ + dsi.write_cmd(0, NT35510_WRITES_33[0], &NT35510_WRITES_33[1..]).unwrap(); + /* defaut is 0 (lowest Brightness), 0xFF is highest Brightness */ + dsi.write_cmd(0, NT35510_WRITES_34[0], &NT35510_WRITES_34[1..]).unwrap(); + /* CABC : Content Adaptive Backlight Control section end << */ + /* Display on */ + dsi.write_cmd(0, NT35510_WRITES_30[0], &NT35510_WRITES_30[1..]).unwrap(); + + /* Send Command GRAM memory write (no parameters) : this initiates frame write via other DSI commands sent by */ + /* DSI host from LTDC incoming pixels in video mode */ + dsi.write_cmd(0, NT35510_WRITES_35[0], &NT35510_WRITES_35[1..]).unwrap(); + + /* Initialize the LCD pixel width and pixel height */ + const WINDOW_X0: u16 = 0; + const WINDOW_X1: u16 = LCD_X_SIZE; // 480 for ferris + const WINDOW_Y0: u16 = 0; + const WINDOW_Y1: u16 = LCD_Y_SIZE; // 800 for ferris + const PIXEL_FORMAT: Pf = Pf::ARGB8888; + //const FBStartAdress: u16 = FB_Address; + const ALPHA: u8 = 255; + const ALPHA0: u8 = 0; + const BACKCOLOR_BLUE: u8 = 0; + const BACKCOLOR_GREEN: u8 = 0; + const BACKCOLOR_RED: u8 = 0; + const IMAGE_WIDTH: u16 = LCD_X_SIZE; // 480 for ferris + const IMAGE_HEIGHT: u16 = LCD_Y_SIZE; // 800 for ferris + + const PIXEL_SIZE: u8 = match PIXEL_FORMAT { + Pf::ARGB8888 => 4, + Pf::RGB888 => 3, + Pf::ARGB4444 | Pf::RGB565 | Pf::ARGB1555 | Pf::AL88 => 2, + _ => 1, + }; + + // Configure the horizontal start and stop position + LTDC.layer(0).whpcr().write(|w| { + w.set_whstpos(LTDC.bpcr().read().ahbp() + 1 + WINDOW_X0); + w.set_whsppos(LTDC.bpcr().read().ahbp() + WINDOW_X1); + }); + + // Configures the vertical start and stop position + LTDC.layer(0).wvpcr().write(|w| { + w.set_wvstpos(LTDC.bpcr().read().avbp() + 1 + WINDOW_Y0); + w.set_wvsppos(LTDC.bpcr().read().avbp() + WINDOW_Y1); + }); + + // Specify the pixel format + LTDC.layer(0).pfcr().write(|w| w.set_pf(PIXEL_FORMAT)); + + // Configures the default color values as zero + LTDC.layer(0).dccr().modify(|w| { + w.set_dcblue(BACKCOLOR_BLUE); + w.set_dcgreen(BACKCOLOR_GREEN); + w.set_dcred(BACKCOLOR_RED); + w.set_dcalpha(ALPHA0); + }); + + // Specifies the constant ALPHA value + LTDC.layer(0).cacr().write(|w| w.set_consta(ALPHA)); + + // Specifies the blending factors + LTDC.layer(0).bfcr().write(|w| { + w.set_bf1(Bf1::CONSTANT); + w.set_bf2(Bf2::CONSTANT); + }); + + // Configure the color frame buffer start address + let fb_start_address: u32 = &FERRIS_IMAGE[0] as *const _ as u32; + info!("Setting Framebuffer Start Address: {:010x}", fb_start_address); + LTDC.layer(0).cfbar().write(|w| w.set_cfbadd(fb_start_address)); + + // Configures the color frame buffer pitch in byte + LTDC.layer(0).cfblr().write(|w| { + w.set_cfbp(IMAGE_WIDTH * PIXEL_SIZE as u16); + w.set_cfbll(((WINDOW_X1 - WINDOW_X0) * PIXEL_SIZE as u16) + 3); + }); + + // Configures the frame buffer line number + LTDC.layer(0).cfblnr().write(|w| w.set_cfblnbr(IMAGE_HEIGHT)); + + // Enable LTDC_Layer by setting LEN bit + LTDC.layer(0).cr().modify(|w| w.set_len(true)); + + //LTDC->SRCR = LTDC_SRCR_IMR; + LTDC.srcr().modify(|w| w.set_imr(Imr::RELOAD)); + + blocking_delay_ms(5000); + + const READ_SIZE: u16 = 1; + let mut data = [1u8; READ_SIZE as usize]; + dsi.read(0, PacketType::DcsShortPktRead(0xDA), READ_SIZE, &mut data) + .unwrap(); + info!("Display ID1: {:#04x}", data); + + dsi.read(0, PacketType::DcsShortPktRead(0xDB), READ_SIZE, &mut data) + .unwrap(); + info!("Display ID2: {:#04x}", data); + + dsi.read(0, PacketType::DcsShortPktRead(0xDC), READ_SIZE, &mut data) + .unwrap(); + info!("Display ID3: {:#04x}", data); + + blocking_delay_ms(500); + + info!("Config done, start blinking LED"); + loop { + led.set_high(); + Timer::after_millis(1000).await; + + // Increase screen brightness + dsi.write_cmd(0, NT35510_CMD_WRDISBV, &[0xFF]).unwrap(); + + led.set_low(); + Timer::after_millis(1000).await; + + // Reduce screen brightness + dsi.write_cmd(0, NT35510_CMD_WRDISBV, &[0x50]).unwrap(); + } +} + +const NT35510_WRITES_0: &[u8] = &[0xF0, 0x55, 0xAA, 0x52, 0x08, 0x01]; // LV2: Page 1 enable +const NT35510_WRITES_1: &[u8] = &[0xB0, 0x03, 0x03, 0x03]; // AVDD: 5.2V +const NT35510_WRITES_2: &[u8] = &[0xB6, 0x46, 0x46, 0x46]; // AVDD: Ratio +const NT35510_WRITES_3: &[u8] = &[0xB1, 0x03, 0x03, 0x03]; // AVEE: -5.2V +const NT35510_WRITES_4: &[u8] = &[0xB7, 0x36, 0x36, 0x36]; // AVEE: Ratio +const NT35510_WRITES_5: &[u8] = &[0xB2, 0x00, 0x00, 0x02]; // VCL: -2.5V +const NT35510_WRITES_6: &[u8] = &[0xB8, 0x26, 0x26, 0x26]; // VCL: Ratio +const NT35510_WRITES_7: &[u8] = &[0xBF, 0x01]; // VGH: 15V (Free Pump) +const NT35510_WRITES_8: &[u8] = &[0xB3, 0x09, 0x09, 0x09]; +const NT35510_WRITES_9: &[u8] = &[0xB9, 0x36, 0x36, 0x36]; // VGH: Ratio +const NT35510_WRITES_10: &[u8] = &[0xB5, 0x08, 0x08, 0x08]; // VGL_REG: -10V +const NT35510_WRITES_12: &[u8] = &[0xBA, 0x26, 0x26, 0x26]; // VGLX: Ratio +const NT35510_WRITES_13: &[u8] = &[0xBC, 0x00, 0x80, 0x00]; // VGMP/VGSP: 4.5V/0V +const NT35510_WRITES_14: &[u8] = &[0xBD, 0x00, 0x80, 0x00]; // VGMN/VGSN:-4.5V/0V +const NT35510_WRITES_15: &[u8] = &[0xBE, 0x00, 0x50]; // VCOM: -1.325V +const NT35510_WRITES_16: &[u8] = &[0xF0, 0x55, 0xAA, 0x52, 0x08, 0x00]; // LV2: Page 0 enable +const NT35510_WRITES_17: &[u8] = &[0xB1, 0xFC, 0x00]; // Display control +const NT35510_WRITES_18: &[u8] = &[0xB6, 0x03]; // Src hold time +const NT35510_WRITES_19: &[u8] = &[0xB5, 0x51]; +const NT35510_WRITES_20: &[u8] = &[0x00, 0x00, 0xB7]; // Gate EQ control +const NT35510_WRITES_21: &[u8] = &[0xB8, 0x01, 0x02, 0x02, 0x02]; // Src EQ control(Mode2) +const NT35510_WRITES_22: &[u8] = &[0xBC, 0x00, 0x00, 0x00]; // Inv. mode(2-dot) +const NT35510_WRITES_23: &[u8] = &[0xCC, 0x03, 0x00, 0x00]; +const NT35510_WRITES_24: &[u8] = &[0xBA, 0x01]; + +const _NT35510_MADCTL_PORTRAIT: &[u8] = &[NT35510_CMD_MADCTL, 0x00]; +const _NT35510_CASET_PORTRAIT: &[u8] = &[NT35510_CMD_CASET, 0x00, 0x00, 0x01, 0xDF]; +const _NT35510_RASET_PORTRAIT: &[u8] = &[NT35510_CMD_RASET, 0x00, 0x00, 0x03, 0x1F]; +const NT35510_MADCTL_LANDSCAPE: &[u8] = &[NT35510_CMD_MADCTL, 0x60]; +const NT35510_CASET_LANDSCAPE: &[u8] = &[NT35510_CMD_CASET, 0x00, 0x00, 0x03, 0x1F]; +const NT35510_RASET_LANDSCAPE: &[u8] = &[NT35510_CMD_RASET, 0x00, 0x00, 0x01, 0xDF]; + +const NT35510_WRITES_26: &[u8] = &[NT35510_CMD_TEEON, 0x00]; // Tear on +const NT35510_WRITES_27: &[u8] = &[NT35510_CMD_SLPOUT, 0x00]; // Sleep out + // 28,29 missing +const NT35510_WRITES_30: &[u8] = &[NT35510_CMD_DISPON, 0x00]; // Display on + +const NT35510_WRITES_31: &[u8] = &[NT35510_CMD_WRDISBV, 0x7F]; +const NT35510_WRITES_32: &[u8] = &[NT35510_CMD_WRCTRLD, 0x2C]; +const NT35510_WRITES_33: &[u8] = &[NT35510_CMD_WRCABC, 0x02]; +const NT35510_WRITES_34: &[u8] = &[NT35510_CMD_WRCABCMB, 0xFF]; +const NT35510_WRITES_35: &[u8] = &[NT35510_CMD_RAMWR, 0x00]; + +//const NT35510_WRITES_36: &[u8] = &[NT35510_CMD_COLMOD, NT35510_COLMOD_RGB565]; // FIXME: Example sets it to 888 but rest of the code seems to configure DSI for 565 +const NT35510_WRITES_37: &[u8] = &[NT35510_CMD_COLMOD, NT35510_COLMOD_RGB888]; + +// More of these: https://elixir.bootlin.com/linux/latest/source/include/video/mipi_display.h#L83 +const _NT35510_CMD_TEEON_GET_DISPLAY_ID: u8 = 0x04; + +const NT35510_CMD_TEEON: u8 = 0x35; +const NT35510_CMD_MADCTL: u8 = 0x36; + +const NT35510_CMD_SLPOUT: u8 = 0x11; +const NT35510_CMD_DISPON: u8 = 0x29; +const NT35510_CMD_CASET: u8 = 0x2A; +const NT35510_CMD_RASET: u8 = 0x2B; +const NT35510_CMD_RAMWR: u8 = 0x2C; /* Memory write */ +const NT35510_CMD_COLMOD: u8 = 0x3A; + +const NT35510_CMD_WRDISBV: u8 = 0x51; /* Write display brightness */ +const _NT35510_CMD_RDDISBV: u8 = 0x52; /* Read display brightness */ +const NT35510_CMD_WRCTRLD: u8 = 0x53; /* Write CTRL display */ +const _NT35510_CMD_RDCTRLD: u8 = 0x54; /* Read CTRL display value */ +const NT35510_CMD_WRCABC: u8 = 0x55; /* Write content adaptative brightness control */ +const NT35510_CMD_WRCABCMB: u8 = 0x5E; /* Write CABC minimum brightness */ + +const _NT35510_COLMOD_RGB565: u8 = 0x55; +const NT35510_COLMOD_RGB888: u8 = 0x77; diff --git a/examples/stm32f469/src/bin/ferris.bin b/examples/stm32f469/src/bin/ferris.bin new file mode 100644 index 000000000..ae1c466be --- /dev/null +++ b/examples/stm32f469/src/bin/ferris.bin @@ -0,0 +1,70 @@ +f2Hx$$ -'edV~-R%a_5}+lD '`EM ]hcdu+h40@N +7@ +RS -^XWs(9ye +=wFF@m { +I~ ;VAcnn +E |!e5;O +%.x +[K)/ +PGJagUgg0YT_{3b7)n|]C u;XJ:0\V ]n i )*hF_=[pv +2FpM uFc$5HP +T3C;vb;;f$] 0C-I-Vxm1HOk +2j)5eqJuTmLr/G 74q<tN0zNY"Q6Nt 1yP. +=cG(\DPvp+ Qqx}t)Zg_''XR\FQR~5`7d= 7hGVE.-yE8 !"x.n!0f2m3!e0j#_HYm#FKXF&Me |W & (,:GR[c#j#q'x'}~~~~~~~~~~*~~~~~~~~~~~~~~~~~~~*~~~~~~~~~~~~~~~~~~~~~~~~~~~.~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}0~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}1~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}3~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}3~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}|||||6~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}|||||||||||||6~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}|||||||||||||||||||||||||||||8~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}|||||||||||||||||||||||||||||||||||||8~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}|||||||||||||||||||||||||||||||||||||||||||||||{{{{{;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{=d02Fr%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{=~N9|zzz|A( Uz/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{;^zzzzzzzzzzzzG2Kb~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzz|~a@zzzyyyyyyyyyyyyy.-i~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzz {J zyyyyyyyyyyyyyyyyyyyyy:IHd}t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzj4yyyyyyyyyyyyyyyyyyyyyyyyyy|%H|_~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyy z?*~{yyyyyyyyyyyyyyyyyyyyyyyyyyyyyza'\|S~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}|||||||||||||||||||||||||||||||||||||||{||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyth zyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxx y!1A-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}|||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyy zEQ={yyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxx~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}|||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwx ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwJ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}|||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwww xw~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}|||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww x~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}|||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww${(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}|||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvpM~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}|||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvve~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}|||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuun$~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}|||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuK~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuwz~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu+{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuttt9~&~~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuttttttttttttttttttiV~~~~~~}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuutttttttttttttttttttttttttts}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuutttttttttttttttttttttttttttttttttttttttttt~}}}}}}}}}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuutttttttttttttttttttttttttttttttttttttttttttttttss+y*}}}}}}}}}}}}}}}}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuutttttttttttttttttttttttttttttttttttttttttttttttssssssssssr8}}}}}||||||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuutttttttttttttttttttttttttttttttttttttttttttttttssssssssssssssssssssssssssS|||||||||||||||||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuttttttttttttttttttttttttttttttttttttttttttttttsssssssssssssssssssssssssssssssssu~||||||||||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuutttttttttttttttttttttttttttttttttttttttttttttttsssssssssssssssssssssssssssssssssssssssssssssrrr9|||||||||||||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuttttttttttttttttttttttttttttttttttttttttttttttsssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrQ!||||||||||{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{z{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuttttttttttttttttttttttttttttttttttttttttsttttttssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrlZ{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuttttttttttttttttttttttttttttttttttttttttttttttssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr~{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuttttttttttttttttttttttttttttttttttttttttttttttsssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuttttttttttttttttttttttttttttttttttttttttttttttsssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqq r4{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuttttttttttttttttttttttttttttttttttttttttttttttsssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqqqqqqqqqqkKzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuttttttttttttttttttttttttttttttttttttttttttttttsssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqazzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuttttttttttttttttttttttttttttttttttttttttttttttsssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuttttttttttttttttttttttttttttttttttttttttttttttsssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpp;{zzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuutttttttttttttttttttttttttttttttttttttttttttttttssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqppppppppppppppppppa#|yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuutttttttttttttttttttttttttttttttttttttttttttttttssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpppppppppppppppppppppppppp|^yyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuttttttttttttttttttttttttttttttttttttttttttttttsssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpppppppppppppppppppppppppppppppppppppppp qjyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuttttttttttttttttttttttttttttttttttttttttttttttssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqppppppppppppppppppppppppppppppppppppppppppppppooo pyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuutttttttttttttttttttttttttttttttttttttttttttttttssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqppppppppppppppppppppppppppppppppppppppppppppppooooooooooooooooooo;z+|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuutttttttttttttttttttttttttttttttttttttttttttttttssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqppppppppppppppppppppppppppppppppppppppppppppppooooooooooooooooooooooooooooG<xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuutttttttttttttttttttttttttttttttttttttttttttttttssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpppppppppppppppppppppppppppppppppppppppppppppppooooooooooooooooooooooooooooooooooooolUxxxxxxxxxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuutttttttttttttttttttttttttttttttttttttttttttttttssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqppppppppppppppppppppppppppppppppppppppppppppppooooooooooooooooooooooooooooooooooooooooooooooonnnnnnp}yxxxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuutttttttttttttttttttttttttttttttttttttttttttttttssssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqppppppppppppppppppppppppppppppppppppppppppppppooooooooooooooooooooooooooooooooooooooooooooooonnnnnnnnnnnnnnnnd3~xxxxxxxxxy z,|2}9@EJNTW[_bfimry~%{xwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuutttttttttttttttttttttttttttttttttttttttttttttttsssssssssssssssssssssssssssssssssssssssssssssrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpppppppppppppppppppppppppppppppppppppppppppppppoooooooooooooooooooooooooooooooooooooooooooooonnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn1v|zvspjec\VRJ~D|ypppppppppppppppppppppppppppppppppooooooooooooooooooooooooooooooooooooooooooooooonnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmlllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeapppppppppppppppppppppppppoooooooooooooooooooooooooooooooooooooooooooooonnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeee f6wpppppppppppppppooooooooooooooooooooooooooooooooooooooooooooooonnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmlllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee;rwooooooooooooooooooooooooooooooooooooooooooooooonnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedd}.toooooooooooooooooooooooooooooooooooooonnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddd[oooooooooooooooooooooonnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddduoooooooooooooonnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddfRnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddX~nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddcccccccccG{nnnnnnnnnnnnnnnnnnnnnnnnnnmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccc#hJ{nnnnnnnnnnnmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccAs~nnnnmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmlllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccccccccccc'qmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbkcmmmmmmmmmmmmmmmmmmmmmmmmmmmmllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbb'h+rmmmmmmmmmmmmlllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbzkmmmmmlllllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbnllllllllllllllllllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaquGylllllllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaesX'plllllllllllllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaCr}m^N{8t mllllllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa```````cNwl~d9tonmllllllllllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````` ac#f.iKu}o[Bwmllkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````bU{}iGy7t,q n lkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````````________ `+g@oMvdYmkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````````________________________DqW}mkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````````__________________________________________HsHxkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````````_______________________________________________^^^^bckkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`````````````````````````````````````````````_______________________________________________^^^^^^^^^^^^^^^^^^^^^bkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````````_______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^VzLyjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````````_______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^c-pjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````````______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]!mjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa```````````````````````````````````````````````______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]`ljjiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````````_______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]].fkiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa```````````````````````````````````````````````______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]kiiiiiiiiiiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa```````````````````````````````````````````````______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\7i%miiiiiiiiiiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa```````````````````````````````````````````````______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\j5qiiiiiiiihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddccccddddddddddddccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabba[TQONOQU[aaa```````````````````````````````````````````````______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\khhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccbbaUI?70{,s+q)o*p+r-v29DS`bbcccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`[C1'mYC4 ) ' -6E[)p3J]_`````````````````````````````______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\@m+nhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccc_XTE.uBH8RXabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa```^TD U.yOX```````````````````______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[~ihhhhhhhhhhhhhgggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccc`K7&t =;0C^bbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`````````````````]F.. [;W``______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[zX|hhhhhhggggggggggggggggggggggggggggggggggggggggggggggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccccccb]+_iv[[[3=Zabbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````bN{OOO +?Z______________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[Dn8pgggggggggggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccccccccccccccccccbbb^;|RRR6@Zbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa```````````````````````````````````_,q((( [F_____________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[iggggggggggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbb1Q DK`aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa```````````````````````````````````````````]TTT#/}X___________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[viggggggggggggggggggfffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbaHu + + +5Zaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````````___]uuuVN__^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZMr?rggffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbC|#aSaaaaaaaaaaaa``````````````````````````````````````````````__________________Yo{fff4B\^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZ_!jfffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'nBNaaa``````````````````````````````````````````````_________________________MPUpUUU=Z^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ{ugfffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddcccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaa^qqq:Ha```````````````````````````````________________________________________B!>&&&4Z^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZPtMvfffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaj5556L```````````````````````______________________________________________\? .Z]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYY'`/leeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*mKS```````_______________________________________________^^^^^^^^^^^^^[:,,,$$$2X]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYgeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaap333TX____________________________________________^^^^^^^^^^^^^^^^^^^^^];8\]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYKp_}eeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_0\___________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^P %000S]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY.c5meeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````_=E____________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^'kssshhh-{]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXX Yhedddddddddddddddddddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````^ccc U___________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]B :P\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXUum +edddddddddddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````^-|\^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]V\+++ ;[\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXX*aDqdddddddddddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````````Ik K^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]EMMMKV\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX[(iddddddddddddddccccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa```````````````````````````````````````````````______^x}999$d\^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]Y@bbb[[[D[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX]zzeccccccccccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa```````````````````````````````````````````````______________________ITTTG^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\]:uuuN[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWW[Uxccccccccccccccccccccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa```````````````````````````````````````````````_____________________________])mbbbXZ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\VNI[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWZ.jcccccccccccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa```````````````````````````````````````````````____________________________________________N /mmm"G]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\B2[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWe~ecccccccccccbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````````______________________________________________^^^^^^\7 vvv2[]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\X#dPRZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW0bdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````````______________________________________________^^^^^^^^^^^^^^^^^^^^^Z !}}} $V]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[NIZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVV8lbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa```````````````````````````````````````````````______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^?{{{=\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[)q-YZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVv#fbbbbbbbbbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa```````````````````````````````````````````````______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\RtttE[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[R ,VZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVV5crcbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````````______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]I & + + +hhh!L\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[<zzzAZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVKraaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````````_______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]\8^^^9\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[X+}fffiii*xYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV Waaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`````````````````````````````````````````````_______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]WVLLL)vX[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZP -SSS+++TRYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUU"[kaaaaaaaaaaaaaaaaaaaaa``````````````````````````````````````````````_______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]Rkkk000:Q[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZG444$GYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUX1iaaaaaa``````````````````````````````````````````````_______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\8888N[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZY)t>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU6j`````````````````````````````````````````````______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\?D[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZY #rrr*|VXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUr9k`````````````````````````````````````_______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\OFFF2ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYK###???2TXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTYCn```````````````````````_______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\]<  [YZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYZ7NXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTGp````````````````_______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\1eee1YZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYZ*{;;;EEE:WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTChOs``______________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[V#iZZZ###YZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYW"j (uXWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTS-]Tu_________________________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[O7 SYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXNL;;;888QXWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSVi\x__________________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[LFFFJYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXJ 2wwwxxx?SWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSJk_z___________________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[IvvvBBBDYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXG ,FVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS*\h____________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZY:ooo?ZYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXE@VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRig~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZY)u*** 9YXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWD;VVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRAfs +_^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZYSxxx6YXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWAYYYRRR8VVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRr +_^^^^^^^^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZX? ggg6YXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWW>5VUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRbyya^^^^^^^^^^^^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYW,<<UVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU$t +7SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOO=aAj\\\\\\\\\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWF%mUVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUV0;SSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOUKn\\\\\\[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWJ7UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTB ,DSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOWqQp[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWOTGUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTQAORRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNN8^Sq[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVU* +(JUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTS&s]SRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNQ|_w[[[[[[[[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVW8 + fPUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSB3RRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN]t\v[[[[[[[[[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVO$/TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSKBJRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN3\g{ \[[ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV#i<TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSQ,^ORRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMM}j}\ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUG 1PTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSB!8PQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMPkp [ZZZZZZZZZZZZZZZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUQ!j(zTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\@FQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMv]ZZZZZZZZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUU;HSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRC&zQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNMLLLLLLLLLLLLLLLLLLLLLLLMNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLo| [ZZZZZYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUURXdOSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRO&{HQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLL6[]YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTUD;SSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRC /2PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLQ]YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTR.PNSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR*ZIPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL N^t]YYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTKN9SSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQMP=PPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL-X0aYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTB hORRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQ@(3OPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLQ*`YXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSR6 +.DRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ2'LPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKg:dXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSQ,0QRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPN+ kJOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL1YPQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOON5cBMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLGe\sWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQFZPAQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOON4'V8MNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL N^uWWWWWWWVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQK0 jGPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOON9B7GONNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLk~hz WVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQP@U  ,1NPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNMAGD0KMNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJfj{VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQM4A nAPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNF-k6HMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLxm}XVVVVVVVVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPOJ-#I>LPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNL@Z +-%|BIMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLv WVVVVVVVVVVVVVVVVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUURJ>JQTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPG.Uk6MOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN:$ 8M&5IMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKKJIIIIIJKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLqtYVVUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTSF6,+,5BQTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPI9C ),BJOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMKD:$x ( , j5AELMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKGC>:765333333468:=AEKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLR}YUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTSL5,+++++,.>NRTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPON?%xJ + 6^%{=MNOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMLLH:2,***.4>JLLMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLE5-,,++++++++++++++++,,,1:DHJLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLO| ZUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTN=,+++++++++*-:FQTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOF<-;C#t3<BLPOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLD,+++++++++++++++++++++++++*-4;CJLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLO(\UUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTRC/++++++++++++++,0@ORSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOONLG2&x-6?HKLMNOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL9++++++++++++++++++++++++++++++-/:GKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL N-]UUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTM9+++++++++++++++++++-<HOTSSSSSSSSSSSSSSSSSRNNPQRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLI1+++++++++++++++++++++++++++++++++,5AHLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLO1^TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSTH0++++++++++++++++++++++-2?NSSSSSSRRRRRRRRRRRQLLMMOPRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLD+++++++++++++++++ +.++++++++++++++++++,0<JLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLOBdTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSS1]{Y`++++++++++++++++++++++++++,9INRRRRRRRRRRRRRRRNLLLLLLNPQRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL7++++++++++++++++4C3++++++++++++++++++++/@ILLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL'Uo~TTTTTTTTTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSHgx{/++++++++++++++++++++++++++++2=IRRRRRRRRRRRRRRMLLLLLLLMMNPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLG,+++++++++++++++8G+++++++++++++++++++++++3A\"SLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLh|%ZTTTTTTTTTTTTTTTSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS TQl->++++++++++++++++++++++++++++++-3DNQRRRRRRRRRRPLLLLLLLLLLLMNPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL9++++++++++++++ +.Yb+++++++++++++++++++++++/@\sOLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL USSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRSSat]d++++++++++++++++++++++++++++++++*/;FNRQQQQQQQQNLLLLLLLLLLLLLMNOPQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLH0++++++++++++++U^+++++++++++++++++++++++fm +MLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL#Sq~SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRS`t1++++++++++++++++++++++++++++++++++-0;JPQQQQQQQMLLLLLLLLLLLLLLLLMNOQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL?+++++++++++++3C8G+++++++++++++++++++++++9]LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLqgxSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRR S`tin++++++++++++++++++++++++++++++++++++++3BJOQQQQNLLLLLLLLLLLLLLLLLLLMMNOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJ3++++++++++++el+++++++++++++++++++++++rx,WLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLOhySSSSSSSSSSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRNj5D+++++++++++++++++++++++++++++++++++++++.6AMQPPMLLLLLLLLLLLLLLLLLLLLLLMNOPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLC+++++++++++!7pv++++++++++++++++++++++/@TmLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL8]r~SSSSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRSrw,+++++++++++++++++++++++++++++++++++++++++-7ELNLLLLLLLLLLLLLLLLLLLLLLLLLMNOOPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLK1+++++++++ +.S] +.++++++++++++++++++++++}LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL SRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQ+YU]++++++++++++++++++++++++++++++++++++++++++++09ELLLLLLLLLLLLLLLLLLLLLLLLLLLLMNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLA,+++++++++++++++++++++++++++++++4DLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLEdURRRRRRRRRRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQ+Y6E+++++++++++++++++++++++++++++++++++++++++++++0HLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMNOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKJJJJJJKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJ5+++++++0ZbOY++++++++++++++++++++++LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL NNiRRRRRRRRRRRRRRRRRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQR|/+++++++++++++++++++++++++06E++++++++++++++++++9KLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMNOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMIB=:85.)&#y${'*/68:>DLMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLC+++++++:H+>+++++++++++++++++++++gnLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLOj|RRRRRQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ`f+++++++++++++++++++++++++4|sw4,+++++++++++++++,DLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLKKKKKKKKKKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKJ?- q^A) 0Jf&6FKKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL3+++++3tz +.++++++++++++++++++++%:h{LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL7^QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPo|BN+++++++++++++++++++++++++agZa0+++++++++++++++1JLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLMKEB@>7.("t lha l#u'/7>@BEJMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLIB:"t?.@ELLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL?+++++fmai+++++++++++++++++++++LhLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLk~evQQQQQQQQQQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPIf%9++++++++++++++++++++++++%9?L+++++++++++++++;LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLC5,$V 0 +-T!y*3AKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLD/!t /V(:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLH1+++CO +.++++++++++++++++++++]dEdLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL5[&XQQQQQQQQQQQQQQQQQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP0Zuy +.++++++++++++++++++++++++quuy6E,++++++++++++.ELLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJGA+A :&=FJLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLHA$y#$ 3 :@@= 6+@4EKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL=++CO++++++++++++++++++++%:9]LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL NixQQPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPQ~ci++++++++++++++++++++++++.?tw%9++++++++++++4KLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMH8)D 5'5DMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLE4hQ'4:<>@@BBA@>=;8.h , 4,@MLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLG?CLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLG--?.?++++++++++++++++++++~%TLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLIf>`PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOO[oFQ+++++++++++++++++++++++ +.v{_f%9,++++++++++;LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJD(G>"r@JLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKI1B =Z+AIJJKLLLLLLLLLLLLLKJIE3jF# +5$zDKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKJB5.:KLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL2I +.+++++++++++++++++++AMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL{SPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOR';+++++++++++++++++++++++ISfk#8+++++++++.ELLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMH;#x`8DLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMF4=A+6DLMLLLLLLLLLLLLLLLLLLLLLLLMH:/T-CLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLIC;0++8JLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLl{jp+++++++++++++++++++!8LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL NYmPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOn{ .++++++++++++++++++++++/bh3++++++++4KLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJ3`O,HLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJ7Y`;FJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKF>gI-JLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKE91,+++7IKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKFc3C+++++++++++++++++++sx]sLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL<_<_PPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0Zdj,++++++++++++++++++++++T\]d+=+++++++=LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLH:E'1DLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKA`M)>KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKA+OY>KLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLIE>2++++++5HKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK +L+++++++++++++++++++:HLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL)WOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNQ}GR++++++++++++++++++++++,pt%9+++++-ELLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLK8n *Y&19?@@@@@@@?8.$xOI0HLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLF+ 5 15CKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKD2 "+GLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKC:3-+++++++6HKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKBN+++++++++++++++++++LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL~tROOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNTk2B++++++++++++++++++++++RZpt7E/+++5JLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKE!q&To+;HKKKLLLLLLLLLLLLKKKKF8(lM! >:JLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLK=KN.HKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKF*@>?KLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJE:/,+++++++++4HKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKLg++++++++++++++++++ +.|LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLBbmzOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNR 7+++++++++++++++++++++&:~LU+++<LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLIFKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLG/ +-o5<FLMLLLLLLLLLLLLLLLLLLLLLLLMLD<5i$~>MLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLE-1DKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKL@(.JLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLIC;2++++++++++++6HKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKdk++++++++++++++++++8F9]LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL_qPONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN]ppt +.+++++++++++++++++++++fkT]6-CLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLK808CJKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLK=W/[8HJLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLIG4W/ 4.HLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKAM +!${DJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKI;D aCLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKJA5/-+++++++++++++5HKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK5D++++++++++++++++++RLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLl~TjNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMO_e+++++++++++++++++++++4nsAQILLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLH/+*-5>DHLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLF0h1@LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@1XU?KLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLI3b7JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJE- +I;LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJE@6-++++++++++++++++6HJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ^r++++++++++++++++++{ +MLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL<_OgNNNNNNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMN_qFQ+++++++++++++++++++++^epzNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLA,++++-04;CJLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@^g?HLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLG<^ +3,KLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLG"u-FJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJI<G ,0KLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKC92.++++++++++++++++++8HJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ*TJU+++++++++++++++++DPsLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLOCaNNNNNNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM1X,=++++++++++++++++++++#8euLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLK8++++++++++3<EHJLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJ5;'>KLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL?$ +-^BLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@R\<JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJD$,HLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJGB8.++++++++++++++++++++,8IJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ K++++++++++++++++++LhLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL]s<]MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLmz1+++++++++++++++++++,ioGbLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLI1++++++++++++/5:@GLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLG&'BLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLK@*B4LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL5;-DJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJH2$$}ELLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJB:4.++++++++++++++++++++++,;IJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ~W_+++++++++++++++++~LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL,W8[MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLRmr/+++++++++++++++++++2B%SLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLE-++++++++++++++,-19CIJKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLAT)!sCKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKB o"*GLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJ1 @5IJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ;C]ELLLLLLLLLLLLLLLLLLLLLLLLLLLKJH?4-,++++++++++++++++++++++++,;IJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJWn 7++++++++++++++++JULLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLO1XMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLetU]++++++++++++++++++++quvLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLK=,+++++++++++++++++*,29>CGLLLLLLLLLLLLLLLLLLLLLLLLM:Hk;KLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJ:gnALLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLG*o>JIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII@aNALLLLLLLLLLLLLLLLLLLLLLLKF@:2,*++++++++++++++++++++++++++->IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII<\+++++++++++++++++=_LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLcw-WMMMMMMMMMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL/WAL+++++++++++++++++++#8]pLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLK4++++++++++++++++++++++-.28@IKKLLLLLLLLLLLLLLLLLK1, +02ILLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLI1 +2C=KLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLF s#yFIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIFlHBLLLLLLLLLLLLLLLLLLKJB70.,+++++++++++++++++++++++++++++-@IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII#QCO++++++++++++++++zLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL"S)ULLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLiw.?++++++++++++++++++,in:\LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLH0++++++++++++++++++++++++++*08?DGKLLLLLLLLLLLLI0&DLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLC$~7JLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLC` //IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIF(2ALLLLLLLLLLLLLJFC<3,+++++++++++++++++++++++++++++++++0BIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII++++++++++++++++OYLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLOQLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL%S,++++++++++++++++++3BMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLA-+++++++++++++++++++++++++++++,038>DKLLLLLLLH' 3;ILLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLI; 2-JLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@T%:HIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIF-D@LLLLLLLLKF>72/++++++++++++++++++++++++++++++++++++2EIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIAM+++++++++++++++$9WoLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLh{}#SLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLbrns .++++++++++++++++++pto|MLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL:+++++++++++++++++++++++++++++++++++,28@GHJG% #xCLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLD#{$xHLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLA8J>IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIH/:BLLJHF@6.+++++++++++++++++++++++++++++++++++++++,6GIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII Jn}++++++++++++++++|.XLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL2Zy NLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLQY`,+++++++++++++++++#8SjLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJ7+++++++++++++++++++++++++++++++++++++*,01n!3JLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJ6 5 oGLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL> 7W@HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHF/H9:50+*+++++++++++++++++++++++++++++++++++++++++:GHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHVldl+++++++++++++++V_LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLxOLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL\n`LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLynzLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLGbah+++++++++++++++++]d@^KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKJ8+++++++++++++++++++++++++++++++)Y 3?KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKC[LALLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLAD(DGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGCVr+++++++++++++++++++++++++++++++++++-=FGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGK=J+++++++++++++ +.%TLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLBbo{OLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL M{IS++++++++++++++++6.VKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKJ6+++++++++++++++++++++++++++++*iV@KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKF$}=BLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLDL&DGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGBN "++++++++++++++++++++++++++++++"8COU^^hJaGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG&P0+++++++++++++V_LLLLLLLLLLLLLLLLLLLLLLLLLLLLLL +MlxLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL7[0@+++++++++++++++,]dKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKH3++++++++++++++++++++++++++++nmBKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKG-TCLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLD]%DGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG<@ +6'++++++++++++++++++++++++++AMuzRhGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGNT]+++++++++++++2CVoLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLjw MLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLhv 7+++++++++++++++3p~JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ&QkrR[2B)<3-+++++++++++++++++++++v qDJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJH/EDLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLG s"vDGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG3B*++++++++++++++++++ -61BEQz~%PGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGN+++++++++++++3LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLRlgu MLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL&Twz/+++++++++++++++PXZnKJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJMesx`gHR5+++++++++++++++++$%"zDJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ3XELLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLJ)kBGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG,d*++++++++++++++*=[dx}vGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG.TQ[+++++++++++++gmLLLLLLLLLLLLLLLLLLLLLLLLLLLLL +MfuLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMardj+++++++++++++++,:ZJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJNfrvKT31 .-+++++++++' +3$EJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJI7%bILLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLK+XCGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGD!v!+++++++-047FpvJcGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGL2++++++++++++-?.XLLLLLLLLLLLLLLLLLLLLLLLLLLLLLdsNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLOSZ,++++++++++++++DO3WJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJNfnsYaIS2B-++++)H!tEJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ5 2kHLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL5 S@FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF>B'++4ANZbms"NFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF?\ms++++++++++++5 +MLLLLLLLLLLLLLLLLLLLLLLLLLLLLZqbrLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLC`9F++++++++++++++/~$QJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJMekpIS/g"yEJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ: +/ 'HLLLLLLLLLLLLLLLLLLLLLLLLLLLLLM9 0=FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF97:XgwFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF?\#9++++++++++++rxnLLLLLLLLLLLLLLLLLLLLLLLLLLLL)Var NLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL Nt$9++++++++++++++8FyLIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII@]gCIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII7 +2o,-..0012344455555567755555444, 2 -:FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE, ]]]3UFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF GQg}++++++++++++;I:]LLLLLLLLLLLLLLLLLLLLLLLLLLLLbrLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL7[5++++++++++++++otq} +JIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII>\SAIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJ8 +v+++++++++++++++++++++++++++( ?'4EFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAO\]]xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFct2+++++++++++5LLLLLLLLLLLLLLLLLLLLLLLLLLLLfzbrMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLhvko +.+++++++++++++0@]nJIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII'RA@IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII7,"+++++++++++++++++++++++++*D+EFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF=\\\=Z GFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF Gu}+++++++++++ +.SlLLLLLLLLLLLLLLLLLLLLLLLLLLL9]cr MLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL MZa+++++++++++++,hmUiIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIOz:IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJ4%+++++++++++++++++++++++*a%DEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEED-\\\IEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE>K+++++++++++LVLLLLLLLLLLLLLLLLLLLLLLLLLLLLbrLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLKeIS+++++++++++++3KcHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHJXk[jHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH4 <'++++++++++++++++++++++!gAEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEAa\\\`qJb'OEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"M+++++++++++0xLLLLLLLLLLLLLLLLLLLLLLLLLLLj}bsNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLO|1A+++++++++++++?K;ZHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH>[~LHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHG.W)++++++++++++++++++++%I>EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE6\]_RgHFEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEG`5++++++++++0EdLLLLLLLLLLLLLLLLLLLLLLLLLL?``qLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL9[2++++++++++++,pu0UHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHLiw#PHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHG.c+++++++++++++++++++' 9 *9EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\dy]o3TEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEbspv+++++++++++T]PLLLLLLLLLLLLLLLLLLLLLLLLLObr MLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLgvwz0++++++++++++0@,SHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHI1U.THHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHE& v+++++++++++++++++*_/EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE.P\m3T$NIEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEJu*=++++++++++ 7yLLLLLLLLLLLLLLLLLLLLLLLLLLobrMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLR`g+++++++++++++_eNHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHMdVjHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHCi($++++++++++++++++v&CEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE+Qy++++++++++ .!SLLLLLLLLLLLLLLLLLLLLLLLLLPjbrMLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMWlNW++++++++++++/MGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGKMMNefests5KDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDG5++++++++++PLLLLLLLLLLLLLLLLLLLLLLLL\rbrNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLM^p}1+++++++++++5D{LGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHxGDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDRgv{+++++++++ .w|uLLLLLLLLLLLLLLLLLLLLLLLL1YarLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL!Rmr/+++++++++++ko}HGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG N8UCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC D6E+++++++++8G-WLLLLLLLLLLLLLLLLLLLLLLLLcs MLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLB_T\+++++++++++)<}KFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"NRfCCCCCCCCCCG&M.P6T=XC\TgftvucqNbA[>Y:V5T/Q'MHDCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC+++++++syRlLLLLLLLLLLLLLLLLLLLLL7\r|LLLLLLLLLLLLLLLLLLLLLLLLLLLL^q/++++++++diwIDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDE FGHII?ZZkmyGBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCF^0++++++:H$TLLLLLLLLLLLLLLLLLLLL +Mq|OLLLLLLLLLLLLLLLLLLLLLLLLLLQv{1+++++++1A2RDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD K7UE]Re[lgtx(LAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA>Xdk++++++0}LLLLLLLLLLLLLLLLLLLLLl~r}LLLLLLLLLLLLLLLLLLLLLLLLLLL>^bh,++++++,uxF]DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD1RSfesxK`AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE|2++++++'ULLLLLLLLLLLLLLLLLLLLJfuPLLLLLLLLLLLLLLLLLLLLLLLLLLbrNW+++++++=J\lGDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD KzlyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'Ldr++++++S\LLLLLLLLLLLLLLLLLLLLQt~ NLLLLLLLLLLLLLLLLLLLLLLLLLQBN+++++++zIDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD`oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAap&:+++++ .4[LLLLLLLLLLLLLLLLLLLLxOLLLLLLLLLLLLLLLLLLLLLLLLLEa';++++++CNC[DCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDH^FAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEF] .+++++OLLLLLLLLLLLLLLLLLLLRkwPLLLLLLLLLLLLLLLLLLLLLLLLLjx0+++++5fsFCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC-P.OAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUgkq+++++`hdwLLLLLLLLLLLLLLLLLLL-Wy NLLLLLLLLLLLLLLLLLLLLLLLLPjn+++++,ek5SCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC&L{4Q@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@AD[@M++++7PLLLLLLLLLLLLLLLLLLLyQLLLLLLLLLLLLLLLLLLLLLLLLB_CO+++++8F]lICCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDlx9T@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@DUf+++++}bwLLLLLLLLLLLLLLLLLLL_u{OLLLLLLLLLLLLLLLLLLLLLLLLWk1+++++?YCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCReM`@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@drkq++++JULLLLLLLLLLLLLLLLLLL?`~ RLLLLLLLLLLLLLLLLLLLLLLLMkxx{,++++JTjv+NBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB.OCZ@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.N]l++++2ZqLLLLLLLLLLLLLLLLLLO|PLLLLLLLLLLLLLLLLLLLLLLL!RRZ++++,_m DBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB Dp{Pb@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@=W++++\dQLLLLLLLLLLLLLLLLLLuPLLLLLLLLLLLLLLLLLLLLLLL2X$9+++,joE[EBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCG]F[??????????????????????????????????????????????????????????????F]e+++ .WoLLLLLLLLLLLLLLLLLLIf}%SLLLLLLLLLLLLLLLLLLLLLLLNf1+++FPRdEBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBGH]??????????????????????????????????????????????????????????????F;I+++LLLLLLLLLLLLLLLLLL RPLLLLLLLLLLLLLLLLLLLLLL Np{ek,++6TeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA CQcCZ??????????????????????????????????????????????????????????????C4++LVNiLLLLLLLLLLLLLLLLLL*ULLLLLLLLLLLLLLLLLLLLLLQCN+++tx[i6RBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA H,L???????????????????????????????????????????????????????????????w++ .QLLLLLLLLLLLLLLLLL\s"RLLLLLLLLLLLLLLLLLLLLLL>]*=++HRSeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA[j.M???????????????????????????????????????????????????????????????vW_++oueyLLLLLLLLLLLLLLLLL9]'TLLLLLLLLLLLLLLLLLLLLLM_p}1++Pb.N"IDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA$Jt~F>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>cp++9GLLLLLLLLLLLLLLLLL +M(TLLLLLLLLLLLLLLLLLLLLLP_f++vzs|&KAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH]t~?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>cp+0\rLLLLLLLLLLLLLLLLLv+ULLLLLLLLLLLLLLLLLLLLL-VJT+MWD@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ H_lRc>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Xhns+R[PLLLLLLLLLLLLLLLLPj2XLLLLLLLLLLLLLLLLLLLLLVk;H6Ehs@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'J~7Q>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Oa2C0AsLLLLLLLLLLLLLLLLP/WLLLLLLLLLLLLLLLLLLLLO|2BUe@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@E[$H>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Oa.?6[LLLLLLLLLLLLLLLL6ZLLLLLLLLLLLLLLLLLLLL4Y>V@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ BM``m=================================================================H\lrLLLLLLLLLLLLLLLLdw4YLLLLLLLLLLLLLLLLLLLLYmG@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@Edp>U=================================================================G[1YLLLLLLLLLLLLLLL2Y8[MLLLLLLLLLLLLLLLLLLP} A????????????????????????????????????????????????????????????????? G[jkvE=================================================================DYLLLLLLLLLLLLLLLL=]LLLLLLLLLLLLLLLLLLLC`qzB??????????????????????????????????????????????????????????????????CoxFZ==================================================================G[SlLLLLLLLLLLLLLLLz@^LLLLLLLLLLLLLLLLLLLmyYh????????????????????????????????????????????????????????????????????.M_lhtE==================================================================H\)VLLLLLLLLLLLLLLPjA_LLLLLLLLLLLLLLLLLLNI]?????????????????????????????????????????????????????????????????????@Te&H===================================================================K^LLLLLLLLLLLLLLQC`LLLLLLLLLLLLLLLLLLPg:S>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>BVfWf=<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>A,KvcoA<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Dboy!E<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>D>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>^lxD<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<=w MLLLLLLLLLLL M}QhLLLLLLLLLLLLLLLMcsjt>==============================================================================9QXf`l.J;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AXoLLLLLLLLLLLLJfRhLLLLLLLLLLLLLLLOXg=================================================================================A\iN_<;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;+HLLLLLLLLLLLLRWlLLLLLLLLLLLLLLLOgUd==================================================================================='HVes|s|EX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1LLLLLLLLLLLLLXkMLLLLLLLLLLLLLPJ\====================================================================================>B#FM_}=SA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;(H8PBWZh{fqAU(F::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::S<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<@Uu|We)G> =;::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;`mLLLLLLLLLLXkLLLLLLLLLLLQ8P;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;|[g[h[g[hVdP_IZ?T7O"C:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::B`uLLLLLLLLLeyKdMLLLLLLLLLL\n]LLLLLLOf`k>:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;:PzNhLLLL[r+ULLLLNfdn:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::dnK\:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::EX.WLLLL|QLLL N~(F:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;\h9P>:::::::::::::::::::::::::::::::::::::::::::::::::::::::::BK\(ULLL{"RLLL}Sa:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::=jt[h>:::::::::::::::::::::::::::::::::::::::::::::::::::::BVu~"SLLXo{QLL^py?:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: \hzM^9P'F =:::::::::::::::::::::::;!C4MAUbnZpfp=::::::::::::::::::::::::::::::::::::::::::::::::7NpyZh?T C:::::::::::::=;QVdjt|Uc@::::::::::::::::::::::::::::::::::::::::::::@\h`k'F:::::::::::::::::::::::::::::::::::::::::Q`t{)G:::::::::::::::::::::::::::::::::::::BUN],H:::::::::::::::::::::::::::::::"CN^Ye;::::::::::::::::::::::::::@Tv}[g4L)G@;:::::::::::::::@*G=Rjtyks[gM] {} - {} mV", v, convert_to_millivolts(v)); Timer::after_millis(100).await; } diff --git a/examples/stm32f7/src/bin/can.rs b/examples/stm32f7/src/bin/can.rs index bcfdb67a8..a82e335a9 100644 --- a/examples/stm32f7/src/bin/can.rs +++ b/examples/stm32f7/src/bin/can.rs @@ -1,16 +1,18 @@ #![no_std] #![no_main] +use core::num::{NonZeroU16, NonZeroU8}; + use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::bind_interrupts; -use embassy_stm32::can::bxcan::filter::Mask32; -use embassy_stm32::can::bxcan::{Fifo, Frame, StandardId}; +use embassy_stm32::can::filter::Mask32; use embassy_stm32::can::{ - Can, CanTx, Rx0InterruptHandler, Rx1InterruptHandler, SceInterruptHandler, TxInterruptHandler, + Can, CanTx, Fifo, Frame, Rx0InterruptHandler, Rx1InterruptHandler, SceInterruptHandler, StandardId, + TxInterruptHandler, }; use embassy_stm32::gpio::{Input, Pull}; use embassy_stm32::peripherals::CAN3; +use embassy_stm32::{bind_interrupts, can}; use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _}; @@ -22,9 +24,9 @@ bind_interrupts!(struct Irqs { }); #[embassy_executor::task] -pub async fn send_can_message(tx: &'static mut CanTx<'static, 'static, CAN3>) { +pub async fn send_can_message(tx: &'static mut CanTx<'static>) { loop { - let frame = Frame::new_data(unwrap!(StandardId::new(0 as _)), [0]); + let frame = Frame::new_data(unwrap!(StandardId::new(0 as _)), &[0]).unwrap(); tx.write(&frame).await; embassy_time::Timer::after_secs(1).await; } @@ -43,21 +45,24 @@ async fn main(spawner: Spawner) { let rx_pin = Input::new(&mut p.PA15, Pull::Up); core::mem::forget(rx_pin); - static CAN: StaticCell> = StaticCell::new(); + static CAN: StaticCell> = StaticCell::new(); let can = CAN.init(Can::new(p.CAN3, p.PA8, p.PA15, Irqs)); - can.as_mut() - .modify_filters() - .enable_bank(0, Fifo::Fifo0, Mask32::accept_all()); + can.modify_filters().enable_bank(0, Fifo::Fifo0, Mask32::accept_all()); - can.as_mut() - .modify_config() - .set_bit_timing(0x001c0001) // http://www.bittiming.can-wiki.info/ - .set_loopback(true) - .enable(); + can.modify_config() + .set_bit_timing(can::util::NominalBitTiming { + prescaler: NonZeroU16::new(2).unwrap(), + seg1: NonZeroU8::new(13).unwrap(), + seg2: NonZeroU8::new(2).unwrap(), + sync_jump_width: NonZeroU8::new(1).unwrap(), + }) // http://www.bittiming.can-wiki.info/ + .set_loopback(true); + + can.enable().await; let (tx, mut rx) = can.split(); - static CAN_TX: StaticCell> = StaticCell::new(); + static CAN_TX: StaticCell> = StaticCell::new(); let tx = CAN_TX.init(tx); spawner.spawn(send_can_message(tx)).unwrap(); diff --git a/examples/stm32f7/src/bin/cryp.rs b/examples/stm32f7/src/bin/cryp.rs new file mode 100644 index 000000000..235853cb9 --- /dev/null +++ b/examples/stm32f7/src/bin/cryp.rs @@ -0,0 +1,80 @@ +#![no_std] +#![no_main] + +use aes_gcm::aead::heapless::Vec; +use aes_gcm::aead::{AeadInPlace, KeyInit}; +use aes_gcm::Aes128Gcm; +use defmt::info; +use embassy_executor::Spawner; +use embassy_stm32::cryp::{self, *}; +use embassy_stm32::{bind_interrupts, peripherals, Config}; +use embassy_time::Instant; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + CRYP => cryp::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) -> ! { + let config = Config::default(); + let p = embassy_stm32::init(config); + + let payload: &[u8] = b"hello world"; + let aad: &[u8] = b"additional data"; + + let mut hw_cryp = Cryp::new(p.CRYP, p.DMA2_CH6, p.DMA2_CH5, Irqs); + let key: [u8; 16] = [0; 16]; + let mut ciphertext: [u8; 11] = [0; 11]; + let mut plaintext: [u8; 11] = [0; 11]; + let iv: [u8; 12] = [0; 12]; + + let hw_start_time = Instant::now(); + + // Encrypt in hardware using AES-GCM 128-bit + let aes_gcm = AesGcm::new(&key, &iv); + let mut gcm_encrypt = hw_cryp.start(&aes_gcm, Direction::Encrypt).await; + hw_cryp.aad(&mut gcm_encrypt, aad, true).await; + hw_cryp.payload(&mut gcm_encrypt, payload, &mut ciphertext, true).await; + let encrypt_tag = hw_cryp.finish(gcm_encrypt).await; + + // Decrypt in hardware using AES-GCM 128-bit + let mut gcm_decrypt = hw_cryp.start(&aes_gcm, Direction::Decrypt).await; + hw_cryp.aad(&mut gcm_decrypt, aad, true).await; + hw_cryp + .payload(&mut gcm_decrypt, &ciphertext, &mut plaintext, true) + .await; + let decrypt_tag = hw_cryp.finish(gcm_decrypt).await; + + let hw_end_time = Instant::now(); + let hw_execution_time = hw_end_time - hw_start_time; + + info!("AES-GCM Ciphertext: {:?}", ciphertext); + info!("AES-GCM Plaintext: {:?}", plaintext); + assert_eq!(payload, plaintext); + assert_eq!(encrypt_tag, decrypt_tag); + + let sw_start_time = Instant::now(); + + // Encrypt in software using AES-GCM 128-bit + let mut payload_vec: Vec = Vec::from_slice(&payload).unwrap(); + let cipher = Aes128Gcm::new(&key.into()); + let _ = cipher.encrypt_in_place(&iv.into(), aad.into(), &mut payload_vec); + + assert_eq!(ciphertext, payload_vec[0..ciphertext.len()]); + assert_eq!( + encrypt_tag, + payload_vec[ciphertext.len()..ciphertext.len() + encrypt_tag.len()] + ); + + // Decrypt in software using AES-GCM 128-bit + let _ = cipher.decrypt_in_place(&iv.into(), aad.into(), &mut payload_vec); + + let sw_end_time = Instant::now(); + let sw_execution_time = sw_end_time - sw_start_time; + + info!("Hardware Execution Time: {:?}", hw_execution_time); + info!("Software Execution Time: {:?}", sw_execution_time); + + loop {} +} diff --git a/examples/stm32f7/src/bin/eth.rs b/examples/stm32f7/src/bin/eth.rs index 5bff48197..1f1eadf37 100644 --- a/examples/stm32f7/src/bin/eth.rs +++ b/examples/stm32f7/src/bin/eth.rs @@ -4,7 +4,7 @@ use defmt::*; use embassy_executor::Spawner; use embassy_net::tcp::TcpSocket; -use embassy_net::{Ipv4Address, Stack, StackResources}; +use embassy_net::{Ipv4Address, StackResources}; use embassy_stm32::eth::generic_smi::GenericSMI; use embassy_stm32::eth::{Ethernet, PacketQueue}; use embassy_stm32::peripherals::ETH; @@ -19,14 +19,14 @@ use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { ETH => eth::InterruptHandler; - RNG => rng::InterruptHandler; + HASH_RNG => rng::InterruptHandler; }); type Device = Ethernet<'static, ETH, GenericSMI>; #[embassy_executor::task] -async fn net_task(stack: &'static Stack) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -63,9 +63,9 @@ async fn main(spawner: Spawner) -> ! { let mac_addr = [0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF]; - static PACKETS: StaticCell> = StaticCell::new(); + static PACKETS: StaticCell> = StaticCell::new(); let device = Ethernet::new( - PACKETS.init(PacketQueue::<16, 16>::new()), + PACKETS.init(PacketQueue::<4, 4>::new()), p.ETH, Irqs, p.PA1, @@ -89,17 +89,11 @@ async fn main(spawner: Spawner) -> ! { //}); // Init network stack - static STACK: StaticCell> = StaticCell::new(); - static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<2>::new()), - seed, - )); + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); // Launch network task - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); // Ensure DHCP configuration is up before trying connect stack.wait_config_up().await; @@ -111,7 +105,7 @@ async fn main(spawner: Spawner) -> ! { let mut tx_buffer = [0; 4096]; loop { - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); + let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer); socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); diff --git a/examples/stm32f7/src/bin/hash.rs b/examples/stm32f7/src/bin/hash.rs new file mode 100644 index 000000000..c2d1a7158 --- /dev/null +++ b/examples/stm32f7/src/bin/hash.rs @@ -0,0 +1,78 @@ +#![no_std] +#![no_main] + +use defmt::info; +use embassy_executor::Spawner; +use embassy_stm32::hash::*; +use embassy_stm32::{bind_interrupts, hash, peripherals, Config}; +use embassy_time::Instant; +use hmac::{Hmac, Mac}; +use sha2::{Digest, Sha256}; +use {defmt_rtt as _, panic_probe as _}; + +type HmacSha256 = Hmac; + +bind_interrupts!(struct Irqs { + HASH_RNG => hash::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) -> ! { + let config = Config::default(); + let p = embassy_stm32::init(config); + + let test_1: &[u8] = b"as;dfhaslfhas;oifvnasd;nifvnhasd;nifvhndlkfghsd;nvfnahssdfgsdafgsasdfasdfasdfasdfasdfghjklmnbvcalskdjghalskdjgfbaslkdjfgbalskdjgbalskdjbdfhsdfhsfghsfghfgh"; + let test_2: &[u8] = b"fdhalksdjfhlasdjkfhalskdjfhgal;skdjfgalskdhfjgalskdjfglafgadfgdfgdafgaadsfgfgdfgadrgsyfthxfgjfhklhjkfgukhulkvhlvhukgfhfsrghzdhxyfufynufyuszeradrtydyytserr"; + + let mut hw_hasher = Hash::new(p.HASH, p.DMA2_CH7, Irqs); + + let hw_start_time = Instant::now(); + + // Compute a digest in hardware. + let mut context = hw_hasher.start(Algorithm::SHA256, DataType::Width8, None); + hw_hasher.update(&mut context, test_1).await; + hw_hasher.update(&mut context, test_2).await; + let mut hw_digest: [u8; 32] = [0; 32]; + hw_hasher.finish(context, &mut hw_digest).await; + + let hw_end_time = Instant::now(); + let hw_execution_time = hw_end_time - hw_start_time; + + let sw_start_time = Instant::now(); + + // Compute a digest in software. + let mut sw_hasher = Sha256::new(); + sw_hasher.update(test_1); + sw_hasher.update(test_2); + let sw_digest = sw_hasher.finalize(); + + let sw_end_time = Instant::now(); + let sw_execution_time = sw_end_time - sw_start_time; + + info!("Hardware Digest: {:?}", hw_digest); + info!("Software Digest: {:?}", sw_digest[..]); + info!("Hardware Execution Time: {:?}", hw_execution_time); + info!("Software Execution Time: {:?}", sw_execution_time); + assert_eq!(hw_digest, sw_digest[..]); + + let hmac_key: [u8; 64] = [0x55; 64]; + + // Compute HMAC in hardware. + let mut sha256hmac_context = hw_hasher.start(Algorithm::SHA256, DataType::Width8, Some(&hmac_key)); + hw_hasher.update(&mut sha256hmac_context, test_1).await; + hw_hasher.update(&mut sha256hmac_context, test_2).await; + let mut hw_hmac: [u8; 32] = [0; 32]; + hw_hasher.finish(sha256hmac_context, &mut hw_hmac).await; + + // Compute HMAC in software. + let mut sw_mac = HmacSha256::new_from_slice(&hmac_key).unwrap(); + sw_mac.update(test_1); + sw_mac.update(test_2); + let sw_hmac = sw_mac.finalize().into_bytes(); + + info!("Hardware HMAC: {:?}", hw_hmac); + info!("Software HMAC: {:?}", sw_hmac[..]); + assert_eq!(hw_hmac, sw_hmac[..]); + + loop {} +} diff --git a/examples/stm32f7/src/bin/qspi.rs b/examples/stm32f7/src/bin/qspi.rs new file mode 100644 index 000000000..90d319b7a --- /dev/null +++ b/examples/stm32f7/src/bin/qspi.rs @@ -0,0 +1,301 @@ +#![no_std] +#![no_main] +#![allow(dead_code)] // Allow dead code as not all commands are used in the example + +use defmt::info; +use embassy_executor::Spawner; +use embassy_stm32::mode::Async; +use embassy_stm32::qspi::enums::{AddressSize, ChipSelectHighTime, FIFOThresholdLevel, MemorySize, *}; +use embassy_stm32::qspi::{Config as QspiCfg, Instance, Qspi, TransferConfig}; +use embassy_stm32::time::mhz; +use embassy_stm32::Config as StmCfg; +use {defmt_rtt as _, panic_probe as _}; + +const MEMORY_PAGE_SIZE: usize = 256; + +const CMD_READ: u8 = 0x03; +const CMD_HS_READ: u8 = 0x0B; +const CMD_QUAD_READ: u8 = 0x6B; + +const CMD_WRITE_PG: u8 = 0xF2; +const CMD_QUAD_WRITE_PG: u8 = 0x32; + +const CMD_READ_ID: u8 = 0x9F; +const CMD_READ_UUID: u8 = 0x4B; + +const CMD_ENABLE_RESET: u8 = 0x66; +const CMD_RESET: u8 = 0x99; + +const CMD_WRITE_ENABLE: u8 = 0x06; +const CMD_WRITE_DISABLE: u8 = 0x04; + +const CMD_CHIP_ERASE: u8 = 0xC7; +const CMD_SECTOR_ERASE: u8 = 0x20; +const CMD_BLOCK_ERASE_32K: u8 = 0x52; +const CMD_BLOCK_ERASE_64K: u8 = 0xD8; + +const CMD_READ_SR: u8 = 0x05; +const CMD_READ_CR: u8 = 0x35; + +const CMD_WRITE_SR: u8 = 0x01; +const CMD_WRITE_CR: u8 = 0x31; +const MEMORY_ADDR: u32 = 0x00000000u32; + +/// Implementation of access to flash chip. +/// Chip commands are hardcoded as it depends on used chip. +/// This implementation is using chip GD25Q64C from Giga Device +pub struct FlashMemory { + qspi: Qspi<'static, I, Async>, +} + +impl FlashMemory { + pub fn new(qspi: Qspi<'static, I, Async>) -> Self { + let mut memory = Self { qspi }; + + memory.reset_memory(); + memory.enable_quad(); + + memory + } + + fn enable_quad(&mut self) { + let cr = self.read_cr(); + self.write_cr(cr | 0x02); + } + + fn exec_command(&mut self, cmd: u8) { + let transaction = TransferConfig { + iwidth: QspiWidth::SING, + awidth: QspiWidth::NONE, + dwidth: QspiWidth::NONE, + instruction: cmd, + address: None, + dummy: DummyCycles::_0, + }; + self.qspi.command(transaction); + } + + pub fn reset_memory(&mut self) { + self.exec_command(CMD_ENABLE_RESET); + self.exec_command(CMD_RESET); + self.wait_write_finish(); + } + + pub fn enable_write(&mut self) { + self.exec_command(CMD_WRITE_ENABLE); + } + + pub fn read_id(&mut self) -> [u8; 3] { + let mut buffer = [0; 3]; + let transaction: TransferConfig = TransferConfig { + iwidth: QspiWidth::SING, + awidth: QspiWidth::NONE, + dwidth: QspiWidth::SING, + instruction: CMD_READ_ID, + address: None, + dummy: DummyCycles::_0, + }; + self.qspi.blocking_read(&mut buffer, transaction); + buffer + } + + pub fn read_uuid(&mut self) -> [u8; 16] { + let mut buffer = [0; 16]; + let transaction: TransferConfig = TransferConfig { + iwidth: QspiWidth::SING, + awidth: QspiWidth::SING, + dwidth: QspiWidth::SING, + instruction: CMD_READ_UUID, + address: Some(0), + dummy: DummyCycles::_8, + }; + self.qspi.blocking_read(&mut buffer, transaction); + buffer + } + + pub fn read_memory(&mut self, addr: u32, buffer: &mut [u8], use_dma: bool) { + let transaction = TransferConfig { + iwidth: QspiWidth::SING, + awidth: QspiWidth::SING, + dwidth: QspiWidth::QUAD, + instruction: CMD_QUAD_READ, + address: Some(addr), + dummy: DummyCycles::_8, + }; + if use_dma { + self.qspi.blocking_read_dma(buffer, transaction); + } else { + self.qspi.blocking_read(buffer, transaction); + } + } + + fn wait_write_finish(&mut self) { + while (self.read_sr() & 0x01) != 0 {} + } + + fn perform_erase(&mut self, addr: u32, cmd: u8) { + let transaction = TransferConfig { + iwidth: QspiWidth::SING, + awidth: QspiWidth::SING, + dwidth: QspiWidth::NONE, + instruction: cmd, + address: Some(addr), + dummy: DummyCycles::_0, + }; + self.enable_write(); + self.qspi.command(transaction); + self.wait_write_finish(); + } + + pub fn erase_sector(&mut self, addr: u32) { + self.perform_erase(addr, CMD_SECTOR_ERASE); + } + + pub fn erase_block_32k(&mut self, addr: u32) { + self.perform_erase(addr, CMD_BLOCK_ERASE_32K); + } + + pub fn erase_block_64k(&mut self, addr: u32) { + self.perform_erase(addr, CMD_BLOCK_ERASE_64K); + } + + pub fn erase_chip(&mut self) { + self.exec_command(CMD_CHIP_ERASE); + } + + fn write_page(&mut self, addr: u32, buffer: &[u8], len: usize, use_dma: bool) { + assert!( + (len as u32 + (addr & 0x000000ff)) <= MEMORY_PAGE_SIZE as u32, + "write_page(): page write length exceeds page boundary (len = {}, addr = {:X}", + len, + addr + ); + + let transaction = TransferConfig { + iwidth: QspiWidth::SING, + awidth: QspiWidth::SING, + dwidth: QspiWidth::QUAD, + instruction: CMD_QUAD_WRITE_PG, + address: Some(addr), + dummy: DummyCycles::_0, + }; + self.enable_write(); + if use_dma { + self.qspi.blocking_write_dma(buffer, transaction); + } else { + self.qspi.blocking_write(buffer, transaction); + } + self.wait_write_finish(); + } + + pub fn write_memory(&mut self, addr: u32, buffer: &[u8], use_dma: bool) { + let mut left = buffer.len(); + let mut place = addr; + let mut chunk_start = 0; + + while left > 0 { + let max_chunk_size = MEMORY_PAGE_SIZE - (place & 0x000000ff) as usize; + let chunk_size = if left >= max_chunk_size { max_chunk_size } else { left }; + let chunk = &buffer[chunk_start..(chunk_start + chunk_size)]; + self.write_page(place, chunk, chunk_size, use_dma); + place += chunk_size as u32; + left -= chunk_size; + chunk_start += chunk_size; + } + } + + fn read_register(&mut self, cmd: u8) -> u8 { + let mut buffer = [0; 1]; + let transaction: TransferConfig = TransferConfig { + iwidth: QspiWidth::SING, + awidth: QspiWidth::NONE, + dwidth: QspiWidth::SING, + instruction: cmd, + address: None, + dummy: DummyCycles::_0, + }; + self.qspi.blocking_read(&mut buffer, transaction); + buffer[0] + } + + fn write_register(&mut self, cmd: u8, value: u8) { + let buffer = [value; 1]; + let transaction: TransferConfig = TransferConfig { + iwidth: QspiWidth::SING, + awidth: QspiWidth::NONE, + dwidth: QspiWidth::SING, + instruction: cmd, + address: None, + dummy: DummyCycles::_0, + }; + self.qspi.blocking_write(&buffer, transaction); + } + + pub fn read_sr(&mut self) -> u8 { + self.read_register(CMD_READ_SR) + } + + pub fn read_cr(&mut self) -> u8 { + self.read_register(CMD_READ_CR) + } + + pub fn write_sr(&mut self, value: u8) { + self.write_register(CMD_WRITE_SR, value); + } + + pub fn write_cr(&mut self, value: u8) { + self.write_register(CMD_WRITE_CR, value); + } +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) -> ! { + let mut config = StmCfg::default(); + { + use embassy_stm32::rcc::*; + config.rcc.hse = Some(Hse { + freq: mhz(8), + mode: HseMode::Oscillator, + }); + config.rcc.pll_src = PllSource::HSE; + config.rcc.pll = Some(Pll { + prediv: PllPreDiv::DIV4, + mul: PllMul::MUL216, + divp: Some(PllPDiv::DIV2), // 8mhz / 4 * 216 / 2 = 216Mhz + divq: None, + divr: None, + }); + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV4; + config.rcc.apb2_pre = APBPrescaler::DIV2; + config.rcc.sys = Sysclk::PLL1_P; + } + let p = embassy_stm32::init(config); + info!("Embassy initialized"); + + let config = QspiCfg { + memory_size: MemorySize::_8MiB, + address_size: AddressSize::_24bit, + prescaler: 16, + cs_high_time: ChipSelectHighTime::_1Cycle, + fifo_threshold: FIFOThresholdLevel::_16Bytes, + }; + let driver = Qspi::new_bank1( + p.QUADSPI, p.PF8, p.PF9, p.PE2, p.PF6, p.PF10, p.PB10, p.DMA2_CH7, config, + ); + let mut flash = FlashMemory::new(driver); + let flash_id = flash.read_id(); + info!("FLASH ID: {:?}", flash_id); + let mut wr_buf = [0u8; 256]; + for i in 0..256 { + wr_buf[i] = i as u8; + } + let mut rd_buf = [0u8; 256]; + flash.erase_sector(MEMORY_ADDR); + flash.write_memory(MEMORY_ADDR, &wr_buf, true); + flash.read_memory(MEMORY_ADDR, &mut rd_buf, true); + info!("WRITE BUF: {:?}", wr_buf); + info!("READ BUF: {:?}", rd_buf); + info!("End of Program, proceed to empty endless loop"); + loop {} +} diff --git a/examples/stm32f7/src/bin/usart_dma.rs b/examples/stm32f7/src/bin/usart_dma.rs index fb604b34f..47456adf2 100644 --- a/examples/stm32f7/src/bin/usart_dma.rs +++ b/examples/stm32f7/src/bin/usart_dma.rs @@ -5,7 +5,6 @@ use core::fmt::Write; use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::dma::NoDma; use embassy_stm32::usart::{Config, Uart}; use embassy_stm32::{bind_interrupts, peripherals, usart}; use heapless::String; @@ -19,7 +18,7 @@ bind_interrupts!(struct Irqs { async fn main(_spawner: Spawner) { let p = embassy_stm32::init(Default::default()); let config = Config::default(); - let mut usart = Uart::new(p.UART7, p.PA8, p.PA15, Irqs, p.DMA1_CH1, NoDma, config).unwrap(); + let mut usart = Uart::new(p.UART7, p.PA8, p.PA15, Irqs, p.DMA1_CH1, p.DMA1_CH3, config).unwrap(); for n in 0u32.. { let mut s: String<128> = String::new(); diff --git a/examples/stm32f7/src/bin/usb_serial.rs b/examples/stm32f7/src/bin/usb_serial.rs index 97daf6bd1..1906b28ed 100644 --- a/examples/stm32f7/src/bin/usb_serial.rs +++ b/examples/stm32f7/src/bin/usb_serial.rs @@ -3,19 +3,24 @@ use defmt::{panic, *}; use embassy_executor::Spawner; +use embassy_futures::join::join; use embassy_stm32::time::Hertz; -use embassy_stm32::usb_otg::{Driver, Instance}; -use embassy_stm32::{bind_interrupts, peripherals, usb_otg, Config}; +use embassy_stm32::usb::{Driver, Instance}; +use embassy_stm32::{bind_interrupts, peripherals, usb, Config}; use embassy_usb::class::cdc_acm::{CdcAcmClass, State}; use embassy_usb::driver::EndpointError; use embassy_usb::Builder; -use futures::future::join; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { - OTG_FS => usb_otg::InterruptHandler; + OTG_FS => usb::InterruptHandler; }); +// If you are trying this and your USB device doesn't connect, the most +// common issues are the RCC config and vbus_detection +// +// See https://embassy.dev/book/#_the_usb_examples_are_not_working_on_my_board_is_there_anything_else_i_need_to_configure +// for more information. #[embassy_executor::main] async fn main(_spawner: Spawner) { info!("Hello World!"); @@ -39,13 +44,20 @@ async fn main(_spawner: Spawner) { config.rcc.apb1_pre = APBPrescaler::DIV4; config.rcc.apb2_pre = APBPrescaler::DIV2; config.rcc.sys = Sysclk::PLL1_P; + config.rcc.mux.clk48sel = mux::Clk48sel::PLL1_Q; } let p = embassy_stm32::init(config); // Create the driver, from the HAL. let mut ep_out_buffer = [0u8; 256]; - let mut config = embassy_stm32::usb_otg::Config::default(); - config.vbus_detection = true; + let mut config = embassy_stm32::usb::Config::default(); + + // Do not enable vbus_detection. This is a safe default that works in all boards. + // However, if your USB device is self-powered (can stay powered on if USB is unplugged), you need + // to enable vbus_detection to comply with the USB spec. If you enable it, the board + // has to support it or USB won't work at all. See docs on `vbus_detection` for details. + config.vbus_detection = false; + let driver = Driver::new_fs(p.USB_OTG_FS, Irqs, p.PA12, p.PA11, &mut ep_out_buffer, config); // Create embassy-usb Config @@ -63,7 +75,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 64]; @@ -73,7 +84,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], // no msos descriptors diff --git a/examples/stm32g0/Cargo.toml b/examples/stm32g0/Cargo.toml index 6ce3418e5..bf258a7fd 100644 --- a/examples/stm32g0/Cargo.toml +++ b/examples/stm32g0/Cargo.toml @@ -7,10 +7,10 @@ license = "MIT OR Apache-2.0" [dependencies] # Change stm32g0b1re to your chip name, if necessary. embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = [ "defmt", "time-driver-any", "stm32g0b1re", "memory-x", "unstable-pac", "exti"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } -embassy-usb = { version = "0.1.0", path = "../../embassy-usb", default-features = false, features = ["defmt"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", default-features = false, features = ["defmt"] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } defmt = "0.3" @@ -20,9 +20,10 @@ cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-sing cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } portable-atomic = { version = "1.5", features = ["unsafe-assume-single-core"] } +embedded-io-async = { version = "0.6.1" } + [profile.release] debug = 2 diff --git a/examples/stm32g0/src/bin/adc.rs b/examples/stm32g0/src/bin/adc.rs new file mode 100644 index 000000000..6c7f3b48a --- /dev/null +++ b/examples/stm32g0/src/bin/adc.rs @@ -0,0 +1,34 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::adc::{Adc, SampleTime}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + let mut adc = Adc::new(p.ADC1); + adc.set_sample_time(SampleTime::CYCLES79_5); + let mut pin = p.PA1; + + let mut vrefint = adc.enable_vrefint(); + let vrefint_sample = adc.blocking_read(&mut vrefint); + let convert_to_millivolts = |sample| { + // From https://www.st.com/resource/en/datasheet/stm32g031g8.pdf + // 6.3.3 Embedded internal reference voltage + const VREFINT_MV: u32 = 1212; // mV + + (u32::from(sample) * VREFINT_MV / u32::from(vrefint_sample)) as u16 + }; + + loop { + let v = adc.blocking_read(&mut pin); + info!("--> {} - {} mV", v, convert_to_millivolts(v)); + Timer::after_millis(100).await; + } +} diff --git a/examples/stm32g0/src/bin/adc_dma.rs b/examples/stm32g0/src/bin/adc_dma.rs new file mode 100644 index 000000000..3713e5a21 --- /dev/null +++ b/examples/stm32g0/src/bin/adc_dma.rs @@ -0,0 +1,44 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::adc::{Adc, AdcChannel as _, SampleTime}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +static mut DMA_BUF: [u16; 2] = [0; 2]; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut read_buffer = unsafe { &mut DMA_BUF[..] }; + + let p = embassy_stm32::init(Default::default()); + + info!("Hello World!"); + + let mut adc = Adc::new(p.ADC1); + + let mut dma = p.DMA1_CH1; + let mut vrefint_channel = adc.enable_vrefint().degrade_adc(); + let mut pa0 = p.PA0.degrade_adc(); + + loop { + adc.read( + &mut dma, + [ + (&mut vrefint_channel, SampleTime::CYCLES160_5), + (&mut pa0, SampleTime::CYCLES160_5), + ] + .into_iter(), + &mut read_buffer, + ) + .await; + + let vrefint = read_buffer[0]; + let measured = read_buffer[1]; + info!("vrefint: {}", vrefint); + info!("measured: {}", measured); + Timer::after_millis(500).await; + } +} diff --git a/examples/stm32g0/src/bin/adc_oversampling.rs b/examples/stm32g0/src/bin/adc_oversampling.rs new file mode 100644 index 000000000..9c5dd872a --- /dev/null +++ b/examples/stm32g0/src/bin/adc_oversampling.rs @@ -0,0 +1,43 @@ +//! adc oversampling example +//! +//! This example uses adc oversampling to achieve 16bit data + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::adc::{Adc, SampleTime}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Adc oversample test"); + + let mut adc = Adc::new(p.ADC1); + adc.set_sample_time(SampleTime::CYCLES1_5); + let mut pin = p.PA1; + + // From https://www.st.com/resource/en/reference_manual/rm0444-stm32g0x1-advanced-armbased-32bit-mcus-stmicroelectronics.pdf + // page373 15.8 Oversampler + // Table 76. Maximum output results vs N and M. Grayed values indicates truncation + // 0x00 oversampling ratio X2 + // 0x01 oversampling ratio X4 + // 0x02 oversampling ratio X8 + // 0x03 oversampling ratio X16 + // 0x04 oversampling ratio X32 + // 0x05 oversampling ratio X64 + // 0x06 oversampling ratio X128 + // 0x07 oversampling ratio X256 + adc.set_oversampling_ratio(0x03); + adc.set_oversampling_shift(0b0000); + adc.oversampling_enable(true); + + loop { + let v = adc.blocking_read(&mut pin); + info!("--> {} ", v); //max 65520 = 0xFFF0 + Timer::after_millis(100).await; + } +} diff --git a/examples/stm32g0/src/bin/hf_timer.rs b/examples/stm32g0/src/bin/hf_timer.rs index 78a779e29..3ea06cdee 100644 --- a/examples/stm32g0/src/bin/hf_timer.rs +++ b/examples/stm32g0/src/bin/hf_timer.rs @@ -4,37 +4,36 @@ use defmt::info; use embassy_executor::Spawner; use embassy_stm32::gpio::OutputType; -use embassy_stm32::pac::rcc::vals::Tim1sel; -use embassy_stm32::rcc::{ClockSrc, Config as RccConfig, PllConfig, PllSource, Pllm, Plln, Pllq, Pllr}; use embassy_stm32::time::khz; use embassy_stm32::timer::complementary_pwm::{ComplementaryPwm, ComplementaryPwmPin}; use embassy_stm32::timer::simple_pwm::PwmPin; use embassy_stm32::timer::Channel; -use embassy_stm32::{pac, Config as PeripheralConfig}; +use embassy_stm32::Config as PeripheralConfig; use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] async fn main(_spawner: Spawner) { - let mut rcc_config = RccConfig::default(); - rcc_config.mux = ClockSrc::PLL(PllConfig { - source: PllSource::HSI, - m: Pllm::DIV1, - n: Plln::MUL16, - r: Pllr::DIV4, // CPU clock comes from PLLR (HSI (16MHz) / 1 * 16 / 4 = 64MHz) - q: Some(Pllq::DIV2), // TIM1 or TIM15 can be sourced from PLLQ (HSI (16MHz) / 1 * 16 / 2 = 128MHz) - p: None, - }); + let mut config = PeripheralConfig::default(); + { + use embassy_stm32::rcc::*; + config.rcc.hsi = true; + config.rcc.pll = Some(Pll { + source: PllSource::HSI, + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL16, + divp: None, + divq: Some(PllQDiv::DIV2), // 16 / 1 * 16 / 2 = 128 Mhz + divr: Some(PllRDiv::DIV4), // 16 / 1 * 16 / 4 = 64 Mhz + }); + config.rcc.sys = Sysclk::PLL1_R; - let mut peripheral_config = PeripheralConfig::default(); - peripheral_config.rcc = rcc_config; - - let p = embassy_stm32::init(peripheral_config); - - // configure TIM1 mux to select PLLQ as clock source - // https://www.st.com/resource/en/reference_manual/rm0444-stm32g0x1-advanced-armbased-32bit-mcus-stmicroelectronics.pdf - // RM0444 page 210 - // RCC - Peripherals Independent Clock Control Register - bit 22 -> 1 - pac::RCC.ccipr().modify(|w| w.set_tim1sel(Tim1sel::PLL1_Q)); + // configure TIM1 mux to select PLLQ as clock source + // https://www.st.com/resource/en/reference_manual/rm0444-stm32g0x1-advanced-armbased-32bit-mcus-stmicroelectronics.pdf + // RM0444 page 210 + // RCC - Peripherals Independent Clock Control Register - bit 22 -> 1 + config.rcc.mux.tim1sel = embassy_stm32::rcc::mux::Tim1sel::PLL1_Q; + } + let p = embassy_stm32::init(config); let ch1 = PwmPin::new_ch1(p.PA8, OutputType::PushPull); let ch1n = ComplementaryPwmPin::new_ch1(p.PA7, OutputType::PushPull); diff --git a/examples/stm32g0/src/bin/i2c_async.rs b/examples/stm32g0/src/bin/i2c_async.rs new file mode 100644 index 000000000..7e3189b05 --- /dev/null +++ b/examples/stm32g0/src/bin/i2c_async.rs @@ -0,0 +1,48 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::i2c::{self, I2c}; +use embassy_stm32::time::Hertz; +use embassy_stm32::{bind_interrupts, peripherals}; +use embassy_time::{Duration, Timer}; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + I2C1 => i2c::EventInterruptHandler, i2c::ErrorInterruptHandler; +}); + +const TMP117_ADDR: u8 = 0x48; +const TMP117_TEMP_RESULT: u8 = 0x00; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + info!("Hello world"); + + let p = embassy_stm32::init(Default::default()); + + let mut data = [0u8; 2]; + let mut i2c = I2c::new( + p.I2C1, + p.PB8, + p.PB9, + Irqs, + p.DMA1_CH1, + p.DMA1_CH2, + Hertz(100_000), + Default::default(), + ); + + loop { + match i2c.write_read(TMP117_ADDR, &[TMP117_TEMP_RESULT], &mut data).await { + Ok(()) => { + let temp = f32::from(i16::from_be_bytes(data)) * 7.8125 / 1000.0; + info!("Temperature {}", temp); + } + Err(_) => error!("I2C Error"), + } + + Timer::after(Duration::from_millis(1000)).await; + } +} diff --git a/examples/stm32g0/src/bin/input_capture.rs b/examples/stm32g0/src/bin/input_capture.rs new file mode 100644 index 000000000..bc814cb13 --- /dev/null +++ b/examples/stm32g0/src/bin/input_capture.rs @@ -0,0 +1,67 @@ +//! Input capture example +//! +//! This example showcases how to use the input capture feature of the timer peripheral. +//! Connect PB1 and PA6 with a 1k Ohm resistor or Connect PB1 and PA8 with a 1k Ohm resistor +//! to see the output. +//! When connecting PB1 (software pwm) and PA6 the output is around 10000 (it will be a bit bigger, around 10040) +//! Output is 1000 when connecting PB1 (PWMOUT) and PA6. +//! +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{Level, Output, OutputType, Pull, Speed}; +use embassy_stm32::time::khz; +use embassy_stm32::timer::input_capture::{CapturePin, InputCapture}; +use embassy_stm32::timer::simple_pwm::{PwmPin, SimplePwm}; +use embassy_stm32::timer::Channel; +use embassy_stm32::{bind_interrupts, peripherals, timer}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +// Connect PB1 and PA6 with a 1k Ohm resistor + +#[embassy_executor::task] +async fn blinky(led: peripherals::PB1) { + let mut led = Output::new(led, Level::High, Speed::Low); + + loop { + led.set_high(); + Timer::after_millis(50).await; + + led.set_low(); + Timer::after_millis(50).await; + } +} + +bind_interrupts!(struct Irqs { + TIM2 => timer::CaptureCompareInterruptHandler; +}); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + unwrap!(spawner.spawn(blinky(p.PB1))); + + // Connect PB1 and PA8 with a 1k Ohm resistor + let ch1_pin = PwmPin::new_ch1(p.PA8, OutputType::PushPull); + let mut pwm = SimplePwm::new(p.TIM1, Some(ch1_pin), None, None, None, khz(1), Default::default()); + pwm.ch1().enable(); + pwm.ch1().set_duty_cycle(50); + + let ch1 = CapturePin::new_ch1(p.PA0, Pull::None); + let mut ic = InputCapture::new(p.TIM2, Some(ch1), None, None, None, Irqs, khz(1000), Default::default()); + + let mut old_capture = 0; + + loop { + ic.wait_for_rising_edge(Channel::Ch1).await; + + let capture_value = ic.get_capture_value(Channel::Ch1); + info!("{}", capture_value - old_capture); + old_capture = capture_value; + } +} diff --git a/examples/stm32g0/src/bin/pwm_complementary.rs b/examples/stm32g0/src/bin/pwm_complementary.rs new file mode 100644 index 000000000..97b163c40 --- /dev/null +++ b/examples/stm32g0/src/bin/pwm_complementary.rs @@ -0,0 +1,57 @@ +//! PWM complementary example +//! +//! This example uses two complementary pwm outputs from TIM1 with different duty cycles +//! ___ ___ +//! |_________| |_________| PA8 +//! _________ _________ +//! ___| |___| | PA7 +//! _________ _________ +//! |___| |___| PB3 +//! ___ ___ +//! _________| |_________| | PB0 + +#![no_std] +#![no_main] + +use defmt::info; +use embassy_executor::Spawner; +use embassy_stm32::gpio::OutputType; +use embassy_stm32::time::khz; +use embassy_stm32::timer::complementary_pwm::{ComplementaryPwm, ComplementaryPwmPin}; +use embassy_stm32::timer::simple_pwm::PwmPin; +use embassy_stm32::timer::Channel; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + + let ch1 = PwmPin::new_ch1(p.PA8, OutputType::PushPull); + let ch1n = ComplementaryPwmPin::new_ch1(p.PA7, OutputType::PushPull); + let ch2 = PwmPin::new_ch2(p.PB3, OutputType::PushPull); + let ch2n = ComplementaryPwmPin::new_ch2(p.PB0, OutputType::PushPull); + + let mut pwm = ComplementaryPwm::new( + p.TIM1, + Some(ch1), + Some(ch1n), + Some(ch2), + Some(ch2n), + None, + None, + None, + None, + khz(100), + Default::default(), + ); + + let max = pwm.get_max_duty(); + info!("Max duty: {}", max); + + pwm.set_duty(Channel::Ch1, max / 4); + pwm.enable(Channel::Ch1); + pwm.set_duty(Channel::Ch2, max * 3 / 4); + pwm.enable(Channel::Ch2); + + loop {} +} diff --git a/examples/stm32g0/src/bin/pwm_input.rs b/examples/stm32g0/src/bin/pwm_input.rs new file mode 100644 index 000000000..db9cf4f8a --- /dev/null +++ b/examples/stm32g0/src/bin/pwm_input.rs @@ -0,0 +1,63 @@ +//! PWM input example +//! +//! This program demonstrates how to capture the parameters of the input waveform (frequency, width and duty cycle) +//! Connect PB1 and PA6 with a 1k Ohm resistor or Connect PB1 and PA8 with a 1k Ohm resistor +//! to see the output. +//! + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{Level, Output, OutputType, Pull, Speed}; +use embassy_stm32::time::khz; +use embassy_stm32::timer::pwm_input::PwmInput; +use embassy_stm32::timer::simple_pwm::{PwmPin, SimplePwm}; +use embassy_stm32::{bind_interrupts, peripherals, timer}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +// Connect PB1 and PA6 with a 1k Ohm resistor +#[embassy_executor::task] +async fn blinky(led: peripherals::PB1) { + let mut led = Output::new(led, Level::High, Speed::Low); + + loop { + led.set_high(); + Timer::after_millis(50).await; + + led.set_low(); + Timer::after_millis(50).await; + } +} + +bind_interrupts!(struct Irqs { + TIM2 => timer::CaptureCompareInterruptHandler; +}); + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + + unwrap!(spawner.spawn(blinky(p.PB1))); + // Connect PA8 and PA6 with a 1k Ohm resistor + let ch1_pin = PwmPin::new_ch1(p.PA8, OutputType::PushPull); + let mut pwm = SimplePwm::new(p.TIM1, Some(ch1_pin), None, None, None, khz(1), Default::default()); + pwm.ch1().set_duty_cycle_fraction(1, 4); + pwm.ch1().enable(); + + let mut pwm_input = PwmInput::new(p.TIM2, p.PA0, Pull::None, khz(1000)); + pwm_input.enable(); + + loop { + Timer::after_millis(500).await; + let period = pwm_input.get_period_ticks(); + let width = pwm_input.get_width_ticks(); + let duty_cycle = pwm_input.get_duty_cycle(); + info!( + "period ticks: {} width ticks: {} duty cycle: {}", + period, width, duty_cycle + ); + } +} diff --git a/examples/stm32g0/src/bin/rtc.rs b/examples/stm32g0/src/bin/rtc.rs new file mode 100644 index 000000000..c02c1ecd7 --- /dev/null +++ b/examples/stm32g0/src/bin/rtc.rs @@ -0,0 +1,31 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::rtc::{DateTime, DayOfWeek, Rtc, RtcConfig}; +use embassy_stm32::Config; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let config = Config::default(); + let p = embassy_stm32::init(config); + + info!("Hello World!"); + + let now = DateTime::from(2023, 6, 14, DayOfWeek::Friday, 15, 59, 10); + + let mut rtc = Rtc::new(p.RTC, RtcConfig::default()); + + rtc.set_datetime(now.unwrap()).expect("datetime not set"); + + loop { + let now: DateTime = rtc.now().unwrap().into(); + + info!("{}:{}:{}", now.hour(), now.minute(), now.second()); + + Timer::after_millis(1000).await; + } +} diff --git a/examples/stm32g0/src/bin/spi_neopixel.rs b/examples/stm32g0/src/bin/spi_neopixel.rs index c5ea51721..edcae74f7 100644 --- a/examples/stm32g0/src/bin/spi_neopixel.rs +++ b/examples/stm32g0/src/bin/spi_neopixel.rs @@ -4,7 +4,6 @@ use defmt::*; use embassy_executor::Spawner; use embassy_stm32::dma::word::U5; -use embassy_stm32::dma::NoDma; use embassy_stm32::spi::{Config, Spi}; use embassy_stm32::time::Hertz; use embassy_time::Timer; @@ -77,7 +76,7 @@ async fn main(_spawner: Spawner) { let mut config = Config::default(); config.frequency = Hertz(4_000_000); - let mut spi = Spi::new_txonly_nosck(p.SPI1, p.PB5, p.DMA1_CH3, NoDma, config); + let mut spi = Spi::new_txonly(p.SPI1, p.PB3, p.PB5, p.DMA1_CH3, config); // SCK is unused. let mut neopixels = Ws2812::new(); diff --git a/examples/stm32g0/src/bin/usart.rs b/examples/stm32g0/src/bin/usart.rs new file mode 100644 index 000000000..037a5c833 --- /dev/null +++ b/examples/stm32g0/src/bin/usart.rs @@ -0,0 +1,25 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_stm32::usart::{Config, Uart}; +use {defmt_rtt as _, panic_probe as _}; + +#[cortex_m_rt::entry] +fn main() -> ! { + info!("Hello World!"); + + let p = embassy_stm32::init(Default::default()); + + let config = Config::default(); + let mut usart = Uart::new_blocking(p.USART2, p.PA3, p.PA2, config).unwrap(); + + unwrap!(usart.blocking_write(b"Hello Embassy World!\r\n")); + info!("wrote Hello, starting echo"); + + let mut buf = [0u8; 1]; + loop { + unwrap!(usart.blocking_read(&mut buf)); + unwrap!(usart.blocking_write(&buf)); + } +} diff --git a/examples/stm32g0/src/bin/usart_buffered.rs b/examples/stm32g0/src/bin/usart_buffered.rs new file mode 100644 index 000000000..c097a0c5a --- /dev/null +++ b/examples/stm32g0/src/bin/usart_buffered.rs @@ -0,0 +1,34 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::usart::{BufferedUart, Config}; +use embassy_stm32::{bind_interrupts, peripherals, usart}; +use embedded_io_async::{Read, Write}; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + USART1 => usart::BufferedInterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hi!"); + + let mut config = Config::default(); + config.baudrate = 115200; + let mut tx_buf = [0u8; 256]; + let mut rx_buf = [0u8; 256]; + let mut usart = BufferedUart::new(p.USART1, Irqs, p.PB7, p.PB6, &mut tx_buf, &mut rx_buf, config).unwrap(); + + usart.write_all(b"Hello Embassy World!\r\n").await.unwrap(); + info!("wrote Hello, starting echo"); + + let mut buf = [0; 4]; + loop { + usart.read_exact(&mut buf[..]).await.unwrap(); + usart.write_all(&buf[..]).await.unwrap(); + } +} diff --git a/examples/stm32g0/src/bin/usart_dma.rs b/examples/stm32g0/src/bin/usart_dma.rs new file mode 100644 index 000000000..8212153ab --- /dev/null +++ b/examples/stm32g0/src/bin/usart_dma.rs @@ -0,0 +1,27 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::usart::{Config, Uart}; +use embassy_stm32::{bind_interrupts, peripherals, usart}; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + USART1 => usart::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + let mut usart = Uart::new(p.USART1, p.PB7, p.PB6, Irqs, p.DMA1_CH2, p.DMA1_CH3, Config::default()).unwrap(); + + usart.write(b"Hello Embassy World!\r\n").await.unwrap(); + info!("wrote Hello, starting echo"); + + let mut buf = [0; 5]; + loop { + usart.read(&mut buf[..]).await.unwrap(); + usart.write(&buf[..]).await.unwrap(); + } +} diff --git a/examples/stm32g0/src/bin/usb_serial.rs b/examples/stm32g0/src/bin/usb_serial.rs index f5aaa5624..162dfd86b 100644 --- a/examples/stm32g0/src/bin/usb_serial.rs +++ b/examples/stm32g0/src/bin/usb_serial.rs @@ -4,7 +4,6 @@ use defmt::{panic, *}; use embassy_executor::Spawner; use embassy_futures::join::join; -use embassy_stm32::rcc::{Hsi48Config, UsbSrc}; use embassy_stm32::usb::{Driver, Instance}; use embassy_stm32::{bind_interrupts, peripherals, usb, Config}; use embassy_usb::class::cdc_acm::{CdcAcmClass, State}; @@ -19,10 +18,11 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut config = Config::default(); - config.rcc.usb_src = Some(UsbSrc::Hsi48(Hsi48Config { - sync_from_usb: true, - ..Default::default() - })); + { + use embassy_stm32::rcc::*; + config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true }); + config.rcc.mux.usbsel = mux::Usbsel::HSI48; + } let p = embassy_stm32::init(config); info!("Hello World!"); @@ -36,7 +36,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 7]; @@ -46,7 +45,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], // no msos descriptors diff --git a/examples/stm32g4/Cargo.toml b/examples/stm32g4/Cargo.toml index 895ad3e7c..cc3b44b57 100644 --- a/examples/stm32g4/Cargo.toml +++ b/examples/stm32g4/Cargo.toml @@ -7,12 +7,12 @@ license = "MIT OR Apache-2.0" [dependencies] # Change stm32g491re to your chip name, if necessary. embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = [ "defmt", "time-driver-any", "stm32g491re", "memory-x", "unstable-pac", "exti"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } -embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } -usbd-hid = "0.6.0" +usbd-hid = "0.8.1" defmt = "0.3" defmt-rtt = "0.4" @@ -20,9 +20,10 @@ defmt-rtt = "0.4" cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] } cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" +embedded-can = { version = "0.4" } panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } +static_cell = "2.0.0" [profile.release] debug = 2 diff --git a/examples/stm32g4/src/bin/adc.rs b/examples/stm32g4/src/bin/adc.rs index 35324d931..adca846d8 100644 --- a/examples/stm32g4/src/bin/adc.rs +++ b/examples/stm32g4/src/bin/adc.rs @@ -4,36 +4,35 @@ use defmt::*; use embassy_executor::Spawner; use embassy_stm32::adc::{Adc, SampleTime}; -use embassy_stm32::rcc::{AdcClockSource, ClockSrc, Pll, PllM, PllN, PllR, PllSource}; use embassy_stm32::Config; -use embassy_time::{Delay, Timer}; +use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut config = Config::default(); - - config.rcc.pll = Some(Pll { - source: PllSource::HSI, - prediv_m: PllM::DIV4, - mul_n: PllN::MUL85, - div_p: None, - div_q: None, - // Main system clock at 170 MHz - div_r: Some(PllR::DIV2), - }); - - config.rcc.adc12_clock_source = AdcClockSource::SYS; - config.rcc.mux = ClockSrc::PLL; - + { + use embassy_stm32::rcc::*; + config.rcc.pll = Some(Pll { + source: PllSource::HSI, + prediv: PllPreDiv::DIV4, + mul: PllMul::MUL85, + divp: None, + divq: None, + // Main system clock at 170 MHz + divr: Some(PllRDiv::DIV2), + }); + config.rcc.mux.adc12sel = mux::Adcsel::SYS; + config.rcc.sys = Sysclk::PLL1_R; + } let mut p = embassy_stm32::init(config); info!("Hello World!"); - let mut adc = Adc::new(p.ADC2, &mut Delay); - adc.set_sample_time(SampleTime::Cycles32_5); + let mut adc = Adc::new(p.ADC2); + adc.set_sample_time(SampleTime::CYCLES24_5); loop { - let measured = adc.read(&mut p.PA7); + let measured = adc.blocking_read(&mut p.PA7); info!("measured: {}", measured); Timer::after_millis(500).await; } diff --git a/examples/stm32g4/src/bin/adc_differential.rs b/examples/stm32g4/src/bin/adc_differential.rs new file mode 100644 index 000000000..78d071d45 --- /dev/null +++ b/examples/stm32g4/src/bin/adc_differential.rs @@ -0,0 +1,47 @@ +//! adc differential mode example +//! +//! This example uses adc1 in differential mode +//! p:pa0 n:pa1 + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::adc::{Adc, SampleTime}; +use embassy_stm32::Config; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.pll = Some(Pll { + source: PllSource::HSI, + prediv: PllPreDiv::DIV4, + mul: PllMul::MUL85, + divp: None, + divq: None, + // Main system clock at 170 MHz + divr: Some(PllRDiv::DIV2), + }); + config.rcc.mux.adc12sel = mux::Adcsel::SYS; + config.rcc.sys = Sysclk::PLL1_R; + } + let mut p = embassy_stm32::init(config); + + let mut adc = Adc::new(p.ADC1); + adc.set_sample_time(SampleTime::CYCLES247_5); + adc.set_differential(&mut p.PA0, true); //p:pa0,n:pa1 + + // can also use + // adc.set_differential_channel(1, true); + info!("adc initialized"); + loop { + let measured = adc.blocking_read(&mut p.PA0); + info!("data: {}", measured); + Timer::after_millis(500).await; + } +} diff --git a/examples/stm32g4/src/bin/adc_oversampling.rs b/examples/stm32g4/src/bin/adc_oversampling.rs new file mode 100644 index 000000000..d31eb20f8 --- /dev/null +++ b/examples/stm32g4/src/bin/adc_oversampling.rs @@ -0,0 +1,57 @@ +//! adc oversampling example +//! +//! This example uses adc oversampling to achieve 16bit data + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::adc::vals::{Rovsm, Trovs}; +use embassy_stm32::adc::{Adc, SampleTime}; +use embassy_stm32::Config; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.pll = Some(Pll { + source: PllSource::HSI, + prediv: PllPreDiv::DIV4, + mul: PllMul::MUL85, + divp: None, + divq: None, + // Main system clock at 170 MHz + divr: Some(PllRDiv::DIV2), + }); + config.rcc.mux.adc12sel = mux::Adcsel::SYS; + config.rcc.sys = Sysclk::PLL1_R; + } + let mut p = embassy_stm32::init(config); + + let mut adc = Adc::new(p.ADC1); + adc.set_sample_time(SampleTime::CYCLES6_5); + // From https://www.st.com/resource/en/reference_manual/rm0440-stm32g4-series-advanced-armbased-32bit-mcus-stmicroelectronics.pdf + // page652 Oversampler + // Table 172. Maximum output results vs N and M. Grayed values indicates truncation + // 0x00 oversampling ratio X2 + // 0x01 oversampling ratio X4 + // 0x02 oversampling ratio X8 + // 0x03 oversampling ratio X16 + // 0x04 oversampling ratio X32 + // 0x05 oversampling ratio X64 + // 0x06 oversampling ratio X128 + // 0x07 oversampling ratio X256 + adc.set_oversampling_ratio(0x03); // ratio X3 + adc.set_oversampling_shift(0b0000); // no shift + adc.enable_regular_oversampling_mode(Rovsm::RESUMED, Trovs::AUTOMATIC, true); + + loop { + let measured = adc.blocking_read(&mut p.PA0); + info!("data: 0x{:X}", measured); //max 0xFFF0 -> 65520 + Timer::after_millis(500).await; + } +} diff --git a/examples/stm32g4/src/bin/can.rs b/examples/stm32g4/src/bin/can.rs index 727921fba..90004f874 100644 --- a/examples/stm32g4/src/bin/can.rs +++ b/examples/stm32g4/src/bin/can.rs @@ -3,8 +3,10 @@ use defmt::*; use embassy_executor::Spawner; use embassy_stm32::peripherals::*; +use embassy_stm32::time::Hertz; use embassy_stm32::{bind_interrupts, can, Config}; use embassy_time::Timer; +use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { @@ -14,43 +16,219 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) { - let config = Config::default(); - + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.hse = Some(Hse { + freq: Hertz(24_000_000), + mode: HseMode::Oscillator, + }); + config.rcc.pll = Some(Pll { + source: PllSource::HSE, + prediv: PllPreDiv::DIV6, + mul: PllMul::MUL85, + divp: None, + divq: Some(PllQDiv::DIV8), // 42.5 Mhz for fdcan. + divr: Some(PllRDiv::DIV2), // Main system clock at 170 MHz + }); + config.rcc.mux.fdcansel = mux::Fdcansel::PLL1_Q; + config.rcc.sys = Sysclk::PLL1_R; + } let peripherals = embassy_stm32::init(config); - let mut can = can::Fdcan::new(peripherals.FDCAN1, peripherals.PA11, peripherals.PA12, Irqs); + let mut can = can::CanConfigurator::new(peripherals.FDCAN1, peripherals.PA11, peripherals.PA12, Irqs); + + can.properties().set_extended_filter( + can::filter::ExtendedFilterSlot::_0, + can::filter::ExtendedFilter::accept_all_into_fifo1(), + ); // 250k bps can.set_bitrate(250_000); + let use_fd = false; + + // 1M bps + if use_fd { + can.set_fd_data_bitrate(1_000_000, false); + } + info!("Configured"); - //let mut can = can.into_external_loopback_mode(); - let mut can = can.into_normal_mode(); + let mut can = can.start(match use_fd { + true => can::OperatingMode::InternalLoopbackMode, + false => can::OperatingMode::NormalOperationMode, + }); let mut i = 0; + let mut last_read_ts = embassy_time::Instant::now(); + loop { - let frame = can::TxFrame::new( - can::TxFrameHeader { - len: 1, - frame_format: can::FrameFormat::Standard, - id: can::StandardId::new(0x123).unwrap().into(), - bit_rate_switching: false, - marker: None, - }, - &[i], - ) - .unwrap(); + let frame = can::frame::Frame::new_extended(0x123456F, &[i; 8]).unwrap(); info!("Writing frame"); + _ = can.write(&frame).await; match can.read().await { - Ok(rx_frame) => info!("Rx: {}", rx_frame.data()[0]), + Ok(envelope) => { + let (ts, rx_frame) = (envelope.ts, envelope.frame); + let delta = (ts - last_read_ts).as_millis(); + last_read_ts = ts; + info!( + "Rx: {} {:02x} --- {}ms", + rx_frame.header().len(), + rx_frame.data()[0..rx_frame.header().len() as usize], + delta, + ) + } Err(_err) => error!("Error in frame"), } Timer::after_millis(250).await; i += 1; + if i > 2 { + break; + } + } + + // Use the FD API's even if we don't get FD packets. + + loop { + if use_fd { + let frame = can::frame::FdFrame::new_extended(0x123456F, &[i; 16]).unwrap(); + info!("Writing frame using FD API"); + _ = can.write_fd(&frame).await; + } else { + let frame = can::frame::FdFrame::new_extended(0x123456F, &[i; 8]).unwrap(); + info!("Writing frame using FD API"); + _ = can.write_fd(&frame).await; + } + + match can.read_fd().await { + Ok(envelope) => { + let (ts, rx_frame) = (envelope.ts, envelope.frame); + let delta = (ts - last_read_ts).as_millis(); + last_read_ts = ts; + info!( + "Rx: {} {:02x} --- using FD API {}ms", + rx_frame.header().len(), + rx_frame.data()[0..rx_frame.header().len() as usize], + delta, + ) + } + Err(_err) => error!("Error in frame"), + } + + Timer::after_millis(250).await; + + i += 1; + if i > 4 { + break; + } + } + i = 0; + let (mut tx, mut rx, _props) = can.split(); + // With split + loop { + let frame = can::frame::Frame::new_extended(0x123456F, &[i; 8]).unwrap(); + info!("Writing frame"); + _ = tx.write(&frame).await; + + match rx.read().await { + Ok(envelope) => { + let (ts, rx_frame) = (envelope.ts, envelope.frame); + let delta = (ts - last_read_ts).as_millis(); + last_read_ts = ts; + info!( + "Rx: {} {:02x} --- {}ms", + rx_frame.header().len(), + rx_frame.data()[0..rx_frame.header().len() as usize], + delta, + ) + } + Err(_err) => error!("Error in frame"), + } + + Timer::after_millis(250).await; + + i += 1; + + if i > 2 { + break; + } + } + + let can = can::Can::join(tx, rx); + + info!("\n\n\nBuffered\n"); + if use_fd { + static TX_BUF: StaticCell> = StaticCell::new(); + static RX_BUF: StaticCell> = StaticCell::new(); + let mut can = can.buffered_fd( + TX_BUF.init(can::TxFdBuf::<8>::new()), + RX_BUF.init(can::RxFdBuf::<10>::new()), + ); + loop { + let frame = can::frame::FdFrame::new_extended(0x123456F, &[i; 16]).unwrap(); + info!("Writing frame"); + + _ = can.write(frame).await; + + match can.read().await { + Ok(envelope) => { + let (ts, rx_frame) = (envelope.ts, envelope.frame); + let delta = (ts - last_read_ts).as_millis(); + last_read_ts = ts; + info!( + "Rx: {} {:02x} --- {}ms", + rx_frame.header().len(), + rx_frame.data()[0..rx_frame.header().len() as usize], + delta, + ) + } + Err(_err) => error!("Error in frame"), + } + + Timer::after_millis(250).await; + + i = i.wrapping_add(1); + } + } else { + static TX_BUF: StaticCell> = StaticCell::new(); + static RX_BUF: StaticCell> = StaticCell::new(); + let mut can = can.buffered( + TX_BUF.init(can::TxBuf::<8>::new()), + RX_BUF.init(can::RxBuf::<10>::new()), + ); + loop { + let frame = can::frame::Frame::new_extended(0x123456F, &[i; 8]).unwrap(); + info!("Writing frame"); + + // You can use any of these approaches to send. The writer makes it + // easy to share sending from multiple tasks. + //_ = can.write(frame).await; + //can.writer().try_write(frame).unwrap(); + can.writer().write(frame).await; + + match can.read().await { + Ok(envelope) => { + let (ts, rx_frame) = (envelope.ts, envelope.frame); + let delta = (ts - last_read_ts).as_millis(); + last_read_ts = ts; + info!( + "Rx: {} {:02x} --- {}ms", + rx_frame.header().len(), + rx_frame.data()[0..rx_frame.header().len() as usize], + delta, + ) + } + Err(_err) => error!("Error in frame"), + } + + Timer::after_millis(250).await; + + i = i.wrapping_add(1); + } } } diff --git a/examples/stm32g4/src/bin/pll.rs b/examples/stm32g4/src/bin/pll.rs index 46ebe0b0d..08ed95b34 100644 --- a/examples/stm32g4/src/bin/pll.rs +++ b/examples/stm32g4/src/bin/pll.rs @@ -3,7 +3,6 @@ use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::rcc::{ClockSrc, Pll, PllM, PllN, PllR, PllSource}; use embassy_stm32::Config; use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; @@ -11,19 +10,20 @@ use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut config = Config::default(); - - config.rcc.pll = Some(Pll { - source: PllSource::HSI, - prediv_m: PllM::DIV4, - mul_n: PllN::MUL85, - div_p: None, - div_q: None, - // Main system clock at 170 MHz - div_r: Some(PllR::DIV2), - }); - - config.rcc.mux = ClockSrc::PLL; - + { + use embassy_stm32::rcc::*; + config.rcc.hsi = true; + config.rcc.pll = Some(Pll { + source: PllSource::HSI, + prediv: PllPreDiv::DIV4, + mul: PllMul::MUL85, + divp: None, + divq: None, + // Main system clock at 170 MHz + divr: Some(PllRDiv::DIV2), + }); + config.rcc.sys = Sysclk::PLL1_R; + } let _p = embassy_stm32::init(config); info!("Hello World!"); diff --git a/examples/stm32g4/src/bin/pwm.rs b/examples/stm32g4/src/bin/pwm.rs index d4809a481..6c965012c 100644 --- a/examples/stm32g4/src/bin/pwm.rs +++ b/examples/stm32g4/src/bin/pwm.rs @@ -6,7 +6,6 @@ use embassy_executor::Spawner; use embassy_stm32::gpio::OutputType; use embassy_stm32::time::khz; use embassy_stm32::timer::simple_pwm::{PwmPin, SimplePwm}; -use embassy_stm32::timer::Channel; use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; @@ -15,22 +14,22 @@ async fn main(_spawner: Spawner) { let p = embassy_stm32::init(Default::default()); info!("Hello World!"); - let ch1 = PwmPin::new_ch1(p.PC0, OutputType::PushPull); - let mut pwm = SimplePwm::new(p.TIM1, Some(ch1), None, None, None, khz(10), Default::default()); - let max = pwm.get_max_duty(); - pwm.enable(Channel::Ch1); + let ch1_pin = PwmPin::new_ch1(p.PC0, OutputType::PushPull); + let mut pwm = SimplePwm::new(p.TIM1, Some(ch1_pin), None, None, None, khz(10), Default::default()); + let mut ch1 = pwm.ch1(); + ch1.enable(); info!("PWM initialized"); - info!("PWM max duty {}", max); + info!("PWM max duty {}", ch1.max_duty_cycle()); loop { - pwm.set_duty(Channel::Ch1, 0); + ch1.set_duty_cycle_fully_off(); Timer::after_millis(300).await; - pwm.set_duty(Channel::Ch1, max / 4); + ch1.set_duty_cycle_fraction(1, 4); Timer::after_millis(300).await; - pwm.set_duty(Channel::Ch1, max / 2); + ch1.set_duty_cycle_fraction(1, 2); Timer::after_millis(300).await; - pwm.set_duty(Channel::Ch1, max - 1); + ch1.set_duty_cycle(ch1.max_duty_cycle() - 1); Timer::after_millis(300).await; } } diff --git a/examples/stm32g4/src/bin/usb_c_pd.rs b/examples/stm32g4/src/bin/usb_c_pd.rs new file mode 100644 index 000000000..2e87d3931 --- /dev/null +++ b/examples/stm32g4/src/bin/usb_c_pd.rs @@ -0,0 +1,86 @@ +#![no_std] +#![no_main] + +use defmt::{error, info, Format}; +use embassy_executor::Spawner; +use embassy_stm32::ucpd::{self, CcPhy, CcPull, CcSel, CcVState, Ucpd}; +use embassy_stm32::{bind_interrupts, peripherals, Config}; +use embassy_time::{with_timeout, Duration}; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + UCPD1 => ucpd::InterruptHandler; +}); + +#[derive(Debug, Format)] +enum CableOrientation { + Normal, + Flipped, + DebugAccessoryMode, +} + +// Returns true when the cable +async fn wait_attached(cc_phy: &mut CcPhy<'_, T>) -> CableOrientation { + loop { + let (cc1, cc2) = cc_phy.vstate(); + if cc1 == CcVState::LOWEST && cc2 == CcVState::LOWEST { + // Detached, wait until attached by monitoring the CC lines. + cc_phy.wait_for_vstate_change().await; + continue; + } + + // Attached, wait for CC lines to be stable for tCCDebounce (100..200ms). + if with_timeout(Duration::from_millis(100), cc_phy.wait_for_vstate_change()) + .await + .is_ok() + { + // State has changed, restart detection procedure. + continue; + }; + + // State was stable for the complete debounce period, check orientation. + return match (cc1, cc2) { + (_, CcVState::LOWEST) => CableOrientation::Normal, // CC1 connected + (CcVState::LOWEST, _) => CableOrientation::Flipped, // CC2 connected + _ => CableOrientation::DebugAccessoryMode, // Both connected (special cable) + }; + } +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = Config::default(); + config.enable_ucpd1_dead_battery = true; + let p = embassy_stm32::init(config); + + info!("Hello World!"); + + let mut ucpd = Ucpd::new(p.UCPD1, Irqs {}, p.PB6, p.PB4, Default::default()); + ucpd.cc_phy().set_pull(CcPull::Sink); + + info!("Waiting for USB connection..."); + let cable_orientation = wait_attached(ucpd.cc_phy()).await; + info!("USB cable connected, orientation: {}", cable_orientation); + + let cc_sel = match cable_orientation { + CableOrientation::Normal => { + info!("Starting PD communication on CC1 pin"); + CcSel::CC1 + } + CableOrientation::Flipped => { + info!("Starting PD communication on CC2 pin"); + CcSel::CC2 + } + CableOrientation::DebugAccessoryMode => panic!("No PD communication in DAM"), + }; + let (_cc_phy, mut pd_phy) = ucpd.split_pd_phy(p.DMA1_CH1, p.DMA1_CH2, cc_sel); + + loop { + // Enough space for the longest non-extended data message. + let mut buf = [0_u8; 30]; + match pd_phy.receive(buf.as_mut()).await { + Ok(n) => info!("USB PD RX: {=[u8]:?}", &buf[..n]), + Err(e) => error!("USB PD RX: {}", e), + } + } +} diff --git a/examples/stm32g4/src/bin/usb_serial.rs b/examples/stm32g4/src/bin/usb_serial.rs index c26fa76b7..ed2ac7fac 100644 --- a/examples/stm32g4/src/bin/usb_serial.rs +++ b/examples/stm32g4/src/bin/usb_serial.rs @@ -3,14 +3,13 @@ use defmt::{panic, *}; use embassy_executor::Spawner; -use embassy_stm32::rcc::{Clock48MhzSrc, ClockSrc, Hsi48Config, Pll, PllM, PllN, PllQ, PllR, PllSource}; +use embassy_futures::join::join; use embassy_stm32::time::Hertz; use embassy_stm32::usb::{self, Driver, Instance}; use embassy_stm32::{bind_interrupts, peripherals, Config}; use embassy_usb::class::cdc_acm::{CdcAcmClass, State}; use embassy_usb::driver::EndpointError; use embassy_usb::Builder; -use futures::future::join; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { @@ -20,31 +19,27 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut config = Config::default(); - - // Change this to `false` to use the HSE clock source for the USB. This example assumes an 8MHz HSE. - const USE_HSI48: bool = true; - - let plldivq = if USE_HSI48 { None } else { Some(PllQ::DIV6) }; - - config.rcc.pll = Some(Pll { - source: PllSource::HSE(Hertz(8_000_000)), - prediv_m: PllM::DIV2, - mul_n: PllN::MUL72, - div_p: None, - div_q: plldivq, - // Main system clock at 144 MHz - div_r: Some(PllR::DIV2), - }); - - config.rcc.mux = ClockSrc::PLL; - - if USE_HSI48 { + { + use embassy_stm32::rcc::*; // Sets up the Clock Recovery System (CRS) to use the USB SOF to trim the HSI48 oscillator. - config.rcc.clock_48mhz_src = Some(Clock48MhzSrc::Hsi48(Hsi48Config { sync_from_usb: true })); - } else { - config.rcc.clock_48mhz_src = Some(Clock48MhzSrc::PllQ); + config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true }); + config.rcc.hse = Some(Hse { + freq: Hertz(8_000_000), + mode: HseMode::Oscillator, + }); + config.rcc.pll = Some(Pll { + source: PllSource::HSE, + prediv: PllPreDiv::DIV2, + mul: PllMul::MUL72, + divp: None, + divq: Some(PllQDiv::DIV6), // 48mhz + divr: Some(PllRDiv::DIV2), // Main system clock at 144 MHz + }); + config.rcc.sys = Sysclk::PLL1_R; + config.rcc.boost = true; // BOOST! + config.rcc.mux.clk48sel = mux::Clk48sel::HSI48; + //config.rcc.mux.clk48sel = mux::Clk48sel::PLL1_Q; // uncomment to use PLL1_Q instead. } - let p = embassy_stm32::init(config); info!("Hello World!"); @@ -61,7 +56,6 @@ async fn main(_spawner: Spawner) { config.device_protocol = 0x01; config.composite_with_iads = true; - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 64]; @@ -71,7 +65,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], // no msos descriptors diff --git a/examples/stm32h5/Cargo.toml b/examples/stm32h5/Cargo.toml index c9f08d24e..d1a865e4c 100644 --- a/examples/stm32h5/Cargo.toml +++ b/examples/stm32h5/Cargo.toml @@ -6,12 +6,13 @@ license = "MIT OR Apache-2.0" [dependencies] # Change stm32h563zi to your chip name, if necessary. -embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32h563zi", "memory-x", "time-driver-any", "exti", "unstable-pac"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32h563zi", "memory-x", "time-driver-any", "exti", "unstable-pac", "low-power"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", "proto-ipv6"] } -embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } defmt = "0.3" defmt-rtt = "0.4" @@ -22,9 +23,8 @@ embedded-hal = "0.2.6" embedded-hal-1 = { package = "embedded-hal", version = "1.0" } embedded-hal-async = { version = "1.0" } embedded-io-async = { version = "0.6.1" } -embedded-nal-async = { version = "0.7.1" } +embedded-nal-async = "0.8.0" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } rand_core = "0.6.3" critical-section = "1.1" diff --git a/examples/stm32h5/src/bin/can.rs b/examples/stm32h5/src/bin/can.rs index 2906d1576..194239d47 100644 --- a/examples/stm32h5/src/bin/can.rs +++ b/examples/stm32h5/src/bin/can.rs @@ -16,59 +16,83 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut config = Config::default(); - - // configure FDCAN to use PLL1_Q at 64 MHz - config.rcc.pll1 = Some(rcc::Pll { - source: rcc::PllSource::HSI, - prediv: rcc::PllPreDiv::DIV4, - mul: rcc::PllMul::MUL8, - divp: None, - divq: Some(rcc::PllDiv::DIV2), - divr: None, + config.rcc.hse = Some(rcc::Hse { + freq: embassy_stm32::time::Hertz(25_000_000), + mode: rcc::HseMode::Oscillator, }); - config.rcc.fdcan_clock_source = rcc::FdCanClockSource::PLL1_Q; + config.rcc.mux.fdcan12sel = rcc::mux::Fdcansel::HSE; let peripherals = embassy_stm32::init(config); - let mut can = can::Fdcan::new(peripherals.FDCAN1, peripherals.PA11, peripherals.PA12, Irqs); + let mut can = can::CanConfigurator::new(peripherals.FDCAN1, peripherals.PA11, peripherals.PA12, Irqs); - can.can.apply_config( - can::config::FdCanConfig::default().set_nominal_bit_timing(can::config::NominalBitTiming { - sync_jump_width: 1.try_into().unwrap(), - prescaler: 8.try_into().unwrap(), - seg1: 13.try_into().unwrap(), - seg2: 2.try_into().unwrap(), - }), - ); + // 250k bps + can.set_bitrate(250_000); - info!("Configured"); + //let mut can = can.into_internal_loopback_mode(); + let mut can = can.into_normal_mode(); - let mut can = can.into_external_loopback_mode(); - //let mut can = can.into_normal_mode(); + info!("CAN Configured"); let mut i = 0; + let mut last_read_ts = embassy_time::Instant::now(); + loop { - let frame = can::TxFrame::new( - can::TxFrameHeader { - len: 1, - frame_format: can::FrameFormat::Standard, - id: can::StandardId::new(0x123).unwrap().into(), - bit_rate_switching: false, - marker: None, - }, - &[i], - ) - .unwrap(); + let frame = can::frame::Frame::new_extended(0x123456F, &[i; 8]).unwrap(); info!("Writing frame"); _ = can.write(&frame).await; match can.read().await { - Ok(rx_frame) => info!("Rx: {}", rx_frame.data()[0]), + Ok(envelope) => { + let (rx_frame, ts) = envelope.parts(); + let delta = (ts - last_read_ts).as_millis(); + last_read_ts = ts; + info!( + "Rx: {:x} {:x} {:x} {:x} --- NEW {}", + rx_frame.data()[0], + rx_frame.data()[1], + rx_frame.data()[2], + rx_frame.data()[3], + delta, + ) + } Err(_err) => error!("Error in frame"), } Timer::after_millis(250).await; i += 1; + if i > 3 { + break; + } + } + + let (mut tx, mut rx, _props) = can.split(); + // With split + loop { + let frame = can::frame::Frame::new_extended(0x123456F, &[i; 8]).unwrap(); + info!("Writing frame"); + _ = tx.write(&frame).await; + + match rx.read().await { + Ok(envelope) => { + let (rx_frame, ts) = envelope.parts(); + let delta = (ts - last_read_ts).as_millis(); + last_read_ts = ts; + info!( + "Rx: {:x} {:x} {:x} {:x} --- NEW {}", + rx_frame.data()[0], + rx_frame.data()[1], + rx_frame.data()[2], + rx_frame.data()[3], + delta, + ) + } + Err(_err) => error!("Error in frame"), + } + + Timer::after_millis(250).await; + + i = i.wrapping_add(1); } } diff --git a/examples/stm32h5/src/bin/cordic.rs b/examples/stm32h5/src/bin/cordic.rs new file mode 100644 index 000000000..73e873574 --- /dev/null +++ b/examples/stm32h5/src/bin/cordic.rs @@ -0,0 +1,78 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::cordic::{self, utils}; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut dp = embassy_stm32::init(Default::default()); + + let mut cordic = cordic::Cordic::new( + &mut dp.CORDIC, + unwrap!(cordic::Config::new( + cordic::Function::Sin, + Default::default(), + Default::default(), + )), + ); + + // for output buf, the length is not that strict, larger than minimal required is ok. + let mut output_f64 = [0f64; 19]; + let mut output_u32 = [0u32; 21]; + + // tips: + // CORDIC peripheral has some strict on input value, you can also use ".check_argX_fXX()" methods + // to make sure your input values are compatible with current CORDIC setup. + let arg1 = [-1.0, -0.5, 0.0, 0.5, 1.0]; // for trigonometric function, the ARG1 value [-pi, pi] should be map to [-1, 1] + let arg2 = [0.5]; // and for Sin function, ARG2 should be in [0, 1] + + let mut input_buf = [0u32; 9]; + + // convert input from floating point to fixed point + input_buf[0] = unwrap!(utils::f64_to_q1_31(arg1[0])); + input_buf[1] = unwrap!(utils::f64_to_q1_31(arg2[0])); + + // If input length is small, blocking mode can be used to minimize overhead. + let cnt0 = unwrap!(cordic.blocking_calc_32bit( + &input_buf[..2], // input length is strict, since driver use its length to detect calculation count + &mut output_u32, + false, + false + )); + + // convert result from fixed point into floating point + for (&u32_val, f64_val) in output_u32[..cnt0].iter().zip(output_f64.iter_mut()) { + *f64_val = utils::q1_31_to_f64(u32_val); + } + + // convert input from floating point to fixed point + // + // first value from arg1 is used, so truncate to arg1[1..] + for (&f64_val, u32_val) in arg1[1..].iter().zip(input_buf.iter_mut()) { + *u32_val = unwrap!(utils::f64_to_q1_31(f64_val)); + } + + // If calculation is a little longer, async mode can make use of DMA, and let core do some other stuff. + let cnt1 = unwrap!( + cordic + .async_calc_32bit( + &mut dp.GPDMA1_CH0, + &mut dp.GPDMA1_CH1, + &input_buf[..arg1.len() - 1], // limit input buf to its actual length + &mut output_u32, + true, + false + ) + .await + ); + + // convert result from fixed point into floating point + for (&u32_val, f64_val) in output_u32[..cnt1].iter().zip(output_f64[cnt0..cnt0 + cnt1].iter_mut()) { + *f64_val = utils::q1_31_to_f64(u32_val); + } + + println!("result: {}", output_f64[..cnt0 + cnt1]); +} diff --git a/examples/stm32h5/src/bin/eth.rs b/examples/stm32h5/src/bin/eth.rs index 2370656e6..eee1632f5 100644 --- a/examples/stm32h5/src/bin/eth.rs +++ b/examples/stm32h5/src/bin/eth.rs @@ -4,7 +4,7 @@ use defmt::*; use embassy_executor::Spawner; use embassy_net::tcp::TcpSocket; -use embassy_net::{Ipv4Address, Stack, StackResources}; +use embassy_net::{Ipv4Address, StackResources}; use embassy_stm32::eth::generic_smi::GenericSMI; use embassy_stm32::eth::{Ethernet, PacketQueue}; use embassy_stm32::peripherals::ETH; @@ -28,8 +28,8 @@ bind_interrupts!(struct Irqs { type Device = Ethernet<'static, ETH, GenericSMI>; #[embassy_executor::task] -async fn net_task(stack: &'static Stack) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -92,17 +92,11 @@ async fn main(spawner: Spawner) -> ! { //}); // Init network stack - static STACK: StaticCell> = StaticCell::new(); - static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<2>::new()), - seed, - )); + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); // Launch network task - unwrap!(spawner.spawn(net_task(&stack))); + unwrap!(spawner.spawn(net_task(runner))); // Ensure DHCP configuration is up before trying connect stack.wait_config_up().await; @@ -114,7 +108,7 @@ async fn main(spawner: Spawner) -> ! { let mut tx_buffer = [0; 1024]; loop { - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); + let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer); socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); diff --git a/examples/stm32h5/src/bin/stop.rs b/examples/stm32h5/src/bin/stop.rs new file mode 100644 index 000000000..0d14c0668 --- /dev/null +++ b/examples/stm32h5/src/bin/stop.rs @@ -0,0 +1,71 @@ +// Notice: +// the MCU might need an extra reset to make the code actually running + +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{AnyPin, Level, Output, Speed}; +use embassy_stm32::low_power::Executor; +use embassy_stm32::rcc::{HSIPrescaler, LsConfig}; +use embassy_stm32::rtc::{Rtc, RtcConfig}; +use embassy_stm32::Config; +use embassy_time::Timer; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[cortex_m_rt::entry] +fn main() -> ! { + Executor::take().run(|spawner| { + unwrap!(spawner.spawn(async_main(spawner))); + }) +} + +#[embassy_executor::task] +async fn async_main(spawner: Spawner) { + defmt::info!("Program Start"); + + let mut config = Config::default(); + + // System Clock seems need to be equal or lower than 16 MHz + config.rcc.hsi = Some(HSIPrescaler::DIV4); + + config.rcc.ls = LsConfig::default_lsi(); + // when enabled the power-consumption is much higher during stop, but debugging and RTT is working + // if you wan't to measure the power-consumption, or for production: uncomment this line + // config.enable_debug_during_sleep = false; + let p = embassy_stm32::init(config); + + // give the RTC to the executor... + let rtc = Rtc::new(p.RTC, RtcConfig::default()); + static RTC: StaticCell = StaticCell::new(); + let rtc = RTC.init(rtc); + embassy_stm32::low_power::stop_with_rtc(rtc); + + unwrap!(spawner.spawn(blinky(p.PB4.into()))); + unwrap!(spawner.spawn(timeout())); +} + +#[embassy_executor::task] +async fn blinky(led: AnyPin) { + let mut led = Output::new(led, Level::Low, Speed::Low); + loop { + info!("high"); + led.set_high(); + Timer::after_millis(300).await; + + info!("low"); + led.set_low(); + Timer::after_millis(300).await; + } +} + +// when enable_debug_during_sleep is false, it is more difficult to reprogram the MCU +// therefore we block the MCU after 30s to be able to reprogram it easily +#[embassy_executor::task] +async fn timeout() -> ! { + Timer::after_secs(30).await; + #[allow(clippy::empty_loop)] + loop {} +} diff --git a/examples/stm32h5/src/bin/usart.rs b/examples/stm32h5/src/bin/usart.rs index f9cbad6af..cc49c2fdb 100644 --- a/examples/stm32h5/src/bin/usart.rs +++ b/examples/stm32h5/src/bin/usart.rs @@ -4,22 +4,16 @@ use cortex_m_rt::entry; use defmt::*; use embassy_executor::Executor; -use embassy_stm32::dma::NoDma; use embassy_stm32::usart::{Config, Uart}; -use embassy_stm32::{bind_interrupts, peripherals, usart}; use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _}; -bind_interrupts!(struct Irqs { - UART7 => usart::InterruptHandler; -}); - #[embassy_executor::task] async fn main_task() { let p = embassy_stm32::init(Default::default()); let config = Config::default(); - let mut usart = Uart::new(p.UART7, p.PF6, p.PF7, Irqs, NoDma, NoDma, config).unwrap(); + let mut usart = Uart::new_blocking(p.UART7, p.PF6, p.PF7, config).unwrap(); unwrap!(usart.blocking_write(b"Hello Embassy World!\r\n")); info!("wrote Hello, starting echo"); diff --git a/examples/stm32h5/src/bin/usart_dma.rs b/examples/stm32h5/src/bin/usart_dma.rs index caae0dd18..c644e84bd 100644 --- a/examples/stm32h5/src/bin/usart_dma.rs +++ b/examples/stm32h5/src/bin/usart_dma.rs @@ -6,7 +6,6 @@ use core::fmt::Write; use cortex_m_rt::entry; use defmt::*; use embassy_executor::Executor; -use embassy_stm32::dma::NoDma; use embassy_stm32::usart::{Config, Uart}; use embassy_stm32::{bind_interrupts, peripherals, usart}; use heapless::String; @@ -22,7 +21,7 @@ async fn main_task() { let p = embassy_stm32::init(Default::default()); let config = Config::default(); - let mut usart = Uart::new(p.UART7, p.PF6, p.PF7, Irqs, p.GPDMA1_CH0, NoDma, config).unwrap(); + let mut usart = Uart::new(p.UART7, p.PF6, p.PF7, Irqs, p.GPDMA1_CH0, p.GPDMA1_CH1, config).unwrap(); for n in 0u32.. { let mut s: String<128> = String::new(); diff --git a/examples/stm32h5/src/bin/usart_split.rs b/examples/stm32h5/src/bin/usart_split.rs index 92047de8d..d26c5003c 100644 --- a/examples/stm32h5/src/bin/usart_split.rs +++ b/examples/stm32h5/src/bin/usart_split.rs @@ -3,8 +3,7 @@ use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::dma::NoDma; -use embassy_stm32::peripherals::{GPDMA1_CH1, UART7}; +use embassy_stm32::mode::Async; use embassy_stm32::usart::{Config, Uart, UartRx}; use embassy_stm32::{bind_interrupts, peripherals, usart}; use embassy_sync::blocking_mutex::raw::ThreadModeRawMutex; @@ -15,18 +14,6 @@ bind_interrupts!(struct Irqs { UART7 => usart::InterruptHandler; }); -#[embassy_executor::task] -async fn writer(mut usart: Uart<'static, UART7, NoDma, NoDma>) { - unwrap!(usart.blocking_write(b"Hello Embassy World!\r\n")); - info!("wrote Hello, starting echo"); - - let mut buf = [0u8; 1]; - loop { - unwrap!(usart.blocking_read(&mut buf)); - unwrap!(usart.blocking_write(&buf)); - } -} - static CHANNEL: Channel = Channel::new(); #[embassy_executor::main] @@ -50,7 +37,7 @@ async fn main(spawner: Spawner) -> ! { } #[embassy_executor::task] -async fn reader(mut rx: UartRx<'static, UART7, GPDMA1_CH1>) { +async fn reader(mut rx: UartRx<'static, Async>) { let mut buf = [0; 8]; loop { info!("reading..."); diff --git a/examples/stm32h5/src/bin/usb_serial.rs b/examples/stm32h5/src/bin/usb_serial.rs index 208493d8c..fbcbdb5f9 100644 --- a/examples/stm32h5/src/bin/usb_serial.rs +++ b/examples/stm32h5/src/bin/usb_serial.rs @@ -3,13 +3,13 @@ use defmt::{panic, *}; use embassy_executor::Spawner; +use embassy_futures::join::join; use embassy_stm32::time::Hertz; use embassy_stm32::usb::{Driver, Instance}; -use embassy_stm32::{bind_interrupts, pac, peripherals, usb, Config}; +use embassy_stm32::{bind_interrupts, peripherals, usb, Config}; use embassy_usb::class::cdc_acm::{CdcAcmClass, State}; use embassy_usb::driver::EndpointError; use embassy_usb::Builder; -use futures::future::join; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { @@ -41,15 +41,12 @@ async fn main(_spawner: Spawner) { config.rcc.apb3_pre = APBPrescaler::DIV4; config.rcc.sys = Sysclk::PLL1_P; config.rcc.voltage_scale = VoltageScale::Scale0; + config.rcc.mux.usbsel = mux::Usbsel::HSI48; } let p = embassy_stm32::init(config); info!("Hello World!"); - pac::RCC.ccipr4().write(|w| { - w.set_usbsel(pac::rcc::vals::Usbsel::HSI48); - }); - // Create the driver, from the HAL. let driver = Driver::new(p.USB, Irqs, p.PA12, p.PA11); @@ -68,7 +65,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 64]; @@ -78,7 +74,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], // no msos descriptors diff --git a/examples/stm32h7/Cargo.toml b/examples/stm32h7/Cargo.toml index d9ea2626d..1ba792f72 100644 --- a/examples/stm32h7/Cargo.toml +++ b/examples/stm32h7/Cargo.toml @@ -6,12 +6,14 @@ license = "MIT OR Apache-2.0" [dependencies] # Change stm32h743bi to your chip name, if necessary. -embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32h743bi", "time-driver-any", "exti", "memory-x", "unstable-pac", "chrono"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32h743bi", "time-driver-tim2", "exti", "memory-x", "unstable-pac", "chrono"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-embedded-hal = { version = "0.2.0", path = "../../embassy-embedded-hal" } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", "proto-ipv6", "dns"] } -embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } defmt = "0.3" defmt-rtt = "0.4" @@ -21,10 +23,9 @@ cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" embedded-hal-1 = { package = "embedded-hal", version = "1.0" } embedded-hal-async = { version = "1.0" } -embedded-nal-async = { version = "0.7.1" } +embedded-nal-async = "0.8.0" embedded-io-async = { version = "0.6.1" } panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } rand_core = "0.6.3" critical-section = "1.1" @@ -33,6 +34,7 @@ stm32-fmc = "0.3.0" embedded-storage = "0.3.1" static_cell = "2" chrono = { version = "^0.4", default-features = false } +grounded = "0.2.0" # cargo build/run [profile.dev] diff --git a/examples/stm32h7/build.rs b/examples/stm32h7/build.rs index 8cd32d7ed..30691aa97 100644 --- a/examples/stm32h7/build.rs +++ b/examples/stm32h7/build.rs @@ -1,4 +1,34 @@ +//! This build script copies the `memory.x` file from the crate root into +//! a directory where the linker can always find it at build time. +//! For many projects this is optional, as the linker always searches the +//! project root directory -- wherever `Cargo.toml` is. However, if you +//! are using a workspace or have a more complicated build setup, this +//! build script becomes required. Additionally, by requesting that +//! Cargo re-run the build script whenever `memory.x` is changed, +//! updating `memory.x` ensures a rebuild of the application with the +//! new memory settings. + +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; + fn main() { + // Put `memory.x` in our output directory and ensure it's + // on the linker search path. + let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); + File::create(out.join("memory.x")) + .unwrap() + .write_all(include_bytes!("memory.x")) + .unwrap(); + println!("cargo:rustc-link-search={}", out.display()); + + // By default, Cargo will re-run a build script whenever + // any file in the project changes. By specifying `memory.x` + // here, we ensure the build script is only re-run when + // `memory.x` is changed. + println!("cargo:rerun-if-changed=memory.x"); + println!("cargo:rustc-link-arg-bins=--nmagic"); println!("cargo:rustc-link-arg-bins=-Tlink.x"); println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); diff --git a/examples/stm32h7/memory.x b/examples/stm32h7/memory.x new file mode 100644 index 000000000..e5ab1f62c --- /dev/null +++ b/examples/stm32h7/memory.x @@ -0,0 +1,14 @@ +MEMORY +{ + FLASH : ORIGIN = 0x08000000, LENGTH = 2048K /* BANK_1 + BANK_2 */ + RAM : ORIGIN = 0x24000000, LENGTH = 512K /* SRAM */ + RAM_D3 : ORIGIN = 0x38000000, LENGTH = 64K /* SRAM4 */ +} + +SECTIONS +{ + .ram_d3 : + { + *(.ram_d3) + } > RAM_D3 +} \ No newline at end of file diff --git a/examples/stm32h7/src/bin/adc.rs b/examples/stm32h7/src/bin/adc.rs index fe6fe69a1..98504ddf6 100644 --- a/examples/stm32h7/src/bin/adc.rs +++ b/examples/stm32h7/src/bin/adc.rs @@ -5,7 +5,7 @@ use defmt::*; use embassy_executor::Spawner; use embassy_stm32::adc::{Adc, SampleTime}; use embassy_stm32::Config; -use embassy_time::{Delay, Timer}; +use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] @@ -38,22 +38,22 @@ async fn main(_spawner: Spawner) { config.rcc.apb3_pre = APBPrescaler::DIV2; // 100 Mhz config.rcc.apb4_pre = APBPrescaler::DIV2; // 100 Mhz config.rcc.voltage_scale = VoltageScale::Scale1; - config.rcc.adc_clock_source = AdcClockSource::PLL2_P; + config.rcc.mux.adcsel = mux::Adcsel::PLL2_P; } let mut p = embassy_stm32::init(config); info!("Hello World!"); - let mut adc = Adc::new(p.ADC3, &mut Delay); + let mut adc = Adc::new(p.ADC3); - adc.set_sample_time(SampleTime::Cycles32_5); + adc.set_sample_time(SampleTime::CYCLES32_5); let mut vrefint_channel = adc.enable_vrefint(); loop { - let vrefint = adc.read_internal(&mut vrefint_channel); + let vrefint = adc.blocking_read(&mut vrefint_channel); info!("vrefint: {}", vrefint); - let measured = adc.read(&mut p.PC0); + let measured = adc.blocking_read(&mut p.PC0); info!("measured: {}", measured); Timer::after_millis(500).await; } diff --git a/examples/stm32h7/src/bin/adc_dma.rs b/examples/stm32h7/src/bin/adc_dma.rs new file mode 100644 index 000000000..0b905d227 --- /dev/null +++ b/examples/stm32h7/src/bin/adc_dma.rs @@ -0,0 +1,76 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::adc::{Adc, AdcChannel as _, SampleTime}; +use embassy_stm32::Config; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".ram_d3"] +static mut DMA_BUF: [u16; 2] = [0; 2]; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut read_buffer = unsafe { &mut DMA_BUF[..] }; + + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.hsi = Some(HSIPrescaler::DIV1); + config.rcc.csi = true; + config.rcc.pll1 = Some(Pll { + source: PllSource::HSI, + prediv: PllPreDiv::DIV4, + mul: PllMul::MUL50, + divp: Some(PllDiv::DIV2), + divq: Some(PllDiv::DIV8), // SPI1 cksel defaults to pll1_q + divr: None, + }); + config.rcc.pll2 = Some(Pll { + source: PllSource::HSI, + prediv: PllPreDiv::DIV4, + mul: PllMul::MUL50, + divp: Some(PllDiv::DIV8), // 100mhz + divq: None, + divr: None, + }); + config.rcc.sys = Sysclk::PLL1_P; // 400 Mhz + config.rcc.ahb_pre = AHBPrescaler::DIV2; // 200 Mhz + config.rcc.apb1_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.apb2_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.apb3_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.apb4_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.voltage_scale = VoltageScale::Scale1; + config.rcc.mux.adcsel = mux::Adcsel::PLL2_P; + } + let p = embassy_stm32::init(config); + + info!("Hello World!"); + + let mut adc = Adc::new(p.ADC3); + + let mut dma = p.DMA1_CH1; + let mut vrefint_channel = adc.enable_vrefint().degrade_adc(); + let mut pc0 = p.PC0.degrade_adc(); + + loop { + adc.read( + &mut dma, + [ + (&mut vrefint_channel, SampleTime::CYCLES387_5), + (&mut pc0, SampleTime::CYCLES810_5), + ] + .into_iter(), + &mut read_buffer, + ) + .await; + + let vrefint = read_buffer[0]; + let measured = read_buffer[1]; + info!("vrefint: {}", vrefint); + info!("measured: {}", measured); + Timer::after_millis(500).await; + } +} diff --git a/examples/stm32h7/src/bin/camera.rs b/examples/stm32h7/src/bin/camera.rs index e5a104baf..170a5aa28 100644 --- a/examples/stm32h7/src/bin/camera.rs +++ b/examples/stm32h7/src/bin/camera.rs @@ -78,9 +78,9 @@ async fn main(_spawner: Spawner) { ); defmt::info!("attempting capture"); - defmt::unwrap!(dcmi.capture(unsafe { &mut FRAME }).await); + defmt::unwrap!(dcmi.capture(unsafe { &mut *core::ptr::addr_of_mut!(FRAME) }).await); - defmt::info!("captured frame: {:x}", unsafe { &FRAME }); + defmt::info!("captured frame: {:x}", unsafe { &*core::ptr::addr_of!(FRAME) }); defmt::info!("main loop running"); loop { diff --git a/examples/stm32h7/src/bin/can.rs b/examples/stm32h7/src/bin/can.rs index 2906d1576..0af11ef3e 100644 --- a/examples/stm32h7/src/bin/can.rs +++ b/examples/stm32h7/src/bin/can.rs @@ -16,59 +16,83 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut config = Config::default(); - - // configure FDCAN to use PLL1_Q at 64 MHz - config.rcc.pll1 = Some(rcc::Pll { - source: rcc::PllSource::HSI, - prediv: rcc::PllPreDiv::DIV4, - mul: rcc::PllMul::MUL8, - divp: None, - divq: Some(rcc::PllDiv::DIV2), - divr: None, + config.rcc.hse = Some(rcc::Hse { + freq: embassy_stm32::time::Hertz(25_000_000), + mode: rcc::HseMode::Oscillator, }); - config.rcc.fdcan_clock_source = rcc::FdCanClockSource::PLL1_Q; + config.rcc.mux.fdcansel = rcc::mux::Fdcansel::HSE; let peripherals = embassy_stm32::init(config); - let mut can = can::Fdcan::new(peripherals.FDCAN1, peripherals.PA11, peripherals.PA12, Irqs); + let mut can = can::CanConfigurator::new(peripherals.FDCAN1, peripherals.PA11, peripherals.PA12, Irqs); - can.can.apply_config( - can::config::FdCanConfig::default().set_nominal_bit_timing(can::config::NominalBitTiming { - sync_jump_width: 1.try_into().unwrap(), - prescaler: 8.try_into().unwrap(), - seg1: 13.try_into().unwrap(), - seg2: 2.try_into().unwrap(), - }), - ); + // 250k bps + can.set_bitrate(250_000); - info!("Configured"); + //let mut can = can.into_internal_loopback_mode(); + let mut can = can.into_normal_mode(); - let mut can = can.into_external_loopback_mode(); - //let mut can = can.into_normal_mode(); + info!("CAN Configured"); let mut i = 0; + let mut last_read_ts = embassy_time::Instant::now(); + loop { - let frame = can::TxFrame::new( - can::TxFrameHeader { - len: 1, - frame_format: can::FrameFormat::Standard, - id: can::StandardId::new(0x123).unwrap().into(), - bit_rate_switching: false, - marker: None, - }, - &[i], - ) - .unwrap(); + let frame = can::frame::Frame::new_extended(0x123456F, &[i; 8]).unwrap(); info!("Writing frame"); _ = can.write(&frame).await; match can.read().await { - Ok(rx_frame) => info!("Rx: {}", rx_frame.data()[0]), + Ok(envelope) => { + let (rx_frame, ts) = envelope.parts(); + let delta = (ts - last_read_ts).as_millis(); + last_read_ts = ts; + info!( + "Rx: {:x} {:x} {:x} {:x} --- NEW {}", + rx_frame.data()[0], + rx_frame.data()[1], + rx_frame.data()[2], + rx_frame.data()[3], + delta, + ) + } Err(_err) => error!("Error in frame"), } Timer::after_millis(250).await; i += 1; + if i > 3 { + break; + } + } + + let (mut tx, mut rx, _props) = can.split(); + // With split + loop { + let frame = can::frame::Frame::new_extended(0x123456F, &[i; 8]).unwrap(); + info!("Writing frame"); + _ = tx.write(&frame).await; + + match rx.read().await { + Ok(envelope) => { + let (rx_frame, ts) = envelope.parts(); + let delta = (ts - last_read_ts).as_millis(); + last_read_ts = ts; + info!( + "Rx: {:x} {:x} {:x} {:x} --- NEW {}", + rx_frame.data()[0], + rx_frame.data()[1], + rx_frame.data()[2], + rx_frame.data()[3], + delta, + ) + } + Err(_err) => error!("Error in frame"), + } + + Timer::after_millis(250).await; + + i = i.wrapping_add(1); } } diff --git a/examples/stm32h7/src/bin/dac.rs b/examples/stm32h7/src/bin/dac.rs index a9bf46de0..a6f969aba 100644 --- a/examples/stm32h7/src/bin/dac.rs +++ b/examples/stm32h7/src/bin/dac.rs @@ -40,7 +40,7 @@ fn main() -> ! { config.rcc.apb3_pre = APBPrescaler::DIV2; // 100 Mhz config.rcc.apb4_pre = APBPrescaler::DIV2; // 100 Mhz config.rcc.voltage_scale = VoltageScale::Scale1; - config.rcc.adc_clock_source = AdcClockSource::PLL2_P; + config.rcc.mux.adcsel = mux::Adcsel::PLL2_P; } let p = embassy_stm32::init(config); diff --git a/examples/stm32h7/src/bin/dac_dma.rs b/examples/stm32h7/src/bin/dac_dma.rs index 8e5c41a43..3a9887e3c 100644 --- a/examples/stm32h7/src/bin/dac_dma.rs +++ b/examples/stm32h7/src/bin/dac_dma.rs @@ -6,9 +6,9 @@ use embassy_executor::Spawner; use embassy_stm32::dac::{DacCh1, DacCh2, ValueArray}; use embassy_stm32::pac::timer::vals::Mms; use embassy_stm32::peripherals::{DAC1, DMA1_CH3, DMA1_CH4, TIM6, TIM7}; -use embassy_stm32::rcc::low_level::RccPeripheral; +use embassy_stm32::rcc::frequency; use embassy_stm32::time::Hertz; -use embassy_stm32::timer::low_level::Basic16bitInstance; +use embassy_stm32::timer::low_level::Timer; use micromath::F32Ext; use {defmt_rtt as _, panic_probe as _}; @@ -42,7 +42,7 @@ async fn main(spawner: Spawner) { config.rcc.apb3_pre = APBPrescaler::DIV2; // 100 Mhz config.rcc.apb4_pre = APBPrescaler::DIV2; // 100 Mhz config.rcc.voltage_scale = VoltageScale::Scale1; - config.rcc.adc_clock_source = AdcClockSource::PLL2_P; + config.rcc.mux.adcsel = mux::Adcsel::PLL2_P; } // Initialize the board and obtain a Peripherals instance @@ -51,19 +51,19 @@ async fn main(spawner: Spawner) { // Obtain two independent channels (p.DAC1 can only be consumed once, though!) let (dac_ch1, dac_ch2) = embassy_stm32::dac::Dac::new(p.DAC1, p.DMA1_CH3, p.DMA1_CH4, p.PA4, p.PA5).split(); - spawner.spawn(dac_task1(dac_ch1)).ok(); - spawner.spawn(dac_task2(dac_ch2)).ok(); + spawner.spawn(dac_task1(p.TIM6, dac_ch1)).ok(); + spawner.spawn(dac_task2(p.TIM7, dac_ch2)).ok(); } #[embassy_executor::task] -async fn dac_task1(mut dac: DacCh1<'static, DAC1, DMA1_CH3>) { +async fn dac_task1(tim: TIM6, mut dac: DacCh1<'static, DAC1, DMA1_CH3>) { let data: &[u8; 256] = &calculate_array::<256>(); - info!("TIM6 frequency is {}", TIM6::frequency()); + info!("TIM6 frequency is {}", frequency::()); const FREQUENCY: Hertz = Hertz::hz(200); // Compute the reload value such that we obtain the FREQUENCY for the sine - let reload: u32 = (TIM6::frequency().0 / FREQUENCY.0) / data.len() as u32; + let reload: u32 = (frequency::().0 / FREQUENCY.0) / data.len() as u32; // Depends on your clock and on the specific chip used, you may need higher or lower values here if reload < 10 { @@ -74,17 +74,17 @@ async fn dac_task1(mut dac: DacCh1<'static, DAC1, DMA1_CH3>) { dac.set_triggering(true); dac.enable(); - TIM6::enable_and_reset(); - TIM6::regs().arr().modify(|w| w.set_arr(reload as u16 - 1)); - TIM6::regs().cr2().modify(|w| w.set_mms(Mms::UPDATE)); - TIM6::regs().cr1().modify(|w| { + let tim = Timer::new(tim); + tim.regs_basic().arr().modify(|w| w.set_arr(reload as u16 - 1)); + tim.regs_basic().cr2().modify(|w| w.set_mms(Mms::UPDATE)); + tim.regs_basic().cr1().modify(|w| { w.set_opm(false); w.set_cen(true); }); debug!( "TIM6 Frequency {}, Target Frequency {}, Reload {}, Reload as u16 {}, Samples {}", - TIM6::frequency(), + frequency::(), FREQUENCY, reload, reload as u16, @@ -99,22 +99,22 @@ async fn dac_task1(mut dac: DacCh1<'static, DAC1, DMA1_CH3>) { } #[embassy_executor::task] -async fn dac_task2(mut dac: DacCh2<'static, DAC1, DMA1_CH4>) { +async fn dac_task2(tim: TIM7, mut dac: DacCh2<'static, DAC1, DMA1_CH4>) { let data: &[u8; 256] = &calculate_array::<256>(); - info!("TIM7 frequency is {}", TIM7::frequency()); + info!("TIM7 frequency is {}", frequency::()); const FREQUENCY: Hertz = Hertz::hz(600); - let reload: u32 = (TIM7::frequency().0 / FREQUENCY.0) / data.len() as u32; + let reload: u32 = (frequency::().0 / FREQUENCY.0) / data.len() as u32; if reload < 10 { error!("Reload value {} below threshold!", reload); } - TIM7::enable_and_reset(); - TIM7::regs().arr().modify(|w| w.set_arr(reload as u16 - 1)); - TIM7::regs().cr2().modify(|w| w.set_mms(Mms::UPDATE)); - TIM7::regs().cr1().modify(|w| { + let tim = Timer::new(tim); + tim.regs_basic().arr().modify(|w| w.set_arr(reload as u16 - 1)); + tim.regs_basic().cr2().modify(|w| w.set_mms(Mms::UPDATE)); + tim.regs_basic().cr1().modify(|w| { w.set_opm(false); w.set_cen(true); }); @@ -125,7 +125,7 @@ async fn dac_task2(mut dac: DacCh2<'static, DAC1, DMA1_CH4>) { debug!( "TIM7 Frequency {}, Target Frequency {}, Reload {}, Reload as u16 {}, Samples {}", - TIM7::frequency(), + frequency::(), FREQUENCY, reload, reload as u16, diff --git a/examples/stm32h7/src/bin/eth.rs b/examples/stm32h7/src/bin/eth.rs index cd9a27fcd..ec3f2c000 100644 --- a/examples/stm32h7/src/bin/eth.rs +++ b/examples/stm32h7/src/bin/eth.rs @@ -4,7 +4,7 @@ use defmt::*; use embassy_executor::Spawner; use embassy_net::tcp::TcpSocket; -use embassy_net::{Ipv4Address, Stack, StackResources}; +use embassy_net::{Ipv4Address, StackResources}; use embassy_stm32::eth::generic_smi::GenericSMI; use embassy_stm32::eth::{Ethernet, PacketQueue}; use embassy_stm32::peripherals::ETH; @@ -24,8 +24,8 @@ bind_interrupts!(struct Irqs { type Device = Ethernet<'static, ETH, GenericSMI>; #[embassy_executor::task] -async fn net_task(stack: &'static Stack) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -64,19 +64,21 @@ async fn main(spawner: Spawner) -> ! { let mac_addr = [0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF]; static PACKETS: StaticCell> = StaticCell::new(); + // warning: Not all STM32H7 devices have the exact same pins here + // for STM32H747XIH, replace p.PB13 for PG12 let device = Ethernet::new( PACKETS.init(PacketQueue::<4, 4>::new()), p.ETH, Irqs, - p.PA1, - p.PA2, - p.PC1, - p.PA7, - p.PC4, - p.PC5, - p.PG13, - p.PB13, - p.PG11, + p.PA1, // ref_clk + p.PA2, // mdio + p.PC1, // eth_mdc + p.PA7, // CRS_DV: Carrier Sense + p.PC4, // RX_D0: Received Bit 0 + p.PC5, // RX_D1: Received Bit 1 + p.PG13, // TX_D0: Transmit Bit 0 + p.PB13, // TX_D1: Transmit Bit 1 + p.PG11, // TX_EN: Transmit Enable GenericSMI::new(0), mac_addr, ); @@ -89,17 +91,11 @@ async fn main(spawner: Spawner) -> ! { //}); // Init network stack - static STACK: StaticCell> = StaticCell::new(); static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<3>::new()), - seed, - )); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); // Launch network task - unwrap!(spawner.spawn(net_task(&stack))); + unwrap!(spawner.spawn(net_task(runner))); // Ensure DHCP configuration is up before trying connect stack.wait_config_up().await; @@ -111,7 +107,7 @@ async fn main(spawner: Spawner) -> ! { let mut tx_buffer = [0; 1024]; loop { - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); + let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer); socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); diff --git a/examples/stm32h7/src/bin/eth_client.rs b/examples/stm32h7/src/bin/eth_client.rs index aeb169e19..a1558b079 100644 --- a/examples/stm32h7/src/bin/eth_client.rs +++ b/examples/stm32h7/src/bin/eth_client.rs @@ -1,10 +1,12 @@ #![no_std] #![no_main] +use core::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; + use defmt::*; use embassy_executor::Spawner; use embassy_net::tcp::client::{TcpClient, TcpClientState}; -use embassy_net::{Stack, StackResources}; +use embassy_net::StackResources; use embassy_stm32::eth::generic_smi::GenericSMI; use embassy_stm32::eth::{Ethernet, PacketQueue}; use embassy_stm32::peripherals::ETH; @@ -12,7 +14,7 @@ use embassy_stm32::rng::Rng; use embassy_stm32::{bind_interrupts, eth, peripherals, rng, Config}; use embassy_time::Timer; use embedded_io_async::Write; -use embedded_nal_async::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpConnect}; +use embedded_nal_async::TcpConnect; use rand_core::RngCore; use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _}; @@ -25,8 +27,8 @@ bind_interrupts!(struct Irqs { type Device = Ethernet<'static, ETH, GenericSMI>; #[embassy_executor::task] -async fn net_task(stack: &'static Stack) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -64,10 +66,10 @@ async fn main(spawner: Spawner) -> ! { let mac_addr = [0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF]; - static PACKETS: StaticCell> = StaticCell::new(); + static PACKETS: StaticCell> = StaticCell::new(); let device = Ethernet::new( - PACKETS.init(PacketQueue::<16, 16>::new()), + PACKETS.init(PacketQueue::<4, 4>::new()), p.ETH, Irqs, p.PA1, @@ -91,17 +93,11 @@ async fn main(spawner: Spawner) -> ! { //}); // Init network stack - static STACK: StaticCell> = StaticCell::new(); static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<3>::new()), - seed, - )); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); // Launch network task - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); // Ensure DHCP configuration is up before trying connect stack.wait_config_up().await; @@ -109,7 +105,7 @@ async fn main(spawner: Spawner) -> ! { info!("Network task initialized"); let state: TcpClientState<1, 1024, 1024> = TcpClientState::new(); - let client = TcpClient::new(&stack, &state); + let client = TcpClient::new(stack, &state); loop { // You need to start a server on the host machine, for example: `nc -l 8000` diff --git a/examples/stm32h7/src/bin/eth_client_mii.rs b/examples/stm32h7/src/bin/eth_client_mii.rs index de6ea522a..a352ef444 100644 --- a/examples/stm32h7/src/bin/eth_client_mii.rs +++ b/examples/stm32h7/src/bin/eth_client_mii.rs @@ -1,10 +1,12 @@ #![no_std] #![no_main] +use core::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; + use defmt::*; use embassy_executor::Spawner; use embassy_net::tcp::client::{TcpClient, TcpClientState}; -use embassy_net::{Stack, StackResources}; +use embassy_net::StackResources; use embassy_stm32::eth::generic_smi::GenericSMI; use embassy_stm32::eth::{Ethernet, PacketQueue}; use embassy_stm32::peripherals::ETH; @@ -12,7 +14,7 @@ use embassy_stm32::rng::Rng; use embassy_stm32::{bind_interrupts, eth, peripherals, rng, Config}; use embassy_time::Timer; use embedded_io_async::Write; -use embedded_nal_async::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpConnect}; +use embedded_nal_async::TcpConnect; use rand_core::RngCore; use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _}; @@ -25,8 +27,8 @@ bind_interrupts!(struct Irqs { type Device = Ethernet<'static, ETH, GenericSMI>; #[embassy_executor::task] -async fn net_task(stack: &'static Stack) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -64,10 +66,10 @@ async fn main(spawner: Spawner) -> ! { let mac_addr = [0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF]; - static PACKETS: StaticCell> = StaticCell::new(); + static PACKETS: StaticCell> = StaticCell::new(); let device = Ethernet::new_mii( - PACKETS.init(PacketQueue::<16, 16>::new()), + PACKETS.init(PacketQueue::<4, 4>::new()), p.ETH, Irqs, p.PA1, @@ -97,17 +99,11 @@ async fn main(spawner: Spawner) -> ! { //}); // Init network stack - static STACK: StaticCell> = StaticCell::new(); static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<3>::new()), - seed, - )); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); // Launch network task - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); // Ensure DHCP configuration is up before trying connect stack.wait_config_up().await; @@ -115,7 +111,7 @@ async fn main(spawner: Spawner) -> ! { info!("Network task initialized"); let state: TcpClientState<1, 1024, 1024> = TcpClientState::new(); - let client = TcpClient::new(&stack, &state); + let client = TcpClient::new(stack, &state); loop { // You need to start a server on the host machine, for example: `nc -l 8000` diff --git a/examples/stm32h7/src/bin/i2c_shared.rs b/examples/stm32h7/src/bin/i2c_shared.rs new file mode 100644 index 000000000..136b91eeb --- /dev/null +++ b/examples/stm32h7/src/bin/i2c_shared.rs @@ -0,0 +1,113 @@ +#![no_std] +#![no_main] + +use core::cell::RefCell; + +use defmt::*; +use embassy_embedded_hal::shared_bus::blocking::i2c::I2cDevice; +use embassy_executor::Spawner; +use embassy_stm32::i2c::{self, I2c}; +use embassy_stm32::mode::Async; +use embassy_stm32::time::Hertz; +use embassy_stm32::{bind_interrupts, peripherals}; +use embassy_sync::blocking_mutex::raw::NoopRawMutex; +use embassy_sync::blocking_mutex::NoopMutex; +use embassy_time::{Duration, Timer}; +use embedded_hal_1::i2c::I2c as _; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +const TMP117_ADDR: u8 = 0x48; +const TMP117_TEMP_RESULT: u8 = 0x00; + +const SHTC3_ADDR: u8 = 0x70; +const SHTC3_WAKEUP: [u8; 2] = [0x35, 0x17]; +const SHTC3_MEASURE_RH_FIRST: [u8; 2] = [0x5c, 0x24]; +const SHTC3_SLEEP: [u8; 2] = [0xb0, 0x98]; + +static I2C_BUS: StaticCell>>> = StaticCell::new(); + +bind_interrupts!(struct Irqs { + I2C1_EV => i2c::EventInterruptHandler; + I2C1_ER => i2c::ErrorInterruptHandler; +}); + +#[embassy_executor::task] +async fn temperature(mut i2c: I2cDevice<'static, NoopRawMutex, I2c<'static, Async>>) { + let mut data = [0u8; 2]; + + loop { + match i2c.write_read(TMP117_ADDR, &[TMP117_TEMP_RESULT], &mut data) { + Ok(()) => { + let temp = f32::from(i16::from_be_bytes(data)) * 7.8125 / 1000.0; + info!("Temperature {}", temp); + } + Err(_) => error!("I2C Error"), + } + + Timer::after(Duration::from_millis(1000)).await; + } +} + +#[embassy_executor::task] +async fn humidity(mut i2c: I2cDevice<'static, NoopRawMutex, I2c<'static, Async>>) { + let mut data = [0u8; 6]; + + loop { + // Wakeup + match i2c.write(SHTC3_ADDR, &SHTC3_WAKEUP) { + Ok(()) => Timer::after(Duration::from_millis(20)).await, + Err(_) => error!("I2C Error"), + } + + // Measurement + match i2c.write(SHTC3_ADDR, &SHTC3_MEASURE_RH_FIRST) { + Ok(()) => Timer::after(Duration::from_millis(5)).await, + Err(_) => error!("I2C Error"), + } + + // Result + match i2c.read(SHTC3_ADDR, &mut data) { + Ok(()) => Timer::after(Duration::from_millis(5)).await, + Err(_) => error!("I2C Error"), + } + + // Sleep + match i2c.write(SHTC3_ADDR, &SHTC3_SLEEP) { + Ok(()) => { + let (bytes, _) = data.split_at(core::mem::size_of::()); + let rh = f32::from(u16::from_be_bytes(bytes.try_into().unwrap())) * 100.0 / 65536.0; + info!("Humidity: {}", rh); + } + Err(_) => error!("I2C Error"), + } + + Timer::after(Duration::from_millis(1000)).await; + } +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + + let i2c = I2c::new( + p.I2C1, + p.PB8, + p.PB9, + Irqs, + p.DMA1_CH4, + p.DMA1_CH5, + Hertz(100_000), + Default::default(), + ); + let i2c_bus = NoopMutex::new(RefCell::new(i2c)); + let i2c_bus = I2C_BUS.init(i2c_bus); + + // Device 1, using embedded-hal-async compatible driver for TMP117 + let i2c_dev1 = I2cDevice::new(i2c_bus); + spawner.spawn(temperature(i2c_dev1)).unwrap(); + + // Device 2, using embedded-hal-async compatible driver for SHTC3 + let i2c_dev2 = I2cDevice::new(i2c_bus); + spawner.spawn(humidity(i2c_dev2)).unwrap(); +} diff --git a/examples/stm32h7/src/bin/low_level_timer_api.rs b/examples/stm32h7/src/bin/low_level_timer_api.rs index cc508c3cf..b796996ea 100644 --- a/examples/stm32h7/src/bin/low_level_timer_api.rs +++ b/examples/stm32h7/src/bin/low_level_timer_api.rs @@ -3,11 +3,11 @@ use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::gpio::low_level::AFType; -use embassy_stm32::gpio::Speed; +use embassy_stm32::gpio::{AfType, Flex, OutputType, Speed}; use embassy_stm32::time::{khz, Hertz}; -use embassy_stm32::timer::*; -use embassy_stm32::{into_ref, Config, Peripheral, PeripheralRef}; +use embassy_stm32::timer::low_level::{OutputCompareMode, Timer as LLTimer}; +use embassy_stm32::timer::{Channel, Channel1Pin, Channel2Pin, Channel3Pin, Channel4Pin, GeneralInstance32bit4Channel}; +use embassy_stm32::{into_ref, Config, Peripheral}; use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; @@ -56,11 +56,15 @@ async fn main(_spawner: Spawner) { Timer::after_millis(300).await; } } -pub struct SimplePwm32<'d, T: CaptureCompare32bitInstance> { - inner: PeripheralRef<'d, T>, +pub struct SimplePwm32<'d, T: GeneralInstance32bit4Channel> { + tim: LLTimer<'d, T>, + _ch1: Flex<'d>, + _ch2: Flex<'d>, + _ch3: Flex<'d>, + _ch4: Flex<'d>, } -impl<'d, T: CaptureCompare32bitInstance> SimplePwm32<'d, T> { +impl<'d, T: GeneralInstance32bit4Channel> SimplePwm32<'d, T> { pub fn new( tim: impl Peripheral

+ 'd, ch1: impl Peripheral

> + 'd, @@ -69,25 +73,33 @@ impl<'d, T: CaptureCompare32bitInstance> SimplePwm32<'d, T> { ch4: impl Peripheral

> + 'd, freq: Hertz, ) -> Self { - into_ref!(tim, ch1, ch2, ch3, ch4); + into_ref!(ch1, ch2, ch3, ch4); - T::enable_and_reset(); + let af1 = ch1.af_num(); + let af2 = ch2.af_num(); + let af3 = ch3.af_num(); + let af4 = ch4.af_num(); + let mut ch1 = Flex::new(ch1); + let mut ch2 = Flex::new(ch2); + let mut ch3 = Flex::new(ch3); + let mut ch4 = Flex::new(ch4); + ch1.set_as_af_unchecked(af1, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + ch2.set_as_af_unchecked(af2, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + ch3.set_as_af_unchecked(af3, AfType::output(OutputType::PushPull, Speed::VeryHigh)); + ch4.set_as_af_unchecked(af4, AfType::output(OutputType::PushPull, Speed::VeryHigh)); - ch1.set_speed(Speed::VeryHigh); - ch1.set_as_af(ch1.af_num(), AFType::OutputPushPull); - ch2.set_speed(Speed::VeryHigh); - ch2.set_as_af(ch1.af_num(), AFType::OutputPushPull); - ch3.set_speed(Speed::VeryHigh); - ch3.set_as_af(ch1.af_num(), AFType::OutputPushPull); - ch4.set_speed(Speed::VeryHigh); - ch4.set_as_af(ch1.af_num(), AFType::OutputPushPull); - - let mut this = Self { inner: tim }; + let mut this = Self { + tim: LLTimer::new(tim), + _ch1: ch1, + _ch2: ch2, + _ch3: ch3, + _ch4: ch4, + }; this.set_frequency(freq); - this.inner.start(); + this.tim.start(); - let r = T::regs_gp32(); + let r = this.tim.regs_gp32(); r.ccmr_output(0) .modify(|w| w.set_ocm(0, OutputCompareMode::PwmMode1.into())); r.ccmr_output(0) @@ -101,23 +113,26 @@ impl<'d, T: CaptureCompare32bitInstance> SimplePwm32<'d, T> { } pub fn enable(&mut self, channel: Channel) { - T::regs_gp32().ccer().modify(|w| w.set_cce(channel.index(), true)); + self.tim.regs_gp32().ccer().modify(|w| w.set_cce(channel.index(), true)); } pub fn disable(&mut self, channel: Channel) { - T::regs_gp32().ccer().modify(|w| w.set_cce(channel.index(), false)); + self.tim + .regs_gp32() + .ccer() + .modify(|w| w.set_cce(channel.index(), false)); } pub fn set_frequency(&mut self, freq: Hertz) { - ::set_frequency(&mut self.inner, freq); + self.tim.set_frequency(freq); } pub fn get_max_duty(&self) -> u32 { - T::regs_gp32().arr().read().arr() + self.tim.regs_gp32().arr().read() } pub fn set_duty(&mut self, channel: Channel, duty: u32) { defmt::assert!(duty < self.get_max_duty()); - T::regs_gp32().ccr(channel.index()).modify(|w| w.set_ccr(duty)) + self.tim.regs_gp32().ccr(channel.index()).write_value(duty) } } diff --git a/examples/stm32h7/src/bin/multiprio.rs b/examples/stm32h7/src/bin/multiprio.rs new file mode 100644 index 000000000..b4620888f --- /dev/null +++ b/examples/stm32h7/src/bin/multiprio.rs @@ -0,0 +1,150 @@ +//! This example showcases how to create multiple Executor instances to run tasks at +//! different priority levels. +//! +//! Low priority executor runs in thread mode (not interrupt), and uses `sev` for signaling +//! there's work in the queue, and `wfe` for waiting for work. +//! +//! Medium and high priority executors run in two interrupts with different priorities. +//! Signaling work is done by pending the interrupt. No "waiting" needs to be done explicitly, since +//! when there's work the interrupt will trigger and run the executor. +//! +//! Sample output below. Note that high priority ticks can interrupt everything else, and +//! medium priority computations can interrupt low priority computations, making them to appear +//! to take significantly longer time. +//! +//! ```not_rust +//! [med] Starting long computation +//! [med] done in 992 ms +//! [high] tick! +//! [low] Starting long computation +//! [med] Starting long computation +//! [high] tick! +//! [high] tick! +//! [med] done in 993 ms +//! [med] Starting long computation +//! [high] tick! +//! [high] tick! +//! [med] done in 993 ms +//! [low] done in 3972 ms +//! [med] Starting long computation +//! [high] tick! +//! [high] tick! +//! [med] done in 993 ms +//! ``` +//! +//! For comparison, try changing the code so all 3 tasks get spawned on the low priority executor. +//! You will get an output like the following. Note that no computation is ever interrupted. +//! +//! ```not_rust +//! [high] tick! +//! [med] Starting long computation +//! [med] done in 496 ms +//! [low] Starting long computation +//! [low] done in 992 ms +//! [med] Starting long computation +//! [med] done in 496 ms +//! [high] tick! +//! [low] Starting long computation +//! [low] done in 992 ms +//! [high] tick! +//! [med] Starting long computation +//! [med] done in 496 ms +//! [high] tick! +//! ``` +//! + +#![no_std] +#![no_main] + +use cortex_m_rt::entry; +use defmt::*; +use embassy_executor::{Executor, InterruptExecutor}; +use embassy_stm32::interrupt; +use embassy_stm32::interrupt::{InterruptExt, Priority}; +use embassy_time::{Instant, Timer}; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::task] +async fn run_high() { + loop { + info!(" [high] tick!"); + Timer::after_ticks(27374).await; + } +} + +#[embassy_executor::task] +async fn run_med() { + loop { + let start = Instant::now(); + info!(" [med] Starting long computation"); + + // Spin-wait to simulate a long CPU computation + embassy_time::block_for(embassy_time::Duration::from_secs(1)); // ~1 second + + let end = Instant::now(); + let ms = end.duration_since(start).as_ticks() / 33; + info!(" [med] done in {} ms", ms); + + Timer::after_ticks(23421).await; + } +} + +#[embassy_executor::task] +async fn run_low() { + loop { + let start = Instant::now(); + info!("[low] Starting long computation"); + + // Spin-wait to simulate a long CPU computation + embassy_time::block_for(embassy_time::Duration::from_secs(2)); // ~2 seconds + + let end = Instant::now(); + let ms = end.duration_since(start).as_ticks() / 33; + info!("[low] done in {} ms", ms); + + Timer::after_ticks(32983).await; + } +} + +static EXECUTOR_HIGH: InterruptExecutor = InterruptExecutor::new(); +static EXECUTOR_MED: InterruptExecutor = InterruptExecutor::new(); +static EXECUTOR_LOW: StaticCell = StaticCell::new(); + +#[interrupt] +unsafe fn UART4() { + EXECUTOR_HIGH.on_interrupt() +} + +#[interrupt] +unsafe fn UART5() { + EXECUTOR_MED.on_interrupt() +} + +#[entry] +fn main() -> ! { + info!("Hello World!"); + + let _p = embassy_stm32::init(Default::default()); + + // STM32s don’t have any interrupts exclusively for software use, but they can all be triggered by software as well as + // by the peripheral, so we can just use any free interrupt vectors which aren’t used by the rest of your application. + // In this case we’re using UART4 and UART5, but there’s nothing special about them. Any otherwise unused interrupt + // vector would work exactly the same. + + // High-priority executor: UART4, priority level 6 + interrupt::UART4.set_priority(Priority::P6); + let spawner = EXECUTOR_HIGH.start(interrupt::UART4); + unwrap!(spawner.spawn(run_high())); + + // Medium-priority executor: UART5, priority level 7 + interrupt::UART5.set_priority(Priority::P7); + let spawner = EXECUTOR_MED.start(interrupt::UART5); + unwrap!(spawner.spawn(run_med())); + + // Low priority executor: runs in thread mode, using WFE/SEV + let executor = EXECUTOR_LOW.init(Executor::new()); + executor.run(|spawner| { + unwrap!(spawner.spawn(run_low())); + }); +} diff --git a/examples/stm32h7/src/bin/pwm.rs b/examples/stm32h7/src/bin/pwm.rs index 1e48ba67b..a1c53fc3f 100644 --- a/examples/stm32h7/src/bin/pwm.rs +++ b/examples/stm32h7/src/bin/pwm.rs @@ -6,7 +6,6 @@ use embassy_executor::Spawner; use embassy_stm32::gpio::OutputType; use embassy_stm32::time::khz; use embassy_stm32::timer::simple_pwm::{PwmPin, SimplePwm}; -use embassy_stm32::timer::Channel; use embassy_stm32::Config; use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; @@ -37,22 +36,22 @@ async fn main(_spawner: Spawner) { let p = embassy_stm32::init(config); info!("Hello World!"); - let ch1 = PwmPin::new_ch1(p.PA6, OutputType::PushPull); - let mut pwm = SimplePwm::new(p.TIM3, Some(ch1), None, None, None, khz(10), Default::default()); - let max = pwm.get_max_duty(); - pwm.enable(Channel::Ch1); + let ch1_pin = PwmPin::new_ch1(p.PA6, OutputType::PushPull); + let mut pwm = SimplePwm::new(p.TIM3, Some(ch1_pin), None, None, None, khz(10), Default::default()); + let mut ch1 = pwm.ch1(); + ch1.enable(); info!("PWM initialized"); - info!("PWM max duty {}", max); + info!("PWM max duty {}", ch1.max_duty_cycle()); loop { - pwm.set_duty(Channel::Ch1, 0); + ch1.set_duty_cycle_fully_off(); Timer::after_millis(300).await; - pwm.set_duty(Channel::Ch1, max / 4); + ch1.set_duty_cycle_fraction(1, 4); Timer::after_millis(300).await; - pwm.set_duty(Channel::Ch1, max / 2); + ch1.set_duty_cycle_fraction(1, 2); Timer::after_millis(300).await; - pwm.set_duty(Channel::Ch1, max - 1); + ch1.set_duty_cycle(ch1.max_duty_cycle() - 1); Timer::after_millis(300).await; } } diff --git a/examples/stm32h7/src/bin/rtc.rs b/examples/stm32h7/src/bin/rtc.rs index c6b9cf57e..0adb48877 100644 --- a/examples/stm32h7/src/bin/rtc.rs +++ b/examples/stm32h7/src/bin/rtc.rs @@ -24,7 +24,7 @@ async fn main(_spawner: Spawner) { .unwrap(); let mut rtc = Rtc::new(p.RTC, RtcConfig::default()); - info!("Got RTC! {:?}", now.timestamp()); + info!("Got RTC! {:?}", now.and_utc().timestamp()); rtc.set_datetime(now.into()).expect("datetime not set"); @@ -32,5 +32,5 @@ async fn main(_spawner: Spawner) { Timer::after_millis(20000).await; let then: NaiveDateTime = rtc.now().unwrap().into(); - info!("Got RTC! {:?}", then.timestamp()); + info!("Got RTC! {:?}", then.and_utc().timestamp()); } diff --git a/examples/stm32h7/src/bin/sai.rs b/examples/stm32h7/src/bin/sai.rs new file mode 100644 index 000000000..04d14bd6b --- /dev/null +++ b/examples/stm32h7/src/bin/sai.rs @@ -0,0 +1,188 @@ +//! Daisy Seed rev.7(with PCM3060 codec) +//! https://electro-smith.com/products/daisy-seed +#![no_std] +#![no_main] + +use embassy_executor::Spawner; +use grounded::uninit::GroundedArrayCell; +use hal::rcc::*; +use hal::sai::*; +use hal::time::Hertz; +use {defmt_rtt as _, embassy_stm32 as hal, panic_probe as _}; + +const BLOCK_LENGTH: usize = 32; // 32 samples +const HALF_DMA_BUFFER_LENGTH: usize = BLOCK_LENGTH * 2; // 2 channels +const DMA_BUFFER_LENGTH: usize = HALF_DMA_BUFFER_LENGTH * 2; // 2 half-blocks +const SAMPLE_RATE: u32 = 48000; + +//DMA buffer must be in special region. Refer https://embassy.dev/book/#_stm32_bdma_only_working_out_of_some_ram_regions +#[link_section = ".sram1_bss"] +static mut TX_BUFFER: GroundedArrayCell = GroundedArrayCell::uninit(); +#[link_section = ".sram1_bss"] +static mut RX_BUFFER: GroundedArrayCell = GroundedArrayCell::uninit(); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = hal::Config::default(); + config.rcc.pll1 = Some(Pll { + source: PllSource::HSE, + prediv: PllPreDiv::DIV4, + mul: PllMul::MUL200, + divp: Some(PllDiv::DIV2), + divq: Some(PllDiv::DIV5), + divr: Some(PllDiv::DIV2), + }); + config.rcc.pll3 = Some(Pll { + source: PllSource::HSE, + prediv: PllPreDiv::DIV6, + mul: PllMul::MUL295, + divp: Some(PllDiv::DIV16), + divq: Some(PllDiv::DIV4), + divr: Some(PllDiv::DIV32), + }); + config.rcc.sys = Sysclk::PLL1_P; + config.rcc.mux.sai1sel = hal::pac::rcc::vals::Saisel::PLL3_P; + config.rcc.ahb_pre = AHBPrescaler::DIV2; // 200 Mhz + config.rcc.apb1_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.apb2_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.apb3_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.apb4_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.hse = Some(Hse { + freq: Hertz::mhz(16), + mode: HseMode::Oscillator, + }); + + let p = hal::init(config); + + let (sub_block_tx, sub_block_rx) = hal::sai::split_subblocks(p.SAI1); + let kernel_clock = hal::rcc::frequency::().0; + let mclk_div = mclk_div_from_u8((kernel_clock / (SAMPLE_RATE * 256)) as u8); + + let mut tx_config = hal::sai::Config::default(); + tx_config.mode = Mode::Master; + tx_config.tx_rx = TxRx::Transmitter; + tx_config.sync_output = true; + tx_config.clock_strobe = ClockStrobe::Falling; + tx_config.master_clock_divider = mclk_div; + tx_config.stereo_mono = StereoMono::Stereo; + tx_config.data_size = DataSize::Data24; + tx_config.bit_order = BitOrder::MsbFirst; + tx_config.frame_sync_polarity = FrameSyncPolarity::ActiveHigh; + tx_config.frame_sync_offset = FrameSyncOffset::OnFirstBit; + tx_config.frame_length = 64; + tx_config.frame_sync_active_level_length = embassy_stm32::sai::word::U7(32); + tx_config.fifo_threshold = FifoThreshold::Quarter; + + let mut rx_config = tx_config.clone(); + rx_config.mode = Mode::Slave; + rx_config.tx_rx = TxRx::Receiver; + rx_config.sync_input = SyncInput::Internal; + rx_config.clock_strobe = ClockStrobe::Rising; + rx_config.sync_output = false; + + let tx_buffer: &mut [u32] = unsafe { + let buf = &mut *core::ptr::addr_of_mut!(TX_BUFFER); + buf.initialize_all_copied(0); + let (ptr, len) = buf.get_ptr_len(); + core::slice::from_raw_parts_mut(ptr, len) + }; + + let mut sai_transmitter = Sai::new_asynchronous_with_mclk( + sub_block_tx, + p.PE5, + p.PE6, + p.PE4, + p.PE2, + p.DMA1_CH0, + tx_buffer, + tx_config, + ); + + let rx_buffer: &mut [u32] = unsafe { + let buf = &mut *core::ptr::addr_of_mut!(RX_BUFFER); + buf.initialize_all_copied(0); + let (ptr, len) = buf.get_ptr_len(); + core::slice::from_raw_parts_mut(ptr, len) + }; + + let mut sai_receiver = Sai::new_synchronous(sub_block_rx, p.PE3, p.DMA1_CH1, rx_buffer, rx_config); + + sai_receiver.start(); + sai_transmitter.start(); + + let mut buf = [0u32; HALF_DMA_BUFFER_LENGTH]; + + loop { + sai_receiver.read(&mut buf).await.unwrap(); + sai_transmitter.write(&buf).await.unwrap(); + } +} + +const fn mclk_div_from_u8(v: u8) -> MasterClockDivider { + match v { + 1 => MasterClockDivider::Div1, + 2 => MasterClockDivider::Div2, + 3 => MasterClockDivider::Div3, + 4 => MasterClockDivider::Div4, + 5 => MasterClockDivider::Div5, + 6 => MasterClockDivider::Div6, + 7 => MasterClockDivider::Div7, + 8 => MasterClockDivider::Div8, + 9 => MasterClockDivider::Div9, + 10 => MasterClockDivider::Div10, + 11 => MasterClockDivider::Div11, + 12 => MasterClockDivider::Div12, + 13 => MasterClockDivider::Div13, + 14 => MasterClockDivider::Div14, + 15 => MasterClockDivider::Div15, + 16 => MasterClockDivider::Div16, + 17 => MasterClockDivider::Div17, + 18 => MasterClockDivider::Div18, + 19 => MasterClockDivider::Div19, + 20 => MasterClockDivider::Div20, + 21 => MasterClockDivider::Div21, + 22 => MasterClockDivider::Div22, + 23 => MasterClockDivider::Div23, + 24 => MasterClockDivider::Div24, + 25 => MasterClockDivider::Div25, + 26 => MasterClockDivider::Div26, + 27 => MasterClockDivider::Div27, + 28 => MasterClockDivider::Div28, + 29 => MasterClockDivider::Div29, + 30 => MasterClockDivider::Div30, + 31 => MasterClockDivider::Div31, + 32 => MasterClockDivider::Div32, + 33 => MasterClockDivider::Div33, + 34 => MasterClockDivider::Div34, + 35 => MasterClockDivider::Div35, + 36 => MasterClockDivider::Div36, + 37 => MasterClockDivider::Div37, + 38 => MasterClockDivider::Div38, + 39 => MasterClockDivider::Div39, + 40 => MasterClockDivider::Div40, + 41 => MasterClockDivider::Div41, + 42 => MasterClockDivider::Div42, + 43 => MasterClockDivider::Div43, + 44 => MasterClockDivider::Div44, + 45 => MasterClockDivider::Div45, + 46 => MasterClockDivider::Div46, + 47 => MasterClockDivider::Div47, + 48 => MasterClockDivider::Div48, + 49 => MasterClockDivider::Div49, + 50 => MasterClockDivider::Div50, + 51 => MasterClockDivider::Div51, + 52 => MasterClockDivider::Div52, + 53 => MasterClockDivider::Div53, + 54 => MasterClockDivider::Div54, + 55 => MasterClockDivider::Div55, + 56 => MasterClockDivider::Div56, + 57 => MasterClockDivider::Div57, + 58 => MasterClockDivider::Div58, + 59 => MasterClockDivider::Div59, + 60 => MasterClockDivider::Div60, + 61 => MasterClockDivider::Div61, + 62 => MasterClockDivider::Div62, + 63 => MasterClockDivider::Div63, + _ => panic!(), + } +} diff --git a/examples/stm32h7/src/bin/spi.rs b/examples/stm32h7/src/bin/spi.rs index aed27723a..ad4a8aaf7 100644 --- a/examples/stm32h7/src/bin/spi.rs +++ b/examples/stm32h7/src/bin/spi.rs @@ -7,8 +7,7 @@ use core::str::from_utf8; use cortex_m_rt::entry; use defmt::*; use embassy_executor::Executor; -use embassy_stm32::dma::NoDma; -use embassy_stm32::peripherals::SPI3; +use embassy_stm32::mode::Blocking; use embassy_stm32::time::mhz; use embassy_stm32::{spi, Config}; use heapless::String; @@ -16,7 +15,7 @@ use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::task] -async fn main_task(mut spi: spi::Spi<'static, SPI3, NoDma, NoDma>) { +async fn main_task(mut spi: spi::Spi<'static, Blocking>) { for n in 0u32.. { let mut write: String<128> = String::new(); core::write!(&mut write, "Hello DMA World {}!\r\n", n).unwrap(); @@ -62,7 +61,7 @@ fn main() -> ! { let mut spi_config = spi::Config::default(); spi_config.frequency = mhz(1); - let spi = spi::Spi::new(p.SPI3, p.PB3, p.PB5, p.PB4, NoDma, NoDma, spi_config); + let spi = spi::Spi::new_blocking(p.SPI3, p.PB3, p.PB5, p.PB4, spi_config); let executor = EXECUTOR.init(Executor::new()); diff --git a/examples/stm32h7/src/bin/spi_bdma.rs b/examples/stm32h7/src/bin/spi_bdma.rs new file mode 100644 index 000000000..9166fe9b6 --- /dev/null +++ b/examples/stm32h7/src/bin/spi_bdma.rs @@ -0,0 +1,85 @@ +#![no_std] +#![no_main] + +use core::fmt::Write; +use core::str::from_utf8; + +use cortex_m_rt::entry; +use defmt::*; +use embassy_executor::Executor; +use embassy_stm32::mode::Async; +use embassy_stm32::time::mhz; +use embassy_stm32::{spi, Config}; +use grounded::uninit::GroundedArrayCell; +use heapless::String; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +// Defined in memory.x +#[link_section = ".ram_d3"] +static mut RAM_D3: GroundedArrayCell = GroundedArrayCell::uninit(); + +#[embassy_executor::task] +async fn main_task(mut spi: spi::Spi<'static, Async>) { + let (read_buffer, write_buffer) = unsafe { + let ram = &mut *core::ptr::addr_of_mut!(RAM_D3); + ram.initialize_all_copied(0); + ( + ram.get_subslice_mut_unchecked(0, 128), + ram.get_subslice_mut_unchecked(128, 128), + ) + }; + + for n in 0u32.. { + let mut write: String<128> = String::new(); + core::write!(&mut write, "Hello DMA World {}!\r\n", n).unwrap(); + let read_buffer = &mut read_buffer[..write.len()]; + let write_buffer = &mut write_buffer[..write.len()]; + // copy data to write_buffer which is located in D3 domain, accessable by BDMA + write_buffer.clone_from_slice(write.as_bytes()); + + spi.transfer(read_buffer, write_buffer).await.ok(); + info!("read via spi+dma: {}", from_utf8(read_buffer).unwrap()); + } +} + +static EXECUTOR: StaticCell = StaticCell::new(); + +#[entry] +fn main() -> ! { + info!("Hello World!"); + + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.hsi = Some(HSIPrescaler::DIV1); + config.rcc.csi = true; + config.rcc.pll1 = Some(Pll { + source: PllSource::HSI, + prediv: PllPreDiv::DIV4, + mul: PllMul::MUL50, + divp: Some(PllDiv::DIV2), + divq: Some(PllDiv::DIV8), // used by SPI3. 100Mhz. + divr: None, + }); + config.rcc.sys = Sysclk::PLL1_P; // 400 Mhz + config.rcc.ahb_pre = AHBPrescaler::DIV2; // 200 Mhz + config.rcc.apb1_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.apb2_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.apb3_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.apb4_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.voltage_scale = VoltageScale::Scale1; + } + let p = embassy_stm32::init(config); + + let mut spi_config = spi::Config::default(); + spi_config.frequency = mhz(1); + + let spi = spi::Spi::new(p.SPI6, p.PA5, p.PA7, p.PA6, p.BDMA_CH1, p.BDMA_CH0, spi_config); + + let executor = EXECUTOR.init(Executor::new()); + + executor.run(|spawner| { + unwrap!(spawner.spawn(main_task(spi))); + }) +} diff --git a/examples/stm32h7/src/bin/spi_dma.rs b/examples/stm32h7/src/bin/spi_dma.rs index 54d4d7656..731c7fef5 100644 --- a/examples/stm32h7/src/bin/spi_dma.rs +++ b/examples/stm32h7/src/bin/spi_dma.rs @@ -7,7 +7,7 @@ use core::str::from_utf8; use cortex_m_rt::entry; use defmt::*; use embassy_executor::Executor; -use embassy_stm32::peripherals::{DMA1_CH3, DMA1_CH4, SPI3}; +use embassy_stm32::mode::Async; use embassy_stm32::time::mhz; use embassy_stm32::{spi, Config}; use heapless::String; @@ -15,7 +15,7 @@ use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::task] -async fn main_task(mut spi: spi::Spi<'static, SPI3, DMA1_CH3, DMA1_CH4>) { +async fn main_task(mut spi: spi::Spi<'static, Async>) { for n in 0u32.. { let mut write: String<128> = String::new(); let mut read = [0; 128]; diff --git a/examples/stm32h7/src/bin/usart.rs b/examples/stm32h7/src/bin/usart.rs index f9cbad6af..cc49c2fdb 100644 --- a/examples/stm32h7/src/bin/usart.rs +++ b/examples/stm32h7/src/bin/usart.rs @@ -4,22 +4,16 @@ use cortex_m_rt::entry; use defmt::*; use embassy_executor::Executor; -use embassy_stm32::dma::NoDma; use embassy_stm32::usart::{Config, Uart}; -use embassy_stm32::{bind_interrupts, peripherals, usart}; use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _}; -bind_interrupts!(struct Irqs { - UART7 => usart::InterruptHandler; -}); - #[embassy_executor::task] async fn main_task() { let p = embassy_stm32::init(Default::default()); let config = Config::default(); - let mut usart = Uart::new(p.UART7, p.PF6, p.PF7, Irqs, NoDma, NoDma, config).unwrap(); + let mut usart = Uart::new_blocking(p.UART7, p.PF6, p.PF7, config).unwrap(); unwrap!(usart.blocking_write(b"Hello Embassy World!\r\n")); info!("wrote Hello, starting echo"); diff --git a/examples/stm32h7/src/bin/usart_dma.rs b/examples/stm32h7/src/bin/usart_dma.rs index ae1f3a2e9..6f340d40a 100644 --- a/examples/stm32h7/src/bin/usart_dma.rs +++ b/examples/stm32h7/src/bin/usart_dma.rs @@ -6,7 +6,6 @@ use core::fmt::Write; use cortex_m_rt::entry; use defmt::*; use embassy_executor::Executor; -use embassy_stm32::dma::NoDma; use embassy_stm32::usart::{Config, Uart}; use embassy_stm32::{bind_interrupts, peripherals, usart}; use heapless::String; @@ -22,7 +21,7 @@ async fn main_task() { let p = embassy_stm32::init(Default::default()); let config = Config::default(); - let mut usart = Uart::new(p.UART7, p.PF6, p.PF7, Irqs, p.DMA1_CH0, NoDma, config).unwrap(); + let mut usart = Uart::new(p.UART7, p.PF6, p.PF7, Irqs, p.DMA1_CH0, p.DMA1_CH1, config).unwrap(); for n in 0u32.. { let mut s: String<128> = String::new(); diff --git a/examples/stm32h7/src/bin/usart_split.rs b/examples/stm32h7/src/bin/usart_split.rs index b98c40877..2bb58be5e 100644 --- a/examples/stm32h7/src/bin/usart_split.rs +++ b/examples/stm32h7/src/bin/usart_split.rs @@ -3,8 +3,7 @@ use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::dma::NoDma; -use embassy_stm32::peripherals::{DMA1_CH1, UART7}; +use embassy_stm32::mode::Async; use embassy_stm32::usart::{Config, Uart, UartRx}; use embassy_stm32::{bind_interrupts, peripherals, usart}; use embassy_sync::blocking_mutex::raw::ThreadModeRawMutex; @@ -15,18 +14,6 @@ bind_interrupts!(struct Irqs { UART7 => usart::InterruptHandler; }); -#[embassy_executor::task] -async fn writer(mut usart: Uart<'static, UART7, NoDma, NoDma>) { - unwrap!(usart.blocking_write(b"Hello Embassy World!\r\n")); - info!("wrote Hello, starting echo"); - - let mut buf = [0u8; 1]; - loop { - unwrap!(usart.blocking_read(&mut buf)); - unwrap!(usart.blocking_write(&buf)); - } -} - static CHANNEL: Channel = Channel::new(); #[embassy_executor::main] @@ -50,7 +37,7 @@ async fn main(spawner: Spawner) -> ! { } #[embassy_executor::task] -async fn reader(mut rx: UartRx<'static, UART7, DMA1_CH1>) { +async fn reader(mut rx: UartRx<'static, Async>) { let mut buf = [0; 8]; loop { info!("reading..."); diff --git a/examples/stm32h7/src/bin/usb_serial.rs b/examples/stm32h7/src/bin/usb_serial.rs index d81efb541..65ae597d4 100644 --- a/examples/stm32h7/src/bin/usb_serial.rs +++ b/examples/stm32h7/src/bin/usb_serial.rs @@ -3,18 +3,23 @@ use defmt::{panic, *}; use embassy_executor::Spawner; -use embassy_stm32::usb_otg::{Driver, Instance}; -use embassy_stm32::{bind_interrupts, peripherals, usb_otg, Config}; +use embassy_futures::join::join; +use embassy_stm32::usb::{Driver, Instance}; +use embassy_stm32::{bind_interrupts, peripherals, usb, Config}; use embassy_usb::class::cdc_acm::{CdcAcmClass, State}; use embassy_usb::driver::EndpointError; use embassy_usb::Builder; -use futures::future::join; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { - OTG_FS => usb_otg::InterruptHandler; + OTG_FS => usb::InterruptHandler; }); +// If you are trying this and your USB device doesn't connect, the most +// common issues are the RCC config and vbus_detection +// +// See https://embassy.dev/book/#_the_usb_examples_are_not_working_on_my_board_is_there_anything_else_i_need_to_configure +// for more information. #[embassy_executor::main] async fn main(_spawner: Spawner) { info!("Hello World!"); @@ -40,13 +45,20 @@ async fn main(_spawner: Spawner) { config.rcc.apb3_pre = APBPrescaler::DIV2; // 100 Mhz config.rcc.apb4_pre = APBPrescaler::DIV2; // 100 Mhz config.rcc.voltage_scale = VoltageScale::Scale1; + config.rcc.mux.usbsel = mux::Usbsel::HSI48; } let p = embassy_stm32::init(config); // Create the driver, from the HAL. let mut ep_out_buffer = [0u8; 256]; - let mut config = embassy_stm32::usb_otg::Config::default(); - config.vbus_detection = true; + let mut config = embassy_stm32::usb::Config::default(); + + // Do not enable vbus_detection. This is a safe default that works in all boards. + // However, if your USB device is self-powered (can stay powered on if USB is unplugged), you need + // to enable vbus_detection to comply with the USB spec. If you enable it, the board + // has to support it or USB won't work at all. See docs on `vbus_detection` for details. + config.vbus_detection = false; + let driver = Driver::new_fs(p.USB_OTG_FS, Irqs, p.PA12, p.PA11, &mut ep_out_buffer, config); // Create embassy-usb Config @@ -64,7 +76,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 64]; @@ -74,7 +85,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], // no msos descriptors diff --git a/examples/stm32h735/.cargo/config.toml b/examples/stm32h735/.cargo/config.toml new file mode 100644 index 000000000..95536c6a8 --- /dev/null +++ b/examples/stm32h735/.cargo/config.toml @@ -0,0 +1,8 @@ +[target.thumbv7em-none-eabihf] +runner = 'probe-rs run --chip STM32H735IGKx' + +[build] +target = "thumbv7em-none-eabihf" # Cortex-M4F and Cortex-M7F (with FPU) + +[env] +DEFMT_LOG = "trace" diff --git a/examples/stm32h735/Cargo.toml b/examples/stm32h735/Cargo.toml new file mode 100644 index 000000000..6a74d83ab --- /dev/null +++ b/examples/stm32h735/Cargo.toml @@ -0,0 +1,61 @@ +[package] +edition = "2021" +name = "embassy-stm32h735-examples" +version = "0.1.0" +license = "MIT OR Apache-2.0" + +[dependencies] +embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32h735ig", "time-driver-tim2", "exti", "memory-x", "unstable-pac", "chrono"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-embedded-hal = { version = "0.2.0", path = "../../embassy-embedded-hal" } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } + +defmt = "0.3" +defmt-rtt = "0.4" + +cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } +cortex-m-rt = "0.7.0" +panic-probe = { version = "0.3", features = ["print-defmt"] } +heapless = { version = "0.8", default-features = false } +embedded-graphics = { version = "0.8.1" } +tinybmp = { version = "0.5" } + +# cargo build/run +[profile.dev] +codegen-units = 1 +debug = 2 +debug-assertions = true # <- +incremental = false +opt-level = 3 # <- +overflow-checks = true # <- + +# cargo test +[profile.test] +codegen-units = 1 +debug = 2 +debug-assertions = true # <- +incremental = false +opt-level = 3 # <- +overflow-checks = true # <- + +# cargo build/run --release +[profile.release] +codegen-units = 1 +debug = 2 +debug-assertions = false # <- +incremental = false +lto = 'fat' +opt-level = 3 # <- +overflow-checks = false # <- + +# cargo test --release +[profile.bench] +codegen-units = 1 +debug = 2 +debug-assertions = false # <- +incremental = false +lto = 'fat' +opt-level = 3 # <- +overflow-checks = false # <- diff --git a/examples/stm32h735/build.rs b/examples/stm32h735/build.rs new file mode 100644 index 000000000..30691aa97 --- /dev/null +++ b/examples/stm32h735/build.rs @@ -0,0 +1,35 @@ +//! This build script copies the `memory.x` file from the crate root into +//! a directory where the linker can always find it at build time. +//! For many projects this is optional, as the linker always searches the +//! project root directory -- wherever `Cargo.toml` is. However, if you +//! are using a workspace or have a more complicated build setup, this +//! build script becomes required. Additionally, by requesting that +//! Cargo re-run the build script whenever `memory.x` is changed, +//! updating `memory.x` ensures a rebuild of the application with the +//! new memory settings. + +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; + +fn main() { + // Put `memory.x` in our output directory and ensure it's + // on the linker search path. + let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); + File::create(out.join("memory.x")) + .unwrap() + .write_all(include_bytes!("memory.x")) + .unwrap(); + println!("cargo:rustc-link-search={}", out.display()); + + // By default, Cargo will re-run a build script whenever + // any file in the project changes. By specifying `memory.x` + // here, we ensure the build script is only re-run when + // `memory.x` is changed. + println!("cargo:rerun-if-changed=memory.x"); + + println!("cargo:rustc-link-arg-bins=--nmagic"); + println!("cargo:rustc-link-arg-bins=-Tlink.x"); + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); +} diff --git a/examples/stm32h735/memory.x b/examples/stm32h735/memory.x new file mode 100644 index 000000000..3a70d24d2 --- /dev/null +++ b/examples/stm32h735/memory.x @@ -0,0 +1,5 @@ +MEMORY +{ + FLASH : ORIGIN = 0x08000000, LENGTH = 1024K + RAM : ORIGIN = 0x24000000, LENGTH = 320K +} \ No newline at end of file diff --git a/examples/stm32h735/src/bin/ferris.bmp b/examples/stm32h735/src/bin/ferris.bmp new file mode 100644 index 000000000..7a222ab84 Binary files /dev/null and b/examples/stm32h735/src/bin/ferris.bmp differ diff --git a/examples/stm32h735/src/bin/ltdc.rs b/examples/stm32h735/src/bin/ltdc.rs new file mode 100644 index 000000000..a36fdef2c --- /dev/null +++ b/examples/stm32h735/src/bin/ltdc.rs @@ -0,0 +1,467 @@ +#![no_std] +#![no_main] +#![macro_use] +#![allow(static_mut_refs)] + +/// This example demonstrates the LTDC lcd display peripheral and was tested to run on an stm32h735g-dk (embassy-stm32 feature "stm32h735ig" and probe-rs chip "STM32H735IGKx") +/// Even though the dev kit has 16MB of attached PSRAM this example uses the 320KB of internal AXIS RAM found on the mcu itself to make the example more standalone and portable. +/// For this reason a 256 color lookup table had to be used to keep the memory requirement down to an acceptable level. +/// The example bounces a ferris crab bitmap around the screen while blinking an led on another task +/// +use bouncy_box::BouncyBox; +use defmt::{info, unwrap}; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::ltdc::{self, Ltdc, LtdcConfiguration, LtdcLayer, LtdcLayerConfig, PolarityActive, PolarityEdge}; +use embassy_stm32::{bind_interrupts, peripherals}; +use embassy_time::{Duration, Timer}; +use embedded_graphics::draw_target::DrawTarget; +use embedded_graphics::geometry::{OriginDimensions, Point, Size}; +use embedded_graphics::image::Image; +use embedded_graphics::pixelcolor::raw::RawU24; +use embedded_graphics::pixelcolor::Rgb888; +use embedded_graphics::prelude::*; +use embedded_graphics::primitives::Rectangle; +use embedded_graphics::Pixel; +use heapless::{Entry, FnvIndexMap}; +use tinybmp::Bmp; +use {defmt_rtt as _, panic_probe as _}; + +const DISPLAY_WIDTH: usize = 480; +const DISPLAY_HEIGHT: usize = 272; +const MY_TASK_POOL_SIZE: usize = 2; + +// the following two display buffers consume 261120 bytes that just about fits into axis ram found on the mcu +pub static mut FB1: [TargetPixelType; DISPLAY_WIDTH * DISPLAY_HEIGHT] = [0; DISPLAY_WIDTH * DISPLAY_HEIGHT]; +pub static mut FB2: [TargetPixelType; DISPLAY_WIDTH * DISPLAY_HEIGHT] = [0; DISPLAY_WIDTH * DISPLAY_HEIGHT]; + +bind_interrupts!(struct Irqs { + LTDC => ltdc::InterruptHandler; +}); + +const NUM_COLORS: usize = 256; + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = rcc_setup::stm32h735g_init(); + + // blink the led on another task + let led = Output::new(p.PC3, Level::High, Speed::Low); + unwrap!(spawner.spawn(led_task(led))); + + // numbers from STMicroelectronics/STM32CubeH7 STM32H735G-DK C-based example + const RK043FN48H_HSYNC: u16 = 41; // Horizontal synchronization + const RK043FN48H_HBP: u16 = 13; // Horizontal back porch + const RK043FN48H_HFP: u16 = 32; // Horizontal front porch + const RK043FN48H_VSYNC: u16 = 10; // Vertical synchronization + const RK043FN48H_VBP: u16 = 2; // Vertical back porch + const RK043FN48H_VFP: u16 = 2; // Vertical front porch + + let ltdc_config = LtdcConfiguration { + active_width: DISPLAY_WIDTH as _, + active_height: DISPLAY_HEIGHT as _, + h_back_porch: RK043FN48H_HBP - 11, // -11 from MX_LTDC_Init + h_front_porch: RK043FN48H_HFP, + v_back_porch: RK043FN48H_VBP, + v_front_porch: RK043FN48H_VFP, + h_sync: RK043FN48H_HSYNC, + v_sync: RK043FN48H_VSYNC, + h_sync_polarity: PolarityActive::ActiveLow, + v_sync_polarity: PolarityActive::ActiveLow, + data_enable_polarity: PolarityActive::ActiveHigh, + pixel_clock_polarity: PolarityEdge::FallingEdge, + }; + + info!("init ltdc"); + let mut ltdc = Ltdc::new_with_pins( + p.LTDC, Irqs, p.PG7, p.PC6, p.PA4, p.PG14, p.PD0, p.PD6, p.PA8, p.PE12, p.PA3, p.PB8, p.PB9, p.PB1, p.PB0, + p.PA6, p.PE11, p.PH15, p.PH4, p.PC7, p.PD3, p.PE0, p.PH3, p.PH8, p.PH9, p.PH10, p.PH11, p.PE1, p.PE15, + ); + ltdc.init(<dc_config); + + // we only need to draw on one layer for this example (not to be confused with the double buffer) + info!("enable bottom layer"); + let layer_config = LtdcLayerConfig { + pixel_format: ltdc::PixelFormat::L8, // 1 byte per pixel + layer: LtdcLayer::Layer1, + window_x0: 0, + window_x1: DISPLAY_WIDTH as _, + window_y0: 0, + window_y1: DISPLAY_HEIGHT as _, + }; + + let ferris_bmp: Bmp = Bmp::from_slice(include_bytes!("./ferris.bmp")).unwrap(); + let color_map = build_color_lookup_map(&ferris_bmp); + let clut = build_clut(&color_map); + + // enable the bottom layer with a 256 color lookup table + ltdc.init_layer(&layer_config, Some(&clut)); + + // Safety: the DoubleBuffer controls access to the statically allocated frame buffers + // and it is the only thing that mutates their content + let mut double_buffer = DoubleBuffer::new( + unsafe { FB1.as_mut() }, + unsafe { FB2.as_mut() }, + layer_config, + color_map, + ); + + // this allows us to perform some simple animation for every frame + let mut bouncy_box = BouncyBox::new( + ferris_bmp.bounding_box(), + Rectangle::new(Point::zero(), Size::new(DISPLAY_WIDTH as u32, DISPLAY_HEIGHT as u32)), + 2, + ); + + loop { + // cpu intensive drawing to the buffer that is NOT currently being copied to the LCD screen + double_buffer.clear(); + let position = bouncy_box.next_point(); + let ferris = Image::new(&ferris_bmp, position); + unwrap!(ferris.draw(&mut double_buffer)); + + // perform async dma data transfer to the lcd screen + unwrap!(double_buffer.swap(&mut ltdc).await); + } +} + +/// builds the color look-up table from all unique colors found in the bitmap. This should be a 256 color indexed bitmap to work. +fn build_color_lookup_map(bmp: &Bmp) -> FnvIndexMap { + let mut color_map: FnvIndexMap = heapless::FnvIndexMap::new(); + let mut counter: u8 = 0; + + // add black to position 0 + color_map.insert(Rgb888::new(0, 0, 0).into_storage(), counter).unwrap(); + counter += 1; + + for Pixel(_point, color) in bmp.pixels() { + let raw = color.into_storage(); + if let Entry::Vacant(v) = color_map.entry(raw) { + v.insert(counter).expect("more than 256 colors detected"); + counter += 1; + } + } + color_map +} + +/// builds the color look-up table from the color map provided +fn build_clut(color_map: &FnvIndexMap) -> [ltdc::RgbColor; NUM_COLORS] { + let mut clut = [ltdc::RgbColor::default(); NUM_COLORS]; + for (color, index) in color_map.iter() { + let color = Rgb888::from(RawU24::new(*color)); + clut[*index as usize] = ltdc::RgbColor { + red: color.r(), + green: color.g(), + blue: color.b(), + }; + } + + clut +} + +#[embassy_executor::task(pool_size = MY_TASK_POOL_SIZE)] +async fn led_task(mut led: Output<'static>) { + let mut counter = 0; + loop { + info!("blink: {}", counter); + counter += 1; + + // on + led.set_low(); + Timer::after(Duration::from_millis(50)).await; + + // off + led.set_high(); + Timer::after(Duration::from_millis(450)).await; + } +} + +pub type TargetPixelType = u8; + +// A simple double buffer +pub struct DoubleBuffer { + buf0: &'static mut [TargetPixelType], + buf1: &'static mut [TargetPixelType], + is_buf0: bool, + layer_config: LtdcLayerConfig, + color_map: FnvIndexMap, +} + +impl DoubleBuffer { + pub fn new( + buf0: &'static mut [TargetPixelType], + buf1: &'static mut [TargetPixelType], + layer_config: LtdcLayerConfig, + color_map: FnvIndexMap, + ) -> Self { + Self { + buf0, + buf1, + is_buf0: true, + layer_config, + color_map, + } + } + + pub fn current(&mut self) -> (&FnvIndexMap, &mut [TargetPixelType]) { + if self.is_buf0 { + (&self.color_map, self.buf0) + } else { + (&self.color_map, self.buf1) + } + } + + pub async fn swap(&mut self, ltdc: &mut Ltdc<'_, T>) -> Result<(), ltdc::Error> { + let (_, buf) = self.current(); + let frame_buffer = buf.as_ptr(); + self.is_buf0 = !self.is_buf0; + ltdc.set_buffer(self.layer_config.layer, frame_buffer as *const _).await + } + + /// Clears the buffer + pub fn clear(&mut self) { + let (color_map, buf) = self.current(); + let black = Rgb888::new(0, 0, 0).into_storage(); + let color_index = color_map.get(&black).expect("no black found in the color map"); + + for a in buf.iter_mut() { + *a = *color_index; // solid black + } + } +} + +// Implement DrawTarget for +impl DrawTarget for DoubleBuffer { + type Color = Rgb888; + type Error = (); + + /// Draw a pixel + fn draw_iter(&mut self, pixels: I) -> Result<(), Self::Error> + where + I: IntoIterator>, + { + let size = self.size(); + let width = size.width as i32; + let height = size.height as i32; + let (color_map, buf) = self.current(); + + for pixel in pixels { + let Pixel(point, color) = pixel; + + if point.x >= 0 && point.y >= 0 && point.x < width && point.y < height { + let index = point.y * width + point.x; + let raw_color = color.into_storage(); + + match color_map.get(&raw_color) { + Some(x) => { + buf[index as usize] = *x; + } + None => panic!("color not found in color map: {}", raw_color), + }; + } else { + // Ignore invalid points + } + } + + Ok(()) + } +} + +impl OriginDimensions for DoubleBuffer { + /// Return the size of the display + fn size(&self) -> Size { + Size::new( + (self.layer_config.window_x1 - self.layer_config.window_x0) as _, + (self.layer_config.window_y1 - self.layer_config.window_y0) as _, + ) + } +} + +mod rcc_setup { + + use embassy_stm32::rcc::{Hse, HseMode, *}; + use embassy_stm32::time::Hertz; + use embassy_stm32::{Config, Peripherals}; + + /// Sets up clocks for the stm32h735g mcu + /// change this if you plan to use a different microcontroller + pub fn stm32h735g_init() -> Peripherals { + /* + https://github.com/STMicroelectronics/STM32CubeH7/blob/master/Projects/STM32H735G-DK/Examples/GPIO/GPIO_EXTI/Src/main.c + @brief System Clock Configuration + The system Clock is configured as follow : + System Clock source = PLL (HSE) + SYSCLK(Hz) = 520000000 (CPU Clock) + HCLK(Hz) = 260000000 (AXI and AHBs Clock) + AHB Prescaler = 2 + D1 APB3 Prescaler = 2 (APB3 Clock 130MHz) + D2 APB1 Prescaler = 2 (APB1 Clock 130MHz) + D2 APB2 Prescaler = 2 (APB2 Clock 130MHz) + D3 APB4 Prescaler = 2 (APB4 Clock 130MHz) + HSE Frequency(Hz) = 25000000 + PLL_M = 5 + PLL_N = 104 + PLL_P = 1 + PLL_Q = 4 + PLL_R = 2 + VDD(V) = 3.3 + Flash Latency(WS) = 3 + */ + + // setup power and clocks for an stm32h735g-dk run from an external 25 Mhz external oscillator + let mut config = Config::default(); + config.rcc.hse = Some(Hse { + freq: Hertz::mhz(25), + mode: HseMode::Oscillator, + }); + config.rcc.hsi = None; + config.rcc.csi = false; + config.rcc.pll1 = Some(Pll { + source: PllSource::HSE, + prediv: PllPreDiv::DIV5, // PLL_M + mul: PllMul::MUL104, // PLL_N + divp: Some(PllDiv::DIV1), + divq: Some(PllDiv::DIV4), + divr: Some(PllDiv::DIV2), + }); + // numbers adapted from Drivers/BSP/STM32H735G-DK/stm32h735g_discovery_ospi.c + // MX_OSPI_ClockConfig + config.rcc.pll2 = Some(Pll { + source: PllSource::HSE, + prediv: PllPreDiv::DIV5, // PLL_M + mul: PllMul::MUL80, // PLL_N + divp: Some(PllDiv::DIV5), + divq: Some(PllDiv::DIV2), + divr: Some(PllDiv::DIV2), + }); + // numbers adapted from Drivers/BSP/STM32H735G-DK/stm32h735g_discovery_lcd.c + // MX_LTDC_ClockConfig + config.rcc.pll3 = Some(Pll { + source: PllSource::HSE, + prediv: PllPreDiv::DIV5, // PLL_M + mul: PllMul::MUL160, // PLL_N + divp: Some(PllDiv::DIV2), + divq: Some(PllDiv::DIV2), + divr: Some(PllDiv::DIV83), + }); + config.rcc.voltage_scale = VoltageScale::Scale0; + config.rcc.supply_config = SupplyConfig::DirectSMPS; + config.rcc.sys = Sysclk::PLL1_P; + config.rcc.ahb_pre = AHBPrescaler::DIV2; + config.rcc.apb1_pre = APBPrescaler::DIV2; + config.rcc.apb2_pre = APBPrescaler::DIV2; + config.rcc.apb3_pre = APBPrescaler::DIV2; + config.rcc.apb4_pre = APBPrescaler::DIV2; + embassy_stm32::init(config) + } +} + +mod bouncy_box { + use embedded_graphics::geometry::Point; + use embedded_graphics::primitives::Rectangle; + + enum Direction { + DownLeft, + DownRight, + UpLeft, + UpRight, + } + + pub struct BouncyBox { + direction: Direction, + child_rect: Rectangle, + parent_rect: Rectangle, + current_point: Point, + move_by: usize, + } + + // This calculates the coordinates of a chile rectangle bounced around inside a parent bounded box + impl BouncyBox { + pub fn new(child_rect: Rectangle, parent_rect: Rectangle, move_by: usize) -> Self { + let center_box = parent_rect.center(); + let center_img = child_rect.center(); + let current_point = Point::new(center_box.x - center_img.x / 2, center_box.y - center_img.y / 2); + Self { + direction: Direction::DownRight, + child_rect, + parent_rect, + current_point, + move_by, + } + } + + pub fn next_point(&mut self) -> Point { + let direction = &self.direction; + let img_height = self.child_rect.size.height as i32; + let box_height = self.parent_rect.size.height as i32; + let img_width = self.child_rect.size.width as i32; + let box_width = self.parent_rect.size.width as i32; + let move_by = self.move_by as i32; + + match direction { + Direction::DownLeft => { + self.current_point.x -= move_by; + self.current_point.y += move_by; + + let x_out_of_bounds = self.current_point.x < 0; + let y_out_of_bounds = (self.current_point.y + img_height) > box_height; + + if x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::UpRight + } else if x_out_of_bounds && !y_out_of_bounds { + self.direction = Direction::DownRight + } else if !x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::UpLeft + } + } + Direction::DownRight => { + self.current_point.x += move_by; + self.current_point.y += move_by; + + let x_out_of_bounds = (self.current_point.x + img_width) > box_width; + let y_out_of_bounds = (self.current_point.y + img_height) > box_height; + + if x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::UpLeft + } else if x_out_of_bounds && !y_out_of_bounds { + self.direction = Direction::DownLeft + } else if !x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::UpRight + } + } + Direction::UpLeft => { + self.current_point.x -= move_by; + self.current_point.y -= move_by; + + let x_out_of_bounds = self.current_point.x < 0; + let y_out_of_bounds = self.current_point.y < 0; + + if x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::DownRight + } else if x_out_of_bounds && !y_out_of_bounds { + self.direction = Direction::UpRight + } else if !x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::DownLeft + } + } + Direction::UpRight => { + self.current_point.x += move_by; + self.current_point.y -= move_by; + + let x_out_of_bounds = (self.current_point.x + img_width) > box_width; + let y_out_of_bounds = self.current_point.y < 0; + + if x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::DownLeft + } else if x_out_of_bounds && !y_out_of_bounds { + self.direction = Direction::UpLeft + } else if !x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::DownRight + } + } + } + + self.current_point + } + } +} diff --git a/examples/stm32h755cm4/.cargo/config.toml b/examples/stm32h755cm4/.cargo/config.toml new file mode 100644 index 000000000..193e6bbc3 --- /dev/null +++ b/examples/stm32h755cm4/.cargo/config.toml @@ -0,0 +1,8 @@ +[target.thumbv7em-none-eabihf] +runner = 'probe-rs run --chip STM32H755ZITx --catch-hardfault --always-print-stacktrace' + +[build] +target = "thumbv7em-none-eabihf" # Cortex-M4F and Cortex-M7F (with FPU) + +[env] +DEFMT_LOG = "trace" diff --git a/examples/stm32h755cm4/Cargo.toml b/examples/stm32h755cm4/Cargo.toml new file mode 100644 index 000000000..ee96e64d6 --- /dev/null +++ b/examples/stm32h755cm4/Cargo.toml @@ -0,0 +1,75 @@ +[package] +edition = "2021" +name = "embassy-stm32h755cm4-examples" +version = "0.1.0" +license = "MIT OR Apache-2.0" + +[dependencies] +# Change stm32h755zi-cm4 to your chip name, if necessary. +embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32h755zi-cm4", "time-driver-tim2", "exti", "memory-x", "unstable-pac", "chrono"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-embedded-hal = { version = "0.2.0", path = "../../embassy-embedded-hal" } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.1", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", "proto-ipv6", "dns"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } + +defmt = "0.3" +defmt-rtt = "0.4" + +cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } +cortex-m-rt = "0.7.0" +embedded-hal = "0.2.6" +embedded-hal-1 = { package = "embedded-hal", version = "1.0" } +embedded-hal-async = { version = "1.0" } +embedded-nal-async = "0.8.0" +embedded-io-async = { version = "0.6.1" } +panic-probe = { version = "0.3", features = ["print-defmt"] } +heapless = { version = "0.8", default-features = false } +rand_core = "0.6.3" +critical-section = "1.1" +micromath = "2.0.0" +stm32-fmc = "0.3.0" +embedded-storage = "0.3.1" +static_cell = "2" +chrono = { version = "^0.4", default-features = false } +grounded = "0.2.0" + +# cargo build/run +[profile.dev] +codegen-units = 1 +debug = 2 +debug-assertions = true # <- +incremental = false +opt-level = 3 # <- +overflow-checks = true # <- + +# cargo test +[profile.test] +codegen-units = 1 +debug = 2 +debug-assertions = true # <- +incremental = false +opt-level = 3 # <- +overflow-checks = true # <- + +# cargo build/run --release +[profile.release] +codegen-units = 1 +debug = 2 +debug-assertions = false # <- +incremental = false +lto = 'fat' +opt-level = 3 # <- +overflow-checks = false # <- + +# cargo test --release +[profile.bench] +codegen-units = 1 +debug = 2 +debug-assertions = false # <- +incremental = false +lto = 'fat' +opt-level = 3 # <- +overflow-checks = false # <- diff --git a/examples/stm32h755cm4/build.rs b/examples/stm32h755cm4/build.rs new file mode 100644 index 000000000..30691aa97 --- /dev/null +++ b/examples/stm32h755cm4/build.rs @@ -0,0 +1,35 @@ +//! This build script copies the `memory.x` file from the crate root into +//! a directory where the linker can always find it at build time. +//! For many projects this is optional, as the linker always searches the +//! project root directory -- wherever `Cargo.toml` is. However, if you +//! are using a workspace or have a more complicated build setup, this +//! build script becomes required. Additionally, by requesting that +//! Cargo re-run the build script whenever `memory.x` is changed, +//! updating `memory.x` ensures a rebuild of the application with the +//! new memory settings. + +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; + +fn main() { + // Put `memory.x` in our output directory and ensure it's + // on the linker search path. + let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); + File::create(out.join("memory.x")) + .unwrap() + .write_all(include_bytes!("memory.x")) + .unwrap(); + println!("cargo:rustc-link-search={}", out.display()); + + // By default, Cargo will re-run a build script whenever + // any file in the project changes. By specifying `memory.x` + // here, we ensure the build script is only re-run when + // `memory.x` is changed. + println!("cargo:rerun-if-changed=memory.x"); + + println!("cargo:rustc-link-arg-bins=--nmagic"); + println!("cargo:rustc-link-arg-bins=-Tlink.x"); + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); +} diff --git a/examples/stm32h755cm4/memory.x b/examples/stm32h755cm4/memory.x new file mode 100644 index 000000000..7d60354e3 --- /dev/null +++ b/examples/stm32h755cm4/memory.x @@ -0,0 +1,15 @@ +MEMORY +{ + FLASH : ORIGIN = 0x08100000, LENGTH = 1024K /* BANK_2 */ + RAM : ORIGIN = 0x10000000, LENGTH = 128K /* SRAM1 */ + RAM_D3 : ORIGIN = 0x38000000, LENGTH = 64K /* SRAM4 */ +} + +SECTIONS +{ + .ram_d3 : + { + *(.ram_d3.shared_data) + *(.ram_d3) + } > RAM_D3 +} \ No newline at end of file diff --git a/examples/stm32h755cm4/src/bin/blinky.rs b/examples/stm32h755cm4/src/bin/blinky.rs new file mode 100644 index 000000000..b5c547839 --- /dev/null +++ b/examples/stm32h755cm4/src/bin/blinky.rs @@ -0,0 +1,32 @@ +#![no_std] +#![no_main] + +use core::mem::MaybeUninit; + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::SharedData; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".ram_d3.shared_data"] +static SHARED_DATA: MaybeUninit = MaybeUninit::uninit(); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init_secondary(&SHARED_DATA); + info!("Hello World!"); + + let mut led = Output::new(p.PE1, Level::High, Speed::Low); + + loop { + info!("high"); + led.set_high(); + Timer::after_millis(250).await; + + info!("low"); + led.set_low(); + Timer::after_millis(250).await; + } +} diff --git a/examples/stm32h755cm7/.cargo/config.toml b/examples/stm32h755cm7/.cargo/config.toml new file mode 100644 index 000000000..193e6bbc3 --- /dev/null +++ b/examples/stm32h755cm7/.cargo/config.toml @@ -0,0 +1,8 @@ +[target.thumbv7em-none-eabihf] +runner = 'probe-rs run --chip STM32H755ZITx --catch-hardfault --always-print-stacktrace' + +[build] +target = "thumbv7em-none-eabihf" # Cortex-M4F and Cortex-M7F (with FPU) + +[env] +DEFMT_LOG = "trace" diff --git a/examples/stm32h755cm7/Cargo.toml b/examples/stm32h755cm7/Cargo.toml new file mode 100644 index 000000000..61c425719 --- /dev/null +++ b/examples/stm32h755cm7/Cargo.toml @@ -0,0 +1,75 @@ +[package] +edition = "2021" +name = "embassy-stm32h755cm7-examples" +version = "0.1.0" +license = "MIT OR Apache-2.0" + +[dependencies] +# Change stm32h743bi to your chip name, if necessary. +embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32h755zi-cm7", "time-driver-tim3", "exti", "memory-x", "unstable-pac", "chrono"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-embedded-hal = { version = "0.2.0", path = "../../embassy-embedded-hal" } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.1", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", "proto-ipv6", "dns"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } + +defmt = "0.3" +defmt-rtt = "0.4" + +cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } +cortex-m-rt = "0.7.0" +embedded-hal = "0.2.6" +embedded-hal-1 = { package = "embedded-hal", version = "1.0" } +embedded-hal-async = { version = "1.0" } +embedded-nal-async = "0.8.0" +embedded-io-async = { version = "0.6.1" } +panic-probe = { version = "0.3", features = ["print-defmt"] } +heapless = { version = "0.8", default-features = false } +rand_core = "0.6.3" +critical-section = "1.1" +micromath = "2.0.0" +stm32-fmc = "0.3.0" +embedded-storage = "0.3.1" +static_cell = "2" +chrono = { version = "^0.4", default-features = false } +grounded = "0.2.0" + +# cargo build/run +[profile.dev] +codegen-units = 1 +debug = 2 +debug-assertions = true # <- +incremental = false +opt-level = 3 # <- +overflow-checks = true # <- + +# cargo test +[profile.test] +codegen-units = 1 +debug = 2 +debug-assertions = true # <- +incremental = false +opt-level = 3 # <- +overflow-checks = true # <- + +# cargo build/run --release +[profile.release] +codegen-units = 1 +debug = 2 +debug-assertions = false # <- +incremental = false +lto = 'fat' +opt-level = 3 # <- +overflow-checks = false # <- + +# cargo test --release +[profile.bench] +codegen-units = 1 +debug = 2 +debug-assertions = false # <- +incremental = false +lto = 'fat' +opt-level = 3 # <- +overflow-checks = false # <- diff --git a/examples/stm32h755cm7/build.rs b/examples/stm32h755cm7/build.rs new file mode 100644 index 000000000..30691aa97 --- /dev/null +++ b/examples/stm32h755cm7/build.rs @@ -0,0 +1,35 @@ +//! This build script copies the `memory.x` file from the crate root into +//! a directory where the linker can always find it at build time. +//! For many projects this is optional, as the linker always searches the +//! project root directory -- wherever `Cargo.toml` is. However, if you +//! are using a workspace or have a more complicated build setup, this +//! build script becomes required. Additionally, by requesting that +//! Cargo re-run the build script whenever `memory.x` is changed, +//! updating `memory.x` ensures a rebuild of the application with the +//! new memory settings. + +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; + +fn main() { + // Put `memory.x` in our output directory and ensure it's + // on the linker search path. + let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); + File::create(out.join("memory.x")) + .unwrap() + .write_all(include_bytes!("memory.x")) + .unwrap(); + println!("cargo:rustc-link-search={}", out.display()); + + // By default, Cargo will re-run a build script whenever + // any file in the project changes. By specifying `memory.x` + // here, we ensure the build script is only re-run when + // `memory.x` is changed. + println!("cargo:rerun-if-changed=memory.x"); + + println!("cargo:rustc-link-arg-bins=--nmagic"); + println!("cargo:rustc-link-arg-bins=-Tlink.x"); + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); +} diff --git a/examples/stm32h755cm7/memory.x b/examples/stm32h755cm7/memory.x new file mode 100644 index 000000000..ef884796a --- /dev/null +++ b/examples/stm32h755cm7/memory.x @@ -0,0 +1,15 @@ +MEMORY +{ + FLASH : ORIGIN = 0x08000000, LENGTH = 1024K /* BANK_1 */ + RAM : ORIGIN = 0x24000000, LENGTH = 512K /* AXIRAM */ + RAM_D3 : ORIGIN = 0x38000000, LENGTH = 64K /* SRAM4 */ +} + +SECTIONS +{ + .ram_d3 : + { + *(.ram_d3.shared_data) + *(.ram_d3) + } > RAM_D3 +} \ No newline at end of file diff --git a/examples/stm32h755cm7/src/bin/blinky.rs b/examples/stm32h755cm7/src/bin/blinky.rs new file mode 100644 index 000000000..94d2226c0 --- /dev/null +++ b/examples/stm32h755cm7/src/bin/blinky.rs @@ -0,0 +1,54 @@ +#![no_std] +#![no_main] + +use core::mem::MaybeUninit; + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::SharedData; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[link_section = ".ram_d3.shared_data"] +static SHARED_DATA: MaybeUninit = MaybeUninit::uninit(); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = embassy_stm32::Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.hsi = Some(HSIPrescaler::DIV1); + config.rcc.csi = true; + config.rcc.pll1 = Some(Pll { + source: PllSource::HSI, + prediv: PllPreDiv::DIV4, + mul: PllMul::MUL50, + divp: Some(PllDiv::DIV2), + divq: Some(PllDiv::DIV8), // 100mhz + divr: None, + }); + config.rcc.sys = Sysclk::PLL1_P; // 400 Mhz + config.rcc.ahb_pre = AHBPrescaler::DIV2; // 200 Mhz + config.rcc.apb1_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.apb2_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.apb3_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.apb4_pre = APBPrescaler::DIV2; // 100 Mhz + config.rcc.voltage_scale = VoltageScale::Scale1; + config.rcc.supply_config = SupplyConfig::DirectSMPS; + } + let p = embassy_stm32::init_primary(config, &SHARED_DATA); + info!("Hello World!"); + + let mut led = Output::new(p.PB14, Level::High, Speed::Low); + + loop { + info!("high"); + led.set_high(); + Timer::after_millis(500).await; + + info!("low"); + led.set_low(); + Timer::after_millis(500).await; + } +} diff --git a/examples/stm32h7b0/.cargo/config.toml b/examples/stm32h7b0/.cargo/config.toml new file mode 100644 index 000000000..870849a27 --- /dev/null +++ b/examples/stm32h7b0/.cargo/config.toml @@ -0,0 +1,8 @@ +[target.thumbv7em-none-eabihf] +runner = 'probe-rs run --chip STM32H7B0VBTx' + +[build] +target = "thumbv7em-none-eabihf" # Cortex-M4F and Cortex-M7F (with FPU) + +[env] +DEFMT_LOG = "trace" diff --git a/examples/stm32h7b0/Cargo.toml b/examples/stm32h7b0/Cargo.toml new file mode 100644 index 000000000..255ce933c --- /dev/null +++ b/examples/stm32h7b0/Cargo.toml @@ -0,0 +1,74 @@ +[package] +edition = "2021" +name = "embassy-stm32h7b0-examples" +version = "0.1.0" +license = "MIT OR Apache-2.0" + +[dependencies] +embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32h7b0vb", "time-driver-tim2", "exti", "memory-x", "unstable-pac", "chrono"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-embedded-hal = { version = "0.2.0", path = "../../embassy-embedded-hal" } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", "proto-ipv6", "dns"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } + +defmt = "0.3" +defmt-rtt = "0.4" + +cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } +cortex-m-rt = "0.7.0" +embedded-hal = "0.2.6" +embedded-hal-1 = { package = "embedded-hal", version = "1.0" } +embedded-hal-async = { version = "1.0" } +embedded-nal-async = "0.8.0" +embedded-io-async = { version = "0.6.1" } +panic-probe = { version = "0.3", features = ["print-defmt"] } +heapless = { version = "0.8", default-features = false } +rand_core = "0.6.3" +critical-section = "1.1" +micromath = "2.0.0" +stm32-fmc = "0.3.0" +embedded-storage = "0.3.1" +static_cell = "2" +chrono = { version = "^0.4", default-features = false } +grounded = "0.2.0" + +# cargo build/run +[profile.dev] +codegen-units = 1 +debug = 2 +debug-assertions = true # <- +incremental = false +opt-level = 3 # <- +overflow-checks = true # <- + +# cargo test +[profile.test] +codegen-units = 1 +debug = 2 +debug-assertions = true # <- +incremental = false +opt-level = 3 # <- +overflow-checks = true # <- + +# cargo build/run --release +[profile.release] +codegen-units = 1 +debug = 2 +debug-assertions = false # <- +incremental = false +lto = 'fat' +opt-level = 3 # <- +overflow-checks = false # <- + +# cargo test --release +[profile.bench] +codegen-units = 1 +debug = 2 +debug-assertions = false # <- +incremental = false +lto = 'fat' +opt-level = 3 # <- +overflow-checks = false # <- diff --git a/examples/stm32h7b0/build.rs b/examples/stm32h7b0/build.rs new file mode 100644 index 000000000..30691aa97 --- /dev/null +++ b/examples/stm32h7b0/build.rs @@ -0,0 +1,35 @@ +//! This build script copies the `memory.x` file from the crate root into +//! a directory where the linker can always find it at build time. +//! For many projects this is optional, as the linker always searches the +//! project root directory -- wherever `Cargo.toml` is. However, if you +//! are using a workspace or have a more complicated build setup, this +//! build script becomes required. Additionally, by requesting that +//! Cargo re-run the build script whenever `memory.x` is changed, +//! updating `memory.x` ensures a rebuild of the application with the +//! new memory settings. + +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; + +fn main() { + // Put `memory.x` in our output directory and ensure it's + // on the linker search path. + let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); + File::create(out.join("memory.x")) + .unwrap() + .write_all(include_bytes!("memory.x")) + .unwrap(); + println!("cargo:rustc-link-search={}", out.display()); + + // By default, Cargo will re-run a build script whenever + // any file in the project changes. By specifying `memory.x` + // here, we ensure the build script is only re-run when + // `memory.x` is changed. + println!("cargo:rerun-if-changed=memory.x"); + + println!("cargo:rustc-link-arg-bins=--nmagic"); + println!("cargo:rustc-link-arg-bins=-Tlink.x"); + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); +} diff --git a/examples/stm32h7b0/memory.x b/examples/stm32h7b0/memory.x new file mode 100644 index 000000000..6eb1bb7c1 --- /dev/null +++ b/examples/stm32h7b0/memory.x @@ -0,0 +1,5 @@ +MEMORY +{ + FLASH : ORIGIN = 0x08000000, LENGTH = 128K /* BANK_1 */ + RAM : ORIGIN = 0x24000000, LENGTH = 512K /* SRAM */ +} \ No newline at end of file diff --git a/examples/stm32h7b0/src/bin/ospi_memory_mapped.rs b/examples/stm32h7b0/src/bin/ospi_memory_mapped.rs new file mode 100644 index 000000000..9c397e507 --- /dev/null +++ b/examples/stm32h7b0/src/bin/ospi_memory_mapped.rs @@ -0,0 +1,433 @@ +#![no_main] +#![no_std] + +// Tested on weact stm32h7b0 board + w25q64 spi flash + +use defmt::info; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::mode::Blocking; +use embassy_stm32::ospi::{ + AddressSize, ChipSelectHighTime, DummyCycles, FIFOThresholdLevel, Instance, MemorySize, MemoryType, Ospi, + OspiWidth, TransferConfig, WrapSize, +}; +use embassy_stm32::time::Hertz; +use embassy_stm32::Config; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + // RCC config + let mut config = Config::default(); + info!("START"); + { + use embassy_stm32::rcc::*; + config.rcc.hsi = Some(HSIPrescaler::DIV1); + config.rcc.csi = true; + // Needed for USB + config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true }); + // External oscillator 25MHZ + config.rcc.hse = Some(Hse { + freq: Hertz(25_000_000), + mode: HseMode::Oscillator, + }); + config.rcc.pll1 = Some(Pll { + source: PllSource::HSE, + prediv: PllPreDiv::DIV5, + mul: PllMul::MUL112, + divp: Some(PllDiv::DIV2), + divq: Some(PllDiv::DIV2), + divr: Some(PllDiv::DIV2), + }); + config.rcc.sys = Sysclk::PLL1_P; + config.rcc.ahb_pre = AHBPrescaler::DIV2; + config.rcc.apb1_pre = APBPrescaler::DIV2; + config.rcc.apb2_pre = APBPrescaler::DIV2; + config.rcc.apb3_pre = APBPrescaler::DIV2; + config.rcc.apb4_pre = APBPrescaler::DIV2; + config.rcc.voltage_scale = VoltageScale::Scale0; + } + + // Initialize peripherals + let p = embassy_stm32::init(config); + + let qspi_config = embassy_stm32::ospi::Config { + fifo_threshold: FIFOThresholdLevel::_16Bytes, + memory_type: MemoryType::Micron, + device_size: MemorySize::_8MiB, + chip_select_high_time: ChipSelectHighTime::_1Cycle, + free_running_clock: false, + clock_mode: false, + wrap_size: WrapSize::None, + clock_prescaler: 4, + sample_shifting: true, + delay_hold_quarter_cycle: false, + chip_select_boundary: 0, + delay_block_bypass: true, + max_transfer: 0, + refresh: 0, + }; + let ospi = embassy_stm32::ospi::Ospi::new_blocking_quadspi( + p.OCTOSPI1, + p.PB2, + p.PD11, + p.PD12, + p.PE2, + p.PD13, + p.PB6, + qspi_config, + ); + + let mut flash = FlashMemory::new(ospi).await; + + let flash_id = flash.read_id(); + info!("FLASH ID: {=[u8]:x}", flash_id); + let mut wr_buf = [0u8; 8]; + for i in 0..8 { + wr_buf[i] = i as u8; + } + let mut rd_buf = [0u8; 8]; + flash.erase_sector(0).await; + flash.write_memory(0, &wr_buf, true).await; + flash.read_memory(0, &mut rd_buf, true); + info!("WRITE BUF: {=[u8]:#X}", wr_buf); + info!("READ BUF: {=[u8]:#X}", rd_buf); + flash.enable_mm().await; + info!("Enabled memory mapped mode"); + + let first_u32 = unsafe { *(0x90000000 as *const u32) }; + assert_eq!(first_u32, 0x03020100); + + let second_u32 = unsafe { *(0x90000004 as *const u32) }; + assert_eq!(second_u32, 0x07060504); + flash.disable_mm().await; + + info!("DONE"); + // Output pin PE3 + let mut led = Output::new(p.PE3, Level::Low, Speed::Low); + + loop { + led.toggle(); + Timer::after_millis(1000).await; + } +} + +const MEMORY_PAGE_SIZE: usize = 8; + +const CMD_QUAD_READ: u8 = 0x6B; + +const CMD_QUAD_WRITE_PG: u8 = 0x32; + +const CMD_READ_ID: u8 = 0x9F; + +const CMD_ENABLE_RESET: u8 = 0x66; +const CMD_RESET: u8 = 0x99; + +const CMD_WRITE_ENABLE: u8 = 0x06; + +const CMD_CHIP_ERASE: u8 = 0xC7; +const CMD_SECTOR_ERASE: u8 = 0x20; +const CMD_BLOCK_ERASE_32K: u8 = 0x52; +const CMD_BLOCK_ERASE_64K: u8 = 0xD8; + +const CMD_READ_SR: u8 = 0x05; +const CMD_READ_CR: u8 = 0x35; + +const CMD_WRITE_SR: u8 = 0x01; +const CMD_WRITE_CR: u8 = 0x31; + +/// Implementation of access to flash chip. +/// Chip commands are hardcoded as it depends on used chip. +/// This implementation is using chip GD25Q64C from Giga Device +pub struct FlashMemory { + ospi: Ospi<'static, I, Blocking>, +} + +impl FlashMemory { + pub async fn new(ospi: Ospi<'static, I, Blocking>) -> Self { + let mut memory = Self { ospi }; + + memory.reset_memory().await; + memory.enable_quad(); + memory + } + + async fn qpi_mode(&mut self) { + // Enter qpi mode + self.exec_command(0x38).await; + + // Set read param + let transaction = TransferConfig { + iwidth: OspiWidth::QUAD, + dwidth: OspiWidth::QUAD, + instruction: Some(0xC0), + ..Default::default() + }; + self.enable_write().await; + self.ospi.blocking_write(&[0x30_u8], transaction).unwrap(); + self.wait_write_finish(); + } + + pub async fn disable_mm(&mut self) { + self.ospi.disable_memory_mapped_mode(); + } + + pub async fn enable_mm(&mut self) { + self.qpi_mode().await; + + let read_config = TransferConfig { + iwidth: OspiWidth::QUAD, + isize: AddressSize::_8Bit, + adwidth: OspiWidth::QUAD, + adsize: AddressSize::_24bit, + dwidth: OspiWidth::QUAD, + instruction: Some(0x0B), // Fast read in QPI mode + dummy: DummyCycles::_8, + ..Default::default() + }; + + let write_config = TransferConfig { + iwidth: OspiWidth::SING, + isize: AddressSize::_8Bit, + adwidth: OspiWidth::SING, + adsize: AddressSize::_24bit, + dwidth: OspiWidth::QUAD, + instruction: Some(0x32), // Write config + dummy: DummyCycles::_0, + ..Default::default() + }; + self.ospi.enable_memory_mapped_mode(read_config, write_config).unwrap(); + } + + fn enable_quad(&mut self) { + let cr = self.read_cr(); + // info!("Read cr: {:x}", cr); + self.write_cr(cr | 0x02); + // info!("Read cr after writing: {:x}", cr); + } + + pub fn disable_quad(&mut self) { + let cr = self.read_cr(); + self.write_cr(cr & (!(0x02))); + } + + async fn exec_command_4(&mut self, cmd: u8) { + let transaction = TransferConfig { + iwidth: OspiWidth::QUAD, + adwidth: OspiWidth::NONE, + // adsize: AddressSize::_24bit, + dwidth: OspiWidth::NONE, + instruction: Some(cmd as u32), + address: None, + dummy: DummyCycles::_0, + ..Default::default() + }; + self.ospi.command(&transaction).await.unwrap(); + } + + async fn exec_command(&mut self, cmd: u8) { + let transaction = TransferConfig { + iwidth: OspiWidth::SING, + adwidth: OspiWidth::NONE, + // adsize: AddressSize::_24bit, + dwidth: OspiWidth::NONE, + instruction: Some(cmd as u32), + address: None, + dummy: DummyCycles::_0, + ..Default::default() + }; + // info!("Excuting command: {:x}", transaction.instruction); + self.ospi.command(&transaction).await.unwrap(); + } + + pub async fn reset_memory(&mut self) { + self.exec_command_4(CMD_ENABLE_RESET).await; + self.exec_command_4(CMD_RESET).await; + self.exec_command(CMD_ENABLE_RESET).await; + self.exec_command(CMD_RESET).await; + self.wait_write_finish(); + } + + pub async fn enable_write(&mut self) { + self.exec_command(CMD_WRITE_ENABLE).await; + } + + pub fn read_id(&mut self) -> [u8; 3] { + let mut buffer = [0; 3]; + let transaction: TransferConfig = TransferConfig { + iwidth: OspiWidth::SING, + isize: AddressSize::_8Bit, + adwidth: OspiWidth::NONE, + // adsize: AddressSize::_24bit, + dwidth: OspiWidth::SING, + instruction: Some(CMD_READ_ID as u32), + ..Default::default() + }; + // info!("Reading id: 0x{:X}", transaction.instruction); + self.ospi.blocking_read(&mut buffer, transaction).unwrap(); + buffer + } + + pub fn read_id_4(&mut self) -> [u8; 3] { + let mut buffer = [0; 3]; + let transaction: TransferConfig = TransferConfig { + iwidth: OspiWidth::SING, + isize: AddressSize::_8Bit, + adwidth: OspiWidth::NONE, + dwidth: OspiWidth::QUAD, + instruction: Some(CMD_READ_ID as u32), + ..Default::default() + }; + info!("Reading id: 0x{:X}", transaction.instruction); + self.ospi.blocking_read(&mut buffer, transaction).unwrap(); + buffer + } + + pub fn read_memory(&mut self, addr: u32, buffer: &mut [u8], use_dma: bool) { + let transaction = TransferConfig { + iwidth: OspiWidth::SING, + adwidth: OspiWidth::SING, + adsize: AddressSize::_24bit, + dwidth: OspiWidth::QUAD, + instruction: Some(CMD_QUAD_READ as u32), + address: Some(addr), + dummy: DummyCycles::_8, + ..Default::default() + }; + if use_dma { + self.ospi.blocking_read(buffer, transaction).unwrap(); + } else { + self.ospi.blocking_read(buffer, transaction).unwrap(); + } + } + + fn wait_write_finish(&mut self) { + while (self.read_sr() & 0x01) != 0 {} + } + + async fn perform_erase(&mut self, addr: u32, cmd: u8) { + let transaction = TransferConfig { + iwidth: OspiWidth::SING, + adwidth: OspiWidth::SING, + adsize: AddressSize::_24bit, + dwidth: OspiWidth::NONE, + instruction: Some(cmd as u32), + address: Some(addr), + dummy: DummyCycles::_0, + ..Default::default() + }; + self.enable_write().await; + self.ospi.command(&transaction).await.unwrap(); + self.wait_write_finish(); + } + + pub async fn erase_sector(&mut self, addr: u32) { + self.perform_erase(addr, CMD_SECTOR_ERASE).await; + } + + pub async fn erase_block_32k(&mut self, addr: u32) { + self.perform_erase(addr, CMD_BLOCK_ERASE_32K).await; + } + + pub async fn erase_block_64k(&mut self, addr: u32) { + self.perform_erase(addr, CMD_BLOCK_ERASE_64K).await; + } + + pub async fn erase_chip(&mut self) { + self.exec_command(CMD_CHIP_ERASE).await; + } + + async fn write_page(&mut self, addr: u32, buffer: &[u8], len: usize, use_dma: bool) { + assert!( + (len as u32 + (addr & 0x000000ff)) <= MEMORY_PAGE_SIZE as u32, + "write_page(): page write length exceeds page boundary (len = {}, addr = {:X}", + len, + addr + ); + + let transaction = TransferConfig { + iwidth: OspiWidth::SING, + adsize: AddressSize::_24bit, + adwidth: OspiWidth::SING, + dwidth: OspiWidth::QUAD, + instruction: Some(CMD_QUAD_WRITE_PG as u32), + address: Some(addr), + dummy: DummyCycles::_0, + ..Default::default() + }; + self.enable_write().await; + if use_dma { + self.ospi.blocking_write(buffer, transaction).unwrap(); + } else { + self.ospi.blocking_write(buffer, transaction).unwrap(); + } + self.wait_write_finish(); + } + + pub async fn write_memory(&mut self, addr: u32, buffer: &[u8], use_dma: bool) { + let mut left = buffer.len(); + let mut place = addr; + let mut chunk_start = 0; + + while left > 0 { + let max_chunk_size = MEMORY_PAGE_SIZE - (place & 0x000000ff) as usize; + let chunk_size = if left >= max_chunk_size { max_chunk_size } else { left }; + let chunk = &buffer[chunk_start..(chunk_start + chunk_size)]; + self.write_page(place, chunk, chunk_size, use_dma).await; + place += chunk_size as u32; + left -= chunk_size; + chunk_start += chunk_size; + } + } + + fn read_register(&mut self, cmd: u8) -> u8 { + let mut buffer = [0; 1]; + let transaction: TransferConfig = TransferConfig { + iwidth: OspiWidth::SING, + isize: AddressSize::_8Bit, + adwidth: OspiWidth::NONE, + adsize: AddressSize::_24bit, + dwidth: OspiWidth::SING, + instruction: Some(cmd as u32), + address: None, + dummy: DummyCycles::_0, + ..Default::default() + }; + self.ospi.blocking_read(&mut buffer, transaction).unwrap(); + // info!("Read w25q64 register: 0x{:x}", buffer[0]); + buffer[0] + } + + fn write_register(&mut self, cmd: u8, value: u8) { + let buffer = [value; 1]; + let transaction: TransferConfig = TransferConfig { + iwidth: OspiWidth::SING, + isize: AddressSize::_8Bit, + instruction: Some(cmd as u32), + adsize: AddressSize::_24bit, + adwidth: OspiWidth::NONE, + dwidth: OspiWidth::SING, + address: None, + dummy: DummyCycles::_0, + ..Default::default() + }; + self.ospi.blocking_write(&buffer, transaction).unwrap(); + } + + pub fn read_sr(&mut self) -> u8 { + self.read_register(CMD_READ_SR) + } + + pub fn read_cr(&mut self) -> u8 { + self.read_register(CMD_READ_CR) + } + + pub fn write_sr(&mut self, value: u8) { + self.write_register(CMD_WRITE_SR, value); + } + + pub fn write_cr(&mut self, value: u8) { + self.write_register(CMD_WRITE_CR, value); + } +} diff --git a/examples/stm32h7rs/.cargo/config.toml b/examples/stm32h7rs/.cargo/config.toml new file mode 100644 index 000000000..44dbda94f --- /dev/null +++ b/examples/stm32h7rs/.cargo/config.toml @@ -0,0 +1,8 @@ +[target.thumbv7em-none-eabihf] +runner = 'probe-rs run --chip STM32H7S3L8Hx' + +[build] +target = "thumbv7em-none-eabihf" # Cortex-M4F and Cortex-M7F (with FPU) + +[env] +DEFMT_LOG = "trace" diff --git a/examples/stm32h7rs/Cargo.toml b/examples/stm32h7rs/Cargo.toml new file mode 100644 index 000000000..055be6a91 --- /dev/null +++ b/examples/stm32h7rs/Cargo.toml @@ -0,0 +1,73 @@ +[package] +edition = "2021" +name = "embassy-stm32h7rs-examples" +version = "0.1.0" +license = "MIT OR Apache-2.0" + +[dependencies] +# Change stm32h743bi to your chip name, if necessary. +embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32h7s3l8", "time-driver-tim2", "exti", "memory-x", "unstable-pac", "chrono"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", "proto-ipv6", "dns"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } + +defmt = "0.3" +defmt-rtt = "0.4" + +cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } +cortex-m-rt = "0.7.0" +embedded-hal = "0.2.6" +embedded-hal-1 = { package = "embedded-hal", version = "1.0" } +embedded-hal-async = { version = "1.0" } +embedded-nal-async = "0.8.0" +embedded-io-async = { version = "0.6.1" } +panic-probe = { version = "0.3", features = ["print-defmt"] } +heapless = { version = "0.8", default-features = false } +rand_core = "0.6.3" +critical-section = "1.1" +micromath = "2.0.0" +stm32-fmc = "0.3.0" +embedded-storage = "0.3.1" +static_cell = "2" +chrono = { version = "^0.4", default-features = false } + +# cargo build/run +[profile.dev] +codegen-units = 1 +debug = 2 +debug-assertions = true # <- +incremental = false +opt-level = 3 # <- +overflow-checks = true # <- + +# cargo test +[profile.test] +codegen-units = 1 +debug = 2 +debug-assertions = true # <- +incremental = false +opt-level = 3 # <- +overflow-checks = true # <- + +# cargo build/run --release +[profile.release] +codegen-units = 1 +debug = 2 +debug-assertions = false # <- +incremental = false +lto = 'fat' +opt-level = 3 # <- +overflow-checks = false # <- + +# cargo test --release +[profile.bench] +codegen-units = 1 +debug = 2 +debug-assertions = false # <- +incremental = false +lto = 'fat' +opt-level = 3 # <- +overflow-checks = false # <- diff --git a/examples/stm32h7rs/build.rs b/examples/stm32h7rs/build.rs new file mode 100644 index 000000000..8cd32d7ed --- /dev/null +++ b/examples/stm32h7rs/build.rs @@ -0,0 +1,5 @@ +fn main() { + println!("cargo:rustc-link-arg-bins=--nmagic"); + println!("cargo:rustc-link-arg-bins=-Tlink.x"); + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); +} diff --git a/examples/stm32h7rs/src/bin/blinky.rs b/examples/stm32h7rs/src/bin/blinky.rs new file mode 100644 index 000000000..137c585b7 --- /dev/null +++ b/examples/stm32h7rs/src/bin/blinky.rs @@ -0,0 +1,51 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::time::Hertz; +use embassy_stm32::Config; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.hse = Some(Hse { + freq: Hertz(24_000_000), + mode: HseMode::Oscillator, + }); + config.rcc.pll1 = Some(Pll { + source: PllSource::HSE, + prediv: PllPreDiv::DIV3, + mul: PllMul::MUL150, + divp: Some(PllDiv::DIV2), + divq: None, + divr: None, + }); + config.rcc.sys = Sysclk::PLL1_P; // 600 Mhz + config.rcc.ahb_pre = AHBPrescaler::DIV2; // 300 Mhz + config.rcc.apb1_pre = APBPrescaler::DIV2; // 150 Mhz + config.rcc.apb2_pre = APBPrescaler::DIV2; // 150 Mhz + config.rcc.apb4_pre = APBPrescaler::DIV2; // 150 Mhz + config.rcc.apb5_pre = APBPrescaler::DIV2; // 150 Mhz + config.rcc.voltage_scale = VoltageScale::HIGH; + } + let p = embassy_stm32::init(config); + info!("Hello World!"); + + let mut led = Output::new(p.PD10, Level::High, Speed::Low); + + loop { + info!("high"); + led.set_high(); + Timer::after_millis(500).await; + + info!("low"); + led.set_low(); + Timer::after_millis(500).await; + } +} diff --git a/examples/stm32h7rs/src/bin/button_exti.rs b/examples/stm32h7rs/src/bin/button_exti.rs new file mode 100644 index 000000000..34a08bbc6 --- /dev/null +++ b/examples/stm32h7rs/src/bin/button_exti.rs @@ -0,0 +1,25 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::exti::ExtiInput; +use embassy_stm32::gpio::Pull; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + let mut button = ExtiInput::new(p.PC13, p.EXTI13, Pull::Up); + + info!("Press the USER button..."); + + loop { + button.wait_for_falling_edge().await; + info!("Pressed!"); + button.wait_for_rising_edge().await; + info!("Released!"); + } +} diff --git a/examples/stm32h7rs/src/bin/can.rs b/examples/stm32h7rs/src/bin/can.rs new file mode 100644 index 000000000..0af11ef3e --- /dev/null +++ b/examples/stm32h7rs/src/bin/can.rs @@ -0,0 +1,98 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::peripherals::*; +use embassy_stm32::{bind_interrupts, can, rcc, Config}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + FDCAN1_IT0 => can::IT0InterruptHandler; + FDCAN1_IT1 => can::IT1InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = Config::default(); + config.rcc.hse = Some(rcc::Hse { + freq: embassy_stm32::time::Hertz(25_000_000), + mode: rcc::HseMode::Oscillator, + }); + config.rcc.mux.fdcansel = rcc::mux::Fdcansel::HSE; + + let peripherals = embassy_stm32::init(config); + + let mut can = can::CanConfigurator::new(peripherals.FDCAN1, peripherals.PA11, peripherals.PA12, Irqs); + + // 250k bps + can.set_bitrate(250_000); + + //let mut can = can.into_internal_loopback_mode(); + let mut can = can.into_normal_mode(); + + info!("CAN Configured"); + + let mut i = 0; + let mut last_read_ts = embassy_time::Instant::now(); + + loop { + let frame = can::frame::Frame::new_extended(0x123456F, &[i; 8]).unwrap(); + info!("Writing frame"); + _ = can.write(&frame).await; + + match can.read().await { + Ok(envelope) => { + let (rx_frame, ts) = envelope.parts(); + let delta = (ts - last_read_ts).as_millis(); + last_read_ts = ts; + info!( + "Rx: {:x} {:x} {:x} {:x} --- NEW {}", + rx_frame.data()[0], + rx_frame.data()[1], + rx_frame.data()[2], + rx_frame.data()[3], + delta, + ) + } + Err(_err) => error!("Error in frame"), + } + + Timer::after_millis(250).await; + + i += 1; + if i > 3 { + break; + } + } + + let (mut tx, mut rx, _props) = can.split(); + // With split + loop { + let frame = can::frame::Frame::new_extended(0x123456F, &[i; 8]).unwrap(); + info!("Writing frame"); + _ = tx.write(&frame).await; + + match rx.read().await { + Ok(envelope) => { + let (rx_frame, ts) = envelope.parts(); + let delta = (ts - last_read_ts).as_millis(); + last_read_ts = ts; + info!( + "Rx: {:x} {:x} {:x} {:x} --- NEW {}", + rx_frame.data()[0], + rx_frame.data()[1], + rx_frame.data()[2], + rx_frame.data()[3], + delta, + ) + } + Err(_err) => error!("Error in frame"), + } + + Timer::after_millis(250).await; + + i = i.wrapping_add(1); + } +} diff --git a/examples/stm32h7rs/src/bin/i2c.rs b/examples/stm32h7rs/src/bin/i2c.rs new file mode 100644 index 000000000..31e83cbb5 --- /dev/null +++ b/examples/stm32h7rs/src/bin/i2c.rs @@ -0,0 +1,42 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::i2c::{Error, I2c}; +use embassy_stm32::time::Hertz; +use embassy_stm32::{bind_interrupts, i2c, peripherals}; +use {defmt_rtt as _, panic_probe as _}; + +const ADDRESS: u8 = 0x5F; +const WHOAMI: u8 = 0x0F; + +bind_interrupts!(struct Irqs { + I2C2_EV => i2c::EventInterruptHandler; + I2C2_ER => i2c::ErrorInterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + info!("Hello world!"); + let p = embassy_stm32::init(Default::default()); + + let mut i2c = I2c::new( + p.I2C2, + p.PB10, + p.PB11, + Irqs, + p.GPDMA1_CH4, + p.GPDMA1_CH5, + Hertz(100_000), + Default::default(), + ); + + let mut data = [0u8; 1]; + + match i2c.blocking_write_read(ADDRESS, &[WHOAMI], &mut data) { + Ok(()) => info!("Whoami: {}", data[0]), + Err(Error::Timeout) => error!("Operation timed out"), + Err(e) => error!("I2c Error: {:?}", e), + } +} diff --git a/examples/stm32h7rs/src/bin/mco.rs b/examples/stm32h7rs/src/bin/mco.rs new file mode 100644 index 000000000..a6ee27625 --- /dev/null +++ b/examples/stm32h7rs/src/bin/mco.rs @@ -0,0 +1,29 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::rcc::{Mco, Mco1Source, McoPrescaler}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + let mut led = Output::new(p.PB14, Level::High, Speed::Low); + + let _mco = Mco::new(p.MCO1, p.PA8, Mco1Source::HSI, McoPrescaler::DIV8); + + loop { + info!("high"); + led.set_high(); + Timer::after_millis(500).await; + + info!("low"); + led.set_low(); + Timer::after_millis(500).await; + } +} diff --git a/examples/stm32h7rs/src/bin/multiprio.rs b/examples/stm32h7rs/src/bin/multiprio.rs new file mode 100644 index 000000000..b4620888f --- /dev/null +++ b/examples/stm32h7rs/src/bin/multiprio.rs @@ -0,0 +1,150 @@ +//! This example showcases how to create multiple Executor instances to run tasks at +//! different priority levels. +//! +//! Low priority executor runs in thread mode (not interrupt), and uses `sev` for signaling +//! there's work in the queue, and `wfe` for waiting for work. +//! +//! Medium and high priority executors run in two interrupts with different priorities. +//! Signaling work is done by pending the interrupt. No "waiting" needs to be done explicitly, since +//! when there's work the interrupt will trigger and run the executor. +//! +//! Sample output below. Note that high priority ticks can interrupt everything else, and +//! medium priority computations can interrupt low priority computations, making them to appear +//! to take significantly longer time. +//! +//! ```not_rust +//! [med] Starting long computation +//! [med] done in 992 ms +//! [high] tick! +//! [low] Starting long computation +//! [med] Starting long computation +//! [high] tick! +//! [high] tick! +//! [med] done in 993 ms +//! [med] Starting long computation +//! [high] tick! +//! [high] tick! +//! [med] done in 993 ms +//! [low] done in 3972 ms +//! [med] Starting long computation +//! [high] tick! +//! [high] tick! +//! [med] done in 993 ms +//! ``` +//! +//! For comparison, try changing the code so all 3 tasks get spawned on the low priority executor. +//! You will get an output like the following. Note that no computation is ever interrupted. +//! +//! ```not_rust +//! [high] tick! +//! [med] Starting long computation +//! [med] done in 496 ms +//! [low] Starting long computation +//! [low] done in 992 ms +//! [med] Starting long computation +//! [med] done in 496 ms +//! [high] tick! +//! [low] Starting long computation +//! [low] done in 992 ms +//! [high] tick! +//! [med] Starting long computation +//! [med] done in 496 ms +//! [high] tick! +//! ``` +//! + +#![no_std] +#![no_main] + +use cortex_m_rt::entry; +use defmt::*; +use embassy_executor::{Executor, InterruptExecutor}; +use embassy_stm32::interrupt; +use embassy_stm32::interrupt::{InterruptExt, Priority}; +use embassy_time::{Instant, Timer}; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::task] +async fn run_high() { + loop { + info!(" [high] tick!"); + Timer::after_ticks(27374).await; + } +} + +#[embassy_executor::task] +async fn run_med() { + loop { + let start = Instant::now(); + info!(" [med] Starting long computation"); + + // Spin-wait to simulate a long CPU computation + embassy_time::block_for(embassy_time::Duration::from_secs(1)); // ~1 second + + let end = Instant::now(); + let ms = end.duration_since(start).as_ticks() / 33; + info!(" [med] done in {} ms", ms); + + Timer::after_ticks(23421).await; + } +} + +#[embassy_executor::task] +async fn run_low() { + loop { + let start = Instant::now(); + info!("[low] Starting long computation"); + + // Spin-wait to simulate a long CPU computation + embassy_time::block_for(embassy_time::Duration::from_secs(2)); // ~2 seconds + + let end = Instant::now(); + let ms = end.duration_since(start).as_ticks() / 33; + info!("[low] done in {} ms", ms); + + Timer::after_ticks(32983).await; + } +} + +static EXECUTOR_HIGH: InterruptExecutor = InterruptExecutor::new(); +static EXECUTOR_MED: InterruptExecutor = InterruptExecutor::new(); +static EXECUTOR_LOW: StaticCell = StaticCell::new(); + +#[interrupt] +unsafe fn UART4() { + EXECUTOR_HIGH.on_interrupt() +} + +#[interrupt] +unsafe fn UART5() { + EXECUTOR_MED.on_interrupt() +} + +#[entry] +fn main() -> ! { + info!("Hello World!"); + + let _p = embassy_stm32::init(Default::default()); + + // STM32s don’t have any interrupts exclusively for software use, but they can all be triggered by software as well as + // by the peripheral, so we can just use any free interrupt vectors which aren’t used by the rest of your application. + // In this case we’re using UART4 and UART5, but there’s nothing special about them. Any otherwise unused interrupt + // vector would work exactly the same. + + // High-priority executor: UART4, priority level 6 + interrupt::UART4.set_priority(Priority::P6); + let spawner = EXECUTOR_HIGH.start(interrupt::UART4); + unwrap!(spawner.spawn(run_high())); + + // Medium-priority executor: UART5, priority level 7 + interrupt::UART5.set_priority(Priority::P7); + let spawner = EXECUTOR_MED.start(interrupt::UART5); + unwrap!(spawner.spawn(run_med())); + + // Low priority executor: runs in thread mode, using WFE/SEV + let executor = EXECUTOR_LOW.init(Executor::new()); + executor.run(|spawner| { + unwrap!(spawner.spawn(run_low())); + }); +} diff --git a/examples/stm32h7rs/src/bin/rng.rs b/examples/stm32h7rs/src/bin/rng.rs new file mode 100644 index 000000000..a9ef7200d --- /dev/null +++ b/examples/stm32h7rs/src/bin/rng.rs @@ -0,0 +1,26 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::rng::Rng; +use embassy_stm32::{bind_interrupts, peripherals, rng, Config}; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + RNG => rng::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = Config::default(); + config.rcc.hsi48 = Some(Default::default()); // needed for RNG + let p = embassy_stm32::init(config); + info!("Hello World!"); + + let mut rng = Rng::new(p.RNG, Irqs); + + let mut buf = [0u8; 16]; + unwrap!(rng.async_fill_bytes(&mut buf).await); + info!("random bytes: {:02x}", buf); +} diff --git a/examples/stm32h7rs/src/bin/rtc.rs b/examples/stm32h7rs/src/bin/rtc.rs new file mode 100644 index 000000000..0adb48877 --- /dev/null +++ b/examples/stm32h7rs/src/bin/rtc.rs @@ -0,0 +1,36 @@ +#![no_std] +#![no_main] + +use chrono::{NaiveDate, NaiveDateTime}; +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::rcc::LsConfig; +use embassy_stm32::rtc::{Rtc, RtcConfig}; +use embassy_stm32::Config; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = Config::default(); + config.rcc.ls = LsConfig::default_lse(); + + let p = embassy_stm32::init(config); + info!("Hello World!"); + + let now = NaiveDate::from_ymd_opt(2020, 5, 15) + .unwrap() + .and_hms_opt(10, 30, 15) + .unwrap(); + + let mut rtc = Rtc::new(p.RTC, RtcConfig::default()); + info!("Got RTC! {:?}", now.and_utc().timestamp()); + + rtc.set_datetime(now.into()).expect("datetime not set"); + + // In reality the delay would be much longer + Timer::after_millis(20000).await; + + let then: NaiveDateTime = rtc.now().unwrap().into(); + info!("Got RTC! {:?}", then.and_utc().timestamp()); +} diff --git a/examples/stm32h7rs/src/bin/signal.rs b/examples/stm32h7rs/src/bin/signal.rs new file mode 100644 index 000000000..b73360f32 --- /dev/null +++ b/examples/stm32h7rs/src/bin/signal.rs @@ -0,0 +1,36 @@ +#![no_std] +#![no_main] + +use defmt::{info, unwrap}; +use embassy_executor::Spawner; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +use embassy_sync::signal::Signal; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +static SIGNAL: Signal = Signal::new(); + +#[embassy_executor::task] +async fn my_sending_task() { + let mut counter: u32 = 0; + + loop { + Timer::after_secs(1).await; + + SIGNAL.signal(counter); + + counter = counter.wrapping_add(1); + } +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let _p = embassy_stm32::init(Default::default()); + unwrap!(spawner.spawn(my_sending_task())); + + loop { + let received_counter = SIGNAL.wait().await; + + info!("signalled, counter: {}", received_counter); + } +} diff --git a/examples/stm32h7rs/src/bin/spi.rs b/examples/stm32h7rs/src/bin/spi.rs new file mode 100644 index 000000000..8d6ccc58b --- /dev/null +++ b/examples/stm32h7rs/src/bin/spi.rs @@ -0,0 +1,49 @@ +#![no_std] +#![no_main] + +use core::fmt::Write; +use core::str::from_utf8; + +use cortex_m_rt::entry; +use defmt::*; +use embassy_executor::Executor; +use embassy_stm32::mode::Blocking; +use embassy_stm32::spi; +use embassy_stm32::time::mhz; +use heapless::String; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::task] +async fn main_task(mut spi: spi::Spi<'static, Blocking>) { + for n in 0u32.. { + let mut write: String<128> = String::new(); + core::write!(&mut write, "Hello DMA World {}!\r\n", n).unwrap(); + unsafe { + let result = spi.blocking_transfer_in_place(write.as_bytes_mut()); + if let Err(_) = result { + defmt::panic!("crap"); + } + } + info!("read via spi: {}", from_utf8(write.as_bytes()).unwrap()); + } +} + +static EXECUTOR: StaticCell = StaticCell::new(); + +#[entry] +fn main() -> ! { + info!("Hello World!"); + let p = embassy_stm32::init(Default::default()); + + let mut spi_config = spi::Config::default(); + spi_config.frequency = mhz(1); + + let spi = spi::Spi::new_blocking(p.SPI3, p.PB3, p.PB5, p.PB4, spi_config); + + let executor = EXECUTOR.init(Executor::new()); + + executor.run(|spawner| { + unwrap!(spawner.spawn(main_task(spi))); + }) +} diff --git a/examples/stm32h7rs/src/bin/spi_dma.rs b/examples/stm32h7rs/src/bin/spi_dma.rs new file mode 100644 index 000000000..cb305351b --- /dev/null +++ b/examples/stm32h7rs/src/bin/spi_dma.rs @@ -0,0 +1,46 @@ +#![no_std] +#![no_main] + +use core::fmt::Write; +use core::str::from_utf8; + +use cortex_m_rt::entry; +use defmt::*; +use embassy_executor::Executor; +use embassy_stm32::mode::Async; +use embassy_stm32::spi; +use embassy_stm32::time::mhz; +use heapless::String; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::task] +async fn main_task(mut spi: spi::Spi<'static, Async>) { + for n in 0u32.. { + let mut write: String<128> = String::new(); + let mut read = [0; 128]; + core::write!(&mut write, "Hello DMA World {}!\r\n", n).unwrap(); + // transfer will slice the &mut read down to &write's actual length. + spi.transfer(&mut read, write.as_bytes()).await.ok(); + info!("read via spi+dma: {}", from_utf8(&read).unwrap()); + } +} + +static EXECUTOR: StaticCell = StaticCell::new(); + +#[entry] +fn main() -> ! { + info!("Hello World!"); + let p = embassy_stm32::init(Default::default()); + + let mut spi_config = spi::Config::default(); + spi_config.frequency = mhz(1); + + let spi = spi::Spi::new(p.SPI3, p.PB3, p.PB5, p.PB4, p.GPDMA1_CH0, p.GPDMA1_CH1, spi_config); + + let executor = EXECUTOR.init(Executor::new()); + + executor.run(|spawner| { + unwrap!(spawner.spawn(main_task(spi))); + }) +} diff --git a/examples/stm32h7rs/src/bin/usart.rs b/examples/stm32h7rs/src/bin/usart.rs new file mode 100644 index 000000000..cc49c2fdb --- /dev/null +++ b/examples/stm32h7rs/src/bin/usart.rs @@ -0,0 +1,39 @@ +#![no_std] +#![no_main] + +use cortex_m_rt::entry; +use defmt::*; +use embassy_executor::Executor; +use embassy_stm32::usart::{Config, Uart}; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::task] +async fn main_task() { + let p = embassy_stm32::init(Default::default()); + + let config = Config::default(); + let mut usart = Uart::new_blocking(p.UART7, p.PF6, p.PF7, config).unwrap(); + + unwrap!(usart.blocking_write(b"Hello Embassy World!\r\n")); + info!("wrote Hello, starting echo"); + + let mut buf = [0u8; 1]; + loop { + unwrap!(usart.blocking_read(&mut buf)); + unwrap!(usart.blocking_write(&buf)); + } +} + +static EXECUTOR: StaticCell = StaticCell::new(); + +#[entry] +fn main() -> ! { + info!("Hello World!"); + + let executor = EXECUTOR.init(Executor::new()); + + executor.run(|spawner| { + unwrap!(spawner.spawn(main_task())); + }) +} diff --git a/examples/stm32h7rs/src/bin/usart_dma.rs b/examples/stm32h7rs/src/bin/usart_dma.rs new file mode 100644 index 000000000..c644e84bd --- /dev/null +++ b/examples/stm32h7rs/src/bin/usart_dma.rs @@ -0,0 +1,47 @@ +#![no_std] +#![no_main] + +use core::fmt::Write; + +use cortex_m_rt::entry; +use defmt::*; +use embassy_executor::Executor; +use embassy_stm32::usart::{Config, Uart}; +use embassy_stm32::{bind_interrupts, peripherals, usart}; +use heapless::String; +use static_cell::StaticCell; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + UART7 => usart::InterruptHandler; +}); + +#[embassy_executor::task] +async fn main_task() { + let p = embassy_stm32::init(Default::default()); + + let config = Config::default(); + let mut usart = Uart::new(p.UART7, p.PF6, p.PF7, Irqs, p.GPDMA1_CH0, p.GPDMA1_CH1, config).unwrap(); + + for n in 0u32.. { + let mut s: String<128> = String::new(); + core::write!(&mut s, "Hello DMA World {}!\r\n", n).unwrap(); + + usart.write(s.as_bytes()).await.ok(); + + info!("wrote DMA"); + } +} + +static EXECUTOR: StaticCell = StaticCell::new(); + +#[entry] +fn main() -> ! { + info!("Hello World!"); + + let executor = EXECUTOR.init(Executor::new()); + + executor.run(|spawner| { + unwrap!(spawner.spawn(main_task())); + }) +} diff --git a/examples/stm32h7rs/src/bin/usart_split.rs b/examples/stm32h7rs/src/bin/usart_split.rs new file mode 100644 index 000000000..d26c5003c --- /dev/null +++ b/examples/stm32h7rs/src/bin/usart_split.rs @@ -0,0 +1,47 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::mode::Async; +use embassy_stm32::usart::{Config, Uart, UartRx}; +use embassy_stm32::{bind_interrupts, peripherals, usart}; +use embassy_sync::blocking_mutex::raw::ThreadModeRawMutex; +use embassy_sync::channel::Channel; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + UART7 => usart::InterruptHandler; +}); + +static CHANNEL: Channel = Channel::new(); + +#[embassy_executor::main] +async fn main(spawner: Spawner) -> ! { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + let config = Config::default(); + let mut usart = Uart::new(p.UART7, p.PF6, p.PF7, Irqs, p.GPDMA1_CH0, p.GPDMA1_CH1, config).unwrap(); + unwrap!(usart.blocking_write(b"Type 8 chars to echo!\r\n")); + + let (mut tx, rx) = usart.split(); + + unwrap!(spawner.spawn(reader(rx))); + + loop { + let buf = CHANNEL.receive().await; + info!("writing..."); + unwrap!(tx.write(&buf).await); + } +} + +#[embassy_executor::task] +async fn reader(mut rx: UartRx<'static, Async>) { + let mut buf = [0; 8]; + loop { + info!("reading..."); + unwrap!(rx.read(&mut buf).await); + CHANNEL.send(buf).await; + } +} diff --git a/examples/stm32h7rs/src/bin/usb_serial.rs b/examples/stm32h7rs/src/bin/usb_serial.rs new file mode 100644 index 000000000..6773f7843 --- /dev/null +++ b/examples/stm32h7rs/src/bin/usb_serial.rs @@ -0,0 +1,140 @@ +#![no_std] +#![no_main] + +use defmt::{panic, *}; +use embassy_executor::Spawner; +use embassy_futures::join::join; +use embassy_stm32::time::Hertz; +use embassy_stm32::usb::{Driver, Instance}; +use embassy_stm32::{bind_interrupts, peripherals, usb, Config}; +use embassy_usb::class::cdc_acm::{CdcAcmClass, State}; +use embassy_usb::driver::EndpointError; +use embassy_usb::Builder; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + OTG_HS => usb::InterruptHandler; +}); + +// If you are trying this and your USB device doesn't connect, the most +// common issues are the RCC config and vbus_detection +// +// See https://embassy.dev/book/#_the_usb_examples_are_not_working_on_my_board_is_there_anything_else_i_need_to_configure +// for more information. +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + info!("Hello World!"); + + let mut config = Config::default(); + + { + use embassy_stm32::rcc::*; + config.rcc.hse = Some(Hse { + freq: Hertz(24_000_000), + mode: HseMode::Oscillator, + }); + config.rcc.pll1 = Some(Pll { + source: PllSource::HSE, + prediv: PllPreDiv::DIV12, + mul: PllMul::MUL300, + divp: Some(PllDiv::DIV1), //600 MHz + divq: Some(PllDiv::DIV2), // 300 MHz + divr: Some(PllDiv::DIV2), // 300 MHz + }); + config.rcc.sys = Sysclk::PLL1_P; // 600 MHz + config.rcc.ahb_pre = AHBPrescaler::DIV2; // 300 MHz + config.rcc.apb1_pre = APBPrescaler::DIV2; // 150 MHz + config.rcc.apb2_pre = APBPrescaler::DIV2; // 150 MHz + config.rcc.apb4_pre = APBPrescaler::DIV2; // 150 MHz + config.rcc.apb5_pre = APBPrescaler::DIV2; // 150 MHz + config.rcc.voltage_scale = VoltageScale::HIGH; + config.rcc.mux.usbphycsel = mux::Usbphycsel::HSE; + } + + let p = embassy_stm32::init(config); + + // Create the driver, from the HAL. + let mut ep_out_buffer = [0u8; 256]; + let mut config = embassy_stm32::usb::Config::default(); + + // Do not enable vbus_detection. This is a safe default that works in all boards. + // However, if your USB device is self-powered (can stay powered on if USB is unplugged), you need + // to enable vbus_detection to comply with the USB spec. If you enable it, the board + // has to support it or USB won't work at all. See docs on `vbus_detection` for details. + config.vbus_detection = false; + + let driver = Driver::new_hs(p.USB_OTG_HS, Irqs, p.PM6, p.PM5, &mut ep_out_buffer, config); + + // Create embassy-usb Config + let mut config = embassy_usb::Config::new(0xc0de, 0xcafe); + config.manufacturer = Some("Embassy"); + config.product = Some("USB-serial example"); + config.serial_number = Some("12345678"); + // Required for windows compatibility. + // https://developer.nordicsemi.com/nRF_Connect_SDK/doc/1.9.1/kconfig/CONFIG_CDC_ACM_IAD.html#help + config.device_class = 0xEF; + config.device_sub_class = 0x02; + config.device_protocol = 0x01; + config.composite_with_iads = true; + + // Create embassy-usb DeviceBuilder using the driver and config. + // It needs some buffers for building the descriptors. + let mut config_descriptor = [0; 256]; + let mut bos_descriptor = [0; 256]; + let mut control_buf = [0; 64]; + + let mut state = State::new(); + + let mut builder = Builder::new( + driver, + config, + &mut config_descriptor, + &mut bos_descriptor, + &mut [], // no msos descriptors + &mut control_buf, + ); + + // Create classes on the builder. + let mut class = CdcAcmClass::new(&mut builder, &mut state, 64); + + // Build the builder. + let mut usb = builder.build(); + + // Run the USB device. + let usb_fut = usb.run(); + + // Do stuff with the class! + let echo_fut = async { + loop { + class.wait_connection().await; + info!("Connected"); + let _ = echo(&mut class).await; + info!("Disconnected"); + } + }; + + // Run everything concurrently. + // If we had made everything `'static` above instead, we could do this using separate tasks instead. + join(usb_fut, echo_fut).await; +} + +struct Disconnected {} + +impl From for Disconnected { + fn from(val: EndpointError) -> Self { + match val { + EndpointError::BufferOverflow => panic!("Buffer overflow"), + EndpointError::Disabled => Disconnected {}, + } + } +} + +async fn echo<'d, T: Instance + 'd>(class: &mut CdcAcmClass<'d, Driver<'d, T>>) -> Result<(), Disconnected> { + let mut buf = [0; 64]; + loop { + let n = class.read_packet(&mut buf).await?; + let data = &buf[..n]; + info!("data: {:x}", data); + class.write_packet(data).await?; + } +} diff --git a/examples/stm32l0/Cargo.toml b/examples/stm32l0/Cargo.toml index dd9097c9b..4e2bb8b67 100644 --- a/examples/stm32l0/Cargo.toml +++ b/examples/stm32l0/Cargo.toml @@ -6,10 +6,10 @@ license = "MIT OR Apache-2.0" [dependencies] # Change stm32l072cz to your chip name, if necessary. -embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32l072cz", "time-driver-any", "exti", "memory-x"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32l072cz", "unstable-pac", "time-driver-any", "exti", "memory-x"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } defmt = "0.3" defmt-rtt = "0.4" @@ -21,7 +21,6 @@ embedded-io-async = { version = "0.6.1" } cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } cortex-m-rt = "0.7.0" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } embedded-hal = "0.2.6" static_cell = { version = "2" } diff --git a/examples/stm32l0/src/bin/adc.rs b/examples/stm32l0/src/bin/adc.rs new file mode 100644 index 000000000..9dd09bc45 --- /dev/null +++ b/examples/stm32l0/src/bin/adc.rs @@ -0,0 +1,40 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::adc::{Adc, SampleTime}; +use embassy_stm32::peripherals::ADC1; +use embassy_stm32::{adc, bind_interrupts}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + ADC1_COMP => adc::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + let mut adc = Adc::new(p.ADC1, Irqs); + adc.set_sample_time(SampleTime::CYCLES79_5); + let mut pin = p.PA1; + + let mut vrefint = adc.enable_vref(); + let vrefint_sample = adc.read(&mut vrefint).await; + let convert_to_millivolts = |sample| { + // From https://www.st.com/resource/en/datasheet/stm32l051c6.pdf + // 6.3.3 Embedded internal reference voltage + const VREFINT_MV: u32 = 1224; // mV + + (u32::from(sample) * VREFINT_MV / u32::from(vrefint_sample)) as u16 + }; + + loop { + let v = adc.read(&mut pin).await; + info!("--> {} - {} mV", v, convert_to_millivolts(v)); + Timer::after_millis(100).await; + } +} diff --git a/examples/stm32l0/src/bin/async-tsc.rs b/examples/stm32l0/src/bin/async-tsc.rs new file mode 100644 index 000000000..c40b86af9 --- /dev/null +++ b/examples/stm32l0/src/bin/async-tsc.rs @@ -0,0 +1,122 @@ +// Example of async TSC (Touch Sensing Controller) that lights an LED when touch is detected. +// +// Suggested physical setup on STM32L073RZ Nucleo board: +// - Connect a 1000pF capacitor between pin A0 and GND. This is your sampling capacitor. +// - Connect one end of a 1K resistor to pin A1 and leave the other end loose. +// The loose end will act as touch sensor which will register your touch. +// +// Troubleshooting the setup: +// - If no touch seems to be registered, then try to disconnect the sampling capacitor from GND momentarily, +// now the led should light up. Next try using a different value for the sampling capacitor. +// Also experiment with increasing the values for `ct_pulse_high_length`, `ct_pulse_low_length`, `pulse_generator_prescaler`, `max_count_value` and `discharge_delay`. +// +// All configuration values and sampling capacitor value have been determined experimentally. +// Suitable configuration and discharge delay values are highly dependent on the value of the sample capacitor. For example, a shorter discharge delay can be used with smaller capacitor values. +// +#![no_std] +#![no_main] + +use defmt::*; +use embassy_stm32::bind_interrupts; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::tsc::{self, *}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + TSC => InterruptHandler; +}); + +#[cortex_m_rt::exception] +unsafe fn HardFault(_: &cortex_m_rt::ExceptionFrame) -> ! { + cortex_m::peripheral::SCB::sys_reset(); +} + +/// This example is written for the nucleo-stm32l073rz, with a stm32l073rz chip. +/// +/// Make sure you check/update the following (whether you use the L073RZ or another board): +/// +/// * [ ] Update .cargo/config.toml with the correct `probe-rs run --chip STM32L073RZTx`chip name. +/// * [ ] Update Cargo.toml to have the correct `embassy-stm32` feature, for L073RZ it should be `stm32l073rz`. +/// * [ ] If your board has a special clock or power configuration, make sure that it is +/// set up appropriately. +/// * [ ] If your board has different pin mapping, update any pin numbers or peripherals +/// to match your schematic +/// +/// If you are unsure, please drop by the Embassy Matrix chat for support, and let us know: +/// +/// * Which example you are trying to run +/// * Which chip and board you are using +/// +/// Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org +#[embassy_executor::main] +async fn main(_spawner: embassy_executor::Spawner) { + let device_config = embassy_stm32::Config::default(); + let context = embassy_stm32::init(device_config); + + let config = tsc::Config { + ct_pulse_high_length: ChargeTransferPulseCycle::_4, + ct_pulse_low_length: ChargeTransferPulseCycle::_4, + spread_spectrum: false, + spread_spectrum_deviation: SSDeviation::new(2).unwrap(), + spread_spectrum_prescaler: false, + pulse_generator_prescaler: PGPrescalerDivider::_16, + max_count_value: MaxCount::_255, + io_default_mode: false, + synchro_pin_polarity: false, + acquisition_mode: false, + max_count_interrupt: false, + channel_ios: TscIOPin::Group1Io1.into(), + shield_ios: 0, // no shield + sampling_ios: TscIOPin::Group1Io2.into(), + }; + + let mut g1: PinGroup = PinGroup::new(); + g1.set_io1(context.PA0, PinType::Sample); + g1.set_io2(context.PA1, PinType::Channel); + + let mut touch_controller = tsc::Tsc::new_async( + context.TSC, + Some(g1), + None, + None, + None, + None, + None, + None, + None, + config, + Irqs, + ); + + // Check if TSC is ready + if touch_controller.get_state() != State::Ready { + info!("TSC not ready!"); + loop {} // Halt execution + } + info!("TSC initialized successfully"); + + // LED2 on the STM32L073RZ nucleo-board (PA5) + let mut led = Output::new(context.PA5, Level::High, Speed::Low); + + // smaller sample capacitor discharge faster and can be used with shorter delay. + let discharge_delay = 5; // ms + + info!("Starting touch_controller interface"); + loop { + touch_controller.start(); + touch_controller.pend_for_acquisition().await; + touch_controller.discharge_io(true); + Timer::after_millis(discharge_delay).await; + + let grp1_status = touch_controller.group_get_status(Group::One); + match grp1_status { + GroupStatus::Complete => { + let group_one_val = touch_controller.group_get_value(Group::One); + info!("{}", group_one_val); + led.set_high(); + } + GroupStatus::Ongoing => led.set_low(), + } + } +} diff --git a/examples/stm32l0/src/bin/blocking-tsc.rs b/examples/stm32l0/src/bin/blocking-tsc.rs new file mode 100644 index 000000000..7e4f40946 --- /dev/null +++ b/examples/stm32l0/src/bin/blocking-tsc.rs @@ -0,0 +1,116 @@ +// Example of polling TSC (Touch Sensing Controller) that lights an LED when touch is detected. +// +// Suggested physical setup on STM32L073RZ Nucleo board: +// - Connect a 1000pF capacitor between pin A0 and GND. This is your sampling capacitor. +// - Connect one end of a 1K resistor to pin A1 and leave the other end loose. +// The loose end will act as touch sensor which will register your touch. +// +// Troubleshooting the setup: +// - If no touch seems to be registered, then try to disconnect the sampling capacitor from GND momentarily, +// now the led should light up. Next try using a different value for the sampling capacitor. +// Also experiment with increasing the values for `ct_pulse_high_length`, `ct_pulse_low_length`, `pulse_generator_prescaler`, `max_count_value` and `discharge_delay`. +// +// All configuration values and sampling capacitor value have been determined experimentally. +// Suitable configuration and discharge delay values are highly dependent on the value of the sample capacitor. For example, a shorter discharge delay can be used with smaller capacitor values. +// +#![no_std] +#![no_main] + +use defmt::*; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::tsc::{self, *}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +/// This example is written for the nucleo-stm32l073rz, with a stm32l073rz chip. +/// +/// Make sure you check/update the following (whether you use the L073RZ or another board): +/// +/// * [ ] Update .cargo/config.toml with the correct `probe-rs run --chip STM32L073RZTx`chip name. +/// * [ ] Update Cargo.toml to have the correct `embassy-stm32` feature, for L073RZ it should be `stm32l073rz`. +/// * [ ] If your board has a special clock or power configuration, make sure that it is +/// set up appropriately. +/// * [ ] If your board has different pin mapping, update any pin numbers or peripherals +/// to match your schematic +/// +/// If you are unsure, please drop by the Embassy Matrix chat for support, and let us know: +/// +/// * Which example you are trying to run +/// * Which chip and board you are using +/// +/// Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org +#[embassy_executor::main] +async fn main(_spawner: embassy_executor::Spawner) { + let device_config = embassy_stm32::Config::default(); + let context = embassy_stm32::init(device_config); + + let tsc_conf = Config { + ct_pulse_high_length: ChargeTransferPulseCycle::_4, + ct_pulse_low_length: ChargeTransferPulseCycle::_4, + spread_spectrum: false, + spread_spectrum_deviation: SSDeviation::new(2).unwrap(), + spread_spectrum_prescaler: false, + pulse_generator_prescaler: PGPrescalerDivider::_16, + max_count_value: MaxCount::_255, + io_default_mode: false, + synchro_pin_polarity: false, + acquisition_mode: false, + max_count_interrupt: false, + channel_ios: TscIOPin::Group1Io1.into(), + shield_ios: 0, // no shield + sampling_ios: TscIOPin::Group1Io2.into(), + }; + + let mut g1: PinGroup = PinGroup::new(); + g1.set_io1(context.PA0, PinType::Sample); + g1.set_io2(context.PA1, PinType::Channel); + + let mut touch_controller = tsc::Tsc::new_blocking( + context.TSC, + Some(g1), + None, + None, + None, + None, + None, + None, + None, + tsc_conf, + ); + + // Check if TSC is ready + if touch_controller.get_state() != State::Ready { + info!("TSC not ready!"); + loop {} // Halt execution + } + info!("TSC initialized successfully"); + + // LED2 on the STM32L073RZ nucleo-board (PA5) + let mut led = Output::new(context.PA5, Level::High, Speed::Low); + + // smaller sample capacitor discharge faster and can be used with shorter delay. + let discharge_delay = 5; // ms + + // the interval at which the loop polls for new touch sensor values + let polling_interval = 100; // ms + + info!("polling for touch"); + loop { + touch_controller.start(); + touch_controller.poll_for_acquisition(); + touch_controller.discharge_io(true); + Timer::after_millis(discharge_delay).await; + + let grp1_status = touch_controller.group_get_status(Group::One); + match grp1_status { + GroupStatus::Complete => { + let group_one_val = touch_controller.group_get_value(Group::One); + info!("{}", group_one_val); + led.set_high(); + } + GroupStatus::Ongoing => led.set_low(), + } + + Timer::after_millis(polling_interval).await; + } +} diff --git a/examples/stm32l0/src/bin/dds.rs b/examples/stm32l0/src/bin/dds.rs new file mode 100644 index 000000000..a54b28a93 --- /dev/null +++ b/examples/stm32l0/src/bin/dds.rs @@ -0,0 +1,116 @@ +#![no_std] +#![no_main] + +use core::option::Option::Some; + +use defmt::info; +use defmt_rtt as _; // global logger +use embassy_executor::Spawner; +use embassy_stm32::gpio::OutputType; +use embassy_stm32::rcc::*; +use embassy_stm32::time::hz; +use embassy_stm32::timer::low_level::{Timer as LLTimer, *}; +use embassy_stm32::timer::simple_pwm::PwmPin; +use embassy_stm32::timer::Channel; +use embassy_stm32::{interrupt, pac, Config}; +use panic_probe as _; + +const DDS_SINE_DATA: [u8; 256] = [ + 0x80, 0x83, 0x86, 0x89, 0x8c, 0x8f, 0x92, 0x95, 0x98, 0x9c, 0x9f, 0xa2, 0xa5, 0xa8, 0xab, 0xae, 0xb0, 0xb3, 0xb6, + 0xb9, 0xbc, 0xbf, 0xc1, 0xc4, 0xc7, 0xc9, 0xcc, 0xce, 0xd1, 0xd3, 0xd5, 0xd8, 0xda, 0xdc, 0xde, 0xe0, 0xe2, 0xe4, + 0xe6, 0xe8, 0xea, 0xec, 0xed, 0xef, 0xf0, 0xf2, 0xf3, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfc, 0xfd, + 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfd, 0xfc, 0xfc, 0xfb, + 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf3, 0xf2, 0xf0, 0xef, 0xed, 0xec, 0xea, 0xe8, 0xe6, 0xe4, 0xe2, 0xe0, 0xde, + 0xdc, 0xda, 0xd8, 0xd5, 0xd3, 0xd1, 0xce, 0xcc, 0xc9, 0xc7, 0xc4, 0xc1, 0xbf, 0xbc, 0xb9, 0xb6, 0xb3, 0xb0, 0xae, + 0xab, 0xa8, 0xa5, 0xa2, 0x9f, 0x9c, 0x98, 0x95, 0x92, 0x8f, 0x8c, 0x89, 0x86, 0x83, 0x80, 0x7c, 0x79, 0x76, 0x73, + 0x70, 0x6d, 0x6a, 0x67, 0x63, 0x60, 0x5d, 0x5a, 0x57, 0x54, 0x51, 0x4f, 0x4c, 0x49, 0x46, 0x43, 0x40, 0x3e, 0x3b, + 0x38, 0x36, 0x33, 0x31, 0x2e, 0x2c, 0x2a, 0x27, 0x25, 0x23, 0x21, 0x1f, 0x1d, 0x1b, 0x19, 0x17, 0x15, 0x13, 0x12, + 0x10, 0x0f, 0x0d, 0x0c, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x03, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x03, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0a, 0x0c, 0x0d, 0x0f, 0x10, 0x12, 0x13, 0x15, 0x17, 0x19, 0x1b, 0x1d, 0x1f, 0x21, 0x23, 0x25, 0x27, 0x2a, 0x2c, + 0x2e, 0x31, 0x33, 0x36, 0x38, 0x3b, 0x3e, 0x40, 0x43, 0x46, 0x49, 0x4c, 0x4f, 0x51, 0x54, 0x57, 0x5a, 0x5d, 0x60, + 0x63, 0x67, 0x6a, 0x6d, 0x70, 0x73, 0x76, 0x79, 0x7c, +]; + +// frequency: 15625/(256/(DDS_INCR/2**24)) = 999,99999Hz +static mut DDS_INCR: u32 = 0x10624DD2; + +// fractional phase accumulator +static mut DDS_AKKU: u32 = 0x00000000; + +#[interrupt] +fn TIM2() { + unsafe { + // get next value of DDS + DDS_AKKU = DDS_AKKU.wrapping_add(DDS_INCR); + let value = (DDS_SINE_DATA[(DDS_AKKU >> 24) as usize] as u16) << 3; + + // set new output compare value + pac::TIM2.ccr(2).modify(|w| w.set_ccr(value)); + + // reset interrupt flag + pac::TIM2.sr().modify(|r| r.set_uif(false)); + } +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + info!("Hello World!"); + + // configure for 32MHz (HSI16 * 6 / 3) + let mut config = Config::default(); + config.rcc.sys = Sysclk::PLL1_R; + config.rcc.hsi = true; + config.rcc.pll = Some(Pll { + source: PllSource::HSI, + div: PllDiv::DIV3, + mul: PllMul::MUL6, + }); + + let p = embassy_stm32::init(config); + + // setup PWM pin in AF mode + let _ch3 = PwmPin::new_ch3(p.PA2, OutputType::PushPull); + + // initialize timer + // we cannot use SimplePWM here because the Time is privately encapsulated + let timer = LLTimer::new(p.TIM2); + + // set counting mode + timer.set_counting_mode(CountingMode::EdgeAlignedUp); + + // set pwm sample frequency + timer.set_frequency(hz(15625)); + + // enable outputs + timer.enable_outputs(); + + // start timer + timer.start(); + + // set output compare mode + timer.set_output_compare_mode(Channel::Ch3, OutputCompareMode::PwmMode1); + + // set output compare preload + timer.set_output_compare_preload(Channel::Ch3, true); + + // set output polarity + timer.set_output_polarity(Channel::Ch3, OutputPolarity::ActiveHigh); + + // set compare value + timer.set_compare_value(Channel::Ch3, timer.get_max_compare_value() / 2); + + // enable pwm channel + timer.enable_channel(Channel::Ch3, true); + + // enable timer interrupts + timer.enable_update_interrupt(true); + unsafe { cortex_m::peripheral::NVIC::unmask(interrupt::TIM2) }; + + async { + loop { + embassy_time::Timer::after_millis(5000).await; + } + } + .await; +} diff --git a/examples/stm32l0/src/bin/spi.rs b/examples/stm32l0/src/bin/spi.rs index f23a537b8..8e0cfdedb 100644 --- a/examples/stm32l0/src/bin/spi.rs +++ b/examples/stm32l0/src/bin/spi.rs @@ -3,7 +3,6 @@ use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::dma::NoDma; use embassy_stm32::gpio::{Level, Output, Speed}; use embassy_stm32::spi::{Config, Spi}; use embassy_stm32::time::Hertz; @@ -17,7 +16,7 @@ async fn main(_spawner: Spawner) { let mut spi_config = Config::default(); spi_config.frequency = Hertz(1_000_000); - let mut spi = Spi::new(p.SPI1, p.PB3, p.PA7, p.PA6, NoDma, NoDma, spi_config); + let mut spi = Spi::new_blocking(p.SPI1, p.PB3, p.PA7, p.PA6, spi_config); let mut cs = Output::new(p.PA15, Level::High, Speed::VeryHigh); diff --git a/examples/stm32l1/Cargo.toml b/examples/stm32l1/Cargo.toml index 322c41262..865cad87f 100644 --- a/examples/stm32l1/Cargo.toml +++ b/examples/stm32l1/Cargo.toml @@ -5,11 +5,12 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = [ "defmt", "stm32l151cb-a", "time-driver-any", "memory-x"] } -embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } defmt = "0.3" defmt-rtt = "0.4" @@ -18,7 +19,6 @@ cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-sing cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } embedded-storage = "0.3.1" diff --git a/examples/stm32l1/src/bin/spi.rs b/examples/stm32l1/src/bin/spi.rs index 8be686c5a..eabf1bac2 100644 --- a/examples/stm32l1/src/bin/spi.rs +++ b/examples/stm32l1/src/bin/spi.rs @@ -3,7 +3,6 @@ use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::dma::NoDma; use embassy_stm32::gpio::{Level, Output, Speed}; use embassy_stm32::spi::{Config, Spi}; use embassy_stm32::time::Hertz; @@ -17,7 +16,7 @@ async fn main(_spawner: Spawner) { let mut spi_config = Config::default(); spi_config.frequency = Hertz(1_000_000); - let mut spi = Spi::new(p.SPI1, p.PA5, p.PA7, p.PA6, NoDma, NoDma, spi_config); + let mut spi = Spi::new_blocking(p.SPI1, p.PA5, p.PA7, p.PA6, spi_config); let mut cs = Output::new(p.PA4, Level::High, Speed::VeryHigh); diff --git a/examples/stm32l1/src/bin/usb_serial.rs b/examples/stm32l1/src/bin/usb_serial.rs index 7b1e84cbc..837f7fa57 100644 --- a/examples/stm32l1/src/bin/usb_serial.rs +++ b/examples/stm32l1/src/bin/usb_serial.rs @@ -3,12 +3,12 @@ use defmt::{panic, *}; use embassy_executor::Spawner; +use embassy_futures::join::join; use embassy_stm32::usb::{self, Driver, Instance}; use embassy_stm32::{bind_interrupts, peripherals}; use embassy_usb::class::cdc_acm::{CdcAcmClass, State}; use embassy_usb::driver::EndpointError; use embassy_usb::Builder; -use futures::future::join; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { @@ -27,7 +27,7 @@ async fn main(_spawner: Spawner) { mul: PllMul::MUL6, // PLLVCO = 16*6 = 96Mhz div: PllDiv::DIV3, // 32Mhz clock (16 * 6 / 3) }); - config.rcc.mux = ClockSrc::PLL1_R; + config.rcc.sys = Sysclk::PLL1_R; } let p = embassy_stm32::init(config); @@ -46,7 +46,6 @@ async fn main(_spawner: Spawner) { config.device_protocol = 0x01; config.composite_with_iads = true; - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 64]; @@ -56,7 +55,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], // no msos descriptors diff --git a/examples/stm32l4/.cargo/config.toml b/examples/stm32l4/.cargo/config.toml index db3a7ceff..83fc6d6f8 100644 --- a/examples/stm32l4/.cargo/config.toml +++ b/examples/stm32l4/.cargo/config.toml @@ -2,7 +2,7 @@ # replace STM32F429ZITx with your chip as listed in `probe-rs chip list` #runner = "probe-rs run --chip STM32L475VGT6" #runner = "probe-rs run --chip STM32L475VG" -runner = "probe-run --chip STM32L4S5QI" +runner = "probe-rs run --chip STM32L4S5QI" [build] target = "thumbv7em-none-eabi" diff --git a/examples/stm32l4/Cargo.toml b/examples/stm32l4/Cargo.toml index d42e69578..7f963fc53 100644 --- a/examples/stm32l4/Cargo.toml +++ b/examples/stm32l4/Cargo.toml @@ -7,11 +7,11 @@ license = "MIT OR Apache-2.0" [dependencies] # Change stm32l4s5vi to your chip name, if necessary. embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = [ "defmt", "unstable-pac", "stm32l4s5qi", "memory-x", "time-driver-any", "exti", "chrono"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768", ] } -embassy-embedded-hal = { version = "0.1.0", path = "../../embassy-embedded-hal" } -embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768", ] } +embassy-embedded-hal = { version = "0.2.0", path = "../../embassy-embedded-hal" } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } embassy-net-adin1110 = { version = "0.2.0", path = "../../embassy-net-adin1110" } embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "udp", "tcp", "dhcpv4", "medium-ethernet"] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } @@ -28,7 +28,6 @@ embedded-hal-1 = { package = "embedded-hal", version = "1.0" } embedded-hal-async = { version = "1.0" } embedded-hal-bus = { version = "0.1", features = ["async"] } panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } chrono = { version = "^0.4", default-features = false } rand = { version = "0.8.5", default-features = false } diff --git a/examples/stm32l4/src/bin/adc.rs b/examples/stm32l4/src/bin/adc.rs index d01e9f1b3..c557ac6d7 100644 --- a/examples/stm32l4/src/bin/adc.rs +++ b/examples/stm32l4/src/bin/adc.rs @@ -3,28 +3,27 @@ use defmt::*; use embassy_stm32::adc::{Adc, Resolution}; -use embassy_stm32::pac; -use embassy_time::Delay; +use embassy_stm32::Config; use {defmt_rtt as _, panic_probe as _}; #[cortex_m_rt::entry] fn main() -> ! { info!("Hello World!"); - pac::RCC.ccipr().modify(|w| { - w.set_adcsel(pac::rcc::vals::Adcsel::SYS); - }); - pac::RCC.ahb2enr().modify(|w| w.set_adcen(true)); + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.mux.adcsel = mux::Adcsel::SYS; + } + let p = embassy_stm32::init(config); - let p = embassy_stm32::init(Default::default()); - - let mut adc = Adc::new(p.ADC1, &mut Delay); + let mut adc = Adc::new(p.ADC1); //adc.enable_vref(); - adc.set_resolution(Resolution::EightBit); + adc.set_resolution(Resolution::BITS8); let mut channel = p.PC0; loop { - let v = adc.read(&mut channel); + let v = adc.blocking_read(&mut channel); info!("--> {}", v); } } diff --git a/examples/stm32l4/src/bin/can.rs b/examples/stm32l4/src/bin/can.rs new file mode 100644 index 000000000..3c4cdac24 --- /dev/null +++ b/examples/stm32l4/src/bin/can.rs @@ -0,0 +1,68 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::can::filter::Mask32; +use embassy_stm32::can::{ + Can, Fifo, Frame, Rx0InterruptHandler, Rx1InterruptHandler, SceInterruptHandler, TxInterruptHandler, +}; +use embassy_stm32::peripherals::CAN1; +use embassy_stm32::{bind_interrupts, Config}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + CAN1_RX0 => Rx0InterruptHandler; + CAN1_RX1 => Rx1InterruptHandler; + CAN1_SCE => SceInterruptHandler; + CAN1_TX => TxInterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Config::default()); + + let mut can = Can::new(p.CAN1, p.PA11, p.PA12, Irqs); + + can.modify_filters().enable_bank(0, Fifo::Fifo0, Mask32::accept_all()); + + can.modify_config() + .set_loopback(true) // Receive own frames + .set_silent(true) + .set_bitrate(250_000); + + can.enable().await; + println!("CAN enabled"); + + let mut i = 0; + let mut last_read_ts = embassy_time::Instant::now(); + loop { + let frame = Frame::new_extended(0x123456F, &[i; 8]).unwrap(); + info!("Writing frame"); + + _ = can.write(&frame).await; + + match can.read().await { + Ok(envelope) => { + let (ts, rx_frame) = (envelope.ts, envelope.frame); + let delta = (ts - last_read_ts).as_millis(); + last_read_ts = ts; + info!( + "Rx: {} {:02x} --- {}ms", + rx_frame.header().len(), + rx_frame.data()[0..rx_frame.header().len() as usize], + delta, + ) + } + Err(err) => error!("Error in frame: {}", err), + } + + Timer::after_millis(250).await; + + i += 1; + if i > 2 { + break; + } + } +} diff --git a/examples/stm32l4/src/bin/dac_dma.rs b/examples/stm32l4/src/bin/dac_dma.rs index 8e5098557..d01b016c0 100644 --- a/examples/stm32l4/src/bin/dac_dma.rs +++ b/examples/stm32l4/src/bin/dac_dma.rs @@ -6,9 +6,9 @@ use embassy_executor::Spawner; use embassy_stm32::dac::{DacCh1, DacCh2, ValueArray}; use embassy_stm32::pac::timer::vals::Mms; use embassy_stm32::peripherals::{DAC1, DMA1_CH3, DMA1_CH4, TIM6, TIM7}; -use embassy_stm32::rcc::low_level::RccPeripheral; +use embassy_stm32::rcc::frequency; use embassy_stm32::time::Hertz; -use embassy_stm32::timer::low_level::Basic16bitInstance; +use embassy_stm32::timer::low_level::Timer; use micromath::F32Ext; use {defmt_rtt as _, panic_probe as _}; @@ -22,19 +22,19 @@ async fn main(spawner: Spawner) { // Obtain two independent channels (p.DAC1 can only be consumed once, though!) let (dac_ch1, dac_ch2) = embassy_stm32::dac::Dac::new(p.DAC1, p.DMA1_CH3, p.DMA1_CH4, p.PA4, p.PA5).split(); - spawner.spawn(dac_task1(dac_ch1)).ok(); - spawner.spawn(dac_task2(dac_ch2)).ok(); + spawner.spawn(dac_task1(p.TIM6, dac_ch1)).ok(); + spawner.spawn(dac_task2(p.TIM7, dac_ch2)).ok(); } #[embassy_executor::task] -async fn dac_task1(mut dac: DacCh1<'static, DAC1, DMA1_CH3>) { +async fn dac_task1(tim: TIM6, mut dac: DacCh1<'static, DAC1, DMA1_CH3>) { let data: &[u8; 256] = &calculate_array::<256>(); - info!("TIM6 frequency is {}", TIM6::frequency()); + info!("TIM6 frequency is {}", frequency::()); const FREQUENCY: Hertz = Hertz::hz(200); // Compute the reload value such that we obtain the FREQUENCY for the sine - let reload: u32 = (TIM6::frequency().0 / FREQUENCY.0) / data.len() as u32; + let reload: u32 = (frequency::().0 / FREQUENCY.0) / data.len() as u32; // Depends on your clock and on the specific chip used, you may need higher or lower values here if reload < 10 { @@ -45,17 +45,17 @@ async fn dac_task1(mut dac: DacCh1<'static, DAC1, DMA1_CH3>) { dac.set_triggering(true); dac.enable(); - TIM6::enable_and_reset(); - TIM6::regs().arr().modify(|w| w.set_arr(reload as u16 - 1)); - TIM6::regs().cr2().modify(|w| w.set_mms(Mms::UPDATE)); - TIM6::regs().cr1().modify(|w| { + let tim = Timer::new(tim); + tim.regs_basic().arr().modify(|w| w.set_arr(reload as u16 - 1)); + tim.regs_basic().cr2().modify(|w| w.set_mms(Mms::UPDATE)); + tim.regs_basic().cr1().modify(|w| { w.set_opm(false); w.set_cen(true); }); debug!( "TIM6 Frequency {}, Target Frequency {}, Reload {}, Reload as u16 {}, Samples {}", - TIM6::frequency(), + frequency::(), FREQUENCY, reload, reload as u16, @@ -70,22 +70,22 @@ async fn dac_task1(mut dac: DacCh1<'static, DAC1, DMA1_CH3>) { } #[embassy_executor::task] -async fn dac_task2(mut dac: DacCh2<'static, DAC1, DMA1_CH4>) { +async fn dac_task2(tim: TIM7, mut dac: DacCh2<'static, DAC1, DMA1_CH4>) { let data: &[u8; 256] = &calculate_array::<256>(); - info!("TIM7 frequency is {}", TIM7::frequency()); + info!("TIM7 frequency is {}", frequency::()); const FREQUENCY: Hertz = Hertz::hz(600); - let reload: u32 = (TIM7::frequency().0 / FREQUENCY.0) / data.len() as u32; + let reload: u32 = (frequency::().0 / FREQUENCY.0) / data.len() as u32; if reload < 10 { error!("Reload value {} below threshold!", reload); } - TIM7::enable_and_reset(); - TIM7::regs().arr().modify(|w| w.set_arr(reload as u16 - 1)); - TIM7::regs().cr2().modify(|w| w.set_mms(Mms::UPDATE)); - TIM7::regs().cr1().modify(|w| { + let tim = Timer::new(tim); + tim.regs_basic().arr().modify(|w| w.set_arr(reload as u16 - 1)); + tim.regs_basic().cr2().modify(|w| w.set_mms(Mms::UPDATE)); + tim.regs_basic().cr1().modify(|w| { w.set_opm(false); w.set_cen(true); }); @@ -96,7 +96,7 @@ async fn dac_task2(mut dac: DacCh2<'static, DAC1, DMA1_CH4>) { debug!( "TIM7 Frequency {}, Target Frequency {}, Reload {}, Reload as u16 {}, Samples {}", - TIM7::frequency(), + frequency::(), FREQUENCY, reload, reload as u16, diff --git a/examples/stm32l4/src/bin/i2c.rs b/examples/stm32l4/src/bin/i2c.rs index f553deb82..2861bc091 100644 --- a/examples/stm32l4/src/bin/i2c.rs +++ b/examples/stm32l4/src/bin/i2c.rs @@ -3,33 +3,17 @@ use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::dma::NoDma; use embassy_stm32::i2c::I2c; use embassy_stm32::time::Hertz; -use embassy_stm32::{bind_interrupts, i2c, peripherals}; use {defmt_rtt as _, panic_probe as _}; const ADDRESS: u8 = 0x5F; const WHOAMI: u8 = 0x0F; -bind_interrupts!(struct Irqs { - I2C2_EV => i2c::EventInterruptHandler; - I2C2_ER => i2c::ErrorInterruptHandler; -}); - #[embassy_executor::main] async fn main(_spawner: Spawner) { let p = embassy_stm32::init(Default::default()); - let mut i2c = I2c::new( - p.I2C2, - p.PB10, - p.PB11, - Irqs, - NoDma, - NoDma, - Hertz(100_000), - Default::default(), - ); + let mut i2c = I2c::new_blocking(p.I2C2, p.PB10, p.PB11, Hertz(100_000), Default::default()); let mut data = [0u8; 1]; unwrap!(i2c.blocking_write_read(ADDRESS, &[WHOAMI], &mut data)); diff --git a/examples/stm32l4/src/bin/i2c_blocking_async.rs b/examples/stm32l4/src/bin/i2c_blocking_async.rs index 1b8652bcc..a014b23e0 100644 --- a/examples/stm32l4/src/bin/i2c_blocking_async.rs +++ b/examples/stm32l4/src/bin/i2c_blocking_async.rs @@ -4,34 +4,18 @@ use defmt::*; use embassy_embedded_hal::adapter::BlockingAsync; use embassy_executor::Spawner; -use embassy_stm32::dma::NoDma; use embassy_stm32::i2c::I2c; use embassy_stm32::time::Hertz; -use embassy_stm32::{bind_interrupts, i2c, peripherals}; use embedded_hal_async::i2c::I2c as I2cTrait; use {defmt_rtt as _, panic_probe as _}; const ADDRESS: u8 = 0x5F; const WHOAMI: u8 = 0x0F; -bind_interrupts!(struct Irqs { - I2C2_EV => i2c::EventInterruptHandler; - I2C2_ER => i2c::ErrorInterruptHandler; -}); - #[embassy_executor::main] async fn main(_spawner: Spawner) { let p = embassy_stm32::init(Default::default()); - let i2c = I2c::new( - p.I2C2, - p.PB10, - p.PB11, - Irqs, - NoDma, - NoDma, - Hertz(100_000), - Default::default(), - ); + let i2c = I2c::new_blocking(p.I2C2, p.PB10, p.PB11, Hertz(100_000), Default::default()); let mut i2c = BlockingAsync::new(i2c); let mut data = [0u8; 1]; diff --git a/examples/stm32l4/src/bin/rng.rs b/examples/stm32l4/src/bin/rng.rs index 638b3e9e4..14d0e3c1e 100644 --- a/examples/stm32l4/src/bin/rng.rs +++ b/examples/stm32l4/src/bin/rng.rs @@ -3,7 +3,7 @@ use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::rcc::{ClockSrc, Pll, PllMul, PllPreDiv, PllQDiv, PllRDiv, PllSource}; +use embassy_stm32::rcc::{Pll, PllMul, PllPreDiv, PllQDiv, PllRDiv, PllSource, Sysclk}; use embassy_stm32::rng::Rng; use embassy_stm32::{bind_interrupts, peripherals, rng, Config}; use {defmt_rtt as _, panic_probe as _}; @@ -15,7 +15,7 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut config = Config::default(); - config.rcc.mux = ClockSrc::PLL1_R; + config.rcc.sys = Sysclk::PLL1_R; config.rcc.hsi = true; config.rcc.pll = Some(Pll { source: PllSource::HSI, diff --git a/examples/stm32l4/src/bin/rtc.rs b/examples/stm32l4/src/bin/rtc.rs index 526620bfb..f554f0f78 100644 --- a/examples/stm32l4/src/bin/rtc.rs +++ b/examples/stm32l4/src/bin/rtc.rs @@ -15,7 +15,7 @@ async fn main(_spawner: Spawner) { let mut config = Config::default(); { use embassy_stm32::rcc::*; - config.rcc.mux = ClockSrc::PLL1_R; + config.rcc.sys = Sysclk::PLL1_R; config.rcc.hse = Some(Hse { freq: Hertz::mhz(8), mode: HseMode::Oscillator, @@ -40,7 +40,7 @@ async fn main(_spawner: Spawner) { .unwrap(); let mut rtc = Rtc::new(p.RTC, RtcConfig::default()); - info!("Got RTC! {:?}", now.timestamp()); + info!("Got RTC! {:?}", now.and_utc().timestamp()); rtc.set_datetime(now.into()).expect("datetime not set"); @@ -48,5 +48,5 @@ async fn main(_spawner: Spawner) { Timer::after_millis(20000).await; let then: NaiveDateTime = rtc.now().unwrap().into(); - info!("Got RTC! {:?}", then.timestamp()); + info!("Got RTC! {:?}", then.and_utc().timestamp()); } diff --git a/examples/stm32l4/src/bin/spe_adin1110_http_server.rs b/examples/stm32l4/src/bin/spe_adin1110_http_server.rs index 026a3a477..4a7c01f9f 100644 --- a/examples/stm32l4/src/bin/spe_adin1110_http_server.rs +++ b/examples/stm32l4/src/bin/spe_adin1110_http_server.rs @@ -23,18 +23,23 @@ use embassy_futures::select::{select, Either}; use embassy_futures::yield_now; use embassy_net::tcp::TcpSocket; use embassy_net::{Ipv4Address, Ipv4Cidr, Stack, StackResources, StaticConfigV4}; +use embassy_net_adin1110::{Device, Runner, ADIN1110}; +use embassy_stm32::gpio::{Input, Level, Output, Pull, Speed}; +use embassy_stm32::i2c::{self, Config as I2C_Config, I2c}; +use embassy_stm32::mode::Async; +use embassy_stm32::rng::{self, Rng}; +use embassy_stm32::spi::{Config as SPI_Config, Spi}; +use embassy_stm32::time::Hertz; +use embassy_stm32::{bind_interrupts, exti, pac, peripherals}; use embassy_time::{Delay, Duration, Ticker, Timer}; use embedded_hal_async::i2c::I2c as I2cBus; +use embedded_hal_bus::spi::ExclusiveDevice; use embedded_io::Write as bWrite; use embedded_io_async::Write; -use hal::gpio::{Input, Level, Output, Speed}; -use hal::i2c::{self, I2c}; -use hal::rng::{self, Rng}; -use hal::{bind_interrupts, exti, pac, peripherals}; use heapless::Vec; +use panic_probe as _; use rand::RngCore; use static_cell::StaticCell; -use {embassy_stm32 as hal, panic_probe as _}; bind_interrupts!(struct Irqs { I2C3_EV => i2c::EventInterruptHandler; @@ -42,27 +47,20 @@ bind_interrupts!(struct Irqs { RNG => rng::InterruptHandler; }); -use embassy_net_adin1110::{self, Device, Runner, ADIN1110}; -use embedded_hal_bus::spi::ExclusiveDevice; -use hal::gpio::Pull; -use hal::i2c::Config as I2C_Config; -use hal::spi::{Config as SPI_Config, Spi}; -use hal::time::Hertz; - // Basic settings // MAC-address used by the adin1110 const MAC: [u8; 6] = [0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]; // Static IP settings -const IP_ADDRESS: Ipv4Cidr = Ipv4Cidr::new(Ipv4Address([192, 168, 1, 5]), 24); +const IP_ADDRESS: Ipv4Cidr = Ipv4Cidr::new(Ipv4Address::new(192, 168, 1, 5), 24); // Listen port for the webserver const HTTP_LISTEN_PORT: u16 = 80; -pub type SpeSpi = Spi<'static, peripherals::SPI2, peripherals::DMA1_CH1, peripherals::DMA1_CH2>; +pub type SpeSpi = Spi<'static, Async>; pub type SpeSpiCs = ExclusiveDevice, Delay>; pub type SpeInt = exti::ExtiInput<'static>; pub type SpeRst = Output<'static>; pub type Adin1110T = ADIN1110; -pub type TempSensI2c = I2c<'static, peripherals::I2C3, peripherals::DMA1_CH6, peripherals::DMA1_CH7>; +pub type TempSensI2c = I2c<'static, Async>; static TEMP: AtomicI32 = AtomicI32::new(0); @@ -75,7 +73,7 @@ async fn main(spawner: Spawner) { use embassy_stm32::rcc::*; // 80Mhz clock (Source: 8 / SrcDiv: 1 * PllMul 20 / ClkDiv 2) // 80MHz highest frequency for flash 0 wait. - config.rcc.mux = ClockSrc::PLL1_R; + config.rcc.sys = Sysclk::PLL1_R; config.rcc.hse = Some(Hse { freq: Hertz::mhz(8), mode: HseMode::Oscillator, @@ -93,12 +91,6 @@ async fn main(spawner: Spawner) { let dp = embassy_stm32::init(config); - // RM0432rev9, 5.1.2: Independent I/O supply rail - // After reset, the I/Os supplied by VDDIO2 are logically and electrically isolated and - // therefore are not available. The isolation must be removed before using any I/O from - // PG[15:2], by setting the IOSV bit in the PWR_CR2 register, once the VDDIO2 supply is present - pac::PWR.cr2().modify(|w| w.set_iosv(true)); - let reset_status = pac::RCC.bdcr().read().0; defmt::println!("bdcr before: 0x{:X}", reset_status); @@ -214,17 +206,11 @@ async fn main(spawner: Spawner) { }; // Init network stack - static STACK: StaticCell>> = StaticCell::new(); - static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - ip_cfg, - RESOURCES.init(StackResources::<2>::new()), - seed, - )); + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new(device, ip_cfg, RESOURCES.init(StackResources::new()), seed); // Launch network task - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); let cfg = wait_for_config(stack).await; let local_addr = cfg.address.address(); @@ -287,7 +273,7 @@ async fn main(spawner: Spawner) { } } -async fn wait_for_config(stack: &'static Stack>) -> embassy_net::StaticConfigV4 { +async fn wait_for_config(stack: Stack<'static>) -> embassy_net::StaticConfigV4 { loop { if let Some(config) = stack.config_v4() { return config; @@ -336,8 +322,8 @@ async fn ethernet_task(runner: Runner<'static, SpeSpiCs, SpeInt, SpeRst>) -> ! { } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static>>) -> ! { + runner.run().await } // same panicking *behavior* as `panic-probe` but doesn't print a panic message diff --git a/examples/stm32l4/src/bin/spi.rs b/examples/stm32l4/src/bin/spi.rs index 6653e4516..5693a3765 100644 --- a/examples/stm32l4/src/bin/spi.rs +++ b/examples/stm32l4/src/bin/spi.rs @@ -2,7 +2,6 @@ #![no_main] use defmt::*; -use embassy_stm32::dma::NoDma; use embassy_stm32::gpio::{Level, Output, Speed}; use embassy_stm32::spi::{Config, Spi}; use embassy_stm32::time::Hertz; @@ -17,7 +16,7 @@ fn main() -> ! { let mut spi_config = Config::default(); spi_config.frequency = Hertz(1_000_000); - let mut spi = Spi::new(p.SPI3, p.PC10, p.PC12, p.PC11, NoDma, NoDma, spi_config); + let mut spi = Spi::new_blocking(p.SPI3, p.PC10, p.PC12, p.PC11, spi_config); let mut cs = Output::new(p.PE0, Level::High, Speed::VeryHigh); diff --git a/examples/stm32l4/src/bin/spi_blocking_async.rs b/examples/stm32l4/src/bin/spi_blocking_async.rs index 68dbb70ad..1f1089101 100644 --- a/examples/stm32l4/src/bin/spi_blocking_async.rs +++ b/examples/stm32l4/src/bin/spi_blocking_async.rs @@ -4,7 +4,6 @@ use defmt::*; use embassy_embedded_hal::adapter::BlockingAsync; use embassy_executor::Spawner; -use embassy_stm32::dma::NoDma; use embassy_stm32::gpio::{Input, Level, Output, Pull, Speed}; use embassy_stm32::spi::{Config, Spi}; use embassy_stm32::time::Hertz; @@ -19,7 +18,7 @@ async fn main(_spawner: Spawner) { let mut spi_config = Config::default(); spi_config.frequency = Hertz(1_000_000); - let spi = Spi::new(p.SPI3, p.PC10, p.PC12, p.PC11, NoDma, NoDma, spi_config); + let spi = Spi::new_blocking(p.SPI3, p.PC10, p.PC12, p.PC11, spi_config); let mut spi = BlockingAsync::new(spi); diff --git a/examples/stm32l4/src/bin/usart.rs b/examples/stm32l4/src/bin/usart.rs index 7bab23950..d9b388026 100644 --- a/examples/stm32l4/src/bin/usart.rs +++ b/examples/stm32l4/src/bin/usart.rs @@ -2,7 +2,6 @@ #![no_main] use defmt::*; -use embassy_stm32::dma::NoDma; use embassy_stm32::usart::{Config, Uart}; use embassy_stm32::{bind_interrupts, peripherals, usart}; use {defmt_rtt as _, panic_probe as _}; @@ -18,7 +17,7 @@ fn main() -> ! { let p = embassy_stm32::init(Default::default()); let config = Config::default(); - let mut usart = Uart::new(p.UART4, p.PA1, p.PA0, Irqs, NoDma, NoDma, config).unwrap(); + let mut usart = Uart::new_blocking(p.UART4, p.PA1, p.PA0, config).unwrap(); unwrap!(usart.blocking_write(b"Hello Embassy World!\r\n")); info!("wrote Hello, starting echo"); diff --git a/examples/stm32l4/src/bin/usart_dma.rs b/examples/stm32l4/src/bin/usart_dma.rs index 031888f70..b4f7a1643 100644 --- a/examples/stm32l4/src/bin/usart_dma.rs +++ b/examples/stm32l4/src/bin/usart_dma.rs @@ -5,7 +5,6 @@ use core::fmt::Write; use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::dma::NoDma; use embassy_stm32::usart::{Config, Uart}; use embassy_stm32::{bind_interrupts, peripherals, usart}; use heapless::String; @@ -21,7 +20,7 @@ async fn main(_spawner: Spawner) { info!("Hello World!"); let config = Config::default(); - let mut usart = Uart::new(p.UART4, p.PA1, p.PA0, Irqs, p.DMA1_CH3, NoDma, config).unwrap(); + let mut usart = Uart::new(p.UART4, p.PA1, p.PA0, Irqs, p.DMA1_CH3, p.DMA1_CH4, config).unwrap(); for n in 0u32.. { let mut s: String<128> = String::new(); diff --git a/examples/stm32l4/src/bin/usb_serial.rs b/examples/stm32l4/src/bin/usb_serial.rs index 8cc9a7aed..c3b1211d8 100644 --- a/examples/stm32l4/src/bin/usb_serial.rs +++ b/examples/stm32l4/src/bin/usb_serial.rs @@ -4,42 +4,55 @@ use defmt::{panic, *}; use defmt_rtt as _; // global logger use embassy_executor::Spawner; -use embassy_stm32::rcc::*; -use embassy_stm32::usb_otg::{Driver, Instance}; -use embassy_stm32::{bind_interrupts, peripherals, usb_otg, Config}; +use embassy_futures::join::join; +use embassy_stm32::usb::{Driver, Instance}; +use embassy_stm32::{bind_interrupts, peripherals, usb, Config}; use embassy_usb::class::cdc_acm::{CdcAcmClass, State}; use embassy_usb::driver::EndpointError; use embassy_usb::Builder; -use futures::future::join; use panic_probe as _; bind_interrupts!(struct Irqs { - OTG_FS => usb_otg::InterruptHandler; + OTG_FS => usb::InterruptHandler; }); +// If you are trying this and your USB device doesn't connect, the most +// common issues are the RCC config and vbus_detection +// +// See https://embassy.dev/book/#_the_usb_examples_are_not_working_on_my_board_is_there_anything_else_i_need_to_configure +// for more information. #[embassy_executor::main] async fn main(_spawner: Spawner) { info!("Hello World!"); let mut config = Config::default(); - config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true }); // needed for USB - config.rcc.mux = ClockSrc::PLL1_R; - config.rcc.hsi = true; - config.rcc.pll = Some(Pll { - source: PllSource::HSI, - prediv: PllPreDiv::DIV1, - mul: PllMul::MUL10, - divp: None, - divq: None, - divr: Some(PllRDiv::DIV2), // sysclk 80Mhz (16 / 1 * 10 / 2) - }); - + { + use embassy_stm32::rcc::*; + config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true }); // needed for USB + config.rcc.sys = Sysclk::PLL1_R; + config.rcc.hsi = true; + config.rcc.pll = Some(Pll { + source: PllSource::HSI, + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL10, + divp: None, + divq: None, + divr: Some(PllRDiv::DIV2), // sysclk 80Mhz (16 / 1 * 10 / 2) + }); + config.rcc.mux.clk48sel = mux::Clk48sel::HSI48; + } let p = embassy_stm32::init(config); // Create the driver, from the HAL. let mut ep_out_buffer = [0u8; 256]; - let mut config = embassy_stm32::usb_otg::Config::default(); - config.vbus_detection = true; + let mut config = embassy_stm32::usb::Config::default(); + + // Do not enable vbus_detection. This is a safe default that works in all boards. + // However, if your USB device is self-powered (can stay powered on if USB is unplugged), you need + // to enable vbus_detection to comply with the USB spec. If you enable it, the board + // has to support it or USB won't work at all. See docs on `vbus_detection` for details. + config.vbus_detection = false; + let driver = Driver::new_fs(p.USB_OTG_FS, Irqs, p.PA12, p.PA11, &mut ep_out_buffer, config); // Create embassy-usb Config @@ -58,7 +71,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 64]; @@ -68,7 +80,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], // no msos descriptors diff --git a/examples/stm32l5/Cargo.toml b/examples/stm32l5/Cargo.toml index 0c6beb72c..0604625f2 100644 --- a/examples/stm32l5/Cargo.toml +++ b/examples/stm32l5/Cargo.toml @@ -7,13 +7,13 @@ license = "MIT OR Apache-2.0" [dependencies] # Change stm32l552ze to your chip name, if necessary. embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = [ "defmt", "unstable-pac", "stm32l552ze", "time-driver-any", "exti", "memory-x", "low-power"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } -embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet"] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } -usbd-hid = "0.6.0" +usbd-hid = "0.8.1" defmt = "0.3" defmt-rtt = "0.4" @@ -22,7 +22,6 @@ panic-probe = { version = "0.3", features = ["print-defmt"] } cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] } cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } rand_core = { version = "0.6.3", default-features = false } embedded-io-async = { version = "0.6.1" } diff --git a/examples/stm32l5/src/bin/rng.rs b/examples/stm32l5/src/bin/rng.rs index 50da6c946..0a644e73d 100644 --- a/examples/stm32l5/src/bin/rng.rs +++ b/examples/stm32l5/src/bin/rng.rs @@ -3,7 +3,7 @@ use defmt::*; use embassy_executor::Spawner; -use embassy_stm32::rcc::{ClockSrc, Pll, PllMul, PllPreDiv, PllRDiv, PllSource}; +use embassy_stm32::rcc::{Pll, PllMul, PllPreDiv, PllRDiv, PllSource, Sysclk}; use embassy_stm32::rng::Rng; use embassy_stm32::{bind_interrupts, peripherals, rng, Config}; use {defmt_rtt as _, panic_probe as _}; @@ -16,7 +16,7 @@ bind_interrupts!(struct Irqs { async fn main(_spawner: Spawner) { let mut config = Config::default(); config.rcc.hsi = true; - config.rcc.mux = ClockSrc::PLL1_R; + config.rcc.sys = Sysclk::PLL1_R; config.rcc.pll = Some(Pll { // 64Mhz clock (16 / 1 * 8 / 2) source: PllSource::HSI, diff --git a/examples/stm32l5/src/bin/usb_ethernet.rs b/examples/stm32l5/src/bin/usb_ethernet.rs index 88060b6b0..095d50c73 100644 --- a/examples/stm32l5/src/bin/usb_ethernet.rs +++ b/examples/stm32l5/src/bin/usb_ethernet.rs @@ -4,8 +4,7 @@ use defmt::*; use embassy_executor::Spawner; use embassy_net::tcp::TcpSocket; -use embassy_net::{Stack, StackResources}; -use embassy_stm32::rcc::*; +use embassy_net::StackResources; use embassy_stm32::rng::Rng; use embassy_stm32::usb::Driver; use embassy_stm32::{bind_interrupts, peripherals, rng, usb, Config}; @@ -37,24 +36,29 @@ async fn usb_ncm_task(class: Runner<'static, MyDriver, MTU>) -> ! { } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static, MTU>>) -> ! { + runner.run().await } #[embassy_executor::main] async fn main(spawner: Spawner) { let mut config = Config::default(); - config.rcc.hsi = true; - config.rcc.mux = ClockSrc::PLL1_R; - config.rcc.pll = Some(Pll { - // 80Mhz clock (16 / 1 * 10 / 2) - source: PllSource::HSI, - prediv: PllPreDiv::DIV1, - mul: PllMul::MUL10, - divp: None, - divq: None, - divr: Some(PllRDiv::DIV2), - }); + { + use embassy_stm32::rcc::*; + config.rcc.hsi = true; + config.rcc.sys = Sysclk::PLL1_R; + config.rcc.pll = Some(Pll { + // 80Mhz clock (16 / 1 * 10 / 2) + source: PllSource::HSI, + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL10, + divp: None, + divq: None, + divr: Some(PllRDiv::DIV2), + }); + config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true }); // needed for USB + config.rcc.mux.clk48sel = mux::Clk48sel::HSI48; + } let p = embassy_stm32::init(config); // Create the driver, from the HAL. @@ -75,14 +79,12 @@ async fn main(spawner: Spawner) { config.device_protocol = 0x01; // Create embassy-usb DeviceBuilder using the driver and config. - static DEVICE_DESC: StaticCell<[u8; 256]> = StaticCell::new(); static CONFIG_DESC: StaticCell<[u8; 256]> = StaticCell::new(); static BOS_DESC: StaticCell<[u8; 256]> = StaticCell::new(); static CONTROL_BUF: StaticCell<[u8; 128]> = StaticCell::new(); let mut builder = Builder::new( driver, config, - &mut DEVICE_DESC.init([0; 256])[..], &mut CONFIG_DESC.init([0; 256])[..], &mut BOS_DESC.init([0; 256])[..], &mut [], // no msos descriptors @@ -119,16 +121,10 @@ async fn main(spawner: Spawner) { let seed = rng.next_u64(); // Init network stack - static STACK: StaticCell>> = StaticCell::new(); - static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<2>::new()), - seed, - )); + static RESOURCES: StaticCell> = StaticCell::new(); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); // And now we can use it! diff --git a/examples/stm32l5/src/bin/usb_hid_mouse.rs b/examples/stm32l5/src/bin/usb_hid_mouse.rs index 7c8a8ebfb..3f8c52b82 100644 --- a/examples/stm32l5/src/bin/usb_hid_mouse.rs +++ b/examples/stm32l5/src/bin/usb_hid_mouse.rs @@ -4,7 +4,6 @@ use defmt::*; use embassy_executor::Spawner; use embassy_futures::join::join; -use embassy_stm32::rcc::*; use embassy_stm32::usb::Driver; use embassy_stm32::{bind_interrupts, peripherals, usb, Config}; use embassy_time::Timer; @@ -21,17 +20,22 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut config = Config::default(); - config.rcc.hsi = true; - config.rcc.mux = ClockSrc::PLL1_R; - config.rcc.pll = Some(Pll { - // 80Mhz clock (16 / 1 * 10 / 2) - source: PllSource::HSI, - prediv: PllPreDiv::DIV1, - mul: PllMul::MUL10, - divp: None, - divq: None, - divr: Some(PllRDiv::DIV2), - }); + { + use embassy_stm32::rcc::*; + config.rcc.hsi = true; + config.rcc.sys = Sysclk::PLL1_R; + config.rcc.pll = Some(Pll { + // 80Mhz clock (16 / 1 * 10 / 2) + source: PllSource::HSI, + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL10, + divp: None, + divq: None, + divr: Some(PllRDiv::DIV2), + }); + config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true }); // needed for USB + config.rcc.mux.clk48sel = mux::Clk48sel::HSI48; + } let p = embassy_stm32::init(config); // Create the driver, from the HAL. @@ -47,18 +51,16 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 64]; - let request_handler = MyRequestHandler {}; + let mut request_handler = MyRequestHandler {}; let mut state = State::new(); let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], // no msos descriptors @@ -68,7 +70,7 @@ async fn main(_spawner: Spawner) { // Create classes on the builder. let config = embassy_usb::class::hid::Config { report_descriptor: MouseReport::desc(), - request_handler: Some(&request_handler), + request_handler: Some(&mut request_handler), poll_ms: 60, max_packet_size: 8, }; @@ -110,21 +112,21 @@ async fn main(_spawner: Spawner) { struct MyRequestHandler {} impl RequestHandler for MyRequestHandler { - fn get_report(&self, id: ReportId, _buf: &mut [u8]) -> Option { + fn get_report(&mut self, id: ReportId, _buf: &mut [u8]) -> Option { info!("Get report for {:?}", id); None } - fn set_report(&self, id: ReportId, data: &[u8]) -> OutResponse { + fn set_report(&mut self, id: ReportId, data: &[u8]) -> OutResponse { info!("Set report for {:?}: {=[u8]}", id, data); OutResponse::Accepted } - fn set_idle_ms(&self, id: Option, dur: u32) { + fn set_idle_ms(&mut self, id: Option, dur: u32) { info!("Set idle rate for {:?} to {:?}", id, dur); } - fn get_idle_ms(&self, id: Option) -> Option { + fn get_idle_ms(&mut self, id: Option) -> Option { info!("Get idle rate for {:?}", id); None } diff --git a/examples/stm32l5/src/bin/usb_serial.rs b/examples/stm32l5/src/bin/usb_serial.rs index 75053ce4b..a64bda31b 100644 --- a/examples/stm32l5/src/bin/usb_serial.rs +++ b/examples/stm32l5/src/bin/usb_serial.rs @@ -4,7 +4,6 @@ use defmt::{panic, *}; use embassy_executor::Spawner; use embassy_futures::join::join; -use embassy_stm32::rcc::*; use embassy_stm32::usb::{Driver, Instance}; use embassy_stm32::{bind_interrupts, peripherals, usb, Config}; use embassy_usb::class::cdc_acm::{CdcAcmClass, State}; @@ -19,17 +18,22 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut config = Config::default(); - config.rcc.hsi = true; - config.rcc.mux = ClockSrc::PLL1_R; - config.rcc.pll = Some(Pll { - // 80Mhz clock (16 / 1 * 10 / 2) - source: PllSource::HSI, - prediv: PllPreDiv::DIV1, - mul: PllMul::MUL10, - divp: None, - divq: None, - divr: Some(PllRDiv::DIV2), - }); + { + use embassy_stm32::rcc::*; + config.rcc.hsi = true; + config.rcc.sys = Sysclk::PLL1_R; + config.rcc.pll = Some(Pll { + // 80Mhz clock (16 / 1 * 10 / 2) + source: PllSource::HSI, + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL10, + divp: None, + divq: None, + divr: Some(PllRDiv::DIV2), + }); + config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true }); // needed for USB + config.rcc.mux.clk48sel = mux::Clk48sel::HSI48; + } let p = embassy_stm32::init(config); info!("Hello World!"); @@ -43,7 +47,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 7]; @@ -53,7 +56,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], // no msos descriptors diff --git a/examples/stm32u0/.cargo/config.toml b/examples/stm32u0/.cargo/config.toml new file mode 100644 index 000000000..688347084 --- /dev/null +++ b/examples/stm32u0/.cargo/config.toml @@ -0,0 +1,9 @@ +[target.'cfg(all(target_arch = "arm", target_os = "none"))'] +# replace stm32u083rctx with your chip as listed in `probe-rs chip list` +runner = "probe-rs run --chip stm32u083rctx" + +[build] +target = "thumbv6m-none-eabi" + +[env] +DEFMT_LOG = "trace" diff --git a/examples/stm32u0/Cargo.toml b/examples/stm32u0/Cargo.toml new file mode 100644 index 000000000..97ef0b704 --- /dev/null +++ b/examples/stm32u0/Cargo.toml @@ -0,0 +1,29 @@ +[package] +edition = "2021" +name = "embassy-stm32u0-examples" +version = "0.1.0" +license = "MIT OR Apache-2.0" + +[dependencies] +# Change stm32u083rc to your chip name, if necessary. +embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = [ "defmt", "time-driver-any", "stm32u083rc", "memory-x", "unstable-pac", "exti", "chrono"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", default-features = false, features = ["defmt"] } +embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } + +defmt = "0.3" +defmt-rtt = "0.4" + +cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] } +cortex-m-rt = "0.7.0" +embedded-hal = "0.2.6" +panic-probe = { version = "0.3", features = ["print-defmt"] } +heapless = { version = "0.8", default-features = false } + +micromath = "2.0.0" +chrono = { version = "0.4.38", default-features = false } + +[profile.release] +debug = 2 diff --git a/examples/stm32u0/build.rs b/examples/stm32u0/build.rs new file mode 100644 index 000000000..8cd32d7ed --- /dev/null +++ b/examples/stm32u0/build.rs @@ -0,0 +1,5 @@ +fn main() { + println!("cargo:rustc-link-arg-bins=--nmagic"); + println!("cargo:rustc-link-arg-bins=-Tlink.x"); + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); +} diff --git a/examples/stm32u0/src/bin/adc.rs b/examples/stm32u0/src/bin/adc.rs new file mode 100644 index 000000000..c8252e4e1 --- /dev/null +++ b/examples/stm32u0/src/bin/adc.rs @@ -0,0 +1,30 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_stm32::adc::{Adc, Resolution}; +use embassy_stm32::Config; +use embassy_time::Duration; +use {defmt_rtt as _, panic_probe as _}; + +#[cortex_m_rt::entry] +fn main() -> ! { + info!("Hello World!"); + + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.mux.adcsel = mux::Adcsel::SYS; + } + let p = embassy_stm32::init(config); + + let mut adc = Adc::new(p.ADC1); + adc.set_resolution(Resolution::BITS8); + let mut channel = p.PC0; + + loop { + let v = adc.blocking_read(&mut channel); + info!("--> {}", v); + embassy_time::block_for(Duration::from_millis(200)); + } +} diff --git a/examples/stm32u0/src/bin/blinky.rs b/examples/stm32u0/src/bin/blinky.rs new file mode 100644 index 000000000..90e479aae --- /dev/null +++ b/examples/stm32u0/src/bin/blinky.rs @@ -0,0 +1,26 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + let mut led = Output::new(p.PA5, Level::High, Speed::Low); + + loop { + info!("high"); + led.set_high(); + Timer::after_millis(300).await; + + info!("low"); + led.set_low(); + Timer::after_millis(300).await; + } +} diff --git a/examples/stm32u0/src/bin/button.rs b/examples/stm32u0/src/bin/button.rs new file mode 100644 index 000000000..8017f0274 --- /dev/null +++ b/examples/stm32u0/src/bin/button.rs @@ -0,0 +1,24 @@ +#![no_std] +#![no_main] + +use cortex_m_rt::entry; +use defmt::*; +use embassy_stm32::gpio::{Input, Pull}; +use {defmt_rtt as _, panic_probe as _}; + +#[entry] +fn main() -> ! { + info!("Hello World!"); + + let p = embassy_stm32::init(Default::default()); + + let button = Input::new(p.PC13, Pull::Up); + + loop { + if button.is_high() { + info!("high"); + } else { + info!("low"); + } + } +} diff --git a/examples/stm32u0/src/bin/button_exti.rs b/examples/stm32u0/src/bin/button_exti.rs new file mode 100644 index 000000000..34a08bbc6 --- /dev/null +++ b/examples/stm32u0/src/bin/button_exti.rs @@ -0,0 +1,25 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::exti::ExtiInput; +use embassy_stm32::gpio::Pull; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + let mut button = ExtiInput::new(p.PC13, p.EXTI13, Pull::Up); + + info!("Press the USER button..."); + + loop { + button.wait_for_falling_edge().await; + info!("Pressed!"); + button.wait_for_rising_edge().await; + info!("Released!"); + } +} diff --git a/examples/stm32u0/src/bin/crc.rs b/examples/stm32u0/src/bin/crc.rs new file mode 100644 index 000000000..d1b545d5b --- /dev/null +++ b/examples/stm32u0/src/bin/crc.rs @@ -0,0 +1,31 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::crc::{Config, Crc, InputReverseConfig, PolySize}; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + // Setup for: https://crccalc.com/?crc=Life, it never dieWomen are my favorite guy&method=crc32&datatype=ascii&outtype=0 + let mut crc = Crc::new( + p.CRC, + unwrap!(Config::new( + InputReverseConfig::Byte, + true, + PolySize::Width32, + 0xFFFFFFFF, + 0x04C11DB7 + )), + ); + + let output = crc.feed_bytes(b"Life, it never die\nWomen are my favorite guy") ^ 0xFFFFFFFF; + + defmt::assert_eq!(output, 0x33F0E26B); + + cortex_m::asm::bkpt(); +} diff --git a/examples/stm32u0/src/bin/dac.rs b/examples/stm32u0/src/bin/dac.rs new file mode 100644 index 000000000..fdbf1d374 --- /dev/null +++ b/examples/stm32u0/src/bin/dac.rs @@ -0,0 +1,35 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_stm32::dac::{DacCh1, Value}; +use embassy_stm32::dma::NoDma; +use {defmt_rtt as _, panic_probe as _}; + +#[cortex_m_rt::entry] +fn main() -> ! { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + let mut dac = DacCh1::new(p.DAC1, NoDma, p.PA4); + + loop { + for v in 0..=255 { + dac.set(Value::Bit8(to_sine_wave(v))); + } + } +} + +use micromath::F32Ext; + +fn to_sine_wave(v: u8) -> u8 { + if v >= 128 { + // top half + let r = 3.14 * ((v - 128) as f32 / 128.0); + (r.sin() * 128.0 + 127.0) as u8 + } else { + // bottom half + let r = 3.14 + 3.14 * (v as f32 / 128.0); + (r.sin() * 128.0 + 127.0) as u8 + } +} diff --git a/examples/stm32u0/src/bin/flash.rs b/examples/stm32u0/src/bin/flash.rs new file mode 100644 index 000000000..01b80a76b --- /dev/null +++ b/examples/stm32u0/src/bin/flash.rs @@ -0,0 +1,43 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::flash::Flash; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + let addr: u32 = 0x40000 - 2 * 1024; + + let mut f = Flash::new_blocking(p.FLASH).into_blocking_regions().bank1_region; + + info!("Reading..."); + let mut buf = [0u8; 32]; + unwrap!(f.blocking_read(addr, &mut buf)); + info!("Read: {=[u8]:x}", buf); + info!("Erasing..."); + unwrap!(f.blocking_erase(addr, addr + 2 * 1024)); + + info!("Reading..."); + let mut buf = [0u8; 32]; + unwrap!(f.blocking_read(addr, &mut buf)); + info!("Read after erase: {=[u8]:x}", buf); + + info!("Writing..."); + unwrap!(f.blocking_write( + addr, + &[ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32 + ] + )); + + info!("Reading..."); + let mut buf = [0u8; 32]; + unwrap!(f.blocking_read(addr, &mut buf)); + info!("Read: {=[u8]:x}", buf); +} diff --git a/examples/stm32u0/src/bin/i2c.rs b/examples/stm32u0/src/bin/i2c.rs new file mode 100644 index 000000000..2861bc091 --- /dev/null +++ b/examples/stm32u0/src/bin/i2c.rs @@ -0,0 +1,21 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::i2c::I2c; +use embassy_stm32::time::Hertz; +use {defmt_rtt as _, panic_probe as _}; + +const ADDRESS: u8 = 0x5F; +const WHOAMI: u8 = 0x0F; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + let mut i2c = I2c::new_blocking(p.I2C2, p.PB10, p.PB11, Hertz(100_000), Default::default()); + + let mut data = [0u8; 1]; + unwrap!(i2c.blocking_write_read(ADDRESS, &[WHOAMI], &mut data)); + info!("Whoami: {}", data[0]); +} diff --git a/examples/stm32u0/src/bin/rng.rs b/examples/stm32u0/src/bin/rng.rs new file mode 100644 index 000000000..89445b042 --- /dev/null +++ b/examples/stm32u0/src/bin/rng.rs @@ -0,0 +1,43 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::rcc::mux::Clk48sel; +use embassy_stm32::rng::Rng; +use embassy_stm32::{bind_interrupts, peripherals, rng, Config}; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + RNG_CRYP => rng::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.hsi = true; + config.rcc.pll = Some(Pll { + source: PllSource::HSI, // 16 MHz + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL7, // 16 * 7 = 112 MHz + divp: None, + divq: None, + divr: Some(PllRDiv::DIV2), // 112 / 2 = 56 MHz + }); + config.rcc.sys = Sysclk::PLL1_R; + config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: false }); // needed for RNG + config.rcc.mux.clk48sel = Clk48sel::HSI48; // needed for RNG (or use MSI or PLLQ if you want) + } + + let p = embassy_stm32::init(config); + + info!("Hello World!"); + + let mut rng = Rng::new(p.RNG, Irqs); + + let mut buf = [0u8; 16]; + unwrap!(rng.async_fill_bytes(&mut buf).await); + info!("random bytes: {:02x}", buf); +} diff --git a/examples/stm32u0/src/bin/rtc.rs b/examples/stm32u0/src/bin/rtc.rs new file mode 100644 index 000000000..72fa0fde4 --- /dev/null +++ b/examples/stm32u0/src/bin/rtc.rs @@ -0,0 +1,49 @@ +#![no_std] +#![no_main] + +use chrono::{NaiveDate, NaiveDateTime}; +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::rtc::{Rtc, RtcConfig}; +use embassy_stm32::Config; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.sys = Sysclk::PLL1_R; + config.rcc.hsi = true; + config.rcc.pll = Some(Pll { + source: PllSource::HSI, // 16 MHz + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL7, // 16 * 7 = 112 MHz + divp: None, + divq: None, + divr: Some(PllRDiv::DIV2), // 112 / 2 = 56 MHz + }); + config.rcc.ls = LsConfig::default(); + } + + let p = embassy_stm32::init(config); + + info!("Hello World!"); + + let now = NaiveDate::from_ymd_opt(2020, 5, 15) + .unwrap() + .and_hms_opt(10, 30, 15) + .unwrap(); + + let mut rtc = Rtc::new(p.RTC, RtcConfig::default()); + info!("Got RTC! {:?}", now.and_utc().timestamp()); + + rtc.set_datetime(now.into()).expect("datetime not set"); + + // In reality the delay would be much longer + Timer::after_millis(20000).await; + + let then: NaiveDateTime = rtc.now().unwrap().into(); + info!("Got RTC! {:?}", then.and_utc().timestamp()); +} diff --git a/examples/stm32u0/src/bin/spi.rs b/examples/stm32u0/src/bin/spi.rs new file mode 100644 index 000000000..5693a3765 --- /dev/null +++ b/examples/stm32u0/src/bin/spi.rs @@ -0,0 +1,30 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::spi::{Config, Spi}; +use embassy_stm32::time::Hertz; +use {defmt_rtt as _, panic_probe as _}; + +#[cortex_m_rt::entry] +fn main() -> ! { + info!("Hello World!"); + + let p = embassy_stm32::init(Default::default()); + + let mut spi_config = Config::default(); + spi_config.frequency = Hertz(1_000_000); + + let mut spi = Spi::new_blocking(p.SPI3, p.PC10, p.PC12, p.PC11, spi_config); + + let mut cs = Output::new(p.PE0, Level::High, Speed::VeryHigh); + + loop { + let mut buf = [0x0Au8; 4]; + cs.set_low(); + unwrap!(spi.blocking_transfer_in_place(&mut buf)); + cs.set_high(); + info!("xfer {=[u8]:x}", buf); + } +} diff --git a/examples/stm32u0/src/bin/usart.rs b/examples/stm32u0/src/bin/usart.rs new file mode 100644 index 000000000..037a5c833 --- /dev/null +++ b/examples/stm32u0/src/bin/usart.rs @@ -0,0 +1,25 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_stm32::usart::{Config, Uart}; +use {defmt_rtt as _, panic_probe as _}; + +#[cortex_m_rt::entry] +fn main() -> ! { + info!("Hello World!"); + + let p = embassy_stm32::init(Default::default()); + + let config = Config::default(); + let mut usart = Uart::new_blocking(p.USART2, p.PA3, p.PA2, config).unwrap(); + + unwrap!(usart.blocking_write(b"Hello Embassy World!\r\n")); + info!("wrote Hello, starting echo"); + + let mut buf = [0u8; 1]; + loop { + unwrap!(usart.blocking_read(&mut buf)); + unwrap!(usart.blocking_write(&buf)); + } +} diff --git a/examples/stm32u0/src/bin/usb_serial.rs b/examples/stm32u0/src/bin/usb_serial.rs new file mode 100644 index 000000000..273f40643 --- /dev/null +++ b/examples/stm32u0/src/bin/usb_serial.rs @@ -0,0 +1,109 @@ +#![no_std] +#![no_main] + +use defmt::{panic, *}; +use defmt_rtt as _; // global logger +use embassy_executor::Spawner; +use embassy_futures::join::join; +use embassy_stm32::usb::{Driver, Instance}; +use embassy_stm32::{bind_interrupts, peripherals, usb, Config}; +use embassy_usb::class::cdc_acm::{CdcAcmClass, State}; +use embassy_usb::driver::EndpointError; +use embassy_usb::Builder; +use panic_probe as _; + +bind_interrupts!(struct Irqs { + USB_DRD_FS => usb::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.hsi = true; + config.rcc.pll = Some(Pll { + source: PllSource::HSI, // 16 MHz + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL7, + divp: None, + divq: None, + divr: Some(PllRDiv::DIV2), // 56 MHz + }); + config.rcc.sys = Sysclk::PLL1_R; + config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true }); // needed for USB + config.rcc.mux.clk48sel = mux::Clk48sel::HSI48; // USB uses ICLK + } + + let p = embassy_stm32::init(config); + + info!("Hello World!"); + + // Create the driver, from the HAL. + let driver = Driver::new(p.USB, Irqs, p.PA12, p.PA11); + + // Create embassy-usb Config + let config = embassy_usb::Config::new(0xc0de, 0xcafe); + //config.max_packet_size_0 = 64; + + // Create embassy-usb DeviceBuilder using the driver and config. + // It needs some buffers for building the descriptors. + let mut config_descriptor = [0; 256]; + let mut bos_descriptor = [0; 256]; + let mut control_buf = [0; 7]; + + let mut state = State::new(); + + let mut builder = Builder::new( + driver, + config, + &mut config_descriptor, + &mut bos_descriptor, + &mut [], // no msos descriptors + &mut control_buf, + ); + + // Create classes on the builder. + let mut class = CdcAcmClass::new(&mut builder, &mut state, 64); + + // Build the builder. + let mut usb = builder.build(); + + // Run the USB device. + let usb_fut = usb.run(); + + // Do stuff with the class! + let echo_fut = async { + loop { + class.wait_connection().await; + info!("Connected"); + let _ = echo(&mut class).await; + info!("Disconnected"); + } + }; + + // Run everything concurrently. + // If we had made everything `'static` above instead, we could do this using separate tasks instead. + join(usb_fut, echo_fut).await; +} + +struct Disconnected {} + +impl From for Disconnected { + fn from(val: EndpointError) -> Self { + match val { + EndpointError::BufferOverflow => panic!("Buffer overflow"), + EndpointError::Disabled => Disconnected {}, + } + } +} + +async fn echo<'d, T: Instance + 'd>(class: &mut CdcAcmClass<'d, Driver<'d, T>>) -> Result<(), Disconnected> { + let mut buf = [0; 64]; + loop { + let n = class.read_packet(&mut buf).await?; + let data = &buf[..n]; + info!("data: {:x}", data); + class.write_packet(data).await?; + } +} diff --git a/examples/stm32u0/src/bin/wdt.rs b/examples/stm32u0/src/bin/wdt.rs new file mode 100644 index 000000000..f6276e2e9 --- /dev/null +++ b/examples/stm32u0/src/bin/wdt.rs @@ -0,0 +1,41 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::wdg::IndependentWatchdog; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hello World!"); + + let mut led = Output::new(p.PA5, Level::High, Speed::Low); + + let mut wdt = IndependentWatchdog::new(p.IWDG, 1_000_000); + wdt.unleash(); + + let mut i = 0; + + loop { + info!("high"); + led.set_high(); + Timer::after_millis(300).await; + + info!("low"); + led.set_low(); + Timer::after_millis(300).await; + + // Pet watchdog for 5 iterations and then stop. + // MCU should restart in 1 second after the last pet. + if i < 5 { + info!("Petting watchdog"); + wdt.pet(); + } + + i += 1; + } +} diff --git a/examples/stm32u5/.cargo/config.toml b/examples/stm32u5/.cargo/config.toml index 36c5b63a6..bdbd86354 100644 --- a/examples/stm32u5/.cargo/config.toml +++ b/examples/stm32u5/.cargo/config.toml @@ -1,6 +1,6 @@ [target.'cfg(all(target_arch = "arm", target_os = "none"))'] -# replace STM32U585AIIx with your chip as listed in `probe-rs chip list` -runner = "probe-rs run --chip STM32U585AIIx" +# replace STM32U5G9ZJTxQ with your chip as listed in `probe-rs chip list` +runner = "probe-rs run --chip STM32U5G9ZJTxQ" [build] target = "thumbv8m.main-none-eabihf" diff --git a/examples/stm32u5/Cargo.toml b/examples/stm32u5/Cargo.toml index 03294339d..f474e6db0 100644 --- a/examples/stm32u5/Cargo.toml +++ b/examples/stm32u5/Cargo.toml @@ -5,12 +5,13 @@ version = "0.1.0" license = "MIT OR Apache-2.0" [dependencies] -# Change stm32u585ai to your chip name, if necessary. -embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "unstable-pac", "stm32u585ai", "time-driver-any", "memory-x" ] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } -embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } +# Change stm32u5g9zj to your chip name, if necessary. +embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "unstable-pac", "stm32u5g9zj", "time-driver-any", "memory-x" ] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-usb = { version = "0.3.0", path = "../../embassy-usb", features = ["defmt"] } +embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } defmt = "0.3" defmt-rtt = "0.4" @@ -19,10 +20,15 @@ cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-sing cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } +embedded-graphics = { version = "0.8.1" } +tinybmp = { version = "0.6.0" } micromath = "2.0.0" +[features] +## Use secure registers when TrustZone is enabled +trustzone-secure = ["embassy-stm32/trustzone-secure"] + [profile.release] debug = 2 diff --git a/examples/stm32u5/src/bin/ferris.bmp b/examples/stm32u5/src/bin/ferris.bmp new file mode 100644 index 000000000..7a222ab84 Binary files /dev/null and b/examples/stm32u5/src/bin/ferris.bmp differ diff --git a/examples/stm32u5/src/bin/flash.rs b/examples/stm32u5/src/bin/flash.rs new file mode 100644 index 000000000..e4fd6bb9c --- /dev/null +++ b/examples/stm32u5/src/bin/flash.rs @@ -0,0 +1,55 @@ +#![no_std] +#![no_main] + +use defmt::{info, unwrap}; +use embassy_executor::Spawner; +use embassy_stm32::flash::Flash; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + info!("Hello Flash!"); + + const ADDR: u32 = 0x8_0000; // This is the offset into the third region, the absolute address is 4x32K + 128K + 0x8_0000. + + // wait a bit before accessing the flash + Timer::after_millis(300).await; + + let mut f = Flash::new_blocking(p.FLASH).into_blocking_regions().bank1_region; + + info!("Reading..."); + let mut buf = [0u8; 32]; + unwrap!(f.blocking_read(ADDR, &mut buf)); + info!("Read: {=[u8]:x}", buf); + + info!("Erasing..."); + unwrap!(f.blocking_erase(ADDR, ADDR + 256 * 1024)); + + info!("Reading..."); + let mut buf = [0u8; 32]; + unwrap!(f.blocking_read(ADDR, &mut buf)); + info!("Read after erase: {=[u8]:x}", buf); + + info!("Writing..."); + unwrap!(f.blocking_write( + ADDR, + &[ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32 + ] + )); + + info!("Reading..."); + let mut buf = [0u8; 32]; + unwrap!(f.blocking_read(ADDR, &mut buf)); + info!("Read: {=[u8]:x}", buf); + assert_eq!( + &buf[..], + &[ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32 + ] + ); +} diff --git a/examples/stm32u5/src/bin/i2c.rs b/examples/stm32u5/src/bin/i2c.rs new file mode 100644 index 000000000..d5f5d6f60 --- /dev/null +++ b/examples/stm32u5/src/bin/i2c.rs @@ -0,0 +1,25 @@ +#![no_std] +#![no_main] + +use defmt::{info, unwrap}; +use embassy_executor::Spawner; +use embassy_stm32::i2c::I2c; +use embassy_stm32::time::Hertz; +use {defmt_rtt as _, panic_probe as _}; + +const HTS221_ADDRESS: u8 = 0x5F; +const WHOAMI: u8 = 0x0F; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + let mut i2c = I2c::new_blocking(p.I2C2, p.PF1, p.PF0, Hertz(100_000), Default::default()); + + let mut data = [0u8; 1]; + unwrap!(i2c.blocking_write_read(HTS221_ADDRESS, &[WHOAMI], &mut data)); + + // HTS221 data sheet is here: https://www.st.com/resource/en/datasheet/hts221.pdf + // 7.1 WHO_AM_I command is x0F which expected response xBC. + info!("Whoami: 0x{:02x}", data[0]); + assert_eq!(0xBC, data[0]); +} diff --git a/examples/stm32u5/src/bin/ltdc.rs b/examples/stm32u5/src/bin/ltdc.rs new file mode 100644 index 000000000..bd59a9148 --- /dev/null +++ b/examples/stm32u5/src/bin/ltdc.rs @@ -0,0 +1,461 @@ +#![no_std] +#![no_main] +#![macro_use] +#![allow(static_mut_refs)] + +/// This example was derived from examples\stm32h735\src\bin\ltdc.rs +/// It demonstrates the LTDC lcd display peripheral and was tested on an STM32U5G9J-DK2 demo board (embassy-stm32 feature "stm32u5g9zj" and probe-rs chip "STM32U5G9ZJTxQ") +/// +use bouncy_box::BouncyBox; +use defmt::{info, unwrap}; +use embassy_executor::Spawner; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::ltdc::{self, Ltdc, LtdcConfiguration, LtdcLayer, LtdcLayerConfig, PolarityActive, PolarityEdge}; +use embassy_stm32::{bind_interrupts, peripherals}; +use embassy_time::{Duration, Timer}; +use embedded_graphics::draw_target::DrawTarget; +use embedded_graphics::geometry::{OriginDimensions, Point, Size}; +use embedded_graphics::image::Image; +use embedded_graphics::pixelcolor::raw::RawU24; +use embedded_graphics::pixelcolor::Rgb888; +use embedded_graphics::prelude::*; +use embedded_graphics::primitives::Rectangle; +use embedded_graphics::Pixel; +use heapless::{Entry, FnvIndexMap}; +use tinybmp::Bmp; +use {defmt_rtt as _, panic_probe as _}; + +const DISPLAY_WIDTH: usize = 800; +const DISPLAY_HEIGHT: usize = 480; +const MY_TASK_POOL_SIZE: usize = 2; + +// the following two display buffers consume 261120 bytes that just about fits into axis ram found on the mcu +pub static mut FB1: [TargetPixelType; DISPLAY_WIDTH * DISPLAY_HEIGHT] = [0; DISPLAY_WIDTH * DISPLAY_HEIGHT]; +pub static mut FB2: [TargetPixelType; DISPLAY_WIDTH * DISPLAY_HEIGHT] = [0; DISPLAY_WIDTH * DISPLAY_HEIGHT]; + +bind_interrupts!(struct Irqs { + LTDC => ltdc::InterruptHandler; +}); + +const NUM_COLORS: usize = 256; + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + let p = rcc_setup::stm32u5g9zj_init(); + + // enable ICACHE + embassy_stm32::pac::ICACHE.cr().write(|w| { + w.set_en(true); + }); + + // blink the led on another task + let led = Output::new(p.PD2, Level::High, Speed::Low); + unwrap!(spawner.spawn(led_task(led))); + + // numbers from STM32U5G9J-DK2.ioc + const RK050HR18H_HSYNC: u16 = 5; // Horizontal synchronization + const RK050HR18H_HBP: u16 = 8; // Horizontal back porch + const RK050HR18H_HFP: u16 = 8; // Horizontal front porch + const RK050HR18H_VSYNC: u16 = 5; // Vertical synchronization + const RK050HR18H_VBP: u16 = 8; // Vertical back porch + const RK050HR18H_VFP: u16 = 8; // Vertical front porch + + // NOTE: all polarities have to be reversed with respect to the STM32U5G9J-DK2 CubeMX parametrization + let ltdc_config = LtdcConfiguration { + active_width: DISPLAY_WIDTH as _, + active_height: DISPLAY_HEIGHT as _, + h_back_porch: RK050HR18H_HBP, + h_front_porch: RK050HR18H_HFP, + v_back_porch: RK050HR18H_VBP, + v_front_porch: RK050HR18H_VFP, + h_sync: RK050HR18H_HSYNC, + v_sync: RK050HR18H_VSYNC, + h_sync_polarity: PolarityActive::ActiveHigh, + v_sync_polarity: PolarityActive::ActiveHigh, + data_enable_polarity: PolarityActive::ActiveHigh, + pixel_clock_polarity: PolarityEdge::RisingEdge, + }; + + info!("init ltdc"); + let mut ltdc_de = Output::new(p.PD6, Level::Low, Speed::High); + let mut ltdc_disp_ctrl = Output::new(p.PE4, Level::Low, Speed::High); + let mut ltdc_bl_ctrl = Output::new(p.PE6, Level::Low, Speed::High); + let mut ltdc = Ltdc::new_with_pins( + p.LTDC, // PERIPHERAL + Irqs, // IRQS + p.PD3, // CLK + p.PE0, // HSYNC + p.PD13, // VSYNC + p.PB9, // B0 + p.PB2, // B1 + p.PD14, // B2 + p.PD15, // B3 + p.PD0, // B4 + p.PD1, // B5 + p.PE7, // B6 + p.PE8, // B7 + p.PC8, // G0 + p.PC9, // G1 + p.PE9, // G2 + p.PE10, // G3 + p.PE11, // G4 + p.PE12, // G5 + p.PE13, // G6 + p.PE14, // G7 + p.PC6, // R0 + p.PC7, // R1 + p.PE15, // R2 + p.PD8, // R3 + p.PD9, // R4 + p.PD10, // R5 + p.PD11, // R6 + p.PD12, // R7 + ); + ltdc.init(<dc_config); + ltdc_de.set_low(); + ltdc_bl_ctrl.set_high(); + ltdc_disp_ctrl.set_high(); + + // we only need to draw on one layer for this example (not to be confused with the double buffer) + info!("enable bottom layer"); + let layer_config = LtdcLayerConfig { + pixel_format: ltdc::PixelFormat::L8, // 1 byte per pixel + layer: LtdcLayer::Layer1, + window_x0: 0, + window_x1: DISPLAY_WIDTH as _, + window_y0: 0, + window_y1: DISPLAY_HEIGHT as _, + }; + + let ferris_bmp: Bmp = Bmp::from_slice(include_bytes!("./ferris.bmp")).unwrap(); + let color_map = build_color_lookup_map(&ferris_bmp); + let clut = build_clut(&color_map); + + // enable the bottom layer with a 256 color lookup table + ltdc.init_layer(&layer_config, Some(&clut)); + + // Safety: the DoubleBuffer controls access to the statically allocated frame buffers + // and it is the only thing that mutates their content + let mut double_buffer = DoubleBuffer::new( + unsafe { FB1.as_mut() }, + unsafe { FB2.as_mut() }, + layer_config, + color_map, + ); + + // this allows us to perform some simple animation for every frame + let mut bouncy_box = BouncyBox::new( + ferris_bmp.bounding_box(), + Rectangle::new(Point::zero(), Size::new(DISPLAY_WIDTH as u32, DISPLAY_HEIGHT as u32)), + 2, + ); + + loop { + // cpu intensive drawing to the buffer that is NOT currently being copied to the LCD screen + double_buffer.clear(); + let position = bouncy_box.next_point(); + let ferris = Image::new(&ferris_bmp, position); + unwrap!(ferris.draw(&mut double_buffer)); + + // perform async dma data transfer to the lcd screen + unwrap!(double_buffer.swap(&mut ltdc).await); + } +} + +/// builds the color look-up table from all unique colors found in the bitmap. This should be a 256 color indexed bitmap to work. +fn build_color_lookup_map(bmp: &Bmp) -> FnvIndexMap { + let mut color_map: FnvIndexMap = heapless::FnvIndexMap::new(); + let mut counter: u8 = 0; + + // add black to position 0 + color_map.insert(Rgb888::new(0, 0, 0).into_storage(), counter).unwrap(); + counter += 1; + + for Pixel(_point, color) in bmp.pixels() { + let raw = color.into_storage(); + if let Entry::Vacant(v) = color_map.entry(raw) { + v.insert(counter).expect("more than 256 colors detected"); + counter += 1; + } + } + color_map +} + +/// builds the color look-up table from the color map provided +fn build_clut(color_map: &FnvIndexMap) -> [ltdc::RgbColor; NUM_COLORS] { + let mut clut = [ltdc::RgbColor::default(); NUM_COLORS]; + for (color, index) in color_map.iter() { + let color = Rgb888::from(RawU24::new(*color)); + clut[*index as usize] = ltdc::RgbColor { + red: color.r(), + green: color.g(), + blue: color.b(), + }; + } + + clut +} + +#[embassy_executor::task(pool_size = MY_TASK_POOL_SIZE)] +async fn led_task(mut led: Output<'static>) { + let mut counter = 0; + loop { + info!("blink: {}", counter); + counter += 1; + + // on + led.set_low(); + Timer::after(Duration::from_millis(50)).await; + + // off + led.set_high(); + Timer::after(Duration::from_millis(450)).await; + } +} + +pub type TargetPixelType = u8; + +// A simple double buffer +pub struct DoubleBuffer { + buf0: &'static mut [TargetPixelType], + buf1: &'static mut [TargetPixelType], + is_buf0: bool, + layer_config: LtdcLayerConfig, + color_map: FnvIndexMap, +} + +impl DoubleBuffer { + pub fn new( + buf0: &'static mut [TargetPixelType], + buf1: &'static mut [TargetPixelType], + layer_config: LtdcLayerConfig, + color_map: FnvIndexMap, + ) -> Self { + Self { + buf0, + buf1, + is_buf0: true, + layer_config, + color_map, + } + } + + pub fn current(&mut self) -> (&FnvIndexMap, &mut [TargetPixelType]) { + if self.is_buf0 { + (&self.color_map, self.buf0) + } else { + (&self.color_map, self.buf1) + } + } + + pub async fn swap(&mut self, ltdc: &mut Ltdc<'_, T>) -> Result<(), ltdc::Error> { + let (_, buf) = self.current(); + let frame_buffer = buf.as_ptr(); + self.is_buf0 = !self.is_buf0; + ltdc.set_buffer(self.layer_config.layer, frame_buffer as *const _).await + } + + /// Clears the buffer + pub fn clear(&mut self) { + let (color_map, buf) = self.current(); + let black = Rgb888::new(0, 0, 0).into_storage(); + let color_index = color_map.get(&black).expect("no black found in the color map"); + + for a in buf.iter_mut() { + *a = *color_index; // solid black + } + } +} + +// Implement DrawTarget for +impl DrawTarget for DoubleBuffer { + type Color = Rgb888; + type Error = (); + + /// Draw a pixel + fn draw_iter(&mut self, pixels: I) -> Result<(), Self::Error> + where + I: IntoIterator>, + { + let size = self.size(); + let width = size.width as i32; + let height = size.height as i32; + let (color_map, buf) = self.current(); + + for pixel in pixels { + let Pixel(point, color) = pixel; + + if point.x >= 0 && point.y >= 0 && point.x < width && point.y < height { + let index = point.y * width + point.x; + let raw_color = color.into_storage(); + + match color_map.get(&raw_color) { + Some(x) => { + buf[index as usize] = *x; + } + None => panic!("color not found in color map: {}", raw_color), + }; + } else { + // Ignore invalid points + } + } + + Ok(()) + } +} + +impl OriginDimensions for DoubleBuffer { + /// Return the size of the display + fn size(&self) -> Size { + Size::new( + (self.layer_config.window_x1 - self.layer_config.window_x0) as _, + (self.layer_config.window_y1 - self.layer_config.window_y0) as _, + ) + } +} + +mod rcc_setup { + + use embassy_stm32::time::Hertz; + use embassy_stm32::{rcc, Config, Peripherals}; + + /// Sets up clocks for the stm32u5g9zj mcu + /// change this if you plan to use a different microcontroller + pub fn stm32u5g9zj_init() -> Peripherals { + // setup power and clocks for an STM32U5G9J-DK2 run from an external 16 Mhz external oscillator + let mut config = Config::default(); + config.rcc.hse = Some(rcc::Hse { + freq: Hertz(16_000_000), + mode: rcc::HseMode::Oscillator, + }); + config.rcc.pll1 = Some(rcc::Pll { + source: rcc::PllSource::HSE, + prediv: rcc::PllPreDiv::DIV1, + mul: rcc::PllMul::MUL10, + divp: None, + divq: None, + divr: Some(rcc::PllDiv::DIV1), + }); + config.rcc.sys = rcc::Sysclk::PLL1_R; // 160 Mhz + config.rcc.pll3 = Some(rcc::Pll { + source: rcc::PllSource::HSE, + prediv: rcc::PllPreDiv::DIV4, // PLL_M + mul: rcc::PllMul::MUL125, // PLL_N + divp: None, + divq: None, + divr: Some(rcc::PllDiv::DIV20), + }); + config.rcc.mux.ltdcsel = rcc::mux::Ltdcsel::PLL3_R; // 25 MHz + embassy_stm32::init(config) + } +} + +mod bouncy_box { + use embedded_graphics::geometry::Point; + use embedded_graphics::primitives::Rectangle; + + enum Direction { + DownLeft, + DownRight, + UpLeft, + UpRight, + } + + pub struct BouncyBox { + direction: Direction, + child_rect: Rectangle, + parent_rect: Rectangle, + current_point: Point, + move_by: usize, + } + + // This calculates the coordinates of a chile rectangle bounced around inside a parent bounded box + impl BouncyBox { + pub fn new(child_rect: Rectangle, parent_rect: Rectangle, move_by: usize) -> Self { + let center_box = parent_rect.center(); + let center_img = child_rect.center(); + let current_point = Point::new(center_box.x - center_img.x / 2, center_box.y - center_img.y / 2); + Self { + direction: Direction::DownRight, + child_rect, + parent_rect, + current_point, + move_by, + } + } + + pub fn next_point(&mut self) -> Point { + let direction = &self.direction; + let img_height = self.child_rect.size.height as i32; + let box_height = self.parent_rect.size.height as i32; + let img_width = self.child_rect.size.width as i32; + let box_width = self.parent_rect.size.width as i32; + let move_by = self.move_by as i32; + + match direction { + Direction::DownLeft => { + self.current_point.x -= move_by; + self.current_point.y += move_by; + + let x_out_of_bounds = self.current_point.x < 0; + let y_out_of_bounds = (self.current_point.y + img_height) > box_height; + + if x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::UpRight + } else if x_out_of_bounds && !y_out_of_bounds { + self.direction = Direction::DownRight + } else if !x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::UpLeft + } + } + Direction::DownRight => { + self.current_point.x += move_by; + self.current_point.y += move_by; + + let x_out_of_bounds = (self.current_point.x + img_width) > box_width; + let y_out_of_bounds = (self.current_point.y + img_height) > box_height; + + if x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::UpLeft + } else if x_out_of_bounds && !y_out_of_bounds { + self.direction = Direction::DownLeft + } else if !x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::UpRight + } + } + Direction::UpLeft => { + self.current_point.x -= move_by; + self.current_point.y -= move_by; + + let x_out_of_bounds = self.current_point.x < 0; + let y_out_of_bounds = self.current_point.y < 0; + + if x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::DownRight + } else if x_out_of_bounds && !y_out_of_bounds { + self.direction = Direction::UpRight + } else if !x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::DownLeft + } + } + Direction::UpRight => { + self.current_point.x += move_by; + self.current_point.y -= move_by; + + let x_out_of_bounds = (self.current_point.x + img_width) > box_width; + let y_out_of_bounds = self.current_point.y < 0; + + if x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::DownLeft + } else if x_out_of_bounds && !y_out_of_bounds { + self.direction = Direction::UpLeft + } else if !x_out_of_bounds && y_out_of_bounds { + self.direction = Direction::DownRight + } + } + } + + self.current_point + } + } +} diff --git a/examples/stm32u5/src/bin/rng.rs b/examples/stm32u5/src/bin/rng.rs new file mode 100644 index 000000000..3a5bce097 --- /dev/null +++ b/examples/stm32u5/src/bin/rng.rs @@ -0,0 +1,25 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_stm32::rng::Rng; +use embassy_stm32::{bind_interrupts, peripherals, rng}; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + RNG => rng::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_stm32::init(Default::default()); + + info!("Hello World!"); + + let mut rng = Rng::new(p.RNG, Irqs); + + let mut buf = [0u8; 16]; + unwrap!(rng.async_fill_bytes(&mut buf).await); + info!("random bytes: {:02x}", buf); +} diff --git a/examples/stm32u5/src/bin/tsc.rs b/examples/stm32u5/src/bin/tsc.rs new file mode 100644 index 000000000..eb15d275a --- /dev/null +++ b/examples/stm32u5/src/bin/tsc.rs @@ -0,0 +1,95 @@ +#![no_std] +#![no_main] + +use defmt::*; +use embassy_stm32::bind_interrupts; +use embassy_stm32::tsc::{self, *}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + TSC => InterruptHandler; +}); + +#[cortex_m_rt::exception] +unsafe fn HardFault(_: &cortex_m_rt::ExceptionFrame) -> ! { + cortex_m::peripheral::SCB::sys_reset(); +} + +#[embassy_executor::main] +async fn main(_spawner: embassy_executor::Spawner) { + let device_config = embassy_stm32::Config::default(); + let context = embassy_stm32::init(device_config); + + let config = tsc::Config { + ct_pulse_high_length: ChargeTransferPulseCycle::_2, + ct_pulse_low_length: ChargeTransferPulseCycle::_2, + spread_spectrum: false, + spread_spectrum_deviation: SSDeviation::new(2).unwrap(), + spread_spectrum_prescaler: false, + pulse_generator_prescaler: PGPrescalerDivider::_4, + max_count_value: MaxCount::_8191, + io_default_mode: false, + synchro_pin_polarity: false, + acquisition_mode: false, + max_count_interrupt: false, + channel_ios: TscIOPin::Group2Io2 | TscIOPin::Group7Io3, + shield_ios: TscIOPin::Group1Io3.into(), + sampling_ios: TscIOPin::Group1Io2 | TscIOPin::Group2Io1 | TscIOPin::Group7Io2, + }; + + let mut g1: PinGroup = PinGroup::new(); + g1.set_io2(context.PB13, PinType::Sample); + g1.set_io3(context.PB14, PinType::Shield); + + let mut g2: PinGroup = PinGroup::new(); + g2.set_io1(context.PB4, PinType::Sample); + g2.set_io2(context.PB5, PinType::Channel); + + let mut g7: PinGroup = PinGroup::new(); + g7.set_io2(context.PE3, PinType::Sample); + g7.set_io3(context.PE4, PinType::Channel); + + let mut touch_controller = tsc::Tsc::new_async( + context.TSC, + Some(g1), + Some(g2), + None, + None, + None, + None, + Some(g7), + None, + config, + Irqs, + ); + + touch_controller.discharge_io(true); + Timer::after_millis(1).await; + + touch_controller.start(); + + let mut group_two_val = 0; + let mut group_seven_val = 0; + info!("Starting touch_controller interface"); + loop { + touch_controller.pend_for_acquisition().await; + touch_controller.discharge_io(true); + Timer::after_millis(1).await; + + if touch_controller.group_get_status(Group::Two) == GroupStatus::Complete { + group_two_val = touch_controller.group_get_value(Group::Two); + } + + if touch_controller.group_get_status(Group::Seven) == GroupStatus::Complete { + group_seven_val = touch_controller.group_get_value(Group::Seven); + } + + info!( + "Group Two value: {}, Group Seven value: {},", + group_two_val, group_seven_val + ); + + touch_controller.start(); + } +} diff --git a/examples/stm32u5/src/bin/usb_serial.rs b/examples/stm32u5/src/bin/usb_serial.rs index dca34fd0e..4bb1a6079 100644 --- a/examples/stm32u5/src/bin/usb_serial.rs +++ b/examples/stm32u5/src/bin/usb_serial.rs @@ -4,17 +4,16 @@ use defmt::{panic, *}; use defmt_rtt as _; // global logger use embassy_executor::Spawner; -use embassy_stm32::rcc::*; -use embassy_stm32::usb_otg::{Driver, Instance}; -use embassy_stm32::{bind_interrupts, peripherals, usb_otg, Config}; +use embassy_futures::join::join; +use embassy_stm32::usb::{Driver, Instance}; +use embassy_stm32::{bind_interrupts, peripherals, usb, Config}; use embassy_usb::class::cdc_acm::{CdcAcmClass, State}; use embassy_usb::driver::EndpointError; use embassy_usb::Builder; -use futures::future::join; use panic_probe as _; bind_interrupts!(struct Irqs { - OTG_FS => usb_otg::InterruptHandler; + OTG_HS => usb::InterruptHandler; }); #[embassy_executor::main] @@ -22,23 +21,34 @@ async fn main(_spawner: Spawner) { info!("Hello World!"); let mut config = Config::default(); - config.rcc.mux = ClockSrc::PLL1_R(PllConfig { - source: PllSource::HSI, - m: Pllm::DIV2, - n: Plln::MUL10, - p: Plldiv::DIV1, - q: Plldiv::DIV1, - r: Plldiv::DIV1, - }); - config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true }); // needed for USB + { + use embassy_stm32::rcc::*; + config.rcc.hsi = true; + config.rcc.pll1 = Some(Pll { + source: PllSource::HSI, // 16 MHz + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL10, + divp: None, + divq: None, + divr: Some(PllDiv::DIV1), // 160 MHz + }); + config.rcc.sys = Sysclk::PLL1_R; + config.rcc.voltage_range = VoltageScale::RANGE1; + config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true }); // needed for USB + config.rcc.mux.iclksel = mux::Iclksel::HSI48; // USB uses ICLK + } let p = embassy_stm32::init(config); // Create the driver, from the HAL. let mut ep_out_buffer = [0u8; 256]; - let mut config = embassy_stm32::usb_otg::Config::default(); - config.vbus_detection = true; - let driver = Driver::new_fs(p.USB_OTG_FS, Irqs, p.PA12, p.PA11, &mut ep_out_buffer, config); + let mut config = embassy_stm32::usb::Config::default(); + // Do not enable vbus_detection. This is a safe default that works in all boards. + // However, if your USB device is self-powered (can stay powered on if USB is unplugged), you need + // to enable vbus_detection to comply with the USB spec. If you enable it, the board + // has to support it or USB won't work at all. See docs on `vbus_detection` for details. + config.vbus_detection = false; + let driver = Driver::new_hs(p.USB_OTG_HS, Irqs, p.PA12, p.PA11, &mut ep_out_buffer, config); // Create embassy-usb Config let mut config = embassy_usb::Config::new(0xc0de, 0xcafe); @@ -55,7 +65,6 @@ async fn main(_spawner: Spawner) { // Create embassy-usb DeviceBuilder using the driver and config. // It needs some buffers for building the descriptors. - let mut device_descriptor = [0; 256]; let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 64]; @@ -65,7 +74,6 @@ async fn main(_spawner: Spawner) { let mut builder = Builder::new( driver, config, - &mut device_descriptor, &mut config_descriptor, &mut bos_descriptor, &mut [], // no msos descriptors diff --git a/examples/stm32wb/.cargo/config.toml b/examples/stm32wb/.cargo/config.toml index 51c499ee7..8b6d6d754 100644 --- a/examples/stm32wb/.cargo/config.toml +++ b/examples/stm32wb/.cargo/config.toml @@ -1,6 +1,6 @@ [target.'cfg(all(target_arch = "arm", target_os = "none"))'] # replace STM32WB55CCUx with your chip as listed in `probe-rs chip list` -# runner = "probe-run --chip STM32WB55RGVx --speed 1000 --connect-under-reset" +# runner = "probe-rs run --chip STM32WB55RGVx --speed 1000 --connect-under-reset" runner = "teleprobe local run --chip STM32WB55RG --elf" [build] diff --git a/examples/stm32wb/Cargo.toml b/examples/stm32wb/Cargo.toml index 94a5141f5..26de81122 100644 --- a/examples/stm32wb/Cargo.toml +++ b/examples/stm32wb/Cargo.toml @@ -8,9 +8,9 @@ license = "MIT OR Apache-2.0" # Change stm32wb55rg to your chip name in both dependencies, if necessary. embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = [ "defmt", "stm32wb55rg", "time-driver-any", "memory-x", "exti"] } embassy-stm32-wpan = { version = "0.1.0", path = "../../embassy-stm32-wpan", features = ["defmt", "stm32wb55rg"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "udp", "proto-ipv6", "medium-ieee802154", ], optional=true } defmt = "0.3" @@ -20,7 +20,6 @@ cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-sing cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } static_cell = "2" diff --git a/examples/stm32wb/src/bin/eddystone_beacon.rs b/examples/stm32wb/src/bin/eddystone_beacon.rs index d3b3c15ca..3bd8b4a63 100644 --- a/examples/stm32wb/src/bin/eddystone_beacon.rs +++ b/examples/stm32wb/src/bin/eddystone_beacon.rs @@ -46,7 +46,6 @@ async fn main(_spawner: Spawner) { - Select that file, the memory address, "verify download", and then "Firmware Upgrade". - Select "Start Wireless Stack". - Disconnect from the device. - - In the examples folder for stm32wb, modify the memory.x file to match your target device. - Run this example. Note: extended stack versions are not supported at this time. Do not attempt to install a stack with "extended" in the name. diff --git a/examples/stm32wb/src/bin/gatt_server.rs b/examples/stm32wb/src/bin/gatt_server.rs index 3b50d6c31..1cc50e134 100644 --- a/examples/stm32wb/src/bin/gatt_server.rs +++ b/examples/stm32wb/src/bin/gatt_server.rs @@ -57,7 +57,6 @@ async fn main(_spawner: Spawner) { - Select that file, the memory address, "verify download", and then "Firmware Upgrade". - Select "Start Wireless Stack". - Disconnect from the device. - - In the examples folder for stm32wb, modify the memory.x file to match your target device. - Run this example. Note: extended stack versions are not supported at this time. Do not attempt to install a stack with "extended" in the name. diff --git a/examples/stm32wb/src/bin/mac_ffd.rs b/examples/stm32wb/src/bin/mac_ffd.rs index 5cd660543..d139aa61b 100644 --- a/examples/stm32wb/src/bin/mac_ffd.rs +++ b/examples/stm32wb/src/bin/mac_ffd.rs @@ -43,7 +43,6 @@ async fn main(spawner: Spawner) { - Select that file, the memory address, "verify download", and then "Firmware Upgrade". - Select "Start Wireless Stack". - Disconnect from the device. - - In the examples folder for stm32wb, modify the memory.x file to match your target device. - Run this example. Note: extended stack versions are not supported at this time. Do not attempt to install a stack with "extended" in the name. diff --git a/examples/stm32wb/src/bin/mac_ffd_net.rs b/examples/stm32wb/src/bin/mac_ffd_net.rs index 7a42bf577..6a97daf4d 100644 --- a/examples/stm32wb/src/bin/mac_ffd_net.rs +++ b/examples/stm32wb/src/bin/mac_ffd_net.rs @@ -49,7 +49,6 @@ async fn main(spawner: Spawner) { - Select that file, the memory address, "verify download", and then "Firmware Upgrade". - Select "Start Wireless Stack". - Disconnect from the device. - - In the examples folder for stm32wb, modify the memory.x file to match your target device. - Run this example. Note: extended stack versions are not supported at this time. Do not attempt to install a stack with "extended" in the name. diff --git a/examples/stm32wb/src/bin/mac_rfd.rs b/examples/stm32wb/src/bin/mac_rfd.rs index 7949211fb..9062bdcd2 100644 --- a/examples/stm32wb/src/bin/mac_rfd.rs +++ b/examples/stm32wb/src/bin/mac_rfd.rs @@ -45,7 +45,6 @@ async fn main(spawner: Spawner) { - Select that file, the memory address, "verify download", and then "Firmware Upgrade". - Select "Start Wireless Stack". - Disconnect from the device. - - In the examples folder for stm32wb, modify the memory.x file to match your target device. - Run this example. Note: extended stack versions are not supported at this time. Do not attempt to install a stack with "extended" in the name. diff --git a/examples/stm32wb/src/bin/tl_mbox.rs b/examples/stm32wb/src/bin/tl_mbox.rs index cb92d462d..4e7f2304d 100644 --- a/examples/stm32wb/src/bin/tl_mbox.rs +++ b/examples/stm32wb/src/bin/tl_mbox.rs @@ -35,7 +35,6 @@ async fn main(_spawner: Spawner) { - Select that file, the memory address, "verify download", and then "Firmware Upgrade". - Select "Start Wireless Stack". - Disconnect from the device. - - In the examples folder for stm32wb, modify the memory.x file to match your target device. - Run this example. Note: extended stack versions are not supported at this time. Do not attempt to install a stack with "extended" in the name. diff --git a/examples/stm32wb/src/bin/tl_mbox_ble.rs b/examples/stm32wb/src/bin/tl_mbox_ble.rs index 2599e1151..72a4c18e6 100644 --- a/examples/stm32wb/src/bin/tl_mbox_ble.rs +++ b/examples/stm32wb/src/bin/tl_mbox_ble.rs @@ -34,7 +34,6 @@ async fn main(_spawner: Spawner) { - Select that file, the memory address, "verify download", and then "Firmware Upgrade". - Select "Start Wireless Stack". - Disconnect from the device. - - In the examples folder for stm32wb, modify the memory.x file to match your target device. - Run this example. Note: extended stack versions are not supported at this time. Do not attempt to install a stack with "extended" in the name. diff --git a/examples/stm32wb/src/bin/tl_mbox_mac.rs b/examples/stm32wb/src/bin/tl_mbox_mac.rs index 5d868412a..9224e626d 100644 --- a/examples/stm32wb/src/bin/tl_mbox_mac.rs +++ b/examples/stm32wb/src/bin/tl_mbox_mac.rs @@ -40,7 +40,6 @@ async fn main(spawner: Spawner) { - Select that file, the memory address, "verify download", and then "Firmware Upgrade". - Select "Start Wireless Stack". - Disconnect from the device. - - In the examples folder for stm32wb, modify the memory.x file to match your target device. - Run this example. Note: extended stack versions are not supported at this time. Do not attempt to install a stack with "extended" in the name. diff --git a/examples/stm32wba/Cargo.toml b/examples/stm32wba/Cargo.toml index 47279a012..807f809e0 100644 --- a/examples/stm32wba/Cargo.toml +++ b/examples/stm32wba/Cargo.toml @@ -6,9 +6,9 @@ license = "MIT OR Apache-2.0" [dependencies] embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = [ "defmt", "stm32wba52cg", "time-driver-any", "memory-x", "exti"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "udp", "proto-ipv6", "medium-ieee802154", ], optional=true } defmt = "0.3" @@ -18,7 +18,6 @@ cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-sing cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } static_cell = "2" diff --git a/examples/stm32wl/Cargo.toml b/examples/stm32wl/Cargo.toml index 4cb55930b..3b4223977 100644 --- a/examples/stm32wl/Cargo.toml +++ b/examples/stm32wl/Cargo.toml @@ -7,10 +7,10 @@ license = "MIT OR Apache-2.0" [dependencies] # Change stm32wl55jc-cm4 to your chip name, if necessary. embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32wl55jc-cm4", "time-driver-any", "memory-x", "unstable-pac", "exti", "chrono"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-4096", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } -embassy-embedded-hal = { version = "0.1.0", path = "../../embassy-embedded-hal" } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-4096", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-embedded-hal = { version = "0.2.0", path = "../../embassy-embedded-hal" } defmt = "0.3" defmt-rtt = "0.4" @@ -20,7 +20,6 @@ cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" embedded-storage = "0.3.1" panic-probe = { version = "0.3", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } heapless = { version = "0.8", default-features = false } chrono = { version = "^0.4", default-features = false } diff --git a/examples/stm32wl/memory.x b/examples/stm32wl/memory.x new file mode 100644 index 000000000..4590867a8 --- /dev/null +++ b/examples/stm32wl/memory.x @@ -0,0 +1,15 @@ +MEMORY +{ + /* NOTE 1 K = 1 KiBi = 1024 bytes */ + FLASH : ORIGIN = 0x08000000, LENGTH = 256K + SHARED_RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 128 + RAM (rwx) : ORIGIN = 0x20000080, LENGTH = 64K - 128 +} + +SECTIONS +{ + .shared_data : + { + *(.shared_data) + } > SHARED_RAM +} diff --git a/examples/stm32wl/src/bin/blinky.rs b/examples/stm32wl/src/bin/blinky.rs index 347bd093f..ce7d0ec58 100644 --- a/examples/stm32wl/src/bin/blinky.rs +++ b/examples/stm32wl/src/bin/blinky.rs @@ -1,15 +1,21 @@ #![no_std] #![no_main] +use core::mem::MaybeUninit; + use defmt::*; use embassy_executor::Spawner; use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::SharedData; use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; +#[link_section = ".shared_data"] +static SHARED_DATA: MaybeUninit = MaybeUninit::uninit(); + #[embassy_executor::main] async fn main(_spawner: Spawner) { - let p = embassy_stm32::init(Default::default()); + let p = embassy_stm32::init_primary(Default::default(), &SHARED_DATA); info!("Hello World!"); let mut led = Output::new(p.PB15, Level::High, Speed::Low); diff --git a/examples/stm32wl/src/bin/button.rs b/examples/stm32wl/src/bin/button.rs index eccd211e2..8b5204479 100644 --- a/examples/stm32wl/src/bin/button.rs +++ b/examples/stm32wl/src/bin/button.rs @@ -1,16 +1,22 @@ #![no_std] #![no_main] +use core::mem::MaybeUninit; + use cortex_m_rt::entry; use defmt::*; use embassy_stm32::gpio::{Input, Level, Output, Pull, Speed}; +use embassy_stm32::SharedData; use {defmt_rtt as _, panic_probe as _}; +#[link_section = ".shared_data"] +static SHARED_DATA: MaybeUninit = MaybeUninit::uninit(); + #[entry] fn main() -> ! { info!("Hello World!"); - let p = embassy_stm32::init(Default::default()); + let p = embassy_stm32::init_primary(Default::default(), &SHARED_DATA); let button = Input::new(p.PA0, Pull::Up); let mut led1 = Output::new(p.PB15, Level::High, Speed::Low); diff --git a/examples/stm32wl/src/bin/button_exti.rs b/examples/stm32wl/src/bin/button_exti.rs index 27d5330bd..8dd1a6a5e 100644 --- a/examples/stm32wl/src/bin/button_exti.rs +++ b/examples/stm32wl/src/bin/button_exti.rs @@ -1,15 +1,21 @@ #![no_std] #![no_main] +use core::mem::MaybeUninit; + use defmt::*; use embassy_executor::Spawner; use embassy_stm32::exti::ExtiInput; use embassy_stm32::gpio::Pull; +use embassy_stm32::SharedData; use {defmt_rtt as _, panic_probe as _}; +#[link_section = ".shared_data"] +static SHARED_DATA: MaybeUninit = MaybeUninit::uninit(); + #[embassy_executor::main] async fn main(_spawner: Spawner) { - let p = embassy_stm32::init(Default::default()); + let p = embassy_stm32::init_primary(Default::default(), &SHARED_DATA); info!("Hello World!"); let mut button = ExtiInput::new(p.PA0, p.EXTI0, Pull::Up); diff --git a/examples/stm32wl/src/bin/flash.rs b/examples/stm32wl/src/bin/flash.rs index 0b7417c01..147f5d293 100644 --- a/examples/stm32wl/src/bin/flash.rs +++ b/examples/stm32wl/src/bin/flash.rs @@ -1,14 +1,20 @@ #![no_std] #![no_main] +use core::mem::MaybeUninit; + use defmt::{info, unwrap}; use embassy_executor::Spawner; use embassy_stm32::flash::Flash; +use embassy_stm32::SharedData; use {defmt_rtt as _, panic_probe as _}; +#[link_section = ".shared_data"] +static SHARED_DATA: MaybeUninit = MaybeUninit::uninit(); + #[embassy_executor::main] async fn main(_spawner: Spawner) { - let p = embassy_stm32::init(Default::default()); + let p = embassy_stm32::init_primary(Default::default(), &SHARED_DATA); info!("Hello Flash!"); const ADDR: u32 = 0x36000; diff --git a/examples/stm32wl/src/bin/random.rs b/examples/stm32wl/src/bin/random.rs index 3610392be..df2ed0054 100644 --- a/examples/stm32wl/src/bin/random.rs +++ b/examples/stm32wl/src/bin/random.rs @@ -1,17 +1,22 @@ #![no_std] #![no_main] +use core::mem::MaybeUninit; + use defmt::*; use embassy_executor::Spawner; use embassy_stm32::rng::{self, Rng}; use embassy_stm32::time::Hertz; -use embassy_stm32::{bind_interrupts, peripherals}; +use embassy_stm32::{bind_interrupts, peripherals, SharedData}; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs{ RNG => rng::InterruptHandler; }); +#[link_section = ".shared_data"] +static SHARED_DATA: MaybeUninit = MaybeUninit::uninit(); + #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut config = embassy_stm32::Config::default(); @@ -22,7 +27,7 @@ async fn main(_spawner: Spawner) { mode: HseMode::Bypass, prescaler: HsePrescaler::DIV1, }); - config.rcc.mux = ClockSrc::PLL1_R; + config.rcc.sys = Sysclk::PLL1_R; config.rcc.pll = Some(Pll { source: PllSource::HSE, prediv: PllPreDiv::DIV2, @@ -32,7 +37,7 @@ async fn main(_spawner: Spawner) { divr: Some(PllRDiv::DIV2), // sysclk 48Mhz clock (32 / 2 * 6 / 2) }); } - let p = embassy_stm32::init(config); + let p = embassy_stm32::init_primary(config, &SHARED_DATA); info!("Hello World!"); diff --git a/examples/stm32wl/src/bin/rtc.rs b/examples/stm32wl/src/bin/rtc.rs index 4738d5770..69a9ddc4c 100644 --- a/examples/stm32wl/src/bin/rtc.rs +++ b/examples/stm32wl/src/bin/rtc.rs @@ -1,15 +1,20 @@ #![no_std] #![no_main] +use core::mem::MaybeUninit; + use chrono::{NaiveDate, NaiveDateTime}; use defmt::*; use embassy_executor::Spawner; use embassy_stm32::rtc::{Rtc, RtcConfig}; use embassy_stm32::time::Hertz; -use embassy_stm32::Config; +use embassy_stm32::{Config, SharedData}; use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; +#[link_section = ".shared_data"] +static SHARED_DATA: MaybeUninit = MaybeUninit::uninit(); + #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut config = Config::default(); @@ -21,7 +26,7 @@ async fn main(_spawner: Spawner) { mode: HseMode::Bypass, prescaler: HsePrescaler::DIV1, }); - config.rcc.mux = ClockSrc::PLL1_R; + config.rcc.sys = Sysclk::PLL1_R; config.rcc.pll = Some(Pll { source: PllSource::HSE, prediv: PllPreDiv::DIV2, @@ -31,7 +36,7 @@ async fn main(_spawner: Spawner) { divr: Some(PllRDiv::DIV2), // sysclk 48Mhz clock (32 / 2 * 6 / 2) }); } - let p = embassy_stm32::init(config); + let p = embassy_stm32::init_primary(config, &SHARED_DATA); info!("Hello World!"); let now = NaiveDate::from_ymd_opt(2020, 5, 15) @@ -40,7 +45,7 @@ async fn main(_spawner: Spawner) { .unwrap(); let mut rtc = Rtc::new(p.RTC, RtcConfig::default()); - info!("Got RTC! {:?}", now.timestamp()); + info!("Got RTC! {:?}", now.and_utc().timestamp()); rtc.set_datetime(now.into()).expect("datetime not set"); @@ -48,5 +53,5 @@ async fn main(_spawner: Spawner) { Timer::after_millis(20000).await; let then: NaiveDateTime = rtc.now().unwrap().into(); - info!("Got RTC! {:?}", then.timestamp()); + info!("Got RTC! {:?}", then.and_utc().timestamp()); } diff --git a/examples/stm32wl/src/bin/uart_async.rs b/examples/stm32wl/src/bin/uart_async.rs index 8e545834c..ece9b9201 100644 --- a/examples/stm32wl/src/bin/uart_async.rs +++ b/examples/stm32wl/src/bin/uart_async.rs @@ -1,10 +1,12 @@ #![no_std] #![no_main] +use core::mem::MaybeUninit; + use defmt::*; use embassy_executor::Spawner; use embassy_stm32::usart::{Config, InterruptHandler, Uart}; -use embassy_stm32::{bind_interrupts, peripherals}; +use embassy_stm32::{bind_interrupts, peripherals, SharedData}; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs{ @@ -12,6 +14,9 @@ bind_interrupts!(struct Irqs{ LPUART1 => InterruptHandler; }); +#[link_section = ".shared_data"] +static SHARED_DATA: MaybeUninit = MaybeUninit::uninit(); + /* Pass Incoming data from LPUART1 to USART1 Example is written for the LoRa-E5 mini v1.0, @@ -20,8 +25,8 @@ but can be surely changed for your needs. #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut config = embassy_stm32::Config::default(); - config.rcc.mux = embassy_stm32::rcc::ClockSrc::HSE; - let p = embassy_stm32::init(config); + config.rcc.sys = embassy_stm32::rcc::Sysclk::HSE; + let p = embassy_stm32::init_primary(config, &SHARED_DATA); defmt::info!("Starting system"); diff --git a/examples/wasm/Cargo.toml b/examples/wasm/Cargo.toml index 3d2300b59..ea66d9b99 100644 --- a/examples/wasm/Cargo.toml +++ b/examples/wasm/Cargo.toml @@ -8,15 +8,14 @@ license = "MIT OR Apache-2.0" crate-type = ["cdylib"] [dependencies] -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["log"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-wasm", "executor-thread", "log", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["log", "wasm", ] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["log"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-wasm", "executor-thread", "log", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["log", "wasm", ] } wasm-logger = "0.2.0" wasm-bindgen = "0.2" web-sys = { version = "0.3", features = ["Document", "Element", "HtmlElement", "Node", "Window" ] } log = "0.4.11" -critical-section = { version = "1.1", features = ["std"] } [profile.release] debug = 2 diff --git a/release/bump-dependency.sh b/release/bump-dependency.sh new file mode 100755 index 000000000..07511d229 --- /dev/null +++ b/release/bump-dependency.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# A helper script to bump version dependencies of a crate to a particular version. It does +# not bump the version of the crate itself, only its entries in dependency lists. +# +# Usage (from the embassy repo folder): ./release/bump-dependency.sh embassy-time 0.4.0 +# +# As a sanity check, after running this script, grep for old versions. +# +CRATE=$1 +TARGET_VER=$2 +find . -name "Cargo.toml" | xargs sed -rie "s/($CRATE = \{.*version = \")[0-9]+.[0-9]+.?[0-9]*(\".*)/\1$TARGET_VER\2/g" diff --git a/rust-toolchain-nightly.toml b/rust-toolchain-nightly.toml index b8a7db353..d0c92e655 100644 --- a/rust-toolchain-nightly.toml +++ b/rust-toolchain-nightly.toml @@ -1,5 +1,5 @@ [toolchain] -channel = "nightly-2023-12-20" +channel = "nightly-2024-11-04" components = [ "rust-src", "rustfmt", "llvm-tools", "miri" ] targets = [ "thumbv7em-none-eabi", diff --git a/rust-toolchain.toml b/rust-toolchain.toml index a6fe52ee2..69a964040 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,5 +1,5 @@ [toolchain] -channel = "1.75" +channel = "1.82" components = [ "rust-src", "rustfmt", "llvm-tools" ] targets = [ "thumbv7em-none-eabi", diff --git a/tests/nrf52840/.cargo/config.toml b/tests/nrf/.cargo/config.toml similarity index 80% rename from tests/nrf52840/.cargo/config.toml rename to tests/nrf/.cargo/config.toml index 9d6b0313a..8f9bccbc0 100644 --- a/tests/nrf52840/.cargo/config.toml +++ b/tests/nrf/.cargo/config.toml @@ -3,7 +3,9 @@ runner = "teleprobe client run" [build] +#target = "thumbv6m-none-eabi" target = "thumbv7em-none-eabi" +#target = "thumbv8m.main-none-eabihf" [env] DEFMT_LOG = "trace,embassy_hal_internal=debug,embassy_net_esp_hosted=debug,smoltcp=info" diff --git a/tests/nrf/Cargo.toml b/tests/nrf/Cargo.toml new file mode 100644 index 000000000..c1d386b93 --- /dev/null +++ b/tests/nrf/Cargo.toml @@ -0,0 +1,114 @@ +[package] +edition = "2021" +name = "embassy-nrf-examples" +version = "0.1.0" +license = "MIT OR Apache-2.0" + +[dependencies] +teleprobe-meta = "1" + +embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt", ] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "task-arena-size-16384", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } +embassy-nrf = { version = "0.2.0", path = "../../embassy-nrf", features = ["defmt", "time-driver-rtc1", "gpiote", "unstable-pac"] } +embedded-io-async = { version = "0.6.1", features = ["defmt-03"] } +embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", ] } +embassy-net-esp-hosted = { version = "0.1.0", path = "../../embassy-net-esp-hosted", features = ["defmt"] } +embassy-net-enc28j60 = { version = "0.1.0", path = "../../embassy-net-enc28j60", features = ["defmt"] } +embedded-hal-async = { version = "1.0" } +embedded-hal-bus = { version = "0.1", features = ["async"] } +static_cell = "2" +perf-client = { path = "../perf-client" } + +defmt = "0.3" +defmt-rtt = "0.4" + +cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] } +cortex-m-rt = "0.7.0" +panic-probe = { version = "0.3", features = ["print-defmt"] } +portable-atomic = { version = "1.6.0" } + +[features] +nrf51422 = ["embassy-nrf/nrf51", "portable-atomic/unsafe-assume-single-core"] +nrf52832 = ["embassy-nrf/nrf52832", "easydma"] +nrf52833 = ["embassy-nrf/nrf52833", "easydma", "two-uarts"] +nrf52840 = ["embassy-nrf/nrf52840", "easydma", "two-uarts"] +nrf5340 = ["embassy-nrf/nrf5340-app-s", "easydma", "two-uarts"] +nrf9160 = ["embassy-nrf/nrf9160-s", "easydma", "two-uarts"] + +easydma = [] +two-uarts = [] + +[profile.release] +codegen-units = 1 +debug = 2 +debug-assertions = false +incremental = false +lto = "fat" +opt-level = 's' +overflow-checks = false + +# BEGIN TESTS +# Generated by gen_test.py. DO NOT EDIT. +[[bin]] +name = "buffered_uart" +path = "src/bin/buffered_uart.rs" +required-features = [ "easydma",] + +[[bin]] +name = "buffered_uart_full" +path = "src/bin/buffered_uart_full.rs" +required-features = [ "easydma",] + +[[bin]] +name = "buffered_uart_halves" +path = "src/bin/buffered_uart_halves.rs" +required-features = [ "two-uarts",] + +[[bin]] +name = "buffered_uart_spam" +path = "src/bin/buffered_uart_spam.rs" +required-features = [ "two-uarts",] + +[[bin]] +name = "ethernet_enc28j60_perf" +path = "src/bin/ethernet_enc28j60_perf.rs" +required-features = [ "nrf52840",] + +[[bin]] +name = "gpio" +path = "src/bin/gpio.rs" +required-features = [] + +[[bin]] +name = "gpiote" +path = "src/bin/gpiote.rs" +required-features = [] + +[[bin]] +name = "spim" +path = "src/bin/spim.rs" +required-features = [ "easydma",] + +[[bin]] +name = "timer" +path = "src/bin/timer.rs" +required-features = [] + +[[bin]] +name = "uart_halves" +path = "src/bin/uart_halves.rs" +required-features = [ "two-uarts",] + +[[bin]] +name = "uart_split" +path = "src/bin/uart_split.rs" +required-features = [ "easydma",] + +[[bin]] +name = "wifi_esp_hosted_perf" +path = "src/bin/wifi_esp_hosted_perf.rs" +required-features = [ "nrf52840",] + +# END TESTS diff --git a/tests/nrf/build.rs b/tests/nrf/build.rs new file mode 100644 index 000000000..3c15cf10f --- /dev/null +++ b/tests/nrf/build.rs @@ -0,0 +1,37 @@ +use std::error::Error; +use std::path::PathBuf; +use std::{env, fs}; + +fn main() -> Result<(), Box> { + let out = PathBuf::from(env::var("OUT_DIR").unwrap()); + + // copy the right memory.x + #[cfg(feature = "nrf51422")] + let memory_x = include_bytes!("memory-nrf51422.x"); + #[cfg(feature = "nrf52832")] + let memory_x = include_bytes!("memory-nrf52832.x"); + #[cfg(feature = "nrf52833")] + let memory_x = include_bytes!("memory-nrf52833.x"); + #[cfg(feature = "nrf52840")] + let memory_x = include_bytes!("memory-nrf52840.x"); + #[cfg(feature = "nrf5340")] + let memory_x = include_bytes!("memory-nrf5340.x"); + #[cfg(feature = "nrf9160")] + let memory_x = include_bytes!("memory-nrf9160.x"); + fs::write(out.join("memory.x"), memory_x).unwrap(); + + // copy main linker script. + fs::write(out.join("link_ram.x"), include_bytes!("../link_ram_cortex_m.x")).unwrap(); + println!("cargo:rustc-link-search={}", out.display()); + println!("cargo:rerun-if-changed=link_ram.x"); + + println!("cargo:rustc-link-arg-bins=--nmagic"); + #[cfg(feature = "nrf51422")] + println!("cargo:rustc-link-arg-bins=-Tlink.x"); + #[cfg(not(feature = "nrf51422"))] + println!("cargo:rustc-link-arg-bins=-Tlink_ram.x"); + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); + println!("cargo:rustc-link-arg-bins=-Tteleprobe.x"); + + Ok(()) +} diff --git a/tests/nrf/gen_test.py b/tests/nrf/gen_test.py new file mode 100644 index 000000000..daf714376 --- /dev/null +++ b/tests/nrf/gen_test.py @@ -0,0 +1,44 @@ +import os +import toml +from glob import glob + +abspath = os.path.abspath(__file__) +dname = os.path.dirname(abspath) +os.chdir(dname) + +# ======= load test list +tests = {} +for f in sorted(glob('./src/bin/*.rs')): + name = os.path.splitext(os.path.basename(f))[0] + features = [] + with open(f, 'r') as f: + for line in f: + if line.startswith('// required-features:'): + features = [feature.strip() for feature in line.split(':', 2)[1].strip().split(',')] + + tests[name] = features + +# ========= Update Cargo.toml + +things = { + 'bin': [ + { + 'name': f'{name}', + 'path': f'src/bin/{name}.rs', + 'required-features': features, + } + for name, features in tests.items() + ] +} + +SEPARATOR_START = '# BEGIN TESTS\n' +SEPARATOR_END = '# END TESTS\n' +HELP = '# Generated by gen_test.py. DO NOT EDIT.\n' +with open('Cargo.toml', 'r') as f: + data = f.read() +before, data = data.split(SEPARATOR_START, maxsplit=1) +_, after = data.split(SEPARATOR_END, maxsplit=1) +data = before + SEPARATOR_START + HELP + \ + toml.dumps(things) + SEPARATOR_END + after +with open('Cargo.toml', 'w') as f: + f.write(data) diff --git a/tests/nrf/memory-nrf51422.x b/tests/nrf/memory-nrf51422.x new file mode 100644 index 000000000..c140005ce --- /dev/null +++ b/tests/nrf/memory-nrf51422.x @@ -0,0 +1,5 @@ +MEMORY +{ + FLASH : ORIGIN = 0x00000000, LENGTH = 256K + RAM : ORIGIN = 0x20000000, LENGTH = 32K +} diff --git a/tests/nrf/memory-nrf52832.x b/tests/nrf/memory-nrf52832.x new file mode 100644 index 000000000..c140005ce --- /dev/null +++ b/tests/nrf/memory-nrf52832.x @@ -0,0 +1,5 @@ +MEMORY +{ + FLASH : ORIGIN = 0x00000000, LENGTH = 256K + RAM : ORIGIN = 0x20000000, LENGTH = 32K +} diff --git a/tests/nrf/memory-nrf52833.x b/tests/nrf/memory-nrf52833.x new file mode 100644 index 000000000..a4baa2dc4 --- /dev/null +++ b/tests/nrf/memory-nrf52833.x @@ -0,0 +1,5 @@ +MEMORY +{ + FLASH : ORIGIN = 0x00000000, LENGTH = 512K + RAM : ORIGIN = 0x20000000, LENGTH = 64K +} diff --git a/tests/nrf52840/memory.x b/tests/nrf/memory-nrf52840.x similarity index 100% rename from tests/nrf52840/memory.x rename to tests/nrf/memory-nrf52840.x diff --git a/tests/nrf/memory-nrf5340.x b/tests/nrf/memory-nrf5340.x new file mode 100644 index 000000000..58900a7bd --- /dev/null +++ b/tests/nrf/memory-nrf5340.x @@ -0,0 +1,5 @@ +MEMORY +{ + FLASH : ORIGIN = 0x00000000, LENGTH = 1024K + RAM : ORIGIN = 0x20000000, LENGTH = 256K +} diff --git a/tests/nrf/memory-nrf9160.x b/tests/nrf/memory-nrf9160.x new file mode 100644 index 000000000..58900a7bd --- /dev/null +++ b/tests/nrf/memory-nrf9160.x @@ -0,0 +1,5 @@ +MEMORY +{ + FLASH : ORIGIN = 0x00000000, LENGTH = 1024K + RAM : ORIGIN = 0x20000000, LENGTH = 256K +} diff --git a/tests/nrf/src/bin/buffered_uart.rs b/tests/nrf/src/bin/buffered_uart.rs new file mode 100644 index 000000000..04f32832f --- /dev/null +++ b/tests/nrf/src/bin/buffered_uart.rs @@ -0,0 +1,82 @@ +// required-features: easydma +#![no_std] +#![no_main] + +#[path = "../common.rs"] +mod common; + +use defmt::{panic, *}; +use embassy_executor::Spawner; +use embassy_futures::join::join; +use embassy_nrf::buffered_uarte::{self, BufferedUarte}; +use embassy_nrf::{peripherals, uarte}; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut p = embassy_nrf::init(Default::default()); + let mut config = uarte::Config::default(); + config.parity = uarte::Parity::EXCLUDED; + config.baudrate = uarte::Baudrate::BAUD1M; + + let mut tx_buffer = [0u8; 1024]; + let mut rx_buffer = [0u8; 1024]; + + // test teardown + recreate of the buffereduarte works fine. + for _ in 0..2 { + let u = BufferedUarte::new( + &mut peri!(p, UART0), + &mut p.TIMER0, + &mut p.PPI_CH0, + &mut p.PPI_CH1, + &mut p.PPI_GROUP0, + irqs!(UART0_BUFFERED), + &mut peri!(p, PIN_A), + &mut peri!(p, PIN_B), + config.clone(), + &mut rx_buffer, + &mut tx_buffer, + ); + + info!("uarte initialized!"); + + let (mut rx, mut tx) = u.split(); + + const COUNT: usize = 40_000; + + let tx_fut = async { + let mut tx_buf = [0; 215]; + let mut i = 0; + while i < COUNT { + let n = tx_buf.len().min(COUNT - i); + let tx_buf = &mut tx_buf[..n]; + for (j, b) in tx_buf.iter_mut().enumerate() { + *b = (i + j) as u8; + } + let n = unwrap!(tx.write(tx_buf).await); + i += n; + } + }; + let rx_fut = async { + let mut i = 0; + while i < COUNT { + let buf = unwrap!(rx.fill_buf().await); + + for &b in buf { + if b != i as u8 { + panic!("mismatch {} vs {}, index {}", b, i as u8, i); + } + i = i + 1; + } + + let n = buf.len(); + rx.consume(n); + } + }; + + join(rx_fut, tx_fut).await; + } + + info!("Test OK"); + cortex_m::asm::bkpt(); +} diff --git a/tests/nrf52840/src/bin/buffered_uart_full.rs b/tests/nrf/src/bin/buffered_uart_full.rs similarity index 68% rename from tests/nrf52840/src/bin/buffered_uart_full.rs rename to tests/nrf/src/bin/buffered_uart_full.rs index e59c75ba9..09353bbe8 100644 --- a/tests/nrf52840/src/bin/buffered_uart_full.rs +++ b/tests/nrf/src/bin/buffered_uart_full.rs @@ -1,18 +1,17 @@ +// required-features: easydma #![no_std] #![no_main] -teleprobe_meta::target!(b"nrf52840-dk"); + +#[path = "../common.rs"] +mod common; use defmt::{assert_eq, *}; use embassy_executor::Spawner; use embassy_nrf::buffered_uarte::{self, BufferedUarte}; -use embassy_nrf::{bind_interrupts, peripherals, uarte}; +use embassy_nrf::{peripherals, uarte}; use embedded_io_async::{Read, Write}; use {defmt_rtt as _, panic_probe as _}; -bind_interrupts!(struct Irqs { - UARTE0_UART0 => buffered_uarte::InterruptHandler; -}); - #[embassy_executor::main] async fn main(_spawner: Spawner) { let p = embassy_nrf::init(Default::default()); @@ -20,18 +19,18 @@ async fn main(_spawner: Spawner) { config.parity = uarte::Parity::EXCLUDED; config.baudrate = uarte::Baudrate::BAUD1M; - let mut tx_buffer = [0u8; 1024]; - let mut rx_buffer = [0u8; 1024]; + let mut tx_buffer = [0u8; 500]; + let mut rx_buffer = [0u8; 500]; - let mut u = BufferedUarte::new( - p.UARTE0, + let u = BufferedUarte::new( + peri!(p, UART0), p.TIMER0, p.PPI_CH0, p.PPI_CH1, p.PPI_GROUP0, - Irqs, - p.P1_03, - p.P1_02, + irqs!(UART0_BUFFERED), + peri!(p, PIN_A), + peri!(p, PIN_B), config.clone(), &mut rx_buffer, &mut tx_buffer, @@ -41,22 +40,22 @@ async fn main(_spawner: Spawner) { let (mut rx, mut tx) = u.split(); - let mut buf = [0; 1024]; + let mut buf = [0; 500]; for (j, b) in buf.iter_mut().enumerate() { *b = j as u8; } - // Write 1024b. This causes the rx buffer to get exactly full. + // Write 500b. This causes the rx buffer to get exactly full. unwrap!(tx.write_all(&buf).await); unwrap!(tx.flush().await); - // Read those 1024b. + // Read those 500b. unwrap!(rx.read_exact(&mut buf).await); for (j, b) in buf.iter().enumerate() { assert_eq!(*b, j as u8); } - // The buffer should now be unclogged. Write 1024b again. + // The buffer should now be unclogged. Write 500b again. unwrap!(tx.write_all(&buf).await); unwrap!(tx.flush().await); diff --git a/tests/nrf/src/bin/buffered_uart_halves.rs b/tests/nrf/src/bin/buffered_uart_halves.rs new file mode 100644 index 000000000..bdf5ad726 --- /dev/null +++ b/tests/nrf/src/bin/buffered_uart_halves.rs @@ -0,0 +1,86 @@ +// required-features: two-uarts +#![no_std] +#![no_main] + +#[path = "../common.rs"] +mod common; + +use defmt::{assert_eq, *}; +use embassy_executor::Spawner; +use embassy_futures::join::join; +use embassy_nrf::buffered_uarte::{self, BufferedUarteRx, BufferedUarteTx}; +use embassy_nrf::{peripherals, uarte}; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut p = embassy_nrf::init(Default::default()); + let mut config = uarte::Config::default(); + config.parity = uarte::Parity::EXCLUDED; + config.baudrate = uarte::Baudrate::BAUD1M; + + let mut tx_buffer = [0u8; 1024]; + let mut rx_buffer = [0u8; 1024]; + + // test teardown + recreate of the buffereduarte works fine. + for _ in 0..2 { + const COUNT: usize = 40_000; + + let mut tx = BufferedUarteTx::new( + &mut peri!(p, UART1), + irqs!(UART1_BUFFERED), + &mut peri!(p, PIN_A), + config.clone(), + &mut tx_buffer, + ); + + let mut rx = BufferedUarteRx::new( + &mut peri!(p, UART0), + &mut p.TIMER0, + &mut p.PPI_CH0, + &mut p.PPI_CH1, + &mut p.PPI_GROUP0, + irqs!(UART0_BUFFERED), + &mut peri!(p, PIN_B), + config.clone(), + &mut rx_buffer, + ); + + let tx_fut = async { + info!("tx initialized!"); + + let mut tx_buf = [0; 215]; + let mut i = 0; + while i < COUNT { + let n = tx_buf.len().min(COUNT - i); + let tx_buf = &mut tx_buf[..n]; + for (j, b) in tx_buf.iter_mut().enumerate() { + *b = (i + j) as u8; + } + let n = unwrap!(tx.write(tx_buf).await); + i += n; + } + }; + let rx_fut = async { + info!("rx initialized!"); + + let mut i = 0; + while i < COUNT { + let buf = unwrap!(rx.fill_buf().await); + + for &b in buf { + assert_eq!(b, i as u8); + i = i + 1; + } + + let n = buf.len(); + rx.consume(n); + } + }; + + join(rx_fut, tx_fut).await; + } + + info!("Test OK"); + cortex_m::asm::bkpt(); +} diff --git a/tests/nrf52840/src/bin/buffered_uart_spam.rs b/tests/nrf/src/bin/buffered_uart_spam.rs similarity index 61% rename from tests/nrf52840/src/bin/buffered_uart_spam.rs rename to tests/nrf/src/bin/buffered_uart_spam.rs index 400c0df99..cf9ca50d2 100644 --- a/tests/nrf52840/src/bin/buffered_uart_spam.rs +++ b/tests/nrf/src/bin/buffered_uart_spam.rs @@ -1,25 +1,23 @@ +// required-features: two-uarts #![no_std] #![no_main] -teleprobe_meta::target!(b"nrf52840-dk"); + +#[path = "../common.rs"] +mod common; use core::mem; use core::ptr::NonNull; use defmt::{assert_eq, *}; use embassy_executor::Spawner; -use embassy_nrf::buffered_uarte::{self, BufferedUarte}; +use embassy_nrf::buffered_uarte::{self, BufferedUarteRx}; use embassy_nrf::gpio::{Level, Output, OutputDrive}; use embassy_nrf::ppi::{Event, Ppi, Task}; -use embassy_nrf::uarte::Uarte; -use embassy_nrf::{bind_interrupts, pac, peripherals, uarte}; +use embassy_nrf::uarte::UarteTx; +use embassy_nrf::{pac, peripherals, uarte}; use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; -bind_interrupts!(struct Irqs { - UARTE0_UART0 => buffered_uarte::InterruptHandler; - UARTE1 => uarte::InterruptHandler; -}); - #[embassy_executor::main] async fn main(_spawner: Spawner) { let mut p = embassy_nrf::init(Default::default()); @@ -27,23 +25,20 @@ async fn main(_spawner: Spawner) { config.parity = uarte::Parity::EXCLUDED; config.baudrate = uarte::Baudrate::BAUD1M; - let mut tx_buffer = [0u8; 1024]; let mut rx_buffer = [0u8; 1024]; - mem::forget(Output::new(&mut p.P1_02, Level::High, OutputDrive::Standard)); + mem::forget(Output::new(&mut peri!(p, PIN_A), Level::High, OutputDrive::Standard)); - let mut u = BufferedUarte::new( - p.UARTE0, + let mut u = BufferedUarteRx::new( + peri!(p, UART0), p.TIMER0, p.PPI_CH0, p.PPI_CH1, p.PPI_GROUP0, - Irqs, - p.P1_03, - p.P1_04, + irqs!(UART0_BUFFERED), + peri!(p, PIN_B), config.clone(), &mut rx_buffer, - &mut tx_buffer, ); info!("uarte initialized!"); @@ -54,16 +49,16 @@ async fn main(_spawner: Spawner) { // Tx spam in a loop. const NSPAM: usize = 17; static mut TX_BUF: [u8; NSPAM] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; - let _spam = Uarte::new(p.UARTE1, Irqs, p.P1_01, p.P1_02, config.clone()); - let spam_peri: pac::UARTE1 = unsafe { mem::transmute(()) }; - let event = unsafe { Event::new_unchecked(NonNull::new_unchecked(&spam_peri.events_endtx as *const _ as _)) }; - let task = unsafe { Task::new_unchecked(NonNull::new_unchecked(&spam_peri.tasks_starttx as *const _ as _)) }; + let _spam = UarteTx::new(peri!(p, UART1), irqs!(UART1), peri!(p, PIN_A), config.clone()); + let spam_peri = pac::UARTE1; + let event = unsafe { Event::new_unchecked(NonNull::new_unchecked(spam_peri.events_endtx().as_ptr())) }; + let task = unsafe { Task::new_unchecked(NonNull::new_unchecked(spam_peri.tasks_starttx().as_ptr())) }; let mut spam_ppi = Ppi::new_one_to_one(p.PPI_CH2, event, task); spam_ppi.enable(); - let p = unsafe { TX_BUF.as_mut_ptr() }; - spam_peri.txd.ptr.write(|w| unsafe { w.ptr().bits(p as u32) }); - spam_peri.txd.maxcnt.write(|w| unsafe { w.maxcnt().bits(NSPAM as _) }); - spam_peri.tasks_starttx.write(|w| unsafe { w.bits(1) }); + let p = (&raw mut TX_BUF) as *mut u8; + spam_peri.txd().ptr().write_value(p as u32); + spam_peri.txd().maxcnt().write(|w| w.set_maxcnt(NSPAM as _)); + spam_peri.tasks_starttx().write_value(1); let mut i = 0; let mut total = 0; diff --git a/tests/nrf52840/src/bin/ethernet_enc28j60_perf.rs b/tests/nrf/src/bin/ethernet_enc28j60_perf.rs similarity index 86% rename from tests/nrf52840/src/bin/ethernet_enc28j60_perf.rs rename to tests/nrf/src/bin/ethernet_enc28j60_perf.rs index 33c2f4235..ed58627f1 100644 --- a/tests/nrf52840/src/bin/ethernet_enc28j60_perf.rs +++ b/tests/nrf/src/bin/ethernet_enc28j60_perf.rs @@ -1,3 +1,4 @@ +// required-features: nrf52840 #![no_std] #![no_main] teleprobe_meta::target!(b"ak-gwe-r7"); @@ -5,7 +6,7 @@ teleprobe_meta::timeout!(120); use defmt::{info, unwrap}; use embassy_executor::Spawner; -use embassy_net::{Stack, StackResources}; +use embassy_net::StackResources; use embassy_net_enc28j60::Enc28j60; use embassy_nrf::gpio::{Level, Output, OutputDrive}; use embassy_nrf::rng::Rng; @@ -24,8 +25,8 @@ bind_interrupts!(struct Irqs { type MyDriver = Enc28j60, Output<'static>, Delay>, Output<'static>>; #[embassy_executor::task] -async fn net_task(stack: &'static Stack) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, MyDriver>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -64,16 +65,10 @@ async fn main(spawner: Spawner) { let seed = u64::from_le_bytes(seed); // Init network stack - static STACK: StaticCell> = StaticCell::new(); static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<2>::new()), - seed, - )); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); perf_client::run( stack, diff --git a/tests/nrf51422/src/bin/gpio.rs b/tests/nrf/src/bin/gpio.rs similarity index 67% rename from tests/nrf51422/src/bin/gpio.rs rename to tests/nrf/src/bin/gpio.rs index 6d5a87d0a..4995d244c 100644 --- a/tests/nrf51422/src/bin/gpio.rs +++ b/tests/nrf/src/bin/gpio.rs @@ -1,25 +1,28 @@ #![no_std] #![no_main] -teleprobe_meta::target!(b"nrf51-dk"); + +#[path = "../common.rs"] +mod common; use defmt::{assert, info}; use embassy_executor::Spawner; use embassy_nrf::gpio::{Input, Level, Output, OutputDrive, Pull}; use embassy_time::Timer; -use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] async fn main(_spawner: Spawner) { let p = embassy_nrf::init(Default::default()); - let input = Input::new(p.P0_13, Pull::Up); - let mut output = Output::new(p.P0_14, Level::Low, OutputDrive::Standard); + let input = Input::new(peri!(p, PIN_A), Pull::Up); + let mut output = Output::new(peri!(p, PIN_B), Level::Low, OutputDrive::Standard); output.set_low(); + assert!(output.is_set_low()); Timer::after_millis(10).await; assert!(input.is_low()); output.set_high(); + assert!(output.is_set_high()); Timer::after_millis(10).await; assert!(input.is_high()); diff --git a/tests/nrf/src/bin/gpiote.rs b/tests/nrf/src/bin/gpiote.rs new file mode 100644 index 000000000..0700016d1 --- /dev/null +++ b/tests/nrf/src/bin/gpiote.rs @@ -0,0 +1,50 @@ +#![no_std] +#![no_main] + +#[path = "../common.rs"] +mod common; + +use defmt::{assert, info}; +use embassy_executor::Spawner; +use embassy_futures::join::join; +use embassy_nrf::gpio::{Input, Level, Output, OutputDrive, Pull}; +use embassy_time::{Duration, Instant, Timer}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_nrf::init(Default::default()); + + let mut input = Input::new(peri!(p, PIN_A), Pull::Up); + let mut output = Output::new(peri!(p, PIN_B), Level::Low, OutputDrive::Standard); + + let fut1 = async { + Timer::after_millis(100).await; + output.set_high(); + }; + let fut2 = async { + let start = Instant::now(); + input.wait_for_high().await; + let dur = Instant::now() - start; + info!("took {} ms", dur.as_millis()); + assert!((Duration::from_millis(90)..Duration::from_millis(110)).contains(&dur)); + }; + + join(fut1, fut2).await; + + let fut1 = async { + Timer::after_millis(100).await; + output.set_low(); + }; + let fut2 = async { + let start = Instant::now(); + input.wait_for_low().await; + let dur = Instant::now() - start; + info!("took {} ms", dur.as_millis()); + assert!((Duration::from_millis(90)..Duration::from_millis(110)).contains(&dur)); + }; + + join(fut1, fut2).await; + + info!("Test OK"); + cortex_m::asm::bkpt(); +} diff --git a/tests/nrf/src/bin/spim.rs b/tests/nrf/src/bin/spim.rs new file mode 100644 index 000000000..c2ec90b88 --- /dev/null +++ b/tests/nrf/src/bin/spim.rs @@ -0,0 +1,42 @@ +// required-features: easydma +#![no_std] +#![no_main] + +#[path = "../common.rs"] +mod common; + +use defmt::{assert_eq, *}; +use embassy_executor::Spawner; +use embassy_nrf::spim::Spim; +use embassy_nrf::{peripherals, spim}; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut p = embassy_nrf::init(Default::default()); + let mut config = spim::Config::default(); + config.frequency = spim::Frequency::M1; + let mut spim = Spim::new( + &mut peri!(p, SPIM0), + irqs!(SPIM0), + &mut peri!(p, PIN_X), + &mut peri!(p, PIN_A), // MISO + &mut peri!(p, PIN_B), // MOSI + config.clone(), + ); + let data = [ + 0x42, 0x43, 0x44, 0x45, 0x66, 0x12, 0x23, 0x34, 0x45, 0x19, 0x91, 0xaa, 0xff, 0xa5, 0x5a, 0x77, + ]; + let mut buf = [0u8; 16]; + + buf.fill(0); + spim.blocking_transfer(&mut buf, &data).unwrap(); + assert_eq!(data, buf); + + buf.fill(0); + spim.transfer(&mut buf, &data).await.unwrap(); + assert_eq!(data, buf); + + info!("Test OK"); + cortex_m::asm::bkpt(); +} diff --git a/tests/nrf51422/src/bin/timer.rs b/tests/nrf/src/bin/timer.rs similarity index 93% rename from tests/nrf51422/src/bin/timer.rs rename to tests/nrf/src/bin/timer.rs index cf9ea41a8..1ae9dd647 100644 --- a/tests/nrf51422/src/bin/timer.rs +++ b/tests/nrf/src/bin/timer.rs @@ -1,6 +1,8 @@ #![no_std] #![no_main] -teleprobe_meta::target!(b"nrf51-dk"); + +#[path = "../common.rs"] +mod common; use defmt::{assert, info}; use embassy_executor::Spawner; diff --git a/tests/nrf/src/bin/uart_halves.rs b/tests/nrf/src/bin/uart_halves.rs new file mode 100644 index 000000000..f48ea43a1 --- /dev/null +++ b/tests/nrf/src/bin/uart_halves.rs @@ -0,0 +1,41 @@ +// required-features: two-uarts +#![no_std] +#![no_main] + +#[path = "../common.rs"] +mod common; + +use defmt::{assert_eq, *}; +use embassy_executor::Spawner; +use embassy_futures::join::join; +use embassy_nrf::uarte::{UarteRx, UarteTx}; +use embassy_nrf::{peripherals, uarte}; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut p = embassy_nrf::init(Default::default()); + let mut config = uarte::Config::default(); + config.parity = uarte::Parity::EXCLUDED; + config.baudrate = uarte::Baudrate::BAUD1M; + + let mut tx = UarteTx::new(&mut peri!(p, UART0), irqs!(UART0), &mut peri!(p, PIN_A), config.clone()); + let mut rx = UarteRx::new(&mut peri!(p, UART1), irqs!(UART1), &mut peri!(p, PIN_B), config.clone()); + + let data = [ + 0x42, 0x43, 0x44, 0x45, 0x66, 0x12, 0x23, 0x34, 0x45, 0x19, 0x91, 0xaa, 0xff, 0xa5, 0x5a, 0x77, + ]; + + let tx_fut = async { + tx.write(&data).await.unwrap(); + }; + let rx_fut = async { + let mut buf = [0u8; 16]; + rx.read(&mut buf).await.unwrap(); + assert_eq!(data, buf); + }; + join(rx_fut, tx_fut).await; + + info!("Test OK"); + cortex_m::asm::bkpt(); +} diff --git a/tests/nrf/src/bin/uart_split.rs b/tests/nrf/src/bin/uart_split.rs new file mode 100644 index 000000000..70d8b2e33 --- /dev/null +++ b/tests/nrf/src/bin/uart_split.rs @@ -0,0 +1,49 @@ +// required-features: easydma +#![no_std] +#![no_main] + +#[path = "../common.rs"] +mod common; + +use defmt::{assert_eq, *}; +use embassy_executor::Spawner; +use embassy_futures::join::join; +use embassy_nrf::uarte::Uarte; +use embassy_nrf::{peripherals, uarte}; +use embassy_time::Timer; +use {defmt_rtt as _, panic_probe as _}; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut p = embassy_nrf::init(Default::default()); + let mut config = uarte::Config::default(); + config.parity = uarte::Parity::EXCLUDED; + config.baudrate = uarte::Baudrate::BAUD9600; + + let uarte = Uarte::new( + &mut peri!(p, UART0), + irqs!(UART0), + &mut peri!(p, PIN_A), + &mut peri!(p, PIN_B), + config.clone(), + ); + let (mut tx, mut rx) = uarte.split(); + + let data = [ + 0x42, 0x43, 0x44, 0x45, 0x66, 0x12, 0x23, 0x34, 0x45, 0x19, 0x91, 0xaa, 0xff, 0xa5, 0x5a, 0x77, + ]; + + let tx_fut = async { + Timer::after_millis(10).await; + tx.write(&data).await.unwrap(); + }; + let rx_fut = async { + let mut buf = [0u8; 16]; + rx.read(&mut buf).await.unwrap(); + assert_eq!(data, buf); + }; + join(rx_fut, tx_fut).await; + + info!("Test OK"); + cortex_m::asm::bkpt(); +} diff --git a/tests/nrf52840/src/bin/wifi_esp_hosted_perf.rs b/tests/nrf/src/bin/wifi_esp_hosted_perf.rs similarity index 89% rename from tests/nrf52840/src/bin/wifi_esp_hosted_perf.rs rename to tests/nrf/src/bin/wifi_esp_hosted_perf.rs index b83edddc4..34fb8103b 100644 --- a/tests/nrf52840/src/bin/wifi_esp_hosted_perf.rs +++ b/tests/nrf/src/bin/wifi_esp_hosted_perf.rs @@ -1,3 +1,4 @@ +// required-features: nrf52840 #![no_std] #![no_main] teleprobe_meta::target!(b"nrf52840-dk"); @@ -5,7 +6,7 @@ teleprobe_meta::timeout!(120); use defmt::{info, unwrap}; use embassy_executor::Spawner; -use embassy_net::{Config, Stack, StackResources}; +use embassy_net::{Config, StackResources}; use embassy_nrf::gpio::{Input, Level, Output, OutputDrive, Pull}; use embassy_nrf::rng::Rng; use embassy_nrf::spim::{self, Spim}; @@ -39,8 +40,8 @@ async fn wifi_task( type MyDriver = hosted::NetDriver<'static>; #[embassy_executor::task] -async fn net_task(stack: &'static Stack) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, MyDriver>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -85,16 +86,15 @@ async fn main(spawner: Spawner) { let seed = u64::from_le_bytes(seed); // Init network stack - static STACK: StaticCell> = StaticCell::new(); static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( + let (stack, runner) = embassy_net::new( device, Config::dhcpv4(Default::default()), - RESOURCES.init(StackResources::<2>::new()), + RESOURCES.init(StackResources::new()), seed, - )); + ); - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); perf_client::run( stack, diff --git a/tests/nrf/src/common.rs b/tests/nrf/src/common.rs new file mode 100644 index 000000000..c588dabf5 --- /dev/null +++ b/tests/nrf/src/common.rs @@ -0,0 +1,117 @@ +#![macro_use] + +use {defmt_rtt as _, panic_probe as _}; + +#[cfg(feature = "nrf52832")] +teleprobe_meta::target!(b"nrf52832-dk"); +#[cfg(feature = "nrf52840")] +teleprobe_meta::target!(b"nrf52840-dk"); +#[cfg(feature = "nrf52833")] +teleprobe_meta::target!(b"nrf52833-dk"); +#[cfg(feature = "nrf5340")] +teleprobe_meta::target!(b"nrf5340-dk"); +#[cfg(feature = "nrf9160")] +teleprobe_meta::target!(b"nrf9160-dk"); +#[cfg(feature = "nrf51422")] +teleprobe_meta::target!(b"nrf51-dk"); + +macro_rules! define_peris { + ($($name:ident = $peri:ident,)* $(@irq $irq_name:ident = $irq_code:tt,)*) => { + #[allow(unused_macros)] + macro_rules! peri { + $( + ($p:expr, $name) => { + $p.$peri + }; + )* + } + #[allow(unused_macros)] + macro_rules! irqs { + $( + ($irq_name) => {{ + embassy_nrf::bind_interrupts!(struct Irqs $irq_code); + Irqs + }}; + )* + ( @ dummy ) => {}; + } + + #[allow(unused)] + #[allow(non_camel_case_types)] + pub mod peris { + $( + pub type $name = embassy_nrf::peripherals::$peri; + )* + } + }; +} + +#[cfg(feature = "nrf51422")] +define_peris!(PIN_A = P0_13, PIN_B = P0_14,); + +#[cfg(feature = "nrf52832")] +define_peris!( + PIN_A = P0_11, PIN_B = P0_12, + PIN_X = P0_13, + UART0 = UARTE0, + SPIM0 = TWISPI0, + @irq UART0 = {UARTE0_UART0 => uarte::InterruptHandler;}, + @irq UART0_BUFFERED = {UARTE0_UART0 => buffered_uarte::InterruptHandler;}, + @irq SPIM0 = {SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0 => spim::InterruptHandler;}, +); + +#[cfg(feature = "nrf52833")] +define_peris!( + PIN_A = P1_01, PIN_B = P1_02, + PIN_X = P1_03, + UART0 = UARTE0, + UART1 = UARTE1, + SPIM0 = TWISPI0, + @irq UART0 = {UARTE0_UART0 => uarte::InterruptHandler;}, + @irq UART1 = {UARTE1 => uarte::InterruptHandler;}, + @irq UART0_BUFFERED = {UARTE0_UART0 => buffered_uarte::InterruptHandler;}, + @irq UART1_BUFFERED = {UARTE1 => buffered_uarte::InterruptHandler;}, + @irq SPIM0 = {SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0 => spim::InterruptHandler;}, +); + +#[cfg(feature = "nrf52840")] +define_peris!( + PIN_A = P1_02, PIN_B = P1_03, + PIN_X = P1_04, + UART0 = UARTE0, + UART1 = UARTE1, + SPIM0 = TWISPI0, + @irq UART0 = {UARTE0_UART0 => uarte::InterruptHandler;}, + @irq UART1 = {UARTE1 => uarte::InterruptHandler;}, + @irq UART0_BUFFERED = {UARTE0_UART0 => buffered_uarte::InterruptHandler;}, + @irq UART1_BUFFERED = {UARTE1 => buffered_uarte::InterruptHandler;}, + @irq SPIM0 = {SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0 => spim::InterruptHandler;}, +); + +#[cfg(feature = "nrf5340")] +define_peris!( + PIN_A = P1_08, PIN_B = P1_09, + PIN_X = P1_10, + UART0 = SERIAL0, + UART1 = SERIAL1, + SPIM0 = SERIAL0, + @irq UART0 = {SERIAL0 => uarte::InterruptHandler;}, + @irq UART1 = {SERIAL1 => uarte::InterruptHandler;}, + @irq UART0_BUFFERED = {SERIAL0 => buffered_uarte::InterruptHandler;}, + @irq UART1_BUFFERED = {SERIAL1 => buffered_uarte::InterruptHandler;}, + @irq SPIM0 = {SERIAL0 => spim::InterruptHandler;}, +); + +#[cfg(feature = "nrf9160")] +define_peris!( + PIN_A = P0_00, PIN_B = P0_01, + PIN_X = P0_02, + UART0 = SERIAL0, + UART1 = SERIAL1, + SPIM0 = SERIAL0, + @irq UART0 = {UARTE0_SPIM0_SPIS0_TWIM0_TWIS0 => uarte::InterruptHandler;}, + @irq UART1 = {UARTE1_SPIM1_SPIS1_TWIM1_TWIS1 => uarte::InterruptHandler;}, + @irq UART0_BUFFERED = {UARTE0_SPIM0_SPIS0_TWIM0_TWIS0 => buffered_uarte::InterruptHandler;}, + @irq UART1_BUFFERED = {UARTE1_SPIM1_SPIS1_TWIM1_TWIS1 => buffered_uarte::InterruptHandler;}, + @irq SPIM0 = {UARTE0_SPIM0_SPIS0_TWIM0_TWIS0 => spim::InterruptHandler;}, +); diff --git a/tests/nrf51422/.cargo/config.toml b/tests/nrf51422/.cargo/config.toml deleted file mode 100644 index 634805633..000000000 --- a/tests/nrf51422/.cargo/config.toml +++ /dev/null @@ -1,9 +0,0 @@ -[target.'cfg(all(target_arch = "arm", target_os = "none"))'] -#runner = "teleprobe local run --chip nRF51422_xxAA --elf" -runner = "teleprobe client run" - -[build] -target = "thumbv6m-none-eabi" - -[env] -DEFMT_LOG = "trace,embassy_hal_internal=debug" diff --git a/tests/nrf51422/Cargo.toml b/tests/nrf51422/Cargo.toml deleted file mode 100644 index 2cab20ac0..000000000 --- a/tests/nrf51422/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -edition = "2021" -name = "embassy-nrf51-tests" -version = "0.1.0" -license = "MIT OR Apache-2.0" - -[dependencies] -teleprobe-meta = "1" - -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt", ] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "task-arena-size-128", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } -embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nrf51", "time-driver-rtc1", "unstable-pac", "time"] } -embedded-io-async = { version = "0.6.1", features = ["defmt-03"] } -embedded-hal-async = { version = "1.0" } - -defmt = "0.3" -defmt-rtt = "0.4" - -cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] } -cortex-m-rt = "0.7.0" -panic-probe = { version = "0.3", features = ["print-defmt"] } diff --git a/tests/nrf51422/build.rs b/tests/nrf51422/build.rs deleted file mode 100644 index 13ebbe4ee..000000000 --- a/tests/nrf51422/build.rs +++ /dev/null @@ -1,17 +0,0 @@ -use std::error::Error; -use std::path::PathBuf; -use std::{env, fs}; - -fn main() -> Result<(), Box> { - let out = PathBuf::from(env::var("OUT_DIR").unwrap()); - fs::write(out.join("memory.x"), include_bytes!("memory.x")).unwrap(); - println!("cargo:rustc-link-search={}", out.display()); - println!("cargo:rerun-if-changed=memory.x"); - - println!("cargo:rustc-link-arg-bins=--nmagic"); - println!("cargo:rustc-link-arg-bins=-Tlink.x"); - println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); - println!("cargo:rustc-link-arg-bins=-Tteleprobe.x"); - - Ok(()) -} diff --git a/tests/nrf51422/memory.x b/tests/nrf51422/memory.x deleted file mode 100644 index a5881e66f..000000000 --- a/tests/nrf51422/memory.x +++ /dev/null @@ -1,5 +0,0 @@ -MEMORY -{ - FLASH : ORIGIN = 0x00000000, LENGTH = 128K - RAM : ORIGIN = 0x20000000, LENGTH = 16K -} diff --git a/tests/nrf52840/Cargo.toml b/tests/nrf52840/Cargo.toml deleted file mode 100644 index 84ca99f1f..000000000 --- a/tests/nrf52840/Cargo.toml +++ /dev/null @@ -1,29 +0,0 @@ -[package] -edition = "2021" -name = "embassy-nrf-examples" -version = "0.1.0" -license = "MIT OR Apache-2.0" - -[dependencies] -teleprobe-meta = "1" - -embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt", ] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "task-arena-size-16384", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } -embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac"] } -embedded-io-async = { version = "0.6.1", features = ["defmt-03"] } -embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", ] } -embassy-net-esp-hosted = { version = "0.1.0", path = "../../embassy-net-esp-hosted", features = ["defmt"] } -embassy-net-enc28j60 = { version = "0.1.0", path = "../../embassy-net-enc28j60", features = ["defmt"] } -embedded-hal-async = { version = "1.0" } -embedded-hal-bus = { version = "0.1", features = ["async"] } -static_cell = "2" -perf-client = { path = "../perf-client" } - -defmt = "0.3" -defmt-rtt = "0.4" - -cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] } -cortex-m-rt = "0.7.0" -panic-probe = { version = "0.3", features = ["print-defmt"] } diff --git a/tests/nrf52840/build.rs b/tests/nrf52840/build.rs deleted file mode 100644 index 71c82a70f..000000000 --- a/tests/nrf52840/build.rs +++ /dev/null @@ -1,17 +0,0 @@ -use std::error::Error; -use std::path::PathBuf; -use std::{env, fs}; - -fn main() -> Result<(), Box> { - let out = PathBuf::from(env::var("OUT_DIR").unwrap()); - fs::write(out.join("link_ram.x"), include_bytes!("../link_ram_cortex_m.x")).unwrap(); - println!("cargo:rustc-link-search={}", out.display()); - println!("cargo:rerun-if-changed=link_ram.x"); - - println!("cargo:rustc-link-arg-bins=--nmagic"); - println!("cargo:rustc-link-arg-bins=-Tlink_ram.x"); - println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); - println!("cargo:rustc-link-arg-bins=-Tteleprobe.x"); - - Ok(()) -} diff --git a/tests/nrf52840/src/bin/buffered_uart.rs b/tests/nrf52840/src/bin/buffered_uart.rs deleted file mode 100644 index 354d787b4..000000000 --- a/tests/nrf52840/src/bin/buffered_uart.rs +++ /dev/null @@ -1,78 +0,0 @@ -#![no_std] -#![no_main] -teleprobe_meta::target!(b"nrf52840-dk"); - -use defmt::{assert_eq, *}; -use embassy_executor::Spawner; -use embassy_futures::join::join; -use embassy_nrf::buffered_uarte::{self, BufferedUarte}; -use embassy_nrf::{bind_interrupts, peripherals, uarte}; -use {defmt_rtt as _, panic_probe as _}; - -bind_interrupts!(struct Irqs { - UARTE0_UART0 => buffered_uarte::InterruptHandler; -}); - -#[embassy_executor::main] -async fn main(_spawner: Spawner) { - let p = embassy_nrf::init(Default::default()); - let mut config = uarte::Config::default(); - config.parity = uarte::Parity::EXCLUDED; - config.baudrate = uarte::Baudrate::BAUD1M; - - let mut tx_buffer = [0u8; 1024]; - let mut rx_buffer = [0u8; 1024]; - - let mut u = BufferedUarte::new( - p.UARTE0, - p.TIMER0, - p.PPI_CH0, - p.PPI_CH1, - p.PPI_GROUP0, - Irqs, - p.P1_03, - p.P1_02, - config.clone(), - &mut rx_buffer, - &mut tx_buffer, - ); - - info!("uarte initialized!"); - - let (mut rx, mut tx) = u.split(); - - const COUNT: usize = 40_000; - - let tx_fut = async { - let mut tx_buf = [0; 215]; - let mut i = 0; - while i < COUNT { - let n = tx_buf.len().min(COUNT - i); - let tx_buf = &mut tx_buf[..n]; - for (j, b) in tx_buf.iter_mut().enumerate() { - *b = (i + j) as u8; - } - let n = unwrap!(tx.write(tx_buf).await); - i += n; - } - }; - let rx_fut = async { - let mut i = 0; - while i < COUNT { - let buf = unwrap!(rx.fill_buf().await); - - for &b in buf { - assert_eq!(b, i as u8); - i = i + 1; - } - - let n = buf.len(); - rx.consume(n); - } - }; - - join(rx_fut, tx_fut).await; - - info!("Test OK"); - cortex_m::asm::bkpt(); -} diff --git a/tests/perf-client/Cargo.toml b/tests/perf-client/Cargo.toml index 4390a6da1..eb2a33a30 100644 --- a/tests/perf-client/Cargo.toml +++ b/tests/perf-client/Cargo.toml @@ -3,10 +3,8 @@ name = "perf-client" version = "0.1.0" edition = "2021" -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - [dependencies] embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", ] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", ] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } defmt = "0.3.0" diff --git a/tests/perf-client/src/lib.rs b/tests/perf-client/src/lib.rs index 54762379a..4bd9e5674 100644 --- a/tests/perf-client/src/lib.rs +++ b/tests/perf-client/src/lib.rs @@ -2,7 +2,6 @@ use defmt::{assert, *}; use embassy_futures::join::join; -use embassy_net::driver::Driver; use embassy_net::tcp::TcpSocket; use embassy_net::{Ipv4Address, Stack}; use embassy_time::{with_timeout, Duration, Timer}; @@ -13,7 +12,7 @@ pub struct Expected { pub updown_kbps: usize, } -pub async fn run(stack: &Stack, expected: Expected) { +pub async fn run(stack: Stack<'_>, expected: Expected) { info!("Waiting for DHCP up..."); while stack.config_v4().is_none() { Timer::after_millis(100).await; @@ -38,7 +37,7 @@ const DOWNLOAD_PORT: u16 = 4321; const UPLOAD_PORT: u16 = 4322; const UPLOAD_DOWNLOAD_PORT: u16 = 4323; -async fn test_download(stack: &Stack) -> usize { +async fn test_download(stack: Stack<'_>) -> usize { info!("Testing download..."); let mut rx_buffer = [0; RX_BUFFER_SIZE]; @@ -78,7 +77,7 @@ async fn test_download(stack: &Stack) -> usize { kbps } -async fn test_upload(stack: &Stack) -> usize { +async fn test_upload(stack: Stack<'_>) -> usize { info!("Testing upload..."); let mut rx_buffer = [0; RX_BUFFER_SIZE]; @@ -118,7 +117,7 @@ async fn test_upload(stack: &Stack) -> usize { kbps } -async fn test_upload_download(stack: &Stack) -> usize { +async fn test_upload_download(stack: Stack<'_>) -> usize { info!("Testing upload+download..."); let mut rx_buffer = [0; RX_BUFFER_SIZE]; diff --git a/tests/riscv32/Cargo.toml b/tests/riscv32/Cargo.toml index 38fb2deec..35dd283eb 100644 --- a/tests/riscv32/Cargo.toml +++ b/tests/riscv32/Cargo.toml @@ -6,13 +6,13 @@ license = "MIT OR Apache-2.0" [dependencies] critical-section = { version = "1.1.1", features = ["restore-state-bool"] } -embassy-sync = { version = "0.5.0", path = "../../embassy-sync" } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-riscv32", "executor-thread"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time" } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync" } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-riscv32", "executor-thread"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time" } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } -riscv-rt = "0.11" -riscv = { version = "0.10", features = ["critical-section-single-hart"] } +riscv-rt = "0.12.2" +riscv = { version = "0.11.1", features = ["critical-section-single-hart"] } [profile.dev] diff --git a/tests/riscv32/link.x b/tests/riscv32/link.x new file mode 100644 index 000000000..4076b0c68 --- /dev/null +++ b/tests/riscv32/link.x @@ -0,0 +1,214 @@ +/* # EMBASSY notes + This file is a workaround for https://github.com/rust-embedded/riscv/issues/196 + Remove when fixed upstream. +*/ +/* # Developer notes + +- Symbols that start with a double underscore (__) are considered "private" + +- Symbols that start with a single underscore (_) are considered "semi-public"; they can be + overridden in a user linker script, but should not be referred from user code (e.g. `extern "C" { + static mut _heap_size }`). + +- `EXTERN` forces the linker to keep a symbol in the final binary. We use this to make sure a + symbol if not dropped if it appears in or near the front of the linker arguments and "it's not + needed" by any of the preceding objects (linker arguments) + +- `PROVIDE` is used to provide default values that can be overridden by a user linker script + +- In this linker script, you may find symbols that look like `${...}` (e.g., `4`). + These are wildcards used by the `build.rs` script to adapt to different target particularities. + Check `build.rs` for more details about these symbols. + +- On alignment: it's important for correctness that the VMA boundaries of both .bss and .data *and* + the LMA of .data are all `4`-byte aligned. These alignments are assumed by the RAM + initialization routine. There's also a second benefit: `4`-byte aligned boundaries + means that you won't see "Address (..) is out of bounds" in the disassembly produced by `objdump`. +*/ + +PROVIDE(_stext = ORIGIN(REGION_TEXT)); +PROVIDE(_stack_start = ORIGIN(REGION_STACK) + LENGTH(REGION_STACK)); +PROVIDE(_max_hart_id = 0); +PROVIDE(_hart_stack_size = 2K); +PROVIDE(_heap_size = 0); + +PROVIDE(InstructionMisaligned = ExceptionHandler); +PROVIDE(InstructionFault = ExceptionHandler); +PROVIDE(IllegalInstruction = ExceptionHandler); +PROVIDE(Breakpoint = ExceptionHandler); +PROVIDE(LoadMisaligned = ExceptionHandler); +PROVIDE(LoadFault = ExceptionHandler); +PROVIDE(StoreMisaligned = ExceptionHandler); +PROVIDE(StoreFault = ExceptionHandler);; +PROVIDE(UserEnvCall = ExceptionHandler); +PROVIDE(SupervisorEnvCall = ExceptionHandler); +PROVIDE(MachineEnvCall = ExceptionHandler); +PROVIDE(InstructionPageFault = ExceptionHandler); +PROVIDE(LoadPageFault = ExceptionHandler); +PROVIDE(StorePageFault = ExceptionHandler); + +PROVIDE(SupervisorSoft = DefaultHandler); +PROVIDE(MachineSoft = DefaultHandler); +PROVIDE(SupervisorTimer = DefaultHandler); +PROVIDE(MachineTimer = DefaultHandler); +PROVIDE(SupervisorExternal = DefaultHandler); +PROVIDE(MachineExternal = DefaultHandler); + +PROVIDE(DefaultHandler = DefaultInterruptHandler); +PROVIDE(ExceptionHandler = DefaultExceptionHandler); + +/* # Pre-initialization function */ +/* If the user overrides this using the `#[pre_init]` attribute or by creating a `__pre_init` function, + then the function this points to will be called before the RAM is initialized. */ +PROVIDE(__pre_init = default_pre_init); + +/* A PAC/HAL defined routine that should initialize custom interrupt controller if needed. */ +PROVIDE(_setup_interrupts = default_setup_interrupts); + +/* # Multi-processing hook function + fn _mp_hook() -> bool; + + This function is called from all the harts and must return true only for one hart, + which will perform memory initialization. For other harts it must return false + and implement wake-up in platform-dependent way (e.g. after waiting for a user interrupt). +*/ +PROVIDE(_mp_hook = default_mp_hook); + +/* # Start trap function override + By default uses the riscv crates default trap handler + but by providing the `_start_trap` symbol external crates can override. +*/ +PROVIDE(_start_trap = default_start_trap); + +SECTIONS +{ + .text.dummy (NOLOAD) : + { + /* This section is intended to make _stext address work */ + . = ABSOLUTE(_stext); + } > REGION_TEXT + + .text _stext : + { + /* Put reset handler first in .text section so it ends up as the entry */ + /* point of the program. */ + KEEP(*(.init)); + KEEP(*(.init.rust)); + . = ALIGN(4); + *(.trap); + *(.trap.rust); + *(.text.abort); + *(.text .text.*); + } > REGION_TEXT + + .eh_frame : { KEEP(*(.eh_frame)) } > REGION_TEXT + .eh_frame_hdr : { *(.eh_frame_hdr) } > REGION_TEXT + + .rodata : ALIGN(4) + { + *(.srodata .srodata.*); + *(.rodata .rodata.*); + + /* 4-byte align the end (VMA) of this section. + This is required by LLD to ensure the LMA of the following .data + section will have the correct alignment. */ + . = ALIGN(4); + } > REGION_RODATA + + .data : ALIGN(4) + { + _sidata = LOADADDR(.data); + _sdata = .; + /* Must be called __global_pointer$ for linker relaxations to work. */ + PROVIDE(__global_pointer$ = . + 0x800); + *(.sdata .sdata.* .sdata2 .sdata2.*); + *(.data .data.*); + . = ALIGN(4); + _edata = .; + } > REGION_DATA AT > REGION_RODATA + + .bss (NOLOAD) : ALIGN(4) + { + _sbss = .; + *(.sbss .sbss.* .bss .bss.*); + . = ALIGN(4); + _ebss = .; + } > REGION_BSS + + /* fictitious region that represents the memory available for the heap */ + .heap (NOLOAD) : + { + _sheap = .; + . += _heap_size; + . = ALIGN(4); + _eheap = .; + } > REGION_HEAP + + /* fictitious region that represents the memory available for the stack */ + .stack (NOLOAD) : + { + _estack = .; + . = ABSOLUTE(_stack_start); + _sstack = .; + } > REGION_STACK + + /* fake output .got section */ + /* Dynamic relocations are unsupported. This section is only used to detect + relocatable code in the input files and raise an error if relocatable code + is found */ + .got (INFO) : + { + KEEP(*(.got .got.*)); + } +} + +/* Do not exceed this mark in the error messages above | */ +ASSERT(ORIGIN(REGION_TEXT) % 4 == 0, " +ERROR(riscv-rt): the start of the REGION_TEXT must be 4-byte aligned"); + +ASSERT(ORIGIN(REGION_RODATA) % 4 == 0, " +ERROR(riscv-rt): the start of the REGION_RODATA must be 4-byte aligned"); + +ASSERT(ORIGIN(REGION_DATA) % 4 == 0, " +ERROR(riscv-rt): the start of the REGION_DATA must be 4-byte aligned"); + +ASSERT(ORIGIN(REGION_HEAP) % 4 == 0, " +ERROR(riscv-rt): the start of the REGION_HEAP must be 4-byte aligned"); + +ASSERT(ORIGIN(REGION_TEXT) % 4 == 0, " +ERROR(riscv-rt): the start of the REGION_TEXT must be 4-byte aligned"); + +ASSERT(ORIGIN(REGION_STACK) % 4 == 0, " +ERROR(riscv-rt): the start of the REGION_STACK must be 4-byte aligned"); + +ASSERT(_stext % 4 == 0, " +ERROR(riscv-rt): `_stext` must be 4-byte aligned"); + +ASSERT(_sdata % 4 == 0 && _edata % 4 == 0, " +BUG(riscv-rt): .data is not 4-byte aligned"); + +ASSERT(_sidata % 4 == 0, " +BUG(riscv-rt): the LMA of .data is not 4-byte aligned"); + +ASSERT(_sbss % 4 == 0 && _ebss % 4 == 0, " +BUG(riscv-rt): .bss is not 4-byte aligned"); + +ASSERT(_sheap % 4 == 0, " +BUG(riscv-rt): start of .heap is not 4-byte aligned"); + +ASSERT(_stext + SIZEOF(.text) < ORIGIN(REGION_TEXT) + LENGTH(REGION_TEXT), " +ERROR(riscv-rt): The .text section must be placed inside the REGION_TEXT region. +Set _stext to an address smaller than 'ORIGIN(REGION_TEXT) + LENGTH(REGION_TEXT)'"); + +ASSERT(SIZEOF(.stack) > (_max_hart_id + 1) * _hart_stack_size, " +ERROR(riscv-rt): .stack section is too small for allocating stacks for all the harts. +Consider changing `_max_hart_id` or `_hart_stack_size`."); + +ASSERT(SIZEOF(.got) == 0, " +.got section detected in the input files. Dynamic relocations are not +supported. If you are linking to C code compiled using the `gcc` crate +then modify your build script to compile the C code _without_ the +-fPIC flag. See the documentation of the `gcc::Config.fpic` method for +details."); + +/* Do not exceed this mark in the error messages above | */ diff --git a/tests/rp/.cargo/config.toml b/tests/rp/.cargo/config.toml index de7bb0e56..4337924cc 100644 --- a/tests/rp/.cargo/config.toml +++ b/tests/rp/.cargo/config.toml @@ -11,7 +11,6 @@ runner = "teleprobe client run" rustflags = [ # Code-size optimizations. #"-Z", "trap-unreachable=no", - "-C", "inline-threshold=5", "-C", "no-vectorize-loops", ] diff --git a/tests/rp/Cargo.toml b/tests/rp/Cargo.toml index 46e1e9a5f..72f7ceb8f 100644 --- a/tests/rp/Cargo.toml +++ b/tests/rp/Cargo.toml @@ -7,13 +7,14 @@ license = "MIT OR Apache-2.0" [dependencies] teleprobe-meta = "1.1" -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", ] } -embassy-rp = { version = "0.1.0", path = "../../embassy-rp", features = [ "defmt", "unstable-pac", "time-driver", "critical-section-impl", "intrinsics", "rom-v2-intrinsics", "run-from-ram"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", ] } +embassy-rp = { version = "0.2.0", path = "../../embassy-rp", features = [ "defmt", "unstable-pac", "time-driver", "critical-section-impl", "intrinsics", "rom-v2-intrinsics", "run-from-ram", "rp2040"] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "udp", "dhcpv4", "medium-ethernet"] } embassy-net-wiznet = { version = "0.1.0", path = "../../embassy-net-wiznet", features = ["defmt"] } +embassy-embedded-hal = { version = "0.2.0", path = "../../embassy-embedded-hal/"} cyw43 = { path = "../../cyw43", features = ["defmt", "firmware-logs"] } cyw43-pio = { path = "../../cyw43-pio", features = ["defmt", "overclock"] } perf-client = { path = "../perf-client" } @@ -28,7 +29,6 @@ embedded-hal-1 = { package = "embedded-hal", version = "1.0" } embedded-hal-async = { version = "1.0" } embedded-hal-bus = { version = "0.1", features = ["async"] } panic-probe = { version = "0.3.0", features = ["print-defmt"] } -futures = { version = "0.3.17", default-features = false, features = ["async-await"] } embedded-io-async = { version = "0.6.1" } embedded-storage = { version = "0.3" } static_cell = "2" diff --git a/tests/rp/src/bin/adc.rs b/tests/rp/src/bin/adc.rs index 29eda95bf..65c246472 100644 --- a/tests/rp/src/bin/adc.rs +++ b/tests/rp/src/bin/adc.rs @@ -130,6 +130,19 @@ async fn main(_spawner: Spawner) { defmt::assert!(temp.iter().all(|t| *t > 0.0)); defmt::assert!(temp.iter().all(|t| *t < 60.0)); } + { + let mut multi = [0u16; 2]; + let mut channels = [ + Channel::new_pin(&mut p.PIN_26, Pull::Up), + Channel::new_temp_sensor(&mut p.ADC_TEMP_SENSOR), + ]; + adc.read_many_multichannel(&mut channels, &mut multi, 1, &mut p.DMA_CH0) + .await + .unwrap(); + defmt::assert!(multi[0] > 3_000); + let temp = convert_to_celsius(multi[1]); + defmt::assert!(temp > 0.0 && temp < 60.0); + } info!("Test OK"); cortex_m::asm::bkpt(); diff --git a/tests/rp/src/bin/cyw43-perf.rs b/tests/rp/src/bin/cyw43-perf.rs index b46ae670a..30e4afb07 100644 --- a/tests/rp/src/bin/cyw43-perf.rs +++ b/tests/rp/src/bin/cyw43-perf.rs @@ -2,10 +2,11 @@ #![no_main] teleprobe_meta::target!(b"rpi-pico"); +use cyw43::JoinOptions; use cyw43_pio::PioSpi; use defmt::{panic, *}; use embassy_executor::Spawner; -use embassy_net::{Config, Stack, StackResources}; +use embassy_net::{Config, StackResources}; use embassy_rp::gpio::{Level, Output}; use embassy_rp::peripherals::{DMA_CH0, PIO0}; use embassy_rp::pio::{InterruptHandler, Pio}; @@ -29,8 +30,8 @@ async fn wifi_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'stati } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, cyw43::NetDriver<'static>>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -45,8 +46,8 @@ async fn main(spawner: Spawner) { } // cyw43 firmware needs to be flashed manually: - // probe-rs download 43439A0.bin --format bin --chip RP2040 --base-address 0x101b0000 - // probe-rs download 43439A0_clm.bin --format bin --chip RP2040 --base-address 0x101f8000 + // probe-rs download 43439A0.bin --binary-format bin --chip RP2040 --base-address 0x101b0000 + // probe-rs download 43439A0_clm.bin --binary-format bin --chip RP2040 --base-address 0x101f8000 let fw = unsafe { core::slice::from_raw_parts(0x101b0000 as *const u8, 230321) }; let clm = unsafe { core::slice::from_raw_parts(0x101f8000 as *const u8, 4752) }; @@ -69,19 +70,21 @@ async fn main(spawner: Spawner) { let seed = 0x0123_4567_89ab_cdef; // chosen by fair dice roll. guarenteed to be random. // Init network stack - static STACK: StaticCell>> = StaticCell::new(); static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( + let (stack, runner) = embassy_net::new( net_device, Config::dhcpv4(Default::default()), - RESOURCES.init(StackResources::<2>::new()), + RESOURCES.init(StackResources::new()), seed, - )); + ); - unwrap!(spawner.spawn(net_task(stack))); + unwrap!(spawner.spawn(net_task(runner))); loop { - match control.join_wpa2(WIFI_NETWORK, WIFI_PASSWORD).await { + match control + .join(WIFI_NETWORK, JoinOptions::new(WIFI_PASSWORD.as_bytes())) + .await + { Ok(_) => break, Err(err) => { panic!("join failed with status={}", err.status); diff --git a/tests/rp/src/bin/ethernet_w5100s_perf.rs b/tests/rp/src/bin/ethernet_w5100s_perf.rs index 5d5547773..ae2adfa55 100644 --- a/tests/rp/src/bin/ethernet_w5100s_perf.rs +++ b/tests/rp/src/bin/ethernet_w5100s_perf.rs @@ -5,7 +5,7 @@ teleprobe_meta::timeout!(120); use defmt::*; use embassy_executor::Spawner; -use embassy_net::{Stack, StackResources}; +use embassy_net::StackResources; use embassy_net_wiznet::chip::W5100S; use embassy_net_wiznet::*; use embassy_rp::clocks::RoscRng; @@ -32,8 +32,8 @@ async fn ethernet_task( } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device<'static>>) -> ! { + runner.run().await } #[embassy_executor::main] @@ -59,24 +59,24 @@ async fn main(spawner: Spawner) { w5500_int, w5500_reset, ) - .await; + .await + .unwrap(); unwrap!(spawner.spawn(ethernet_task(runner))); // Generate random seed let seed = rng.next_u64(); // Init network stack - static STACK: StaticCell>> = StaticCell::new(); static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( + let (stack, runner) = embassy_net::new( device, embassy_net::Config::dhcpv4(Default::default()), - RESOURCES.init(StackResources::<2>::new()), + RESOURCES.init(StackResources::new()), seed, - )); + ); // Launch network task - unwrap!(spawner.spawn(net_task(&stack))); + unwrap!(spawner.spawn(net_task(runner))); perf_client::run( stack, diff --git a/tests/rp/src/bin/gpio_multicore.rs b/tests/rp/src/bin/gpio_multicore.rs index 8aed9b80c..e9c6f3122 100644 --- a/tests/rp/src/bin/gpio_multicore.rs +++ b/tests/rp/src/bin/gpio_multicore.rs @@ -21,10 +21,14 @@ static CHANNEL1: Channel = Channel::new(); #[cortex_m_rt::entry] fn main() -> ! { let p = embassy_rp::init(Default::default()); - spawn_core1(p.CORE1, unsafe { &mut CORE1_STACK }, move || { - let executor1 = EXECUTOR1.init(Executor::new()); - executor1.run(|spawner| unwrap!(spawner.spawn(core1_task(p.PIN_1)))); - }); + spawn_core1( + p.CORE1, + unsafe { &mut *core::ptr::addr_of_mut!(CORE1_STACK) }, + move || { + let executor1 = EXECUTOR1.init(Executor::new()); + executor1.run(|spawner| unwrap!(spawner.spawn(core1_task(p.PIN_1)))); + }, + ); let executor0 = EXECUTOR0.init(Executor::new()); executor0.run(|spawner| unwrap!(spawner.spawn(core0_task(p.PIN_0)))); } diff --git a/tests/rp/src/bin/i2c.rs b/tests/rp/src/bin/i2c.rs index 77d628cf6..9615007bd 100644 --- a/tests/rp/src/bin/i2c.rs +++ b/tests/rp/src/bin/i2c.rs @@ -3,7 +3,10 @@ teleprobe_meta::target!(b"rpi-pico"); use defmt::{assert_eq, info, panic, unwrap}; -use embassy_executor::Executor; +use embassy_embedded_hal::SetConfig; +use embassy_executor::{Executor, Spawner}; +use embassy_rp::clocks::{PllConfig, XoscConfig}; +use embassy_rp::config::Config as rpConfig; use embassy_rp::multicore::{spawn_core1, Stack}; use embassy_rp::peripherals::{I2C0, I2C1}; use embassy_rp::{bind_interrupts, i2c, i2c_slave}; @@ -13,7 +16,6 @@ use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _, panic_probe as _, panic_probe as _}; static mut CORE1_STACK: Stack<1024> = Stack::new(); -static EXECUTOR0: StaticCell = StaticCell::new(); static EXECUTOR1: StaticCell = StaticCell::new(); use crate::i2c::AbortReason; @@ -44,10 +46,7 @@ async fn device_task(mut dev: i2c_slave::I2cSlave<'static, I2C1>) -> ! { Ok(x) => match x { i2c_slave::ReadStatus::Done => break, i2c_slave::ReadStatus::NeedMoreBytes => count += 1, - i2c_slave::ReadStatus::LeftoverBytes(x) => { - info!("tried to write {} extra bytes", x); - break; - } + i2c_slave::ReadStatus::LeftoverBytes(x) => panic!("tried to write {} extra bytes", x), }, Err(e) => match e { embassy_rp::i2c_slave::Error::Abort(AbortReason::Other(n)) => panic!("Other {:b}", n), @@ -80,7 +79,7 @@ async fn device_task(mut dev: i2c_slave::I2cSlave<'static, I2C1>) -> ! { _ => panic!("Invalid write length {}", len), }, Ok(i2c_slave::Command::WriteRead(len)) => { - info!("device recieved write read: {:x}", buf[..len]); + info!("device received write read: {:x}", buf[..len]); match buf[0] { 0xC2 => { let resp_buff = [0xD1, 0xD2, 0xD3, 0xD4]; @@ -92,6 +91,8 @@ async fn device_task(mut dev: i2c_slave::I2cSlave<'static, I2C1>) -> ! { resp_buff[i] = i as u8; } dev.respond_to_read(&resp_buff).await.unwrap(); + // reset count for next round of tests + count = 0xD0; } x => panic!("Invalid Write Read {:x}", x), } @@ -104,8 +105,7 @@ async fn device_task(mut dev: i2c_slave::I2cSlave<'static, I2C1>) -> ! { } } -#[embassy_executor::task] -async fn controller_task(mut con: i2c::I2c<'static, I2C0, i2c::Async>) { +async fn controller_task(con: &mut i2c::I2c<'static, I2C0, i2c::Async>) { info!("Device start"); { @@ -179,33 +179,59 @@ async fn controller_task(mut con: i2c::I2c<'static, I2C0, i2c::Async>) { info!("large write_read - OK") } - info!("Test OK"); - cortex_m::asm::bkpt(); -} - -#[cortex_m_rt::entry] -fn main() -> ! { - let p = embassy_rp::init(Default::default()); - info!("Hello World!"); - - let d_sda = p.PIN_19; - let d_scl = p.PIN_18; - let mut config = i2c_slave::Config::default(); - config.addr = DEV_ADDR as u16; - let device = i2c_slave::I2cSlave::new(p.I2C1, d_sda, d_scl, Irqs, config); - - spawn_core1(p.CORE1, unsafe { &mut CORE1_STACK }, move || { - let executor1 = EXECUTOR1.init(Executor::new()); - executor1.run(|spawner| unwrap!(spawner.spawn(device_task(device)))); - }); - - let executor0 = EXECUTOR0.init(Executor::new()); - - let c_sda = p.PIN_21; - let c_scl = p.PIN_20; - let mut config = i2c::Config::default(); - config.frequency = 5_000; - let controller = i2c::I2c::new_async(p.I2C0, c_sda, c_scl, Irqs, config); - - executor0.run(|spawner| unwrap!(spawner.spawn(controller_task(controller)))); + #[embassy_executor::main] + async fn main(_core0_spawner: Spawner) { + let mut config = rpConfig::default(); + // Configure clk_sys to 48MHz to support 1kHz scl. + // In theory it can go lower, but we won't bother to test below 1kHz. + config.clocks.xosc = Some(XoscConfig { + hz: 12_000_000, + delay_multiplier: 128, + sys_pll: Some(PllConfig { + refdiv: 1, + fbdiv: 120, + post_div1: 6, + post_div2: 5, + }), + usb_pll: Some(PllConfig { + refdiv: 1, + fbdiv: 120, + post_div1: 6, + post_div2: 5, + }), + }); + + let p = embassy_rp::init(config); + info!("Hello World!"); + + let d_sda = p.PIN_19; + let d_scl = p.PIN_18; + let mut config = i2c_slave::Config::default(); + config.addr = DEV_ADDR as u16; + let device = i2c_slave::I2cSlave::new(p.I2C1, d_sda, d_scl, Irqs, config); + + spawn_core1( + p.CORE1, + unsafe { &mut *core::ptr::addr_of_mut!(CORE1_STACK) }, + move || { + let executor1 = EXECUTOR1.init(Executor::new()); + executor1.run(|spawner| unwrap!(spawner.spawn(device_task(device)))); + }, + ); + + let c_sda = p.PIN_21; + let c_scl = p.PIN_20; + let mut controller = i2c::I2c::new_async(p.I2C0, c_sda, c_scl, Irqs, Default::default()); + + for freq in [1000, 100_000, 400_000, 1_000_000] { + info!("testing at {}hz", freq); + let mut config = i2c::Config::default(); + config.frequency = freq; + controller.set_config(&config).unwrap(); + controller_task(&mut controller).await; + } + + info!("Test OK"); + cortex_m::asm::bkpt(); + } } diff --git a/tests/rp/src/bin/multicore.rs b/tests/rp/src/bin/multicore.rs index 60d9f85ec..783ea0f27 100644 --- a/tests/rp/src/bin/multicore.rs +++ b/tests/rp/src/bin/multicore.rs @@ -19,10 +19,14 @@ static CHANNEL1: Channel = Channel::new(); #[cortex_m_rt::entry] fn main() -> ! { let p = embassy_rp::init(Default::default()); - spawn_core1(p.CORE1, unsafe { &mut CORE1_STACK }, move || { - let executor1 = EXECUTOR1.init(Executor::new()); - executor1.run(|spawner| unwrap!(spawner.spawn(core1_task()))); - }); + spawn_core1( + p.CORE1, + unsafe { &mut *core::ptr::addr_of_mut!(CORE1_STACK) }, + move || { + let executor1 = EXECUTOR1.init(Executor::new()); + executor1.run(|spawner| unwrap!(spawner.spawn(core1_task()))); + }, + ); let executor0 = EXECUTOR0.init(Executor::new()); executor0.run(|spawner| unwrap!(spawner.spawn(core0_task()))); } diff --git a/tests/rp/src/bin/pwm.rs b/tests/rp/src/bin/pwm.rs index e71d9e610..c05197000 100644 --- a/tests/rp/src/bin/pwm.rs +++ b/tests/rp/src/bin/pwm.rs @@ -28,7 +28,7 @@ async fn main(_spawner: Spawner) { // Test free-running clock { - let pwm = Pwm::new_free(&mut p.PWM_CH3, cfg.clone()); + let pwm = Pwm::new_free(&mut p.PWM_SLICE3, cfg.clone()); cortex_m::asm::delay(125); let ctr = pwm.counter(); assert!(ctr > 0); @@ -46,7 +46,7 @@ async fn main(_spawner: Spawner) { // Test output from A { let pin1 = Input::new(&mut p9, Pull::None); - let _pwm = Pwm::new_output_a(&mut p.PWM_CH3, &mut p6, cfg.clone()); + let _pwm = Pwm::new_output_a(&mut p.PWM_SLICE3, &mut p6, cfg.clone()); Timer::after_millis(1).await; assert_eq!(pin1.is_low(), invert_a); Timer::after_millis(5).await; @@ -60,7 +60,7 @@ async fn main(_spawner: Spawner) { // Test output from B { let pin2 = Input::new(&mut p11, Pull::None); - let _pwm = Pwm::new_output_b(&mut p.PWM_CH3, &mut p7, cfg.clone()); + let _pwm = Pwm::new_output_b(&mut p.PWM_SLICE3, &mut p7, cfg.clone()); Timer::after_millis(1).await; assert_ne!(pin2.is_low(), invert_a); Timer::after_millis(5).await; @@ -75,7 +75,7 @@ async fn main(_spawner: Spawner) { { let pin1 = Input::new(&mut p9, Pull::None); let pin2 = Input::new(&mut p11, Pull::None); - let _pwm = Pwm::new_output_ab(&mut p.PWM_CH3, &mut p6, &mut p7, cfg.clone()); + let _pwm = Pwm::new_output_ab(&mut p.PWM_SLICE3, &mut p6, &mut p7, cfg.clone()); Timer::after_millis(1).await; assert_eq!(pin1.is_low(), invert_a); assert_ne!(pin2.is_low(), invert_a); @@ -94,7 +94,7 @@ async fn main(_spawner: Spawner) { // Test level-gated { let mut pin2 = Output::new(&mut p11, Level::Low); - let pwm = Pwm::new_input(&mut p.PWM_CH3, &mut p7, InputMode::Level, cfg.clone()); + let pwm = Pwm::new_input(&mut p.PWM_SLICE3, &mut p7, Pull::None, InputMode::Level, cfg.clone()); assert_eq!(pwm.counter(), 0); Timer::after_millis(5).await; assert_eq!(pwm.counter(), 0); @@ -110,7 +110,13 @@ async fn main(_spawner: Spawner) { // Test rising-gated { let mut pin2 = Output::new(&mut p11, Level::Low); - let pwm = Pwm::new_input(&mut p.PWM_CH3, &mut p7, InputMode::RisingEdge, cfg.clone()); + let pwm = Pwm::new_input( + &mut p.PWM_SLICE3, + &mut p7, + Pull::None, + InputMode::RisingEdge, + cfg.clone(), + ); assert_eq!(pwm.counter(), 0); Timer::after_millis(5).await; assert_eq!(pwm.counter(), 0); @@ -125,7 +131,13 @@ async fn main(_spawner: Spawner) { // Test falling-gated { let mut pin2 = Output::new(&mut p11, Level::High); - let pwm = Pwm::new_input(&mut p.PWM_CH3, &mut p7, InputMode::FallingEdge, cfg.clone()); + let pwm = Pwm::new_input( + &mut p.PWM_SLICE3, + &mut p7, + Pull::None, + InputMode::FallingEdge, + cfg.clone(), + ); assert_eq!(pwm.counter(), 0); Timer::after_millis(5).await; assert_eq!(pwm.counter(), 0); @@ -137,6 +149,34 @@ async fn main(_spawner: Spawner) { assert_eq!(pwm.counter(), 1); } + // pull-down + { + let pin2 = Input::new(&mut p11, Pull::None); + Pwm::new_input( + &mut p.PWM_SLICE3, + &mut p7, + Pull::Down, + InputMode::FallingEdge, + cfg.clone(), + ); + Timer::after_millis(1).await; + assert!(pin2.is_low()); + } + + // pull-up + { + let pin2 = Input::new(&mut p11, Pull::None); + Pwm::new_input( + &mut p.PWM_SLICE3, + &mut p7, + Pull::Up, + InputMode::FallingEdge, + cfg.clone(), + ); + Timer::after_millis(1).await; + assert!(pin2.is_high()); + } + info!("Test OK"); cortex_m::asm::bkpt(); } diff --git a/tests/nrf52840/src/bin/timer.rs b/tests/rp/src/bin/timer.rs similarity index 77% rename from tests/nrf52840/src/bin/timer.rs rename to tests/rp/src/bin/timer.rs index 117947a94..be9242144 100644 --- a/tests/nrf52840/src/bin/timer.rs +++ b/tests/rp/src/bin/timer.rs @@ -1,15 +1,15 @@ #![no_std] #![no_main] -teleprobe_meta::target!(b"nrf52840-dk"); +teleprobe_meta::target!(b"rpi-pico"); -use defmt::{assert, info}; +use defmt::{assert, *}; use embassy_executor::Spawner; use embassy_time::{Instant, Timer}; use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] async fn main(_spawner: Spawner) { - let _p = embassy_nrf::init(Default::default()); + let _p = embassy_rp::init(Default::default()); info!("Hello World!"); let start = Instant::now(); @@ -18,6 +18,7 @@ async fn main(_spawner: Spawner) { let ms = (end - start).as_millis(); info!("slept for {} ms", ms); assert!(ms >= 99); + assert!(ms < 110); info!("Test OK"); cortex_m::asm::bkpt(); diff --git a/tests/stm32/.cargo/config.toml b/tests/stm32/.cargo/config.toml index 8e32b4cee..d94342598 100644 --- a/tests/stm32/.cargo/config.toml +++ b/tests/stm32/.cargo/config.toml @@ -4,19 +4,18 @@ [target.'cfg(all(target_arch = "arm", target_os = "none"))'] runner = "teleprobe client run" -#runner = "teleprobe local run --chip STM32F103C8 --elf" +#runner = "teleprobe local run --chip STM32H7S3L8Hx --elf" rustflags = [ # Code-size optimizations. #"-Z", "trap-unreachable=no", - "-C", "inline-threshold=5", "-C", "no-vectorize-loops", ] [build] -target = "thumbv6m-none-eabi" +#target = "thumbv6m-none-eabi" #target = "thumbv7m-none-eabi" -#target = "thumbv7em-none-eabi" +target = "thumbv7em-none-eabi" #target = "thumbv8m.main-none-eabihf" [env] diff --git a/tests/stm32/Cargo.toml b/tests/stm32/Cargo.toml index cb1bd9a50..f30217fc0 100644 --- a/tests/stm32/Cargo.toml +++ b/tests/stm32/Cargo.toml @@ -7,30 +7,38 @@ autobins = false [features] stm32c031c6 = ["embassy-stm32/stm32c031c6", "cm0", "not-gpdma"] -stm32f103c8 = ["embassy-stm32/stm32f103c8", "not-gpdma"] -stm32f207zg = ["embassy-stm32/stm32f207zg", "chrono", "not-gpdma", "eth", "rng"] +stm32f103c8 = ["embassy-stm32/stm32f103c8", "spi-v1", "not-gpdma"] +stm32f207zg = ["embassy-stm32/stm32f207zg", "spi-v1", "chrono", "not-gpdma", "eth", "rng"] stm32f303ze = ["embassy-stm32/stm32f303ze", "chrono", "not-gpdma"] -stm32f429zi = ["embassy-stm32/stm32f429zi", "chrono", "eth", "stop", "can", "not-gpdma", "dac", "rng"] -stm32f446re = ["embassy-stm32/stm32f446re", "chrono", "stop", "can", "not-gpdma", "dac", "sdmmc"] +stm32f429zi = ["embassy-stm32/stm32f429zi", "spi-v1", "chrono", "eth", "stop", "can", "not-gpdma", "dac", "rng"] +stm32f446re = ["embassy-stm32/stm32f446re", "spi-v1", "chrono", "stop", "can", "not-gpdma", "dac", "sdmmc"] stm32f767zi = ["embassy-stm32/stm32f767zi", "chrono", "not-gpdma", "eth", "rng"] -stm32g071rb = ["embassy-stm32/stm32g071rb", "cm0", "not-gpdma", "dac"] -stm32g491re = ["embassy-stm32/stm32g491re", "chrono", "stop", "not-gpdma", "rng", "fdcan"] -stm32h563zi = ["embassy-stm32/stm32h563zi", "chrono", "eth", "rng"] -stm32h753zi = ["embassy-stm32/stm32h753zi", "chrono", "not-gpdma", "eth", "rng", "fdcan"] -stm32h755zi = ["embassy-stm32/stm32h755zi-cm7", "chrono", "not-gpdma", "eth", "dac", "rng", "fdcan"] -stm32h7a3zi = ["embassy-stm32/stm32h7a3zi", "not-gpdma", "rng", "fdcan"] +stm32g071rb = ["embassy-stm32/stm32g071rb", "cm0", "not-gpdma", "dac", "ucpd"] +stm32g491re = ["embassy-stm32/stm32g491re", "chrono", "stop", "not-gpdma", "rng", "fdcan", "cordic"] +stm32h563zi = ["embassy-stm32/stm32h563zi", "spi-v345", "chrono", "eth", "rng", "fdcan", "hash", "cordic", "stop"] +stm32h753zi = ["embassy-stm32/stm32h753zi", "spi-v345", "chrono", "not-gpdma", "eth", "rng", "fdcan", "hash", "cryp"] +stm32h755zi = ["embassy-stm32/stm32h755zi-cm7", "spi-v345", "chrono", "not-gpdma", "eth", "dac", "rng", "fdcan", "hash", "cryp"] +stm32h7a3zi = ["embassy-stm32/stm32h7a3zi", "spi-v345", "not-gpdma", "rng", "fdcan"] stm32l073rz = ["embassy-stm32/stm32l073rz", "cm0", "not-gpdma", "rng"] -stm32l152re = ["embassy-stm32/stm32l152re", "chrono", "not-gpdma"] +stm32l152re = ["embassy-stm32/stm32l152re", "spi-v1", "chrono", "not-gpdma"] stm32l496zg = ["embassy-stm32/stm32l496zg", "not-gpdma", "rng"] -stm32l4a6zg = ["embassy-stm32/stm32l4a6zg", "chrono", "not-gpdma", "rng"] +stm32l4a6zg = ["embassy-stm32/stm32l4a6zg", "chrono", "not-gpdma", "rng", "hash"] stm32l4r5zi = ["embassy-stm32/stm32l4r5zi", "chrono", "not-gpdma", "rng"] -stm32l552ze = ["embassy-stm32/stm32l552ze", "not-gpdma", "rng"] -stm32u585ai = ["embassy-stm32/stm32u585ai", "chrono", "rng"] -stm32u5a5zj = ["embassy-stm32/stm32u5a5zj", "chrono", "rng"] +stm32l552ze = ["embassy-stm32/stm32l552ze", "not-gpdma", "rng", "hash"] +stm32u585ai = ["embassy-stm32/stm32u585ai", "spi-v345", "chrono", "rng", "hash", "cordic"] +stm32u5a5zj = ["embassy-stm32/stm32u5a5zj", "spi-v345", "chrono", "rng", "hash"] # FIXME: cordic test cause it crash stm32wb55rg = ["embassy-stm32/stm32wb55rg", "chrono", "not-gpdma", "ble", "mac" , "rng"] -stm32wba52cg = ["embassy-stm32/stm32wba52cg", "chrono", "rng"] +stm32wba52cg = ["embassy-stm32/stm32wba52cg", "spi-v345", "chrono", "rng", "hash"] stm32wl55jc = ["embassy-stm32/stm32wl55jc-cm4", "not-gpdma", "rng", "chrono"] +stm32f091rc = ["embassy-stm32/stm32f091rc", "cm0", "not-gpdma", "chrono"] +stm32h503rb = ["embassy-stm32/stm32h503rb", "spi-v345", "rng", "stop"] +stm32h7s3l8 = ["embassy-stm32/stm32h7s3l8", "spi-v345", "rng", "cordic", "hash"] # TODO: fdcan crashes, cryp dma hangs. +stm32u083rc = ["embassy-stm32/stm32u083rc", "cm0", "rng", "chrono"] +spi-v1 = [] +spi-v345 = [] +cryp = [] +hash = [] eth = ["embassy-executor/task-arena-size-16384"] rng = [] sdmmc = [] @@ -43,15 +51,17 @@ mac = ["dep:embassy-stm32-wpan", "embassy-stm32-wpan/mac"] embassy-stm32-wpan = [] not-gpdma = [] dac = [] +ucpd = [] +cordic = ["dep:num-traits"] cm0 = ["portable-atomic/unsafe-assume-single-core"] [dependencies] teleprobe-meta = "1" -embassy-sync = { version = "0.5.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.3.0", path = "../../embassy-time", features = ["defmt", "tick-hz-131_072", "defmt-timestamp-uptime"] } +embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { version = "0.6.2", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.3.2", path = "../../embassy-time", features = ["defmt", "tick-hz-131_072", "defmt-timestamp-uptime"] } embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = [ "defmt", "unstable-pac", "memory-x", "time-driver-any"] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } embassy-stm32-wpan = { version = "0.1.0", path = "../../embassy-stm32-wpan", optional = true, features = ["defmt", "stm32wb55rg", "ble"] } @@ -66,6 +76,7 @@ cortex-m-rt = "0.7.0" embedded-hal = "0.2.6" embedded-hal-1 = { package = "embedded-hal", version = "1.0" } embedded-hal-async = { version = "1.0" } +embedded-can = { version = "0.4" } micromath = "2.0.0" panic-probe = { version = "0.3.0", features = ["print-defmt"] } rand_core = { version = "0.6", default-features = false } @@ -74,6 +85,10 @@ static_cell = "2" portable-atomic = { version = "1.5", features = [] } chrono = { version = "^0.4", default-features = false, optional = true} +sha2 = { version = "0.10.8", default-features = false } +hmac = "0.12.1" +aes-gcm = {version = "0.10.3", default-features = false, features = ["aes", "heapless"] } +num-traits = {version="0.2", default-features = false,features = ["libm"], optional = true} # BEGIN TESTS # Generated by gen_test.py. DO NOT EDIT. @@ -82,6 +97,16 @@ name = "can" path = "src/bin/can.rs" required-features = [ "can",] +[[bin]] +name = "cordic" +path = "src/bin/cordic.rs" +required-features = [ "rng", "cordic",] + +[[bin]] +name = "cryp" +path = "src/bin/cryp.rs" +required-features = [ "cryp",] + [[bin]] name = "dac" path = "src/bin/dac.rs" @@ -107,6 +132,11 @@ name = "gpio" path = "src/bin/gpio.rs" required-features = [] +[[bin]] +name = "hash" +path = "src/bin/hash.rs" +required-features = [ "hash",] + [[bin]] name = "rng" path = "src/bin/rng.rs" @@ -142,6 +172,11 @@ name = "timer" path = "src/bin/timer.rs" required-features = [] +[[bin]] +name = "ucpd" +path = "src/bin/ucpd.rs" +required-features = [ "ucpd",] + [[bin]] name = "usart" path = "src/bin/usart.rs" diff --git a/tests/stm32/build.rs b/tests/stm32/build.rs index f32a7b2f8..722671bf1 100644 --- a/tests/stm32/build.rs +++ b/tests/stm32/build.rs @@ -10,12 +10,12 @@ fn main() -> Result<(), Box> { if cfg!(any( // too little RAM to run from RAM. - feature = "stm32f103c8", - feature = "stm32c031c6", - feature = "stm32wb55rg", - feature = "stm32l073rz", - // wrong ram size in stm32-data - feature = "stm32wl55jc", + feature = "stm32f103c8", // 20 kb + feature = "stm32c031c6", // 6 kb + feature = "stm32l073rz", // 20 kb + feature = "stm32h503rb", // 32 kb + // no VTOR, so interrupts can't work when running from RAM + feature = "stm32f091rc", )) { println!("cargo:rustc-link-arg-bins=-Tlink.x"); println!("cargo:rerun-if-changed=link.x"); diff --git a/tests/stm32/gen_test.py b/tests/stm32/gen_test.py index 8ff156c0e..daf714376 100644 --- a/tests/stm32/gen_test.py +++ b/tests/stm32/gen_test.py @@ -14,7 +14,7 @@ for f in sorted(glob('./src/bin/*.rs')): with open(f, 'r') as f: for line in f: if line.startswith('// required-features:'): - features = line.split(':', 2)[1].strip().split(',') + features = [feature.strip() for feature in line.split(':', 2)[1].strip().split(',')] tests[name] = features diff --git a/tests/stm32/src/bin/can.rs b/tests/stm32/src/bin/can.rs index f4effa244..85a5f8d83 100644 --- a/tests/stm32/src/bin/can.rs +++ b/tests/stm32/src/bin/can.rs @@ -6,17 +6,18 @@ #[path = "../common.rs"] mod common; use common::*; -use defmt::assert; use embassy_executor::Spawner; use embassy_stm32::bind_interrupts; -use embassy_stm32::can::bxcan::filter::Mask32; -use embassy_stm32::can::bxcan::{Fifo, Frame, StandardId}; -use embassy_stm32::can::{Can, Rx0InterruptHandler, Rx1InterruptHandler, SceInterruptHandler, TxInterruptHandler}; +use embassy_stm32::can::filter::Mask32; +use embassy_stm32::can::{Fifo, Rx0InterruptHandler, Rx1InterruptHandler, SceInterruptHandler, TxInterruptHandler}; use embassy_stm32::gpio::{Input, Pull}; use embassy_stm32::peripherals::CAN1; -use embassy_time::{Duration, Instant}; +use embassy_time::Duration; use {defmt_rtt as _, panic_probe as _}; +mod can_common; +use can_common::*; + bind_interrupts!(struct Irqs { CAN1_RX0 => Rx0InterruptHandler; CAN1_RX1 => Rx1InterruptHandler; @@ -26,9 +27,14 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) { - let p = embassy_stm32::init(config()); + let p = init(); info!("Hello World!"); + let options = TestOptions { + max_latency: Duration::from_micros(1200), + max_buffered: 2, + }; + let can = peri!(p, CAN); let tx = peri!(p, CAN_TX); let mut rx = peri!(p, CAN_RX); @@ -40,58 +46,29 @@ async fn main(_spawner: Spawner) { let rx_pin = Input::new(&mut rx, Pull::Up); core::mem::forget(rx_pin); - let mut can = Can::new(can, rx, tx, Irqs); + let mut can = embassy_stm32::can::Can::new(can, rx, tx, Irqs); info!("Configuring can..."); - can.as_mut() - .modify_filters() - .enable_bank(0, Fifo::Fifo0, Mask32::accept_all()); + can.modify_filters().enable_bank(0, Fifo::Fifo0, Mask32::accept_all()); - can.set_bitrate(1_000_000); - can.as_mut() - .modify_config() + can.modify_config() .set_loopback(true) // Receive own frames .set_silent(true) // .set_bit_timing(0x001c0003) - .enable(); + .set_bitrate(1_000_000); + + can.enable().await; info!("Can configured"); - let mut i: u8 = 0; - loop { - let tx_frame = Frame::new_data(unwrap!(StandardId::new(i as _)), [i]); + run_can_tests(&mut can, &options).await; - info!("Transmitting frame..."); - let tx_ts = Instant::now(); - can.write(&tx_frame).await; - - let envelope = can.read().await.unwrap(); - info!("Frame received!"); - - info!("loopback time {}", envelope.ts); - info!("loopback frame {=u8}", envelope.frame.data().unwrap()[0]); - - let latency = envelope.ts.saturating_duration_since(tx_ts); - info!("loopback latency {} us", latency.as_micros()); - - // Theoretical minimum latency is 55us, actual is usually ~80us - const MIN_LATENCY: Duration = Duration::from_micros(50); - const MAX_LATENCY: Duration = Duration::from_micros(150); - assert!( - MIN_LATENCY <= latency && latency <= MAX_LATENCY, - "{} <= {} <= {}", - MIN_LATENCY, - latency, - MAX_LATENCY - ); - - i += 1; - if i > 10 { - break; - } - } + // Test again with a split + let (mut tx, mut rx) = can.split(); + run_split_can_tests(&mut tx, &mut rx, &options).await; info!("Test OK"); + cortex_m::asm::bkpt(); } diff --git a/tests/stm32/src/bin/can_common.rs b/tests/stm32/src/bin/can_common.rs new file mode 100644 index 000000000..4e1740ad5 --- /dev/null +++ b/tests/stm32/src/bin/can_common.rs @@ -0,0 +1,109 @@ +use defmt::{assert, *}; +use embassy_stm32::can; +use embassy_time::{Duration, Instant}; + +#[derive(Clone, Copy, Debug)] +pub struct TestOptions { + pub max_latency: Duration, + pub max_buffered: u8, +} + +pub async fn run_can_tests<'d>(can: &mut can::Can<'d>, options: &TestOptions) { + //pub async fn run_can_tests<'d, T: can::Instance>(can: &mut can::Can<'d, T>, options: &TestOptions) { + let mut i: u8 = 0; + loop { + //let tx_frame = can::frame::Frame::new_standard(0x123, &[i, 0x12 as u8, 0x34 as u8, 0x56 as u8, 0x78 as u8, 0x9A as u8, 0xBC as u8 ]).unwrap(); + let tx_frame = can::frame::Frame::new_standard(0x123, &[i; 1]).unwrap(); + + //info!("Transmitting frame..."); + let tx_ts = Instant::now(); + can.write(&tx_frame).await; + + let (frame, timestamp) = can.read().await.unwrap().parts(); + //info!("Frame received!"); + + // Check data. + assert!(i == frame.data()[0], "{} == {}", i, frame.data()[0]); + + //info!("loopback time {}", timestamp); + //info!("loopback frame {=u8}", frame.data()[0]); + let latency = timestamp.saturating_duration_since(tx_ts); + info!("loopback latency {} us", latency.as_micros()); + + // Theoretical minimum latency is 55us, actual is usually ~80us + const MIN_LATENCY: Duration = Duration::from_micros(50); + // Was failing at 150 but we are not getting a real time stamp. I'm not + // sure if there are other delays + assert!( + MIN_LATENCY <= latency && latency <= options.max_latency, + "{} <= {} <= {}", + MIN_LATENCY, + latency, + options.max_latency + ); + + i += 1; + if i > 5 { + break; + } + } + + // Below here, check that we can receive from both FIFO0 and FIFO1 + // Above we configured FIFO1 for extended ID packets. There are only 3 slots + // in each FIFO so make sure we write enough to fill them both up before reading. + for i in 0..options.max_buffered { + // Try filling up the RX FIFO0 buffers + //let tx_frame = if 0 != (i & 0x01) { + let tx_frame = if i < options.max_buffered / 2 { + info!("Transmitting standard frame {}", i); + can::frame::Frame::new_standard(0x123, &[i; 1]).unwrap() + } else { + info!("Transmitting extended frame {}", i); + can::frame::Frame::new_extended(0x1232344, &[i; 1]).unwrap() + }; + can.write(&tx_frame).await; + } + + // Try and receive all 6 packets + for _i in 0..options.max_buffered { + let (frame, _ts) = can.read().await.unwrap().parts(); + match frame.id() { + embedded_can::Id::Extended(_id) => { + info!("Extended received! {}", frame.data()[0]); + //info!("Extended received! {:x} {} {}", id.as_raw(), frame.data()[0], i); + } + embedded_can::Id::Standard(_id) => { + info!("Standard received! {}", frame.data()[0]); + //info!("Standard received! {:x} {} {}", id.as_raw(), frame.data()[0], i); + } + } + } +} + +pub async fn run_split_can_tests<'d>(tx: &mut can::CanTx<'d>, rx: &mut can::CanRx<'d>, options: &TestOptions) { + for i in 0..options.max_buffered { + // Try filling up the RX FIFO0 buffers + //let tx_frame = if 0 != (i & 0x01) { + let tx_frame = if i < options.max_buffered / 2 { + info!("Transmitting standard frame {}", i); + can::frame::Frame::new_standard(0x123, &[i; 1]).unwrap() + } else { + info!("Transmitting extended frame {}", i); + can::frame::Frame::new_extended(0x1232344, &[i; 1]).unwrap() + }; + tx.write(&tx_frame).await; + } + + // Try and receive all 6 packets + for _i in 0..options.max_buffered { + let (frame, _ts) = rx.read().await.unwrap().parts(); + match frame.id() { + embedded_can::Id::Extended(_id) => { + info!("Extended received! {}", frame.data()[0]); + } + embedded_can::Id::Standard(_id) => { + info!("Standard received! {}", frame.data()[0]); + } + } + } +} diff --git a/tests/stm32/src/bin/cordic.rs b/tests/stm32/src/bin/cordic.rs new file mode 100644 index 000000000..879ad56b6 --- /dev/null +++ b/tests/stm32/src/bin/cordic.rs @@ -0,0 +1,140 @@ +// required-features: rng, cordic + +// Test Cordic driver, with Q1.31 format, Sin function, at 24 iterations (aka PRECISION = 6), using DMA transfer + +#![no_std] +#![no_main] + +#[path = "../common.rs"] +mod common; +use common::*; +use embassy_executor::Spawner; +use embassy_stm32::cordic::utils; +use embassy_stm32::{bind_interrupts, cordic, peripherals, rng}; +use num_traits::Float; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + RNG => rng::InterruptHandler; +}); + +/* input value control, can be changed */ + +const INPUT_U32_COUNT: usize = 9; +const INPUT_U8_COUNT: usize = 4 * INPUT_U32_COUNT; + +// Assume first calculation needs 2 arguments, the reset needs 1 argument. +// And all calculation generate 2 results. +const OUTPUT_LENGTH: usize = (INPUT_U32_COUNT - 1) * 2; + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let dp = init(); + + // + // use RNG generate random Q1.31 value + // + // we don't generate floating-point value, since not all binary value are valid floating-point value, + // and Q1.31 only accept a fixed range of value. + + let mut rng = rng::Rng::new(dp.RNG, Irqs); + + let mut input_buf_u8 = [0u8; INPUT_U8_COUNT]; + defmt::unwrap!(rng.async_fill_bytes(&mut input_buf_u8).await); + + // convert every [u8; 4] to a u32, for a Q1.31 value + let mut input_q1_31 = unsafe { core::mem::transmute::<[u8; INPUT_U8_COUNT], [u32; INPUT_U32_COUNT]>(input_buf_u8) }; + + // ARG2 for Sin function should be inside [0, 1], set MSB to 0 of a Q1.31 value, will make sure it's no less than 0. + input_q1_31[1] &= !(1u32 << 31); + + // + // CORDIC calculation + // + + let mut output_q1_31 = [0u32; OUTPUT_LENGTH]; + + // setup Cordic driver + let mut cordic = cordic::Cordic::new( + dp.CORDIC, + defmt::unwrap!(cordic::Config::new( + cordic::Function::Sin, + Default::default(), + Default::default(), + )), + ); + + #[cfg(feature = "stm32g491re")] + let (mut write_dma, mut read_dma) = (dp.DMA1_CH4, dp.DMA1_CH5); + + #[cfg(any( + feature = "stm32h563zi", + feature = "stm32u585ai", + feature = "stm32u5a5zj", + feature = "stm32h7s3l8" + ))] + let (mut write_dma, mut read_dma) = (dp.GPDMA1_CH0, dp.GPDMA1_CH1); + + // calculate first result using blocking mode + let cnt0 = defmt::unwrap!(cordic.blocking_calc_32bit(&input_q1_31[..2], &mut output_q1_31, false, false)); + + // calculate rest results using async mode + let cnt1 = defmt::unwrap!( + cordic + .async_calc_32bit( + &mut write_dma, + &mut read_dma, + &input_q1_31[2..], + &mut output_q1_31[cnt0..], + true, + false, + ) + .await + ); + + // all output value length should be the same as our output buffer size + defmt::assert_eq!(cnt0 + cnt1, output_q1_31.len()); + + let mut cordic_result_f64 = [0.0f64; OUTPUT_LENGTH]; + + for (f64_val, u32_val) in cordic_result_f64.iter_mut().zip(output_q1_31) { + *f64_val = utils::q1_31_to_f64(u32_val); + } + + // + // software calculation + // + + let mut software_result_f64 = [0.0f64; OUTPUT_LENGTH]; + + let arg2 = utils::q1_31_to_f64(input_q1_31[1]); + + for (&arg1, res) in input_q1_31 + .iter() + .enumerate() + .filter_map(|(idx, val)| if idx != 1 { Some(val) } else { None }) + .zip(software_result_f64.chunks_mut(2)) + { + let arg1 = utils::q1_31_to_f64(arg1); + + let (raw_res1, raw_res2) = (arg1 * core::f64::consts::PI).sin_cos(); + (res[0], res[1]) = (raw_res1 * arg2, raw_res2 * arg2); + } + + // + // check result are the same + // + + for (cordic_res, software_res) in cordic_result_f64[..cnt0 + cnt1] + .chunks(2) + .zip(software_result_f64.chunks(2)) + { + for (cord_res, soft_res) in cordic_res.iter().zip(software_res.iter()) { + // 2.0.powi(-19) is the max residual error for Sin function, in q1.31 format, with 24 iterations (aka PRECISION = 6) + defmt::assert!((cord_res - soft_res).abs() <= 2.0.powi(-19)); + } + } + + info!("Test OK"); + cortex_m::asm::bkpt(); +} diff --git a/tests/stm32/src/bin/cryp.rs b/tests/stm32/src/bin/cryp.rs new file mode 100644 index 000000000..028775ac8 --- /dev/null +++ b/tests/stm32/src/bin/cryp.rs @@ -0,0 +1,79 @@ +// required-features: cryp +#![no_std] +#![no_main] + +#[path = "../common.rs"] +mod common; + +use aes_gcm::aead::heapless::Vec; +use aes_gcm::aead::{AeadInPlace, KeyInit}; +use aes_gcm::Aes128Gcm; +use common::*; +use embassy_executor::Spawner; +use embassy_stm32::cryp::{self, *}; +use embassy_stm32::{bind_interrupts, peripherals}; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + CRYP => cryp::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p: embassy_stm32::Peripherals = init(); + + const PAYLOAD1: &[u8] = b"payload data 1 ;zdfhzdfhS;GKJASBDG;ASKDJBAL,zdfhzdfhzdfhzdfhvljhb,jhbjhb,sdhsdghsdhsfhsghzdfhzdfhzdfhzdfdhsdthsthsdhsgaadfhhgkdgfuoyguoft6783567"; + const PAYLOAD2: &[u8] = b"payload data 2 ;SKEzdfhzdfhzbhgvljhb,jhbjhb,sdhsdghsdhsfhsghshsfhshstsdthadfhsdfjhsfgjsfgjxfgjzdhgDFghSDGHjtfjtjszftjzsdtjhstdsdhsdhsdhsdhsdthsthsdhsgfh"; + const AAD1: &[u8] = b"additional data 1 stdargadrhaethaethjatjatjaetjartjstrjsfkk;'jopofyuisrteytweTASTUIKFUKIXTRDTEREharhaeryhaterjartjarthaethjrtjarthaetrhartjatejatrjsrtjartjyt1"; + const AAD2: &[u8] = b"additional data 2 stdhthsthsthsrthsrthsrtjdykjdukdyuldadfhsdghsdghsdghsadghjk'hioethjrtjarthaetrhartjatecfgjhzdfhgzdfhzdfghzdfhzdfhzfhjatrjsrtjartjytjfytjfyg"; + + let in_dma = peri!(p, CRYP_IN_DMA); + let out_dma = peri!(p, CRYP_OUT_DMA); + + let mut hw_cryp = Cryp::new(p.CRYP, in_dma, out_dma, Irqs); + let key: [u8; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + let mut ciphertext: [u8; PAYLOAD1.len() + PAYLOAD2.len()] = [0; PAYLOAD1.len() + PAYLOAD2.len()]; + let mut plaintext: [u8; PAYLOAD1.len() + PAYLOAD2.len()] = [0; PAYLOAD1.len() + PAYLOAD2.len()]; + let iv: [u8; 12] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; + + // Encrypt in hardware using AES-GCM 128-bit in blocking mode. + let aes_gcm = AesGcm::new(&key, &iv); + let mut gcm_encrypt = hw_cryp.start_blocking(&aes_gcm, Direction::Encrypt); + hw_cryp.aad_blocking(&mut gcm_encrypt, AAD1, false); + hw_cryp.aad_blocking(&mut gcm_encrypt, AAD2, true); + hw_cryp.payload_blocking(&mut gcm_encrypt, PAYLOAD1, &mut ciphertext[..PAYLOAD1.len()], false); + hw_cryp.payload_blocking(&mut gcm_encrypt, PAYLOAD2, &mut ciphertext[PAYLOAD1.len()..], true); + let encrypt_tag = hw_cryp.finish_blocking(gcm_encrypt); + + // Decrypt in hardware using AES-GCM 128-bit in async (DMA) mode. + let mut gcm_decrypt = hw_cryp.start(&aes_gcm, Direction::Decrypt).await; + hw_cryp.aad(&mut gcm_decrypt, AAD1, false).await; + hw_cryp.aad(&mut gcm_decrypt, AAD2, true).await; + hw_cryp + .payload(&mut gcm_decrypt, &ciphertext, &mut plaintext, true) + .await; + let decrypt_tag = hw_cryp.finish(gcm_decrypt).await; + + info!("AES-GCM Ciphertext: {:?}", ciphertext); + info!("AES-GCM Plaintext: {:?}", plaintext); + defmt::assert!(PAYLOAD1 == &plaintext[..PAYLOAD1.len()]); + defmt::assert!(PAYLOAD2 == &plaintext[PAYLOAD1.len()..]); + defmt::assert!(encrypt_tag == decrypt_tag); + + // Encrypt in software using AES-GCM 128-bit + let mut payload_vec: Vec = Vec::from_slice(&PAYLOAD1).unwrap(); + payload_vec.extend_from_slice(&PAYLOAD2).unwrap(); + let cipher = Aes128Gcm::new(&key.into()); + let mut aad: Vec = Vec::from_slice(&AAD1).unwrap(); + aad.extend_from_slice(&AAD2).unwrap(); + let _ = cipher.encrypt_in_place(&iv.into(), &aad, &mut payload_vec); + + defmt::assert!(ciphertext == payload_vec[0..ciphertext.len()]); + defmt::assert!(encrypt_tag == payload_vec[ciphertext.len()..ciphertext.len() + encrypt_tag.len()]); + + // Decrypt in software using AES-GCM 128-bit + let _ = cipher.decrypt_in_place(&iv.into(), &aad, &mut payload_vec); + + info!("Test OK"); + cortex_m::asm::bkpt(); +} diff --git a/tests/stm32/src/bin/dac.rs b/tests/stm32/src/bin/dac.rs index 9d64742df..88e661525 100644 --- a/tests/stm32/src/bin/dac.rs +++ b/tests/stm32/src/bin/dac.rs @@ -13,14 +13,14 @@ use embassy_executor::Spawner; use embassy_stm32::adc::Adc; use embassy_stm32::dac::{DacCh1, Value}; use embassy_stm32::dma::NoDma; -use embassy_time::{Delay, Timer}; +use embassy_time::Timer; use micromath::F32Ext; use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] async fn main(_spawner: Spawner) { // Initialize the board and obtain a Peripherals instance - let p: embassy_stm32::Peripherals = embassy_stm32::init(config()); + let p: embassy_stm32::Peripherals = init(); let adc = peri!(p, ADC); let dac = peri!(p, DAC); @@ -28,7 +28,7 @@ async fn main(_spawner: Spawner) { let mut adc_pin = unsafe { core::ptr::read(&dac_pin) }; let mut dac = DacCh1::new(dac, NoDma, dac_pin); - let mut adc = Adc::new(adc, &mut Delay); + let mut adc = Adc::new(adc); #[cfg(feature = "stm32h755zi")] let normalization_factor = 256; @@ -38,7 +38,7 @@ async fn main(_spawner: Spawner) { dac.set(Value::Bit8(0)); // Now wait a little to obtain a stable value Timer::after_millis(30).await; - let offset = adc.read(&mut adc_pin); + let offset = adc.blocking_read(&mut adc_pin); for v in 0..=255 { // First set the DAC output value @@ -49,7 +49,7 @@ async fn main(_spawner: Spawner) { Timer::after_millis(30).await; // Need to steal the peripherals here because PA4 is obviously in use already - let measured = adc.read(&mut unsafe { embassy_stm32::Peripherals::steal() }.PA4); + let measured = adc.blocking_read(&mut unsafe { embassy_stm32::Peripherals::steal() }.PA4); // Calibrate and normalize the measurement to get close to the dac_output_val let measured_normalized = ((measured as i32 - offset as i32) / normalization_factor) as i16; diff --git a/tests/stm32/src/bin/dac_l1.rs b/tests/stm32/src/bin/dac_l1.rs index f8b00aaef..925db617d 100644 --- a/tests/stm32/src/bin/dac_l1.rs +++ b/tests/stm32/src/bin/dac_l1.rs @@ -19,13 +19,13 @@ use micromath::F32Ext; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { - ADC1 => embassy_stm32::adc::InterruptHandler; + ADC1 => embassy_stm32::adc::InterruptHandler; }); #[embassy_executor::main] async fn main(_spawner: Spawner) { // Initialize the board and obtain a Peripherals instance - let p: embassy_stm32::Peripherals = embassy_stm32::init(config()); + let p: embassy_stm32::Peripherals = init(); let adc = peri!(p, ADC); let dac = peri!(p, DAC); diff --git a/tests/stm32/src/bin/eth.rs b/tests/stm32/src/bin/eth.rs index 7c02f0354..bf1922dde 100644 --- a/tests/stm32/src/bin/eth.rs +++ b/tests/stm32/src/bin/eth.rs @@ -6,7 +6,7 @@ mod common; use common::*; use embassy_executor::Spawner; -use embassy_net::{Stack, StackResources}; +use embassy_net::StackResources; use embassy_stm32::eth::generic_smi::GenericSMI; use embassy_stm32::eth::{Ethernet, PacketQueue}; use embassy_stm32::peripherals::ETH; @@ -32,13 +32,13 @@ bind_interrupts!(struct Irqs { type Device = Ethernet<'static, ETH, GenericSMI>; #[embassy_executor::task] -async fn net_task(stack: &'static Stack) -> ! { - stack.run().await +async fn net_task(mut runner: embassy_net::Runner<'static, Device>) -> ! { + runner.run().await } #[embassy_executor::main] async fn main(spawner: Spawner) { - let p = embassy_stm32::init(config()); + let p = init(); info!("Hello World!"); // Generate random seed. @@ -99,17 +99,11 @@ async fn main(spawner: Spawner) { //}); // Init network stack - static STACK: StaticCell> = StaticCell::new(); static RESOURCES: StaticCell> = StaticCell::new(); - let stack = &*STACK.init(Stack::new( - device, - config, - RESOURCES.init(StackResources::<2>::new()), - seed, - )); + let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed); // Launch network task - unwrap!(spawner.spawn(net_task(&stack))); + unwrap!(spawner.spawn(net_task(runner))); perf_client::run( stack, diff --git a/tests/stm32/src/bin/fdcan.rs b/tests/stm32/src/bin/fdcan.rs index 7363eaa16..83d7eca85 100644 --- a/tests/stm32/src/bin/fdcan.rs +++ b/tests/stm32/src/bin/fdcan.rs @@ -6,26 +6,38 @@ #[path = "../common.rs"] mod common; use common::*; -use defmt::assert; use embassy_executor::Spawner; use embassy_stm32::peripherals::*; use embassy_stm32::{bind_interrupts, can, Config}; -use embassy_time::{Duration, Instant}; +use embassy_time::Duration; use {defmt_rtt as _, panic_probe as _}; -bind_interrupts!(struct Irqs { +mod can_common; +use can_common::*; + +bind_interrupts!(struct Irqs2 { + FDCAN2_IT0 => can::IT0InterruptHandler; + FDCAN2_IT1 => can::IT1InterruptHandler; +}); +bind_interrupts!(struct Irqs1 { FDCAN1_IT0 => can::IT0InterruptHandler; FDCAN1_IT1 => can::IT1InterruptHandler; }); -struct TestOptions { - config: Config, - max_latency: Duration, - second_fifo_working: bool, +#[cfg(feature = "stm32h563zi")] +fn options() -> (Config, TestOptions) { + info!("H563 config"); + ( + config(), + TestOptions { + max_latency: Duration::from_micros(1200), + max_buffered: 3, + }, + ) } -#[cfg(any(feature = "stm32h755zi", feature = "stm32h753zi", feature = "stm32h563zi"))] -fn options() -> TestOptions { +#[cfg(any(feature = "stm32h755zi", feature = "stm32h753zi"))] +fn options() -> (Config, TestOptions) { use embassy_stm32::rcc; info!("H75 config"); let mut c = config(); @@ -33,16 +45,18 @@ fn options() -> TestOptions { freq: embassy_stm32::time::Hertz(25_000_000), mode: rcc::HseMode::Oscillator, }); - c.rcc.fdcan_clock_source = rcc::FdCanClockSource::HSE; - TestOptions { - config: c, - max_latency: Duration::from_micros(3800), - second_fifo_working: false, - } + c.rcc.mux.fdcansel = rcc::mux::Fdcansel::HSE; + ( + c, + TestOptions { + max_latency: Duration::from_micros(1200), + max_buffered: 3, + }, + ) } #[cfg(any(feature = "stm32h7a3zi"))] -fn options() -> TestOptions { +fn options() -> (Config, TestOptions) { use embassy_stm32::rcc; info!("H7a config"); let mut c = config(); @@ -50,193 +64,78 @@ fn options() -> TestOptions { freq: embassy_stm32::time::Hertz(25_000_000), mode: rcc::HseMode::Oscillator, }); - c.rcc.fdcan_clock_source = rcc::FdCanClockSource::HSE; - TestOptions { - config: c, - max_latency: Duration::from_micros(5500), - second_fifo_working: false, - } + c.rcc.mux.fdcansel = rcc::mux::Fdcansel::HSE; + ( + c, + TestOptions { + max_latency: Duration::from_micros(1200), + max_buffered: 3, + }, + ) +} + +#[cfg(any(feature = "stm32h7s3l8"))] +fn options() -> (Config, TestOptions) { + use embassy_stm32::rcc; + let mut c = config(); + c.rcc.mux.fdcansel = rcc::mux::Fdcansel::HSE; + ( + c, + TestOptions { + max_latency: Duration::from_micros(1200), + max_buffered: 3, + }, + ) } #[cfg(any(feature = "stm32g491re"))] -fn options() -> TestOptions { +fn options() -> (Config, TestOptions) { info!("G4 config"); - TestOptions { - config: config(), - max_latency: Duration::from_micros(500), - second_fifo_working: true, - } + ( + config(), + TestOptions { + max_latency: Duration::from_micros(500), + max_buffered: 6, + }, + ) } #[embassy_executor::main] async fn main(_spawner: Spawner) { - //let peripherals = embassy_stm32::init(config()); + //let peripherals = init(); - let options = options(); - let peripherals = embassy_stm32::init(options.config); + let (config, options) = options(); + let peripherals = init_with_config(config); - let mut can = can::Fdcan::new(peripherals.FDCAN1, peripherals.PB8, peripherals.PB9, Irqs); + let mut can = can::CanConfigurator::new(peripherals.FDCAN1, peripherals.PB8, peripherals.PB9, Irqs1); + let mut can2 = can::CanConfigurator::new(peripherals.FDCAN2, peripherals.PB12, peripherals.PB13, Irqs2); // 250k bps can.set_bitrate(250_000); + can2.set_bitrate(250_000); - can.can.set_extended_filter( + can.properties().set_extended_filter( + can::filter::ExtendedFilterSlot::_0, + can::filter::ExtendedFilter::accept_all_into_fifo1(), + ); + can2.properties().set_extended_filter( can::filter::ExtendedFilterSlot::_0, can::filter::ExtendedFilter::accept_all_into_fifo1(), ); let mut can = can.into_internal_loopback_mode(); + let mut can2 = can2.into_internal_loopback_mode(); + + run_can_tests(&mut can, &options).await; + run_can_tests(&mut can2, &options).await; info!("CAN Configured"); - let mut i: u8 = 0; - loop { - let tx_frame = can::TxFrame::new( - can::TxFrameHeader { - len: 1, - frame_format: can::FrameFormat::Standard, - id: can::StandardId::new(0x123).unwrap().into(), - bit_rate_switching: false, - marker: None, - }, - &[i], - ) - .unwrap(); - - info!("Transmitting frame..."); - let tx_ts = Instant::now(); - can.write(&tx_frame).await; - - let envelope = can.read().await.unwrap(); - info!("Frame received!"); - - // Check data. - assert!(i == envelope.data()[0], "{} == {}", i, envelope.data()[0]); - - info!("loopback time {}", envelope.header.time_stamp); - info!("loopback frame {=u8}", envelope.data()[0]); - let latency = envelope.timestamp.saturating_duration_since(tx_ts); - info!("loopback latency {} us", latency.as_micros()); - - // Theoretical minimum latency is 55us, actual is usually ~80us - const MIN_LATENCY: Duration = Duration::from_micros(50); - // Was failing at 150 but we are not getting a real time stamp. I'm not - // sure if there are other delays - assert!( - MIN_LATENCY <= latency && latency <= options.max_latency, - "{} <= {} <= {}", - MIN_LATENCY, - latency, - options.max_latency - ); - - i += 1; - if i > 10 { - break; - } - } - - let max_buffered = if options.second_fifo_working { 6 } else { 3 }; - - // Below here, check that we can receive from both FIFO0 and FIFO0 - // Above we configured FIFO1 for extended ID packets. There are only 3 slots - // in each FIFO so make sure we write enough to fill them both up before reading. - for i in 0..3 { - // Try filling up the RX FIFO0 buffers with standard packets - let tx_frame = can::TxFrame::new( - can::TxFrameHeader { - len: 1, - frame_format: can::FrameFormat::Standard, - id: can::StandardId::new(0x123).unwrap().into(), - bit_rate_switching: false, - marker: None, - }, - &[i], - ) - .unwrap(); - info!("Transmitting frame {}", i); - can.write(&tx_frame).await; - } - for i in 3..max_buffered { - // Try filling up the RX FIFO0 buffers with extended packets - let tx_frame = can::TxFrame::new( - can::TxFrameHeader { - len: 1, - frame_format: can::FrameFormat::Standard, - id: can::ExtendedId::new(0x1232344).unwrap().into(), - bit_rate_switching: false, - marker: None, - }, - &[i], - ) - .unwrap(); - - info!("Transmitting frame {}", i); - can.write(&tx_frame).await; - } - - // Try and receive all 6 packets - for i in 0..max_buffered { - let envelope = can.read().await.unwrap(); - match envelope.header.id { - can::Id::Extended(id) => { - info!("Extended received! {:x} {} {}", id.as_raw(), envelope.data()[0], i); - } - can::Id::Standard(id) => { - info!("Standard received! {:x} {} {}", id.as_raw(), envelope.data()[0], i); - } - } - } - // Test again with a split - let (mut tx, mut rx) = can.split(); - for i in 0..3 { - // Try filling up the RX FIFO0 buffers with standard packets - let tx_frame = can::TxFrame::new( - can::TxFrameHeader { - len: 1, - frame_format: can::FrameFormat::Standard, - id: can::StandardId::new(0x123).unwrap().into(), - bit_rate_switching: false, - marker: None, - }, - &[i], - ) - .unwrap(); - - info!("Transmitting frame {}", i); - tx.write(&tx_frame).await; - } - for i in 3..max_buffered { - // Try filling up the RX FIFO0 buffers with extended packets - let tx_frame = can::TxFrame::new( - can::TxFrameHeader { - len: 1, - frame_format: can::FrameFormat::Standard, - id: can::ExtendedId::new(0x1232344).unwrap().into(), - bit_rate_switching: false, - marker: None, - }, - &[i], - ) - .unwrap(); - - info!("Transmitting frame {}", i); - tx.write(&tx_frame).await; - } - - // Try and receive all 6 packets - for i in 0..max_buffered { - let envelope = rx.read().await.unwrap(); - match envelope.header.id { - can::Id::Extended(id) => { - info!("Extended received! {:x} {} {}", id.as_raw(), envelope.data()[0], i); - } - can::Id::Standard(id) => { - info!("Standard received! {:x} {} {}", id.as_raw(), envelope.data()[0], i); - } - } - } + let (mut tx, mut rx, _props) = can.split(); + let (mut tx2, mut rx2, _props) = can2.split(); + run_split_can_tests(&mut tx, &mut rx, &options).await; + run_split_can_tests(&mut tx2, &mut rx2, &options).await; info!("Test OK"); cortex_m::asm::bkpt(); diff --git a/tests/stm32/src/bin/gpio.rs b/tests/stm32/src/bin/gpio.rs index c4e2fe161..4a2584b4e 100644 --- a/tests/stm32/src/bin/gpio.rs +++ b/tests/stm32/src/bin/gpio.rs @@ -10,7 +10,7 @@ use embassy_stm32::gpio::{Flex, Input, Level, Output, OutputOpenDrain, Pull, Spe #[embassy_executor::main] async fn main(_spawner: Spawner) { - let p = embassy_stm32::init(config()); + let p = init(); info!("Hello World!"); // Arduino pins D0 and D1 @@ -112,7 +112,7 @@ async fn main(_spawner: Spawner) { let b = Input::new(&mut b, Pull::Down); // no pull, the status is undefined - let mut a = OutputOpenDrain::new(&mut a, Level::Low, Speed::Low, Pull::None); + let mut a = OutputOpenDrain::new(&mut a, Level::Low, Speed::Low); delay(); assert!(b.is_low()); a.set_high(); // High-Z output @@ -203,7 +203,7 @@ async fn main(_spawner: Spawner) { let mut a = Flex::new(&mut a); a.set_low(); - a.set_as_input_output(Speed::Low, Pull::None); + a.set_as_input_output(Speed::Low); delay(); assert!(b.is_low()); a.set_high(); // High-Z output @@ -216,7 +216,12 @@ async fn main(_spawner: Spawner) { } fn delay() { - #[cfg(any(feature = "stm32h755zi", feature = "stm32h753zi", feature = "stm32h7a3zi"))] + #[cfg(any( + feature = "stm32h755zi", + feature = "stm32h753zi", + feature = "stm32h7a3zi", + feature = "stm32h7s3l8" + ))] cortex_m::asm::delay(9000); cortex_m::asm::delay(1000); } diff --git a/tests/stm32/src/bin/hash.rs b/tests/stm32/src/bin/hash.rs new file mode 100644 index 000000000..bdb3c9a69 --- /dev/null +++ b/tests/stm32/src/bin/hash.rs @@ -0,0 +1,102 @@ +// required-features: hash +#![no_std] +#![no_main] + +#[path = "../common.rs"] +mod common; +use common::*; +use embassy_executor::Spawner; +use embassy_stm32::dma::NoDma; +use embassy_stm32::hash::*; +use embassy_stm32::{bind_interrupts, hash, peripherals}; +use hmac::{Hmac, Mac}; +use sha2::{Digest, Sha224, Sha256}; +use {defmt_rtt as _, panic_probe as _}; + +type HmacSha256 = Hmac; + +#[cfg(any(feature = "stm32l4a6zg", feature = "stm32h755zi", feature = "stm32h753zi"))] +bind_interrupts!(struct Irqs { + HASH_RNG => hash::InterruptHandler; +}); + +#[cfg(any( + feature = "stm32wba52cg", + feature = "stm32l552ze", + feature = "stm32h563zi", + feature = "stm32h503rb", + feature = "stm32u5a5zj", + feature = "stm32u585ai", + feature = "stm32h7s3l8" +))] +bind_interrupts!(struct Irqs { + HASH => hash::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p: embassy_stm32::Peripherals = init(); + let mut hw_hasher = Hash::new(p.HASH, NoDma, Irqs); + + let test_1: &[u8] = b"as;dfhaslfhas;oifvnasd;nifvnhasd;nifvhndlkfghsd;nvfnahssdfgsdafgsasdfasdfasdfasdfasdfghjklmnbvcalskdjghalskdjgfbaslkdjfgbalskdjgbalskdjbdfhsdfhsfghsfghfgh"; + let test_2: &[u8] = b"fdhalksdjfhlasdjkfhalskdjfhgal;skdjfgalskdhfjgalskdjfglafgadfgdfgdafgaadsfgfgdfgadrgsyfthxfgjfhklhjkfgukhulkvhlvhukgfhfsrghzdhxyfufynufyuszeradrtydyytserr"; + let test_3: &[u8] = b"a.ewtkluGWEBR.KAJRBTA,RMNRBG,FDMGB.kger.tkasjrbt.akrjtba.krjtba.ktmyna,nmbvtyliasd;gdrtba,sfvs.kgjzshd.gkbsr.tksejb.SDkfBSE.gkfgb>ESkfbSE>gkJSBESE>kbSE>fk"; + + // Start an SHA-256 digest. + let mut sha256context = hw_hasher.start(Algorithm::SHA256, DataType::Width8, None); + hw_hasher.update_blocking(&mut sha256context, test_1); + + // Interrupt the SHA-256 digest to compute an SHA-224 digest. + let mut sha224context = hw_hasher.start(Algorithm::SHA224, DataType::Width8, None); + hw_hasher.update_blocking(&mut sha224context, test_3); + let mut sha224_digest_buffer: [u8; 28] = [0; 28]; + let _ = hw_hasher.finish_blocking(sha224context, &mut sha224_digest_buffer); + + // Finish the SHA-256 digest. + hw_hasher.update_blocking(&mut sha256context, test_2); + let mut sha256_digest_buffer: [u8; 32] = [0; 32]; + let _ = hw_hasher.finish_blocking(sha256context, &mut sha256_digest_buffer); + + // Compute the SHA-256 digest in software. + let mut sw_sha256_hasher = Sha256::new(); + sw_sha256_hasher.update(test_1); + sw_sha256_hasher.update(test_2); + let sw_sha256_digest = sw_sha256_hasher.finalize(); + + //Compute the SHA-224 digest in software. + let mut sw_sha224_hasher = Sha224::new(); + sw_sha224_hasher.update(test_3); + let sw_sha224_digest = sw_sha224_hasher.finalize(); + + // Compare the SHA-256 digests. + info!("Hardware SHA-256 Digest: {:?}", sha256_digest_buffer); + info!("Software SHA-256 Digest: {:?}", sw_sha256_digest[..]); + defmt::assert!(sha256_digest_buffer == sw_sha256_digest[..]); + + // Compare the SHA-224 digests. + info!("Hardware SHA-256 Digest: {:?}", sha224_digest_buffer); + info!("Software SHA-256 Digest: {:?}", sw_sha224_digest[..]); + defmt::assert!(sha224_digest_buffer == sw_sha224_digest[..]); + + let hmac_key: [u8; 64] = [0x55; 64]; + + // Compute HMAC in hardware. + let mut sha256hmac_context = hw_hasher.start(Algorithm::SHA256, DataType::Width8, Some(&hmac_key)); + hw_hasher.update_blocking(&mut sha256hmac_context, test_1); + hw_hasher.update_blocking(&mut sha256hmac_context, test_2); + let mut hw_hmac: [u8; 32] = [0; 32]; + hw_hasher.finish_blocking(sha256hmac_context, &mut hw_hmac); + + // Compute HMAC in software. + let mut sw_mac = HmacSha256::new_from_slice(&hmac_key).unwrap(); + sw_mac.update(test_1); + sw_mac.update(test_2); + let sw_hmac = sw_mac.finalize().into_bytes(); + + info!("Hardware HMAC: {:?}", hw_hmac); + info!("Software HMAC: {:?}", sw_hmac[..]); + defmt::assert!(hw_hmac == sw_hmac[..]); + + info!("Test OK"); + cortex_m::asm::bkpt(); +} diff --git a/tests/stm32/src/bin/rng.rs b/tests/stm32/src/bin/rng.rs index 7f2023d4d..8438353a8 100644 --- a/tests/stm32/src/bin/rng.rs +++ b/tests/stm32/src/bin/rng.rs @@ -23,12 +23,17 @@ bind_interrupts!(struct Irqs { bind_interrupts!(struct Irqs { RNG_LPUART1 => rng::InterruptHandler; }); +#[cfg(any(feature = "stm32u083rc"))] +bind_interrupts!(struct Irqs { + RNG_CRYP => rng::InterruptHandler; +}); #[cfg(not(any( feature = "stm32l4a6zg", feature = "stm32l073rz", feature = "stm32h755zi", feature = "stm32h753zi", - feature = "stm32f429zi" + feature = "stm32f429zi", + feature = "stm32u083rc" )))] bind_interrupts!(struct Irqs { RNG => rng::InterruptHandler; @@ -36,7 +41,7 @@ bind_interrupts!(struct Irqs { #[embassy_executor::main] async fn main(_spawner: Spawner) { - let p: embassy_stm32::Peripherals = embassy_stm32::init(config()); + let p: embassy_stm32::Peripherals = init(); let mut rng = Rng::new(p.RNG, Irqs); diff --git a/tests/stm32/src/bin/rtc.rs b/tests/stm32/src/bin/rtc.rs index c04d616ac..5fe98d807 100644 --- a/tests/stm32/src/bin/rtc.rs +++ b/tests/stm32/src/bin/rtc.rs @@ -18,7 +18,7 @@ async fn main(_spawner: Spawner) { let mut config = config(); config.rcc.ls = LsConfig::default_lse(); - let p = embassy_stm32::init(config); + let p = init_with_config(config); info!("Hello World!"); let now = NaiveDate::from_ymd_opt(2020, 5, 15) diff --git a/tests/stm32/src/bin/sdmmc.rs b/tests/stm32/src/bin/sdmmc.rs index 54f55d2d6..a6bc117c0 100644 --- a/tests/stm32/src/bin/sdmmc.rs +++ b/tests/stm32/src/bin/sdmmc.rs @@ -20,7 +20,7 @@ bind_interrupts!(struct Irqs { async fn main(_spawner: Spawner) { info!("Hello World!"); - let p = embassy_stm32::init(config()); + let p = init(); let (mut sdmmc, mut dma, mut clk, mut cmd, mut d0, mut d1, mut d2, mut d3) = (p.SDIO, p.DMA2_CH3, p.PC12, p.PD2, p.PC8, p.PC9, p.PC10, p.PC11); diff --git a/tests/stm32/src/bin/spi.rs b/tests/stm32/src/bin/spi.rs index b0bdd477f..9712a8c5a 100644 --- a/tests/stm32/src/bin/spi.rs +++ b/tests/stm32/src/bin/spi.rs @@ -6,35 +6,84 @@ mod common; use common::*; use defmt::assert_eq; use embassy_executor::Spawner; -use embassy_stm32::dma::NoDma; -use embassy_stm32::spi::{self, Spi}; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::mode::Blocking; +use embassy_stm32::spi::{self, Spi, Word}; use embassy_stm32::time::Hertz; #[embassy_executor::main] async fn main(_spawner: Spawner) { - let p = embassy_stm32::init(config()); + let p = init(); info!("Hello World!"); - let spi = peri!(p, SPI); - let sck = peri!(p, SPI_SCK); - let mosi = peri!(p, SPI_MOSI); - let miso = peri!(p, SPI_MISO); + let mut spi_peri = peri!(p, SPI); + let mut sck = peri!(p, SPI_SCK); + let mut mosi = peri!(p, SPI_MOSI); + let mut miso = peri!(p, SPI_MISO); let mut spi_config = spi::Config::default(); spi_config.frequency = Hertz(1_000_000); - let mut spi = Spi::new( - spi, sck, // Arduino D13 - mosi, // Arduino D11 - miso, // Arduino D12 - NoDma, NoDma, spi_config, + let mut spi = Spi::new_blocking( + &mut spi_peri, + &mut sck, // Arduino D13 + &mut mosi, // Arduino D11 + &mut miso, // Arduino D12 + spi_config, ); - let data: [u8; 9] = [0x00, 0xFF, 0xAA, 0x55, 0xC0, 0xFF, 0xEE, 0xC0, 0xDE]; + test_txrx::(&mut spi); + test_txrx::(&mut spi); + + // Assert the RCC bit gets disabled on drop. + #[cfg(feature = "stm32f429zi")] + defmt::assert!(embassy_stm32::pac::RCC.apb2enr().read().spi1en()); + drop(spi); + #[cfg(feature = "stm32f429zi")] + defmt::assert!(!embassy_stm32::pac::RCC.apb2enr().read().spi1en()); + + // test rx-only configuration + let mut spi = Spi::new_blocking_rxonly(&mut spi_peri, &mut sck, &mut miso, spi_config); + let mut mosi_out = Output::new(&mut mosi, Level::Low, Speed::VeryHigh); + + test_rx::(&mut spi, &mut mosi_out); + test_rx::(&mut spi, &mut mosi_out); + drop(spi); + drop(mosi_out); + + let mut spi = Spi::new_blocking_txonly(&mut spi_peri, &mut sck, &mut mosi, spi_config); + test_tx::(&mut spi); + test_tx::(&mut spi); + drop(spi); + + let mut spi = Spi::new_blocking_txonly_nosck(&mut spi_peri, &mut mosi, spi_config); + test_tx::(&mut spi); + test_tx::(&mut spi); + drop(spi); + + info!("Test OK"); + cortex_m::asm::bkpt(); +} + +fn test_txrx + defmt::Format + Eq>(spi: &mut Spi<'_, Blocking>) +where + W: core::ops::Not, +{ + let data: [W; 9] = [ + 0x00u8.into(), + 0xFFu8.into(), + 0xAAu8.into(), + 0x55u8.into(), + 0xC0u8.into(), + 0xFFu8.into(), + 0xEEu8.into(), + 0xC0u8.into(), + 0xDEu8.into(), + ]; // Arduino pins D11 and D12 (MOSI-MISO) are connected together with a 1K resistor. // so we should get the data we sent back. - let mut buf = [0; 9]; + let mut buf = [W::default(); 9]; spi.blocking_transfer(&mut buf, &data).unwrap(); assert_eq!(buf, data); @@ -58,7 +107,33 @@ async fn main(_spawner: Spawner) { spi.blocking_transfer_in_place::(&mut []).unwrap(); spi.blocking_read::(&mut []).unwrap(); spi.blocking_write::(&[]).unwrap(); - - info!("Test OK"); - cortex_m::asm::bkpt(); +} + +fn test_rx + defmt::Format + Eq>(spi: &mut Spi<'_, Blocking>, mosi_out: &mut Output<'_>) +where + W: core::ops::Not, +{ + let mut buf = [W::default(); 9]; + + mosi_out.set_high(); + spi.blocking_read(&mut buf).unwrap(); + assert_eq!(buf, [!W::default(); 9]); + mosi_out.set_low(); + spi.blocking_read(&mut buf).unwrap(); + assert_eq!(buf, [W::default(); 9]); + spi.blocking_read::(&mut []).unwrap(); + spi.blocking_read::(&mut []).unwrap(); +} + +fn test_tx + defmt::Format + Eq>(spi: &mut Spi<'_, Blocking>) +where + W: core::ops::Not, +{ + let buf = [W::default(); 9]; + + // Test tx-only. Just check it doesn't hang, not much else we can do without using SPI slave. + spi.blocking_write(&buf).unwrap(); + spi.blocking_write::(&[]).unwrap(); + spi.blocking_write(&buf).unwrap(); + spi.blocking_write::(&[]).unwrap(); } diff --git a/tests/stm32/src/bin/spi_dma.rs b/tests/stm32/src/bin/spi_dma.rs index 5d46726dd..307409a16 100644 --- a/tests/stm32/src/bin/spi_dma.rs +++ b/tests/stm32/src/bin/spi_dma.rs @@ -6,36 +6,91 @@ mod common; use common::*; use defmt::assert_eq; use embassy_executor::Spawner; -use embassy_stm32::spi::{self, Spi}; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::mode::Async; +use embassy_stm32::spi::{self, Spi, Word}; use embassy_stm32::time::Hertz; #[embassy_executor::main] async fn main(_spawner: Spawner) { - let p = embassy_stm32::init(config()); + let p = init(); info!("Hello World!"); - let spi = peri!(p, SPI); - let sck = peri!(p, SPI_SCK); - let mosi = peri!(p, SPI_MOSI); - let miso = peri!(p, SPI_MISO); - let tx_dma = peri!(p, SPI_TX_DMA); - let rx_dma = peri!(p, SPI_RX_DMA); + let mut spi_peri = peri!(p, SPI); + let mut sck = peri!(p, SPI_SCK); + let mut mosi = peri!(p, SPI_MOSI); + let mut miso = peri!(p, SPI_MISO); + let mut tx_dma = peri!(p, SPI_TX_DMA); + let mut rx_dma = peri!(p, SPI_RX_DMA); let mut spi_config = spi::Config::default(); spi_config.frequency = Hertz(1_000_000); let mut spi = Spi::new( - spi, sck, // Arduino D13 - mosi, // Arduino D11 - miso, // Arduino D12 - tx_dma, rx_dma, spi_config, + &mut spi_peri, + &mut sck, // Arduino D13 + &mut mosi, // Arduino D11 + &mut miso, // Arduino D12 + &mut tx_dma, + &mut rx_dma, + spi_config, ); - let data: [u8; 9] = [0x00, 0xFF, 0xAA, 0x55, 0xC0, 0xFF, 0xEE, 0xC0, 0xDE]; + test_txrx::(&mut spi).await; + test_txrx::(&mut spi).await; + drop(spi); + + // test rx-only configuration + let mut spi = Spi::new_rxonly( + &mut spi_peri, + &mut sck, + &mut miso, + // SPIv1/f1 requires txdma even if rxonly. + #[cfg(not(feature = "spi-v345"))] + &mut tx_dma, + &mut rx_dma, + spi_config, + ); + let mut mosi_out = Output::new(&mut mosi, Level::Low, Speed::VeryHigh); + + test_rx::(&mut spi, &mut mosi_out).await; + test_rx::(&mut spi, &mut mosi_out).await; + drop(spi); + drop(mosi_out); + + let mut spi = Spi::new_txonly(&mut spi_peri, &mut sck, &mut mosi, &mut tx_dma, spi_config); + test_tx::(&mut spi).await; + test_tx::(&mut spi).await; + drop(spi); + + let mut spi = Spi::new_txonly_nosck(&mut spi_peri, &mut mosi, &mut tx_dma, spi_config); + test_tx::(&mut spi).await; + test_tx::(&mut spi).await; + drop(spi); + + info!("Test OK"); + cortex_m::asm::bkpt(); +} + +async fn test_txrx + defmt::Format + Eq>(spi: &mut Spi<'_, Async>) +where + W: core::ops::Not, +{ + let data: [W; 9] = [ + 0x00u8.into(), + 0xFFu8.into(), + 0xAAu8.into(), + 0x55u8.into(), + 0xC0u8.into(), + 0xFFu8.into(), + 0xEEu8.into(), + 0xC0u8.into(), + 0xDEu8.into(), + ]; // Arduino pins D11 and D12 (MOSI-MISO) are connected together with a 1K resistor. // so we should get the data we sent back. - let mut buf = [0; 9]; + let mut buf = [W::default(); 9]; spi.transfer(&mut buf, &data).await.unwrap(); assert_eq!(buf, data); @@ -59,8 +114,12 @@ async fn main(_spawner: Spawner) { spi.transfer_in_place::(&mut []).await.unwrap(); spi.read::(&mut []).await.unwrap(); spi.write::(&[]).await.unwrap(); + spi.blocking_transfer::(&mut [], &[]).unwrap(); + spi.blocking_transfer_in_place::(&mut []).unwrap(); + spi.blocking_read::(&mut []).unwrap(); + spi.blocking_write::(&[]).unwrap(); - // === Check mixing blocking with async. + // Check mixing blocking with async. spi.blocking_transfer(&mut buf, &data).unwrap(); assert_eq!(buf, data); spi.transfer(&mut buf, &data).await.unwrap(); @@ -75,7 +134,47 @@ async fn main(_spawner: Spawner) { spi.blocking_write(&buf).unwrap(); spi.blocking_read(&mut buf).unwrap(); spi.write(&buf).await.unwrap(); - - info!("Test OK"); - cortex_m::asm::bkpt(); +} + +async fn test_rx + defmt::Format + Eq>(spi: &mut Spi<'_, Async>, mosi_out: &mut Output<'_>) +where + W: core::ops::Not, +{ + let mut buf = [W::default(); 9]; + + mosi_out.set_high(); + spi.read(&mut buf).await.unwrap(); + assert_eq!(buf, [!W::default(); 9]); + spi.blocking_read(&mut buf).unwrap(); + assert_eq!(buf, [!W::default(); 9]); + spi.read(&mut buf).await.unwrap(); + assert_eq!(buf, [!W::default(); 9]); + spi.read(&mut buf).await.unwrap(); + assert_eq!(buf, [!W::default(); 9]); + spi.blocking_read(&mut buf).unwrap(); + assert_eq!(buf, [!W::default(); 9]); + spi.blocking_read(&mut buf).unwrap(); + assert_eq!(buf, [!W::default(); 9]); + mosi_out.set_low(); + spi.read(&mut buf).await.unwrap(); + assert_eq!(buf, [W::default(); 9]); + spi.read::(&mut []).await.unwrap(); + spi.blocking_read::(&mut []).unwrap(); +} + +async fn test_tx + defmt::Format + Eq>(spi: &mut Spi<'_, Async>) +where + W: core::ops::Not, +{ + let buf = [W::default(); 9]; + + // Test tx-only. Just check it doesn't hang, not much else we can do without using SPI slave. + spi.blocking_write(&buf).unwrap(); + spi.write(&buf).await.unwrap(); + spi.blocking_write(&buf).unwrap(); + spi.blocking_write(&buf).unwrap(); + spi.write(&buf).await.unwrap(); + spi.write(&buf).await.unwrap(); + spi.write::(&[]).await.unwrap(); + spi.blocking_write::(&[]).unwrap(); } diff --git a/tests/stm32/src/bin/stop.rs b/tests/stm32/src/bin/stop.rs index 000296d46..772bc527c 100644 --- a/tests/stm32/src/bin/stop.rs +++ b/tests/stm32/src/bin/stop.rs @@ -51,7 +51,14 @@ async fn async_main(spawner: Spawner) { let mut config = Config::default(); config.rcc.ls = LsConfig::default_lse(); - let p = embassy_stm32::init(config); + // System Clock seems cannot be greater than 16 MHz + #[cfg(any(feature = "stm32h563zi", feature = "stm32h503rb"))] + { + use embassy_stm32::rcc::HSIPrescaler; + config.rcc.hsi = Some(HSIPrescaler::DIV4); // 64 MHz HSI will need a /4 + } + + let p = init_with_config(config); info!("Hello World!"); let now = NaiveDate::from_ymd_opt(2020, 5, 15) diff --git a/tests/stm32/src/bin/timer.rs b/tests/stm32/src/bin/timer.rs index d86f54ad2..8719e7670 100644 --- a/tests/stm32/src/bin/timer.rs +++ b/tests/stm32/src/bin/timer.rs @@ -10,7 +10,7 @@ use embassy_time::{Instant, Timer}; #[embassy_executor::main] async fn main(_spawner: Spawner) { - let _p = embassy_stm32::init(config()); + let _p = init(); info!("Hello World!"); let start = Instant::now(); diff --git a/tests/stm32/src/bin/ucpd.rs b/tests/stm32/src/bin/ucpd.rs new file mode 100644 index 000000000..bd7b35d6b --- /dev/null +++ b/tests/stm32/src/bin/ucpd.rs @@ -0,0 +1,120 @@ +// required-features: ucpd +#![no_std] +#![no_main] +#[path = "../common.rs"] +mod common; + +use common::*; +use defmt::{assert, assert_eq}; +use embassy_executor::Spawner; +use embassy_futures::join::join; +use embassy_stm32::ucpd::{self, CcPhy, CcPull, CcSel, CcVState, RxError, Ucpd}; +use embassy_stm32::{bind_interrupts, peripherals}; +use embassy_time::Timer; + +bind_interrupts!(struct Irqs { + UCPD1_2 => ucpd::InterruptHandler, ucpd::InterruptHandler; +}); + +static SRC_TO_SNK: [u8; 6] = [0, 1, 2, 3, 4, 5]; +static SNK_TO_SRC: [u8; 4] = [9, 8, 7, 6]; + +async fn wait_for_vstate(cc_phy: &mut CcPhy<'_, T>, vstate: CcVState) { + let (mut cc1, mut _cc2) = cc_phy.vstate(); + while cc1 != vstate { + (cc1, _cc2) = cc_phy.wait_for_vstate_change().await; + } +} + +async fn source( + mut ucpd: Ucpd<'static, peripherals::UCPD1>, + rx_dma: peripherals::DMA1_CH1, + tx_dma: peripherals::DMA1_CH2, +) { + debug!("source: setting default current pull-up"); + ucpd.cc_phy().set_pull(CcPull::SourceDefaultUsb); + + // Wait for default sink. + debug!("source: wait for sink"); + wait_for_vstate(ucpd.cc_phy(), CcVState::LOW).await; + + // Advertise a higher current by changing the pull-up resistor. + debug!("source: sink detected, setting 3.0A current pull-up"); + ucpd.cc_phy().set_pull(CcPull::Source3_0A); + + let (_, mut pd_phy) = ucpd.split_pd_phy(rx_dma, tx_dma, CcSel::CC1); + + // Listen for an incoming message + debug!("source: wait for message from sink"); + let mut snk_to_src_buf = [0_u8; 30]; + let n = unwrap!(pd_phy.receive(snk_to_src_buf.as_mut()).await); + assert_eq!(n, SNK_TO_SRC.len()); + assert_eq!(&snk_to_src_buf[..n], SNK_TO_SRC.as_slice()); + + // Send message + debug!("source: message received, sending message"); + unwrap!(pd_phy.transmit(SRC_TO_SNK.as_slice()).await); + + // Wait for hard-reset + debug!("source: message sent, waiting for hard-reset"); + assert!(matches!( + pd_phy.receive(snk_to_src_buf.as_mut()).await, + Err(RxError::HardReset) + )); +} + +async fn sink( + mut ucpd: Ucpd<'static, peripherals::UCPD2>, + rx_dma: peripherals::DMA1_CH3, + tx_dma: peripherals::DMA1_CH4, +) { + debug!("sink: setting pull down"); + ucpd.cc_phy().set_pull(CcPull::Sink); + + // Wait for default source. + debug!("sink: waiting for default vstate"); + wait_for_vstate(ucpd.cc_phy(), CcVState::LOW).await; + + // Wait higher current pull-up. + //debug!("sink: source default vstate detected, waiting for 3.0A vstate"); + //wait_for_vstate(ucpd.cc_phy(), CcVState::HIGHEST).await; + //debug!("sink: source 3.0A vstate detected"); + // TODO: not working yet, why? no idea, replace with timer for now + Timer::after_millis(100).await; + + let (_, mut pd_phy) = ucpd.split_pd_phy(rx_dma, tx_dma, CcSel::CC1); + + // Send message + debug!("sink: sending message"); + unwrap!(pd_phy.transmit(SNK_TO_SRC.as_slice()).await); + + // Listen for an incoming message + debug!("sink: message sent, waiting for message from source"); + let mut src_to_snk_buf = [0_u8; 30]; + let n = unwrap!(pd_phy.receive(src_to_snk_buf.as_mut()).await); + assert_eq!(n, SRC_TO_SNK.len()); + assert_eq!(&src_to_snk_buf[..n], SRC_TO_SNK.as_slice()); + + // Send hard reset + debug!("sink: message received, sending hard-reset"); + unwrap!(pd_phy.transmit_hardreset().await); +} + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = init(); + info!("Hello World!"); + + // Wire between PD0 and PA8 + let ucpd1 = Ucpd::new(p.UCPD1, Irqs {}, p.PA8, p.PB15, Default::default()); + let ucpd2 = Ucpd::new(p.UCPD2, Irqs {}, p.PD0, p.PD2, Default::default()); + + join( + source(ucpd1, p.DMA1_CH1, p.DMA1_CH2), + sink(ucpd2, p.DMA1_CH3, p.DMA1_CH4), + ) + .await; + + info!("Test OK"); + cortex_m::asm::bkpt(); +} diff --git a/tests/stm32/src/bin/usart.rs b/tests/stm32/src/bin/usart.rs index 9b20eb784..2f601ad0e 100644 --- a/tests/stm32/src/bin/usart.rs +++ b/tests/stm32/src/bin/usart.rs @@ -6,13 +6,12 @@ mod common; use common::*; use defmt::{assert, assert_eq, unreachable}; use embassy_executor::Spawner; -use embassy_stm32::dma::NoDma; use embassy_stm32::usart::{Config, ConfigError, Error, Uart}; use embassy_time::{block_for, Duration, Instant}; #[embassy_executor::main] async fn main(_spawner: Spawner) { - let p = embassy_stm32::init(config()); + let p = init(); info!("Hello World!"); // Arduino pins D0 and D1 @@ -20,11 +19,10 @@ async fn main(_spawner: Spawner) { let mut usart = peri!(p, UART); let mut rx = peri!(p, UART_RX); let mut tx = peri!(p, UART_TX); - let irq = irqs!(UART); { let config = Config::default(); - let mut usart = Uart::new(&mut usart, &mut rx, &mut tx, irq, NoDma, NoDma, config).unwrap(); + let mut usart = Uart::new_blocking(&mut usart, &mut rx, &mut tx, config).unwrap(); // We can't send too many bytes, they have to fit in the FIFO. // This is because we aren't sending+receiving at the same time. @@ -35,12 +33,19 @@ async fn main(_spawner: Spawner) { let mut buf = [0; 2]; usart.blocking_read(&mut buf).unwrap(); assert_eq!(buf, data); + + // Test flush doesn't hang. + usart.blocking_write(&data).unwrap(); + usart.blocking_flush().unwrap(); + + // Test flush doesn't hang if there's nothing to flush + usart.blocking_flush().unwrap(); } // Test error handling with with an overflow error { let config = Config::default(); - let mut usart = Uart::new(&mut usart, &mut rx, &mut tx, irq, NoDma, NoDma, config).unwrap(); + let mut usart = Uart::new_blocking(&mut usart, &mut rx, &mut tx, config).unwrap(); // Send enough bytes to fill the RX FIFOs off all USART versions. let data = [0; 64]; @@ -70,7 +75,7 @@ async fn main(_spawner: Spawner) { let mut config = Config::default(); config.baudrate = baudrate; - let mut usart = match Uart::new(&mut usart, &mut rx, &mut tx, irq, NoDma, NoDma, config) { + let mut usart = match Uart::new_blocking(&mut usart, &mut rx, &mut tx, config) { Ok(x) => x, Err(ConfigError::BaudrateTooHigh) => { info!("baudrate too high"); diff --git a/tests/stm32/src/bin/usart_dma.rs b/tests/stm32/src/bin/usart_dma.rs index 24e2b2896..a34498376 100644 --- a/tests/stm32/src/bin/usart_dma.rs +++ b/tests/stm32/src/bin/usart_dma.rs @@ -11,7 +11,7 @@ use embassy_stm32::usart::{Config, Uart}; #[embassy_executor::main] async fn main(_spawner: Spawner) { - let p = embassy_stm32::init(config()); + let p = init(); info!("Hello World!"); // Arduino pins D0 and D1 @@ -51,6 +51,23 @@ async fn main(_spawner: Spawner) { assert_eq!(tx_buf, rx_buf); } + // Test flush doesn't hang. Check multiple combinations of async+blocking. + tx.write(&tx_buf).await.unwrap(); + tx.flush().await.unwrap(); + tx.flush().await.unwrap(); + + tx.write(&tx_buf).await.unwrap(); + tx.blocking_flush().unwrap(); + tx.flush().await.unwrap(); + + tx.blocking_write(&tx_buf).unwrap(); + tx.blocking_flush().unwrap(); + tx.flush().await.unwrap(); + + tx.blocking_write(&tx_buf).unwrap(); + tx.flush().await.unwrap(); + tx.blocking_flush().unwrap(); + info!("Test OK"); cortex_m::asm::bkpt(); } diff --git a/tests/stm32/src/bin/usart_rx_ringbuffered.rs b/tests/stm32/src/bin/usart_rx_ringbuffered.rs index f5d618db4..83c0887ac 100644 --- a/tests/stm32/src/bin/usart_rx_ringbuffered.rs +++ b/tests/stm32/src/bin/usart_rx_ringbuffered.rs @@ -8,6 +8,7 @@ mod common; use common::*; use defmt::{assert_eq, panic}; use embassy_executor::Spawner; +use embassy_stm32::mode::Async; use embassy_stm32::usart::{Config, DataBits, Parity, RingBufferedUartRx, StopBits, Uart, UartTx}; use embassy_time::Timer; use rand_chacha::ChaCha8Rng; @@ -17,7 +18,7 @@ const DMA_BUF_SIZE: usize = 256; #[embassy_executor::main] async fn main(spawner: Spawner) { - let p = embassy_stm32::init(config()); + let p = init(); info!("Hello World!"); // Arduino pins D0 and D1 @@ -42,8 +43,7 @@ async fn main(spawner: Spawner) { let usart = Uart::new(usart, rx, tx, irq, tx_dma, rx_dma, config).unwrap(); let (tx, rx) = usart.split(); static mut DMA_BUF: [u8; DMA_BUF_SIZE] = [0; DMA_BUF_SIZE]; - let dma_buf = unsafe { DMA_BUF.as_mut() }; - let rx = rx.into_ring_buffered(dma_buf); + let rx = rx.into_ring_buffered(unsafe { &mut *core::ptr::addr_of_mut!(DMA_BUF) }); info!("Spawning tasks"); spawner.spawn(transmit_task(tx)).unwrap(); @@ -51,7 +51,7 @@ async fn main(spawner: Spawner) { } #[embassy_executor::task] -async fn transmit_task(mut tx: UartTx<'static, peris::UART, peris::UART_TX_DMA>) { +async fn transmit_task(mut tx: UartTx<'static, Async>) { // workaround https://github.com/embassy-rs/embassy/issues/1426 Timer::after_millis(100).await; @@ -74,7 +74,7 @@ async fn transmit_task(mut tx: UartTx<'static, peris::UART, peris::UART_TX_DMA>) } #[embassy_executor::task] -async fn receive_task(mut rx: RingBufferedUartRx<'static, peris::UART, peris::UART_RX_DMA>) { +async fn receive_task(mut rx: RingBufferedUartRx<'static>) { info!("Ready to receive..."); let mut rng = ChaCha8Rng::seed_from_u64(1337); diff --git a/tests/stm32/src/bin/wpan_ble.rs b/tests/stm32/src/bin/wpan_ble.rs index 82a540d45..fde1dfa9b 100644 --- a/tests/stm32/src/bin/wpan_ble.rs +++ b/tests/stm32/src/bin/wpan_ble.rs @@ -41,7 +41,7 @@ async fn main(spawner: Spawner) { let mut config = config(); config.rcc = WPAN_DEFAULT; - let p = embassy_stm32::init(config); + let p = init_with_config(config); info!("Hello World!"); let config = Config::default(); diff --git a/tests/stm32/src/bin/wpan_mac.rs b/tests/stm32/src/bin/wpan_mac.rs index fe53b8786..b65ace40f 100644 --- a/tests/stm32/src/bin/wpan_mac.rs +++ b/tests/stm32/src/bin/wpan_mac.rs @@ -34,7 +34,7 @@ async fn main(spawner: Spawner) { let mut config = config(); config.rcc = WPAN_DEFAULT; - let p = embassy_stm32::init(config); + let p = init_with_config(config); info!("Hello World!"); let config = Config::default(); diff --git a/tests/stm32/src/common.rs b/tests/stm32/src/common.rs index fefe72c86..935a41ed2 100644 --- a/tests/stm32/src/common.rs +++ b/tests/stm32/src/common.rs @@ -2,6 +2,8 @@ pub use defmt::*; #[allow(unused)] +use embassy_stm32::rcc::*; +#[allow(unused)] use embassy_stm32::time::Hertz; use embassy_stm32::Config; use {defmt_rtt as _, panic_probe as _}; @@ -54,6 +56,14 @@ teleprobe_meta::target!(b"nucleo-stm32l496zg"); teleprobe_meta::target!(b"nucleo-stm32wl55jc"); #[cfg(feature = "stm32wba52cg")] teleprobe_meta::target!(b"nucleo-stm32wba52cg"); +#[cfg(feature = "stm32f091rc")] +teleprobe_meta::target!(b"nucleo-stm32f091rc"); +#[cfg(feature = "stm32h503rb")] +teleprobe_meta::target!(b"nucleo-stm32h503rb"); +#[cfg(feature = "stm32h7s3l8")] +teleprobe_meta::target!(b"nucleo-stm32h7s3l8"); +#[cfg(feature = "stm32u083rc")] +teleprobe_meta::target!(b"nucleo-stm32u083rc"); macro_rules! define_peris { ($($name:ident = $peri:ident,)* $(@irq $irq_name:ident = $irq_code:tt,)*) => { @@ -85,6 +95,12 @@ macro_rules! define_peris { }; } +#[cfg(feature = "stm32f091rc")] +define_peris!( + UART = USART1, UART_TX = PA9, UART_RX = PA10, UART_TX_DMA = DMA1_CH4, UART_RX_DMA = DMA1_CH5, + SPI = SPI1, SPI_SCK = PA5, SPI_MOSI = PA7, SPI_MISO = PA6, SPI_TX_DMA = DMA1_CH3, SPI_RX_DMA = DMA1_CH2, + @irq UART = {USART1 => embassy_stm32::usart::InterruptHandler;}, +); #[cfg(feature = "stm32f103c8")] define_peris!( UART = USART1, UART_TX = PA9, UART_RX = PA10, UART_TX_DMA = DMA1_CH4, UART_RX_DMA = DMA1_CH5, @@ -108,7 +124,7 @@ define_peris!( define_peris!( UART = USART6, UART_TX = PG14, UART_RX = PG9, UART_TX_DMA = DMA2_CH6, UART_RX_DMA = DMA2_CH1, SPI = SPI1, SPI_SCK = PA5, SPI_MOSI = PA7, SPI_MISO = PA6, SPI_TX_DMA = DMA2_CH3, SPI_RX_DMA = DMA2_CH2, - ADC = ADC1, DAC = DAC, DAC_PIN = PA4, + ADC = ADC1, DAC = DAC1, DAC_PIN = PA4, CAN = CAN1, CAN_RX = PD0, CAN_TX = PD1, @irq UART = {USART6 => embassy_stm32::usart::InterruptHandler;}, ); @@ -116,7 +132,7 @@ define_peris!( define_peris!( UART = USART1, UART_TX = PA9, UART_RX = PA10, UART_TX_DMA = DMA2_CH7, UART_RX_DMA = DMA2_CH5, SPI = SPI1, SPI_SCK = PA5, SPI_MOSI = PA7, SPI_MISO = PA6, SPI_TX_DMA = DMA2_CH3, SPI_RX_DMA = DMA2_CH2, - ADC = ADC1, DAC = DAC, DAC_PIN = PA4, + ADC = ADC1, DAC = DAC1, DAC_PIN = PA4, CAN = CAN1, CAN_RX = PA11, CAN_TX = PA12, @irq UART = {USART1 => embassy_stm32::usart::InterruptHandler;}, ); @@ -128,6 +144,7 @@ define_peris!( ); #[cfg(any(feature = "stm32h755zi", feature = "stm32h753zi"))] define_peris!( + CRYP_IN_DMA = DMA1_CH0, CRYP_OUT_DMA = DMA1_CH1, UART = USART1, UART_TX = PB6, UART_RX = PB7, UART_TX_DMA = DMA1_CH0, UART_RX_DMA = DMA1_CH1, SPI = SPI1, SPI_SCK = PA5, SPI_MOSI = PB5, SPI_MISO = PA6, SPI_TX_DMA = DMA1_CH0, SPI_RX_DMA = DMA1_CH1, ADC = ADC1, DAC = DAC1, DAC_PIN = PA4, @@ -157,6 +174,12 @@ define_peris!( SPI = SPI4, SPI_SCK = PE12, SPI_MOSI = PE14, SPI_MISO = PE13, SPI_TX_DMA = GPDMA1_CH0, SPI_RX_DMA = GPDMA1_CH1, @irq UART = {LPUART1 => embassy_stm32::usart::InterruptHandler;}, ); +#[cfg(feature = "stm32h503rb")] +define_peris!( + UART = USART1, UART_TX = PB14, UART_RX = PB15, UART_TX_DMA = GPDMA1_CH0, UART_RX_DMA = GPDMA1_CH1, + SPI = SPI1, SPI_SCK = PA5, SPI_MOSI = PA7, SPI_MISO = PA6, SPI_TX_DMA = GPDMA1_CH0, SPI_RX_DMA = GPDMA1_CH1, + @irq UART = {USART1 => embassy_stm32::usart::InterruptHandler;}, +); #[cfg(feature = "stm32c031c6")] define_peris!( UART = USART1, UART_TX = PB6, UART_RX = PB7, UART_TX_DMA = DMA1_CH1, UART_RX_DMA = DMA1_CH2, @@ -191,7 +214,7 @@ define_peris!( define_peris!( UART = USART3, UART_TX = PB10, UART_RX = PB11, UART_TX_DMA = DMA1_CH2, UART_RX_DMA = DMA1_CH3, SPI = SPI1, SPI_SCK = PA5, SPI_MOSI = PA7, SPI_MISO = PA6, SPI_TX_DMA = DMA1_CH3, SPI_RX_DMA = DMA1_CH2, - ADC = ADC, DAC = DAC, DAC_PIN = PA4, + ADC = ADC1, DAC = DAC1, DAC_PIN = PA4, @irq UART = {USART3 => embassy_stm32::usart::InterruptHandler;}, ); #[cfg(feature = "stm32l552ze")] @@ -230,26 +253,86 @@ define_peris!( SPI = SPI1, SPI_SCK = PB4, SPI_MOSI = PA15, SPI_MISO = PB3, SPI_TX_DMA = GPDMA1_CH0, SPI_RX_DMA = GPDMA1_CH1, @irq UART = {LPUART1 => embassy_stm32::usart::InterruptHandler;}, ); +#[cfg(feature = "stm32h7s3l8")] +define_peris!( + CRYP_IN_DMA = GPDMA1_CH0, CRYP_OUT_DMA = GPDMA1_CH1, + UART = USART1, UART_TX = PB14, UART_RX = PA10, UART_TX_DMA = GPDMA1_CH0, UART_RX_DMA = GPDMA1_CH1, + SPI = SPI1, SPI_SCK = PA5, SPI_MOSI = PB5, SPI_MISO = PA6, SPI_TX_DMA = GPDMA1_CH0, SPI_RX_DMA = GPDMA1_CH1, + @irq UART = {USART1 => embassy_stm32::usart::InterruptHandler;}, +); +#[cfg(feature = "stm32u083rc")] +define_peris!( + UART = USART1, UART_TX = PA9, UART_RX = PA10, UART_TX_DMA = DMA1_CH1, UART_RX_DMA = DMA1_CH2, + SPI = SPI1, SPI_SCK = PA5, SPI_MOSI = PA7, SPI_MISO = PA6, SPI_TX_DMA = DMA1_CH1, SPI_RX_DMA = DMA1_CH2, + @irq UART = {USART1 => embassy_stm32::usart::InterruptHandler;}, +); pub fn config() -> Config { - // Setting this bit is mandatory to use PG[15:2]. - #[cfg(feature = "stm32u5a5zj")] - embassy_stm32::pac::PWR.svmcr().modify(|w| { - w.set_io2sv(true); - w.set_io2vmen(true); - }); - #[allow(unused_mut)] let mut config = Config::default(); + #[cfg(feature = "stm32c031c6")] + { + config.rcc.hsi = Some(Hsi { + sys_div: HsiSysDiv::DIV1, // 48Mhz + ker_div: HsiKerDiv::DIV3, // 16Mhz + }); + config.rcc.sys = Sysclk::HSISYS; + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV1; + } + + #[cfg(feature = "stm32g071rb")] + { + config.rcc.hsi = true; + config.rcc.pll = Some(Pll { + source: PllSource::HSI, + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL16, + divp: None, + divq: None, + divr: Some(PllRDiv::DIV4), // 16 / 1 * 16 / 4 = 64 Mhz + }); + config.rcc.sys = Sysclk::PLL1_R; + } #[cfg(feature = "stm32wb55rg")] { config.rcc = embassy_stm32::rcc::WPAN_DEFAULT; } + #[cfg(feature = "stm32f091rc")] + { + config.rcc.hse = Some(Hse { + freq: Hertz(8_000_000), + mode: HseMode::Bypass, + }); + config.rcc.pll = Some(Pll { + src: PllSource::HSE, + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL6, + }); + config.rcc.sys = Sysclk::PLL1_P; + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV1; + } + #[cfg(feature = "stm32f103c8")] + { + config.rcc.hse = Some(Hse { + freq: Hertz(8_000_000), + mode: HseMode::Oscillator, + }); + config.rcc.pll = Some(Pll { + src: PllSource::HSE, + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL9, + }); + config.rcc.sys = Sysclk::PLL1_P; + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV2; + config.rcc.apb2_pre = APBPrescaler::DIV1; + } #[cfg(feature = "stm32f207zg")] { - use embassy_stm32::rcc::*; // By default, HSE on the board comes from a 8 MHz clock signal (not a crystal) config.rcc.hse = Some(Hse { freq: Hertz(8_000_000), @@ -276,9 +359,25 @@ pub fn config() -> Config { config.rcc.apb2_pre = APBPrescaler::DIV2; } + #[cfg(feature = "stm32f303ze")] + { + config.rcc.hse = Some(Hse { + freq: Hertz(8_000_000), + mode: HseMode::Bypass, + }); + config.rcc.pll = Some(Pll { + src: PllSource::HSE, + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL9, + }); + config.rcc.sys = Sysclk::PLL1_P; + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV2; + config.rcc.apb2_pre = APBPrescaler::DIV1; + } + #[cfg(feature = "stm32f429zi")] { - use embassy_stm32::rcc::*; config.rcc.hse = Some(Hse { freq: Hertz(8_000_000), mode: HseMode::Bypass, @@ -299,7 +398,6 @@ pub fn config() -> Config { #[cfg(feature = "stm32f446re")] { - use embassy_stm32::rcc::*; config.rcc.hse = Some(Hse { freq: Hertz(8_000_000), mode: HseMode::Oscillator, @@ -320,7 +418,6 @@ pub fn config() -> Config { #[cfg(feature = "stm32f767zi")] { - use embassy_stm32::rcc::*; config.rcc.hse = Some(Hse { freq: Hertz(8_000_000), mode: HseMode::Bypass, @@ -341,7 +438,6 @@ pub fn config() -> Config { #[cfg(feature = "stm32h563zi")] { - use embassy_stm32::rcc::*; config.rcc.hsi = None; config.rcc.hsi48 = Some(Default::default()); // needed for RNG config.rcc.hse = Some(Hse { @@ -364,9 +460,50 @@ pub fn config() -> Config { config.rcc.voltage_scale = VoltageScale::Scale0; } + #[cfg(feature = "stm32h503rb")] + { + config.rcc.hsi = None; + config.rcc.hsi48 = Some(Default::default()); // needed for RNG + config.rcc.hse = Some(Hse { + freq: Hertz(24_000_000), + mode: HseMode::Oscillator, + }); + config.rcc.pll1 = Some(Pll { + source: PllSource::HSE, + prediv: PllPreDiv::DIV6, + mul: PllMul::MUL125, + divp: Some(PllDiv::DIV2), + divq: Some(PllDiv::DIV2), + divr: None, + }); + config.rcc.ahb_pre = AHBPrescaler::DIV1; + config.rcc.apb1_pre = APBPrescaler::DIV1; + config.rcc.apb2_pre = APBPrescaler::DIV1; + config.rcc.apb3_pre = APBPrescaler::DIV1; + config.rcc.sys = Sysclk::PLL1_P; + config.rcc.voltage_scale = VoltageScale::Scale0; + } + + #[cfg(feature = "stm32g491re")] + { + config.rcc.hse = Some(Hse { + freq: Hertz(24_000_000), + mode: HseMode::Oscillator, + }); + config.rcc.pll = Some(Pll { + source: PllSource::HSE, + prediv: PllPreDiv::DIV6, + mul: PllMul::MUL85, + divp: None, + divq: Some(PllQDiv::DIV8), // 42.5 Mhz for fdcan. + divr: Some(PllRDiv::DIV2), // Main system clock at 170 MHz + }); + config.rcc.mux.fdcansel = mux::Fdcansel::PLL1_Q; + config.rcc.sys = Sysclk::PLL1_R; + } + #[cfg(any(feature = "stm32h755zi", feature = "stm32h753zi"))] { - use embassy_stm32::rcc::*; config.rcc.hsi = Some(HSIPrescaler::DIV1); config.rcc.csi = true; config.rcc.hsi48 = Some(Default::default()); // needed for RNG @@ -393,7 +530,7 @@ pub fn config() -> Config { config.rcc.apb3_pre = APBPrescaler::DIV2; // 100 Mhz config.rcc.apb4_pre = APBPrescaler::DIV2; // 100 Mhz config.rcc.voltage_scale = VoltageScale::Scale1; - config.rcc.adc_clock_source = AdcClockSource::PLL2_P; + config.rcc.mux.adcsel = mux::Adcsel::PLL2_P; #[cfg(any(feature = "stm32h755zi"))] { config.rcc.supply_config = SupplyConfig::DirectSMPS; @@ -402,7 +539,6 @@ pub fn config() -> Config { #[cfg(any(feature = "stm32h7a3zi"))] { - use embassy_stm32::rcc::*; config.rcc.hsi = Some(HSIPrescaler::DIV1); config.rcc.csi = true; config.rcc.hsi48 = Some(Default::default()); // needed for RNG @@ -429,13 +565,12 @@ pub fn config() -> Config { config.rcc.apb3_pre = APBPrescaler::DIV2; // 140 Mhz config.rcc.apb4_pre = APBPrescaler::DIV2; // 140 Mhz config.rcc.voltage_scale = VoltageScale::Scale0; - config.rcc.adc_clock_source = AdcClockSource::PLL2_P; + config.rcc.mux.adcsel = mux::Adcsel::PLL2_P; } #[cfg(any(feature = "stm32l496zg", feature = "stm32l4a6zg", feature = "stm32l4r5zi"))] { - use embassy_stm32::rcc::*; - config.rcc.mux = ClockSrc::PLL1_R; + config.rcc.sys = Sysclk::PLL1_R; config.rcc.hsi = true; config.rcc.pll = Some(Pll { source: PllSource::HSI, @@ -449,13 +584,12 @@ pub fn config() -> Config { #[cfg(feature = "stm32wl55jc")] { - use embassy_stm32::rcc::*; config.rcc.hse = Some(Hse { freq: Hertz(32_000_000), mode: HseMode::Bypass, prescaler: HsePrescaler::DIV1, }); - config.rcc.mux = ClockSrc::PLL1_R; + config.rcc.sys = Sysclk::PLL1_R; config.rcc.pll = Some(Pll { source: PllSource::HSE, prediv: PllPreDiv::DIV2, @@ -468,9 +602,8 @@ pub fn config() -> Config { #[cfg(any(feature = "stm32l552ze"))] { - use embassy_stm32::rcc::*; config.rcc.hsi = true; - config.rcc.mux = ClockSrc::PLL1_R; + config.rcc.sys = Sysclk::PLL1_R; config.rcc.pll = Some(Pll { // 110Mhz clock (16 / 4 * 55 / 2) source: PllSource::HSI, @@ -484,43 +617,103 @@ pub fn config() -> Config { #[cfg(any(feature = "stm32u585ai", feature = "stm32u5a5zj"))] { - use embassy_stm32::rcc::*; - config.rcc.mux = ClockSrc::MSI(Msirange::RANGE_48MHZ); + config.rcc.hsi = true; + config.rcc.pll1 = Some(Pll { + source: PllSource::HSI, // 16 MHz + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL10, + divp: None, + divq: None, + divr: Some(PllDiv::DIV1), // 160 MHz + }); + config.rcc.sys = Sysclk::PLL1_R; + config.rcc.voltage_range = VoltageScale::RANGE1; + config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true }); // needed for USB } #[cfg(feature = "stm32wba52cg")] { - use embassy_stm32::rcc::*; - config.rcc.mux = ClockSrc::HSI; - - embassy_stm32::pac::RCC.ccipr2().write(|w| { - w.set_rngsel(embassy_stm32::pac::rcc::vals::Rngsel::HSI); - }); + config.rcc.sys = Sysclk::HSI; + config.rcc.mux.rngsel = mux::Rngsel::HSI; } #[cfg(feature = "stm32l073rz")] { - use embassy_stm32::rcc::*; config.rcc.hsi = true; config.rcc.pll = Some(Pll { source: PllSource::HSI, mul: PllMul::MUL4, div: PllDiv::DIV2, // 32Mhz clock (16 * 4 / 2) }); - config.rcc.mux = ClockSrc::PLL1_R; + config.rcc.sys = Sysclk::PLL1_R; } #[cfg(any(feature = "stm32l152re"))] { - use embassy_stm32::rcc::*; config.rcc.hsi = true; config.rcc.pll = Some(Pll { source: PllSource::HSI, mul: PllMul::MUL4, div: PllDiv::DIV2, // 32Mhz clock (16 * 4 / 2) }); - config.rcc.mux = ClockSrc::PLL1_R; + config.rcc.sys = Sysclk::PLL1_R; + } + #[cfg(any(feature = "stm32h7s3l8"))] + { + config.rcc.hse = Some(Hse { + freq: Hertz(24_000_000), + mode: HseMode::Oscillator, + }); + config.rcc.pll1 = Some(Pll { + source: PllSource::HSE, + prediv: PllPreDiv::DIV3, + mul: PllMul::MUL150, + divp: Some(PllDiv::DIV2), // 600Mhz + divq: Some(PllDiv::DIV25), // 48Mhz + divr: None, + }); + config.rcc.sys = Sysclk::PLL1_P; // 600 Mhz + config.rcc.ahb_pre = AHBPrescaler::DIV2; // 300 Mhz + config.rcc.apb1_pre = APBPrescaler::DIV2; // 150 Mhz + config.rcc.apb2_pre = APBPrescaler::DIV2; // 150 Mhz + config.rcc.apb4_pre = APBPrescaler::DIV2; // 150 Mhz + config.rcc.apb5_pre = APBPrescaler::DIV2; // 150 Mhz + config.rcc.voltage_scale = VoltageScale::HIGH; + config.rcc.mux.spi1sel = mux::Spi123sel::PLL1_Q; + } + #[cfg(any(feature = "stm32u083rc"))] + { + config.rcc.hsi = true; + config.rcc.pll = Some(Pll { + source: PllSource::HSI, // 16 MHz + prediv: PllPreDiv::DIV1, + mul: PllMul::MUL7, + divp: None, + divq: None, + divr: Some(PllRDiv::DIV2), // 56 MHz + }); + config.rcc.sys = Sysclk::PLL1_R; + config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true }); // needed for USB + config.rcc.mux.clk48sel = mux::Clk48sel::HSI48; // USB uses ICLK } config } + +#[allow(unused)] +pub fn init() -> embassy_stm32::Peripherals { + init_with_config(config()) +} + +#[allow(unused)] +pub fn init_with_config(config: Config) -> embassy_stm32::Peripherals { + #[cfg(any(feature = "stm32wl55jc", feature = "stm32h755zi"))] + { + // Not in shared memory, but we're not running the second core, so it's fine + static SHARED_DATA: core::mem::MaybeUninit = core::mem::MaybeUninit::uninit(); + embassy_stm32::init_primary(config, &SHARED_DATA) + } + + #[cfg(not(any(feature = "stm32wl55jc", feature = "stm32h755zi")))] + embassy_stm32::init(config) +} diff --git a/tests/stm32/teleprobe.sh b/tests/stm32/teleprobe.sh deleted file mode 100755 index 6eec6ca93..000000000 --- a/tests/stm32/teleprobe.sh +++ /dev/null @@ -1,12 +0,0 @@ -echo Running target=$1 elf=$2 -STATUSCODE=$( - curl \ - -sS \ - --output /dev/stderr \ - --write-out "%{http_code}" \ - -H "Authorization: Bearer $TELEPROBE_TOKEN" \ - https://teleprobe.embassy.dev/targets/$1/run --data-binary @$2 -) -echo -echo HTTP Status code: $STATUSCODE -test "$STATUSCODE" -eq 200 diff --git a/tests/utils/Cargo.toml b/tests/utils/Cargo.toml index 7d66fd586..7b54a4f52 100644 --- a/tests/utils/Cargo.toml +++ b/tests/utils/Cargo.toml @@ -3,8 +3,6 @@ name = "test-utils" version = "0.1.0" edition = "2021" -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - [dependencies] rand = "0.8" serial = "0.4"