X-Git-Url: http://git.code-monkey.de/?a=blobdiff_plain;f=src%2Fcommon%2Fmx25l.rs;h=2cc79f08f526b853c3a21a9c77965c09d8c57ff5;hb=821707231e866e5710d6d8a0d7a68a85015de062;hp=24f9c36cb5a4f91d346ea69cc1c1c8eb8f86a45a;hpb=b46a5f5c521e9dddb1a75faa247ce4aa8f64de0f;p=gps-watch.git diff --git a/src/common/mx25l.rs b/src/common/mx25l.rs index 24f9c36..2cc79f0 100644 --- a/src/common/mx25l.rs +++ b/src/common/mx25l.rs @@ -25,17 +25,29 @@ use gpio; use spi; use storage::Storage; +const SECTOR_SIZE: usize = 4096; +const PAGE_SIZE: usize = 256; + pub struct Mx25l { cs_gpio: u32, cs_gpio_pin: u32, } enum Command { + PP = 0x02, READ = 0x03, RDSR = 0x05, + WREN = 0x06, + SE = 0x20, RDID = 0x9f, } +pub enum Error { + UnalignedAddress = 1, +} + +const SR_WIP: u8 = 1 << 0; + impl Mx25l { pub fn new(cs_gpio: u32, cs_gpio_pin: u32) -> Mx25l { Mx25l { @@ -64,6 +76,65 @@ impl Mx25l { }) } + pub fn erase_sector(&self, address: usize) -> Result<(), Error> { + if (address & (SECTOR_SIZE - 1)) != 0 { + return Err(Error::UnalignedAddress); + } + + self.write_enable(); + + self.with_selected(|| { + spi::tx8(spi::SPI0, Command::SE as u8); + + spi::tx8(spi::SPI0, (address >> 16) as u8); + spi::tx8(spi::SPI0, (address >> 8) as u8); + spi::tx8(spi::SPI0, (address >> 0) as u8); + }); + + while self.write_in_progress() { + } + + Ok(()) + } + + pub fn program_page(&self, address: usize, buffer: &[u8; PAGE_SIZE]) + -> Result<(), Error> { + if (address & (PAGE_SIZE - 1)) != 0 { + return Err(Error::UnalignedAddress); + } + + if buffer.iter().all(|&b| b == 0xff) { + return Ok(()); + } + + self.with_selected(|| { + spi::tx8(spi::SPI0, Command::PP as u8); + + spi::tx8(spi::SPI0, (address >> 16) as u8); + spi::tx8(spi::SPI0, (address >> 8) as u8); + spi::tx8(spi::SPI0, (address >> 0) as u8); + + for &b in buffer.iter() { + spi::tx8(spi::SPI0, b); + } + }); + + while self.write_in_progress() { + } + + Ok(()) + } + + fn write_enable(&self) { + self.with_selected(|| { + spi::tx8(spi::SPI0, Command::WREN as u8); + }); + } + + fn write_in_progress(&self) -> bool { + (self.read_status() & SR_WIP) != 0 + } + fn with_selected(&self, func: F) -> T where F: FnOnce() -> T {