Compare commits

..

10 Commits

Author SHA1 Message Date
J / Jacob Babich
4fa7351d91 remove todos 2022-04-29 23:42:44 -04:00
J / Jacob Babich
062441b5e2 update 2022-04-29 23:24:13 -04:00
J / Jacob Babich
18e9a5d7de starting uart and refactoring 2022-04-22 03:11:45 -04:00
J / Jacob Babich
e809e84afc clean 2022-04-20 21:01:15 -04:00
J / Jacob Babich
508e3897e0 color refactor 2022-04-18 15:06:55 -04:00
J / Jacob Babich
d875364deb stuffs 2022-04-17 20:08:48 -04:00
J / Jacob Babich
db033c7ee6 trying out uart and asm 2022-04-17 13:18:43 -04:00
J / Jacob Babich
ac0e1067d0 uart beginnings (fragile handle with care) 2022-04-15 13:44:18 -04:00
J / Jacob Babich
45b5e73ac6 publish all 2022-04-15 13:17:39 -04:00
J / Jacob Babich
ee1b811360 delete unneeded build script 2022-04-14 19:30:16 -04:00
16 changed files with 748 additions and 601 deletions

203
Cargo.lock generated
View File

@@ -2,67 +2,6 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3 version = 3
[[package]]
name = "aligned"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a785a543aea40f5e4e2e93bb2655d31bc21bb391fff65697150973e383f16bb"
dependencies = [
"as-slice",
]
[[package]]
name = "as-slice"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45403b49e3954a4b8428a0ac21a4b7afadccf92bfd96273f1a58cd4812496ae0"
dependencies = [
"generic-array 0.12.4",
"generic-array 0.13.3",
"generic-array 0.14.5",
"stable_deref_trait",
]
[[package]]
name = "bare-metal"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5deb64efa5bd81e31fcd1938615a6d98c82eafcbcd787162b6f63b91d6bac5b3"
dependencies = [
"rustc_version",
]
[[package]]
name = "bitfield"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46afbd2983a5d5a7bd740ccb198caf5b82f45c40c09c0eed36052d91cb92e719"
[[package]]
name = "cortex-m"
version = "0.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9075300b07c6a56263b9b582c214d0ff037b00d45ec9fde1cc711490c56f1bb9"
dependencies = [
"aligned",
"bare-metal",
"bitfield",
"cortex-m 0.7.4",
"volatile-register",
]
[[package]]
name = "cortex-m"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37ff967e867ca14eba0c34ac25cd71ea98c678e741e3915d923999bb2fe7c826"
dependencies = [
"bare-metal",
"bitfield",
"embedded-hal",
"volatile-register",
]
[[package]] [[package]]
name = "cortex-m-rt" name = "cortex-m-rt"
version = "0.6.15" version = "0.6.15"
@@ -84,84 +23,13 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "cortex-m-semihosting"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bffa6c1454368a6aa4811ae60964c38e6996d397ff8095a8b9211b1c1f749bc"
dependencies = [
"cortex-m 0.7.4",
]
[[package]] [[package]]
name = "driver-and-task-library" name = "driver-and-task-library"
version = "4.14.0" version = "4.14.0"
dependencies = [ dependencies = [
"cortex-m 0.6.7",
"cortex-m-rt", "cortex-m-rt",
"cortex-m-semihosting",
"panic-halt",
] ]
[[package]]
name = "embedded-hal"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35949884794ad573cf46071e41c9b60efb0cb311e3ca01f7af807af1debc66ff"
dependencies = [
"nb 0.1.3",
"void",
]
[[package]]
name = "generic-array"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd"
dependencies = [
"typenum",
]
[[package]]
name = "generic-array"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f797e67af32588215eaaab8327027ee8e71b9dd0b2b26996aedf20c030fce309"
dependencies = [
"typenum",
]
[[package]]
name = "generic-array"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "nb"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "801d31da0513b6ec5214e9bf433a77966320625a37860f910be265be6e18d06f"
dependencies = [
"nb 1.0.0",
]
[[package]]
name = "nb"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "546c37ac5d9e56f55e73b677106873d9d9f5190605e41a856503623648488cae"
[[package]]
name = "panic-halt"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de96540e0ebde571dc55c73d60ef407c653844e6f9a1e2fdbd40c07b9252d812"
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.37" version = "1.0.37"
@@ -173,9 +41,9 @@ dependencies = [
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.17" version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "632d02bff7f874a36f33ea8bb416cd484b90cc66c1194b1a1110d067a7013f58" checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
] ]
@@ -186,82 +54,19 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2a38df5b15c8d5c7e8654189744d8e396bddc18ad48041a500ce52d6948941f" checksum = "e2a38df5b15c8d5c7e8654189744d8e396bddc18ad48041a500ce52d6948941f"
[[package]]
name = "rustc_version"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"
dependencies = [
"semver",
]
[[package]]
name = "semver"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403"
dependencies = [
"semver-parser",
]
[[package]]
name = "semver-parser"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"
[[package]]
name = "stable_deref_trait"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
[[package]] [[package]]
name = "syn" name = "syn"
version = "1.0.91" version = "1.0.92"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d" checksum = "7ff7c592601f11445996a06f8ad0c27f094a58857c2f89e97974ab9235b92c52"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"unicode-xid", "unicode-xid",
] ]
[[package]]
name = "typenum"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987"
[[package]] [[package]]
name = "unicode-xid" name = "unicode-xid"
version = "0.2.2" version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
[[package]]
name = "vcell"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77439c1b53d2303b20d9459b1ade71a83c716e3f9c34f3228c00e6f185d6c002"
[[package]]
name = "version_check"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "void"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d"
[[package]]
name = "volatile-register"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ee8f19f9d74293faf70901bc20ad067dc1ad390d2cbf1e3f75f721ffee908b6"
dependencies = [
"vcell",
]

View File

@@ -5,10 +5,7 @@ name = "driver-and-task-library"
version = "4.14.0" version = "4.14.0"
[dependencies] [dependencies]
cortex-m = "0.6.0"
cortex-m-rt = "0.6.10" cortex-m-rt = "0.6.10"
cortex-m-semihosting = "0.3.3"
panic-halt = "0.2.0"
[lib] [lib]
path = "src/lib/mod.rs" path = "src/lib/mod.rs"
@@ -22,6 +19,7 @@ test = false
bench = false bench = false
[profile.release] [profile.release]
# These comments are from the starter project (not written by me). I left them in since they explain it:
codegen-units = 1 # better optimizations codegen-units = 1 # better optimizations
debug = true # symbols are nice and they don't increase the size on Flash debug = true # symbols are nice and they don't increase the size on Flash
lto = true # better optimizations lto = true # better optimizations

View File

@@ -1 +0,0 @@
# TODO: Write README

View File

