22#include "as5047u_version.h"
33template <
typename Port>
34concept DeclaresDelayUs =
requires(Port& port) { port.DelayUs(1U); };
38template <
typename Port>
39concept HasDelayUs =
requires { ExactHook<Port, void(uint32_t)
noexcept>::Take(&Port::DelayUs); };
42template <
typename Port>
43concept DeclaresLog =
requires(Port& port) { port.Log(
LogLevel::Info,
""); };
46template <
typename Port>
48 requires { ExactHook<Port, void(
LogLevel,
const char*)
noexcept>::Take(&Port::Log); };
53template <
typename Port>
54void DelayUs(Port& port, uint32_t us)
noexcept {
55 if constexpr (HasDelayUs<Port>) {
58 static_assert(kAlwaysFalse<Port>,
59 "as5047u: the port must implement `void DelayUs(uint32_t us) noexcept`");
64template <
typename Port>
65void Log(Port& port, [[maybe_unused]]
LogLevel level,
66 [[maybe_unused]]
const char* message)
noexcept {
67 if constexpr (HasLog<Port>) {
68 port.Log(level, message);
75constexpr int16_t SignExtend14(uint16_t raw)
noexcept {
76 const auto v =
static_cast<int32_t
>(
static_cast<uint32_t
>(raw) &
reg::kDataMask);
77 return static_cast<int16_t
>(((
static_cast<uint32_t
>(v) & 0x2000U) != 0U) ? (v - 0x4000) : v);
79static_assert((SignExtend14(0x1FFF_u16) == 8191) && (SignExtend14(0x2000_u16) == -8192) &&
80 (SignExtend14(0x3FFF_u16) == -1));
83constexpr ErrorFlags DecodeErrorFlags(uint16_t raw)
noexcept {
84 const auto v =
static_cast<uint32_t
>(raw);
101constexpr Diagnostics DecodeDiagnostics(uint16_t raw)
noexcept {
102 const auto v =
static_cast<uint32_t
>(raw);
118[[nodiscard]]
constexpr Error ClassifyErrorFlags(uint16_t errfl)
noexcept {
119 const auto v =
static_cast<uint32_t
>(errfl);
136constexpr bool IsVerify(
Verify v)
noexcept {
137 return IsEnumerator(v);
146constexpr uint32_t BitIf(
bool on, uint16_t bit)
noexcept {
147 return on ?
static_cast<uint32_t
>(bit) : 0U;
158 r[At(NvIndex::Disable)] =
static_cast<uint16_t
>(
162 r[At(NvIndex::Zposl)] =
163 static_cast<uint16_t
>((
static_cast<uint32_t
>(now[At(NvIndex::Zposl)]) &
reg::kZposlDiaBits) |
165 r[At(NvIndex::Settings1)] =
static_cast<uint16_t
>(
166 (
static_cast<uint32_t
>(now[At(NvIndex::Settings1)]) &
reg::kS1DiaBits) |
169 r[At(NvIndex::Settings2)] =
static_cast<uint16_t
>(
177 r[At(NvIndex::Settings3)] =
static_cast<uint16_t
>(
190 const auto disable =
static_cast<uint32_t
>(r[At(NvIndex::Disable)]);
197 const auto s1 =
static_cast<uint32_t
>(r[At(NvIndex::Settings1)]);
200 const auto s2 =
static_cast<uint32_t
>(r[At(NvIndex::Settings2)]);
209 const auto s3 =
static_cast<uint32_t
>(r[At(NvIndex::Settings3)]);
220constexpr Config RoundTripSample()
noexcept {
246static_assert(DecodeSettings(EncodeSettings(RoundTripSample(), {}),
Config{}) == RoundTripSample());
247static_assert(DecodeSettings(EncodeSettings(RoundTripSample(),
249 Config{}) == RoundTripSample());
300template <SpiPort Port>
302 static_assert(!detail::DeclaresDelayUs<Port> || detail::HasDelayUs<Port>,
303 "as5047u: the DelayUs hook must be `void DelayUs(uint32_t us) noexcept`, so that "
304 "no wait is truncated");
305 static_assert(!detail::DeclaresLog<Port> || detail::HasLog<Port>,
306 "as5047u: the optional Log hook must be `void Log(LogLevel, const char* message) "
315 explicit AS5047U(Port& port,
const Config& config = {})
noexcept : bus_(port), config_(config) {}
501 return detail::DecodeErrorFlags(last_errfl_);
525 ErrorFlags f = detail::DecodeErrorFlags(latched_errfl_);
541 return bus_.LastReply();
602 Result<
void> initialize() noexcept;
603 Result<
void> applyConfig(const
Config& config,
bool verify) noexcept;
604 Result<
void> waitReady() noexcept;
605 Error classifyDia() noexcept;
606 Result<
void> writeSettings(const
Config& config,
bool verify) noexcept;
607 Result<uint16_t> readRaw(uint16_t address) noexcept;
608 Result<uint16_t> readChecked(uint16_t address) noexcept;
609 Result<uint16_t> readMeasurement(uint16_t address) noexcept;
610 Result<uint16_t> measure(uint16_t address) noexcept;
611 Result<uint16_t> readErrfl() noexcept;
612 Result<
void> writeRaw(uint16_t address, uint16_t value,
bool verify) noexcept;
613 Result<
void> resolveFlags(
bool measurement) noexcept;
614 Result<
void> checkReset() noexcept;
615 void flagsLost() noexcept;
616 void rereadAfterFailedWrite(const
Config& base,
bool settings) noexcept;
622 Result<
void> fail(
Error error, const
char* message) noexcept;
626 template <typename T>
628 if (!reset_hint_ && !lost_hint_) {
639 const auto c = checkReset();
649 [[nodiscard]]
FrameFormat writeFormat() const noexcept {
653 detail::FrameBus<Port> bus_;
655 uint16_t last_errfl_{0};
656 uint16_t latched_errfl_{0};
659 bool flags_lost_{
false};
661 bool reset_hint_{
false};
664 bool lost_hint_{
false};
665 bool initialized_{
false};
673#include "../src/as5047u.ipp"
Compile-time helpers of the AS5047U driver: exact hook matching, the dependent-false helper,...
AS5047U register map: addresses, field masks and shifts.
The SPI port of the AS5047U driver: the CRTP base, the SpiPort concept and the frame layer.
Public types of the AS5047U driver: errors, Result<T>, configuration, decoded registers.
Driver for one AS5047U on a platform port.
Definition as5047u.hpp:301
Result< void > Deinitialize() noexcept
Mark the driver uninitialised; the next EnsureInitialized() starts the chip again (the recovery after...
Result< void > SetDirection(Direction direction, Verify verify=Verify::None) noexcept
Set the direction in which the angle increases.
Result< void > ApplyConfig(const Config &config, Verify verify=Verify::None) noexcept
Change the configuration.
Result< float > ReadAngleRadians() noexcept
Result< void > SetZeroPosition(uint16_t counts, Verify verify=Verify::None) noexcept
Set the zero position (ZPOSM, ZPOSL).
ErrorFlags GetLastErrorFlags() const noexcept
Definition as5047u.hpp:500
ErrorFlags GetLatchedErrorFlags() const noexcept
Every ERRFL flag the driver has read since the last ClearLatchedErrorFlags(). No I/O.
Definition as5047u.hpp:524
const Config & GetConfig() const &noexcept
Definition as5047u.hpp:391
Result< Diagnostics > ReadDiagnostics() noexcept
AS5047U & operator=(const AS5047U &)=delete
One driver object per chip.
Result< NonVolatileRegisters > ReadNonVolatile() noexcept
Result< float > ReadVelocityRpm() noexcept
Result< int16_t > ReadVelocityCounts() noexcept
Result< void > CheckForReset() noexcept
Check that the chip still holds the settings the driver wrote: the cheap test for a reset of the chip...
Result< void > ProgramOtp(OtpBurnConfirm confirm, OtpReport &report) noexcept
Burn the current settings into the OTP. This cannot be undone.
Result< float > ReadAngleDegrees() noexcept
uint16_t GetLastReply() const noexcept
Definition as5047u.hpp:540
void ClearLatchedErrorFlags() noexcept
Empty the latch of GetLatchedErrorFlags(), flags_lost included. No I/O.
Definition as5047u.hpp:531
AS5047U(Port &port, const Config &config={}) noexcept
Bind the driver to a port and store the configuration. No I/O, cannot fail.
Definition as5047u.hpp:315
Result< void > WriteRegister(uint16_t address, uint16_t value, Verify verify=Verify::None) noexcept
Write a register: the command and data frames, nothing more unless verify asks for a read-back....
Result< uint16_t > ReadAngleCounts() noexcept
The angle at address 0x3FFF (with DAEC unless it is off): the hot path.
Result< float > ReadVelocityDegPerSec() noexcept
Result< uint16_t > ReadUncompensatedAngleCounts() noexcept
Result< uint8_t > ReadAgc() noexcept
Result< ErrorFlags > ReadErrorFlags() noexcept
Read ERRFL, which clears it on the chip. The value is also kept in GetLastErrorFlags() and ORed into ...
bool IsInitialized() const noexcept
Definition as5047u.hpp:351
AS5047U(const AS5047U &)=delete
One driver object per chip.
void GetConfig() const &&=delete
Not on a temporary driver: the reference would dangle (KB-CPP20-044).
Result< uint16_t > ReadRegister(uint16_t address) noexcept
Read one register once: the command frame and the NOP frame that carries the answer,...
Result< uint16_t > SetZeroHere(Verify verify=Verify::None) noexcept
Make the current position read as 0.
Result< void > EnsureInitialized() noexcept
Start the chip, once: the only way to initialise the driver.
Result< uint16_t > ReadMagnitude() noexcept
LogLevel
Severity passed to the optional Log() hook.
Definition as5047u_types.hpp:189
Error
Why a call failed. Every call of the driver returns one of these in its Result.
Definition as5047u_types.hpp:37
constexpr uint8_t kMaxUvwPolePairs
Highest UVW pole-pair count.
Definition as5047u_types.hpp:361
std::array< uint16_t, reg::kNonVolatileCount > NonVolatileRegisters
The non-volatile registers DISABLE to ECC, in address order; index with reg::At(reg::NvIndex).
Definition as5047u_types.hpp:399
Direction
Direction in which the angle increases (SETTINGS2.DIR).
Definition as5047u_types.hpp:218
Verify
Whether a run-time write reads the register back, chosen per call.
Definition as5047u_types.hpp:261
FrameFormat
SPI frame length. The chip recognises the length of each frame, so the driver may mix them.
Definition as5047u_types.hpp:203
@ Info
Lifecycle events: initialised, OTP burned.
@ Framing
The chip saw an SPI framing error (ERRFL.Framing_error).
@ Crc
A reply's CRC was wrong, or the chip saw a wrong CRC (ERRFL.CRC_error).
@ Command
The chip saw an invalid command (ERRFL.Command_error).
@ ThreeLsb
3 LSB. Reset value.
@ CounterClockwise
Inverted (DIR = 1).
@ Clockwise
The datasheet's default direction, seen from above the magnet.
@ Abi
A, B and index pulses; PWM, when on, goes on pin W. Reset value.
@ Uvw
U, V and W commutation signals; PWM, when on, goes on pin I.
@ None
Command and data frames only. The default: nothing extra on a timed path.
@ Bits16
16-bit frames, no CRC: the fastest reads, but a corrupted reply goes unnoticed.
@ Bits24
24-bit frames with CRC-8 in both directions. Default.
constexpr uint16_t kErrflCordic
Definition as5047u_registers.hpp:123
constexpr uint16_t kZeroHighShift
Zero position bits 13..6 go in ZPOSM.
Definition as5047u_registers.hpp:182
constexpr uint16_t kDisableFilterOff
FILTER_disable: adaptive filter off.
Definition as5047u_registers.hpp:175
constexpr uint16_t kDiaOffsetCompDone
Offset compensation finished.
Definition as5047u_registers.hpp:160
constexpr uint16_t kDiaVdd5V
VDD_mode: 1 = 5 V operation.
Definition as5047u_registers.hpp:152
constexpr uint16_t kS2PwmOn
PWMon: PWM output on.
Definition as5047u_registers.hpp:200
constexpr uint16_t kDiaMagHalf
Field at half the regulated value.
Definition as5047u_registers.hpp:157
constexpr uint16_t kErrflCommand
Invalid SPI command.
Definition as5047u_registers.hpp:119
constexpr uint16_t kDiaSpiCountMask
Definition as5047u_registers.hpp:163
constexpr uint16_t kErrflP2ramError
ECC found an uncorrectable P2RAM error.
Definition as5047u_registers.hpp:117
constexpr uint16_t kZposlMask
ZPOSL bits 5..0 hold zero-position bits 5..0.
Definition as5047u_registers.hpp:180
constexpr uint16_t kDiaAgcDone
AGC loop finished.
Definition as5047u_registers.hpp:161
constexpr uint16_t kDiaSpiCountShift
SPI_cnt: frame counter, bits 12..11.
Definition as5047u_registers.hpp:162
constexpr uint16_t kErrflMagHalf
Field at half the regulated value.
Definition as5047u_registers.hpp:115
constexpr uint16_t kErrflDeviceFault
The flags that mean the measurement path is faulty.
Definition as5047u_registers.hpp:128
constexpr uint16_t kErrflWatchdog
Internal oscillator or watchdog fault.
Definition as5047u_registers.hpp:121
constexpr uint16_t kErrflAgcWarning
AGC at its minimum or maximum.
Definition as5047u_registers.hpp:114
constexpr uint16_t kS3AbiresShift
ABIRES, bits 7..5.
Definition as5047u_registers.hpp:207
constexpr uint16_t kDiaCompLow
AGC at its low limit.
Definition as5047u_registers.hpp:155
constexpr uint16_t kDisableUvwOff
UVW_off: UVW pins tristate.
Definition as5047u_registers.hpp:173
constexpr uint16_t kS1KminMask
K_min mask.
Definition as5047u_registers.hpp:188
constexpr uint16_t kS3UvwppMask
UVWPP: pole pairs minus one, bits 2..0.
Definition as5047u_registers.hpp:204
constexpr uint16_t kS1KmaxMask
K_max code, bits 2..0.
Definition as5047u_registers.hpp:186
constexpr std::size_t At(NvIndex index) noexcept
The array index of a non-volatile register.
Definition as5047u_registers.hpp:78
constexpr uint16_t kS2DataSelect
Data_select: 0x3FFF reads ANGLEUNC.
Definition as5047u_registers.hpp:199
constexpr uint16_t kDataMask
The 14 address or data bits of a frame word.
Definition as5047u_registers.hpp:102
constexpr uint16_t kS3AbiresMask
ABIRES mask.
Definition as5047u_registers.hpp:208
constexpr uint16_t kS2AbiDecimal
ABI_DEC: decimal ABI resolution.
Definition as5047u_registers.hpp:198
constexpr uint16_t kErrflOffComp
Offset compensation not finished.
Definition as5047u_registers.hpp:122
constexpr uint16_t kDiaCordicOverflow
CORDIC overflow.
Definition as5047u_registers.hpp:154
constexpr uint16_t kS1KminShift
K_min code, bits 5..3.
Definition as5047u_registers.hpp:187
constexpr uint16_t kDisableAbiOff
ABI_off: A, B and I pins tristate.
Definition as5047u_registers.hpp:174
constexpr uint16_t kErrflP2ramWarning
ECC corrected one bit in P2RAM.
Definition as5047u_registers.hpp:116
constexpr uint16_t kZposlDiaBits
ZPOSL bits 7..6: Dia1_en, Dia2_en (kept).
Definition as5047u_registers.hpp:181
NvIndex
Index of a non-volatile register in NonVolatileRegisters (address order from DISABLE).
Definition as5047u_registers.hpp:63
constexpr uint16_t kS2NoiseSet
NOISESET: reduced noise at 150 °C, 3.3 V.
Definition as5047u_registers.hpp:194
constexpr uint16_t kS2Dir
DIR: invert the rotation direction.
Definition as5047u_registers.hpp:195
constexpr uint16_t kErrflCrc
CRC error on a MOSI frame.
Definition as5047u_registers.hpp:120
constexpr uint16_t kS2UvwAbi
UVW_ABI: 0 = ABI with PWM on W, 1 = UVW.
Definition as5047u_registers.hpp:196
constexpr uint16_t kS3HysMask
HYS mask.
Definition as5047u_registers.hpp:206
constexpr uint16_t kErrflFraming
SPI framing error.
Definition as5047u_registers.hpp:118
constexpr uint16_t kS2IndexWidth1
IWIDTH: 1 = 1 LSB index pulse, 0 = 3 LSB.
Definition as5047u_registers.hpp:193
constexpr uint16_t kS1DiaBits
Dia3_en, Dia4_en (kept).
Definition as5047u_registers.hpp:189
constexpr uint16_t kS3HysShift
HYS, bits 4..3.
Definition as5047u_registers.hpp:205
constexpr uint16_t kDiaLoopsFinished
All magnetic loops have settled.
Definition as5047u_registers.hpp:153
constexpr uint16_t kS2DaecDis
DAECDIS: dynamic compensation off.
Definition as5047u_registers.hpp:197
constexpr uint16_t kZposmMask
ZPOSM holds zero-position bits 13..6.
Definition as5047u_registers.hpp:179
constexpr uint16_t kDiaCompHigh
AGC at its high limit.
Definition as5047u_registers.hpp:156
The AS5047U driver: everything it declares lives here; internals in detail.
Definition as5047u.hpp:24
Everything EnsureInitialized() and ApplyConfig() write to the chip.
Definition as5047u_types.hpp:287
Direction direction
SETTINGS2.DIR.
Definition as5047u_types.hpp:305
bool high_temperature_noise
Definition as5047u_types.hpp:320
uint16_t zero_position
ZPOSM/ZPOSL, counts 0 to 16383.
Definition as5047u_types.hpp:306
bool uvw_enable
U/V/W pins driven (DISABLE.UVW_off = 0).
Definition as5047u_types.hpp:313
bool pwm_enable
SETTINGS2.PWMon.
Definition as5047u_types.hpp:314
uint8_t filter_k_max_code
SETTINGS1.K_max code, 0 to 7.
Definition as5047u_types.hpp:310
bool uncompensated_at_angle_register
SETTINGS2.Data_select: address 0x3FFF (and the PWM output) carry the angle without DAEC.
Definition as5047u_types.hpp:322
bool abi_decimal
SETTINGS2.ABI_DEC.
Definition as5047u_types.hpp:316
uint8_t uvw_pole_pairs
SETTINGS3.UVWPP + 1, 1 to 7.
Definition as5047u_types.hpp:318
uint8_t filter_k_min_code
SETTINGS1.K_min code, 0 to 7.
Definition as5047u_types.hpp:309
uint8_t hysteresis_code
SETTINGS3.HYS, 0 to 3.
Definition as5047u_types.hpp:319
IndexWidth index_width
SETTINGS2.IWIDTH.
Definition as5047u_types.hpp:317
bool abi_enable
A/B/I pins driven (DISABLE.ABI_off = 0).
Definition as5047u_types.hpp:312
bool adaptive_filter
Velocity filter on (DISABLE bit 6 = 0).
Definition as5047u_types.hpp:308
IncrementalOutput incremental
SETTINGS2.UVW_ABI.
Definition as5047u_types.hpp:311
bool dynamic_compensation
DAEC on (SETTINGS2.DAECDIS = 0).
Definition as5047u_types.hpp:307
FrameFormat frame
Definition as5047u_types.hpp:292
uint8_t abi_resolution_code
SETTINGS3.ABIRES, 0 to 7.
Definition as5047u_types.hpp:315
DIA, decoded: the state of the chip's internal loops.
Definition as5047u_types.hpp:385
bool vdd_5v
VDD_mode: the chip runs from 5 V (else 3.3 V).
Definition as5047u_types.hpp:386
ERRFL, decoded. Reading ERRFL clears it on the chip.
Definition as5047u_types.hpp:364
bool flags_lost
Not an ERRFL bit: in GetLatchedErrorFlags() only, true when a read of ERRFL failed after its command ...
Definition as5047u_types.hpp:380
bool agc_warning
AGC at its minimum or maximum: magnet too far or too close.
Definition as5047u_types.hpp:365
The typed confirmation ProgramOtp() requires: burning the OTP cannot be undone, so the call names its...
Definition as5047u_types.hpp:351
Outcome of AS5047U::ProgramOtp().
Definition as5047u_types.hpp:402
The value of a call, or why there is none.
Definition as5047u_types.hpp:129
static constexpr Result Failure(Error e) noexcept
A failed result.
Definition as5047u_types.hpp:155