use crate::error::Error; use display_interface_i2c::I2CInterface; use embedded_graphics::{ mono_font::{ascii::FONT_10X20, MonoTextStyle}, pixelcolor::BinaryColor, prelude::*, text::{Alignment, Text}, }; use esp_idf_svc::hal::i2c::I2cDriver; use ssd1306::{ prelude::*, rotation::DisplayRotation, size::DisplaySize, I2CDisplayInterface, Ssd1306, }; // clear the stage of failure of the display #[derive(Debug)] pub enum DisplayError { SetupError(display_interface::DisplayError), DrawingError, FlushError, } pub struct Display<'a, SIZE: DisplaySize> { display: Ssd1306>, SIZE, ssd1306::mode::BufferedGraphicsMode>, } impl<'a, SIZE: DisplaySize> Display<'a, SIZE> { /// Function to create a new display interface abstraction pub fn new( i2c: I2cDriver<'a>, size: SIZE, rotation: DisplayRotation, ) -> Result, Error> { // Construct the I2C driver into a display interface let interface = I2CDisplayInterface::new(i2c); // Construct display with new anew driver let mut display = Ssd1306::new(interface, size, rotation).into_buffered_graphics_mode(); display .init() .map_err(|err| Error::DisplayError(DisplayError::SetupError(err)))?; Ok(Display { display }) } /// Function to draw a given set of text to a display pub fn draw(&mut self, text: &str) -> Result<(), Error> { // Clear display ready for next write let style = MonoTextStyle::new(&FONT_10X20, BinaryColor::On); self.display .clear(BinaryColor::Off) .map_err(|_| Error::DisplayError(DisplayError::DrawingError))?; // Draw text to Display Text::with_alignment(text, Point::new(64, 20), style, Alignment::Center) .draw(&mut self.display) .map_err(|_| Error::DisplayError(DisplayError::DrawingError))?; //Flush data to the display self.display .flush() .map_err(|_| Error::DisplayError(DisplayError::FlushError))?; Ok(()) } }