Compare commits
125 Commits
rm-xtensa
...
james/fix-
Author | SHA1 | Date | |
---|---|---|---|
2b497c1e57 | |||
88e77c733c | |||
2a542bc143 | |||
c0cfd68c0c | |||
80c9d04bbd | |||
9959c8c3e3 | |||
b857334f92 | |||
a2d4bab2f8 | |||
a5379e708c | |||
2a7a44477e | |||
f6bc96dfbd | |||
ccf602b333 | |||
3568e4a5ff | |||
858987263b | |||
b966f55883 | |||
ea1e1973eb | |||
560e728132 | |||
c17fee27bb | |||
a8d0da91dc | |||
e5e85ba02b | |||
77e372e842 | |||
a165d73eed | |||
df0f41c41c | |||
98481c20fe | |||
5ec2fbe3a2 | |||
33e8943e5b | |||
9f9f6e75bb | |||
cbc8ccc51e | |||
485765320a | |||
27d054aa68 | |||
e579095a90 | |||
a34abd849f | |||
138ed87b95 | |||
d81395fab3 | |||
ef692c5141 | |||
9cc5d8ac89 | |||
c1438fe87b | |||
e27e00f628 | |||
7b9b22d7f8 | |||
879c0ad989 | |||
2c3d399220 | |||
b17f16f0af | |||
b60b3f4eb8 | |||
702d2a1a19 | |||
c2942f2727 | |||
6bf70e14fb | |||
2afec225e3 | |||
976a7ae22a | |||
1279a1b7f6 | |||
876faa5685 | |||
d596a1091d | |||
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 | |||
ac2aec4e7a | |||
ad2d9040d9 | |||
536e91d263 | |||
ecaa62aa42 | |||
7561696a57 | |||
195b492158 | |||
10c9e2e723 | |||
cd62d2cd84 | |||
925f5cbc26 | |||
c5e8a2e834 | |||
7703f47c1e | |||
0ffb35a2a1 | |||
d2a7322978 | |||
1f6ffdcdd2 | |||
83bed7bca4 | |||
a76dd2d70f | |||
bf7115cb44 | |||
0b0ca62a95 | |||
85d5f42562 | |||
18e89d7410 | |||
5f7cd821b5 | |||
d2dcbed920 | |||
e9fa79bd77 | |||
334900752a | |||
c7d6ea3c78 | |||
a6f4538219 | |||
d7eb067b4c | |||
2cba879afc | |||
03325ea81b | |||
52fabbfb46 | |||
09592ffa6a | |||
35f16c6003 | |||
b867f9b5b6 | |||
198ef8183e | |||
696c703b8c | |||
521cdef8a1 | |||
1dc31c4627 | |||
9fb2eb7470 | |||
ea43d74780 | |||
22c39fd697 | |||
87c0f1525d | |||
c97f65ac60 |
@ -1,3 +0,0 @@
|
||||
[patch.crates-io]
|
||||
embedded-storage = { git = "https://github.com/rust-embedded-community/embedded-storage", rev = "634302740f8d676538c3890748e7d7dfe372a040" }
|
||||
embedded-storage-async = { git = "https://github.com/rust-embedded-community/embedded-storage", rev = "634302740f8d676538c3890748e7d7dfe372a040" }
|
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
|
||||
|
1
.github/ci/doc.sh
vendored
1
.github/ci/doc.sh
vendored
@ -22,7 +22,6 @@ docserver-builder -i ./embassy-boot/stm32 -o webroot/crates/embassy-boot-stm32/g
|
||||
docserver-builder -i ./embassy-embedded-hal -o webroot/crates/embassy-embedded-hal/git.zup
|
||||
docserver-builder -i ./embassy-executor -o webroot/crates/embassy-executor/git.zup
|
||||
docserver-builder -i ./embassy-futures -o webroot/crates/embassy-futures/git.zup
|
||||
docserver-builder -i ./embassy-lora -o webroot/crates/embassy-lora/git.zup
|
||||
docserver-builder -i ./embassy-net -o webroot/crates/embassy-net/git.zup
|
||||
docserver-builder -i ./embassy-net-driver -o webroot/crates/embassy-net-driver/git.zup
|
||||
docserver-builder -i ./embassy-net-driver-channel -o webroot/crates/embassy-net-driver-channel/git.zup
|
||||
|
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
|
||||
|
||||
|
3
.vscode/settings.json
vendored
3
.vscode/settings.json
vendored
@ -3,6 +3,9 @@
|
||||
"[toml]": {
|
||||
"editor.formatOnSave": false
|
||||
},
|
||||
"[markdown]": {
|
||||
"editor.formatOnSave": false
|
||||
},
|
||||
"rust-analyzer.check.allTargets": false,
|
||||
"rust-analyzer.check.noDefaultFeatures": true,
|
||||
"rust-analyzer.cargo.noDefaultFeatures": true,
|
||||
|
@ -36,7 +36,7 @@ The <a href="https://github.com/embassy-rs/nrf-softdevice">nrf-softdevice</a> cr
|
||||
The <a href="https://github.com/embassy-rs/embassy/tree/main/embassy-stm32-wpan">embassy-stm32-wpan</a> crate provides Bluetooth Low Energy 5.x support for stm32wb microcontrollers.
|
||||
|
||||
- **LoRa** -
|
||||
<a href="https://docs.embassy.dev/embassy-lora/">embassy-lora</a> supports LoRa networking.
|
||||
<a href="hthttps://github.com/lora-rs/lora-rs">The lora-rs project</a> provides an async LoRa and LoRaWAN stack that works well on Embassy.
|
||||
|
||||
- **USB** -
|
||||
<a href="https://docs.embassy.dev/embassy-usb/">embassy-usb</a> implements a device-side USB stack. Implementations for common classes such as USB serial (CDC ACM) and USB HID are available, and a rich builder API allows building your own.
|
||||
|
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 \
|
||||
|
@ -11,8 +11,8 @@ log = ["dep:log"]
|
||||
firmware-logs = []
|
||||
|
||||
[dependencies]
|
||||
embassy-time = { version = "0.1.5", path = "../embassy-time"}
|
||||
embassy-sync = { version = "0.4.0", path = "../embassy-sync"}
|
||||
embassy-time = { version = "0.2", path = "../embassy-time"}
|
||||
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"}
|
||||
|
||||
@ -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]
|
||||
|
@ -6,8 +6,8 @@ version = "0.1.0"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[dependencies]
|
||||
embassy-executor = { version = "0.3.0", path = "../../../../../embassy-executor", features = ["defmt", "integrated-timers", "arch-cortex-m", "executor-thread"] }
|
||||
embassy-time = { version = "0.1.4", path = "../../../../../embassy-time", features = ["defmt"] }
|
||||
embassy-executor = { version = "0.4.0", path = "../../../../../embassy-executor", features = ["defmt", "integrated-timers", "arch-cortex-m", "executor-thread"] }
|
||||
embassy-time = { version = "0.2.0", path = "../../../../../embassy-time", features = ["defmt"] }
|
||||
embassy-nrf = { version = "0.1.0", path = "../../../../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote"] }
|
||||
|
||||
defmt = "0.3"
|
||||
|
@ -8,7 +8,7 @@ license = "MIT OR Apache-2.0"
|
||||
cortex-m = "0.7"
|
||||
cortex-m-rt = "0.7"
|
||||
embassy-stm32 = { version = "0.1.0", features = ["stm32l475vg", "memory-x", "exti"] }
|
||||
embassy-executor = { version = "0.3.0", features = ["nightly", "arch-cortex-m", "executor-thread"] }
|
||||
embassy-executor = { version = "0.4.0", features = ["nightly", "arch-cortex-m", "executor-thread"] }
|
||||
|
||||
defmt = "0.3.0"
|
||||
defmt-rtt = "0.3.0"
|
||||
|
@ -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,14 +1,18 @@
|
||||
* 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]
|
||||
* xref:hal.adoc[HAL]
|
||||
** xref:nrf.adoc[nRF]
|
||||
** xref:stm32.adoc[STM32]
|
||||
* 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]
|
||||
|
@ -6,9 +6,11 @@ So you've got one of the xref:examples.adoc[examples] running, but what now? Let
|
||||
|
||||
The full example can be found link:https://github.com/embassy-rs/embassy/tree/master/docs/modules/ROOT/examples/basic[here].
|
||||
|
||||
NOTE: If you’re using VS Code and rust-analyzer to view and edit the examples, you may need to make some changes to `.vscode/settings.json` to tell it which project we’re working on. Follow the instructions commented in that file to get rust-analyzer working correctly.
|
||||
|
||||
=== Bare metal
|
||||
|
||||
The first thing you'll notice is a few declarations, two of which indicate that Embassy is suitable for bare metal development:
|
||||
The first thing you’ll notice are two attributes at the top of the file. These tells the compiler that program has no access to std, and that there is no main function (because it is not run by an OS).
|
||||
|
||||
[source,rust]
|
||||
----
|
||||
@ -48,9 +50,9 @@ NOTE: Notice that there is no busy waiting going on in this task. It is using th
|
||||
|
||||
=== Main
|
||||
|
||||
The main entry point of an Embassy application is defined using the `#[embassy_executor::main]` macro. The entry point is also required to take a `Spawner` and a `Peripherals` argument.
|
||||
The main entry point of an Embassy application is defined using the `#[embassy_executor::main]` macro. The entry point is passed a `Spawner`, which it can use to spawn other tasks.
|
||||
|
||||
The `Spawner` is the way the main application spawns other tasks. The `Peripherals` type comes from the HAL and holds all peripherals that the application may use. In this case, we want to configure one of the pins as a GPIO output driving the LED:
|
||||
We then initialize the HAL with a default config, which gives us a `Peripherals` struct we can use to access the MCU’s various peripherals. In this case, we want to configure one of the pins as a GPIO output driving the LED:
|
||||
|
||||
[source,rust]
|
||||
----
|
||||
@ -60,7 +62,6 @@ include::example$basic/src/main.rs[lines="22..-1"]
|
||||
What happens when the `blinker` task has been spawned and main returns? Well, the main entry point is actually just like any other task, except that you can only have one and it takes some specific type arguments. The magic lies within the `#[embassy_executor::main]` macro. The macro does the following:
|
||||
|
||||
. Creates an Embassy Executor
|
||||
. Initializes the microcontroller HAL to get the `Peripherals`
|
||||
. Defines a main task for the entry point
|
||||
. Runs the executor spawning the main task
|
||||
|
||||
|
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.
|
||||
|
28
docs/modules/ROOT/pages/delaying_a_task.adoc
Normal file
28
docs/modules/ROOT/pages/delaying_a_task.adoc
Normal file
@ -0,0 +1,28 @@
|
||||
= Delaying a Task
|
||||
|
||||
In an embedded program, delaying a task is one of the most common actions taken. In an event loop, delays will need to be inserted to ensure
|
||||
that other tasks have a chance to run before the next iteration of the loop is called, if no other I/O is performed. Embassy provides an abstraction
|
||||
to delay the current task for a specified interval of time.
|
||||
|
||||
Timing is serviced by the `embassy::time::Timer` struct, which provides two timing methods.
|
||||
|
||||
`Timer::at` creates a future that completes at the specified `Instant`, relative to the system boot time.
|
||||
`Timer::after` creates a future that completes after the specified `Duration`, relative to when the future was created.
|
||||
|
||||
An example of a delay is provided as follows:
|
||||
|
||||
[,rust]
|
||||
----
|
||||
use embassy::executor::{task, Executor};
|
||||
use embassy::time::{Duration, Timer};
|
||||
|
||||
#[task]
|
||||
/// Task that ticks periodically
|
||||
async fn tick_periodic() -> ! {
|
||||
loop {
|
||||
rprintln!("tick!");
|
||||
// async sleep primitive, suspends the task for 500ms.
|
||||
Timer::after(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
----
|
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.
|
@ -9,7 +9,9 @@ If you don't have any supported board, don't worry: you can also run embassy on
|
||||
|
||||
== Getting a board with examples
|
||||
|
||||
Embassy supports many microcontroller families, but the easiest ways to get started is if you have one of the more common development kits.
|
||||
Embassy supports many microcontroller families, but the quickest way to get started is by using a board which Embassy has existing example code for.
|
||||
|
||||
This list is non-exhaustive. If your board isn’t included here, check the link:https://github.com/embassy-rs/embassy/tree/main/examples[examples folder] to see if example code has been written for it.
|
||||
|
||||
=== nRF kits
|
||||
|
||||
@ -36,7 +38,7 @@ Embassy supports many microcontroller families, but the easiest ways to get star
|
||||
|
||||
== Running an example
|
||||
|
||||
First you need to clone the [github repository];
|
||||
First you need to clone the link:https://github.com/embassy-rs/embassy[github repository];
|
||||
|
||||
[source, bash]
|
||||
----
|
||||
@ -44,17 +46,80 @@ git clone https://github.com/embassy-rs/embassy.git
|
||||
cd embassy
|
||||
----
|
||||
|
||||
You can run an example by opening a terminal and entering the following commands:
|
||||
Once you have a copy of the repository, find examples folder for your board and, and build an example program. `blinky` is a good choice as all it does is blink an LED – the embedded world’s equivalent of “Hello World”.
|
||||
|
||||
[source, bash]
|
||||
----
|
||||
cd examples/nrf52840
|
||||
cargo build --bin blinky --release
|
||||
----
|
||||
|
||||
Once you’ve confirmed you can build the example, connect your computer to your board with a debug probe and run it on hardware:
|
||||
|
||||
[source, bash]
|
||||
----
|
||||
cargo run --bin blinky --release
|
||||
----
|
||||
|
||||
If everything worked correctly, you should see a blinking LED on your board, and debug output similar to this on your computer:
|
||||
|
||||
[source]
|
||||
----
|
||||
Finished dev [unoptimized + debuginfo] target(s) in 1m 56s
|
||||
Running `probe-run --chip STM32F407VGTx target/thumbv7em-none-eabi/debug/blinky`
|
||||
(HOST) INFO flashing program (71.36 KiB)
|
||||
(HOST) INFO success!
|
||||
────────────────────────────────────────────────────────────────────────────────
|
||||
0 INFO Hello World!
|
||||
└─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:18
|
||||
1 INFO high
|
||||
└─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:23
|
||||
2 INFO low
|
||||
└─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:27
|
||||
3 INFO high
|
||||
└─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:23
|
||||
4 INFO low
|
||||
└─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:27
|
||||
----
|
||||
|
||||
NOTE: How does the `cargo run` command know how to connect to our board and program it? In each `examples` folder, there’s a `.cargo/config.toml` file which tells cargo to use link:https://probe.rs/[probe-rs] as the runner for ARM binaries in that folder. probe-rs handles communication with the debug probe and MCU. In order for this to work, probe-rs needs to know which chip it’s programming, so you’ll have to edit this file if you want to run examples on other chips.
|
||||
|
||||
=== It didn’t work!
|
||||
|
||||
If you hare having issues when running `cargo run --release`, please check the following:
|
||||
|
||||
* You are specifying the correct `--chip on the command line``, OR
|
||||
* You have set `.cargo/config.toml`'s run line to the correct chip, AND
|
||||
* You have changed `examples/Cargo.toml`'s HAL (e.g. embassy-stm32) dependency's feature to use the correct chip (replace the existing stm32xxxx feature)
|
||||
|
||||
At this point the project should run. If you do not see a blinky LED for blinky, for example, be sure to check the code is toggling your board's LED pin.
|
||||
|
||||
If you are trying to run an example with `cargo run --release` and you see the following output:
|
||||
[source]
|
||||
----
|
||||
0.000000 INFO Hello World!
|
||||
└─ <invalid location: defmt frame-index: 14>
|
||||
0.000000 DEBUG rcc: Clocks { sys: Hertz(80000000), apb1: Hertz(80000000), apb1_tim: Hertz(80000000), apb2: Hertz(80000000), apb2_tim: Hertz(80000000), ahb1: Hertz(80000000), ahb2: Hertz(80000000), ahb3: Hertz(80000000) }
|
||||
└─ <invalid location: defmt frame-index: 124>
|
||||
0.000061 TRACE allocating type=Interrupt mps=8 interval_ms=255, dir=In
|
||||
└─ <invalid location: defmt frame-index: 68>
|
||||
0.000091 TRACE index=1
|
||||
└─ <invalid location: defmt frame-index: 72>
|
||||
----
|
||||
|
||||
To get rid of the frame-index error add the following to your `Cargo.toml`:
|
||||
|
||||
[source,toml]
|
||||
----
|
||||
[profile.release]
|
||||
debug = 2
|
||||
----
|
||||
|
||||
If you’re still having problems, check the link:https://embassy.dev/book/dev/faq.html[FAQ], or ask for help in the link:https://matrix.to/#/#embassy-rs:matrix.org[Embassy Chat Room].
|
||||
|
||||
== What's next?
|
||||
|
||||
Congratulations, you have your first Embassy application running! Here are some alternatives on where to go from here:
|
||||
Congratulations, you have your first Embassy application running! Here are some suggestions for where to go from here:
|
||||
|
||||
* Read more about the xref:runtime.adoc[executor].
|
||||
* Read more about the xref:hal.adoc[HAL].
|
||||
|
@ -4,34 +4,56 @@ Embassy is a project to make async/await a first-class option for embedded devel
|
||||
|
||||
== What is async?
|
||||
|
||||
When handling I/O, software must call functions that block program execution until the I/O operation completes. When running inside of an OS such as Linux, such functions generally transfer control to the kernel so that another task, known as a thread, can be executed if available, or the CPU can be put to sleep until another such task is ready to perform more work. Because an OS cannot presume that threads will behave cooperatively, threads are relatively resource-intensive, and may be forcibly interrupted they do not transfer control back to the kernel within an allotted time. But if tasks could be presumed to behave cooperatively, or at least not maliciously, it would be possible to create tasks that appear to be almost free when compared to a traditional OS thread. In Rust, these lightweight tasks, known as 'coroutines' or 'goroutines' in other languages, are implemented with async.
|
||||
When handling I/O, software must call functions that block program execution until the I/O operation completes. When running inside of an OS such as Linux, such functions generally transfer control to the kernel so that another task (known as a “thread”) can be executed if available, or the CPU can be put to sleep until another task is ready.
|
||||
|
||||
Async-await works by transforming each async function into an object called a future. When a future blocks on I/O the future yields, and the scheduler, called an executor, can select a different future to execute. Compared to alternatives such as an RTOS, async can yield better performance and lower power consumption because the executor doesn't have to guess when a future is ready to execute. However, program size may be higher than other alternatives, which may be a problem for certain space-constrained devices with very low memory. On the devices Embassy supports, such as stm32 and nrf, memory is generally large enough to accommodate the modestly-increased program size.
|
||||
Because an OS cannot presume that threads will behave cooperatively, threads are relatively resource-intensive, and may be forcibly interrupted they do not transfer control back to the kernel within an allotted time. If tasks could be presumed to behave cooperatively, or at least not maliciously, it would be possible to create tasks that appear to be almost free when compared to a traditional OS thread.
|
||||
|
||||
In other programming languages, these lightweight tasks are known as “coroutines” or ”goroutines”. In Rust, they are implemented with async. Async-await works by transforming each async function into an object called a future. When a future blocks on I/O the future yields, and the scheduler, called an executor, can select a different future to execute.
|
||||
|
||||
Compared to alternatives such as an RTOS, async can yield better performance and lower power consumption because the executor doesn't have to guess when a future is ready to execute. However, program size may be higher than other alternatives, which may be a problem for certain space-constrained devices with very low memory. On the devices Embassy supports, such as stm32 and nrf, memory is generally large enough to accommodate the modestly-increased program size.
|
||||
|
||||
== What is Embassy?
|
||||
|
||||
The Embassy project consists of several crates that you can use together or independently:
|
||||
|
||||
* **Executor** - The link:https://docs.embassy.dev/embassy-executor/[embassy-executor] is an async/await executor that generally executes a fixed number of tasks, allocated at startup, though more can be added later. The HAL is an API that you can use to access peripherals, such as USART, UART, I2C, SPI, CAN, and USB. Embassy provides implementations of both async and blocking APIs where it makes sense. DMA (Direct Memory Access) is an example where async is a good fit, whereas GPIO states are a better fit for a blocking API. The executor may also provide a system timer that you can use for both async and blocking delays. For less than one microsecond, blocking delays should be used because the cost of context-switching is too high and the executor will be unable to provide accurate timing.
|
||||
=== Executor
|
||||
The link:https://docs.embassy.dev/embassy-executor/[embassy-executor] is an async/await executor that generally executes a fixed number of tasks, allocated at startup, though more can be added later. The executor may also provide a system timer that you can use for both async and blocking delays. For less than one microsecond, blocking delays should be used because the cost of context-switching is too high and the executor will be unable to provide accurate timing.
|
||||
|
||||
=== Hardware Abstraction Layers
|
||||
HALs implement safe Rust API which let you use peripherals such as USART, UART, I2C, SPI, CAN, and USB without having to directly manipulate registers.
|
||||
|
||||
Embassy provides implementations of both async and blocking APIs where it makes sense. DMA (Direct Memory Access) is an example where async is a good fit, whereas GPIO states are a better fit for a blocking API.
|
||||
|
||||
The Embassy project maintains HALs for select hardware, but you can still use HALs from other projects with Embassy.
|
||||
|
||||
* link:https://docs.embassy.dev/embassy-stm32/[embassy-stm32], for all STM32 microcontroller families.
|
||||
* link:https://docs.embassy.dev/embassy-nrf/[embassy-nrf], for the Nordic Semiconductor nRF52, nRF53, nRF91 series.
|
||||
* link:https://docs.embassy.dev/embassy-rp/[embassy-rp], for the Raspberry Pi RP2040 microcontroller.
|
||||
* link:https://github.com/esp-rs[esp-rs], for the Espressif Systems ESP32 series of chips.
|
||||
|
||||
* **Hardware Abstraction Layers** - HALs implement safe, idiomatic Rust APIs to use the hardware capabilities, so raw register manipulation is not needed. The Embassy project maintains HALs for select hardware, but you can still use HALs from other projects with Embassy.
|
||||
** link:https://docs.embassy.dev/embassy-stm32/[embassy-stm32], for all STM32 microcontroller families.
|
||||
** link:https://docs.embassy.dev/embassy-nrf/[embassy-nrf], for the Nordic Semiconductor nRF52, nRF53, nRF91 series.
|
||||
** link:https://docs.embassy.dev/embassy-rp/[embassy-rp], for the Raspberry Pi RP2040 microcontroller.
|
||||
** link:https://github.com/esp-rs[esp-rs], for the Espressif Systems ESP32 series of chips.
|
||||
+
|
||||
NOTE: A common question is if one can use the Embassy HALs standalone. Yes, it is possible! There are no dependency on the executor within the HALs. You can even use them without async,
|
||||
as they implement both the link:https://github.com/rust-embedded/embedded-hal[Embedded HAL] blocking and async traits.
|
||||
|
||||
* **Networking** - The link:https://docs.embassy.dev/embassy-net/[embassy-net] network stack implements extensive networking functionality, including Ethernet, IP, TCP, UDP, ICMP and DHCP. Async drastically simplifies managing timeouts and serving multiple connections concurrently. Several drivers for WiFi and Ethernet chips can be found.
|
||||
=== Networking
|
||||
The link:https://docs.embassy.dev/embassy-net/[embassy-net] network stack implements extensive networking functionality, including Ethernet, IP, TCP, UDP, ICMP and DHCP. Async drastically simplifies managing timeouts and serving multiple connections concurrently. Several drivers for WiFi and Ethernet chips can be found.
|
||||
|
||||
* **Bluetooth** - The link:https://github.com/embassy-rs/nrf-softdevice[nrf-softdevice] crate provides Bluetooth Low Energy 4.x and 5.x support for nRF52 microcontrollers.
|
||||
=== Bluetooth
|
||||
The link:https://github.com/embassy-rs/nrf-softdevice[nrf-softdevice] crate provides Bluetooth Low Energy 4.x and 5.x support for nRF52 microcontrollers.
|
||||
|
||||
* **LoRa** - link:https://github.com/embassy-rs/lora-phy[lora-phy] and link:https://docs.embassy.dev/embassy-lora/[embassy-lora] supports LoRa networking on a wide range of LoRa radios, fully integrated with a Rust link:https://github.com/ivajloip/rust-lorawan[LoRaWAN] implementation.
|
||||
=== LoRa
|
||||
link:https://github.com/embassy-rs/lora-phy[lora-phy] and link:https://docs.embassy.dev/embassy-lora/[embassy-lora] supports LoRa networking on a wide range of LoRa radios, fully integrated with a Rust link:https://github.com/ivajloip/rust-lorawan[LoRaWAN] implementation.
|
||||
|
||||
* **USB** - link:https://docs.embassy.dev/embassy-usb/[embassy-usb] implements a device-side USB stack. Implementations for common classes such as USB serial (CDC ACM) and USB HID are available, and a rich builder API allows building your own.
|
||||
=== USB
|
||||
link:https://docs.embassy.dev/embassy-usb/[embassy-usb] implements a device-side USB stack. Implementations for common classes such as USB serial (CDC ACM) and USB HID are available, and a rich builder API allows building your own.
|
||||
|
||||
* **Bootloader and DFU** - link:https://github.com/embassy-rs/embassy/tree/master/embassy-boot[embassy-boot] is a lightweight bootloader supporting firmware application upgrades in a power-fail-safe way, with trial boots and rollbacks.
|
||||
=== Bootloader and DFU
|
||||
link:https://github.com/embassy-rs/embassy/tree/master/embassy-boot[embassy-boot] is a lightweight bootloader supporting firmware application upgrades in a power-fail-safe way, with trial boots and rollbacks.
|
||||
|
||||
== What is DMA?
|
||||
|
||||
For most I/O in embedded devices, the peripheral doesn't directly support the transmission of multiple bits at once, with CAN being a notable exception. Instead, the MCU must write each byte, one at a time, and then wait until the peripheral is ready to send the next. For high I/O rates, this can pose a problem if the MCU must devote an increasing portion of its time handling each byte. The solution to this problem is to use the Direct Memory Access controller.
|
||||
|
||||
The Direct Memory Access controller (DMA) is a controller that is present in MCUs that Embassy supports, including stm32 and nrf. The DMA allows the MCU to set up a transfer, either send or receive, and then wait for the transfer to complete. With DMA, once started, no MCU intervention is required until the transfer is complete, meaning that the MCU can perform other computation, or set up other I/O while the transfer is in progress. For high I/O rates, DMA can cut the time that the MCU spends handling I/O by over half. However, because DMA is more complex to set-up, it is less widely used in the embedded community. Embassy aims to change that by making DMA the first choice rather than the last. Using Embassy, there's no additional tuning required once I/O rates increase because your application is already set-up to handle them.
|
||||
|
||||
== Resources
|
||||
|
||||
|
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
|
||||
----
|
@ -28,9 +28,9 @@ digest = "0.10"
|
||||
log = { version = "0.4", optional = true }
|
||||
ed25519-dalek = { version = "1.0.1", default_features = false, features = ["u32_backend"], optional = true }
|
||||
embassy-embedded-hal = { version = "0.1.0", path = "../../embassy-embedded-hal" }
|
||||
embassy-sync = { version = "0.4.0", path = "../../embassy-sync" }
|
||||
embedded-storage = "0.3.0"
|
||||
embedded-storage-async = { version = "0.4.0" }
|
||||
embassy-sync = { version = "0.5.0", path = "../../embassy-sync" }
|
||||
embedded-storage = "0.3.1"
|
||||
embedded-storage-async = { version = "0.4.1" }
|
||||
salty = { git = "https://github.com/ycrypto/salty.git", rev = "a9f17911a5024698406b75c0fac56ab5ccf6a8c7", optional = true }
|
||||
signature = { version = "1.6.4", default-features = false }
|
||||
|
||||
|
@ -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.
|
||||
|
@ -16,13 +16,13 @@ target = "thumbv7em-none-eabi"
|
||||
[dependencies]
|
||||
defmt = { version = "0.3", optional = true }
|
||||
|
||||
embassy-sync = { version = "0.4.0", path = "../../embassy-sync" }
|
||||
embassy-sync = { version = "0.5.0", path = "../../embassy-sync" }
|
||||
embassy-nrf = { path = "../../embassy-nrf" }
|
||||
embassy-boot = { path = "../boot", default-features = false }
|
||||
cortex-m = { version = "0.7.6" }
|
||||
cortex-m-rt = { version = "0.7" }
|
||||
embedded-storage = "0.3.0"
|
||||
embedded-storage-async = { version = "0.4.0" }
|
||||
embedded-storage = "0.3.1"
|
||||
embedded-storage-async = { version = "0.4.1" }
|
||||
cfg-if = "1.0.0"
|
||||
|
||||
nrf-softdevice-mbr = { version = "0.1.0", git = "https://github.com/embassy-rs/nrf-softdevice.git", branch = "master", optional = true }
|
||||
|
@ -17,15 +17,15 @@ defmt = { version = "0.3", optional = true }
|
||||
defmt-rtt = { version = "0.4", optional = true }
|
||||
log = { version = "0.4", optional = true }
|
||||
|
||||
embassy-sync = { version = "0.4.0", path = "../../embassy-sync" }
|
||||
embassy-sync = { version = "0.5.0", path = "../../embassy-sync" }
|
||||
embassy-rp = { path = "../../embassy-rp", default-features = false }
|
||||
embassy-boot = { path = "../boot", default-features = false }
|
||||
embassy-time = { path = "../../embassy-time" }
|
||||
|
||||
cortex-m = { version = "0.7.6" }
|
||||
cortex-m-rt = { version = "0.7" }
|
||||
embedded-storage = "0.3.0"
|
||||
embedded-storage-async = { version = "0.4.0" }
|
||||
embedded-storage = "0.3.1"
|
||||
embedded-storage-async = { version = "0.4.1" }
|
||||
cfg-if = "1.0.0"
|
||||
|
||||
[features]
|
||||
|
@ -18,13 +18,13 @@ defmt = { version = "0.3", optional = true }
|
||||
defmt-rtt = { version = "0.4", optional = true }
|
||||
log = { version = "0.4", optional = true }
|
||||
|
||||
embassy-sync = { version = "0.4.0", path = "../../embassy-sync" }
|
||||
embassy-sync = { version = "0.5.0", path = "../../embassy-sync" }
|
||||
embassy-stm32 = { path = "../../embassy-stm32", default-features = false }
|
||||
embassy-boot = { path = "../boot", default-features = false }
|
||||
cortex-m = { version = "0.7.6" }
|
||||
cortex-m-rt = { version = "0.7" }
|
||||
embedded-storage = "0.3.0"
|
||||
embedded-storage-async = { version = "0.4.0" }
|
||||
embedded-storage = "0.3.1"
|
||||
embedded-storage-async = { version = "0.4.1" }
|
||||
cfg-if = "1.0.0"
|
||||
|
||||
[features]
|
||||
|
@ -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.
|
||||
|
@ -18,15 +18,15 @@ default = ["time"]
|
||||
|
||||
[dependencies]
|
||||
embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
|
||||
embassy-sync = { version = "0.4.0", path = "../embassy-sync" }
|
||||
embassy-time = { version = "0.1.5", path = "../embassy-time", optional = true }
|
||||
embassy-sync = { version = "0.5.0", path = "../embassy-sync" }
|
||||
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-storage = "0.3.0"
|
||||
embedded-storage-async = { version = "0.4.0" }
|
||||
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"
|
||||
|
||||
defmt = { version = "0.3", optional = true }
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "embassy-macros"
|
||||
version = "0.2.1"
|
||||
name = "embassy-executor-macros"
|
||||
version = "0.4.0"
|
||||
edition = "2021"
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "macros for creating the entry point and tasks for embassy-executor"
|
15
embassy-executor-macros/README.md
Normal file
15
embassy-executor-macros/README.md
Normal file
@ -0,0 +1,15 @@
|
||||
# embassy-executor-macros
|
||||
|
||||
An [Embassy](https://embassy.dev) project.
|
||||
|
||||
NOTE: Do not use this crate directly. The macros are re-exported by `embassy-executor`.
|
||||
|
||||
## License
|
||||
|
||||
This work is licensed under either of
|
||||
|
||||
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or
|
||||
<http://www.apache.org/licenses/LICENSE-2.0>)
|
||||
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
|
||||
|
||||
at your option.
|
@ -7,7 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Removed `arch-xtensa`. Use the executor provided by the HAL crate (`esp-hal`, `esp32s3-hal`, etc...) instead.
|
||||
## 0.4.0 - 2023-12-05
|
||||
|
||||
- Removed `arch-xtensa`. Use the executor provided by the HAL crate (`esp-hal`, `esp32s3-hal`, etc...) instead.
|
||||
- Added an arena allocator for tasks, allowing using the `main` and `task` macros on Rust 1.75 stable. (it is only used if the `nightly` feature is not enabled. When `nightly` is enabled, `type_alias_impl_trait` is used to statically allocate tasks, as before).
|
||||
|
||||
## 0.3.3 - 2023-11-15
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "embassy-executor"
|
||||
version = "0.3.3"
|
||||
version = "0.4.0"
|
||||
edition = "2021"
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "async/await executor designed for embedded usage"
|
||||
@ -32,8 +32,8 @@ defmt = { version = "0.3", optional = true }
|
||||
log = { version = "0.4.14", optional = true }
|
||||
rtos-trace = { version = "0.1.2", optional = true }
|
||||
|
||||
embassy-macros = { version = "0.2.1", path = "../embassy-macros" }
|
||||
embassy-time = { version = "0.1.5", path = "../embassy-time", optional = true}
|
||||
embassy-executor-macros = { version = "0.4.0", path = "../embassy-executor-macros" }
|
||||
embassy-time = { version = "0.2", path = "../embassy-time", optional = true}
|
||||
critical-section = "1.1"
|
||||
|
||||
# needed for riscv
|
||||
@ -66,7 +66,7 @@ executor-thread = []
|
||||
executor-interrupt = []
|
||||
|
||||
# Enable nightly-only features
|
||||
nightly = ["embassy-macros/nightly"]
|
||||
nightly = ["embassy-executor-macros/nightly"]
|
||||
|
||||
turbowakers = []
|
||||
|
||||
|
@ -51,7 +51,7 @@ mod thread {
|
||||
use core::arch::asm;
|
||||
use core::marker::PhantomData;
|
||||
|
||||
pub use embassy_macros::main_cortex_m as main;
|
||||
pub use embassy_executor_macros::main_cortex_m as main;
|
||||
|
||||
use crate::{raw, Spawner};
|
||||
|
||||
|
@ -7,7 +7,7 @@ pub use thread::*;
|
||||
mod thread {
|
||||
use core::marker::PhantomData;
|
||||
|
||||
pub use embassy_macros::main_riscv as main;
|
||||
pub use embassy_executor_macros::main_riscv as main;
|
||||
use portable_atomic::{AtomicBool, Ordering};
|
||||
|
||||
use crate::{raw, Spawner};
|
||||
|
@ -8,7 +8,7 @@ mod thread {
|
||||
use std::marker::PhantomData;
|
||||
use std::sync::{Condvar, Mutex};
|
||||
|
||||
pub use embassy_macros::main_std as main;
|
||||
pub use embassy_executor_macros::main_std as main;
|
||||
|
||||
use crate::{raw, Spawner};
|
||||
|
||||
|
@ -8,7 +8,7 @@ mod thread {
|
||||
|
||||
use core::marker::PhantomData;
|
||||
|
||||
pub use embassy_macros::main_wasm as main;
|
||||
pub use embassy_executor_macros::main_wasm as main;
|
||||
use js_sys::Promise;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
|
@ -6,7 +6,7 @@
|
||||
// This mod MUST go first, so that the others see its macros.
|
||||
pub(crate) mod fmt;
|
||||
|
||||
pub use embassy_macros::task;
|
||||
pub use embassy_executor_macros::task;
|
||||
|
||||
macro_rules! check_at_most_one {
|
||||
(@amo [$($feats:literal)*] [] [$($res:tt)*]) => {
|
||||
|
@ -5,7 +5,7 @@
|
||||
//! ## WARNING: here be dragons!
|
||||
//!
|
||||
//! Using this module requires respecting subtle safety contracts. If you can, prefer using the safe
|
||||
//! [executor wrappers](crate::Executor) and the [`embassy_executor::task`](embassy_macros::task) macro, which are fully safe.
|
||||
//! [executor wrappers](crate::Executor) and the [`embassy_executor::task`](embassy_executor_macros::task) macro, which are fully safe.
|
||||
|
||||
#[cfg_attr(target_has_atomic = "ptr", path = "run_queue_atomics.rs")]
|
||||
#[cfg_attr(not(target_has_atomic = "ptr"), path = "run_queue_critical_section.rs")]
|
||||
@ -97,7 +97,7 @@ impl TaskRef {
|
||||
/// A `TaskStorage` must live forever, it may not be deallocated even after the task has finished
|
||||
/// running. Hence the relevant methods require `&'static self`. It may be reused, however.
|
||||
///
|
||||
/// Internally, the [embassy_executor::task](embassy_macros::task) macro allocates an array of `TaskStorage`s
|
||||
/// Internally, the [embassy_executor::task](embassy_executor_macros::task) macro allocates an array of `TaskStorage`s
|
||||
/// in a `static`. The most common reason to use the raw `Task` is to have control of where
|
||||
/// the memory for the task is allocated: on the stack, or on the heap with e.g. `Box::leak`, etc.
|
||||
|
||||
|
@ -115,9 +115,9 @@ impl Spawner {
|
||||
}
|
||||
}
|
||||
|
||||
// Used by the `embassy_macros::main!` macro to throw an error when spawn
|
||||
// Used by the `embassy_executor_macros::main!` macro to throw an error when spawn
|
||||
// fails. This is here to allow conditional use of `defmt::unwrap!`
|
||||
// without introducing a `defmt` feature in the `embassy_macros` package,
|
||||
// without introducing a `defmt` feature in the `embassy_executor_macros` package,
|
||||
// which would require use of `-Z namespaced-features`.
|
||||
/// Spawn a task into an executor, panicking on failure.
|
||||
///
|
||||
|
@ -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};
|
||||
|
@ -1,21 +0,0 @@
|
||||
# embassy-macros
|
||||
|
||||
An [Embassy](https://embassy.dev) project.
|
||||
|
||||
Macros for creating the main entry point and tasks that can be spawned by `embassy-executor`.
|
||||
|
||||
NOTE: The macros are re-exported by the `embassy-executor` crate which should be used instead of adding a direct dependency on the `embassy-macros` crate.
|
||||
|
||||
## Minimum supported Rust version (MSRV)
|
||||
|
||||
The `task` and `main` macros require the type alias impl trait (TAIT) nightly feature in order to compile.
|
||||
|
||||
## License
|
||||
|
||||
This work is licensed under either of
|
||||
|
||||
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or
|
||||
<http://www.apache.org/licenses/LICENSE-2.0>)
|
||||
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
|
||||
|
||||
at your option.
|
@ -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.1.5", path = "../embassy-time" }
|
||||
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"] }
|
||||
|
@ -24,6 +24,6 @@ features = ["defmt"]
|
||||
defmt = { version = "0.3", optional = true }
|
||||
log = { version = "0.4.14", optional = true }
|
||||
|
||||
embassy-sync = { version = "0.4.0", path = "../embassy-sync" }
|
||||
embassy-sync = { version = "0.5.0", path = "../embassy-sync" }
|
||||
embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
|
||||
embassy-net-driver = { version = "0.2.0", path = "../embassy-net-driver" }
|
||||
|
@ -8,10 +8,10 @@ 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.1.5", path = "../embassy-time" }
|
||||
embassy-time = { version = "0.2", path = "../embassy-time" }
|
||||
embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
|
||||
|
||||
defmt = { version = "0.3", optional = true }
|
||||
|
@ -7,13 +7,13 @@ edition = "2021"
|
||||
defmt = { version = "0.3", optional = true }
|
||||
log = { version = "0.4.14", optional = true }
|
||||
|
||||
embassy-time = { version = "0.1.5", path = "../embassy-time" }
|
||||
embassy-sync = { version = "0.4.0", path = "../embassy-sync"}
|
||||
embassy-time = { version = "0.2", path = "../embassy-time" }
|
||||
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"] }
|
||||
|
@ -19,7 +19,7 @@ embedded-io-async = { version = "0.6.1" }
|
||||
embassy-net-driver-channel = { version = "0.2.0", path = "../embassy-net-driver-channel" }
|
||||
embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
|
||||
ppproto = { version = "0.1.2"}
|
||||
embassy-sync = { version = "0.4.0", path = "../embassy-sync" }
|
||||
embassy-sync = { version = "0.5.0", path = "../embassy-sync" }
|
||||
|
||||
[package.metadata.embassy_docs]
|
||||
src_base = "https://github.com/embassy-rs/embassy/blob/embassy-net-ppp-v$VERSION/embassy-net-ppp/src/"
|
||||
|
@ -8,10 +8,10 @@ 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.1.5", path = "../embassy-time" }
|
||||
embassy-time = { version = "0.2", path = "../embassy-time" }
|
||||
embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
|
||||
defmt = { version = "0.3", optional = true }
|
||||
|
||||
|
@ -50,8 +50,8 @@ smoltcp = { git = "https://github.com/smoltcp-rs/smoltcp.git", rev = "b57e2f9e70
|
||||
] }
|
||||
|
||||
embassy-net-driver = { version = "0.2.0", path = "../embassy-net-driver" }
|
||||
embassy-time = { version = "0.1.5", path = "../embassy-time" }
|
||||
embassy-sync = { version = "0.4.0", path = "../embassy-sync" }
|
||||
embassy-time = { version = "0.2", path = "../embassy-time" }
|
||||
embassy-sync = { version = "0.5.0", path = "../embassy-sync" }
|
||||
embedded-io-async = { version = "0.6.1" }
|
||||
|
||||
managed = { version = "0.8.0", default-features = false, features = [ "map" ] }
|
||||
|
@ -64,6 +64,11 @@ nfc-pins-as-gpio = []
|
||||
# nrf52820, nrf52833, nrf52840: P0_18
|
||||
reset-pin-as-gpio = []
|
||||
|
||||
# Implements the MultiwriteNorFlash trait for QSPI. Should only be enabled if your external
|
||||
# flash supports the semantics described in
|
||||
# https://docs.rs/embedded-storage/0.3.1/embedded_storage/nor_flash/trait.MultiwriteNorFlash.html
|
||||
qspi-multiwrite-flash = []
|
||||
|
||||
# Features starting with `_` are for internal use only. They're not intended
|
||||
# to be enabled by other crates, and are not covered by semver guarantees.
|
||||
|
||||
@ -87,15 +92,15 @@ _gpio-p1 = []
|
||||
_nrf52832_anomaly_109 = []
|
||||
|
||||
[dependencies]
|
||||
embassy-time = { version = "0.1.5", path = "../embassy-time", optional = true }
|
||||
embassy-sync = { version = "0.4.0", path = "../embassy-sync" }
|
||||
embassy-time = { version = "0.2", path = "../embassy-time", optional = true }
|
||||
embassy-sync = { version = "0.5.0", path = "../embassy-sync" }
|
||||
embassy-hal-internal = {version = "0.1.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-3"] }
|
||||
embassy-embedded-hal = {version = "0.1.0", path = "../embassy-embedded-hal" }
|
||||
embassy-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" }
|
||||
|
||||
@ -106,7 +111,7 @@ cortex-m = "0.7.6"
|
||||
critical-section = "1.1"
|
||||
rand_core = "0.6.3"
|
||||
fixed = "1.10.0"
|
||||
embedded-storage = "0.3.0"
|
||||
embedded-storage = "0.3.1"
|
||||
embedded-storage-async = "0.4.0"
|
||||
cfg-if = "1.0.0"
|
||||
|
||||
@ -120,4 +125,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 }
|
||||
|
||||
|
@ -50,21 +50,21 @@ impl<'d, T: Pin> Input<'d, T> {
|
||||
Self { pin }
|
||||
}
|
||||
|
||||
/// Test if current pin level is high.
|
||||
/// Get whether the pin input 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.
|
||||
/// Get whether the pin input 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
|
||||
/// Get the pin input level.
|
||||
#[inline]
|
||||
pub fn get_level(&self) -> Level {
|
||||
pub fn get_level(&mut self) -> Level {
|
||||
self.pin.get_level()
|
||||
}
|
||||
}
|
||||
@ -158,21 +158,21 @@ impl<'d, T: Pin> Output<'d, T> {
|
||||
self.pin.set_level(level)
|
||||
}
|
||||
|
||||
/// Is the output pin set as high?
|
||||
/// Get whether the output level is set to 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?
|
||||
/// Get whether the output level is set to 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
|
||||
/// Get the current output level.
|
||||
#[inline]
|
||||
pub fn get_output_level(&self) -> Level {
|
||||
pub fn get_output_level(&mut self) -> Level {
|
||||
self.pin.get_output_level()
|
||||
}
|
||||
}
|
||||
@ -275,21 +275,26 @@ impl<'d, T: Pin> Flex<'d, T> {
|
||||
self.pin.conf().reset();
|
||||
}
|
||||
|
||||
/// Test if current pin level is high.
|
||||
/// Get whether the pin input 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.
|
||||
/// Get whether the pin input 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
|
||||
/// Get the pin input level.
|
||||
#[inline]
|
||||
pub fn get_level(&self) -> Level {
|
||||
pub fn get_level(&mut self) -> Level {
|
||||
self.is_high().into()
|
||||
}
|
||||
|
||||
@ -314,21 +319,26 @@ impl<'d, T: Pin> Flex<'d, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the output pin set as high?
|
||||
/// Get whether the output level is set to 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?
|
||||
/// Get whether the output level is set to 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.block().out.read().bits() & (1 << self.pin.pin()) == 0
|
||||
}
|
||||
|
||||
/// What level output is set to
|
||||
/// Get the current output level.
|
||||
#[inline]
|
||||
pub fn get_output_level(&self) -> Level {
|
||||
pub fn get_output_level(&mut self) -> Level {
|
||||
self.is_set_high().into()
|
||||
}
|
||||
}
|
||||
@ -498,11 +508,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 +530,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 +545,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 +567,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 +581,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 +605,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 +622,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 +642,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 {
|
||||
|
25
embassy-nrf/src/qspi.rs
Normal file → Executable file
25
embassy-nrf/src/qspi.rs
Normal file → Executable file
@ -391,8 +391,13 @@ impl<'d, T: Instance> Qspi<'d, T> {
|
||||
///
|
||||
/// The difference with `read` is that this does not do bounds checks
|
||||
/// against the flash capacity. It is intended for use when QSPI is used as
|
||||
/// a raw bus, not with flash memory.
|
||||
/// a raw bus, not with flash memory.
|
||||
pub async fn read_raw(&mut self, address: u32, data: &mut [u8]) -> Result<(), Error> {
|
||||
// Avoid blocking_wait_ready() blocking forever on zero-length buffers.
|
||||
if data.len() == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let ondrop = OnDrop::new(Self::blocking_wait_ready);
|
||||
|
||||
self.start_read(address, data)?;
|
||||
@ -409,6 +414,11 @@ impl<'d, T: Instance> Qspi<'d, T> {
|
||||
/// against the flash capacity. It is intended for use when QSPI is used as
|
||||
/// a raw bus, not with flash memory.
|
||||
pub async fn write_raw(&mut self, address: u32, data: &[u8]) -> Result<(), Error> {
|
||||
// Avoid blocking_wait_ready() blocking forever on zero-length buffers.
|
||||
if data.len() == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let ondrop = OnDrop::new(Self::blocking_wait_ready);
|
||||
|
||||
self.start_write(address, data)?;
|
||||
@ -425,6 +435,11 @@ impl<'d, T: Instance> Qspi<'d, T> {
|
||||
/// against the flash capacity. It is intended for use when QSPI is used as
|
||||
/// a raw bus, not with flash memory.
|
||||
pub fn blocking_read_raw(&mut self, address: u32, data: &mut [u8]) -> Result<(), Error> {
|
||||
// Avoid blocking_wait_ready() blocking forever on zero-length buffers.
|
||||
if data.len() == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.start_read(address, data)?;
|
||||
Self::blocking_wait_ready();
|
||||
Ok(())
|
||||
@ -436,6 +451,11 @@ impl<'d, T: Instance> Qspi<'d, T> {
|
||||
/// against the flash capacity. It is intended for use when QSPI is used as
|
||||
/// a raw bus, not with flash memory.
|
||||
pub fn blocking_write_raw(&mut self, address: u32, data: &[u8]) -> Result<(), Error> {
|
||||
// Avoid blocking_wait_ready() blocking forever on zero-length buffers.
|
||||
if data.len() == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.start_write(address, data)?;
|
||||
Self::blocking_wait_ready();
|
||||
Ok(())
|
||||
@ -585,6 +605,9 @@ impl<'d, T: Instance> NorFlash for Qspi<'d, T> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "qspi-multiwrite-flash")]
|
||||
impl<'d, T: Instance> embedded_storage::nor_flash::MultiwriteNorFlash for Qspi<'d, T> {}
|
||||
|
||||
mod _eh1 {
|
||||
use embedded_storage_async::nor_flash::{NorFlash as AsyncNorFlash, ReadNorFlash as AsyncReadNorFlash};
|
||||
|
||||
|
@ -52,8 +52,8 @@ qspi-as-gpio = []
|
||||
run-from-ram = []
|
||||
|
||||
[dependencies]
|
||||
embassy-sync = { version = "0.4.0", path = "../embassy-sync" }
|
||||
embassy-time = { version = "0.1.5", path = "../embassy-time", features = [ "tick-hz-1_000_000" ] }
|
||||
embassy-sync = { version = "0.5.0", path = "../embassy-sync" }
|
||||
embassy-time = { version = "0.2", path = "../embassy-time", features = [ "tick-hz-1_000_000" ] }
|
||||
embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
|
||||
embassy-hal-internal = {version = "0.1.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-2"] }
|
||||
embassy-embedded-hal = {version = "0.1.0", path = "../embassy-embedded-hal" }
|
||||
@ -71,21 +71,21 @@ chrono = { version = "0.4", default-features = false, optional = true }
|
||||
embedded-io = { version = "0.6.0" }
|
||||
embedded-io-async = { version = "0.6.1" }
|
||||
embedded-storage = { version = "0.3" }
|
||||
embedded-storage-async = { version = "0.4.0" }
|
||||
embedded-storage-async = { version = "0.4.1" }
|
||||
rand_core = "0.6.4"
|
||||
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" }
|
||||
rp2040-boot2 = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
embassy-executor = { version = "0.3.3", path = "../embassy-executor", features = ["nightly", "arch-std", "executor-thread"] }
|
||||
embassy-executor = { version = "0.4.0", path = "../embassy-executor", features = ["nightly", "arch-std", "executor-thread"] }
|
||||
static_cell = { version = "2" }
|
||||
|
@ -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 {
|
||||
|
@ -820,6 +820,10 @@ impl<'d, T: Instance, M: Mode> embedded_hal_nb::serial::ErrorType for Uart<'d, T
|
||||
impl<'d, T: Instance, M: Mode> embedded_hal_nb::serial::Read for UartRx<'d, T, M> {
|
||||
fn read(&mut self) -> nb::Result<u8, Self::Error> {
|
||||
let r = T::regs();
|
||||
if r.uartfr().read().rxfe() {
|
||||
return Err(nb::Error::WouldBlock);
|
||||
}
|
||||
|
||||
let dr = r.uartdr().read();
|
||||
|
||||
if dr.oe() {
|
||||
@ -830,10 +834,8 @@ impl<'d, T: Instance, M: Mode> embedded_hal_nb::serial::Read for UartRx<'d, T, M
|
||||
Err(nb::Error::Other(Error::Parity))
|
||||
} else if dr.fe() {
|
||||
Err(nb::Error::Other(Error::Framing))
|
||||
} else if dr.fe() {
|
||||
Ok(dr.data())
|
||||
} else {
|
||||
Err(nb::Error::WouldBlock)
|
||||
Ok(dr.data())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -363,7 +363,7 @@ impl<'d, T: Instance> driver::Bus for Bus<'d, T> {
|
||||
let siestatus = regs.sie_status().read();
|
||||
let intrstatus = regs.intr().read();
|
||||
|
||||
if siestatus.resume() {
|
||||
if siestatus.resume() || intrstatus.dev_resume_from_host() {
|
||||
regs.sie_status().write(|w| w.set_resume(true));
|
||||
return Poll::Ready(Event::Resume);
|
||||
}
|
||||
|
@ -12,8 +12,8 @@ features = ["stm32wb55rg"]
|
||||
|
||||
[dependencies]
|
||||
embassy-stm32 = { version = "0.1.0", path = "../embassy-stm32" }
|
||||
embassy-sync = { version = "0.4.0", path = "../embassy-sync" }
|
||||
embassy-time = { version = "0.1.5", path = "../embassy-time", optional = true }
|
||||
embassy-sync = { version = "0.5.0", path = "../embassy-sync" }
|
||||
embassy-time = { version = "0.2", path = "../embassy-time", optional = true }
|
||||
embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
|
||||
embassy-hal-internal = { version = "0.1.0", path = "../embassy-hal-internal" }
|
||||
embassy-embedded-hal = { version = "0.1.0", path = "../embassy-embedded-hal" }
|
||||
|
@ -32,22 +32,22 @@ flavors = [
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
embassy-sync = { version = "0.4.0", path = "../embassy-sync" }
|
||||
embassy-time = { version = "0.1.5", path = "../embassy-time", optional = true }
|
||||
embassy-sync = { version = "0.5.0", path = "../embassy-sync" }
|
||||
embassy-time = { version = "0.2", path = "../embassy-time", optional = true }
|
||||
embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
|
||||
embassy-hal-internal = {version = "0.1.0", path = "../embassy-hal-internal", features = ["cortex-m", "prio-bits-4"] }
|
||||
embassy-embedded-hal = {version = "0.1.0", path = "../embassy-embedded-hal" }
|
||||
embassy-net-driver = { version = "0.2.0", path = "../embassy-net-driver" }
|
||||
embassy-usb-driver = {version = "0.1.0", path = "../embassy-usb-driver" }
|
||||
embassy-executor = { version = "0.3.3", path = "../embassy-executor", optional = true }
|
||||
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.0"
|
||||
embedded-storage-async = { version = "0.4.0" }
|
||||
embedded-storage = "0.3.1"
|
||||
embedded-storage-async = { version = "0.4.1" }
|
||||
|
||||
defmt = { version = "0.3", optional = true }
|
||||
log = { version = "0.4.14", optional = true }
|
||||
@ -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();
|
||||
}
|
||||
}
|
@ -1,8 +1,10 @@
|
||||
//! Analog to Digital (ADC) converter driver.
|
||||
#![macro_use]
|
||||
|
||||
#[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")]
|
||||
@ -23,23 +25,24 @@ pub use sample_time::SampleTime;
|
||||
|
||||
use crate::peripherals;
|
||||
|
||||
/// Analog to Digital driver.
|
||||
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 +57,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,12 +77,16 @@ pub(crate) mod sealed {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_g0)))]
|
||||
/// ADC instance.
|
||||
#[cfg(not(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_f3_v1_1, adc_g0)))]
|
||||
pub trait Instance: sealed::Instance + crate::Peripheral<P = Self> {}
|
||||
#[cfg(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_g0))]
|
||||
/// ADC instance.
|
||||
#[cfg(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_f3_v1_1, adc_g0))]
|
||||
pub trait Instance: sealed::Instance + crate::Peripheral<P = Self> + crate::rcc::RccPeripheral {}
|
||||
|
||||
/// ADC pin.
|
||||
pub trait AdcPin<T: Instance>: sealed::AdcPin<T> {}
|
||||
/// ADC internal channel.
|
||||
pub trait InternalChannel<T>: sealed::InternalChannel<T> {}
|
||||
|
||||
foreach_adc!(
|
||||
@ -89,7 +96,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 +106,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,8 @@
|
||||
#[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3))]
|
||||
/// ADC resolution
|
||||
#[allow(missing_docs)]
|
||||
#[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3, adc_f3_v1_1))]
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum Resolution {
|
||||
TwelveBit,
|
||||
TenBit,
|
||||
@ -7,8 +10,11 @@ pub enum Resolution {
|
||||
SixBit,
|
||||
}
|
||||
|
||||
/// ADC resolution
|
||||
#[allow(missing_docs)]
|
||||
#[cfg(adc_v4)]
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum Resolution {
|
||||
SixteenBit,
|
||||
FourteenBit,
|
||||
@ -19,7 +25,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,13 +46,16 @@ 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolution {
|
||||
/// Get the maximum reading value for this resolution.
|
||||
///
|
||||
/// This is `2**n - 1`.
|
||||
pub fn to_max_count(&self) -> u32 {
|
||||
match self {
|
||||
#[cfg(adc_v4)]
|
||||
@ -56,7 +65,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)
|
||||
)
|
||||
);
|
||||
|
@ -32,6 +32,7 @@ const TEMP_CHANNEL: u8 = 18;
|
||||
const VBAT_CHANNEL: u8 = 17;
|
||||
|
||||
// NOTE: Vrefint/Temperature/Vbat are not available on all ADCs, this currently cannot be modeled with stm32-data, so these are available from the software on all ADCs
|
||||
/// Internal voltage reference channel.
|
||||
pub struct VrefInt;
|
||||
impl<T: Instance> InternalChannel<T> for VrefInt {}
|
||||
impl<T: Instance> super::sealed::InternalChannel<T> for VrefInt {
|
||||
@ -40,6 +41,7 @@ impl<T: Instance> super::sealed::InternalChannel<T> for VrefInt {
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal temperature channel.
|
||||
pub struct Temperature;
|
||||
impl<T: Instance> InternalChannel<T> for Temperature {}
|
||||
impl<T: Instance> super::sealed::InternalChannel<T> for Temperature {
|
||||
@ -48,6 +50,7 @@ impl<T: Instance> super::sealed::InternalChannel<T> for Temperature {
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal battery voltage channel.
|
||||
pub struct Vbat;
|
||||
impl<T: Instance> InternalChannel<T> for Vbat {}
|
||||
impl<T: Instance> super::sealed::InternalChannel<T> for Vbat {
|
||||
@ -125,6 +128,7 @@ impl Prescaler {
|
||||
}
|
||||
|
||||
impl<'d, T: Instance> Adc<'d, T> {
|
||||
/// Create a new ADC driver.
|
||||
pub fn new(adc: impl Peripheral<P = T> + 'd, delay: &mut impl DelayUs<u16>) -> Self {
|
||||
embassy_hal_internal::into_ref!(adc);
|
||||
T::enable_and_reset();
|
||||
@ -212,6 +216,7 @@ impl<'d, T: Instance> Adc<'d, T> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Enable reading the voltage reference internal channel.
|
||||
pub fn enable_vrefint(&self) -> VrefInt {
|
||||
T::common_regs().ccr().modify(|reg| {
|
||||
reg.set_vrefen(true);
|
||||
@ -220,6 +225,7 @@ impl<'d, T: Instance> Adc<'d, T> {
|
||||
VrefInt {}
|
||||
}
|
||||
|
||||
/// Enable reading the temperature internal channel.
|
||||
pub fn enable_temperature(&self) -> Temperature {
|
||||
T::common_regs().ccr().modify(|reg| {
|
||||
reg.set_vsenseen(true);
|
||||
@ -228,6 +234,7 @@ impl<'d, T: Instance> Adc<'d, T> {
|
||||
Temperature {}
|
||||
}
|
||||
|
||||
/// Enable reading the vbat internal channel.
|
||||
pub fn enable_vbat(&self) -> Vbat {
|
||||
T::common_regs().ccr().modify(|reg| {
|
||||
reg.set_vbaten(true);
|
||||
@ -236,10 +243,12 @@ impl<'d, T: Instance> Adc<'d, T> {
|
||||
Vbat {}
|
||||
}
|
||||
|
||||
/// Set the ADC sample time.
|
||||
pub fn set_sample_time(&mut self, sample_time: SampleTime) {
|
||||
self.sample_time = sample_time;
|
||||
}
|
||||
|
||||
/// Set the ADC resolution.
|
||||
pub fn set_resolution(&mut self, resolution: Resolution) {
|
||||
T::regs().cfgr().modify(|reg| reg.set_res(resolution.into()));
|
||||
}
|
||||
@ -263,6 +272,7 @@ impl<'d, T: Instance> Adc<'d, T> {
|
||||
T::regs().dr().read().0 as u16
|
||||
}
|
||||
|
||||
/// Read an ADC pin.
|
||||
pub fn read<P>(&mut self, pin: &mut P) -> u16
|
||||
where
|
||||
P: AdcPin<T>,
|
||||
@ -273,6 +283,7 @@ impl<'d, T: Instance> Adc<'d, T> {
|
||||
self.read_channel(pin.channel())
|
||||
}
|
||||
|
||||
/// Read an ADC internal channel.
|
||||
pub fn read_internal(&mut self, channel: &mut impl InternalChannel<T>) -> u16 {
|
||||
self.read_channel(channel.channel())
|
||||
}
|
||||
|
@ -1,6 +1,3 @@
|
||||
pub use bxcan;
|
||||
use embassy_hal_internal::PeripheralRef;
|
||||
|
||||
use crate::peripherals;
|
||||
|
||||
pub(crate) mod sealed {
|
||||
@ -25,27 +22,19 @@ pub(crate) mod sealed {
|
||||
}
|
||||
|
||||
pub trait Instance {
|
||||
const REGISTERS: *mut bxcan::RegisterBlock;
|
||||
|
||||
fn regs() -> &'static crate::pac::can::Fdcan;
|
||||
fn state() -> &'static State;
|
||||
}
|
||||
}
|
||||
|
||||
/// Interruptable FDCAN instance.
|
||||
pub trait InterruptableInstance {}
|
||||
/// FDCAN instance.
|
||||
pub trait Instance: sealed::Instance + InterruptableInstance + 'static {}
|
||||
|
||||
pub struct BxcanInstance<'a, T>(PeripheralRef<'a, T>);
|
||||
|
||||
unsafe impl<'d, T: Instance> bxcan::Instance for BxcanInstance<'d, T> {
|
||||
const REGISTERS: *mut bxcan::RegisterBlock = T::REGISTERS;
|
||||
}
|
||||
|
||||
foreach_peripheral!(
|
||||
(can, $inst:ident) => {
|
||||
impl sealed::Instance for peripherals::$inst {
|
||||
const REGISTERS: *mut bxcan::RegisterBlock = crate::pac::$inst.as_ptr() as *mut _;
|
||||
|
||||
fn regs() -> &'static crate::pac::can::Fdcan {
|
||||
&crate::pac::$inst
|
||||
}
|
||||
|
@ -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::*;
|
||||
|
@ -6,15 +6,19 @@ use crate::peripherals::CRC;
|
||||
use crate::rcc::sealed::RccPeripheral;
|
||||
use crate::Peripheral;
|
||||
|
||||
/// CRC driver.
|
||||
pub struct Crc<'d> {
|
||||
_peripheral: PeripheralRef<'d, CRC>,
|
||||
_config: Config,
|
||||
}
|
||||
|
||||
/// CRC configuration errlr
|
||||
pub enum ConfigError {
|
||||
/// The selected polynomial is invalid.
|
||||
InvalidPolynomial,
|
||||
}
|
||||
|
||||
/// CRC configuration
|
||||
pub struct Config {
|
||||
reverse_in: InputReverseConfig,
|
||||
reverse_out: bool,
|
||||
@ -25,14 +29,20 @@ pub struct Config {
|
||||
crc_poly: u32,
|
||||
}
|
||||
|
||||
/// Input reverse configuration.
|
||||
pub enum InputReverseConfig {
|
||||
/// Don't reverse anything
|
||||
None,
|
||||
/// Reverse bytes
|
||||
Byte,
|
||||
/// Reverse 16-bit halfwords.
|
||||
Halfword,
|
||||
/// Reverse 32-bit words.
|
||||
Word,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Create a new CRC config.
|
||||
pub fn new(
|
||||
reverse_in: InputReverseConfig,
|
||||
reverse_out: bool,
|
||||
@ -57,7 +67,9 @@ impl Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// Polynomial size
|
||||
#[cfg(crc_v3)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum PolySize {
|
||||
Width7,
|
||||
Width8,
|
||||
@ -81,6 +93,7 @@ impl<'d> Crc<'d> {
|
||||
instance
|
||||
}
|
||||
|
||||
/// Reset the CRC engine.
|
||||
pub fn reset(&mut self) {
|
||||
PAC_CRC.cr().modify(|w| w.set_reset(true));
|
||||
}
|
||||
|
@ -62,11 +62,11 @@ impl Mode {
|
||||
///
|
||||
/// 12-bit values outside the permitted range are silently truncated.
|
||||
pub enum Value {
|
||||
// 8 bit value
|
||||
/// 8 bit value
|
||||
Bit8(u8),
|
||||
// 12 bit value stored in a u16, left-aligned
|
||||
/// 12 bit value stored in a u16, left-aligned
|
||||
Bit12Left(u16),
|
||||
// 12 bit value stored in a u16, right-aligned
|
||||
/// 12 bit value stored in a u16, right-aligned
|
||||
Bit12Right(u16),
|
||||
}
|
||||
|
||||
@ -76,11 +76,11 @@ pub enum Value {
|
||||
///
|
||||
/// 12-bit values outside the permitted range are silently truncated.
|
||||
pub enum DualValue {
|
||||
// 8 bit value
|
||||
/// 8 bit value
|
||||
Bit8(u8, u8),
|
||||
// 12 bit value stored in a u16, left-aligned
|
||||
/// 12 bit value stored in a u16, left-aligned
|
||||
Bit12Left(u16, u16),
|
||||
// 12 bit value stored in a u16, right-aligned
|
||||
/// 12 bit value stored in a u16, right-aligned
|
||||
Bit12Right(u16, u16),
|
||||
}
|
||||
|
||||
@ -88,11 +88,11 @@ pub enum DualValue {
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
/// Array variant of [`Value`].
|
||||
pub enum ValueArray<'a> {
|
||||
// 8 bit values
|
||||
/// 8 bit values
|
||||
Bit8(&'a [u8]),
|
||||
// 12 bit value stored in a u16, left-aligned
|
||||
/// 12 bit value stored in a u16, left-aligned
|
||||
Bit12Left(&'a [u16]),
|
||||
// 12 bit values stored in a u16, right-aligned
|
||||
/// 12 bit values stored in a u16, right-aligned
|
||||
Bit12Right(&'a [u16]),
|
||||
}
|
||||
|
||||
@ -106,7 +106,9 @@ pub struct DacChannel<'d, T: Instance, const N: u8, DMA = NoDma> {
|
||||
dma: PeripheralRef<'d, DMA>,
|
||||
}
|
||||
|
||||
/// DAC channel 1 type alias.
|
||||
pub type DacCh1<'d, T, DMA = NoDma> = DacChannel<'d, T, 1, DMA>;
|
||||
/// DAC channel 2 type alias.
|
||||
pub type DacCh2<'d, T, DMA = NoDma> = DacChannel<'d, T, 2, DMA>;
|
||||
|
||||
impl<'d, T: Instance, const N: u8, DMA> DacChannel<'d, T, N, DMA> {
|
||||
@ -492,6 +494,7 @@ pub(crate) mod sealed {
|
||||
}
|
||||
}
|
||||
|
||||
/// DAC instance.
|
||||
pub trait Instance: sealed::Instance + RccPeripheral + 'static {}
|
||||
dma_trait!(DacDma1, Instance);
|
||||
dma_trait!(DacDma2, Instance);
|
||||
|
@ -1,3 +1,5 @@
|
||||
#![allow(missing_docs)]
|
||||
|
||||
/// Trigger selection for STM32F0.
|
||||
#[cfg(stm32f0)]
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||
|
@ -36,6 +36,7 @@ impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandl
|
||||
}
|
||||
|
||||
/// The level on the VSync pin when the data is not valid on the parallel interface.
|
||||
#[allow(missing_docs)]
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub enum VSyncDataInvalidLevel {
|
||||
Low,
|
||||
@ -43,6 +44,7 @@ pub enum VSyncDataInvalidLevel {
|
||||
}
|
||||
|
||||
/// The level on the VSync pin when the data is not valid on the parallel interface.
|
||||
#[allow(missing_docs)]
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub enum HSyncDataInvalidLevel {
|
||||
Low,
|
||||
@ -50,14 +52,16 @@ pub enum HSyncDataInvalidLevel {
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum PixelClockPolarity {
|
||||
RisingEdge,
|
||||
FallingEdge,
|
||||
}
|
||||
|
||||
pub struct State {
|
||||
struct State {
|
||||
waker: AtomicWaker,
|
||||
}
|
||||
|
||||
impl State {
|
||||
const fn new() -> State {
|
||||
State {
|
||||
@ -68,18 +72,25 @@ impl State {
|
||||
|
||||
static STATE: State = State::new();
|
||||
|
||||
/// DCMI error.
|
||||
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
/// Overrun error: the hardware generated data faster than we could read it.
|
||||
Overrun,
|
||||
/// Internal peripheral error.
|
||||
PeripheralError,
|
||||
}
|
||||
|
||||
/// DCMI configuration.
|
||||
#[non_exhaustive]
|
||||
pub struct Config {
|
||||
/// VSYNC level.
|
||||
pub vsync_level: VSyncDataInvalidLevel,
|
||||
/// HSYNC level.
|
||||
pub hsync_level: HSyncDataInvalidLevel,
|
||||
/// PIXCLK polarity.
|
||||
pub pixclk_polarity: PixelClockPolarity,
|
||||
}
|
||||
|
||||
@ -105,6 +116,7 @@ macro_rules! config_pins {
|
||||
};
|
||||
}
|
||||
|
||||
/// DCMI driver.
|
||||
pub struct Dcmi<'d, T: Instance, Dma: FrameDma<T>> {
|
||||
inner: PeripheralRef<'d, T>,
|
||||
dma: PeripheralRef<'d, Dma>,
|
||||
@ -115,6 +127,7 @@ where
|
||||
T: Instance,
|
||||
Dma: FrameDma<T>,
|
||||
{
|
||||
/// Create a new DCMI driver with 8 data bits.
|
||||
pub fn new_8bit(
|
||||
peri: impl Peripheral<P = T> + 'd,
|
||||
dma: impl Peripheral<P = Dma> + 'd,
|
||||
@ -139,6 +152,7 @@ where
|
||||
Self::new_inner(peri, dma, config, false, 0b00)
|
||||
}
|
||||
|
||||
/// Create a new DCMI driver with 10 data bits.
|
||||
pub fn new_10bit(
|
||||
peri: impl Peripheral<P = T> + 'd,
|
||||
dma: impl Peripheral<P = Dma> + 'd,
|
||||
@ -165,6 +179,7 @@ where
|
||||
Self::new_inner(peri, dma, config, false, 0b01)
|
||||
}
|
||||
|
||||
/// Create a new DCMI driver with 12 data bits.
|
||||
pub fn new_12bit(
|
||||
peri: impl Peripheral<P = T> + 'd,
|
||||
dma: impl Peripheral<P = Dma> + 'd,
|
||||
@ -193,6 +208,7 @@ where
|
||||
Self::new_inner(peri, dma, config, false, 0b10)
|
||||
}
|
||||
|
||||
/// Create a new DCMI driver with 14 data bits.
|
||||
pub fn new_14bit(
|
||||
peri: impl Peripheral<P = T> + 'd,
|
||||
dma: impl Peripheral<P = Dma> + 'd,
|
||||
@ -223,6 +239,7 @@ where
|
||||
Self::new_inner(peri, dma, config, false, 0b11)
|
||||
}
|
||||
|
||||
/// Create a new DCMI driver with 8 data bits, with embedded synchronization.
|
||||
pub fn new_es_8bit(
|
||||
peri: impl Peripheral<P = T> + 'd,
|
||||
dma: impl Peripheral<P = Dma> + 'd,
|
||||
@ -245,6 +262,7 @@ where
|
||||
Self::new_inner(peri, dma, config, true, 0b00)
|
||||
}
|
||||
|
||||
/// Create a new DCMI driver with 10 data bits, with embedded synchronization.
|
||||
pub fn new_es_10bit(
|
||||
peri: impl Peripheral<P = T> + 'd,
|
||||
dma: impl Peripheral<P = Dma> + 'd,
|
||||
@ -269,6 +287,7 @@ where
|
||||
Self::new_inner(peri, dma, config, true, 0b01)
|
||||
}
|
||||
|
||||
/// Create a new DCMI driver with 12 data bits, with embedded synchronization.
|
||||
pub fn new_es_12bit(
|
||||
peri: impl Peripheral<P = T> + 'd,
|
||||
dma: impl Peripheral<P = Dma> + 'd,
|
||||
@ -295,6 +314,7 @@ where
|
||||
Self::new_inner(peri, dma, config, true, 0b10)
|
||||
}
|
||||
|
||||
/// Create a new DCMI driver with 14 data bits, with embedded synchronization.
|
||||
pub fn new_es_14bit(
|
||||
peri: impl Peripheral<P = T> + 'd,
|
||||
dma: impl Peripheral<P = Dma> + 'd,
|
||||
@ -538,7 +558,9 @@ mod sealed {
|
||||
}
|
||||
}
|
||||
|
||||
/// DCMI instance.
|
||||
pub trait Instance: sealed::Instance + 'static {
|
||||
/// Interrupt for this instance.
|
||||
type Interrupt: interrupt::typelevel::Interrupt;
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
#![macro_use]
|
||||
//! Basic Direct Memory Acccess (BDMA)
|
||||
|
||||
use core::future::Future;
|
||||
use core::pin::Pin;
|
||||
@ -17,6 +17,7 @@ use crate::interrupt::Priority;
|
||||
use crate::pac;
|
||||
use crate::pac::bdma::{regs, vals};
|
||||
|
||||
/// BDMA transfer options.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[non_exhaustive]
|
||||
@ -140,13 +141,17 @@ pub(crate) unsafe fn on_irq_inner(dma: pac::bdma::Dma, channel_num: usize, index
|
||||
STATE.ch_wakers[index].wake();
|
||||
}
|
||||
|
||||
/// DMA request type alias.
|
||||
#[cfg(any(bdma_v2, dmamux))]
|
||||
pub type Request = u8;
|
||||
/// DMA request type alias.
|
||||
#[cfg(not(any(bdma_v2, dmamux)))]
|
||||
pub type Request = ();
|
||||
|
||||
/// DMA channel.
|
||||
#[cfg(dmamux)]
|
||||
pub trait Channel: sealed::Channel + Peripheral<P = Self> + 'static + super::dmamux::MuxChannel {}
|
||||
/// DMA channel.
|
||||
#[cfg(not(dmamux))]
|
||||
pub trait Channel: sealed::Channel + Peripheral<P = Self> + 'static {}
|
||||
|
||||
@ -161,12 +166,14 @@ pub(crate) mod sealed {
|
||||
}
|
||||
}
|
||||
|
||||
/// DMA transfer.
|
||||
#[must_use = "futures do nothing unless you `.await` or poll them"]
|
||||
pub struct Transfer<'a, C: Channel> {
|
||||
channel: PeripheralRef<'a, C>,
|
||||
}
|
||||
|
||||
impl<'a, C: Channel> Transfer<'a, C> {
|
||||
/// Create a new read DMA transfer (peripheral to memory).
|
||||
pub unsafe fn new_read<W: Word>(
|
||||
channel: impl Peripheral<P = C> + 'a,
|
||||
request: Request,
|
||||
@ -177,6 +184,7 @@ impl<'a, C: Channel> Transfer<'a, C> {
|
||||
Self::new_read_raw(channel, request, peri_addr, buf, options)
|
||||
}
|
||||
|
||||
/// Create a new read DMA transfer (peripheral to memory), using raw pointers.
|
||||
pub unsafe fn new_read_raw<W: Word>(
|
||||
channel: impl Peripheral<P = C> + 'a,
|
||||
request: Request,
|
||||
@ -202,6 +210,7 @@ impl<'a, C: Channel> Transfer<'a, C> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Create a new write DMA transfer (memory to peripheral).
|
||||
pub unsafe fn new_write<W: Word>(
|
||||
channel: impl Peripheral<P = C> + 'a,
|
||||
request: Request,
|
||||
@ -212,6 +221,7 @@ impl<'a, C: Channel> Transfer<'a, C> {
|
||||
Self::new_write_raw(channel, request, buf, peri_addr, options)
|
||||
}
|
||||
|
||||
/// Create a new write DMA transfer (memory to peripheral), using raw pointers.
|
||||
pub unsafe fn new_write_raw<W: Word>(
|
||||
channel: impl Peripheral<P = C> + 'a,
|
||||
request: Request,
|
||||
@ -237,6 +247,7 @@ impl<'a, C: Channel> Transfer<'a, C> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Create a new write DMA transfer (memory to peripheral), writing the same value repeatedly.
|
||||
pub unsafe fn new_write_repeated<W: Word>(
|
||||
channel: impl Peripheral<P = C> + 'a,
|
||||
request: Request,
|
||||
@ -321,6 +332,9 @@ impl<'a, C: Channel> Transfer<'a, C> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Request the transfer to stop.
|
||||
///
|
||||
/// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false.
|
||||
pub fn request_stop(&mut self) {
|
||||
let ch = self.channel.regs().ch(self.channel.num());
|
||||
|
||||
@ -331,6 +345,10 @@ impl<'a, C: Channel> Transfer<'a, C> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Return whether this transfer is still running.
|
||||
///
|
||||
/// If this returns `false`, it can be because either the transfer finished, or
|
||||
/// it was requested to stop early with [`request_stop`](Self::request_stop).
|
||||
pub fn is_running(&mut self) -> bool {
|
||||
let ch = self.channel.regs().ch(self.channel.num());
|
||||
let en = ch.cr().read().en();
|
||||
@ -339,13 +357,15 @@ impl<'a, C: Channel> Transfer<'a, C> {
|
||||
en && (circular || !tcif)
|
||||
}
|
||||
|
||||
/// Gets the total remaining transfers for the channel
|
||||
/// Note: this will be zero for transfers that completed without cancellation.
|
||||
/// Get the total remaining transfers for the channel.
|
||||
///
|
||||
/// This will be zero for transfers that completed instead of being canceled with [`request_stop`](Self::request_stop).
|
||||
pub fn get_remaining_transfers(&self) -> u16 {
|
||||
let ch = self.channel.regs().ch(self.channel.num());
|
||||
ch.ndtr().read().ndt()
|
||||
}
|
||||
|
||||
/// Blocking wait until the transfer finishes.
|
||||
pub fn blocking_wait(mut self) {
|
||||
while self.is_running() {}
|
||||
self.request_stop();
|
||||
@ -411,6 +431,7 @@ impl<'a, C: Channel> DmaCtrl for DmaCtrlImpl<'a, C> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Ringbuffer for reading data using DMA circular mode.
|
||||
pub struct ReadableRingBuffer<'a, C: Channel, W: Word> {
|
||||
cr: regs::Cr,
|
||||
channel: PeripheralRef<'a, C>,
|
||||
@ -418,7 +439,8 @@ pub struct ReadableRingBuffer<'a, C: Channel, W: Word> {
|
||||
}
|
||||
|
||||
impl<'a, C: Channel, W: Word> ReadableRingBuffer<'a, C, W> {
|
||||
pub unsafe fn new_read(
|
||||
/// Create a new ring buffer.
|
||||
pub unsafe fn new(
|
||||
channel: impl Peripheral<P = C> + 'a,
|
||||
_request: Request,
|
||||
peri_addr: *mut W,
|
||||
@ -473,11 +495,15 @@ impl<'a, C: Channel, W: Word> ReadableRingBuffer<'a, C, W> {
|
||||
this
|
||||
}
|
||||
|
||||
/// Start the ring buffer operation.
|
||||
///
|
||||
/// You must call this after creating it for it to work.
|
||||
pub fn start(&mut self) {
|
||||
let ch = self.channel.regs().ch(self.channel.num());
|
||||
ch.cr().write_value(self.cr)
|
||||
}
|
||||
|
||||
/// Clear all data in the ring buffer.
|
||||
pub fn clear(&mut self) {
|
||||
self.ringbuf.clear(&mut DmaCtrlImpl(self.channel.reborrow()));
|
||||
}
|
||||
@ -509,10 +535,11 @@ impl<'a, C: Channel, W: Word> ReadableRingBuffer<'a, C, W> {
|
||||
}
|
||||
|
||||
/// The capacity of the ringbuffer.
|
||||
pub const fn cap(&self) -> usize {
|
||||
pub const fn capacity(&self) -> usize {
|
||||
self.ringbuf.cap()
|
||||
}
|
||||
|
||||
/// Set a waker to be woken when at least one byte is received.
|
||||
pub fn set_waker(&mut self, waker: &Waker) {
|
||||
DmaCtrlImpl(self.channel.reborrow()).set_waker(waker);
|
||||
}
|
||||
@ -526,6 +553,9 @@ impl<'a, C: Channel, W: Word> ReadableRingBuffer<'a, C, W> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Request DMA to stop.
|
||||
///
|
||||
/// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false.
|
||||
pub fn request_stop(&mut self) {
|
||||
let ch = self.channel.regs().ch(self.channel.num());
|
||||
|
||||
@ -539,6 +569,10 @@ impl<'a, C: Channel, W: Word> ReadableRingBuffer<'a, C, W> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Return whether DMA is still running.
|
||||
///
|
||||
/// If this returns `false`, it can be because either the transfer finished, or
|
||||
/// it was requested to stop early with [`request_stop`](Self::request_stop).
|
||||
pub fn is_running(&mut self) -> bool {
|
||||
let ch = self.channel.regs().ch(self.channel.num());
|
||||
ch.cr().read().en()
|
||||
@ -555,6 +589,7 @@ impl<'a, C: Channel, W: Word> Drop for ReadableRingBuffer<'a, C, W> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Ringbuffer for writing data using DMA circular mode.
|
||||
pub struct WritableRingBuffer<'a, C: Channel, W: Word> {
|
||||
cr: regs::Cr,
|
||||
channel: PeripheralRef<'a, C>,
|
||||
@ -562,7 +597,8 @@ pub struct WritableRingBuffer<'a, C: Channel, W: Word> {
|
||||
}
|
||||
|
||||
impl<'a, C: Channel, W: Word> WritableRingBuffer<'a, C, W> {
|
||||
pub unsafe fn new_write(
|
||||
/// Create a new ring buffer.
|
||||
pub unsafe fn new(
|
||||
channel: impl Peripheral<P = C> + 'a,
|
||||
_request: Request,
|
||||
peri_addr: *mut W,
|
||||
@ -617,11 +653,15 @@ impl<'a, C: Channel, W: Word> WritableRingBuffer<'a, C, W> {
|
||||
this
|
||||
}
|
||||
|
||||
/// Start the ring buffer operation.
|
||||
///
|
||||
/// You must call this after creating it for it to work.
|
||||
pub fn start(&mut self) {
|
||||
let ch = self.channel.regs().ch(self.channel.num());
|
||||
ch.cr().write_value(self.cr)
|
||||
}
|
||||
|
||||
/// Clear all data in the ring buffer.
|
||||
pub fn clear(&mut self) {
|
||||
self.ringbuf.clear(&mut DmaCtrlImpl(self.channel.reborrow()));
|
||||
}
|
||||
@ -640,10 +680,11 @@ impl<'a, C: Channel, W: Word> WritableRingBuffer<'a, C, W> {
|
||||
}
|
||||
|
||||
/// The capacity of the ringbuffer.
|
||||
pub const fn cap(&self) -> usize {
|
||||
pub const fn capacity(&self) -> usize {
|
||||
self.ringbuf.cap()
|
||||
}
|
||||
|
||||
/// Set a waker to be woken when at least one byte is sent.
|
||||
pub fn set_waker(&mut self, waker: &Waker) {
|
||||
DmaCtrlImpl(self.channel.reborrow()).set_waker(waker);
|
||||
}
|
||||
@ -657,6 +698,9 @@ impl<'a, C: Channel, W: Word> WritableRingBuffer<'a, C, W> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Request DMA to stop.
|
||||
///
|
||||
/// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false.
|
||||
pub fn request_stop(&mut self) {
|
||||
let ch = self.channel.regs().ch(self.channel.num());
|
||||
|
||||
@ -670,6 +714,10 @@ impl<'a, C: Channel, W: Word> WritableRingBuffer<'a, C, W> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Return whether DMA is still running.
|
||||
///
|
||||
/// If this returns `false`, it can be because either the transfer finished, or
|
||||
/// it was requested to stop early with [`request_stop`](Self::request_stop).
|
||||
pub fn is_running(&mut self) -> bool {
|
||||
let ch = self.channel.regs().ch(self.channel.num());
|
||||
ch.cr().read().en()
|
||||
|
@ -16,6 +16,7 @@ use crate::interrupt::Priority;
|
||||
use crate::pac::dma::{regs, vals};
|
||||
use crate::{interrupt, pac};
|
||||
|
||||
/// DMA transfer options.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
#[non_exhaustive]
|
||||
@ -69,6 +70,7 @@ impl From<Dir> for vals::Dir {
|
||||
}
|
||||
}
|
||||
|
||||
/// DMA transfer burst setting.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum Burst {
|
||||
@ -93,6 +95,7 @@ impl From<Burst> for vals::Burst {
|
||||
}
|
||||
}
|
||||
|
||||
/// DMA flow control setting.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum FlowControl {
|
||||
@ -111,6 +114,7 @@ impl From<FlowControl> for vals::Pfctrl {
|
||||
}
|
||||
}
|
||||
|
||||
/// DMA FIFO threshold.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum FifoThreshold {
|
||||
@ -208,13 +212,17 @@ pub(crate) unsafe fn on_irq_inner(dma: pac::dma::Dma, channel_num: usize, index:
|
||||
STATE.ch_wakers[index].wake();
|
||||
}
|
||||
|
||||
/// DMA request type alias. (also known as DMA channel number in some chips)
|
||||
#[cfg(any(dma_v2, dmamux))]
|
||||
pub type Request = u8;
|
||||
/// DMA request type alias. (also known as DMA channel number in some chips)
|
||||
#[cfg(not(any(dma_v2, dmamux)))]
|
||||
pub type Request = ();
|
||||
|
||||
/// DMA channel.
|
||||
#[cfg(dmamux)]
|
||||
pub trait Channel: sealed::Channel + Peripheral<P = Self> + 'static + super::dmamux::MuxChannel {}
|
||||
/// DMA channel.
|
||||
#[cfg(not(dmamux))]
|
||||
pub trait Channel: sealed::Channel + Peripheral<P = Self> + 'static {}
|
||||
|
||||
@ -229,12 +237,14 @@ pub(crate) mod sealed {
|
||||
}
|
||||
}
|
||||
|
||||
/// DMA transfer.
|
||||
#[must_use = "futures do nothing unless you `.await` or poll them"]
|
||||
pub struct Transfer<'a, C: Channel> {
|
||||
channel: PeripheralRef<'a, C>,
|
||||
}
|
||||
|
||||
impl<'a, C: Channel> Transfer<'a, C> {
|
||||
/// Create a new read DMA transfer (peripheral to memory).
|
||||
pub unsafe fn new_read<W: Word>(
|
||||
channel: impl Peripheral<P = C> + 'a,
|
||||
request: Request,
|
||||
@ -245,6 +255,7 @@ impl<'a, C: Channel> Transfer<'a, C> {
|
||||
Self::new_read_raw(channel, request, peri_addr, buf, options)
|
||||
}
|
||||
|
||||
/// Create a new read DMA transfer (peripheral to memory), using raw pointers.
|
||||
pub unsafe fn new_read_raw<W: Word>(
|
||||
channel: impl Peripheral<P = C> + 'a,
|
||||
request: Request,
|
||||
@ -270,6 +281,7 @@ impl<'a, C: Channel> Transfer<'a, C> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Create a new write DMA transfer (memory to peripheral).
|
||||
pub unsafe fn new_write<W: Word>(
|
||||
channel: impl Peripheral<P = C> + 'a,
|
||||
request: Request,
|
||||
@ -280,6 +292,7 @@ impl<'a, C: Channel> Transfer<'a, C> {
|
||||
Self::new_write_raw(channel, request, buf, peri_addr, options)
|
||||
}
|
||||
|
||||
/// Create a new write DMA transfer (memory to peripheral), using raw pointers.
|
||||
pub unsafe fn new_write_raw<W: Word>(
|
||||
channel: impl Peripheral<P = C> + 'a,
|
||||
request: Request,
|
||||
@ -305,6 +318,7 @@ impl<'a, C: Channel> Transfer<'a, C> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Create a new write DMA transfer (memory to peripheral), writing the same value repeatedly.
|
||||
pub unsafe fn new_write_repeated<W: Word>(
|
||||
channel: impl Peripheral<P = C> + 'a,
|
||||
request: Request,
|
||||
@ -407,6 +421,9 @@ impl<'a, C: Channel> Transfer<'a, C> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Request the transfer to stop.
|
||||
///
|
||||
/// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false.
|
||||
pub fn request_stop(&mut self) {
|
||||
let ch = self.channel.regs().st(self.channel.num());
|
||||
|
||||
@ -417,6 +434,10 @@ impl<'a, C: Channel> Transfer<'a, C> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Return whether this transfer is still running.
|
||||
///
|
||||
/// If this returns `false`, it can be because either the transfer finished, or
|
||||
/// it was requested to stop early with [`request_stop`](Self::request_stop).
|
||||
pub fn is_running(&mut self) -> bool {
|
||||
let ch = self.channel.regs().st(self.channel.num());
|
||||
ch.cr().read().en()
|
||||
@ -429,6 +450,7 @@ impl<'a, C: Channel> Transfer<'a, C> {
|
||||
ch.ndtr().read().ndt()
|
||||
}
|
||||
|
||||
/// Blocking wait until the transfer finishes.
|
||||
pub fn blocking_wait(mut self) {
|
||||
while self.is_running() {}
|
||||
|
||||
@ -465,12 +487,14 @@ impl<'a, C: Channel> Future for Transfer<'a, C> {
|
||||
|
||||
// ==================================
|
||||
|
||||
/// Double-buffered DMA transfer.
|
||||
pub struct DoubleBuffered<'a, C: Channel, W: Word> {
|
||||
channel: PeripheralRef<'a, C>,
|
||||
_phantom: PhantomData<W>,
|
||||
}
|
||||
|
||||
impl<'a, C: Channel, W: Word> DoubleBuffered<'a, C, W> {
|
||||
/// Create a new read DMA transfer (peripheral to memory).
|
||||
pub unsafe fn new_read(
|
||||
channel: impl Peripheral<P = C> + 'a,
|
||||
_request: Request,
|
||||
@ -554,25 +578,36 @@ impl<'a, C: Channel, W: Word> DoubleBuffered<'a, C, W> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Set the first buffer address.
|
||||
///
|
||||
/// You may call this while DMA is transferring the other buffer.
|
||||
pub unsafe fn set_buffer0(&mut self, buffer: *mut W) {
|
||||
let ch = self.channel.regs().st(self.channel.num());
|
||||
ch.m0ar().write_value(buffer as _);
|
||||
}
|
||||
|
||||
/// Set the second buffer address.
|
||||
///
|
||||
/// You may call this while DMA is transferring the other buffer.
|
||||
pub unsafe fn set_buffer1(&mut self, buffer: *mut W) {
|
||||
let ch = self.channel.regs().st(self.channel.num());
|
||||
ch.m1ar().write_value(buffer as _);
|
||||
}
|
||||
|
||||
/// Returh whether buffer0 is accessible (i.e. whether DMA is transferring buffer1 now)
|
||||
pub fn is_buffer0_accessible(&mut self) -> bool {
|
||||
let ch = self.channel.regs().st(self.channel.num());
|
||||
ch.cr().read().ct() == vals::Ct::MEMORY1
|
||||
}
|
||||
|
||||
/// Set a waker to be woken when one of the buffers is being transferred.
|
||||
pub fn set_waker(&mut self, waker: &Waker) {
|
||||
STATE.ch_wakers[self.channel.index()].register(waker);
|
||||
}
|
||||
|
||||
/// Request the transfer to stop.
|
||||
///
|
||||
/// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false.
|
||||
pub fn request_stop(&mut self) {
|
||||
let ch = self.channel.regs().st(self.channel.num());
|
||||
|
||||
@ -583,6 +618,10 @@ impl<'a, C: Channel, W: Word> DoubleBuffered<'a, C, W> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Return whether this transfer is still running.
|
||||
///
|
||||
/// If this returns `false`, it can be because either the transfer finished, or
|
||||
/// it was requested to stop early with [`request_stop`](Self::request_stop).
|
||||
pub fn is_running(&mut self) -> bool {
|
||||
let ch = self.channel.regs().st(self.channel.num());
|
||||
ch.cr().read().en()
|
||||
@ -629,6 +668,7 @@ impl<'a, C: Channel> DmaCtrl for DmaCtrlImpl<'a, C> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Ringbuffer for receiving data using DMA circular mode.
|
||||
pub struct ReadableRingBuffer<'a, C: Channel, W: Word> {
|
||||
cr: regs::Cr,
|
||||
channel: PeripheralRef<'a, C>,
|
||||
@ -636,7 +676,8 @@ pub struct ReadableRingBuffer<'a, C: Channel, W: Word> {
|
||||
}
|
||||
|
||||
impl<'a, C: Channel, W: Word> ReadableRingBuffer<'a, C, W> {
|
||||
pub unsafe fn new_read(
|
||||
/// Create a new ring buffer.
|
||||
pub unsafe fn new(
|
||||
channel: impl Peripheral<P = C> + 'a,
|
||||
_request: Request,
|
||||
peri_addr: *mut W,
|
||||
@ -706,11 +747,15 @@ impl<'a, C: Channel, W: Word> ReadableRingBuffer<'a, C, W> {
|
||||
this
|
||||
}
|
||||
|
||||
/// Start the ring buffer operation.
|
||||
///
|
||||
/// You must call this after creating it for it to work.
|
||||
pub fn start(&mut self) {
|
||||
let ch = self.channel.regs().st(self.channel.num());
|
||||
ch.cr().write_value(self.cr);
|
||||
}
|
||||
|
||||
/// Clear all data in the ring buffer.
|
||||
pub fn clear(&mut self) {
|
||||
self.ringbuf.clear(&mut DmaCtrlImpl(self.channel.reborrow()));
|
||||
}
|
||||
@ -741,11 +786,12 @@ impl<'a, C: Channel, W: Word> ReadableRingBuffer<'a, C, W> {
|
||||
.await
|
||||
}
|
||||
|
||||
// The capacity of the ringbuffer
|
||||
pub const fn cap(&self) -> usize {
|
||||
/// The capacity of the ringbuffer
|
||||
pub const fn capacity(&self) -> usize {
|
||||
self.ringbuf.cap()
|
||||
}
|
||||
|
||||
/// Set a waker to be woken when at least one byte is received.
|
||||
pub fn set_waker(&mut self, waker: &Waker) {
|
||||
DmaCtrlImpl(self.channel.reborrow()).set_waker(waker);
|
||||
}
|
||||
@ -763,6 +809,9 @@ impl<'a, C: Channel, W: Word> ReadableRingBuffer<'a, C, W> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Request DMA to stop.
|
||||
///
|
||||
/// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false.
|
||||
pub fn request_stop(&mut self) {
|
||||
let ch = self.channel.regs().st(self.channel.num());
|
||||
|
||||
@ -774,6 +823,10 @@ impl<'a, C: Channel, W: Word> ReadableRingBuffer<'a, C, W> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Return whether DMA is still running.
|
||||
///
|
||||
/// If this returns `false`, it can be because either the transfer finished, or
|
||||
/// it was requested to stop early with [`request_stop`](Self::request_stop).
|
||||
pub fn is_running(&mut self) -> bool {
|
||||
let ch = self.channel.regs().st(self.channel.num());
|
||||
ch.cr().read().en()
|
||||
@ -790,6 +843,7 @@ impl<'a, C: Channel, W: Word> Drop for ReadableRingBuffer<'a, C, W> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Ringbuffer for writing data using DMA circular mode.
|
||||
pub struct WritableRingBuffer<'a, C: Channel, W: Word> {
|
||||
cr: regs::Cr,
|
||||
channel: PeripheralRef<'a, C>,
|
||||
@ -797,7 +851,8 @@ pub struct WritableRingBuffer<'a, C: Channel, W: Word> {
|
||||
}
|
||||
|
||||
impl<'a, C: Channel, W: Word> WritableRingBuffer<'a, C, W> {
|
||||
pub unsafe fn new_write(
|
||||
/// Create a new ring buffer.
|
||||
pub unsafe fn new(
|
||||
channel: impl Peripheral<P = C> + 'a,
|
||||
_request: Request,
|
||||
peri_addr: *mut W,
|
||||
@ -867,11 +922,15 @@ impl<'a, C: Channel, W: Word> WritableRingBuffer<'a, C, W> {
|
||||
this
|
||||
}
|
||||
|
||||
/// Start the ring buffer operation.
|
||||
///
|
||||
/// You must call this after creating it for it to work.
|
||||
pub fn start(&mut self) {
|
||||
let ch = self.channel.regs().st(self.channel.num());
|
||||
ch.cr().write_value(self.cr);
|
||||
}
|
||||
|
||||
/// Clear all data in the ring buffer.
|
||||
pub fn clear(&mut self) {
|
||||
self.ringbuf.clear(&mut DmaCtrlImpl(self.channel.reborrow()));
|
||||
}
|
||||
@ -889,11 +948,12 @@ impl<'a, C: Channel, W: Word> WritableRingBuffer<'a, C, W> {
|
||||
.await
|
||||
}
|
||||
|
||||
// The capacity of the ringbuffer
|
||||
pub const fn cap(&self) -> usize {
|
||||
/// The capacity of the ringbuffer
|
||||
pub const fn capacity(&self) -> usize {
|
||||
self.ringbuf.cap()
|
||||
}
|
||||
|
||||
/// Set a waker to be woken when at least one byte is received.
|
||||
pub fn set_waker(&mut self, waker: &Waker) {
|
||||
DmaCtrlImpl(self.channel.reborrow()).set_waker(waker);
|
||||
}
|
||||
@ -911,6 +971,9 @@ impl<'a, C: Channel, W: Word> WritableRingBuffer<'a, C, W> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Request DMA to stop.
|
||||
///
|
||||
/// This doesn't immediately stop the transfer, you have to wait until [`is_running`](Self::is_running) returns false.
|
||||
pub fn request_stop(&mut self) {
|
||||
let ch = self.channel.regs().st(self.channel.num());
|
||||
|
||||
@ -922,6 +985,10 @@ impl<'a, C: Channel, W: Word> WritableRingBuffer<'a, C, W> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Return whether DMA is still running.
|
||||
///
|
||||
/// If this returns `false`, it can be because either the transfer finished, or
|
||||
/// it was requested to stop early with [`request_stop`](Self::request_stop).
|
||||
pub fn is_running(&mut self) -> bool {
|
||||
let ch = self.channel.regs().st(self.channel.num());
|
||||
ch.cr().read().en()
|
||||
|
@ -22,11 +22,15 @@ pub(crate) mod dmamux_sealed {
|
||||
}
|
||||
}
|
||||
|
||||
/// DMAMUX1 instance.
|
||||
pub struct DMAMUX1;
|
||||
/// DMAMUX2 instance.
|
||||
#[cfg(stm32h7)]
|
||||
pub struct DMAMUX2;
|
||||
|
||||
/// DMAMUX channel trait.
|
||||
pub trait MuxChannel: dmamux_sealed::MuxChannel {
|
||||
/// DMAMUX instance this channel is on.
|
||||
type Mux;
|
||||
}
|
||||
|
||||
|
@ -39,6 +39,13 @@ enum Dir {
|
||||
PeripheralToMemory,
|
||||
}
|
||||
|
||||
/// "No DMA" placeholder.
|
||||
///
|
||||
/// You may pass this in place of a real DMA channel when creating a driver
|
||||
/// to indicate it should not use DMA.
|
||||
///
|
||||
/// This often causes async functionality to not be available on the instance,
|
||||
/// leaving only blocking functionality.
|
||||
pub struct NoDma;
|
||||
|
||||
impl_peripheral!(NoDma);
|
||||
|
@ -1,3 +1,6 @@
|
||||
//! DMA word sizes.
|
||||
|
||||
#[allow(missing_docs)]
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||
pub enum WordSize {
|
||||
@ -7,6 +10,7 @@ pub enum WordSize {
|
||||
}
|
||||
|
||||
impl WordSize {
|
||||
/// Amount of bytes of this word size.
|
||||
pub fn bytes(&self) -> usize {
|
||||
match self {
|
||||
Self::OneByte => 1,
|
||||
@ -20,8 +24,13 @@ mod sealed {
|
||||
pub trait Word {}
|
||||
}
|
||||
|
||||
/// DMA word trait.
|
||||
///
|
||||
/// This is implemented for u8, u16, u32, etc.
|
||||
pub trait Word: sealed::Word + Default + Copy + 'static {
|
||||
/// Word size
|
||||
fn size() -> WordSize;
|
||||
/// Amount of bits of this word size.
|
||||
fn bits() -> usize;
|
||||
}
|
||||
|
||||
@ -40,6 +49,7 @@ macro_rules! impl_word {
|
||||
($T:ident, $uX:ident, $bits:literal, $size:ident) => {
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone, Default)]
|
||||
#[doc = concat!(stringify!($T), " word size")]
|
||||
pub struct $T(pub $uX);
|
||||
impl_word!(_, $T, $bits, $size);
|
||||
};
|
||||
|
@ -102,6 +102,7 @@ unsafe impl PHY for GenericSMI {
|
||||
|
||||
/// Public functions for the PHY
|
||||
impl GenericSMI {
|
||||
/// Set the SMI polling interval.
|
||||
#[cfg(feature = "time")]
|
||||
pub fn set_poll_interval(&mut self, poll_interval: Duration) {
|
||||
self.poll_interval = poll_interval
|
||||
|
@ -22,6 +22,14 @@ const RX_BUFFER_SIZE: usize = 1536;
|
||||
#[derive(Copy, Clone)]
|
||||
pub(crate) struct Packet<const N: usize>([u8; N]);
|
||||
|
||||
/// Ethernet packet queue.
|
||||
///
|
||||
/// This struct owns the memory used for reading and writing packets.
|
||||
///
|
||||
/// `TX` is the number of packets in the transmit queue, `RX` in the receive
|
||||
/// queue. A bigger queue allows the hardware to receive more packets while the
|
||||
/// CPU is busy doing other things, which may increase performance (especially for RX)
|
||||
/// at the cost of more RAM usage.
|
||||
pub struct PacketQueue<const TX: usize, const RX: usize> {
|
||||
tx_desc: [TDes; TX],
|
||||
rx_desc: [RDes; RX],
|
||||
@ -30,6 +38,7 @@ pub struct PacketQueue<const TX: usize, const RX: usize> {
|
||||
}
|
||||
|
||||
impl<const TX: usize, const RX: usize> PacketQueue<TX, RX> {
|
||||
/// Create a new packet queue.
|
||||
pub const fn new() -> Self {
|
||||
const NEW_TDES: TDes = TDes::new();
|
||||
const NEW_RDES: RDes = RDes::new();
|
||||
@ -41,7 +50,18 @@ impl<const TX: usize, const RX: usize> PacketQueue<TX, RX> {
|
||||
}
|
||||
}
|
||||
|
||||
// Allow to initialize a Self without requiring it to go on the stack
|
||||
/// Initialize a packet queue in-place.
|
||||
///
|
||||
/// This can be helpful to avoid accidentally stack-allocating the packet queue in the stack. The
|
||||
/// Rust compiler can sometimes be a bit dumb when working with large owned values: if you call `new()`
|
||||
/// and then store the returned PacketQueue in its final place (like a `static`), the compiler might
|
||||
/// place it temporarily on the stack then move it. Since this struct is quite big, it may result
|
||||
/// in a stack overflow.
|
||||
///
|
||||
/// With this function, you can create an uninitialized `static` with type `MaybeUninit<PacketQueue<...>>`
|
||||
/// and initialize it in-place, guaranteeing no stack usage.
|
||||
///
|
||||
/// After calling this function, calling `assume_init` on the MaybeUninit is guaranteed safe.
|
||||
pub fn init(this: &mut MaybeUninit<Self>) {
|
||||
unsafe {
|
||||
this.as_mut_ptr().write_bytes(0u8, 1);
|
||||
@ -93,6 +113,7 @@ impl<'d, T: Instance, P: PHY> embassy_net_driver::Driver for Ethernet<'d, T, P>
|
||||
}
|
||||
}
|
||||
|
||||
/// `embassy-net` RX token.
|
||||
pub struct RxToken<'a, 'd> {
|
||||
rx: &'a mut RDesRing<'d>,
|
||||
}
|
||||
@ -110,6 +131,7 @@ impl<'a, 'd> embassy_net_driver::RxToken for RxToken<'a, 'd> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `embassy-net` TX token.
|
||||
pub struct TxToken<'a, 'd> {
|
||||
tx: &'a mut TDesRing<'d>,
|
||||
}
|
||||
@ -159,6 +181,7 @@ pub(crate) mod sealed {
|
||||
}
|
||||
}
|
||||
|
||||
/// Ethernet instance.
|
||||
pub trait Instance: sealed::Instance + Send + 'static {}
|
||||
|
||||
impl sealed::Instance for crate::peripherals::ETH {
|
||||
|
@ -34,6 +34,7 @@ impl interrupt::typelevel::Handler<interrupt::typelevel::ETH> for InterruptHandl
|
||||
}
|
||||
}
|
||||
|
||||
/// Ethernet driver.
|
||||
pub struct Ethernet<'d, T: Instance, P: PHY> {
|
||||
_peri: PeripheralRef<'d, T>,
|
||||
pub(crate) tx: TDesRing<'d>,
|
||||
@ -56,6 +57,7 @@ macro_rules! config_pins {
|
||||
}
|
||||
|
||||
impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> {
|
||||
/// Create a new Ethernet driver.
|
||||
pub fn new<const TX: usize, const RX: usize>(
|
||||
queue: &'d mut PacketQueue<TX, RX>,
|
||||
peri: impl Peripheral<P = T> + 'd,
|
||||
@ -237,6 +239,7 @@ impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Ethernet SMI driver.
|
||||
pub struct EthernetStationManagement<T: Instance> {
|
||||
peri: PhantomData<T>,
|
||||
clock_range: u8,
|
||||
|
@ -39,7 +39,7 @@ fn exticr_regs() -> pac::afio::Afio {
|
||||
pac::AFIO
|
||||
}
|
||||
|
||||
pub unsafe fn on_irq() {
|
||||
unsafe fn on_irq() {
|
||||
#[cfg(feature = "low-power")]
|
||||
crate::low_power::on_wakeup_irq();
|
||||
|
||||
@ -85,7 +85,13 @@ impl Iterator for BitIter {
|
||||
}
|
||||
}
|
||||
|
||||
/// EXTI input driver
|
||||
/// EXTI input driver.
|
||||
///
|
||||
/// This driver augments a GPIO `Input` with EXTI functionality. EXTI is not
|
||||
/// built into `Input` itself because it needs to take ownership of the corresponding
|
||||
/// EXTI channel, which is a limited resource.
|
||||
///
|
||||
/// Pins PA5, PB5, PC5... all use EXTI channel 5, so you can't use EXTI on, say, PA5 and PC5 at the same time.
|
||||
pub struct ExtiInput<'d, T: GpioPin> {
|
||||
pin: Input<'d, T>,
|
||||
}
|
||||
@ -93,23 +99,30 @@ pub struct ExtiInput<'d, T: GpioPin> {
|
||||
impl<'d, T: GpioPin> Unpin for ExtiInput<'d, T> {}
|
||||
|
||||
impl<'d, T: GpioPin> ExtiInput<'d, T> {
|
||||
/// Create an EXTI input.
|
||||
pub fn new(pin: Input<'d, T>, _ch: impl Peripheral<P = T::ExtiChannel> + 'd) -> Self {
|
||||
Self { pin }
|
||||
}
|
||||
|
||||
pub fn is_high(&self) -> bool {
|
||||
/// Get whether the pin is high.
|
||||
pub fn is_high(&mut self) -> bool {
|
||||
self.pin.is_high()
|
||||
}
|
||||
|
||||
pub fn is_low(&self) -> bool {
|
||||
/// Get whether the pin is low.
|
||||
pub fn is_low(&mut self) -> bool {
|
||||
self.pin.is_low()
|
||||
}
|
||||
|
||||
pub fn get_level(&self) -> Level {
|
||||
/// Get the pin level.
|
||||
pub fn get_level(&mut self) -> Level {
|
||||
self.pin.get_level()
|
||||
}
|
||||
|
||||
pub async fn wait_for_high<'a>(&'a mut self) {
|
||||
/// Asynchronously wait until the pin is high.
|
||||
///
|
||||
/// This returns immediately if the pin is already high.
|
||||
pub async fn wait_for_high(&mut self) {
|
||||
let fut = ExtiInputFuture::new(self.pin.pin.pin.pin(), self.pin.pin.pin.port(), true, false);
|
||||
if self.is_high() {
|
||||
return;
|
||||
@ -117,7 +130,10 @@ impl<'d, T: GpioPin> ExtiInput<'d, T> {
|
||||
fut.await
|
||||
}
|
||||
|
||||
pub async fn wait_for_low<'a>(&'a mut self) {
|
||||
/// Asynchronously wait until the pin is low.
|
||||
///
|
||||
/// This returns immediately if the pin is already low.
|
||||
pub async fn wait_for_low(&mut self) {
|
||||
let fut = ExtiInputFuture::new(self.pin.pin.pin.pin(), self.pin.pin.pin.port(), false, true);
|
||||
if self.is_low() {
|
||||
return;
|
||||
@ -125,15 +141,22 @@ impl<'d, T: GpioPin> ExtiInput<'d, T> {
|
||||
fut.await
|
||||
}
|
||||
|
||||
pub async fn wait_for_rising_edge<'a>(&'a mut self) {
|
||||
/// Asynchronously wait until the pin sees a rising edge.
|
||||
///
|
||||
/// If the pin is already high, it will wait for it to go low then back high.
|
||||
pub async fn wait_for_rising_edge(&mut self) {
|
||||
ExtiInputFuture::new(self.pin.pin.pin.pin(), self.pin.pin.pin.port(), true, false).await
|
||||
}
|
||||
|
||||
pub async fn wait_for_falling_edge<'a>(&'a mut self) {
|
||||
/// Asynchronously wait until the pin sees a falling edge.
|
||||
///
|
||||
/// If the pin is already low, it will wait for it to go high then back low.
|
||||
pub async fn wait_for_falling_edge(&mut self) {
|
||||
ExtiInputFuture::new(self.pin.pin.pin.pin(), self.pin.pin.pin.port(), false, true).await
|
||||
}
|
||||
|
||||
pub async fn wait_for_any_edge<'a>(&'a mut self) {
|
||||
/// Asynchronously wait until the pin sees any edge (either rising or falling).
|
||||
pub async fn wait_for_any_edge(&mut self) {
|
||||
ExtiInputFuture::new(self.pin.pin.pin.pin(), self.pin.pin.pin.port(), true, true).await
|
||||
}
|
||||
}
|
||||
@ -142,11 +165,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 +178,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())
|
||||
}
|
||||
}
|
||||
@ -284,6 +307,7 @@ macro_rules! foreach_exti_irq {
|
||||
|
||||
macro_rules! impl_irq {
|
||||
($e:ident) => {
|
||||
#[allow(non_snake_case)]
|
||||
#[cfg(feature = "rt")]
|
||||
#[interrupt]
|
||||
unsafe fn $e() {
|
||||
@ -298,8 +322,16 @@ pub(crate) mod sealed {
|
||||
pub trait Channel {}
|
||||
}
|
||||
|
||||
/// EXTI channel trait.
|
||||
pub trait Channel: sealed::Channel + Sized {
|
||||
/// Get the EXTI channel number.
|
||||
fn number(&self) -> usize;
|
||||
|
||||
/// Type-erase (degrade) this channel into an `AnyChannel`.
|
||||
///
|
||||
/// This converts EXTI channel singletons (`EXTI0`, `EXTI1`, ...), which
|
||||
/// are all different types, into the same type. It is useful for
|
||||
/// creating arrays of channels, or avoiding generics.
|
||||
fn degrade(self) -> AnyChannel {
|
||||
AnyChannel {
|
||||
number: self.number() as u8,
|
||||
@ -307,9 +339,13 @@ pub trait Channel: sealed::Channel + Sized {
|
||||
}
|
||||
}
|
||||
|
||||
/// Type-erased (degraded) EXTI channel.
|
||||
///
|
||||
/// This represents ownership over any EXTI channel, known at runtime.
|
||||
pub struct AnyChannel {
|
||||
number: u8,
|
||||
}
|
||||
|
||||
impl_peripheral!(AnyChannel);
|
||||
impl sealed::Channel for AnyChannel {}
|
||||
impl Channel for AnyChannel {
|
||||
|
@ -59,7 +59,7 @@ impl embedded_storage_async::nor_flash::ReadNorFlash for Flash<'_, Async> {
|
||||
const READ_SIZE: usize = super::READ_SIZE;
|
||||
|
||||
async fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
|
||||
self.read(offset, bytes)
|
||||
self.blocking_read(offset, bytes)
|
||||
}
|
||||
|
||||
fn capacity(&self) -> usize {
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user