From 57715ad5c0c53cb4f8fc2de55c040f9c10944be2 Mon Sep 17 00:00:00 2001 From: Felix Rusu Date: Tue, 29 Jul 2014 17:10:06 -0400 Subject: [PATCH] Unintrusive SPI transactions & misc fixes --- SPIFlash.cpp | 38 ++++++++++++++++++-------------------- SPIFlash.h | 2 ++ 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/SPIFlash.cpp b/SPIFlash.cpp index e1b8bc1..2817242 100644 --- a/SPIFlash.cpp +++ b/SPIFlash.cpp @@ -32,38 +32,36 @@ SPIFlash::SPIFlash(uint8_t slaveSelectPin, uint16_t jedecID) { /// Select the flash chip void SPIFlash::select() { -#ifdef SPI_HAS_TRANSACTION - SPI.beginTransaction(SPISettings(33000000, MSBFIRST, SPI_MODE0)); -#else noInterrupts(); -#endif + //save current SPI settings + _SPCR = SPCR; + _SPSR = SPSR; + //set FLASH chip SPI settings + SPI.setDataMode(SPI_MODE0); + SPI.setBitOrder(MSBFIRST); + SPI.setClockDivider(SPI_CLOCK_DIV4); //decided to slow down from DIV2 after SPI stalling in some instances, especially visible on mega1284p when RFM69 and FLASH chip both present + SPI.begin(); digitalWrite(_slaveSelectPin, LOW); } /// UNselect the flash chip void SPIFlash::unselect() { digitalWrite(_slaveSelectPin, HIGH); -#ifdef SPI_HAS_TRANSACTION - SPI.endTransaction(); -#else + //restore SPI settings to what they were before talking to the FLASH chip + SPCR = _SPCR; + SPSR = _SPSR; interrupts(); -#endif } /// setup SPI, read device ID etc... boolean SPIFlash::initialize() { + _SPCR = SPCR; + _SPSR = SPSR; pinMode(_slaveSelectPin, OUTPUT); -#ifdef SPI_HAS_TRANSACTION - digitalWrite(_slaveSelectPin, HIGH); -#else unselect(); - SPI.setDataMode(SPI_MODE0); - SPI.setBitOrder(MSBFIRST); - SPI.setClockDivider(SPI_CLOCK_DIV2); //max speed, except on Due which can run at system clock speed -#endif - SPI.begin(); - + wakeup(); + if (_jedecID == 0 || readDeviceId() == _jedecID) { command(SPIFLASH_STATUSWRITE, true); // Write Status Register SPI.transfer(0); // Global Unprotect @@ -228,16 +226,16 @@ void SPIFlash::blockErase32K(long addr) { } void SPIFlash::sleep() { - command(SPIFLASH_SLEEP); // Block Erase + command(SPIFLASH_SLEEP); unselect(); } void SPIFlash::wakeup() { - command(SPIFLASH_WAKE); // Block Erase + command(SPIFLASH_WAKE); unselect(); } /// cleanup void SPIFlash::end() { SPI.end(); -} +} \ No newline at end of file diff --git a/SPIFlash.h b/SPIFlash.h index 20863c1..f0c071a 100644 --- a/SPIFlash.h +++ b/SPIFlash.h @@ -93,6 +93,8 @@ protected: void unselect(); byte _slaveSelectPin; uint16_t _jedecID; + byte _SPCR; + byte _SPSR; }; #endif \ No newline at end of file