Add support for the stm32 ltdc display peripheral

This commit is contained in:
David Haig 2024-06-27 20:13:20 +01:00
parent 26e660722c
commit 0e84bd8a91
5 changed files with 933 additions and 51 deletions

View File

@ -72,7 +72,8 @@ rand_core = "0.6.3"
sdio-host = "0.5.0"
critical-section = "1.1"
#stm32-metapac = { version = "15" }
stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-a8ab0a3421ed0ca4b282f54028a0a2decacd8631" }
#stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-a8ab0a3421ed0ca4b282f54028a0a2decacd8631" }
stm32-metapac = { git = "https://github.com/ninjasource/stm32-data-generated", branch = "stm32-ltdc", commit = "4c902fcd0889619e8af8bc03fa13b45c56fb3540" }
vcell = "0.1.3"
nb = "1.0.0"
@ -97,7 +98,7 @@ proc-macro2 = "1.0.36"
quote = "1.0.15"
#stm32-metapac = { version = "15", default-features = false, features = ["metadata"]}
stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-a8ab0a3421ed0ca4b282f54028a0a2decacd8631", default-features = false, features = ["metadata"] }
stm32-metapac = { git = "https://github.com/ninjasource/stm32-data-generated", branch = "stm32-ltdc", commit = "4c902fcd0889619e8af8bc03fa13b45c56fb3540", default-features = false, features = ["metadata"] }
[features]
default = ["rt"]

View File

