Initial Checkin

This commit is contained in:
Iain (Bill) Wiseman 2025-04-17 16:44:02 +12:00
commit 285cc1382d
15 changed files with 2224 additions and 0 deletions

16
.cargo/config.toml Normal file
View File

@ -0,0 +1,16 @@
[target.xtensa-esp32-none-elf]
runner = "espflash flash --monitor"
[env]
ESP_LOG="info"
[build]
rustflags = [
"-C", "link-arg=-nostartfiles",
]
target = "xtensa-esp32-none-elf"
[unstable]
build-std = ["core"]

13
.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
# Generated by Cargo
# will have compiled files and executables
debug/
target/
# These are backup files generated by rustfmt
**/*.rs.bk
# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
.env*
.vscode*

1364
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

48
Cargo.toml Normal file
View File

@ -0,0 +1,48 @@
[package]
name = "esp-lora-send"
version = "0.1.0"
authors = ["Iain (Bill) Wiseman <iwiseman@bibble.co.nz>"]
edition = "2021"
license = "MIT OR Apache-2.0"
[dependencies]
esp-backtrace = { version = "0.14.2", features = [
"esp32",
"exception-handler",
"panic-handler",
"println",
] }
esp-hal = { version = "0.23.1", features = [ "esp32" ] }
esp-println = { version = "0.12.0", features = ["esp32", "log"] }
esp-hal-embassy = { version = "0.6.0", features = ["esp32"] }
embassy-executor = { version = "0.7.0", features = ["task-arena-size-20480"] }
embassy-futures = "0.1.1"
embassy-sync = "0.6.0"
embassy-time = "0.4.0"
embassy-embedded-hal = "0.3.0"
static_cell = { version = "2.1.0", features = ["nightly"] }
log = { version = "0.4.22" }
lora-phy = "3.0.1"
fugit = "0.3.7"
embedded-graphics = "0.8.1"
ssd1306 = "0.10.0"
[profile.dev]
# Rust debug is too slow.
# For debug builds always builds with some optimization
opt-level = "s"
[profile.release]
codegen-units = 1 # LLVM can perform better optimizations using a single thread
debug = 2
debug-assertions = false
incremental = false
lto = 'fat'
opt-level = 's'
overflow-checks = false

201
LICENSE-APACHE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2021-2024 esp-rs
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

25
LICENSE-MIT Normal file
View File

@ -0,0 +1,25 @@
Copyright 2021-2024 esp-rs
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

68
README.md Normal file
View File

@ -0,0 +1,68 @@
# ESP Embassy LoRa Project
Welcome to the **ESP Embassy LoRa** project! This is a working example of how to configure an AP using embassy.
## Features
## Features
- Demonstrates LoRa sending and receiving functionality.
- Tested on a LoRa32 T3 v1.6.1 board.
- Adapted for the SX1276 module in New Zealand.
- Includes integration with an SSD1306 display for send and receive status.
- Based on the [lora-rs project](https://github.com/lora-rs/lora-rs/tree/main/examples/esp32).
## Requirements
- [espup](https://github.com/esp-rs/espup) for setting up the ESP32 Rust environment.
- [Rust](https://www.rust-lang.org/) (latest stable version recommended).
- A LoRa32 T3 v1.6.1 board with an SX1276 LoRa module.
- An SSD1306-compatible display (optional, for status updates).
## Installation
1. Clone the repository:
```bash
git clone https://github.com/bibble235/esp-lora.git
```
2. Navigate to the project directory:
```bash
cd esp-lora
```
## Usage
1. For receiving
Build and run the application with the receiver application:
```bash
ESPFLASH_PORT=/dev/ttyACM0 cargo run --bin receive
```
2. For sending
Build and run the application with the send application:
```bash
ESPFLASH_PORT=/dev/ttyACM1 cargo run --bin send
```
## License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
## Demonstration
Below is a screenshot of a Lora32 T3 v1.6.1 running this application:
![Screenshot of a Lora32 T3 v1.6.1 running this app.](./assets/images/two_loras.jpg)
## Contact
For questions or feedback, please contact [iwiseman@bibble.co.nz](mailto:iwiseman@bibble.co.nz).
---
![Rust](https://img.shields.io/badge/Rust-Language-black?logo=rust&logoColor=white)
![ESP32](https://img.shields.io/badge/ESP32-Microcontroller-blue)
![LoRa](https://img.shields.io/badge/LoRa-Wireless-green?logo=wifi&logoColor=white)

BIN
assets/images/T3_1.6.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 986 KiB

BIN
assets/images/two_loras.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 226 KiB

3
build.rs Normal file
View File

@ -0,0 +1,3 @@
fn main() {
println!("cargo:rustc-link-arg-bins=-Tlinkall.x");
}

2
rust-toolchain.toml Normal file
View File

@ -0,0 +1,2 @@
[toolchain]
channel = "esp"

209
src/bin/receive.rs Normal file
View File

@ -0,0 +1,209 @@
//! It demonstrates LORA P2P send functionality.
//! And is based of the example in https://github.com/lora-rs/lora-rs
#![no_std]
#![no_main]
mod shared;
use esp_backtrace as _;
use esp_println::println;
use embassy_time::{Duration, Timer};
use embassy_executor::Spawner;
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex};
use embassy_time::Delay;
use esp_hal::gpio::{Input, Level, Output, Pull};
use esp_hal::spi::{master::Config, master::Spi, Mode};
use esp_hal::Async;
use esp_hal::{clock::CpuClock, timer::timg::TimerGroup};
use fugit::RateExtU32;
use static_cell::StaticCell;
use lora_phy::iv::GenericSx127xInterfaceVariant;
use lora_phy::mod_params::{Bandwidth, CodingRate, SpreadingFactor};
use lora_phy::sx127x::{Sx1276, Sx127x};
use lora_phy::{sx127x, LoRa};
use lora_phy::RxMode;
const LORA_FREQUENCY_IN_HZ: u32 = 923_200_000; // WARNING: Set this appropriately for the region
static SPI_BUS: StaticCell<
Mutex<CriticalSectionRawMutex, esp_hal::spi::master::Spi<'static, Async>>,
> = StaticCell::new();
#[esp_hal_embassy::main]
async fn main(_spawner: Spawner) {
// Initialize line number for logging
let mut line_number = 0;
// Initialize the logger
esp_println::logger::init_logger_from_env();
println!("Starting LoRa P2P example");
// Set up ESP32
let peripherals = esp_hal::init(esp_hal::Config::default().with_cpu_clock(CpuClock::max()));
let timer_group = TimerGroup::new(peripherals.TIMG0);
esp_hal_embassy::init(timer_group.timer1);
println!("Send Embassy initialized");
// Initialize the display
let mut display =
match shared::Display::new(peripherals.I2C0, peripherals.GPIO22, peripherals.GPIO21) {
Ok(display) => display,
Err(err) => {
println!("Error initializing display: {:?}", err);
return;
}
};
// Initialize the SPI bus
let nss = Output::new(peripherals.GPIO18, Level::Low);
let sclk = peripherals.GPIO5;
let mosi = peripherals.GPIO27;
let miso = peripherals.GPIO19;
// Initialize the sx127x radio pins
let mut reset = Output::new(peripherals.GPIO23, Level::Low);
let dio1 = Input::new(peripherals.GPIO26, Pull::None);
println!("Pins Initialized");
let spi = Spi::new(
peripherals.SPI2,
Config::default()
.with_frequency(100.kHz())
.with_mode(Mode::_0),
)
.unwrap()
.with_sck(sclk)
.with_mosi(mosi)
.with_miso(miso)
.into_async();
// Initialize the static SPI bus
let spi_bus = SPI_BUS.init(Mutex::new(spi));
let spi_device = embassy_embedded_hal::shared_bus::asynch::spi::SpiDevice::new(spi_bus, nss);
// reset.set_low();
// Timer::after(Duration::from_millis(10)).await;
// reset.set_high();
// Timer::after(Duration::from_millis(10)).await;
println!("Receive SPI Initialized");
// We use Sx1276
// Create the SX126x configuration
let sx127x_config = sx127x::Config {
chip: Sx1276, // Specify the SX1276 chip
tcxo_used: false, // The LoRa32 T3 v1.6.1 uses a crystal oscillator, not a TCXO
tx_boost: true, // Use PA_BOOST for higher transmit power (depends on board layout)
rx_boost: true,
};
println!("Send SX127x configuration created");
// Create the radio instance
let iv = match GenericSx127xInterfaceVariant::new(reset, dio1, None, None) {
Ok(interface) => interface,
Err(err) => {
println!("Error creating GenericSx127xInterfaceVariant: {:?}", err);
return;
}
};
// Create the LoRa instance
let mut lora = match LoRa::new(Sx127x::new(spi_device, iv, sx127x_config), false, Delay).await {
Ok(lora_instance) => lora_instance,
Err(err) => {
println!("Error creating LoRa instance: {:?}", err);
return;
}
};
println!("Receive Radio Initialized");
let mut receiving_buffer = [00u8; 100];
let modulation_params = {
match lora.create_modulation_params(
SpreadingFactor::_10,
Bandwidth::_125KHz,
CodingRate::_4_8,
LORA_FREQUENCY_IN_HZ,
) {
Ok(mp) => {
println!("Modulation parameters created successfully");
mp
}
Err(err) => {
println!("Error creating modulation parameters: {:?}", err);
return;
}
}
};
display.write_text(line_number, "setup successful");
line_number = line_number + 1;
Timer::after(Duration::from_millis(200)).await;
let rx_packet_params = {
match lora.create_rx_packet_params(
4,
false,
receiving_buffer.len() as u8,
true,
false,
&modulation_params,
) {
Ok(pp) => pp,
Err(err) => {
println!("Radio error = {:?}", err);
return;
}
}
};
match lora
.prepare_for_rx(RxMode::Continuous, &modulation_params, &rx_packet_params)
.await
{
Ok(()) => {
display.write_text(line_number, "preparing successful");
line_number = line_number + 1;
Timer::after(Duration::from_millis(200)).await;
}
Err(err) => {
println!("Radio error = {:?}", err);
return;
}
};
let expected_msg = b"hello";
let expected_msg_len = expected_msg.len();
println!("Receive going into loop");
loop {
receiving_buffer = [00u8; 100];
match lora.rx(&rx_packet_params, &mut receiving_buffer).await {
Ok((received_len, _rx_pkt_status)) => {
if (received_len == expected_msg_len as u8)
&& (receiving_buffer[..expected_msg_len] == *expected_msg)
{
display.write_text(line_number, "receive successful");
line_number = 0;
println!(
"rx successful: {:?}",
core::str::from_utf8(&receiving_buffer[..received_len as usize]).unwrap()
);
} else {
println!("rx unknown packet");
}
}
Err(err) => println!("rx unsuccessful = {:?}", err),
}
}
}

181
src/bin/send.rs Normal file
View File

@ -0,0 +1,181 @@
//! It demonstrates LORA P2P send functionality.
//! And is based of the example in https://github.com/lora-rs/lora-rs
#![no_std]
#![no_main]
mod shared;
use embassy_embedded_hal::shared_bus::asynch::spi::SpiDevice;
use esp_backtrace as _;
use esp_hal::peripherals::Peripherals;
use esp_println::println;
use embassy_executor::Spawner;
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex};
use embassy_time::Delay;
use esp_hal::gpio::{Input, Level, Output, Pull};
use esp_hal::spi::{master::Config, master::Spi, Mode};
use esp_hal::{clock::CpuClock, timer::timg::TimerGroup};
use esp_hal::{peripheral, Async};
use fugit::RateExtU32;
use static_cell::StaticCell;
use lora_phy::iv::GenericSx127xInterfaceVariant;
use lora_phy::mod_params::{Bandwidth, CodingRate, SpreadingFactor};
use lora_phy::sx127x::{Sx1276, Sx127x};
use lora_phy::{sx127x, LoRa};
const LORA_FREQUENCY_IN_HZ: u32 = 923_200_000; // WARNING: Set this appropriately for the region
static SPI_BUS: StaticCell<
Mutex<CriticalSectionRawMutex, esp_hal::spi::master::Spi<'static, Async>>,
> = StaticCell::new();
#[esp_hal_embassy::main]
async fn main(_spawner: Spawner) {
// Initialize line number for logging
let mut line_number = 0;
// Initialize the logger
esp_println::logger::init_logger_from_env();
println!("Starting LoRa P2P example");
// Set up ESP32
let peripherals = esp_hal::init(esp_hal::Config::default().with_cpu_clock(CpuClock::max()));
let timer_group = TimerGroup::new(peripherals.TIMG0);
esp_hal_embassy::init(timer_group.timer1);
println!("Send Embassy initialized");
// Initialize the display
let mut display =
match shared::Display::new(peripherals.I2C0, peripherals.GPIO22, peripherals.GPIO21) {
Ok(display) => display,
Err(err) => {
println!("Error initializing display: {:?}", err);
return;
}
};
// Initialize the SPI bus
let nss = Output::new(peripherals.GPIO18, Level::Low);
let sclk = peripherals.GPIO5;
let mosi = peripherals.GPIO27;
let miso = peripherals.GPIO19;
// // Initialize the sx127x radio pins
let mut reset = Output::new(peripherals.GPIO23, Level::Low);
let dio0 = Input::new(peripherals.GPIO26, Pull::None);
println!("Pins Initialized");
let spi = Spi::new(
peripherals.SPI2,
Config::default()
.with_frequency(200.kHz())
.with_mode(Mode::_0),
)
.unwrap()
.with_sck(sclk)
.with_mosi(mosi)
.with_miso(miso)
.into_async();
// Initialize the static SPI bus
let spi_bus = SPI_BUS.init(Mutex::new(spi));
let spi_device = embassy_embedded_hal::shared_bus::asynch::spi::SpiDevice::new(spi_bus, nss);
println!("Send SPI initialized");
// Create the SX127x configuration
let sx127x_config = sx127x::Config {
chip: Sx1276, // Specify the SX1276 chip
tcxo_used: false, // The LoRa32 T3 v1.6.1 uses a crystal oscillator, not a TCXO
tx_boost: true, // Use PA_BOOST for higher transmit power (depends on board layout)
rx_boost: true,
};
println!("Send SX127x configuration created");
// Create the radio instance
let iv = match GenericSx127xInterfaceVariant::new(reset, dio0, None, None) {
Ok(interface) => interface,
Err(err) => {
println!("Error creating GenericSx127xInterfaceVariant: {:?}", err);
return;
}
};
// Create the LoRa instance
let mut lora = match LoRa::new(Sx127x::new(spi_device, iv, sx127x_config), false, Delay).await {
Ok(lora_instance) => lora_instance,
Err(err) => {
println!("Error creating LoRa instance: {:?}", err);
return;
}
};
let modulation_params = {
match lora.create_modulation_params(
SpreadingFactor::_10,
Bandwidth::_125KHz,
CodingRate::_4_8,
LORA_FREQUENCY_IN_HZ,
) {
Ok(mp) => mp,
Err(err) => {
println!("Radio error = {:?}", err);
return;
}
}
};
println!("Send Modulation parameters created");
let mut tx_packet_params = {
match lora.create_tx_packet_params(4, false, true, false, &modulation_params) {
Ok(pp) => pp,
Err(err) => {
println!("Radio error = {:?}", err);
return;
}
}
};
let buffer = b"hello";
display.write_text(line_number, "buffer creation successful");
line_number = line_number + 1;
match lora
.prepare_for_tx(&modulation_params, &mut tx_packet_params, 20, buffer)
.await
{
Ok(()) => {
println!("prepare_for_tx successful");
}
Err(err) => {
println!("Radio error = {:?}", err);
return;
}
};
match lora.tx().await {
Ok(()) => {
display.write_text(line_number, "send of hello successful");
line_number = line_number + 1;
}
Err(err) => {
println!("Radio error = {:?}", err);
return;
}
};
match lora.sleep(false).await {
Ok(()) => {
display.write_text(line_number, "sleep successful");
line_number = 0;
}
Err(err) => println!("Sleep unsuccessful = {:?}", err),
}
}

91
src/bin/shared/display.rs Normal file
View File

@ -0,0 +1,91 @@
use embedded_graphics::mono_font::ascii::FONT_6X10;
use embedded_graphics::mono_font::MonoTextStyleBuilder;
use esp_hal::gpio::interconnect::PeripheralOutput;
use esp_hal::peripheral::Peripheral;
use esp_println::println;
use embedded_graphics::mono_font::MonoTextStyle;
use embedded_graphics::pixelcolor::BinaryColor;
use embedded_graphics::prelude::Point;
use embedded_graphics::text::Baseline;
use embedded_graphics::text::Text;
use embedded_graphics::Drawable;
use esp_hal::i2c::master::I2c;
use esp_hal::Blocking;
use ssd1306::mode::BufferedGraphicsMode;
use ssd1306::mode::DisplayConfig;
use ssd1306::prelude::DisplayRotation;
use ssd1306::prelude::I2CInterface;
use ssd1306::size::DisplaySize128x64;
use ssd1306::I2CDisplayInterface;
use ssd1306::Ssd1306;
#[derive(Debug)]
pub enum DisplayError {
InitializationError,
CommunicationError,
}
pub struct Display<'a> {
display: Ssd1306<
I2CInterface<I2c<'a, Blocking>>,
DisplaySize128x64,
BufferedGraphicsMode<DisplaySize128x64>,
>,
text_style: MonoTextStyle<'static, BinaryColor>,
}
impl<'a> Display<'a> {
/// Initialize the display with the given I2C pins
pub fn new(
i2c: impl Peripheral<P = impl esp_hal::i2c::master::Instance> + 'a,
scl: impl Peripheral<P = impl PeripheralOutput> + 'a,
sda: impl Peripheral<P = impl PeripheralOutput> + 'a,
) -> Result<Display<'a>, DisplayError> {
let i2c = I2c::new(i2c, esp_hal::i2c::master::Config::default())
.unwrap()
.with_scl(scl)
.with_sda(sda);
// let i2c = i2c.with_scl(scl.clone()).with_sda(sda.clone());
let interface = I2CDisplayInterface::new(i2c);
let mut display = Ssd1306::new(interface, DisplaySize128x64, DisplayRotation::Rotate0)
.into_buffered_graphics_mode();
display.init().unwrap();
// Create the text style
let text_style = MonoTextStyleBuilder::new()
.font(&FONT_6X10)
.text_color(BinaryColor::On)
.build();
Ok(Display {
display,
text_style,
})
}
pub fn clear(&mut self) {
// Clear the display
self.display.clear_buffer();
self.display.flush().unwrap();
}
/// Write text to the display
pub fn write_text(&mut self, line: i32, text: &str) {
println!("{}", text);
Text::with_baseline(
text,
Point::new(0, line * 16),
self.text_style,
Baseline::Top,
)
.draw(&mut self.display)
.unwrap();
self.display.flush().unwrap();
}
}

3
src/bin/shared/mod.rs Normal file
View File

@ -0,0 +1,3 @@
pub mod display;
pub use display::Display;