22 Commits

Author SHA1 Message Date
aa4cc58b42 expand doom memory for pimoroni 2025-10-31 17:59:48 -06:00
85e888193d Merge branch 'main' into doom 2025-10-31 17:51:18 -06:00
7fcc5291e6 fix build 2025-10-31 17:46:52 -06:00
9afec60033 set rp2350 as kernel default target 2025-10-31 17:46:02 -06:00
382e2e73ef fix rp2350 2025-10-31 17:41:36 -06:00
1d7ab3fb42 move fb to psram to save 200KB for user apps 2025-10-31 17:28:16 -06:00
beee2392ae Merge branch 'main' into doom 2025-10-31 14:15:53 -06:00
2226541813 fix release 2025-10-31 14:15:47 -06:00
46bfa89e18 doom compiles but is BIG 2025-10-31 13:39:16 -06:00
970d021a9a layout 2025-10-29 17:49:14 -06:00
05198c716d increase clock speed of display 2025-10-29 08:07:58 -06:00
ba426f5baa center gif 2025-10-28 19:06:32 -06:00
7bc6aeb998 forgot display lock 2025-10-28 17:44:31 -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
34 changed files with 1110 additions and 274 deletions

1
.gitignore vendored
View File

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

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "user-apps/doom/doomgeneric"]
path = user-apps/doom/doomgeneric
url = https://github.com/ozkl/doomgeneric

148
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]]
@@ -134,6 +133,26 @@ version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
[[package]]
name = "bindgen"
version = "0.71.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3"
dependencies = [
"bitflags 2.9.4",
"cexpr",
"clang-sys",
"itertools 0.10.5",
"log",
"prettyplease",
"proc-macro2",
"quote",
"regex",
"rustc-hash",
"shlex",
"syn 2.0.104",
]
[[package]]
name = "bit-set"
version = "0.5.3"
@@ -276,12 +295,42 @@ dependencies = [
"toml",
]
[[package]]
name = "cc"
version = "1.2.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "739eb0f94557554b3ca9a86d2d37bebd49c5e6d0c1d2bda35ba5bdac830befc2"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cexpr"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
dependencies = [
"nom",
]
[[package]]
name = "cfg-if"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268"
[[package]]
name = "clang-sys"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
dependencies = [
"glob",
"libc",
"libloading",
]
[[package]]
name = "clap"
version = "3.2.25"
@@ -565,6 +614,16 @@ dependencies = [
"litrs",
]
[[package]]
name = "doom"
version = "0.1.0"
dependencies = [
"abi",
"bindgen",
"cc",
"embedded-graphics",
]
[[package]]
name = "either"
version = "1.15.0"
@@ -1039,6 +1098,7 @@ dependencies = [
[[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",
@@ -1107,6 +1167,12 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
name = "find-msvc-tools"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52051878f80a721bb68ebfbc930e07b65ba72f2da88968ea5c06fd6ca3d3a127"
[[package]]
name = "fixed"
version = "1.29.0"
@@ -1283,6 +1349,21 @@ dependencies = [
"wasip2",
]
[[package]]
name = "gif"
version = "0.1.0"
dependencies = [
"abi",
"embedded-graphics",
"tinygif",
]
[[package]]
name = "glob"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
[[package]]
name = "goblin"
version = "0.10.2"
@@ -1595,6 +1676,16 @@ version = "0.2.174"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776"
[[package]]
name = "libloading"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
dependencies = [
"cfg-if",
"windows-link",
]
[[package]]
name = "libredox"
version = "0.1.4"
@@ -1651,6 +1742,12 @@ version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3c8dda44ff03a2f238717214da50f65d5a53b45cd213a7370424ffdb6fae815"
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "nb"
version = "0.1.3"
@@ -1672,6 +1769,16 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -1935,6 +2042,16 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]]
name = "prettyplease"
version = "0.2.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff24dfcda44452b9816fff4cd4227e1bb73ff5a2f1bc1105aa92fb8565ce44d2"
dependencies = [
"proc-macro2",
"syn 2.0.104",
]
[[package]]
name = "proc-macro-error"
version = "1.0.4"
@@ -2127,6 +2244,12 @@ dependencies = [
"crc-any",
]
[[package]]
name = "rustc-hash"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
[[package]]
name = "rustc_version"
version = "0.2.3"
@@ -2256,6 +2379,12 @@ dependencies = [
"keccak",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "siphasher"
version = "1.0.1"
@@ -2551,6 +2680,15 @@ dependencies = [
"embedded-graphics",
]
[[package]]
name = "tinygif"
version = "0.0.4"
source = "git+https://github.com/LegitCamper/tinygif#083c0efbdbeb21835de30425e234247340f6e370"
dependencies = [
"embedded-graphics",
"heapless",
]
[[package]]
name = "toml"
version = "0.5.11"
@@ -2815,6 +2953,12 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.59.0"

View File

@@ -7,6 +7,8 @@ members = [
"user-apps/calculator",
"user-apps/snake",
"user-apps/gallery",
"user-apps/gif",
"user-apps/doom",
]
[profile.release]
@@ -17,9 +19,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,27 +1,45 @@
#![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()
}
@@ -41,11 +59,10 @@ pub mod display {
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 +86,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 {
unsafe { Layout::from_size_align_unchecked(self.size, self.alignment) }
}
}
#[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,5 @@ userapps: cbindgen
just userapp calculator
just userapp snake
just userapp gallery
just userapp gif
just userapp doom

View File

@@ -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, sync::atomic::Ordering};
use embassy_rp::clocks::{RoscRng, clk_sys_freq};
use embassy_time::Instant;
use embedded_graphics::draw_target::DrawTarget;
@@ -11,10 +11,35 @@ use embedded_sdmmc::{DirEntry, LfnBuffer};
use heapless::spsc::Queue;
use crate::{
display::{FB_PAUSED, FRAMEBUFFER},
display::FRAMEBUFFER,
framebuffer::FB_PAUSED,
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 +73,16 @@ 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() }
FB_PAUSED.store(true, Ordering::Release);
unsafe { FRAMEBUFFER.as_mut().unwrap().draw_iter(iter).unwrap() }
FB_PAUSED.store(false, Ordering::Release);
}
pub static mut KEY_CACHE: Queue<KeyEvent, 32> = Queue::new();

