diff --git a/embassy-lora/Cargo.toml b/embassy-lora/Cargo.toml index 50449dd4..692a8204 100644 --- a/embassy-lora/Cargo.toml +++ b/embassy-lora/Cargo.toml @@ -22,6 +22,7 @@ sx127x = [] stm32wl = ["dep:embassy-stm32"] time = [] defmt = ["dep:defmt", "lorawan/defmt", "lorawan-device/defmt"] +external-lora-phy = ["dep:lora-phy"] [dependencies] @@ -38,5 +39,6 @@ futures = { version = "0.3.17", default-features = false, features = [ "async-aw embedded-hal = { version = "0.2", features = ["unproven"] } bit_field = { version = "0.10" } -lorawan-device = { version = "0.9.0", default-features = false, features = ["async"] } -lorawan = { version = "0.7.2", default-features = false } +lora-phy = { version = "1", optional = true } +lorawan-device = { version = "0.10.0", default-features = false, features = ["async"] } +lorawan = { version = "0.7.3", default-features = false } diff --git a/embassy-lora/src/iv.rs b/embassy-lora/src/iv.rs new file mode 100644 index 00000000..f8113440 --- /dev/null +++ b/embassy-lora/src/iv.rs @@ -0,0 +1,325 @@ +#[cfg(feature = "stm32wl")] +use embassy_stm32::interrupt::*; +#[cfg(feature = "stm32wl")] +use embassy_stm32::{pac, PeripheralRef}; +#[cfg(feature = "stm32wl")] +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +#[cfg(feature = "stm32wl")] +use embassy_sync::signal::Signal; +use embedded_hal::digital::v2::OutputPin; +use embedded_hal_async::delay::DelayUs; +use embedded_hal_async::digital::Wait; +use lora_phy::mod_params::RadioError::*; +use lora_phy::mod_params::{BoardType, RadioError}; +use lora_phy::mod_traits::InterfaceVariant; + +#[cfg(feature = "stm32wl")] +static IRQ_SIGNAL: Signal = Signal::new(); + +#[cfg(feature = "stm32wl")] +/// Base for the InterfaceVariant implementation for an stm32wl/sx1262 combination +pub struct Stm32wlInterfaceVariant<'a, CTRL> { + board_type: BoardType, + irq: PeripheralRef<'a, SUBGHZ_RADIO>, + rf_switch_rx: Option, + rf_switch_tx: Option, +} + +#[cfg(feature = "stm32wl")] +impl<'a, CTRL> Stm32wlInterfaceVariant<'a, CTRL> +where + CTRL: OutputPin, +{ + /// Create an InterfaceVariant instance for an stm32wl/sx1262 combination + pub fn new( + irq: PeripheralRef<'a, SUBGHZ_RADIO>, + rf_switch_rx: Option, + rf_switch_tx: Option, + ) -> Result { + irq.disable(); + irq.set_handler(Self::on_interrupt); + Ok(Self { + board_type: BoardType::Stm32wlSx1262, // updated when associated with a specific LoRa board + irq, + rf_switch_rx, + rf_switch_tx, + }) + } + + fn on_interrupt(_: *mut ()) { + unsafe { SUBGHZ_RADIO::steal() }.disable(); + IRQ_SIGNAL.signal(()); + } +} + +#[cfg(feature = "stm32wl")] +impl InterfaceVariant for Stm32wlInterfaceVariant<'_, CTRL> +where + CTRL: OutputPin, +{ + fn set_board_type(&mut self, board_type: BoardType) { + self.board_type = board_type; + } + async fn set_nss_low(&mut self) -> Result<(), RadioError> { + let pwr = pac::PWR; + unsafe { + pwr.subghzspicr().modify(|w| w.set_nss(pac::pwr::vals::Nss::LOW)); + } + Ok(()) + } + async fn set_nss_high(&mut self) -> Result<(), RadioError> { + let pwr = pac::PWR; + unsafe { + pwr.subghzspicr().modify(|w| w.set_nss(pac::pwr::vals::Nss::HIGH)); + } + Ok(()) + } + async fn reset(&mut self, _delay: &mut impl DelayUs) -> Result<(), RadioError> { + let rcc = pac::RCC; + unsafe { + rcc.csr().modify(|w| w.set_rfrst(true)); + rcc.csr().modify(|w| w.set_rfrst(false)); + } + Ok(()) + } + async fn wait_on_busy(&mut self) -> Result<(), RadioError> { + let pwr = pac::PWR; + while unsafe { pwr.sr2().read().rfbusys() == pac::pwr::vals::Rfbusys::BUSY } {} + Ok(()) + } + + async fn await_irq(&mut self) -> Result<(), RadioError> { + self.irq.enable(); + IRQ_SIGNAL.wait().await; + Ok(()) + } + + async fn enable_rf_switch_rx(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_tx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchTx)?, + None => (), + }; + match &mut self.rf_switch_rx { + Some(pin) => pin.set_high().map_err(|_| RfSwitchRx), + None => Ok(()), + } + } + async fn enable_rf_switch_tx(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_rx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchRx)?, + None => (), + }; + match &mut self.rf_switch_tx { + Some(pin) => pin.set_high().map_err(|_| RfSwitchTx), + None => Ok(()), + } + } + async fn disable_rf_switch(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_rx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchRx)?, + None => (), + }; + match &mut self.rf_switch_tx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchTx), + None => Ok(()), + } + } +} + +/// Base for the InterfaceVariant implementation for an stm32l0/sx1276 combination +pub struct Stm32l0InterfaceVariant { + board_type: BoardType, + nss: CTRL, + reset: CTRL, + irq: WAIT, + rf_switch_rx: Option, + rf_switch_tx: Option, +} + +impl Stm32l0InterfaceVariant +where + CTRL: OutputPin, + WAIT: Wait, +{ + /// Create an InterfaceVariant instance for an stm32l0/sx1276 combination + pub fn new( + nss: CTRL, + reset: CTRL, + irq: WAIT, + rf_switch_rx: Option, + rf_switch_tx: Option, + ) -> Result { + Ok(Self { + board_type: BoardType::Stm32l0Sx1276, // updated when associated with a specific LoRa board + nss, + reset, + irq, + rf_switch_rx, + rf_switch_tx, + }) + } +} + +impl InterfaceVariant for Stm32l0InterfaceVariant +where + CTRL: OutputPin, + WAIT: Wait, +{ + fn set_board_type(&mut self, board_type: BoardType) { + self.board_type = board_type; + } + async fn set_nss_low(&mut self) -> Result<(), RadioError> { + self.nss.set_low().map_err(|_| NSS) + } + async fn set_nss_high(&mut self) -> Result<(), RadioError> { + self.nss.set_high().map_err(|_| NSS) + } + async fn reset(&mut self, delay: &mut impl DelayUs) -> Result<(), RadioError> { + delay.delay_ms(10).await; + self.reset.set_low().map_err(|_| Reset)?; + delay.delay_ms(10).await; + self.reset.set_high().map_err(|_| Reset)?; + delay.delay_ms(10).await; + Ok(()) + } + async fn wait_on_busy(&mut self) -> Result<(), RadioError> { + Ok(()) + } + async fn await_irq(&mut self) -> Result<(), RadioError> { + self.irq.wait_for_high().await.map_err(|_| Irq) + } + + async fn enable_rf_switch_rx(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_tx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchTx)?, + None => (), + }; + match &mut self.rf_switch_rx { + Some(pin) => pin.set_high().map_err(|_| RfSwitchRx), + None => Ok(()), + } + } + async fn enable_rf_switch_tx(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_rx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchRx)?, + None => (), + }; + match &mut self.rf_switch_tx { + Some(pin) => pin.set_high().map_err(|_| RfSwitchTx), + None => Ok(()), + } + } + async fn disable_rf_switch(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_rx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchRx)?, + None => (), + }; + match &mut self.rf_switch_tx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchTx), + None => Ok(()), + } + } +} + +/// Base for the InterfaceVariant implementation for a generic Sx126x LoRa board +pub struct GenericSx126xInterfaceVariant { + board_type: BoardType, + nss: CTRL, + reset: CTRL, + dio1: WAIT, + busy: WAIT, + rf_switch_rx: Option, + rf_switch_tx: Option, +} + +impl GenericSx126xInterfaceVariant +where + CTRL: OutputPin, + WAIT: Wait, +{ + /// Create an InterfaceVariant instance for an nrf52840/sx1262 combination + pub fn new( + nss: CTRL, + reset: CTRL, + dio1: WAIT, + busy: WAIT, + rf_switch_rx: Option, + rf_switch_tx: Option, + ) -> Result { + Ok(Self { + board_type: BoardType::Rak4631Sx1262, // updated when associated with a specific LoRa board + nss, + reset, + dio1, + busy, + rf_switch_rx, + rf_switch_tx, + }) + } +} + +impl InterfaceVariant for GenericSx126xInterfaceVariant +where + CTRL: OutputPin, + WAIT: Wait, +{ + fn set_board_type(&mut self, board_type: BoardType) { + self.board_type = board_type; + } + async fn set_nss_low(&mut self) -> Result<(), RadioError> { + self.nss.set_low().map_err(|_| NSS) + } + async fn set_nss_high(&mut self) -> Result<(), RadioError> { + self.nss.set_high().map_err(|_| NSS) + } + async fn reset(&mut self, delay: &mut impl DelayUs) -> Result<(), RadioError> { + delay.delay_ms(10).await; + self.reset.set_low().map_err(|_| Reset)?; + delay.delay_ms(20).await; + self.reset.set_high().map_err(|_| Reset)?; + delay.delay_ms(10).await; + Ok(()) + } + async fn wait_on_busy(&mut self) -> Result<(), RadioError> { + self.busy.wait_for_low().await.map_err(|_| Busy) + } + async fn await_irq(&mut self) -> Result<(), RadioError> { + if self.board_type != BoardType::RpPicoWaveshareSx1262 { + self.dio1.wait_for_high().await.map_err(|_| DIO1)?; + } else { + self.dio1.wait_for_rising_edge().await.map_err(|_| DIO1)?; + } + Ok(()) + } + + async fn enable_rf_switch_rx(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_tx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchTx)?, + None => (), + }; + match &mut self.rf_switch_rx { + Some(pin) => pin.set_high().map_err(|_| RfSwitchRx), + None => Ok(()), + } + } + async fn enable_rf_switch_tx(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_rx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchRx)?, + None => (), + }; + match &mut self.rf_switch_tx { + Some(pin) => pin.set_high().map_err(|_| RfSwitchTx), + None => Ok(()), + } + } + async fn disable_rf_switch(&mut self) -> Result<(), RadioError> { + match &mut self.rf_switch_rx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchRx)?, + None => (), + }; + match &mut self.rf_switch_tx { + Some(pin) => pin.set_low().map_err(|_| RfSwitchTx), + None => Ok(()), + } + } +} diff --git a/embassy-lora/src/lib.rs b/embassy-lora/src/lib.rs index 5c919cbb..c01d3f71 100644 --- a/embassy-lora/src/lib.rs +++ b/embassy-lora/src/lib.rs @@ -5,12 +5,18 @@ //! crate's async LoRaWAN MAC implementation. pub(crate) mod fmt; +#[cfg(feature = "external-lora-phy")] +/// interface variants required by the external lora crate +pub mod iv; #[cfg(feature = "stm32wl")] +#[deprecated(note = "use the external LoRa physical layer crate - https://crates.io/crates/lora-phy")] pub mod stm32wl; #[cfg(feature = "sx126x")] +#[deprecated(note = "use the external LoRa physical layer crate - https://crates.io/crates/lora-phy")] pub mod sx126x; #[cfg(feature = "sx127x")] +#[deprecated(note = "use the external LoRa physical layer crate - https://crates.io/crates/lora-phy")] pub mod sx127x; #[cfg(feature = "time")] diff --git a/embassy-lora/src/stm32wl/mod.rs b/embassy-lora/src/stm32wl/mod.rs index d76e8c43..dae9a195 100644 --- a/embassy-lora/src/stm32wl/mod.rs +++ b/embassy-lora/src/stm32wl/mod.rs @@ -1,4 +1,5 @@ //! A radio driver integration for the radio found on STM32WL family devices. +#![allow(deprecated)] use core::future::poll_fn; use core::task::Poll; diff --git a/embassy-stm32/src/lib.rs b/embassy-stm32/src/lib.rs index bbde2da5..f0fc152c 100644 --- a/embassy-stm32/src/lib.rs +++ b/embassy-stm32/src/lib.rs @@ -56,6 +56,7 @@ pub mod sdmmc; #[cfg(spi)] pub mod spi; #[cfg(stm32wl)] +#[deprecated(note = "use the external LoRa physical layer crate - https://crates.io/crates/lora-phy")] pub mod subghz; #[cfg(usart)] pub mod usart; diff --git a/embassy-stm32/src/spi/mod.rs b/embassy-stm32/src/spi/mod.rs index 492d0649..aefa4243 100644 --- a/embassy-stm32/src/spi/mod.rs +++ b/embassy-stm32/src/spi/mod.rs @@ -197,7 +197,7 @@ impl<'d, T: Instance, Tx, Rx> Spi<'d, T, Tx, Rx> { /// Useful for on chip peripherals like SUBGHZ which are hardwired. /// The bus can optionally be exposed externally with `Spi::new()` still. #[allow(dead_code)] - pub(crate) fn new_internal( + pub fn new_subghz( peri: impl Peripheral

+ 'd, txdma: impl Peripheral

+ 'd, rxdma: impl Peripheral

+ 'd, diff --git a/embassy-stm32/src/subghz/mod.rs b/embassy-stm32/src/subghz/mod.rs index 33398fa1..cd566ba2 100644 --- a/embassy-stm32/src/subghz/mod.rs +++ b/embassy-stm32/src/subghz/mod.rs @@ -224,7 +224,7 @@ impl<'d, Tx, Rx> SubGhz<'d, Tx, Rx> { let mut config = SpiConfig::default(); config.mode = MODE_0; config.bit_order = BitOrder::MsbFirst; - let spi = Spi::new_internal(peri, txdma, rxdma, clk, config); + let spi = Spi::new_subghz(peri, txdma, rxdma, clk, config); unsafe { wakeup() }; diff --git a/examples/nrf52840/Cargo.toml b/examples/nrf52840/Cargo.toml index 10c269a7..59f30a9b 100644 --- a/examples/nrf52840/Cargo.toml +++ b/examples/nrf52840/Cargo.toml @@ -6,8 +6,8 @@ license = "MIT OR Apache-2.0" [features] default = ["nightly"] -nightly = ["embassy-executor/nightly", "embassy-nrf/nightly", "embassy-net/nightly", "embassy-nrf/unstable-traits", "embassy-usb", "embedded-io/async", "embassy-net", - "embassy-lora", "lorawan-device", "lorawan"] +nightly = ["embassy-executor/nightly", "embassy-nrf/nightly", "embassy-net/nightly", "embassy-nrf/unstable-traits", "embassy-time/nightly", "embassy-time/unstable-traits", + "embassy-usb", "embedded-io/async", "embassy-net", "embassy-lora", "lora-phy", "lorawan-device", "lorawan"] [dependencies] embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } @@ -18,10 +18,10 @@ embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defm embassy-net = { version = "0.1.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet"], optional = true } embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt", "msos-descriptor",], optional = true } embedded-io = "0.4.0" -embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["sx126x", "time", "defmt"], optional = true } - -lorawan-device = { version = "0.9.0", default-features = false, features = ["async"], optional = true } -lorawan = { version = "0.7.2", default-features = false, features = ["default-crypto"], optional = true } +embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["sx126x", "time", "defmt", "external-lora-phy"], optional = true } +lora-phy = { version = "1", optional = true } +lorawan-device = { version = "0.10.0", default-features = false, features = ["async", "external-lora-phy"], optional = true } +lorawan = { version = "0.7.3", default-features = false, features = ["default-crypto"], optional = true } defmt = "0.3" defmt-rtt = "0.4" diff --git a/examples/nrf52840/src/bin/lora_cad.rs b/examples/nrf52840/src/bin/lora_cad.rs new file mode 100644 index 00000000..beca061e --- /dev/null +++ b/examples/nrf52840/src/bin/lora_cad.rs @@ -0,0 +1,99 @@ +//! This example runs on the RAK4631 WisBlock, which has an nRF52840 MCU and Semtech Sx126x radio. +//! Other nrf/sx126x combinations may work with appropriate pin modifications. +//! It demonstrates LORA CAD functionality. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_lora::iv::GenericSx126xInterfaceVariant; +use embassy_nrf::gpio::{Input, Level, Output, OutputDrive, Pin as _, Pull}; +use embassy_nrf::{bind_interrupts, peripherals, spim}; +use embassy_time::{Delay, Duration, Timer}; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +const LORA_FREQUENCY_IN_HZ: u32 = 903_900_000; // warning: set this appropriately for the region + +bind_interrupts!(struct Irqs { + SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1 => spim::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_nrf::init(Default::default()); + let mut spi_config = spim::Config::default(); + spi_config.frequency = spim::Frequency::M16; + + let spim = spim::Spim::new(p.TWISPI1, Irqs, p.P1_11, p.P1_13, p.P1_12, spi_config); + + let nss = Output::new(p.P1_10.degrade(), Level::High, OutputDrive::Standard); + let reset = Output::new(p.P1_06.degrade(), Level::High, OutputDrive::Standard); + let dio1 = Input::new(p.P1_15.degrade(), Pull::Down); + let busy = Input::new(p.P1_14.degrade(), Pull::Down); + let rf_switch_rx = Output::new(p.P1_05.degrade(), Level::Low, OutputDrive::Standard); + let rf_switch_tx = Output::new(p.P1_07.degrade(), Level::Low, OutputDrive::Standard); + + let iv = + GenericSx126xInterfaceVariant::new(nss, reset, dio1, busy, Some(rf_switch_rx), Some(rf_switch_tx)).unwrap(); + + let mut delay = Delay; + + let mut lora = { + match LoRa::new(SX1261_2::new(BoardType::Rak4631Sx1262, spim, iv), false, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut debug_indicator = Output::new(p.P1_03, Level::Low, OutputDrive::Standard); + let mut start_indicator = Output::new(p.P1_04, Level::Low, OutputDrive::Standard); + + start_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + start_indicator.set_low(); + + let mdltn_params = { + match lora.create_modulation_params( + SpreadingFactor::_10, + Bandwidth::_250KHz, + CodingRate::_4_8, + LORA_FREQUENCY_IN_HZ, + ) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + match lora.prepare_for_cad(&mdltn_params, true).await { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + match lora.cad().await { + Ok(cad_activity_detected) => { + if cad_activity_detected { + info!("cad successful with activity detected") + } else { + info!("cad successful without activity detected") + } + debug_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + debug_indicator.set_low(); + } + Err(err) => info!("cad unsuccessful = {}", err), + } +} diff --git a/examples/nrf52840/src/bin/lora_lorawan.rs b/examples/nrf52840/src/bin/lora_lorawan.rs new file mode 100644 index 00000000..c953680c --- /dev/null +++ b/examples/nrf52840/src/bin/lora_lorawan.rs @@ -0,0 +1,83 @@ +//! This example runs on the RAK4631 WisBlock, which has an nRF52840 MCU and Semtech Sx126x radio. +//! Other nrf/sx126x combinations may work with appropriate pin modifications. +//! It demonstrates LoRaWAN join functionality. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_lora::iv::GenericSx126xInterfaceVariant; +use embassy_lora::LoraTimer; +use embassy_nrf::gpio::{Input, Level, Output, OutputDrive, Pin as _, Pull}; +use embassy_nrf::rng::Rng; +use embassy_nrf::{bind_interrupts, peripherals, rng, spim}; +use embassy_time::Delay; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use lorawan::default_crypto::DefaultFactory as Crypto; +use lorawan_device::async_device::lora_radio::LoRaRadio; +use lorawan_device::async_device::{region, Device, JoinMode}; +use {defmt_rtt as _, panic_probe as _}; + +const LORAWAN_REGION: region::Region = region::Region::EU868; // warning: set this appropriately for the region + +bind_interrupts!(struct Irqs { + SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1 => spim::InterruptHandler; + RNG => rng::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_nrf::init(Default::default()); + let mut spi_config = spim::Config::default(); + spi_config.frequency = spim::Frequency::M16; + + let spim = spim::Spim::new(p.TWISPI1, Irqs, p.P1_11, p.P1_13, p.P1_12, spi_config); + + let nss = Output::new(p.P1_10.degrade(), Level::High, OutputDrive::Standard); + let reset = Output::new(p.P1_06.degrade(), Level::High, OutputDrive::Standard); + let dio1 = Input::new(p.P1_15.degrade(), Pull::Down); + let busy = Input::new(p.P1_14.degrade(), Pull::Down); + let rf_switch_rx = Output::new(p.P1_05.degrade(), Level::Low, OutputDrive::Standard); + let rf_switch_tx = Output::new(p.P1_07.degrade(), Level::Low, OutputDrive::Standard); + + let iv = + GenericSx126xInterfaceVariant::new(nss, reset, dio1, busy, Some(rf_switch_rx), Some(rf_switch_tx)).unwrap(); + + let mut delay = Delay; + + let lora = { + match LoRa::new(SX1261_2::new(BoardType::Rak4631Sx1262, spim, iv), true, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let radio = LoRaRadio::new(lora); + let region: region::Configuration = region::Configuration::new(LORAWAN_REGION); + let mut device: Device<_, Crypto, _, _> = Device::new(region, radio, LoraTimer::new(), Rng::new(p.RNG, Irqs)); + + defmt::info!("Joining LoRaWAN network"); + + // TODO: Adjust the EUI and Keys according to your network credentials + match device + .join(&JoinMode::OTAA { + deveui: [0, 0, 0, 0, 0, 0, 0, 0], + appeui: [0, 0, 0, 0, 0, 0, 0, 0], + appkey: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + }) + .await + { + Ok(()) => defmt::info!("LoRaWAN network joined"), + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; +} diff --git a/examples/nrf52840/src/bin/lora_p2p_receive.rs b/examples/nrf52840/src/bin/lora_p2p_receive.rs new file mode 100644 index 00000000..563fe42e --- /dev/null +++ b/examples/nrf52840/src/bin/lora_p2p_receive.rs @@ -0,0 +1,121 @@ +//! This example runs on the RAK4631 WisBlock, which has an nRF52840 MCU and Semtech Sx126x radio. +//! Other nrf/sx126x combinations may work with appropriate pin modifications. +//! It demonstrates LORA P2P receive functionality in conjunction with the lora_p2p_send example. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_lora::iv::GenericSx126xInterfaceVariant; +use embassy_nrf::gpio::{Input, Level, Output, OutputDrive, Pin as _, Pull}; +use embassy_nrf::{bind_interrupts, peripherals, spim}; +use embassy_time::{Delay, Duration, Timer}; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +const LORA_FREQUENCY_IN_HZ: u32 = 903_900_000; // warning: set this appropriately for the region + +bind_interrupts!(struct Irqs { + SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1 => spim::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_nrf::init(Default::default()); + let mut spi_config = spim::Config::default(); + spi_config.frequency = spim::Frequency::M16; + + let spim = spim::Spim::new(p.TWISPI1, Irqs, p.P1_11, p.P1_13, p.P1_12, spi_config); + + let nss = Output::new(p.P1_10.degrade(), Level::High, OutputDrive::Standard); + let reset = Output::new(p.P1_06.degrade(), Level::High, OutputDrive::Standard); + let dio1 = Input::new(p.P1_15.degrade(), Pull::Down); + let busy = Input::new(p.P1_14.degrade(), Pull::Down); + let rf_switch_rx = Output::new(p.P1_05.degrade(), Level::Low, OutputDrive::Standard); + let rf_switch_tx = Output::new(p.P1_07.degrade(), Level::Low, OutputDrive::Standard); + + let iv = + GenericSx126xInterfaceVariant::new(nss, reset, dio1, busy, Some(rf_switch_rx), Some(rf_switch_tx)).unwrap(); + + let mut delay = Delay; + + let mut lora = { + match LoRa::new(SX1261_2::new(BoardType::Rak4631Sx1262, spim, iv), false, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut debug_indicator = Output::new(p.P1_03, Level::Low, OutputDrive::Standard); + let mut start_indicator = Output::new(p.P1_04, Level::Low, OutputDrive::Standard); + + start_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + start_indicator.set_low(); + + let mut receiving_buffer = [00u8; 100]; + + let mdltn_params = { + match lora.create_modulation_params( + SpreadingFactor::_10, + Bandwidth::_250KHz, + CodingRate::_4_8, + LORA_FREQUENCY_IN_HZ, + ) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let rx_pkt_params = { + match lora.create_rx_packet_params(4, false, receiving_buffer.len() as u8, true, false, &mdltn_params) { + Ok(pp) => pp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + match lora + .prepare_for_rx(&mdltn_params, &rx_pkt_params, None, true, false, 0, 0x00ffffffu32) + .await + { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + loop { + receiving_buffer = [00u8; 100]; + match lora.rx(&rx_pkt_params, &mut receiving_buffer).await { + Ok((received_len, _rx_pkt_status)) => { + if (received_len == 3) + && (receiving_buffer[0] == 0x01u8) + && (receiving_buffer[1] == 0x02u8) + && (receiving_buffer[2] == 0x03u8) + { + info!("rx successful"); + debug_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + debug_indicator.set_low(); + } else { + info!("rx unknown packet"); + } + } + Err(err) => info!("rx unsuccessful = {}", err), + } + } +} diff --git a/examples/nrf52840/src/bin/lora_p2p_receive_duty_cycle.rs b/examples/nrf52840/src/bin/lora_p2p_receive_duty_cycle.rs new file mode 100644 index 00000000..1fd8f61a --- /dev/null +++ b/examples/nrf52840/src/bin/lora_p2p_receive_duty_cycle.rs @@ -0,0 +1,131 @@ +//! This example runs on the RAK4631 WisBlock, which has an nRF52840 MCU and Semtech Sx126x radio. +//! Other nrf/sx126x combinations may work with appropriate pin modifications. +//! It demonstrates LoRa Rx duty cycle functionality in conjunction with the lora_p2p_send example. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_lora::iv::GenericSx126xInterfaceVariant; +use embassy_nrf::gpio::{Input, Level, Output, OutputDrive, Pin as _, Pull}; +use embassy_nrf::{bind_interrupts, peripherals, spim}; +use embassy_time::{Delay, Duration, Timer}; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +const LORA_FREQUENCY_IN_HZ: u32 = 903_900_000; // warning: set this appropriately for the region + +bind_interrupts!(struct Irqs { + SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1 => spim::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_nrf::init(Default::default()); + let mut spi_config = spim::Config::default(); + spi_config.frequency = spim::Frequency::M16; + + let spim = spim::Spim::new(p.TWISPI1, Irqs, p.P1_11, p.P1_13, p.P1_12, spi_config); + + let nss = Output::new(p.P1_10.degrade(), Level::High, OutputDrive::Standard); + let reset = Output::new(p.P1_06.degrade(), Level::High, OutputDrive::Standard); + let dio1 = Input::new(p.P1_15.degrade(), Pull::Down); + let busy = Input::new(p.P1_14.degrade(), Pull::Down); + let rf_switch_rx = Output::new(p.P1_05.degrade(), Level::Low, OutputDrive::Standard); + let rf_switch_tx = Output::new(p.P1_07.degrade(), Level::Low, OutputDrive::Standard); + + let iv = + GenericSx126xInterfaceVariant::new(nss, reset, dio1, busy, Some(rf_switch_rx), Some(rf_switch_tx)).unwrap(); + + let mut delay = Delay; + + let mut lora = { + match LoRa::new(SX1261_2::new(BoardType::Rak4631Sx1262, spim, iv), false, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut debug_indicator = Output::new(p.P1_03, Level::Low, OutputDrive::Standard); + let mut start_indicator = Output::new(p.P1_04, Level::Low, OutputDrive::Standard); + + start_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + start_indicator.set_low(); + + let mut receiving_buffer = [00u8; 100]; + + let mdltn_params = { + match lora.create_modulation_params( + SpreadingFactor::_10, + Bandwidth::_250KHz, + CodingRate::_4_8, + LORA_FREQUENCY_IN_HZ, + ) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let rx_pkt_params = { + match lora.create_rx_packet_params(4, false, receiving_buffer.len() as u8, true, false, &mdltn_params) { + Ok(pp) => pp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + // See "RM0453 Reference manual STM32WL5x advanced ArmĀ®-based 32-bit MCUs with sub-GHz radio solution" for the best explanation of Rx duty cycle processing. + match lora + .prepare_for_rx( + &mdltn_params, + &rx_pkt_params, + Some(&DutyCycleParams { + rx_time: 300_000, // 300_000 units * 15.625 us/unit = 4.69 s + sleep_time: 200_000, // 200_000 units * 15.625 us/unit = 3.13 s + }), + false, + false, + 0, + 0, + ) + .await + { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + receiving_buffer = [00u8; 100]; + match lora.rx(&rx_pkt_params, &mut receiving_buffer).await { + Ok((received_len, _rx_pkt_status)) => { + if (received_len == 3) + && (receiving_buffer[0] == 0x01u8) + && (receiving_buffer[1] == 0x02u8) + && (receiving_buffer[2] == 0x03u8) + { + info!("rx successful"); + debug_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + debug_indicator.set_low(); + } else { + info!("rx unknown packet") + } + } + Err(err) => info!("rx unsuccessful = {}", err), + } +} diff --git a/examples/nrf52840/src/bin/lora_p2p_report.rs b/examples/nrf52840/src/bin/lora_p2p_report.rs deleted file mode 100644 index e24f0db0..00000000 --- a/examples/nrf52840/src/bin/lora_p2p_report.rs +++ /dev/null @@ -1,81 +0,0 @@ -//! This example runs on the RAK4631 WisBlock, which has an nRF52840 MCU and Semtech Sx126x radio. -//! Other nrf/sx126x combinations may work with appropriate pin modifications. -//! It demonstates LORA P2P functionality in conjunction with example lora_p2p_sense.rs. -#![no_std] -#![no_main] -#![macro_use] -#![allow(dead_code)] -#![feature(type_alias_impl_trait)] - -use defmt::*; -use embassy_executor::Spawner; -use embassy_lora::sx126x::*; -use embassy_nrf::gpio::{Input, Level, Output, OutputDrive, Pin as _, Pull}; -use embassy_nrf::{bind_interrupts, peripherals, spim}; -use embassy_time::{Duration, Timer}; -use lorawan_device::async_device::radio::{Bandwidth, CodingRate, PhyRxTx, RfConfig, SpreadingFactor}; -use {defmt_rtt as _, panic_probe as _}; - -bind_interrupts!(struct Irqs { - SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1 => spim::InterruptHandler; -}); - -#[embassy_executor::main] -async fn main(_spawner: Spawner) { - let p = embassy_nrf::init(Default::default()); - let mut spi_config = spim::Config::default(); - spi_config.frequency = spim::Frequency::M16; - - let mut radio = { - let spim = spim::Spim::new(p.TWISPI1, Irqs, p.P1_11, p.P1_13, p.P1_12, spi_config); - - let cs = Output::new(p.P1_10.degrade(), Level::High, OutputDrive::Standard); - let reset = Output::new(p.P1_06.degrade(), Level::High, OutputDrive::Standard); - let dio1 = Input::new(p.P1_15.degrade(), Pull::Down); - let busy = Input::new(p.P1_14.degrade(), Pull::Down); - let antenna_rx = Output::new(p.P1_05.degrade(), Level::Low, OutputDrive::Standard); - let antenna_tx = Output::new(p.P1_07.degrade(), Level::Low, OutputDrive::Standard); - - match Sx126xRadio::new(spim, cs, reset, antenna_rx, antenna_tx, dio1, busy, false).await { - Ok(r) => r, - Err(err) => { - info!("Sx126xRadio error = {}", err); - return; - } - } - }; - - let mut debug_indicator = Output::new(p.P1_03, Level::Low, OutputDrive::Standard); - let mut start_indicator = Output::new(p.P1_04, Level::Low, OutputDrive::Standard); - - start_indicator.set_high(); - Timer::after(Duration::from_secs(5)).await; - start_indicator.set_low(); - - loop { - let rf_config = RfConfig { - frequency: 903900000, // channel in Hz - bandwidth: Bandwidth::_250KHz, - spreading_factor: SpreadingFactor::_10, - coding_rate: CodingRate::_4_8, - }; - - let mut buffer = [00u8; 100]; - - // P2P receive - match radio.rx(rf_config, &mut buffer).await { - Ok((buffer_len, rx_quality)) => info!( - "RX received = {:?} with length = {} rssi = {} snr = {}", - &buffer[0..buffer_len], - buffer_len, - rx_quality.rssi(), - rx_quality.snr() - ), - Err(err) => info!("RX error = {}", err), - } - - debug_indicator.set_high(); - Timer::after(Duration::from_secs(2)).await; - debug_indicator.set_low(); - } -} diff --git a/examples/nrf52840/src/bin/lora_p2p_send.rs b/examples/nrf52840/src/bin/lora_p2p_send.rs new file mode 100644 index 00000000..1c8bbc27 --- /dev/null +++ b/examples/nrf52840/src/bin/lora_p2p_send.rs @@ -0,0 +1,104 @@ +//! This example runs on the RAK4631 WisBlock, which has an nRF52840 MCU and Semtech Sx126x radio. +//! Other nrf/sx126x combinations may work with appropriate pin modifications. +//! It demonstrates LORA P2P send functionality. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_lora::iv::GenericSx126xInterfaceVariant; +use embassy_nrf::gpio::{Input, Level, Output, OutputDrive, Pin as _, Pull}; +use embassy_nrf::{bind_interrupts, peripherals, spim}; +use embassy_time::Delay; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +const LORA_FREQUENCY_IN_HZ: u32 = 903_900_000; // warning: set this appropriately for the region + +bind_interrupts!(struct Irqs { + SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1 => spim::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_nrf::init(Default::default()); + let mut spi_config = spim::Config::default(); + spi_config.frequency = spim::Frequency::M16; + + let spim = spim::Spim::new(p.TWISPI1, Irqs, p.P1_11, p.P1_13, p.P1_12, spi_config); + + let nss = Output::new(p.P1_10.degrade(), Level::High, OutputDrive::Standard); + let reset = Output::new(p.P1_06.degrade(), Level::High, OutputDrive::Standard); + let dio1 = Input::new(p.P1_15.degrade(), Pull::Down); + let busy = Input::new(p.P1_14.degrade(), Pull::Down); + let rf_switch_rx = Output::new(p.P1_05.degrade(), Level::Low, OutputDrive::Standard); + let rf_switch_tx = Output::new(p.P1_07.degrade(), Level::Low, OutputDrive::Standard); + + let iv = + GenericSx126xInterfaceVariant::new(nss, reset, dio1, busy, Some(rf_switch_rx), Some(rf_switch_tx)).unwrap(); + + let mut delay = Delay; + + let mut lora = { + match LoRa::new(SX1261_2::new(BoardType::Rak4631Sx1262, spim, iv), false, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mdltn_params = { + match lora.create_modulation_params( + SpreadingFactor::_10, + Bandwidth::_250KHz, + CodingRate::_4_8, + LORA_FREQUENCY_IN_HZ, + ) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut tx_pkt_params = { + match lora.create_tx_packet_params(4, false, true, false, &mdltn_params) { + Ok(pp) => pp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + match lora.prepare_for_tx(&mdltn_params, 20, false).await { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + let buffer = [0x01u8, 0x02u8, 0x03u8]; + match lora.tx(&mdltn_params, &mut tx_pkt_params, &buffer, 0xffffff).await { + Ok(()) => { + info!("TX DONE"); + } + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + match lora.sleep(&mut delay).await { + Ok(()) => info!("Sleep successful"), + Err(err) => info!("Sleep unsuccessful = {}", err), + } +} diff --git a/examples/nrf52840/src/bin/lora_p2p_sense.rs b/examples/nrf52840/src/bin/lora_p2p_sense.rs deleted file mode 100644 index b6f41ffc..00000000 --- a/examples/nrf52840/src/bin/lora_p2p_sense.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! This example runs on the RAK4631 WisBlock, which has an nRF52840 MCU and Semtech Sx126x radio. -//! Other nrf/sx126x combinations may work with appropriate pin modifications. -//! It demonstates LORA P2P functionality in conjunction with example lora_p2p_report.rs. -#![no_std] -#![no_main] -#![macro_use] -#![feature(type_alias_impl_trait)] -#![feature(alloc_error_handler)] -#![allow(incomplete_features)] - -use defmt::*; -use embassy_executor::Spawner; -use embassy_lora::sx126x::*; -use embassy_nrf::gpio::{Input, Level, Output, OutputDrive, Pin as _, Pull}; -use embassy_nrf::{bind_interrupts, peripherals, spim}; -use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; -use embassy_sync::pubsub::{PubSubChannel, Publisher}; -use embassy_time::{Duration, Timer}; -use lorawan_device::async_device::radio::{Bandwidth, CodingRate, PhyRxTx, RfConfig, SpreadingFactor, TxConfig}; -use {defmt_rtt as _, panic_probe as _, panic_probe as _}; - -bind_interrupts!(struct Irqs { - SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1 => spim::InterruptHandler; -}); - -// Message bus: queue of 2, 1 subscriber (Lora P2P), 2 publishers (temperature, motion detection) -static MESSAGE_BUS: PubSubChannel = PubSubChannel::new(); - -#[derive(Clone, defmt::Format)] -enum Message { - Temperature(i32), - MotionDetected, -} - -#[embassy_executor::task] -async fn temperature_task(publisher: Publisher<'static, CriticalSectionRawMutex, Message, 2, 1, 2>) { - // Publish a fake temperature every 43 seconds, minimizing LORA traffic. - loop { - Timer::after(Duration::from_secs(43)).await; - publisher.publish(Message::Temperature(9)).await; - } -} - -#[embassy_executor::task] -async fn motion_detection_task(publisher: Publisher<'static, CriticalSectionRawMutex, Message, 2, 1, 2>) { - // Publish a fake motion detection every 79 seconds, minimizing LORA traffic. - loop { - Timer::after(Duration::from_secs(79)).await; - publisher.publish(Message::MotionDetected).await; - } -} - -#[embassy_executor::main] -async fn main(spawner: Spawner) { - let p = embassy_nrf::init(Default::default()); - // set up to funnel temperature and motion detection events to the Lora Tx task - let mut lora_tx_subscriber = unwrap!(MESSAGE_BUS.subscriber()); - let temperature_publisher = unwrap!(MESSAGE_BUS.publisher()); - let motion_detection_publisher = unwrap!(MESSAGE_BUS.publisher()); - - let mut spi_config = spim::Config::default(); - spi_config.frequency = spim::Frequency::M16; - - let mut radio = { - let spim = spim::Spim::new(p.TWISPI1, Irqs, p.P1_11, p.P1_13, p.P1_12, spi_config); - - let cs = Output::new(p.P1_10.degrade(), Level::High, OutputDrive::Standard); - let reset = Output::new(p.P1_06.degrade(), Level::High, OutputDrive::Standard); - let dio1 = Input::new(p.P1_15.degrade(), Pull::Down); - let busy = Input::new(p.P1_14.degrade(), Pull::Down); - let antenna_rx = Output::new(p.P1_05.degrade(), Level::Low, OutputDrive::Standard); - let antenna_tx = Output::new(p.P1_07.degrade(), Level::Low, OutputDrive::Standard); - - match Sx126xRadio::new(spim, cs, reset, antenna_rx, antenna_tx, dio1, busy, false).await { - Ok(r) => r, - Err(err) => { - info!("Sx126xRadio error = {}", err); - return; - } - } - }; - - let mut start_indicator = Output::new(p.P1_04, Level::Low, OutputDrive::Standard); - - start_indicator.set_high(); - Timer::after(Duration::from_secs(5)).await; - start_indicator.set_low(); - - match radio.lora.sleep().await { - Ok(()) => info!("Sleep successful"), - Err(err) => info!("Sleep unsuccessful = {}", err), - } - - unwrap!(spawner.spawn(temperature_task(temperature_publisher))); - unwrap!(spawner.spawn(motion_detection_task(motion_detection_publisher))); - - loop { - let message = lora_tx_subscriber.next_message_pure().await; - - let tx_config = TxConfig { - // 11 byte maximum payload for Bandwidth 125 and SF 10 - pw: 10, // up to 20 - rf: RfConfig { - frequency: 903900000, // channel in Hz, not MHz - bandwidth: Bandwidth::_250KHz, - spreading_factor: SpreadingFactor::_10, - coding_rate: CodingRate::_4_8, - }, - }; - - let mut buffer = [0x00u8]; - match message { - Message::Temperature(temperature) => buffer[0] = temperature as u8, - Message::MotionDetected => buffer[0] = 0x01u8, - }; - - // unencrypted - match radio.tx(tx_config, &buffer).await { - Ok(ret_val) => info!("TX ret_val = {}", ret_val), - Err(err) => info!("TX error = {}", err), - } - - match radio.lora.sleep().await { - Ok(()) => info!("Sleep successful"), - Err(err) => info!("Sleep unsuccessful = {}", err), - } - } -} diff --git a/examples/rp/Cargo.toml b/examples/rp/Cargo.toml index 8067f7ba..45af8762 100644 --- a/examples/rp/Cargo.toml +++ b/examples/rp/Cargo.toml @@ -9,12 +9,16 @@ license = "MIT OR Apache-2.0" embassy-embedded-hal = { version = "0.1.0", path = "../../embassy-embedded-hal", features = ["defmt"] } embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["defmt"] } embassy-executor = { version = "0.1.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } +embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["nightly", "unstable-traits", "defmt", "defmt-timestamp-uptime"] } embassy-rp = { version = "0.1.0", path = "../../embassy-rp", features = ["defmt", "unstable-traits", "nightly", "unstable-pac", "time-driver", "pio", "critical-section-impl"] } embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } embassy-net = { version = "0.1.0", path = "../../embassy-net", features = ["defmt", "nightly", "tcp", "dhcpv4", "medium-ethernet"] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } embassy-usb-logger = { version = "0.1.0", path = "../../embassy-usb-logger" } +embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["time", "defmt", "external-lora-phy"] } +lora-phy = { version = "1" } +lorawan-device = { version = "0.10.0", default-features = false, features = ["async", "external-lora-phy"] } +lorawan = { version = "0.7.3", default-features = false, features = ["default-crypto"] } defmt = "0.3" defmt-rtt = "0.4" diff --git a/examples/rp/src/bin/lora_lorawan.rs b/examples/rp/src/bin/lora_lorawan.rs new file mode 100644 index 00000000..a9c84bf9 --- /dev/null +++ b/examples/rp/src/bin/lora_lorawan.rs @@ -0,0 +1,80 @@ +//! This example runs on the Raspberry Pi Pico with a Waveshare board containing a Semtech Sx1262 radio. +//! It demonstrates LoRaWAN join functionality. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_lora::iv::GenericSx126xInterfaceVariant; +use embassy_lora::LoraTimer; +use embassy_rp::gpio::{Input, Level, Output, Pin, Pull}; +use embassy_rp::spi::{Config, Spi}; +use embassy_time::Delay; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use lorawan::default_crypto::DefaultFactory as Crypto; +use lorawan_device::async_device::lora_radio::LoRaRadio; +use lorawan_device::async_device::{region, Device, JoinMode}; +use {defmt_rtt as _, panic_probe as _}; + +const LORAWAN_REGION: region::Region = region::Region::EU868; // warning: set this appropriately for the region + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + + let miso = p.PIN_12; + let mosi = p.PIN_11; + let clk = p.PIN_10; + let spi = Spi::new(p.SPI1, clk, mosi, miso, p.DMA_CH0, p.DMA_CH1, Config::default()); + + let nss = Output::new(p.PIN_3.degrade(), Level::High); + let reset = Output::new(p.PIN_15.degrade(), Level::High); + let dio1 = Input::new(p.PIN_20.degrade(), Pull::None); + let busy = Input::new(p.PIN_2.degrade(), Pull::None); + + let iv = GenericSx126xInterfaceVariant::new(nss, reset, dio1, busy, None, None).unwrap(); + + let mut delay = Delay; + + let lora = { + match LoRa::new( + SX1261_2::new(BoardType::RpPicoWaveshareSx1262, spi, iv), + true, + &mut delay, + ) + .await + { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let radio = LoRaRadio::new(lora); + let region: region::Configuration = region::Configuration::new(LORAWAN_REGION); + let mut device: Device<_, Crypto, _, _> = Device::new(region, radio, LoraTimer::new(), embassy_rp::clocks::RoscRng); + + defmt::info!("Joining LoRaWAN network"); + + // TODO: Adjust the EUI and Keys according to your network credentials + match device + .join(&JoinMode::OTAA { + deveui: [0, 0, 0, 0, 0, 0, 0, 0], + appeui: [0, 0, 0, 0, 0, 0, 0, 0], + appkey: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + }) + .await + { + Ok(()) => defmt::info!("LoRaWAN network joined"), + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; +} diff --git a/examples/rp/src/bin/lora_p2p_receive.rs b/examples/rp/src/bin/lora_p2p_receive.rs new file mode 100644 index 00000000..25041920 --- /dev/null +++ b/examples/rp/src/bin/lora_p2p_receive.rs @@ -0,0 +1,115 @@ +//! This example runs on the Raspberry Pi Pico with a Waveshare board containing a Semtech Sx1262 radio. +//! It demonstrates LORA P2P receive functionality in conjunction with the lora_p2p_send example. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_lora::iv::GenericSx126xInterfaceVariant; +use embassy_rp::gpio::{Input, Level, Output, Pin, Pull}; +use embassy_rp::spi::{Config, Spi}; +use embassy_time::{Delay, Duration, Timer}; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +const LORA_FREQUENCY_IN_HZ: u32 = 903_900_000; // warning: set this appropriately for the region + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + + let miso = p.PIN_12; + let mosi = p.PIN_11; + let clk = p.PIN_10; + let spi = Spi::new(p.SPI1, clk, mosi, miso, p.DMA_CH0, p.DMA_CH1, Config::default()); + + let nss = Output::new(p.PIN_3.degrade(), Level::High); + let reset = Output::new(p.PIN_15.degrade(), Level::High); + let dio1 = Input::new(p.PIN_20.degrade(), Pull::None); + let busy = Input::new(p.PIN_2.degrade(), Pull::None); + + let iv = GenericSx126xInterfaceVariant::new(nss, reset, dio1, busy, None, None).unwrap(); + + let mut delay = Delay; + + let mut lora = { + match LoRa::new( + SX1261_2::new(BoardType::RpPicoWaveshareSx1262, spi, iv), + false, + &mut delay, + ) + .await + { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut debug_indicator = Output::new(p.PIN_25, Level::Low); + + let mut receiving_buffer = [00u8; 100]; + + let mdltn_params = { + match lora.create_modulation_params( + SpreadingFactor::_10, + Bandwidth::_250KHz, + CodingRate::_4_8, + LORA_FREQUENCY_IN_HZ, + ) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let rx_pkt_params = { + match lora.create_rx_packet_params(4, false, receiving_buffer.len() as u8, true, false, &mdltn_params) { + Ok(pp) => pp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + match lora + .prepare_for_rx(&mdltn_params, &rx_pkt_params, None, true, false, 0, 0x00ffffffu32) + .await + { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + loop { + receiving_buffer = [00u8; 100]; + match lora.rx(&rx_pkt_params, &mut receiving_buffer).await { + Ok((received_len, _rx_pkt_status)) => { + if (received_len == 3) + && (receiving_buffer[0] == 0x01u8) + && (receiving_buffer[1] == 0x02u8) + && (receiving_buffer[2] == 0x03u8) + { + info!("rx successful"); + debug_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + debug_indicator.set_low(); + } else { + info!("rx unknown packet"); + } + } + Err(err) => info!("rx unsuccessful = {}", err), + } + } +} diff --git a/examples/rp/src/bin/lora_p2p_send.rs b/examples/rp/src/bin/lora_p2p_send.rs new file mode 100644 index 00000000..3a0544b1 --- /dev/null +++ b/examples/rp/src/bin/lora_p2p_send.rs @@ -0,0 +1,103 @@ +//! This example runs on the Raspberry Pi Pico with a Waveshare board containing a Semtech Sx1262 radio. +//! It demonstrates LORA P2P send functionality. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_lora::iv::GenericSx126xInterfaceVariant; +use embassy_rp::gpio::{Input, Level, Output, Pin, Pull}; +use embassy_rp::spi::{Config, Spi}; +use embassy_time::Delay; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +const LORA_FREQUENCY_IN_HZ: u32 = 903_900_000; // warning: set this appropriately for the region + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let p = embassy_rp::init(Default::default()); + + let miso = p.PIN_12; + let mosi = p.PIN_11; + let clk = p.PIN_10; + let spi = Spi::new(p.SPI1, clk, mosi, miso, p.DMA_CH0, p.DMA_CH1, Config::default()); + + let nss = Output::new(p.PIN_3.degrade(), Level::High); + let reset = Output::new(p.PIN_15.degrade(), Level::High); + let dio1 = Input::new(p.PIN_20.degrade(), Pull::None); + let busy = Input::new(p.PIN_2.degrade(), Pull::None); + + let iv = GenericSx126xInterfaceVariant::new(nss, reset, dio1, busy, None, None).unwrap(); + + let mut delay = Delay; + + let mut lora = { + match LoRa::new( + SX1261_2::new(BoardType::RpPicoWaveshareSx1262, spi, iv), + false, + &mut delay, + ) + .await + { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mdltn_params = { + match lora.create_modulation_params( + SpreadingFactor::_10, + Bandwidth::_250KHz, + CodingRate::_4_8, + LORA_FREQUENCY_IN_HZ, + ) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut tx_pkt_params = { + match lora.create_tx_packet_params(4, false, true, false, &mdltn_params) { + Ok(pp) => pp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + match lora.prepare_for_tx(&mdltn_params, 20, false).await { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + let buffer = [0x01u8, 0x02u8, 0x03u8]; + match lora.tx(&mdltn_params, &mut tx_pkt_params, &buffer, 0xffffff).await { + Ok(()) => { + info!("TX DONE"); + } + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + match lora.sleep(&mut delay).await { + Ok(()) => info!("Sleep successful"), + Err(err) => info!("Sleep unsuccessful = {}", err), + } +} diff --git a/examples/rp/src/bin/lora_p2p_send_multicore.rs b/examples/rp/src/bin/lora_p2p_send_multicore.rs new file mode 100644 index 00000000..5585606d --- /dev/null +++ b/examples/rp/src/bin/lora_p2p_send_multicore.rs @@ -0,0 +1,139 @@ +//! This example runs on the Raspberry Pi Pico with a Waveshare board containing a Semtech Sx1262 radio. +//! It demonstrates LORA P2P send functionality using the second core, with data provided by the first core. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Executor; +use embassy_executor::_export::StaticCell; +use embassy_lora::iv::GenericSx126xInterfaceVariant; +use embassy_rp::gpio::{AnyPin, Input, Level, Output, Pin, Pull}; +use embassy_rp::multicore::{spawn_core1, Stack}; +use embassy_rp::peripherals::SPI1; +use embassy_rp::spi::{Async, Config, Spi}; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +use embassy_sync::channel::Channel; +use embassy_time::{Delay, Duration, Timer}; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +static mut CORE1_STACK: Stack<4096> = Stack::new(); +static EXECUTOR0: StaticCell = StaticCell::new(); +static EXECUTOR1: StaticCell = StaticCell::new(); +static CHANNEL: Channel = Channel::new(); + +const LORA_FREQUENCY_IN_HZ: u32 = 903_900_000; // warning: set this appropriately for the region + +#[cortex_m_rt::entry] +fn main() -> ! { + let p = embassy_rp::init(Default::default()); + + let miso = p.PIN_12; + let mosi = p.PIN_11; + let clk = p.PIN_10; + let spi = Spi::new(p.SPI1, clk, mosi, miso, p.DMA_CH0, p.DMA_CH1, Config::default()); + + let nss = Output::new(p.PIN_3.degrade(), Level::High); + let reset = Output::new(p.PIN_15.degrade(), Level::High); + let dio1 = Input::new(p.PIN_20.degrade(), Pull::None); + let busy = Input::new(p.PIN_2.degrade(), Pull::None); + + let iv = GenericSx126xInterfaceVariant::new(nss, reset, dio1, busy, None, None).unwrap(); + + spawn_core1(p.CORE1, unsafe { &mut CORE1_STACK }, move || { + let executor1 = EXECUTOR1.init(Executor::new()); + executor1.run(|spawner| unwrap!(spawner.spawn(core1_task(spi, iv)))); + }); + + let executor0 = EXECUTOR0.init(Executor::new()); + executor0.run(|spawner| unwrap!(spawner.spawn(core0_task()))); +} + +#[embassy_executor::task] +async fn core0_task() { + info!("Hello from core 0"); + loop { + CHANNEL.send([0x01u8, 0x02u8, 0x03u8]).await; + Timer::after(Duration::from_millis(60 * 1000)).await; + } +} + +#[embassy_executor::task] +async fn core1_task( + spi: Spi<'static, SPI1, Async>, + iv: GenericSx126xInterfaceVariant, Input<'static, AnyPin>>, +) { + info!("Hello from core 1"); + let mut delay = Delay; + + let mut lora = { + match LoRa::new( + SX1261_2::new(BoardType::RpPicoWaveshareSx1262, spi, iv), + false, + &mut delay, + ) + .await + { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mdltn_params = { + match lora.create_modulation_params( + SpreadingFactor::_10, + Bandwidth::_250KHz, + CodingRate::_4_8, + LORA_FREQUENCY_IN_HZ, + ) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut tx_pkt_params = { + match lora.create_tx_packet_params(4, false, true, false, &mdltn_params) { + Ok(pp) => pp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + loop { + let buffer: [u8; 3] = CHANNEL.recv().await; + match lora.prepare_for_tx(&mdltn_params, 20, false).await { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + match lora.tx(&mdltn_params, &mut tx_pkt_params, &buffer, 0xffffff).await { + Ok(()) => { + info!("TX DONE"); + } + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + match lora.sleep(&mut delay).await { + Ok(()) => info!("Sleep successful"), + Err(err) => info!("Sleep unsuccessful = {}", err), + } + } +} diff --git a/examples/stm32l0/Cargo.toml b/examples/stm32l0/Cargo.toml index d08e2b61..ca022e25 100644 --- a/examples/stm32l0/Cargo.toml +++ b/examples/stm32l0/Cargo.toml @@ -6,17 +6,18 @@ license = "MIT OR Apache-2.0" [features] default = ["nightly"] -nightly = ["embassy-stm32/nightly", "embassy-lora", "lorawan-device", "lorawan", "embedded-io/async"] +nightly = ["embassy-stm32/nightly", "embassy-time/nightly", "embassy-time/unstable-traits", + "embassy-lora", "lora-phy", "lorawan-device", "lorawan", "embedded-io/async"] [dependencies] embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["defmt"] } embassy-executor = { version = "0.1.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["defmt", "stm32l072cz", "time-driver-any", "exti", "unstable-traits", "memory-x"] } -embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["sx127x", "time", "defmt"], optional = true} - -lorawan-device = { version = "0.9.0", default-features = false, features = ["async"], optional = true } -lorawan = { version = "0.7.2", default-features = false, features = ["default-crypto"], optional = true } +embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["sx127x", "time", "defmt", "external-lora-phy"], optional = true } +lora-phy = { version = "1", optional = true } +lorawan-device = { version = "0.10.0", default-features = false, features = ["async", "external-lora-phy"], optional = true } +lorawan = { version = "0.7.3", default-features = false, features = ["default-crypto"], optional = true } defmt = "0.3" defmt-rtt = "0.4" diff --git a/examples/stm32l0/src/bin/lora_cad.rs b/examples/stm32l0/src/bin/lora_cad.rs new file mode 100644 index 00000000..588cea1e --- /dev/null +++ b/examples/stm32l0/src/bin/lora_cad.rs @@ -0,0 +1,105 @@ +//! This example runs on the STM32 LoRa Discovery board, which has a builtin Semtech Sx1276 radio. +//! It demonstrates LORA P2P CAD functionality. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_lora::iv::Stm32l0InterfaceVariant; +use embassy_stm32::exti::{Channel, ExtiInput}; +use embassy_stm32::gpio::{Input, Level, Output, Pin, Pull, Speed}; +use embassy_stm32::spi; +use embassy_stm32::time::khz; +use embassy_time::{Delay, Duration, Timer}; +use lora_phy::mod_params::*; +use lora_phy::sx1276_7_8_9::SX1276_7_8_9; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +const LORA_FREQUENCY_IN_HZ: u32 = 903_900_000; // warning: set this appropriately for the region + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = embassy_stm32::Config::default(); + config.rcc.mux = embassy_stm32::rcc::ClockSrc::HSI16; + config.rcc.enable_hsi48 = true; + let p = embassy_stm32::init(config); + + // SPI for sx1276 + let spi = spi::Spi::new( + p.SPI1, + p.PB3, + p.PA7, + p.PA6, + p.DMA1_CH3, + p.DMA1_CH2, + khz(200), + spi::Config::default(), + ); + + let nss = Output::new(p.PA15.degrade(), Level::High, Speed::Low); + let reset = Output::new(p.PC0.degrade(), Level::High, Speed::Low); + + let irq_pin = Input::new(p.PB4.degrade(), Pull::Up); + let irq = ExtiInput::new(irq_pin, p.EXTI4.degrade()); + + let iv = Stm32l0InterfaceVariant::new(nss, reset, irq, None, None).unwrap(); + + let mut delay = Delay; + + let mut lora = { + match LoRa::new(SX1276_7_8_9::new(BoardType::Stm32l0Sx1276, spi, iv), false, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut debug_indicator = Output::new(p.PB5, Level::Low, Speed::Low); + let mut start_indicator = Output::new(p.PB6, Level::Low, Speed::Low); + + start_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + start_indicator.set_low(); + + let mdltn_params = { + match lora.create_modulation_params( + SpreadingFactor::_10, + Bandwidth::_250KHz, + CodingRate::_4_8, + LORA_FREQUENCY_IN_HZ, + ) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + match lora.prepare_for_cad(&mdltn_params, true).await { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + match lora.cad().await { + Ok(cad_activity_detected) => { + if cad_activity_detected { + info!("cad successful with activity detected") + } else { + info!("cad successful without activity detected") + } + debug_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + debug_indicator.set_low(); + } + Err(err) => info!("cad unsuccessful = {}", err), + } +} diff --git a/examples/stm32l0/src/bin/lora_lorawan.rs b/examples/stm32l0/src/bin/lora_lorawan.rs new file mode 100644 index 00000000..c397edd5 --- /dev/null +++ b/examples/stm32l0/src/bin/lora_lorawan.rs @@ -0,0 +1,88 @@ +//! This example runs on the STM32 LoRa Discovery board, which has a builtin Semtech Sx1276 radio. +//! It demonstrates LoRaWAN join functionality. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_lora::iv::Stm32l0InterfaceVariant; +use embassy_lora::LoraTimer; +use embassy_stm32::exti::{Channel, ExtiInput}; +use embassy_stm32::gpio::{Input, Level, Output, Pin, Pull, Speed}; +use embassy_stm32::rng::Rng; +use embassy_stm32::spi; +use embassy_stm32::time::khz; +use embassy_time::Delay; +use lora_phy::mod_params::*; +use lora_phy::sx1276_7_8_9::SX1276_7_8_9; +use lora_phy::LoRa; +use lorawan::default_crypto::DefaultFactory as Crypto; +use lorawan_device::async_device::lora_radio::LoRaRadio; +use lorawan_device::async_device::{region, Device, JoinMode}; +use {defmt_rtt as _, panic_probe as _}; + +const LORAWAN_REGION: region::Region = region::Region::EU868; // warning: set this appropriately for the region + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = embassy_stm32::Config::default(); + config.rcc.mux = embassy_stm32::rcc::ClockSrc::HSI16; + config.rcc.enable_hsi48 = true; + let p = embassy_stm32::init(config); + + // SPI for sx1276 + let spi = spi::Spi::new( + p.SPI1, + p.PB3, + p.PA7, + p.PA6, + p.DMA1_CH3, + p.DMA1_CH2, + khz(200), + spi::Config::default(), + ); + + let nss = Output::new(p.PA15.degrade(), Level::High, Speed::Low); + let reset = Output::new(p.PC0.degrade(), Level::High, Speed::Low); + + let irq_pin = Input::new(p.PB4.degrade(), Pull::Up); + let irq = ExtiInput::new(irq_pin, p.EXTI4.degrade()); + + let iv = Stm32l0InterfaceVariant::new(nss, reset, irq, None, None).unwrap(); + + let mut delay = Delay; + + let lora = { + match LoRa::new(SX1276_7_8_9::new(BoardType::Stm32l0Sx1276, spi, iv), true, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let radio = LoRaRadio::new(lora); + let region: region::Configuration = region::Configuration::new(LORAWAN_REGION); + let mut device: Device<_, Crypto, _, _> = Device::new(region, radio, LoraTimer::new(), Rng::new(p.RNG)); + + defmt::info!("Joining LoRaWAN network"); + + // TODO: Adjust the EUI and Keys according to your network credentials + match device + .join(&JoinMode::OTAA { + deveui: [0, 0, 0, 0, 0, 0, 0, 0], + appeui: [0, 0, 0, 0, 0, 0, 0, 0], + appkey: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + }) + .await + { + Ok(()) => defmt::info!("LoRaWAN network joined"), + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; +} diff --git a/examples/stm32l0/src/bin/lora_p2p_receive.rs b/examples/stm32l0/src/bin/lora_p2p_receive.rs new file mode 100644 index 00000000..bb750950 --- /dev/null +++ b/examples/stm32l0/src/bin/lora_p2p_receive.rs @@ -0,0 +1,127 @@ +//! This example runs on the STM32 LoRa Discovery board, which has a builtin Semtech Sx1276 radio. +//! It demonstrates LORA P2P receive functionality in conjunction with the lora_p2p_send example. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_lora::iv::Stm32l0InterfaceVariant; +use embassy_stm32::exti::{Channel, ExtiInput}; +use embassy_stm32::gpio::{Input, Level, Output, Pin, Pull, Speed}; +use embassy_stm32::spi; +use embassy_stm32::time::khz; +use embassy_time::{Delay, Duration, Timer}; +use lora_phy::mod_params::*; +use lora_phy::sx1276_7_8_9::SX1276_7_8_9; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +const LORA_FREQUENCY_IN_HZ: u32 = 903_900_000; // warning: set this appropriately for the region + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = embassy_stm32::Config::default(); + config.rcc.mux = embassy_stm32::rcc::ClockSrc::HSI16; + config.rcc.enable_hsi48 = true; + let p = embassy_stm32::init(config); + + // SPI for sx1276 + let spi = spi::Spi::new( + p.SPI1, + p.PB3, + p.PA7, + p.PA6, + p.DMA1_CH3, + p.DMA1_CH2, + khz(200), + spi::Config::default(), + ); + + let nss = Output::new(p.PA15.degrade(), Level::High, Speed::Low); + let reset = Output::new(p.PC0.degrade(), Level::High, Speed::Low); + + let irq_pin = Input::new(p.PB4.degrade(), Pull::Up); + let irq = ExtiInput::new(irq_pin, p.EXTI4.degrade()); + + let iv = Stm32l0InterfaceVariant::new(nss, reset, irq, None, None).unwrap(); + + let mut delay = Delay; + + let mut lora = { + match LoRa::new(SX1276_7_8_9::new(BoardType::Stm32l0Sx1276, spi, iv), false, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut debug_indicator = Output::new(p.PB5, Level::Low, Speed::Low); + let mut start_indicator = Output::new(p.PB6, Level::Low, Speed::Low); + + start_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + start_indicator.set_low(); + + let mut receiving_buffer = [00u8; 100]; + + let mdltn_params = { + match lora.create_modulation_params( + SpreadingFactor::_10, + Bandwidth::_250KHz, + CodingRate::_4_8, + LORA_FREQUENCY_IN_HZ, + ) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let rx_pkt_params = { + match lora.create_rx_packet_params(4, false, receiving_buffer.len() as u8, true, false, &mdltn_params) { + Ok(pp) => pp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + match lora + .prepare_for_rx(&mdltn_params, &rx_pkt_params, None, true, false, 0, 0x00ffffffu32) + .await + { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + loop { + receiving_buffer = [00u8; 100]; + match lora.rx(&rx_pkt_params, &mut receiving_buffer).await { + Ok((received_len, _rx_pkt_status)) => { + if (received_len == 3) + && (receiving_buffer[0] == 0x01u8) + && (receiving_buffer[1] == 0x02u8) + && (receiving_buffer[2] == 0x03u8) + { + info!("rx successful"); + debug_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + debug_indicator.set_low(); + } else { + info!("rx unknown packet"); + } + } + Err(err) => info!("rx unsuccessful = {}", err), + } + } +} diff --git a/examples/stm32l0/src/bin/lora_p2p_send.rs b/examples/stm32l0/src/bin/lora_p2p_send.rs new file mode 100644 index 00000000..e6fadc01 --- /dev/null +++ b/examples/stm32l0/src/bin/lora_p2p_send.rs @@ -0,0 +1,110 @@ +//! This example runs on the STM32 LoRa Discovery board, which has a builtin Semtech Sx1276 radio. +//! It demonstrates LORA P2P send functionality. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait)] + +use defmt::*; +use embassy_executor::Spawner; +use embassy_lora::iv::Stm32l0InterfaceVariant; +use embassy_stm32::exti::{Channel, ExtiInput}; +use embassy_stm32::gpio::{Input, Level, Output, Pin, Pull, Speed}; +use embassy_stm32::spi; +use embassy_stm32::time::khz; +use embassy_time::Delay; +use lora_phy::mod_params::*; +use lora_phy::sx1276_7_8_9::SX1276_7_8_9; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +const LORA_FREQUENCY_IN_HZ: u32 = 903_900_000; // warning: set this appropriately for the region + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = embassy_stm32::Config::default(); + config.rcc.mux = embassy_stm32::rcc::ClockSrc::HSI16; + config.rcc.enable_hsi48 = true; + let p = embassy_stm32::init(config); + + // SPI for sx1276 + let spi = spi::Spi::new( + p.SPI1, + p.PB3, + p.PA7, + p.PA6, + p.DMA1_CH3, + p.DMA1_CH2, + khz(200), + spi::Config::default(), + ); + + let nss = Output::new(p.PA15.degrade(), Level::High, Speed::Low); + let reset = Output::new(p.PC0.degrade(), Level::High, Speed::Low); + + let irq_pin = Input::new(p.PB4.degrade(), Pull::Up); + let irq = ExtiInput::new(irq_pin, p.EXTI4.degrade()); + + let iv = Stm32l0InterfaceVariant::new(nss, reset, irq, None, None).unwrap(); + + let mut delay = Delay; + + let mut lora = { + match LoRa::new(SX1276_7_8_9::new(BoardType::Stm32l0Sx1276, spi, iv), false, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mdltn_params = { + match lora.create_modulation_params( + SpreadingFactor::_10, + Bandwidth::_250KHz, + CodingRate::_4_8, + LORA_FREQUENCY_IN_HZ, + ) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut tx_pkt_params = { + match lora.create_tx_packet_params(4, false, true, false, &mdltn_params) { + Ok(pp) => pp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + match lora.prepare_for_tx(&mdltn_params, 17, true).await { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + let buffer = [0x01u8, 0x02u8, 0x03u8]; + match lora.tx(&mdltn_params, &mut tx_pkt_params, &buffer, 0xffffff).await { + Ok(()) => { + info!("TX DONE"); + } + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + match lora.sleep(&mut delay).await { + Ok(()) => info!("Sleep successful"), + Err(err) => info!("Sleep unsuccessful = {}", err), + } +} diff --git a/examples/stm32l0/src/bin/lorawan.rs b/examples/stm32l0/src/bin/lorawan.rs deleted file mode 100644 index ea01f610..00000000 --- a/examples/stm32l0/src/bin/lorawan.rs +++ /dev/null @@ -1,74 +0,0 @@ -//! This example runs on the STM32 LoRa Discovery board which has a builtin Semtech Sx127x radio -#![no_std] -#![no_main] -#![macro_use] -#![allow(dead_code)] -#![feature(type_alias_impl_trait)] - -use embassy_executor::Spawner; -use embassy_lora::sx127x::*; -use embassy_lora::LoraTimer; -use embassy_stm32::exti::ExtiInput; -use embassy_stm32::gpio::{Input, Level, Output, Pull, Speed}; -use embassy_stm32::rng::Rng; -use embassy_stm32::spi; -use embassy_stm32::time::khz; -use lorawan::default_crypto::DefaultFactory as Crypto; -use lorawan_device::async_device::{region, Device, JoinMode}; -use {defmt_rtt as _, panic_probe as _}; - -#[embassy_executor::main] -async fn main(_spawner: Spawner) { - let mut config = embassy_stm32::Config::default(); - config.rcc.mux = embassy_stm32::rcc::ClockSrc::HSI16; - config.rcc.enable_hsi48 = true; - let p = embassy_stm32::init(config); - - // SPI for sx127x - let spi = spi::Spi::new( - p.SPI1, - p.PB3, - p.PA7, - p.PA6, - p.DMA1_CH3, - p.DMA1_CH2, - khz(200), - spi::Config::default(), - ); - - let cs = Output::new(p.PA15, Level::High, Speed::Low); - let reset = Output::new(p.PC0, Level::High, Speed::Low); - let _ = Input::new(p.PB1, Pull::None); - - let ready = Input::new(p.PB4, Pull::Up); - let ready_pin = ExtiInput::new(ready, p.EXTI4); - - let radio = Sx127xRadio::new(spi, cs, reset, ready_pin, DummySwitch).await.unwrap(); - - let region = region::Configuration::new(region::Region::EU868); - let mut device: Device<_, Crypto, _, _> = Device::new(region, radio, LoraTimer::new(), Rng::new(p.RNG)); - - defmt::info!("Joining LoRaWAN network"); - - // TODO: Adjust the EUI and Keys according to your network credentials - device - .join(&JoinMode::OTAA { - deveui: [0, 0, 0, 0, 0, 0, 0, 0], - appeui: [0, 0, 0, 0, 0, 0, 0, 0], - appkey: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - }) - .await - .ok() - .unwrap(); - defmt::info!("LoRaWAN network joined"); - - defmt::info!("Sending 'PING'"); - device.send(b"PING", 1, false).await.ok().unwrap(); - defmt::info!("Message sent!"); -} - -pub struct DummySwitch; -impl RadioSwitch for DummySwitch { - fn set_rx(&mut self) {} - fn set_tx(&mut self) {} -} diff --git a/examples/stm32wl/Cargo.toml b/examples/stm32wl/Cargo.toml index 07f136b4..0eb24bc4 100644 --- a/examples/stm32wl/Cargo.toml +++ b/examples/stm32wl/Cargo.toml @@ -7,12 +7,13 @@ license = "MIT OR Apache-2.0" [dependencies] embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["defmt"] } embassy-executor = { version = "0.1.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } -embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } -embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "stm32wl55jc-cm4", "time-driver-any", "memory-x", "unstable-pac", "exti"] } -embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["stm32wl", "time", "defmt"] } - -lorawan-device = { version = "0.9.0", default-features = false, features = ["async"] } -lorawan = { version = "0.7.2", default-features = false, features = ["default-crypto"] } +embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["nightly", "unstable-traits", "defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "unstable-traits", "defmt", "stm32wl55jc-cm4", "time-driver-any", "memory-x", "unstable-pac", "exti"] } +embassy-embedded-hal = {version = "0.1.0", path = "../../embassy-embedded-hal" } +embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["stm32wl", "time", "defmt", "external-lora-phy"] } +lora-phy = { version = "1" } +lorawan-device = { version = "0.10.0", default-features = false, features = ["async", "external-lora-phy"] } +lorawan = { version = "0.7.3", default-features = false, features = ["default-crypto"] } defmt = "0.3" defmt-rtt = "0.4" diff --git a/examples/stm32wl/src/bin/lora_lorawan.rs b/examples/stm32wl/src/bin/lora_lorawan.rs new file mode 100644 index 00000000..4bcc5420 --- /dev/null +++ b/examples/stm32wl/src/bin/lora_lorawan.rs @@ -0,0 +1,90 @@ +//! This example runs on a STM32WL board, which has a builtin Semtech Sx1262 radio. +//! It demonstrates LoRaWAN join functionality. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait, async_fn_in_trait)] +#![allow(incomplete_features)] + +use defmt::info; +use embassy_embedded_hal::adapter::BlockingAsync; +use embassy_executor::Spawner; +use embassy_lora::iv::Stm32wlInterfaceVariant; +use embassy_lora::LoraTimer; +use embassy_stm32::dma::NoDma; +use embassy_stm32::gpio::{Level, Output, Pin, Speed}; +use embassy_stm32::peripherals::SUBGHZSPI; +use embassy_stm32::rcc::low_level::RccPeripheral; +use embassy_stm32::rng::Rng; +use embassy_stm32::spi::{BitOrder, Config as SpiConfig, Spi, MODE_0}; +use embassy_stm32::time::Hertz; +use embassy_stm32::{interrupt, into_ref, pac, Peripheral}; +use embassy_time::Delay; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use lorawan::default_crypto::DefaultFactory as Crypto; +use lorawan_device::async_device::lora_radio::LoRaRadio; +use lorawan_device::async_device::{region, Device, JoinMode}; +use {defmt_rtt as _, panic_probe as _}; + +const LORAWAN_REGION: region::Region = region::Region::EU868; // warning: set this appropriately for the region + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = embassy_stm32::Config::default(); + config.rcc.mux = embassy_stm32::rcc::ClockSrc::HSI16; + config.rcc.enable_lsi = true; + let p = embassy_stm32::init(config); + + unsafe { pac::RCC.ccipr().modify(|w| w.set_rngsel(0b01)) } + + let clk = Hertz(core::cmp::min(SUBGHZSPI::frequency().0 / 2, 16_000_000)); + let mut spi_config = SpiConfig::default(); + spi_config.mode = MODE_0; + spi_config.bit_order = BitOrder::MsbFirst; + let spi = Spi::new_subghz(p.SUBGHZSPI, NoDma, NoDma, clk, spi_config); + + let spi = BlockingAsync::new(spi); + + let irq = interrupt::take!(SUBGHZ_RADIO); + into_ref!(irq); + // Set CTRL1 and CTRL3 for high-power transmission, while CTRL2 acts as an RF switch between tx and rx + let _ctrl1 = Output::new(p.PC4.degrade(), Level::Low, Speed::High); + let ctrl2 = Output::new(p.PC5.degrade(), Level::High, Speed::High); + let _ctrl3 = Output::new(p.PC3.degrade(), Level::High, Speed::High); + let iv = Stm32wlInterfaceVariant::new(irq, None, Some(ctrl2)).unwrap(); + + let mut delay = Delay; + + let lora = { + match LoRa::new(SX1261_2::new(BoardType::Stm32wlSx1262, spi, iv), true, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + let radio = LoRaRadio::new(lora); + let region: region::Configuration = region::Configuration::new(LORAWAN_REGION); + let mut device: Device<_, Crypto, _, _> = Device::new(region, radio, LoraTimer::new(), Rng::new(p.RNG)); + + defmt::info!("Joining LoRaWAN network"); + + // TODO: Adjust the EUI and Keys according to your network credentials + match device + .join(&JoinMode::OTAA { + deveui: [0, 0, 0, 0, 0, 0, 0, 0], + appeui: [0, 0, 0, 0, 0, 0, 0, 0], + appkey: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + }) + .await + { + Ok(()) => defmt::info!("LoRaWAN network joined"), + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; +} diff --git a/examples/stm32wl/src/bin/lora_p2p_receive.rs b/examples/stm32wl/src/bin/lora_p2p_receive.rs new file mode 100644 index 00000000..bb31518c --- /dev/null +++ b/examples/stm32wl/src/bin/lora_p2p_receive.rs @@ -0,0 +1,127 @@ +//! This example runs on the STM32WL board, which has a builtin Semtech Sx1262 radio. +//! It demonstrates LORA P2P receive functionality in conjunction with the lora_p2p_send example. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait, async_fn_in_trait)] +#![allow(incomplete_features)] + +use defmt::info; +use embassy_embedded_hal::adapter::BlockingAsync; +use embassy_executor::Spawner; +use embassy_lora::iv::Stm32wlInterfaceVariant; +use embassy_stm32::dma::NoDma; +use embassy_stm32::gpio::{Level, Output, Pin, Speed}; +use embassy_stm32::peripherals::SUBGHZSPI; +use embassy_stm32::rcc::low_level::RccPeripheral; +use embassy_stm32::spi::{BitOrder, Config as SpiConfig, Spi, MODE_0}; +use embassy_stm32::time::Hertz; +use embassy_stm32::{interrupt, into_ref, Peripheral}; +use embassy_time::{Delay, Duration, Timer}; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +const LORA_FREQUENCY_IN_HZ: u32 = 903_900_000; // warning: set this appropriately for the region + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = embassy_stm32::Config::default(); + config.rcc.mux = embassy_stm32::rcc::ClockSrc::HSE32; + let p = embassy_stm32::init(config); + + let clk = Hertz(core::cmp::min(SUBGHZSPI::frequency().0 / 2, 16_000_000)); + let mut spi_config = SpiConfig::default(); + spi_config.mode = MODE_0; + spi_config.bit_order = BitOrder::MsbFirst; + let spi = Spi::new_subghz(p.SUBGHZSPI, NoDma, NoDma, clk, spi_config); + + let spi = BlockingAsync::new(spi); + + let irq = interrupt::take!(SUBGHZ_RADIO); + into_ref!(irq); + // Set CTRL1 and CTRL3 for high-power transmission, while CTRL2 acts as an RF switch between tx and rx + let _ctrl1 = Output::new(p.PC4.degrade(), Level::Low, Speed::High); + let ctrl2 = Output::new(p.PC5.degrade(), Level::High, Speed::High); + let _ctrl3 = Output::new(p.PC3.degrade(), Level::High, Speed::High); + let iv = Stm32wlInterfaceVariant::new(irq, None, Some(ctrl2)).unwrap(); + + let mut delay = Delay; + + let mut lora = { + match LoRa::new(SX1261_2::new(BoardType::Stm32wlSx1262, spi, iv), false, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut debug_indicator = Output::new(p.PB9, Level::Low, Speed::Low); + let mut start_indicator = Output::new(p.PB15, Level::Low, Speed::Low); + + start_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + start_indicator.set_low(); + + let mut receiving_buffer = [00u8; 100]; + + let mdltn_params = { + match lora.create_modulation_params( + SpreadingFactor::_10, + Bandwidth::_250KHz, + CodingRate::_4_8, + LORA_FREQUENCY_IN_HZ, + ) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let rx_pkt_params = { + match lora.create_rx_packet_params(4, false, receiving_buffer.len() as u8, true, false, &mdltn_params) { + Ok(pp) => pp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + match lora + .prepare_for_rx(&mdltn_params, &rx_pkt_params, None, true, false, 0, 0x00ffffffu32) + .await + { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + loop { + receiving_buffer = [00u8; 100]; + match lora.rx(&rx_pkt_params, &mut receiving_buffer).await { + Ok((received_len, _rx_pkt_status)) => { + if (received_len == 3) + && (receiving_buffer[0] == 0x01u8) + && (receiving_buffer[1] == 0x02u8) + && (receiving_buffer[2] == 0x03u8) + { + info!("rx successful"); + debug_indicator.set_high(); + Timer::after(Duration::from_secs(5)).await; + debug_indicator.set_low(); + } else { + info!("rx unknown packet"); + } + } + Err(err) => info!("rx unsuccessful = {}", err), + } + } +} diff --git a/examples/stm32wl/src/bin/lora_p2p_send.rs b/examples/stm32wl/src/bin/lora_p2p_send.rs new file mode 100644 index 00000000..8a38402f --- /dev/null +++ b/examples/stm32wl/src/bin/lora_p2p_send.rs @@ -0,0 +1,110 @@ +//! This example runs on a STM32WL board, which has a builtin Semtech Sx1262 radio. +//! It demonstrates LORA P2P send functionality. +#![no_std] +#![no_main] +#![macro_use] +#![feature(type_alias_impl_trait, async_fn_in_trait)] +#![allow(incomplete_features)] + +use defmt::info; +use embassy_embedded_hal::adapter::BlockingAsync; +use embassy_executor::Spawner; +use embassy_lora::iv::Stm32wlInterfaceVariant; +use embassy_stm32::dma::NoDma; +use embassy_stm32::gpio::{Level, Output, Pin, Speed}; +use embassy_stm32::peripherals::SUBGHZSPI; +use embassy_stm32::rcc::low_level::RccPeripheral; +use embassy_stm32::spi::{BitOrder, Config as SpiConfig, Spi, MODE_0}; +use embassy_stm32::time::Hertz; +use embassy_stm32::{interrupt, into_ref, Peripheral}; +use embassy_time::Delay; +use lora_phy::mod_params::*; +use lora_phy::sx1261_2::SX1261_2; +use lora_phy::LoRa; +use {defmt_rtt as _, panic_probe as _}; + +const LORA_FREQUENCY_IN_HZ: u32 = 903_900_000; // warning: set this appropriately for the region + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + let mut config = embassy_stm32::Config::default(); + config.rcc.mux = embassy_stm32::rcc::ClockSrc::HSE32; + let p = embassy_stm32::init(config); + + let clk = Hertz(core::cmp::min(SUBGHZSPI::frequency().0 / 2, 16_000_000)); + let mut spi_config = SpiConfig::default(); + spi_config.mode = MODE_0; + spi_config.bit_order = BitOrder::MsbFirst; + let spi = Spi::new_subghz(p.SUBGHZSPI, NoDma, NoDma, clk, spi_config); + + let spi = BlockingAsync::new(spi); + + let irq = interrupt::take!(SUBGHZ_RADIO); + into_ref!(irq); + // Set CTRL1 and CTRL3 for high-power transmission, while CTRL2 acts as an RF switch between tx and rx + let _ctrl1 = Output::new(p.PC4.degrade(), Level::Low, Speed::High); + let ctrl2 = Output::new(p.PC5.degrade(), Level::High, Speed::High); + let _ctrl3 = Output::new(p.PC3.degrade(), Level::High, Speed::High); + let iv = Stm32wlInterfaceVariant::new(irq, None, Some(ctrl2)).unwrap(); + + let mut delay = Delay; + + let mut lora = { + match LoRa::new(SX1261_2::new(BoardType::Stm32wlSx1262, spi, iv), false, &mut delay).await { + Ok(l) => l, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mdltn_params = { + match lora.create_modulation_params( + SpreadingFactor::_10, + Bandwidth::_250KHz, + CodingRate::_4_8, + LORA_FREQUENCY_IN_HZ, + ) { + Ok(mp) => mp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + let mut tx_pkt_params = { + match lora.create_tx_packet_params(4, false, true, false, &mdltn_params) { + Ok(pp) => pp, + Err(err) => { + info!("Radio error = {}", err); + return; + } + } + }; + + match lora.prepare_for_tx(&mdltn_params, 20, false).await { + Ok(()) => {} + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + let buffer = [0x01u8, 0x02u8, 0x03u8]; + match lora.tx(&mdltn_params, &mut tx_pkt_params, &buffer, 0xffffff).await { + Ok(()) => { + info!("TX DONE"); + } + Err(err) => { + info!("Radio error = {}", err); + return; + } + }; + + match lora.sleep(&mut delay).await { + Ok(()) => info!("Sleep successful"), + Err(err) => info!("Sleep unsuccessful = {}", err), + } +} diff --git a/examples/stm32wl/src/bin/lorawan.rs b/examples/stm32wl/src/bin/lorawan.rs deleted file mode 100644 index 32f29cc5..00000000 --- a/examples/stm32wl/src/bin/lorawan.rs +++ /dev/null @@ -1,104 +0,0 @@ -#![no_std] -#![no_main] -#![macro_use] -#![allow(dead_code)] -#![feature(type_alias_impl_trait)] - -use embassy_executor::Spawner; -use embassy_lora::stm32wl::*; -use embassy_lora::LoraTimer; -use embassy_stm32::dma::NoDma; -use embassy_stm32::gpio::{AnyPin, Level, Output, Pin, Speed}; -use embassy_stm32::rng::Rng; -use embassy_stm32::subghz::*; -use embassy_stm32::{interrupt, pac}; -use lorawan::default_crypto::DefaultFactory as Crypto; -use lorawan_device::async_device::{region, Device, JoinMode}; -use {defmt_rtt as _, panic_probe as _}; - -struct RadioSwitch<'a> { - ctrl1: Output<'a, AnyPin>, - ctrl2: Output<'a, AnyPin>, - ctrl3: Output<'a, AnyPin>, -} - -impl<'a> RadioSwitch<'a> { - fn new(ctrl1: Output<'a, AnyPin>, ctrl2: Output<'a, AnyPin>, ctrl3: Output<'a, AnyPin>) -> Self { - Self { ctrl1, ctrl2, ctrl3 } - } -} - -impl<'a> embassy_lora::stm32wl::RadioSwitch for RadioSwitch<'a> { - fn set_rx(&mut self) { - self.ctrl1.set_high(); - self.ctrl2.set_low(); - self.ctrl3.set_high(); - } - - fn set_tx(&mut self) { - self.ctrl1.set_high(); - self.ctrl2.set_high(); - self.ctrl3.set_high(); - } -} - -#[embassy_executor::main] -async fn main(_spawner: Spawner) { - let mut config = embassy_stm32::Config::default(); - config.rcc.mux = embassy_stm32::rcc::ClockSrc::HSI16; - config.rcc.enable_lsi = true; - let p = embassy_stm32::init(config); - - unsafe { pac::RCC.ccipr().modify(|w| w.set_rngsel(0b01)) } - - let ctrl1 = Output::new(p.PC3.degrade(), Level::High, Speed::High); - let ctrl2 = Output::new(p.PC4.degrade(), Level::High, Speed::High); - let ctrl3 = Output::new(p.PC5.degrade(), Level::High, Speed::High); - let rfs = RadioSwitch::new(ctrl1, ctrl2, ctrl3); - - let radio = SubGhz::new(p.SUBGHZSPI, NoDma, NoDma); - let irq = interrupt::take!(SUBGHZ_RADIO); - - let mut radio_config = SubGhzRadioConfig::default(); - radio_config.calibrate_image = CalibrateImage::ISM_863_870; - let radio = SubGhzRadio::new(radio, rfs, irq, radio_config).unwrap(); - - let mut region = region::Configuration::new(region::Region::EU868); - - // NOTE: This is specific for TTN, as they have a special RX1 delay - region.set_receive_delay1(5000); - - let mut device: Device<_, Crypto, _, _> = Device::new(region, radio, LoraTimer::new(), Rng::new(p.RNG)); - - // Depending on network, this might be part of JOIN - device.set_datarate(region::DR::_0); // SF12 - - // device.set_datarate(region::DR::_1); // SF11 - // device.set_datarate(region::DR::_2); // SF10 - // device.set_datarate(region::DR::_3); // SF9 - // device.set_datarate(region::DR::_4); // SF8 - // device.set_datarate(region::DR::_5); // SF7 - - defmt::info!("Joining LoRaWAN network"); - - // TODO: Adjust the EUI and Keys according to your network credentials - device - .join(&JoinMode::OTAA { - deveui: [0, 0, 0, 0, 0, 0, 0, 0], - appeui: [0, 0, 0, 0, 0, 0, 0, 0], - appkey: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - }) - .await - .ok() - .unwrap(); - defmt::info!("LoRaWAN network joined"); - - let mut rx: [u8; 255] = [0; 255]; - defmt::info!("Sending 'PING'"); - let len = device.send_recv(b"PING", &mut rx[..], 1, true).await.ok().unwrap(); - if len > 0 { - defmt::info!("Message sent, received downlink: {:?}", &rx[..len]); - } else { - defmt::info!("Message sent!"); - } -} diff --git a/examples/stm32wl/src/bin/subghz.rs b/examples/stm32wl/src/bin/subghz.rs deleted file mode 100644 index 32c8b551..00000000 --- a/examples/stm32wl/src/bin/subghz.rs +++ /dev/null @@ -1,119 +0,0 @@ -#![no_std] -#![no_main] -#![macro_use] -#![allow(dead_code)] -#![feature(type_alias_impl_trait)] - -use defmt::*; -use embassy_executor::Spawner; -use embassy_stm32::dma::NoDma; -use embassy_stm32::exti::ExtiInput; -use embassy_stm32::gpio::{Input, Level, Output, Pull, Speed}; -use embassy_stm32::interrupt; -use embassy_stm32::interrupt::{Interrupt, InterruptExt}; -use embassy_stm32::subghz::*; -use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; -use embassy_sync::signal::Signal; -use {defmt_rtt as _, panic_probe as _}; - -const PING_DATA: &str = "PING"; -const DATA_LEN: u8 = PING_DATA.len() as u8; -const PING_DATA_BYTES: &[u8] = PING_DATA.as_bytes(); -const PREAMBLE_LEN: u16 = 5 * 8; - -const RF_FREQ: RfFreq = RfFreq::from_frequency(867_500_000); - -const SYNC_WORD: [u8; 8] = [0x79, 0x80, 0x0C, 0xC0, 0x29, 0x95, 0xF8, 0x4A]; -const SYNC_WORD_LEN: u8 = SYNC_WORD.len() as u8; -const SYNC_WORD_LEN_BITS: u8 = SYNC_WORD_LEN * 8; - -const TX_BUF_OFFSET: u8 = 128; -const RX_BUF_OFFSET: u8 = 0; -const LORA_PACKET_PARAMS: LoRaPacketParams = LoRaPacketParams::new() - .set_crc_en(true) - .set_preamble_len(PREAMBLE_LEN) - .set_payload_len(DATA_LEN) - .set_invert_iq(false) - .set_header_type(HeaderType::Fixed); - -const LORA_MOD_PARAMS: LoRaModParams = LoRaModParams::new() - .set_bw(LoRaBandwidth::Bw125) - .set_cr(CodingRate::Cr45) - .set_ldro_en(true) - .set_sf(SpreadingFactor::Sf7); - -// configuration for +10 dBm output power -// see table 35 "PA optimal setting and operating modes" -const PA_CONFIG: PaConfig = PaConfig::new().set_pa_duty_cycle(0x1).set_hp_max(0x0).set_pa(PaSel::Lp); - -const TCXO_MODE: TcxoMode = TcxoMode::new() - .set_txco_trim(TcxoTrim::Volts1pt7) - .set_timeout(Timeout::from_duration_sat(core::time::Duration::from_millis(10))); - -const TX_PARAMS: TxParams = TxParams::new().set_power(0x0D).set_ramp_time(RampTime::Micros40); - -#[embassy_executor::main] -async fn main(_spawner: Spawner) { - let mut config = embassy_stm32::Config::default(); - config.rcc.mux = embassy_stm32::rcc::ClockSrc::HSE32; - let p = embassy_stm32::init(config); - - let mut led1 = Output::new(p.PB15, Level::High, Speed::Low); - let mut led2 = Output::new(p.PB9, Level::Low, Speed::Low); - let mut led3 = Output::new(p.PB11, Level::Low, Speed::Low); - - let button = Input::new(p.PA0, Pull::Up); - let mut pin = ExtiInput::new(button, p.EXTI0); - - static IRQ_SIGNAL: Signal = Signal::new(); - let radio_irq = interrupt::take!(SUBGHZ_RADIO); - radio_irq.set_handler(|_| { - IRQ_SIGNAL.signal(()); - unsafe { interrupt::SUBGHZ_RADIO::steal() }.disable(); - }); - - let mut radio = SubGhz::new(p.SUBGHZSPI, NoDma, NoDma); - - defmt::info!("Radio ready for use"); - - led1.set_low(); - - led2.set_high(); - - unwrap!(radio.set_standby(StandbyClk::Rc)); - unwrap!(radio.set_tcxo_mode(&TCXO_MODE)); - unwrap!(radio.set_standby(StandbyClk::Hse)); - unwrap!(radio.set_regulator_mode(RegMode::Ldo)); - unwrap!(radio.set_buffer_base_address(TX_BUF_OFFSET, RX_BUF_OFFSET)); - unwrap!(radio.set_pa_config(&PA_CONFIG)); - unwrap!(radio.set_pa_ocp(Ocp::Max60m)); - unwrap!(radio.set_tx_params(&TX_PARAMS)); - unwrap!(radio.set_packet_type(PacketType::LoRa)); - unwrap!(radio.set_lora_sync_word(LoRaSyncWord::Public)); - unwrap!(radio.set_lora_mod_params(&LORA_MOD_PARAMS)); - unwrap!(radio.set_lora_packet_params(&LORA_PACKET_PARAMS)); - unwrap!(radio.calibrate_image(CalibrateImage::ISM_863_870)); - unwrap!(radio.set_rf_frequency(&RF_FREQ)); - - defmt::info!("Status: {:?}", unwrap!(radio.status())); - - led2.set_low(); - - loop { - pin.wait_for_rising_edge().await; - led3.set_high(); - unwrap!(radio.set_irq_cfg(&CfgIrq::new().irq_enable_all(Irq::TxDone))); - unwrap!(radio.write_buffer(TX_BUF_OFFSET, PING_DATA_BYTES)); - unwrap!(radio.set_tx(Timeout::DISABLED)); - - radio_irq.enable(); - IRQ_SIGNAL.wait().await; - - let (_, irq_status) = unwrap!(radio.irq_status()); - if irq_status & Irq::TxDone.mask() != 0 { - defmt::info!("TX done"); - } - unwrap!(radio.clear_irq_status(irq_status)); - led3.set_low(); - } -}