Improved NFC reading speed

This commit is contained in:
2026-08-22 19:40:41 +02:00
parent b6f43d1055
commit ca3c3114fc
3 changed files with 13 additions and 57 deletions
+5 -2
View File
@@ -17,6 +17,7 @@ use creaturedex::navigation::inputs::Inputs;
use creaturedex::navigation::navigation::{self, CARD_DATA}; use creaturedex::navigation::navigation::{self, CARD_DATA};
use creaturedex::network::wifi::setup_wifi; use creaturedex::network::wifi::setup_wifi;
use embassy_executor::Spawner; use embassy_executor::Spawner;
use embassy_time::Instant;
use embedded_hal_bus::i2c::AtomicDevice; use embedded_hal_bus::i2c::AtomicDevice;
use embedded_hal_bus::util::AtomicCell; use embedded_hal_bus::util::AtomicCell;
use esp_hal::Blocking; use esp_hal::Blocking;
@@ -68,7 +69,7 @@ async fn main(spawner: Spawner) {
peripherals.GPIO12, // shared dc peripherals.GPIO12, // shared dc
))); )));
let config = I2cConfig::default().with_frequency(esp_hal::time::Rate::from_khz(20)); let config = I2cConfig::default().with_frequency(esp_hal::time::Rate::from_khz(400));
let i2c = match I2c::new(peripherals.I2C0, config) { let i2c = match I2c::new(peripherals.I2C0, config) {
Ok(bus) => bus.with_sda(peripherals.GPIO17).with_scl(peripherals.GPIO18), Ok(bus) => bus.with_sda(peripherals.GPIO17).with_scl(peripherals.GPIO18),
Err(e) => { Err(e) => {
@@ -113,14 +114,16 @@ async fn main(spawner: Spawner) {
async fn nfc_driver_task(mut nfc_driver: NfcPn532Driver<AtomicDevice<'static, I2c<'static, Blocking>>>) { async fn nfc_driver_task(mut nfc_driver: NfcPn532Driver<AtomicDevice<'static, I2c<'static, Blocking>>>) {
loop { loop {
while CARD_DATA.lock().await.is_none() { while CARD_DATA.lock().await.is_none() {
let start = Instant::now();
match nfc_driver.read_card_data().await { match nfc_driver.read_card_data().await {
Ok(card_data) => { Ok(card_data) => {
log::info!("NFC Card Data Read: {:?}", card_data);
let Some(split_data) = split_nfc_hex(&card_data) else { let Some(split_data) = split_nfc_hex(&card_data) else {
log::error!("Failed to split NFC card data"); log::error!("Failed to split NFC card data");
continue; continue;
}; };
CARD_DATA.lock().await.replace(Card::try_from(split_data).unwrap()); CARD_DATA.lock().await.replace(Card::try_from(split_data).unwrap());
let elapsed_ms = start.elapsed().as_millis();
log::info!("NFC read duration: {} ms, card data length: {}", elapsed_ms, card_data.len());
} }
Err(_) => { Err(_) => {
log::info!("No NFC card found"); log::info!("No NFC card found");
+8 -53
View File
@@ -7,53 +7,9 @@ use pn532::i2c::I2CInterface;
use pn532::requests::SAMMode; use pn532::requests::SAMMode;
use pn532::{nb, Pn532, Request}; use pn532::{nb, Pn532, Request};
/// Timer implementation required by `pn532::CountDown`. pub type Pn532Device<I2C> = Pn532<I2CInterface<I2C>, (), 34>;
pub struct TimerWrapper {
start: Instant,
duration: Duration,
counter: u32,
}
impl TimerWrapper { pub const PAGES_PER_READ: usize = 4;
pub fn new() -> Self {
Self {
start: Instant::now(),
duration: Duration::ZERO,
counter: 0,
}
}
}
impl Default for TimerWrapper {
fn default() -> Self {
Self::new()
}
}
impl pn532::CountDown for TimerWrapper {
type Time = Duration;
fn start<T>(&mut self, timeout: T)
where
T: Into<Self::Time>,
{
self.start = Instant::now();
self.duration = timeout.into();
self.counter = 0;
}
fn wait(&mut self) -> nb::Result<(), Infallible> {
let elapsed = self.start.elapsed();
self.counter += 1;
if elapsed >= self.duration {
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
}
}
pub type Pn532Device<I2C> = Pn532<I2CInterface<I2C>, (), 32>;
/// PN532 NFC reader driver. /// PN532 NFC reader driver.
pub struct NfcPn532Driver<I2C> pub struct NfcPn532Driver<I2C>
@@ -98,11 +54,12 @@ where
} }
} }
pub fn parse_nfc_page(iteration: u8, bytes: &[u8]) -> Result<[u8; 4], ()> { pub fn parse_nfc_page(iteration: u8, bytes: &[u8]) -> Result<[u8; PAGES_PER_READ * 4], ()> {
let success = bytes.first().is_some_and(|x| *x == 0); let success = bytes.first().is_some_and(|x| *x == 0);
if success { if success {
let mut arr = [0; 4]; let slice_len = bytes.len().min(PAGES_PER_READ * 4 + 1);
arr.copy_from_slice(&bytes[1..5]); let mut arr = [0; PAGES_PER_READ * 4];
arr[..slice_len - 1].copy_from_slice(&bytes[1..slice_len]);
Ok(arr) Ok(arr)
} else { } else {
info!("err {iteration}: {:02x?}", bytes); info!("err {iteration}: {:02x?}", bytes);
@@ -118,10 +75,10 @@ where
let mut data: Vec<u8> = Vec::with_capacity(858); let mut data: Vec<u8> = Vec::with_capacity(858);
for i in 0x0B..=230 { for i in (0x0B..=230).step_by(PAGES_PER_READ) {
let mut parse_result = Err(()); let mut parse_result = Err(());
while parse_result.is_err() { while parse_result.is_err() {
let Ok(result) = self.pn532.process_async(&Request::ntag_read(i), 17).await else { let Ok(result) = self.pn532.process_async(&Request::ntag_read(i), PAGES_PER_READ * 4 + 1).await else {
continue; continue;
}; };
parse_result = Self::parse_nfc_page(i, result); parse_result = Self::parse_nfc_page(i, result);
@@ -134,8 +91,6 @@ where
}; };
data.extend(bytes); data.extend(bytes);
} }
info!("PN532 full card payload read over I2C: {:02x?}", data);
Ok(data) Ok(data)
} }
-2
View File
@@ -87,9 +87,7 @@ impl Navigable for ScanMenu {
fn handle_input(&self, input: Action) -> impl core::future::Future<Output = NewState> + Send { fn handle_input(&self, input: Action) -> impl core::future::Future<Output = NewState> + Send {
async move { async move {
log::info!("Scan view detected, checking for NFC card data");
if let Some(card_data) = CARD_DATA.lock().await.take() { if let Some(card_data) = CARD_DATA.lock().await.take() {
log::info!("NFC Card to be displayed: {:?}", card_data);
NewState { NewState {
view: View::Card(crate::views::card_view::CardView { card: card_data }), view: View::Card(crate::views::card_view::CardView { card: card_data }),
replace_view: true, replace_view: true,