aboutsummaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorDario Nieuwenhuis <[email protected]>2021-07-01 01:55:55 +0200
committerGitHub <[email protected]>2021-07-01 01:55:55 +0200
commite55c89f890d6ca6eaf568e1f701643525c999ebc (patch)
treef205fa33083c39768ebb0ed203976f2c128b70f3 /examples
parent334c3a44a42873b6d60d7020ece3f8e90870796f (diff)
parent99339e940e568c08329bce9e93a36fb79a21685d (diff)
Merge pull request #262 from Liamolucko/nrf-rng
Add an nRF RNG driver
Diffstat (limited to 'examples')
-rw-r--r--examples/nrf/Cargo.toml1
-rw-r--r--examples/nrf/src/bin/rng.rs43
2 files changed, 44 insertions, 0 deletions
diff --git a/examples/nrf/Cargo.toml b/examples/nrf/Cargo.toml
index fa1dab360..8db0ad53f 100644
--- a/examples/nrf/Cargo.toml
+++ b/examples/nrf/Cargo.toml
@@ -29,3 +29,4 @@ cortex-m-rt = "0.6.13"
29embedded-hal = { version = "0.2.4" } 29embedded-hal = { version = "0.2.4" }
30panic-probe = { version = "0.2.0", features = ["print-defmt"] } 30panic-probe = { version = "0.2.0", features = ["print-defmt"] }
31futures = { version = "0.3.8", default-features = false, features = ["async-await"] } 31futures = { version = "0.3.8", default-features = false, features = ["async-await"] }
32rand = { version = "0.8.4", default-features = false }
diff --git a/examples/nrf/src/bin/rng.rs b/examples/nrf/src/bin/rng.rs
new file mode 100644
index 000000000..6aa43d0db
--- /dev/null
+++ b/examples/nrf/src/bin/rng.rs
@@ -0,0 +1,43 @@
1#![no_std]
2#![no_main]
3#![feature(min_type_alias_impl_trait)]
4#![feature(impl_trait_in_bindings)]
5#![feature(type_alias_impl_trait)]
6#![allow(incomplete_features)]
7
8#[path = "../example_common.rs"]
9mod example_common;
10
11use defmt::panic;
12use embassy::executor::Spawner;
13use embassy::traits::rng::Rng as _;
14use embassy_nrf::interrupt;
15use embassy_nrf::rng::Rng;
16use embassy_nrf::Peripherals;
17use rand::Rng as _;
18
19#[embassy::main]
20async fn main(_spawner: Spawner, p: Peripherals) {
21 let mut rng = unsafe { Rng::new(p.RNG, interrupt::take!(RNG)) };
22
23 // Async API
24 let mut bytes = [0; 4];
25 rng.fill_bytes(&mut bytes).await.unwrap(); // nRF RNG is infallible
26 defmt::info!("Some random bytes: {:?}", bytes);
27
28 // Sync API with `rand`
29 defmt::info!("A random number from 1 to 10: {:?}", rng.gen_range(1..=10));
30
31 let mut bytes = [0; 1024];
32 rng.fill_bytes(&mut bytes).await.unwrap();
33 let zero_count: u32 = bytes.iter().fold(0, |acc, val| acc + val.count_zeros());
34 let one_count: u32 = bytes.iter().fold(0, |acc, val| acc + val.count_ones());
35 defmt::info!(
36 "Chance of zero: {}%",
37 zero_count * 100 / (bytes.len() as u32 * 8)
38 );
39 defmt::info!(
40 "Chance of one: {}%",
41 one_count * 100 / (bytes.len() as u32 * 8)
42 );
43}