Skip to content

Commit

Permalink
start rust examples in linux
Browse files Browse the repository at this point in the history
  • Loading branch information
2bndy5 committed Jan 29, 2025
1 parent dfb5832 commit 284036f
Show file tree
Hide file tree
Showing 6 changed files with 79 additions and 67 deletions.
5 changes: 0 additions & 5 deletions examples/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,9 @@ rf24-rs = {path = "../../crates/rf24-rs"}
embedded-hal = "1.0.0"
anyhow = {version = "1.0.95", default-features = false }
linux-embedded-hal = {version = "0.4.0", optional = true}
embassy-rp = {version = "0.2.0", optional = true}
embassy-sync = {version = "0.6.1", optional = true}
embassy-embedded-hal = {version = "0.2.0", optional = true}

[features]
default = ["linux"]
# default = ["rp2040"]
rp2040 = ["dep:embassy-rp", "dep:embassy-sync", "dep:embassy-embedded-hal", "rf24-rs/defmt"]
linux = ["dep:linux-embedded-hal", "rf24-rs/std"]

[[bin]]
Expand Down
Empty file removed examples/rust/Embed.toml
Empty file.
2 changes: 0 additions & 2 deletions examples/rust/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#![no_std]
#[cfg(feature = "linux")]
pub mod linux;
#[cfg(feature = "rp2040")]
pub mod rp2040;
6 changes: 4 additions & 2 deletions examples/rust/src/linux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ pub struct BoardHardware {
gpio: Chip,
}

#[cfg(target_os = "linux")]
#[cfg(feature = "linux")]
extern crate std;
#[cfg(target_os = "linux")]
#[cfg(feature = "linux")]
use std::{format, string::ToString};
#[cfg(feature = "linux")]
pub use std::{print, println};

impl BoardHardware {
pub fn new(dev_gpio_chip: u8) -> Result<Self> {
Expand Down
91 changes: 75 additions & 16 deletions examples/rust/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
#![no_std]

use core::{f32, time::Duration};
use std::{io::Write, string::ToString};

use anyhow::{anyhow, Result};
use embedded_hal::delay::DelayNs;
use rf24::{
radio::{prelude::*, RF24},
PaLevel,
};
#[cfg(feature = "linux")]
use rf24_rs_examples::linux::{
BoardHardware, CdevPin as DigitalOutImpl, Delay as DelayImpl, SpidevDevice as SpiImpl,
print, println, BoardHardware, CdevPin as DigitalOutImpl, Delay as DelayImpl,
SpidevDevice as SpiImpl,
};
#[cfg(feature = "rp2040")]
use rf24_rs_examples::rp2040::BoardHardware;
#[cfg(feature = "linux")]
extern crate std;

/// A struct to drive our example app
struct App {
Expand Down Expand Up @@ -46,7 +49,7 @@ impl App {
/// Setup the radio for this example.
///
/// This will initialize and configure the [`App::radio`] object.
pub fn setup(&mut self) -> Result<()> {
pub fn setup(&mut self, radio_number: u8) -> Result<()> {
// initialize the radio hardware
self.radio.init().map_err(|e| anyhow!("{e:?}"))?;

Expand All @@ -62,10 +65,10 @@ impl App {

let address = [b"1Node", b"2Node"];
self.radio
.open_rx_pipe(1, address[0])
.open_rx_pipe(1, address[radio_number as usize])
.map_err(|e| anyhow!("{e:?}"))?;
self.radio
.open_tx_pipe(address[1])
.open_tx_pipe(address[1 - radio_number as usize])
.map_err(|e| anyhow!("{e:?}"))?;
Ok(())
}
Expand All @@ -79,14 +82,23 @@ impl App {
let mut remaining = count;
while remaining > 0 {
let buf = self.payload.to_le_bytes();
let start = std::time::Instant::now();
let result = self.radio.send(&buf, false).map_err(|e| anyhow!("{e:?}"))?;
let end = std::time::Instant::now();
if result {
// succeeded
println!(
"Transmission successful! Time to Transmit: {} us. Sent: {}",
end.saturating_duration_since(start).as_micros(),
self.payload
);
self.payload += 0.01;
} else {
// failed
println!("Transmission failed or timed out");
}
remaining -= 1;
DelayImpl.delay_ms(1000);
}
Ok(())
}
Expand All @@ -98,37 +110,84 @@ impl App {
let _end = Duration::from_secs(timeout as u64);
// put radio into active RX mode
self.radio.as_rx().map_err(|e| anyhow!("{e:?}"))?;
while false {
let mut end_time =
std::time::Instant::now() + std::time::Duration::from_secs(timeout as u64);
while std::time::Instant::now() < end_time {
let mut pipe = 15u8;
if self
.radio
.available_pipe(&mut pipe)
.map_err(|e| anyhow!("{e:?}"))?
{
let mut buf = [0u8; 4];
let _len = self
let len = self
.radio
.read(&mut buf, None)
.map_err(|e| anyhow!("{e:?}"))?;
// print pipe number and payload length
// print buf
self.payload = f32::from_le_bytes(buf);
// print pipe number and payload length and payload
print!("Received {len} bytes on pipe {pipe}: {}", self.payload);
// reset timeout
end_time =
std::time::Instant::now() + std::time::Duration::from_secs(timeout as u64);
}
}

// It is highly recommended to keep the radio idling in an inactive TX mode
self.radio.as_tx().map_err(|e| anyhow!("{e:?}"))?;
Ok(())
}

pub fn set_role(&mut self) -> Result<bool> {
let prompt = "*** Enter 'R' for receiver role.\n\
*** Enter 'T' for transmitter role.\n\
*** Enter 'Q' to quit example.";
println!("{prompt}");
let mut input = std::string::String::new();
std::io::stdin().read_line(&mut input)?;
let mut inputs = input.trim().split(' ');
let role = inputs
.next()
.map(|v| v.to_uppercase())
.unwrap_or("?".to_string());
if role.starts_with('T') {
let count = inputs
.next()
.map(|v| v.parse::<u8>().ok())
.flatten()
.unwrap_or(5);
self.tx(count)?;
return Ok(true);
} else if role.starts_with('R') {
let timeout = inputs
.next()
.map(|v| v.parse::<u8>().ok())
.flatten()
.unwrap_or(6);
self.rx(timeout)?;
return Ok(true);
} else if role.starts_with('Q') {
self.radio.power_down().map_err(|e| anyhow!("{e:?}"))?;
return Ok(false);
}
println!("{role} is an unrecognized input. Please try again.");
return Ok(true);
}
}

fn main() -> Result<()> {
let mut app = App::new()?;
app.setup()?;
if option_env!("ROLE").unwrap_or_default() == "master" {
app.tx(5)?;
} else {
app.rx(6)?;
}
let mut input = std::string::String::new();
print!("Which radio is this? Enter '0' or '1'. Defaults to '0' ");
std::io::stdout().flush()?;
std::io::stdin().read_line(&mut input)?;
let radio_number = input
.trim()
.chars()
.next()
.map(|c| if c == '1' { 1 } else { 0 })
.unwrap_or_default();
app.setup(radio_number)?;
while app.set_role()? {}
Ok(())
}
42 changes: 0 additions & 42 deletions examples/rust/src/rp2040.rs

This file was deleted.

0 comments on commit 284036f

Please sign in to comment.