Merge branch 'main' of https://github.com/embassy-rs/embassy into fix_main

This commit is contained in:
Gustav Toft 2024-05-30 09:56:09 +02:00
commit d3c3670a96
405 changed files with 20190 additions and 5254 deletions

17
.github/ci/book.sh vendored Executable file
View file

@ -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

2
.github/ci/build.sh vendored
View file

@ -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)

1
.github/ci/doc.sh vendored
View file

@ -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

View file

@ -11,3 +11,4 @@ mv rust-toolchain-nightly.toml rust-toolchain.toml
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

7
.github/ci/test.sh vendored
View file

@ -8,9 +8,10 @@ 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
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

22
.vscode/settings.json vendored
View file

@ -9,25 +9,29 @@
"rust-analyzer.check.noDefaultFeatures": true,
"rust-analyzer.cargo.noDefaultFeatures": true,
"rust-analyzer.showUnlinkedFileNotification": false,
// uncomment the target of your chip.
"rust-analyzer.cargo.target": "thumbv6m-none-eabi",
// 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-eabi",
//"rust-analyzer.cargo.target": "thumbv7em-none-eabihf",
//"rust-analyzer.cargo.target": "thumbv8m.main-none-eabihf",
/* "rust-analyzer.cargo.features": [
"stm32f103c8",
"rust-analyzer.cargo.features": [
// 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.
"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.
// "embassy-stm32/Cargo.toml",
// "examples/nrf52840-rtic/Cargo.toml",
// "examples/nrf5340/Cargo.toml",
// "examples/nrf-rtos-trace/Cargo.toml",
"examples/rp/Cargo.toml",
// "examples/rp/Cargo.toml",
// "examples/std/Cargo.toml",
// "examples/stm32c0/Cargo.toml",
// "examples/stm32f0/Cargo.toml",

428
LICENSE-CC-BY-SA Normal file
View file

@ -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.

View file

@ -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

View file

@ -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.
## <a href="https://embassy.dev/book/dev/index.html">Documentation</a> - <a href="https://docs.embassy.dev/">API reference</a> - <a href="https://embassy.dev/">Website</a> - <a href="https://matrix.to/#/#embassy-rs:matrix.org">Chat</a>
## <a href="https://embassy.dev/book/index.html">Documentation</a> - <a href="https://docs.embassy.dev/">API reference</a> - <a href="https://embassy.dev/">Website</a> - <a href="https://matrix.to/#/#embassy-rs:matrix.org">Chat</a>
## 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 <a href="https://rust-lang.github.io/async-book/">async/await</a> 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 <a href="https://tweedegolf.nl/en/blog/65/async-rust-vs-rtos-showdown">faster and smaller than one!</a>
Rust's <a href="https://rust-lang.github.io/async-book/">async/await</a> 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 <a href="https://tweedegolf.nl/en/blog/65/async-rust-vs-rtos-showdown">faster and smaller than one!</a>
## Batteries included
@ -18,6 +18,7 @@ Rust's <a href="https://rust-lang.github.io/async-book/">async/await</a> allows
- <a href="https://github.com/esp-rs">esp-rs</a>, 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.
- <a href="https://github.com/ch32-rs/ch32-hal">ch32-hal</a>, for the WCH 32-bit RISC-V(CH32V) series of chips.
- **Time that Just Works** -
No more messing with hardware timers. <a href="https://docs.embassy.dev/embassy-time">embassy_time</a> 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 <https://probe.rs>.
- 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)

30
ci.sh
View file

@ -125,6 +125,10 @@ cargo batch \
--- 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 \
@ -147,8 +151,15 @@ cargo batch \
--- 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 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 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 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' \
@ -160,11 +171,12 @@ cargo batch \
--- 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 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 \
@ -176,16 +188,19 @@ cargo batch \
--- 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/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 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/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-eabi --out-dir out/examples/stm32wb \
--- build --release --manifest-path examples/stm32wba/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/stm32wba \
@ -232,8 +247,10 @@ 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 \
@ -250,6 +267,9 @@ rm out/tests/stm32f207zg/eth
# doesn't work, gives "noise error", no idea why. usart_dma does pass.
rm out/tests/stm32u5a5zj/usart
# flaky, perhaps bad wire
rm out/tests/stm32l152re/usart_rx_ringbuffered
if [[ -z "${TELEPROBE_TOKEN-}" ]]; then
echo No teleprobe token found, skipping running HIL tests
exit

View file

@ -18,7 +18,7 @@ firmware-logs = []
[dependencies]
embassy-time = { version = "0.3.0", path = "../embassy-time"}
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-channel = { version = "0.2.0", path = "../embassy-net-driver-channel"}

View file

@ -23,7 +23,7 @@ TODO:
## Running the examples
- `cargo install probe-rs --features cli`
- Install `probe-rs` following the instructions at <https://probe.rs>.
- `cd examples/rp`
### Example 1: Scan the wifi stations
- `cargo run --release --bin wifi_scan`

View file

@ -124,8 +124,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;
@ -229,8 +228,8 @@ impl<'a> Control<'a> {
self.wait_for_join(i).await
}
/// Join an protected network with the provided ssid and passphrase.
pub async fn join_wpa2(&mut self, ssid: &str, passphrase: &str) -> Result<(), Error> {
/// Join a protected network with the provided ssid and [`PassphraseInfo`].
async fn join_wpa2_passphrase_info(&mut self, ssid: &str, passphrase_info: &PassphraseInfo) -> Result<(), Error> {
self.set_iovar_u32("ampdu_ba_wsize", 8).await;
self.ioctl_set_u32(134, 0, 4).await; // wsec = wpa2
@ -240,14 +239,13 @@ impl<'a> Control<'a> {
Timer::after_millis(100).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(
IoctlType::Set,
IOCTL_CMD_SET_PASSPHRASE,
0,
&mut passphrase_info.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)
@ -262,6 +260,28 @@ impl<'a> Control<'a> {
self.wait_for_join(i).await
}
/// Join a protected network with the provided ssid and passphrase.
pub async fn join_wpa2(&mut self, ssid: &str, passphrase: &str) -> Result<(), Error> {
let mut pfi = PassphraseInfo {
len: passphrase.len() as _,
flags: 1,
passphrase: [0; 64],
};
pfi.passphrase[..passphrase.len()].copy_from_slice(passphrase.as_bytes());
self.join_wpa2_passphrase_info(ssid, &pfi).await
}
/// Join a protected network with the provided ssid and precomputed PSK.
pub async fn join_wpa2_psk(&mut self, ssid: &str, psk: &[u8; 32]) -> Result<(), Error> {
let mut pfi = PassphraseInfo {
len: psk.len() as _,
flags: 0,
passphrase: [0; 64],
};
pfi.passphrase[..psk.len()].copy_from_slice(psk);
self.join_wpa2_passphrase_info(ssid, &pfi).await
}
async fn wait_for_join(&mut self, i: SsidInfo) -> Result<(), Error> {
self.events.mask.enable(&[Event::SET_SSID, Event::AUTH]);
let mut subscriber = self.events.queue.subscriber().unwrap();
@ -574,6 +594,13 @@ impl<'a> Control<'a> {
self.ioctl(IoctlType::Set, IOCTL_CMD_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.

View file

@ -1,6 +1,5 @@
use embassy_futures::select::{select3, Either3};
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;
@ -438,13 +437,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 => {

8
docs/Makefile Normal file
View file

@ -0,0 +1,8 @@
all:
asciidoctor -d book -D book/ index.adoc
cp -r images book
clean:
rm -rf book
.PHONY: all clean

View file

@ -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

View file

@ -1,5 +0,0 @@
name: ROOT
title: Embassy
version: dev
nav:
- modules/ROOT/nav.adoc

View file

@ -0,0 +1,18 @@
[package]
authors = ["Dario Nieuwenhuis <dirbaio@dirbaio.net>"]
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"] }

1
docs/examples/examples Symbolic link
View file

@ -0,0 +1 @@
../../examples

View file

@ -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

View file

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 31 KiB

View file

Before

Width:  |  Height:  |  Size: 118 KiB

After

Width:  |  Height:  |  Size: 118 KiB

View file

Before

Width:  |  Height:  |  Size: 131 KiB

After

Width:  |  Height:  |  Size: 131 KiB

16
docs/index.adoc Normal file
View file

@ -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]

View file

@ -1,18 +0,0 @@
[package]
authors = ["Dario Nieuwenhuis <dirbaio@dirbaio.net>"]
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"] }

View file

@ -1 +0,0 @@
../../../../examples

View file

@ -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]

View file

@ -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/master/docs/examples/basic[here].
NOTE: If youre 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 were working on. Follow the instructions commented in that file to get rust-analyzer working correctly.
@ -14,7 +14,7 @@ The first thing youll notice are two attributes at the top of the file. These
[source,rust]
----
include::example$basic/src/main.rs[lines="1..2"]
include::../examples/basic/src/main.rs[lines="1..2"]
----
=== Dealing with errors
@ -23,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="8"]
include::../examples/basic/src/main.rs[lines="8"]
----
=== Task declaration
@ -32,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="10..18"]
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.
@ -47,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="20..-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:
@ -64,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).

11
docs/pages/beginners.adoc Normal file
View file

@ -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]

View file

@ -1,14 +1,17 @@
= 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]!
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/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/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:

View file

@ -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[]
----

View file

@ -2,7 +2,7 @@
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!
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.
@ -231,3 +231,129 @@ Please refer to the STM32 documentation for the specific values suitable for you
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/dev/new_project.html#_cargo_toml[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.
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.

View file

@ -137,7 +137,7 @@ If youre still having problems, check the link:https://embassy.dev/book/dev/f
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].
* Learn how to xref:new_project.adoc[start a new embassy project by adapting an example].
* 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].

View file

@ -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.

View file

@ -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:

View file

@ -1,17 +1,18 @@
= Starting a new Embassy project
= Starting a new project
Once youve successfully xref:getting_started.adoc[run some example projects], the next step is to make a standalone Embassy project.
There are some tools for generating Embassy projects: (WIP)
== Tools for generating Embassy projects
==== CLI
=== CLI
- link:https://github.com/adinack/cargo-embassy[cargo-embassy] (STM32 and NRF)
==== cargo-generate
=== 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)
But if you want to start from scratch:
== Starting a project from scratch
As an example, lets create a new embassy project from scratch for a STM32G474. The same instructions are applicable for any supported chip with some minor changes.
@ -35,7 +36,7 @@ stm32g474-example
Looking in link:https://github.com/embassy-rs/embassy/tree/main/examples[the Embassy examples], we can see theres a `stm32g4` folder. Find `src/blinky.rs` and copy its contents into our `src/main.rs`.
== .cargo/config.toml
=== The .cargo/config.toml
Currently, wed need to provide cargo with a target triple every time we run `cargo build` or `cargo run`. Lets spare ourselves that work by copying `.cargo/config.toml` from `examples/stm32g4` into our project.
@ -66,7 +67,7 @@ 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), were ready to add some dependencies.
@ -117,7 +118,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`:
@ -142,7 +143,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:
@ -158,7 +159,7 @@ stm32g474-example
└── main.rs
----
== Building and running
=== Building and running
At this point, were finally ready to build and run our project! Connect your board via a debug probe and run:

View file

@ -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.
@ -55,6 +56,20 @@ For most I/O in embedded devices, the peripheral doesn't directly support the tr
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:

View file

@ -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,21 +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 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.
==== Features
===== Time
[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.
@ -68,6 +75,7 @@ MEMORY
}
----
[discrete]
== rust-toolchain.toml
This file configures the rust version and configuration to use.

View file

@ -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:/book/dev/basic_application.html#_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:/book/dev/basic_application.html#_the_cargo_toml[can be found here].
[,rust]
----
use defmt::*;
@ -123,4 +125,4 @@ 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.

13
docs/pages/system.adoc Normal file
View file

@ -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]

View file

@ -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:/book/dev/basic_application.html#_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:/book/dev/basic_application.html#_the_cargo_toml[can be found here].
[,rust]
----
use embassy::executor::{task, Executor};

View file

@ -23,7 +23,7 @@ target = "thumbv7em-none-eabi"
[dependencies]
defmt = { version = "0.3", optional = true }
embassy-sync = { version = "0.5.0", path = "../embassy-sync" }
embassy-sync = { version = "0.6.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" }
cortex-m = { version = "0.7.6" }

View file

@ -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

View file

@ -24,7 +24,7 @@ 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-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" }

View file

@ -25,7 +25,7 @@ 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" }
cortex-m = { version = "0.7.6" }

View file

@ -29,7 +29,7 @@ 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" }
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 }

View file

@ -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:

View file

@ -28,7 +28,7 @@ default = ["time"]
[dependencies]
embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
embassy-sync = { version = "0.5.0", path = "../embassy-sync" }
embassy-sync = { version = "0.6.0", path = "../embassy-sync" }
embassy-time = { version = "0.3.0", path = "../embassy-time", optional = true }
embedded-hal-02 = { package = "embedded-hal", version = "0.2.6", features = [
"unproven",

View file

@ -55,13 +55,14 @@ where
type Error = SpiDeviceError<BUS::Error, CS::Error>;
}
impl<M, BUS, CS> spi::SpiDevice for SpiDevice<'_, M, BUS, CS>
impl<M, BUS, CS, Word> spi::SpiDevice<Word> for SpiDevice<'_, M, BUS, CS>
where
M: RawMutex,
BUS: spi::SpiBus,
BUS: spi::SpiBus<Word>,
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);
}
@ -138,13 +139,14 @@ where
type Error = SpiDeviceError<BUS::Error, CS::Error>;
}
impl<M, BUS, CS> spi::SpiDevice for SpiDeviceWithConfig<'_, M, BUS, CS>
impl<M, BUS, CS, Word> spi::SpiDevice<Word> for SpiDeviceWithConfig<'_, M, BUS, CS>
where
M: RawMutex,
BUS: spi::SpiBus + SetConfig,
BUS: spi::SpiBus<Word> + 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);
}

View file

@ -48,13 +48,14 @@ where
type Error = SpiDeviceError<BUS::Error, CS::Error>;
}
impl<BUS, M, CS> embedded_hal_1::spi::SpiDevice for SpiDevice<'_, M, BUS, CS>
impl<BUS, M, CS, Word> embedded_hal_1::spi::SpiDevice<Word> for SpiDevice<'_, M, BUS, CS>
where
M: RawMutex,
BUS: SpiBus,
BUS: SpiBus<Word>,
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<u8> for SpiDevice<'_, M, BUS, CS>
where
M: RawMutex,
BUS: embedded_hal_02::blocking::spi::Transfer<u8, Error = BusErr>,
CS: OutputPin<Error = CsErr>,
{
type Error = SpiDeviceError<BusErr, CsErr>;
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<u8> for SpiDevice<'_, M, BUS, CS>
where
M: RawMutex,
BUS: embedded_hal_02::blocking::spi::Write<u8, Error = BusErr>,
CS: OutputPin<Error = CsErr>,
{
type Error = SpiDeviceError<BusErr, CsErr>;
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
@ -163,13 +123,14 @@ where
type Error = SpiDeviceError<BUS::Error, CS::Error>;
}
impl<BUS, M, CS> embedded_hal_1::spi::SpiDevice for SpiDeviceWithConfig<'_, M, BUS, CS>
impl<BUS, M, CS, Word> embedded_hal_1::spi::SpiDevice<Word> for SpiDeviceWithConfig<'_, M, BUS, CS>
where
M: RawMutex,
BUS: SpiBus + SetConfig,
BUS: SpiBus<Word> + 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);
}

View file

@ -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

View file

@ -123,6 +123,11 @@ impl RingBuffer {
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)
@ -478,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);

View file

@ -1,5 +1,5 @@
use core::marker::PhantomData;
use core::ops::Deref;
use core::ops::{Deref, DerefMut};
/// An exclusive reference to a peripheral.
///
@ -155,7 +155,7 @@ pub trait Peripheral: Sized {
}
}
impl<'b, T: Deref> Peripheral for T
impl<'b, T: DerefMut> Peripheral for T
where
T::Target: Peripheral,
{
@ -163,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)
}
}

View file

@ -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" }

View file

@ -9,12 +9,16 @@ 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-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"}

View file

@ -21,7 +21,7 @@ embedded-io-async = { version = "0.6.1" }
embassy-net-driver-channel = { version = "0.2.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" }
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/"

View file

@ -73,15 +73,10 @@ smoltcp = { version = "0.11.0", default-features = false, features = [
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-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" }
document-features = "0.2.7"

View file

@ -13,8 +13,8 @@ memory management designed to work well for embedded systems, aiming for a more
- TCP, UDP, DNS, DHCPv4, IGMPv4
- TCP sockets implement the `embedded-io` async traits.
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

View file

@ -25,13 +25,13 @@ pub mod udp;
use core::cell::RefCell;
use core::future::{poll_fn, Future};
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")]
@ -905,8 +905,7 @@ impl<D: Driver> Inner<D> {
}
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);
let t = pin!(Timer::at(instant_from_smoltcp(poll_at)));
if t.poll(cx).is_ready() {
cx.waker().wake_by_ref();
}

View file

@ -91,7 +91,7 @@ impl<'a> RawSocket<'a> {
/// Send a datagram.
///
/// This method will wait until the datagram has been sent.`
pub async fn send<T>(&self, buf: &[u8]) -> Result<(), raw::SendError> {
pub async fn send(&self, buf: &[u8]) {
poll_fn(move |cx| self.poll_send(buf, cx)).await
}
@ -101,10 +101,10 @@ impl<'a> RawSocket<'a> {
///
/// 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<Result<(), raw::SendError>> {
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(Ok(())),
Ok(()) => Poll::Ready(()),
Err(raw::SendError::BufferFull) => {
s.register_send_waker(cx.waker());
Poll::Pending

View file

@ -555,7 +555,7 @@ mod embedded_io_impls {
impl<'d> embedded_io_async::ReadReady for TcpSocket<'d> {
fn read_ready(&mut self) -> Result<bool, Self::Error> {
Ok(self.io.with(|s, _| s.may_recv()))
Ok(self.io.with(|s, _| s.can_recv()))
}
}
@ -587,7 +587,7 @@ mod embedded_io_impls {
impl<'d> embedded_io_async::ReadReady for TcpReader<'d> {
fn read_ready(&mut self) -> Result<bool, Self::Error> {
Ok(self.io.with(|s, _| s.may_recv()))
Ok(self.io.with(|s, _| s.can_recv()))
}
}

View file

@ -8,8 +8,8 @@ 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};
@ -111,7 +111,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 +122,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<Result<(usize, IpEndpoint), RecvError>> {
pub fn poll_recv_from(
&self,
buf: &mut [u8],
cx: &mut Context<'_>,
) -> Poll<Result<(usize, UdpMetadata), RecvError>> {
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) => {
@ -141,9 +145,9 @@ impl<'a> UdpSocket<'a> {
/// When the remote endpoint is not reachable, this method will return `Err(SendError::NoRoute)`
pub async fn send_to<T>(&self, buf: &[u8], remote_endpoint: T) -> Result<(), SendError>
where
T: Into<IpEndpoint>,
T: Into<UdpMetadata>,
{
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 +161,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<T>(&self, buf: &[u8], remote_endpoint: T, cx: &mut Context<'_>) -> Poll<Result<(), SendError>>
where
T: Into<IpEndpoint>,
T: Into<UdpMetadata>,
{
self.with_mut(|s, _| match s.send_slice(buf, remote_endpoint) {
// Entire datagram has been sent

40
embassy-nrf/CHANGELOG.md Normal file
View file

@ -0,0 +1,40 @@
# 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
- Drop `sealed` mod
- nrf52840: Add dcdc voltage parameter to configure REG0 regulator
- radio: Add support for IEEE 802.15.4 and BLE via radio peripheral
- spim: Reduce trace-level messages ("Copying SPIM tx buffer..")
- uart: Add support for rx- or tx-only BufferedUart
- uart: Implement splitting Rx/Tx
- spi: Allow specifying OutputDrive for SPI spins
- pdm: Fix gain register value derivation
- spim: Implement chunked DMA transfers
- spi: Add bounds checks for EasyDMA buffer size
- uarte: Add support for handling RX errors
- nrf51: Implement support for nrf51 chip
- pwm: Expose `duty` method
- pwm: Fix infinite loop
- spi: Add support for configuring bit order for bus
- pwm: Expose `pwm::PWM_CLK_HZ` and add `is_enabled` method
- gpio: Drop GPIO Pin generics (API break)
## 0.1.0 - 2024-01-12
- First release with support for following NRF chips:
- nrf52805
- nrf52810
- nrf52811
- nrf52820
- nrf52832
- nrf52833
- nrf52840
- nrf5340
- nrf9160

View file

@ -126,7 +126,7 @@ _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-sync = { version = "0.6.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-usb-driver = {version = "0.1.0", path = "../embassy-usb-driver" }

View file

@ -1,4 +1,4 @@
//! Pulse Density Modulation (PDM) mirophone driver
//! Pulse Density Modulation (PDM) microphone driver
#![macro_use]

View file

@ -368,7 +368,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>,

View file

@ -471,12 +471,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 +491,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> {

View file

@ -81,7 +81,7 @@ boot2-w25q080 = []
boot2-w25x10cl = []
[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-futures = { version = "0.1.0", path = "../embassy-futures" }
@ -96,7 +96,6 @@ 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"] }
chrono = { version = "0.4", default-features = false, optional = true }
embedded-io = { version = "0.6.1" }
embedded-io-async = { version = "0.6.1" }

View file

@ -714,10 +714,6 @@ pub fn clk_rtc_freq() -> u16 {
}
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| {
@ -1027,7 +1023,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.

View file

@ -374,6 +374,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;

View file

@ -352,12 +352,60 @@ pub fn init(config: config::Config) -> Peripherals {
peripherals
}
#[cfg(feature = "rt")]
#[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<T: Copy> {
#[allow(unused)]
fn write_xor<R>(&self, f: impl FnOnce(&mut T) -> R) -> R;
fn write_set<R>(&self, f: impl FnOnce(&mut T) -> R) -> R;
fn write_clear<R>(&self, f: impl FnOnce(&mut T) -> R) -> R;
fn write_and_wait<R>(&self, f: impl FnOnce(&mut T) -> R) -> R
where
T: PartialEq;
}
impl<T: Default + Copy, A: pac::common::Write> RegExt<T> for pac::common::Reg<T, A> {
@ -390,4 +438,17 @@ impl<T: Default + Copy, A: pac::common::Write> RegExt<T> for pac::common::Reg<T,
}
res
}
fn write_and_wait<R>(&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
}
}

View file

@ -324,6 +324,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()
}

View file

@ -81,24 +81,22 @@ impl From<InputMode> for Divmode {
}
/// PWM driver.
pub struct Pwm<'d, T: Slice> {
inner: PeripheralRef<'d, T>,
pub struct Pwm<'d> {
pin_a: Option<PeripheralRef<'d, AnyPin>>,
pin_b: Option<PeripheralRef<'d, AnyPin>>,
slice: usize,
}
impl<'d, T: Slice> Pwm<'d, T> {
impl<'d> Pwm<'d> {
fn new_inner(
inner: impl Peripheral<P = T> + 'd,
slice: usize,
a: Option<PeripheralRef<'d, AnyPin>>,
b: Option<PeripheralRef<'d, AnyPin>>,
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);
@ -117,51 +115,67 @@ impl<'d, T: Slice> Pwm<'d, T> {
});
}
Self {
inner,
// 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<P = T> + 'd, config: Config) -> Self {
Self::new_inner(inner, None, None, Pull::None, config, Divmode::DIV)
pub fn new_free<T: Slice>(slice: impl Peripheral<P = T> + '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.
#[inline]
pub fn new_output_a(
inner: impl Peripheral<P = T> + 'd,
pub fn new_output_a<T: Slice>(
slice: impl Peripheral<P = T> + 'd,
a: impl Peripheral<P = impl ChannelAPin<T>> + 'd,
config: Config,
) -> Self {
into_ref!(a);
Self::new_inner(inner, Some(a.map_into()), None, Pull::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<P = T> + 'd,
pub fn new_output_b<T: Slice>(
slice: impl Peripheral<P = T> + 'd,
b: impl Peripheral<P = impl ChannelBPin<T>> + 'd,
config: Config,
) -> Self {
into_ref!(b);
Self::new_inner(inner, None, Some(b.map_into()), Pull::None, 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<P = T> + 'd,
pub fn new_output_ab<T: Slice>(
slice: impl Peripheral<P = T> + 'd,
a: impl Peripheral<P = impl ChannelAPin<T>> + 'd,
b: impl Peripheral<P = impl ChannelBPin<T>> + 'd,
config: Config,
) -> Self {
into_ref!(a, b);
into_ref!(slice, a, b);
Self::new_inner(
inner,
slice.number(),
Some(a.map_into()),
Some(b.map_into()),
Pull::None,
@ -172,30 +186,30 @@ impl<'d, T: Slice> Pwm<'d, T> {
/// Create PWM driver with a single 'b' as input pin.
#[inline]
pub fn new_input(
inner: impl Peripheral<P = T> + 'd,
pub fn new_input<T: Slice>(
slice: impl Peripheral<P = T> + 'd,
b: impl Peripheral<P = impl ChannelBPin<T>> + 'd,
b_pull: Pull,
mode: InputMode,
config: Config,
) -> Self {
into_ref!(b);
Self::new_inner(inner, None, Some(b.map_into()), b_pull, 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<P = T> + 'd,
pub fn new_output_input<T: Slice>(
slice: impl Peripheral<P = T> + 'd,
a: impl Peripheral<P = impl ChannelAPin<T>> + 'd,
b: impl Peripheral<P = impl ChannelBPin<T>> + 'd,
b_pull: Pull,
mode: InputMode,
config: Config,
) -> Self {
into_ref!(a, b);
into_ref!(slice, a, b);
Self::new_inner(
inner,
slice.number(),
Some(a.map_into()),
Some(b.map_into()),
b_pull,
@ -206,7 +220,7 @@ impl<'d, T: Slice> Pwm<'d, T> {
/// 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) {
@ -228,22 +242,22 @@ impl<'d, T: Slice> Pwm<'d, T> {
});
}
/// Advances a slices 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 slices 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() {}
}
@ -251,13 +265,13 @@ impl<'d, T: Slice> 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.
@ -281,7 +295,7 @@ impl<'d, T: Slice> Pwm<'d, T> {
#[inline]
fn bit(&self) -> u32 {
1 << self.inner.number() as usize
1 << self.slice as usize
}
}
@ -291,7 +305,7 @@ pub struct PwmBatch(u32);
impl PwmBatch {
#[inline]
/// Enable a PWM slice in this batch.
pub fn enable(&mut self, pwm: &Pwm<'_, impl Slice>) {
pub fn enable(&mut self, pwm: &Pwm<'_>) {
self.0 |= pwm.bit();
}
@ -308,9 +322,9 @@ impl PwmBatch {
}
}
impl<'d, T: Slice> 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));
}
@ -326,19 +340,14 @@ trait SealedSlice {}
#[allow(private_bounds)]
pub trait Slice: Peripheral<P = Self> + SealedSlice + Sized + 'static {
/// Slice number.
fn number(&self) -> u8;
/// Slice register block.
fn regs(&self) -> pac::pwm::Channel {
pac::PWM.ch(self.number() as _)
}
fn number(&self) -> usize;
}
macro_rules! slice {
($name:ident, $num:expr) => {
impl SealedSlice for peripherals::$name {}
impl Slice for peripherals::$name {
fn number(&self) -> u8 {
fn number(&self) -> usize {
$num
}
}

View file

@ -51,14 +51,20 @@ pub struct BufferedUartTx<'d, T: Instance> {
pub(crate) fn init_buffers<'d, T: Instance + 'd>(
_irq: impl Binding<T::Interrupt, BufferedInterruptHandler<T>>,
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
@ -95,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::<T>(irq, tx_buffer, rx_buffer);
init_buffers::<T>(irq, Some(tx_buffer), Some(rx_buffer));
Self {
rx: BufferedUartRx { phantom: PhantomData },
@ -124,7 +130,7 @@ impl<'d, T: Instance> BufferedUart<'d, T> {
Some(cts.map_into()),
config,
);
init_buffers::<T>(irq, tx_buffer, rx_buffer);
init_buffers::<T>(irq, Some(tx_buffer), Some(rx_buffer));
Self {
rx: BufferedUartRx { phantom: PhantomData },
@ -175,7 +181,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::<T>(irq, &mut [], rx_buffer);
init_buffers::<T>(irq, None, Some(rx_buffer));
Self { phantom: PhantomData }
}
@ -192,7 +198,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::<T>(irq, &mut [], rx_buffer);
init_buffers::<T>(irq, None, Some(rx_buffer));
Self { phantom: PhantomData }
}
@ -323,7 +329,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::<T>(irq, tx_buffer, &mut []);
init_buffers::<T>(irq, Some(tx_buffer), None);
Self { phantom: PhantomData }
}
@ -340,12 +346,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::<T>(irq, tx_buffer, &mut []);
init_buffers::<T>(irq, Some(tx_buffer), None);
Self { phantom: PhantomData }
}
fn write<'a>(buf: &'a [u8]) -> impl Future<Output = Result<usize, Error>> + 'a {
fn write(buf: &[u8]) -> impl Future<Output = Result<usize, Error>> + '_ {
poll_fn(move |cx| {
if buf.is_empty() {
return Poll::Ready(Ok(0));
@ -459,9 +465,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.is_empty() {
if !state.tx_buf.is_available() {
T::Interrupt::disable();
}
}
@ -472,9 +478,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.is_empty() {
if !state.rx_buf.is_available() {
T::Interrupt::disable();
}
}
@ -520,64 +526,68 @@ impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> 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.
}
}

View file

@ -231,7 +231,7 @@ impl<'d, T: Instance> UartTx<'d, T, Blocking> {
irq: impl Binding<T::Interrupt, BufferedInterruptHandler<T>>,
tx_buffer: &'d mut [u8],
) -> BufferedUartTx<'d, T> {
buffered::init_buffers::<T>(irq, tx_buffer, &mut []);
buffered::init_buffers::<T>(irq, Some(tx_buffer), None);
BufferedUartTx { phantom: PhantomData }
}
@ -352,7 +352,7 @@ impl<'d, T: Instance> UartRx<'d, T, Blocking> {
irq: impl Binding<T::Interrupt, BufferedInterruptHandler<T>>,
rx_buffer: &'d mut [u8],
) -> BufferedUartRx<'d, T> {
buffered::init_buffers::<T>(irq, &mut [], rx_buffer);
buffered::init_buffers::<T>(irq, None, Some(rx_buffer));
BufferedUartRx { phantom: PhantomData }
}
@ -690,7 +690,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::<T>(irq, tx_buffer, rx_buffer);
buffered::init_buffers::<T>(irq, Some(tx_buffer), Some(rx_buffer));
BufferedUart {
rx: BufferedUartRx { phantom: PhantomData },
@ -860,7 +860,7 @@ impl<'d, T: Instance + 'd, M: Mode> Uart<'d, T, M> {
});
}
/// sets baudrate on runtime
/// sets baudrate on runtime
pub fn set_baudrate(&mut self, baudrate: u32) {
Self::set_baudrate_inner(baudrate);
}

View file

@ -412,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) {

View file

@ -46,7 +46,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 +60,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

View file

@ -20,7 +20,7 @@ features = ["stm32wb55rg"]
[dependencies]
embassy-stm32 = { version = "0.1.0", path = "../embassy-stm32" }
embassy-sync = { version = "0.5.0", path = "../embassy-sync" }
embassy-sync = { version = "0.6.0", path = "../embassy-sync" }
embassy-time = { version = "0.3.0", 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" }
@ -35,7 +35,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]

Some files were not shown because too many files have changed in this diff Show more