Skip to content

Commit aad5fb9

Browse files
author
Henrik Alsér
committed
Twim write/write_read: Implicitly copy buffer into RAM if needed when using embedded hal traits
1 parent 1afbb8e commit aad5fb9

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

nrf-hal-common/src/twim.rs

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ use crate::target::TWIM1;
1919
use crate::{
2020
gpio::{Floating, Input, Pin},
2121
slice_in_ram_or,
22-
target_constants::EASY_DMA_SIZE,
22+
slice_in_ram,
23+
target_constants::{EASY_DMA_SIZE, FORCE_COPY_BUFFER_SIZE},
2324
};
2425

2526
pub use twim0::frequency::FREQUENCY_A as Frequency;
@@ -348,7 +349,17 @@ where
348349
type Error = Error;
349350

350351
fn write<'w>(&mut self, addr: u8, bytes: &'w [u8]) -> Result<(), Error> {
351-
self.write(addr, bytes)
352+
if slice_in_ram(bytes){
353+
self.write(addr, bytes)
354+
}
355+
else {
356+
let buf = &mut [0; FORCE_COPY_BUFFER_SIZE][..];
357+
for chunk in bytes.chunks(FORCE_COPY_BUFFER_SIZE) {
358+
buf[..chunk.len()].copy_from_slice(chunk);
359+
self.write(addr, &buf[..chunk.len()])?;
360+
}
361+
Ok(())
362+
}
352363
}
353364
}
354365

@@ -375,11 +386,22 @@ where
375386
bytes: &'w [u8],
376387
buffer: &'w mut [u8],
377388
) -> Result<(), Error> {
378-
self.write_then_read(addr, bytes, buffer)
389+
if slice_in_ram(bytes){
390+
self.write_then_read(addr, bytes, buffer)
391+
} else {
392+
let txi = bytes.chunks(FORCE_COPY_BUFFER_SIZE);
393+
let rxi = buffer.chunks_mut(FORCE_COPY_BUFFER_SIZE);
394+
let tx_buf = &mut [0; FORCE_COPY_BUFFER_SIZE][..];
395+
txi.zip(rxi).try_for_each(|(tx_chunk, rx_chunk)| {
396+
tx_buf[..tx_chunk.len()].copy_from_slice(tx_chunk);
397+
self.write_then_read(addr, &tx_buf[..tx_chunk.len()], rx_chunk)
398+
})?;
399+
Ok(())
400+
}
379401
}
380402
}
381403

382-
/// The pins used by the TWIN peripheral
404+
/// The pins used by the TWIM peripheral
383405
///
384406
/// Currently, only P0 pins are supported.
385407
pub struct Pins {

0 commit comments

Comments
 (0)