Files
creaturedex/src/display/tertiary_lcd.rs
T

101 lines
2.7 KiB
Rust

use embedded_hal::i2c::I2c;
use esp_hal::delay::Delay;
use i2c_character_display::{CharacterDisplayPCF8574T, LcdDisplayType};
use log::error;
pub type TertiaryLcd<I2C> = CharacterDisplayPCF8574T<I2C, Delay>;
pub fn init_tertiary_lcd<I2C>(i2c: I2C) -> TertiaryLcd<I2C>
where
I2C: I2c,
{
let mut lcd = CharacterDisplayPCF8574T::new(i2c, LcdDisplayType::Lcd16x2, Delay::new());
match lcd.init() {
Ok(()) => {
log::info!("I2C tertiary LCD initialized on PCF8574T at address 0x27");
lcd
}
Err(_) => {
error!(
"I2C tertiary LCD init failed on PCF8574T at address 0x27; check bus wiring, power, and device address"
);
panic!("tertiary LCD initialization failed");
}
}
}
pub fn write_line<I2C>(
lcd: &mut TertiaryLcd<I2C>,
line: u8,
text: &str,
) -> Result<(), i2c_character_display::CharacterDisplayError<I2C>>
where
I2C: I2c,
{
if let Err(e) = lcd.set_cursor(0, line) {
error!("I2C LCD cursor move failed on line {line}; bus or device may be unavailable");
return Err(e);
}
if let Err(e) = lcd.print(text) {
error!(
"I2C LCD print failed on line {line}; payload length={} and device may be busy or disconnected",
text.len()
);
return Err(e);
}
Ok(())
}
pub fn write_wrapped<I2C>(
lcd: &mut TertiaryLcd<I2C>,
text: &str,
) -> Result<(), i2c_character_display::CharacterDisplayError<I2C>>
where
I2C: I2c,
{
const DISPLAY_WIDTH: usize = 16;
const DISPLAY_ROWS: usize = 2;
if let Err(e) = lcd.clear() {
error!(
"I2C LCD clear failed before wrapped write; check the shared bus and display response"
);
return Err(e);
}
let mut offset = 0;
for row in 0..DISPLAY_ROWS {
let remaining = &text[offset..];
if remaining.is_empty() {
return Ok(());
}
let chunk = if remaining.len() > DISPLAY_WIDTH {
&remaining[..DISPLAY_WIDTH]
} else {
remaining
};
if let Err(e) = lcd.set_cursor(0, row as u8) {
error!(
"I2C LCD cursor move failed while writing wrapped row {row}; bus may be busy or device unresponsive"
);
return Err(e);
}
if let Err(e) = lcd.print(chunk) {
error!(
"I2C LCD wrapped write failed on row {row}; chunk length={} and text may exceed display width",
chunk.len()
);
return Err(e);
}
offset += chunk.len();
if offset >= text.len() {
return Ok(());
}
}
Ok(())
}