aboutsummaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rw-r--r--examples/Cargo.toml31
-rw-r--r--examples/build.rs31
-rw-r--r--examples/memory.x7
-rw-r--r--examples/src/bin/qspi.rs123
-rw-r--r--examples/src/bin/uart.rs72
-rw-r--r--examples/src/example_common.rs68
6 files changed, 332 insertions, 0 deletions
diff --git a/examples/Cargo.toml b/examples/Cargo.toml
new file mode 100644
index 000000000..c243691a7
--- /dev/null
+++ b/examples/Cargo.toml
@@ -0,0 +1,31 @@
1[package]
2authors = ["Dario Nieuwenhuis <[email protected]>"]
3edition = "2018"
4name = "embassy-examples"
5version = "0.1.0"
6
7[features]
8default = [
9 "defmt-default",
10]
11defmt-default = []
12defmt-trace = []
13defmt-debug = []
14defmt-info = []
15defmt-warn = []
16defmt-error = []
17
18
19[dependencies]
20cortex-m = { version = "0.6.3" }
21cortex-m-rt = "0.6.12"
22defmt = "0.1.0"
23embedded-hal = { version = "0.2.4" }
24defmt-rtt = "0.1.0"
25panic-probe = "0.1.0"
26nrf52840-hal = { version = "0.11.0" }
27embassy = { version = "0.1.0", path = "../embassy" }
28embassy-nrf = { version = "0.1.0", path = "../embassy-nrf", features = ["defmt-trace", "nrf52840"] }
29static-executor = { version = "0.1.0", features=["defmt"]}
30static-executor-cortex-m = { version = "0.1.0" }
31futures = { version = "0.3.5", default-features = false }
diff --git a/examples/build.rs b/examples/build.rs
new file mode 100644
index 000000000..d534cc3df
--- /dev/null
+++ b/examples/build.rs
@@ -0,0 +1,31 @@
1//! This build script copies the `memory.x` file from the crate root into
2//! a directory where the linker can always find it at build time.
3//! For many projects this is optional, as the linker always searches the
4//! project root directory -- wherever `Cargo.toml` is. However, if you
5//! are using a workspace or have a more complicated build setup, this
6//! build script becomes required. Additionally, by requesting that
7//! Cargo re-run the build script whenever `memory.x` is changed,
8//! updating `memory.x` ensures a rebuild of the application with the
9//! new memory settings.
10
11use std::env;
12use std::fs::File;
13use std::io::Write;
14use std::path::PathBuf;
15
16fn main() {
17 // Put `memory.x` in our output directory and ensure it's
18 // on the linker search path.
19 let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
20 File::create(out.join("memory.x"))
21 .unwrap()
22 .write_all(include_bytes!("memory.x"))
23 .unwrap();
24 println!("cargo:rustc-link-search={}", out.display());
25
26 // By default, Cargo will re-run a build script whenever
27 // any file in the project changes. By specifying `memory.x`
28 // here, we ensure the build script is only re-run when
29 // `memory.x` is changed.
30 println!("cargo:rerun-if-changed=memory.x");
31}
diff --git a/examples/memory.x b/examples/memory.x
new file mode 100644
index 000000000..9b04edec0
--- /dev/null
+++ b/examples/memory.x
@@ -0,0 +1,7 @@
1MEMORY
2{
3 /* NOTE 1 K = 1 KiBi = 1024 bytes */
4 /* These values correspond to the NRF52840 with Softdevices S140 7.0.1 */
5 FLASH : ORIGIN = 0x00000000, LENGTH = 1024K
6 RAM : ORIGIN = 0x20000000, LENGTH = 256K
7}
diff --git a/examples/src/bin/qspi.rs b/examples/src/bin/qspi.rs
new file mode 100644
index 000000000..395422e7f
--- /dev/null
+++ b/examples/src/bin/qspi.rs
@@ -0,0 +1,123 @@
1#![no_std]
2#![no_main]
3#![feature(type_alias_impl_trait)]
4
5#[path = "../example_common.rs"]
6mod example_common;
7use example_common::*;
8
9use cortex_m_rt::entry;
10use embassy::flash::Flash;
11use embassy_nrf::qspi;
12use nrf52840_hal::gpio;
13
14const PAGE_SIZE: usize = 4096;
15
16// Workaround for alignment requirements.
17// Nicer API will probably come in the future.
18#[repr(C, align(4))]
19struct AlignedBuf([u8; 4096]);
20
21#[static_executor::task]
22async fn run() {
23 let p = embassy_nrf::pac::Peripherals::take().dewrap();
24
25 let port0 = gpio::p0::Parts::new(p.P0);
26
27 let pins = qspi::Pins {
28 csn: port0
29 .p0_17
30 .into_push_pull_output(gpio::Level::High)
31 .degrade(),
32 sck: port0
33 .p0_19
34 .into_push_pull_output(gpio::Level::High)
35 .degrade(),
36 io0: port0
37 .p0_20
38 .into_push_pull_output(gpio::Level::High)
39 .degrade(),
40 io1: port0
41 .p0_21
42 .into_push_pull_output(gpio::Level::High)
43 .degrade(),
44 io2: Some(
45 port0
46 .p0_22
47 .into_push_pull_output(gpio::Level::High)
48 .degrade(),
49 ),
50 io3: Some(
51 port0
52 .p0_23
53 .into_push_pull_output(gpio::Level::High)
54 .degrade(),
55 ),
56 };
57
58 let config = qspi::Config {
59 pins,
60 read_opcode: qspi::ReadOpcode::READ4IO,
61 write_opcode: qspi::WriteOpcode::PP4IO,
62 xip_offset: 0,
63 write_page_size: qspi::WritePageSize::_256BYTES,
64 };
65
66 let mut q = qspi::Qspi::new(p.QSPI, config);
67
68 let mut id = [1; 3];
69 q.custom_instruction(0x9F, &[], &mut id).await.unwrap();
70 info!("id: {:[u8]}", id);
71
72 // Read status register
73 let mut status = [0; 1];
74 q.custom_instruction(0x05, &[], &mut status).await.unwrap();
75
76 info!("status: {:?}", status[0]);
77
78 if status[0] & 0x40 == 0 {
79 status[0] |= 0x40;
80
81 q.custom_instruction(0x01, &status, &mut []).await.unwrap();
82
83 info!("enabled quad in status");
84 }
85
86 let mut buf = AlignedBuf([0u8; PAGE_SIZE]);
87
88 let pattern = |a: u32| (a ^ (a >> 8) ^ (a >> 16) ^ (a >> 24)) as u8;
89
90 for i in 0..8 {
91 info!("page {:?}: erasing... ", i);
92 q.erase(i * PAGE_SIZE).await.unwrap();
93
94 for j in 0..PAGE_SIZE {
95 buf.0[j] = pattern((j + i * PAGE_SIZE) as u32);
96 }
97
98 info!("programming...");
99 q.write(i * PAGE_SIZE, &buf.0).await.unwrap();
100 }
101
102 for i in 0..8 {
103 info!("page {:?}: reading... ", i);
104 q.read(i * PAGE_SIZE, &mut buf.0).await.unwrap();
105
106 info!("verifying...");
107 for j in 0..PAGE_SIZE {
108 assert_eq!(buf.0[j], pattern((j + i * PAGE_SIZE) as u32));
109 }
110 }
111
112 info!("done!")
113}
114
115#[entry]
116fn main() -> ! {
117 info!("Hello World!");
118
119 unsafe {
120 run.spawn().dewrap();
121 static_executor::run();
122 }
123}
diff --git a/examples/src/bin/uart.rs b/examples/src/bin/uart.rs
new file mode 100644
index 000000000..21e26e3ad
--- /dev/null
+++ b/examples/src/bin/uart.rs
@@ -0,0 +1,72 @@
1#![no_std]
2#![no_main]
3#![feature(type_alias_impl_trait)]
4
5#[path = "../example_common.rs"]
6mod example_common;
7use example_common::*;
8
9use cortex_m_rt::entry;
10use embassy::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt};
11use embassy_nrf::uarte;
12use futures::pin_mut;
13use nrf52840_hal::gpio;
14
15#[static_executor::task]
16async fn run() {
17 let p = embassy_nrf::pac::Peripherals::take().dewrap();
18
19 let port0 = gpio::p0::Parts::new(p.P0);
20
21 let pins = uarte::Pins {
22 rxd: port0.p0_08.into_floating_input().degrade(),
23 txd: port0
24 .p0_06
25 .into_push_pull_output(gpio::Level::Low)
26 .degrade(),
27 cts: None,
28 rts: None,
29 };
30
31 let u = uarte::Uarte::new(
32 p.UARTE0,
33 pins,
34 uarte::Parity::EXCLUDED,
35 uarte::Baudrate::BAUD115200,
36 );
37 pin_mut!(u);
38
39 info!("uarte initialized!");
40
41 u.write_all(b"Hello!\r\n").await.dewrap();
42 info!("wrote hello in uart!");
43
44 // Simple demo, reading 8-char chunks and echoing them back reversed.
45 loop {
46 info!("reading...");
47 let mut buf = [0u8; 8];
48 u.read_exact(&mut buf).await.dewrap();
49 info!("read done, got {:[u8]}", buf);
50
51 // Reverse buf
52 for i in 0..4 {
53 let tmp = buf[i];
54 buf[i] = buf[7 - i];
55 buf[7 - i] = tmp;
56 }
57
58 info!("writing...");
59 u.write_all(&buf).await.dewrap();
60 info!("write done");
61 }
62}
63
64#[entry]
65fn main() -> ! {
66 info!("Hello World!");
67
68 unsafe {
69 run.spawn().dewrap();
70 static_executor::run();
71 }
72}
diff --git a/examples/src/example_common.rs b/examples/src/example_common.rs
new file mode 100644
index 000000000..e9919153c
--- /dev/null
+++ b/examples/src/example_common.rs
@@ -0,0 +1,68 @@
1#![macro_use]
2
3use defmt_rtt as _; // global logger
4use nrf52840_hal as _;
5use panic_probe as _;
6use static_executor_cortex_m as _;
7
8pub use defmt::{info, intern};
9
10use core::sync::atomic::{AtomicUsize, Ordering};
11
12#[defmt::timestamp]
13fn timestamp() -> u64 {
14 static COUNT: AtomicUsize = AtomicUsize::new(0);
15 // NOTE(no-CAS) `timestamps` runs with interrupts disabled
16 let n = COUNT.load(Ordering::Relaxed);
17 COUNT.store(n + 1, Ordering::Relaxed);
18 n as u64
19}
20
21macro_rules! depanic {
22 ($( $i:expr ),*) => {
23 {
24 defmt::error!($( $i ),*);
25 panic!();
26 }
27 }
28}
29
30pub trait Dewrap<T> {
31 /// dewrap = defmt unwrap
32 fn dewrap(self) -> T;
33
34 /// dexpect = defmt expect
35 fn dexpect<M: defmt::Format>(self, msg: M) -> T;
36}
37
38impl<T> Dewrap<T> for Option<T> {
39 fn dewrap(self) -> T {
40 match self {
41 Some(t) => t,
42 None => depanic!("Dewrap failed: enum is none"),
43 }
44 }
45
46 fn dexpect<M: defmt::Format>(self, msg: M) -> T {
47 match self {
48 Some(t) => t,
49 None => depanic!("Unexpected None: {:?}", msg),
50 }
51 }
52}
53
54impl<T, E: defmt::Format> Dewrap<T> for Result<T, E> {
55 fn dewrap(self) -> T {
56 match self {
57 Ok(t) => t,
58 Err(e) => depanic!("Dewrap failed: {:?}", e),
59 }
60 }
61
62 fn dexpect<M: defmt::Format>(self, msg: M) -> T {
63 match self {
64 Ok(t) => t,
65 Err(e) => depanic!("Unexpected error: {:?}: {:?}", msg, e),
66 }
67 }
68}