View File

@@ -1,6 +1,6 @@
use core::sync::atomic::{AtomicBool, Ordering};
use crate::framebuffer::AtomicFrameBuffer;
use crate::framebuffer::{self, AtomicFrameBuffer, FB_PAUSED};
use core::alloc::{GlobalAlloc, Layout};
use core::sync::atomic::Ordering;
use embassy_rp::{
Peri,
gpio::{Level, Output},
@@ -8,6 +8,10 @@ use embassy_rp::{
spi::{Async, Spi},
};
use embassy_time::{Delay, Timer};
use embedded_graphics::{
pixelcolor::Rgb565,
prelude::{DrawTarget, RgbColor},
};
use embedded_hal_bus::spi::ExclusiveDevice;
use st7365p_lcd::ST7365P;
@@ -21,8 +25,24 @@ 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);
pub static mut FRAMEBUFFER: Option<AtomicFrameBuffer> = None;
fn init_fb() {
unsafe {
FRAMEBUFFER = Some(if cfg!(not(feature = "pimoroni2w")) {
static mut BUF: [u16; framebuffer::SIZE] = [0; framebuffer::SIZE];
AtomicFrameBuffer::new(&mut BUF)
} else {
let slab = crate::heap::HEAP.alloc(Layout::array::<u16>(framebuffer::SIZE).unwrap())
as *mut u16;
let buf = core::slice::from_raw_parts_mut(slab, framebuffer::SIZE);
let mut fb = AtomicFrameBuffer::new(buf);
fb.clear(Rgb565::BLACK).unwrap();
fb
});
}
}
pub async fn init_display(
spi: Spi<'static, SPI1, Async>,
@@ -30,6 +50,8 @@ pub async fn init_display(
data: Peri<'static, PIN_14>,
reset: Peri<'static, PIN_15>,
) -> DISPLAY {
init_fb();
let spi_device = ExclusiveDevice::new(spi, Output::new(cs, Level::Low), Delay).unwrap();
let mut display = ST7365P::new(
spi_device,
@@ -41,7 +63,14 @@ pub async fn init_display(
);
display.init().await.unwrap();
display.set_custom_orientation(0x40).await.unwrap();
unsafe { FRAMEBUFFER.draw(&mut display).await.unwrap() }
unsafe {
FRAMEBUFFER
.as_mut()
.unwrap()
.draw(&mut display)
.await
.unwrap()
}
display.set_on().await.unwrap();
display
@@ -53,12 +82,15 @@ pub async fn display_handler(mut display: DISPLAY) {
if !FB_PAUSED.load(Ordering::Acquire) {
unsafe {
FRAMEBUFFER
.partial_draw_batched(&mut display)
.as_mut()
.unwrap()
.safe_draw(&mut display)
.await
.unwrap()
}
};
}
Timer::after_millis(10).await;
// small yield to allow other tasks to run
Timer::after_nanos(500).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,22 +12,21 @@ 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;
pub const SIZE: usize = SCREEN_HEIGHT * SCREEN_WIDTH;
static mut BUFFER: [u16; SIZE] = [0; SIZE];
pub static FB_PAUSED: AtomicBool = AtomicBool::new(false);
static mut DIRTY_TILES: LazyLock<heapless::Vec<AtomicBool, TILE_COUNT>> = LazyLock::new(|| {
let mut tiles = Vec::new();
let mut tiles = heapless::Vec::new();
for _ in 0..TILE_COUNT {
tiles.push(AtomicBool::new(true)).unwrap();
}
@@ -35,11 +34,12 @@ static mut DIRTY_TILES: LazyLock<heapless::Vec<AtomicBool, TILE_COUNT>> = LazyLo
});
#[allow(dead_code)]
pub struct AtomicFrameBuffer;
pub struct AtomicFrameBuffer<'a>(&'a mut [u16]);
impl AtomicFrameBuffer {
pub const fn new() -> Self {
Self
impl<'a> AtomicFrameBuffer<'a> {
pub fn new(buffer: &'a mut [u16]) -> Self {
assert!(buffer.len() == SIZE);
Self(buffer)
}
fn mark_tiles_dirty(&mut self, rect: Rectangle) {
@@ -52,18 +52,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) };
unsafe { DIRTY_TILES.get_mut()[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 +78,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.0[(y as usize * SCREEN_WIDTH) + x as usize] = color;
} else {
return Err(()); // Not enough data
}
@@ -119,7 +113,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)
DIRTY_TILES.get()[ty * tiles_x + tx + width_tiles].load(Ordering::Acquire)
}
&& (width_tiles + height_tiles) <= MAX_META_TILES
{
@@ -171,7 +165,7 @@ impl AtomicFrameBuffer {
0,
self.size().width as u16 - 1,
self.size().height as u16 - 1,
unsafe { &BUFFER },
&self.0[..],
)
.await?;
@@ -184,8 +178,59 @@ impl AtomicFrameBuffer {
Ok(())
}
pub async fn safe_draw<SPI, DC, RST, DELAY>(
&mut self,
display: &mut ST7365P<SPI, DC, RST, DELAY>,
) -> Result<(), ()>
where
SPI: SpiDevice,
DC: OutputPin,
RST: OutputPin,
DELAY: DelayNs,
{
let tiles_x = SCREEN_WIDTH / TILE_SIZE;
let _tiles_y = SCREEN_HEIGHT / TILE_SIZE;
let tiles = unsafe { DIRTY_TILES.get_mut() };
let mut pixel_buffer: heapless::Vec<u16, { TILE_SIZE * TILE_SIZE }> = heapless::Vec::new();
for tile_idx in 0..TILE_COUNT {
if 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.0[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_batched<SPI, DC, RST, DELAY>(
pub async fn partial_draw<SPI, DC, RST, DELAY>(
&mut self,
display: &mut ST7365P<SPI, DC, RST, DELAY>,
) -> Result<(), ()>
@@ -203,7 +248,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;
@@ -219,9 +264,7 @@ impl AtomicFrameBuffer {
let end = start + rect_width;
// Safe: we guarantee buffer will not exceed MAX_META_TILE_PIXELS
pixel_buffer
.extend_from_slice(unsafe { &BUFFER[start..end] })
.unwrap();
pixel_buffer.extend_from_slice(&self.0[start..end]).unwrap();
}
display
@@ -253,7 +296,7 @@ impl AtomicFrameBuffer {
}
}
impl DrawTarget for AtomicFrameBuffer {
impl<'a> DrawTarget for AtomicFrameBuffer<'a> {
type Error = ();
type Color = Rgb565;
@@ -262,6 +305,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 +313,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.0[idx] != raw_color {
self.0[idx] = raw_color;
changed = true;
}
if let Some(ref mut rect) = dirty_rect {
rect.top_left.x = rect.top_left.x.min(x);
@@ -288,8 +334,10 @@ impl DrawTarget for AtomicFrameBuffer {
}
}
if let Some(rect) = dirty_rect {
self.mark_tiles_dirty(rect);
if changed {
if let Some(rect) = dirty_rect {
self.mark_tiles_dirty(rect);
}
}
Ok(())
@@ -307,6 +355,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 +363,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.0[idx] != raw_color {
self.0[idx] = raw_color;
changed = true;
}
} else {
break;
}
@@ -329,7 +379,9 @@ impl DrawTarget for AtomicFrameBuffer {
}
}
self.mark_tiles_dirty(*area);
if changed {
self.mark_tiles_dirty(*area);
}
}
Ok(())
@@ -343,7 +395,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,
@@ -360,7 +412,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>;
@@ -81,14 +81,35 @@ 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(feature = "pimoroni2w")]
static mut ARENA: [u8; 400 * 1024] = [0; 400 * 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",
};
#[cfg(feature = "debug")]
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 +162,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()
});
}
@@ -175,7 +198,7 @@ async fn userland_task() {
{
ENABLE_UI.store(true, Ordering::Release);
UI_CHANGE.signal(());
unsafe { FRAMEBUFFER.clear(Rgb565::BLACK).unwrap() };
unsafe { FRAMEBUFFER.as_mut().unwrap().clear(Rgb565::BLACK).unwrap() };
let mut selections = SELECTIONS.lock().await;
selections.set_changed(true);
@@ -227,7 +250,7 @@ async fn setup_mcu(mcu: Mcu) {
async fn setup_display(display: Display, spawner: Spawner) {
let mut config = spi::Config::default();
config.frequency = 16_000_000;
config.frequency = 64_000_000;
let spi = Spi::new(
display.spi,
display.clk,
@@ -241,6 +264,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,13 +279,21 @@ async fn setup_psram(psram: Psram) {
#[cfg(feature = "defmt")]
defmt::info!("\u{1b}[1mExternal PSRAM was NOT found!\u{1b}[0m");
}
}
#[cfg(feature = "pimoroni2w")]
{
let psram_qmi_size = init_psram_qmi(&embassy_rp::pac::QMI, &embassy_rp::pac::XIP_CTRL);
if psram_qmi_size > 0 {
init_qmi_psram_heap(psram_qmi_size);
}
#[cfg(feature = "pimoroni2w")]
async fn setup_qmi_psram() {
Timer::after_millis(250).await;
let psram_qmi_size = init_psram_qmi(&embassy_rp::pac::QMI, &embassy_rp::pac::XIP_CTRL);
#[cfg(feature = "debug")]
defmt::info!("size: {}", psram_qmi_size);
Timer::after_millis(100).await;
if psram_qmi_size > 0 {
init_qmi_psram_heap(psram_qmi_size);
return;
} else {
panic!("qmi psram not initialized");
}
}
@@ -282,16 +315,24 @@ 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_mcu(mcu).await;
Timer::after_millis(250).await;
// setup_psram(psram).await;
#[cfg(feature = "pimoroni2w")]
setup_qmi_psram().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,11 @@ pub fn init_psram_qmi(
let psram_size = detect_psram_qmi(qmi);
if psram_size == 0 {
#[cfg(feature = "debug")]
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,9 +1,6 @@
use crate::{
BINARY_CH,
display::{FB_PAUSED, FRAMEBUFFER},
elf::load_binary,
peripherals::keyboard,
storage::FileName,
BINARY_CH, display::FRAMEBUFFER, elf::load_binary, framebuffer::FB_PAUSED,
peripherals::keyboard, storage::FileName,
};
use abi_sys::keyboard::{KeyCode, KeyState};
use alloc::{str::FromStr, string::String, vec::Vec};
@@ -71,7 +68,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.as_mut().unwrap() })
.unwrap();
}
}
@@ -81,7 +78,7 @@ async fn draw_selection() {
let file_names = &guard.selections.clone();
let text_style = MonoTextStyle::new(&FONT_10X20, Rgb565::WHITE);
let display_area = unsafe { FRAMEBUFFER.bounding_box() };
let display_area = unsafe { FRAMEBUFFER.as_mut().unwrap().bounding_box() };
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();
@@ -97,7 +94,7 @@ async fn draw_selection() {
),
text_style,
)
.draw(unsafe { &mut FRAMEBUFFER })
.draw(unsafe { &mut *FRAMEBUFFER.as_mut().unwrap() })
.unwrap();
} else {
let mut views: alloc::vec::Vec<Text<MonoTextStyle<Rgb565>>> = Vec::new();
@@ -122,12 +119,14 @@ 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(unsafe { &mut *FRAMEBUFFER.as_mut().unwrap() })
.unwrap();
guard.last_bounds = Some(layout.bounds());
layout.draw(unsafe { &mut FRAMEBUFFER }).unwrap();
layout
.draw(unsafe { &mut *FRAMEBUFFER.as_mut().unwrap() })
.unwrap();
}
guard.changed = false;

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();

12
user-apps/doom/Cargo.toml Normal file
View File

@@ -0,0 +1,12 @@
[package]
name = "doom"
version = "0.1.0"
edition = "2024"
[dependencies]
abi = { path = "../../abi" }
embedded-graphics = "0.8.1"
[build-dependencies]
bindgen = "0.71.0"
cc = "1.0"

126
user-apps/doom/build.rs Normal file
View File

@@ -0,0 +1,126 @@
//! 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::{Path, PathBuf};
use std::process::Command;
fn main() {
build_newlib();
build_doom();
// 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");
}
// TODO: use target to change newlib build - only workds for rp2350 right now
fn build_newlib() {
let out_dir = std::env::var("OUT_DIR").unwrap();
let picolibc_dir = format!("{}/picolibc", out_dir);
if !Path::new(&picolibc_dir).exists() {
let status = Command::new("git")
.args(&[
"clone",
"https://github.com/picolibc/picolibc",
&picolibc_dir,
])
.status()
.expect("Failed to clone picolibc");
assert!(status.success());
}
let build_dir = format!("{}/build", picolibc_dir);
std::fs::create_dir_all(&build_dir).unwrap();
let status = Command::new(&format!("{picolibc_dir}/scripts/do-configure"))
.current_dir(&build_dir)
.args(&[
"thumbv8m_main_fp-none-eabi",
"--buildtype=minsize",
"-Dtests=true",
"-Dtinystdio=false",
"-Dsingle-thread=true",
"-Db_pie=true",
"-Ddefault_library=static",
"-Dtinystdio=false",
"-Dmultilib=false",
".",
])
.status()
.expect("Failed to run Meson configure");
assert!(status.success());
let status = Command::new("ninja")
.current_dir(&build_dir)
.status()
.expect("Failed to run Ninja build");
assert!(status.success());
println!("cargo:rustc-link-search={}/newlib", build_dir);
println!("cargo:rustc-link-lib=c");
println!("cargo:rustc-link-lib=m");
}
fn build_doom() {
let ref dg_src_dir = std::path::PathBuf::from("doomgeneric/doomgeneric");
let mut dg_c_paths = vec![];
let mut dg_h_paths = vec![];
// Find most c and h files
for entry in std::fs::read_dir(dg_src_dir).unwrap() {
let entry = entry.unwrap();
if let Some(filename) = entry.file_name().to_str() {
if filename.starts_with("doomgeneric")
|| filename.contains("_allegro")
|| filename.contains("_sdl")
|| filename.contains("net_")
|| filename == "i_main.c"
{
continue;
}
if filename.ends_with(".h") {
dg_h_paths.push(dg_src_dir.join(filename));
} else if filename.ends_with(".c") {
dg_c_paths.push(dg_src_dir.join(filename));
}
}
}
dg_c_paths
.iter()
.chain(dg_h_paths.iter())
.for_each(|path| println!("cargo:rerun-if-changed={}", path.to_str().unwrap()));
cc::Build::new()
.compiler("arm-none-eabi-gcc")
.flag("-w") // silence warnings
.flag("-Os") // optimize for size
.flag("-ffunction-sections")
.flag("-fdata-sections")
.define("CMAP256", None)
.define("DOOMGENERIC_RESX", Some("320"))
.define("DOOMGENERIC_RESY", Some("200"))
.flag_if_supported("-std=gnu99")
.define("_POSIX_C_SOURCE", Some("200809L"))
.files(dg_c_paths)
.compile("doomgeneric");
}

31
user-apps/doom/memory.x Normal file
View File

@@ -0,0 +1,31 @@
MEMORY
{
RAM : ORIGIN = 0x0, LENGTH = 400K
}
SECTIONS
{
.text : ALIGN(4)
{
*(.text .text.*);
*(.rodata .rodata.*);
} > RAM
.data : ALIGN(4)
{
*(.data .data.*);
} > RAM
.bss : ALIGN(4)
{
*(.bss .bss.*);
*(COMMON);
} > RAM
.syscall_table (NOLOAD) : ALIGN(4)
{
__user_reloc_start = .;
KEEP(*(.user_reloc*));
__user_reloc_end = .;
} > RAM
}

112
user-apps/doom/src/doom.rs Normal file
View File

@@ -0,0 +1,112 @@
use abi::{
abi_sys::{get_ms, sleep},
display::Display,
};
use core::ffi::{c_int, c_uchar};
use embedded_graphics::{
Drawable, Pixel,
draw_target::DrawTarget,
pixelcolor::Rgb565,
prelude::{Point, RgbColor},
};
#[unsafe(no_mangle)]
#[allow(non_snake_case)]
static mut DG_ScreenBuffer: *const u8 = core::ptr::null();
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct RGBA {
pub b: u8,
pub g: u8,
pub r: u8,
pub a: u8,
}
unsafe extern "C" {
fn D_DoomMain();
fn doomgeneric_Tick();
fn M_FindResponseFile();
pub static colors: [RGBA; 256];
}
pub fn tick() {
unsafe { doomgeneric_Tick() };
}
pub struct ScreenBuffer<const RESX: usize, const RESY: usize, const SIZE: usize>(pub [u8; SIZE]);
impl<const RESX: usize, const RESY: usize, const SIZE: usize> ScreenBuffer<RESX, RESY, SIZE> {
#[allow(dead_code)]
const NA: () = assert!(SIZE == RESX * RESY);
pub const fn new() -> Self {
Self([0_u8; SIZE])
}
}
#[unsafe(no_mangle)]
extern "C" fn DG_SetWindowTitle() {}
pub fn create<const RESX: usize, const RESY: usize, const SIZE: usize>(
screenbuffer: &ScreenBuffer<RESX, RESY, SIZE>,
) {
unsafe {
M_FindResponseFile();
DG_ScreenBuffer = screenbuffer.0.as_ptr();
D_DoomMain();
}
}
const X: usize = 320;
const Y: usize = 200;
const SIZE: usize = X * Y;
pub static mut DISPLAY: Option<Display> = None;
pub static mut SCREEN_BUFFER: ScreenBuffer<X, Y, SIZE> = ScreenBuffer::new();
#[unsafe(no_mangle)]
extern "C" fn DG_DrawFrame() {
let palette565: [Rgb565; 256] = unsafe {
colors.map(|c| {
Rgb565::new(
((c.r as u16 * 31) / 255) as u8, // red 5 bits
((c.g as u16 * 63) / 255) as u8, // green 6 bits
((c.b as u16 * 31) / 255) as u8, // blue 5 bits
)
})
};
let buf = unsafe { &SCREEN_BUFFER.0 };
let display = unsafe { DISPLAY.as_mut().unwrap() };
display.clear(Rgb565::BLACK).unwrap();
for y in 0..Y {
for x in 0..X {
let idx = y * X + x;
let color = palette565[buf[idx] as usize];
Pixel(Point::new(x as i32, y as i32), color)
.draw(display)
.unwrap();
}
}
}
#[unsafe(no_mangle)]
extern "C" fn DG_GetTicksMs() -> u32 {
get_ms() as u32
}
#[unsafe(no_mangle)]
extern "C" fn DG_GetKey(pressed: *mut c_int, key: *mut c_uchar) -> c_int {
0
}
#[unsafe(no_mangle)]
extern "C" fn DG_SleepMs(ms: u32) {
sleep(ms.into());
}

118
user-apps/doom/src/libc.rs Normal file
View File

@@ -0,0 +1,118 @@
use core::ffi::{c_char, c_int, c_uchar, c_void};
use core::ptr;
#[unsafe(no_mangle)]
pub static _ctype_: [c_uchar; 256] = [0u8; 256];
#[repr(C)]
pub struct Reent {
pub errno: c_int,
_reserved: [u8; 32],
}
#[unsafe(no_mangle)]
pub static mut _reent_data: Reent = Reent {
errno: 0,
_reserved: [0; 32],
};
#[unsafe(no_mangle)]
pub static mut _impure_ptr: *mut Reent = unsafe { &mut _reent_data as *mut Reent };
#[unsafe(no_mangle)]
pub extern "C" fn __errno() -> *mut c_int {
unsafe { &mut (*_impure_ptr).errno as *mut c_int }
}
#[unsafe(no_mangle)]
pub extern "C" fn exit(_status: i32) -> ! {
loop {}
}
#[unsafe(no_mangle)]
pub extern "C" fn close(_file: i32) -> i32 {
-1
}
#[repr(C)]
pub struct Stat {
st_mode: u32,
}
#[unsafe(no_mangle)]
pub extern "C" fn fstat(_file: i32, st: *mut Stat) -> i32 {
unsafe {
if !st.is_null() {
(*st).st_mode = 0x2000; // S_IFCHR
}
}
0
}
#[unsafe(no_mangle)]
pub extern "C" fn isatty(_file: i32) -> i32 {
1
}
#[unsafe(no_mangle)]
pub extern "C" fn lseek(_file: i32, _ptr: i32, _dir: i32) -> i32 {
0
}
#[unsafe(no_mangle)]
pub extern "C" fn lseek64(_fd: c_int, _offset: i64, _whence: c_int) -> i64 {
0
}
#[unsafe(no_mangle)]
pub extern "C" fn open(_name: *const u8, _flags: i32, _mode: i32) -> i32 {
-1
}
#[unsafe(no_mangle)]
pub extern "C" fn read(_file: i32, _ptr: *mut u8, len: usize) -> i32 {
len as i32
}
#[unsafe(no_mangle)]
pub extern "C" fn write(_file: i32, _ptr: *const u8, len: usize) -> i32 {
len as i32
}
#[unsafe(no_mangle)]
pub extern "C" fn rename(_old: *const c_char, _new: *const c_char) -> c_int {
-1
}
#[unsafe(no_mangle)]
pub extern "C" fn kill(_pid: i32, _sig: i32) -> i32 {
-1
}
#[unsafe(no_mangle)]
pub extern "C" fn getpid() -> i32 {
1
}
#[unsafe(no_mangle)]
pub extern "C" fn link(_old: *const u8, _new: *const u8) -> i32 {
-1
}
#[unsafe(no_mangle)]
pub extern "C" fn unlink(_name: *const u8) -> i32 {
-1
}
#[unsafe(no_mangle)]
pub extern "C" fn mkdir(_path: *const u8, _mode: u32) -> i32 {
0
}
#[unsafe(no_mangle)]
pub extern "C" fn sbrk(incr: isize) -> *mut c_void {
core::ptr::null_mut()
}
#[unsafe(no_mangle)]
pub extern "C" fn fini() {}

View File

@@ -0,0 +1,43 @@
#![no_std]
#![no_main]
#![allow(static_mut_refs)]
#![feature(c_variadic)]
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::{pixelcolor::Rgb565, prelude::Point};
mod doom;
use crate::doom::{DISPLAY, SCREEN_BUFFER, create, tick};
mod libc;
#[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 Doom app");
let display = Display;
unsafe { DISPLAY = Some(display) };
unsafe { create(&SCREEN_BUFFER) };
loop {
tick();
}
}

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 = { git = "https://github.com/LegitCamper/tinygif" }

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");
}

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

@@ -0,0 +1,66 @@
#![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, prelude::Point, transform::Transform,
};
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 height = gif.height();
let mut frame_num = 0;
loop {
for mut frame in gif.frames() {
let start = get_ms();
frame
.translate_mut(Point::new(0, (320 - height as i32) / 2))
.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);
}