@@ -1,31 +0,0 @@
//! 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());
// By default, Cargo will re-run a build script whenever
// any file in the project changes. By specifying `memory.x`
// here, we ensure the build script is only re-run when
// `memory.x` is changed.
println!("cargo:rerun-if-changed=memory.x");
}

View File

@@ -5,19 +5,20 @@ use panic_halt as _; // you can put a breakpoint on `rust_begin_unwind` to catch
use cortex_m_rt::entry; use cortex_m_rt::entry;
use driver_and_task_library::{ use driver_and_task_library::{
setup_board, Function, Pin, Port, PortOptions, ReadablePinOptions, WritablePinOptions, H, L, setup_board, Function, GPIOPortOptions, Pin, Port, Pull, ReadablePinOptions,
WritablePinOptions, H, L,
}; };
#[entry] #[entry]
fn main() -> ! { fn main() -> ! {
let board = setup_board(); let board = setup_board();
let port_f = board.setup_gpio_port(Port::F, PortOptions); let port_f = board.setup_gpio_port(Port::F);
let switches = port_f.setup_readable_pins( let switches = port_f.setup_readable_pins(
[Pin::Zero, Pin::Four], [Pin::Zero, Pin::Four],
ReadablePinOptions { ReadablePinOptions {
function: Function::Digital, function: Function::Digital,
pull_up: Some(true), pull: Pull::Up,
}, },
); );
let [_sw1, _sw2] = switches.pins(); let [_sw1, _sw2] = switches.pins();

BIN
src/.DS_Store vendored Normal file

Binary file not shown.

View File

@@ -1,16 +1,74 @@
use crate::gpio::ports::{setup_gpio_port, Port, PortOptions, UsablePort}; //! Data sheet: https://www.ti.com/lit/ds/spms376e/spms376e.pdf
pub struct UsableBoard; use core::arch::asm;
impl UsableBoard {
pub fn setup_gpio_port(&self, port: Port, options: PortOptions) -> UsablePort { use crate::gpio::ports::{
setup_gpio_port(port, options) setup_port as setup_gpio_port, Port as GPIOPort, UsablePort as UsableGPIOPort,
};
use crate::uart::{
setup_port as setup_uart_port, Port as UARTPort, PortOptions as UARTPortOptions,
UsablePort as UsableUARTPort,
};
/// The board
///
/// Houses memory addresses of registers
#[derive(Clone, Copy)]
pub struct Board;
impl Board {
/// Page 231 of data sheet
const fn base(&self) -> u32 {
0x400F_E000
} }
// TODO: check page 704 for timers /// The memory address of the GPIO Run mode clock gating control (RCGCGPIO) register for GPIO ports
// TODO: impl Drop trait so that tasks all run before the main function ends? ///
// TODO: examine page 670 for when (if) I do interrupts /// Page 340 of data sheet
pub(crate) const fn gpio_run_mode_clock_gating_control(&self) -> *mut u32 {
const OFFSET: u32 = 0x608;
(self.base() + OFFSET) as *mut u32
}
/// The memory address of the run mode clock gating control 1 (RCGC1) register for the system
///
/// Page (ran out of time) of data sheet
pub(crate) const fn run_mode_clock_gating_control_1(&self) -> *mut u32 {
const OFFSET: u32 = 0x104;
(self.base() + OFFSET) as *mut u32
}
} }
pub fn setup_board() -> UsableBoard { /// A setup version of the board that GPIO and UART ports can be set up on
UsableBoard pub struct UsableBoard {
board: Board,
}
impl UsableBoard {
pub(crate) fn no_op(&self) {
unsafe {
asm!("nop");
}
}
pub(crate) fn no_ops(&self, n: u32) {
for _ in 0..n {
self.no_op();
}
}
}
impl UsableBoard {
pub fn setup_gpio_port(&mut self, port: GPIOPort) -> UsableGPIOPort {
setup_gpio_port(self.board, port)
}
pub fn setup_uart_port(&mut self, port: UARTPort, options: UARTPortOptions) -> UsableUARTPort {
setup_uart_port(self.board, port, options, &|n| self.no_ops(n))
}
}
/// Start using the driver and task library by setting up the TM4C123GXL board
pub fn setup_board() -> UsableBoard {
UsableBoard { board: Board }
} }

View File

@@ -1,4 +1,8 @@
use crate::{memory, L}; use crate::{
memory,
utils::{pins_to_bits, reverse_array},
H, L,
};
use super::ports::Port; use super::ports::Port;
@@ -13,7 +17,6 @@ pub enum Pin {
Six = 6, Six = 6,
Seven = 7, Seven = 7,
} }
pub enum Function { pub enum Function {
Analog, Analog,
Digital, Digital,
@@ -23,10 +26,16 @@ pub enum Function {
UART, UART,
} }
pub enum Pull {
Down,
Up,
Neither,
}
/// Page 1351 of data sheet /// Page 1351 of data sheet
pub struct ReadablePinOptions { pub struct ReadablePinOptions {
pub function: Function, pub function: Function,
pub pull_up: Option<bool>, pub pull: Pull,
} }
pub struct ReadablePins<const N: usize> { pub struct ReadablePins<const N: usize> {
data_address: *mut u32, data_address: *mut u32,
@@ -38,18 +47,18 @@ impl<const N: usize> ReadablePins<N> {
} }
pub fn read_all(&self) -> [bool; N] { pub fn read_all(&self) -> [bool; N] {
unsafe { memory::read_bits(self.data_address, &self.pins.map(|pin| pin.bit as u32)) } unsafe { memory::read_bits(self.data_address, &self.pins.map(|pin| pin.pin as u32)) }
} }
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct ReadablePin { pub struct ReadablePin {
data_address: *mut u32, data_address: *mut u32,
bit: Pin, pin: Pin,
} }
impl ReadablePin { impl ReadablePin {
pub fn read(&self) -> bool { pub fn read(&self) -> bool {
let current = unsafe { memory::read(self.data_address) }; let current = unsafe { memory::read(self.data_address) };
current & (1 << self.bit as u32) != 0 current & (1 << self.pin as u32) != 0
} }
} }
@@ -66,34 +75,34 @@ impl<const N: usize> WritablePins<N> {
} }
pub fn read_all(&self) -> [bool; N] { pub fn read_all(&self) -> [bool; N] {
unsafe { memory::read_bits(self.data_address, &self.pins.map(|pin| pin.bit as u32)) } unsafe { memory::read_bits(self.data_address, &self.pins.map(|pin| pin.pin as u32)) }
} }
pub fn write_all(&mut self, values: [bool; N]) { pub fn write_all(&mut self, values: [bool; N]) {
unsafe { unsafe {
memory::write_bits( memory::write_bits(
self.data_address, self.data_address,
&self.pins.map(|pin| pin.bit as u32), &self.pins.map(|pin| pin.pin as u32),
values, values,
) )
} }
} }
pub fn update_all<Updater: Fn([bool; N]) -> [bool; N]>(&mut self, updater: Updater) { pub fn update_all(&mut self, updater: &dyn Fn([bool; N]) -> [bool; N]) {
self.write_all(updater(self.read_all())); self.write_all(updater(self.read_all()));
} }
pub fn clear_all(&mut self) { pub fn clear_all(&mut self) {
unsafe { unsafe {
memory::clear_bits(self.data_address, &self.pins.map(|pin| pin.bit as u32)); memory::clear_bits(self.data_address, &self.pins.map(|pin| pin.pin as u32));
} }
} }
pub fn set_all(&mut self) { pub fn set_all(&mut self) {
unsafe { unsafe {
memory::set_bits(self.data_address, &self.pins.map(|pin| pin.bit as u32)); memory::set_bits(self.data_address, &self.pins.map(|pin| pin.pin as u32));
} }
} }
pub fn toggle_all(&mut self) { pub fn toggle_all(&mut self) {
unsafe { unsafe {
memory::toggle_bits(self.data_address, &self.pins.map(|pin| pin.bit as u32)); memory::toggle_bits(self.data_address, &self.pins.map(|pin| pin.pin as u32));
} }
} }
} }
@@ -101,26 +110,26 @@ impl<const N: usize> WritablePins<N> {
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct WritablePin { pub struct WritablePin {
data_address: *mut u32, data_address: *mut u32,
bit: Pin, pin: Pin,
} }
impl WritablePin { impl WritablePin {
pub fn read(&self) -> bool { pub fn read(&self) -> bool {
let current = unsafe { memory::read(self.data_address) }; let current = unsafe { memory::read(self.data_address) };
current & (1 << self.bit as u32) != 0 current & (1 << self.pin as u32) != 0
} }
pub fn clear(&mut self) { pub fn clear(&mut self) {
unsafe { unsafe {
memory::clear_bits(self.data_address, &[self.bit as u32]); memory::clear_bits(self.data_address, &[self.pin as u32]);
} }
} }
pub fn set(&mut self) { pub fn set(&mut self) {
unsafe { unsafe {
memory::set_bits(self.data_address, &[self.bit as u32]); memory::set_bits(self.data_address, &[self.pin as u32]);
} }
} }
pub fn toggle(&mut self) { pub fn toggle(&mut self) {
unsafe { unsafe {
memory::toggle_bits(self.data_address, &[self.bit as u32]); memory::toggle_bits(self.data_address, &[self.pin as u32]);
} }
} }
} }
@@ -128,8 +137,116 @@ impl WritablePin {
/// Page 684 of the data sheet for how the lock mechanism works /// Page 684 of the data sheet for how the lock mechanism works
const UNLOCK: u32 = 0x4C4F434B; const UNLOCK: u32 = 0x4C4F434B;
fn setup_pins() { fn setup_pins<const N: usize>(
todo!(); port: Port,
pins: [Pin; N],
writable: bool,
function: Function,
pull: Pull,
) {
// Unlock the pins
unsafe {
memory::write(port.lock(), UNLOCK);
}
// Set to output pins if output (otherwise set to input)
if writable {
unsafe {
memory::set_bits(port.direction(), &pins_to_bits(&pins));
}
} else {
unsafe {
memory::clear_bits(port.direction(), &pins_to_bits(&pins));
}
}
// Disable alternate function when it's not used (and enable it when it is)
if let Function::Analog | Function::Digital = function {
unsafe {
memory::clear_bits(port.alternate_function_select(), &pins_to_bits(&pins));
}
} else {
unsafe {
memory::set_bits(port.alternate_function_select(), &pins_to_bits(&pins));
}
}
// Configure pull-up and pull-down resistors
match pull {
Pull::Down => unsafe {
memory::set_bits(port.pull_down_select(), &pins_to_bits(&pins));
},
Pull::Up => unsafe {
memory::set_bits(port.pull_up_select(), &pins_to_bits(&pins));
},
Pull::Neither => {
unsafe {
memory::clear_bits(port.pull_up_select(), &pins_to_bits(&pins));
}
unsafe {
memory::clear_bits(port.pull_down_select(), &pins_to_bits(&pins));
}
}
}
unsafe {
memory::set_bits(port.commit(), &pins_to_bits(&pins));
}
// Enable digital function when it's needed (and disable it when it's not)
match function {
Function::Digital | Function::UART => unsafe {
memory::set_bits(port.digital_enable(), &pins_to_bits(&pins));
},
Function::Analog => unsafe {
memory::clear_bits(port.digital_enable(), &pins_to_bits(&pins));
},
_ => todo!(), // and rewrite to if let when solved
}
// Enable analog when it's needed (and disable it when it's not)
if let Function::Analog = function {
unsafe {
memory::set_bits(port.analog_mode_select(), &pins_to_bits(&pins));
}
} else {
unsafe {
memory::clear_bits(port.analog_mode_select(), &pins_to_bits(&pins));
}
}
// Table 10-2 on page 650-651 of data sheet
let digital_function = match function {
Function::Analog => None,
Function::Digital => Some([L, L, L, L]),
Function::CAN => Some([H, L, L, L]),
Function::I2C => Some([L, L, H, H]),
Function::PWM => Some([L, H, L, H]),
Function::UART => Some([L, L, L, H]),
};
if let Some(array) = digital_function {
let port_control_values = reverse_array(array);
for pin in pins {
let mut memory_bits = [0; 4];
let min = (pin as u32) * 4;
let max = min + 3;
let range = min..=max;
for (i, memory_bit) in range.enumerate() {
memory_bits[i] = memory_bit;
}
unsafe {
memory::write_bits(port.port_control(), &memory_bits, port_control_values);
}
}
}
unsafe {
memory::write(port.lock(), 0);
}
} }
pub fn setup_readable_pins<const N: usize>( pub fn setup_readable_pins<const N: usize>(
@@ -137,83 +254,10 @@ pub fn setup_readable_pins<const N: usize>(
pins: [Pin; N], pins: [Pin; N],
options: ReadablePinOptions, options: ReadablePinOptions,
) -> ReadablePins<N> { ) -> ReadablePins<N> {
// Unlock the pins setup_pins(port, pins, false, options.function, options.pull);
unsafe {
memory::write(port.lock(), UNLOCK);
memory::set_bits(port.commit(), &pins.map(|bit| bit as u32));
}
// Disable analog when it's not selected (and enable analog if it is)
match options.function {
Function::Analog => unsafe {
memory::set_bits(port.analog_mode_select(), &pins.map(|bit| bit as u32));
},
_ => unsafe {
memory::clear_bits(port.analog_mode_select(), &pins.map(|bit| bit as u32));
},
}
unsafe {
memory::clear_bits(port.direction(), &pins.map(|bit| bit as u32));
}
for pin in pins {
let mut memory_bits = [0; 4];
let min = (pin as u32) * 4;
let max = min + 4;
let range = min..max;
for (i, memory_bit) in range.enumerate() {
memory_bits[i] = memory_bit;
}
let values = match options.function {
Function::Analog => todo!(),
Function::Digital => [L, L, L, L],
Function::CAN => todo!(),
Function::I2C => todo!(),
Function::PWM => todo!(),
Function::UART => todo!(),
};
unsafe {
memory::write_bits(port.port_control(), &memory_bits, values);
}
}
// Configure pull-up and pull-down resistors
match options.pull_up {
Some(true) => unsafe {
memory::set_bits(port.pull_up_select(), &pins.map(|bit| bit as u32));
},
Some(false) => unsafe {
memory::set_bits(port.pull_down_select(), &pins.map(|bit| bit as u32));
},
None => {
unsafe {
memory::clear_bits(port.pull_up_select(), &pins.map(|bit| bit as u32));
}
unsafe {
memory::clear_bits(port.pull_down_select(), &pins.map(|bit| bit as u32));
}
}
}
match options.function {
Function::Digital => unsafe {
memory::set_bits(port.digital_enable(), &pins.map(|bit| bit as u32));
},
Function::Analog => unsafe {
memory::clear_bits(port.digital_enable(), &pins.map(|bit| bit as u32));
},
_ => todo!(),
}
let data_address = port.data(&pins); let data_address = port.data(&pins);
let pins: [ReadablePin; N] = pins.map(|pin| ReadablePin { data_address, pin });
let pins: [ReadablePin; N] = pins.map(|bit| ReadablePin { data_address, bit });
ReadablePins { data_address, pins } ReadablePins { data_address, pins }
} }
@@ -222,86 +266,9 @@ pub fn setup_writable_pins<const N: usize>(
pins: [Pin; N], pins: [Pin; N],
options: WritablePinOptions, options: WritablePinOptions,
) -> WritablePins<N> { ) -> WritablePins<N> {
// Unlock the pins setup_pins(port, pins, true, options.function, Pull::Neither);
unsafe {
memory::write(port.lock(), UNLOCK);
memory::set_bits(port.commit(), &pins.map(|bit| bit as u32));
}
// Disable analog when it's not selected (and enable analog if it is)
match options.function {
Function::Analog => unsafe {
memory::set_bits(port.analog_mode_select(), &pins.map(|bit| bit as u32));
},
_ => unsafe {
memory::clear_bits(port.analog_mode_select(), &pins.map(|bit| bit as u32));
},
}
unsafe {
memory::set_bits(port.direction(), &pins.map(|bit| bit as u32));
}
for pin in pins {
let mut memory_bits = [0; 4];
let min = (pin as u32) * 4;
let max = min + 3;
let range = min..=max;
for (i, memory_bit) in range.enumerate() {
memory_bits[i] = memory_bit;
}
let values = match options.function {
Function::Analog => todo!(),
Function::Digital => [L, L, L, L],
Function::CAN => todo!(),
Function::I2C => todo!(),
Function::PWM => todo!(),
Function::UART => todo!(),
};
unsafe {
memory::write_bits(port.port_control(), &memory_bits, values);
}
}
// TODO: check page 671 or 682 (+ more prob) for a table showing initial pin states
// TODO: finish
match options.function {
Function::Analog | Function::Digital => unsafe {
memory::clear_bits(
port.alternate_function_select(),
&pins.map(|bit| bit as u32),
);
},
_ => unsafe {
memory::set_bits(
port.alternate_function_select(),
&pins.map(|bit| bit as u32),
);
},
}
match options.function {
Function::Digital => unsafe {
memory::set_bits(port.digital_enable(), &pins.map(|bit| bit as u32));
},
Function::Analog => unsafe {
memory::clear_bits(port.digital_enable(), &pins.map(|bit| bit as u32));
},
_ => todo!(),
}
let data_address = port.data(&pins); let data_address = port.data(&pins);
let pins: [WritablePin; N] = pins.map(|pin| WritablePin { data_address, pin });
let pins: [WritablePin; N] = pins.map(|pin| WritablePin {
data_address,
bit: pin,
});
WritablePins { data_address, pins } WritablePins { data_address, pins }
} }

View File

@@ -1,5 +1,5 @@
use crate::{ use crate::{
memory, registers, Pin, ReadablePinOptions, ReadablePins, WritablePinOptions, WritablePins, memory, Board, Pin, ReadablePinOptions, ReadablePins, WritablePinOptions, WritablePins,
}; };
use super::pins::{setup_readable_pins, setup_writable_pins}; use super::pins::{setup_readable_pins, setup_writable_pins};
@@ -20,7 +20,7 @@ impl Port {
/// The starting point of memory addresses corresponding to this GPIO register /// The starting point of memory addresses corresponding to this GPIO register
/// ///
/// Modeled after page 660 of data sheet (GPIO Register Map) /// Modeled after page 660 of data sheet (GPIO Register Map)
fn base(&self) -> u32 { const fn base(&self) -> u32 {
match self { match self {
Port::A => 0x4000_4000, Port::A => 0x4000_4000,
Port::B => 0x4000_5000, Port::B => 0x4000_5000,
@@ -34,7 +34,7 @@ impl Port {
/// The memory address of the alternate function select (AFSEL) register for this port /// The memory address of the alternate function select (AFSEL) register for this port
/// ///
/// Page 671 of data sheet /// Page 671 of data sheet
pub(super) fn alternate_function_select(&self) -> *mut u32 { pub(super) const fn alternate_function_select(&self) -> *mut u32 {
const OFFSET: u32 = 0x420; const OFFSET: u32 = 0x420;
(self.base() + OFFSET) as *mut u32 (self.base() + OFFSET) as *mut u32
} }
@@ -42,7 +42,7 @@ impl Port {
/// The memory address of the analog mode select (AMSEL) register for this port /// The memory address of the analog mode select (AMSEL) register for this port
/// ///
/// Page 687 of data sheet /// Page 687 of data sheet
pub(super) fn analog_mode_select(&self) -> *mut u32 { pub(super) const fn analog_mode_select(&self) -> *mut u32 {
const OFFSET: u32 = 0x52C; const OFFSET: u32 = 0x52C;
(self.base() + OFFSET) as *mut u32 (self.base() + OFFSET) as *mut u32
} }
@@ -50,7 +50,7 @@ impl Port {
/// The memory address of the commit (CR) register for this port /// The memory address of the commit (CR) register for this port
/// ///
/// Page 685 of data sheet /// Page 685 of data sheet
pub(super) fn commit(&self) -> *mut u32 { pub(super) const fn commit(&self) -> *mut u32 {
const OFFSET: u32 = 0x524; const OFFSET: u32 = 0x524;
(self.base() + OFFSET) as *mut u32 (self.base() + OFFSET) as *mut u32
} }
@@ -76,7 +76,7 @@ impl Port {
/// The memory address of the digital enable (DEN) register for this port /// The memory address of the digital enable (DEN) register for this port
/// ///
/// Page 682 of data sheet /// Page 682 of data sheet
pub(super) fn digital_enable(&self) -> *mut u32 { pub(super) const fn digital_enable(&self) -> *mut u32 {
const OFFSET: u32 = 0x51C; const OFFSET: u32 = 0x51C;
(self.base() + OFFSET) as *mut u32 (self.base() + OFFSET) as *mut u32
} }
@@ -84,7 +84,7 @@ impl Port {
/// The memory address of the direction (DIR) register for this port /// The memory address of the direction (DIR) register for this port
/// ///
/// Page 663 of data sheet /// Page 663 of data sheet
pub(super) fn direction(&self) -> *mut u32 { pub(super) const fn direction(&self) -> *mut u32 {
const OFFSET: u32 = 0x400; const OFFSET: u32 = 0x400;
(self.base() + OFFSET) as *mut u32 (self.base() + OFFSET) as *mut u32
} }
@@ -92,7 +92,7 @@ impl Port {
/// The memory address of the lock (LOCK) register /// The memory address of the lock (LOCK) register
/// ///
/// Page 684 of data sheet /// Page 684 of data sheet
pub(super) fn lock(&self) -> *mut u32 { pub(super) const fn lock(&self) -> *mut u32 {
const OFFSET: u32 = 0x520; const OFFSET: u32 = 0x520;
(self.base() + OFFSET) as *mut u32 (self.base() + OFFSET) as *mut u32
} }
@@ -100,33 +100,29 @@ impl Port {
/// The memory address of the port control (PCTL) register for this port /// The memory address of the port control (PCTL) register for this port
/// ///
/// Page 688 of data sheet /// Page 688 of data sheet
pub(super) fn port_control(&self) -> *mut u32 { pub(super) const fn port_control(&self) -> *mut u32 {
const OFFSET: u32 = 0x52C; const OFFSET: u32 = 0x52C;
(self.base() + OFFSET) as *mut u32 (self.base() + OFFSET) as *mut u32
} }
/// The memory address of the pull-down resistor select (PDR) register for this port /// The memory address of the pull-down resistor select (PDR) register for this port
/// Page 679 of data sheet /// Page 679 of data sheet
pub(super) fn pull_down_select(&self) -> *mut u32 { pub(super) const fn pull_down_select(&self) -> *mut u32 {
const OFFSET: u32 = 0x514; const OFFSET: u32 = 0x514;
(self.base() + OFFSET) as *mut u32 (self.base() + OFFSET) as *mut u32
} }
/// The memory address of the pull-up resistor select (PUR) register for this port /// The memory address of the pull-up resistor select (PUR) register for this port
/// Page 677 of data sheet /// Page 677 of data sheet
pub(super) fn pull_up_select(&self) -> *mut u32 { pub(super) const fn pull_up_select(&self) -> *mut u32 {
const OFFSET: u32 = 0x510; const OFFSET: u32 = 0x510;
(self.base() + OFFSET) as *mut u32 (self.base() + OFFSET) as *mut u32
} }
// TODO: examine page 690 (ADC) for applicability
// Note to self: page 1351 of data sheet for PWM
// Apparently also for ADC!
} }
impl Port { impl Port {
/// The corresponding bit for this port in system's run-mode clock gate control (RCGC) register /// The corresponding bit for this port in the system's GPIO Run mode clock gating control (RCGCGPIO) register
fn run_mode_clock_gate_control(&self) -> u32 { const fn run_mode_clock_gate_control(&self) -> u32 {
match self { match self {
Port::A => 0, Port::A => 0,
Port::B => 1, Port::B => 1,
@@ -144,7 +140,7 @@ pub struct UsablePort {
impl UsablePort { impl UsablePort {
pub fn setup_readable_pins<const N: usize>( pub fn setup_readable_pins<const N: usize>(
&self, &mut self,
pins: [Pin; N], pins: [Pin; N],
options: ReadablePinOptions, options: ReadablePinOptions,
) -> ReadablePins<N> { ) -> ReadablePins<N> {
@@ -152,7 +148,7 @@ impl UsablePort {
} }
pub fn setup_writable_pins<const N: usize>( pub fn setup_writable_pins<const N: usize>(
&self, &mut self,
pins: [Pin; N], pins: [Pin; N],
options: WritablePinOptions, options: WritablePinOptions,
) -> WritablePins<N> { ) -> WritablePins<N> {
@@ -160,11 +156,11 @@ impl UsablePort {
} }
} }
pub fn setup_gpio_port(port: Port, _options: PortOptions) -> UsablePort { pub fn setup_port(board: Board, port: Port) -> UsablePort {
unsafe { unsafe {
memory::set_bits( memory::set_bits(
registers::system::RCGCGPIO, board.gpio_run_mode_clock_gating_control(),
&[port.run_mode_clock_gate_control() as u32], &[port.run_mode_clock_gate_control()],
); );
} }

View File

@@ -2,86 +2,47 @@
use core::ptr; use core::ptr;
use crate::L; pub unsafe fn read(address: *const u32) -> u32 {
pub unsafe fn read(address: *mut u32) -> u32 {
ptr::read_volatile(address) ptr::read_volatile(address)
} }
pub unsafe fn write(address: *mut u32, new: u32) { pub unsafe fn write(address: *mut u32, new: u32) {
ptr::write_volatile(address, new); ptr::write_volatile(address, new);
} }
pub unsafe fn update<Updater: Fn(u32) -> u32>(address: *mut u32, updater: Updater) { pub unsafe fn update(address: *mut u32, updater: &dyn Fn(u32) -> u32) {
write(address, updater(read(address))); write(address, updater(read(address)));
} }
pub unsafe fn read_bits<const N: usize>(address: *mut u32, bits: &[u32; N]) -> [bool; N] { pub unsafe fn read_bits<const N: usize>(address: *const u32, bits: &[u32; N]) -> [bool; N] {
let current = read(address); let current = read(address);
let mut result = [L; N];
// TODO: look up accumulate or reduce or something bits.map(|bit| current & (1 << bit) != 0)
for (i, bit) in bits.iter().enumerate() {
result[i] = (current & (1 << bit)) != 0;
}
result
} }
pub unsafe fn write_bits<const N: usize>(address: *mut u32, bits: &[u32; N], values: [bool; N]) { pub unsafe fn write_bits<const N: usize>(address: *mut u32, bits: &[u32; N], values: [bool; N]) {
update(address, |current| { update(address, &|current| {
let mut new = current; bits.iter().zip(values).fold(current, |result, (bit, set)| {
// TODO: look up accumulate or reduce or something
for (bit, set) in bits.iter().zip(values) {
if set { if set {
new |= 1 << bit; result | (1 << bit)
} else { } else {
new &= !(1 << bit); result & !(1 << bit)
} }
} })
new
}) })
} }
pub unsafe fn update_bits<Updater: Fn([bool; N]) -> [bool; N], const N: usize>(
address: *mut u32,
bits: &[u32; N],
updater: Updater,
) {
write_bits(address, bits, updater(read_bits(address, bits)))
}
pub unsafe fn set_bits(address: *mut u32, bits: &[u32]) { pub unsafe fn set_bits(address: *mut u32, bits: &[u32]) {
update(address, |current| { update(address, &|current| {
let mut new = current; bits.iter().fold(current, |result, bit| result | (1 << bit))
// TODO: look up accumulate or reduce or something
for bit in bits {
new |= 1 << bit;
}
new
}) })
} }
pub unsafe fn clear_bits(address: *mut u32, bits: &[u32]) { pub unsafe fn clear_bits(address: *mut u32, bits: &[u32]) {
update(address, |current| { update(address, &|current| {
let mut new = current; bits.iter()
.fold(current, |result, bit| result & !(1 << bit))
// TODO: look up accumulate or reduce or something
for bit in bits {
new &= !(1 << bit);
}
new
}) })
} }
pub unsafe fn toggle_bits(address: *mut u32, bits: &[u32]) { pub unsafe fn toggle_bits(address: *mut u32, bits: &[u32]) {
update(address, |current| { update(address, &|current| {
let mut new = current; bits.iter().fold(current, |result, bit| result ^ (1 << bit))
// TODO: look up accumulate or reduce or something
for bit in bits {
new ^= 1 << bit;
}
new
}) })
} }

View File

@@ -1,16 +1,135 @@
#![no_std] #![no_std]
#![feature(alloc_error_handler)]
mod board; mod board;
mod gpio; mod gpio;
mod memory; mod memory;
mod registers; mod uart;
mod utils;
pub use board::setup_board; pub use board::*;
pub use gpio::pins::{ pub use gpio::pins::*;
Function, Pin, ReadablePin, ReadablePinOptions, ReadablePins, WritablePin, WritablePinOptions, pub use gpio::ports::{Port as GPIOPort, PortOptions as GPIOPortOptions};
WritablePins, pub use uart::{Port as UARTPort, PortOptions as UARTPortOptions, WordLength};
};
pub use gpio::ports::{Port, PortOptions, UsablePort};
pub const H: bool = true; pub const H: bool = true;
pub const L: bool = false; pub const L: bool = false;
extern crate alloc;
use alloc::string::ToString;
use core::alloc::{GlobalAlloc, Layout};
use core::panic::PanicInfo;
use core::ptr;
const BLACK: [bool; 3] = [L, L, L];
const RED: [bool; 3] = [H, L, L];
const YELLOW: [bool; 3] = [H, H, L];
const CYAN: [bool; 3] = [L, H, H];
#[panic_handler]
fn panic(panic_info: &PanicInfo) -> ! {
let mut board = setup_board();
let mut port_f = board.setup_gpio_port(GPIOPort::F);
let mut rgb_led = port_f.setup_writable_pins(
[Pin::One, Pin::Three, Pin::Two],
WritablePinOptions {
function: Function::Digital,
},
);
// Set the LED to red in case setting up UART causes the system to hang
// and the loop where we flash red / cyan isn't reached
// (but there's no reason that should happen...)
rgb_led.write_all(RED);
let mut port_a = board.setup_gpio_port(GPIOPort::A);
let [_uart_0_rx] = port_a
.setup_readable_pins(
[Pin::Zero],
ReadablePinOptions {
function: Function::UART,
pull: Pull::Neither,
},
)
.pins();
let [mut uart_0_tx] = port_a
.setup_writable_pins(
[Pin::One],
WritablePinOptions {
function: Function::UART,
},
)
.pins();
let mut uart_0 = board.setup_uart_port(
UARTPort::Zero,
UARTPortOptions {
baud_rate: 115_200,
fifos: true,
word_length: WordLength::Eight,
},
);
// https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797
uart_0.write_line(&mut uart_0_tx, "\x1b[31m");
uart_0.write_line(&mut uart_0_tx, &panic_info.to_string());
uart_0.write_line(&mut uart_0_tx, "\x1b[0m");
let pattern = [RED, BLACK, CYAN, BLACK];
loop {
for color in pattern {
rgb_led.write_all(color);
board.no_ops(1_000_000);
}
}
}
struct BumpPointerAlloc;
static mut HEAP: [u8; 0x1000] = [0; 0x1000];
static mut USED: usize = 0;
#[global_allocator]
static ALLOCATOR: BumpPointerAlloc = BumpPointerAlloc;
unsafe impl GlobalAlloc for BumpPointerAlloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let size = layout.size();
if USED + size > HEAP.len() {
ptr::null_mut()
} else {
let pointer = &mut HEAP[USED] as *mut u8;
USED += size;
pointer
}
}
unsafe fn dealloc(&self, _: *mut u8, _: Layout) {}
}
#[alloc_error_handler]
fn alloc_error(_cause: Layout) -> ! {
let mut board = setup_board();
let mut port_f = board.setup_gpio_port(GPIOPort::F);
let mut rgb_led = port_f.setup_writable_pins(
[Pin::One, Pin::Three, Pin::Two],
WritablePinOptions {
function: Function::Digital,
},
);
let pattern = [YELLOW, BLACK, RED, BLACK];
loop {
for color in pattern {
rgb_led.write_all(color);
board.no_ops(1_000_000);
}
}
}

View File

@@ -1,16 +0,0 @@
//! Memory addresses of registers
//! Data sheet: https://www.ti.com/lit/ds/spms376e/spms376e.pdf
// TODO: check page 92-94 for more features ("Memory Map" table)!
// TODO: check page 1230 onward for PWM
/// Page 231 of data sheet
pub mod system {
const BASE: u32 = 0x400F_E000;
// TODO: page 340
pub const RCGCGPIO: *mut u32 = (BASE + 0x608) as *mut u32;
}
// TODO: delete this file

303
src/lib/uart.rs Normal file
View File

@@ -0,0 +1,303 @@
use alloc::string::String;
use crate::{memory, Board, ReadablePin, WritablePin, H, L};
#[derive(Clone, Copy)]
pub enum Port {
Zero = 0,
One = 1,
Two = 2,
Three = 3,
Four = 4,
Five = 5,
Six = 6,
Seven = 7,
}
#[derive(Clone, Copy)]
pub enum WordLength {
Five,
Six,
Seven,
Eight,
}
pub struct PortOptions {
pub baud_rate: u32,
pub fifos: bool,
pub word_length: WordLength,
}
impl Port {
/// The starting point of memory addresses corresponding to this GPIO register
///
/// Modeled after page 904 of data sheet (UART Register Map)
const fn base(&self) -> u32 {
match self {
Port::Zero => 0x4000_C000,
Port::One => 0x4000_D000,
Port::Two => 0x4000_E000,
Port::Three => 0x4000_F000,
Port::Four => 0x4001_0000,
Port::Five => 0x4001_1000,
Port::Six => 0x4001_2000,
Port::Seven => 0x4001_3000,
}
}
/// The memory address of the control (CTL) register for this port
///
/// Page 918 of data sheet
pub(super) const fn control(&self) -> *mut u32 {
const OFFSET: u32 = 0x030;
(self.base() + OFFSET) as *mut u32
}
/// The memory address of the data (DR) register for this port
///
/// Page 906 of data sheet
pub(super) const fn data(&self) -> *mut u32 {
const OFFSET: u32 = 0x000;
(self.base() + OFFSET) as *mut u32
}
/// The memory address of the flag (FR) register for this port
///
/// Page 911 of data sheet
pub(super) const fn flag(&self) -> *mut u32 {
const OFFSET: u32 = 0x018;
(self.base() + OFFSET) as *mut u32
}
/// The memory address of the fractional part of the baud rate register
///
/// Page (ran out of time) of data sheet
pub(super) const fn fractional_baud_rate_divisor(&self) -> *mut u32 {
const OFFSET: u32 = 0x028;
(self.base() + OFFSET) as *mut u32
}
/// The memory address of the integer part of the baud rate register
///
/// Page (ran out of time) of data sheet
pub(super) const fn integer_baud_rate_divisor(&self) -> *mut u32 {
const OFFSET: u32 = 0x024;
(self.base() + OFFSET) as *mut u32
}
/// The memory address of the line control (LCRH) register for this port
///
/// Page 916 of data sheet
pub(super) const fn line_control(&self) -> *mut u32 {
const OFFSET: u32 = 0x02C;
(self.base() + OFFSET) as *mut u32
}
}
impl Port {
/// The receive FIFO empty (RXFE) bit in the flag register
const fn receive_fifo_empty(&self) -> u32 {
4
}
/// The transmit FIFO full (TXFF) bit in the flag register
const fn transmit_fifo_full(&self) -> u32 {
5
}
}
impl Port {
/// The enable (EN) bit in the control register
const fn enable_bit(&self) -> u32 {
0
}
/// The enable FIFOs (FEN) bit in the line control register
const fn enable_fifos_bit(&self) -> u32 {
4
}
/// The word length (WLEN) bits in the line control register
const fn word_length_bits(&self) -> [u32; 2] {
[6, 5]
}
}
impl Port {
/// The system's Run mode clock gating control (RCGC) register address containing this port
const fn run_mode_clock_gating_control_address(&self, board: &Board) -> *mut u32 {
match self {
Port::Zero => board.run_mode_clock_gating_control_1(),
Port::One => board.run_mode_clock_gating_control_1(),
Port::Two => board.run_mode_clock_gating_control_1(),
_ => todo!(),
}
}
/// The corresponding bit for this port in the system's Run mode clock gating control (RCGC) register
const fn run_mode_clock_gating_control_bit(&self) -> u32 {
match self {
Port::Zero => 0,
Port::One => 1,
Port::Two => 2,
_ => todo!(),
}
}
}
pub struct UsablePort {
port: Port,
}
impl UsablePort {
pub fn read_byte(&self, _receive_pin: &ReadablePin, blocking: bool) -> Option<u8> {
loop {
let [receive_fifo_empty] =
unsafe { memory::read_bits(self.port.flag(), &[self.port.receive_fifo_empty()]) };
if !receive_fifo_empty {
let byte = unsafe { memory::read(self.port.data()) } as u8;
return Some(byte);
}
if !blocking {
return None;
}
}
}
pub fn write_byte(
&mut self,
_transmit_pin: &mut WritablePin,
byte: u8,
blocking: bool,
) -> bool {
loop {
let [transmit_fifo_full] =
unsafe { memory::read_bits(self.port.flag(), &[self.port.transmit_fifo_full()]) };
if !transmit_fifo_full {
unsafe { memory::write(self.port.data(), byte as u32) };
return true;
}
if !blocking {
return false;
}
}
}
pub fn write_string(&mut self, _transmit_pin: &mut WritablePin, string: &str) {
for byte in string.bytes() {
self.write_byte(_transmit_pin, byte, true);
}
}
pub fn write_line(&mut self, _transmit_pin: &mut WritablePin, string: &str) {
self.write_string(_transmit_pin, string);
self.write_string(_transmit_pin, "\r\n");
}
pub fn read_line(
&mut self,
_transmit_pin: &mut WritablePin,
_receive_pin: &ReadablePin,
) -> String {
let mut s = String::new();
loop {
if let Some(c) = self.read_byte(_receive_pin, true) {
// Enter
if c == b'\r' {
self.write_string(_transmit_pin, "\r\n");
return s;
}
// Backspace
else if c == b'\x7F' {
if !s.is_empty() {
// https://stackoverflow.com/a/53976873
self.write_string(_transmit_pin, "\x1B[1D\x1B[1P");
s.pop();
}
} else {
self.write_byte(_transmit_pin, c, true);
s.push(c as char);
}
}
}
}
}
pub fn setup_port(
board: Board,
port: Port,
options: PortOptions,
no_ops: &dyn Fn(u32),
) -> UsablePort {
// Activate the associated peripheral
unsafe {
memory::set_bits(
port.run_mode_clock_gating_control_address(&board),
&[port.run_mode_clock_gating_control_bit()],
);
}
// Page 904: There must be a delay of 3 system clocks after the UART module clock is enabled before any UART module registers are accessed.
// But in actuality, 7 (not 3) no-ops are needed for some reason
no_ops(7);
// Disable this UART port while setting it up
unsafe {
memory::clear_bits(port.control(), &[port.enable_bit()]);
}
// Page 896: baud rate generation
// page 219
/// 16 MHz
const SYSTEM_OSC_CLOCK_SPEED: u32 = 16_000_000;
let system_clock = SYSTEM_OSC_CLOCK_SPEED;
// The UART generates an internal baud-rate reference clock at 8x or 16x the baud-rate (referred to
// as Baud8 and Baud16, depending on the setting of the HSE bit (bit 5) in UARTCTL)
// I ran out of time and don't check this bit
let clock_divider = 16;
let baud_rate_divisor = (system_clock as f32) / ((clock_divider * options.baud_rate) as f32);
let baud_rate_divisor_integer = baud_rate_divisor as u32;
let baud_rate_divisor_fraction = baud_rate_divisor - (baud_rate_divisor_integer as f32);
let baud_rate_divisor_fraction = ((baud_rate_divisor_fraction * 64.0) + 0.5) as u32;
unsafe {
memory::write(port.integer_baud_rate_divisor(), baud_rate_divisor_integer);
memory::write(
port.fractional_baud_rate_divisor(),
baud_rate_divisor_fraction,
);
}
// Set the word length
// Page 916 of data sheet
let word_length = match options.word_length {
WordLength::Five => [L, L],
WordLength::Six => [L, H],
WordLength::Seven => [H, L],
WordLength::Eight => [H, H],
};
unsafe {
memory::write_bits(port.line_control(), &port.word_length_bits(), word_length);
}
// Enable or disable FIFOs
let fifos = if options.fifos { [H] } else { [L] };
unsafe {
memory::write_bits(port.line_control(), &[port.enable_fifos_bit()], fifos);
}
// Enable this UART port
unsafe {
memory::set_bits(port.control(), &[port.enable_bit()]);
}
UsablePort { port }
}

15
src/lib/utils.rs Normal file
View File

@@ -0,0 +1,15 @@
use crate::Pin;
pub fn pins_to_bits<const N: usize>(pins: &[Pin; N]) -> [u32; N] {
pins.map(|pin| pin as u32)
}
pub fn reverse_array<const N: usize, T: Default + Copy>(array: [T; N]) -> [T; N] {
let mut result: [T; N] = [<T>::default(); N];
for (out_index, in_index) in (0..N).rev().enumerate() {
result[out_index] = array[in_index];
}
result
}

View File

@@ -1,59 +0,0 @@
#![no_std]
#![no_main]
use panic_halt as _;
use cortex_m_rt::entry;
use my_library::{Bit, Color, setup_board};
const H: bool = true;
const L: bool = false;
#[entry]
fn main() -> ! {
let board = setup_board();
let port_f = board.setup_port(Port::F);
let switches = port_f.setup_readable_pins([Bit::Zero, Bit::Four], PinSetup {
alternate_function: false,
analog: false,
pullup: true,
pctl: false,
});
let rgb_led = port_f.setup_writable_pins([Bit::One, Bit::Three, Bit::Two], PinSetup {
alternate_function: false,
analog: false,
pctl: false,
});
// Integrate PWM for arbitrary color support
let rgb_led_driver = rgb_led.driver();
// Maybe?
let every_5_seconds = board.time_trigger(5);
// Example of adding tasks
board.add_task(
some_kind_of_task,
10, // priority maybe?
every_5_seconds, // trigger every 5 seconds
);
loop {
match switches.read_all() {
[L, L] => rgb_led_driver.set_color(Color::Green),
[L, H] => rgb_led_driver.set_color(Color::Blue),
[H, L] => rgb_led_driver.set_color(Color::Red),
[H, H] => rgb_led_driver.set_color(Color::Black),
}
}
}
fn some_kind_of_task() {
// ...
}

View File

@@ -1,27 +1,38 @@
#![no_std] #![no_std]
#![no_main] #![no_main]
use panic_halt as _; // you can put a breakpoint on `rust_begin_unwind` to catch panics extern crate alloc;
use alloc::format;
use cortex_m_rt::entry; use cortex_m_rt::entry;
use driver_and_task_library::{ use driver_and_task_library::{
setup_board, Function, Pin, Port, PortOptions, ReadablePinOptions, WritablePinOptions, H, L, setup_board, Function, GPIOPort, Pin, Pull, ReadablePinOptions, UARTPort,
UARTPortOptions, WordLength, WritablePinOptions, H, L,
}; };
const WHITE: [bool; 3] = [H, H, H];
const BLACK: [bool; 3] = [L, L, L];
const RED: [bool; 3] = [H, L, L];
const _YELLOW: [bool; 3] = [H, H, L];
const _GREEN: [bool; 3] = [L, H, L];
const _CYAN: [bool; 3] = [L, H, H];
const BLUE: [bool; 3] = [L, L, H];
const _MAGENTA: [bool; 3] = [H, L, H];
static _RAINBOW: [[bool; 3]; 6] = [RED, _YELLOW, _GREEN, _CYAN, BLUE, _MAGENTA];
#[entry] #[entry]
fn main() -> ! { fn main() -> ! {
let board = setup_board(); let mut board = setup_board();
let port_f = board.setup_gpio_port(Port::F, PortOptions);
let mut port_f = board.setup_gpio_port(GPIOPort::F);
let switches = port_f.setup_readable_pins( let switches = port_f.setup_readable_pins(
[Pin::Zero, Pin::Four], [Pin::Zero, Pin::Four],
ReadablePinOptions { ReadablePinOptions {
function: Function::Digital, function: Function::Digital,
pull_up: Some(true), pull: Pull::Up,
}, },
); );
let [_sw1, _sw2] = switches.pins();
let mut rgb_led = port_f.setup_writable_pins( let mut rgb_led = port_f.setup_writable_pins(
[Pin::One, Pin::Three, Pin::Two], [Pin::One, Pin::Three, Pin::Two],
WritablePinOptions { WritablePinOptions {
@@ -29,24 +40,44 @@ fn main() -> ! {
}, },
); );
let white = [H, H, H]; let mut port_a = board.setup_gpio_port(GPIOPort::A);
let _black = [L, L, L]; let [uart_0_rx] = port_a
.setup_readable_pins(
[Pin::Zero],
ReadablePinOptions {
function: Function::UART,
pull: Pull::Neither,
},
).pins();
let [mut uart_0_tx] = port_a
.setup_writable_pins(
[Pin::One],
WritablePinOptions {
function: Function::UART,
},
).pins();
let mut uart_0 = board.setup_uart_port(
UARTPort::Zero,
UARTPortOptions {
baud_rate: 115_200,
fifos: true,
word_length: WordLength::Eight,
},
);
let red = [H, L, L]; uart_0.write_line(&mut uart_0_tx, "");
let yellow = [H, H, L]; uart_0.write_line(&mut uart_0_tx, "Program start!");
let green = [L, H, L];
let cyan = [L, H, H];
let blue = [L, L, H];
let magenta = [H, L, H];
let _rainbow = [red, yellow, green, cyan, blue, magenta];
loop { loop {
match switches.read_all() { match switches.read_all() {
[L, L] => rgb_led.write_all(white), [L, L] => rgb_led.write_all(WHITE),
[L, H] => rgb_led.write_all(blue), [L, H] => rgb_led.write_all(BLUE),
[H, L] => rgb_led.write_all(red), [H, L] => rgb_led.write_all(RED),
[H, H] => rgb_led.write_all(green), [H, H] => rgb_led.write_all(BLACK),
} }
uart_0.write_string(&mut uart_0_tx, "What's your name? ");
let input = uart_0.read_line(&mut uart_0_tx, &uart_0_rx);
uart_0.write_line(&mut uart_0_tx, &format!("Good afternoon {:?}!", &input));
} }
} }