Skip to content

Commit

Permalink
add better errors, a retry function + async display init
Browse files Browse the repository at this point in the history
  • Loading branch information
Sycrosity committed Jan 10, 2024
1 parent de445e5 commit 610fd3e
Show file tree
Hide file tree
Showing 9 changed files with 171 additions and 53 deletions.
2 changes: 1 addition & 1 deletion .cargo/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ target = "xtensa-esp32-none-elf"

[unstable]
build-std = [
"alloc",
# "alloc",
"core"
]
20 changes: 10 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 8 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,27 +17,30 @@ esp-alloc = { version = "0.3.0", optional = true }

log = "0.4.20"
embedded-error-chain = "1.0.0"
static_cell = "2.0.0"
static_cell = "2"

shared-bus = { version = "0.3.1", features = ["xtensa"] }
embedded-graphics = { version = "0.8.1", features = ["nalgebra_support"] }
nalgebra = { version = "0.32.3", default-features = false }

embedded-svc = { version = "0.26.4", default-features = false, features = ["log"] }
embedded-io = "0.6.1"
heapless = { version = "0.8.0", default-features = false }

embedded-graphics = { version = "0.8.1", features = ["nalgebra_support"] }
ssd1306 = "0.8.4"


embassy-executor = { version = "0.4.0", features = ["nightly", "log"] }
embassy-time = { version = "0.2.0", features = ["log"] }
embassy-sync = { version = "0.5.0", features = ["log"] }
embassy-net = { version = "0.3.0", features = ["log"], optional = true }

mpu6050 = { version = "0.1.6", git = "https://github.com/Sycrosity/mpu6050" }
shared-bus = { version = "0.3.1", features = ["xtensa"] }
nalgebra = { version = "0.32.3", default-features = false }
ssd1306 = "0.8.4"

[features]
alloc = ["dep:esp-alloc"]
net = [
# "dep:esp-wifi",
"dep:embassy-net"
]
# log = ["dep:log",""]
114 changes: 80 additions & 34 deletions src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use crate::{
prelude::*,
};