@ -1,19 +1,184 @@
//! LTDC
use core::marker::PhantomData;
//! LTDC - LCD-TFT Display Controller
//! See ST application note AN4861: Introduction to LCD-TFT display controller (LTDC) on STM32 MCUs for high level details
//! This module was tested against the stm32h735g-dk using the RM0468 ST reference manual for detailed register information
use crate::rcc::{self, RccPeripheral};
use crate::{peripherals, Peripheral};
use crate::{
gpio::{AfType, OutputType, Speed},
interrupt::{self, typelevel::Interrupt},
peripherals, rcc, Peripheral,
};
use core::{future::poll_fn, marker::PhantomData, task::Poll};
use embassy_hal_internal::{into_ref, PeripheralRef};
use embassy_sync::waitqueue::AtomicWaker;
use stm32_metapac::ltdc::{
regs::Dccr,
vals::{Bf1, Bf2, Cfuif, Clif, Crrif, Cterrif, Pf, Vbr},
};
static LTDC_WAKER: AtomicWaker = AtomicWaker::new();
/// LTDC error
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
/// FIFO underrun. Generated when a pixel is requested while the FIFO is empty
FifoUnderrun,
/// Transfer error. Generated when a bus error occurs
TransferError,
}
/// Display configuration parameters
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct LtdcConfiguration {
/// Active width in pixels
pub active_width: u16,
/// Active height in pixels
pub active_height: u16,
/// Horizontal back porch (in units of pixel clock period)
pub h_back_porch: u16,
/// Horizontal front porch (in units of pixel clock period)
pub h_front_porch: u16,
/// Vertical back porch (in units of horizontal scan line)
pub v_back_porch: u16,
/// Vertical front porch (in units of horizontal scan line)
pub v_front_porch: u16,
/// Horizontal synchronization width (in units of pixel clock period)
pub h_sync: u16,
/// Vertical synchronization height (in units of horizontal scan line)
pub v_sync: u16,
/// Horizontal synchronization polarity: `false`: active low, `true`: active high
pub h_sync_polarity: PolarityActive,
/// Vertical synchronization polarity: `false`: active low, `true`: active high
pub v_sync_polarity: PolarityActive,
/// Data enable polarity: `false`: active low, `true`: active high
pub data_enable_polarity: PolarityActive,
/// Pixel clock polarity: `false`: falling edge, `true`: rising edge
pub pixel_clock_polarity: PolarityEdge,
}
/// Edge polarity
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum PolarityEdge {
/// Falling edge
FallingEdge,
/// Rising edge
RisingEdge,
}
/// Active polarity
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum PolarityActive {
/// Active low
ActiveLow,
/// Active high
ActiveHigh,
}
/// LTDC driver.
pub struct Ltdc<'d, T: Instance> {
_peri: PhantomData<&'d mut T>,
_peri: PeripheralRef<'d, T>,
}
/// LTDC interrupt handler.
pub struct InterruptHandler<T: Instance> {
_phantom: PhantomData<T>,
}
/// 24 bit color
#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct RgbColor {
/// Red
pub red: u8,
/// Green
pub green: u8,
/// Blue
pub blue: u8,
}
/// Layer
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct LtdcLayerConfig {
/// Layer number
pub layer: LtdcLayer,
/// Pixel format
pub pixel_format: PixelFormat,
/// Window left x in pixels
pub window_x0: u16,
/// Window right x in pixels
pub window_x1: u16,
/// Window top y in pixels
pub window_y0: u16,
/// Window bottom y in pixels
pub window_y1: u16,
}
/// Pixel format
#[repr(u8)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum PixelFormat {
/// ARGB8888
ARGB8888 = Pf::ARGB8888 as u8,
/// RGB888
RGB888 = Pf::RGB888 as u8,
/// RGB565
RGB565 = Pf::RGB565 as u8,
/// ARGB1555
ARGB1555 = Pf::ARGB1555 as u8,
/// ARGB4444
ARGB4444 = Pf::ARGB4444 as u8,
/// L8 (8-bit luminance)
L8 = Pf::L8 as u8,
/// AL44 (4-bit alpha, 4-bit luminance
AL44 = Pf::AL44 as u8,
/// AL88 (8-bit alpha, 8-bit luminance)
AL88 = Pf::AL88 as u8,
}
impl PixelFormat {
/// Number of bytes per pixel
pub fn bytes_per_pixel(&self) -> usize {
match self {
PixelFormat::ARGB8888 => 4,
PixelFormat::RGB888 => 3,
PixelFormat::RGB565 | PixelFormat::ARGB4444 | PixelFormat::ARGB1555 | PixelFormat::AL88 => 2,
PixelFormat::AL44 | PixelFormat::L8 => 1,
}
}
}
/// Ltdc Blending Layer
#[repr(usize)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum LtdcLayer {
/// Bottom layer
Layer1 = 0,
/// Top layer
Layer2 = 1,
}
impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
unsafe fn on_interrupt() {
cortex_m::asm::dsb();
Ltdc::<T>::enable_interrupts(false);
LTDC_WAKER.wake();
}
}
impl<'d, T: Instance> Ltdc<'d, T> {
/// Note: Full-Duplex modes are not supported at this time
/// Create a new LTDC driver. 8 pins per color channel for blue, green and red
pub fn new(
_peri: impl Peripheral<P = T> + 'd,
/*
peri: impl Peripheral<P = T> + 'd,
_irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
clk: impl Peripheral<P = impl ClkPin<T>> + 'd,
hsync: impl Peripheral<P = impl HsyncPin<T>> + 'd,
vsync: impl Peripheral<P = impl VsyncPin<T>> + 'd,
@ -41,49 +206,274 @@ impl<'d, T: Instance> Ltdc<'d, T> {
r5: impl Peripheral<P = impl R5Pin<T>> + 'd,
r6: impl Peripheral<P = impl R6Pin<T>> + 'd,
r7: impl Peripheral<P = impl R7Pin<T>> + 'd,
*/
) -> Self {
//into_ref!(clk);
critical_section::with(|_cs| {
// RM says the pllsaidivr should only be changed when pllsai is off. But this could have other unintended side effects. So let's just give it a try like this.
// According to the debugger, this bit gets set, anyway.
#[cfg(stm32f7)]
stm32_metapac::RCC
.dckcfgr1()
.modify(|w| w.set_pllsaidivr(stm32_metapac::rcc::vals::Pllsaidivr::DIV2));
// It is set to RCC_PLLSAIDIVR_2 in ST's BSP example for the STM32469I-DISCO.
#[cfg(not(any(stm32f7, stm32u5)))]
stm32_metapac::RCC
.dckcfgr()
.modify(|w| w.set_pllsaidivr(stm32_metapac::rcc::vals::Pllsaidivr::DIV2));
});
rcc::enable_and_reset::<T>();
//new_pin!(clk, AfType::output(OutputType::PushPull, Speed::VeryHigh));
into_ref!(peri);
new_pin!(clk, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(hsync, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(vsync, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(b0, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(b1, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(b2, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(b3, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(b4, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(b5, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(b6, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(b7, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(g0, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(g1, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(g2, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(g3, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(g4, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(g5, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(g6, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(g7, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(r0, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(r1, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(r2, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(r3, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(r4, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(r5, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(r6, AfType::output(OutputType::PushPull, Speed::VeryHigh));
new_pin!(r7, AfType::output(OutputType::PushPull, Speed::VeryHigh));
// Set Tearing Enable pin according to CubeMx example
//te.set_as_af_pull(te.af_num(), AfType::output(OutputType::PushPull, Speed::Low));
/*
T::regs().wcr().modify(|w| {
w.set_dsien(true);
Self { _peri: peri }
}
fn clear_interrupt_flags() {
T::regs().icr().write(|w| {
w.set_cfuif(Cfuif::CLEAR);
w.set_clif(Clif::CLEAR);
w.set_crrif(Crrif::CLEAR);
w.set_cterrif(Cterrif::CLEAR);
});
}
fn enable_interrupts(enable: bool) {
T::regs().ier().write(|w| {
w.set_fuie(enable);
w.set_lie(false); // we are not interested in the line interrupt enable event
w.set_rrie(enable);
w.set_terrie(enable)
});
// enable interrupts for LTDC peripheral
T::Interrupt::unpend();
if enable {
unsafe { T::Interrupt::enable() };
} else {
T::Interrupt::disable()
}
}
/// Set the current buffer. The async function will return when buffer has been completely copied to the LCD screen
/// frame_buffer_addr is a pointer to memory that should not move (best to make it static)
pub async fn set_buffer(&mut self, layer: LtdcLayer, frame_buffer_addr: *const ()) -> Result<(), Error> {
let mut bits = T::regs().isr().read();
// if all clear
if !bits.fuif() && !bits.lif() && !bits.rrif() && !bits.terrif() {
// wait for interrupt
poll_fn(|cx| {
// quick check to avoid registration if already done.
let bits = T::regs().isr().read();
if bits.fuif() || bits.lif() || bits.rrif() || bits.terrif() {
return Poll::Ready(());
}
LTDC_WAKER.register(cx.waker());
Self::clear_interrupt_flags(); // don't poison the request with old flags
Self::enable_interrupts(true);
// set the new frame buffer address
let layer = T::regs().layer(layer as usize);
layer.cfbar().modify(|w| w.set_cfbadd(frame_buffer_addr as u32));
// configure a shadow reload for the next blanking period
T::regs().srcr().write(|w| {
w.set_vbr(Vbr::RELOAD);
});
*/
Self { _peri: PhantomData }
// need to check condition after register to avoid a race
// condition that would result in lost notifications.
let bits = T::regs().isr().read();
if bits.fuif() || bits.lif() || bits.rrif() || bits.terrif() {
Poll::Ready(())
} else {
Poll::Pending
}
})
.await;
// re-read the status register after wait.
bits = T::regs().isr().read();
}
let result = if bits.fuif() {
Err(Error::FifoUnderrun)
} else if bits.terrif() {
Err(Error::TransferError)
} else if bits.lif() {
panic!("line interrupt event is disabled")
} else if bits.rrif() {
// register reload flag is expected
Ok(())
} else {
unreachable!("all interrupt status values checked")
};
Self::clear_interrupt_flags();
result
}
/// Set the enable bit in the control register and assert that it has been enabled
pub fn enable(&mut self) {
T::regs().gcr().modify(|w| w.set_ltdcen(true));
assert!(T::regs().gcr().read().ltdcen())
/// Initialize the display
pub fn init(&mut self, config: &LtdcConfiguration) {
use stm32_metapac::ltdc::vals::{Depol, Hspol, Pcpol, Vspol};
let ltdc = T::regs();
// check bus access
assert!(ltdc.gcr().read().0 == 0x2220); // reset value
// configure the HS, VS, DE and PC polarity
ltdc.gcr().modify(|w| {
w.set_hspol(match config.h_sync_polarity {
PolarityActive::ActiveHigh => Hspol::ACTIVEHIGH,
PolarityActive::ActiveLow => Hspol::ACTIVELOW,
});
w.set_vspol(match config.v_sync_polarity {
PolarityActive::ActiveHigh => Vspol::ACTIVEHIGH,
PolarityActive::ActiveLow => Vspol::ACTIVELOW,
});
w.set_depol(match config.data_enable_polarity {
PolarityActive::ActiveHigh => Depol::ACTIVEHIGH,
PolarityActive::ActiveLow => Depol::ACTIVELOW,
});
w.set_pcpol(match config.pixel_clock_polarity {
PolarityEdge::RisingEdge => Pcpol::RISINGEDGE,
PolarityEdge::FallingEdge => Pcpol::FALLINGEDGE,
});
});
// set synchronization pulse width
ltdc.sscr().modify(|w| {
w.set_vsh(config.v_sync - 1);
w.set_hsw(config.h_sync - 1);
});
// set accumulated back porch
ltdc.bpcr().modify(|w| {
w.set_avbp(config.v_sync + config.v_back_porch - 1);
w.set_ahbp(config.h_sync + config.h_back_porch - 1);
});
// set accumulated active width
let aa_height = config.v_sync + config.v_back_porch + config.active_height - 1;
let aa_width = config.h_sync + config.h_back_porch + config.active_width - 1;
ltdc.awcr().modify(|w| {
w.set_aah(aa_height);
w.set_aaw(aa_width);
});
// set total width and height
let total_height: u16 = config.v_sync + config.v_back_porch + config.active_height + config.v_front_porch - 1;
let total_width: u16 = config.h_sync + config.h_back_porch + config.active_width + config.h_front_porch - 1;
ltdc.twcr().modify(|w| {
w.set_totalh(total_height);
w.set_totalw(total_width)
});
// set the background color value to black
ltdc.bccr().modify(|w| {
w.set_bcred(0);
w.set_bcgreen(0);
w.set_bcblue(0);
});
// enable LTDC by setting LTDCEN bit
ltdc.gcr().modify(|w| {
w.set_ltdcen(true);
});
}
/// Unset the enable bit in the control register and assert that it has been disabled
pub fn disable(&mut self) {
T::regs().gcr().modify(|w| w.set_ltdcen(false));
assert!(!T::regs().gcr().read().ltdcen())
/// Enable the layer
///
/// clut - color look-up table applies to L8, AL44 and AL88 pixel format and will default to greyscale if None supplied and these pixel formats are used
pub fn enable_layer(&mut self, layer_config: &LtdcLayerConfig, clut: Option<&[RgbColor]>) {
let ltdc = T::regs();
let layer = ltdc.layer(layer_config.layer as usize);
// 256 color look-up table for L8, AL88 and AL88 pixel formats
if let Some(clut) = clut {
assert_eq!(clut.len(), 256, "Color lookup table must be exactly 256 in length");
for (index, color) in clut.iter().enumerate() {
layer.clutwr().write(|w| {
w.set_clutadd(index as u8);
w.set_red(color.red);
w.set_green(color.green);
w.set_blue(color.blue);
});
}
}
// configure the horizontal start and stop position
let h_win_start = layer_config.window_x0 + ltdc.bpcr().read().ahbp() + 1;
let h_win_stop = layer_config.window_x1 + ltdc.bpcr().read().ahbp();
layer.whpcr().write(|w| {
w.set_whstpos(h_win_start);
w.set_whsppos(h_win_stop);
});
// configure the vertical start and stop position
let v_win_start = layer_config.window_y0 + ltdc.bpcr().read().avbp() + 1;
let v_win_stop = layer_config.window_y1 + ltdc.bpcr().read().avbp();
layer.wvpcr().write(|w| {
w.set_wvstpos(v_win_start);
w.set_wvsppos(v_win_stop)
});
// set the pixel format
layer
.pfcr()
.write(|w| w.set_pf(Pf::from_bits(layer_config.pixel_format as u8)));
// set the default color value to transparent black
layer.dccr().write_value(Dccr::default());
// set the global constant alpha value
let alpha = 0xFF;
layer.cacr().write(|w| w.set_consta(alpha));
// set the blending factors.
layer.bfcr().modify(|w| {
w.set_bf1(Bf1::PIXEL);
w.set_bf2(Bf2::PIXEL);
});
// calculate framebuffer pixel size in bytes
let bytes_per_pixel = layer_config.pixel_format.bytes_per_pixel() as u16;
let width = layer_config.window_x1 - layer_config.window_x0;
let height = layer_config.window_y1 - layer_config.window_y0;
// framebuffer pitch and line length
layer.cfblr().modify(|w| {
w.set_cfbp(width * bytes_per_pixel);
w.set_cfbll(width * bytes_per_pixel + 7);
});
// framebuffer line number
layer.cfblnr().modify(|w| w.set_cfblnbr(height));
// enable LTDC_Layer by setting LEN bit
layer.cr().modify(|w| {
if clut.is_some() {
w.set_cluten(true);
}
w.set_len(true);
});
}
}
@ -95,9 +485,12 @@ trait SealedInstance: crate::rcc::SealedRccPeripheral {
fn regs() -> crate::pac::ltdc::Ltdc;
}
/// DSI instance trait.
/// LTDC instance trait.
#[allow(private_bounds)]
pub trait Instance: SealedInstance + RccPeripheral + 'static {}
pub trait Instance: SealedInstance + Peripheral<P = Self> + crate::rcc::RccPeripheral + 'static + Send {
/// Interrupt for this LTDC instance.
type Interrupt: interrupt::typelevel::Interrupt;
}
pin_trait!(ClkPin, Instance);
pin_trait!(HsyncPin, Instance);
@ -128,14 +521,16 @@ pin_trait!(B5Pin, Instance);
pin_trait!(B6Pin, Instance);
pin_trait!(B7Pin, Instance);
foreach_peripheral!(
(ltdc, $inst:ident) => {
impl crate::ltdc::SealedInstance for peripherals::$inst {
foreach_interrupt!(
($inst:ident, ltdc, LTDC, GLOBAL, $irq:ident) => {
impl Instance for peripherals::$inst {
type Interrupt = crate::interrupt::typelevel::$irq;
}
impl SealedInstance for peripherals::$inst {
fn regs() -> crate::pac::ltdc::Ltdc {
crate::pac::$inst
}
}
impl crate::ltdc::Instance for peripherals::$inst {}
};
);

View File

@ -34,6 +34,8 @@ stm32-fmc = "0.3.0"
embedded-storage = "0.3.1"
static_cell = "2"
chrono = { version = "^0.4", default-features = false }
embedded-graphics = { version = "0.8.1" }
tinybmp = { version = "0.5" }
# cargo build/run
[profile.dev]

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

View File

@ -0,0 +1,484 @@
#![no_std]
#![no_main]
#![macro_use]
#![allow(static_mut_refs)]
/// This example demonstrates the LTDC lcd display peripheral and was tested to run on an stm32h735g-dk (embassy-stm32 feature "stm32h735ig" and probe-rs chip "STM32H735IGKx")
/// Even though the dev kit has 16MB of attached PSRAM this example uses the 320KB of internal AXIS RAM found on the mcu itself to make the example more standalone and portable.
/// For this reason a 256 color lookup table had to be used to keep the memory requirement down to an acceptable level.
/// The example bounces a ferris crab bitmap around the screen while blinking an led on another task
///
use bouncy_box::BouncyBox;
use defmt::{info, unwrap};
use embassy_executor::Spawner;
use embassy_stm32::{
bind_interrupts,
gpio::{Level, Output, Speed},
ltdc::{self, Ltdc, LtdcConfiguration, LtdcLayer, LtdcLayerConfig, PolarityActive, PolarityEdge},
peripherals,
};
use embassy_time::{Duration, Timer};
use embedded_graphics::{
draw_target::DrawTarget,
geometry::{OriginDimensions, Point, Size},
image::Image,
pixelcolor::{raw::RawU24, Rgb888},
prelude::*,
primitives::Rectangle,
Pixel,
};
use heapless::{Entry, FnvIndexMap};
use tinybmp::Bmp;
use {defmt_rtt as _, panic_probe as _};
const DISPLAY_WIDTH: usize = 480;
const DISPLAY_HEIGHT: usize = 272;
const MY_TASK_POOL_SIZE: usize = 2;
// the following two display buffers consume 261120 bytes that just about fits into axis ram found on the mcu
// see memory.x linker script
pub static mut FB1: [TargetPixelType; DISPLAY_WIDTH * DISPLAY_HEIGHT] = [0; DISPLAY_WIDTH * DISPLAY_HEIGHT];
pub static mut FB2: [TargetPixelType; DISPLAY_WIDTH * DISPLAY_HEIGHT] = [0; DISPLAY_WIDTH * DISPLAY_HEIGHT];
// a basic memory.x linker script for the stm32h735g-dk is as follows:
/*
MEMORY
{
FLASH : ORIGIN = 0x08000000, LENGTH = 1024K
RAM : ORIGIN = 0x24000000, LENGTH = 320K
}
*/
bind_interrupts!(struct Irqs {
LTDC => ltdc::InterruptHandler<peripherals::LTDC>;
});
const NUM_COLORS: usize = 256;
#[embassy_executor::main]
async fn main(spawner: Spawner) {
let p = rcc_setup::stm32h735g_init();
// blink the led on another task
let led = Output::new(p.PC3, Level::High, Speed::Low);
unwrap!(spawner.spawn(led_task(led)));
// numbers from STMicroelectronics/STM32CubeH7 STM32H735G-DK C-based example
const RK043FN48H_HSYNC: u16 = 41; // Horizontal synchronization
const RK043FN48H_HBP: u16 = 13; // Horizontal back porch
const RK043FN48H_HFP: u16 = 32; // Horizontal front porch
const RK043FN48H_VSYNC: u16 = 10; // Vertical synchronization
const RK043FN48H_VBP: u16 = 2; // Vertical back porch
const RK043FN48H_VFP: u16 = 2; // Vertical front porch
let ltdc_config = LtdcConfiguration {
active_width: DISPLAY_WIDTH as _,
active_height: DISPLAY_HEIGHT as _,
h_back_porch: RK043FN48H_HBP - 11, // -11 from MX_LTDC_Init
h_front_porch: RK043FN48H_HFP,
v_back_porch: RK043FN48H_VBP,
v_front_porch: RK043FN48H_VFP,
h_sync: RK043FN48H_HSYNC,
v_sync: RK043FN48H_VSYNC,
h_sync_polarity: PolarityActive::ActiveLow,
v_sync_polarity: PolarityActive::ActiveLow,
data_enable_polarity: PolarityActive::ActiveHigh,
pixel_clock_polarity: PolarityEdge::FallingEdge,
};
info!("init ltdc");
let mut ltdc = Ltdc::new(
p.LTDC, Irqs, p.PG7, p.PC6, p.PA4, p.PG14, p.PD0, p.PD6, p.PA8, p.PE12, p.PA3, p.PB8, p.PB9, p.PB1, p.PB0,
p.PA6, p.PE11, p.PH15, p.PH4, p.PC7, p.PD3, p.PE0, p.PH3, p.PH8, p.PH9, p.PH10, p.PH11, p.PE1, p.PE15,
);
ltdc.init(&ltdc_config);
// we only need to draw on one layer for this example (not to be confused with the double buffer)
info!("enable bottom layer");
let layer_config = LtdcLayerConfig {
pixel_format: ltdc::PixelFormat::L8, // 1 byte per pixel
layer: LtdcLayer::Layer1,
window_x0: 0,
window_x1: DISPLAY_WIDTH as _,
window_y0: 0,
window_y1: DISPLAY_HEIGHT as _,
};
let ferris_bmp: Bmp<Rgb888> = Bmp::from_slice(include_bytes!("./ferris.bmp")).unwrap();
let color_map = build_color_lookup_map(&ferris_bmp);
let clut = build_clut(&color_map);
// enable the bottom layer with a 256 color lookup table
ltdc.enable_layer(&layer_config, Some(&clut));
// Safety: the DoubleBuffer controls access to the statically allocated frame buffers
// and it is the only thing that mutates their content
let mut double_buffer = DoubleBuffer::new(
unsafe { FB1.as_mut() },
unsafe { FB2.as_mut() },
layer_config,
color_map,
);
// this allows us to perform some simple animation for every frame
let mut bouncy_box = BouncyBox::new(
ferris_bmp.bounding_box(),
Rectangle::new(Point::zero(), Size::new(DISPLAY_WIDTH as u32, DISPLAY_HEIGHT as u32)),
2,
);
loop {
// cpu intensive drawing to the buffer that is NOT currently being copied to the LCD screen
double_buffer.clear();
let position = bouncy_box.next_point();
let ferris = Image::new(&ferris_bmp, position);
unwrap!(ferris.draw(&mut double_buffer));
// perform async dma data transfer to the lcd screen
unwrap!(double_buffer.swap(&mut ltdc).await);
}
}
/// builds the color look-up table from all unique colors found in the bitmap. This should be a 256 color indexed bitmap to work.
fn build_color_lookup_map(bmp: &Bmp<Rgb888>) -> FnvIndexMap<u32, u8, NUM_COLORS> {
let mut color_map: FnvIndexMap<u32, u8, NUM_COLORS> = heapless::FnvIndexMap::new();
let mut counter: u8 = 0;
// add black to position 0
color_map.insert(Rgb888::new(0, 0, 0).into_storage(), counter).unwrap();
counter += 1;
for Pixel(_point, color) in bmp.pixels() {
let raw = color.into_storage();
if let Entry::Vacant(v) = color_map.entry(raw) {
v.insert(counter).expect("more than 256 colors detected");
counter += 1;
}
}
color_map
}
/// builds the color look-up table from the color map provided
fn build_clut(color_map: &FnvIndexMap<u32, u8, NUM_COLORS>) -> [ltdc::RgbColor; NUM_COLORS] {
let mut clut = [ltdc::RgbColor::default(); NUM_COLORS];
for (color, index) in color_map.iter() {
let color = Rgb888::from(RawU24::new(*color));
clut[*index as usize] = ltdc::RgbColor {
red: color.r(),
green: color.g(),
blue: color.b(),
};
}
clut
}
#[embassy_executor::task(pool_size = MY_TASK_POOL_SIZE)]
async fn led_task(mut led: Output<'static>) {
let mut counter = 0;
loop {
info!("blink: {}", counter);
counter += 1;
// on
led.set_low();
Timer::after(Duration::from_millis(50)).await;
// off
led.set_high();
Timer::after(Duration::from_millis(450)).await;
}
}
pub type TargetPixelType = u8;
// A simple double buffer
pub struct DoubleBuffer {
buf0: &'static mut [TargetPixelType],
buf1: &'static mut [TargetPixelType],
is_buf0: bool,
layer_config: LtdcLayerConfig,
color_map: FnvIndexMap<u32, u8, NUM_COLORS>,
}
impl DoubleBuffer {
pub fn new(
buf0: &'static mut [TargetPixelType],
buf1: &'static mut [TargetPixelType],
layer_config: LtdcLayerConfig,
color_map: FnvIndexMap<u32, u8, NUM_COLORS>,
) -> Self {
Self {
buf0,
buf1,
is_buf0: true,
layer_config,
color_map,
}
}
pub fn current(&mut self) -> (&FnvIndexMap<u32, u8, NUM_COLORS>, &mut [TargetPixelType]) {
if self.is_buf0 {
(&self.color_map, self.buf0)
} else {
(&self.color_map, self.buf1)
}
}
pub async fn swap<T: ltdc::Instance>(&mut self, ltdc: &mut Ltdc<'_, T>) -> Result<(), ltdc::Error> {
let (_, buf) = self.current();
let frame_buffer = buf.as_ptr();
self.is_buf0 = !self.is_buf0;
ltdc.set_buffer(self.layer_config.layer, frame_buffer as *const _).await
}
/// Clears the buffer
pub fn clear(&mut self) {
let (color_map, buf) = self.current();
let black = Rgb888::new(0, 0, 0).into_storage();
let color_index = color_map.get(&black).expect("no black found in the color map");
for a in buf.iter_mut() {
*a = *color_index; // solid black
}
}
}
// Implement DrawTarget for
impl DrawTarget for DoubleBuffer {
type Color = Rgb888;
type Error = ();
/// Draw a pixel
fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
where
I: IntoIterator<Item = Pixel<Self::Color>>,
{
let size = self.size();
let width = size.width as i32;
let height = size.height as i32;
let (color_map, buf) = self.current();
for pixel in pixels {
let Pixel(point, color) = pixel;
if point.x >= 0 && point.y >= 0 && point.x < width && point.y < height {
let index = point.y * width + point.x;
let raw_color = color.into_storage();
match color_map.get(&raw_color) {
Some(x) => {
buf[index as usize] = *x;
}
None => panic!("color not found in color map: {}", raw_color),
};
} else {
// Ignore invalid points
}
}
Ok(())
}
}
impl OriginDimensions for DoubleBuffer {
/// Return the size of the display
fn size(&self) -> Size {
Size::new(
(self.layer_config.window_x1 - self.layer_config.window_x0) as _,
(self.layer_config.window_y1 - self.layer_config.window_y0) as _,
)
}
}
mod rcc_setup {
use embassy_stm32::{rcc::*, Peripherals};
use embassy_stm32::{
rcc::{Hse, HseMode},
time::Hertz,
Config,
};
/// Sets up clocks for the stm32h735g mcu
/// change this if you plan to use a different microcontroller
pub fn stm32h735g_init() -> Peripherals {
/*
https://github.com/STMicroelectronics/STM32CubeH7/blob/master/Projects/STM32H735G-DK/Examples/GPIO/GPIO_EXTI/Src/main.c
@brief System Clock Configuration
The system Clock is configured as follow :
System Clock source = PLL (HSE)
SYSCLK(Hz) = 520000000 (CPU Clock)
HCLK(Hz) = 260000000 (AXI and AHBs Clock)
AHB Prescaler = 2
D1 APB3 Prescaler = 2 (APB3 Clock 130MHz)
D2 APB1 Prescaler = 2 (APB1 Clock 130MHz)
D2 APB2 Prescaler = 2 (APB2 Clock 130MHz)
D3 APB4 Prescaler = 2 (APB4 Clock 130MHz)
HSE Frequency(Hz) = 25000000
PLL_M = 5
PLL_N = 104
PLL_P = 1
PLL_Q = 4
PLL_R = 2
VDD(V) = 3.3
Flash Latency(WS) = 3
*/
// setup power and clocks for an stm32h735g-dk run from an external 25 Mhz external oscillator
let mut config = Config::default();
config.rcc.hse = Some(Hse {
freq: Hertz::mhz(25),
mode: HseMode::Oscillator,
});
config.rcc.hsi = None;
config.rcc.csi = false;
config.rcc.pll1 = Some(Pll {
source: PllSource::HSE,
prediv: PllPreDiv::DIV5, // PLL_M
mul: PllMul::MUL104, // PLL_N
divp: Some(PllDiv::DIV1),
divq: Some(PllDiv::DIV4),
divr: Some(PllDiv::DIV2),
});
// numbers adapted from Drivers/BSP/STM32H735G-DK/stm32h735g_discovery_ospi.c
// MX_OSPI_ClockConfig
config.rcc.pll2 = Some(Pll {
source: PllSource::HSE,
prediv: PllPreDiv::DIV5, // PLL_M
mul: PllMul::MUL80, // PLL_N
divp: Some(PllDiv::DIV5),
divq: Some(PllDiv::DIV2),
divr: Some(PllDiv::DIV2),
});
// numbers adapted from Drivers/BSP/STM32H735G-DK/stm32h735g_discovery_lcd.c
// MX_LTDC_ClockConfig
config.rcc.pll3 = Some(Pll {
source: PllSource::HSE,
prediv: PllPreDiv::DIV5, // PLL_M
mul: PllMul::MUL160, // PLL_N
divp: Some(PllDiv::DIV2),
divq: Some(PllDiv::DIV2),
divr: Some(PllDiv::DIV83),
});
config.rcc.voltage_scale = VoltageScale::Scale0;
config.rcc.supply_config = SupplyConfig::DirectSMPS;
config.rcc.sys = Sysclk::PLL1_P;
config.rcc.ahb_pre = AHBPrescaler::DIV2;
config.rcc.apb1_pre = APBPrescaler::DIV2;
config.rcc.apb2_pre = APBPrescaler::DIV2;
config.rcc.apb3_pre = APBPrescaler::DIV2;
config.rcc.apb4_pre = APBPrescaler::DIV2;
let p = embassy_stm32::init(config);
p
}
}
mod bouncy_box {
use embedded_graphics::{geometry::Point, primitives::Rectangle};
enum Direction {
DownLeft,
DownRight,
UpLeft,
UpRight,
}
pub struct BouncyBox {
direction: Direction,
child_rect: Rectangle,
parent_rect: Rectangle,
current_point: Point,
move_by: usize,
}
// This calculates the coordinates of a chile rectangle bounced around inside a parent bounded box
impl BouncyBox {
pub fn new(child_rect: Rectangle, parent_rect: Rectangle, move_by: usize) -> Self {
let center_box = parent_rect.center();
let center_img = child_rect.center();
let current_point = Point::new(center_box.x - center_img.x / 2, center_box.y - center_img.y / 2);
Self {
direction: Direction::DownRight,
child_rect,
parent_rect,
current_point,
move_by,
}
}
pub fn next_point(&mut self) -> Point {
let direction = &self.direction;
let img_height = self.child_rect.size.height as i32;
let box_height = self.parent_rect.size.height as i32;
let img_width = self.child_rect.size.width as i32;
let box_width = self.parent_rect.size.width as i32;
let move_by = self.move_by as i32;
match direction {
Direction::DownLeft => {
self.current_point.x -= move_by;
self.current_point.y += move_by;
let x_out_of_bounds = self.current_point.x < 0;
let y_out_of_bounds = (self.current_point.y + img_height) > box_height;
if x_out_of_bounds && y_out_of_bounds {
self.direction = Direction::UpRight
} else if x_out_of_bounds && !y_out_of_bounds {
self.direction = Direction::DownRight
} else if !x_out_of_bounds && y_out_of_bounds {
self.direction = Direction::UpLeft
}
}
Direction::DownRight => {
self.current_point.x += move_by;
self.current_point.y += move_by;
let x_out_of_bounds = (self.current_point.x + img_width) > box_width;
let y_out_of_bounds = (self.current_point.y + img_height) > box_height;
if x_out_of_bounds && y_out_of_bounds {
self.direction = Direction::UpLeft
} else if x_out_of_bounds && !y_out_of_bounds {
self.direction = Direction::DownLeft
} else if !x_out_of_bounds && y_out_of_bounds {
self.direction = Direction::UpRight
}
}
Direction::UpLeft => {
self.current_point.x -= move_by;
self.current_point.y -= move_by;
let x_out_of_bounds = self.current_point.x < 0;
let y_out_of_bounds = self.current_point.y < 0;
if x_out_of_bounds && y_out_of_bounds {
self.direction = Direction::DownRight
} else if x_out_of_bounds && !y_out_of_bounds {
self.direction = Direction::UpRight
} else if !x_out_of_bounds && y_out_of_bounds {
self.direction = Direction::DownLeft
}
}
Direction::UpRight => {
self.current_point.x += move_by;
self.current_point.y -= move_by;
let x_out_of_bounds = (self.current_point.x + img_width) > box_width;
let y_out_of_bounds = self.current_point.y < 0;
if x_out_of_bounds && y_out_of_bounds {
self.direction = Direction::DownLeft
} else if x_out_of_bounds && !y_out_of_bounds {
self.direction = Direction::UpLeft
} else if !x_out_of_bounds && y_out_of_bounds {
self.direction = Direction::DownRight
}
}
}
self.current_point
}
}
}