Skip to content

Commit

Permalink
feat: Use shared i2c (with async ssd1306 fork)
Browse files Browse the repository at this point in the history
  • Loading branch information
Sycrosity committed Apr 25, 2024
1 parent 7469a25 commit cd1a4c3
Show file tree
Hide file tree
Showing 8 changed files with 140 additions and 118 deletions.
89 changes: 71 additions & 18 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ embassy-embedded-hal = { version = "0.1.0" }
ssd1306 = { version = "0.9.0" }
httparse = { version = "1.8.0", default-features = false }
display-interface = "0.5.0"
heapless = "0.8.0"

[build-dependencies]
dotenv = "0.15.0"
Expand Down Expand Up @@ -121,4 +122,4 @@ log = [
# async = []

[patch.crates-io]
ssd1306 = { version = "0.9.0", git = "https://github.com/embedevices-rs/ssd1306" }
ssd1306 = { version = "0.9.0", git = "https://github.com/embedevices-rs/ssd1306", branch = "async" }
4 changes: 2 additions & 2 deletions src/blink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ pub async fn blink(mut led: AnyPin<Output<PushPull>>) {
on = !on;

if on {
info!("ON!")
info!("ON!");
} else {
info!("OFF!")
info!("OFF!");
}

Timer::after(Duration::from_millis(1000)).await;
Expand Down
37 changes: 22 additions & 15 deletions src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ use core::fmt::{Debug, Write};

use ssd1306::{prelude::*, I2CDisplayInterface, Ssd1306};

const MAX_CHARS: usize =
(DisplaySize128x64::WIDTH / 8) as usize * (DisplaySize128x64::HEIGHT / 8) as usize;

#[derive(Debug, Clone)]
#[allow(unused)]
enum DisplayError {
Expand All @@ -29,42 +32,46 @@ impl From<ssd1306::mode::TerminalModeError> for DisplayError {
}

async fn screen_counter_internal(i2c: &mut SharedI2C) -> Result<(), DisplayError> {
error!("init screen");
info!("Initialising screen...");

let i2c = I2CDisplayInterface::new(i2c);

let mut display = Ssd1306::new(i2c, DisplaySize128x64, DisplayRotation::Rotate0);
display.init()?;
display.init().await?;

display.clear().await?;

display.clear()?;
info!("Screen Initialised!");

let mut display = display.into_terminal_mode();

let mut counter: u16 = 0;

loop {
Timer::after_millis(1).await;
display.reset_pos().await?;

let mut string: String<MAX_CHARS> = String::new();

display.reset_pos()?;
string.write_fmt(format_args!("{counter}"))?;

display.write_fmt(format_args!("{}", counter))?;
display.write_str(&string).await?;

counter = match counter.checked_add(1) {
Some(next) => next,
None => {
display.clear()?;
1
}
counter = if let Some(next) = counter.checked_add(1) {
next
} else {
display.clear().await?;
1
};
}
}

#[task]
pub async fn screen_counter(mut i2c: SharedI2C) {
loop {
match screen_counter_internal(&mut i2c).await {
Ok(_) => unreachable!(),
Err(e) => warn!("Display error: {e:?}"),
if let Err(e) = screen_counter_internal(&mut i2c).await {
warn!("Display error: {e:?}");
} else {
unreachable!()
}

Timer::after_secs(1).await;
Expand Down
34 changes: 7 additions & 27 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,56 +20,36 @@ pub mod prelude {

pub const SSID: &str = env!("SSID");
pub const PASSWORD: &str = env!("PASSWORD");
pub const TICKS_PER_SECOND: u64 = 16_000_000;

#[cfg(feature = "async")]
pub type SharedI2C = I2cDevice<
'static,
embassy_sync::blocking_mutex::raw::NoopRawMutex,
I2C<'static, hal::peripherals::I2C0, Async>,
>;

#[cfg(not(feature = "async"))]
pub type SharedI2C = I2cDevice<
'static,
embassy_sync::blocking_mutex::raw::NoopRawMutex,
I2C<'static, hal::peripherals::I2C0, Blocking>,
>;
pub const TICKS_PER_SECOND: u64 = 16_000_000;

pub use core::f64::consts::PI;

pub use crate::errors::*;

#[cfg(feature = "async")]
pub use embassy_embedded_hal::shared_bus::asynch::i2c::I2cDevice;
#[cfg(not(feature = "async"))]
pub use embassy_embedded_hal::shared_bus::blocking::i2c::I2cDevice;
#[cfg(not(feature = "async"))]
pub use embassy_sync::blocking_mutex::Mutex;
#[cfg(feature = "async")]
pub use embassy_sync::mutex::Mutex;
pub use embassy_sync::{blocking_mutex::raw::NoopRawMutex, mutex::Mutex, signal::Signal};

pub use embassy_sync::blocking_mutex::raw::NoopRawMutex;
pub type SharedI2C =
I2cDevice<'static, NoopRawMutex, I2C<'static, esp_hal::peripherals::I2C0, Async>>;

#[allow(unused)]
pub use esp_backtrace as _;
pub use esp_hal as hal;

pub use esp_println::{print, println};

pub use embassy_executor::task;

pub use embassy_sync::signal::Signal;

use hal::Blocking;
pub use hal::{
pub use esp_hal::{
embassy,
gpio::{AnyPin, Output, PushPull},
i2c::I2C,
prelude::*,
Async,
};

pub use heapless::String;

pub use nb::block;

pub use embassy_time::{Delay, Duration, Instant, Ticker, Timer};
Expand Down
30 changes: 8 additions & 22 deletions src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ pub fn init_logger(level: log::LevelFilter) {
}

pub fn init_logger_from_env() {
const LEVEL: Option<&'static str> = option_env!("ESP_LOGLEVEL");

unsafe {
log::set_logger_racy(&Logger).unwrap();
}

const LEVEL: Option<&'static str> = option_env!("ESP_LOGLEVEL");

if let Some(lvl) = LEVEL {
let level = LevelFilter::from_str(lvl).unwrap_or(LevelFilter::Off);
unsafe { log::set_max_level_racy(level) };
Expand All @@ -38,17 +38,12 @@ impl log::Log for Logger {

#[allow(unused)]
fn log(&self, record: &log::Record) {
// check enabled log targets if any
// if let Some(targets) = LOG_TARGETS {
// if targets
// .split(",")
// .map(|x| {let pos = &x.find('=').unwrap_or_else({;}); x.split_at(pos); x } )
// .find(|(target, level): | record.target().starts_with(v))
// .is_none()
// {
// return;
// }
// }
const RESET: &str = "\u{001B}[0m";
const RED: &str = "\u{001B}[31m";
const GREEN: &str = "\u{001B}[32m";
const YELLOW: &str = "\u{001B}[33m";
const BLUE: &str = "\u{001B}[34m";
const CYAN: &str = "\u{001B}[35m";

if let Some(targets) = LOG_TARGETS {
if targets
Expand All @@ -64,15 +59,6 @@ impl log::Log for Logger {
};
}

// let level = ;

const RESET: &str = "\u{001B}[0m";
const RED: &str = "\u{001B}[31m";
const GREEN: &str = "\u{001B}[32m";
const YELLOW: &str = "\u{001B}[33m";
const BLUE: &str = "\u{001B}[34m";
const CYAN: &str = "\u{001B}[35m";

let color = match record.level() {
log::Level::Error => RED,
log::Level::Warn => YELLOW,
Expand Down
Loading

0 comments on commit cd1a4c3

Please sign in to comment.