AT25040B Driver 0.1.0
API reference
Loading...
Searching...
No Matches
at25040b.hpp
Go to the documentation of this file.
1
13#ifndef AT25040B_HPP
14#define AT25040B_HPP
15
16#include <algorithm>
17#include <array>
18#include <concepts>
19#include <cstddef>
20#include <cstdint>
21#include <span>
22#include <type_traits>
23
24#include "at25040b_detail.hpp"
27#include "at25040b_types.hpp"
28#include "at25040b_version.h"
29
30namespace at25040b {
31
32namespace detail {
33
34// Optional hooks: a `Declares*` concept only tests the name, the `Has*` concept the exact
35// signature, `noexcept` and the result type; the driver rejects a hook that is declared but does
36// not match (KB-CPP20-007).
37
39template <typename Port>
40concept DeclaresGpioSet =
41 requires(Port& port) { port.GpioSet(CtrlPin::WriteProtect, GpioSignal::ACTIVE); };
42
44template <typename Port>
45concept HasGpioSet =
46 requires { ExactHook<Port, bool(CtrlPin, GpioSignal) noexcept>::Take(&Port::GpioSet); };
47
49template <typename Port>
50concept DeclaresDelayUs = requires(Port& port) { port.DelayUs(1U); };
51
54template <typename Port>
55concept HasDelayUs = requires { ExactHook<Port, void(uint32_t) noexcept>::Take(&Port::DelayUs); };
56
58template <typename Port>
59concept DeclaresLog = requires(Port& port) { port.Log(LogLevel::Info, ""); };
60
62template <typename Port>
63concept HasLog =
64 requires { ExactHook<Port, void(LogLevel, const char*) noexcept>::Take(&Port::Log); };
65
68template <typename Port>
69void DelayUs(Port& port, uint32_t us) noexcept {
70 if constexpr (HasDelayUs<Port>) {
71 port.DelayUs(us);
72 } else {
73 static_assert(kAlwaysFalse<Port>,
74 "at25040b: the port must implement `void DelayUs(uint32_t us) noexcept`");
75 }
76}
77
79template <typename Port>
80void Log([[maybe_unused]] Port& port, [[maybe_unused]] LogLevel level,
81 [[maybe_unused]] const char* message) noexcept {
82 if constexpr (HasLog<Port>) {
83 port.Log(level, message);
84 }
85}
86
89template <typename Op>
90concept WriteAccessOp =
91 std::invocable<Op&> && std::same_as<std::invoke_result_t<Op&>, Result<void>>;
92
94constexpr BlockProtect DecodeBlockProtect(uint8_t status) noexcept {
95 return static_cast<BlockProtect>(reg::StatusBp::Extract(status));
96}
97
99constexpr uint8_t EncodeBlockProtect(BlockProtect level) noexcept {
100 return reg::StatusBp::Insert(0_u8, static_cast<uint32_t>(ToUnderlying(level)));
101}
102
106constexpr Error ToggleError(uint8_t got, uint8_t expected) noexcept {
107 const bool only_wen =
108 reg::IsIdleStatus(got) &&
109 ((static_cast<uint32_t>(got) ^ static_cast<uint32_t>(expected)) == reg::kStatusWen);
110 return only_wen ? Error::DeviceIdMismatch : Error::BusNoise;
111}
112
113static_assert((DecodeBlockProtect(0x0C_u8) == BlockProtect::All) &&
114 (DecodeBlockProtect(0x06_u8) == BlockProtect::UpperQuarter));
115static_assert((EncodeBlockProtect(BlockProtect::UpperHalf) == reg::kStatusBp1) &&
116 (DecodeBlockProtect(EncodeBlockProtect(BlockProtect::UpperQuarter)) ==
118static_assert((ToggleError(0x00_u8, reg::kStatusWen) == Error::DeviceIdMismatch) &&
119 (ToggleError(0x04_u8, reg::kStatusWen) == Error::BusNoise) &&
120 (ToggleError(reg::kStatusBusyByte, 0x00_u8) == Error::BusNoise));
121
122} // namespace detail
123
130// clang-format off: the hook table below must keep one row per line.
156// clang-format on
157template <SpiPort Port>
158class AT25040B {
159 static_assert(!detail::DeclaresGpioSet<Port> || detail::HasGpioSet<Port>,
160 "at25040b: the optional GpioSet hook must be `bool GpioSet(CtrlPin, GpioSignal) "
161 "noexcept`, so that a failed pin write is reported");
162 static_assert(
163 !detail::DeclaresDelayUs<Port> || detail::HasDelayUs<Port>,
164 "at25040b: the DelayUs hook must be `void DelayUs(uint32_t us) noexcept`, so that no "
165 "wait is truncated");
166 static_assert(!detail::DeclaresLog<Port> || detail::HasLog<Port>,
167 "at25040b: the optional Log hook must be `void Log(LogLevel, const char* message) "
168 "noexcept`");
169
170public:
176 explicit AT25040B(Port& port, const Config& config = {}) noexcept : bus_(port), config_(config) {}
177
179 AT25040B(const AT25040B&) = delete;
181 AT25040B& operator=(const AT25040B&) = delete;
182
185
203
205 [[nodiscard]] bool IsInitialized() const noexcept {
206 return initialized_;
207 }
208
220
224
231 Result<void> ApplyConfig(const Config& config) noexcept;
232
234 [[nodiscard]] const Config& GetConfig() const& noexcept {
235 return config_;
236 }
238 void GetConfig() const&& = delete;
239
241 [[nodiscard]] std::size_t GetCapacityBytes() const noexcept {
242 return CapacityBytes(config_.variant);
243 }
244
248
268 Result<void> Read(uint16_t address, std::span<uint8_t> out,
269 Verify verify = Verify::None) noexcept;
270
298 Result<void> Write(uint16_t address, std::span<const uint8_t> data,
299 Verify verify = Verify::None) noexcept;
300
304
312
319
333
340 [[nodiscard]] uint8_t GetLastStatusByte() const noexcept {
341 return last_status_;
342 }
343
355
357
358private:
359 Result<void> initialize() noexcept;
360 Result<void> checkWriteEnableToggle(uint8_t idle) noexcept;
361 Result<void> checkStableHead() noexcept;
362 Result<void> expectAfter(uint8_t opcode, uint8_t expected) noexcept;
363 Result<uint8_t> readStatusByte() noexcept;
364 Result<uint8_t> waitIdle(bool started) noexcept;
365 Result<void> readRange(uint16_t address, std::span<uint8_t> out, Verify verify) noexcept;
366 Result<void> writeRange(uint16_t address, std::span<const uint8_t> data, Verify verify) noexcept;
367 Result<void> writePage(uint16_t address, std::span<const uint8_t> data, Verify verify) noexcept;
368 Result<void> writeStatusRegister(BlockProtect level) noexcept;
369 Result<void> enableWrite() noexcept;
370 Result<uint8_t> finishWriteCycle() noexcept;
371 void disableWrite() noexcept;
372 Result<void> releaseWriteProtect() noexcept;
373 Result<void> parkWriteProtect() noexcept;
374 template <detail::WriteAccessOp Op>
375 Result<void> withWriteAccess(Op op) noexcept;
376 [[nodiscard]] bool inRange(uint16_t address, std::size_t length) const noexcept;
377 Result<void> fail(Error error, const char* message) noexcept;
378
379 detail::EepromBus<Port> bus_;
380 Config config_{};
381 uint8_t last_status_{reg::kStatusBusyByte};
382 bool initialized_{false};
383};
384
387} // namespace at25040b
388
389// codeql::misra_deviation_next_line(MD-CPP-009)
390#include "../src/at25040b.ipp" // IWYU pragma: export
391
392#endif // AT25040B_HPP
Compile-time helpers of the AT25040B driver: exact hook matching, typed register fields and enumerati...
Instruction opcodes and status register bits of the AT25010B, AT25020B and AT25040B.
The SPI port of the AT25040B driver: the bus requirements, the CRTP base, its pin enums,...
Public types of the AT25040B driver: errors, Result<T>, variants, block protection and configuration.
Driver for one AT25010B, AT25020B or AT25040B on a platform port.
Definition at25040b.hpp:158
AT25040B(const AT25040B &)=delete
One driver object per chip.
Result< void > ApplyConfig(const Config &config) noexcept
Replace the configuration. Never any I/O: the chip has no setting to write. The variant and the check...
Result< void > Deinitialize() noexcept
Leave the chip safe and mark the driver uninitialised: WRDI, then WP parked.
Result< void > Write(uint16_t address, std::span< const uint8_t > data, Verify verify=Verify::None) noexcept
Write data from address: one WRITE and one write cycle per 8-byte page.
Result< uint8_t > ReadRawStatus() noexcept
Read the status register once: one RDSR transfer, no wait, no retry, no decoding and no check of the ...
Result< void > SetBlockProtection(BlockProtect level) noexcept
Set BP1:BP0 (WRSR, section 6, "Write Status Register").
Result< void > EnsureInitialized() noexcept
Check that an AT25xxxB answers, once: the only way to initialise the driver.
const Config & GetConfig() const &noexcept
Definition at25040b.hpp:234
void GetConfig() const &&=delete
No reference into a temporary driver: it would dangle.
Result< Status > ReadStatus() noexcept
One status read (RDSR), decoded. Does not wait: during a write cycle it returns busy = true.
Result< BlockProtect > GetBlockProtection() noexcept
The block protection level, from the status (Table 6-4). Waits for a running write cycle first.
std::size_t GetCapacityBytes() const noexcept
Definition at25040b.hpp:241
Result< void > Read(uint16_t address, std::span< uint8_t > out, Verify verify=Verify::None) noexcept
Read out.size() bytes from address (sequential READ, section 6, "Read Sequence").
uint8_t GetLastStatusByte() const noexcept
The last status byte the driver read, by any call, for logs: 0xFF before the first....
Definition at25040b.hpp:340
AT25040B & operator=(const AT25040B &)=delete
One driver object per chip.
AT25040B(Port &port, const Config &config={}) noexcept
Bind the driver to a port and store the configuration. No I/O, cannot fail.
Definition at25040b.hpp:176
bool IsInitialized() const noexcept
Definition at25040b.hpp:205
constexpr std::size_t CapacityBytes(Variant variant) noexcept
Array size of a variant.
Definition at25040b_types.hpp:287
Error
Why a call failed. Every call of the driver returns one of these in its Result.
Definition at25040b_types.hpp:36
Verify
Extra verification for one Read() or Write() call, chosen per call.
Definition at25040b_types.hpp:226
LogLevel
Severity passed to the optional Log() hook.
Definition at25040b_types.hpp:186
BlockProtect
Block write protection level, BP1:BP0 in the status register (Table 6-4).
Definition at25040b_types.hpp:212
@ None
Each chunk read once; no page read back. The default.
@ Info
Lifecycle events: initialised.
@ UpperQuarter
01: the top quarter is read-only (0x180 to 0x1FF on the AT25040B).
@ All
11: the whole array is read-only.
@ UpperHalf
10: the top half is read-only (0x100 to 0x1FF on the AT25040B).
constexpr bool IsIdleStatus(uint8_t status) noexcept
True for a status byte an idle chip can return: bits 7 to 4 clear and RDY clear (Table 6-3)....
Definition at25040b_registers.hpp:62
constexpr uint8_t kStatusBp1
BP1: block protection, high bit.
Definition at25040b_registers.hpp:44
constexpr uint8_t kStatusWen
WEN: 1 when the write enable latch is set.
Definition at25040b_registers.hpp:42
constexpr uint8_t kStatusBusyByte
Every bit reads 1 during a write cycle.
Definition at25040b_registers.hpp:48
The AT25040B driver: everything it declares lives here; internals in detail.
Definition at25040b.hpp:30
CtrlPin
Control pins the port may drive through the optional GpioSet() hook.
Definition at25040b_spi_interface.hpp:143
@ WriteProtect
WP, active low on the package pin. ACTIVE (pin low) blocks every write.
GpioSignal
Logical level of a control pin; the port maps it to the physical polarity.
Definition at25040b_spi_interface.hpp:148
@ ACTIVE
The pin function is asserted (WP: pin low, writes blocked).
What the driver is told about the board. The chip itself has nothing to configure: its only setting,...
Definition at25040b_types.hpp:361
Variant variant
Definition at25040b_types.hpp:362
The value of a call, or why there is none.
Definition at25040b_types.hpp:126