aboutsummaryrefslogtreecommitdiff
path: root/docs/pages
diff options
context:
space:
mode:
authorUlf Lilleengen <[email protected]>2024-05-18 10:17:03 +0200
committerUlf Lilleengen <[email protected]>2024-05-21 10:05:21 +0200
commit739e5861c2e47db251725163fcd91cd822cf97b7 (patch)
tree947dc7961ca7c42ec216056fc2adf616ab812b10 /docs/pages
parent51d553092550059afb22b2620cea14bbed21abff (diff)
convert from antora to asciidoctor
Diffstat (limited to 'docs/pages')
-rw-r--r--docs/pages/basic_application.adoc72
-rw-r--r--docs/pages/beginners.adoc11
-rw-r--r--docs/pages/best_practices.adoc55
-rw-r--r--docs/pages/bootloader.adoc96
-rw-r--r--docs/pages/developer.adoc1
-rw-r--r--docs/pages/developer_stm32.adoc79
-rw-r--r--docs/pages/embassy_in_the_wild.adoc22
-rw-r--r--docs/pages/examples.adoc11
-rw-r--r--docs/pages/faq.adoc335
-rw-r--r--docs/pages/getting_started.adoc143
-rw-r--r--docs/pages/hal.adoc14
-rw-r--r--docs/pages/layer_by_layer.adoc85
-rw-r--r--docs/pages/new_project.adoc190
-rw-r--r--docs/pages/nrf.adoc29
-rw-r--r--docs/pages/overview.adoc79
-rw-r--r--docs/pages/project_structure.adoc93
-rw-r--r--docs/pages/runtime.adoc46
-rw-r--r--docs/pages/sharing_peripherals.adoc128
-rw-r--r--docs/pages/stm32.adoc24
-rw-r--r--docs/pages/system.adoc13
-rw-r--r--docs/pages/time_keeping.adoc62
21 files changed, 1588 insertions, 0 deletions
diff --git a/docs/pages/basic_application.adoc b/docs/pages/basic_application.adoc
new file mode 100644
index 000000000..aa3ea2d1b
--- /dev/null
+++ b/docs/pages/basic_application.adoc
@@ -0,0 +1,72 @@
1= A basic Embassy application
2
3So you've got one of the xref:examples.adoc[examples] running, but what now? Let's go through a simple Embassy application for the nRF52 DK to understand it better.
4
5== Main
6
7The full example can be found link:https://github.com/embassy-rs/embassy/tree/master/docs/modules/ROOT/examples/basic[here].
8
9NOTE: 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.
10
11=== Bare metal
12
13The 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).
14
15[source,rust]
16----
17include::../examples/basic/src/main.rs[lines="1..2"]
18----
19
20=== Dealing with errors
21
22Then, what follows are some declarations on how to deal with panics and faults. During development, a good practice is to rely on `defmt-rtt` and `panic-probe` to print diagnostics to the terminal:
23
24[source,rust]
25----
26include::../examples/basic/src/main.rs[lines="8"]
27----
28
29=== Task declaration
30
31After a bit of import declaration, the tasks run by the application should be declared:
32
33[source,rust]
34----
35include::../examples/basic/src/main.rs[lines="10..18"]
36----
37
38An embassy task must be declared `async`, and may NOT take generic arguments. In this case, we are handed the LED that should be blinked and the interval of the blinking.
39
40NOTE: Notice that there is no busy waiting going on in this task. It is using the Embassy timer to yield execution, allowing the microcontroller to sleep in between the blinking.
41
42=== Main
43
44The 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.
45
46We 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:
47
48[source,rust]
49----
50include::../examples/basic/src/main.rs[lines="20..-1"]
51----
52
53What 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:
54
55. Creates an Embassy Executor
56. Defines a main task for the entry point
57. Runs the executor spawning the main task
58
59There is also a way to run the executor without using the macro, in which case you have to create the `Executor` instance yourself.
60
61== The Cargo.toml
62
63The project definition needs to contain the embassy dependencies:
64
65[source,toml]
66----
67include::../examples/basic/Cargo.toml[lines="9..11"]
68----
69
70Depending on your microcontroller, you may need to replace `embassy-nrf` with something else (`embassy-stm32` for STM32. Remember to update feature flags as well).
71
72In this particular case, the nrf52840 chip is selected, and the RTC1 peripheral is used as the time driver.
diff --git a/docs/pages/beginners.adoc b/docs/pages/beginners.adoc
new file mode 100644
index 000000000..48c9f4541
--- /dev/null
+++ b/docs/pages/beginners.adoc
@@ -0,0 +1,11 @@
1= For beginners
2
3The articles in this section are primarily aimed at users new to Embassy,
4showing how to get started, how to structure your project and other best practices.
5
6include::getting_started.adoc[leveloffset = 2]
7include::basic_application.adoc[leveloffset = 2]
8include::project_structure.adoc[leveloffset = 2]
9include::new_project.adoc[leveloffset = 2]
10include::best_practices.adoc[leveloffset = 2]
11include::layer_by_layer.adoc[leveloffset = 2]
diff --git a/docs/pages/best_practices.adoc b/docs/pages/best_practices.adoc
new file mode 100644
index 000000000..bfcedec06
--- /dev/null
+++ b/docs/pages/best_practices.adoc
@@ -0,0 +1,55 @@
1= Best Practices
2
3Over 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.
4
5== Passing Buffers by Reference
6It may be tempting to pass arrays or wrappers, like link:https://docs.rs/heapless/latest/heapless/[`heapless::Vec`],
7to a function or return one just like you would with a `std::Vec`. However, in most embedded applications you don't
8want to spend resources on an allocator and end up placing buffers on the stack. This, however, can easily blow up
9your stack if you are not careful.
10
11Consider the following example:
12[,rust]
13----
14fn process_buffer(mut buf: [u8; 1024]) -> [u8; 1024] {
15 // do stuff and return new buffer
16 for elem in buf.iter_mut() {
17 *elem = 0;
18 }
19 buf
20}
21
22pub fn main() -> () {
23 let buf = [1u8; 1024];
24 let buf_new = process_buffer(buf);
25 // do stuff with buf_new
26 ()
27}
28----
29When calling `process_buffer` in your program, a copy of the buffer you pass to the function will be created,
30consuming another 1024 bytes.
31After the processing, another 1024 byte buffer will be placed on the stack to be returned to the caller.
32(You can check the assembly, there will be two memcopy operations, e.g., `bl __aeabi_memcpy` when compiling for a Cortex-M processor.)
33
34*Possible Solution:*
35
36Pass the data by reference and not by value on both, the way in and the way out.
37For example, you could return a slice of the input buffer as the output.
38Requiring 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.
39
40[,rust]
41----
42fn process_buffer<'a>(buf: &'a mut [u8]) -> &'a mut[u8] {
43 for elem in buf.iter_mut() {
44 *elem = 0;
45 }
46 buf
47}
48
49pub fn main() -> () {
50 let mut buf = [1u8; 1024];
51 let buf_new = process_buffer(&mut buf);
52 // do stuff with buf_new
53 ()
54}
55----
diff --git a/docs/pages/bootloader.adoc b/docs/pages/bootloader.adoc
new file mode 100644
index 000000000..3b0cdb182
--- /dev/null
+++ b/docs/pages/bootloader.adoc
@@ -0,0 +1,96 @@
1= Bootloader
2
3`embassy-boot` a lightweight bootloader supporting firmware application upgrades in a power-fail-safe way, with trial boots and rollbacks.
4
5The bootloader can be used either as a library or be flashed directly if you are happy with the default configuration and capabilities.
6
7By 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.
8
9The bootloader supports both internal and external flash by relying on the `embedded-storage` traits. The bootloader optionally supports the verification of firmware that has been digitally signed (recommended).
10
11
12== Hardware support
13
14The bootloader supports
15
16* nRF52 with and without softdevice
17* STM32 L4, WB, WL, L1, L0, F3, F7 and H7
18* Raspberry Pi: RP2040
19
20In general, the bootloader works on any platform that implements the `embedded-storage` traits for its internal flash, but may require custom initialization code to work.
21
22== Design
23
24image::bootloader_flash.png[Bootloader flash layout]
25
26The bootloader divides the storage into 4 main partitions, configurable when creating the bootloader
27instance or via linker scripts:
28
29* 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.
30* ACTIVE - Where the main application is placed. The bootloader will attempt to load the application at the start of this partition. This partition is only written to by the bootloader. The size required for this partition depends on the size of your application.
31* 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, since the swap algorithm uses the extra space to ensure power safe copy of data:
32+
33Partition Size~dfu~= Partition Size~active~+ Page Size~active~
34+
35All values are specified in bytes.
36
37* BOOTLOADER STATE - Where the bootloader stores the current state describing if the active and dfu partitions need to be swapped. When the new firmware has been written to the DFU partition, a magic field is written to instruct the bootloader that the partitions should be swapped. This partition must be able to store a magic field as well as the partition swap progress. The partition size given by:
38+
39Partition Size~state~ = Write Size~state~ + (2 × Partition Size~active~ / Page Size~active~)
40+
41All values are specified in bytes.
42
43The partitions for ACTIVE (+BOOTLOADER), DFU and BOOTLOADER_STATE may be placed in separate flash. The page size used by the bootloader is determined by the lowest common multiple of the ACTIVE and DFU page sizes.
44The BOOTLOADER_STATE partition must be big enough to store one word per page in the ACTIVE and DFU partitions combined.
45
46The 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.
47
48NOTE: 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.
49
50=== FirmwareUpdater
51
52The `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.
53
54=== Verification
55
56The bootloader supports the verification of firmware that has been flashed to the DFU partition. Verification requires that firmware has been signed digitally using link:https://ed25519.cr.yp.to/[`ed25519`] signatures. With verification enabled, the `FirmwareUpdater::verify_and_mark_updated` method is called in place of `mark_updated`. A public key and signature are required, along with the actual length of the firmware that has been flashed. If verification fails then the firmware will not be marked as updated and therefore be rejected.
57
58Signatures are normally conveyed with the firmware to be updated and not written to flash. How signatures are provided is a firmware responsibility.
59
60To enable verification use either the `ed25519-dalek` or `ed25519-salty` features when depending on the `embassy-boot` crate. We recommend `ed25519-salty` at this time due to its small size.
61
62==== Tips on keys and signing with ed25519
63
64Ed25519 is a public key signature system where you are responsible for keeping the private key secure. We recommend embedding the *public* key in your program so that it can be easily passed to `verify_and_mark_updated`. An example declaration of the public key in your firmware:
65
66[source, rust]
67----
68static PUBLIC_SIGNING_KEY: &[u8] = include_bytes!("key.pub");
69----
70
71Signatures are often conveyed along with firmware by appending them.
72
73Ed25519 keys can be generated by a variety of tools. We recommend link:https://man.openbsd.org/signify[`signify`] as it is in wide use to sign and verify OpenBSD distributions, and is straightforward to use.
74
75The following set of Bash commands can be used to generate public and private keys on Unix platforms, and also generate a local `key.pub` file with the `signify` file headers removed. Declare a `SECRETS_DIR` environment variable in a secure location.
76
77[source, bash]
78----
79signify -G -n -p $SECRETS_DIR/key.pub -s $SECRETS_DIR/key.sec
80tail -n1 $SECRETS_DIR/key.pub | base64 -d -i - | dd ibs=10 skip=1 > key.pub
81chmod 700 $SECRETS_DIR/key.sec
82export SECRET_SIGNING_KEY=$(tail -n1 $SECRETS_DIR/key.sec)
83----
84
85Then, to sign your firmware given a declaration of `FIRMWARE_DIR` and a firmware filename of `myfirmware`:
86
87[source, bash]
88----
89shasum -a 512 -b $FIRMWARE_DIR/myfirmware > $SECRETS_DIR/message.txt
90cat $SECRETS_DIR/message.txt | dd ibs=128 count=1 | xxd -p -r > $SECRETS_DIR/message.txt
91signify -S -s $SECRETS_DIR/key.sec -m $SECRETS_DIR/message.txt -x $SECRETS_DIR/message.txt.sig
92cp $FIRMWARE_DIR/myfirmware $FIRMWARE_DIR/myfirmware+signed
93tail -n1 $SECRETS_DIR/message.txt.sig | base64 -d -i - | dd ibs=10 skip=1 >> $FIRMWARE_DIR/myfirmware+signed
94----
95
96Remember, guard the `$SECRETS_DIR/key.sec` key as compromising it means that another party can sign your firmware.
diff --git a/docs/pages/developer.adoc b/docs/pages/developer.adoc
new file mode 100644
index 000000000..e03ee51a8
--- /dev/null
+++ b/docs/pages/developer.adoc
@@ -0,0 +1 @@
= Developer Documentation \ No newline at end of file
diff --git a/docs/pages/developer_stm32.adoc b/docs/pages/developer_stm32.adoc
new file mode 100644
index 000000000..7c04ab1a4
--- /dev/null
+++ b/docs/pages/developer_stm32.adoc
@@ -0,0 +1,79 @@
1= Developer Documentation: STM32
2
3== Understanding metapac
4
5When a project that imports `embassy-stm32` is compiled, that project selects the feature corresponding to the chip that project is using. Based on that feature, `embassy-stm32` selects supported link:https://anysilicon.com/ip-intellectual-property-core-semiconductors/[IP] for the chip, and enables the corresponding HAL implementations. But how does `embassy-stm32` know what IP the chip contains, out of the hundreds of chips that we support? It's a long story that starts with `stm32-data-sources`.
6
7== `stm32-data-sources`
8
9link:https://github.com/embassy-rs/stm32-data-sources[`stm32-data-sources`] is as mostly barren repository. It has no README, no documentation, and few watchers. But it's the core of what makes `embassy-stm32` possible. The data for every chip that we support is taken in part from a corresponding XML file like link:https://github.com/embassy-rs/stm32-data-sources/blob/b8b85202e22a954d6c59d4a43d9795d34cff05cf/cubedb/mcu/STM32F051K4Ux.xml[`STM32F051K4Ux.xml`]. In that file, you'll see lines like the following:
10
11[source,xml]
12----
13 <IP InstanceName="I2C1" Name="I2C" Version="i2c2_v1_1_Cube"/>
14 <!-- snip -->
15 <IP ConfigFile="TIM-STM32F0xx" InstanceName="TIM1" Name="TIM1_8F0" Version="gptimer2_v2_x_Cube"/>
16----
17
18These lines indicate that this chip has an i2c, and that it's version is "v1_1". It also indicates that it has a general purpose timer that with a version of "v2_x". From this data, it's possible to determine which implementations should be included in `embassy-stm32`. But actually doing that is another matter.
19
20
21== `stm32-data`
22
23While all users of this project are familiar with `embassy-stm32`, fewer are familiar with the project that powers it: `stm32-data`. This project doesn't just aim to generate data for `embassy-stm32`, but for machine consumption in general. To acheive this, information from multiple files from the `stm32-data-sources` project are combined and parsed to assign register block implementations for each supported IP. The core of this matching resides in `chips.rs`:
24
25[source,rust]
26----
27 (".*:I2C:i2c2_v1_1", ("i2c", "v2", "I2C")),
28 // snip
29 (r".*TIM\d.*:gptimer.*", ("timer", "v1", "TIM_GP16")),
30----
31
32In this case, the i2c version corresponds to our "v2" and the general purpose timer version corresponds to our "v1". Therefore, the `i2c_v2.yaml` and `timer_v1.yaml` register block implementations are assigned to those IP, respectively. The result is that these lines arr generated in `STM32F051K4.json`:
33
34[source,json]
35----
36 {
37 "name": "I2C1",
38 "address": 1073763328,
39 "registers": {
40 "kind": "i2c",
41 "version": "v2",
42 "block": "I2C"
43 },
44 // snip
45 }
46 // snip
47 {
48 "name": "TIM1",
49 "address": 1073818624,
50 "registers": {
51 "kind": "timer",
52 "version": "v1",
53 "block": "TIM_ADV"
54 },
55 // snip
56 }
57----
58
59In addition to register blocks, data for pin and RCC mapping is also generated and consumed by `embassy-stm32`. `stm32-metapac-gen` is used to package and publish the data as a crate.
60
61
62== `embassy-stm32`
63
64In the `lib.rs` file located in the root of `embassy-stm32`, you'll see this line:
65
66[source,rust]
67----
68#[cfg(i2c)]
69pub mod i2c;
70----
71
72And in the `mod.rs` of the i2c mod, you'll see this:
73
74[source,rust]
75----
76#[cfg_attr(i2c_v2, path = "v2.rs")]
77----
78
79Because i2c is supported for STM32F051K4 and its version corresponds to our "v2", the `i2c` and `i2c_v2`, configuration directives will be present, and `embassy-stm32` will include these files, respectively. This and other configuration directives and tables are generated from the data for chip, allowing `embassy-stm32` to expressively and clearly adapt logic and implementations to what is required for each chip. Compared to other projects across the embedded ecosystem, `embassy-stm32` is the only project that can re-use code across the entire stm32 lineup and remove difficult-to-implement unsafe logic to the HAL. \ No newline at end of file
diff --git a/docs/pages/embassy_in_the_wild.adoc b/docs/pages/embassy_in_the_wild.adoc
new file mode 100644
index 000000000..a7d63f990
--- /dev/null
+++ b/docs/pages/embassy_in_the_wild.adoc
@@ -0,0 +1,22 @@
1= Embassy in the wild!
2
3Here 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]!
4
5* link:https://github.com/haobogu/rmk/[RMK: A feature-rich Rust keyboard firmware]
6** RMK has built-in layer support, wireless(BLE) support, real-time key editing support using vial, and more!
7** Targets STM32, RP2040, nRF52 and ESP32 MCUs
8* link:https://github.com/cbruiz/printhor/[Printhor: The highly reliable but not necessarily functional 3D printer firmware]
9** Targets some STM32 MCUs
10* link:https://github.com/card-io-ecg/card-io-fw[Card/IO firmware] - firmware for an open source ECG device
11** Targets the ESP32-S3 or ESP32-C6 MCU
12* 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
13** link:https://github.com/matoushybl/air-force-one[Air force one: A simple air quality monitoring system]
14*** Targets nRF52 and uses nrf-softdevice
15
16* link:https://github.com/schmettow/ylab-edge-go[YLab Edge Go] and link:https://github.com/schmettow/ylab-edge-pro[YLab Edge Pro] projects develop
17firmware (RP2040, STM32) for capturing physiological data in behavioural science research. Included so far are:
18** biopotentials (analog ports)
19** motion capture (6-axis accelerometers)
20** air quality (CO2, Temp, Humidity)
21** comes with an app for capturing and visualizing data [link:https://github.com/schmettow/ystudio-zero[Ystudio]]
22
diff --git a/docs/pages/examples.adoc b/docs/pages/examples.adoc
new file mode 100644
index 000000000..82381a2c5
--- /dev/null
+++ b/docs/pages/examples.adoc
@@ -0,0 +1,11 @@
1= Examples
2
3Embassy provides examples for all HALs supported. You can find them in the `examples/` folder.
4
5
6Main loop example
7
8[source,rust]
9----
10include::../examples/examples/std/src/bin/tick.rs[]
11----
diff --git a/docs/pages/faq.adoc b/docs/pages/faq.adoc
new file mode 100644
index 000000000..8b1f22f6e
--- /dev/null
+++ b/docs/pages/faq.adoc
@@ -0,0 +1,335 @@
1= Frequently Asked Questions
2
3These are a list of unsorted, commonly asked questions and answers.
4
5Please feel free to add items to link:https://github.com/embassy-rs/embassy/edit/main/docs/modules/ROOT/pages/faq.adoc[this page], especially if someone in the chat answered a question for you!
6
7== How to deploy to RP2040 without a debugging probe.
8
9Install link:https://github.com/JoNil/elf2uf2-rs[elf2uf2-rs] for converting the generated elf binary into a uf2 file.
10
11Configure the runner to use this tool, add this to `.cargo/config.toml`:
12[source,toml]
13----
14[target.'cfg(all(target_arch = "arm", target_os = "none"))']
15runner = "elf2uf2-rs --deploy --serial --verbose"
16----
17
18The command-line parameters `--deploy` will detect your device and upload the binary, `--serial` starts a serial connection. See the documentation for more info.
19
20== Missing main macro
21
22If you see an error like this:
23
24[source,rust]
25----
26#[embassy_executor::main]
27| ^^^^ could not find `main` in `embassy_executor`
28----
29
30You are likely missing some features of the `embassy-executor` crate.
31
32For Cortex-M targets, check whether ALL of the following features are enabled in your `Cargo.toml` for the `embassy-executor` crate:
33
34* `arch-cortex-m`
35* `executor-thread`
36
37For ESP32, consider using the executors and `#[main]` macro provided by your appropriate link:https://crates.io/crates/esp-hal-common[HAL crate].
38
39== Why is my binary so big?
40
41The first step to managing your binary size is to set up your link:https://doc.rust-lang.org/cargo/reference/profiles.html[profiles].
42
43[source,toml]
44----
45[profile.release]
46lto = true
47opt-level = "s"
48incremental = false
49codegen-units = 1
50# note: debug = true is okay - debuginfo isn't flashed to the device!
51debug = true
52----
53
54All of these flags are elaborated on in the Rust Book page linked above.
55
56=== My binary is still big... filled with `std::fmt` stuff!
57
58This means your code is sufficiently complex that `panic!` invocation's formatting requirements could not be optimized out, despite your usage of `panic-halt` or `panic-reset`.
59
60You can remedy this by adding the following to your `.cargo/config.toml`:
61
62[source,toml]
63----
64[unstable]
65build-std = ["core"]
66build-std-features = ["panic_immediate_abort"]
67----
68
69This replaces all panics with a `UDF` (undefined) instruction.
70
71Depending on your chipset, this will exhibit different behavior.
72
73Refer to the spec for your chipset, but for `thumbv6m`, it results in a hardfault. Which can be configured like so:
74
75[source,rust]
76----
77#[exception]
78unsafe fn HardFault(_frame: &ExceptionFrame) -> ! {
79 SCB::sys_reset() // <- you could do something other than reset
80}
81----
82
83Refer to cortex-m's link:https://docs.rs/cortex-m-rt/latest/cortex_m_rt/attr.exception.html[exception handling] for more info.
84
85== `embassy-time` throws linker errors
86
87If you see linker error like this:
88
89[source,text]
90----
91 = note: rust-lld: error: undefined symbol: _embassy_time_now
92 >>> referenced by driver.rs:127 (src/driver.rs:127)
93 >>> embassy_time-846f66f1620ad42c.embassy_time.4f6a638abb75dd4c-cgu.0.rcgu.o:(embassy_time::driver::now::hefb1f99d6e069842) in archive Devel/Embedded/pogodyna/target/thumbv7em-none-eabihf/debug/deps/libembassy_time-846f66f1620ad42c.rlib
94
95 rust-lld: error: undefined symbol: _embassy_time_allocate_alarm
96 >>> referenced by driver.rs:134 (src/driver.rs:134)
97 >>> embassy_time-846f66f1620ad42c.embassy_time.4f6a638abb75dd4c-cgu.0.rcgu.o:(embassy_time::driver::allocate_alarm::hf5145b6bd46706b2) in archive Devel/Embedded/pogodyna/target/thumbv7em-none-eabihf/debug/deps/libembassy_time-846f66f1620ad42c.rlib
98
99 rust-lld: error: undefined symbol: _embassy_time_set_alarm_callback
100 >>> referenced by driver.rs:139 (src/driver.rs:139)
101 >>> embassy_time-846f66f1620ad42c.embassy_time.4f6a638abb75dd4c-cgu.0.rcgu.o:(embassy_time::driver::set_alarm_callback::h24f92388d96eafd2) in archive Devel/Embedded/pogodyna/target/thumbv7em-none-eabihf/debug/deps/libembassy_time-846f66f1620ad42c.rlib
102
103 rust-lld: error: undefined symbol: _embassy_time_set_alarm
104 >>> referenced by driver.rs:144 (src/driver.rs:144)
105 >>> embassy_time-846f66f1620ad42c.embassy_time.4f6a638abb75dd4c-cgu.0.rcgu.o:(embassy_time::driver::set_alarm::h530a5b1f444a6d5b) in archive Devel/Embedded/pogodyna/target/thumbv7em-none-eabihf/debug/deps/libembassy_time-846f66f1620ad42c.rlib
106----
107
108You probably need to enable a time driver for your HAL (not in `embassy-time`!). For example with `embassy-stm32`, you might need to enable `time-driver-any`:
109
110[source,toml]
111----
112[dependencies.embassy-stm32]
113version = "0.1.0"
114features = [
115 # ...
116 "time-driver-any", # Add this line!
117 # ...
118]
119----
120
121If you are in the early project setup phase and not using anything from the HAL, make sure the HAL is explicitly used to prevent the linker removing it as dead code by adding this line to your source:
122
123[source,rust]
124----
125use embassy_stm32 as _;
126----
127
128== Error: `Only one package in the dependency graph may specify the same links value.`
129
130You have multiple versions of the same crate in your dependency tree. This means that some of your
131embassy crates are coming from crates.io, and some from git, each of them pulling in a different set
132of dependencies.
133
134To resolve this issue, make sure to only use a single source for all your embassy crates!
135To do this, you should patch your dependencies to use git sources using `[patch.crates.io]`
136and maybe `[patch.'https://github.com/embassy-rs/embassy.git']`.
137
138Example:
139
140[source,toml]
141----
142[patch.crates-io]
143embassy-time-queue-driver = { git = "https://github.com/embassy-rs/embassy.git", rev = "e5fdd35" }
144embassy-time-driver = { git = "https://github.com/embassy-rs/embassy.git", rev = "e5fdd35" }
145# embassy-time = { git = "https://github.com/embassy-rs/embassy.git", rev = "e5fdd35" }
146----
147
148Note that the git revision should match any other embassy patches or git dependencies that you are using!
149
150== How can I optimize the speed of my embassy-stm32 program?
151
152* Make sure RCC is set up to go as fast as possible
153* Make sure link:https://docs.rs/cortex-m/latest/cortex_m/peripheral/struct.SCB.html[flash cache] is enabled
154* build with `--release`
155* Set the following keys for the release profile in your `Cargo.toml`:
156 ** `opt-level = "s"`
157 ** `lto = "fat"`
158* Set the following keys in the `[unstable]` section of your `.cargo/config.toml`
159 ** `build-std = ["core"]`
160 ** `build-std-features = ["panic_immediate_abort"]`
161* Enable feature `embassy-time/generic-queue`, disable feature `embassy-executor/integrated-timers`
162* When using `InterruptExecutor`:
163 ** disable `executor-thread`
164 ** 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() }`
165 ** *Note:* If you need 2 priority levels, using 2 interrupt executors is better than 1 thread executor + 1 interrupt executor.
166
167== How do I set up the task arenas on stable?
168
169When you aren't using the `nightly` feature of `embassy-executor`, the executor uses a bump allocator, which may require configuration.
170
171Something like this error will occur at **compile time** if the task arena is *too large* for the target's RAM:
172
173[source,plain]
174----
175rust-lld: error: section '.bss' will not fit in region 'RAM': overflowed by _ bytes
176rust-lld: error: section '.uninit' will not fit in region 'RAM': overflowed by _ bytes
177----
178
179And this message will appear at **runtime** if the task arena is *too small* for the tasks running:
180
181[source,plain]
182----
183ERROR panicked at 'embassy-executor: task arena is full. You must increase the arena size, see the documentation for details: https://docs.embassy.dev/embassy-executor/'
184----
185
186NOTE: If all tasks are spawned at startup, this panic will occur immediately.
187
188Check out link:https://docs.embassy.dev/embassy-executor/git/cortex-m/index.html#task-arena[Task Arena Documentation] for more details.
189
190== Can I use manual ISRs alongside Embassy?
191
192Yes! This can be useful if you need to respond to an event as fast as possible, and the latency caused by the usual “ISR, wake, return from ISR, context switch to woken task” flow is too much for your application. Simply define a `#[interrupt] fn INTERRUPT_NAME() {}` handler as you would link:https://docs.rust-embedded.org/book/start/interrupts.html[in any other embedded rust project].
193
194== How can I measure resource usage (CPU, RAM, etc.)?
195
196=== For CPU Usage:
197
198There are a couple techniques that have been documented, generally you want to measure how long you are spending in the idle or low priority loop.
199
200We need to document specifically how to do this in embassy, but link:https://blog.japaric.io/cpu-monitor/[this older post] describes the general process.
201
202If you end up doing this, please update this section with more specific examples!
203
204=== For Static Memory Usage
205
206Tools like `cargo size` and `cargo nm` can tell you the size of any globals or other static usage. Specifically you will want to see the size of the `.data` and `.bss` sections, which together make up the total global/static memory usage.
207
208=== For Max Stack Usage
209
210Check out link:https://github.com/Dirbaio/cargo-call-stack/[`cargo-call-stack`] for statically calculating worst-case stack usage. There are some caveats and inaccuracies possible with this, but this is a good way to get the general idea. See link:https://github.com/dirbaio/cargo-call-stack#known-limitations[the README] for more details.
211
212== The memory definition for my STM chip seems wrong, how do I define a `memory.x` file?
213
214It could happen that your project compiles, flashes but fails to run. The following situation can be true for your setup:
215
216The `memory.x` is generated automatically when enabling the `memory-x` feature on the `embassy-stm32` crate in the `Cargo.toml` file.
217This, in turn, uses `stm32-metapac` to generate the `memory.x` file for you. Unfortunately, more often than not this memory definition is not correct.
218
219You can override this by adding your own `memory.x` file. Such a file could look like this:
220```
221MEMORY
222{
223 FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 1024K
224 RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 320K
225}
226
227_stack_start = ORIGIN(RAM) + LENGTH(RAM);
228```
229
230Please refer to the STM32 documentation for the specific values suitable for your board and setup. The STM32 Cube examples often contain a linker script `.ld` file.
231Look for the `MEMORY` section and try to determine the FLASH and RAM sizes and section start.
232
233If you find a case where the memory.x is wrong, please report it on [this Github issue](https://github.com/embassy-rs/stm32-data/issues/301) so other users are not caught by surprise.
234
235== The USB examples are not working on my board, is there anything else I need to configure?
236
237If you are trying out the USB examples and your device doesn not connect, the most common issues are listed below.
238
239=== Incorrect RCC config
240
241Check your board and crystal/oscillator, in particular make sure that `HSE` is set to the correct value, e.g. `8_000_000` Hertz if your board does indeed run on a 8 MHz oscillator.
242
243=== VBUS detection on STM32 platform
244
245The USB specification requires that all USB devices monitor the bus for detection of plugging/unplugging actions. The devices must pull-up the D+ or D- lane as soon as the host supplies VBUS.
246
247See the docs, for example at link:https://docs.embassy.dev/embassy-stm32/git/stm32f401vc/usb/struct.Config.html[`usb/struct.Config.html`] for information on how to enable/disable `vbus_detection`.
248
249When the device is powered only from the USB bus that simultaneously serves as the data connection, this is optional. (If there's no power in VBUS the device would be off anyway, so it's safe to always assume there's power in VBUS, i.e. the USB cable is always plugged in). If your device doesn't have the required connections in place to allow VBUS sensing (see below), then this option needs to be set to `false` to work.
250
251When the device is powered from another power source and therefore can stay powered through USB cable plug/unplug events, then this must be implemented and `vbus_detection` MUST be set to `true`.
252
253If your board is powered from the USB and you are unsure whether it supports `vbus_detection`, consult the schematics of your board to see if VBUS is connected to PA9 for USB Full Speed or PB13 for USB High Speed, vice versa, possibly with a voltage divider. When designing your own hardware, see ST application note AN4879 (in particular section 2.6) and the reference manual of your specific chip for more details.
254
255== Known issues (details and/or mitigations)
256
257These are issues that are commonly reported. Help wanted fixing them, or improving the UX when possible!
258
259=== STM32H5 and STM32H7 power issues
260
261STM32 chips with built-in power management (SMPS and LDO) settings often cause user problems when the configuration does not match how the board was designed.
262
263Settings from the examples, or even from other working boards, may not work on YOUR board, because they are wired differently.
264
265Additionally, some PWR settings require a full device reboot (and enough time to discharge any power capacitors!), making this hard to troubleshoot. Also, some
266"wrong" power settings will ALMOST work, meaning it will sometimes work on some boots, or for a while, but crash unexpectedly.
267
268There is not a fix for this yet, as it is board/hardware dependant. See link:https://github.com/embassy-rs/embassy/issues/2806[this tracking issue] for more details
269
270=== STM32 BDMA only work out of some RAM regions
271
272The STM32 BDMA controller included in some chips (TODO: list which ones) has a limitation in that it only works out of certain regions of RAM (TODO: list which ones), otherwise the transfer
273will fail.
274
275If you see errors that look like this:
276
277[source,plain]
278----
279DMA: error on BDMA@1234ABCD channel 4
280----
281
282You need to set up your linker script to define a special region for this area, and copy data to that region before using with BDMA.
283
284General steps:
285
2861. Find out which memory region BDMA has access to. You can get this information from the bus matrix and the memory mapping table in the STM32 datasheet.
2872. Add the memory region to `memory.x`, you can modify the generated one from https://github.com/embassy-rs/stm32-data-generated/tree/main/data/chips.
2883. You might need to modify `build.rs` to make cargo pick up the modified `memory.x`.
2894. In your code, access the defined memory region using `#[link_section = ".xxx"]`
2905. Copy data to that region before using BDMA.
291
292See link:/examples/stm32h7/src/bin/spi_bdma.rs[this example] for more details.
293
294== How do I switch to the `main` branch?
295
296Sometimes to test new changes or fixes, you'll want to switch your project to using a version from GitHub.
297
298You can add a section to your `Cargo.toml` file like this, you'll need to patch ALL embassy crates to the same revision:
299
300Using `patch` will replace all direct AND indirect dependencies.
301
302See the link:https://embassy.dev/book/dev/new_project.html#_cargo_toml[new project docs] for more details on this approach.
303
304[source,toml]
305----
306[patch.crates-io]
307# make sure to get the latest git rev from github, you can see the latest one here:
308# https://github.com/embassy-rs/embassy/commits/main/
309embassy-embedded-hal = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" }
310embassy-executor = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" }
311embassy-rp = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" }
312embassy-sync = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" }
313embassy-time = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" }
314embassy-usb = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" }
315embassy-usb-driver = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" }
316----
317
318== How do I add support for a new microcontroller to embassy?
319
320This is particularly for cortex-m, and potentially risc-v, where there is already support for basics like interrupt handling, or even already embassy-executor support for your architecture.
321
322This is a *much harder path* than just using Embassy on an already supported chip. If you are a beginner, consider using embassy on an existing, well supported chip for a while, before you decide to write drivers from scratch. It's also worth reading the existing source of supported Embassy HALs, to get a feel for how drivers are implemented for various chips. You should already be comfortable reading and writing unsafe code, and understanding the responsibilities of writing safe abstractions for users of your HAL.
323
324This is not the only possible approach, but if you are looking for where to start, this is a reasonable way to tackle the task:
325
3261. First, drop by the Matrix room or search around to see if someone has already started writing drivers, either in Embassy or otherwise in Rust. You might not have to start from scratch!
3272. Make sure the target is supported in probe-rs, it likely is, and if not, there is likely a cmsis-pack you can use to add support so that flashing and debugging is possible. You will definitely appreciate being able to debug with SWD or JTAG when writing drivers!
3283. See if there is an SVD (or SVDs, if it's a family) available, if it is, run it through chiptool to create a PAC for low level register access. If not, there are other ways (like scraping the PDF datasheets or existing C header files), but these are more work than starting from the SVD file to define peripheral memory locations necessary for writing drivers.
3294. Either make a fork of embassy repo, and add your target there, or make a repo that just contains the PAC and an empty HAL. It doesn't necessarily have to live in the embassy repo at first.
3305. Get a hello world binary working on your chip, either with minimal HAL or just PAC access, use delays and blink a light or send some raw data on some interface, make sure it works and you can flash, debug with defmt + RTT, write a proper linker script, etc.
3316. Get basic timer operations and timer interrupts working, upgrade your blinking application to use hardware timers and interrupts, and ensure they are accurate (with a logic analyzer or oscilloscope, if possible).
3327. Implement the embassy-time driver API with your timer and timer interrupt code, so that you can use embassy-time operations in your drivers and applications.
3338. Then start implementing whatever peripherals you need, like GPIOs, UART, SPI, I2C, etc. This is the largest part of the work, and will likely continue for a while! Don't feel like you need 100% coverage of all peripherals at first, this is likely to be an ongoing process over time.
3349. Start implementing the embedded-hal, embedded-io, and embedded-hal-async traits on top of your HAL drivers, once you start having more features completed. This will allow users to use standard external device drivers (e.g. sensors, actuators, displays, etc.) with your HAL.
33510. Discuss upstreaming the PAC/HAL for embassy support, or make sure your drivers are added to the awesome-embedded-rust list so that people can find it.
diff --git a/docs/pages/getting_started.adoc b/docs/pages/getting_started.adoc
new file mode 100644
index 000000000..73cb5530d
--- /dev/null
+++ b/docs/pages/getting_started.adoc
@@ -0,0 +1,143 @@
1= Getting started
2
3So you want to try Embassy, great! To get started, there are a few tools you need to install:
4
5* link:https://rustup.rs/[rustup] - the Rust toolchain is needed to compile Rust code.
6* link:https://probe.rs/[probe-rs] - to flash the firmware on your device. If you already have other tools like `OpenOCD` setup, you can use that as well.
7
8If you don't have any supported board, don't worry: you can also run embassy on your PC using the `std` examples.
9
10== Getting a board with examples
11
12Embassy supports many microcontroller families, but the quickest way to get started is by using a board which Embassy has existing example code for.
13
14This 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.
15
16=== nRF kits
17
18* link:https://www.nordicsemi.com/Products/Development-hardware/nrf52-dk[nRF52 DK]
19* link:https://www.nordicsemi.com/Products/Development-hardware/nRF9160-DK[nRF9160 DK]
20
21=== STM32 kits
22
23* link:https://www.st.com/en/evaluation-tools/nucleo-h743zi.html[STM32 Nucleo-144 development board with STM32H743ZI MCU]
24* link:https://www.st.com/en/evaluation-tools/nucleo-f429zi.html[STM32 Nucleo-144 development board with STM32F429ZI MCU]
25* link:https://www.st.com/en/evaluation-tools/b-l4s5i-iot01a.html[STM32L4+ Discovery kit IoT node, low-power wireless, BLE, NFC, WiFi]
26* link:https://www.st.com/en/evaluation-tools/b-l072z-lrwan1.html[STM32L0 Discovery kit LoRa, Sigfox, low-power wireless]
27* link:https://www.st.com/en/evaluation-tools/nucleo-wl55jc.html[STM32 Nucleo-64 development board with STM32WL55JCI MCU]
28* link:https://www.st.com/en/evaluation-tools/b-u585i-iot02a.html[Discovery kit for IoT node with STM32U5 series]
29
30
31=== RP2040 kits
32
33* link:https://www.raspberrypi.com/products/raspberry-pi-pico/[Raspberry Pi Pico]
34
35=== ESP32
36
37* link:https://github.com/esp-rs/esp-rust-board[ESP32C3]
38
39== Running an example
40
41First you need to clone the link:https://github.com/embassy-rs/embassy[github repository];
42
43[source, bash]
44----
45git clone https://github.com/embassy-rs/embassy.git
46cd embassy
47----
48
49Once 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”.
50
51[source, bash]
52----
53cd examples/nrf52840
54cargo build --bin blinky --release
55----
56
57Once you’ve confirmed you can build the example, connect your computer to your board with a debug probe and run it on hardware:
58
59[source, bash]
60----
61cargo run --bin blinky --release
62----
63
64If everything worked correctly, you should see a blinking LED on your board, and debug output similar to this on your computer:
65
66[source]
67----
68 Finished dev [unoptimized + debuginfo] target(s) in 1m 56s
69 Running `probe-run --chip STM32F407VGTx target/thumbv7em-none-eabi/debug/blinky`
70(HOST) INFO flashing program (71.36 KiB)
71(HOST) INFO success!
72────────────────────────────────────────────────────────────────────────────────
730 INFO Hello World!
74└─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:18
751 INFO high
76└─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:23
772 INFO low
78└─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:27
793 INFO high
80└─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:23
814 INFO low
82└─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:27
83----
84
85NOTE: 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.
86
87=== It didn’t work!
88
89If you hare having issues when running `+cargo run --release+`, please check the following:
90
91* You are specifying the correct `+--chip+` on the command line, OR
92* You have set `+.cargo/config.toml+`’s run line to the correct chip, AND
93* 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)
94
95At 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.
96
97If you are trying to run an example with `+cargo run --release+` and you see the following output:
98[source]
99----
1000.000000 INFO Hello World!
101└─ <invalid location: defmt frame-index: 14>
1020.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) }
103└─ <invalid location: defmt frame-index: 124>
1040.000061 TRACE allocating type=Interrupt mps=8 interval_ms=255, dir=In
105└─ <invalid location: defmt frame-index: 68>
1060.000091 TRACE index=1
107└─ <invalid location: defmt frame-index: 72>
108----
109
110To get rid of the frame-index error add the following to your `Cargo.toml`:
111
112[source,toml]
113----
114[profile.release]
115debug = 2
116----
117
118If you’re getting an extremely long error message containing something like the following:
119
120[source]
121----
122error[E0463]: can't find crate for `std`
123 |
124 = note: the `thumbv6m-none-eabi` target may not support the standard library
125 = note: `std` is required by `stable_deref_trait` because it does not declare `#![no_std]`
126----
127
128Make sure that you didn’t accidentally run `+cargo add probe-rs+` (which adds it as a dependency) instead of link:https://probe.rs/docs/getting-started/installation/[correctly installing probe-rs].
129
130If you’re using a raspberry pi pico-w, make sure you’re running `+cargo run --bin wifi_blinky --release+` rather than the regular blinky. The pico-w’s on-board LED is connected to the WiFi chip, which needs to be initialized before the LED can be blinked.
131
132If you’re using an rp2040 debug probe (e.g. the pico probe) and are having issues after running `probe-rs info`, unplug and reconnect the probe, letting it power cycle. Running `probe-rs info` is link:https://github.com/probe-rs/probe-rs/issues/1849[known to put the pico probe into an unusable state].
133
134If 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].
135
136== What's next?
137
138Congratulations, you have your first Embassy application running! Here are some suggestions for where to go from here:
139
140* Read more about the xref:runtime.adoc[executor].
141* Read more about the xref:hal.adoc[HAL].
142* Start xref:basic_application.adoc[writing your application].
143* Learn how to xref:new_project.adoc[start a new embassy project by adapting an example].
diff --git a/docs/pages/hal.adoc b/docs/pages/hal.adoc
new file mode 100644
index 000000000..14b85e1f1
--- /dev/null
+++ b/docs/pages/hal.adoc
@@ -0,0 +1,14 @@
1= Hardware Abstraction Layer (HAL)
2
3Embassy provides HALs for several microcontroller families:
4
5* `embassy-nrf` for the nRF microcontrollers from Nordic Semiconductor
6* `embassy-stm32` for STM32 microcontrollers from ST Microelectronics
7* `embassy-rp` for the Raspberry Pi RP2040 microcontrollers
8
9These HALs implement async/await functionality for most peripherals while also implementing the
10async traits in `embedded-hal` and `embedded-hal-async`. You can also use these HALs with another executor.
11
12For the ESP32 series, there is an link:https://github.com/esp-rs/esp-hal[esp-hal] which you can use.
13
14For the WCH 32-bit RISC-V series, there is an link:https://github.com/ch32-rs/ch32-hal[ch32-hal], which you can use.
diff --git a/docs/pages/layer_by_layer.adoc b/docs/pages/layer_by_layer.adoc
new file mode 100644
index 000000000..f87291c20
--- /dev/null
+++ b/docs/pages/layer_by_layer.adoc
@@ -0,0 +1,85 @@
1= From bare metal to async Rust
2
3If you're new to Embassy, it can be overwhelming to grasp all the terminology and concepts. This guide aims to clarify the different layers in Embassy, which problem each layer solves for the application writer.
4
5This guide uses the STM32 IOT01A board, but should be easy to translate to any STM32 chip. For nRF, the PAC itself is not maintained within the Embassy project, but the concepts and the layers are similar.
6
7The application we'll write is a simple 'push button, blink led' application, which is great for illustrating input and output handling for each of the examples we'll go through. We'll start at the Peripheral Access Crate (PAC) example and end at the async example.
8
9== PAC version
10
11The PAC is the lowest API for accessing peripherals and registers, if you don't count reading/writing directly to memory addresses. It provides distinct types to make accessing peripheral registers easier, but it does not prevent you from writing unsafe code.
12
13Writing an application using the PAC directly is therefore not recommended, but if the functionality you want to use is not exposed in the upper layers, that's what you need to use.
14
15The blinky app using PAC is shown below:
16
17[source,rust]
18----
19include::../examples/layer-by-layer/blinky-pac/src/main.rs[]
20----
21
22As you can see, a lot of code is needed to enable the peripheral clocks and to configure the input pins and the output pins of the application.
23
24Another downside of this application is that it is busy-looping while polling the button state. This prevents the microcontroller from utilizing any sleep mode to save power.
25
26== HAL version
27
28To simplify our application, we can use the HAL instead. The HAL exposes higher level APIs that handle details such as:
29
30* Automatically enabling the peripheral clock when you're using the peripheral
31* Deriving and applying register configuration from higher level types
32* Implementing the embedded-hal traits to make peripherals useful in third party drivers
33
34The HAL example is shown below:
35
36[source,rust]
37----
38include::../examples/layer-by-layer/blinky-hal/src/main.rs[]
39----
40
41As you can see, the application becomes a lot simpler, even without using any async code. The `Input` and `Output` types hide all the details of accessing the GPIO registers and allow you to use a much simpler API for querying the state of the button and toggling the LED output.
42
43The same downside from the PAC example still applies though: the application is busy looping and consuming more power than necessary.
44
45== Interrupt driven
46
47To save power, we need to configure the application so that it can be notified when the button is pressed using an interrupt.
48
49Once the interrupt is configured, the application can instruct the microcontroller to enter a sleep mode, consuming very little power.
50
51Given Embassy focus on async Rust (which we'll come back to after this example), the example application must use a combination of the HAL and PAC in order to use interrupts. For this reason, the application also contains some helper functions to access the PAC (not shown below).
52
53[source,rust]
54----
55include::../examples/layer-by-layer/blinky-irq/src/main.rs[lines="1..57"]
56----
57
58The simple application is now more complex again, primarily because of the need to keep the button and LED states in the global scope where it is accessible by the main application loop, as well as the interrupt handler.
59
60To do that, the types must be guarded by a mutex, and interrupts must be disabled whenever we are accessing this global state to gain access to the peripherals.
61
62Luckily, there is an elegant solution to this problem when using Embassy.
63
64== Async version
65
66It's time to use the Embassy capabilities to its fullest. At the core, Embassy has an async executor, or a runtime for async tasks if you will. The executor polls a set of tasks (defined at compile time), and whenever a task `blocks`, the executor will run another task, or put the microcontroller to sleep.
67
68[source,rust]
69----
70include::../examples/layer-by-layer/blinky-async/src/main.rs[]
71----
72
73The async version looks very similar to the HAL version, apart from a few minor details:
74
75* The main entry point is annotated with a different macro and has an async type signature. This macro creates and starts an Embassy runtime instance and launches the main application task. Using the `Spawner` instance, the application may spawn other tasks.
76* The peripheral initialization is done by the main macro, and is handed to the main task.
77* Before checking the button state, the application is awaiting a transition in the pin state (low -> high or high -> low).
78
79When `button.await_for_any_edge().await` is called, the executor will pause the main task and put the microcontroller in sleep mode, unless there are other tasks that can run. Internally, the Embassy HAL has configured the interrupt handler for the button (in `ExtiButton`), so that whenever an interrupt is raised, the task awaiting the button will be woken up.
80
81The minimal overhead of the executor and the ability to run multiple tasks "concurrently" combined with the enormous simplification of the application, makes `async` a great fit for embedded.
82
83== Summary
84
85We have seen how the same application can be written at the different abstraction levels in Embassy. First starting out at the PAC level, then using the HAL, then using interrupts, and then using interrupts indirectly using async Rust.
diff --git a/docs/pages/new_project.adoc b/docs/pages/new_project.adoc
new file mode 100644
index 000000000..346d9f0f8
--- /dev/null
+++ b/docs/pages/new_project.adoc
@@ -0,0 +1,190 @@
1= Starting a new project
2
3Once you’ve successfully xref:getting_started.adoc[run some example projects], the next step is to make a standalone Embassy project.
4
5== Tools for generating Embassy projects
6
7=== CLI
8- link:https://github.com/adinack/cargo-embassy[cargo-embassy] (STM32 and NRF)
9
10=== cargo-generate
11- link:https://github.com/lulf/embassy-template[embassy-template] (STM32, NRF, and RP)
12- link:https://github.com/bentwire/embassy-rp2040-template[embassy-rp2040-template] (RP)
13
14
15== Starting a project from scratch
16
17As 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.
18
19Run:
20
21[source,bash]
22----
23cargo new stm32g474-example
24cd stm32g474-example
25----
26
27to create an empty rust project:
28
29[source]
30----
31stm32g474-example
32├── Cargo.toml
33└── src
34 └── main.rs
35----
36
37Looking 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`.
38
39=== The .cargo/config.toml
40
41Currently, 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.
42
43[source]
44----
45stm32g474-example
46├── .cargo
47│   └── config.toml
48├── Cargo.toml
49└── src
50 └── main.rs
51----
52
53In 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`:
54
55[source,bash]
56----
57$ probe-rs chip list | grep -i stm32g474re
58 STM32G474RETx
59----
60
61and copying `STM32G474RETx` into `.cargo/config.toml` as so:
62
63[source,toml]
64----
65[target.'cfg(all(target_arch = "arm", target_os = "none"))']
66# replace STM32G071C8Rx with your chip as listed in `probe-rs chip list`
67runner = "probe-rs run --chip STM32G474RETx"
68----
69
70=== Cargo.toml
71
72Now 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.
73
74Looking 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`.
75
76At 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:
77
78* Copy the required `embassy-*` lines from the example `Cargo.toml`
79* Make any necessary changes to `features`, e.g. requiring the `stm32g474re` feature of `embassy-stm32`
80* Remove the `path = ""` keys in the `embassy-*` entries
81* 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`
82
83NOTE: 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!
84
85At the time of writing, this method produces the following results:
86
87[source,toml]
88----
89[dependencies]
90embassy-stm32 = {version = "0.1.0", features = ["defmt", "time-driver-any", "stm32g474re", "memory-x", "unstable-pac", "exti"]}
91embassy-executor = { version = "0.3.3", features = ["nightly", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] }
92embassy-time = { version = "0.2", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] }
93
94[patch.crates-io]
95embassy-time = { git = "https://github.com/embassy-rs/embassy", rev = "7703f47c1ecac029f603033b7977d9a2becef48c" }
96embassy-executor = { git = "https://github.com/embassy-rs/embassy", rev = "7703f47c1ecac029f603033b7977d9a2becef48c" }
97embassy-stm32 = { git = "https://github.com/embassy-rs/embassy", rev = "7703f47c1ecac029f603033b7977d9a2becef48c" }
98----
99
100There 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`:
101
102[source,toml]
103----
104defmt = "0.3.5"
105defmt-rtt = "0.4.0"
106cortex-m = {version = "0.7.7", features = ["critical-section-single-core"]}
107cortex-m-rt = "0.7.3"
108panic-probe = "0.3.1"
109----
110
111These 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"] }`.
112
113Finally, copy the `[profile.release]` section from the example `Cargo.toml` into ours.
114
115[source,toml]
116----
117[profile.release]
118debug = 2
119----
120
121=== rust-toolchain.toml
122
123Before 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`:
124
125[source]
126----
127stm32g474-example
128├── .cargo
129│   └── config.toml
130├── Cargo.toml
131├── rust-toolchain.toml
132└── src
133 └── main.rs
134----
135
136[source,toml]
137----
138# Before upgrading check that everything is available on all tier1 targets here:
139# https://rust-lang.github.io/rustup-components-history
140[toolchain]
141channel = "nightly-2023-11-01"
142components = [ "rust-src", "rustfmt", "llvm-tools", "miri" ]
143targets = ["thumbv7em-none-eabi"]
144----
145
146=== build.rs
147
148In order to produce a working binary for our target, cargo requires a custom build script. Copy `build.rs` from the example to our project:
149
150[source]
151----
152stm32g474-example
153├── build.rs
154├── .cargo
155│ └── config.toml
156├── Cargo.toml
157├── rust-toolchain.toml
158└── src
159 └── main.rs
160----
161
162=== Building and running
163
164At this point, we‘re finally ready to build and run our project! Connect your board via a debug probe and run:
165
166[source,bash]
167----
168cargo run --release
169----
170
171should 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:
172
173[source]
174----
175 Compiling stm32g474-example v0.1.0 (/home/you/stm32g474-example)
176 Finished release [optimized + debuginfo] target(s) in 0.22s
177 Running `probe-rs run --chip STM32G474RETx target/thumbv7em-none-eabi/release/stm32g474-example`
178 Erasing sectors ✔ [00:00:00] [#########################################################] 18.00 KiB/18.00 KiB @ 54.09 KiB/s (eta 0s )
179 Programming pages ✔ [00:00:00] [#########################################################] 17.00 KiB/17.00 KiB @ 35.91 KiB/s (eta 0s ) Finished in 0.817s
1800.000000 TRACE BDCR configured: 00008200
181└─ embassy_stm32::rcc::bd::{impl#3}::init::{closure#4} @ /home/you/.cargo/git/checkouts/embassy-9312dcb0ed774b29/7703f47/embassy-stm32/src/fmt.rs:117
1820.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)) }
183└─ embassy_stm32::rcc::set_freqs @ /home/you/.cargo/git/checkouts/embassy-9312dcb0ed774b29/7703f47/embassy-stm32/src/fmt.rs:130
1840.000000 INFO Hello World!
185└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:14
1860.000091 INFO high
187└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:19
1880.300201 INFO low
189└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:23
190----
diff --git a/docs/pages/nrf.adoc b/docs/pages/nrf.adoc
new file mode 100644
index 000000000..1706087ae
--- /dev/null
+++ b/docs/pages/nrf.adoc
@@ -0,0 +1,29 @@
1= Embassy nRF HAL
2
3The link:https://github.com/embassy-rs/embassy/tree/master/embassy-nrf[Embassy nRF HAL] is based on the PACs (Peripheral Access Crate) from link:https://github.com/nrf-rs/[nrf-rs].
4
5== Timer driver
6
7The nRF timer driver operates at 32768 Hz by default.
8
9== Peripherals
10
11The following peripherals have a HAL implementation at present
12
13* PWM
14* SPIM
15* QSPI
16* NVMC
17* GPIOTE
18* RNG
19* TIMER
20* WDT
21* TEMP
22* PPI
23* UARTE
24* TWIM
25* SAADC
26
27== Bluetooth
28
29For bluetooth, you can use the link:https://github.com/embassy-rs/nrf-softdevice[nrf-softdevice] crate.
diff --git a/docs/pages/overview.adoc b/docs/pages/overview.adoc
new file mode 100644
index 000000000..1b9381bfe
--- /dev/null
+++ b/docs/pages/overview.adoc
@@ -0,0 +1,79 @@
1= Introduction
2
3Embassy is a project to make async/await a first-class option for embedded development.
4
5== What is async?
6
7When 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.
8
9Because 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.
10
11In 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.
12
13Compared 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.
14
15== What is Embassy?
16
17The Embassy project consists of several crates that you can use together or independently:
18
19=== Executor
20The 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.
21
22=== Hardware Abstraction Layers
23HALs implement safe Rust API which let you use peripherals such as USART, UART, I2C, SPI, CAN, and USB without having to directly manipulate registers.
24
25Embassy 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.
26
27The Embassy project maintains HALs for select hardware, but you can still use HALs from other projects with Embassy.
28
29* link:https://docs.embassy.dev/embassy-stm32/[embassy-stm32], for all STM32 microcontroller families.
30* link:https://docs.embassy.dev/embassy-nrf/[embassy-nrf], for the Nordic Semiconductor nRF52, nRF53, nRF91 series.
31* link:https://docs.embassy.dev/embassy-rp/[embassy-rp], for the Raspberry Pi RP2040 microcontroller.
32* link:https://github.com/esp-rs[esp-rs], for the Espressif Systems ESP32 series of chips.
33* link:https://github.com/ch32-rs/ch32-hal[ch32-hal], for the WCH 32-bit RISC-V(CH32V) series of chips.
34
35NOTE: 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,
36as they implement both the link:https://github.com/rust-embedded/embedded-hal[Embedded HAL] blocking and async traits.
37
38=== Networking
39The 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.
40
41=== Bluetooth
42The link:https://github.com/embassy-rs/nrf-softdevice[nrf-softdevice] crate provides Bluetooth Low Energy 4.x and 5.x support for nRF52 microcontrollers.
43
44=== LoRa
45link:https://github.com/lora-rs/lora-rs[lora-rs] supports LoRa networking on a wide range of LoRa radios, fully integrated with a Rust LoRaWAN implementation. It provides four crates — lora-phy, lora-modulation, lorawan-encoding, and lorawan-device — and basic examples for various development boards. It has support for STM32WL wireless microcontrollers or Semtech SX127x transceivers, among others.
46
47=== USB
48link: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.
49
50=== Bootloader and DFU
51link: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.
52
53== What is DMA?
54
55For 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.
56
57The 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.
58
59== Examples
60
61Embassy provides examples for all HALs supported. You can find them in the `examples/` folder.
62
63
64Main loop example
65
66[source,rust]
67----
68include::../examples/examples/std/src/bin/tick.rs[]
69----
70
71include::embassy_in_the_wild.adoc[leveloffset = 2]
72
73== Resources
74
75For more reading material on async Rust and Embassy:
76
77* link:https://tweedegolf.nl/en/blog/65/async-rust-vs-rtos-showdown[Comparsion of FreeRTOS and Embassy]
78* link:https://dev.to/apollolabsbin/series/20707[Tutorials]
79* link:https://blog.drogue.io/firmware-updates-part-1/[Firmware Updates with Embassy]
diff --git a/docs/pages/project_structure.adoc b/docs/pages/project_structure.adoc
new file mode 100644
index 000000000..722ec8d9d
--- /dev/null
+++ b/docs/pages/project_structure.adoc
@@ -0,0 +1,93 @@
1= Project Structure
2
3There are many ways to configure embassy and its components for your exact application. The link:https://github.com/embassy-rs/embassy/tree/main/examples[examples] directory for each chipset demonstrates how your project structure should look. Let's break it down:
4
5The toplevel file structure of your project should look like this:
6[source,plain]
7----
8{} = Maybe
9
10my-project
11|- .cargo
12| |- config.toml
13|- src
14| |- main.rs
15|- build.rs
16|- Cargo.toml
17|- {memory.x}
18|- rust-toolchain.toml
19----
20
21[discrete]
22== .cargo/config.toml
23
24This directory/file describes what platform you're on, and configures link:https://github.com/probe-rs/probe-rs[probe-rs] to deploy to your device.
25
26Here is a minimal example:
27
28[source,toml]
29----
30[target.thumbv6m-none-eabi] # <-change for your platform
31runner = 'probe-rs run --chip STM32F031K6Tx' # <- change for your chip
32
33[build]
34target = "thumbv6m-none-eabi" # <-change for your platform
35
36[env]
37DEFMT_LOG = "trace" # <- can change to info, warn, or error
38----
39
40[discrete]
41== build.rs
42
43This is the build script for your project. It links defmt (what is link:https://defmt.ferrous-systems.com[defmt]?) and the `memory.x` file if needed. This file is pretty specific for each chipset, just copy and paste from the corresponding link:https://github.com/embassy-rs/embassy/tree/main/examples[example].
44
45[discrete]
46== Cargo.toml
47
48This is your manifest file, where you can configure all of the embassy components to use the features you need.
49
50[discrete]
51=== Features
52
53[discrete]
54==== Time
55- tick-hz-x: Configures the tick rate of `embassy-time`. Higher tick rate means higher precision, and higher CPU wakes.
56- defmt-timestamp-uptime: defmt log entries will display the uptime in seconds.
57
58...more to come
59
60[discrete]
61== memory.x
62
63This file outlines the flash/ram usage of your program. It is especially useful when using link:https://github.com/embassy-rs/nrf-softdevice[nrf-softdevice] on an nRF5x.
64
65Here is an example for using S140 with an nRF52840:
66
67[source,x]
68----
69MEMORY
70{
71 /* NOTE 1 K = 1 KiBi = 1024 bytes */
72 /* These values correspond to the NRF52840 with Softdevices S140 7.0.1 */
73 FLASH : ORIGIN = 0x00027000, LENGTH = 868K
74 RAM : ORIGIN = 0x20020000, LENGTH = 128K
75}
76----
77
78[discrete]
79== rust-toolchain.toml
80
81This file configures the rust version and configuration to use.
82
83A minimal example:
84
85[source,toml]
86----
87[toolchain]
88channel = "nightly-2023-08-19" # <- as of writing, this is the exact rust version embassy uses
89components = [ "rust-src", "rustfmt" ] # <- optionally add "llvm-tools-preview" for some extra features like "cargo size"
90targets = [
91 "thumbv6m-none-eabi" # <-change for your platform
92]
93----
diff --git a/docs/pages/runtime.adoc b/docs/pages/runtime.adoc
new file mode 100644
index 000000000..f2812dd7c
--- /dev/null
+++ b/docs/pages/runtime.adoc
@@ -0,0 +1,46 @@
1= Embassy executor
2
3The Embassy executor is an async/await executor designed for embedded usage along with support functionality for interrupts and timers.
4
5== Features
6
7* No `alloc`, no heap needed. Task are statically allocated.
8* No "fixed capacity" data structures, executor works with 1 or 1000 tasks without needing config/tuning.
9* Integrated timer queue: sleeping is easy, just do `Timer::after_secs(1).await;`.
10* No busy-loop polling: CPU sleeps when there's no work to do, using interrupts or `WFE/SEV`.
11* Efficient polling: a wake will only poll the woken task, not all of them.
12* Fair: a task can't monopolize CPU time even if it's constantly being woken. All other tasks get a chance to run before a given task gets polled for the second time.
13* Creating multiple executor instances is supported, to run tasks at different priority levels. This allows higher-priority tasks to preempt lower-priority tasks.
14
15== Executor
16
17The executor function is described below. The executor keeps a queue of tasks that it should poll. When a task is created, it is polled (1). The task will attempt to make progress until it reaches a point where it would be blocked. This may happen whenever a task is .await'ing an async function. When that happens, the task yields execution by (2) returning `Poll::Pending`. Once a task yields, the executor enqueues the task at the end of the run queue, and proceeds to (3) poll the next task in the queue. When a task is finished or canceled, it will not be enqueued again.
18
19IMPORTANT: The executor relies on tasks not blocking indefinitely, as this prevents the executor to regain control and schedule another task.
20
21image::embassy_executor.png[Executor model]
22
23If you use the `#[embassy_executor::main]` macro in your application, it creates the `Executor` for you and spawns the main entry point as the first task. You can also create the Executor manually, and you can in fact create multiple Executors.
24
25
26== Interrupts
27
28Interrupts are a common way for peripherals to signal completion of some operation and fits well with the async execution model. The following diagram describes a typical application flow where (1) a task is polled and is attempting to make progress. The task then (2) instructs the peripheral to perform some operation, and awaits. After some time has passed, (3) an interrupt is raised, marking the completion of the operation.
29
30The peripheral HAL then (4) ensures that interrupt signals are routed to the peripheral and updating the peripheral state with the results of the operation. The executor is then (5) notified that the task should be polled, which it will do.
31
32image::embassy_irq.png[Interrupt handling]
33
34NOTE: There exists a special executor named `InterruptExecutor` which can be driven by an interrupt. This can be used to drive tasks at different priority levels by creating multiple `InterruptExecutor` instances.
35
36== Time
37
38Embassy features an internal timer queue enabled by the `time` feature flag. When enabled, Embassy assumes a time `Driver` implementation existing for the platform. Embassy provides time drivers for the nRF, STM32, RPi Pico, WASM and Std platforms.
39
40The timer driver implementations for the embedded platforms might support only a fixed number of alarms that can be set. Make sure the number of tasks you expect wanting to use the timer at the same time do not exceed this limit.
41
42The timer speed is configurable at compile time using the `time-tick-<frequency>`. At present, the timer may be configured to run at 1000 Hz, 32768 Hz, or 1 MHz. Before changing the defaults, make sure the target HAL supports the particular frequency setting.
43
44
45
46NOTE: If you do not require timers in your application, not enabling the `time` feature can save some CPU cycles and reduce power usage.
diff --git a/docs/pages/sharing_peripherals.adoc b/docs/pages/sharing_peripherals.adoc
new file mode 100644
index 000000000..6bcd56b01
--- /dev/null
+++ b/docs/pages/sharing_peripherals.adoc
@@ -0,0 +1,128 @@
1= Sharing peripherals between tasks
2
3Often times, more than one task needs access to the same resource (pin, communication interface, etc.). Embassy provides many different synchronization primitives in the link:https://crates.io/crates/embassy-sync[embassy-sync] crate.
4
5The following examples shows different ways to use the on-board LED on a Raspberry Pi Pico board by two tasks simultaneously.
6
7== Sharing using a Mutex
8
9Using mutual exclusion is the simplest way to share a peripheral.
10
11TIP: Dependencies needed to run this example link:/book/dev/basic_application.html#_the_cargo_toml[can be found here].
12[,rust]
13----
14use defmt::*;
15use embassy_executor::Spawner;
16use embassy_rp::gpio;
17use embassy_sync::blocking_mutex::raw::ThreadModeRawMutex;
18use embassy_sync::mutex::Mutex;
19use embassy_time::{Duration, Ticker};
20use gpio::{AnyPin, Level, Output};
21use {defmt_rtt as _, panic_probe as _};
22
23type LedType = Mutex<ThreadModeRawMutex, Option<Output<'static, AnyPin>>>;
24static LED: LedType = Mutex::new(None);
25
26#[embassy_executor::main]
27async fn main(spawner: Spawner) {
28 let p = embassy_rp::init(Default::default());
29 // set the content of the global LED reference to the real LED pin
30 let led = Output::new(AnyPin::from(p.PIN_25), Level::High);
31 // inner scope is so that once the mutex is written to, the MutexGuard is dropped, thus the
32 // Mutex is released
33 {
34 *(LED.lock().await) = Some(led);
35 }
36 let dt = 100 * 1_000_000;
37 let k = 1.003;
38
39 unwrap!(spawner.spawn(toggle_led(&LED, Duration::from_nanos(dt))));
40 unwrap!(spawner.spawn(toggle_led(&LED, Duration::from_nanos((dt as f64 * k) as u64))));
41}
42
43// A pool size of 2 means you can spawn two instances of this task.
44#[embassy_executor::task(pool_size = 2)]
45async fn toggle_led(led: &'static LedType, delay: Duration) {
46 let mut ticker = Ticker::every(delay);
47 loop {
48 {
49 let mut led_unlocked = led.lock().await;
50 if let Some(pin_ref) = led_unlocked.as_mut() {
51 pin_ref.toggle();
52 }
53 }
54 ticker.next().await;
55 }
56}
57----
58
59The structure facilitating access to the resource is the defined `LedType`.
60
61=== Why so complicated
62
63Unwrapping the layers gives insight into why each one is needed.
64
65==== `Mutex<RawMutexType, T>`
66
67The mutex is there so if one task gets the resource first and begins modifying it, all other tasks wanting to write will have to wait (the `led.lock().await` will return immediately if no task has locked the mutex, and will block if it is accessed somewhere else).
68
69==== `Option<T>`
70
71The `LED` variable needs to be defined outside the main task as references accepted by tasks need to be `'static`. However, if it is outside the main task, it cannot be initialised to point to any pin, as the pins themselves are not initialised. Thus, it is set to `None`.
72
73==== `Output<AnyPin>`
74
75To indicate that the pin will be set to an Output. The `AnyPin` could have been `embassy_rp::peripherals::PIN_25`, however this option lets the `toggle_led` function be more generic.
76
77== Sharing using a Channel
78
79A channel is another way to ensure exclusive access to a resource. Using a channel is great in the cases where the access can happen at a later point in time, allowing you to enqueue operations and do other things.
80
81TIP: Dependencies needed to run this example link:/book/dev/basic_application.html#_the_cargo_toml[can be found here].
82[,rust]
83----
84use defmt::*;
85use embassy_executor::Spawner;
86use embassy_rp::gpio;
87use embassy_sync::blocking_mutex::raw::ThreadModeRawMutex;
88use embassy_sync::channel::{Channel, Sender};
89use embassy_time::{Duration, Ticker};
90use gpio::{AnyPin, Level, Output};
91use {defmt_rtt as _, panic_probe as _};
92
93enum LedState {
94 Toggle,
95}
96static CHANNEL: Channel<ThreadModeRawMutex, LedState, 64> = Channel::new();
97
98#[embassy_executor::main]
99async fn main(spawner: Spawner) {
100 let p = embassy_rp::init(Default::default());
101 let mut led = Output::new(AnyPin::from(p.PIN_25), Level::High);
102
103 let dt = 100 * 1_000_000;
104 let k = 1.003;
105
106 unwrap!(spawner.spawn(toggle_led(CHANNEL.sender(), Duration::from_nanos(dt))));
107 unwrap!(spawner.spawn(toggle_led(CHANNEL.sender(), Duration::from_nanos((dt as f64 * k) as u64))));
108
109 loop {
110 match CHANNEL.receive().await {
111 LedState::Toggle => led.toggle(),
112 }
113 }
114}
115
116// A pool size of 2 means you can spawn two instances of this task.
117#[embassy_executor::task(pool_size = 2)]
118async fn toggle_led(control: Sender<'static, ThreadModeRawMutex, LedState, 64>, delay: Duration) {
119 let mut ticker = Ticker::every(delay);
120 loop {
121 control.send(LedState::Toggle).await;
122 ticker.next().await;
123 }
124}
125----
126
127This example replaces the Mutex with a Channel, and uses another task (the main loop) to drive the LED. The advantage of this approach is that only a single task references the peripheral, separating concerns. However, using a Mutex has a lower overhead and might be necessary if you need to ensure
128that the operation is completed before continuing to do other work in your task.
diff --git a/docs/pages/stm32.adoc b/docs/pages/stm32.adoc
new file mode 100644
index 000000000..7bfc0592b
--- /dev/null
+++ b/docs/pages/stm32.adoc
@@ -0,0 +1,24 @@
1= Embassy STM32 HAL
2
3The link:https://github.com/embassy-rs/embassy/tree/master/embassy-stm32[Embassy STM32 HAL] is based on the `stm32-metapac` project.
4
5== The infinite variant problem
6
7STM32 microcontrollers come in many families, and flavors and supporting all of them is a big undertaking. Embassy has taken advantage of the fact
8that the STM32 peripheral versions are shared across chip families. Instead of re-implementing the SPI
9peripheral for every STM32 chip family, embassy has a single SPI implementation that depends on
10code-generated register types that are identical for STM32 families with the same version of a given peripheral.
11
12=== The metapac
13
14The `stm32-metapac` module uses pre-generated chip and register definitions for STM32 chip families to generate register types. This is done at compile time based on Cargo feature flags.
15
16The chip and register definitions are located in a separate module, `stm32-data`, which is modified whenever a bug is found in the definitions, or when adding support for new chip families.
17
18=== The HAL
19
20The `embassy-stm32` module contains the HAL implementation for all STM32 families. The implementation uses automatically derived feature flags to support the correct version of a given peripheral for a given chip family.
21
22== Timer driver
23
24The STM32 timer driver operates at 32768 Hz by default.
diff --git a/docs/pages/system.adoc b/docs/pages/system.adoc
new file mode 100644
index 000000000..985f92b18
--- /dev/null
+++ b/docs/pages/system.adoc
@@ -0,0 +1,13 @@
1= System description
2
3This section describes different parts of Embassy in more detail.
4
5include::runtime.adoc[leveloffset = 2]
6include::bootloader.adoc[leveloffset = 2]
7include::time_keeping.adoc[leveloffset = 2]
8include::hal.adoc[leveloffset = 2]
9include::nrf.adoc[leveloffset = 2]
10include::stm32.adoc[leveloffset = 2]
11include::sharing_peripherals.adoc[leveloffset = 2]
12include::developer.adoc[leveloffset = 2]
13include::developer_stm32.adoc[leveloffset = 2]
diff --git a/docs/pages/time_keeping.adoc b/docs/pages/time_keeping.adoc
new file mode 100644
index 000000000..17492a884
--- /dev/null
+++ b/docs/pages/time_keeping.adoc
@@ -0,0 +1,62 @@
1= Time-keeping
2
3In 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
4that 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 abstractions
5to delay the current task for a specified interval of time.
6
7The interface for time-keeping in Embassy is handled by the link:https://crates.io/crates/embassy-time[embassy-time] crate. The types can be used with the internal
8timer queue in link:https://crates.io/crates/embassy-executor[embassy-executor] or a custom timer queue implementation.
9
10== Timer
11
12The `embassy::time::Timer` type provides two timing methods.
13
14`Timer::at` creates a future that completes at the specified `Instant`, relative to the system boot time.
15`Timer::after` creates a future that completes after the specified `Duration`, relative to when the future was created.
16
17An example of a delay is provided as follows:
18
19TIP: Dependencies needed to run this example link:/book/dev/basic_application.html#_the_cargo_toml[can be found here].
20[,rust]
21----
22use embassy::executor::{task, Executor};
23use embassy::time::{Duration, Timer};
24
25#[task]
26/// Task that ticks periodically
27async fn tick_periodic() -> ! {
28 loop {
29 rprintln!("tick!");
30 // async sleep primitive, suspends the task for 500ms.
31 Timer::after(Duration::from_millis(500)).await;
32 }
33}
34----
35
36== Delay
37
38The `embassy::time::Delay` type provides an implementation of the link:https://docs.rs/embedded-hal/1.0.0/embedded_hal/delay/index.html[embedded-hal] and
39link:https://docs.rs/embedded-hal-async/latest/embedded_hal_async/delay/index.html[embedded-hal-async] traits. This can be used for drivers
40that expect a generic delay implementation to be provided.
41
42An example of how this can be used:
43
44TIP: Dependencies needed to run this example link:/book/dev/basic_application.html#_the_cargo_toml[can be found here].
45[,rust]
46----
47use embassy::executor::{task, Executor};
48
49#[task]
50/// Task that ticks periodically
51async fn tick_periodic() -> ! {
52 loop {
53 rprintln!("tick!");
54 // async sleep primitive, suspends the task for 500ms.
55 generic_delay(embassy::time::Delay).await
56 }
57}
58
59async fn generic_delay<D: embedded_hal_async::delay::DelayNs>(delay: D) {
60 delay.delay_ms(500).await;
61}
62----