├── .gitignore ├── litex-sim-pac ├── .gitignore ├── src │ └── lib.rs ├── Cargo.toml └── build.rs ├── .cargo └── config.toml ├── xtask ├── Cargo.toml └── src │ └── main.rs ├── src ├── lib.rs ├── timer.rs ├── gpio.rs ├── uart.rs ├── spi.rs └── litei2cmaster.rs ├── .github ├── dependabot.yml └── workflows │ ├── dependencies.yml │ └── main.yml ├── deny.toml ├── Cargo.toml ├── examples └── counter.rs ├── LICENSE-MIT ├── README.md └── LICENSE-APACHE /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /litex-sim-pac/.gitignore: -------------------------------------------------------------------------------- 1 | src/soc.rs 2 | -------------------------------------------------------------------------------- /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [alias] 2 | xtask = "run --package xtask --" 3 | 4 | [target.riscv32i-unknown-none-elf] 5 | rustflags = ["-C", "link-arg=-Tmemory.x", "-C", "link-arg=-Tlink.x"] 6 | -------------------------------------------------------------------------------- /xtask/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "xtask" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | clap = { version = "4.4", features = ["derive"] } 8 | xshell = "0.2" 9 | anyhow = "1.0" 10 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | 3 | pub mod gpio; 4 | pub mod spi; 5 | pub mod timer; 6 | pub mod uart; 7 | 8 | pub mod litei2cmaster; 9 | 10 | pub use embedded_hal as hal; 11 | pub use embedded_io as hal_io; 12 | pub use nb; 13 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: / 5 | schedule: 6 | interval: weekly 7 | - package-ecosystem: github-actions 8 | directory: / 9 | schedule: 10 | interval: weekly 11 | -------------------------------------------------------------------------------- /litex-sim-pac/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | 3 | // Generated file, ignore warnings and formatting 4 | #[allow(non_camel_case_types, clippy::all)] 5 | #[rustfmt::skip] 6 | pub mod soc; 7 | 8 | pub use riscv; 9 | #[cfg(feature = "rt")] 10 | pub use riscv_rt; 11 | pub use soc::generic::*; 12 | pub use soc::*; 13 | -------------------------------------------------------------------------------- /deny.toml: -------------------------------------------------------------------------------- 1 | [advisories] 2 | unmaintained = "deny" 3 | yanked = "deny" 4 | notice = "deny" 5 | 6 | [licenses] 7 | copyleft = "deny" 8 | allow-osi-fsf-free = "either" 9 | 10 | [[licenses.clarify]] 11 | name = "stretch" 12 | expression = "MIT" 13 | license-files = [] 14 | 15 | [bans] 16 | multiple-versions = "allow" 17 | 18 | [sources] 19 | unknown-registry = "deny" 20 | unknown-git = "deny" 21 | -------------------------------------------------------------------------------- /litex-sim-pac/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "litex-sim-pac" 3 | version = "0.4.0" 4 | edition = "2021" 5 | license = "MIT OR Apache-2.0" 6 | description = "PAC for the LiteX simulator generated from svd2rust" 7 | authors = ["Pepijn de Vos "] 8 | rust-version = "1.60" 9 | 10 | [lib] 11 | test = false 12 | bench = false 13 | 14 | [dependencies] 15 | bare-metal = "1.0" 16 | riscv = "0.15" 17 | vcell = "0.1" 18 | riscv-rt = { optional = true, version = "0.16" } 19 | 20 | [build-dependencies] 21 | svd2rust = { version = "0.37", default-features = false } 22 | 23 | [features] 24 | default = ["rt"] 25 | rt = ["dep:riscv-rt"] 26 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "litex-hal" 3 | version = "0.4.0" 4 | authors = ["Pepijn de Vos "] 5 | edition = "2021" 6 | license = "MIT OR Apache-2.0" 7 | description = "A embedded HAL crate for LiteX cores" 8 | repository = "https://github.com/pepijndevos/rust-litex-hal" 9 | readme = "README.md" 10 | 11 | [lib] 12 | test = false 13 | bench = false 14 | 15 | [dependencies] 16 | nb = "1.0" 17 | embedded-hal = { version = "1.0" } 18 | embedded-io = "0.6.1" 19 | 20 | [dev-dependencies] 21 | litex-sim-pac = { path = "litex-sim-pac" } 22 | panic-halt = "1.0.0" 23 | 24 | 25 | [workspace] 26 | members = ["litex-sim-pac", "xtask"] 27 | -------------------------------------------------------------------------------- /.github/workflows/dependencies.yml: -------------------------------------------------------------------------------- 1 | name: Dependencies 2 | on: 3 | push: 4 | branches-ignore: 5 | - "dependabot/**" 6 | - "releases/**" 7 | paths: 8 | - "Cargo.toml" 9 | - "deny.toml" 10 | pull_request: 11 | paths: 12 | - "Cargo.toml" 13 | - "deny.toml" 14 | schedule: 15 | - cron: "0 0 * * 0" 16 | env: 17 | CARGO_TERM_COLOR: always 18 | jobs: 19 | dependencies: 20 | name: Check dependencies 21 | runs-on: ubuntu-latest 22 | steps: 23 | - name: Clone repo 24 | uses: actions/checkout@v6 25 | 26 | - name: Check dependencies 27 | uses: EmbarkStudios/cargo-deny-action@v2 28 | -------------------------------------------------------------------------------- /examples/counter.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![no_main] 3 | 4 | use embedded_hal::delay::DelayNs; 5 | use litex_hal::hal_io::Write; 6 | use litex_sim_pac::{riscv_rt::entry, Peripherals}; 7 | use panic_halt as _; 8 | 9 | litex_hal::uart! { 10 | Uart: litex_sim_pac::Uart, 11 | } 12 | 13 | litex_hal::timer! { 14 | Timer: litex_sim_pac::Timer0, 15 | } 16 | 17 | const SYSTEM_CLOCK_FREQUENCY: u32 = 1_000_000; 18 | 19 | #[entry] 20 | fn main() -> ! { 21 | let peripherals = unsafe { Peripherals::steal() }; 22 | let mut uart = Uart::new(peripherals.uart); 23 | writeln!(uart, "Peripherals initialized").unwrap(); 24 | 25 | let mut timer = Timer::new(peripherals.timer0, SYSTEM_CLOCK_FREQUENCY); 26 | let mut uptime = 0; 27 | loop { 28 | timer.delay_ms(1000_u32); 29 | uptime += 1; 30 | writeln!(uart, "Uptime: {} seconds", uptime).unwrap(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Pepijn de Vos 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /litex-sim-pac/build.rs: -------------------------------------------------------------------------------- 1 | use std::{env, error::Error, fs, process::Command}; 2 | use svd2rust::{Config, Target}; 3 | 4 | fn main() -> Result<(), Box> { 5 | const LINKER_SCRIPT_NAME: &str = "memory.x"; 6 | const SVD_NAME: &str = "soc.svd"; 7 | let out_dir = env::var("OUT_DIR")?; 8 | 9 | Command::new("litex_sim") 10 | .arg(format!("--output-dir={out_dir}/litex_sim")) 11 | .arg(format!("--csr-svd={out_dir}/{SVD_NAME}")) 12 | .arg(format!("--memory-x={out_dir}/{LINKER_SCRIPT_NAME}")) 13 | .arg("--cpu-variant=minimal") 14 | .arg("--no-compile") 15 | .status()?; 16 | 17 | println!("cargo:rustc-link-search={out_dir}"); // Let linker find the generated linker script 18 | 19 | let mut config = Config::default(); 20 | config.target = Target::RISCV; 21 | config.make_mod = true; 22 | // Generate the svd file to a string in RAM 23 | let mut generation = svd2rust::generate( 24 | fs::read_to_string(format!("{out_dir}/{SVD_NAME}"))?.as_str(), 25 | &config, 26 | )?; 27 | 28 | // Add newlines as the svd2rust utility do 29 | generation.lib_rs = generation.lib_rs.replace("] ", "]\n"); 30 | 31 | // Write the generate peripheral access code 32 | fs::write("src/soc.rs", generation.lib_rs)?; 33 | 34 | Ok(()) 35 | } 36 | -------------------------------------------------------------------------------- /xtask/src/main.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; 2 | use clap::{Args, Parser}; 3 | use xshell::{cmd, Shell}; 4 | 5 | #[derive(Parser)] 6 | enum Cli { 7 | Simulate(Simulate), 8 | } 9 | 10 | #[derive(Args)] 11 | struct Simulate { 12 | /// Example to simulate. 13 | #[arg(long, short)] 14 | example: String, 15 | 16 | /// Build artifacts in release mode, with optimizations. 17 | #[arg(long, short)] 18 | release: bool, 19 | } 20 | 21 | fn main() -> Result<()> { 22 | const TARGET: &str = "riscv32i-unknown-none-elf"; 23 | 24 | let Cli::Simulate(Simulate { example, release }) = Cli::parse(); 25 | 26 | let release_flag = release.then_some("--release"); 27 | 28 | let sh = Shell::new()?; 29 | cmd!( 30 | sh, 31 | "cargo build {release_flag...} --target {TARGET} --example {example}" 32 | ) 33 | .run()?; 34 | 35 | let profile_dir = if release { "release" } else { "debug" }; 36 | let example_path = format!("target/{TARGET}/{profile_dir}/examples/{example}"); 37 | cmd!( 38 | sh, 39 | "riscv64-elf-objcopy {example_path} -O binary {example_path}.bin" 40 | ) 41 | .run()?; 42 | 43 | cmd!( 44 | sh, 45 | "litex_sim --output-dir=target/litex_sim --cpu-variant=minimal --rom-init={example_path}.bin --non-interactive" 46 | ) 47 | .run()?; 48 | 49 | Ok(()) 50 | } 51 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Main 2 | on: 3 | push: 4 | branches: 5 | - master 6 | paths-ignore: 7 | - "**.md" 8 | - ".gitignore" 9 | - ".github/dependabot.yml" 10 | pull_request: 11 | paths-ignore: 12 | - "**.md" 13 | - ".gitignore" 14 | - ".github/dependabot.yml" 15 | env: 16 | CARGO_TERM_COLOR: always 17 | jobs: 18 | clippy: 19 | name: Clippy 20 | runs-on: ubuntu-latest 21 | steps: 22 | - name: Clone repo 23 | uses: actions/checkout@v6 24 | 25 | - name: Cache crates 26 | uses: Swatinem/rust-cache@v2 27 | 28 | - name: Install riscv32i-unknown-none-elf target 29 | run: rustup target add riscv32i-unknown-none-elf 30 | 31 | - name: Install LiteX 32 | run: | 33 | mkdir litex 34 | cd litex 35 | wget https://raw.githubusercontent.com/enjoy-digital/litex/master/litex_setup.py 36 | chmod +x litex_setup.py 37 | ./litex_setup.py --init --install --user 38 | 39 | - name: Clippy 40 | run: cargo clippy --target riscv32i-unknown-none-elf --no-deps --examples --all-features -- -D warnings 41 | 42 | format: 43 | name: Format 44 | runs-on: ubuntu-latest 45 | steps: 46 | - name: Clone repo 47 | uses: actions/checkout@v6 48 | 49 | - name: Cache crates 50 | uses: Swatinem/rust-cache@v2 51 | 52 | - name: Install Taplo 53 | run: cargo install taplo-cli 54 | 55 | - name: Format 56 | run: | 57 | cargo fmt --check 58 | taplo fmt --check 59 | -------------------------------------------------------------------------------- /src/timer.rs: -------------------------------------------------------------------------------- 1 | #[macro_export] 2 | macro_rules! timer { 3 | ($( 4 | $TIMERX:ident: $PACTIMERX:ty, 5 | )+) => { 6 | $( 7 | #[derive(Debug)] 8 | pub struct $TIMERX { 9 | registers: $PACTIMERX, 10 | pub sys_clk: u32, 11 | } 12 | 13 | impl $TIMERX { 14 | pub fn new(registers: $PACTIMERX, sys_clk: u32) -> Self { 15 | Self { registers, sys_clk } 16 | } 17 | 18 | pub fn free(self) -> $PACTIMERX { 19 | self.registers 20 | } 21 | } 22 | 23 | impl $crate::hal::delay::DelayNs for $TIMERX { 24 | fn delay_ns(&mut self, ns: u32) -> () { 25 | let nanos_per_clk: u32 = 1_000_000_000 / self.sys_clk; 26 | // Round up to nearest clock cycle increment. 27 | let value: u32 = (ns / nanos_per_clk) + 1; 28 | unsafe { 29 | self.registers.en().write(|w| w.bits(0)); 30 | self.registers.reload().write(|w| w.bits(0)); 31 | self.registers.load().write(|w| w.bits(value)); 32 | self.registers.en().write(|w| w.bits(1)); 33 | self.registers.update_value().write(|w| w.bits(1)); 34 | while self.registers.value().read().bits() > 0 { 35 | self.registers.update_value().write(|w| w.bits(1)); 36 | } 37 | } 38 | } 39 | } 40 | )+ 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rust Litex HAL 2 | 3 | A Rust embedded HAL crate for [LiteX](https://github.com/enjoy-digital/litex) cores. It contains basic HAL traits for GPIO, UART, SPI, and delay. 4 | 5 | ![ULX3S demo](http://pepijndevos.nl/images/ulx3s_oled.gif) 6 | 7 | More info and instructions [on my blog](http://pepijndevos.nl/2020/08/04/a-rust-hal-for-your-litex-fpga-soc.html) and example project [in this repo](https://github.com/pepijndevos/rust-litex-example/tree/master) 8 | 9 | The repository also contains an example that you can run on Verilator using `litex_sim`. 10 | 11 | ## Compiling and simulating the example 12 | 13 | ### Compilation 14 | 15 | The following dependencies are required to generate Rust code for peripherals (also called Peripheral Access Crate or PAC) and build the example for it. 16 | 17 | #### Rust target for RISCV 32I 18 | 19 | Our example use VexRiscv, so to be able to compile them you need to add `riscv32i-unknown-none-elf` target for Rust. 20 | 21 | ```bash 22 | rustup target add riscv32i-unknown-none-elf 23 | ``` 24 | 25 | #### Python 26 | 27 | For LiteX scripts. 28 | 29 | * ArchLinux: 30 | 31 | ```bash 32 | sudo pacman -S python 33 | ``` 34 | 35 | * Ubuntu: 36 | 37 | ```bash 38 | sudo apt install python3 39 | ``` 40 | 41 | * Universal LiteX script 42 | 43 | [Official instructions](https://github.com/enjoy-digital/litex#quick-start-guide). 44 | 45 | #### LiteX 46 | 47 | To build cores and optionally simulate it using [verilator](#verilator). 48 | 49 | [Official instructions](https://github.com/enjoy-digital/litex#quick-start-guide). 50 | 51 | ### Simulation on litex_sim 52 | 53 | The following dependencies are required if you want to run the example on `litex_sim`. 54 | 55 | #### Cross compiler for RISCV 32I 56 | 57 | To compile VexRiscv soft core. RISCV 64 can also build RISCV 32. 58 | 59 | * ArchLinux: 60 | 61 | ```bash 62 | sudo pacman -S riscv64-elf-gcc 63 | ``` 64 | 65 | * Ubuntu: 66 | 67 | ```bash 68 | sudo apt install gcc-riscv64-unknown-elf 69 | ``` 70 | 71 | #### Verilator 72 | 73 | Simulator to run simulation. 74 | 75 | * ArchLinux: 76 | 77 | ```bash 78 | sudo pacman -S verilator 79 | ``` 80 | 81 | * Ubuntu: 82 | 83 | ```bash 84 | sudo apt install verilator 85 | ``` 86 | 87 | ## Simulation 88 | 89 | To run the simulation execute the following command: 90 | 91 | ```bash 92 | cargo xtask simulate --example counter 93 | ``` 94 | 95 | You can also pass `--release` to the simulation command. 96 | -------------------------------------------------------------------------------- /src/gpio.rs: -------------------------------------------------------------------------------- 1 | use embedded_hal; 2 | 3 | #[derive(Debug)] 4 | pub enum GpioError {} 5 | 6 | impl embedded_hal::digital::Error for GpioError { 7 | fn kind(&self) -> embedded_hal::digital::ErrorKind { 8 | embedded_hal::digital::ErrorKind::Other 9 | } 10 | } 11 | 12 | #[macro_export] 13 | macro_rules! gpio { 14 | ($( 15 | $GPIOX:ident: $PACGPIOX:ty, 16 | )+) => { 17 | $( 18 | #[derive(Debug)] 19 | pub struct $GPIOX { 20 | pub index: usize, 21 | } 22 | 23 | impl $GPIOX { 24 | pub fn new(index: usize) -> Self { 25 | Self { index } 26 | } 27 | } 28 | 29 | impl $crate::hal::digital::ErrorType for $GPIOX { 30 | type Error = $crate::gpio::GpioError; 31 | } 32 | impl $crate::hal::digital::OutputPin for $GPIOX { 33 | 34 | fn set_low(&mut self) -> Result<(), Self::Error> { 35 | let reg = unsafe { &*<$PACGPIOX>::ptr() }; 36 | let mask: u32 = !(1 << self.index); 37 | riscv::interrupt::machine::free(|| { 38 | let val: u32 = reg.out().read().bits() & mask; 39 | unsafe { 40 | reg.out().write(|w| w.bits(val)); 41 | } 42 | }); 43 | Ok(()) 44 | } 45 | fn set_high(&mut self) -> Result<(), Self::Error> { 46 | let reg = unsafe { &*<$PACGPIOX>::ptr() }; 47 | let mask: u32 = 1 << self.index; 48 | riscv::interrupt::machine::free(|| { 49 | let val: u32 = reg.out().read().bits() | mask; 50 | unsafe { 51 | reg.out().write(|w| w.bits(val)); 52 | } 53 | }); 54 | Ok(()) 55 | } 56 | } 57 | 58 | impl $crate::hal::digital::StatefulOutputPin for $GPIOX { 59 | fn is_set_low(&mut self) -> Result { 60 | let reg = unsafe { &*<$PACGPIOX>::ptr() }; 61 | let mask: u32 = 1 << self.index; 62 | let val: u32 = reg.out().read().bits() & mask; 63 | Ok(val == 0) 64 | } 65 | fn is_set_high(&mut self) -> Result { 66 | let reg = unsafe { &*<$PACGPIOX>::ptr() }; 67 | let mask: u32 = 1 << self.index; 68 | let val: u32 = reg.out().read().bits() & mask; 69 | Ok(val != 0) 70 | } 71 | } 72 | )+ 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/uart.rs: -------------------------------------------------------------------------------- 1 | #[macro_export] 2 | macro_rules! uart { 3 | ($( 4 | $UARTX:ident: $PACUARTX:ty, 5 | )+) => { 6 | $( 7 | #[derive(Debug)] 8 | pub struct $UARTX { 9 | registers: $PACUARTX, 10 | } 11 | 12 | #[derive(Debug)] 13 | pub enum UartError { 14 | InvalidState 15 | } 16 | 17 | impl $crate::hal_io::Error for UartError { 18 | fn kind(&self) -> $crate::hal_io::ErrorKind { 19 | $crate::hal_io::ErrorKind::Other 20 | } 21 | } 22 | 23 | impl $crate::hal_io::ErrorType for $UARTX { 24 | type Error = UartError; 25 | } 26 | 27 | impl $UARTX { 28 | pub fn new(registers: $PACUARTX) -> Self { 29 | Self { registers } 30 | } 31 | 32 | pub fn free(self) -> $PACUARTX { 33 | self.registers 34 | } 35 | 36 | fn tx_ready(&self) -> bool { 37 | self.registers.txfull().read().bits() == 0 38 | } 39 | 40 | fn write_char(&mut self, word: &u8) -> () { 41 | 42 | // Wait until TXFULL is `0` 43 | while !self.tx_ready() {} 44 | unsafe { 45 | self.registers.rxtx().write(|w| w.rxtx().bits(*word)); 46 | } 47 | } 48 | } 49 | 50 | 51 | impl $crate::hal_io::Write for $UARTX { 52 | 53 | fn write(&mut self, buf: &[u8]) -> Result { 54 | for word in buf.iter() { 55 | self.write_char(word); 56 | } 57 | Ok(buf.len()) 58 | } 59 | fn flush(&mut self) -> Result<(), Self::Error> { 60 | while !self.tx_ready() {} 61 | Ok(()) 62 | } 63 | } 64 | 65 | impl $crate::hal_io::Read for $UARTX { 66 | 67 | fn read(&mut self, buf: &mut [u8]) -> Result { 68 | let mut i = 0; 69 | for word in buf.iter_mut() { 70 | while self.registers.rxempty().read().bits() != 0 {} 71 | 72 | *word = unsafe { 73 | self.registers.rxtx().read().bits() as u8 74 | }; 75 | self.registers.ev_pending().write(|w| w.rx().set_bit()); 76 | i += 1; 77 | } 78 | Ok(i) 79 | } 80 | } 81 | 82 | impl From<$PACUARTX> for $UARTX { 83 | fn from(registers: $PACUARTX) -> $UARTX { 84 | $UARTX::new(registers) 85 | } 86 | } 87 | )+ 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/spi.rs: -------------------------------------------------------------------------------- 1 | #[macro_export] 2 | macro_rules! spi { 3 | ($( 4 | $SPIX:ident: ($PACSPIX:ty, $WORD:ty, $LENGTH:tt), 5 | )+) => { 6 | $( 7 | #[derive(Debug)] 8 | pub struct $SPIX { 9 | registers: $PACSPIX, 10 | } 11 | 12 | #[derive(Debug, Copy, Clone, Eq, PartialEq)] 13 | pub enum SpiError { 14 | TransactionFailed, 15 | InvalidState, 16 | } 17 | impl $crate::hal::spi::Error for SpiError { 18 | fn kind(&self) -> $crate::hal::spi::ErrorKind { 19 | match *self { 20 | SpiError::TransactionFailed => $crate::hal::spi::ErrorKind::Other, 21 | SpiError::InvalidState => $crate::hal::spi::ErrorKind::Other 22 | } 23 | } 24 | } 25 | 26 | impl $crate::hal::spi::ErrorType for $SPIX { 27 | type Error = SpiError; 28 | } 29 | 30 | impl $SPIX { 31 | pub fn new(registers: $PACSPIX) -> Self { 32 | Self { registers } 33 | } 34 | 35 | pub fn free(self) -> $PACSPIX { 36 | self.registers 37 | } 38 | 39 | fn write_one(&mut self, word: &$WORD) -> Result<(), SpiError> { 40 | if self.registers.status().read().done().bit() { 41 | unsafe { 42 | self.registers.mosi().write(|w| w.bits(*word as u32)); 43 | self.registers.control().write(|w| { 44 | w.length().bits($LENGTH).start().bit(true) 45 | }); 46 | } 47 | Ok(()) 48 | } else { 49 | Err(SpiError::InvalidState) 50 | } 51 | } 52 | 53 | fn is_done(&mut self) -> bool { 54 | self.registers.status().read().done().bit() 55 | } 56 | 57 | fn read_priv(&mut self, bufs: &mut [$WORD]) -> Result<(), SpiError> { 58 | if self.registers.status().read().done().bit() { 59 | for buf in bufs.iter_mut() { 60 | unsafe { 61 | self.registers.control().write(|w| { 62 | w.length().bits($LENGTH).start().bit(true) 63 | }); 64 | } 65 | while !self.is_done() {} 66 | *buf = self.registers.miso().read().bits() as $WORD; 67 | } 68 | Ok(()) 69 | } else { 70 | Err(SpiError::InvalidState) 71 | } 72 | } 73 | 74 | fn write_priv(&mut self, words: &[$WORD]) -> Result<(), SpiError> { 75 | if self.registers.status().read().done().bit() { 76 | for word in words.iter() { 77 | self.write_one(word)?; 78 | while !self.is_done() {} 79 | } 80 | Ok(()) 81 | } else { 82 | Err(SpiError::InvalidState) 83 | } 84 | } 85 | 86 | fn transfer_priv(&mut self, read: &mut [$WORD], write: &[$WORD]) -> Result<(), SpiError> { 87 | let len = read.len().max(write.len()); 88 | for i in 0..len { 89 | let wb = write.get(i).copied().unwrap_or(0); 90 | 91 | self.write_one(&wb)?; 92 | while !self.is_done() {} 93 | let rb = self.registers.miso().read().bits() as $WORD; 94 | if let Some(r) = read.get_mut(i) { 95 | *r = rb; 96 | } 97 | } 98 | Ok(()) 99 | } 100 | 101 | fn transfer_in_place_priv(&mut self, words: &mut [$WORD]) -> Result<(), SpiError> { 102 | if self.is_done() { 103 | for word in words.iter_mut() { 104 | self.write_one(word)?; 105 | while !self.is_done() {} 106 | *word = self.registers.miso().read().bits() as $WORD; 107 | } 108 | Ok(()) 109 | } else { 110 | Err(SpiError::InvalidState) 111 | } 112 | } 113 | } 114 | 115 | impl $crate::hal::spi::SpiDevice<$WORD> for $SPIX { 116 | 117 | fn transaction(&mut self, operations: &mut [$crate::hal::spi::Operation<'_, $WORD>]) -> Result<(), Self::Error> { 118 | for op in operations { 119 | match op { 120 | $crate::hal::spi::Operation::Read(buf) => self.read_priv(buf)?, 121 | $crate::hal::spi::Operation::Write(buf) => self.write_priv(buf)?, 122 | $crate::hal::spi::Operation::Transfer(read_buf, write_buf) => self.transfer_priv(read_buf, write_buf)?, 123 | $crate::hal::spi::Operation::TransferInPlace(buf) => self.transfer_in_place(buf)?, 124 | $crate::hal::spi::Operation::DelayNs(_) => continue, 125 | } 126 | } 127 | Ok(()) 128 | } 129 | } 130 | )+ 131 | }; 132 | } 133 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /src/litei2cmaster.rs: -------------------------------------------------------------------------------- 1 | /* 2 | HAL I2C implementation of LiteX litei2c I2C master IP. 3 | Based on the Zephyr RTOS driver by Vogl Electronic GmbH written in C (Apache 2.0 license) 4 | */ 5 | 6 | #[derive(Debug, Copy, Clone, Eq, PartialEq)] 7 | pub enum LiteI2CSpeedMode { 8 | Standard, 9 | Fast, 10 | FastPlus, 11 | } 12 | 13 | #[derive(Debug, Copy, Clone, Eq, PartialEq)] 14 | pub enum LiteI2CError { 15 | NACK, 16 | Other, 17 | // ... 18 | } 19 | 20 | impl core::fmt::Display for LiteI2CSpeedMode { 21 | fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { 22 | match *self { 23 | LiteI2CSpeedMode::Standard => { 24 | write!(f, "LiteI2CSpeedMode::Standard") 25 | } 26 | LiteI2CSpeedMode::Fast => { 27 | write!(f, "LiteI2CSpeedMode::Fast") 28 | } 29 | LiteI2CSpeedMode::FastPlus => write!(f, "LiteI2CSpeedMode::FastPlus"), 30 | } 31 | } 32 | } 33 | 34 | impl core::error::Error for LiteI2CError {} 35 | 36 | impl core::fmt::Display for LiteI2CError { 37 | fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { 38 | match *self { 39 | LiteI2CError::NACK => { 40 | write!(f, "LiteI2CError: NACK receied!") 41 | } 42 | LiteI2CError::Other => write!(f, "LiteI2CError: Unknown error!"), 43 | } 44 | } 45 | } 46 | 47 | impl embedded_hal::i2c::Error for LiteI2CError { 48 | fn kind(&self) -> embedded_hal::i2c::ErrorKind { 49 | match *self { 50 | LiteI2CError::NACK => embedded_hal::i2c::ErrorKind::NoAcknowledge( 51 | embedded_hal::i2c::NoAcknowledgeSource::Unknown, 52 | ), 53 | _ => embedded_hal::i2c::ErrorKind::Other, 54 | } 55 | } 56 | } 57 | 58 | #[macro_export] 59 | macro_rules! litei2cmaster { 60 | ($( 61 | $LITEI2CMASTER:ident: $PACI2CMASTERX:ty, 62 | )+) => { 63 | $( 64 | #[derive(Debug)] 65 | pub struct $LITEI2CMASTER { 66 | registers: $PACI2CMASTERX, 67 | pub speed_mode: $crate::litei2cmaster::LiteI2CSpeedMode, 68 | } 69 | 70 | impl $LITEI2CMASTER { 71 | pub fn new(registers: $PACI2CMASTERX, speed_mode: $crate::litei2cmaster::LiteI2CSpeedMode) -> Self { 72 | 73 | let speed_mode_reg_setting : u32 = 74 | match speed_mode { 75 | $crate::litei2cmaster::LiteI2CSpeedMode::Standard => {0}, 76 | $crate::litei2cmaster::LiteI2CSpeedMode::Fast => {1}, 77 | $crate::litei2cmaster::LiteI2CSpeedMode::FastPlus => {2} 78 | }; 79 | 80 | //Set PHY speed mode 81 | registers. 82 | phy_speed_mode().write(|w| unsafe { w.bits(speed_mode_reg_setting) }); 83 | 84 | Self { registers, speed_mode } 85 | } 86 | 87 | pub fn free(self) -> $PACI2CMASTERX { 88 | self.registers 89 | } 90 | } 91 | 92 | impl $crate::hal::i2c::ErrorType for $LITEI2CMASTER { 93 | type Error = $crate::litei2cmaster::LiteI2CError; 94 | } 95 | 96 | impl I2c<$crate::hal::i2c::SevenBitAddress> for $LITEI2CMASTER { 97 | 98 | fn transaction( 99 | &mut self, 100 | address: u8, 101 | operations: &mut [$crate::hal::i2c::Operation<'_>], 102 | ) -> Result<(), $crate::litei2cmaster::LiteI2CError> { 103 | 104 | if operations.len() == 0 { 105 | return Ok(()); 106 | } 107 | 108 | let mut operations_peekable_iter = operations.iter_mut().peekable(); 109 | 110 | 111 | //Activate master 112 | self.registers.master_active().write(|w| unsafe { w.bits(1) }); 113 | 114 | //Flush RX buffer 115 | while self.registers.master_status().read().rx_ready().bit() { 116 | let _ = self.registers.master_rxtx().read().bits(); 117 | } 118 | //Wait for TX ready 119 | while !self.registers.master_status().read().tx_ready().bit() { 120 | } 121 | 122 | //Set slave address 123 | self.registers.master_addr().write(|w| unsafe { w.bits(address as u32) }); 124 | 125 | let mut len_tx_buf : usize = 0; 126 | let mut len_rx_buf : usize = 0; 127 | let mut len_tx : u8 = 0; 128 | let mut len_rx : u8 = 0; 129 | let mut tx_buf : u32 = 0; 130 | let mut write_next_read_op = false; 131 | 132 | loop { 133 | 134 | if let Some(operation) = operations_peekable_iter.next() { 135 | 136 | write_next_read_op = false; 137 | 138 | match operation { 139 | $crate::hal::i2c::Operation::Read(read_buffer) => { 140 | len_rx_buf = read_buffer.len(); 141 | }, 142 | $crate::hal::i2c::Operation::Write(write_buffer) => { 143 | 144 | len_tx_buf = write_buffer.len(); 145 | 146 | } 147 | 148 | } 149 | 150 | if len_rx_buf > 255 || len_rx_buf > 255 { 151 | break; 152 | } 153 | 154 | let mut tx_j : usize = 0; 155 | let mut rx_j : usize = 0; 156 | 157 | loop { 158 | 159 | if len_tx_buf > (tx_j + 4) { 160 | len_tx = 5; 161 | len_rx = 0; 162 | } else { 163 | len_tx = u8::try_from(len_tx_buf - tx_j).unwrap(); 164 | 165 | if (len_rx_buf > (rx_j + 4)) { 166 | len_rx = 5; 167 | } else { 168 | len_rx = u8::try_from(len_rx_buf - rx_j).unwrap(); 169 | } 170 | } 171 | 172 | tx_buf = 0; 173 | 174 | match operation { 175 | $crate::hal::i2c::Operation::Write(write_buffer) => { 176 | 177 | match len_tx { 178 | 5 | 4 => { 179 | tx_buf |= (write_buffer[0 + tx_j] as u32) << 24_u32; 180 | tx_buf |= (write_buffer[1 + tx_j] as u32) << 16_u32; 181 | tx_buf |= (write_buffer[2 + tx_j] as u32) << 8_u32; 182 | tx_buf |= write_buffer[3 + tx_j] as u32; 183 | tx_j = tx_j.checked_add(4).unwrap(); 184 | }, 185 | 3 => { 186 | tx_buf |= (write_buffer[0 + tx_j] as u32) << 16_u32; 187 | tx_buf |= (write_buffer[1 + tx_j] as u32) << 8_u32; 188 | tx_buf |= write_buffer[2 + tx_j] as u32; 189 | tx_j = tx_j.checked_add(3).unwrap(); 190 | }, 191 | 2 => { 192 | tx_buf |= (write_buffer[0 + tx_j] as u32) << 8_u32; 193 | tx_buf |= write_buffer[1 + tx_j] as u32; 194 | tx_j = tx_j.checked_add(2).unwrap(); 195 | }, 196 | 1 => { 197 | tx_buf |= write_buffer[0 + tx_j] as u32; 198 | tx_j = tx_j.checked_add(1).unwrap(); 199 | } 200 | _ => { panic!(); } 201 | }; 202 | 203 | }, 204 | _ => {} 205 | } 206 | 207 | //Write transfer settings 208 | self.registers 209 | .master_settings() 210 | .write(|w| unsafe { w.len_tx().bits(len_tx).len_rx().bits(len_rx).recover().bit(false) }); 211 | 212 | //Send data 213 | self.registers 214 | .master_rxtx() 215 | .write(|w| unsafe { w.bits(tx_buf) }); 216 | 217 | while !self.registers.master_status().read().rx_ready().bit() {} 218 | 219 | //Abort if NACK is received 220 | if self.registers.master_status().read().nack().bit() { 221 | 222 | self.registers.master_active().write(|w| unsafe { w.bits(0) }); 223 | 224 | return Err(LiteI2CError::NACK); 225 | 226 | } 227 | 228 | let rx_buf : u32 = self.registers.master_rxtx().read().bits(); 229 | 230 | 231 | if len_rx_buf > 0 { 232 | 233 | match operation { 234 | 235 | $crate::hal::i2c::Operation::Read(read_buffer) => { 236 | 237 | match len_rx { 238 | 5 | 4 => { 239 | read_buffer[0 + rx_j] = (rx_buf >> 24_u32) as u8; 240 | read_buffer[1 + rx_j] = (rx_buf >> 16_u32) as u8; 241 | read_buffer[2 + rx_j] = (rx_buf >> 8_u32) as u8; 242 | read_buffer[3 + rx_j] = rx_buf as u8; 243 | rx_j = rx_j.checked_add(4).unwrap(); 244 | }, 245 | 3 => { 246 | read_buffer[0 + rx_j] = (rx_buf >> 16_u32) as u8; 247 | read_buffer[1 + rx_j] = (rx_buf >> 8_u32) as u8; 248 | read_buffer[2 + rx_j] = rx_buf as u8; 249 | rx_j = rx_j.checked_add(3).unwrap(); 250 | }, 251 | 2 => { 252 | read_buffer[0 + rx_j] = (rx_buf >> 8_u32) as u8; 253 | read_buffer[1 + rx_j] = rx_buf as u8; 254 | rx_j = rx_j.checked_add(2).unwrap(); 255 | }, 256 | 1 => { 257 | read_buffer[0 + rx_j] = rx_buf as u8; 258 | rx_j = rx_j.checked_add(1).unwrap(); 259 | } 260 | _ => { panic!(); } 261 | }; 262 | }, 263 | _ => { } 264 | } 265 | 266 | } 267 | 268 | if (tx_j >= len_tx_buf) || (rx_j >= len_rx_buf) { 269 | break; 270 | } 271 | 272 | } 273 | 274 | } 275 | else { 276 | break; 277 | } 278 | 279 | 280 | } 281 | 282 | //Deactivate master 283 | self.registers.master_active().write(|w| unsafe { w.bits(0) }); 284 | 285 | Ok(()) 286 | } 287 | } 288 | 289 | )+ 290 | } 291 | } 292 | --------------------------------------------------------------------------------