// use alloc::format;
use core::fmt::{self, Write};
use esp32_hal::{i2c::I2C, peripherals::I2C0};
use ssd1306::{
Expand All @@ -14,49 +13,112 @@ use ssd1306::{

type DisplayInternals<SIZE> = Ssd1306<I2CInterface<I2CShared>, SIZE, TerminalMode>;

type Result<T> = core::result::Result<T, Error<DisplayError>>;

#[derive(Clone, Copy, ErrorCategory)]
#[error_category(links(DisplayError))]
#[repr(u8)]
pub enum DisplayError {
/// Display initialisation failed
InitFailed,
/// The Display was used before initialisation
Uninitialised,
/// An error occured while attempting to write to the screen
WriteError,
/// A write location was specified outside of the screen
OutOfBounds,
/// An error with the underlying interface of the display
#[error("{variant}: {summary}")]
InterfaceError,
ClearError,
}

impl From<TerminalModeError> for DisplayError {
fn from(value: TerminalModeError) -> Self {
match value {
TerminalModeError::InterfaceError(_) => Self::InterfaceError,
TerminalModeError::Uninitialized => Self::Uninitialised,
TerminalModeError::OutOfBounds => Self::OutOfBounds,
}
}
}

impl From<core::fmt::Error> for DisplayError {
fn from(_value: core::fmt::Error) -> Self {
Self::WriteError
}
}

pub struct Display<SIZE> {
display: DisplayInternals<SIZE>,
}

impl<SIZE: DisplaySize + TerminalDisplaySize> Display<SIZE> {
pub fn new(i2c: I2CShared, display_size: SIZE) -> Self {
pub async fn new(i2c: I2CShared, display_size: SIZE) -> Result<Self> {
let interface = I2CDisplayInterface::new(i2c);

let mut display =
let display =
Ssd1306::new(interface, display_size, DisplayRotation::Rotate0).into_terminal_mode();

display.init().unwrap();
let mut display = Self { display };

// display.display.init()?;

display.clear().unwrap();
display.try_init().await?;

Self { display }
if let Err(e) = display.clear() {
error!("{e:?}")
};

Ok(display)
}

fn init(&mut self) -> Result<()> {
self.display.init().map_err(DisplayError::from)?;
Ok(())
}

pub fn clear(&mut self) -> Result<(), TerminalModeError> {
self.display.clear()
async fn try_init(&mut self) -> Result<()> {
try_repeat(|| self.init(), DEFAULT_INTERVAL, DEFAULT_MAX_ELAPSED_TIME).await?;
debug!("Initialised Display");
Ok(())
}

pub fn quick_clear(&mut self) {
pub fn clear(&mut self) -> Result<()> {
self.display
.clear()
.map_err(DisplayError::from)
.chain_err(DisplayError::ClearError)?;
Ok(())
}

pub fn quick_clear(&mut self) -> Result<()> {
if let Err(e) = self.set_position(0, 0) {
warn!("{e:?}");
self.clear();
self.clear()?;
};
if let Err(e) = self.display.write_str("") {
warn!("{e:?}");
self.clear();
self.clear()?;
};
Ok(())
}

pub fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> {
self.display.write_str(s)
pub fn write_str(&mut self, s: &str) -> Result<()> {
self.display.write_str(s).map_err(DisplayError::from)?;
Ok(())
}

pub fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<(), fmt::Error> {
self.display.write_fmt(args)
pub fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<()> {
self.display.write_fmt(args).map_err(DisplayError::from)?;
Ok(())
}

pub fn set_position(&mut self, column: u8, row: u8) -> Result<(), TerminalModeError> {
self.display.set_position(column, row)
pub fn set_position(&mut self, column: u8, row: u8) -> Result<()> {
self.display
.set_position(column, row)
.map_err(DisplayError::from)?;
Ok(())
}
}

Expand Down Expand Up @@ -88,8 +150,6 @@ pub async fn display_numerical_data(
loop {
let mpu_data = MPU_SIGNAL.wait().await;

// Timer::after_millis(1).await;

display.quick_clear();

if let Err(e) = display
Expand All @@ -108,20 +168,6 @@ pub async fn display_numerical_data(
warn!("{e:?}");
display.clear();
};

// display
// .write_fmt(format_args!(
// "temp: {:.4}c\nacc: (x,y,z)\n{:.1}, {:.1}, {:.1}\ngyro:\n{:.1},{:.1},{:.1}\nroll/pitch:\n{:.2}, {:.2}",
// mpu_data.temp,
// mpu_data.acc.x,
// mpu_data.acc.y,
// mpu_data.acc.z,
// mpu_data.gyro.x,
// mpu_data.gyro.y,
// mpu_data.gyro.z,
// mpu_data.roll_pitch.x,
// mpu_data.roll_pitch.y
// ))
// .unwrap();
}
}
// farago
10 changes: 10 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use crate::prelude::*;

#[derive(Clone, Copy, ErrorCategory)]
#[repr(u8)]
pub enum CansatError {
I2C,
Unknown,
IntegerOverflow,
InterfaceError,
}
13 changes: 12 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@
#![no_main]
#![feature(type_alias_impl_trait)]
#![allow(unused)]
#![allow(clippy::unused_unit)]

pub mod blink;
pub mod display;
pub mod errors;
pub mod mpu6050;
pub mod utils;

#[cfg(feature = "alloc")]
extern crate alloc;
Expand Down Expand Up @@ -33,10 +36,18 @@ pub mod prelude {
shared_bus::XtensaMutex<hal::i2c::I2C<'static, hal::peripherals::I2C0>>,
>;

pub const DEFAULT_INTERVAL: Duration = Duration::from_millis(500);

pub const DEFAULT_MAX_ELAPSED_TIME: Duration = Duration::from_secs(5);

pub use crate::{errors::*, utils::*};

pub use esp32_hal as hal;
pub use esp_backtrace as _;
pub use esp_println as _;

pub use embedded_error_chain::prelude::*;

pub use embassy_executor::task;
pub use esp_println::println;

Expand All @@ -46,7 +57,7 @@ pub mod prelude {
prelude::*,
};

pub use embassy_time::{Duration, Timer};
pub use embassy_time::{Duration, Instant, Ticker, Timer};

pub use log::{debug, error, info, trace, warn};
}
4 changes: 3 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ async fn main(spawner: Spawner) -> ! {
//we must share the i2c bus between the two, as otherwise the functions want to "own" the i2c bus themselves
let shared_i2c = shared_bus::new_xtensa!(I2C<'static,I2C0> = i2c).unwrap();

let display = Display::new(shared_i2c.acquire_i2c(), ssd1306::size::DisplaySize128x64);
let display = Display::new(shared_i2c.acquire_i2c(), ssd1306::size::DisplaySize128x64)
.await
.unwrap();

let mpu = mpu6050::Mpu6050::new(shared_i2c.acquire_i2c());

Expand Down
16 changes: 15 additions & 1 deletion src/mpu6050.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ use nalgebra::{Vector2, Vector3};
pub type MpuSignal = Signal<CriticalSectionRawMutex, MpuData>;
pub static MPU_SIGNAL: MpuSignal = Signal::new();

#[derive(Clone, Copy, ErrorCategory)]
#[repr(u8)]
pub enum MpuError {
InitFailed,
ReadoutFailed,
}

#[derive(Debug)]
pub struct MpuData {
pub roll_pitch: Vector2<f32>,
Expand Down Expand Up @@ -58,6 +65,13 @@ pub async fn mpu6050_stream(
// mpu.

loop {
// let mpu_data = MpuData {
// roll_pitch: mpu.get_acc_angles(),
// temp: mpu.get_temp(),
// gyro: mpu.get_gyro_deg(),
// acc: mpu.get_acc().chain_err(CansatError::I2C)
// };

let mpu_data = MpuData {
roll_pitch: mpu.get_acc_angles().unwrap(),
temp: mpu.get_temp().unwrap(),
Expand All @@ -69,6 +83,6 @@ pub async fn mpu6050_stream(

MPU_SIGNAL.signal(mpu_data);

Timer::after_millis(25).await;
Timer::after_millis(100).await;
}
}
Loading

0 comments on commit 610fd3e

Please sign in to comment.