diff --git a/include/sta/drivers/w25qxx.hpp b/include/sta/drivers/w25qxx.hpp index 9d93c20..7031b7e 100644 --- a/include/sta/drivers/w25qxx.hpp +++ b/include/sta/drivers/w25qxx.hpp @@ -2,6 +2,8 @@ #define STA_SENSORS_W25Q128_HPP #include +#include + #include #include @@ -60,12 +62,14 @@ namespace sta using DelayUsFunc = void (*)(uint32_t); /** - * @brief Construct a new W25Qxx object + * @brief Driver class for the W25QXX flash storage series. * - * @param device - * @param addrMode + * @param device A SPI device handle from sta-core. + * @param delay A microsecond delay function. + * @param addrMode Choose between 24 Bit and 32 Bit addressing. + * @param mutex A mutex for thread safety if the flash chip is used by multiple threads. Defaults to a always free mutex. */ - W25Qxx(SPIDevice * device, DelayUsFunc delay, AddressMode addrMode = AddressMode::_24BIT); + W25Qxx(SPIDevice * device, DelayUsFunc delay, AddressMode addrMode = AddressMode::_24BIT, Mutex * mutex = Mutex::ALWAYS_FREE); /** * @brief Initialize the flash chip. @@ -318,6 +322,7 @@ namespace sta private: SPIDevice * device_; DelayUsFunc delay_; + Mutex * mutex_; ChipState state_; AddressMode addrMode_; }; diff --git a/include/sta/utils/logger.tpp b/include/sta/utils/logger.tpp index 7078895..6816ff9 100644 --- a/include/sta/utils/logger.tpp +++ b/include/sta/utils/logger.tpp @@ -33,6 +33,12 @@ namespace sta // If the written data exceeds the remaining bytes in the page. if (ptr_ + length >= W25QXX_PAGE_SIZE) { + // If the segment is full, stop writing data to it. + if (address_ / W25QXX_SECTOR_SIZE == end_) + { + return; + } + std::memcpy(buffer_ + ptr_, bytes, remaining); flash_->pageProgram(address_, buffer_, W25QXX_PAGE_SIZE); @@ -43,15 +49,9 @@ namespace sta address_ += W25QXX_PAGE_SIZE; - // If a new sector was started, erase the new sector. + // If a new sector has to be started, erase the new sector. if (address_ % W25QXX_SECTOR_SIZE == 0) { - // If the size of the logger segment was exceeded, restart at the first sector. - if (address_ / W25QXX_SECTOR_SIZE == end_) - { - address_ = start_ * W25QXX_SECTOR_SIZE; - } - flash_->sectorErase(address_); } } @@ -81,7 +81,7 @@ namespace sta template size_t Logger::remaining() { - return (end_ * W25QXX_SECTOR_SIZE - address_) / sizeof(T); + return (end_ * W25QXX_SECTOR_SIZE - address_) / sizeof(T); } template diff --git a/src/w25qxx.cpp b/src/w25qxx.cpp index 3351bbe..f8654d2 100644 --- a/src/w25qxx.cpp +++ b/src/w25qxx.cpp @@ -9,13 +9,15 @@ namespace sta { - W25Qxx::W25Qxx(SPIDevice * device, DelayUsFunc delay, AddressMode addrMode /* = AddressMode::_24BIT */) + W25Qxx::W25Qxx(SPIDevice * device, DelayUsFunc delay, AddressMode addrMode /* = AddressMode::_24BIT */, Mutex * mutex /* = Mutex::ALWAYS_FREE */) : device_{device}, delay_{delay}, + mutex_{mutex}, state_{ChipState::POWERED_DOWN}, addrMode_{addrMode} { STA_ASSERT(device != nullptr); + STA_ASSERT(mutex != nullptr); } uint8_t W25Qxx::init()