Skip to content

Commit

Permalink
Merge pull request #29 from BradenEverson/feat/async-lidar-reads
Browse files Browse the repository at this point in the history
Feat: async lidar reads
  • Loading branch information
BradenEverson authored Oct 13, 2024
2 parents e9a8570 + 516e5d4 commit 0087f62
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
5 changes: 5 additions & 0 deletions rplidar-rppal/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,8 @@ categories = ["embedded", "hardware-support"]

[dependencies]
rppal = "0.19.0"
tokio = { version = "1.40.0", features = ["full"], optional = true}

[features]
default = ["tokio"]
tokio = ["dep:tokio"]
4 changes: 2 additions & 2 deletions rplidar-rppal/examples/hello_lidar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ fn main() {
uart.set_read_mode(255, Duration::from_millis(500))
.expect("Failed to set timeout");

let lidar = RpLidarA1::new(uart, motor_pin);
let mut lidar = RpLidarA1::new(uart, motor_pin);
lidar.run_with_callback(parse_scan_data);
}

/// Scans the lidar data and prints the readings to the console
pub fn parse_scan_data(data: &[u8]) {
pub fn parse_scan_data(data: [u8; 255], _read: u8) {
if data.len() < 5 {
return;
}
Expand Down
18 changes: 16 additions & 2 deletions rplidar-rppal/src/rplidar_a1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ impl RpLidarA1 {
/// Continously reads lidar data until a failure happens. Pipes the data through to a
/// `response_callback` function that does something to a `&[u8]` allowing fine-grained control
/// over data response
pub fn run_with_callback<FN: Fn(&[u8])>(mut self, response_callback: FN) {
pub fn run_with_callback<FN: Fn([u8; 255], u8)>(&mut self, response_callback: FN) {
self.motor.set_high();

self.send_command(Command::Reset);
Expand All @@ -63,12 +63,26 @@ impl RpLidarA1 {
let mut buffer: [u8; 255] = [0; 255];
loop {
match self.uart.read(&mut buffer) {
Ok(bytes_read) if bytes_read > 0 => response_callback(&buffer),
Ok(bytes_read) if bytes_read > 0 => response_callback(buffer, bytes_read as u8),
_ => break,
}
}

self.motor.set_low();
self.send_command(Command::Stop);
}

#[cfg(feature = "tokio")]
pub fn run_with_channel(&mut self) -> tokio::sync::mpsc::UnboundedReceiver<([u8; 255], u8)> {
let (writer, reader) = tokio::sync::mpsc::unbounded_channel();

let handler = move |buf: [u8; 255], read: u8| {
let writer = writer.clone();
writer.send((buf, read)).expect("Failed to send");
};

self.run_with_callback(handler);

reader
}
}

0 comments on commit 0087f62

Please sign in to comment.