Implement basic eeprom wrapper for integral and float variables

This commit is contained in:
BlackMark 2020-04-07 05:02:38 +02:00
parent 1a99dbfbc5
commit 4f8828dbee

80
eeprom.hpp Normal file
View File

@ -0,0 +1,80 @@
#pragma once
#include <avr/eeprom.h>
#include "../type/type.hpp"
#define EEVAR(type, name) \
type EEMEM __##name; \
constexpr auto name = &__##name
template <typename T, T *Address, bool Update = false>
class Eeprom {
public:
operator T() const
{
if constexpr (type::is_integral_v<T>) {
if constexpr (sizeof(T) == 1) {
return eeprom_read_byte(reinterpret_cast<const uint8_t *>(Address));
} else if constexpr (sizeof(T) == 2) {
return eeprom_read_word(reinterpret_cast<const uint16_t *>(Address));
} else if constexpr (sizeof(T) == 4) {
return eeprom_read_dword(reinterpret_cast<const uint32_t *>(Address));
} else if constexpr (sizeof(T) == 8) {
T number;
eeprom_read_block(&number, Address, sizeof(T));
return number;
}
} else if constexpr (type::is_floating_point_v<T>) {
static_assert(sizeof(T) == 4, "Only floats of size 4 are supported");
return eeprom_read_float(reinterpret_cast<const float *>(Address));
}
}
Eeprom &operator=(const T &other)
{
if constexpr (type::is_integral_v<T>) {
if constexpr (sizeof(T) == 1) {
if constexpr (Update) {
eeprom_update_byte(reinterpret_cast<uint8_t *>(Address), other);
} else {
eeprom_write_byte(reinterpret_cast<uint8_t *>(Address), other);
}
} else if constexpr (sizeof(T) == 2) {
if constexpr (Update) {
eeprom_update_word(reinterpret_cast<uint16_t *>(Address), other);
} else {
eeprom_write_word(reinterpret_cast<uint16_t *>(Address), other);
}
} else if constexpr (sizeof(T) == 4) {
if constexpr (Update) {
eeprom_update_dword(reinterpret_cast<uint32_t *>(Address), other);
} else {
eeprom_write_dword(reinterpret_cast<uint32_t *>(Address), other);
}
} else if constexpr (sizeof(T) == 8) {
if constexpr (Update) {
eeprom_update_block(&other, Address, sizeof(T));
} else {
eeprom_write_block(&other, Address, sizeof(T));
}
}
} else if constexpr (type::is_floating_point_v<T>) {
static_assert(sizeof(T) == 4, "Only floats of size 4 are supported");
if constexpr (Update) {
eeprom_update_float(reinterpret_cast<float *>(Address), other);
} else {
eeprom_write_float(reinterpret_cast<float *>(Address), other);
}
}
return *this;
}
private:
static_assert(type::is_integral_v<T> || type::is_floating_point_v<T>,
"Only integral and floating point types are supported");
static_assert(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8,
"Only sizes 1, 2, 4, and 8 are supported");
};