Successful reading and writing

This commit is contained in:
dario 2024-06-03 22:23:00 +02:00
parent fde868c9db
commit 9dd2a8da9c
2 changed files with 25 additions and 11 deletions

View File

@ -13,11 +13,11 @@ namespace sta
{
public:
/**
* @brief Construct a new Logger object
* @brief Constructs a logger object which manages reading and writing data to a segment of a flash chip.
*
* @param flash The flash chip to use for logging.
* @param startSector The index of the start sector (4096 bytes).
* @param endAddr The index of the end sector (4096 bytes).
* @param startSector The index of the start sector (1 LSB = 4096 bytes).
* @param endSector The index of the end sector (1 LSB = 4096 bytes).
*/
Logger(W25Qxx * flash, uint32_t startSector, uint32_t endSector);
@ -62,7 +62,7 @@ namespace sta
* @param idx The index of the segement.
* @return const T& The read data value.
*/
const T& operator[](std::size_t idx);
T operator[](std::size_t idx);
private:
W25Qxx * flash_;
uint32_t start_;

View File

@ -23,11 +23,13 @@ namespace sta
void Logger<T>::write(T data)
{
uint8_t * bytes = (uint8_t*)(&data);
uint8_t length = sizeof(data);
uint8_t length = sizeof(T);
// Bytes remaining until the page is full.
uint8_t remaining = W25QXX_PAGE_SIZE - ptr_;
STA_DEBUG_PRINTF("Writing at address %d\n", address_+ptr_);
// If the written data exceeds the remaining bytes in the page.
if (ptr_ + length >= W25QXX_PAGE_SIZE)
{
@ -37,6 +39,7 @@ namespace sta
bytes += remaining;
length -= remaining;
ptr_ = 0;
STA_DEBUG_PRINTLN("New PAGE!");
address_ += W25QXX_PAGE_SIZE;
@ -54,6 +57,7 @@ namespace sta
}
std::memcpy(buffer_ + ptr_, bytes, length);
ptr_ += length;
}
template <typename T>
@ -62,9 +66,9 @@ namespace sta
address_ = start_ * W25QXX_SECTOR_SIZE;
ptr_ = 0;
for (uint32_t i = 0; i < end_ - start_; i++)
for (uint32_t i = start_; i < end_; i++)
{
flash_->sectorErase((start_ + i) * W25QXX_SECTOR_SIZE);
flash_->sectorErase(i * W25QXX_SECTOR_SIZE);
}
}
@ -87,13 +91,23 @@ namespace sta
}
template <typename T>
const T& Logger<T>::operator[](std::size_t idx)
T Logger<T>::operator[](std::size_t idx)
{
uint32_t address = start_ * W25QXX_SECTOR_SIZE + idx * sizeof(T);
uint8_t buffer[sizeof(T)];
flash_->readData(address, buffer, sizeof(T));
return *((T*)buffer);
// If the requested element is in the cache, read it from there.
if (address / W25QXX_PAGE_SIZE == address_ / W25QXX_PAGE_SIZE)
{
STA_DEBUG_PRINTLN("Reading data from buffer!");
uint8_t * ptr = buffer_ + address % W25QXX_PAGE_SIZE;
return *reinterpret_cast<T*>(ptr);
}
else
{
uint8_t buffer[sizeof(T)];
flash_->readData(address, buffer, sizeof(T));
return *reinterpret_cast<T*>(buffer);
}
}
} // namespace sta