Compare commits
68 Commits
executor-m
...
ehm-rc4
Author | SHA1 | Date | |
---|---|---|---|
98481c20fe | |||
5ec2fbe3a2 | |||
33e8943e5b | |||
9f9f6e75bb | |||
cbc8ccc51e | |||
485765320a | |||
27d054aa68 | |||
e579095a90 | |||
a34abd849f | |||
138ed87b95 | |||
d81395fab3 | |||
ef692c5141 | |||
9cc5d8ac89 | |||
c1438fe87b | |||
e27e00f628 | |||
7b9b22d7f8 | |||
879c0ad989 | |||
2c3d399220 | |||
b17f16f0af | |||
b60b3f4eb8 | |||
702d2a1a19 | |||
c2942f2727 | |||
2afec225e3 | |||
976a7ae22a | |||
1279a1b7f6 | |||
876faa5685 | |||
915423fc63 | |||
6782fb1efa | |||
14f41a71b6 | |||
3626deecaa | |||
b34c8e3eb1 | |||
13af76af88 | |||
2d2bd679ee | |||
dfba51d3f2 | |||
343be37f39 | |||
78f709a362 | |||
e99649e37d | |||
4051aead0f | |||
e0e5f66c4b | |||
5973e69244 | |||
4d3fcd8d2d | |||
6629c7525b | |||
02b7a833d9 | |||
a4d53c7cb1 | |||
6c746dcf39 | |||
3ef18ec133 | |||
4e7b855b2d | |||
3f30e87cb5 | |||
a9ec623622 | |||
fe218ed978 | |||
c27459c052 | |||
881cb16d28 | |||
c05149e5e4 | |||
c94a9b8d75 | |||
d87864c6a5 | |||
8fa5a6b282 | |||
83138ce68e | |||
16e31747cc | |||
536e91d263 | |||
ecaa62aa42 | |||
7561696a57 | |||
195b492158 | |||
10c9e2e723 | |||
cd62d2cd84 | |||
1f6ffdcdd2 | |||
bf7115cb44 | |||
0b0ca62a95 | |||
35f16c6003 |
2
.github/ci/build-stable.sh
vendored
2
.github/ci/build-stable.sh
vendored
@ -27,4 +27,4 @@ sed -i 's/channel.*/channel = "beta"/g' rust-toolchain.toml
|
||||
|
||||
# Save lockfiles
|
||||
echo Saving lockfiles...
|
||||
find . -type f -name Cargo.lock -exec tar -cf /ci/cache/lockfiles.tar '{}' \+
|
||||
find . -type f -name Cargo.lock -exec tar -cf /ci/cache/lockfiles.tar '{}' \+
|
||||
|
2
.github/ci/build.sh
vendored
2
.github/ci/build.sh
vendored
@ -31,4 +31,4 @@ hashtime save /ci/cache/filetime.json
|
||||
|
||||
# Save lockfiles
|
||||
echo Saving lockfiles...
|
||||
find . -type f -name Cargo.lock -exec tar -cf /ci/cache/lockfiles.tar '{}' \+
|
||||
find . -type f -name Cargo.lock -exec tar -cf /ci/cache/lockfiles.tar '{}' \+
|
||||
|
2
.github/ci/crlf.sh
vendored
2
.github/ci/crlf.sh
vendored
@ -14,4 +14,4 @@ else
|
||||
echo -e "ERROR: Found ${NR_FILES} files with CRLF endings."
|
||||
echo "$FILES_WITH_CRLF"
|
||||
exit "$NR_FILES"
|
||||
fi
|
||||
fi
|
||||
|
4
.github/ci/test.sh
vendored
4
.github/ci/test.sh
vendored
@ -4,6 +4,10 @@
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
export RUSTUP_HOME=/ci/cache/rustup
|
||||
export CARGO_HOME=/ci/cache/cargo
|
||||
export CARGO_TARGET_DIR=/ci/cache/target
|
||||
|
||||
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
|
||||
|
||||
|
2
ci.sh
2
ci.sh
@ -173,10 +173,12 @@ cargo batch \
|
||||
--- build --release --manifest-path examples/boot/application/stm32l1/Cargo.toml --target thumbv7m-none-eabi --features skip-include --out-dir out/examples/boot/stm32l1 \
|
||||
--- build --release --manifest-path examples/boot/application/stm32l4/Cargo.toml --target thumbv7em-none-eabi --features skip-include --out-dir out/examples/boot/stm32l4 \
|
||||
--- build --release --manifest-path examples/boot/application/stm32wl/Cargo.toml --target thumbv7em-none-eabihf --features skip-include --out-dir out/examples/boot/stm32wl \
|
||||
--- build --release --manifest-path examples/boot/application/stm32wb-dfu/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/boot/stm32wb-dfu \
|
||||
--- build --release --manifest-path examples/boot/bootloader/nrf/Cargo.toml --target thumbv7em-none-eabi --features embassy-nrf/nrf52840 \
|
||||
--- build --release --manifest-path examples/boot/bootloader/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9160-ns \
|
||||
--- build --release --manifest-path examples/boot/bootloader/rp/Cargo.toml --target thumbv6m-none-eabi \
|
||||
--- build --release --manifest-path examples/boot/bootloader/stm32/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32wl55jc-cm4 \
|
||||
--- build --release --manifest-path examples/boot/bootloader/stm32wb-dfu/Cargo.toml --target thumbv7em-none-eabihf \
|
||||
--- build --release --manifest-path examples/wasm/Cargo.toml --target wasm32-unknown-unknown --out-dir out/examples/wasm \
|
||||
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f103c8 --out-dir out/tests/stm32f103c8 \
|
||||
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f429zi --out-dir out/tests/stm32f429zi \
|
||||
|
@ -23,7 +23,7 @@ cortex-m = "0.7.6"
|
||||
cortex-m-rt = "0.7.0"
|
||||
futures = { version = "0.3.17", default-features = false, features = ["async-await", "cfg-target-has-atomic", "unstable"] }
|
||||
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "1.0.0-rc.2" }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "1.0.0-rc.3" }
|
||||
num_enum = { version = "0.5.7", default-features = false }
|
||||
|
||||
[package.metadata.embassy_docs]
|
||||
|
@ -9,7 +9,7 @@ use {defmt_rtt as _, panic_probe as _};
|
||||
fn main() -> ! {
|
||||
let p = embassy_stm32::init(Default::default());
|
||||
let mut led = Output::new(p.PB14, Level::High, Speed::VeryHigh);
|
||||
let button = Input::new(p.PC13, Pull::Up);
|
||||
let mut button = Input::new(p.PC13, Pull::Up);
|
||||
|
||||
loop {
|
||||
if button.is_low() {
|
||||
|
@ -1,6 +1,8 @@
|
||||
* 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:layer_by_layer.adoc[Bare metal to async]
|
||||
* xref:runtime.adoc[Executor]
|
||||
* xref:delaying_a_task.adoc[Delaying a Task]
|
||||
@ -10,6 +12,7 @@
|
||||
* xref:bootloader.adoc[Bootloader]
|
||||
|
||||
* xref:examples.adoc[Examples]
|
||||
* xref:developer.adoc[Developer]
|
||||
** xref:developer_stm32.adoc[Developer: STM32]
|
||||
* 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]
|
||||
|
53
docs/modules/ROOT/pages/best_practices.adoc
Normal file
53
docs/modules/ROOT/pages/best_practices.adoc
Normal file
@ -0,0 +1,53 @@
|
||||
= Best Practices
|
||||
|
||||
Over time, a couple of best practices have emerged. The following list should serve as a guideline for developers writing embedded software in _Rust_, especially in the context of the _Embassy_ framework.
|
||||
|
||||
== Passing Buffers by Reference
|
||||
It may be tempting to pass arrays or wrappers, like link:https://docs.rs/heapless/latest/heapless/[`heapless::Vec`], to a function or return one just like you would with a `std::Vec`. However, in most embedded applications you don't want to spend ressources on an allocator and end up placing buffers on the stack.
|
||||
This, however, can easily blow up your stack if you are not careful.
|
||||
|
||||
Consider the following example:
|
||||
[,rust]
|
||||
----
|
||||
fn process_buffer(mut buf: [u8; 1024]) -> [u8; 1024] {
|
||||
// do stuff and return new buffer
|
||||
for elem in buf.iter_mut() {
|
||||
*elem = 0;
|
||||
}
|
||||
buf
|
||||
}
|
||||
|
||||
pub fn main() -> () {
|
||||
let buf = [1u8; 1024];
|
||||
let buf_new = process_buffer(buf);
|
||||
// do stuff with buf_new
|
||||
()
|
||||
}
|
||||
----
|
||||
When calling `process_buffer` in your program, a copy of the buffer you pass to the function will be created,
|
||||
consuming another 1024 bytes.
|
||||
After the processing, another 1024 byte buffer will be placed on the stack to be returned to the caller.
|
||||
(You can check the assembly, there will be two memcopy operations, e.g., `bl __aeabi_memcpy` when compiling for a Cortex-M processor.)
|
||||
|
||||
*Possible Solution:*
|
||||
|
||||
Pass the data by reference and not by value on both, the way in and the way out.
|
||||
For example, you could return a slice of the input buffer as the output.
|
||||
Requiring the lifetime of the input slice and the output slice to be the same, the memory safetly of this procedure will be enforced by the compiler.
|
||||
|
||||
[,rust]
|
||||
----
|
||||
fn process_buffer<'a>(buf: &'a mut [u8]) -> &'a mut[u8] {
|
||||
for elem in buf.iter_mut() {
|
||||
*elem = 0;
|
||||
}
|
||||
buf
|
||||
}
|
||||
|
||||
pub fn main() -> () {
|
||||
let mut buf = [1u8; 1024];
|
||||
let buf_new = process_buffer(&mut buf);
|
||||
// do stuff with buf_new
|
||||
()
|
||||
}
|
||||
----
|
@ -45,6 +45,8 @@ The BOOTLOADER_STATE partition must be big enough to store one word per page in
|
||||
|
||||
The bootloader has a platform-agnostic part, which implements the power fail safe swapping algorithm given the boundaries set by the partitions. The platform-specific part is a minimal shim that provides additional functionality such as watchdogs or supporting the nRF52 softdevice.
|
||||
|
||||
NOTE: The linker scripts for the application and bootloader look similar, but the FLASH region must point to the BOOTLOADER partition for the bootloader, and the ACTIVE partition for the application.
|
||||
|
||||
=== FirmwareUpdater
|
||||
|
||||
The `FirmwareUpdater` is an object for conveniently flashing firmware to the DFU partition and subsequently marking it as being ready for swapping with the active partition on the next reset. Its principle methods are `write_firmware`, which is called once per the size of the flash "write block" (typically 4KiB), and `mark_updated`, which is the final call.
|
||||
@ -91,4 +93,4 @@ cp $FIRMWARE_DIR/myfirmware $FIRMWARE_DIR/myfirmware+signed
|
||||
tail -n1 $SECRETS_DIR/message.txt.sig | base64 -d -i - | dd ibs=10 skip=1 >> $FIRMWARE_DIR/myfirmware+signed
|
||||
----
|
||||
|
||||
Remember, guard the `$SECRETS_DIR/key.sec` key as compromising it means that another party can sign your firmware.
|
||||
Remember, guard the `$SECRETS_DIR/key.sec` key as compromising it means that another party can sign your firmware.
|
||||
|
9
docs/modules/ROOT/pages/embassy_in_the_wild.adoc
Normal file
9
docs/modules/ROOT/pages/embassy_in_the_wild.adoc
Normal file
@ -0,0 +1,9 @@
|
||||
= Embassy in the wild!
|
||||
|
||||
Here are known examples of real-world projects which make use of Embassy. Feel free to link:https://github.com/embassy-rs/embassy/blob/main/docs/modules/ROOT/pages/embassy_in_the_wild.adoc[add more]!
|
||||
|
||||
* link:https://github.com/cbruiz/printhor/[Printhor: The highly reliable but not necessarily functional 3D printer firmware]
|
||||
** Targets some STM32 MCUs
|
||||
* link:https://github.com/card-io-ecg/card-io-fw[Card/IO firmware] - firmware for an open source ECG device
|
||||
** Targets the ESP32-S3 or ESP32-C6 MCU
|
||||
* The link:https://github.com/lora-rs/lora-rs[lora-rs] project includes link:https://github.com/lora-rs/lora-rs/tree/main/examples/stm32l0/src/bin[various standalone examples] for NRF52840, RP2040, STM32L0 and STM32WL
|
@ -47,7 +47,8 @@ The first step to managing your binary size is to set up your link:https://doc.r
|
||||
debug = false
|
||||
lto = true
|
||||
opt-level = "s"
|
||||
incremental = true
|
||||
incremental = false
|
||||
codegen-units = 1
|
||||
----
|
||||
|
||||
All of these flags are elaborated on in the Rust Book page linked above.
|
||||
@ -135,3 +136,20 @@ embassy-time = { git = "https://github.com/embassy-rs/embassy.git", rev = "e5fdd
|
||||
----
|
||||
|
||||
Note that the git revision should match any other embassy patches or git dependencies that you are using!
|
||||
|
||||
== How can I optimize the speed of my embassy-stm32 program?
|
||||
|
||||
* Make sure RCC is set up to go as fast as possible
|
||||
* Make sure link:https://docs.rs/cortex-m/latest/cortex_m/peripheral/struct.SCB.html[flash cache] is enabled
|
||||
* build with `--release`
|
||||
* Set the following keys for the release profile in your `Cargo.toml`:
|
||||
** `opt-level = "s"`
|
||||
** `lto = "fat"`
|
||||
* Set the following keys in the `[unstable]` section of your `.cargo/config.toml`
|
||||
** `build-std = ["core"]`
|
||||
** `build-std-features = ["panic_immediate_abort"]`
|
||||
* Enable feature `embassy-time/generic-queue`, disable feature `embassy-executor/integrated-timers`
|
||||
* When using `InterruptExecutor`:
|
||||
** disable `executor-thread`
|
||||
** make `main`` spawn everything, then enable link:https://docs.rs/cortex-m/latest/cortex_m/peripheral/struct.SCB.html#method.set_sleeponexit[SCB.SLEEPONEXIT] and `loop { cortex_m::asm::wfi() }`
|
||||
** *Note:* If you need 2 priority levels, using 2 interrupt executors is better than 1 thread executor + 1 interrupt executor.
|
178
docs/modules/ROOT/pages/new_project.adoc
Normal file
178
docs/modules/ROOT/pages/new_project.adoc
Normal file
@ -0,0 +1,178 @@
|
||||
= Starting a new Embassy project
|
||||
|
||||
Once you’ve successfully xref:getting_started.adoc[run some example projects], the next step is to make a standalone Embassy project. The easiest way to do this is to adapt an example for a similar chip to the one you’re targeting.
|
||||
|
||||
As an example, let’s create a new embassy project from scratch for a STM32G474. The same instructions are applicable for any supported chip with some minor changes.
|
||||
|
||||
Run:
|
||||
|
||||
[source,bash]
|
||||
----
|
||||
cargo new stm32g474-example
|
||||
cd stm32g474-example
|
||||
----
|
||||
|
||||
to create an empty rust project:
|
||||
|
||||
[source]
|
||||
----
|
||||
stm32g474-example
|
||||
├── Cargo.toml
|
||||
└── src
|
||||
└── main.rs
|
||||
----
|
||||
|
||||
Looking in link:https://github.com/embassy-rs/embassy/tree/main/examples[the Embassy examples], we can see there’s a `stm32g4` folder. Find `src/blinky.rs` and copy its contents into our `src/main.rs`.
|
||||
|
||||
== .cargo/config.toml
|
||||
|
||||
Currently, we’d need to provide cargo with a target triple every time we run `cargo build` or `cargo run`. Let’s spare ourselves that work by copying `.cargo/config.toml` from `examples/stm32g4` into our project.
|
||||
|
||||
[source]
|
||||
----
|
||||
stm32g474-example
|
||||
├── .cargo
|
||||
│ └── config.toml
|
||||
├── Cargo.toml
|
||||
└── src
|
||||
└── main.rs
|
||||
----
|
||||
|
||||
In addition to a target triple, `.cargo/config.toml` contains a `runner` key which allows us to conveniently run our project on hardware with `cargo run` via probe-rs. In order for this to work, we need to provide the correct chip ID. We can do this by checking `probe-rs chip list`:
|
||||
|
||||
[source,bash]
|
||||
----
|
||||
$ probe-rs chip list | grep -i stm32g474re
|
||||
STM32G474RETx
|
||||
----
|
||||
|
||||
and copying `STM32G474RETx` into `.cargo/config.toml` as so:
|
||||
|
||||
[source,toml]
|
||||
----
|
||||
[target.'cfg(all(target_arch = "arm", target_os = "none"))']
|
||||
# replace STM32G071C8Rx with your chip as listed in `probe-rs chip list`
|
||||
runner = "probe-rs run --chip STM32G474RETx"
|
||||
----
|
||||
|
||||
== Cargo.toml
|
||||
|
||||
Now that cargo knows what target to compile for (and probe-rs knows what chip to run it on), we’re ready to add some dependencies.
|
||||
|
||||
Looking in `examples/stm32g4/Cargo.toml`, we can see that the examples require a number of embassy crates. For blinky, we’ll only need three of them: `embassy-stm32`, `embassy-executor` and `embassy-time`.
|
||||
|
||||
At the time of writing, the latest version of embassy isn‘t available on crates.io, so we need to install it straight from the git repository. The recommended way of doing so is as follows:
|
||||
|
||||
* Copy the required `embassy-*` lines from the example `Cargo.toml`
|
||||
* Make any necessary changes to `features`, e.g. requiring the `stm32g474re` feature of `embassy-stm32`
|
||||
* Remove the `path = ""` keys in the `embassy-*` entries
|
||||
* Create a `[patch.crates-io]` section, with entries for each embassy crate we need. These should all contain identical values: a link to the git repository, and a reference to the commit we’re checking out. Assuming you want the latest commit, you can find it by running `git ls-remote https://github.com/embassy-rs/embassy.git HEAD`
|
||||
|
||||
NOTE: When using this method, it’s necessary that the `version` keys in `[dependencies]` match up with the versions defined in each crate’s `Cargo.toml` in the specificed `rev` under `[patch.crates.io]`. This means that when updating, you have to a pick a new revision, change everything in `[patch.crates.io]` to match it, and then correct any versions under `[dependencies]` which have changed. Hopefully this will no longer be necessary once embassy is released on crates.io!
|
||||
|
||||
At the time of writing, this method produces the following results:
|
||||
|
||||
[source,toml]
|
||||
----
|
||||
[dependencies]
|
||||
embassy-stm32 = {version = "0.1.0", features = ["defmt", "time-driver-any", "stm32g474re", "memory-x", "unstable-pac", "exti"]}
|
||||
embassy-executor = { version = "0.3.3", features = ["nightly", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] }
|
||||
embassy-time = { version = "0.2", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] }
|
||||
|
||||
[patch.crates-io]
|
||||
embassy-time = { git = "https://github.com/embassy-rs/embassy", rev = "7703f47c1ecac029f603033b7977d9a2becef48c" }
|
||||
embassy-executor = { git = "https://github.com/embassy-rs/embassy", rev = "7703f47c1ecac029f603033b7977d9a2becef48c" }
|
||||
embassy-stm32 = { git = "https://github.com/embassy-rs/embassy", rev = "7703f47c1ecac029f603033b7977d9a2becef48c" }
|
||||
----
|
||||
|
||||
There are a few other dependencies we need to build the project, but fortunately they’re much simpler to install. Copy their lines from the example `Cargo.toml` to the the `[dependencies]` section in the new `Cargo.toml`:
|
||||
|
||||
[source,toml]
|
||||
----
|
||||
defmt = "0.3.5"
|
||||
defmt-rtt = "0.4.0"
|
||||
cortex-m = {version = "0.7.7", features = ["critical-section-single-core"]}
|
||||
cortex-m-rt = "0.7.3"
|
||||
panic-probe = "0.3.1"
|
||||
----
|
||||
|
||||
These are the bare minimum dependencies required to run `blinky.rs`, but it’s worth taking a look at the other dependencies specified in the example `Cargo.toml`, and noting what features are required for use with embassy – for example `futures = { version = "0.3.17", default-features = false, features = ["async-await"] }`.
|
||||
|
||||
Finally, copy the `[profile.release]` section from the example `Cargo.toml` into ours.
|
||||
|
||||
[source,toml]
|
||||
----
|
||||
[profile.release]
|
||||
debug = 2
|
||||
----
|
||||
|
||||
== 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`:
|
||||
|
||||
[source]
|
||||
----
|
||||
stm32g474-example
|
||||
├── .cargo
|
||||
│ └── config.toml
|
||||
├── Cargo.toml
|
||||
├── rust-toolchain.toml
|
||||
└── src
|
||||
└── main.rs
|
||||
----
|
||||
|
||||
[source,toml]
|
||||
----
|
||||
# Before upgrading check that everything is available on all tier1 targets here:
|
||||
# https://rust-lang.github.io/rustup-components-history
|
||||
[toolchain]
|
||||
channel = "nightly-2023-11-01"
|
||||
components = [ "rust-src", "rustfmt", "llvm-tools", "miri" ]
|
||||
targets = ["thumbv7em-none-eabi"]
|
||||
----
|
||||
|
||||
== 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:
|
||||
|
||||
[source]
|
||||
----
|
||||
stm32g474-example
|
||||
├── build.rs
|
||||
├── .cargo
|
||||
│ └── config.toml
|
||||
├── Cargo.toml
|
||||
├── rust-toolchain.toml
|
||||
└── src
|
||||
└── main.rs
|
||||
----
|
||||
|
||||
== Building and running
|
||||
|
||||
At this point, we‘re finally ready to build and run our project! Connect your board via a debug probe and run:
|
||||
|
||||
[source,bash]
|
||||
----
|
||||
cargo run --release
|
||||
----
|
||||
|
||||
should result in a blinking LED (if there’s one attached to the pin in `src/main.rs` – change it if not!) and the following output:
|
||||
|
||||
[source]
|
||||
----
|
||||
Compiling stm32g474-example v0.1.0 (/home/you/stm32g474-example)
|
||||
Finished release [optimized + debuginfo] target(s) in 0.22s
|
||||
Running `probe-rs run --chip STM32G474RETx target/thumbv7em-none-eabi/release/stm32g474-example`
|
||||
Erasing sectors ✔ [00:00:00] [#########################################################] 18.00 KiB/18.00 KiB @ 54.09 KiB/s (eta 0s )
|
||||
Programming pages ✔ [00:00:00] [#########################################################] 17.00 KiB/17.00 KiB @ 35.91 KiB/s (eta 0s ) Finished in 0.817s
|
||||
0.000000 TRACE BDCR configured: 00008200
|
||||
└─ embassy_stm32::rcc::bd::{impl#3}::init::{closure#4} @ /home/you/.cargo/git/checkouts/embassy-9312dcb0ed774b29/7703f47/embassy-stm32/src/fmt.rs:117
|
||||
0.000000 DEBUG rcc: Clocks { sys: Hertz(16000000), pclk1: Hertz(16000000), pclk1_tim: Hertz(16000000), pclk2: Hertz(16000000), pclk2_tim: Hertz(16000000), hclk1: Hertz(16000000), hclk2: Hertz(16000000), pll1_p: None, adc: None, adc34: None, rtc: Some(Hertz(32000)) }
|
||||
└─ embassy_stm32::rcc::set_freqs @ /home/you/.cargo/git/checkouts/embassy-9312dcb0ed774b29/7703f47/embassy-stm32/src/fmt.rs:130
|
||||
0.000000 INFO Hello World!
|
||||
└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:14
|
||||
0.000091 INFO high
|
||||
└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:19
|
||||
0.300201 INFO low
|
||||
└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:23
|
||||
----
|
@ -8,6 +8,24 @@ The bootloader can be used either as a library or be flashed directly with the d
|
||||
|
||||
By design, the bootloader does not provide any network capabilities. Networking capabilities for fetching new firmware can be provided by the user application, using the bootloader as a library for updating the firmware, or by using the bootloader as a library and adding this capability yourself.
|
||||
|
||||
## Overview
|
||||
|
||||
The bootloader divides the storage into 4 main partitions, configurable when creating the bootloader instance or via linker scripts:
|
||||
|
||||
* 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.
|
||||
|
||||
For any partition, the following preconditions are required:
|
||||
|
||||
* Partitions must be aligned on the page size.
|
||||
* Partitions must be a multiple of the page size.
|
||||
|
||||
The linker scripts for the application and bootloader look similar, but the FLASH region must point to the BOOTLOADER partition for the bootloader, and the ACTIVE partition for the application.
|
||||
|
||||
For more details on the bootloader, see [the documentation](https://embassy.dev/book/dev/bootloader.html).
|
||||
|
||||
## Hardware support
|
||||
|
||||
The bootloader supports different hardware in separate crates:
|
||||
@ -16,6 +34,7 @@ The bootloader supports different hardware in separate crates:
|
||||
* `embassy-boot-rp` - for the RP2040 microcontrollers.
|
||||
* `embassy-boot-stm32` - for the STM32 microcontrollers.
|
||||
|
||||
|
||||
## Minimum supported Rust version (MSRV)
|
||||
|
||||
`embassy-boot` is guaranteed to compile on the latest stable Rust version at the time of release. It might compile with older versions but that may change in any new patch release.
|
||||
|
@ -5,7 +5,7 @@ use embassy_sync::blocking_mutex::raw::NoopRawMutex;
|
||||
use embassy_sync::blocking_mutex::Mutex;
|
||||
use embedded_storage::nor_flash::{NorFlash, NorFlashError, NorFlashErrorKind};
|
||||
|
||||
use crate::{State, BOOT_MAGIC, STATE_ERASE_VALUE, SWAP_MAGIC};
|
||||
use crate::{State, BOOT_MAGIC, DFU_DETACH_MAGIC, STATE_ERASE_VALUE, SWAP_MAGIC};
|
||||
|
||||
/// Errors returned by bootloader
|
||||
#[derive(PartialEq, Eq, Debug)]
|
||||
@ -135,51 +135,44 @@ impl<ACTIVE: NorFlash, DFU: NorFlash, STATE: NorFlash> BootLoader<ACTIVE, DFU, S
|
||||
/// The provided aligned_buf argument must satisfy any alignment requirements
|
||||
/// given by the partition flashes. All flash operations will use this buffer.
|
||||
///
|
||||
/// SWAPPING
|
||||
/// ## SWAPPING
|
||||
///
|
||||
/// Assume a flash size of 3 pages for the active partition, and 4 pages for the DFU partition.
|
||||
/// The swap index contains the copy progress, as to allow continuation of the copy process on
|
||||
/// power failure. The index counter is represented within 1 or more pages (depending on total
|
||||
/// flash size), where a page X is considered swapped if index at location (X + WRITE_SIZE)
|
||||
/// flash size), where a page X is considered swapped if index at location (`X + WRITE_SIZE`)
|
||||
/// contains a zero value. This ensures that index updates can be performed atomically and
|
||||
/// avoid a situation where the wrong index value is set (page write size is "atomic").
|
||||
///
|
||||
/// +-----------+------------+--------+--------+--------+--------+
|
||||
///
|
||||
/// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
|
||||
/// +-----------+------------+--------+--------+--------+--------+
|
||||
/// |-----------|------------|--------|--------|--------|--------|
|
||||
/// | Active | 0 | 1 | 2 | 3 | - |
|
||||
/// | DFU | 0 | 3 | 2 | 1 | X |
|
||||
/// +-----------+------------+--------+--------+--------+--------+
|
||||
///
|
||||
/// The algorithm starts by copying 'backwards', and after the first step, the layout is
|
||||
/// as follows:
|
||||
///
|
||||
/// +-----------+------------+--------+--------+--------+--------+
|
||||
/// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
|
||||
/// +-----------+------------+--------+--------+--------+--------+
|
||||
/// |-----------|------------|--------|--------|--------|--------|
|
||||
/// | Active | 1 | 1 | 2 | 1 | - |
|
||||
/// | DFU | 1 | 3 | 2 | 1 | 3 |
|
||||
/// +-----------+------------+--------+--------+--------+--------+
|
||||
///
|
||||
/// The next iteration performs the same steps
|
||||
///
|
||||
/// +-----------+------------+--------+--------+--------+--------+
|
||||
/// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
|
||||
/// +-----------+------------+--------+--------+--------+--------+
|
||||
/// |-----------|------------|--------|--------|--------|--------|
|
||||
/// | Active | 2 | 1 | 2 | 1 | - |
|
||||
/// | DFU | 2 | 3 | 2 | 2 | 3 |
|
||||
/// +-----------+------------+--------+--------+--------+--------+
|
||||
///
|
||||
/// And again until we're done
|
||||
///
|
||||
/// +-----------+------------+--------+--------+--------+--------+
|
||||
/// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
|
||||
/// +-----------+------------+--------+--------+--------+--------+
|
||||
/// |-----------|------------|--------|--------|--------|--------|
|
||||
/// | Active | 3 | 3 | 2 | 1 | - |
|
||||
/// | DFU | 3 | 3 | 1 | 2 | 3 |
|
||||
/// +-----------+------------+--------+--------+--------+--------+
|
||||
///
|
||||
/// REVERTING
|
||||
/// ## REVERTING
|
||||
///
|
||||
/// The reverting algorithm uses the swap index to discover that images were swapped, but that
|
||||
/// the application failed to mark the boot successful. In this case, the revert algorithm will
|
||||
@ -190,28 +183,21 @@ impl<ACTIVE: NorFlash, DFU: NorFlash, STATE: NorFlash> BootLoader<ACTIVE, DFU, S
|
||||
///
|
||||
/// The revert algorithm works forwards, by starting copying into the 'unused' DFU page at the start.
|
||||
///
|
||||
/// +-----------+--------------+--------+--------+--------+--------+
|
||||
/// | Partition | Revert Index | Page 0 | Page 1 | Page 3 | Page 4 |
|
||||
//*/
|
||||
/// +-----------+--------------+--------+--------+--------+--------+
|
||||
/// |-----------|--------------|--------|--------|--------|--------|
|
||||
/// | Active | 3 | 1 | 2 | 1 | - |
|
||||
/// | DFU | 3 | 3 | 1 | 2 | 3 |
|
||||
/// +-----------+--------------+--------+--------+--------+--------+
|
||||
///
|
||||
///
|
||||
/// +-----------+--------------+--------+--------+--------+--------+
|
||||
/// | Partition | Revert Index | Page 0 | Page 1 | Page 3 | Page 4 |
|
||||
/// +-----------+--------------+--------+--------+--------+--------+
|
||||
/// |-----------|--------------|--------|--------|--------|--------|
|
||||
/// | Active | 3 | 1 | 2 | 1 | - |
|
||||
/// | DFU | 3 | 3 | 2 | 2 | 3 |
|
||||
/// +-----------+--------------+--------+--------+--------+--------+
|
||||
///
|
||||
/// +-----------+--------------+--------+--------+--------+--------+
|
||||
/// | Partition | Revert Index | Page 0 | Page 1 | Page 3 | Page 4 |
|
||||
/// +-----------+--------------+--------+--------+--------+--------+
|
||||
/// |-----------|--------------|--------|--------|--------|--------|
|
||||
/// | Active | 3 | 1 | 2 | 3 | - |
|
||||
/// | DFU | 3 | 3 | 2 | 1 | 3 |
|
||||
/// +-----------+--------------+--------+--------+--------+--------+
|
||||
///
|
||||
pub fn prepare_boot(&mut self, aligned_buf: &mut [u8]) -> Result<State, BootError> {
|
||||
// Ensure we have enough progress pages to store copy progress
|
||||
@ -224,6 +210,7 @@ impl<ACTIVE: NorFlash, DFU: NorFlash, STATE: NorFlash> BootLoader<ACTIVE, DFU, S
|
||||
assert_eq!(0, aligned_buf.len() % ACTIVE::WRITE_SIZE);
|
||||
assert_eq!(0, aligned_buf.len() % DFU::WRITE_SIZE);
|
||||
|
||||
// Ensure our partitions are able to handle boot operations
|
||||
assert_partitions(&self.active, &self.dfu, &self.state, Self::PAGE_SIZE);
|
||||
|
||||
// Copy contents from partition N to active
|
||||
@ -384,6 +371,8 @@ impl<ACTIVE: NorFlash, DFU: NorFlash, STATE: NorFlash> BootLoader<ACTIVE, DFU, S
|
||||
|
||||
if !state_word.iter().any(|&b| b != SWAP_MAGIC) {
|
||||
Ok(State::Swap)
|
||||
} else if !state_word.iter().any(|&b| b != DFU_DETACH_MAGIC) {
|
||||
Ok(State::DfuDetach)
|
||||
} else {
|
||||
Ok(State::Boot)
|
||||
}
|
||||
@ -398,6 +387,7 @@ fn assert_partitions<ACTIVE: NorFlash, DFU: NorFlash, STATE: NorFlash>(
|
||||
) {
|
||||
assert_eq!(active.capacity() as u32 % page_size, 0);
|
||||
assert_eq!(dfu.capacity() as u32 % page_size, 0);
|
||||
// DFU partition has to be bigger than ACTIVE partition to handle swap algorithm
|
||||
assert!(dfu.capacity() as u32 - active.capacity() as u32 >= page_size);
|
||||
assert!(2 + 2 * (active.capacity() as u32 / page_size) <= state.capacity() as u32 / STATE::WRITE_SIZE as u32);
|
||||
}
|
||||
|
@ -6,7 +6,7 @@ use embassy_sync::blocking_mutex::raw::NoopRawMutex;
|
||||
use embedded_storage_async::nor_flash::NorFlash;
|
||||
|
||||
use super::FirmwareUpdaterConfig;
|
||||
use crate::{FirmwareUpdaterError, State, BOOT_MAGIC, STATE_ERASE_VALUE, SWAP_MAGIC};
|
||||
use crate::{FirmwareUpdaterError, State, BOOT_MAGIC, DFU_DETACH_MAGIC, STATE_ERASE_VALUE, SWAP_MAGIC};
|
||||
|
||||
/// FirmwareUpdater is an application API for interacting with the BootLoader without the ability to
|
||||
/// 'mess up' the internal bootloader state
|
||||
@ -161,6 +161,12 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> FirmwareUpdater<'d, DFU, STATE> {
|
||||
self.state.mark_updated().await
|
||||
}
|
||||
|
||||
/// Mark to trigger USB DFU on next boot.
|
||||
pub async fn mark_dfu(&mut self) -> Result<(), FirmwareUpdaterError> {
|
||||
self.state.verify_booted().await?;
|
||||
self.state.mark_dfu().await
|
||||
}
|
||||
|
||||
/// Mark firmware boot successful and stop rollback on reset.
|
||||
pub async fn mark_booted(&mut self) -> Result<(), FirmwareUpdaterError> {
|
||||
self.state.mark_booted().await
|
||||
@ -207,6 +213,16 @@ pub struct FirmwareState<'d, STATE> {
|
||||
}
|
||||
|
||||
impl<'d, STATE: NorFlash> FirmwareState<'d, STATE> {
|
||||
/// Create a firmware state instance from a FirmwareUpdaterConfig with a buffer for magic content and state partition.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// The `aligned` buffer must have a size of STATE::WRITE_SIZE, and follow the alignment rules for the flash being read from
|
||||
/// and written to.
|
||||
pub fn from_config<DFU: NorFlash>(config: FirmwareUpdaterConfig<DFU, STATE>, aligned: &'d mut [u8]) -> Self {
|
||||
Self::new(config.state, aligned)
|
||||
}
|
||||
|
||||
/// Create a firmware state instance with a buffer for magic content and state partition.
|
||||
///
|
||||
/// # Safety
|
||||
@ -247,6 +263,11 @@ impl<'d, STATE: NorFlash> FirmwareState<'d, STATE> {
|
||||
self.set_magic(SWAP_MAGIC).await
|
||||
}
|
||||
|
||||
/// Mark to trigger USB DFU on next boot.
|
||||
pub async fn mark_dfu(&mut self) -> Result<(), FirmwareUpdaterError> {
|
||||
self.set_magic(DFU_DETACH_MAGIC).await
|
||||
}
|
||||
|
||||
/// Mark firmware boot successful and stop rollback on reset.
|
||||
pub async fn mark_booted(&mut self) -> Result<(), FirmwareUpdaterError> {
|
||||
self.set_magic(BOOT_MAGIC).await
|
||||
|
@ -6,7 +6,7 @@ use embassy_sync::blocking_mutex::raw::NoopRawMutex;
|
||||
use embedded_storage::nor_flash::NorFlash;
|
||||
|
||||
use super::FirmwareUpdaterConfig;
|
||||
use crate::{FirmwareUpdaterError, State, BOOT_MAGIC, STATE_ERASE_VALUE, SWAP_MAGIC};
|
||||
use crate::{FirmwareUpdaterError, State, BOOT_MAGIC, DFU_DETACH_MAGIC, STATE_ERASE_VALUE, SWAP_MAGIC};
|
||||
|
||||
/// Blocking FirmwareUpdater is an application API for interacting with the BootLoader without the ability to
|
||||
/// 'mess up' the internal bootloader state
|
||||
@ -168,6 +168,12 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<'d, DFU, STATE>
|
||||
self.state.mark_updated()
|
||||
}
|
||||
|
||||
/// Mark to trigger USB DFU device on next boot.
|
||||
pub fn mark_dfu(&mut self) -> Result<(), FirmwareUpdaterError> {
|
||||
self.state.verify_booted()?;
|
||||
self.state.mark_dfu()
|
||||
}
|
||||
|
||||
/// Mark firmware boot successful and stop rollback on reset.
|
||||
pub fn mark_booted(&mut self) -> Result<(), FirmwareUpdaterError> {
|
||||
self.state.mark_booted()
|
||||
@ -213,6 +219,16 @@ pub struct BlockingFirmwareState<'d, STATE> {
|
||||
}
|
||||
|
||||
impl<'d, STATE: NorFlash> BlockingFirmwareState<'d, STATE> {
|
||||
/// Creates a firmware state instance from a FirmwareUpdaterConfig, with a buffer for magic content and state partition.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// The `aligned` buffer must have a size of STATE::WRITE_SIZE, and follow the alignment rules for the flash being read from
|
||||
/// and written to.
|
||||
pub fn from_config<DFU: NorFlash>(config: FirmwareUpdaterConfig<DFU, STATE>, aligned: &'d mut [u8]) -> Self {
|
||||
Self::new(config.state, aligned)
|
||||
}
|
||||
|
||||
/// Create a firmware state instance with a buffer for magic content and state partition.
|
||||
///
|
||||
/// # Safety
|
||||
@ -226,7 +242,7 @@ impl<'d, STATE: NorFlash> BlockingFirmwareState<'d, STATE> {
|
||||
|
||||
// Make sure we are running a booted firmware to avoid reverting to a bad state.
|
||||
fn verify_booted(&mut self) -> Result<(), FirmwareUpdaterError> {
|
||||
if self.get_state()? == State::Boot {
|
||||
if self.get_state()? == State::Boot || self.get_state()? == State::DfuDetach {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(FirmwareUpdaterError::BadState)
|
||||
@ -243,6 +259,8 @@ impl<'d, STATE: NorFlash> BlockingFirmwareState<'d, STATE> {
|
||||
|
||||
if !self.aligned.iter().any(|&b| b != SWAP_MAGIC) {
|
||||
Ok(State::Swap)
|
||||
} else if !self.aligned.iter().any(|&b| b != DFU_DETACH_MAGIC) {
|
||||
Ok(State::DfuDetach)
|
||||
} else {
|
||||
Ok(State::Boot)
|
||||
}
|
||||
@ -253,6 +271,11 @@ impl<'d, STATE: NorFlash> BlockingFirmwareState<'d, STATE> {
|
||||
self.set_magic(SWAP_MAGIC)
|
||||
}
|
||||
|
||||
/// Mark to trigger USB DFU on next boot.
|
||||
pub fn mark_dfu(&mut self) -> Result<(), FirmwareUpdaterError> {
|
||||
self.set_magic(DFU_DETACH_MAGIC)
|
||||
}
|
||||
|
||||
/// Mark firmware boot successful and stop rollback on reset.
|
||||
pub fn mark_booted(&mut self) -> Result<(), FirmwareUpdaterError> {
|
||||
self.set_magic(BOOT_MAGIC)
|
||||
|
@ -23,6 +23,7 @@ pub use firmware_updater::{
|
||||
|
||||
pub(crate) const BOOT_MAGIC: u8 = 0xD0;
|
||||
pub(crate) const SWAP_MAGIC: u8 = 0xF0;
|
||||
pub(crate) const DFU_DETACH_MAGIC: u8 = 0xE0;
|
||||
|
||||
/// The state of the bootloader after running prepare.
|
||||
#[derive(PartialEq, Eq, Debug)]
|
||||
@ -32,6 +33,8 @@ pub enum State {
|
||||
Boot,
|
||||
/// Bootloader has swapped the active partition with the dfu partition and will attempt boot.
|
||||
Swap,
|
||||
/// Application has received a request to reboot into DFU mode to apply an update.
|
||||
DfuDetach,
|
||||
}
|
||||
|
||||
/// Buffer aligned to 32 byte boundary, largest known alignment requirement for embassy-boot.
|
||||
|
@ -10,7 +10,10 @@ pub use embassy_boot::{
|
||||
use embedded_storage::nor_flash::NorFlash;
|
||||
|
||||
/// A bootloader for STM32 devices.
|
||||
pub struct BootLoader;
|
||||
pub struct BootLoader {
|
||||
/// The reported state of the bootloader after preparing for boot
|
||||
pub state: State,
|
||||
}
|
||||
|
||||
impl BootLoader {
|
||||
/// Inspect the bootloader state and perform actions required before booting, such as swapping firmware
|
||||
@ -19,8 +22,8 @@ impl BootLoader {
|
||||
) -> Self {
|
||||
let mut aligned_buf = AlignedBuffer([0; BUFFER_SIZE]);
|
||||
let mut boot = embassy_boot::BootLoader::new(config);
|
||||
boot.prepare_boot(aligned_buf.as_mut()).expect("Boot prepare error");
|
||||
Self
|
||||
let state = boot.prepare_boot(aligned_buf.as_mut()).expect("Boot prepare error");
|
||||
Self { state }
|
||||
}
|
||||
|
||||
/// Boots the application.
|
||||
|
@ -23,8 +23,8 @@ embassy-time = { version = "0.2", path = "../embassy-time", optional = true }
|
||||
embedded-hal-02 = { package = "embedded-hal", version = "0.2.6", features = [
|
||||
"unproven",
|
||||
] }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.2" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.3" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.3" }
|
||||
embedded-storage = "0.3.1"
|
||||
embedded-storage-async = { version = "0.4.1" }
|
||||
nb = "1.0.0"
|
||||
|
@ -1,3 +1,4 @@
|
||||
//! Atomic reusable ringbuffer.
|
||||
use core::slice;
|
||||
use core::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
|
||||
|
||||
@ -14,8 +15,9 @@ use core::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
|
||||
/// One concurrent writer and one concurrent reader are supported, even at
|
||||
/// different execution priorities (like main and irq).
|
||||
pub struct RingBuffer {
|
||||
#[doc(hidden)]
|
||||
pub buf: AtomicPtr<u8>,
|
||||
pub len: AtomicUsize,
|
||||
len: AtomicUsize,
|
||||
|
||||
// start and end wrap at len*2, not at len.
|
||||
// This allows distinguishing "full" and "empty".
|
||||
@ -24,11 +26,16 @@ pub struct RingBuffer {
|
||||
//
|
||||
// This avoids having to consider the ringbuffer "full" at len-1 instead of len.
|
||||
// The usual solution is adding a "full" flag, but that can't be made atomic
|
||||
#[doc(hidden)]
|
||||
pub start: AtomicUsize,
|
||||
#[doc(hidden)]
|
||||
pub end: AtomicUsize,
|
||||
}
|
||||
|
||||
/// A type which can only read from a ring buffer.
|
||||
pub struct Reader<'a>(&'a RingBuffer);
|
||||
|
||||
/// A type which can only write to a ring buffer.
|
||||
pub struct Writer<'a>(&'a RingBuffer);
|
||||
|
||||
impl RingBuffer {
|
||||
@ -89,10 +96,12 @@ impl RingBuffer {
|
||||
Writer(self)
|
||||
}
|
||||
|
||||
/// Return length of buffer.
|
||||
pub fn len(&self) -> usize {
|
||||
self.len.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Check if buffer is full.
|
||||
pub fn is_full(&self) -> bool {
|
||||
let len = self.len.load(Ordering::Relaxed);
|
||||
let start = self.start.load(Ordering::Relaxed);
|
||||
@ -101,6 +110,7 @@ impl RingBuffer {
|
||||
self.wrap(start + len) == end
|
||||
}
|
||||
|
||||
/// Check if buffer is empty.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
let start = self.start.load(Ordering::Relaxed);
|
||||
let end = self.end.load(Ordering::Relaxed);
|
||||
@ -238,6 +248,7 @@ impl<'a> Writer<'a> {
|
||||
[(unsafe { buf.add(end) }, n0), (buf, n1)]
|
||||
}
|
||||
|
||||
/// Mark n bytes as written and advance the write index.
|
||||
pub fn push_done(&mut self, n: usize) {
|
||||
trace!(" ringbuf: push {:?}", n);
|
||||
let end = self.0.end.load(Ordering::Relaxed);
|
||||
@ -323,6 +334,7 @@ impl<'a> Reader<'a> {
|
||||
(unsafe { buf.add(start) }, n)
|
||||
}
|
||||
|
||||
/// Mark n bytes as read and allow advance the read index.
|
||||
pub fn pop_done(&mut self, n: usize) {
|
||||
trace!(" ringbuf: pop {:?}", n);
|
||||
|
||||
|
@ -1,16 +1,20 @@
|
||||
//! Types for controlling when drop is invoked.
|
||||
use core::mem;
|
||||
use core::mem::MaybeUninit;
|
||||
|
||||
#[must_use = "to delay the drop handler invokation to the end of the scope"]
|
||||
/// A type to delay the drop handler invocation.
|
||||
#[must_use = "to delay the drop handler invocation to the end of the scope"]
|
||||
pub struct OnDrop<F: FnOnce()> {
|
||||
f: MaybeUninit<F>,
|
||||
}
|
||||
|
||||
impl<F: FnOnce()> OnDrop<F> {
|
||||
/// Create a new instance.
|
||||
pub fn new(f: F) -> Self {
|
||||
Self { f: MaybeUninit::new(f) }
|
||||
}
|
||||
|
||||
/// Prevent drop handler from running.
|
||||
pub fn defuse(self) {
|
||||
mem::forget(self)
|
||||
}
|
||||
@ -34,6 +38,7 @@ pub struct DropBomb {
|
||||
}
|
||||
|
||||
impl DropBomb {
|
||||
/// Create a new instance.
|
||||
pub fn new() -> Self {
|
||||
Self { _private: () }
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
#![no_std]
|
||||
#![allow(clippy::new_without_default)]
|
||||
#![doc = include_str!("../README.md")]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
// This mod MUST go first, so that the others see its macros.
|
||||
pub(crate) mod fmt;
|
||||
|
@ -1,3 +1,4 @@
|
||||
/// Types for the peripheral singletons.
|
||||
#[macro_export]
|
||||
macro_rules! peripherals_definition {
|
||||
($($(#[$cfg:meta])? $name:ident),*$(,)?) => {
|
||||
@ -29,6 +30,7 @@ macro_rules! peripherals_definition {
|
||||
};
|
||||
}
|
||||
|
||||
/// Define the peripherals struct.
|
||||
#[macro_export]
|
||||
macro_rules! peripherals_struct {
|
||||
($($(#[$cfg:meta])? $name:ident),*$(,)?) => {
|
||||
@ -87,6 +89,7 @@ macro_rules! peripherals_struct {
|
||||
};
|
||||
}
|
||||
|
||||
/// Defining peripheral type.
|
||||
#[macro_export]
|
||||
macro_rules! peripherals {
|
||||
($($(#[$cfg:meta])? $name:ident),*$(,)?) => {
|
||||
@ -105,6 +108,7 @@ macro_rules! peripherals {
|
||||
};
|
||||
}
|
||||
|
||||
/// Convenience converting into reference.
|
||||
#[macro_export]
|
||||
macro_rules! into_ref {
|
||||
($($name:ident),*) => {
|
||||
@ -114,6 +118,7 @@ macro_rules! into_ref {
|
||||
}
|
||||
}
|
||||
|
||||
/// Implement the peripheral trait.
|
||||
#[macro_export]
|
||||
macro_rules! impl_peripheral {
|
||||
($type:ident) => {
|
||||
|
@ -20,6 +20,7 @@ pub struct PeripheralRef<'a, T> {
|
||||
}
|
||||
|
||||
impl<'a, T> PeripheralRef<'a, T> {
|
||||
/// Create a new reference to a peripheral.
|
||||
#[inline]
|
||||
pub fn new(inner: T) -> Self {
|
||||
Self {
|
||||
|
@ -1,3 +1,4 @@
|
||||
//! Types for dealing with rational numbers.
|
||||
use core::ops::{Add, Div, Mul};
|
||||
|
||||
use num_traits::{CheckedAdd, CheckedDiv, CheckedMul};
|
||||
|
@ -13,16 +13,16 @@ edition = "2021"
|
||||
heapless = "0.8"
|
||||
defmt = { version = "0.3", optional = true }
|
||||
log = { version = "0.4", default-features = false, optional = true }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.2" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal-bus = { version = "=0.1.0-rc.2", features = ["async"] }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.3" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.3" }
|
||||
embedded-hal-bus = { version = "=0.1.0-rc.3", features = ["async"] }
|
||||
embassy-net-driver-channel = { version = "0.2.0", path = "../embassy-net-driver-channel" }
|
||||
embassy-time = { version = "0.2", path = "../embassy-time" }
|
||||
embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
|
||||
bitfield = "0.14.0"
|
||||
|
||||
[dev-dependencies]
|
||||
embedded-hal-mock = { git = "https://github.com/Dirbaio/embedded-hal-mock", rev = "c5c4dca18e043e6386aee02173f61a65fea3981e", features = ["embedded-hal-async", "eh1"] }
|
||||
embedded-hal-mock = { version = "0.10.0-rc.4", features = ["embedded-hal-async", "eh1"] }
|
||||
crc = "3.0.1"
|
||||
env_logger = "0.10"
|
||||
critical-section = { version = "1.1.2", features = ["std"] }
|
||||
|
@ -8,8 +8,8 @@ license = "MIT OR Apache-2.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
embedded-hal = { version = "1.0.0-rc.2" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal = { version = "1.0.0-rc.3" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.3" }
|
||||
embassy-net-driver = { version = "0.2.0", path = "../embassy-net-driver" }
|
||||
embassy-time = { version = "0.2", path = "../embassy-time" }
|
||||
embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
|
||||
|
@ -12,8 +12,8 @@ embassy-sync = { version = "0.5.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"}
|
||||
|
||||
embedded-hal = { version = "1.0.0-rc.2" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal = { version = "1.0.0-rc.3" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.3" }
|
||||
|
||||
noproto = { git="https://github.com/embassy-rs/noproto", rev = "f5e6d1f325b6ad4e344f60452b09576e24671f62", default-features = false, features = ["derive"] }
|
||||
#noproto = { version = "0.1", path = "/home/dirbaio/noproto", default-features = false, features = ["derive"] }
|
||||
|
@ -8,8 +8,8 @@ license = "MIT OR Apache-2.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
embedded-hal = { version = "1.0.0-rc.2" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal = { version = "1.0.0-rc.3" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.3" }
|
||||
embassy-net-driver-channel = { version = "0.2.0", path = "../embassy-net-driver-channel" }
|
||||
embassy-time = { version = "0.2", path = "../embassy-time" }
|
||||
embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
|
||||
|
@ -94,8 +94,8 @@ embassy-embedded-hal = {version = "0.1.0", path = "../embassy-embedded-hal" }
|
||||
embassy-usb-driver = {version = "0.1.0", path = "../embassy-usb-driver" }
|
||||
|
||||
embedded-hal-02 = { package = "embedded-hal", version = "0.2.6", features = ["unproven"] }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.2" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.3" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.3" }
|
||||
embedded-io = { version = "0.6.0" }
|
||||
embedded-io-async = { version = "0.6.1" }
|
||||
|
||||
@ -120,4 +120,3 @@ nrf52840-pac = { version = "0.12.0", optional = true }
|
||||
nrf5340-app-pac = { version = "0.12.0", optional = true }
|
||||
nrf5340-net-pac = { version = "0.12.0", optional = true }
|
||||
nrf9160-pac = { version = "0.12.0", optional = true }
|
||||
|
||||
|
@ -52,19 +52,19 @@ impl<'d, T: Pin> Input<'d, T> {
|
||||
|
||||
/// Test if current pin level is high.
|
||||
#[inline]
|
||||
pub fn is_high(&self) -> bool {
|
||||
pub fn is_high(&mut self) -> bool {
|
||||
self.pin.is_high()
|
||||
}
|
||||
|
||||
/// Test if current pin level is low.
|
||||
#[inline]
|
||||
pub fn is_low(&self) -> bool {
|
||||
pub fn is_low(&mut self) -> bool {
|
||||
self.pin.is_low()
|
||||
}
|
||||
|
||||
/// Returns current pin level
|
||||
#[inline]
|
||||
pub fn get_level(&self) -> Level {
|
||||
pub fn get_level(&mut self) -> Level {
|
||||
self.pin.get_level()
|
||||
}
|
||||
}
|
||||
@ -160,19 +160,19 @@ impl<'d, T: Pin> Output<'d, T> {
|
||||
|
||||
/// Is the output pin set as high?
|
||||
#[inline]
|
||||
pub fn is_set_high(&self) -> bool {
|
||||
pub fn is_set_high(&mut self) -> bool {
|
||||
self.pin.is_set_high()
|
||||
}
|
||||
|
||||
/// Is the output pin set as low?
|
||||
#[inline]
|
||||
pub fn is_set_low(&self) -> bool {
|
||||
pub fn is_set_low(&mut self) -> bool {
|
||||
self.pin.is_set_low()
|
||||
}
|
||||
|
||||
/// What level output is set to
|
||||
#[inline]
|
||||
pub fn get_output_level(&self) -> Level {
|
||||
pub fn get_output_level(&mut self) -> Level {
|
||||
self.pin.get_output_level()
|
||||
}
|
||||
}
|
||||
@ -277,19 +277,24 @@ impl<'d, T: Pin> Flex<'d, T> {
|
||||
|
||||
/// Test if current pin level is high.
|
||||
#[inline]
|
||||
pub fn is_high(&self) -> bool {
|
||||
pub fn is_high(&mut self) -> bool {
|
||||
!self.is_low()
|
||||
}
|
||||
|
||||
/// Test if current pin level is low.
|
||||
#[inline]
|
||||
pub fn is_low(&self) -> bool {
|
||||
pub fn is_low(&mut self) -> bool {
|
||||
self.ref_is_low()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn ref_is_low(&self) -> bool {
|
||||
self.pin.block().in_.read().bits() & (1 << self.pin.pin()) == 0
|
||||
}
|
||||
|
||||
/// Returns current pin level
|
||||
#[inline]
|
||||
pub fn get_level(&self) -> Level {
|
||||
pub fn get_level(&mut self) -> Level {
|
||||
self.is_high().into()
|
||||
}
|
||||
|
||||
@ -316,19 +321,25 @@ impl<'d, T: Pin> Flex<'d, T> {
|
||||
|
||||
/// Is the output pin set as high?
|
||||
#[inline]
|
||||
pub fn is_set_high(&self) -> bool {
|
||||
pub fn is_set_high(&mut self) -> bool {
|
||||
!self.is_set_low()
|
||||
}
|
||||
|
||||
/// Is the output pin set as low?
|
||||
#[inline]
|
||||
pub fn is_set_low(&self) -> bool {
|
||||
pub fn is_set_low(&mut self) -> bool {
|
||||
self.ref_is_set_low()
|
||||
}
|
||||
|
||||
/// Is the output pin set as low?
|
||||
#[inline]
|
||||
pub(crate) fn ref_is_set_low(&self) -> bool {
|
||||
self.pin.block().out.read().bits() & (1 << self.pin.pin()) == 0
|
||||
}
|
||||
|
||||
/// What level output is set to
|
||||
#[inline]
|
||||
pub fn get_output_level(&self) -> Level {
|
||||
pub fn get_output_level(&mut self) -> Level {
|
||||
self.is_set_high().into()
|
||||
}
|
||||
}
|
||||
@ -498,11 +509,11 @@ mod eh02 {
|
||||
type Error = Infallible;
|
||||
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
Ok(!self.pin.ref_is_low())
|
||||
}
|
||||
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
Ok(self.pin.ref_is_low())
|
||||
}
|
||||
}
|
||||
|
||||
@ -520,11 +531,11 @@ mod eh02 {
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_02::digital::v2::StatefulOutputPin for Output<'d, T> {
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
Ok(!self.pin.ref_is_set_low())
|
||||
}
|
||||
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
Ok(self.pin.ref_is_set_low())
|
||||
}
|
||||
}
|
||||
|
||||
@ -535,11 +546,11 @@ mod eh02 {
|
||||
type Error = Infallible;
|
||||
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
Ok(!self.ref_is_low())
|
||||
}
|
||||
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
Ok(self.ref_is_low())
|
||||
}
|
||||
}
|
||||
|
||||
@ -557,11 +568,11 @@ mod eh02 {
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_02::digital::v2::StatefulOutputPin for Flex<'d, T> {
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
Ok(!self.ref_is_set_low())
|
||||
}
|
||||
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
Ok(self.ref_is_set_low())
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -571,11 +582,11 @@ impl<'d, T: Pin> embedded_hal_1::digital::ErrorType for Input<'d, T> {
|
||||
}
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::InputPin for Input<'d, T> {
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
}
|
||||
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
}
|
||||
}
|
||||
@ -595,11 +606,11 @@ impl<'d, T: Pin> embedded_hal_1::digital::OutputPin for Output<'d, T> {
|
||||
}
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::StatefulOutputPin for Output<'d, T> {
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
}
|
||||
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
}
|
||||
}
|
||||
@ -612,11 +623,11 @@ impl<'d, T: Pin> embedded_hal_1::digital::ErrorType for Flex<'d, T> {
|
||||
///
|
||||
/// If the pin is not in input mode the result is unspecified.
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::InputPin for Flex<'d, T> {
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
}
|
||||
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
}
|
||||
}
|
||||
@ -632,11 +643,11 @@ impl<'d, T: Pin> embedded_hal_1::digital::OutputPin for Flex<'d, T> {
|
||||
}
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::StatefulOutputPin for Flex<'d, T> {
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
}
|
||||
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
}
|
||||
}
|
||||
|
@ -243,7 +243,7 @@ impl<'d, C: Channel, T: GpioPin> Drop for OutputChannel<'d, C, T> {
|
||||
|
||||
impl<'d, C: Channel, T: GpioPin> OutputChannel<'d, C, T> {
|
||||
/// Create a new GPIOTE output channel driver.
|
||||
pub fn new(ch: impl Peripheral<P = C> + 'd, pin: Output<'d, T>, polarity: OutputChannelPolarity) -> Self {
|
||||
pub fn new(ch: impl Peripheral<P = C> + 'd, mut pin: Output<'d, T>, polarity: OutputChannelPolarity) -> Self {
|
||||
into_ref!(ch);
|
||||
let g = regs();
|
||||
let num = ch.number();
|
||||
@ -481,11 +481,11 @@ mod eh02 {
|
||||
type Error = Infallible;
|
||||
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.pin.is_high())
|
||||
Ok(!self.pin.pin.ref_is_low())
|
||||
}
|
||||
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.pin.is_low())
|
||||
Ok(self.pin.pin.ref_is_low())
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -495,11 +495,11 @@ impl<'d, C: Channel, T: GpioPin> embedded_hal_1::digital::ErrorType for InputCha
|
||||
}
|
||||
|
||||
impl<'d, C: Channel, T: GpioPin> embedded_hal_1::digital::InputPin for InputChannel<'d, C, T> {
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.pin.is_high())
|
||||
}
|
||||
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.pin.is_low())
|
||||
}
|
||||
}
|
||||
|
@ -97,6 +97,28 @@ mod chip;
|
||||
/// This defines the right interrupt handlers, and creates a unit struct (like `struct Irqs;`)
|
||||
/// and implements the right [`Binding`]s for it. You can pass this struct to drivers to
|
||||
/// prove at compile-time that the right interrupts have been bound.
|
||||
///
|
||||
/// Example of how to bind one interrupt:
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// use embassy_nrf::{bind_interrupts, spim, peripherals};
|
||||
///
|
||||
/// bind_interrupts!(struct Irqs {
|
||||
/// SPIM3 => spim::InterruptHandler<peripherals::SPI3>;
|
||||
/// });
|
||||
/// ```
|
||||
///
|
||||
/// Example of how to bind multiple interrupts in a single macro invocation:
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// use embassy_nrf::{bind_interrupts, spim, twim, peripherals};
|
||||
///
|
||||
/// bind_interrupts!(struct Irqs {
|
||||
/// SPIM3 => spim::InterruptHandler<peripherals::SPI3>;
|
||||
/// SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0 => twim::InterruptHandler<peripherals::TWISPI0>;
|
||||
/// });
|
||||
/// ```
|
||||
|
||||
// developer note: this macro can't be in `embassy-hal-internal` due to the use of `$crate`.
|
||||
#[macro_export]
|
||||
macro_rules! bind_interrupts {
|
||||
|
@ -78,9 +78,9 @@ fixed = "1.23.1"
|
||||
rp-pac = { version = "6" }
|
||||
|
||||
embedded-hal-02 = { package = "embedded-hal", version = "0.2.6", features = ["unproven"] }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.2" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal-nb = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.3" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.3" }
|
||||
embedded-hal-nb = { version = "=1.0.0-rc.3" }
|
||||
|
||||
pio-proc = {version= "0.2" }
|
||||
pio = {version= "0.2.1" }
|
||||
|
@ -105,18 +105,18 @@ impl<'d, T: Pin> Input<'d, T> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_high(&self) -> bool {
|
||||
pub fn is_high(&mut self) -> bool {
|
||||
self.pin.is_high()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_low(&self) -> bool {
|
||||
pub fn is_low(&mut self) -> bool {
|
||||
self.pin.is_low()
|
||||
}
|
||||
|
||||
/// Returns current pin level
|
||||
#[inline]
|
||||
pub fn get_level(&self) -> Level {
|
||||
pub fn get_level(&mut self) -> Level {
|
||||
self.pin.get_level()
|
||||
}
|
||||
|
||||
@ -357,19 +357,19 @@ impl<'d, T: Pin> Output<'d, T> {
|
||||
|
||||
/// Is the output pin set as high?
|
||||
#[inline]
|
||||
pub fn is_set_high(&self) -> bool {
|
||||
pub fn is_set_high(&mut self) -> bool {
|
||||
self.pin.is_set_high()
|
||||
}
|
||||
|
||||
/// Is the output pin set as low?
|
||||
#[inline]
|
||||
pub fn is_set_low(&self) -> bool {
|
||||
pub fn is_set_low(&mut self) -> bool {
|
||||
self.pin.is_set_low()
|
||||
}
|
||||
|
||||
/// What level output is set to
|
||||
#[inline]
|
||||
pub fn get_output_level(&self) -> Level {
|
||||
pub fn get_output_level(&mut self) -> Level {
|
||||
self.pin.get_output_level()
|
||||
}
|
||||
|
||||
@ -434,19 +434,19 @@ impl<'d, T: Pin> OutputOpenDrain<'d, T> {
|
||||
|
||||
/// Is the output level high?
|
||||
#[inline]
|
||||
pub fn is_set_high(&self) -> bool {
|
||||
pub fn is_set_high(&mut self) -> bool {
|
||||
!self.is_set_low()
|
||||
}
|
||||
|
||||
/// Is the output level low?
|
||||
#[inline]
|
||||
pub fn is_set_low(&self) -> bool {
|
||||
pub fn is_set_low(&mut self) -> bool {
|
||||
self.pin.is_set_as_output()
|
||||
}
|
||||
|
||||
/// What level output is set to
|
||||
#[inline]
|
||||
pub fn get_output_level(&self) -> Level {
|
||||
pub fn get_output_level(&mut self) -> Level {
|
||||
self.is_set_high().into()
|
||||
}
|
||||
|
||||
@ -457,18 +457,18 @@ impl<'d, T: Pin> OutputOpenDrain<'d, T> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_high(&self) -> bool {
|
||||
pub fn is_high(&mut self) -> bool {
|
||||
self.pin.is_high()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_low(&self) -> bool {
|
||||
pub fn is_low(&mut self) -> bool {
|
||||
self.pin.is_low()
|
||||
}
|
||||
|
||||
/// Returns current pin level
|
||||
#[inline]
|
||||
pub fn get_level(&self) -> Level {
|
||||
pub fn get_level(&mut self) -> Level {
|
||||
self.is_high().into()
|
||||
}
|
||||
|
||||
@ -590,7 +590,12 @@ impl<'d, T: Pin> Flex<'d, T> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_set_as_output(&self) -> bool {
|
||||
pub fn is_set_as_output(&mut self) -> bool {
|
||||
self.ref_is_set_as_output()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn ref_is_set_as_output(&self) -> bool {
|
||||
(self.pin.sio_oe().value().read() & self.bit()) != 0
|
||||
}
|
||||
|
||||
@ -600,18 +605,23 @@ impl<'d, T: Pin> Flex<'d, T> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_high(&self) -> bool {
|
||||
pub fn is_high(&mut self) -> bool {
|
||||
!self.is_low()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_low(&self) -> bool {
|
||||
pub fn is_low(&mut self) -> bool {
|
||||
self.ref_is_low()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn ref_is_low(&self) -> bool {
|
||||
self.pin.sio_in().read() & self.bit() == 0
|
||||
}
|
||||
|
||||
/// Returns current pin level
|
||||
#[inline]
|
||||
pub fn get_level(&self) -> Level {
|
||||
pub fn get_level(&mut self) -> Level {
|
||||
self.is_high().into()
|
||||
}
|
||||
|
||||
@ -638,19 +648,24 @@ impl<'d, T: Pin> Flex<'d, T> {
|
||||
|
||||
/// Is the output level high?
|
||||
#[inline]
|
||||
pub fn is_set_high(&self) -> bool {
|
||||
pub fn is_set_high(&mut self) -> bool {
|
||||
!self.is_set_low()
|
||||
}
|
||||
|
||||
/// Is the output level low?
|
||||
#[inline]
|
||||
pub fn is_set_low(&self) -> bool {
|
||||
pub fn is_set_low(&mut self) -> bool {
|
||||
self.ref_is_set_low()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn ref_is_set_low(&self) -> bool {
|
||||
(self.pin.sio_out().value().read() & self.bit()) == 0
|
||||
}
|
||||
|
||||
/// What level output is set to
|
||||
#[inline]
|
||||
pub fn get_output_level(&self) -> Level {
|
||||
pub fn get_output_level(&mut self) -> Level {
|
||||
self.is_set_high().into()
|
||||
}
|
||||
|
||||
@ -912,11 +927,11 @@ mod eh02 {
|
||||
type Error = Infallible;
|
||||
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
Ok(!self.pin.ref_is_low())
|
||||
}
|
||||
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
Ok(self.pin.ref_is_low())
|
||||
}
|
||||
}
|
||||
|
||||
@ -934,11 +949,11 @@ mod eh02 {
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_02::digital::v2::StatefulOutputPin for Output<'d, T> {
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
Ok(!self.pin.ref_is_set_low())
|
||||
}
|
||||
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
Ok(self.pin.ref_is_set_low())
|
||||
}
|
||||
}
|
||||
|
||||
@ -954,11 +969,11 @@ mod eh02 {
|
||||
type Error = Infallible;
|
||||
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
Ok(!self.pin.ref_is_low())
|
||||
}
|
||||
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
Ok(self.pin.ref_is_low())
|
||||
}
|
||||
}
|
||||
|
||||
@ -978,11 +993,11 @@ mod eh02 {
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_02::digital::v2::StatefulOutputPin for OutputOpenDrain<'d, T> {
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
Ok(!self.pin.ref_is_set_as_output())
|
||||
}
|
||||
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
Ok(self.pin.ref_is_set_as_output())
|
||||
}
|
||||
}
|
||||
|
||||
@ -998,11 +1013,11 @@ mod eh02 {
|
||||
type Error = Infallible;
|
||||
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
Ok(!self.ref_is_low())
|
||||
}
|
||||
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
Ok(self.ref_is_low())
|
||||
}
|
||||
}
|
||||
|
||||
@ -1020,11 +1035,11 @@ mod eh02 {
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_02::digital::v2::StatefulOutputPin for Flex<'d, T> {
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
Ok(!self.ref_is_set_low())
|
||||
}
|
||||
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
Ok(self.ref_is_set_low())
|
||||
}
|
||||
}
|
||||
|
||||
@ -1042,11 +1057,11 @@ impl<'d, T: Pin> embedded_hal_1::digital::ErrorType for Input<'d, T> {
|
||||
}
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::InputPin for Input<'d, T> {
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
}
|
||||
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
}
|
||||
}
|
||||
@ -1066,11 +1081,11 @@ impl<'d, T: Pin> embedded_hal_1::digital::OutputPin for Output<'d, T> {
|
||||
}
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::StatefulOutputPin for Output<'d, T> {
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
}
|
||||
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
}
|
||||
}
|
||||
@ -1096,11 +1111,11 @@ impl<'d, T: Pin> embedded_hal_1::digital::OutputPin for OutputOpenDrain<'d, T> {
|
||||
}
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::StatefulOutputPin for OutputOpenDrain<'d, T> {
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
}
|
||||
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
}
|
||||
}
|
||||
@ -1112,11 +1127,11 @@ impl<'d, T: Pin> embedded_hal_1::digital::ToggleableOutputPin for OutputOpenDrai
|
||||
}
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::InputPin for OutputOpenDrain<'d, T> {
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
}
|
||||
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
}
|
||||
}
|
||||
@ -1126,11 +1141,11 @@ impl<'d, T: Pin> embedded_hal_1::digital::ErrorType for Flex<'d, T> {
|
||||
}
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::InputPin for Flex<'d, T> {
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
}
|
||||
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
}
|
||||
}
|
||||
@ -1146,11 +1161,11 @@ impl<'d, T: Pin> embedded_hal_1::digital::OutputPin for Flex<'d, T> {
|
||||
}
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::StatefulOutputPin for Flex<'d, T> {
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
}
|
||||
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
}
|
||||
}
|
||||
|
@ -86,6 +86,17 @@ embassy_hal_internal::interrupt_mod!(
|
||||
/// This defines the right interrupt handlers, and creates a unit struct (like `struct Irqs;`)
|
||||
/// and implements the right [`Binding`]s for it. You can pass this struct to drivers to
|
||||
/// prove at compile-time that the right interrupts have been bound.
|
||||
///
|
||||
/// Example of how to bind one interrupt:
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// use embassy_rp::{bind_interrupts, usb, peripherals};
|
||||
///
|
||||
/// bind_interrupts!(struct Irqs {
|
||||
/// USBCTRL_IRQ => usb::InterruptHandler<peripherals::USB>;
|
||||
/// });
|
||||
/// ```
|
||||
///
|
||||
// developer note: this macro can't be in `embassy-hal-internal` due to the use of `$crate`.
|
||||
#[macro_export]
|
||||
macro_rules! bind_interrupts {
|
||||
|
@ -42,9 +42,9 @@ embassy-usb-driver = {version = "0.1.0", path = "../embassy-usb-driver" }
|
||||
embassy-executor = { version = "0.4.0", path = "../embassy-executor", optional = true }
|
||||
|
||||
embedded-hal-02 = { package = "embedded-hal", version = "0.2.6", features = ["unproven"] }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.2" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal-nb = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.3" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.3" }
|
||||
embedded-hal-nb = { version = "=1.0.0-rc.3" }
|
||||
|
||||
embedded-storage = "0.3.1"
|
||||
embedded-storage-async = { version = "0.4.1" }
|
||||
@ -58,7 +58,7 @@ rand_core = "0.6.3"
|
||||
sdio-host = "0.5.0"
|
||||
embedded-sdmmc = { git = "https://github.com/embassy-rs/embedded-sdmmc-rs", rev = "a4f293d3a6f72158385f79c98634cb8a14d0d2fc", optional = true }
|
||||
critical-section = "1.1"
|
||||
stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-7117ad49c06fa00c388130a34977e029910083bd" }
|
||||
stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-91cee0d1fdcb4e447b65a09756b506f4af91b7e2" }
|
||||
vcell = "0.1.3"
|
||||
bxcan = "0.7.0"
|
||||
nb = "1.0.0"
|
||||
@ -76,7 +76,7 @@ critical-section = { version = "1.1", features = ["std"] }
|
||||
[build-dependencies]
|
||||
proc-macro2 = "1.0.36"
|
||||
quote = "1.0.15"
|
||||
stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-7117ad49c06fa00c388130a34977e029910083bd", default-features = false, features = ["metadata"]}
|
||||
stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-91cee0d1fdcb4e447b65a09756b506f4af91b7e2", default-features = false, features = ["metadata"]}
|
||||
|
||||
|
||||
[features]
|
||||
@ -120,6 +120,10 @@ time-driver-tim3 = ["_time-driver"]
|
||||
time-driver-tim4 = ["_time-driver"]
|
||||
## Use TIM5 as time driver
|
||||
time-driver-tim5 = ["_time-driver"]
|
||||
## Use TIM9 as time driver
|
||||
time-driver-tim9 = ["_time-driver"]
|
||||
## Use TIM11 as time driver
|
||||
time-driver-tim11 = ["_time-driver"]
|
||||
## Use TIM12 as time driver
|
||||
time-driver-tim12 = ["_time-driver"]
|
||||
## Use TIM15 as time driver
|
||||
|
@ -187,6 +187,8 @@ fn main() {
|
||||
Some("tim3") => "TIM3",
|
||||
Some("tim4") => "TIM4",
|
||||
Some("tim5") => "TIM5",
|
||||
Some("tim9") => "TIM9",
|
||||
Some("tim11") => "TIM11",
|
||||
Some("tim12") => "TIM12",
|
||||
Some("tim15") => "TIM15",
|
||||
Some("any") => {
|
||||
@ -198,12 +200,16 @@ fn main() {
|
||||
"TIM4"
|
||||
} else if singletons.contains(&"TIM5".to_string()) {
|
||||
"TIM5"
|
||||
} else if singletons.contains(&"TIM9".to_string()) {
|
||||
"TIM9"
|
||||
} else if singletons.contains(&"TIM11".to_string()) {
|
||||
"TIM11"
|
||||
} else if singletons.contains(&"TIM12".to_string()) {
|
||||
"TIM12"
|
||||
} else if singletons.contains(&"TIM15".to_string()) {
|
||||
"TIM15"
|
||||
} else {
|
||||
panic!("time-driver-any requested, but the chip doesn't have TIM2, TIM3, TIM4, TIM5, TIM12 or TIM15.")
|
||||
panic!("time-driver-any requested, but the chip doesn't have TIM2, TIM3, TIM4, TIM5, TIM9, TIM11, TIM12 or TIM15.")
|
||||
}
|
||||
}
|
||||
_ => panic!("unknown time_driver {:?}", time_driver),
|
||||
@ -930,6 +936,10 @@ fn main() {
|
||||
} else if pin.signal.starts_with("INN") {
|
||||
// TODO handle in the future when embassy supports differential measurements
|
||||
None
|
||||
} else if pin.signal.starts_with("IN") && pin.signal.ends_with("b") {
|
||||
// we number STM32L1 ADC bank 1 as 0..=31, bank 2 as 32..=63
|
||||
let signal = pin.signal.strip_prefix("IN").unwrap().strip_suffix("b").unwrap();
|
||||
Some(32u8 + signal.parse::<u8>().unwrap())
|
||||
} else if pin.signal.starts_with("IN") {
|
||||
Some(pin.signal.strip_prefix("IN").unwrap().parse().unwrap())
|
||||
} else {
|
||||
|
@ -148,7 +148,7 @@ impl<'d, T: Instance> Adc<'d, T> {
|
||||
reg.set_cont(false);
|
||||
reg.set_exttrig(true);
|
||||
reg.set_swstart(false);
|
||||
reg.set_extsel(crate::pac::adc::vals::Extsel::SWSTART);
|
||||
reg.set_extsel(7); // SWSTART
|
||||
});
|
||||
|
||||
// Configure the channel to sample
|
||||
|
413
embassy-stm32/src/adc/f3_v1_1.rs
Normal file
413
embassy-stm32/src/adc/f3_v1_1.rs
Normal file
@ -0,0 +1,413 @@
|
||||
use core::future::poll_fn;
|
||||
use core::marker::PhantomData;
|
||||
use core::task::Poll;
|
||||
|
||||
use embassy_futures::yield_now;
|
||||
use embassy_hal_internal::into_ref;
|
||||
use embassy_time::Instant;
|
||||
|
||||
use super::Resolution;
|
||||
use crate::adc::{Adc, AdcPin, Instance, SampleTime};
|
||||
use crate::interrupt::typelevel::Interrupt;
|
||||
use crate::time::Hertz;
|
||||
use crate::{interrupt, Peripheral};
|
||||
|
||||
const ADC_FREQ: Hertz = crate::rcc::HSI_FREQ;
|
||||
|
||||
pub const VDDA_CALIB_MV: u32 = 3300;
|
||||
pub const ADC_MAX: u32 = (1 << 12) - 1;
|
||||
pub const VREF_INT: u32 = 1230;
|
||||
|
||||
pub enum AdcPowerMode {
|
||||
AlwaysOn,
|
||||
DelayOff,
|
||||
IdleOff,
|
||||
DelayIdleOff,
|
||||
}
|
||||
|
||||
pub enum Prescaler {
|
||||
Div1,
|
||||
Div2,
|
||||
Div3,
|
||||
Div4,
|
||||
}
|
||||
|
||||
/// Interrupt handler.
|
||||
pub struct InterruptHandler<T: Instance> {
|
||||
_phantom: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
|
||||
unsafe fn on_interrupt() {
|
||||
if T::regs().sr().read().eoc() {
|
||||
T::regs().cr1().modify(|w| w.set_eocie(false));
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
T::state().waker.wake();
|
||||
}
|
||||
}
|
||||
|
||||
fn update_vref<T: Instance>(op: i8) {
|
||||
static VREF_STATUS: core::sync::atomic::AtomicU8 = core::sync::atomic::AtomicU8::new(0);
|
||||
|
||||
if op > 0 {
|
||||
if VREF_STATUS.fetch_add(1, core::sync::atomic::Ordering::SeqCst) == 0 {
|
||||
T::regs().ccr().modify(|w| w.set_tsvrefe(true));
|
||||
}
|
||||
} else {
|
||||
if VREF_STATUS.fetch_sub(1, core::sync::atomic::Ordering::SeqCst) == 1 {
|
||||
T::regs().ccr().modify(|w| w.set_tsvrefe(false));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Vref<T: Instance>(core::marker::PhantomData<T>);
|
||||
impl<T: Instance> AdcPin<T> for Vref<T> {}
|
||||
impl<T: Instance> super::sealed::AdcPin<T> for Vref<T> {
|
||||
fn channel(&self) -> u8 {
|
||||
17
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Instance> Vref<T> {
|
||||
/// The value that vref would be if vdda was at 3000mv
|
||||
pub fn calibrated_value(&self) -> u16 {
|
||||
crate::pac::VREFINTCAL.data().read().value()
|
||||
}
|
||||
|
||||
pub async fn calibrate(&mut self, adc: &mut Adc<'_, T>) -> Calibration {
|
||||
let vref_val = adc.read(self).await;
|
||||
Calibration {
|
||||
vref_cal: self.calibrated_value(),
|
||||
vref_val,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Calibration {
|
||||
vref_cal: u16,
|
||||
vref_val: u16,
|
||||
}
|
||||
|
||||
impl Calibration {
|
||||
/// The millivolts that the calibration value was measured at
|
||||
pub const CALIBRATION_UV: u32 = 3_000_000;
|
||||
|
||||
/// Returns the measured VddA in microvolts (uV)
|
||||
pub fn vdda_uv(&self) -> u32 {
|
||||
(Self::CALIBRATION_UV * self.vref_cal as u32) / self.vref_val as u32
|
||||
}
|
||||
|
||||
/// Returns the measured VddA as an f32
|
||||
pub fn vdda_f32(&self) -> f32 {
|
||||
(Self::CALIBRATION_UV as f32 / 1_000.0) * (self.vref_cal as f32 / self.vref_val as f32)
|
||||
}
|
||||
|
||||
/// Returns a calibrated voltage value as in microvolts (uV)
|
||||
pub fn cal_uv(&self, raw: u16, resolution: super::Resolution) -> u32 {
|
||||
(self.vdda_uv() / resolution.to_max_count()) * raw as u32
|
||||
}
|
||||
|
||||
/// Returns a calibrated voltage value as an f32
|
||||
pub fn cal_f32(&self, raw: u16, resolution: super::Resolution) -> f32 {
|
||||
raw as f32 * self.vdda_f32() / resolution.to_max_count() as f32
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Instance> Drop for Vref<T> {
|
||||
fn drop(&mut self) {
|
||||
update_vref::<T>(-1)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Temperature<T: Instance>(core::marker::PhantomData<T>);
|
||||
impl<T: Instance> AdcPin<T> for Temperature<T> {}
|
||||
impl<T: Instance> super::sealed::AdcPin<T> for Temperature<T> {
|
||||
fn channel(&self) -> u8 {
|
||||
16
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Instance> Drop for Temperature<T> {
|
||||
fn drop(&mut self) {
|
||||
update_vref::<T>(-1)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> Adc<'d, T> {
|
||||
pub fn new(
|
||||
adc: impl Peripheral<P = T> + 'd,
|
||||
_irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
|
||||
) -> Self {
|
||||
into_ref!(adc);
|
||||
|
||||
T::enable_and_reset();
|
||||
|
||||
//let r = T::regs();
|
||||
//r.cr2().write(|w| w.set_align(true));
|
||||
|
||||
T::Interrupt::unpend();
|
||||
unsafe {
|
||||
T::Interrupt::enable();
|
||||
}
|
||||
|
||||
Self { adc }
|
||||
}
|
||||
|
||||
fn freq() -> Hertz {
|
||||
let div = T::regs().ccr().read().adcpre() + 1;
|
||||
ADC_FREQ / div as u32
|
||||
}
|
||||
|
||||
pub async fn set_resolution(&mut self, res: Resolution) {
|
||||
let was_on = Self::is_on();
|
||||
if was_on {
|
||||
self.stop_adc().await;
|
||||
}
|
||||
|
||||
T::regs().cr1().modify(|w| w.set_res(res.into()));
|
||||
|
||||
if was_on {
|
||||
self.start_adc().await;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolution(&self) -> Resolution {
|
||||
match T::regs().cr1().read().res() {
|
||||
crate::pac::adc::vals::Res::TWELVEBIT => Resolution::TwelveBit,
|
||||
crate::pac::adc::vals::Res::TENBIT => Resolution::TenBit,
|
||||
crate::pac::adc::vals::Res::EIGHTBIT => Resolution::EightBit,
|
||||
crate::pac::adc::vals::Res::SIXBIT => Resolution::SixBit,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn enable_vref(&self) -> Vref<T> {
|
||||
update_vref::<T>(1);
|
||||
|
||||
Vref(core::marker::PhantomData)
|
||||
}
|
||||
|
||||
pub fn enable_temperature(&self) -> Temperature<T> {
|
||||
T::regs().ccr().modify(|w| w.set_tsvrefe(true));
|
||||
|
||||
Temperature::<T>(core::marker::PhantomData)
|
||||
}
|
||||
|
||||
/// Perform a single conversion.
|
||||
async fn convert(&mut self) -> u16 {
|
||||
let was_on = Self::is_on();
|
||||
|
||||
if !was_on {
|
||||
self.start_adc().await;
|
||||
}
|
||||
|
||||
self.wait_sample_ready().await;
|
||||
|
||||
T::regs().sr().write(|_| {});
|
||||
T::regs().cr1().modify(|w| {
|
||||
w.set_eocie(true);
|
||||
w.set_scan(false);
|
||||
});
|
||||
T::regs().cr2().modify(|w| {
|
||||
w.set_swstart(true);
|
||||
w.set_cont(false);
|
||||
}); // swstart cleared by HW
|
||||
|
||||
let res = poll_fn(|cx| {
|
||||
T::state().waker.register(cx.waker());
|
||||
|
||||
if T::regs().sr().read().eoc() {
|
||||
let res = T::regs().dr().read().rdata();
|
||||
Poll::Ready(res)
|
||||
} else {
|
||||
Poll::Pending
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
if !was_on {
|
||||
self.stop_adc().await;
|
||||
}
|
||||
|
||||
res
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn is_on() -> bool {
|
||||
T::regs().sr().read().adons() || T::regs().cr2().read().adon()
|
||||
}
|
||||
|
||||
pub async fn start_adc(&self) {
|
||||
//defmt::trace!("Turn ADC on");
|
||||
T::regs().cr2().modify(|w| w.set_adon(true));
|
||||
//defmt::trace!("Waiting for ADC to turn on");
|
||||
|
||||
let mut t = Instant::now();
|
||||
|
||||
while !T::regs().sr().read().adons() {
|
||||
yield_now().await;
|
||||
if t.elapsed() > embassy_time::Duration::from_millis(1000) {
|
||||
t = Instant::now();
|
||||
//defmt::trace!("ADC still not on");
|
||||
}
|
||||
}
|
||||
|
||||
//defmt::trace!("ADC on");
|
||||
}
|
||||
|
||||
pub async fn stop_adc(&self) {
|
||||
if T::regs().cr2().read().adon() {
|
||||
//defmt::trace!("ADC should be on, wait for it to start");
|
||||
while !T::regs().csr().read().adons1() {
|
||||
yield_now().await;
|
||||
}
|
||||
}
|
||||
|
||||
//defmt::trace!("Turn ADC off");
|
||||
|
||||
T::regs().cr2().modify(|w| w.set_adon(false));
|
||||
|
||||
//defmt::trace!("Waiting for ADC to turn off");
|
||||
|
||||
while T::regs().csr().read().adons1() {
|
||||
yield_now().await;
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn read(&mut self, pin: &mut impl AdcPin<T>) -> u16 {
|
||||
self.set_sample_sequence(&[pin.channel()]).await;
|
||||
self.convert().await
|
||||
}
|
||||
|
||||
async fn wait_sample_ready(&self) {
|
||||
//trace!("Waiting for sample channel to be ready");
|
||||
while T::regs().sr().read().rcnr() {
|
||||
yield_now().await;
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn set_sample_time(&mut self, pin: &mut impl AdcPin<T>, sample_time: SampleTime) {
|
||||
if Self::get_channel_sample_time(pin.channel()) != sample_time {
|
||||
self.stop_adc().await;
|
||||
unsafe {
|
||||
Self::set_channel_sample_time(pin.channel(), sample_time);
|
||||
}
|
||||
self.start_adc().await;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_sample_time(&self, pin: &impl AdcPin<T>) -> SampleTime {
|
||||
Self::get_channel_sample_time(pin.channel())
|
||||
}
|
||||
|
||||
/// Sets the channel sample time
|
||||
///
|
||||
/// ## SAFETY:
|
||||
/// - ADON == 0 i.e ADC must not be enabled when this is called.
|
||||
unsafe fn set_channel_sample_time(ch: u8, sample_time: SampleTime) {
|
||||
let sample_time = sample_time.into();
|
||||
|
||||
match ch {
|
||||
0..=9 => T::regs().smpr3().modify(|reg| reg.set_smp(ch as _, sample_time)),
|
||||
10..=19 => T::regs()
|
||||
.smpr2()
|
||||
.modify(|reg| reg.set_smp(ch as usize - 10, sample_time)),
|
||||
20..=29 => T::regs()
|
||||
.smpr1()
|
||||
.modify(|reg| reg.set_smp(ch as usize - 20, sample_time)),
|
||||
30..=31 => T::regs()
|
||||
.smpr0()
|
||||
.modify(|reg| reg.set_smp(ch as usize - 30, sample_time)),
|
||||
_ => panic!("Invalid channel to sample"),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_channel_sample_time(ch: u8) -> SampleTime {
|
||||
match ch {
|
||||
0..=9 => T::regs().smpr3().read().smp(ch as _),
|
||||
10..=19 => T::regs().smpr2().read().smp(ch as usize - 10),
|
||||
20..=29 => T::regs().smpr1().read().smp(ch as usize - 20),
|
||||
30..=31 => T::regs().smpr0().read().smp(ch as usize - 30),
|
||||
_ => panic!("Invalid channel to sample"),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Sets the sequence to sample the ADC. Must be less than 28 elements.
|
||||
async fn set_sample_sequence(&self, sequence: &[u8]) {
|
||||
assert!(sequence.len() <= 28);
|
||||
let mut iter = sequence.iter();
|
||||
T::regs().sqr1().modify(|w| w.set_l((sequence.len() - 1) as _));
|
||||
for (idx, ch) in iter.by_ref().take(6).enumerate() {
|
||||
T::regs().sqr5().modify(|w| w.set_sq(idx, *ch));
|
||||
}
|
||||
for (idx, ch) in iter.by_ref().take(6).enumerate() {
|
||||
T::regs().sqr4().modify(|w| w.set_sq(idx, *ch));
|
||||
}
|
||||
for (idx, ch) in iter.by_ref().take(6).enumerate() {
|
||||
T::regs().sqr3().modify(|w| w.set_sq(idx, *ch));
|
||||
}
|
||||
for (idx, ch) in iter.by_ref().take(6).enumerate() {
|
||||
T::regs().sqr2().modify(|w| w.set_sq(idx, *ch));
|
||||
}
|
||||
for (idx, ch) in iter.by_ref().take(4).enumerate() {
|
||||
T::regs().sqr1().modify(|w| w.set_sq(idx, *ch));
|
||||
}
|
||||
}
|
||||
|
||||
fn get_res_clks(res: Resolution) -> u32 {
|
||||
match res {
|
||||
Resolution::TwelveBit => 12,
|
||||
Resolution::TenBit => 11,
|
||||
Resolution::EightBit => 9,
|
||||
Resolution::SixBit => 7,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_sample_time_clks(sample_time: SampleTime) -> u32 {
|
||||
match sample_time {
|
||||
SampleTime::Cycles4 => 4,
|
||||
SampleTime::Cycles9 => 9,
|
||||
SampleTime::Cycles16 => 16,
|
||||
SampleTime::Cycles24 => 24,
|
||||
SampleTime::Cycles48 => 48,
|
||||
SampleTime::Cycles96 => 96,
|
||||
SampleTime::Cycles192 => 192,
|
||||
SampleTime::Cycles384 => 384,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sample_time_for_us(&self, us: u32) -> SampleTime {
|
||||
let res_clks = Self::get_res_clks(self.resolution());
|
||||
let us_clks = us * Self::freq().0 / 1_000_000;
|
||||
let clks = us_clks.saturating_sub(res_clks);
|
||||
match clks {
|
||||
0..=4 => SampleTime::Cycles4,
|
||||
5..=9 => SampleTime::Cycles9,
|
||||
10..=16 => SampleTime::Cycles16,
|
||||
17..=24 => SampleTime::Cycles24,
|
||||
25..=48 => SampleTime::Cycles48,
|
||||
49..=96 => SampleTime::Cycles96,
|
||||
97..=192 => SampleTime::Cycles192,
|
||||
193.. => SampleTime::Cycles384,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn us_for_cfg(&self, res: Resolution, sample_time: SampleTime) -> u32 {
|
||||
let res_clks = Self::get_res_clks(res);
|
||||
let sample_clks = Self::get_sample_time_clks(sample_time);
|
||||
(res_clks + sample_clks) * 1_000_000 / Self::freq().0
|
||||
}
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> Drop for Adc<'d, T> {
|
||||
fn drop(&mut self) {
|
||||
while !T::regs().sr().read().adons() {}
|
||||
|
||||
T::regs().cr2().modify(|w| w.set_adon(false));
|
||||
|
||||
T::disable();
|
||||
}
|
||||
}
|
@ -3,6 +3,7 @@
|
||||
#[cfg(not(adc_f3_v2))]
|
||||
#[cfg_attr(adc_f1, path = "f1.rs")]
|
||||
#[cfg_attr(adc_f3, path = "f3.rs")]
|
||||
#[cfg_attr(adc_f3_v1_1, path = "f3_v1_1.rs")]
|
||||
#[cfg_attr(adc_v1, path = "v1.rs")]
|
||||
#[cfg_attr(adc_v2, path = "v2.rs")]
|
||||
#[cfg_attr(any(adc_v3, adc_g0), path = "v3.rs")]
|
||||
@ -26,20 +27,20 @@ use crate::peripherals;
|
||||
pub struct Adc<'d, T: Instance> {
|
||||
#[allow(unused)]
|
||||
adc: crate::PeripheralRef<'d, T>,
|
||||
#[cfg(not(adc_f3_v2))]
|
||||
#[cfg(not(any(adc_f3_v2, adc_f3_v1_1)))]
|
||||
sample_time: SampleTime,
|
||||
}
|
||||
|
||||
pub(crate) mod sealed {
|
||||
#[cfg(any(adc_f1, adc_f3, adc_v1))]
|
||||
#[cfg(any(adc_f1, adc_f3, adc_v1, adc_f3_v1_1))]
|
||||
use embassy_sync::waitqueue::AtomicWaker;
|
||||
|
||||
#[cfg(any(adc_f1, adc_f3, adc_v1))]
|
||||
#[cfg(any(adc_f1, adc_f3, adc_v1, adc_f3_v1_1))]
|
||||
pub struct State {
|
||||
pub waker: AtomicWaker,
|
||||
}
|
||||
|
||||
#[cfg(any(adc_f1, adc_f3, adc_v1))]
|
||||
#[cfg(any(adc_f1, adc_f3, adc_v1, adc_f3_v1_1))]
|
||||
impl State {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
@ -54,11 +55,11 @@ pub(crate) mod sealed {
|
||||
|
||||
pub trait Instance: InterruptableInstance {
|
||||
fn regs() -> crate::pac::adc::Adc;
|
||||
#[cfg(not(any(adc_f1, adc_v1, adc_f3_v2, adc_g0)))]
|
||||
#[cfg(not(any(adc_f1, adc_v1, adc_f3_v2, adc_f3_v1_1, adc_g0)))]
|
||||
fn common_regs() -> crate::pac::adccommon::AdcCommon;
|
||||
#[cfg(adc_f3)]
|
||||
fn frequency() -> crate::time::Hertz;
|
||||
#[cfg(any(adc_f1, adc_f3, adc_v1))]
|
||||
#[cfg(any(adc_f1, adc_f3, adc_v1, adc_f3_v1_1))]
|
||||
fn state() -> &'static State;
|
||||
}
|
||||
|
||||
@ -74,9 +75,9 @@ pub(crate) mod sealed {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_g0)))]
|
||||
#[cfg(not(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_f3_v1_1, adc_g0)))]
|
||||
pub trait Instance: sealed::Instance + crate::Peripheral<P = Self> {}
|
||||
#[cfg(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_g0))]
|
||||
#[cfg(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_f3_v1_1, adc_g0))]
|
||||
pub trait Instance: sealed::Instance + crate::Peripheral<P = Self> + crate::rcc::RccPeripheral {}
|
||||
|
||||
pub trait AdcPin<T: Instance>: sealed::AdcPin<T> {}
|
||||
@ -89,7 +90,7 @@ foreach_adc!(
|
||||
crate::pac::$inst
|
||||
}
|
||||
|
||||
#[cfg(not(any(adc_f1, adc_v1, adc_f3_v2, adc_g0)))]
|
||||
#[cfg(not(any(adc_f1, adc_v1, adc_f3_v2, adc_f3_v1_1, adc_g0)))]
|
||||
fn common_regs() -> crate::pac::adccommon::AdcCommon {
|
||||
return crate::pac::$common_inst
|
||||
}
|
||||
@ -99,7 +100,7 @@ foreach_adc!(
|
||||
unsafe { crate::rcc::get_freqs() }.$clock.unwrap()
|
||||
}
|
||||
|
||||
#[cfg(any(adc_f1, adc_f3, adc_v1))]
|
||||
#[cfg(any(adc_f1, adc_f3, adc_v1, adc_f3_v1_1))]
|
||||
fn state() -> &'static sealed::State {
|
||||
static STATE: sealed::State = sealed::State::new();
|
||||
&STATE
|
||||
|
@ -1,5 +1,6 @@
|
||||
#[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3))]
|
||||
#[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3, adc_f3_v1_1))]
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum Resolution {
|
||||
TwelveBit,
|
||||
TenBit,
|
||||
@ -9,6 +10,7 @@ pub enum Resolution {
|
||||
|
||||
#[cfg(adc_v4)]
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum Resolution {
|
||||
SixteenBit,
|
||||
FourteenBit,
|
||||
@ -19,7 +21,7 @@ pub enum Resolution {
|
||||
|
||||
impl Default for Resolution {
|
||||
fn default() -> Self {
|
||||
#[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3))]
|
||||
#[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3, adc_f3_v1_1))]
|
||||
{
|
||||
Self::TwelveBit
|
||||
}
|
||||
@ -40,7 +42,7 @@ impl From<Resolution> for crate::pac::adc::vals::Res {
|
||||
Resolution::TwelveBit => crate::pac::adc::vals::Res::TWELVEBIT,
|
||||
Resolution::TenBit => crate::pac::adc::vals::Res::TENBIT,
|
||||
Resolution::EightBit => crate::pac::adc::vals::Res::EIGHTBIT,
|
||||
#[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3))]
|
||||
#[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3, adc_f3_v1_1))]
|
||||
Resolution::SixBit => crate::pac::adc::vals::Res::SIXBIT,
|
||||
}
|
||||
}
|
||||
@ -56,7 +58,7 @@ impl Resolution {
|
||||
Resolution::TwelveBit => (1 << 12) - 1,
|
||||
Resolution::TenBit => (1 << 10) - 1,
|
||||
Resolution::EightBit => (1 << 8) - 1,
|
||||
#[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3))]
|
||||
#[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3, adc_f3_v1_1))]
|
||||
Resolution::SixBit => (1 << 6) - 1,
|
||||
}
|
||||
}
|
||||
|
@ -3,6 +3,7 @@ macro_rules! impl_sample_time {
|
||||
($default_doc:expr, $default:ident, ($(($doc:expr, $variant:ident, $pac_variant:ident)),*)) => {
|
||||
#[doc = concat!("ADC sample time\n\nThe default setting is ", $default_doc, " ADC clock cycles.")]
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum SampleTime {
|
||||
$(
|
||||
#[doc = concat!($doc, " ADC clock cycles.")]
|
||||
@ -18,6 +19,14 @@ macro_rules! impl_sample_time {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<crate::pac::adc::vals::SampleTime> for SampleTime {
|
||||
fn from(sample_time: crate::pac::adc::vals::SampleTime) -> SampleTime {
|
||||
match sample_time {
|
||||
$(crate::pac::adc::vals::SampleTime::$pac_variant => SampleTime::$variant),*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for SampleTime {
|
||||
fn default() -> Self {
|
||||
Self::$default
|
||||
@ -121,3 +130,19 @@ impl_sample_time!(
|
||||
("601.5", Cycles601_5, CYCLES601_5)
|
||||
)
|
||||
);
|
||||
|
||||
#[cfg(any(adc_f3_v1_1))]
|
||||
impl_sample_time!(
|
||||
"4",
|
||||
Cycles4,
|
||||
(
|
||||
("4", Cycles4, CYCLES4),
|
||||
("9", Cycles9, CYCLES9),
|
||||
("16", Cycles16, CYCLES16),
|
||||
("24", Cycles24, CYCLES24),
|
||||
("48", Cycles48, CYCLES48),
|
||||
("96", Cycles96, CYCLES96),
|
||||
("192", Cycles192, CYCLES192),
|
||||
("384", Cycles384, CYCLES384)
|
||||
)
|
||||
);
|
||||
|
@ -1,6 +1,6 @@
|
||||
#![macro_use]
|
||||
|
||||
#[cfg_attr(can_bxcan, path = "bxcan.rs")]
|
||||
#[cfg_attr(can_fdcan, path = "fdcan.rs")]
|
||||
#[cfg_attr(any(can_fdcan_v1, can_fdcan_h7), path = "fdcan.rs")]
|
||||
mod _version;
|
||||
pub use _version::*;
|
||||
|
@ -97,15 +97,15 @@ impl<'d, T: GpioPin> ExtiInput<'d, T> {
|
||||
Self { pin }
|
||||
}
|
||||
|
||||
pub fn is_high(&self) -> bool {
|
||||
pub fn is_high(&mut self) -> bool {
|
||||
self.pin.is_high()
|
||||
}
|
||||
|
||||
pub fn is_low(&self) -> bool {
|
||||
pub fn is_low(&mut self) -> bool {
|
||||
self.pin.is_low()
|
||||
}
|
||||
|
||||
pub fn get_level(&self) -> Level {
|
||||
pub fn get_level(&mut self) -> Level {
|
||||
self.pin.get_level()
|
||||
}
|
||||
|
||||
@ -142,11 +142,11 @@ impl<'d, T: GpioPin> embedded_hal_02::digital::v2::InputPin for ExtiInput<'d, T>
|
||||
type Error = Infallible;
|
||||
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
Ok(!self.pin.pin.ref_is_low())
|
||||
}
|
||||
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
Ok(self.pin.pin.ref_is_low())
|
||||
}
|
||||
}
|
||||
|
||||
@ -155,11 +155,11 @@ impl<'d, T: GpioPin> embedded_hal_1::digital::ErrorType for ExtiInput<'d, T> {
|
||||
}
|
||||
|
||||
impl<'d, T: GpioPin> embedded_hal_1::digital::InputPin for ExtiInput<'d, T> {
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
}
|
||||
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
}
|
||||
}
|
||||
|
@ -142,36 +142,46 @@ impl<'d, T: Pin> Flex<'d, T> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_high(&self) -> bool {
|
||||
!self.is_low()
|
||||
pub fn is_high(&mut self) -> bool {
|
||||
!self.ref_is_low()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_low(&self) -> bool {
|
||||
pub fn is_low(&mut self) -> bool {
|
||||
self.ref_is_low()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn ref_is_low(&self) -> bool {
|
||||
let state = self.pin.block().idr().read().idr(self.pin.pin() as _);
|
||||
state == vals::Idr::LOW
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_level(&self) -> Level {
|
||||
pub fn get_level(&mut self) -> Level {
|
||||
self.is_high().into()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_set_high(&self) -> bool {
|
||||
!self.is_set_low()
|
||||
pub fn is_set_high(&mut self) -> bool {
|
||||
!self.ref_is_set_low()
|
||||
}
|
||||
|
||||
/// Is the output pin set as low?
|
||||
#[inline]
|
||||
pub fn is_set_low(&self) -> bool {
|
||||
pub fn is_set_low(&mut self) -> bool {
|
||||
self.ref_is_set_low()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn ref_is_set_low(&self) -> bool {
|
||||
let state = self.pin.block().odr().read().odr(self.pin.pin() as _);
|
||||
state == vals::Odr::LOW
|
||||
}
|
||||
|
||||
/// What level output is set to
|
||||
#[inline]
|
||||
pub fn get_output_level(&self) -> Level {
|
||||
pub fn get_output_level(&mut self) -> Level {
|
||||
self.is_set_high().into()
|
||||
}
|
||||
|
||||
@ -310,17 +320,17 @@ impl<'d, T: Pin> Input<'d, T> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_high(&self) -> bool {
|
||||
pub fn is_high(&mut self) -> bool {
|
||||
self.pin.is_high()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_low(&self) -> bool {
|
||||
pub fn is_low(&mut self) -> bool {
|
||||
self.pin.is_low()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_level(&self) -> Level {
|
||||
pub fn get_level(&mut self) -> Level {
|
||||
self.pin.get_level()
|
||||
}
|
||||
}
|
||||
@ -399,19 +409,19 @@ impl<'d, T: Pin> Output<'d, T> {
|
||||
|
||||
/// Is the output pin set as high?
|
||||
#[inline]
|
||||
pub fn is_set_high(&self) -> bool {
|
||||
pub fn is_set_high(&mut self) -> bool {
|
||||
self.pin.is_set_high()
|
||||
}
|
||||
|
||||
/// Is the output pin set as low?
|
||||
#[inline]
|
||||
pub fn is_set_low(&self) -> bool {
|
||||
pub fn is_set_low(&mut self) -> bool {
|
||||
self.pin.is_set_low()
|
||||
}
|
||||
|
||||
/// What level output is set to
|
||||
#[inline]
|
||||
pub fn get_output_level(&self) -> Level {
|
||||
pub fn get_output_level(&mut self) -> Level {
|
||||
self.pin.get_output_level()
|
||||
}
|
||||
|
||||
@ -453,18 +463,18 @@ impl<'d, T: Pin> OutputOpenDrain<'d, T> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_high(&self) -> bool {
|
||||
pub fn is_high(&mut self) -> bool {
|
||||
!self.pin.is_low()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_low(&self) -> bool {
|
||||
pub fn is_low(&mut self) -> bool {
|
||||
self.pin.is_low()
|
||||
}
|
||||
|
||||
/// Returns current pin level
|
||||
#[inline]
|
||||
pub fn get_level(&self) -> Level {
|
||||
pub fn get_level(&mut self) -> Level {
|
||||
self.pin.get_level()
|
||||
}
|
||||
|
||||
@ -488,19 +498,19 @@ impl<'d, T: Pin> OutputOpenDrain<'d, T> {
|
||||
|
||||
/// Is the output pin set as high?
|
||||
#[inline]
|
||||
pub fn is_set_high(&self) -> bool {
|
||||
pub fn is_set_high(&mut self) -> bool {
|
||||
self.pin.is_set_high()
|
||||
}
|
||||
|
||||
/// Is the output pin set as low?
|
||||
#[inline]
|
||||
pub fn is_set_low(&self) -> bool {
|
||||
pub fn is_set_low(&mut self) -> bool {
|
||||
self.pin.is_set_low()
|
||||
}
|
||||
|
||||
/// What level output is set to
|
||||
#[inline]
|
||||
pub fn get_output_level(&self) -> Level {
|
||||
pub fn get_output_level(&mut self) -> Level {
|
||||
self.pin.get_output_level()
|
||||
}
|
||||
|
||||
@ -777,12 +787,12 @@ impl<'d, T: Pin> embedded_hal_02::digital::v2::InputPin for Input<'d, T> {
|
||||
|
||||
#[inline]
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
Ok(!self.pin.ref_is_low())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
Ok(self.pin.ref_is_low())
|
||||
}
|
||||
}
|
||||
|
||||
@ -805,13 +815,13 @@ impl<'d, T: Pin> embedded_hal_02::digital::v2::OutputPin for Output<'d, T> {
|
||||
impl<'d, T: Pin> embedded_hal_02::digital::v2::StatefulOutputPin for Output<'d, T> {
|
||||
#[inline]
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
Ok(!self.pin.ref_is_set_low())
|
||||
}
|
||||
|
||||
/// Is the output pin set as low?
|
||||
#[inline]
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
Ok(self.pin.ref_is_set_low())
|
||||
}
|
||||
}
|
||||
|
||||
@ -843,13 +853,13 @@ impl<'d, T: Pin> embedded_hal_02::digital::v2::OutputPin for OutputOpenDrain<'d,
|
||||
impl<'d, T: Pin> embedded_hal_02::digital::v2::StatefulOutputPin for OutputOpenDrain<'d, T> {
|
||||
#[inline]
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
Ok(!self.pin.ref_is_set_low())
|
||||
}
|
||||
|
||||
/// Is the output pin set as low?
|
||||
#[inline]
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
Ok(self.pin.ref_is_set_low())
|
||||
}
|
||||
}
|
||||
|
||||
@ -867,12 +877,12 @@ impl<'d, T: Pin> embedded_hal_02::digital::v2::InputPin for Flex<'d, T> {
|
||||
|
||||
#[inline]
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
Ok(!self.ref_is_low())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
Ok(self.ref_is_low())
|
||||
}
|
||||
}
|
||||
|
||||
@ -895,13 +905,13 @@ impl<'d, T: Pin> embedded_hal_02::digital::v2::OutputPin for Flex<'d, T> {
|
||||
impl<'d, T: Pin> embedded_hal_02::digital::v2::StatefulOutputPin for Flex<'d, T> {
|
||||
#[inline]
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
Ok(!self.ref_is_set_low())
|
||||
}
|
||||
|
||||
/// Is the output pin set as low?
|
||||
#[inline]
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
Ok(self.ref_is_set_low())
|
||||
}
|
||||
}
|
||||
|
||||
@ -920,12 +930,12 @@ impl<'d, T: Pin> embedded_hal_1::digital::ErrorType for Input<'d, T> {
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::InputPin for Input<'d, T> {
|
||||
#[inline]
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
}
|
||||
}
|
||||
@ -948,13 +958,13 @@ impl<'d, T: Pin> embedded_hal_1::digital::OutputPin for Output<'d, T> {
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::StatefulOutputPin for Output<'d, T> {
|
||||
#[inline]
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
}
|
||||
|
||||
/// Is the output pin set as low?
|
||||
#[inline]
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
}
|
||||
}
|
||||
@ -972,12 +982,12 @@ impl<'d, T: Pin> embedded_hal_1::digital::ErrorType for OutputOpenDrain<'d, T> {
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::InputPin for OutputOpenDrain<'d, T> {
|
||||
#[inline]
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
}
|
||||
}
|
||||
@ -996,13 +1006,13 @@ impl<'d, T: Pin> embedded_hal_1::digital::OutputPin for OutputOpenDrain<'d, T> {
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::StatefulOutputPin for OutputOpenDrain<'d, T> {
|
||||
#[inline]
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
}
|
||||
|
||||
/// Is the output pin set as low?
|
||||
#[inline]
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
}
|
||||
}
|
||||
@ -1016,12 +1026,12 @@ impl<'d, T: Pin> embedded_hal_1::digital::ToggleableOutputPin for OutputOpenDrai
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::InputPin for Flex<'d, T> {
|
||||
#[inline]
|
||||
fn is_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_high())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_low())
|
||||
}
|
||||
}
|
||||
@ -1051,13 +1061,13 @@ impl<'d, T: Pin> embedded_hal_1::digital::ErrorType for Flex<'d, T> {
|
||||
|
||||
impl<'d, T: Pin> embedded_hal_1::digital::StatefulOutputPin for Flex<'d, T> {
|
||||
#[inline]
|
||||
fn is_set_high(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_high(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_high())
|
||||
}
|
||||
|
||||
/// Is the output pin set as low?
|
||||
#[inline]
|
||||
fn is_set_low(&self) -> Result<bool, Self::Error> {
|
||||
fn is_set_low(&mut self) -> Result<bool, Self::Error> {
|
||||
Ok(self.is_set_low())
|
||||
}
|
||||
}
|
||||
|
@ -90,6 +90,29 @@ pub use crate::_generated::interrupt;
|
||||
/// This defines the right interrupt handlers, and creates a unit struct (like `struct Irqs;`)
|
||||
/// and implements the right [`Binding`]s for it. You can pass this struct to drivers to
|
||||
/// prove at compile-time that the right interrupts have been bound.
|
||||
///
|
||||
/// Example of how to bind one interrupt:
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// use embassy_stm32::{bind_interrupts, usb_otg, peripherals};
|
||||
///
|
||||
/// bind_interrupts!(struct Irqs {
|
||||
/// OTG_FS => usb_otg::InterruptHandler<peripherals::USB_OTG_FS>;
|
||||
/// });
|
||||
/// ```
|
||||
///
|
||||
/// Example of how to bind multiple interrupts, and multiple handlers to each interrupt, in a single macro invocation:
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// use embassy_stm32::{bind_interrupts, i2c, peripherals};
|
||||
///
|
||||
/// bind_interrupts!(struct Irqs {
|
||||
/// I2C1 => i2c::EventInterruptHandler<peripherals::I2C1>, i2c::ErrorInterruptHandler<peripherals::I2C1>;
|
||||
/// I2C2_3 => i2c::EventInterruptHandler<peripherals::I2C2>, i2c::ErrorInterruptHandler<peripherals::I2C2>,
|
||||
/// i2c::EventInterruptHandler<peripherals::I2C3>, i2c::ErrorInterruptHandler<peripherals::I2C3>;
|
||||
/// });
|
||||
/// ```
|
||||
|
||||
// developer note: this macro can't be in `embassy-hal-internal` due to the use of `$crate`.
|
||||
#[macro_export]
|
||||
macro_rules! bind_interrupts {
|
||||
|
@ -308,6 +308,7 @@ pub(crate) unsafe fn init(config: Config) {
|
||||
sys: sys_clk,
|
||||
hclk1: ahb_freq,
|
||||
hclk2: ahb_freq,
|
||||
hclk3: ahb_freq,
|
||||
pclk1: apb1_freq,
|
||||
pclk1_tim: apb1_tim_freq,
|
||||
pclk2: apb2_freq,
|
||||
@ -315,6 +316,8 @@ pub(crate) unsafe fn init(config: Config) {
|
||||
adc: adc12_ck,
|
||||
adc34: adc345_ck,
|
||||
pll1_p: None,
|
||||
pll1_q: None, // TODO
|
||||
hse: None, // TODO
|
||||
rtc,
|
||||
});
|
||||
}
|
||||
|
@ -95,6 +95,7 @@ pub struct Clocks {
|
||||
rcc_h7rm0433,
|
||||
rcc_h7ab,
|
||||
rcc_u5,
|
||||
rcc_g4,
|
||||
rcc_wb,
|
||||
rcc_wl5,
|
||||
rcc_wle
|
||||
@ -119,7 +120,7 @@ pub struct Clocks {
|
||||
|
||||
#[cfg(any(stm32g4, rcc_l4))]
|
||||
pub pll1_p: Option<Hertz>,
|
||||
#[cfg(any(stm32h5, stm32h7, rcc_f2, rcc_f4, rcc_f410, rcc_f7, rcc_l4))]
|
||||
#[cfg(any(stm32h5, stm32h7, stm32f2, stm32f4, stm32f7, rcc_l4, stm32g4))]
|
||||
pub pll1_q: Option<Hertz>,
|
||||
#[cfg(any(stm32h5, stm32h7))]
|
||||
pub pll2_p: Option<Hertz>,
|
||||
@ -167,7 +168,7 @@ pub struct Clocks {
|
||||
|
||||
#[cfg(any(stm32h5, stm32h7, rcc_l4, rcc_c0))]
|
||||
pub lse: Option<Hertz>,
|
||||
#[cfg(any(stm32h5, stm32h7))]
|
||||
#[cfg(any(stm32h5, stm32h7, stm32g4))]
|
||||
pub hse: Option<Hertz>,
|
||||
|
||||
#[cfg(stm32h5)]
|
||||
|
@ -43,7 +43,10 @@ type T = peripherals::TIM3;
|
||||
type T = peripherals::TIM4;
|
||||
#[cfg(time_driver_tim5)]
|
||||
type T = peripherals::TIM5;
|
||||
|
||||
#[cfg(time_driver_tim9)]
|
||||
type T = peripherals::TIM9;
|
||||
#[cfg(time_driver_tim11)]
|
||||
type T = peripherals::TIM11;
|
||||
#[cfg(time_driver_tim12)]
|
||||
type T = peripherals::TIM12;
|
||||
#[cfg(time_driver_tim15)]
|
||||
@ -82,6 +85,22 @@ foreach_interrupt! {
|
||||
DRIVER.on_interrupt()
|
||||
}
|
||||
};
|
||||
(TIM9, timer, $block:ident, UP, $irq:ident) => {
|
||||
#[cfg(time_driver_tim9)]
|
||||
#[cfg(feature = "rt")]
|
||||
#[interrupt]
|
||||
fn $irq() {
|
||||
DRIVER.on_interrupt()
|
||||
}
|
||||
};
|
||||
(TIM11, timer, $block:ident, UP, $irq:ident) => {
|
||||
#[cfg(time_driver_tim11)]
|
||||
#[cfg(feature = "rt")]
|
||||
#[interrupt]
|
||||
fn $irq() {
|
||||
DRIVER.on_interrupt()
|
||||
}
|
||||
};
|
||||
(TIM12, timer, $block:ident, UP, $irq:ident) => {
|
||||
#[cfg(time_driver_tim12)]
|
||||
#[cfg(feature = "rt")]
|
||||
|
@ -77,7 +77,7 @@ pub(crate) mod sealed {
|
||||
Self::regs().dier().write(|r| r.set_uie(enable));
|
||||
}
|
||||
|
||||
fn set_autoreload_preload(&mut self, enable: vals::Arpe) {
|
||||
fn set_autoreload_preload(&mut self, enable: bool) {
|
||||
Self::regs().cr1().modify(|r| r.set_arpe(enable));
|
||||
}
|
||||
|
||||
|
@ -132,6 +132,14 @@ pub struct Config {
|
||||
/// Set this to true to swap the RX and TX pins.
|
||||
#[cfg(any(usart_v3, usart_v4))]
|
||||
pub swap_rx_tx: bool,
|
||||
|
||||
/// Set this to true to invert TX pin signal values (V<sub>DD</sub> =0/mark, Gnd = 1/idle).
|
||||
#[cfg(any(usart_v3, usart_v4))]
|
||||
pub invert_tx: bool,
|
||||
|
||||
/// Set this to true to invert RX pin signal values (V<sub>DD</sub> =0/mark, Gnd = 1/idle).
|
||||
#[cfg(any(usart_v3, usart_v4))]
|
||||
pub invert_rx: bool,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
@ -147,6 +155,10 @@ impl Default for Config {
|
||||
assume_noise_free: false,
|
||||
#[cfg(any(usart_v3, usart_v4))]
|
||||
swap_rx_tx: false,
|
||||
#[cfg(any(usart_v3, usart_v4))]
|
||||
invert_tx: false,
|
||||
#[cfg(any(usart_v3, usart_v4))]
|
||||
invert_rx: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -972,7 +984,11 @@ fn configure(
|
||||
});
|
||||
|
||||
#[cfg(any(usart_v3, usart_v4))]
|
||||
w.set_swap(config.swap_rx_tx);
|
||||
{
|
||||
w.set_txinv(config.invert_tx);
|
||||
w.set_rxinv(config.invert_rx);
|
||||
w.set_swap(config.swap_rx_tx);
|
||||
}
|
||||
});
|
||||
|
||||
#[cfg(not(usart_v1))]
|
||||
|
@ -263,7 +263,7 @@ impl<'d, T: Instance> Driver<'d, T> {
|
||||
|
||||
let regs = T::regs();
|
||||
|
||||
#[cfg(stm32l5)]
|
||||
#[cfg(any(stm32l5, stm32wb))]
|
||||
crate::pac::PWR.cr2().modify(|w| w.set_usv(true));
|
||||
|
||||
#[cfg(pwr_h5)]
|
||||
|
@ -24,8 +24,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## 0.1.3 - 2023-08-28
|
||||
|
||||
- Update `embedded-hal-async` to `1.0.0-rc.2`
|
||||
- Update `embedded-hal v1` to `1.0.0-rc.2`
|
||||
- Update `embedded-hal-async` to `1.0.0-rc.3`
|
||||
- Update `embedded-hal v1` to `1.0.0-rc.3`
|
||||
|
||||
## 0.1.2 - 2023-07-05
|
||||
|
||||
|
@ -235,8 +235,8 @@ defmt = { version = "0.3", optional = true }
|
||||
log = { version = "0.4.14", optional = true }
|
||||
|
||||
embedded-hal-02 = { package = "embedded-hal", version = "0.2.6" }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.2" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.3" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.3" }
|
||||
|
||||
futures-util = { version = "0.3.17", default-features = false }
|
||||
critical-section = "1.1"
|
||||
|
32
embassy-usb-dfu/Cargo.toml
Normal file
32
embassy-usb-dfu/Cargo.toml
Normal file
@ -0,0 +1,32 @@
|
||||
[package]
|
||||
edition = "2021"
|
||||
name = "embassy-usb-dfu"
|
||||
version = "0.1.0"
|
||||
description = "An implementation of the USB DFU 1.1 protocol, using embassy-boot"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/embassy-rs/embassy"
|
||||
categories = [
|
||||
"embedded",
|
||||
"no-std",
|
||||
"asynchronous"
|
||||
]
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
bitflags = "2.4.1"
|
||||
cortex-m = { version = "0.7.7", features = ["inline-asm"], optional = true }
|
||||
defmt = { version = "0.3.5", optional = true }
|
||||
embassy-boot = { version = "0.1.1", path = "../embassy-boot/boot" }
|
||||
# embassy-embedded-hal = { version = "0.1.0", path = "../embassy-embedded-hal" }
|
||||
embassy-futures = { version = "0.1.1", path = "../embassy-futures" }
|
||||
embassy-sync = { version = "0.5.0", path = "../embassy-sync" }
|
||||
embassy-time = { version = "0.2.0", path = "../embassy-time" }
|
||||
embassy-usb = { version = "0.1.0", path = "../embassy-usb", default-features = false }
|
||||
embedded-storage = { version = "0.3.1" }
|
||||
esp32c3-hal = { version = "0.13.0", optional = true, default-features = false }
|
||||
|
||||
[features]
|
||||
dfu = []
|
||||
application = []
|
||||
defmt = ["dep:defmt"]
|
135
embassy-usb-dfu/src/application.rs
Normal file
135
embassy-usb-dfu/src/application.rs
Normal file
@ -0,0 +1,135 @@
|
||||
use core::marker::PhantomData;
|
||||
|
||||
use embassy_boot::BlockingFirmwareState;
|
||||
use embassy_time::{Duration, Instant};
|
||||
use embassy_usb::control::{InResponse, OutResponse, Recipient, RequestType};
|
||||
use embassy_usb::driver::Driver;
|
||||
use embassy_usb::{Builder, Handler};
|
||||
use embedded_storage::nor_flash::NorFlash;
|
||||
|
||||
use crate::consts::{
|
||||
DfuAttributes, Request, State, Status, APPN_SPEC_SUBCLASS_DFU, DESC_DFU_FUNCTIONAL, DFU_PROTOCOL_RT,
|
||||
USB_CLASS_APPN_SPEC,
|
||||
};
|
||||
use crate::Reset;
|
||||
|
||||
/// Internal state for the DFU class
|
||||
pub struct Control<'d, STATE: NorFlash, RST: Reset> {
|
||||
firmware_state: BlockingFirmwareState<'d, STATE>,
|
||||
attrs: DfuAttributes,
|
||||
state: State,
|
||||
timeout: Option<Duration>,
|
||||
detach_start: Option<Instant>,
|
||||
_rst: PhantomData<RST>,
|
||||
}
|
||||
|
||||
impl<'d, STATE: NorFlash, RST: Reset> Control<'d, STATE, RST> {
|
||||
pub fn new(firmware_state: BlockingFirmwareState<'d, STATE>, attrs: DfuAttributes) -> Self {
|
||||
Control {
|
||||
firmware_state,
|
||||
attrs,
|
||||
state: State::AppIdle,
|
||||
detach_start: None,
|
||||
timeout: None,
|
||||
_rst: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'d, STATE: NorFlash, RST: Reset> Handler for Control<'d, STATE, RST> {
|
||||
fn reset(&mut self) {
|
||||
if let Some(start) = self.detach_start {
|
||||
let delta = Instant::now() - start;
|
||||
let timeout = self.timeout.unwrap();
|
||||
trace!(
|
||||
"Received RESET with delta = {}, timeout = {}",
|
||||
delta.as_millis(),
|
||||
timeout.as_millis()
|
||||
);
|
||||
if delta < timeout {
|
||||
self.firmware_state
|
||||
.mark_dfu()
|
||||
.expect("Failed to mark DFU mode in bootloader");
|
||||
RST::sys_reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn control_out(
|
||||
&mut self,
|
||||
req: embassy_usb::control::Request,
|
||||
_: &[u8],
|
||||
) -> Option<embassy_usb::control::OutResponse> {
|
||||
if (req.request_type, req.recipient) != (RequestType::Class, Recipient::Interface) {
|
||||
return None;
|
||||
}
|
||||
|
||||
trace!("Received request {}", req);
|
||||
|
||||
match Request::try_from(req.request) {
|
||||
Ok(Request::Detach) => {
|
||||
trace!("Received DETACH, awaiting USB reset");
|
||||
self.detach_start = Some(Instant::now());
|
||||
self.timeout = Some(Duration::from_millis(req.value as u64));
|
||||
self.state = State::AppDetach;
|
||||
Some(OutResponse::Accepted)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn control_in<'a>(
|
||||
&'a mut self,
|
||||
req: embassy_usb::control::Request,
|
||||
buf: &'a mut [u8],
|
||||
) -> Option<embassy_usb::control::InResponse<'a>> {
|
||||
if (req.request_type, req.recipient) != (RequestType::Class, Recipient::Interface) {
|
||||
return None;
|
||||
}
|
||||
|
||||
trace!("Received request {}", req);
|
||||
|
||||
match Request::try_from(req.request) {
|
||||
Ok(Request::GetStatus) => {
|
||||
buf[0..6].copy_from_slice(&[Status::Ok as u8, 0x32, 0x00, 0x00, self.state as u8, 0x00]);
|
||||
Some(InResponse::Accepted(buf))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An implementation of the USB DFU 1.1 runtime protocol
|
||||
///
|
||||
/// This function will add a DFU interface descriptor to the provided Builder, and register the provided Control as a handler for the USB device. The USB builder can be used as normal once this is complete.
|
||||
/// The handler is responsive to DFU GetStatus and Detach commands.
|
||||
///
|
||||
/// Once a detach command, followed by a USB reset is received by the host, a magic number will be written into the bootloader state partition to indicate that
|
||||
/// it should expose a DFU device, and a software reset will be issued.
|
||||
///
|
||||
/// To apply USB DFU updates, the bootloader must be capable of recognizing the DFU magic and exposing a device to handle the full DFU transaction with the host.
|
||||
pub fn usb_dfu<'d, D: Driver<'d>, STATE: NorFlash, RST: Reset>(
|
||||
builder: &mut Builder<'d, D>,
|
||||
handler: &'d mut Control<'d, STATE, RST>,
|
||||
timeout: Duration,
|
||||
) {
|
||||
let mut func = builder.function(0x00, 0x00, 0x00);
|
||||
let mut iface = func.interface();
|
||||
let mut alt = iface.alt_setting(USB_CLASS_APPN_SPEC, APPN_SPEC_SUBCLASS_DFU, DFU_PROTOCOL_RT, None);
|
||||
let timeout = timeout.as_millis() as u16;
|
||||
alt.descriptor(
|
||||
DESC_DFU_FUNCTIONAL,
|
||||
&[
|
||||
handler.attrs.bits(),
|
||||
(timeout & 0xff) as u8,
|
||||
((timeout >> 8) & 0xff) as u8,
|
||||
0x40,
|
||||
0x00, // 64B control buffer size for application side
|
||||
0x10,
|
||||
0x01, // DFU 1.1
|
||||
],
|
||||
);
|
||||
|
||||
drop(func);
|
||||
builder.handler(handler);
|
||||
}
|
189
embassy-usb-dfu/src/bootloader.rs
Normal file
189
embassy-usb-dfu/src/bootloader.rs
Normal file
@ -0,0 +1,189 @@
|
||||
use core::marker::PhantomData;
|
||||
|
||||
use embassy_boot::{AlignedBuffer, BlockingFirmwareUpdater};
|
||||
use embassy_usb::control::{InResponse, OutResponse, Recipient, RequestType};
|
||||
use embassy_usb::driver::Driver;
|
||||
use embassy_usb::{Builder, Handler};
|
||||
use embedded_storage::nor_flash::{NorFlash, NorFlashErrorKind};
|
||||
|
||||
use crate::consts::{
|
||||
DfuAttributes, Request, State, Status, APPN_SPEC_SUBCLASS_DFU, DESC_DFU_FUNCTIONAL, DFU_PROTOCOL_DFU,
|
||||
USB_CLASS_APPN_SPEC,
|
||||
};
|
||||
use crate::Reset;
|
||||
|
||||
/// Internal state for USB DFU
|
||||
pub struct Control<'d, DFU: NorFlash, STATE: NorFlash, RST: Reset, const BLOCK_SIZE: usize> {
|
||||
updater: BlockingFirmwareUpdater<'d, DFU, STATE>,
|
||||
attrs: DfuAttributes,
|
||||
state: State,
|
||||
status: Status,
|
||||
offset: usize,
|
||||
_rst: PhantomData<RST>,
|
||||
}
|
||||
|
||||
impl<'d, DFU: NorFlash, STATE: NorFlash, RST: Reset, const BLOCK_SIZE: usize> Control<'d, DFU, STATE, RST, BLOCK_SIZE> {
|
||||
pub fn new(updater: BlockingFirmwareUpdater<'d, DFU, STATE>, attrs: DfuAttributes) -> Self {
|
||||
Self {
|
||||
updater,
|
||||
attrs,
|
||||
state: State::DfuIdle,
|
||||
status: Status::Ok,
|
||||
offset: 0,
|
||||
_rst: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
fn reset_state(&mut self) {
|
||||
self.offset = 0;
|
||||
self.state = State::DfuIdle;
|
||||
self.status = Status::Ok;
|
||||
}
|
||||
}
|
||||
|
||||
impl<'d, DFU: NorFlash, STATE: NorFlash, RST: Reset, const BLOCK_SIZE: usize> Handler
|
||||
for Control<'d, DFU, STATE, RST, BLOCK_SIZE>
|
||||
{
|
||||
fn control_out(
|
||||
&mut self,
|
||||
req: embassy_usb::control::Request,
|
||||
data: &[u8],
|
||||
) -> Option<embassy_usb::control::OutResponse> {
|
||||
if (req.request_type, req.recipient) != (RequestType::Class, Recipient::Interface) {
|
||||
return None;
|
||||
}
|
||||
match Request::try_from(req.request) {
|
||||
Ok(Request::Abort) => {
|
||||
self.reset_state();
|
||||
Some(OutResponse::Accepted)
|
||||
}
|
||||
Ok(Request::Dnload) if self.attrs.contains(DfuAttributes::CAN_DOWNLOAD) => {
|
||||
if req.value == 0 {
|
||||
self.state = State::Download;
|
||||
self.offset = 0;
|
||||
}
|
||||
|
||||
let mut buf = AlignedBuffer([0; BLOCK_SIZE]);
|
||||
buf.as_mut()[..data.len()].copy_from_slice(data);
|
||||
|
||||
if req.length == 0 {
|
||||
match self.updater.mark_updated() {
|
||||
Ok(_) => {
|
||||
self.status = Status::Ok;
|
||||
self.state = State::ManifestSync;
|
||||
}
|
||||
Err(e) => {
|
||||
self.state = State::Error;
|
||||
match e {
|
||||
embassy_boot::FirmwareUpdaterError::Flash(e) => match e {
|
||||
NorFlashErrorKind::NotAligned => self.status = Status::ErrWrite,
|
||||
NorFlashErrorKind::OutOfBounds => self.status = Status::ErrAddress,
|
||||
_ => self.status = Status::ErrUnknown,
|
||||
},
|
||||
embassy_boot::FirmwareUpdaterError::Signature(_) => self.status = Status::ErrVerify,
|
||||
embassy_boot::FirmwareUpdaterError::BadState => self.status = Status::ErrUnknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if self.state != State::Download {
|
||||
// Unexpected DNLOAD while chip is waiting for a GETSTATUS
|
||||
self.status = Status::ErrUnknown;
|
||||
self.state = State::Error;
|
||||
return Some(OutResponse::Rejected);
|
||||
}
|
||||
match self.updater.write_firmware(self.offset, buf.as_ref()) {
|
||||
Ok(_) => {
|
||||
self.status = Status::Ok;
|
||||
self.state = State::DlSync;
|
||||
self.offset += data.len();
|
||||
}
|
||||
Err(e) => {
|
||||
self.state = State::Error;
|
||||
match e {
|
||||
embassy_boot::FirmwareUpdaterError::Flash(e) => match e {
|
||||
NorFlashErrorKind::NotAligned => self.status = Status::ErrWrite,
|
||||
NorFlashErrorKind::OutOfBounds => self.status = Status::ErrAddress,
|
||||
_ => self.status = Status::ErrUnknown,
|
||||
},
|
||||
embassy_boot::FirmwareUpdaterError::Signature(_) => self.status = Status::ErrVerify,
|
||||
embassy_boot::FirmwareUpdaterError::BadState => self.status = Status::ErrUnknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(OutResponse::Accepted)
|
||||
}
|
||||
Ok(Request::Detach) => Some(OutResponse::Accepted), // Device is already in DFU mode
|
||||
Ok(Request::ClrStatus) => {
|
||||
self.reset_state();
|
||||
Some(OutResponse::Accepted)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn control_in<'a>(
|
||||
&'a mut self,
|
||||
req: embassy_usb::control::Request,
|
||||
buf: &'a mut [u8],
|
||||
) -> Option<embassy_usb::control::InResponse<'a>> {
|
||||
if (req.request_type, req.recipient) != (RequestType::Class, Recipient::Interface) {
|
||||
return None;
|
||||
}
|
||||
match Request::try_from(req.request) {
|
||||
Ok(Request::GetStatus) => {
|
||||
//TODO: Configurable poll timeout, ability to add string for Vendor error
|
||||
buf[0..6].copy_from_slice(&[self.status as u8, 0x32, 0x00, 0x00, self.state as u8, 0x00]);
|
||||
match self.state {
|
||||
State::DlSync => self.state = State::Download,
|
||||
State::ManifestSync => RST::sys_reset(),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
Some(InResponse::Accepted(&buf[0..6]))
|
||||
}
|
||||
Ok(Request::GetState) => {
|
||||
buf[0] = self.state as u8;
|
||||
Some(InResponse::Accepted(&buf[0..1]))
|
||||
}
|
||||
Ok(Request::Upload) if self.attrs.contains(DfuAttributes::CAN_UPLOAD) => {
|
||||
//TODO: FirmwareUpdater does not provide a way of reading the active partition, can't upload.
|
||||
Some(InResponse::Rejected)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An implementation of the USB DFU 1.1 protocol
|
||||
///
|
||||
/// This function will add a DFU interface descriptor to the provided Builder, and register the provided Control as a handler for the USB device
|
||||
/// The handler is responsive to DFU GetState, GetStatus, Abort, and ClrStatus commands, as well as Download if configured by the user.
|
||||
///
|
||||
/// Once the host has initiated a DFU download operation, the chunks sent by the host will be written to the DFU partition.
|
||||
/// Once the final sync in the manifestation phase has been received, the handler will trigger a system reset to swap the new firmware.
|
||||
pub fn usb_dfu<'d, D: Driver<'d>, DFU: NorFlash, STATE: NorFlash, RST: Reset, const BLOCK_SIZE: usize>(
|
||||
builder: &mut Builder<'d, D>,
|
||||
handler: &'d mut Control<'d, DFU, STATE, RST, BLOCK_SIZE>,
|
||||
) {
|
||||
let mut func = builder.function(0x00, 0x00, 0x00);
|
||||
let mut iface = func.interface();
|
||||
let mut alt = iface.alt_setting(USB_CLASS_APPN_SPEC, APPN_SPEC_SUBCLASS_DFU, DFU_PROTOCOL_DFU, None);
|
||||
alt.descriptor(
|
||||
DESC_DFU_FUNCTIONAL,
|
||||
&[
|
||||
handler.attrs.bits(),
|
||||
0xc4,
|
||||
0x09, // 2500ms timeout, doesn't affect operation as DETACH not necessary in bootloader code
|
||||
(BLOCK_SIZE & 0xff) as u8,
|
||||
((BLOCK_SIZE & 0xff00) >> 8) as u8,
|
||||
0x10,
|
||||
0x01, // DFU 1.1
|
||||
],
|
||||
);
|
||||
|
||||
drop(func);
|
||||
builder.handler(handler);
|
||||
}
|
95
embassy-usb-dfu/src/consts.rs
Normal file
95
embassy-usb-dfu/src/consts.rs
Normal file
@ -0,0 +1,95 @@
|
||||
pub(crate) const USB_CLASS_APPN_SPEC: u8 = 0xFE;
|
||||
pub(crate) const APPN_SPEC_SUBCLASS_DFU: u8 = 0x01;
|
||||
#[allow(unused)]
|
||||
pub(crate) const DFU_PROTOCOL_DFU: u8 = 0x02;
|
||||
#[allow(unused)]
|
||||
pub(crate) const DFU_PROTOCOL_RT: u8 = 0x01;
|
||||
pub(crate) const DESC_DFU_FUNCTIONAL: u8 = 0x21;
|
||||
|
||||
#[cfg(feature = "defmt")]
|
||||
defmt::bitflags! {
|
||||
pub struct DfuAttributes: u8 {
|
||||
const WILL_DETACH = 0b0000_1000;
|
||||
const MANIFESTATION_TOLERANT = 0b0000_0100;
|
||||
const CAN_UPLOAD = 0b0000_0010;
|
||||
const CAN_DOWNLOAD = 0b0000_0001;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "defmt"))]
|
||||
bitflags::bitflags! {
|
||||
pub struct DfuAttributes: u8 {
|
||||
const WILL_DETACH = 0b0000_1000;
|
||||
const MANIFESTATION_TOLERANT = 0b0000_0100;
|
||||
const CAN_UPLOAD = 0b0000_0010;
|
||||
const CAN_DOWNLOAD = 0b0000_0001;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
#[allow(unused)]
|
||||
pub enum State {
|
||||
AppIdle = 0,
|
||||
AppDetach = 1,
|
||||
DfuIdle = 2,
|
||||
DlSync = 3,
|
||||
DlBusy = 4,
|
||||
Download = 5,
|
||||
ManifestSync = 6,
|
||||
Manifest = 7,
|
||||
ManifestWaitReset = 8,
|
||||
UploadIdle = 9,
|
||||
Error = 10,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
#[allow(unused)]
|
||||
pub enum Status {
|
||||
Ok = 0x00,
|
||||
ErrTarget = 0x01,
|
||||
ErrFile = 0x02,
|
||||
ErrWrite = 0x03,
|
||||
ErrErase = 0x04,
|
||||
ErrCheckErased = 0x05,
|
||||
ErrProg = 0x06,
|
||||
ErrVerify = 0x07,
|
||||
ErrAddress = 0x08,
|
||||
ErrNotDone = 0x09,
|
||||
ErrFirmware = 0x0A,
|
||||
ErrVendor = 0x0B,
|
||||
ErrUsbr = 0x0C,
|
||||
ErrPor = 0x0D,
|
||||
ErrUnknown = 0x0E,
|
||||
ErrStalledPkt = 0x0F,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
pub enum Request {
|
||||
Detach = 0,
|
||||
Dnload = 1,
|
||||
Upload = 2,
|
||||
GetStatus = 3,
|
||||
ClrStatus = 4,
|
||||
GetState = 5,
|
||||
Abort = 6,
|
||||
}
|
||||
|
||||
impl TryFrom<u8> for Request {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: u8) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
0 => Ok(Request::Detach),
|
||||
1 => Ok(Request::Dnload),
|
||||
2 => Ok(Request::Upload),
|
||||
3 => Ok(Request::GetStatus),
|
||||
4 => Ok(Request::ClrStatus),
|
||||
5 => Ok(Request::GetState),
|
||||
6 => Ok(Request::Abort),
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
258
embassy-usb-dfu/src/fmt.rs
Normal file
258
embassy-usb-dfu/src/fmt.rs
Normal file
@ -0,0 +1,258 @@
|
||||
#![macro_use]
|
||||
#![allow(unused_macros)]
|
||||
|
||||
use core::fmt::{Debug, Display, LowerHex};
|
||||
|
||||
#[cfg(all(feature = "defmt", feature = "log"))]
|
||||
compile_error!("You may not enable both `defmt` and `log` features.");
|
||||
|
||||
macro_rules! assert {
|
||||
($($x:tt)*) => {
|
||||
{
|
||||
#[cfg(not(feature = "defmt"))]
|
||||
::core::assert!($($x)*);
|
||||
#[cfg(feature = "defmt")]
|
||||
::defmt::assert!($($x)*);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! assert_eq {
|
||||
($($x:tt)*) => {
|
||||
{
|
||||
#[cfg(not(feature = "defmt"))]
|
||||
::core::assert_eq!($($x)*);
|
||||
#[cfg(feature = "defmt")]
|
||||
::defmt::assert_eq!($($x)*);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! assert_ne {
|
||||
($($x:tt)*) => {
|
||||
{
|
||||
#[cfg(not(feature = "defmt"))]
|
||||
::core::assert_ne!($($x)*);
|
||||
#[cfg(feature = "defmt")]
|
||||
::defmt::assert_ne!($($x)*);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! debug_assert {
|
||||
($($x:tt)*) => {
|
||||
{
|
||||
#[cfg(not(feature = "defmt"))]
|
||||
::core::debug_assert!($($x)*);
|
||||
#[cfg(feature = "defmt")]
|
||||
::defmt::debug_assert!($($x)*);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! debug_assert_eq {
|
||||
($($x:tt)*) => {
|
||||
{
|
||||
#[cfg(not(feature = "defmt"))]
|
||||
::core::debug_assert_eq!($($x)*);
|
||||
#[cfg(feature = "defmt")]
|
||||
::defmt::debug_assert_eq!($($x)*);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! debug_assert_ne {
|
||||
($($x:tt)*) => {
|
||||
{
|
||||
#[cfg(not(feature = "defmt"))]
|
||||
::core::debug_assert_ne!($($x)*);
|
||||
#[cfg(feature = "defmt")]
|
||||
::defmt::debug_assert_ne!($($x)*);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! todo {
|
||||
($($x:tt)*) => {
|
||||
{
|
||||
#[cfg(not(feature = "defmt"))]
|
||||
::core::todo!($($x)*);
|
||||
#[cfg(feature = "defmt")]
|
||||
::defmt::todo!($($x)*);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "defmt"))]
|
||||
macro_rules! unreachable {
|
||||
($($x:tt)*) => {
|
||||
::core::unreachable!($($x)*)
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(feature = "defmt")]
|
||||
macro_rules! unreachable {
|
||||
($($x:tt)*) => {
|
||||
::defmt::unreachable!($($x)*)
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! panic {
|
||||
($($x:tt)*) => {
|
||||
{
|
||||
#[cfg(not(feature = "defmt"))]
|
||||
::core::panic!($($x)*);
|
||||
#[cfg(feature = "defmt")]
|
||||
::defmt::panic!($($x)*);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! trace {
|
||||
($s:literal $(, $x:expr)* $(,)?) => {
|
||||
{
|
||||
#[cfg(feature = "log")]
|
||||
::log::trace!($s $(, $x)*);
|
||||
#[cfg(feature = "defmt")]
|
||||
::defmt::trace!($s $(, $x)*);
|
||||
#[cfg(not(any(feature = "log", feature="defmt")))]
|
||||
let _ = ($( & $x ),*);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! debug {
|
||||
($s:literal $(, $x:expr)* $(,)?) => {
|
||||
{
|
||||
#[cfg(feature = "log")]
|
||||
::log::debug!($s $(, $x)*);
|
||||
#[cfg(feature = "defmt")]
|
||||
::defmt::debug!($s $(, $x)*);
|
||||
#[cfg(not(any(feature = "log", feature="defmt")))]
|
||||
let _ = ($( & $x ),*);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! info {
|
||||
($s:literal $(, $x:expr)* $(,)?) => {
|
||||
{
|
||||
#[cfg(feature = "log")]
|
||||
::log::info!($s $(, $x)*);
|
||||
#[cfg(feature = "defmt")]
|
||||
::defmt::info!($s $(, $x)*);
|
||||
#[cfg(not(any(feature = "log", feature="defmt")))]
|
||||
let _ = ($( & $x ),*);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! warn {
|
||||
($s:literal $(, $x:expr)* $(,)?) => {
|
||||
{
|
||||
#[cfg(feature = "log")]
|
||||
::log::warn!($s $(, $x)*);
|
||||
#[cfg(feature = "defmt")]
|
||||
::defmt::warn!($s $(, $x)*);
|
||||
#[cfg(not(any(feature = "log", feature="defmt")))]
|
||||
let _ = ($( & $x ),*);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! error {
|
||||
($s:literal $(, $x:expr)* $(,)?) => {
|
||||
{
|
||||
#[cfg(feature = "log")]
|
||||
::log::error!($s $(, $x)*);
|
||||
#[cfg(feature = "defmt")]
|
||||
::defmt::error!($s $(, $x)*);
|
||||
#[cfg(not(any(feature = "log", feature="defmt")))]
|
||||
let _ = ($( & $x ),*);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(feature = "defmt")]
|
||||
macro_rules! unwrap {
|
||||
($($x:tt)*) => {
|
||||
::defmt::unwrap!($($x)*)
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "defmt"))]
|
||||
macro_rules! unwrap {
|
||||
($arg:expr) => {
|
||||
match $crate::fmt::Try::into_result($arg) {
|
||||
::core::result::Result::Ok(t) => t,
|
||||
::core::result::Result::Err(e) => {
|
||||
::core::panic!("unwrap of `{}` failed: {:?}", ::core::stringify!($arg), e);
|
||||
}
|
||||
}
|
||||
};
|
||||
($arg:expr, $($msg:expr),+ $(,)? ) => {
|
||||
match $crate::fmt::Try::into_result($arg) {
|
||||
::core::result::Result::Ok(t) => t,
|
||||
::core::result::Result::Err(e) => {
|
||||
::core::panic!("unwrap of `{}` failed: {}: {:?}", ::core::stringify!($arg), ::core::format_args!($($msg,)*), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||
pub struct NoneError;
|
||||
|
||||
pub trait Try {
|
||||
type Ok;
|
||||
type Error;
|
||||
fn into_result(self) -> Result<Self::Ok, Self::Error>;
|
||||
}
|
||||
|
||||
impl<T> Try for Option<T> {
|
||||
type Ok = T;
|
||||
type Error = NoneError;
|
||||
|
||||
#[inline]
|
||||
fn into_result(self) -> Result<T, NoneError> {
|
||||
self.ok_or(NoneError)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E> Try for Result<T, E> {
|
||||
type Ok = T;
|
||||
type Error = E;
|
||||
|
||||
#[inline]
|
||||
fn into_result(self) -> Self {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub(crate) struct Bytes<'a>(pub &'a [u8]);
|
||||
|
||||
impl<'a> Debug for Bytes<'a> {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
write!(f, "{:#02x?}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Display for Bytes<'a> {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
write!(f, "{:#02x?}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> LowerHex for Bytes<'a> {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
write!(f, "{:#02x?}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "defmt")]
|
||||
impl<'a> defmt::Format for Bytes<'a> {
|
||||
fn format(&self, fmt: defmt::Formatter) {
|
||||
defmt::write!(fmt, "{:02x}", self.0)
|
||||
}
|
||||
}
|
51
embassy-usb-dfu/src/lib.rs
Normal file
51
embassy-usb-dfu/src/lib.rs
Normal file
@ -0,0 +1,51 @@
|
||||
#![no_std]
|
||||
mod fmt;
|
||||
|
||||
pub mod consts;
|
||||
|
||||
#[cfg(feature = "dfu")]
|
||||
mod bootloader;
|
||||
#[cfg(feature = "dfu")]
|
||||
pub use self::bootloader::*;
|
||||
|
||||
#[cfg(feature = "application")]
|
||||
mod application;
|
||||
#[cfg(feature = "application")]
|
||||
pub use self::application::*;
|
||||
|
||||
#[cfg(any(
|
||||
all(feature = "dfu", feature = "application"),
|
||||
not(any(feature = "dfu", feature = "application"))
|
||||
))]
|
||||
compile_error!("usb-dfu must be compiled with exactly one of `bootloader`, or `application` features");
|
||||
|
||||
/// Provides a platform-agnostic interface for initiating a system reset.
|
||||
///
|
||||
/// This crate exposes `ResetImmediate` when compiled with cortex-m or esp32c3 support, which immediately issues a
|
||||
/// reset request without interfacing with any other peripherals.
|
||||
///
|
||||
/// If alternate behaviour is desired, a custom implementation of Reset can be provided as a type argument to the usb_dfu function.
|
||||
pub trait Reset {
|
||||
fn sys_reset() -> !;
|
||||
}
|
||||
|
||||
#[cfg(feature = "esp32c3-hal")]
|
||||
pub struct ResetImmediate;
|
||||
|
||||
#[cfg(feature = "esp32c3-hal")]
|
||||
impl Reset for ResetImmediate {
|
||||
fn sys_reset() -> ! {
|
||||
esp32c3_hal::reset::software_reset();
|
||||
loop {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "cortex-m")]
|
||||
pub struct ResetImmediate;
|
||||
|
||||
#[cfg(feature = "cortex-m")]
|
||||
impl Reset for ResetImmediate {
|
||||
fn sys_reset() -> ! {
|
||||
cortex_m::peripheral::SCB::sys_reset()
|
||||
}
|
||||
}
|
9
examples/boot/application/stm32wb-dfu/.cargo/config.toml
Normal file
9
examples/boot/application/stm32wb-dfu/.cargo/config.toml
Normal file
@ -0,0 +1,9 @@
|
||||
[target.'cfg(all(target_arch = "arm", target_os = "none"))']
|
||||
# replace your chip as listed in `probe-rs chip list`
|
||||
runner = "probe-rs run --chip STM32WLE5JCIx"
|
||||
|
||||
[build]
|
||||
target = "thumbv7em-none-eabihf"
|
||||
|
||||
[env]
|
||||
DEFMT_LOG = "trace"
|
32
examples/boot/application/stm32wb-dfu/Cargo.toml
Normal file
32
examples/boot/application/stm32wb-dfu/Cargo.toml
Normal file
@ -0,0 +1,32 @@
|
||||
[package]
|
||||
edition = "2021"
|
||||
name = "embassy-boot-stm32wb-dfu-examples"
|
||||
version = "0.1.0"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" }
|
||||
embassy-executor = { version = "0.4.0", path = "../../../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "nightly", "integrated-timers"] }
|
||||
embassy-time = { version = "0.2", path = "../../../../embassy-time", features = [ "tick-hz-32_768"] }
|
||||
embassy-stm32 = { version = "0.1.0", path = "../../../../embassy-stm32", features = ["stm32wb55rg", "time-driver-any", "exti"] }
|
||||
embassy-boot-stm32 = { version = "0.1.0", path = "../../../../embassy-boot/stm32", features = [] }
|
||||
embassy-embedded-hal = { version = "0.1.0", path = "../../../../embassy-embedded-hal" }
|
||||
embassy-usb = { version = "0.1.0", path = "../../../../embassy-usb" }
|
||||
embassy-usb-dfu = { version = "0.1.0", path = "../../../../embassy-usb-dfu", features = ["application", "cortex-m"] }
|
||||
|
||||
defmt = { version = "0.3", optional = true }
|
||||
defmt-rtt = { version = "0.4", optional = true }
|
||||
panic-reset = { version = "0.1.1" }
|
||||
embedded-hal = { version = "0.2.6" }
|
||||
|
||||
cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] }
|
||||
cortex-m-rt = "0.7.0"
|
||||
|
||||
[features]
|
||||
defmt = [
|
||||
"dep:defmt",
|
||||
"dep:defmt-rtt",
|
||||
"embassy-stm32/defmt",
|
||||
"embassy-boot-stm32/defmt",
|
||||
"embassy-sync/defmt",
|
||||
]
|
29
examples/boot/application/stm32wb-dfu/README.md
Normal file
29
examples/boot/application/stm32wb-dfu/README.md
Normal file
@ -0,0 +1,29 @@
|
||||
# Examples using bootloader
|
||||
|
||||
Example for STM32WL demonstrating the bootloader. The example consists of application binaries, 'a'
|
||||
which allows you to press a button to start the DFU process, and 'b' which is the updated
|
||||
application.
|
||||
|
||||
|
||||
## Prerequisites
|
||||
|
||||
* `cargo-binutils`
|
||||
* `cargo-flash`
|
||||
* `embassy-boot-stm32`
|
||||
|
||||
## Usage
|
||||
|
||||
```
|
||||
# Flash bootloader
|
||||
cargo flash --manifest-path ../../bootloader/stm32/Cargo.toml --release --features embassy-stm32/stm32wl55jc-cm4 --chip STM32WLE5JCIx
|
||||
# Build 'b'
|
||||
cargo build --release --bin b
|
||||
# Generate binary for 'b'
|
||||
cargo objcopy --release --bin b -- -O binary b.bin
|
||||
```
|
||||
|
||||
# Flash `a` (which includes b.bin)
|
||||
|
||||
```
|
||||
cargo flash --release --bin a --chip STM32WLE5JCIx
|
||||
```
|
37
examples/boot/application/stm32wb-dfu/build.rs
Normal file
37
examples/boot/application/stm32wb-dfu/build.rs
Normal file
@ -0,0 +1,37 @@
|
||||
//! This build script copies the `memory.x` file from the crate root into
|
||||
//! a directory where the linker can always find it at build time.
|
||||
//! For many projects this is optional, as the linker always searches the
|
||||
//! project root directory -- wherever `Cargo.toml` is. However, if you
|
||||
//! are using a workspace or have a more complicated build setup, this
|
||||
//! build script becomes required. Additionally, by requesting that
|
||||
//! Cargo re-run the build script whenever `memory.x` is changed,
|
||||
//! updating `memory.x` ensures a rebuild of the application with the
|
||||
//! new memory settings.
|
||||
|
||||
use std::env;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() {
|
||||
// Put `memory.x` in our output directory and ensure it's
|
||||
// on the linker search path.
|
||||
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
|
||||
File::create(out.join("memory.x"))
|
||||
.unwrap()
|
||||
.write_all(include_bytes!("memory.x"))
|
||||
.unwrap();
|
||||
println!("cargo:rustc-link-search={}", out.display());
|
||||
|
||||
// By default, Cargo will re-run a build script whenever
|
||||
// any file in the project changes. By specifying `memory.x`
|
||||
// here, we ensure the build script is only re-run when
|
||||
// `memory.x` is changed.
|
||||
println!("cargo:rerun-if-changed=memory.x");
|
||||
|
||||
println!("cargo:rustc-link-arg-bins=--nmagic");
|
||||
println!("cargo:rustc-link-arg-bins=-Tlink.x");
|
||||
if env::var("CARGO_FEATURE_DEFMT").is_ok() {
|
||||
println!("cargo:rustc-link-arg-bins=-Tdefmt.x");
|
||||
}
|
||||
}
|
15
examples/boot/application/stm32wb-dfu/memory.x
Normal file
15
examples/boot/application/stm32wb-dfu/memory.x
Normal file
@ -0,0 +1,15 @@
|
||||
MEMORY
|
||||
{
|
||||
/* NOTE 1 K = 1 KiBi = 1024 bytes */
|
||||
BOOTLOADER : ORIGIN = 0x08000000, LENGTH = 24K
|
||||
BOOTLOADER_STATE : ORIGIN = 0x08006000, LENGTH = 4K
|
||||
FLASH : ORIGIN = 0x08008000, LENGTH = 128K
|
||||
DFU : ORIGIN = 0x08028000, LENGTH = 132K
|
||||
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 32K
|
||||
}
|
||||
|
||||
__bootloader_state_start = ORIGIN(BOOTLOADER_STATE) - ORIGIN(BOOTLOADER);
|
||||
__bootloader_state_end = ORIGIN(BOOTLOADER_STATE) + LENGTH(BOOTLOADER_STATE) - ORIGIN(BOOTLOADER);
|
||||
|
||||
__bootloader_dfu_start = ORIGIN(DFU) - ORIGIN(BOOTLOADER);
|
||||
__bootloader_dfu_end = ORIGIN(DFU) + LENGTH(DFU) - ORIGIN(BOOTLOADER);
|
64
examples/boot/application/stm32wb-dfu/src/main.rs
Normal file
64
examples/boot/application/stm32wb-dfu/src/main.rs
Normal file
@ -0,0 +1,64 @@
|
||||
#![no_std]
|
||||
#![no_main]
|
||||
#![feature(type_alias_impl_trait)]
|
||||
|
||||
use core::cell::RefCell;
|
||||
|
||||
#[cfg(feature = "defmt-rtt")]
|
||||
use defmt_rtt::*;
|
||||
use embassy_boot_stm32::{AlignedBuffer, BlockingFirmwareState, FirmwareUpdaterConfig};
|
||||
use embassy_executor::Spawner;
|
||||
use embassy_stm32::flash::{Flash, WRITE_SIZE};
|
||||
use embassy_stm32::rcc::WPAN_DEFAULT;
|
||||
use embassy_stm32::usb::{self, Driver};
|
||||
use embassy_stm32::{bind_interrupts, peripherals};
|
||||
use embassy_sync::blocking_mutex::Mutex;
|
||||
use embassy_time::Duration;
|
||||
use embassy_usb::Builder;
|
||||
use embassy_usb_dfu::consts::DfuAttributes;
|
||||
use embassy_usb_dfu::{usb_dfu, Control, ResetImmediate};
|
||||
use panic_reset as _;
|
||||
|
||||
bind_interrupts!(struct Irqs {
|
||||
USB_LP => usb::InterruptHandler<peripherals::USB>;
|
||||
});
|
||||
|
||||
#[embassy_executor::main]
|
||||
async fn main(_spawner: Spawner) {
|
||||
let mut config = embassy_stm32::Config::default();
|
||||
config.rcc = WPAN_DEFAULT;
|
||||
let p = embassy_stm32::init(config);
|
||||
let flash = Flash::new_blocking(p.FLASH);
|
||||
let flash = Mutex::new(RefCell::new(flash));
|
||||
|
||||
let config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash);
|
||||
let mut magic = AlignedBuffer([0; WRITE_SIZE]);
|
||||
let mut firmware_state = BlockingFirmwareState::from_config(config, &mut magic.0);
|
||||
firmware_state.mark_booted().expect("Failed to mark booted");
|
||||
|
||||
let driver = Driver::new(p.USB, Irqs, p.PA12, p.PA11);
|
||||
let mut config = embassy_usb::Config::new(0xc0de, 0xcafe);
|
||||
config.manufacturer = Some("Embassy");
|
||||
config.product = Some("USB-DFU Runtime example");
|
||||
config.serial_number = Some("1235678");
|
||||
|
||||
let mut device_descriptor = [0; 256];
|
||||
let mut config_descriptor = [0; 256];
|
||||
let mut bos_descriptor = [0; 256];
|
||||
let mut control_buf = [0; 64];
|
||||
let mut state = Control::new(firmware_state, DfuAttributes::CAN_DOWNLOAD);
|
||||
let mut builder = Builder::new(
|
||||
driver,
|
||||
config,
|
||||
&mut device_descriptor,
|
||||
&mut config_descriptor,
|
||||
&mut bos_descriptor,
|
||||
&mut [],
|
||||
&mut control_buf,
|
||||
);
|
||||
|
||||
usb_dfu::<_, _, ResetImmediate>(&mut builder, &mut state, Duration::from_millis(2500));
|
||||
|
||||
let mut dev = builder.build();
|
||||
dev.run().await
|
||||
}
|
63
examples/boot/bootloader/stm32wb-dfu/Cargo.toml
Normal file
63
examples/boot/bootloader/stm32wb-dfu/Cargo.toml
Normal file
@ -0,0 +1,63 @@
|
||||
[package]
|
||||
edition = "2021"
|
||||
name = "stm32wb-dfu-bootloader-example"
|
||||
version = "0.1.0"
|
||||
description = "Example USB DFUbootloader for the STM32WB series of chips"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
defmt = { version = "0.3", optional = true }
|
||||
defmt-rtt = { version = "0.4", optional = true }
|
||||
|
||||
embassy-stm32 = { path = "../../../../embassy-stm32", features = ["stm32wb55rg"] }
|
||||
embassy-boot-stm32 = { path = "../../../../embassy-boot/stm32" }
|
||||
cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] }
|
||||
embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" }
|
||||
cortex-m-rt = { version = "0.7" }
|
||||
embedded-storage = "0.3.1"
|
||||
embedded-storage-async = "0.4.0"
|
||||
cfg-if = "1.0.0"
|
||||
embassy-usb-dfu = { version = "0.1.0", path = "../../../../embassy-usb-dfu", features = ["dfu", "cortex-m"] }
|
||||
embassy-usb = { version = "0.1.0", path = "../../../../embassy-usb", default-features = false }
|
||||
embassy-futures = { version = "0.1.1", path = "../../../../embassy-futures" }
|
||||
|
||||
[features]
|
||||
defmt = [
|
||||
"dep:defmt",
|
||||
"embassy-boot-stm32/defmt",
|
||||
"embassy-stm32/defmt",
|
||||
"embassy-usb/defmt",
|
||||
"embassy-usb-dfu/defmt"
|
||||
]
|
||||
debug = ["defmt-rtt", "defmt"]
|
||||
|
||||
[profile.dev]
|
||||
debug = 2
|
||||
debug-assertions = true
|
||||
incremental = false
|
||||
opt-level = 'z'
|
||||
overflow-checks = true
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
debug = 2
|
||||
debug-assertions = false
|
||||
incremental = false
|
||||
lto = 'fat'
|
||||
opt-level = 'z'
|
||||
overflow-checks = false
|
||||
|
||||
# do not optimize proc-macro crates = faster builds from scratch
|
||||
[profile.dev.build-override]
|
||||
codegen-units = 8
|
||||
debug = false
|
||||
debug-assertions = false
|
||||
opt-level = 0
|
||||
overflow-checks = false
|
||||
|
||||
[profile.release.build-override]
|
||||
codegen-units = 8
|
||||
debug = false
|
||||
debug-assertions = false
|
||||
opt-level = 0
|
||||
overflow-checks = false
|
11
examples/boot/bootloader/stm32wb-dfu/README.md
Normal file
11
examples/boot/bootloader/stm32wb-dfu/README.md
Normal file
@ -0,0 +1,11 @@
|
||||
# Bootloader for STM32
|
||||
|
||||
The bootloader uses `embassy-boot` to interact with the flash.
|
||||
|
||||
# Usage
|
||||
|
||||
Flash the bootloader
|
||||
|
||||
```
|
||||
cargo flash --features embassy-stm32/stm32wl55jc-cm4 --release --chip STM32WLE5JCIx
|
||||
```
|
27
examples/boot/bootloader/stm32wb-dfu/build.rs
Normal file
27
examples/boot/bootloader/stm32wb-dfu/build.rs
Normal file
@ -0,0 +1,27 @@
|
||||
use std::env;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() {
|
||||
// Put `memory.x` in our output directory and ensure it's
|
||||
// on the linker search path.
|
||||
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
|
||||
File::create(out.join("memory.x"))
|
||||
.unwrap()
|
||||
.write_all(include_bytes!("memory.x"))
|
||||
.unwrap();
|
||||
println!("cargo:rustc-link-search={}", out.display());
|
||||
|
||||
// By default, Cargo will re-run a build script whenever
|
||||
// any file in the project changes. By specifying `memory.x`
|
||||
// here, we ensure the build script is only re-run when
|
||||
// `memory.x` is changed.
|
||||
println!("cargo:rerun-if-changed=memory.x");
|
||||
|
||||
println!("cargo:rustc-link-arg-bins=--nmagic");
|
||||
println!("cargo:rustc-link-arg-bins=-Tlink.x");
|
||||
if env::var("CARGO_FEATURE_DEFMT").is_ok() {
|
||||
println!("cargo:rustc-link-arg-bins=-Tdefmt.x");
|
||||
}
|
||||
}
|
18
examples/boot/bootloader/stm32wb-dfu/memory.x
Normal file
18
examples/boot/bootloader/stm32wb-dfu/memory.x
Normal file
@ -0,0 +1,18 @@
|
||||
MEMORY
|
||||
{
|
||||
/* NOTE 1 K = 1 KiBi = 1024 bytes */
|
||||
FLASH : ORIGIN = 0x08000000, LENGTH = 24K
|
||||
BOOTLOADER_STATE : ORIGIN = 0x08006000, LENGTH = 4K
|
||||
ACTIVE : ORIGIN = 0x08008000, LENGTH = 128K
|
||||
DFU : ORIGIN = 0x08028000, LENGTH = 132K
|
||||
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 16K
|
||||
}
|
||||
|
||||
__bootloader_state_start = ORIGIN(BOOTLOADER_STATE) - ORIGIN(FLASH);
|
||||
__bootloader_state_end = ORIGIN(BOOTLOADER_STATE) + LENGTH(BOOTLOADER_STATE) - ORIGIN(FLASH);
|
||||
|
||||
__bootloader_active_start = ORIGIN(ACTIVE) - ORIGIN(FLASH);
|
||||
__bootloader_active_end = ORIGIN(ACTIVE) + LENGTH(ACTIVE) - ORIGIN(FLASH);
|
||||
|
||||
__bootloader_dfu_start = ORIGIN(DFU) - ORIGIN(FLASH);
|
||||
__bootloader_dfu_end = ORIGIN(DFU) + LENGTH(DFU) - ORIGIN(FLASH);
|
93
examples/boot/bootloader/stm32wb-dfu/src/main.rs
Normal file
93
examples/boot/bootloader/stm32wb-dfu/src/main.rs
Normal file
@ -0,0 +1,93 @@
|
||||
#![no_std]
|
||||
#![no_main]
|
||||
|
||||
use core::cell::RefCell;
|
||||
|
||||
use cortex_m_rt::{entry, exception};
|
||||
#[cfg(feature = "defmt")]
|
||||
use defmt_rtt as _;
|
||||
use embassy_boot_stm32::*;
|
||||
use embassy_stm32::flash::{Flash, BANK1_REGION, WRITE_SIZE};
|
||||
use embassy_stm32::rcc::WPAN_DEFAULT;
|
||||
use embassy_stm32::usb::Driver;
|
||||
use embassy_stm32::{bind_interrupts, peripherals, usb};
|
||||
use embassy_sync::blocking_mutex::Mutex;
|
||||
use embassy_usb::Builder;
|
||||
use embassy_usb_dfu::consts::DfuAttributes;
|
||||
use embassy_usb_dfu::{usb_dfu, Control, ResetImmediate};
|
||||
|
||||
bind_interrupts!(struct Irqs {
|
||||
USB_LP => usb::InterruptHandler<peripherals::USB>;
|
||||
});
|
||||
|
||||
#[entry]
|
||||
fn main() -> ! {
|
||||
let mut config = embassy_stm32::Config::default();
|
||||
config.rcc = WPAN_DEFAULT;
|
||||
let p = embassy_stm32::init(config);
|
||||
|
||||
// Prevent a hard fault when accessing flash 'too early' after boot.
|
||||
#[cfg(feature = "defmt")]
|
||||
for _ in 0..10000000 {
|
||||
cortex_m::asm::nop();
|
||||
}
|
||||
|
||||
let layout = Flash::new_blocking(p.FLASH).into_blocking_regions();
|
||||
let flash = Mutex::new(RefCell::new(layout.bank1_region));
|
||||
|
||||
let config = BootLoaderConfig::from_linkerfile_blocking(&flash);
|
||||
let active_offset = config.active.offset();
|
||||
let bl = BootLoader::prepare::<_, _, _, 2048>(config);
|
||||
if bl.state == State::DfuDetach {
|
||||
let driver = Driver::new(p.USB, Irqs, p.PA12, p.PA11);
|
||||
let mut config = embassy_usb::Config::new(0xc0de, 0xcafe);
|
||||
config.manufacturer = Some("Embassy");
|
||||
config.product = Some("USB-DFU Bootloader example");
|
||||
config.serial_number = Some("1235678");
|
||||
|
||||
let fw_config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash);
|
||||
let mut buffer = AlignedBuffer([0; WRITE_SIZE]);
|
||||
let updater = BlockingFirmwareUpdater::new(fw_config, &mut buffer.0[..]);
|
||||
|
||||
let mut device_descriptor = [0; 256];
|
||||
let mut config_descriptor = [0; 256];
|
||||
let mut bos_descriptor = [0; 256];
|
||||
let mut control_buf = [0; 4096];
|
||||
let mut state = Control::new(updater, DfuAttributes::CAN_DOWNLOAD);
|
||||
let mut builder = Builder::new(
|
||||
driver,
|
||||
config,
|
||||
&mut device_descriptor,
|
||||
&mut config_descriptor,
|
||||
&mut bos_descriptor,
|
||||
&mut [],
|
||||
&mut control_buf,
|
||||
);
|
||||
|
||||
usb_dfu::<_, _, _, ResetImmediate, 4096>(&mut builder, &mut state);
|
||||
|
||||
let mut dev = builder.build();
|
||||
embassy_futures::block_on(dev.run());
|
||||
}
|
||||
|
||||
unsafe { bl.load(BANK1_REGION.base + active_offset) }
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
#[cfg_attr(target_os = "none", link_section = ".HardFault.user")]
|
||||
unsafe extern "C" fn HardFault() {
|
||||
cortex_m::peripheral::SCB::sys_reset();
|
||||
}
|
||||
|
||||
#[exception]
|
||||
unsafe fn DefaultHandler(_: i16) -> ! {
|
||||
const SCB_ICSR: *const u32 = 0xE000_ED04 as *const u32;
|
||||
let irqn = core::ptr::read_volatile(SCB_ICSR) as u8 as i16 - 16;
|
||||
|
||||
panic!("DefaultHandler #{:?}", irqn);
|
||||
}
|
||||
|
||||
#[panic_handler]
|
||||
fn panic(_info: &core::panic::PanicInfo) -> ! {
|
||||
cortex_m::asm::udf();
|
||||
}
|
@ -36,9 +36,9 @@ rand = { version = "0.8.4", default-features = false }
|
||||
embedded-storage = "0.3.1"
|
||||
usbd-hid = "0.6.0"
|
||||
serde = { version = "1.0.136", default-features = false }
|
||||
embedded-hal = { version = "1.0.0-rc.2" }
|
||||
embedded-hal-async = { version = "1.0.0-rc.2" }
|
||||
embedded-hal-bus = { version = "0.1.0-rc.2", features = ["async"] }
|
||||
embedded-hal = { version = "1.0.0-rc.3" }
|
||||
embedded-hal-async = { version = "1.0.0-rc.3" }
|
||||
embedded-hal-bus = { version = "0.1.0-rc.3", features = ["async"] }
|
||||
num-integer = { version = "0.1.45", default-features = false }
|
||||
microfft = "0.5.0"
|
||||
|
||||
|
@ -38,9 +38,9 @@ smart-leds = "0.3.0"
|
||||
heapless = "0.8"
|
||||
usbd-hid = "0.6.1"
|
||||
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.2" }
|
||||
embedded-hal-async = "1.0.0-rc.2"
|
||||
embedded-hal-bus = { version = "0.1.0-rc.2", features = ["async"] }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.3" }
|
||||
embedded-hal-async = "1.0.0-rc.3"
|
||||
embedded-hal-bus = { version = "0.1.0-rc.3", features = ["async"] }
|
||||
embedded-io-async = { version = "0.6.1", features = ["defmt-03"] }
|
||||
embedded-storage = { version = "0.3" }
|
||||
static_cell = { version = "2", features = ["nightly"]}
|
||||
|
@ -17,7 +17,7 @@ async fn main(_spawner: Spawner) {
|
||||
|
||||
// Use PIN_28, Pin34 on J0 for RP Pico, as a input.
|
||||
// You need to add your own button.
|
||||
let button = Input::new(p.PIN_28, Pull::Up);
|
||||
let mut button = Input::new(p.PIN_28, Pull::Up);
|
||||
|
||||
loop {
|
||||
if button.is_high() {
|
||||
|
@ -13,7 +13,7 @@ fn main() -> ! {
|
||||
|
||||
let p = embassy_stm32::init(Default::default());
|
||||
|
||||
let button = Input::new(p.PC13, Pull::Up);
|
||||
let mut button = Input::new(p.PC13, Pull::Up);
|
||||
|
||||
loop {
|
||||
if button.is_high() {
|
||||
|
67
examples/stm32f1/src/bin/can.rs
Normal file
67
examples/stm32f1/src/bin/can.rs
Normal file
@ -0,0 +1,67 @@
|
||||
#![no_std]
|
||||
#![no_main]
|
||||
#![feature(type_alias_impl_trait)]
|
||||
|
||||
use defmt::*;
|
||||
use embassy_executor::Spawner;
|
||||
use embassy_stm32::can::bxcan::filter::Mask32;
|
||||
use embassy_stm32::can::bxcan::{Fifo, Frame, Id, StandardId};
|
||||
use embassy_stm32::can::{Can, Rx0InterruptHandler, Rx1InterruptHandler, SceInterruptHandler, TxInterruptHandler};
|
||||
use embassy_stm32::peripherals::CAN;
|
||||
use embassy_stm32::{bind_interrupts, Config};
|
||||
use {defmt_rtt as _, panic_probe as _};
|
||||
|
||||
bind_interrupts!(struct Irqs {
|
||||
USB_LP_CAN1_RX0 => Rx0InterruptHandler<CAN>;
|
||||
CAN1_RX1 => Rx1InterruptHandler<CAN>;
|
||||
CAN1_SCE => SceInterruptHandler<CAN>;
|
||||
USB_HP_CAN1_TX => TxInterruptHandler<CAN>;
|
||||
});
|
||||
|
||||
// This example is configured to work with real CAN transceivers on B8/B9.
|
||||
// See other examples for loopback.
|
||||
|
||||
#[embassy_executor::main]
|
||||
async fn main(_spawner: Spawner) {
|
||||
let p = embassy_stm32::init(Config::default());
|
||||
|
||||
// Set alternate pin mapping to B8/B9
|
||||
embassy_stm32::pac::AFIO.mapr().modify(|w| w.set_can1_remap(2));
|
||||
|
||||
let mut can = Can::new(p.CAN, p.PB8, p.PB9, Irqs);
|
||||
|
||||
can.as_mut()
|
||||
.modify_filters()
|
||||
.enable_bank(0, Fifo::Fifo0, Mask32::accept_all());
|
||||
|
||||
can.as_mut()
|
||||
.modify_config()
|
||||
.set_loopback(false)
|
||||
.set_silent(false)
|
||||
.leave_disabled();
|
||||
|
||||
can.set_bitrate(250_000);
|
||||
|
||||
can.enable().await;
|
||||
|
||||
let mut i: u8 = 0;
|
||||
loop {
|
||||
let tx_frame = Frame::new_data(unwrap!(StandardId::new(i as _)), [i]);
|
||||
can.write(&tx_frame).await;
|
||||
|
||||
match can.read().await {
|
||||
Ok(env) => match env.frame.id() {
|
||||
Id::Extended(id) => {
|
||||
defmt::println!("Extended Frame id={:x}", id.as_raw());
|
||||
}
|
||||
Id::Standard(id) => {
|
||||
defmt::println!("Standard Frame id={:x}", id.as_raw());
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
defmt::println!("Error {}", err);
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
@ -13,7 +13,7 @@ fn main() -> ! {
|
||||
|
||||
let p = embassy_stm32::init(Default::default());
|
||||
|
||||
let button = Input::new(p.PA0, Pull::Down);
|
||||
let mut button = Input::new(p.PA0, Pull::Down);
|
||||
let mut led1 = Output::new(p.PE9, Level::High, Speed::Low);
|
||||
let mut led2 = Output::new(p.PE15, Level::High, Speed::Low);
|
||||
|
||||
|
@ -13,7 +13,7 @@ fn main() -> ! {
|
||||
|
||||
let p = embassy_stm32::init(Default::default());
|
||||
|
||||
let button = Input::new(p.PC13, Pull::Down);
|
||||
let mut button = Input::new(p.PC13, Pull::Down);
|
||||
let mut led1 = Output::new(p.PB0, Level::High, Speed::Low);
|
||||
let _led2 = Output::new(p.PB7, Level::High, Speed::Low);
|
||||
let mut led3 = Output::new(p.PB14, Level::High, Speed::Low);
|
||||
|
@ -13,7 +13,7 @@ fn main() -> ! {
|
||||
|
||||
let p = embassy_stm32::init(Default::default());
|
||||
|
||||
let button = Input::new(p.PC13, Pull::Down);
|
||||
let mut button = Input::new(p.PC13, Pull::Down);
|
||||
let mut led1 = Output::new(p.PB0, Level::High, Speed::Low);
|
||||
let _led2 = Output::new(p.PB7, Level::High, Speed::Low);
|
||||
let mut led3 = Output::new(p.PB14, Level::High, Speed::Low);
|
||||
|
@ -13,7 +13,7 @@ fn main() -> ! {
|
||||
|
||||
let p = embassy_stm32::init(Default::default());
|
||||
|
||||
let button = Input::new(p.PC13, Pull::Up);
|
||||
let mut button = Input::new(p.PC13, Pull::Up);
|
||||
|
||||
loop {
|
||||
if button.is_high() {
|
||||
|
@ -13,7 +13,7 @@ fn main() -> ! {
|
||||
|
||||
let p = embassy_stm32::init(Default::default());
|
||||
|
||||
let button = Input::new(p.PC13, Pull::Down);
|
||||
let mut button = Input::new(p.PC13, Pull::Down);
|
||||
|
||||
loop {
|
||||
if button.is_high() {
|
||||
|
@ -19,8 +19,8 @@ defmt-rtt = "0.4"
|
||||
cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] }
|
||||
cortex-m-rt = "0.7.0"
|
||||
embedded-hal = "0.2.6"
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.2" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.3" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.3" }
|
||||
embedded-io-async = { version = "0.6.1" }
|
||||
embedded-nal-async = { version = "0.7.1" }
|
||||
panic-probe = { version = "0.3", features = ["print-defmt"] }
|
||||
|
@ -19,8 +19,8 @@ defmt-rtt = "0.4"
|
||||
cortex-m = { version = "0.7.6", features = ["inline-asm", "critical-section-single-core"] }
|
||||
cortex-m-rt = "0.7.0"
|
||||
embedded-hal = "0.2.6"
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.2" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.3" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.3" }
|
||||
embedded-nal-async = { version = "0.7.1" }
|
||||
embedded-io-async = { version = "0.6.1" }
|
||||
panic-probe = { version = "0.3", features = ["print-defmt"] }
|
||||
|
@ -12,7 +12,7 @@ async fn main(_spawner: Spawner) {
|
||||
let p = embassy_stm32::init(Default::default());
|
||||
info!("Hello World!");
|
||||
|
||||
let button = Input::new(p.PB2, Pull::Up);
|
||||
let mut button = Input::new(p.PB2, Pull::Up);
|
||||
let mut led1 = Output::new(p.PA5, Level::High, Speed::Low);
|
||||
let mut led2 = Output::new(p.PB5, Level::High, Speed::Low);
|
||||
|
||||
|
@ -24,9 +24,9 @@ defmt-rtt = "0.4"
|
||||
cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] }
|
||||
cortex-m-rt = "0.7.0"
|
||||
embedded-hal = "0.2.6"
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.2" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal-bus = { version = "=0.1.0-rc.2", features = ["async"] }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.3" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.3" }
|
||||
embedded-hal-bus = { version = "=0.1.0-rc.3", features = ["async"] }
|
||||
panic-probe = { version = "0.3", features = ["print-defmt"] }
|
||||
futures = { version = "0.3.17", default-features = false, features = ["async-await"] }
|
||||
heapless = { version = "0.8", default-features = false }
|
||||
|
@ -12,7 +12,7 @@ fn main() -> ! {
|
||||
|
||||
let p = embassy_stm32::init(Default::default());
|
||||
|
||||
let button = Input::new(p.PC13, Pull::Up);
|
||||
let mut button = Input::new(p.PC13, Pull::Up);
|
||||
|
||||
loop {
|
||||
if button.is_high() {
|
||||
|
@ -114,8 +114,8 @@ async fn main(spawner: Spawner) {
|
||||
let led_uc4_blue = Output::new(dp.PG15, Level::High, Speed::Low);
|
||||
|
||||
// Read the uc_cfg switches
|
||||
let uc_cfg0 = Input::new(dp.PB2, Pull::None);
|
||||
let uc_cfg1 = Input::new(dp.PF11, Pull::None);
|
||||
let mut uc_cfg0 = Input::new(dp.PB2, Pull::None);
|
||||
let mut uc_cfg1 = Input::new(dp.PF11, Pull::None);
|
||||
let _uc_cfg2 = Input::new(dp.PG6, Pull::None);
|
||||
let _uc_cfg3 = Input::new(dp.PG11, Pull::None);
|
||||
|
||||
@ -133,8 +133,8 @@ async fn main(spawner: Spawner) {
|
||||
|
||||
// Setup IO and SPI for the SPE chip
|
||||
let spe_reset_n = Output::new(dp.PC7, Level::Low, Speed::Low);
|
||||
let spe_cfg0 = Input::new(dp.PC8, Pull::None);
|
||||
let spe_cfg1 = Input::new(dp.PC9, Pull::None);
|
||||
let mut spe_cfg0 = Input::new(dp.PC8, Pull::None);
|
||||
let mut spe_cfg1 = Input::new(dp.PC9, Pull::None);
|
||||
let _spe_ts_capt = Output::new(dp.PC6, Level::Low, Speed::Low);
|
||||
|
||||
let spe_int = Input::new(dp.PB11, Pull::None);
|
||||
|
@ -30,7 +30,7 @@ async fn main(_spawner: Spawner) {
|
||||
let _wake = Output::new(p.PB13, Level::Low, Speed::VeryHigh);
|
||||
let mut reset = Output::new(p.PE8, Level::Low, Speed::VeryHigh);
|
||||
let mut cs = Output::new(p.PE0, Level::High, Speed::VeryHigh);
|
||||
let ready = Input::new(p.PE1, Pull::Up);
|
||||
let mut ready = Input::new(p.PE1, Pull::Up);
|
||||
|
||||
cortex_m::asm::delay(100_000);
|
||||
reset.set_high();
|
||||
|
@ -25,7 +25,7 @@ async fn main(_spawner: Spawner) {
|
||||
let _wake = Output::new(p.PB13, Level::Low, Speed::VeryHigh);
|
||||
let mut reset = Output::new(p.PE8, Level::Low, Speed::VeryHigh);
|
||||
let mut cs = Output::new(p.PE0, Level::High, Speed::VeryHigh);
|
||||
let ready = Input::new(p.PE1, Pull::Up);
|
||||
let mut ready = Input::new(p.PE1, Pull::Up);
|
||||
|
||||
cortex_m::asm::delay(100_000);
|
||||
reset.set_high();
|
||||
|
@ -13,7 +13,7 @@ fn main() -> ! {
|
||||
|
||||
let p = embassy_stm32::init(Default::default());
|
||||
|
||||
let button = Input::new(p.PA0, Pull::Up);
|
||||
let mut button = Input::new(p.PA0, Pull::Up);
|
||||
let mut led1 = Output::new(p.PB15, Level::High, Speed::Low);
|
||||
let mut led2 = Output::new(p.PB9, Level::High, Speed::Low);
|
||||
|
||||
|
@ -16,8 +16,8 @@ embedded-io-async = { version = "0.6.1", features = ["defmt-03"] }
|
||||
embassy-net = { version = "0.2.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", ] }
|
||||
embassy-net-esp-hosted = { version = "0.1.0", path = "../../embassy-net-esp-hosted", features = ["defmt"] }
|
||||
embassy-net-enc28j60 = { version = "0.1.0", path = "../../embassy-net-enc28j60", features = ["defmt"] }
|
||||
embedded-hal-async = { version = "1.0.0-rc.2" }
|
||||
embedded-hal-bus = { version = "0.1.0-rc.2", features = ["async"] }
|
||||
embedded-hal-async = { version = "1.0.0-rc.3" }
|
||||
embedded-hal-bus = { version = "0.1.0-rc.3", features = ["async"] }
|
||||
static_cell = { version = "2", features = [ "nightly" ] }
|
||||
perf-client = { path = "../perf-client" }
|
||||
|
||||
|
@ -24,9 +24,9 @@ defmt-rtt = "0.4"
|
||||
cortex-m = { version = "0.7.6" }
|
||||
cortex-m-rt = "0.7.0"
|
||||
embedded-hal = "0.2.6"
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.2" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal-bus = { version = "=0.1.0-rc.2", features = ["async"] }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.3" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.3" }
|
||||
embedded-hal-bus = { version = "=0.1.0-rc.3", features = ["async"] }
|
||||
panic-probe = { version = "0.3.0", features = ["print-defmt"] }
|
||||
futures = { version = "0.3.17", default-features = false, features = ["async-await"] }
|
||||
embedded-io-async = { version = "0.6.1" }
|
||||
|
@ -16,10 +16,10 @@ async fn main(_spawner: Spawner) {
|
||||
|
||||
// Test initial output
|
||||
{
|
||||
let b = Input::new(&mut b, Pull::None);
|
||||
let mut b = Input::new(&mut b, Pull::None);
|
||||
|
||||
{
|
||||
let a = Output::new(&mut a, Level::Low);
|
||||
let mut a = Output::new(&mut a, Level::Low);
|
||||
delay();
|
||||
assert!(b.is_low());
|
||||
assert!(!b.is_high());
|
||||
@ -64,7 +64,7 @@ async fn main(_spawner: Spawner) {
|
||||
|
||||
// Test input no pull
|
||||
{
|
||||
let b = Input::new(&mut b, Pull::None);
|
||||
let mut b = Input::new(&mut b, Pull::None);
|
||||
// no pull, the status is undefined
|
||||
|
||||
let mut a = Output::new(&mut a, Level::Low);
|
||||
@ -77,7 +77,7 @@ async fn main(_spawner: Spawner) {
|
||||
|
||||
// Test input pulldown
|
||||
{
|
||||
let b = Input::new(&mut b, Pull::Down);
|
||||
let mut b = Input::new(&mut b, Pull::Down);
|
||||
delay();
|
||||
assert!(b.is_low());
|
||||
|
||||
@ -91,7 +91,7 @@ async fn main(_spawner: Spawner) {
|
||||
|
||||
// Test input pullup
|
||||
{
|
||||
let b = Input::new(&mut b, Pull::Up);
|
||||
let mut b = Input::new(&mut b, Pull::Up);
|
||||
delay();
|
||||
assert!(b.is_high());
|
||||
|
||||
|
@ -45,7 +45,7 @@ async fn main(_spawner: Spawner) {
|
||||
|
||||
// Test output from A
|
||||
{
|
||||
let pin1 = Input::new(&mut p9, Pull::None);
|
||||
let mut pin1 = Input::new(&mut p9, Pull::None);
|
||||
let _pwm = Pwm::new_output_a(&mut p.PWM_CH3, &mut p6, cfg.clone());
|
||||
Timer::after_millis(1).await;
|
||||
assert_eq!(pin1.is_low(), invert_a);
|
||||
@ -59,7 +59,7 @@ async fn main(_spawner: Spawner) {
|
||||
|
||||
// Test output from B
|
||||
{
|
||||
let pin2 = Input::new(&mut p11, Pull::None);
|
||||
let mut pin2 = Input::new(&mut p11, Pull::None);
|
||||
let _pwm = Pwm::new_output_b(&mut p.PWM_CH3, &mut p7, cfg.clone());
|
||||
Timer::after_millis(1).await;
|
||||
assert_ne!(pin2.is_low(), invert_a);
|
||||
@ -73,8 +73,8 @@ async fn main(_spawner: Spawner) {
|
||||
|
||||
// Test output from A+B
|
||||
{
|
||||
let pin1 = Input::new(&mut p9, Pull::None);
|
||||
let pin2 = Input::new(&mut p11, Pull::None);
|
||||
let mut pin1 = Input::new(&mut p9, Pull::None);
|
||||
let mut pin2 = Input::new(&mut p11, Pull::None);
|
||||
let _pwm = Pwm::new_output_ab(&mut p.PWM_CH3, &mut p6, &mut p7, cfg.clone());
|
||||
Timer::after_millis(1).await;
|
||||
assert_eq!(pin1.is_low(), invert_a);
|
||||
|
@ -10,14 +10,14 @@ stm32c031c6 = ["embassy-stm32/stm32c031c6", "cm0", "not-gpdma"]
|
||||
stm32f103c8 = ["embassy-stm32/stm32f103c8", "not-gpdma"]
|
||||
stm32f207zg = ["embassy-stm32/stm32f207zg", "chrono", "not-gpdma", "eth", "rng"]
|
||||
stm32f303ze = ["embassy-stm32/stm32f303ze", "chrono", "not-gpdma"]
|
||||
stm32f429zi = ["embassy-stm32/stm32f429zi", "chrono", "eth", "stop", "can", "not-gpdma", "dac-adc-pin", "rng"]
|
||||
stm32f446re = ["embassy-stm32/stm32f446re", "chrono", "stop", "can", "not-gpdma", "dac-adc-pin", "sdmmc"]
|
||||
stm32f429zi = ["embassy-stm32/stm32f429zi", "chrono", "eth", "stop", "can", "not-gpdma", "dac", "rng"]
|
||||
stm32f446re = ["embassy-stm32/stm32f446re", "chrono", "stop", "can", "not-gpdma", "dac", "sdmmc"]
|
||||
stm32f767zi = ["embassy-stm32/stm32f767zi", "chrono", "not-gpdma", "eth", "rng"]
|
||||
stm32g071rb = ["embassy-stm32/stm32g071rb", "cm0", "not-gpdma", "dac-adc-pin"]
|
||||
stm32g071rb = ["embassy-stm32/stm32g071rb", "cm0", "not-gpdma", "dac"]
|
||||
stm32g491re = ["embassy-stm32/stm32g491re", "chrono", "stop", "not-gpdma", "rng"]
|
||||
stm32h563zi = ["embassy-stm32/stm32h563zi", "chrono", "eth", "rng"]
|
||||
stm32h753zi = ["embassy-stm32/stm32h753zi", "chrono", "not-gpdma", "eth", "rng"]
|
||||
stm32h755zi = ["embassy-stm32/stm32h755zi-cm7", "chrono", "not-gpdma", "eth", "dac-adc-pin", "rng"]
|
||||
stm32h755zi = ["embassy-stm32/stm32h755zi-cm7", "chrono", "not-gpdma", "eth", "dac", "rng"]
|
||||
stm32h7a3zi = ["embassy-stm32/stm32h7a3zi", "not-gpdma", "rng"]
|
||||
stm32l073rz = ["embassy-stm32/stm32l073rz", "cm0", "not-gpdma", "rng"]
|
||||
stm32l152re = ["embassy-stm32/stm32l152re", "chrono", "not-gpdma"]
|
||||
@ -41,7 +41,7 @@ ble = ["dep:embassy-stm32-wpan", "embassy-stm32-wpan/ble"]
|
||||
mac = ["dep:embassy-stm32-wpan", "embassy-stm32-wpan/mac"]
|
||||
embassy-stm32-wpan = []
|
||||
not-gpdma = []
|
||||
dac-adc-pin = []
|
||||
dac = []
|
||||
|
||||
cm0 = ["portable-atomic/unsafe-assume-single-core"]
|
||||
|
||||
@ -63,8 +63,8 @@ defmt-rtt = "0.4"
|
||||
cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] }
|
||||
cortex-m-rt = "0.7.0"
|
||||
embedded-hal = "0.2.6"
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.2" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.2" }
|
||||
embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.3" }
|
||||
embedded-hal-async = { version = "=1.0.0-rc.3" }
|
||||
micromath = "2.0.0"
|
||||
panic-probe = { version = "0.3.0", features = ["print-defmt"] }
|
||||
rand_core = { version = "0.6", default-features = false }
|
||||
@ -84,7 +84,12 @@ required-features = [ "can",]
|
||||
[[bin]]
|
||||
name = "dac"
|
||||
path = "src/bin/dac.rs"
|
||||
required-features = [ "dac-adc-pin",]
|
||||
required-features = [ "dac",]
|
||||
|
||||
[[bin]]
|
||||
name = "dac_l1"
|
||||
path = "src/bin/dac_l1.rs"
|
||||
required-features = [ "stm32l152re",]
|
||||
|
||||
[[bin]]
|
||||
name = "eth"
|
||||
|
@ -1,7 +1,7 @@
|
||||
#![no_std]
|
||||
#![no_main]
|
||||
|
||||
// required-features: dac-adc-pin
|
||||
// required-features: dac
|
||||
|
||||
#[path = "../common.rs"]
|
||||
mod common;
|
||||
@ -22,12 +22,13 @@ async fn main(_spawner: Spawner) {
|
||||
// Initialize the board and obtain a Peripherals instance
|
||||
let p: embassy_stm32::Peripherals = embassy_stm32::init(config());
|
||||
|
||||
let adc = peri!(p, ADC);
|
||||
let dac = peri!(p, DAC);
|
||||
let dac_pin = peri!(p, DAC_PIN);
|
||||
let mut adc_pin = unsafe { core::ptr::read(&dac_pin) };
|
||||
|
||||
let mut dac = DacCh1::new(dac, NoDma, dac_pin);
|
||||
let mut adc = Adc::new(p.ADC1, &mut Delay);
|
||||
let mut adc = Adc::new(adc, &mut Delay);
|
||||
|
||||
#[cfg(feature = "stm32h755zi")]
|
||||
let normalization_factor = 256;
|
||||
|
86
tests/stm32/src/bin/dac_l1.rs
Normal file
86
tests/stm32/src/bin/dac_l1.rs
Normal file
@ -0,0 +1,86 @@
|
||||
#![no_std]
|
||||
#![no_main]
|
||||
|
||||
// required-features: stm32l152re
|
||||
|
||||
#[path = "../common.rs"]
|
||||
mod common;
|
||||
use core::f32::consts::PI;
|
||||
|
||||
use common::*;
|
||||
use defmt::assert;
|
||||
use embassy_executor::Spawner;
|
||||
use embassy_stm32::adc::Adc;
|
||||
use embassy_stm32::dac::{DacCh1, Value};
|
||||
use embassy_stm32::dma::NoDma;
|
||||
use embassy_stm32::{bind_interrupts, peripherals};
|
||||
use embassy_time::Timer;
|
||||
use micromath::F32Ext;
|
||||
use {defmt_rtt as _, panic_probe as _};
|
||||
|
||||
bind_interrupts!(struct Irqs {
|
||||
ADC1 => embassy_stm32::adc::InterruptHandler<peripherals::ADC>;
|
||||
});
|
||||
|
||||
#[embassy_executor::main]
|
||||
async fn main(_spawner: Spawner) {
|
||||
// Initialize the board and obtain a Peripherals instance
|
||||
let p: embassy_stm32::Peripherals = embassy_stm32::init(config());
|
||||
|
||||
let adc = peri!(p, ADC);
|
||||
let dac = peri!(p, DAC);
|
||||
let dac_pin = peri!(p, DAC_PIN);
|
||||
let mut adc_pin = unsafe { core::ptr::read(&dac_pin) };
|
||||
|
||||
let mut dac = DacCh1::new(dac, NoDma, dac_pin);
|
||||
let mut adc = Adc::new(adc, Irqs);
|
||||
|
||||
#[cfg(feature = "stm32h755zi")]
|
||||
let normalization_factor = 256;
|
||||
#[cfg(any(
|
||||
feature = "stm32f429zi",
|
||||
feature = "stm32f446re",
|
||||
feature = "stm32g071rb",
|
||||
feature = "stm32l152re",
|
||||
))]
|
||||
let normalization_factor: i32 = 16;
|
||||
|
||||
dac.set(Value::Bit8(0));
|
||||
// Now wait a little to obtain a stable value
|
||||
Timer::after_millis(30).await;
|
||||
let offset = adc.read(&mut adc_pin).await;
|
||||
|
||||
for v in 0..=255 {
|
||||
// First set the DAC output value
|
||||
let dac_output_val = to_sine_wave(v);
|
||||
dac.set(Value::Bit8(dac_output_val));
|
||||
|
||||
// Now wait a little to obtain a stable value
|
||||
Timer::after_millis(30).await;
|
||||
|
||||
// Need to steal the peripherals here because PA4 is obviously in use already
|
||||
let measured = adc.read(&mut unsafe { embassy_stm32::Peripherals::steal() }.PA4).await;
|
||||
// Calibrate and normalize the measurement to get close to the dac_output_val
|
||||
let measured_normalized = ((measured as i32 - offset as i32) / normalization_factor) as i16;
|
||||
|
||||
info!("value / measured: {} / {}", dac_output_val, measured_normalized);
|
||||
|
||||
// The deviations are quite enormous but that does not matter since this is only a quick test
|
||||
assert!((dac_output_val as i16 - measured_normalized).abs() < 15);
|
||||
}
|
||||
|
||||
info!("Test OK");
|
||||
cortex_m::asm::bkpt();
|
||||
}
|
||||
|
||||
fn to_sine_wave(v: u8) -> u8 {
|
||||
if v >= 128 {
|
||||
// top half
|
||||
let r = PI * ((v - 128) as f32 / 128.0);
|
||||
(r.sin() * 128.0 + 127.0) as u8
|
||||
} else {
|
||||
// bottom half
|
||||
let r = PI + PI * (v as f32 / 128.0);
|
||||
(r.sin() * 128.0 + 127.0) as u8
|
||||
}
|
||||
}
|
@ -20,10 +20,10 @@ async fn main(_spawner: Spawner) {
|
||||
|
||||
// Test initial output
|
||||
{
|
||||
let b = Input::new(&mut b, Pull::None);
|
||||
let mut b = Input::new(&mut b, Pull::None);
|
||||
|
||||
{
|
||||
let a = Output::new(&mut a, Level::Low, Speed::Low);
|
||||
let mut a = Output::new(&mut a, Level::Low, Speed::Low);
|
||||
delay();
|
||||
assert!(b.is_low());
|
||||
assert!(!b.is_high());
|
||||
@ -68,7 +68,7 @@ async fn main(_spawner: Spawner) {
|
||||
|
||||
// Test input no pull
|
||||
{
|
||||
let b = Input::new(&mut b, Pull::None);
|
||||
let mut b = Input::new(&mut b, Pull::None);
|
||||
// no pull, the status is undefined
|
||||
|
||||
let mut a = Output::new(&mut a, Level::Low, Speed::Low);
|
||||
@ -81,7 +81,7 @@ async fn main(_spawner: Spawner) {
|
||||
|
||||
// Test input pulldown
|
||||
{
|
||||
let b = Input::new(&mut b, Pull::Down);
|
||||
let mut b = Input::new(&mut b, Pull::Down);
|
||||
delay();
|
||||
assert!(b.is_low());
|
||||
|
||||
@ -95,7 +95,7 @@ async fn main(_spawner: Spawner) {
|
||||
|
||||
// Test input pullup
|
||||
{
|
||||
let b = Input::new(&mut b, Pull::Up);
|
||||
let mut b = Input::new(&mut b, Pull::Up);
|
||||
delay();
|
||||
assert!(b.is_high());
|
||||
|
||||
@ -109,7 +109,7 @@ async fn main(_spawner: Spawner) {
|
||||
|
||||
// Test output open drain
|
||||
{
|
||||
let b = Input::new(&mut b, Pull::Down);
|
||||
let mut b = Input::new(&mut b, Pull::Down);
|
||||
// no pull, the status is undefined
|
||||
|
||||
let mut a = OutputOpenDrain::new(&mut a, Level::Low, Speed::Low, Pull::None);
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user