13.20 The AS5048A and SPI
The code in code/spi_encoder builds with PlatformIO, but has not yet been run on the ESP32 DevKit bench setup. The hardware photos and pinout come from our two-wheel balancing robot build on the ESP32.
In Angle and motion sensors on I²C we read an AS5600 shaft encoder and an MPU6050 over the same two wires because their fixed addresses (0x36 and 0x68) are distinct. Putting two identical AS5600 encoders on one robot, one per wheel of a balancing robot, runs straight into an address collision: both chips answer to 0x36 at once. Fast closed-loop motor control also pushes against the speed of an I²C bus. The AS5048A resolves both limits. It reads a rotating magnet to 14 bits (16 384 steps per revolution, \(0.022^\circ\) per step) and talks over SPI (Serial Peripheral Interface) at up to \(10~\text{MHz}\). Instead of fixed addresses, each device on an SPI bus has its own chip-select wire, so two identical encoders share one bus without conflict.
The Guide
Step 1: Solder and mount the AS5048A
The compact circular AS5048A breakout board carries the 14-pin sensor IC in the centre, flanked by two decoupling capacitors (C1 and C2) and two mounting holes (Figure 13.20.1). Three large pads along one edge provide power (VDD in the middle, GND marked − on the right) and an unused PWM output marked P on the left. Along the opposite edge sit eight narrow pads; four of them carry the SPI signals (MISO, MOSI, SCK, and CSn), while the remaining four duplicate GND and VDD.
VDD) and black (GND) power leads on the top pads, and orange (MISO), blue (MOSI), white (SCK), and yellow (CSn) signal leads on the bottom row.
Follow the tinning and trim rules from Soldering with thin silicone-insulated wire. The eight signal pads sit close together, so trim each tinned wire end to 1 to 2 mm, inspect adjacent pads under good light, and verify with a multimeter in continuity mode that no neighbour is bridged before applying power. Scrub leftover flux residue off the pads with isopropyl alcohol.
According to the ams AS5048A datasheet, the sensor’s MISO output drives up to \(V_{OH} \ge V_{\text{DD5V}} - 0.5~\text{V}\). Powering the module from 5 V can drive MISO close to 5 V, above the 3.3 V rating of an ESP32 GPIO pin. Power the encoder from the ESP32 3V3 pin so MISO stays at 3.3 V. For a bare chip or a 5 V-configured breakout board, the datasheet specifies shorting VDD3V to VDD5V when running from 3.3 V; check your breakout board’s documentation before connecting VDD to 5 V, and never feed a 5 V MISO signal straight into an ESP32 pin.
Just like the AS5600, the AS5048A measures the direction of the magnetic field from a two-pole diametrically magnetised disc magnet fixed concentrically to the end of the shaft. The short clip below shows a disc magnet glued to the rear shaft of a brushless motor inside a 3D-printed sensor holder before the PCB is installed.
Once the leads are soldered, the circular PCB drops straight into the pocket of the printed backplate directly above the spinning magnet (Figure 13.20.2). The pocket sets the air gap between the chip surface and the magnet within the typical 0.5 to 2.5 mm working window (30 to 70 mT at the die) and centres the chip on the shaft axis within 0.25 to 0.5 mm [1]. Routing the power leads around the moulded channel provides strain relief so cable movement does not pull on the solder joints.
Step 2: Wire one or two encoders to the ESP32
Connect VDD to 3V3 and GND to GND on the ESP32 DevKit, then wire the four SPI lines using the default VSPI pins from the ESP32 pinout (Figure 13.20.3 and Table 13.20.1). To add a second AS5048A, join its 3V3, GND, SCK, MOSI, and MISO wires in parallel with the first encoder, and run only its CSn wire to a separate GPIO pin (GPIO 17). Unlike I²C, SPI needs no pull-up resistors.
SCK, MOSI, and MISO are shared across both devices, while each encoder has its own chip-select wire (CS1 on GPIO 5, CS2 on GPIO 17).
| AS5048A pad | Photo wire colour | ESP32 DevKit pin | Role |
|---|---|---|---|
VDD |
red | 3V3 |
3.3 V supply (shared) |
GND |
black | GND |
common ground (shared) |
SCK (CLK) |
white | GPIO 18 | clock from ESP32 (shared) |
MOSI |
blue | GPIO 23 | data from ESP32 to sensor (shared) |
MISO |
orange | GPIO 19 | data from sensor to ESP32 (shared) |
CSn (encoder 1) |
yellow | GPIO 5 | chip select for encoder 1 (active low) |
CSn (encoder 2) |
yellow | GPIO 17 | chip select for encoder 2 (active low) |
Note the naming convention: MOSI (Master Out, Slave In) carries commands from the ESP32 to the sensor, and MISO (Master In, Slave Out) carries replies back from the sensor to the ESP32. Connect MOSI to MOSI and MISO to MISO, never crossed.
The ESP32 routes its SPI peripherals through an internal GPIO matrix, so SPI.begin(sck, miso, mosi) can move the bus onto almost any free pins when shields claim the defaults. In our two-wheel balancing robot build (Figure 13.20.4), two stacked SimpleFOC motor driver shields take GPIO 23 and GPIO 5 for motor PWM, so the encoders share the second SPI bus (HSPI) on SCK = 18, MISO = 19, MOSI = 26, with CS1 = 33 and CS2 = 15. When driving brushless motors with the SimpleFOC library, the same wiring works in four lines:
SPIClass SPI_2(HSPI);
MagneticSensorSPI sensor1(AS5048_SPI, 33);
MagneticSensorSPI sensor2(AS5048_SPI, 15);
// in setup(): SPI_2.begin(18, 19, 26); sensor1.init(&SPI_2); sensor2.init(&SPI_2);
Step 3: Check the magnet and read the angle
The PlatformIO project is code/spi_encoder next to this chapter. It uses only the built-in <SPI.h> library (platformio.ini needs no lib_deps). as5048a.h handles the 16-bit SPI frames, even parity, error flags, and magnetic diagnostics; The AS5048A frame, parity and pipeline explains every line inside it.
as5048a.h, SPI transfers, parity and diagnostics
// as5048a.h: read registers from one or more AS5048A encoders on one SPI bus
// (default VSPI pins: SCK 18, MISO 19, MOSI 23; SPI mode 1, 16-bit even-parity frames).
#pragma once
#include <Arduino.h>
#include <SPI.h>
const int spiSckPin = 18;
const int spiMisoPin = 19;
const int spiMosiPin = 23;
const uint32_t spiClockHz = 1000000; // 1 MHz is safe on jumper wires (chip supports 10 MHz)
const uint16_t regClearError = 0x0001; // reading clears the sticky error flag
const uint16_t regDiagAgc = 0x3FFD; // bits 11..8 flags, bits 7..0 AGC (0 strong, 255 weak)
const uint16_t regMagnitude = 0x3FFE; // 14-bit CORDIC magnetic field magnitude
const uint16_t regAngle = 0x3FFF; // 14-bit absolute angle, 0 to 16383
// Return 1 if the lowest 15 bits contain an odd number of ones (even parity bit for bit 15)
uint16_t evenParity(uint16_t word) {
uint16_t p = 0;
for (int i = 0; i < 15; i++) p ^= (word >> i) & 1;
return p;
}
// Build a 16-bit read command frame: bit 15 parity, bit 14 read (1), bits 13..0 address
uint16_t readCommand(uint16_t reg) {
uint16_t cmd = 0x4000 | (reg & 0x3FFF);
return cmd | (evenParity(cmd) << 15);
}
// Exchange one 16-bit frame with the sensor selected by csPin
uint16_t as5048Transfer(int csPin, uint16_t command) {
SPI.beginTransaction(SPISettings(spiClockHz, MSBFIRST, SPI_MODE1));
digitalWrite(csPin, LOW);
uint16_t reply = SPI.transfer16(command);
digitalWrite(csPin, HIGH);
SPI.endTransaction();
delayMicroseconds(1); // datasheet requires CSn high >= 350 ns between frames
return reply;
}
// Prepare one chip-select pin before starting the bus
void as5048Begin(int csPin) {
pinMode(csPin, OUTPUT);
digitalWrite(csPin, HIGH); // deselect so this sensor releases MISO
}
// Read a 14-bit register (two frames because the answer arrives on the next transfer).
// Returns -1 on a parity mismatch or sensor error flag.
int as5048Read(int csPin, uint16_t reg) {
as5048Transfer(csPin, readCommand(reg));
uint16_t reply = as5048Transfer(csPin, 0x0000); // NOP clocks out the requested register
bool parityOk = (evenParity(reply) == ((reply >> 15) & 1));
bool errorFlag = (reply & 0x4000) != 0;
if (!parityOk || errorFlag) {
as5048Transfer(csPin, readCommand(regClearError));
as5048Transfer(csPin, 0x0000);
return -1;
}
return reply & 0x3FFF;
}
// Print magnetic field diagnostics and return true if a live sensor answered
bool as5048Check(int csPin, const char* name) {
int diag = as5048Read(csPin, regDiagAgc);
int mag = as5048Read(csPin, regMagnitude);
if (diag < 0 || (diag & (1 << 8)) == 0) {
Serial.printf("%s (CS %d): no valid answer (check wiring and power)\n", name, csPin);
return false;
}
int agc = diag & 0xFF;
Serial.printf("%s (CS %d): ok, AGC=%d, magnitude=%d\n", name, csPin, agc, mag);
if (diag & (1 << 9)) Serial.printf("%s: CORDIC overflow (magnet field invalid)\n", name);
if (diag & (1 << 10)) Serial.printf("%s: magnet too close (COMP low)\n", name);
if (diag & (1 << 11)) Serial.printf("%s: magnet too far away (COMP high)\n", name);
return true;
}main.cpp prepares both chip-select pins before starting the bus, checks both sensors at start-up, and then reads the angle every 10 ms to print angle1, rpm1, turns1, and (when wired) angle2 for Teleplot.
// main.cpp: one or two AS5048A magnetic encoders on a shared SPI bus.
// Every 10 ms it prints angle, speed and turns for sensor 1 (and angle for sensor 2
// when connected), formatted for Teleplot.
#include <Arduino.h>
#include "as5048a.h"
const int cs1Pin = 5; // chip select for encoder 1 (default VSPI SS)
const int cs2Pin = 17; // chip select for encoder 2 (optional second sensor)
const int stepMs = 10; // one reading every 10 ms
const int countsPerTurn = 16384; // 14-bit resolution: 2^14 steps per revolution
unsigned long lastMs = 0;
unsigned long lastUs = 0;
int lastCounts = 0;
long totalCounts = 0; // cumulative counts since start, whole turns included
bool hasSensor2 = false;
void setup() {
Serial.begin(115200);
as5048Begin(cs1Pin);
as5048Begin(cs2Pin);
SPI.begin(spiSckPin, spiMisoPin, spiMosiPin);
as5048Check(cs1Pin, "encoder 1");
hasSensor2 = as5048Check(cs2Pin, "encoder 2");
int first = as5048Read(cs1Pin, regAngle);
if (first >= 0) lastCounts = first;
lastUs = micros();
}
void loop() {
if (millis() - lastMs < stepMs) return;
lastMs = millis();
unsigned long nowUs = micros();
float dtSec = (nowUs - lastUs) / 1000000.0;
lastUs = nowUs;
int counts1 = as5048Read(cs1Pin, regAngle);
if (counts1 < 0) return;
// Fold the step change into [-8192, +8192] across the 16383 -> 0 wrap
int diff = counts1 - lastCounts;
if (diff > countsPerTurn / 2) diff -= countsPerTurn;
if (diff < -countsPerTurn / 2) diff += countsPerTurn;
lastCounts = counts1;
totalCounts += diff;
float angle1 = counts1 * 360.0 / countsPerTurn;
float turns1 = totalCounts / (float)countsPerTurn;
float rpm1 = (diff / (float)countsPerTurn) * (60.0 / dtSec);
Serial.printf(">angle1:%.2f\n>rpm1:%.0f\n>turns1:%.2f\n", angle1, rpm1, turns1);
if (hasSensor2) {
int counts2 = as5048Read(cs2Pin, regAngle);
if (counts2 >= 0) {
float angle2 = counts2 * 360.0 / countsPerTurn;
Serial.printf(">angle2:%.2f\n", angle2);
}
}
}Upload the project and open the Serial Monitor. Press EN on the ESP32 and read the start-up diagnostic lines:
encoder 1 (CS 5): ok, AGC=84, magnitude=7820
encoder 2 (CS 17): no valid answer (check wiring and power)
If encoder 1 prints no valid answer, check 3V3 and GND first, then verify that MOSI and MISO are not swapped and that CSn reaches GPIO 5. When encoder 1 reports magnet too close or magnet too far away, adjust the air gap until both warnings disappear and AGC falls near the middle of its 0 to 255 range.
Close the Serial Monitor and open Teleplot. Turn the motor shaft slowly by hand: angle1 climbs smoothly from 0° to 360° and wraps back to 0° once per revolution, turns1 counts full revolutions continuously through the wrap, and rpm1 shows the shaft speed with sign. Connect the second encoder to GPIO 17 and press EN: encoder 2 now prints ok, and angle2 tracks the second shaft independently on the same three bus wires.
How It Works
The SPI bus
On the I²C bus of the previous chapter, every device shares one open-drain data wire pulled up by a resistor. That resistor limits how fast the line can rise back to 3.3 V, capping standard I²C at 100 kHz or 400 kHz [2]. SPI takes a different approach. It uses push-pull outputs that actively drive each signal both high and low, removing the pull-up resistors and allowing sharp edges at megahertz clock rates.
SPI also splits the single data line into two unidirectional paths, MOSI (controller to sensor) and MISO (sensor to controller), both stepped by one shared clock SCK from the ESP32. On every clock cycle, one bit shifts out of the ESP32 on MOSI at the exact same instant another bit shifts back in on MISO. This simultaneous two-way exchange is called full-duplex communication [3].
Because SPI has no addresses on the wire, the controller chooses which device talks by pulling that device’s chip-select pin (CSn, where n marks active low) to 0 V while holding every other CSn pin at 3.3 V (Figure 13.20.3). Any deselected sensor disconnects its MISO driver into a high-impedance (Hi-Z) state so it cannot fight the active sensor on the shared line. This is why setup() calls as5048Begin() to drive every CS pin HIGH before starting SPI.begin(): if two sensors ever had their CSn pins low at the same time, both would drive MISO together and corrupt each other’s data.
SPI defines four clock modes (0 through 3) set by two bits: CPOL chooses the idle level of SCK (0 = low, 1 = high), and CPHA chooses which clock edge samples the data (0 = leading edge, 1 = trailing edge) [3]. The AS5048A requires SPI Mode 1 (CPOL = 0, CPHA = 1): SCK idles low, both sides shift out a new bit on the rising edge, and both sample the incoming bit on the falling edge [1]. Selecting the wrong mode (such as the common default SPI_MODE0) shifts every read by half a clock cycle, tripping the parity check and turning angles into garbage.
| Property | I²C (AS5600) | SPI (AS5048A) |
|---|---|---|
| Signal wires for \(N\) sensors | 2 (SDA, SCL) |
\(3 + N\) (SCK, MOSI, MISO, plus \(N\) CSn) |
| Device selection | 7-bit address (0x36, fixed on AS5600) |
dedicated CSn wire per sensor |
| Pull-up resistors | required on SDA and SCL |
none (push-pull drivers) |
| Direction | half-duplex (one shared data wire) | full-duplex (MOSI and MISO simultaneous) |
| Typical clock speed | 100 kHz to 400 kHz | 1 MHz to 10 MHz |
| Angle resolution | 12-bit (4096 steps, \(0.088^\circ\)) | 14-bit (16 384 steps, \(0.022^\circ\)) |
| Time for one angle read | \(\approx 600~\mu\text{s}\) at 100 kHz | \(\approx 33~\mu\text{s}\) at 1 MHz (\(< 2~\mu\text{s}\) pipelined at 10 MHz) |
The AS5048A frame, parity and pipeline
Every transfer with the AS5048A is a 16-bit word, most significant bit first (Figure 13.20.5). In a command sent on MOSI, bits 13 down to 0 hold the register address, bit 14 selects read (1) or write (0), and bit 15 (PAR) is an even parity bit chosen so that the total count of 1 bits across all 16 bits is even [1].
Take the angle register 0x3FFF (0011 1111 1111 1111 in binary, fourteen 1 bits). Setting bit 14 for a read produces 0x7FFF, which has fifteen 1 bits, an odd count. The even parity bit at bit 15 must therefore be 1 to bring the total to sixteen, yielding the command word 0xFFFF. By the same rule, reading the diagnostics register 0x3FFD sets bit 14 to give 0x7FFD, which already has fourteen 1 bits (even), so bit 15 stays 0 and the command word is 0x7FFD. readCommand() in as5048a.h computes this bit automatically for any register.
CPOL = 0, CPHA = 1) transfers reading angle register 0x3FFF. Frame 1 sends 0xFFFF on MOSI while MISO returns the previous answer. After CSn rises for at least \(350~\text{ns}\), Frame 2 sends the NOP command 0x0000 to clock out the 14-bit angle together with its parity bit (PAR) and error flag (EF).
Because MOSI and MISO shift simultaneously, the sensor has not yet received the address bits of Frame 1 when it must start driving MISO on the first clock pulse. The AS5048A handles this with a one-frame pipeline: during Frame 1 it clocks out the answer to whatever command came before, decodes the new address once CSn rises, and prepares the requested register for the next frame. Between the two frames, CSn must stay high for at least \(t_{\text{CSnH}} = 350~\text{ns}\) so the internal state machine can latch the result [1]; as5048Transfer() waits \(1~\mu\text{s}\) to leave ample margin. During Frame 2, sending the no-operation command 0x0000 (all zeros, which has even parity) clocks the requested 14-bit value back into the ESP32.
The sensor’s 16-bit reply on MISO carries its own even parity bit in bit 15 (PAR) and an error flag in bit 14 (EF), leaving the 14-bit payload in bits 13 down to 0. If the sensor detected a parity error, a bad command, or a wrong clock count on the previous frame, it sets EF = 1 and keeps it set on every subsequent reply until the host clears it by reading register 0x0001 (0x4001) [1]. as5048Read() checks both the incoming parity and EF; if either fails, it clears the sticky error flag and returns -1 so a corrupted reading never reaches the control loop.
At \(1~\text{MHz}\), one 16-bit frame takes \(16~\mu\text{s}\), so a two-frame read with its \(1~\mu\text{s}\) chip-select gap finishes in about \(33~\mu\text{s}\). At the chip’s \(10~\text{MHz}\) ceiling, a continuous loop that pipelines 0xFFFF on every call reads the angle in \(1.6~\mu\text{s} + 0.35~\mu\text{s} \approx 2~\mu\text{s}\), roughly three hundred times faster than an AS5600 at \(100~\text{kHz}\) on I²C.
That speed margin is why field-oriented motor control (FOC) uses SPI encoders: a brushless motor controller running at 2 to 10 kHz cannot spend \(600~\mu\text{s}\) waiting on I²C per wheel. Note that the sensor’s internal Hall array and CORDIC solver still introduce a fixed propagation delay of about \(100~\mu\text{s}\) [1], which sets the true freshness of the angle even when the bus itself runs at \(10~\text{MHz}\).
Resolution, diagnostics and unwrapping
With 14 bits over one full turn, the AS5048A divides \(360^\circ\) into \(2^{14} = 16\,384\) counts, giving an angular resolution of
\[ \Delta\varphi = \frac{360^\circ}{16\,384} \approx 0.022^\circ \]
per count, four times finer than the 12-bit AS5600. Computing shaft speed from the change \(\Delta n\) in counts over a step \(\Delta t\) gives
\[ n_\text{rpm} = \frac{\Delta n}{16\,384} \cdot \frac{60}{\Delta t} \approx 0.366\,\Delta n \quad \text{for } \Delta t = 0.01~\text{s}. \]
One count per 10 ms step is therefore \(0.37~\text{rpm}\) instead of the AS5600’s \(1.46~\text{rpm}\), reducing velocity quantization noise at low speeds. When the shaft crosses zero, the raw count jumps between 16 383 and 0, and main.cpp folds \(\Delta n\) into \([-8192, +8192]\) using the same half-turn wrap rule introduced in the I²C chapter. Because the aliasing ceiling is always half a turn per sample interval, the unwrapping limit at \(\Delta t = 0.01~\text{s}\) remains \(3000~\text{rpm}\) regardless of bit depth; measuring faster shafts simply requires a shorter sample interval, which the fast SPI bus easily affords.
Unlike an optical encoder that fails silently when dirty, the AS5048A exposes its magnetic health directly in two diagnostic registers. Register 0x3FFD (DIAAGC) packs an 8-bit automatic gain control value (AGC, bits 7..0) together with four status flags:
0x3FFD), after datasheet v1-11 [1].
Bits of 0x3FFD |
Flag | Meaning |
|---|---|---|
11 |
COMP high |
Magnetic field too weak (magnet too far away or missing) |
10 |
COMP low |
Magnetic field too strong (magnet too close) |
9 |
COF |
CORDIC overflow: internal angle calculation invalid |
8 |
OCF |
Offset compensation finished (1 during normal operation) |
7..0 |
AGC |
Internal gain from 0 (strong field) to 255 (weak field) |
With OCF = 1 and the other three flags at 0, the field at the die lies inside the 30 to 70 mT operating window [1]. Register 0x3FFE reports the raw 14-bit CORDIC magnitude of the field signal, which the next section uses together with AGC to check the mounting. The mechanical alignment rules from Mounting apply here with even greater force, because a 14-bit sensor resolves \(0.022^\circ\) steps while displacing an 8 mm magnet by \(0.5~\text{mm}\) in \(x\) and \(y\) raises the non-linearity to \(\pm 0.7^\circ\), and to \(\pm 1.2^\circ\) over the full temperature range from \(-40\) to \(150^\circ\text{C}\) [1].
Finally, the unused P pad on the breakout board carries a 1 kHz PWM signal whose duty cycle is proportional to the angle at a coarser 12-bit resolution (4096 steps) [1]. That output uses only one wire and needs no SPI peripheral, which can be handy on a pin-starved microcontroller, though reading its pulse width takes at least one full millisecond per sample instead of a few microseconds over SPI.
AGC, magnitude and a tilted sensor
The Hall plates of the AS5048A sit on a circle of radius 1.1 mm around the die centre and measure the field component \(B_z\) perpendicular to the die [1]. Their signals grow with the field strength, so the chip amplifies them to a fixed level before the CORDIC computes angle and magnitude. This automatic gain control stores the gain it needed in AGC. A magnet close to the die gives a strong field and an AGC near 0, while a distant or missing magnet gives a weak field and an AGC near 255. A single reading therefore measures the air gap, and Exercise 4 maps that relation with shims.
The same two registers expose a fault that a single reading misses: a die that is not parallel to the magnet. When the die is parallel and centred on the shaft, every Hall plate keeps its distance to the magnet as the shaft turns. The field pattern then rotates without changing shape, and AGC and magnitude stay flat over a full revolution. When the board is tilted, one edge of the die sits closer to the magnet than the opposite edge. The plate nearest the magnet sees a stronger field than the plate across from it, and which plate that is depends on the shaft angle, so the signal amplitude and the computed angle both carry an error that repeats once per revolution. An off-centre chip produces the same signature, and it is the only case the datasheet quantifies (\(\pm 0.7^\circ\) at 0.5 mm displacement).
A brushless motor magnifies that error. Field-oriented control places the stator field from the electrical angle \(\theta_e\), which a motor with \(p\) pole pairs relates to the measured shaft angle \(\theta_m\) through
\[ \theta_e = p\,\theta_m, \qquad \Delta\theta_e = p\,\Delta\theta_m . \]
On a motor with 7 pole pairs, a \(1^\circ\) sensor error becomes a \(7^\circ\) error in where the controller points the stator field. Because the error changes around the turn, the torque per ampere changes with wheel position, and the speed computed from the angle carries a ripple at the wheel’s rotation frequency. A balancing controller sees both as a disturbance tied to wheel position that its gains cannot tune away.
Our balancing robot build ran into exactly this. Both encoders passed the start-up check with clear flags and mid-range AGC, and the angle counted smoothly from 0° to 360°, yet the robot would not balance. Students spent days on the controller before they found that the board holder held the AS5048A at an angle to the magnet, and they had to redesign the holder in the motor mount before the robot balanced.
Judge the mounting by how AGC and magnitude change over one revolution. A single reading only tells us the air gap.
The test takes a few lines in loop() of main.cpp. With the motor driver switched off, we stream the two diagnostic values next to angle1 and turn the wheel slowly through one revolution by hand:
// Field health over one turn: flat lines mean a parallel, centred chip
int diag = as5048Read(cs1Pin, regDiagAgc);
int mag = as5048Read(cs1Pin, regMagnitude);
if (diag >= 0 && mag >= 0) {
Serial.printf(">agc1:%d\n>mag1:%d\n", diag & 0xFF, mag);
}In Teleplot, flat agc1 and mag1 traces mean a good mount. One clear wave per revolution in mag1 means the chip is tilted or off-centre, and a larger wave means a larger angle error. Flat traces with AGC pinned near 0 or 255 mean the chip is parallel but the gap is wrong. On a robot with two wheels, the flatter of the two traces is the reference: two encoders mounted the same way should give the same picture, so a difference between them points to the mount and away from the code. Only once both traces are flat is it worth tuning the balance controller.
Exercises
Exercise 1: Parity and command frames by hand
Using the rule that bit 15 (PAR) makes the total number of 1 bits even and bit 14 is 1 for a read, compute the 16-bit hexadecimal command words for reading 0x3FFD (diagnostics), 0x3FFE (magnitude), and 0x0001 (clear error flag). Print readCommand() for each register in setup() and verify your hand calculation.
Exercise 2: Single-frame pipelined reads
In as5048Read(), every call sends two 16-bit frames (readCommand(reg) followed by NOP 0x0000). When loop() reads only the angle register 0x3FFF repeatedly, sending 0xFFFF on every call returns the previous angle in one frame while simultaneously requesting the next. Add a single-frame as5048ReadAngleFast(int csPin) to as5048a.h, prime it once in setup(), and verify in Teleplot that it tracks the shaft identically while cutting bus transfers in half.
Exercise 3: Timing the SPI bus
Measure with micros() how long 1000 calls to as5048Read(cs1Pin, regAngle) take at spiClockHz = 1000000, 4000000, and 8000000. Divide each total by 1000 and compare it with \(2 \cdot (16 / f_{\text{SCK}}) + 2~\mu\text{s}\) (accounting for the two \(1~\mu\text{s}\) pauses). Does the parity check start catching errors at higher clock rates over long breadboard jumper wires?
Exercise 4: Mapping the air gap with AGC
Place thin spacers (such as folded paper or 3D-printed shims of known thickness) between the AS5048A holder and the motor backplate, and record AGC, magnitude, COMP low, and COMP high from as5048Check() at each gap from 0.5 mm up to 4.0 mm. Over what air-gap range do both warning flags stay off, and how does magnitude vary as the magnet moves further away?
Exercise 5: Tilting the sensor on purpose
Slide a thin shim (a strip of paper or a 0.2 mm printed wedge) under one edge of the AS5048A holder so that the die tilts relative to the magnet. With the motor driver off, turn the shaft slowly through one revolution and record angle1, agc1 and mag1 as in the tilt test, then repeat with the holder flat. Compare the peak-to-peak wave in mag1 for the two cases, and check whether the start-up line from as5048Check() shows any difference at all.