10 Commits

Author SHA1 Message Date
d7fb4b4058 fuck 2025-10-28 17:08:50 -06:00
1182560582 remvove lock_display 2025-10-28 12:36:15 -06:00
a7daa4c5fc get fps better 2025-10-28 12:20:02 -06:00
bbc9613f62 cleanup 2025-10-28 09:50:15 -06:00
10c9457953 double framebuffer 2025-10-27 19:46:09 -06:00
4c58f66c94 gif plays at low fps 2025-10-27 18:53:22 -06:00
999b22a96f only mark framebuffer tile as dirty if pixel changes 2025-10-27 12:30:23 -06:00
f6d5fb98ab alloc user to access kernel backed heap (psram, if equiped) 2025-10-27 12:25:57 -06:00
b872e6be7c Merge branch 'psram-alloc' into gif 2025-10-27 09:15:40 -06:00
7662e485c0 gif need psram 2025-10-19 15:25:01 -06:00
26 changed files with 631 additions and 302 deletions

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
/target
*.uf2
abi_sys.h
assets/gif/bad_apple.gif

101
Cargo.lock generated
View File

@@ -19,9 +19,8 @@ dependencies = [
"abi_sys",
"embedded-graphics",
"embedded-sdmmc",
"once_cell",
"rand_core 0.9.3",
"spin",
"talc",
]
[[package]]
@@ -125,7 +124,7 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5deb64efa5bd81e31fcd1938615a6d98c82eafcbcd787162b6f63b91d6bac5b3"
dependencies = [
"rustc_version",
"rustc_version 0.2.3",
]
[[package]]
@@ -226,7 +225,7 @@ dependencies = [
"embedded-io",
"embedded-io-async",
"futures-intrusive",
"heapless",
"heapless 0.8.0",
"uuid",
]
@@ -410,7 +409,7 @@ dependencies = [
"embedded-hal 1.0.0",
"embedded-io-async",
"futures",
"heapless",
"heapless 0.8.0",
"num_enum 0.5.11",
]
@@ -789,7 +788,7 @@ dependencies = [
"embedded-io-async",
"futures-sink",
"futures-util",
"heapless",
"heapless 0.8.0",
]
[[package]]
@@ -804,7 +803,7 @@ dependencies = [
"embedded-io-async",
"futures-core",
"futures-sink",
"heapless",
"heapless 0.8.0",
]
[[package]]
@@ -857,7 +856,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80e2ee86063bd028a420a5fb5898c18c87a8898026da1d4c852af2c443d0a454"
dependencies = [
"embassy-executor-timer-queue",
"heapless",
"heapless 0.8.0",
]
[[package]]
@@ -871,7 +870,7 @@ dependencies = [
"embassy-sync 0.7.2",
"embassy-usb-driver 0.2.0",
"embedded-io-async",
"heapless",
"heapless 0.8.0",
"ssmarshal",
"usbd-hid",
]
@@ -1033,12 +1032,13 @@ dependencies = [
"defmt 0.3.100",
"embedded-hal 1.0.0",
"embedded-io",
"heapless",
"heapless 0.8.0",
]
[[package]]
name = "embedded-snake"
version = "0.0.3"
source = "git+https://github.com/LegitCamper/embedded-snake-rs#3986819c55819283dc5c1e89717d2a2f52e9b161"
dependencies = [
"embedded-graphics",
"rand_core 0.9.3",
@@ -1283,6 +1283,15 @@ dependencies = [
"wasip2",
]
[[package]]
name = "gif"
version = "0.1.0"
dependencies = [
"abi",
"embedded-graphics",
"tinygif",
]
[[package]]
name = "goblin"
version = "0.10.2"
@@ -1303,6 +1312,15 @@ dependencies = [
"crunchy",
]
[[package]]
name = "hash32"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67"
dependencies = [
"byteorder",
]
[[package]]
name = "hash32"
version = "0.3.1"
@@ -1333,13 +1351,26 @@ version = "0.15.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5971ac85611da7067dbfcabef3c70ebb5606018acd9e2a3903a0da507521e0d5"
[[package]]
name = "heapless"
version = "0.7.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f"
dependencies = [
"atomic-polyfill",
"hash32 0.2.1",
"rustc_version 0.4.1",
"spin 0.9.8",
"stable_deref_trait",
]
[[package]]
name = "heapless"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"
dependencies = [
"hash32",
"hash32 0.3.1",
"serde",
"stable_deref_trait",
]
@@ -1493,14 +1524,14 @@ dependencies = [
"embedded-sdmmc",
"embedded-text",
"goblin",
"heapless",
"heapless 0.8.0",
"kolibri-embedded-gui",
"num_enum 0.7.4",
"once_cell",
"panic-probe",
"portable-atomic",
"rand",
"spin",
"spin 0.10.0",
"st7365p-lcd",
"static_cell",
"strum",
@@ -1517,7 +1548,7 @@ dependencies = [
"embedded-graphics",
"embedded-iconoir",
"foldhash",
"heapless",
"heapless 0.8.0",
]
[[package]]
@@ -2133,7 +2164,16 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"
dependencies = [
"semver",
"semver 0.9.0",
]
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver 1.0.27",
]
[[package]]
@@ -2191,6 +2231,12 @@ dependencies = [
"semver-parser",
]
[[package]]
name = "semver"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
[[package]]
name = "semver-parser"
version = "0.7.0"
@@ -2296,6 +2342,15 @@ dependencies = [
"rand",
]
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
dependencies = [
"lock_api",
]
[[package]]
name = "spin"
version = "0.10.0"
@@ -2324,7 +2379,7 @@ dependencies = [
"embedded-graphics-core",
"embedded-hal 1.0.0",
"embedded-hal-async",
"heapless",
"heapless 0.8.0",
"nb 1.1.0",
]
@@ -2551,6 +2606,16 @@ dependencies = [
"embedded-graphics",
]
[[package]]
name = "tinygif"
version = "0.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09f1406b710986188de8d393c810213d4bbf940e327d90d52cff9930d007a248"
dependencies = [
"embedded-graphics",
"heapless 0.7.17",
]
[[package]]
name = "toml"
version = "0.5.11"
@@ -2572,7 +2637,7 @@ dependencies = [
"embassy-time 0.4.0",
"embedded-io",
"futures",
"heapless",
"heapless 0.8.0",
"rand_core 0.6.4",
"static_cell",
"trouble-host-macros",
@@ -2623,7 +2688,7 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98816b1accafbb09085168b90f27e93d790b4bfa19d883466b5e53315b5f06a6"
dependencies = [
"heapless",
"heapless 0.8.0",
"portable-atomic",
]

View File

@@ -7,6 +7,7 @@ members = [
"user-apps/calculator",
"user-apps/snake",
"user-apps/gallery",
"user-apps/gif",
]
[profile.release]
@@ -17,9 +18,11 @@ codegen-units = 1
[profile.release-binary]
inherits = "release"
codegen-units = 1
lto = true
debug = false
opt-level = "s"
opt-level = "z"
panic = "abort"
[profile.dev]
lto = true

View File

@@ -7,6 +7,5 @@ edition = "2024"
embedded-sdmmc = { version = "0.9.0", default-features = false }
embedded-graphics = "0.8.1"
abi_sys = { path = "../abi_sys" }
talc = "4.4.3"
spin = "0.10.0"
once_cell = { version = "1", default-features = false }
rand_core = "0.9.3"

View File

@@ -1,33 +1,52 @@
#![no_std]
pub use abi_sys::keyboard;
use abi_sys::{RngRequest, keyboard::KeyEvent};
use rand_core::RngCore;
use talc::*;
#![allow(static_mut_refs)]
extern crate alloc;
static mut ARENA: [u8; 10000] = [0; 10000];
pub use abi_sys::{self, keyboard};
use abi_sys::{RngRequest, alloc, dealloc, keyboard::KeyEvent};
pub use alloc::format;
use core::alloc::{GlobalAlloc, Layout};
use rand_core::RngCore;
#[global_allocator]
static ALLOCATOR: Talck<spin::Mutex<()>, ClaimOnOom> =
Talc::new(unsafe { ClaimOnOom::new(Span::from_array(core::ptr::addr_of!(ARENA).cast_mut())) })
.lock();
static ALLOC: Alloc = Alloc;
pub fn print(msg: &str) {
abi_sys::print(msg.as_ptr(), msg.len());
struct Alloc;
unsafe impl GlobalAlloc for Alloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
alloc(layout.into())
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
dealloc(ptr, layout.into());
}
}
#[macro_export]
macro_rules! print {
($($arg:tt)*) => {{
let s = $crate::format!($($arg)*);
$crate::abi_sys::print(s.as_ptr(), s.len());
}};
}
pub fn sleep(ms: u64) {
abi_sys::sleep(ms);
}
pub fn get_ms() -> u64 {
abi_sys::get_ms()
}
pub fn get_key() -> KeyEvent {
abi_sys::keyboard::get_key().into()
}
pub mod display {
use abi_sys::CPixel;
// use alloc::{vec, vec::Vec};
use embedded_graphics::{
Pixel,
geometry::{Dimensions, Point},
@@ -35,17 +54,17 @@ pub mod display {
prelude::{DrawTarget, Size},
primitives::Rectangle,
};
// use once_cell::unsync::Lazy;
pub const SCREEN_WIDTH: usize = 320;
pub const SCREEN_HEIGHT: usize = 320;
pub type Pixel565 = Pixel<Rgb565>;
pub fn lock_display(lock: bool) {
abi_sys::lock_display(lock);
}
const BUF_SIZE: usize = 1024; // tune this for performance
const BUF_SIZE: usize = 15 * 1024; // tune this for performance
static mut BUF: [CPixel; BUF_SIZE] = [CPixel::new(); BUF_SIZE];
// const BUF_SIZE: usize = 250 * 1024; // tune this for performance
// static mut BUF: Lazy<Vec<CPixel>> = Lazy::new(|| vec![const { CPixel::new() }; BUF_SIZE]);
pub struct Display;
@@ -69,21 +88,19 @@ pub mod display {
where
I: IntoIterator<Item = Pixel<Self::Color>>,
{
let mut buf: [CPixel; BUF_SIZE] = [CPixel::new(); BUF_SIZE];
let mut count = 0;
for p in pixels {
buf[count] = p.into();
unsafe { BUF[count] = p.into() };
count += 1;
if count == BUF_SIZE {
abi_sys::draw_iter(buf.as_ptr(), count);
if count == BUF_SIZE - 1 {
abi_sys::draw_iter(unsafe { BUF.as_ptr() }, count);
count = 0;
}
}
if count > 0 {
abi_sys::draw_iter(buf.as_ptr(), count);
abi_sys::draw_iter(unsafe { BUF.as_ptr() }, count);
}
Ok(())

View File

@@ -4,7 +4,8 @@ version = "0.1.0"
edition = "2024"
[features]
default = []
default = ["alloc"]
alloc = []
defmt = ["dep:defmt"]
[dependencies]

View File

@@ -1,42 +1,88 @@
#![no_std]
#[cfg(feature = "alloc")]
use core::alloc::Layout;
use embedded_graphics::{
Pixel,
pixelcolor::{Rgb565, raw::RawU16},
prelude::{IntoStorage, Point},
};
use embedded_sdmmc::DirEntry;
use strum::EnumIter;
pub const ABI_CALL_TABLE_COUNT: usize = 10;
#[derive(Clone, Copy, EnumIter)]
#[repr(u8)]
pub enum CallAbiTable {
PrintString = 0,
SleepMs = 1,
GetMs = 2,
LockDisplay = 3,
DrawIter = 4,
GetKey = 5,
GenRand = 6,
ListDir = 7,
ReadFile = 8,
FileLen = 9,
}
use strum::{EnumCount, EnumIter};
pub type EntryFn = fn();
pub const ABI_CALL_TABLE_COUNT: usize = 11;
const _: () = assert!(ABI_CALL_TABLE_COUNT == CallTable::COUNT);
#[derive(Clone, Copy, EnumIter, EnumCount)]
#[repr(u8)]
pub enum CallTable {
Alloc = 0,
Dealloc = 1,
PrintString = 2,
SleepMs = 3,
GetMs = 4,
DrawIter = 5,
GetKey = 6,
GenRand = 7,
ListDir = 8,
ReadFile = 9,
FileLen = 10,
}
#[unsafe(no_mangle)]
#[unsafe(link_section = ".syscall_table")]
pub static mut CALL_ABI_TABLE: [usize; ABI_CALL_TABLE_COUNT] = [0; ABI_CALL_TABLE_COUNT];
#[cfg(feature = "alloc")]
#[repr(C)]
pub struct CLayout {
size: usize,
alignment: usize,
}
#[cfg(feature = "alloc")]
impl Into<Layout> for CLayout {
fn into(self) -> Layout {
Layout::from_size_align(self.size, self.alignment).unwrap()
}
}
#[cfg(feature = "alloc")]
impl From<Layout> for CLayout {
fn from(value: Layout) -> Self {
Self {
size: value.size(),
alignment: value.align(),
}
}
}
pub type AllocAbi = extern "C" fn(layout: CLayout) -> *mut u8;
#[unsafe(no_mangle)]
pub extern "C" fn alloc(layout: CLayout) -> *mut u8 {
let f: AllocAbi = unsafe { core::mem::transmute(CALL_ABI_TABLE[CallTable::Alloc as usize]) };
f(layout)
}
pub type DeallocAbi = extern "C" fn(ptr: *mut u8, layout: CLayout);
#[unsafe(no_mangle)]
pub extern "C" fn dealloc(ptr: *mut u8, layout: CLayout) {
let f: DeallocAbi =
unsafe { core::mem::transmute(CALL_ABI_TABLE[CallTable::Dealloc as usize]) };
f(ptr, layout)
}
pub type PrintAbi = extern "C" fn(ptr: *const u8, len: usize);
#[unsafe(no_mangle)]
pub extern "C" fn print(ptr: *const u8, len: usize) {
let f: PrintAbi =
unsafe { core::mem::transmute(CALL_ABI_TABLE[CallAbiTable::PrintString as usize]) };
unsafe { core::mem::transmute(CALL_ABI_TABLE[CallTable::PrintString as usize]) };
f(ptr, len);
}
@@ -45,7 +91,7 @@ pub type SleepMsAbi = extern "C" fn(ms: u64);
#[unsafe(no_mangle)]
pub extern "C" fn sleep(ms: u64) {
let f: SleepMsAbi =
unsafe { core::mem::transmute(CALL_ABI_TABLE[CallAbiTable::SleepMs as usize]) };
unsafe { core::mem::transmute(CALL_ABI_TABLE[CallTable::SleepMs as usize]) };
f(ms);
}
@@ -53,19 +99,10 @@ pub type GetMsAbi = extern "C" fn() -> u64;
#[unsafe(no_mangle)]
pub extern "C" fn get_ms() -> u64 {
let f: GetMsAbi = unsafe { core::mem::transmute(CALL_ABI_TABLE[CallAbiTable::GetMs as usize]) };
let f: GetMsAbi = unsafe { core::mem::transmute(CALL_ABI_TABLE[CallTable::GetMs as usize]) };
f()
}
pub type LockDisplay = extern "C" fn(lock: bool);
#[unsafe(no_mangle)]
pub extern "C" fn lock_display(lock: bool) {
let f: LockDisplay =
unsafe { core::mem::transmute(CALL_ABI_TABLE[CallAbiTable::LockDisplay as usize]) };
f(lock);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct CPixel {
@@ -75,7 +112,7 @@ pub struct CPixel {
}
impl CPixel {
pub fn new() -> Self {
pub const fn new() -> Self {
Self {
x: 0,
y: 0,
@@ -105,12 +142,12 @@ pub type DrawIterAbi = extern "C" fn(ptr: *const CPixel, len: usize);
#[unsafe(no_mangle)]
pub extern "C" fn draw_iter(ptr: *const CPixel, len: usize) {
let f: DrawIterAbi =
unsafe { core::mem::transmute(CALL_ABI_TABLE[CallAbiTable::DrawIter as usize]) };
unsafe { core::mem::transmute(CALL_ABI_TABLE[CallTable::DrawIter as usize]) };
f(ptr, len);
}
pub mod keyboard {
use crate::{CALL_ABI_TABLE, CallAbiTable};
use crate::{CALL_ABI_TABLE, CallTable};
bitflags::bitflags! {
#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)]
@@ -333,7 +370,7 @@ pub mod keyboard {
#[unsafe(no_mangle)]
pub extern "C" fn get_key() -> KeyEventC {
let f: GetKeyAbi =
unsafe { core::mem::transmute(CALL_ABI_TABLE[CallAbiTable::GetKey as usize]) };
unsafe { core::mem::transmute(CALL_ABI_TABLE[CallTable::GetKey as usize]) };
f()
}
}
@@ -350,7 +387,7 @@ pub type GenRand = extern "C" fn(req: &mut RngRequest);
#[unsafe(no_mangle)]
pub extern "C" fn gen_rand(req: &mut RngRequest) {
unsafe {
let ptr = CALL_ABI_TABLE[CallAbiTable::GenRand as usize];
let ptr = CALL_ABI_TABLE[CallTable::GenRand as usize];
let f: GenRand = core::mem::transmute(ptr);
f(req)
}
@@ -371,7 +408,7 @@ pub extern "C" fn list_dir(
file_len: usize,
) -> usize {
unsafe {
let ptr = CALL_ABI_TABLE[CallAbiTable::ListDir as usize];
let ptr = CALL_ABI_TABLE[CallTable::ListDir as usize];
let f: ListDir = core::mem::transmute(ptr);
f(str, len, files, file_len)
}
@@ -394,7 +431,7 @@ pub extern "C" fn read_file(
buf_len: usize,
) -> usize {
unsafe {
let ptr = CALL_ABI_TABLE[CallAbiTable::ReadFile as usize];
let ptr = CALL_ABI_TABLE[CallTable::ReadFile as usize];
let f: ReadFile = core::mem::transmute(ptr);
f(str, len, read_from, buf, buf_len)
}
@@ -405,7 +442,7 @@ pub type FileLen = extern "C" fn(str: *const u8, len: usize) -> usize;
#[unsafe(no_mangle)]
pub extern "C" fn file_len(str: *const u8, len: usize) -> usize {
unsafe {
let ptr = CALL_ABI_TABLE[CallAbiTable::FileLen as usize];
let ptr = CALL_ABI_TABLE[CallTable::FileLen as usize];
let f: FileLen = core::mem::transmute(ptr);
f(str, len)
}

View File

@@ -16,3 +16,4 @@ userapps: cbindgen
just userapp calculator
just userapp snake
just userapp gallery
just userapp gif

View File

@@ -11,7 +11,7 @@ doctest = false
bench = false
[features]
default = ["rp235x", "defmt"]
default = ["rp235x", "defmt", "pimoroni2w"]
pimoroni2w = ["rp235x"]
rp2040 = ["embassy-rp/rp2040"]
rp235x = ["embassy-rp/rp235xb"]
@@ -90,7 +90,7 @@ spin = "0.10.0"
num_enum = { version = "0.7.4", default-features = false }
goblin = { version = "0.10.1", default-features = false, features = ["elf32"] }
talc = "4.4.3"
embedded-alloc = "0.6.0"
embedded-alloc = { version = "0.6.0", features = ["allocator_api"] }
bumpalo = "3.19.0"
abi_sys = { path = "../abi_sys" }

View File

@@ -2,7 +2,7 @@ MEMORY {
FLASH : ORIGIN = 0x10000000, LENGTH = 16M - 4K
RAM : ORIGIN = 0x20000000, LENGTH = 512K
SRAM4 : ORIGIN = 0x20080000, LENGTH = 4K
# SRAM4 : ORIGIN = 0x20080000, LENGTH = 4K
SRAM5 : ORIGIN = 0x20081000, LENGTH = 4K
}

View File

@@ -1,9 +1,9 @@
use abi_sys::{
CPixel, DrawIterAbi, FileLen, GenRand, GetMsAbi, ListDir, LockDisplay, PrintAbi, ReadFile,
RngRequest, SleepMsAbi, keyboard::*,
AllocAbi, CLayout, CPixel, DeallocAbi, DrawIterAbi, FileLen, GenRand, GetMsAbi, ListDir,
PrintAbi, ReadFile, RngRequest, SleepMsAbi, keyboard::*,
};
use alloc::{string::ToString, vec::Vec};
use core::sync::atomic::Ordering;
use core::{alloc::GlobalAlloc, ops::DerefMut, sync::atomic::Ordering};
use embassy_rp::clocks::{RoscRng, clk_sys_freq};
use embassy_time::Instant;
use embedded_graphics::draw_target::DrawTarget;
@@ -11,10 +11,34 @@ use embedded_sdmmc::{DirEntry, LfnBuffer};
use heapless::spsc::Queue;
use crate::{
display::{FB_PAUSED, FRAMEBUFFER},
display::{FRAMEBUFFER, FRAMEBUFFER2, WRITE_FRAMEBUFFER2},
storage::{Dir, File, SDCARD},
};
const _: AllocAbi = alloc;
pub extern "C" fn alloc(layout: CLayout) -> *mut u8 {
// SAFETY: caller guarantees layout is valid
unsafe {
if cfg!(feature = "pimoroni2w") {
crate::heap::HEAP.alloc(layout.into())
} else {
alloc::alloc::alloc(layout.into())
}
}
}
const _: DeallocAbi = dealloc;
pub extern "C" fn dealloc(ptr: *mut u8, layout: CLayout) {
// SAFETY: caller guarantees ptr and layout are valid
unsafe {
if cfg!(feature = "pimoroni2w") {
crate::heap::HEAP.dealloc(ptr, layout.into())
} else {
alloc::alloc::dealloc(ptr, layout.into())
}
}
}
const _: PrintAbi = print;
pub extern "C" fn print(ptr: *const u8, len: usize) {
// SAFETY: caller guarantees `ptr` is valid for `len` bytes
@@ -48,19 +72,26 @@ pub extern "C" fn get_ms() -> u64 {
.as_millis()
}
const _: LockDisplay = lock_display;
pub extern "C" fn lock_display(lock: bool) {
FB_PAUSED.store(lock, Ordering::Relaxed);
}
const _: DrawIterAbi = draw_iter;
// TODO: maybe return result
pub extern "C" fn draw_iter(cpixels: *const CPixel, len: usize) {
// SAFETY: caller guarantees `ptr` is valid for `len` bytes
let cpixels = unsafe { core::slice::from_raw_parts(cpixels, len) };
let iter = cpixels.iter().copied().map(|c: CPixel| c.into());
unsafe { FRAMEBUFFER.draw_iter(iter).unwrap() }
let fb = if cfg!(feature = "pimoroni2w") {
if WRITE_FRAMEBUFFER2.load(Ordering::Acquire) {
unsafe { FRAMEBUFFER2.deref_mut() }
} else {
unsafe { &mut FRAMEBUFFER }
}
} else {
unsafe { &mut FRAMEBUFFER }
};
fb.draw_iter(iter).unwrap();
WRITE_FRAMEBUFFER2.fetch_not(Ordering::AcqRel);
}
pub static mut KEY_CACHE: Queue<KeyEvent, 32> = Queue::new();

View File

@@ -1,6 +1,10 @@
use core::sync::atomic::{AtomicBool, Ordering};
use crate::framebuffer::AtomicFrameBuffer;
use crate::framebuffer::{self, AtomicFrameBuffer};
use alloc::vec;
use core::alloc::GlobalAlloc;
use core::alloc::Layout;
#[cfg(feature = "pimoroni2w")]
use core::sync::atomic::AtomicBool;
use core::sync::atomic::Ordering;
use embassy_rp::{
Peri,
gpio::{Level, Output},
@@ -9,6 +13,7 @@ use embassy_rp::{
};
use embassy_time::{Delay, Timer};
use embedded_hal_bus::spi::ExclusiveDevice;
use once_cell::unsync::Lazy;
use st7365p_lcd::ST7365P;
type DISPLAY = ST7365P<
@@ -21,8 +26,33 @@ type DISPLAY = ST7365P<
pub const SCREEN_WIDTH: usize = 320;
pub const SCREEN_HEIGHT: usize = 320;
pub static mut FRAMEBUFFER: AtomicFrameBuffer = AtomicFrameBuffer::new();
pub static FB_PAUSED: AtomicBool = AtomicBool::new(false);
// used to switch which fb is being used for read/write
#[cfg(feature = "pimoroni2w")]
pub static WRITE_FRAMEBUFFER2: AtomicBool = AtomicBool::new(false);
// the default screen buffer - the only one on boards without extra ram or psram
pub static mut FRAMEBUFFER: Lazy<AtomicFrameBuffer> = Lazy::new(|| {
static mut BUF: [u16; framebuffer::SIZE] = [0; framebuffer::SIZE];
AtomicFrameBuffer::new(unsafe { &mut BUF })
});
#[cfg(feature = "pimoroni2w")]
pub static mut FRAMEBUFFER2: Lazy<AtomicFrameBuffer> = Lazy::new(|| {
use embedded_graphics::{
pixelcolor::Rgb565,
prelude::{DrawTarget, RgbColor},
};
let buf = unsafe {
let slab =
crate::heap::HEAP.alloc(Layout::array::<u16>(framebuffer::SIZE).unwrap()) as *mut u16;
core::slice::from_raw_parts_mut(slab, framebuffer::SIZE)
};
let mut fb = AtomicFrameBuffer::new(buf);
fb.set_all_tiles(false);
fb.clear(Rgb565::BLACK).unwrap();
fb
});
pub async fn init_display(
spi: Spi<'static, SPI1, Async>,
@@ -50,15 +80,18 @@ pub async fn init_display(
#[embassy_executor::task]
pub async fn display_handler(mut display: DISPLAY) {
loop {
if !FB_PAUSED.load(Ordering::Acquire) {
unsafe {
FRAMEBUFFER
.partial_draw_batched(&mut display)
.await
.unwrap()
}
let fb = if cfg!(feature = "pimoroni2w") {
if WRITE_FRAMEBUFFER2.load(Ordering::Acquire) {
unsafe { &mut FRAMEBUFFER }
} else {
unsafe { &mut FRAMEBUFFER2 }
}
} else {
unsafe { &mut FRAMEBUFFER }
};
fb.safe_draw(&mut display).await.unwrap();
Timer::after_millis(10).await;
// small yield to allow other tasks to run
Timer::after_nanos(100).await;
}
}

View File

@@ -2,7 +2,7 @@ use crate::{
abi,
storage::{File, SDCARD},
};
use abi_sys::CallAbiTable;
use abi_sys::CallTable;
use abi_sys::EntryFn;
use alloc::{vec, vec::Vec};
use bumpalo::Bump;
@@ -194,18 +194,19 @@ fn patch_abi(
unsafe { base.add((sym.st_value as usize) - min_vaddr as usize) }
as *mut usize;
for (idx, call) in CallAbiTable::iter().enumerate() {
for (idx, call) in CallTable::iter().enumerate() {
let ptr = match call {
CallAbiTable::PrintString => abi::print as usize,
CallAbiTable::SleepMs => abi::sleep as usize,
CallAbiTable::GetMs => abi::get_ms as usize,
CallAbiTable::LockDisplay => abi::lock_display as usize,
CallAbiTable::DrawIter => abi::draw_iter as usize,
CallAbiTable::GetKey => abi::get_key as usize,
CallAbiTable::GenRand => abi::gen_rand as usize,
CallAbiTable::ListDir => abi::list_dir as usize,
CallAbiTable::ReadFile => abi::read_file as usize,
CallAbiTable::FileLen => abi::file_len as usize,
CallTable::Alloc => abi::alloc as usize,
CallTable::Dealloc => abi::dealloc as usize,
CallTable::PrintString => abi::print as usize,
CallTable::SleepMs => abi::sleep as usize,
CallTable::GetMs => abi::get_ms as usize,
CallTable::DrawIter => abi::draw_iter as usize,
CallTable::GetKey => abi::get_key as usize,
CallTable::GenRand => abi::gen_rand as usize,
CallTable::ListDir => abi::list_dir as usize,
CallTable::ReadFile => abi::read_file as usize,
CallTable::FileLen => abi::file_len as usize,
};
unsafe {
table_base.add(idx as usize).write(ptr);

View File

@@ -12,34 +12,40 @@ use embedded_graphics::{
};
use embedded_hal_2::digital::OutputPin;
use embedded_hal_async::{delay::DelayNs, spi::SpiDevice};
use heapless::Vec;
use st7365p_lcd::ST7365P;
pub const TILE_SIZE: usize = 16; // 16x16 tile
pub const TILE_COUNT: usize = (SCREEN_WIDTH / TILE_SIZE) * (SCREEN_HEIGHT / TILE_SIZE); // 400 tiles
// Group of tiles for batching
pub const MAX_META_TILES: usize = SCREEN_WIDTH / TILE_SIZE; // max number of meta tiles in buffer
pub const MAX_META_TILES: usize = (SCREEN_WIDTH / TILE_SIZE) * 2; // max number of meta tiles in buffer
type MetaTileVec = heapless::Vec<Rectangle, { TILE_COUNT / MAX_META_TILES }>;
const SIZE: usize = SCREEN_HEIGHT * SCREEN_WIDTH;
static mut BUFFER: [u16; SIZE] = [0; SIZE];
static mut DIRTY_TILES: LazyLock<heapless::Vec<AtomicBool, TILE_COUNT>> = LazyLock::new(|| {
let mut tiles = Vec::new();
for _ in 0..TILE_COUNT {
tiles.push(AtomicBool::new(true)).unwrap();
}
tiles
});
pub const SIZE: usize = SCREEN_HEIGHT * SCREEN_WIDTH;
#[allow(dead_code)]
pub struct AtomicFrameBuffer;
pub struct AtomicFrameBuffer<'a> {
fb: &'a mut [u16],
dirty_tiles: heapless::Vec<AtomicBool, TILE_COUNT>,
}
impl AtomicFrameBuffer {
pub const fn new() -> Self {
Self
impl<'a> AtomicFrameBuffer<'a> {
pub fn new(buffer: &'a mut [u16]) -> Self {
assert!(buffer.len() == SIZE);
let mut dirty_tiles = heapless::Vec::new();
for _ in 0..TILE_COUNT {
dirty_tiles.push(AtomicBool::new(true)).unwrap()
}
Self {
fb: buffer,
dirty_tiles,
}
}
pub fn set_all_tiles(&mut self, set: bool) {
for t in self.dirty_tiles.iter_mut() {
t.store(set, Ordering::Release);
}
}
fn mark_tiles_dirty(&mut self, rect: Rectangle) {
@@ -52,18 +58,12 @@ impl AtomicFrameBuffer {
for ty in start_ty..=end_ty {
for tx in start_tx..=end_tx {
let tile_idx = ty * tiles_x + tx;
unsafe { DIRTY_TILES.get_mut()[tile_idx].store(true, Ordering::Relaxed) };
self.dirty_tiles[tile_idx].store(true, Ordering::Release);
}
}
}
fn set_pixel(&mut self, x: u16, y: u16, color: u16) -> Result<(), ()> {
unsafe { BUFFER[(y as usize * SCREEN_WIDTH) + x as usize] = color };
Ok(())
}
fn set_pixels_buffered<P: IntoIterator<Item = u16>>(
fn set_pixels<P: IntoIterator<Item = u16>>(
&mut self,
sx: u16,
sy: u16,
@@ -84,7 +84,7 @@ impl AtomicFrameBuffer {
for y in sy..=ey {
for x in sx..=ex {
if let Some(color) = color_iter.next() {
unsafe { BUFFER[(y as usize * SCREEN_WIDTH) + x as usize] = color };
self.fb[(y as usize * SCREEN_WIDTH) + x as usize] = color;
} else {
return Err(()); // Not enough data
}
@@ -107,7 +107,7 @@ impl AtomicFrameBuffer {
let mut tx = 0;
while tx < tiles_x {
let idx = ty * tiles_x + tx;
if !unsafe { DIRTY_TILES.get()[idx].load(Ordering::Acquire) } {
if !self.dirty_tiles[idx].load(Ordering::Acquire) {
tx += 1;
continue;
}
@@ -119,7 +119,7 @@ impl AtomicFrameBuffer {
// Grow horizontally, but keep under MAX_TILES_PER_METATILE
while tx + width_tiles < tiles_x
&& unsafe {
DIRTY_TILES.get()[ty * tiles_x + tx + width_tiles].load(Ordering::Relaxed)
self.dirty_tiles[ty * tiles_x + tx + width_tiles].load(Ordering::Acquire)
}
&& (width_tiles + height_tiles) <= MAX_META_TILES
{
@@ -130,8 +130,7 @@ impl AtomicFrameBuffer {
for x_off in 0..width_tiles {
unsafe {
DIRTY_TILES.get()[ty * tiles_x + tx + x_off]
.store(false, Ordering::Release);
self.dirty_tiles[ty * tiles_x + tx + x_off].store(false, Ordering::Release);
};
}
@@ -171,12 +170,12 @@ impl AtomicFrameBuffer {
0,
self.size().width as u16 - 1,
self.size().height as u16 - 1,
unsafe { &BUFFER },
&self.fb[..],
)
.await?;
unsafe {
for tile in DIRTY_TILES.get_mut().iter() {
for tile in self.dirty_tiles.iter() {
tile.store(false, Ordering::Release);
}
};
@@ -184,8 +183,7 @@ impl AtomicFrameBuffer {
Ok(())
}
/// Sends only dirty tiles (16x16px) in batches to the display
pub async fn partial_draw_batched<SPI, DC, RST, DELAY>(
pub async fn safe_draw<SPI, DC, RST, DELAY>(
&mut self,
display: &mut ST7365P<SPI, DC, RST, DELAY>,
) -> Result<(), ()>
@@ -195,7 +193,60 @@ impl AtomicFrameBuffer {
RST: OutputPin,
DELAY: DelayNs,
{
if unsafe { DIRTY_TILES.get().iter().any(|p| p.load(Ordering::Acquire)) } {
let tiles_x = SCREEN_WIDTH / TILE_SIZE;
let _tiles_y = SCREEN_HEIGHT / TILE_SIZE;
let mut pixel_buffer: heapless::Vec<u16, { TILE_SIZE * TILE_SIZE }> = heapless::Vec::new();
for tile_idx in 0..TILE_COUNT {
if self.dirty_tiles[tile_idx].swap(false, Ordering::AcqRel) {
let tx = tile_idx % tiles_x;
let ty = tile_idx / tiles_x;
let x_start = tx * TILE_SIZE;
let y_start = ty * TILE_SIZE;
let x_end = (x_start + TILE_SIZE).min(SCREEN_WIDTH);
let y_end = (y_start + TILE_SIZE).min(SCREEN_HEIGHT);
pixel_buffer.clear();
for y in y_start..y_end {
let start = y * SCREEN_WIDTH + x_start;
let end = y * SCREEN_WIDTH + x_end;
pixel_buffer
.extend_from_slice(&self.fb[start..end])
.unwrap();
}
display
.set_pixels_buffered(
x_start as u16,
y_start as u16,
(x_end - 1) as u16,
(y_end - 1) as u16,
&pixel_buffer,
)
.await
.unwrap();
}
}
Ok(())
}
/// Sends only dirty tiles (16x16px) in batches to the display
pub async fn partial_draw<SPI, DC, RST, DELAY>(
&mut self,
display: &mut ST7365P<SPI, DC, RST, DELAY>,
) -> Result<(), ()>
where
SPI: SpiDevice,
DC: OutputPin,
RST: OutputPin,
DELAY: DelayNs,
{
if unsafe { self.dirty_tiles.iter().any(|p| p.load(Ordering::Acquire)) } {
let tiles_x = (SCREEN_WIDTH + TILE_SIZE - 1) / TILE_SIZE;
let tiles_y = (SCREEN_HEIGHT + TILE_SIZE - 1) / TILE_SIZE;
@@ -203,7 +254,7 @@ impl AtomicFrameBuffer {
// buffer for copying meta tiles before sending to display
let mut pixel_buffer: heapless::Vec<u16, { MAX_META_TILES * TILE_SIZE * TILE_SIZE }> =
Vec::new();
heapless::Vec::new();
for rect in meta_tiles {
let rect_width = rect.size.width as usize;
@@ -220,7 +271,7 @@ impl AtomicFrameBuffer {
// Safe: we guarantee buffer will not exceed MAX_META_TILE_PIXELS
pixel_buffer
.extend_from_slice(unsafe { &BUFFER[start..end] })
.extend_from_slice(&self.fb[start..end])
.unwrap();
}
@@ -243,7 +294,7 @@ impl AtomicFrameBuffer {
for ty in start_ty..=end_ty {
for tx in start_tx..=end_tx {
let tile_idx = ty * tiles_x + tx;
unsafe { DIRTY_TILES.get_mut()[tile_idx].store(false, Ordering::Release) };
self.dirty_tiles[tile_idx].store(false, Ordering::Release);
}
}
}
@@ -253,7 +304,7 @@ impl AtomicFrameBuffer {
}
}
impl DrawTarget for AtomicFrameBuffer {
impl<'a> DrawTarget for AtomicFrameBuffer<'a> {
type Error = ();
type Color = Rgb565;
@@ -262,6 +313,7 @@ impl DrawTarget for AtomicFrameBuffer {
I: IntoIterator<Item = Pixel<Self::Color>>,
{
let mut dirty_rect: Option<Rectangle> = None;
let mut changed = false;
for Pixel(coord, color) in pixels {
if coord.x >= 0 && coord.y >= 0 {
@@ -269,10 +321,12 @@ impl DrawTarget for AtomicFrameBuffer {
let y = coord.y as i32;
if (x as usize) < SCREEN_WIDTH && (y as usize) < SCREEN_HEIGHT {
unsafe {
BUFFER[(y as usize) * SCREEN_WIDTH + (x as usize)] =
RawU16::from(color).into_inner()
};
let idx = (y as usize) * SCREEN_WIDTH + (x as usize);
let raw_color = RawU16::from(color).into_inner();
if self.fb[idx] != raw_color {
self.fb[idx] = raw_color;
changed = true;
}
if let Some(ref mut rect) = dirty_rect {
rect.top_left.x = rect.top_left.x.min(x);
@@ -288,9 +342,11 @@ impl DrawTarget for AtomicFrameBuffer {
}
}
if changed {
if let Some(rect) = dirty_rect {
self.mark_tiles_dirty(rect);
}
}
Ok(())
}
@@ -307,6 +363,7 @@ impl DrawTarget for AtomicFrameBuffer {
let area_width = area.size.width;
let area_height = area.size.height;
let mut colors = colors.into_iter();
let mut changed = false;
for y in 0..area_height {
for x in 0..area_width {
@@ -314,11 +371,12 @@ impl DrawTarget for AtomicFrameBuffer {
if drawable_area.contains(p) {
if let Some(color) = colors.next() {
self.set_pixel(
p.x as u16,
p.y as u16,
RawU16::from(color).into_inner(),
)?;
let idx = (p.y as usize * SCREEN_WIDTH) + (p.x as usize);
let raw_color = RawU16::from(color).into_inner();
if self.fb[idx] != raw_color {
self.fb[idx] = raw_color;
changed = true;
}
} else {
break;
}
@@ -329,8 +387,10 @@ impl DrawTarget for AtomicFrameBuffer {
}
}
if changed {
self.mark_tiles_dirty(*area);
}
}
Ok(())
}
@@ -343,7 +403,7 @@ impl DrawTarget for AtomicFrameBuffer {
}
fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> {
self.set_pixels_buffered(
self.set_pixels(
0,
0,
self.size().width as u16 - 1,
@@ -352,7 +412,7 @@ impl DrawTarget for AtomicFrameBuffer {
.take((self.size().width * self.size().height) as usize),
)?;
for tile in unsafe { DIRTY_TILES.get_mut() }.iter() {
for tile in self.dirty_tiles.iter() {
tile.store(true, Ordering::Release);
}
@@ -360,7 +420,7 @@ impl DrawTarget for AtomicFrameBuffer {
}
}
impl OriginDimensions for AtomicFrameBuffer {
impl<'a> OriginDimensions for AtomicFrameBuffer<'a> {
fn size(&self) -> Size {
Size::new(SCREEN_WIDTH as u32, SCREEN_HEIGHT as u32)
}

View File

@@ -2,14 +2,10 @@
// https://github.com/wezterm/picocalc-wezterm/blob/main/src/heap.rs
use core::alloc::{GlobalAlloc, Layout};
use core::mem::MaybeUninit;
use core::sync::atomic::{AtomicUsize, Ordering};
use embedded_alloc::LlffHeap as Heap;
#[global_allocator]
pub static HEAP: DualHeap = DualHeap::empty();
const HEAP_SIZE: usize = 64 * 1024;
static mut HEAP_MEM: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE];
pub static mut HEAP: PsramHeap = PsramHeap::empty();
struct Region {
start: AtomicUsize,
@@ -38,95 +34,62 @@ impl Region {
}
}
/// This is an allocator that combines two regions of memory.
/// The intent is to use some of the directly connected RAM
/// for this, and if we find some XIP capable PSRAM, add that
/// as a secondary region.
/// Allocation from the primary region is always preferred,
/// as it is expected to be a bit faster than PSRAM.
/// FIXME: PSRAM-allocated memory isn't compatible with
/// CAS atomics, so we might need a bit of a think about this!
pub struct DualHeap {
primary: Heap,
primary_region: Region,
secondary: Heap,
pub struct PsramHeap {
heap: Heap,
region: Region,
}
impl DualHeap {
impl PsramHeap {
pub const fn empty() -> Self {
Self {
primary: Heap::empty(),
primary_region: Region::default(),
secondary: Heap::empty(),
heap: Heap::empty(),
region: Region::default(),
}
}
unsafe fn add_primary(&self, region: Region) {
unsafe fn add_psram(&self, region: Region) {
let start = region.start.load(Ordering::SeqCst);
let size = region.size.load(Ordering::SeqCst);
unsafe {
self.primary.init(start, size);
}
self.primary_region.start.store(start, Ordering::SeqCst);
self.primary_region.size.store(size, Ordering::SeqCst);
}
unsafe fn add_secondary(&self, region: Region) {
let start = region.start.load(Ordering::SeqCst);
let size = region.size.load(Ordering::SeqCst);
unsafe {
self.secondary.init(start, size);
self.heap.init(start, size);
}
self.region.start.store(start, Ordering::SeqCst);
self.region.size.store(size, Ordering::SeqCst);
}
pub fn used(&self) -> usize {
self.primary.used() + self.secondary.used()
self.heap.used()
}
pub fn free(&self) -> usize {
self.primary.free() + self.secondary.free()
self.heap.free()
}
}
unsafe impl GlobalAlloc for DualHeap {
unsafe impl GlobalAlloc for PsramHeap {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
unsafe {
let ptr = self.primary.alloc(layout);
let ptr = self.heap.alloc(layout);
if !ptr.is_null() {
return ptr;
} else {
panic!("HEAP FULL");
}
// start using secondary area when primary heap is full
self.secondary.alloc(layout)
}
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe {
let ptr_usize = ptr as usize;
if self.primary_region.contains(ptr_usize) {
self.primary.dealloc(ptr, layout);
} else {
self.secondary.dealloc(ptr, layout);
if self.region.contains(ptr_usize) {
self.heap.dealloc(ptr, layout);
}
}
}
}
pub fn init_heap() {
let primary_start = &raw mut HEAP_MEM as usize;
unsafe { HEAP.add_primary(Region::new(primary_start, HEAP_SIZE)) }
}
pub fn init_qmi_psram_heap(size: u32) {
unsafe { HEAP.add_secondary(Region::new(0x11000000, size as usize)) }
}
pub async fn free_command(_args: &[&str]) {
let ram_used = HEAP.primary.used();
let ram_free = HEAP.primary.free();
let ram_total = ram_used + ram_free;
let qmi_used = HEAP.secondary.used();
let qmi_free = HEAP.secondary.free();
let qmi_total = qmi_used + qmi_free;
unsafe { HEAP.add_psram(Region::new(0x11000000, size as usize)) }
}

View File

@@ -3,6 +3,8 @@
#![cfg_attr(not(test), no_std)]
#![cfg_attr(not(test), no_main)]
#![allow(static_mut_refs)]
#![feature(allocator_api)]
#![feature(slice_ptr_get)]
extern crate alloc;
@@ -10,7 +12,6 @@ mod abi;
mod display;
mod elf;
mod framebuffer;
#[cfg(feature = "pimoroni2w")]
mod heap;
mod peripherals;
mod psram;
@@ -37,13 +38,6 @@ use crate::{
};
use abi_sys::EntryFn;
use bumpalo::Bump;
use embedded_graphics::{
pixelcolor::Rgb565,
prelude::{DrawTarget, RgbColor},
};
use {defmt_rtt as _, panic_probe as _};
use core::sync::atomic::{AtomicBool, Ordering};
use embassy_executor::{Executor, Spawner};
use embassy_futures::{join::join, select::select};
@@ -55,20 +49,26 @@ use embassy_rp::{
peripherals::{
DMA_CH0, DMA_CH1, DMA_CH3, DMA_CH4, I2C1, PIN_2, PIN_3, PIN_6, PIN_7, PIN_10, PIN_11,
PIN_12, PIN_13, PIN_14, PIN_15, PIN_16, PIN_17, PIN_18, PIN_19, PIN_20, PIN_21, PIN_22,
PIO0, SPI0, SPI1, USB,
PIO0, SPI0, SPI1, USB, WATCHDOG,
},
pio,
spi::{self, Spi},
usb as embassy_rp_usb,
watchdog::{ResetReason, Watchdog},
};
use embassy_sync::{
blocking_mutex::raw::CriticalSectionRawMutex, channel::Channel, signal::Signal,
};
use embassy_time::{Delay, Instant, Timer};
use embassy_time::{Delay, Duration, Instant, Ticker, Timer};
use embedded_graphics::{
pixelcolor::Rgb565,
prelude::{DrawTarget, RgbColor},
};
use embedded_hal_bus::spi::ExclusiveDevice;
use embedded_sdmmc::SdCard as SdmmcSdCard;
use static_cell::StaticCell;
use talc::*;
use {defmt_rtt as _, panic_probe as _};
embassy_rp::bind_interrupts!(struct Irqs {
I2C1_IRQ => i2c::InterruptHandler<I2C1>;
@@ -80,15 +80,32 @@ static mut CORE1_STACK: Stack<16384> = Stack::new();
static EXECUTOR0: StaticCell<Executor> = StaticCell::new();
static EXECUTOR1: StaticCell<Executor> = StaticCell::new();
#[cfg(not(feature = "pimoroni2w"))]
static mut ARENA: [u8; 200 * 1024] = [0; 200 * 1024];
static mut ARENA: [u8; 250 * 1024] = [0; 250 * 1024];
#[cfg(not(feature = "pimoroni2w"))]
#[global_allocator]
static ALLOCATOR: Talck<spin::Mutex<()>, ClaimOnOom> =
Talc::new(unsafe { ClaimOnOom::new(Span::from_array(core::ptr::addr_of!(ARENA).cast_mut())) })
.lock();
#[embassy_executor::task]
async fn watchdog_task(mut watchdog: Watchdog) {
if let Some(reason) = watchdog.reset_reason() {
let reason = match reason {
ResetReason::Forced => "forced",
ResetReason::TimedOut => "timed out",
};
defmt::error!("Watchdog reset reason: {}", reason);
}
watchdog.start(Duration::from_secs(3));
let mut ticker = Ticker::every(Duration::from_secs(2));
loop {
watchdog.feed();
ticker.next().await;
}
}
static ENABLE_UI: AtomicBool = AtomicBool::new(true);
static UI_CHANGE: Signal<CriticalSectionRawMutex, ()> = Signal::new();
@@ -141,7 +158,9 @@ async fn main(_spawner: Spawner) {
let executor0 = EXECUTOR0.init(Executor::new());
executor0.run(|spawner| {
spawner
.spawn(kernel_task(spawner, display, sd, psram, mcu, p.USB))
.spawn(kernel_task(
spawner, p.WATCHDOG, display, sd, psram, mcu, p.USB,
))
.unwrap()
});
}
@@ -241,6 +260,8 @@ async fn setup_display(display: Display, spawner: Spawner) {
spawner.spawn(display_handler(display)).unwrap();
}
// psram is kind of useless on the pico calc
// ive opted to use the pimoroni with on onboard xip psram instead
async fn setup_psram(psram: Psram) {
let psram = init_psram(
psram.pio, psram.sclk, psram.mosi, psram.miso, psram.cs, psram.dma1, psram.dma2,
@@ -254,14 +275,24 @@ async fn setup_psram(psram: Psram) {
#[cfg(feature = "defmt")]
defmt::info!("\u{1b}[1mExternal PSRAM was NOT found!\u{1b}[0m");
}
}
#[cfg(feature = "pimoroni2w")]
{
#[cfg(feature = "pimoroni2w")]
async fn setup_qmi_psram() {
let mut tries = 5;
Timer::after_millis(250).await;
while tries > 1 {
let psram_qmi_size = init_psram_qmi(&embassy_rp::pac::QMI, &embassy_rp::pac::XIP_CTRL);
defmt::info!("size: {}", psram_qmi_size);
Timer::after_millis(100).await;
if psram_qmi_size > 0 {
init_qmi_psram_heap(psram_qmi_size);
return;
}
defmt::info!("failed to init qmi psram... trying again");
tries -= 1;
}
panic!("qmi psram not initialized");
}
async fn setup_sd(sd: Sd) {
@@ -282,16 +313,23 @@ async fn setup_sd(sd: Sd) {
#[embassy_executor::task]
async fn kernel_task(
spawner: Spawner,
watchdog: Peri<'static, WATCHDOG>,
display: Display,
sd: Sd,
psram: Psram,
mcu: Mcu,
usb: Peri<'static, USB>,
) {
spawner
.spawn(watchdog_task(Watchdog::new(watchdog)))
.unwrap();
// setup_psram(psram).await;
#[cfg(feature = "pimoroni2w")]
setup_qmi_psram().await;
setup_mcu(mcu).await;
Timer::after_millis(250).await;
setup_display(display, spawner).await;
setup_psram(psram).await;
setup_sd(sd).await;
let _usb = embassy_rp_usb::Driver::new(usb, Irqs);

View File

@@ -526,16 +526,10 @@ pub fn init_psram_qmi(
let psram_size = detect_psram_qmi(qmi);
if psram_size == 0 {
defmt::error!("qmi psram size 0");
return 0;
}
// Set PSRAM timing for APS6404
//
// Using an rxdelay equal to the divisor isn't enough when running the APS6404 close to 133MHz.
// So: don't allow running at divisor 1 above 100MHz (because delay of 2 would be too late),
// and add an extra 1 to the rxdelay if the divided clock is > 100MHz (i.e. sys clock > 200MHz).
const MAX_PSRAM_FREQ: u32 = 133_000_000;
let clock_hz = clk_peri_freq();
let mut divisor: u32 = (clock_hz + MAX_PSRAM_FREQ - 1) / MAX_PSRAM_FREQ;

View File

@@ -1,13 +1,13 @@
use crate::{
BINARY_CH,
display::{FB_PAUSED, FRAMEBUFFER},
display::{FRAMEBUFFER, FRAMEBUFFER2, WRITE_FRAMEBUFFER2},
elf::load_binary,
peripherals::keyboard,
storage::FileName,
};
use abi_sys::keyboard::{KeyCode, KeyState};
use alloc::{str::FromStr, string::String, vec::Vec};
use core::sync::atomic::Ordering;
use core::{ops::DerefMut, sync::atomic::Ordering};
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex};
use embedded_graphics::{
Drawable,
@@ -71,7 +71,7 @@ pub async fn clear_selection() {
if let Some(area) = sel.last_bounds {
Rectangle::new(area.top_left, area.size)
.into_styled(PrimitiveStyle::with_fill(Rgb565::BLACK))
.draw(unsafe { &mut FRAMEBUFFER })
.draw(unsafe { &mut *FRAMEBUFFER })
.unwrap();
}
}
@@ -86,7 +86,15 @@ async fn draw_selection() {
const NO_BINS: &str = "No Programs found on SD Card. Ensure programs end with '.bin', and are located in the root directory";
let no_bins = String::from_str(NO_BINS).unwrap();
FB_PAUSED.store(true, Ordering::Release); // ensure all elements show up at once
let mut fb = if cfg!(feature = "pimoroni2w") {
if WRITE_FRAMEBUFFER2.load(Ordering::Acquire) {
unsafe { FRAMEBUFFER2.deref_mut() }
} else {
unsafe { &mut FRAMEBUFFER }
}
} else {
unsafe { &mut FRAMEBUFFER }
};
if file_names.is_empty() {
TextBox::new(
@@ -97,7 +105,7 @@ async fn draw_selection() {
),
text_style,
)
.draw(unsafe { &mut FRAMEBUFFER })
.draw(fb.deref_mut())
.unwrap();
} else {
let mut views: alloc::vec::Vec<Text<MonoTextStyle<Rgb565>>> = Vec::new();
@@ -122,16 +130,17 @@ async fn draw_selection() {
.bounding_box();
Rectangle::new(selected_bounds.top_left, selected_bounds.size)
.into_styled(PrimitiveStyle::with_stroke(Rgb565::WHITE, 1))
.draw(unsafe { &mut FRAMEBUFFER })
.draw(fb.deref_mut())
.unwrap();
guard.last_bounds = Some(layout.bounds());
layout.draw(unsafe { &mut FRAMEBUFFER }).unwrap();
layout.draw(fb.deref_mut()).unwrap();
}
guard.changed = false;
FB_PAUSED.store(false, Ordering::Release); // ensure all elements show up at once
WRITE_FRAMEBUFFER2.fetch_not(Ordering::AcqRel);
}
#[derive(Clone)]

View File

@@ -3,7 +3,7 @@
extern crate alloc;
use abi::{
display::{Display, lock_display},
display::Display,
get_key,
keyboard::{KeyCode, KeyState},
print,
@@ -28,11 +28,7 @@ use embedded_layout::{
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
print(&format!(
"user panic: {} @ {:?}",
info.message(),
info.location(),
));
print!("user panic: {} @ {:?}", info.message(), info.location(),);
loop {}
}
@@ -42,7 +38,7 @@ pub extern "Rust" fn _start() {
}
pub fn main() {
print("Starting Calculator app");
print!("Starting Calculator app");
let mut display = Display;
let mut input = vec!['e', 'x', 'p', 'r', ':', ' '];
@@ -62,8 +58,6 @@ pub fn main() {
loop {
if dirty {
lock_display(true);
let style = PrimitiveStyle::with_fill(Rgb565::BLACK);
if let Some(area) = last_area {
Rectangle::new(area.0.top_left, area.0.size)
@@ -107,7 +101,6 @@ pub fn main() {
eq_layout.draw(&mut display).unwrap();
dirty = false;
lock_display(false);
}
let event = get_key();

View File

@@ -4,13 +4,13 @@
extern crate alloc;
use abi::{
display::{Display, SCREEN_HEIGHT, SCREEN_WIDTH, lock_display},
display::{Display, SCREEN_HEIGHT, SCREEN_WIDTH},
fs::{list_dir, read_file},
get_key,
keyboard::{KeyCode, KeyState},
print,
};
use alloc::{format, string::ToString};
use alloc::{format, string::ToString, vec};
use core::panic::PanicInfo;
use embedded_graphics::{
Drawable, image::Image, mono_font::MonoTextStyle, mono_font::ascii::FONT_6X10,
@@ -20,11 +20,7 @@ use tinybmp::Bmp;
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
print(&format!(
"user panic: {} @ {:?}",
info.message(),
info.location(),
));
print!("user panic: {} @ {:?}", info.message(), info.location());
loop {}
}
@@ -34,8 +30,8 @@ pub extern "Rust" fn _start() {
}
pub fn main() {
print("Starting Gallery app");
static mut BMP_BUF: [u8; 100_000] = [0_u8; 100_000];
print!("Starting Gallery app");
let mut bmp_buf = vec![0_u8; 100_000];
let mut display = Display;
// Grid parameters
@@ -55,13 +51,13 @@ pub fn main() {
}
if let Some(f) = file {
print(&format!("file: {}", f.name));
print!("file: {}", f.name);
if f.name.extension() == b"bmp" || f.name.extension() == b"BMP" {
let file = format!("/images/{}", f.name);
let read = read_file(&file, 0, &mut unsafe { &mut BMP_BUF[..] });
let read = read_file(&file, 0, &mut &mut bmp_buf[..]);
if read > 0 {
let bmp = Bmp::from_slice(unsafe { &BMP_BUF }).expect("failed to parse bmp");
let bmp = Bmp::from_slice(&bmp_buf).expect("failed to parse bmp");
let row = images_drawn / grid_cols;
let col = images_drawn % grid_cols;
@@ -74,7 +70,6 @@ pub fn main() {
let x = cell_x + (cell_width - bmp_w) / 2;
let y = cell_y + 5; // 5px top margin
lock_display(true);
Image::new(&bmp, Point::new(x, y))
.draw(&mut display)
.unwrap();
@@ -89,8 +84,6 @@ pub fn main() {
.draw(&mut display)
.unwrap();
lock_display(false);
images_drawn += 1;
}
}

9
user-apps/gif/Cargo.toml Normal file
View File

@@ -0,0 +1,9 @@
[package]
name = "gif"
version = "0.1.0"
edition = "2024"
[dependencies]
abi = { path = "../../abi" }
embedded-graphics = "0.8.1"
tinygif = "0.0.4"

28
user-apps/gif/build.rs Normal file
View File

@@ -0,0 +1,28 @@
//! This build script copies the `memory.x` file from the crate root into
//! a directory where the linker can always find it at build time.
//! For many projects this is optional, as the linker always searches the
//! project root directory -- wherever `Cargo.toml` is. However, if you
//! are using a workspace or have a more complicated build setup, this
//! build script becomes required. Additionally, by requesting that
//! Cargo re-run the build script whenever `memory.x` is changed,
//! updating `memory.x` ensures a rebuild of the application with the
//! new memory settings.
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
fn main() {
// Put `memory.x` in our output directory and ensure it's
// on the linker search path.
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
File::create(out.join("memory.x"))
.unwrap()
.write_all(include_bytes!("../memory.x"))
.unwrap();
println!("cargo:rustc-link-search={}", out.display());
println!("cargo:rerun-if-changed=memory.x");
println!("cargo:rustc-link-arg-bins=-Tmemory.x");
}

60
user-apps/gif/src/main.rs Normal file
View File

@@ -0,0 +1,60 @@
#![no_std]
#![no_main]
extern crate alloc;
use abi::{
display::Display,
fs::{file_len, read_file},
get_key, get_ms,
keyboard::{KeyCode, KeyState},
print, sleep,
};
use alloc::vec;
use core::panic::PanicInfo;
use embedded_graphics::{image::ImageDrawable, pixelcolor::Rgb565};
use tinygif::Gif;
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
print!("user panic: {} @ {:?}", info.message(), info.location(),);
loop {}
}
#[unsafe(no_mangle)]
pub extern "Rust" fn _start() {
main()
}
pub fn main() {
print!("Starting Gif app");
let mut display = Display;
let size = file_len("/gifs/bad_apple.gif");
let mut buf = vec![0_u8; size];
let read = read_file("/gifs/bad_apple.gif", 0, &mut buf);
print!("read: {}, file size: {}", read, size);
assert!(read == size);
let gif = Gif::<Rgb565>::from_slice(&buf).unwrap();
let mut frame_num = 0;
loop {
for frame in gif.frames() {
let start = get_ms();
frame.draw(&mut display).unwrap();
frame_num += 1;
if frame_num % 100 == 0 {
let event = get_key();
if event.state != KeyState::Idle {
match event.key {
KeyCode::Esc => return,
_ => (),
};
};
}
sleep(((frame.delay_centis as u64) * 10).saturating_sub(start));
}
}
}

View File

@@ -1,6 +1,6 @@
MEMORY
{
RAM : ORIGIN = 0x0, LENGTH = 150K
RAM : ORIGIN = 0x0, LENGTH = 250K
}
SECTIONS

View File

@@ -6,5 +6,5 @@ edition = "2024"
[dependencies]
abi = { path = "../../abi" }
embedded-graphics = "0.8.1"
embedded-snake = { path = "../../../embedded-snake-rs" }
embedded-snake = { git = "https://github.com/LegitCamper/embedded-snake-rs" }
rand = { version = "0.9.0", default-features = false }

View File

@@ -4,23 +4,18 @@
extern crate alloc;
use abi::{
Rng,
display::{Display, SCREEN_HEIGHT, SCREEN_WIDTH, lock_display},
display::{Display, SCREEN_HEIGHT, SCREEN_WIDTH},
get_key,
keyboard::{KeyCode, KeyState},
print, sleep,
};
use alloc::format;
use core::panic::PanicInfo;
use embedded_graphics::{pixelcolor::Rgb565, prelude::RgbColor};
use embedded_snake::{Direction, SnakeGame};
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
print(&format!(
"user panic: {} @ {:?}",
info.message(),
info.location(),
));
print!("user panic: {} @ {:?}", info.message(), info.location(),);
loop {}
}
@@ -32,7 +27,7 @@ pub extern "Rust" fn _start() {
const CELL_SIZE: usize = 8;
pub fn main() {
print("Starting Snake app");
print!("Starting Snake app");
let mut display = Display;
let mut game = SnakeGame::<100, Rgb565, Rng>::new(
@@ -62,10 +57,8 @@ pub fn main() {
};
// ensure all draws show up at once
lock_display(true);
game.pre_draw(&mut display);
game.draw(&mut display);
lock_display(false);
sleep(15);
}