X-Git-Url: http://git.code-monkey.de/?a=blobdiff_plain;f=src%2Fcommon%2Fspi.rs;fp=src%2Fcommon%2Fspi.rs;h=1dcaa22280e5b669c35fb7bae3f2b80682d17957;hb=aae0fbad25fcb502bf425eac753d83c0a6fce1cd;hp=0000000000000000000000000000000000000000;hpb=9a8a254d92e81cb9030dce2ff7055160ea042246;p=gps-watch.git diff --git a/src/common/spi.rs b/src/common/spi.rs new file mode 100644 index 0000000..1dcaa22 --- /dev/null +++ b/src/common/spi.rs @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2020 Tilman Sauerbeck (tilman at code-monkey de) + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +use register; + +type Reg8 = register::Register; +type Reg32 = register::Register; + +const SPI_BASE: u32 = 0x40076000; + +pub const SPI0: u32 = SPI_BASE + 0x0000; +pub const SPI1: u32 = SPI_BASE + 0x1000; + +const SIM_SCGC4: u32 = 0x40048034; + +const SIM_SCGC4_SPI0: u32 = 1 << 22; + +const SPI_S : u32 = 0x00; +const SPI_BR: u32 = 0x01; +const SPI_C2: u32 = 0x02; +const SPI_C1: u32 = 0x03; +const SPI_DL: u32 = 0x06; + +const SPI_S_SPTEF: u8 = 1 << 5; +const SPI_S_SPRF : u8 = 1 << 7; + +const SPI_C1_MSTR: u8 = 1 << 4; +const SPI_C1_SPE: u8 = 1 << 6; + +pub fn configure(spi: u32) { + { + let mut scgc4 = Reg32::new(SIM_SCGC4); + + if spi == SPI0 { + scgc4.modify(|v| v | SIM_SCGC4_SPI0); + } + } + + Reg8::new(spi + SPI_C1).write(SPI_C1_MSTR); + Reg8::new(spi + SPI_C2).write(0x0); + Reg8::new(spi + SPI_BR).write(0x0); + Reg8::new(spi + SPI_C1).modify(|v| v | SPI_C1_SPE); +} + +pub fn tx8(spi: u32, v: u8) -> u8 { + let s = Reg8::new(spi + SPI_S); + + // Wait for transmit buffer to become empty. + while (s.read() & SPI_S_SPTEF) == 0 { + } + + let mut dl = Reg8::new(spi + SPI_DL); + dl.write(v); + + // Wait for receive buffer to become full. + while (s.read() & SPI_S_SPRF) == 0 { + } + + dl.read() +}