element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products & Partners
    Products & Partners
    • Arduino
    • Avnet & Tria Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • About Us
    About the element14 Community
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Japan
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      •  Vietnam
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
My Project Is Trash
  • Challenges & Projects
  • Design Challenges
  • My Project Is Trash
  • More
  • Cancel
My Project Is Trash
Forum TRS-05: “P” is for Proximity, “P” is for Power (and "P" is for Prayer?)
  • News
  • Forum
  • Projects
  • Enroll
  • Leaderboard
  • Files
  • Members
  • More
  • Cancel
  • New
Join My Project Is Trash to participate - click to join for free!
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • Replies 4 replies
  • Subscribers 4 subscribers
  • Views 53 views
  • Users 0 members are here
  • adpd2140
  • adpd1080
  • TRASH_PROJECT_NAME
  • camdenboss
  • esp32-s3
  • my-project-is-trash
  • design-challenge
  • arduino
Related

TRS-05: “P” is for Proximity, “P” is for Power (and "P" is for Prayer?)

Gough Lui
Gough Lui 15 hours ago

So far, the project has been envisioned, received an injection of parts, obtained its name, went on a dumpster-dive for even more parts and sorted out some communications. But the raccoons are still far from being finished as we still have plenty of things to build before we can even think about putting the system together. In this section, the raccoons will be learning about things starting with the letter “P”.

Getting the CN0569 Running

In addition to the datasheets for the chips themselves, Analog Devices provides a design and integration file which contains the schematic and PCB design files, a user guide and a set of sample code for the IIO Framework.

Unfortunately, this is not a framework I’m familiar with. There is a porting guide which suggests that IIO mimics what Linux does and that porting can be achieved by connecting IIO functions with the functions that produce the corresponding effect on your platform of choice. Unfortunately, for me, I didn’t find any pre-built translation layers for ESP32-S3 so I’m a bit stuck.

Looking at the provided code, it seems broken up into two parts – iio_adpd1080 which seems to be dealing more with the hardware side which seems to be setup for an EVAL-ADICUP3029 based on an ADUCM3029. But this seems to be involved in returning somewhat “raw” values from the analog front end, rather than gestures, based on iio_example.c.

I had to do some digging to find more – turns out, the gesture magic seems to be happening in adpd2140_gesture_sensor.py in the pyadi-iio repository.

The first thing I started with was just getting GPT-6 Luna to help me port the IIO-based example to something that will run directly on an ESP32-S3. After two or three rounds, I was able to get something up and running that seemed to be working …

[CN0569_ESP32_Arduino_Direct_Port.ino]

/*
 * CN0569 (ADPD1080 + two ADPD2140 sensors) - ESP32 Arduino port
 * Ported by OpenAI's ChatGPT GPT-6 Luna guided by Gough Lui
 *
 * Ported from the Analog Devices no-OS iio_adpd1080 example and the
 * ADPD188/ADPD1080 no-OS driver.
 *
 * Hardware assumptions:
 *   CN0569 P1 pin 1 INT  -> ESP32 GPIO 13 (used only for 32 kHz/sample-clock calibration)
 *   CN0569 P1 pin 3 SCL  -> ESP32 GPIO 5
 *   CN0569 P1 pin 4 SDA  -> ESP32 GPIO 4
 *   CN0569 P1 pin 5 GND  -> ESP32 GND
 *   CN0569 P1 pin 6 VCC  -> regulated 3.3 V
 *   P1 pin 2 RESET is not connected on the CN0569.
 *
 * The ADPD1080 I2C address is 0x64 (7-bit).  The board's LED1 output drives
 * the on-board IR LED by default.  This sketch uses the LED1 settings from
 * the ADI example; check the board supply and LED configuration before use.
 *
 * Output: one CSV row per sample:
 *   micros,pd0,pd1,pd2,pd3,pd4,pd5,pd6,pd7
 *
 * CN0569 photodiode channel order:
 *   pd0..pd3 = ADPD1080 PD1..PD4 = Sensor 1 XR, XL, YB, YT
 *   pd4..pd7 = ADPD1080 PD5..PD8 = Sensor 2 XR, XL, YB, YT
 *
 * This is a data-acquisition port.  It does not implement ADI's IIO server,
 * host-side Python gesture classification, or an application-level baseline
 * calibration algorithm.
 */

#include <Arduino.h>
#include <Wire.h>
#include <esp_timer.h>

// -----------------------------------------------------------------------------
// User-adjustable connections and operating parameters
// -----------------------------------------------------------------------------
#define CN0569_SDA_PIN       4
#define CN0569_SCL_PIN       5
#define CN0569_INT_PIN       13

static const uint8_t  ADPD1080_I2C_ADDRESS = 0x64;
static const uint32_t I2C_CLOCK_HZ = 400000;
static const uint16_t REQUESTED_SAMPLE_RATE_HZ = 512;
static const uint32_t FIFO_WAIT_TIMEOUT_MS = 1000;
static const uint8_t  MAX_32K_CALIBRATION_STEPS = 64;
static const uint32_t SERIAL_BAUD = 921600;

// -----------------------------------------------------------------------------
// ADPD1080 register addresses used by the ADI example / driver
// -----------------------------------------------------------------------------
static const uint8_t REG_STATUS          = 0x00;
static const uint8_t REG_GPIO_DRV        = 0x02;
static const uint8_t REG_DEVID           = 0x08;
static const uint8_t REG_CLK_RATIO       = 0x0A;
static const uint8_t REG_GPIO_CTRL       = 0x0B;
static const uint8_t REG_SW_RESET        = 0x0F;
static const uint8_t REG_MODE            = 0x10;
static const uint8_t REG_SLOT_EN         = 0x11;
static const uint8_t REG_FSAMPLE         = 0x12;
static const uint8_t REG_PD_LED_SELECT   = 0x14;
static const uint8_t REG_NUM_AVG         = 0x15;
static const uint8_t REG_INT_SEQ_A       = 0x17;
static const uint8_t REG_INT_SEQ_B       = 0x1D;
static const uint8_t REG_ILED1_COARSE    = 0x23;
static const uint8_t REG_SLOTA_NUMPULSES = 0x31;
static const uint8_t REG_SLOTB_NUMPULSES = 0x36;
static const uint8_t REG_SLOTA_AFE_WINDOW= 0x39;
static const uint8_t REG_SLOTB_AFE_WINDOW= 0x3B;
static const uint8_t REG_SAMPLE_CLK      = 0x4B;
static const uint8_t REG_CLK32M_ADJUST   = 0x4D;
static const uint8_t REG_CLK32M_CAL_EN   = 0x50;
static const uint8_t REG_MATH            = 0x58;
static const uint8_t REG_DATA_ACCESS_CTL = 0x5F;
static const uint8_t REG_FIFO_ACCESS     = 0x60;

// Register field masks / constants.
static const uint16_t DEVICE_ID_ADPD1080 = 0x0A16;
static const uint16_t MODE_STANDBY = 0;
static const uint16_t MODE_PROGRAM = 1;
static const uint16_t MODE_NORMAL  = 2;

static const uint16_t SAMPLE_CLK_32K_ENABLE = 0x0080;
static const uint16_t SAMPLE_CLK_32K_ADJUST_MASK = 0x003F;
static const uint16_t SLOT_A_ENABLE = 0x0001;
static const uint16_t SLOT_A_FIFO_MASK = 0x001C;
static const uint16_t SLOT_B_ENABLE = 0x0020;
static const uint16_t SLOT_B_FIFO_MASK = 0x01C0;
static const uint16_t SLOT_FIFO_32BIT_4CHAN = 0x0006;
static const uint16_t SLOT_READOUT_MODE = 0x2000;
static const uint16_t SLOT_FIFO_OVERRUN_PREVENT = 0x1000;

// GPIO0 output configuration used during the ADI 1 kHz calibration routine.
static const uint16_t GPIO0_ENABLE = 0x0004;
static const uint16_t GPIO0_ACTIVE_PULSE_FUNCTION = 0x0002;

// The ADI driver reports the FIFO occupancy in the upper byte of STATUS.
static const uint8_t FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE = 32;

// -----------------------------------------------------------------------------
// Error reporting
// -----------------------------------------------------------------------------
static void stopWithError(const char *message)
{
  Serial.println();
  Serial.print("FATAL: ");
  Serial.println(message);
  while (true) {
    delay(1000);
  }
}

// -----------------------------------------------------------------------------
// Low-level I2C register access
// ADPD registers are 16-bit, most-significant byte first.
// -----------------------------------------------------------------------------
static bool writeRegister(uint8_t reg, uint16_t value)
{
  Wire.beginTransmission(ADPD1080_I2C_ADDRESS);
  Wire.write(reg);
  Wire.write((uint8_t)(value >> 8));
  Wire.write((uint8_t)(value & 0xFF));
  return (Wire.endTransmission() == 0);
}

static bool readRegister(uint8_t reg, uint16_t &value)
{
  Wire.beginTransmission(ADPD1080_I2C_ADDRESS);
  Wire.write(reg);
  if (Wire.endTransmission(false) != 0) {
    return false;
  }

  const uint8_t received = Wire.requestFrom(
      (uint8_t)ADPD1080_I2C_ADDRESS, (uint8_t)2, (uint8_t)true);
  if (received != 2 || Wire.available() < 2) {
    while (Wire.available()) {
      (void)Wire.read();
    }
    return false;
  }

  const uint8_t msb = (uint8_t)Wire.read();
  const uint8_t lsb = (uint8_t)Wire.read();
  value = ((uint16_t)msb << 8) | lsb;
  return true;
}

static bool updateRegister(uint8_t reg, uint16_t clearMask, uint16_t setBits)
{
  uint16_t value;
  if (!readRegister(reg, value)) {
    return false;
  }
  value = (uint16_t)((value & (uint16_t)~clearMask) | setBits);
  return writeRegister(reg, value);
}

static bool setMode(uint16_t mode)
{
  return writeRegister(REG_MODE, (uint16_t)(mode & 0x0003));
}

// The ADI driver's ADC-rate helper uses integer division:
// FSAMPLE = 32000 / (requested_rate * 4).
static bool setAdcSampleRate(uint16_t requestedRateHz)
{
  if (requestedRateHz == 0 || requestedRateHz > 2000) {
    return false;
  }
  const uint16_t fsample = (uint16_t)(32000UL / ((uint32_t)requestedRateHz * 4UL));
  return writeRegister(REG_FSAMPLE, fsample);
}

// -----------------------------------------------------------------------------
// 32 kHz/sample-clock calibration
//
// The ADI no-OS sample configures GPIO0 as an active-pulse output while the
// ADC sampling rate is set to 1 kHz.  The ESP32 counts rising edges for one
// second and adjusts SAMPLE_CLK until the count is closest to 1000.
// -----------------------------------------------------------------------------
static volatile uint32_t g_gpio0PulseCount = 0;

void IRAM_ATTR onCn0569IntRise()
{
  g_gpio0PulseCount++;
}

static uint32_t countGpioPulsesForOneSecond()
{
  noInterrupts();
  g_gpio0PulseCount = 0;
  interrupts();

  const uint64_t startUs = (uint64_t)esp_timer_get_time();
  while (((uint64_t)esp_timer_get_time() - startUs) < 1000000ULL) {
    delay(1);
  }

  noInterrupts();
  const uint32_t count = g_gpio0PulseCount;
  interrupts();
  return count;
}

static bool calibrate32kClock()
{
  Serial.println("Calibrating ADPD1080 sample clock using P1 INT...");

  if (!setAdcSampleRate(1000)) {
    return false;
  }
  if (!writeRegister(REG_GPIO_DRV, GPIO0_ENABLE)) {
    return false;
  }
  if (!writeRegister(REG_GPIO_CTRL, GPIO0_ACTIVE_PULSE_FUNCTION)) {
    return false;
  }
  if (!setMode(MODE_NORMAL)) {
    return false;
  }

  pinMode(CN0569_INT_PIN, INPUT);
  g_gpio0PulseCount = 0;
  attachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN), onCn0569IntRise, RISING);

  uint16_t sampleClockReg;
  if (!readRegister(REG_SAMPLE_CLK, sampleClockReg)) {
    detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));
    return false;
  }

  uint8_t currentAdjust = (uint8_t)(sampleClockReg & SAMPLE_CLK_32K_ADJUST_MASK);
  uint8_t bestAdjust = currentAdjust;
  uint32_t bestDifference = UINT32_MAX;

  for (uint8_t step = 0; step < MAX_32K_CALIBRATION_STEPS; step++) {
    const uint32_t pulseCount = countGpioPulsesForOneSecond();
    const uint32_t difference = (pulseCount > 1000U)
                                  ? (pulseCount - 1000U)
                                  : (1000U - pulseCount);

    Serial.print("  calibration pulse count = ");
    Serial.print(pulseCount);
    Serial.print("; error = ");
    Serial.println(difference);

    if (pulseCount == 0) {
      Serial.println("No INT pulses were counted. Check P1 pin 1 -> ESP32 GPIO 13.");
      detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));
      return false;
    }

    // Retain the best trim code.  Like the ADI routine, stop as soon as a
    // one-step adjustment no longer improves the measured 1 kHz pulse count.
    if (difference >= bestDifference) {
      break;
    }

    bestDifference = difference;
    bestAdjust = currentAdjust;

    if (difference == 0) {
      break;
    }

    int16_t nextAdjust = (int16_t)currentAdjust;
    if (pulseCount < 1000U) {
      nextAdjust--;
    } else {
      nextAdjust++;
    }

    if (nextAdjust < 0 || nextAdjust > 63) {
      break;
    }

    sampleClockReg = (uint16_t)((sampleClockReg & (uint16_t)~SAMPLE_CLK_32K_ADJUST_MASK)
                                | (uint16_t)nextAdjust);
    if (!writeRegister(REG_SAMPLE_CLK, sampleClockReg)) {
      detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));
      return false;
    }
    currentAdjust = (uint8_t)nextAdjust;
    delay(5);
  }

  detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));

  // Restore the best trim value, even if the final test was worse.
  if (!readRegister(REG_SAMPLE_CLK, sampleClockReg)) {
    return false;
  }
  sampleClockReg = (uint16_t)((sampleClockReg & (uint16_t)~SAMPLE_CLK_32K_ADJUST_MASK)
                              | bestAdjust);
  if (!writeRegister(REG_SAMPLE_CLK, sampleClockReg)) {
    return false;
  }

  if (!setMode(MODE_PROGRAM)) {
    return false;
  }
  if (!setAdcSampleRate(16)) {
    return false;
  }
  if (!writeRegister(REG_GPIO_DRV, 0x0000)) {
    return false;
  }
  if (!writeRegister(REG_GPIO_CTRL, 0x0000)) {
    return false;
  }

  Serial.print("32 kHz/sample-clock trim selected: 0x");
  Serial.println(bestAdjust, HEX);
  return true;
}

// -----------------------------------------------------------------------------
// Internal 32 MHz clock calibration, matching adpd188_clk32mhz_cal().
// This must follow the 32 kHz calibration.
// -----------------------------------------------------------------------------
static bool calibrate32MHzClock()
{
  uint16_t value;

  if (!readRegister(REG_DATA_ACCESS_CTL, value)) {
    return false;
  }
  if (!writeRegister(REG_DATA_ACCESS_CTL, (uint16_t)(value | 0x0001))) {
    return false;
  }

  if (!readRegister(REG_CLK32M_CAL_EN, value)) {
    return false;
  }
  if (!writeRegister(REG_CLK32M_CAL_EN, (uint16_t)(value | 0x0020))) {
    return false;
  }

  delay(1);

  if (!readRegister(REG_CLK_RATIO, value)) {
    return false;
  }
  const uint16_t clockRatio = (uint16_t)(value & 0x0FFF);
  const float clockError = 32000000.0f * (1.0f - ((float)clockRatio / 2000.0f));

  // ADPD1080/ADPD1081 use the 112000 divisor in the ADI driver.  Casting the
  // signed result to uint8_t gives the same low-byte adjustment written there.
  const int32_t signedAdjustment = (int32_t)(clockError / 112000.0f);
  const uint8_t adjustment = (uint8_t)signedAdjustment;

  if (!writeRegister(REG_CLK32M_ADJUST, adjustment)) {
    return false;
  }

  if (!readRegister(REG_CLK32M_CAL_EN, value)) {
    return false;
  }
  if (!writeRegister(REG_CLK32M_CAL_EN, (uint16_t)(value & (uint16_t)~0x0020))) {
    return false;
  }

  if (!readRegister(REG_DATA_ACCESS_CTL, value)) {
    return false;
  }
  if (!writeRegister(REG_DATA_ACCESS_CTL, (uint16_t)(value & (uint16_t)~0x0001))) {
    return false;
  }

  Serial.print("32 MHz clock adjustment: 0x");
  Serial.println(adjustment, HEX);
  return true;
}

// -----------------------------------------------------------------------------
// Device setup: directly follows adpd188_iio_init() and iio_example.c.
// -----------------------------------------------------------------------------
static bool configureAdpd1080()
{
  uint16_t value;

  // Verify the silicon ID before issuing the software reset.
  if (!readRegister(REG_DEVID, value)) {
    Serial.println("Could not read ADPD1080 device ID. Check power, wiring and I2C address.");
    return false;
  }
  Serial.print("ADPD device ID: 0x");
  Serial.println(value, HEX);
  if (value != DEVICE_ID_ADPD1080) {
    Serial.println("Unexpected device ID (expected 0x0A16 for ADPD1080).");
    return false;
  }

  if (!writeRegister(REG_SW_RESET, 0x0001)) {
    return false;
  }
  delay(10);

  // Enable the ADPD1080 state-machine clock, then enter program mode.
  if (!readRegister(REG_SAMPLE_CLK, value)) {
    return false;
  }
  if (!writeRegister(REG_SAMPLE_CLK, (uint16_t)(value | SAMPLE_CLK_32K_ENABLE))) {
    return false;
  }
  if (!setMode(MODE_PROGRAM)) {
    return false;
  }

  // Enable slots A and B, each with 32-bit FIFO words for all four channels.
  if (!readRegister(REG_SLOT_EN, value)) {
    return false;
  }
  value &= (uint16_t)~(SLOT_A_ENABLE | SLOT_A_FIFO_MASK | SLOT_B_ENABLE | SLOT_B_FIFO_MASK);
  value |= SLOT_A_ENABLE | (SLOT_FIFO_32BIT_4CHAN << 2);
  value |= SLOT_B_ENABLE | (SLOT_FIFO_32BIT_4CHAN << 6);
  if (!writeRegister(REG_SLOT_EN, value)) {
    return false;
  }

  // Slot A selects photodiodes 1-4; Slot B selects photodiodes 5-8.
  // LED selector 1 selects LEDX1 (the CN0569's on-board IR LED on its default build).
  if (!readRegister(REG_PD_LED_SELECT, value)) {
    return false;
  }
  value &= (uint16_t)~0x0FFF;
  value |= (uint16_t)(1U | (1U << 2) | (5U << 4) | (4U << 8));
  if (!writeRegister(REG_PD_LED_SELECT, value)) {
    return false;
  }

  // Disable averaging / decimation for both slots.
  if (!writeRegister(REG_NUM_AVG, 0x0000)) {
    return false;
  }

  // Initial ADC rate used by the ADI example before calibration.
  if (!setAdcSampleRate(16)) {
    return false;
  }

  // Enable the readout mode and FIFO overflow-prevention feature.
  if (!updateRegister(REG_SLOT_EN, 0x0000,
                      SLOT_READOUT_MODE | SLOT_FIFO_OVERRUN_PREVENT)) {
    return false;
  }

  // Chop sequence: inverted, non-inverted, non-inverted, inverted.
  if (!updateRegister(REG_INT_SEQ_A, 0x0000, 0x0009)) {
    return false;
  }
  if (!updateRegister(REG_INT_SEQ_B, 0x0000, 0x0009)) {
    return false;
  }

  // LED1 coarse current, slew and scale settings from the ADI example.
  // The CN0569's LED1 driver sinks current for the on-board IR LED by default.
  if (!readRegister(REG_ILED1_COARSE, value)) {
    return false;
  }
  value &= (uint16_t)~(0x000F | 0x0070);
  value |= (uint16_t)(0x0006 | (0x0003 << 4) | 0x2000);
  if (!writeRegister(REG_ILED1_COARSE, value)) {
    return false;
  }

  // Four LED pulses per slot, with period code 0x0E (15 us per ADI comment).
  // The pulse-count and period fields occupy the complete 16-bit registers.
  if (!writeRegister(REG_SLOTA_NUMPULSES, 0x040E)) {
    return false;
  }
  if (!writeRegister(REG_SLOTB_NUMPULSES, 0x040E)) {
    return false;
  }

  // AFE integration windows: width 4, offset 0x2F0, for both slots.
  if (!writeRegister(REG_SLOTA_AFE_WINDOW, 0x22F0)) {
    return false;
  }
  if (!writeRegister(REG_SLOTB_AFE_WINDOW, 0x22F0)) {
    return false;
  }

  // Math/chop configuration used by the ADI example.
  if (!updateRegister(REG_MATH, 0x0F66, 0x0544)) {
    return false;
  }

  return true;
}

// -----------------------------------------------------------------------------
// FIFO acquisition: one frame contains 16 x 16-bit FIFO words:
// (low word, high word) for each of eight 32-bit photodiode values.
// -----------------------------------------------------------------------------
static bool readOneEightChannelSample(uint32_t samples[8])
{
  const uint32_t startMs = millis();
  uint16_t status;

  while (true) {
    if (!readRegister(REG_STATUS, status)) {
      return false;
    }

    const uint8_t fifoBytes = (uint8_t)((status >> 8) & 0xFF);
    if (fifoBytes >= FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE) {
      break;
    }

    if ((uint32_t)(millis() - startMs) >= FIFO_WAIT_TIMEOUT_MS) {
      Serial.println("Timed out waiting for a complete FIFO sample.");
      return false;
    }
    delay(1);
  }

  uint16_t fifoWords[16];
  for (uint8_t i = 0; i < 16; i++) {
    if (!readRegister(REG_FIFO_ACCESS, fifoWords[i])) {
      return false;
    }
  }

  for (uint8_t channel = 0; channel < 8; channel++) {
    const uint32_t lowWord = (uint32_t)fifoWords[channel * 2];
    const uint32_t highWord = (uint32_t)fifoWords[channel * 2 + 1];
    // The ADI IIO channel definition uses 27 meaningful bits in 32-bit storage.
    samples[channel] = (lowWord | (highWord << 16)) & 0x07FFFFFFUL;
  }

  return true;
}

static void printSample(const uint32_t samples[8])
{
  Serial.print((uint32_t)micros());
  for (uint8_t i = 0; i < 8; i++) {
    Serial.print(',');
    Serial.print(samples[i]);
  }
  Serial.println();
}

// -----------------------------------------------------------------------------
// Arduino entry points
// -----------------------------------------------------------------------------
void setup()
{
  Serial.begin(SERIAL_BAUD);
  delay(1500);

  Serial.println();
  Serial.println("CN0569 / ADPD1080 ESP32 acquisition example");
  Serial.println("Starting I2C at 400 kHz...");

  Wire.begin(CN0569_SDA_PIN, CN0569_SCL_PIN, I2C_CLOCK_HZ);
  Wire.setClock(I2C_CLOCK_HZ);

  if (!configureAdpd1080()) {
    stopWithError("ADPD1080 initialisation/configuration failed.");
  }

  if (!calibrate32kClock()) {
    stopWithError("32 kHz/sample-clock calibration failed. Check P1 INT to GPIO 13.");
  }

  if (!calibrate32MHzClock()) {
    stopWithError("32 MHz clock calibration failed.");
  }

  // Request the same rate as the no-OS example and enter continuous mode.
  if (!setAdcSampleRate(REQUESTED_SAMPLE_RATE_HZ)) {
    stopWithError("Could not set the ADC sample rate.");
  }

  uint16_t fsampleRegister;
  if (!readRegister(REG_FSAMPLE, fsampleRegister) || fsampleRegister == 0) {
    stopWithError("Could not read back the ADC sample-rate register.");
  }
  Serial.print("Requested sample rate: ");
  Serial.print(REQUESTED_SAMPLE_RATE_HZ);
  Serial.print(" Hz; FSAMPLE register: ");
  Serial.print(fsampleRegister);
  Serial.print("; ADI-driver nominal integer readback: ");
  Serial.print(32000UL / ((uint32_t)fsampleRegister * 4UL));
  Serial.println(" Hz");

  if (!setMode(MODE_NORMAL)) {
    stopWithError("Could not enter ADPD1080 normal measurement mode.");
  }

  Serial.println("timestamp_us,pd0,pd1,pd2,pd3,pd4,pd5,pd6,pd7");
}

void loop()
{
  uint32_t samples[8];
  if (!readOneEightChannelSample(samples)) {
    stopWithError("FIFO acquisition failed. Check I2C wiring and sensor power.");
  }
  printSample(samples);
}

image

I grabbed some “premium” Dupont-style jumper wires and connected the board’s PMOD header to my ESP32-S3 directly. To minimise mistakes, I combined the single-unit female sockets into a six-in-a-row so at least one side would be fixed – but note that Pin 1 of the Pmod (INT) is connected differently across some of the sketches.

image image

After an initial calibration, rapidly, the window scrolls with samples from the sensor at a rate of about 500Hz. That’s a lot of data!

image

At least, I’m getting something out of the sensor that does somewhat reflect the presence of a hand in the field-of-view and does react to motion. Actually, the raccoons seemingly have it right …

image

… because that’s what I’m seeing inside my own Arduino Serial Plotter. The values between the two photodiode packages were quite different and the first channel was not entirely happy, so I was a little concerned.

image

The datasheet does seem to suggest there’s quite a bit of difference between the two photodiode packages. I suppose it’s down to the different distance between the photodiodes and the IR LED package. I did notice the first channel acting a little odd too.

Not being sure what to make of it, I have to thank javagoza  for their post on Tiltie and the CN0569 where they identified a number of issues with the library’s initialisation and settings to improve the response. While I couldn’t access the linked repository in his post, GPT-6 Luna was able to understand the gist of it and implement it. After three or four prompts, I was able to get it to roll-in the code that computes the gesture and fix some performance issues due to the initially naïve implementation.

[CN0569_Tiltie_ESP32_Gesture.ino]

/*
 * CN0569 (ADPD1080 + 2 x ADPD2140) - ESP32 gesture sensor port
 * Ported by OpenAI's ChatGPT GPT-6 Luna guided by Gough Lui
 *
 * ESP32 adaptation of the ADI CN0569 data path, with sensor register
 * corrections and gesture-state/acquisition fixes from the element14 Tiltie
 * '04: Bringing Touch-Free Gesture Control to Tiltie with the CN0569' article
 * by @javagoza (https://community.element14.com/challenges-projects/
 * design-challenges/my-project-is-trash/f/forum/57465/tiltie---04-bringing-
 * touch-free-gesture-control-to-tiltie-with-the-cn0569). 
 * Much thanks to @javagoza for the tweaks - it didn't work well without them!
 *
 * Gesture algorithm copyright (C) 2021 Analog Devices, Inc.
 * SPDX-License-Identifier: ADIBSD
 *
 * Sensor corrections based on the Tiltie investigation:
 *   - preserve the 0x98 CLK32M_ADJUST base and ADD the signed correction;
 *   - use LED period 0x13 with the existing 4 us AFE width;
 *   - clear the eight actual per-channel ADC offset registers;
 *   - apply approximately 250 mV photodiode reverse bias;
 *   - set Slot A TIA gain to 50 kohm and Slot B to 200 kohm.
 *
 * Gesture-data fixes based on the same investigation:
 *   - both sensors are processed from the same acquired frame;
 *   - baseline and live data use the same eight-sample aggregation;
 *   - short gestures reset their state instead of leaving it armed;
 *   - gesture end position uses the last valid above-threshold frame.
 *
 * The sample rate remains the original 512 Hz request (FSAMPLE register
 * calculation inherited from ADI), and the AFE integration window, pulse
 * count, LED current, chop sequence and sampling cadence are otherwise kept.
 *
 * Connections (CN0569 P1 Pmod connector):
 *   P1-1 INT / ADPD1080 GPIO0 -> ESP32 GPIO 6
 *   P1-2 RESET                -> NC (not connected)
 *   P1-3 SCL                  -> ESP32 GPIO 5
 *   P1-4 SDA                  -> ESP32 GPIO 4
 *   P1-5 GND                  -> ESP32 GND
 *   P1-6 VCC                  -> regulated 3.3 V
 *
 * ADPD1080 I2C address: 0x64 (7-bit), 400 kHz. The ESP32 CPU is
 * not a limiting factor; the I2C/FIFO service cadence is the critical path.
 *
 * Output gesture strings match the ADI Python example:
 *   CLICK_0, UP_0, DOWN_0, LEFT_0, RIGHT_0
 *   CLICK_1, UP_1, DOWN_1, LEFT_1, RIGHT_1
 *
 * Note on buffering: the Tiltie driver aggregates eight consecutive FIFO
 * samples into one gesture frame. Both sensors are evaluated from that same
 * eight-channel frame; baseline calibration averages five such frames.
 */

#include <Arduino.h>
#include <Wire.h>
#include <esp_timer.h>
#include <math.h>
#include <stdio.h>  // snprintf() used for ADI-compatible gesture labels

struct GestureState; // Forward declaration of struct

// -----------------------------------------------------------------------------
// Connections and operating parameters
// -----------------------------------------------------------------------------
#define CN0569_SDA_PIN       4
#define CN0569_SCL_PIN       5
#define CN0569_INT_PIN       6   // CN0569 P1 pin 1: GPIO0 active-pulse output

static const uint8_t  ADPD1080_I2C_ADDRESS = 0x64;
static const uint32_t I2C_CLOCK_HZ = 400000;
static const uint16_t REQUESTED_SAMPLE_RATE_HZ = 512; // ADI iio_example.c sets 512 Hz
static const uint32_t FIFO_WAIT_TIMEOUT_MS = 1000;
static const uint8_t  MAX_32K_CALIBRATION_STEPS = 64;
static const uint32_t SERIAL_BAUD = 921600;

// These are the exact settings in ADI's Python gesture class.
static const uint8_t GESTURE_BUFFER_SAMPLES = 8;
static const uint8_t GAIN_CALIBRATION_BUFFERS = 5;
static const uint32_t GESTURE_INTENSITY_THRESHOLD = 1000;
static const float GESTURE_DISTANCE_THRESHOLD = 0.07f;
static const uint8_t GESTURE_MIN_ACTIVE_BUFFERS = 5;

// Set to 1 to print the aggregated eight-channel frame and calculated
// per-sensor intensity/position values for tuning. Leave at 0 for normal use.
#define CN0569_DEBUG_RAW_FRAMES 0

// -----------------------------------------------------------------------------
// ADPD1080 register addresses used by the existing sensor setup
// -----------------------------------------------------------------------------
static const uint8_t REG_STATUS           = 0x00;
static const uint8_t REG_GPIO_DRV         = 0x02;
static const uint8_t REG_DEVID            = 0x08;
static const uint8_t REG_CLK_RATIO        = 0x0A;
static const uint8_t REG_GPIO_CTRL        = 0x0B;
static const uint8_t REG_SW_RESET         = 0x0F;
static const uint8_t REG_MODE             = 0x10;
static const uint8_t REG_SLOT_EN          = 0x11;
static const uint8_t REG_FSAMPLE          = 0x12;
static const uint8_t REG_PD_LED_SELECT    = 0x14;
static const uint8_t REG_NUM_AVG          = 0x15;
static const uint8_t REG_INT_SEQ_A        = 0x17;
static const uint8_t REG_INT_SEQ_B        = 0x1D;
static const uint8_t REG_SLOTA_CH1_OFFSET = 0x18;
static const uint8_t REG_SLOTB_CH1_OFFSET = 0x1E;
static const uint8_t REG_ILED1_COARSE     = 0x23;
static const uint8_t REG_SLOTA_NUMPULSES  = 0x31;
static const uint8_t REG_SLOTB_NUMPULSES  = 0x36;
static const uint8_t REG_SLOTA_AFE_WINDOW = 0x39;
static const uint8_t REG_SLOTB_AFE_WINDOW = 0x3B;
static const uint8_t REG_SLOTA_TIA_CFG    = 0x42;
static const uint8_t REG_SLOTB_TIA_CFG    = 0x44;
static const uint8_t REG_SAMPLE_CLK       = 0x4B;
static const uint8_t REG_CLK32M_ADJUST    = 0x4D;
static const uint8_t REG_CLK32M_CAL_EN    = 0x50;
static const uint8_t REG_MATH             = 0x58;
static const uint8_t REG_AFE_PWR_CFG2    = 0x54;
static const uint8_t REG_DATA_ACCESS_CTL = 0x5F;
static const uint8_t REG_FIFO_ACCESS      = 0x60;

static const uint16_t DEVICE_ID_ADPD1080 = 0x0A16;
static const uint16_t MODE_PROGRAM = 1;
static const uint16_t MODE_NORMAL  = 2;
static const uint16_t SAMPLE_CLK_32K_ADJUST_MASK = 0x003F;
static const uint16_t SLOT_READOUT_MODE = 0x2000;
static const uint16_t SLOT_FIFO_OVERRUN_PREVENT = 0x1000;
static const uint16_t GPIO0_ENABLE = 0x0004;
static const uint16_t GPIO0_ACTIVE_PULSE_FUNCTION = 0x0002;
static const uint8_t FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE = 32;

// -----------------------------------------------------------------------------
// Low-level I2C register access (16-bit, MSB first)
// -----------------------------------------------------------------------------
static bool writeRegister(uint8_t reg, uint16_t value)
{
  Wire.beginTransmission(ADPD1080_I2C_ADDRESS);
  Wire.write(reg);
  Wire.write((uint8_t)(value >> 8));
  Wire.write((uint8_t)(value & 0xFF));
  return Wire.endTransmission() == 0;
}

static bool readRegister(uint8_t reg, uint16_t &value)
{
  Wire.beginTransmission(ADPD1080_I2C_ADDRESS);
  Wire.write(reg);
  if (Wire.endTransmission(false) != 0) return false;

  const uint8_t received = Wire.requestFrom(
      (uint8_t)ADPD1080_I2C_ADDRESS, (uint8_t)2, (uint8_t)true);
  if (received != 2 || Wire.available() < 2) {
    while (Wire.available()) (void)Wire.read();
    return false;
  }
  const uint8_t msb = (uint8_t)Wire.read();
  const uint8_t lsb = (uint8_t)Wire.read();
  value = ((uint16_t)msb << 8) | lsb;
  return true;
}

static bool updateRegister(uint8_t reg, uint16_t clearMask, uint16_t setBits)
{
  uint16_t value;
  if (!readRegister(reg, value)) return false;
  value = (uint16_t)((value & (uint16_t)~clearMask) | setBits);
  return writeRegister(reg, value);
}

static bool setMode(uint16_t mode)
{
  return writeRegister(REG_MODE, (uint16_t)(mode & 0x0003));
}

static bool setAdcSampleRate(uint16_t requestedRateHz)
{
  if (requestedRateHz == 0 || requestedRateHz > 2000) return false;
  const uint16_t fsample = (uint16_t)(32000UL / ((uint32_t)requestedRateHz * 4UL));
  return writeRegister(REG_FSAMPLE, fsample);
}

static void stopWithError(const char *message)
{
  Serial.println();
  Serial.print("FATAL: ");
  Serial.println(message);
  while (true) delay(1000);
}

// -----------------------------------------------------------------------------
// 32 kHz sample-clock calibration using the P1 INT / GPIO0 connection
// -----------------------------------------------------------------------------
static volatile uint32_t g_gpio0PulseCount = 0;

void IRAM_ATTR onCn0569IntRise()
{
  // Avoid deprecated volatile ++ syntax on newer Arduino toolchains.
  const uint32_t currentCount = g_gpio0PulseCount;
  g_gpio0PulseCount = currentCount + 1U;
}

static uint32_t countGpioPulsesForOneSecond()
{
  noInterrupts();
  g_gpio0PulseCount = 0;
  interrupts();

  const uint64_t startUs = (uint64_t)esp_timer_get_time();
  while (((uint64_t)esp_timer_get_time() - startUs) < 1000000ULL) delay(1);

  noInterrupts();
  const uint32_t count = g_gpio0PulseCount;
  interrupts();
  return count;
}

static bool calibrate32kClock()
{
  Serial.println("Calibrating ADPD1080 sample clock on INT/GPIO0...");
  if (!setAdcSampleRate(1000)) return false;
  if (!writeRegister(REG_GPIO_DRV, GPIO0_ENABLE)) return false;
  if (!writeRegister(REG_GPIO_CTRL, GPIO0_ACTIVE_PULSE_FUNCTION)) return false;
  if (!setMode(MODE_NORMAL)) return false;

  pinMode(CN0569_INT_PIN, INPUT);
  g_gpio0PulseCount = 0;
  attachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN), onCn0569IntRise, RISING);

  uint16_t sampleClockReg;
  if (!readRegister(REG_SAMPLE_CLK, sampleClockReg)) {
    detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));
    return false;
  }

  uint8_t currentAdjust = (uint8_t)(sampleClockReg & SAMPLE_CLK_32K_ADJUST_MASK);
  uint8_t bestAdjust = currentAdjust;
  uint32_t bestDifference = UINT32_MAX;

  for (uint8_t step = 0; step < MAX_32K_CALIBRATION_STEPS; step++) {
    const uint32_t pulseCount = countGpioPulsesForOneSecond();
    const uint32_t difference = (pulseCount > 1000U)
                                  ? pulseCount - 1000U : 1000U - pulseCount;
    Serial.print("  INT pulses: ");
    Serial.print(pulseCount);
    Serial.print("; error: ");
    Serial.println(difference);

    if (pulseCount == 0) {
      Serial.println("No INT pulses; check CN0569 P1 pin 1 to ESP32 GPIO 6.");
      detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));
      return false;
    }
    if (difference >= bestDifference) break;

    bestDifference = difference;
    bestAdjust = currentAdjust;
    if (difference == 0) break;

    int16_t nextAdjust = (int16_t)currentAdjust;
    if (pulseCount < 1000U) nextAdjust--;
    else nextAdjust++;
    if (nextAdjust < 0 || nextAdjust > 63) break;

    sampleClockReg = (uint16_t)((sampleClockReg & (uint16_t)~SAMPLE_CLK_32K_ADJUST_MASK)
                                | (uint16_t)nextAdjust);
    if (!writeRegister(REG_SAMPLE_CLK, sampleClockReg)) {
      detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));
      return false;
    }
    currentAdjust = (uint8_t)nextAdjust;
    delay(5);
  }

  detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));
  if (!readRegister(REG_SAMPLE_CLK, sampleClockReg)) return false;
  sampleClockReg = (uint16_t)((sampleClockReg & (uint16_t)~SAMPLE_CLK_32K_ADJUST_MASK)
                              | bestAdjust);
  if (!writeRegister(REG_SAMPLE_CLK, sampleClockReg)) return false;
  if (!setMode(MODE_PROGRAM)) return false;
  if (!setAdcSampleRate(16)) return false;
  if (!writeRegister(REG_GPIO_DRV, 0x0000)) return false;
  if (!writeRegister(REG_GPIO_CTRL, 0x0000)) return false;

  Serial.print("32 kHz/sample-clock trim: 0x");
  Serial.println(bestAdjust, HEX);
  return true;
}

// -----------------------------------------------------------------------------
// Internal 32 MHz clock calibration (same sequence as the preceding sketch)
// -----------------------------------------------------------------------------
static bool calibrate32MHzClock()
{
  uint16_t value;
  if (!readRegister(REG_DATA_ACCESS_CTL, value)) return false;
  if (!writeRegister(REG_DATA_ACCESS_CTL, (uint16_t)(value | 0x0001))) return false;
  if (!readRegister(REG_CLK32M_CAL_EN, value)) return false;
  if (!writeRegister(REG_CLK32M_CAL_EN, (uint16_t)(value | 0x0020))) return false;
  delay(1);

  if (!readRegister(REG_CLK_RATIO, value)) return false;
  const uint16_t clockRatio = (uint16_t)(value & 0x0FFF);
  const float clockError = 32000000.0f * (1.0f - ((float)clockRatio / 2000.0f));
  const int32_t correction = (int32_t)(clockError / 112000.0f);

  // REG_CLK32M_ADJUST resets to 0x98. The signed calibration correction is
  // a delta from that trim value; writing the signed delta itself causes
  // negative corrections to wrap (e.g. -14 -> 0xF2) and over-speed the clock.
  uint16_t trimBase;
  if (!readRegister(REG_CLK32M_ADJUST, trimBase)) return false;
  const int32_t adjustedTrim = (int32_t)(trimBase & 0x00FF) + correction;
  if (adjustedTrim < 0 || adjustedTrim > 0xFF) {
    Serial.println("32 MHz clock correction is outside the register range.");
    return false;
  }
  const uint8_t adjustment = (uint8_t)adjustedTrim;
  if (!writeRegister(REG_CLK32M_ADJUST, adjustment)) return false;

  if (!readRegister(REG_CLK32M_CAL_EN, value)) return false;
  if (!writeRegister(REG_CLK32M_CAL_EN, (uint16_t)(value & (uint16_t)~0x0020))) return false;
  if (!readRegister(REG_DATA_ACCESS_CTL, value)) return false;
  if (!writeRegister(REG_DATA_ACCESS_CTL, (uint16_t)(value & (uint16_t)~0x0001))) return false;

  Serial.print("32 MHz clock ratio: ");
  Serial.println(clockRatio);
  Serial.print("32 MHz trim base: 0x");
  Serial.println(trimBase & 0x00FF, HEX);
  Serial.print("32 MHz trim correction: ");
  Serial.println(correction);
  Serial.print("32 MHz final adjustment: 0x");
  Serial.println(adjustment, HEX);
  return true;
}

// -----------------------------------------------------------------------------
// Sensor initialisation. Base setup follows ADI's iio_adpd1080 example;
// hardware corrections follow the Tiltie investigation described above.
// -----------------------------------------------------------------------------
static bool configureAdpd1080()
{
  uint16_t value;
  if (!readRegister(REG_DEVID, value)) {
    Serial.println("Could not read ADPD1080 device ID; check wiring and power.");
    return false;
  }
  Serial.print("ADPD device ID: 0x");
  Serial.println(value, HEX);
  if (value != DEVICE_ID_ADPD1080) return false;

  if (!writeRegister(REG_SW_RESET, 0x0001)) return false;
  delay(10);

  // Enable the 32 kHz state-machine clock before programming slots.
  if (!readRegister(REG_SAMPLE_CLK, value)) return false;
  value |= 0x0080;
  if (!writeRegister(REG_SAMPLE_CLK, value)) return false;
  if (!setMode(MODE_PROGRAM)) return false;

  // Enable both time slots with four 32-bit photodiode channels in each FIFO
  // packet. A complete packet is 8 channels x 32 bits = 32 bytes.
  if (!readRegister(REG_SLOT_EN, value)) return false;
  value &= (uint16_t)~(0x0001 | 0x001C | 0x0020 | 0x01C0);
  value |= (uint16_t)(0x0001 | (0x0006 << 2) | 0x0020 | (0x0006 << 6));
  if (!writeRegister(REG_SLOT_EN, value)) return false;

  // Select LEDX1 for both slots; PD1-4 in A and PD5-8 in B.
  if (!readRegister(REG_PD_LED_SELECT, value)) return false;
  value &= (uint16_t)~0x0FFF;
  value |= (uint16_t)(0x0001 | (0x0001 << 2) | (0x0005 << 4) | (0x0004 << 8));
  if (!writeRegister(REG_PD_LED_SELECT, value)) return false;

  // No decimation/averaging in either slot.
  if (!writeRegister(REG_NUM_AVG, 0x0000)) return false;

  // Integrator chop sequence: inverted, normal, normal, inverted.
  if (!updateRegister(REG_INT_SEQ_A, 0x0000, 0x0009)) return false;
  if (!updateRegister(REG_INT_SEQ_B, 0x0000, 0x0009)) return false;

  // In integrator chop mode, zero the eight real channel-offset registers.
  // 0x1C and 0x1D are NOT offset registers; they are BG_MEAS_B and INT_SEQ_B.
  for (uint8_t i = 0; i < 4; i++) {
    if (!writeRegister((uint8_t)(REG_SLOTA_CH1_OFFSET + i), 0x0000)) return false;
    if (!writeRegister((uint8_t)(REG_SLOTB_CH1_OFFSET + i), 0x0000)) return false;
  }

  // LED1 coarse current and slew retain the established ADI example setting.
  if (!readRegister(REG_ILED1_COARSE, value)) return false;
  value &= (uint16_t)~(0x000F | 0x0070);
  value |= (uint16_t)(0x0006 | (0x0003 << 4) | 0x2000);
  if (!writeRegister(REG_ILED1_COARSE, value)) return false;

  // Keep four pulses and the 4 us AFE width/0x2F0 offset. Only change the
  // period low byte from 0x0E to the datasheet-compliant 0x13.
  if (!writeRegister(REG_SLOTA_NUMPULSES, 0x0413)) return false;
  if (!writeRegister(REG_SLOTB_NUMPULSES, 0x0413)) return false;
  if (!writeRegister(REG_SLOTA_AFE_WINDOW, 0x22F0)) return false;
  if (!writeRegister(REG_SLOTB_AFE_WINDOW, 0x22F0)) return false;

  // The Tiltie settings use 50 kohm for the closer Slot A sensor and the
  // default 200 kohm for Slot B. Change only TIA_GAIN bits [1:0].
  if (!updateRegister(REG_SLOTA_TIA_CFG, 0x0003, 0x0002)) return false;
  if (!updateRegister(REG_SLOTB_TIA_CFG, 0x0003, 0x0000)) return false;

  // Apply about 250 mV reverse bias to both photodiodes using the override.
  if (!writeRegister(REG_AFE_PWR_CFG2, 0x0AA0)) return false;

  // Original integrator-chop math setup.
  if (!updateRegister(REG_MATH, 0x0F66, 0x0544)) return false;

  // Enable FIFO readout and FIFO overrun prevention without disturbing slot
  // enable/FIFO-format fields.
  if (!readRegister(REG_SLOT_EN, value)) return false;
  value |= SLOT_READOUT_MODE | SLOT_FIFO_OVERRUN_PREVENT;
  if (!writeRegister(REG_SLOT_EN, value)) return false;

  // Useful configuration readback for the first hardware validation.
  const uint8_t regs[] = {REG_SAMPLE_CLK, REG_SLOT_EN, REG_PD_LED_SELECT,
                          REG_SLOTA_NUMPULSES, REG_SLOTB_NUMPULSES,
                          REG_SLOTA_TIA_CFG, REG_SLOTB_TIA_CFG,
                          REG_AFE_PWR_CFG2};
  const char *names[] = {"SAMPLE_CLK", "SLOT_EN", "PD_LED_SELECT",
                         "SLOTA_NUMPULSES", "SLOTB_NUMPULSES",
                         "SLOTA_TIA_CFG", "SLOTB_TIA_CFG", "AFE_PWR_CFG2"};
  for (uint8_t i = 0; i < sizeof(regs); i++) {
    if (!readRegister(regs[i], value)) return false;
    Serial.print(names[i]);
    Serial.print(" = 0x");
    Serial.println(value, HEX);
  }
  return true;
}

// -----------------------------------------------------------------------------
// One simultaneous 8-photodiode sample from the ADPD1080 FIFO
// -----------------------------------------------------------------------------
static bool readOneEightChannelSample(uint32_t samples[8])
{
  const uint32_t startMs = millis();
  uint16_t status;

  // Wait for one complete 32-byte packet (8 channels x 32 bits).
  while (true) {
    if (!readRegister(REG_STATUS, status)) return false;
    const uint8_t fifoBytes = (uint8_t)((status >> 8) & 0xFF);
    if (fifoBytes >= FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE) break;
    if ((uint32_t)(millis() - startMs) >= FIFO_WAIT_TIMEOUT_MS) {
      Serial.println("Timed out waiting for FIFO data.");
      return false;
    }
    delay(1);
  }

  // ADPD1080 supports multiword reads from FIFO_ACCESS: each acknowledged
  // 16-bit word advances the FIFO. Read the full 32-byte packet in ONE I2C
  // transaction instead of sixteen independent register transactions. This
  // substantially reduces bus overhead and helps avoid FIFO overrun at 512 Hz.
  Wire.beginTransmission(ADPD1080_I2C_ADDRESS);
  Wire.write(REG_FIFO_ACCESS);
  if (Wire.endTransmission(false) != 0) return false;

  uint8_t fifoBytes[32];
  const uint8_t received = Wire.requestFrom(
      (uint8_t)ADPD1080_I2C_ADDRESS, (uint8_t)sizeof(fifoBytes), (uint8_t)true);
  if (received != sizeof(fifoBytes)) {
    while (Wire.available()) (void)Wire.read();
    Serial.print("Incomplete FIFO burst read: received ");
    Serial.print(received);
    Serial.println(" of 32 bytes.");
    return false;
  }

  for (uint8_t i = 0; i < sizeof(fifoBytes); i++) {
    if (!Wire.available()) {
      Serial.println("FIFO burst ended before all 32 bytes were received.");
      return false;
    }
    fifoBytes[i] = (uint8_t)Wire.read();
  }

  for (uint8_t channel = 0; channel < 8; channel++) {
    const uint8_t offset = (uint8_t)(channel * 4);
    // Each FIFO word is transmitted MSB first. The first 16-bit word holds
    // the low half of the channel result; the second holds the high half.
    const uint16_t lowWord = ((uint16_t)fifoBytes[offset] << 8) |
                             (uint16_t)fifoBytes[offset + 1];
    const uint16_t highWord = ((uint16_t)fifoBytes[offset + 2] << 8) |
                              (uint16_t)fifoBytes[offset + 3];
    samples[channel] = ((uint32_t)lowWord | ((uint32_t)highWord << 16)) &
                       0x07FFFFFFUL;
  }
  return true;
}

// Read eight consecutive complete FIFO packets and sum each of the eight
// channels. This is one gesture-engine frame (~64 frames/s at 512 samples/s;
// the inherited integer FSAMPLE calculation can produce a slightly different
// actual rate, which setup() reports).
// Both ADPD2140 sensors are carried in the same frame so they are evaluated
// against the same physical acquisition interval.
static bool readAveragedFrame(uint32_t frame[8])
{
  uint64_t channelSums[8] = {0, 0, 0, 0, 0, 0, 0, 0};
  uint32_t sample[8];

  for (uint8_t n = 0; n < GESTURE_BUFFER_SAMPLES; n++) {
    if (!readOneEightChannelSample(sample)) return false;
    for (uint8_t ch = 0; ch < 8; ch++) {
      channelSums[ch] += sample[ch];
    }
  }

  for (uint8_t ch = 0; ch < 8; ch++) {
    // The Tiltie driver aggregates the eight raw samples by summing them.
    if (channelSums[ch] > UINT32_MAX) return false;
    frame[ch] = (uint32_t)channelSums[ch];
  }
  return true;
}

// -----------------------------------------------------------------------------
// Faithful port of Analog Devices' Python class:
// adpd2140_gesture_sensor.py
// -----------------------------------------------------------------------------
struct GestureState {
  bool active;
  uint8_t activeFrames;
  float startX;
  float startY;
  float lastValidX;
  float lastValidY;

  GestureState()
    : active(false), activeFrames(0), startX(0.0f), startY(0.0f),
      lastValidX(0.0f), lastValidY(0.0f) {}
};

// Per-channel baseline uses the same eight-sample sum as the live frame.
static uint32_t channelBaselineAverage[8] = {0, 0, 0, 0, 0, 0, 0, 0};
static GestureState gestureSensor0;
static GestureState gestureSensor1;

// Average five quiet eight-sample frames. Keep the hand away during this step.
static bool gainCalibration()
{
  uint64_t accumulated[8] = {0, 0, 0, 0, 0, 0, 0, 0};
  uint32_t frame[8];

  Serial.println("Baseline calibration: keep the sensor field clear...");
  for (uint8_t n = 0; n < GAIN_CALIBRATION_BUFFERS; n++) {
    if (!readAveragedFrame(frame)) return false;
    for (uint8_t ch = 0; ch < 8; ch++) accumulated[ch] += frame[ch];
  }
  for (uint8_t ch = 0; ch < 8; ch++) {
    channelBaselineAverage[ch] = (uint32_t)(accumulated[ch] / GAIN_CALIBRATION_BUFFERS);
  }

  Serial.println("Baseline calibration complete. Channel baselines:");
  for (uint8_t ch = 0; ch < 8; ch++) {
    Serial.print("  ch"); Serial.print(ch); Serial.print(" = ");
    Serial.println(channelBaselineAverage[ch]);
  }
  return true;
}

static float positionDifference(uint64_t positive, uint64_t negative)
{
  const uint64_t denominator = positive + negative;
  if (denominator == 0) return 0.0f;
  return ((float)positive - (float)negative) / (float)denominator;
}

// Convert one four-quadrant sensor frame into intensity L and coordinates.
// Channel order is XR, XL, YB, YT, matching the CN0569 physical mapping.
static void calculateSensorFrame(const uint32_t frame[8], uint8_t firstChannel,
                                 uint64_t &intensity, float &x, float &y)
{
  uint64_t channel[4];
  for (uint8_t i = 0; i < 4; i++) {
    const uint32_t raw = frame[firstChannel + i];
    const uint32_t base = channelBaselineAverage[firstChannel + i];
    channel[i] = (raw > base) ? (uint64_t)(raw - base) : 0ULL;
  }

  intensity = channel[0] + channel[1] + channel[2] + channel[3];
  x = positionDifference(channel[1], channel[0]); // (XL - XR)/(XL + XR)
  y = positionDifference(channel[3], channel[2]); // (YT - YB)/(YT + YB)
}

// Return -1 for no completed gesture, otherwise 0=CLICK, 1=UP, 2=DOWN,
// 3=LEFT, 4=RIGHT. The short-event reset and last-valid endpoint avoid the
// two state/endpoint problems identified in the Tiltie investigation.
static int8_t processGestureFrame(const uint32_t frame[8], uint8_t firstChannel,
                                  GestureState &state, uint64_t *intensityOut = nullptr,
                                  float *xOut = nullptr, float *yOut = nullptr)
{
  uint64_t intensity = 0;
  float x = 0.0f, y = 0.0f;
  calculateSensorFrame(frame, firstChannel, intensity, x, y);

  if (intensityOut) *intensityOut = intensity;
  if (xOut) *xOut = x;
  if (yOut) *yOut = y;

  if (intensity > GESTURE_INTENSITY_THRESHOLD) {
    if (!state.active) {
      // A new event starts on the first above-threshold frame.
      state.active = true;
      state.activeFrames = 1;
      state.startX = x;
      state.startY = y;
    } else if (state.activeFrames < 255) {
      state.activeFrames++;
    }
    // Track the last position while the signal is still valid.
    state.lastValidX = x;
    state.lastValidY = y;
    return -1;
  }

  if (!state.active) return -1;

  // Regardless of duration, close and reset the event. A gesture shorter than
  // five frames is discarded but must not leave stale state armed.
  const uint8_t duration = state.activeFrames;
  const float endX = state.lastValidX;
  const float endY = state.lastValidY;
  state.active = false;
  state.activeFrames = 0;

  if (duration < GESTURE_MIN_ACTIVE_BUFFERS) return -1;

  const float dx = state.startX - endX;
  const float dy = state.startY - endY;
  const float distance = sqrtf(dx * dx + dy * dy);
  const float slope = (state.startY - endY) /
                      (state.startX - endX + 0.000001f);

  if (distance < GESTURE_DISTANCE_THRESHOLD) {
    return 0; // CLICK
  } else if (fabsf(slope) > 1.0f) {
    return (state.startY < endY) ? 1 : 2; // UP : DOWN
  } else if (fabsf(slope) < 1.0f) {
    return (state.startX > endX) ? 3 : 4; // LEFT : RIGHT
  }
  return 0;
}

static const char *gestureName(int8_t gesture, uint8_t sensorNumber)
{
  static const char *names[5] = {"CLICK", "UP", "DOWN", "LEFT", "RIGHT"};
  if (gesture < 0 || gesture > 4) return nullptr;
  static char label[10];
  snprintf(label, sizeof(label), "%s_%u", names[(uint8_t)gesture], sensorNumber);
  return label;
}

// -----------------------------------------------------------------------------
// Arduino setup and loop
// -----------------------------------------------------------------------------
void setup()
{
  Serial.begin(SERIAL_BAUD);
  delay(1500);
  Serial.println();
  Serial.println("CN0569 / ADPD1080 ESP32 Tiltie gesture recognition");
  Serial.println("INT: GPIO 6; SDA: GPIO 4; SCL: GPIO 5");

  Wire.begin(CN0569_SDA_PIN, CN0569_SCL_PIN, I2C_CLOCK_HZ);
  Wire.setClock(I2C_CLOCK_HZ);

  if (!configureAdpd1080()) {
    stopWithError("ADPD1080 initialisation/configuration failed.");
  }
  if (!calibrate32kClock()) {
    stopWithError("32 kHz/sample-clock calibration failed; check P1 INT to GPIO 6.");
  }
  if (!calibrate32MHzClock()) {
    stopWithError("32 MHz clock calibration failed.");
  }

  // Same final sample-rate setting as ADI no-OS iio_example.c (512 Hz).
  if (!setAdcSampleRate(REQUESTED_SAMPLE_RATE_HZ)) {
    stopWithError("Could not set ADC sample rate.");
  }
  uint16_t fsampleReadback = 0;
  if (!readRegister(REG_FSAMPLE, fsampleReadback) || fsampleReadback == 0) {
    stopWithError("Could not read back FSAMPLE.");
  }
  Serial.print("Requested ADC rate: ");
  Serial.print(REQUESTED_SAMPLE_RATE_HZ);
  Serial.print(" Hz; programmed FSAMPLE: ");
  Serial.print(fsampleReadback);
  Serial.print(" (integer-driver nominal rate ");
  Serial.print(32000UL / ((uint32_t)fsampleReadback * 4UL));
  Serial.println(" Hz)");
  if (!setMode(MODE_NORMAL)) {
    stopWithError("Could not enter ADPD1080 normal measurement mode.");
  }

  if (!gainCalibration()) {
    stopWithError("Gesture baseline calibration failed while reading FIFO.");
  }

  Serial.println("Gesture recognition active.");
}

void loop()
{
  uint32_t frame[8];
  if (!readAveragedFrame(frame)) {
    stopWithError("Could not acquire a complete eight-sample frame from the FIFO.");
  }

  uint64_t intensity0 = 0, intensity1 = 0;
  float x0 = 0.0f, y0 = 0.0f, x1 = 0.0f, y1 = 0.0f;
  const int8_t gesture0 = processGestureFrame(frame, 0, gestureSensor0,
                                               &intensity0, &x0, &y0);
  const int8_t gesture1 = processGestureFrame(frame, 4, gestureSensor1,
                                               &intensity1, &x1, &y1);

#if CN0569_DEBUG_RAW_FRAMES
  Serial.print("FRAME,");
  for (uint8_t ch = 0; ch < 8; ch++) {
    Serial.print(frame[ch]);
    Serial.print(ch == 7 ? ',' : ';');
  }
  Serial.print(intensity0); Serial.print(',');
  Serial.print(x0, 4); Serial.print(',');
  Serial.print(y0, 4); Serial.print(',');
  Serial.print(intensity1); Serial.print(',');
  Serial.print(x1, 4); Serial.print(',');
  Serial.println(y1, 4);
#endif

  if (gesture0 >= 0) {
    const char *label = gestureName(gesture0, 0);
    if (label) Serial.println(label);
  }
  if (gesture1 >= 0) {
    const char *label = gestureName(gesture1, 1);
    if (label) Serial.println(label);
  }
}

image

The board now is able to translate the photodiode values into gesture classifications based on their simple algorithm. What I didn’t understand was that gesture monitoring requires just one photodiode package – the code emits a gesture for the left and right mixed together in one stream (suffix “_0” from one sensor, suffix “_1” from the other).

image image

The datasheet describes how it works … for some reason I thought both packages were necessary for this, but as it turns out, it’s only necessary for the triangulation mode of operation. But while I was able to get the gestures working with just the ESP32-S3 … that’s not what I need for this project!

How Much Trash? Triangulating first, then Calibrating the Inverse-Square Law

What I really needed was the proximity of the trash to the sensor, so the suggested approach is to go with triangulation. The ADPD2080 datasheet gives a bit of the simple math behind it:

image

I asked ChatGPT to modify the code to implement this calculation in the code whilst maintaining the tweaks that were previously mentioned. The resulting code looked right even on repeated inspection ...

[CN0569_ESP32_Distance.ino]

/*
 * CN0569 (ADPD1080 + two ADPD2140 sensors) - ESP32 Arduino port (Triangulation)
 * Ported by OpenAI's ChatGPT GPT-6 Luna guided by Gough Lui
 *
 * ESP32 distance measurement using the two ADPD2140 angle sensors on the
 * Analog Devices EVAL-CN0569-PMDZ board.
 *
 * It incorporates the register changes documented in
 * @javagoza's Tiltie 04 post (https://community.element14.com/challenges-
 * projects/design-challenges/my-project-is-trash/f/forum/57465/tiltie---
 * 04-bringing-touch-free-gesture-control-to-tiltie-with-the-cn0569) including
 * trim adjustment, a 19 us LED period, photodiode reverse bias, and 50 kOhm
 * Slot A TIA gain (with Slot B retained at 200 kOhm).
 * Much thanks to @javagoza for the tweaks - it didn't work well without them!
 *
 * Range is calculated using the ADPD2140 data-sheet two-sensor triangulation
 * equation. The initial C constant is theoretical; use `CAL <distance_mm>`
 * with a target at a known distance to calibrate it for this board. The C
 * value is stored in ESP32 Preferences (NVS) and survives resets.
 *
 * Connections, CN0569 P1:
 *   P1-1 INT / GPIO0 -> ESP32 GPIO 6
 *   P1-2 RESET       -> NC
 *   P1-3 SCL         -> ESP32 GPIO 5
 *   P1-4 SDA         -> ESP32 GPIO 4
 *   P1-5 GND         -> ESP32 GND
 *   P1-6 VCC         -> regulated 3.3 V
 *
 * ADPD1080 I2C address: 0x64 (7-bit), 400 kHz.
 * This pin assignment assumes an ESP32-S3 or another ESP32 variant where
 * GPIO6 is a normal GPIO. Do not use GPIO6 on classic ESP32-WROOM modules
 * where GPIO6 is connected to SPI flash.
 *
 * Serial Monitor: 921600 baud.
 * Output: DIST,<mm>,<cm>,yA,yB,term,signalA,signalB
 *
 * Commands (send newline):
 *   CAL <mm>  Calibrate C using a stationary target at the specified distance.
 *   ZERO     Re-measure the empty-scene baseline; remove the target first.
 *   SHOW     Print baseline, sensor spacing and active C constant.
 *   DEFAULT  Restore the theoretical C constant and save it in NVS.
 */

#include <Arduino.h>
#include <Wire.h>
#include <Preferences.h>
#include <esp_timer.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>

// -----------------------------------------------------------------------------
// Connections and operating parameters
// -----------------------------------------------------------------------------
#define CN0569_SDA_PIN       4
#define CN0569_SCL_PIN       5
#define CN0569_INT_PIN       6

static const uint8_t  ADPD1080_I2C_ADDRESS = 0x64;
static const uint32_t I2C_CLOCK_HZ = 400000;
static const uint16_t REQUESTED_SAMPLE_RATE_HZ = 512;
static const uint32_t FIFO_WAIT_TIMEOUT_MS = 1000;
static const uint8_t  MAX_32K_CALIBRATION_STEPS = 64;
static const uint32_t SERIAL_BAUD = 921600;

// CN0569 factory geometry: ADPD2140 sensor centres are 1 inch apart.
static const float SENSOR_BASELINE_MM = 25.4f;
static const float ADPD2140_ANGULAR_SLOPE_RATIO_PER_DEG = 0.00631f;
static const float DEGREES_PER_RADIAN = 57.2957795f;
// Small-angle theoretical starting point; C is empirical in ADI's equation.
static const float DEFAULT_TRIANGULATION_C_MM =
    SENSOR_BASELINE_MM * ADPD2140_ANGULAR_SLOPE_RATIO_PER_DEG * DEGREES_PER_RADIAN;

// Eight raw FIFO packets are summed to form one measurement frame (~64-67 Hz
// at the requested 512 Hz setting, depending on the integer FSAMPLE code).
static const uint8_t DISTANCE_FRAME_SAMPLES = 8;
static const uint8_t BACKGROUND_CALIBRATION_FRAMES = 48;
static const uint8_t RANGE_CALIBRATION_FRAMES = 32;

// Signal validity is assessed after subtracting the empty-scene channel
// baselines. Adjust only if real target signals are routinely weaker/stronger.
static const uint32_t MIN_SENSOR_SIGNAL_CODES = 1000;
static const uint32_t MIN_VERTICAL_CHANNEL_SUM = 100;
static const float MIN_TRIANGULATION_TERM = 0.0005f;
static const float ANGLE_FILTER_ALPHA = 0.30f;

// The current PD_LED_SELECT setting routes Slot A to PD1..PD4 (U1), and
// Slot B to PD5..PD8 (U2). Set a flag only if physical test data proves one
// sensor's Y axis is reversed relative to the other.
static const bool INVERT_SLOT_A_Y = false;
static const bool INVERT_SLOT_B_Y = false;

#define CN0569_DEBUG_DISTANCE 0

// -----------------------------------------------------------------------------
// ADPD1080 register addresses
// -----------------------------------------------------------------------------
static const uint8_t REG_STATUS           = 0x00;
static const uint8_t REG_GPIO_DRV         = 0x02;
static const uint8_t REG_DEVID            = 0x08;
static const uint8_t REG_CLK_RATIO        = 0x0A;
static const uint8_t REG_GPIO_CTRL        = 0x0B;
static const uint8_t REG_SW_RESET         = 0x0F;
static const uint8_t REG_MODE             = 0x10;
static const uint8_t REG_SLOT_EN          = 0x11;
static const uint8_t REG_FSAMPLE          = 0x12;
static const uint8_t REG_PD_LED_SELECT    = 0x14;
static const uint8_t REG_NUM_AVG          = 0x15;
static const uint8_t REG_INT_SEQ_A        = 0x17;
static const uint8_t REG_SLOTA_CH1_OFFSET = 0x18;
static const uint8_t REG_SLOTB_CH1_OFFSET = 0x1E;
static const uint8_t REG_INT_SEQ_B        = 0x1D;
static const uint8_t REG_ILED1_COARSE     = 0x23;
static const uint8_t REG_SLOTA_NUMPULSES  = 0x31;
static const uint8_t REG_SLOTB_NUMPULSES  = 0x36;
static const uint8_t REG_SLOTA_AFE_WINDOW = 0x39;
static const uint8_t REG_SLOTB_AFE_WINDOW = 0x3B;
static const uint8_t REG_SLOTA_TIA_CFG    = 0x42;
static const uint8_t REG_SLOTB_TIA_CFG    = 0x44;
static const uint8_t REG_SAMPLE_CLK       = 0x4B;
static const uint8_t REG_CLK32M_ADJUST    = 0x4D;
static const uint8_t REG_CLK32M_CAL_EN    = 0x50;
static const uint8_t REG_AFE_PWR_CFG2     = 0x54;
static const uint8_t REG_MATH             = 0x58;
static const uint8_t REG_DATA_ACCESS_CTL  = 0x5F;
static const uint8_t REG_FIFO_ACCESS      = 0x60;

static const uint16_t DEVICE_ID_ADPD1080 = 0x0A16;
static const uint16_t MODE_PROGRAM = 1;
static const uint16_t MODE_NORMAL = 2;
static const uint16_t SAMPLE_CLK_32K_ADJUST_MASK = 0x003F;
static const uint16_t SLOT_READOUT_MODE = 0x2000;
static const uint16_t SLOT_FIFO_OVERRUN_PREVENT = 0x1000;
static const uint16_t GPIO0_ENABLE = 0x0004;
static const uint16_t GPIO0_ACTIVE_PULSE_FUNCTION = 0x0002;
static const uint8_t FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE = 32;

// Slot A has PD1..PD4 (U1); Slot B has PD5..PD8 (U2).
// CN0569 guide maps PD1..PD4 and PD5..PD8 to the four quadrants in XR, XL,
// YB, YT order, respectively.
static uint32_t backgroundBaseline[8] = {0};
static bool backgroundReady = false;
static bool angleFilterReady = false;
static float filteredYA = 0.0f;
static float filteredYB = 0.0f;
static float triangulationCmm = DEFAULT_TRIANGULATION_C_MM;
static Preferences rangePreferences;
static bool preferencesReady = false;

static char serialCommandBuffer[48];
static uint8_t serialCommandLength = 0;

// -----------------------------------------------------------------------------
// Low-level I2C register access (16-bit, MSB first)
// -----------------------------------------------------------------------------
static bool writeRegister(uint8_t reg, uint16_t value)
{
  Wire.beginTransmission(ADPD1080_I2C_ADDRESS);
  Wire.write(reg);
  Wire.write((uint8_t)(value >> 8));
  Wire.write((uint8_t)(value & 0xFF));
  return Wire.endTransmission() == 0;
}

static bool readRegister(uint8_t reg, uint16_t &value)
{
  Wire.beginTransmission(ADPD1080_I2C_ADDRESS);
  Wire.write(reg);
  if (Wire.endTransmission(false) != 0) return false;

  const uint8_t received = Wire.requestFrom(
      (uint8_t)ADPD1080_I2C_ADDRESS, (uint8_t)2, (uint8_t)true);
  if (received != 2 || Wire.available() < 2) {
    while (Wire.available()) (void)Wire.read();
    return false;
  }
  const uint8_t msb = (uint8_t)Wire.read();
  const uint8_t lsb = (uint8_t)Wire.read();
  value = ((uint16_t)msb << 8) | lsb;
  return true;
}

static bool updateRegister(uint8_t reg, uint16_t clearMask, uint16_t setBits)
{
  uint16_t value;
  if (!readRegister(reg, value)) return false;
  value = (uint16_t)((value & (uint16_t)~clearMask) | setBits);
  return writeRegister(reg, value);
}

static bool setMode(uint16_t mode)
{
  return writeRegister(REG_MODE, (uint16_t)(mode & 0x0003));
}

static bool setAdcSampleRate(uint16_t requestedRateHz)
{
  if (requestedRateHz == 0 || requestedRateHz > 2000) return false;
  const uint16_t fsample = (uint16_t)(32000UL / ((uint32_t)requestedRateHz * 4UL));
  return writeRegister(REG_FSAMPLE, fsample);
}

static void stopWithError(const char *message)
{
  Serial.println();
  Serial.print("FATAL: ");
  Serial.println(message);
  while (true) delay(1000);
}

// -----------------------------------------------------------------------------
// 32 kHz sample-clock calibration using the P1 INT / GPIO0 connection
// -----------------------------------------------------------------------------
static volatile uint32_t g_gpio0PulseCount = 0;

void IRAM_ATTR onCn0569IntRise()
{
  // Avoid deprecated volatile ++ syntax on newer Arduino toolchains.
  const uint32_t currentCount = g_gpio0PulseCount;
  g_gpio0PulseCount = currentCount + 1U;
}

static uint32_t countGpioPulsesForOneSecond()
{
  noInterrupts();
  g_gpio0PulseCount = 0;
  interrupts();

  const uint64_t startUs = (uint64_t)esp_timer_get_time();
  while (((uint64_t)esp_timer_get_time() - startUs) < 1000000ULL) delay(1);

  noInterrupts();
  const uint32_t count = g_gpio0PulseCount;
  interrupts();
  return count;
}

static bool calibrate32kClock()
{
  Serial.println("Calibrating ADPD1080 sample clock on INT/GPIO0...");
  if (!setAdcSampleRate(1000)) return false;
  if (!writeRegister(REG_GPIO_DRV, GPIO0_ENABLE)) return false;
  if (!writeRegister(REG_GPIO_CTRL, GPIO0_ACTIVE_PULSE_FUNCTION)) return false;
  if (!setMode(MODE_NORMAL)) return false;

  pinMode(CN0569_INT_PIN, INPUT);
  g_gpio0PulseCount = 0;
  attachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN), onCn0569IntRise, RISING);

  uint16_t sampleClockReg;
  if (!readRegister(REG_SAMPLE_CLK, sampleClockReg)) {
    detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));
    return false;
  }

  uint8_t currentAdjust = (uint8_t)(sampleClockReg & SAMPLE_CLK_32K_ADJUST_MASK);
  uint8_t bestAdjust = currentAdjust;
  uint32_t bestDifference = UINT32_MAX;

  for (uint8_t step = 0; step < MAX_32K_CALIBRATION_STEPS; step++) {
    const uint32_t pulseCount = countGpioPulsesForOneSecond();
    const uint32_t difference = (pulseCount > 1000U)
                                  ? pulseCount - 1000U : 1000U - pulseCount;
    Serial.print("  INT pulses: ");
    Serial.print(pulseCount);
    Serial.print("; error: ");
    Serial.println(difference);

    if (pulseCount == 0) {
      Serial.println("No INT pulses; check CN0569 P1 pin 1 to ESP32 GPIO 6.");
      detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));
      return false;
    }
    if (difference >= bestDifference) break;

    bestDifference = difference;
    bestAdjust = currentAdjust;
    if (difference == 0) break;

    int16_t nextAdjust = (int16_t)currentAdjust;
    if (pulseCount < 1000U) nextAdjust--;
    else nextAdjust++;
    if (nextAdjust < 0 || nextAdjust > 63) break;

    sampleClockReg = (uint16_t)((sampleClockReg & (uint16_t)~SAMPLE_CLK_32K_ADJUST_MASK)
                                | (uint16_t)nextAdjust);
    if (!writeRegister(REG_SAMPLE_CLK, sampleClockReg)) {
      detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));
      return false;
    }
    currentAdjust = (uint8_t)nextAdjust;
    delay(5);
  }

  detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));
  if (!readRegister(REG_SAMPLE_CLK, sampleClockReg)) return false;
  sampleClockReg = (uint16_t)((sampleClockReg & (uint16_t)~SAMPLE_CLK_32K_ADJUST_MASK)
                              | bestAdjust);
  if (!writeRegister(REG_SAMPLE_CLK, sampleClockReg)) return false;
  if (!setMode(MODE_PROGRAM)) return false;
  if (!setAdcSampleRate(16)) return false;
  if (!writeRegister(REG_GPIO_DRV, 0x0000)) return false;
  if (!writeRegister(REG_GPIO_CTRL, 0x0000)) return false;

  Serial.print("32 kHz/sample-clock trim: 0x");
  Serial.println(bestAdjust, HEX);
  return true;
}

// -----------------------------------------------------------------------------
// Internal 32 MHz clock calibration (same sequence as the preceding sketch)
// -----------------------------------------------------------------------------
static bool calibrate32MHzClock()
{
  uint16_t value;
  if (!readRegister(REG_DATA_ACCESS_CTL, value)) return false;
  if (!writeRegister(REG_DATA_ACCESS_CTL, (uint16_t)(value | 0x0001))) return false;
  if (!readRegister(REG_CLK32M_CAL_EN, value)) return false;
  if (!writeRegister(REG_CLK32M_CAL_EN, (uint16_t)(value | 0x0020))) return false;
  delay(1);

  if (!readRegister(REG_CLK_RATIO, value)) return false;
  const uint16_t clockRatio = (uint16_t)(value & 0x0FFF);
  const float clockError = 32000000.0f * (1.0f - ((float)clockRatio / 2000.0f));
  const int32_t correction = (int32_t)(clockError / 112000.0f);

  // REG_CLK32M_ADJUST resets to 0x98. The signed calibration correction is
  // a delta from that trim value; writing the signed delta itself causes
  // negative corrections to wrap (e.g. -14 -> 0xF2) and over-speed the clock.
  uint16_t trimBase;
  if (!readRegister(REG_CLK32M_ADJUST, trimBase)) return false;
  const int32_t adjustedTrim = (int32_t)(trimBase & 0x00FF) + correction;
  if (adjustedTrim < 0 || adjustedTrim > 0xFF) {
    Serial.println("32 MHz clock correction is outside the register range.");
    return false;
  }
  const uint8_t adjustment = (uint8_t)adjustedTrim;
  if (!writeRegister(REG_CLK32M_ADJUST, adjustment)) return false;

  if (!readRegister(REG_CLK32M_CAL_EN, value)) return false;
  if (!writeRegister(REG_CLK32M_CAL_EN, (uint16_t)(value & (uint16_t)~0x0020))) return false;
  if (!readRegister(REG_DATA_ACCESS_CTL, value)) return false;
  if (!writeRegister(REG_DATA_ACCESS_CTL, (uint16_t)(value & (uint16_t)~0x0001))) return false;

  Serial.print("32 MHz clock ratio: ");
  Serial.println(clockRatio);
  Serial.print("32 MHz trim base: 0x");
  Serial.println(trimBase & 0x00FF, HEX);
  Serial.print("32 MHz trim correction: ");
  Serial.println(correction);
  Serial.print("32 MHz final adjustment: 0x");
  Serial.println(adjustment, HEX);
  return true;
}

// -----------------------------------------------------------------------------
// Sensor initialisation. Base setup follows ADI's iio_adpd1080 example;
// hardware corrections follow the Tiltie investigation described above.
// -----------------------------------------------------------------------------
static bool configureAdpd1080()
{
  uint16_t value;
  if (!readRegister(REG_DEVID, value)) {
    Serial.println("Could not read ADPD1080 device ID; check wiring and power.");
    return false;
  }
  Serial.print("ADPD device ID: 0x");
  Serial.println(value, HEX);
  if (value != DEVICE_ID_ADPD1080) return false;

  if (!writeRegister(REG_SW_RESET, 0x0001)) return false;
  delay(10);

  // Enable the 32 kHz state-machine clock before programming slots.
  if (!readRegister(REG_SAMPLE_CLK, value)) return false;
  value |= 0x0080;
  if (!writeRegister(REG_SAMPLE_CLK, value)) return false;
  if (!setMode(MODE_PROGRAM)) return false;

  // Enable both time slots with four 32-bit photodiode channels in each FIFO
  // packet. A complete packet is 8 channels x 32 bits = 32 bytes.
  if (!readRegister(REG_SLOT_EN, value)) return false;
  value &= (uint16_t)~(0x0001 | 0x001C | 0x0020 | 0x01C0);
  value |= (uint16_t)(0x0001 | (0x0006 << 2) | 0x0020 | (0x0006 << 6));
  if (!writeRegister(REG_SLOT_EN, value)) return false;

  // Select LEDX1 for both slots; PD1-4 in A and PD5-8 in B.
  if (!readRegister(REG_PD_LED_SELECT, value)) return false;
  value &= (uint16_t)~0x0FFF;
  value |= (uint16_t)(0x0001 | (0x0001 << 2) | (0x0005 << 4) | (0x0004 << 8));
  if (!writeRegister(REG_PD_LED_SELECT, value)) return false;

  // No decimation/averaging in either slot.
  if (!writeRegister(REG_NUM_AVG, 0x0000)) return false;

  // Integrator chop sequence: inverted, normal, normal, inverted.
  if (!updateRegister(REG_INT_SEQ_A, 0x0000, 0x0009)) return false;
  if (!updateRegister(REG_INT_SEQ_B, 0x0000, 0x0009)) return false;

  // In integrator chop mode, zero the eight real channel-offset registers.
  // 0x1C and 0x1D are NOT offset registers; they are BG_MEAS_B and INT_SEQ_B.
  for (uint8_t i = 0; i < 4; i++) {
    if (!writeRegister((uint8_t)(REG_SLOTA_CH1_OFFSET + i), 0x0000)) return false;
    if (!writeRegister((uint8_t)(REG_SLOTB_CH1_OFFSET + i), 0x0000)) return false;
  }

  // LED1 coarse current and slew retain the established ADI example setting.
  if (!readRegister(REG_ILED1_COARSE, value)) return false;
  value &= (uint16_t)~(0x000F | 0x0070);
  value |= (uint16_t)(0x0006 | (0x0003 << 4) | 0x2000);
  if (!writeRegister(REG_ILED1_COARSE, value)) return false;

  // Keep four pulses and the 4 us AFE width/0x2F0 offset. Only change the
  // period low byte from 0x0E to the datasheet-compliant 0x13.
  if (!writeRegister(REG_SLOTA_NUMPULSES, 0x0413)) return false;
  if (!writeRegister(REG_SLOTB_NUMPULSES, 0x0413)) return false;
  if (!writeRegister(REG_SLOTA_AFE_WINDOW, 0x22F0)) return false;
  if (!writeRegister(REG_SLOTB_AFE_WINDOW, 0x22F0)) return false;

  // The Tiltie settings use 50 kohm for the closer Slot A sensor and the
  // default 200 kohm for Slot B. Change only TIA_GAIN bits [1:0].
  if (!updateRegister(REG_SLOTA_TIA_CFG, 0x0003, 0x0002)) return false;
  if (!updateRegister(REG_SLOTB_TIA_CFG, 0x0003, 0x0000)) return false;

  // Apply about 250 mV reverse bias to both photodiodes using the override.
  if (!writeRegister(REG_AFE_PWR_CFG2, 0x0AA0)) return false;

  // Original integrator-chop math setup.
  if (!updateRegister(REG_MATH, 0x0F66, 0x0544)) return false;

  // Enable FIFO readout and FIFO overrun prevention without disturbing slot
  // enable/FIFO-format fields.
  if (!readRegister(REG_SLOT_EN, value)) return false;
  value |= SLOT_READOUT_MODE | SLOT_FIFO_OVERRUN_PREVENT;
  if (!writeRegister(REG_SLOT_EN, value)) return false;

  // Useful configuration readback for the first hardware validation.
  const uint8_t regs[] = {REG_SAMPLE_CLK, REG_SLOT_EN, REG_PD_LED_SELECT,
                          REG_SLOTA_NUMPULSES, REG_SLOTB_NUMPULSES,
                          REG_SLOTA_TIA_CFG, REG_SLOTB_TIA_CFG,
                          REG_AFE_PWR_CFG2};
  const char *names[] = {"SAMPLE_CLK", "SLOT_EN", "PD_LED_SELECT",
                         "SLOTA_NUMPULSES", "SLOTB_NUMPULSES",
                         "SLOTA_TIA_CFG", "SLOTB_TIA_CFG", "AFE_PWR_CFG2"};
  for (uint8_t i = 0; i < sizeof(regs); i++) {
    if (!readRegister(regs[i], value)) return false;
    Serial.print(names[i]);
    Serial.print(" = 0x");
    Serial.println(value, HEX);
  }
  return true;
}

// -----------------------------------------------------------------------------
// One simultaneous 8-photodiode sample from the ADPD1080 FIFO
// -----------------------------------------------------------------------------
static bool readOneEightChannelSample(uint32_t samples[8])
{
  const uint32_t startMs = millis();
  uint16_t status;

  // Wait for one complete 32-byte packet (8 channels x 32 bits).
  while (true) {
    if (!readRegister(REG_STATUS, status)) return false;
    const uint8_t fifoBytes = (uint8_t)((status >> 8) & 0xFF);
    if (fifoBytes >= FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE) break;
    if ((uint32_t)(millis() - startMs) >= FIFO_WAIT_TIMEOUT_MS) {
      Serial.println("Timed out waiting for FIFO data.");
      return false;
    }
    delay(1);
  }

  // ADPD1080 supports multiword reads from FIFO_ACCESS: each acknowledged
  // 16-bit word advances the FIFO. Read the full 32-byte packet in ONE I2C
  // transaction instead of sixteen independent register transactions. This
  // substantially reduces bus overhead and helps avoid FIFO overrun at 512 Hz.
  Wire.beginTransmission(ADPD1080_I2C_ADDRESS);
  Wire.write(REG_FIFO_ACCESS);
  if (Wire.endTransmission(false) != 0) return false;

  uint8_t fifoBytes[32];
  const uint8_t received = Wire.requestFrom(
      (uint8_t)ADPD1080_I2C_ADDRESS, (uint8_t)sizeof(fifoBytes), (uint8_t)true);
  if (received != sizeof(fifoBytes)) {
    while (Wire.available()) (void)Wire.read();
    Serial.print("Incomplete FIFO burst read: received ");
    Serial.print(received);
    Serial.println(" of 32 bytes.");
    return false;
  }

  for (uint8_t i = 0; i < sizeof(fifoBytes); i++) {
    if (!Wire.available()) {
      Serial.println("FIFO burst ended before all 32 bytes were received.");
      return false;
    }
    fifoBytes[i] = (uint8_t)Wire.read();
  }

  for (uint8_t channel = 0; channel < 8; channel++) {
    const uint8_t offset = (uint8_t)(channel * 4);
    // Each FIFO word is transmitted MSB first. The first 16-bit word holds
    // the low half of the channel result; the second holds the high half.
    const uint16_t lowWord = ((uint16_t)fifoBytes[offset] << 8) |
                             (uint16_t)fifoBytes[offset + 1];
    const uint16_t highWord = ((uint16_t)fifoBytes[offset + 2] << 8) |
                              (uint16_t)fifoBytes[offset + 3];
    samples[channel] = ((uint32_t)lowWord | ((uint32_t)highWord << 16)) &
                       0x07FFFFFFUL;
  }
  return true;
}

// -----------------------------------------------------------------------------
// Aggregate eight successive simultaneous U1/U2 FIFO packets into one frame.
// frame[0..3] = Slot A / U1 / PD1..PD4; frame[4..7] = Slot B / U2 / PD5..PD8.
// -----------------------------------------------------------------------------
static bool readAveragedFrame(uint32_t frame[8])
{
  uint64_t channelSums[8] = {0, 0, 0, 0, 0, 0, 0, 0};
  uint32_t sample[8];

  for (uint8_t n = 0; n < DISTANCE_FRAME_SAMPLES; n++) {
    if (!readOneEightChannelSample(sample)) return false;
    for (uint8_t ch = 0; ch < 8; ch++) channelSums[ch] += sample[ch];
  }

  for (uint8_t ch = 0; ch < 8; ch++) {
    if (channelSums[ch] > UINT32_MAX) return false;
    frame[ch] = (uint32_t)channelSums[ch];
  }
  return true;
}

// -----------------------------------------------------------------------------
// Software background calibration, angle extraction and triangulation
// -----------------------------------------------------------------------------
static bool calibrateBackground()
{
  Serial.println();
  Serial.println("EMPTY-SCENE CALIBRATION: remove target from both sensor fields.");
  Serial.print("Collecting ");
  Serial.print(BACKGROUND_CALIBRATION_FRAMES);
  Serial.println(" eight-sample frames...");

  uint64_t sums[8] = {0, 0, 0, 0, 0, 0, 0, 0};
  uint32_t frame[8];
  for (uint8_t n = 0; n < BACKGROUND_CALIBRATION_FRAMES; n++) {
    if (!readAveragedFrame(frame)) {
      Serial.println("ERROR: FIFO read failed during empty-scene calibration.");
      return false;
    }
    for (uint8_t ch = 0; ch < 8; ch++) sums[ch] += frame[ch];
  }

  for (uint8_t ch = 0; ch < 8; ch++) {
    backgroundBaseline[ch] = (uint32_t)(sums[ch] / BACKGROUND_CALIBRATION_FRAMES);
  }
  backgroundReady = true;
  angleFilterReady = false;

  Serial.println("Background baseline updated:");
  for (uint8_t ch = 0; ch < 8; ch++) {
    Serial.print("  CH"); Serial.print(ch); Serial.print(" = ");
    Serial.println(backgroundBaseline[ch]);
  }
  return true;
}

// Compute a single sensor's intensity and ADPD2140 angle ratios from one
// eight-sample-sum frame after subtracting the matching empty-scene baselines.
static bool calculateSensorAngles(const uint32_t frame[8], uint8_t base,
                                  float &xRatio, float &yRatio,
                                  uint32_t &intensity)
{
  uint32_t corrected[4];
  uint64_t sum = 0;
  for (uint8_t i = 0; i < 4; i++) {
    const uint32_t raw = frame[base + i];
    const uint32_t baseline = backgroundBaseline[base + i];
    corrected[i] = (raw > baseline) ? (raw - baseline) : 0U;
    sum += corrected[i];
  }

  intensity = (sum > UINT32_MAX) ? UINT32_MAX : (uint32_t)sum;
  const uint64_t xDenominator = (uint64_t)corrected[0] + corrected[1];
  const uint64_t yDenominator = (uint64_t)corrected[2] + corrected[3];
  if (intensity < MIN_SENSOR_SIGNAL_CODES ||
      yDenominator < MIN_VERTICAL_CHANNEL_SUM || xDenominator == 0) {
    xRatio = 0.0f;
    yRatio = 0.0f;
    return false;
  }

  // ADPD2140 equations: x=(XL-XR)/(XL+XR), y=(YT-YB)/(YT+YB).
  xRatio = ((float)corrected[1] - (float)corrected[0]) / (float)xDenominator;
  yRatio = ((float)corrected[3] - (float)corrected[2]) / (float)yDenominator;

  if ((base == 0 && INVERT_SLOT_A_Y) || (base == 4 && INVERT_SLOT_B_Y)) {
    yRatio = -yRatio;
  }
  return isfinite(xRatio) && isfinite(yRatio);
}

// ADPD2140 datasheet Object Triangulation equation. The square root of the
// squared term shown in the datasheet is simply its absolute value.
static bool calculateTriangulationTerm(float yA, float yB, float &term)
{
  if (!isfinite(yA) || !isfinite(yB)) return false;
  const bool sameSign = ((yA >= 0.0f && yB >= 0.0f) ||
                         (yA < 0.0f && yB < 0.0f));
  term = sameSign ? fabsf(yA - yB) : fabsf(yA + yB);
  return isfinite(term) && term >= MIN_TRIANGULATION_TERM;
}

static void printRangeSettings()
{
  Serial.println();
  Serial.println("CN0569 triangulation settings:");
  Serial.print("  Sensor baseline: "); Serial.print(SENSOR_BASELINE_MM, 2); Serial.println(" mm");
  Serial.print("  Active C constant: "); Serial.print(triangulationCmm, 5); Serial.println(" mm");
  Serial.print("  Theoretical C start: "); Serial.print(DEFAULT_TRIANGULATION_C_MM, 5); Serial.println(" mm");
  Serial.println("  Sensor mapping: Slot A = U1 (PD1..PD4), Slot B = U2 (PD5..PD8)");
}

static bool saveTriangulationConstant(float newC)
{
  if (!isfinite(newC) || newC <= 0.0f || newC > 10000.0f) return false;
  triangulationCmm = newC;
  if (preferencesReady) {
    const size_t saved = rangePreferences.putFloat("triCmm", triangulationCmm);
    if (saved != sizeof(float)) {
      Serial.println("WARNING: Could not persist C to ESP32 NVS; value remains active until reset.");
    }
  } else {
    Serial.println("WARNING: NVS unavailable; C remains active until reset.");
  }
  Serial.print("Triangulation C set to ");
  Serial.print(triangulationCmm, 6);
  Serial.println(" mm.");
  return true;
}

// Calibrate empirical C from a stationary target at a known distance. Average
// the triangulation term over a set of frames to reduce noise before updating C.
static bool calibrateKnownDistance(float knownDistanceMm)
{
  if (knownDistanceMm < 10.0f || knownDistanceMm > 5000.0f) {
    Serial.println("CAL distance must be between 10 and 5000 mm.");
    return false;
  }
  if (!backgroundReady) {
    Serial.println("ERROR: Run ZERO first so an empty-scene baseline is available.");
    return false;
  }

  Serial.println();
  Serial.print("RANGE CALIBRATION: keep target stationary at ");
  Serial.print(knownDistanceMm, 1);
  Serial.println(" mm from the sensor baseline plane.");
  Serial.println("Collecting calibration frames...");

  double termSum = 0.0;
  double termSquaredSum = 0.0;
  double yASum = 0.0;
  double yBSum = 0.0;
  uint8_t accepted = 0;
  uint32_t frame[8];

  for (uint8_t n = 0; n < RANGE_CALIBRATION_FRAMES; n++) {
    if (!readAveragedFrame(frame)) {
      Serial.println("ERROR: FIFO read failed during range calibration.");
      return false;
    }
    float xA, yA, xB, yB;
    uint32_t signalA, signalB;
    const bool validA = calculateSensorAngles(frame, 0, xA, yA, signalA);
    const bool validB = calculateSensorAngles(frame, 4, xB, yB, signalB);
    float term = 0.0f;
    if (validA && validB && calculateTriangulationTerm(yA, yB, term)) {
      termSum += term;
      termSquaredSum += (double)term * (double)term;
      yASum += yA;
      yBSum += yB;
      accepted++;
    }
  }

  if (accepted < (RANGE_CALIBRATION_FRAMES * 3U) / 4U) {
    Serial.print("ERROR: Only "); Serial.print(accepted);
    Serial.println(" stable valid frames; check target signal and alignment.");
    return false;
  }

  const double meanTerm = termSum / accepted;
  const double variance = fmax(0.0, termSquaredSum / accepted - meanTerm * meanTerm);
  const double standardDeviation = sqrt(variance);
  const float newC = (float)(knownDistanceMm * meanTerm);

  Serial.print("Mean yA: "); Serial.println((float)(yASum / accepted), 6);
  Serial.print("Mean yB: "); Serial.println((float)(yBSum / accepted), 6);
  Serial.print("Mean triangulation term: "); Serial.println((float)meanTerm, 6);
  Serial.print("Term standard deviation: "); Serial.println((float)standardDeviation, 6);

  if (!saveTriangulationConstant(newC)) {
    Serial.println("ERROR: Calculated C was invalid; previous value retained.");
    return false;
  }
  Serial.println("Calibration saved. Normal distance output resumes.");
  angleFilterReady = false;
  return true;
}

static void resetTriangulationConstant()
{
  saveTriangulationConstant(DEFAULT_TRIANGULATION_C_MM);
  Serial.println("Theoretical starting C restored; use CAL <known_mm> for accuracy.");
}

// Non-blocking line parser. Serial input is never allowed to stall the FIFO
// acquisition loop while a command is incomplete.
static void handleSerialCommand(const char *line)
{
  if (strncmp(line, "CAL ", 4) == 0 || strncmp(line, "cal ", 4) == 0) {
    char *end = nullptr;
    const float knownDistance = strtof(line + 4, &end);
    if (end == line + 4 || !isfinite(knownDistance)) {
      Serial.println("Usage: CAL <known distance in mm>");
      return;
    }
    calibrateKnownDistance(knownDistance);
  } else if (strcmp(line, "ZERO") == 0 || strcmp(line, "zero") == 0) {
    calibrateBackground();
  } else if (strcmp(line, "SHOW") == 0 || strcmp(line, "show") == 0) {
    printRangeSettings();
  } else if (strcmp(line, "DEFAULT") == 0 || strcmp(line, "default") == 0) {
    resetTriangulationConstant();
  } else if (line[0] != '\0') {
    Serial.println("Commands: CAL <mm>, ZERO, SHOW, DEFAULT");
  }
}

static void pollSerialCommands()
{
  while (Serial.available() > 0) {
    const char c = (char)Serial.read();
    if (c == '\r') continue;
    if (c == '\n') {
      serialCommandBuffer[serialCommandLength] = '\0';
      handleSerialCommand(serialCommandBuffer);
      serialCommandLength = 0;
    } else if (serialCommandLength < sizeof(serialCommandBuffer) - 1) {
      serialCommandBuffer[serialCommandLength++] = c;
    } else {
      serialCommandLength = 0;
      Serial.println("Serial command too long; discarded.");
    }
  }
}

// Process one frame and output a calibrated object distance along the board's
// normal (z) axis. The ADI formula is undefined when the angular term is near 0.
static void processDistanceFrame(const uint32_t frame[8])
{
  float xA, yA, xB, yB;
  uint32_t signalA, signalB;
  const bool validA = calculateSensorAngles(frame, 0, xA, yA, signalA);
  const bool validB = calculateSensorAngles(frame, 4, xB, yB, signalB);

  if (!validA || !validB) {
    angleFilterReady = false;
    Serial.print("NO_TARGET,signalA="); Serial.print(signalA);
    Serial.print(",signalB="); Serial.println(signalB);
    return;
  }

  if (!angleFilterReady) {
    filteredYA = yA;
    filteredYB = yB;
    angleFilterReady = true;
  } else {
    filteredYA += ANGLE_FILTER_ALPHA * (yA - filteredYA);
    filteredYB += ANGLE_FILTER_ALPHA * (yB - filteredYB);
  }

  float term = 0.0f;
  if (!calculateTriangulationTerm(filteredYA, filteredYB, term)) {
    Serial.print("UNRESOLVED, yA="); Serial.print(filteredYA, 6);
    Serial.print(", yB="); Serial.print(filteredYB, 6);
    Serial.print(", signalA="); Serial.print(signalA);
    Serial.print(", signalB="); Serial.println(signalB);
    return;
  }

  const float distanceMm = triangulationCmm / term;
  if (!isfinite(distanceMm) || distanceMm <= 0.0f) {
    Serial.println("INVALID_DISTANCE");
    return;
  }

  Serial.print("DIST,"); Serial.print(distanceMm, 1);
  Serial.print(" mm,"); Serial.print(distanceMm / 10.0f, 2);
  Serial.print(" cm,yA="); Serial.print(filteredYA, 5);
  Serial.print(",yB="); Serial.print(filteredYB, 5);
  Serial.print(",term="); Serial.print(term, 6);
#if CN0569_DEBUG_DISTANCE
  Serial.print(",xA="); Serial.print(xA, 5);
  Serial.print(",xB="); Serial.print(xB, 5);
#endif
  Serial.print(",signalA="); Serial.print(signalA);
  Serial.print(",signalB="); Serial.println(signalB);
}

// -----------------------------------------------------------------------------
// Arduino setup and loop
// -----------------------------------------------------------------------------
void setup()
{
  Serial.begin(SERIAL_BAUD);
  delay(1200);
  Serial.println();
  Serial.println("CN0569 / ADPD1080 ESP32 triangulation distance");
  Serial.println("INT: GPIO 6; SDA: GPIO 4; SCL: GPIO 5");
  Serial.println("Remove the target during empty-scene baseline calibration.");

  Wire.begin(CN0569_SDA_PIN, CN0569_SCL_PIN, I2C_CLOCK_HZ);
  Wire.setClock(I2C_CLOCK_HZ);

  preferencesReady = rangePreferences.begin("cn0569Range", false);
  if (preferencesReady) {
    const float savedC = rangePreferences.getFloat("triCmm", DEFAULT_TRIANGULATION_C_MM);
    if (isfinite(savedC) && savedC > 0.0f && savedC <= 10000.0f) {
      triangulationCmm = savedC;
    }
  } else {
    Serial.println("WARNING: ESP32 Preferences unavailable; using theoretical C.");
  }

  if (!configureAdpd1080()) stopWithError("ADPD1080 initialisation/configuration failed.");
  if (!calibrate32kClock()) stopWithError("32 kHz/sample-clock calibration failed; check P1 INT to GPIO 6.");
  if (!calibrate32MHzClock()) stopWithError("32 MHz clock calibration failed.");

  if (!setAdcSampleRate(REQUESTED_SAMPLE_RATE_HZ)) {
    stopWithError("Could not set ADC sample rate.");
  }
  uint16_t fsample = 0;
  if (!readRegister(REG_FSAMPLE, fsample) || fsample == 0) {
    stopWithError("Could not read FSAMPLE register.");
  }
  Serial.print("Requested sample rate: "); Serial.print(REQUESTED_SAMPLE_RATE_HZ);
  Serial.print(" Hz; FSAMPLE="); Serial.print(fsample);
  Serial.print("; nominal integer readback=");
  Serial.print(32000UL / ((uint32_t)fsample * 4UL)); Serial.println(" Hz");

  if (!setMode(MODE_NORMAL)) stopWithError("Could not enter normal measurement mode.");
  delay(100);
  if (!calibrateBackground()) stopWithError("Empty-scene baseline calibration failed.");

  printRangeSettings();
  Serial.println();
  Serial.println("Distance output active. For calibration, hold a target at a known distance and send: CAL <mm>");
  Serial.println("Other commands: ZERO (empty scene), SHOW, DEFAULT");
}

void loop()
{
  uint32_t frame[8];
  if (!readAveragedFrame(frame)) {
    stopWithError("Could not acquire a complete eight-sample FIFO frame.");
  }
  processDistanceFrame(frame);
  pollSerialCommands();
}

Unfortunately, when I tried it, I was getting some unusual results for distance which was not what I was expecting. I performed a full calibration at 70mm which seemed to work.

image

But challenging the system with moving the target to 100mm and to 35mm respectively –

image image

Instead, I receive a wildly fluctuating result, likely because of the presence of no-signal “zero” counts, or I get told the target is at 85mm respectively. It wasn’t very obvious that the signal was tracking in either direction consistently when the target was slid back and forth. Perhaps my setup simply was not optimal – perhaps it covered too much of the field of view and the target was too “ambiguous”.

Instead, I opted to go for a more basic approach – intensity-based monitoring. In this case, just one photodiode would be enough and I’d rely on the way the intensity falls off with distance to get an indicative distance. But to make this work, I needed to calibrate it.

To do this, I got ChatGPT to modify the operational parameters to reduce the sample rate to around 30Hz and grab multiple samples to hopefully improve sensitivity and reduce noise. Trash doesn’t really move around when it’s inside the closed-lid of a bin.

[CN0569_ESP32_Arduino_Testing_Modes.ino]

/*
 * CN0569 (ADPD1080 + two ADPD2140 sensors) - ESP32 Arduino port (Multi-Mode Test)
 * Ported by OpenAI's ChatGPT GPT-6 Luna guided by Gough Lui
 *
 * Ported from the Analog Devices no-OS iio_adpd1080 example and the
 * ADPD188/ADPD1080 no-OS driver.
 *
 * Hardware assumptions:
 *   CN0569 P1 pin 1 INT  -> ESP32 GPIO 6 (used for 32 kHz/sample-clock calibration)
 *   CN0569 P1 pin 3 SCL  -> ESP32 GPIO 5
 *   CN0569 P1 pin 4 SDA  -> ESP32 GPIO 4
 *   CN0569 P1 pin 5 GND  -> ESP32 GND
 *   CN0569 P1 pin 6 VCC  -> regulated 3.3 V
 *   P1 pin 2 RESET is not connected on the CN0569.
 *
 * Board note: GPIO6 is suitable on the ESP32-S3 boards used for this port,
 * but GPIO6 is connected to SPI flash on the original ESP32 modules (where
 * GPIOs 6..11 must not be used). Confirm the exact ESP32 variant before wiring.
 *
 * The ADPD1080 I2C address is 0x64 (7-bit).  The board's LED1 output drives
 * the on-board IR LED by default.  This sketch uses the LED1 settings from
 * the ADI example; check the board supply and LED configuration before use.
 *
 * Operating profiles can be changed while running from the Serial Monitor:
 *   1 = approximately 30 Hz, 4 pulses per slot
 *   2 = approximately 30 Hz, 8 pulses per slot (default)
 *   3 = approximately 30 Hz, 16 pulses per slot
 *   4 = fast comparison, approximately 533 Hz, 4 pulses per slot
 *   ? = show the profile menu
 *
 * Output: one CSV row per sample:
 *   micros,pd0,pd1,pd2,pd3,pd4,pd5,pd6,pd7
 *
 * CN0569 photodiode channel order:
 *   pd0..pd3 = ADPD1080 PD1..PD4 = Sensor 1 XR, XL, YB, YT
 *   pd4..pd7 = ADPD1080 PD5..PD8 = Sensor 2 XR, XL, YB, YT
 *
 * This is a data-acquisition port.  It does not implement ADI's IIO server,
 * host-side Python gesture classification, or an application-level baseline
 * calibration algorithm.  It incorporates the register changes documented in 
 * @javagoza's Tiltie 04 post (https://community.element14.com/challenges-
 * projects/design-challenges/my-project-is-trash/f/forum/57465/tiltie---
 * 04-bringing-touch-free-gesture-control-to-tiltie-with-the-cn0569) including
 * trim adjustment, a 19 us LED period, photodiode reverse bias, and 50 kOhm
 * Slot A TIA gain (with Slot B retained at 200 kOhm).
 * Much thanks to @javagoza for the tweaks - it didn't work well without them!
 */

#include <Arduino.h>
#include <Wire.h>
#include <esp_timer.h>

// -----------------------------------------------------------------------------
// User-adjustable connections and operating parameters
// -----------------------------------------------------------------------------
#define CN0569_SDA_PIN       4
#define CN0569_SCL_PIN       5
#define CN0569_INT_PIN       6

static const uint8_t  ADPD1080_I2C_ADDRESS = 0x64;
static const uint32_t I2C_CLOCK_HZ = 400000;
static const uint32_t FIFO_WAIT_TIMEOUT_MS = 1000;
static const uint8_t  MAX_32K_CALIBRATION_STEPS = 64;
static const uint32_t SERIAL_BAUD = 921600;

// -----------------------------------------------------------------------------
// Selectable acquisition profiles
//
// All slow profiles use FSAMPLE=267, giving 32000/(4*267) = 29.96 Hz.
// The fast comparison profile uses FSAMPLE=15, giving 533.33 Hz. This is the
// integer-divided result of the original port's nominal 512 Hz request.
// Pulse count must remain a multiple of four for the four-pulse chop sequence.
// The pulse period stays at 19 us, the minimum recommended for a 4 us AFE
// integration window.
// -----------------------------------------------------------------------------
struct OperatingProfile {
  const char *name;
  uint16_t fsampleRegister;
  uint8_t pulsesPerSlot;
};

static const OperatingProfile OPERATING_PROFILES[] = {
  {"30 Hz / 4 pulses",       267,  4},
  {"30 Hz / 8 pulses",       267,  8},
  {"30 Hz / 16 pulses",      267, 16},
  {"Fast / 4 pulses (~533 Hz)", 15, 4}
};
static const uint8_t OPERATING_PROFILE_COUNT =
    sizeof(OPERATING_PROFILES) / sizeof(OPERATING_PROFILES[0]);
static const uint8_t DEFAULT_OPERATING_PROFILE = 1;  // 30 Hz / 8 pulses
static const uint8_t LED_PULSE_PERIOD_US = 19;
static uint8_t g_operatingProfileIndex = 0xFF;

// -----------------------------------------------------------------------------
// ADPD1080 register addresses used by the ADI example / driver
// -----------------------------------------------------------------------------
static const uint8_t REG_STATUS          = 0x00;
static const uint8_t REG_GPIO_DRV        = 0x02;
static const uint8_t REG_DEVID           = 0x08;
static const uint8_t REG_CLK_RATIO       = 0x0A;
static const uint8_t REG_GPIO_CTRL       = 0x0B;
static const uint8_t REG_SW_RESET        = 0x0F;
static const uint8_t REG_MODE            = 0x10;
static const uint8_t REG_SLOT_EN         = 0x11;
static const uint8_t REG_FSAMPLE         = 0x12;
static const uint8_t REG_PD_LED_SELECT   = 0x14;
static const uint8_t REG_NUM_AVG         = 0x15;
static const uint8_t REG_INT_SEQ_A       = 0x17;
static const uint8_t REG_INT_SEQ_B       = 0x1D;
static const uint8_t REG_ILED1_COARSE    = 0x23;
static const uint8_t REG_SLOTA_NUMPULSES = 0x31;
static const uint8_t REG_SLOTB_NUMPULSES = 0x36;
static const uint8_t REG_SLOTA_AFE_WINDOW= 0x39;
static const uint8_t REG_SLOTB_AFE_WINDOW= 0x3B;
static const uint8_t REG_SLOTA_AFE_CONFIG= 0x42;
static const uint8_t REG_SLOTB_AFE_CONFIG= 0x44;
static const uint8_t REG_SAMPLE_CLK      = 0x4B;
static const uint8_t REG_CLK32M_ADJUST   = 0x4D;
static const uint8_t REG_CLK32M_CAL_EN   = 0x50;
static const uint8_t REG_PD_REVERSE_BIAS = 0x54;
static const uint8_t REG_MATH            = 0x58;
static const uint8_t REG_DATA_ACCESS_CTL = 0x5F;
static const uint8_t REG_FIFO_ACCESS     = 0x60;

// Register field masks / constants.
static const uint16_t DEVICE_ID_ADPD1080 = 0x0A16;
static const uint16_t MODE_STANDBY = 0;
static const uint16_t MODE_PROGRAM = 1;
static const uint16_t MODE_NORMAL  = 2;

static const uint16_t SAMPLE_CLK_32K_ENABLE = 0x0080;
static const uint16_t SAMPLE_CLK_32K_ADJUST_MASK = 0x003F;
static const uint16_t SLOT_A_ENABLE = 0x0001;
static const uint16_t SLOT_A_FIFO_MASK = 0x001C;
static const uint16_t SLOT_B_ENABLE = 0x0020;
static const uint16_t SLOT_B_FIFO_MASK = 0x01C0;
static const uint16_t SLOT_FIFO_32BIT_4CHAN = 0x0006;
static const uint16_t SLOT_READOUT_MODE = 0x2000;
static const uint16_t SLOT_FIFO_OVERRUN_PREVENT = 0x1000;

// GPIO0 output configuration used during the ADI 1 kHz calibration routine.
static const uint16_t GPIO0_ENABLE = 0x0004;
static const uint16_t GPIO0_ACTIVE_PULSE_FUNCTION = 0x0002;

// The ADI driver reports the FIFO occupancy in the upper byte of STATUS.
static const uint8_t FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE = 32;

// -----------------------------------------------------------------------------
// Error reporting
// -----------------------------------------------------------------------------
static void stopWithError(const char *message)
{
  Serial.println();
  Serial.print("FATAL: ");
  Serial.println(message);
  while (true) {
    delay(1000);
  }
}

// -----------------------------------------------------------------------------
// Low-level I2C register access
// ADPD registers are 16-bit, most-significant byte first.
// -----------------------------------------------------------------------------
static bool writeRegister(uint8_t reg, uint16_t value)
{
  Wire.beginTransmission(ADPD1080_I2C_ADDRESS);
  Wire.write(reg);
  Wire.write((uint8_t)(value >> 8));
  Wire.write((uint8_t)(value & 0xFF));
  return (Wire.endTransmission() == 0);
}

static bool readRegister(uint8_t reg, uint16_t &value)
{
  Wire.beginTransmission(ADPD1080_I2C_ADDRESS);
  Wire.write(reg);
  if (Wire.endTransmission(false) != 0) {
    return false;
  }

  const uint8_t received = Wire.requestFrom(
      (uint8_t)ADPD1080_I2C_ADDRESS, (uint8_t)2, (uint8_t)true);
  if (received != 2 || Wire.available() < 2) {
    while (Wire.available()) {
      (void)Wire.read();
    }
    return false;
  }

  const uint8_t msb = (uint8_t)Wire.read();
  const uint8_t lsb = (uint8_t)Wire.read();
  value = ((uint16_t)msb << 8) | lsb;
  return true;
}

static bool updateRegister(uint8_t reg, uint16_t clearMask, uint16_t setBits)
{
  uint16_t value;
  if (!readRegister(reg, value)) {
    return false;
  }
  value = (uint16_t)((value & (uint16_t)~clearMask) | setBits);
  return writeRegister(reg, value);
}

static bool setMode(uint16_t mode)
{
  return writeRegister(REG_MODE, (uint16_t)(mode & 0x0003));
}

// The ADI driver's ADC-rate helper uses integer division:
// FSAMPLE = 32000 / (requested_rate * 4).
static bool setAdcSampleRate(uint16_t requestedRateHz)
{
  if (requestedRateHz == 0 || requestedRateHz > 2000) {
    return false;
  }
  const uint16_t fsample = (uint16_t)(32000UL / ((uint32_t)requestedRateHz * 4UL));
  return writeRegister(REG_FSAMPLE, fsample);
}

static bool readFifoFrameAndDiscard()
{
  Wire.beginTransmission(ADPD1080_I2C_ADDRESS);
  Wire.write(REG_FIFO_ACCESS);
  if (Wire.endTransmission(false) != 0) {
    return false;
  }

  const uint8_t received = Wire.requestFrom(
      (uint8_t)ADPD1080_I2C_ADDRESS,
      (uint8_t)FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE,
      (uint8_t)true);
  if (received != FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE ||
      Wire.available() < FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE) {
    while (Wire.available()) {
      (void)Wire.read();
    }
    return false;
  }

  for (uint8_t i = 0; i < FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE; i++) {
    (void)Wire.read();
  }
  return true;
}

// Stop conversions, discard complete old-profile frames, then apply the
// selected sample-rate and pulse-count settings before restarting acquisition.
static bool applyOperatingProfile(uint8_t profileIndex)
{
  if (profileIndex >= OPERATING_PROFILE_COUNT) {
    return false;
  }

  const OperatingProfile &profile = OPERATING_PROFILES[profileIndex];

  if (!setMode(MODE_PROGRAM)) {
    return false;
  }
  delay(2);

  // Discard any complete frames collected before the mode change. A frame is
  // always 32 bytes with both four-channel slots enabled in this configuration.
  for (uint8_t attempt = 0; attempt < 4; attempt++) {
    uint16_t status;
    if (!readRegister(REG_STATUS, status)) {
      return false;
    }
    const uint8_t fifoBytes = (uint8_t)((status >> 8) & 0xFF);
    if (fifoBytes < FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE) {
      break;
    }
    if (!readFifoFrameAndDiscard()) {
      return false;
    }
  }

  const uint16_t pulseSetting =
      (uint16_t)(((uint16_t)profile.pulsesPerSlot << 8) | LED_PULSE_PERIOD_US);

  if (!writeRegister(REG_FSAMPLE, profile.fsampleRegister) ||
      !writeRegister(REG_SLOTA_NUMPULSES, pulseSetting) ||
      !writeRegister(REG_SLOTB_NUMPULSES, pulseSetting)) {
    return false;
  }

  // Verify all profile registers before restarting the measurement state machine.
  uint16_t checkFsample, checkSlotA, checkSlotB;
  if (!readRegister(REG_FSAMPLE, checkFsample) ||
      !readRegister(REG_SLOTA_NUMPULSES, checkSlotA) ||
      !readRegister(REG_SLOTB_NUMPULSES, checkSlotB) ||
      checkFsample != profile.fsampleRegister ||
      checkSlotA != pulseSetting || checkSlotB != pulseSetting) {
    Serial.println("Acquisition profile register readback did not match the requested values.");
    return false;
  }

  delay(2);
  if (!setMode(MODE_NORMAL)) {
    return false;
  }

  g_operatingProfileIndex = profileIndex;

  const float actualRate = 32000.0f /
      (4.0f * (float)profile.fsampleRegister);
  Serial.println();
  Serial.print("Active profile: ");
  Serial.println(profile.name);
  Serial.print("  FSAMPLE register: ");
  Serial.println(profile.fsampleRegister);
  Serial.print("  Nominal sample rate: ");
  Serial.print(actualRate, 2);
  Serial.println(" Hz");
  Serial.print("  Pulses per slot: ");
  Serial.println(profile.pulsesPerSlot);
  Serial.print("  LED pulse period: ");
  Serial.print(LED_PULSE_PERIOD_US);
  Serial.println(" us");
  Serial.println("  TIA gains unchanged: Slot A 50 kOhm, Slot B 200 kOhm");
  return true;
}

static void printOperatingProfileMenu()
{
  Serial.println();
  Serial.println("CN0569 acquisition profiles (send one character):");
  Serial.println("  1 - ~30 Hz, 4 LED pulses per slot (slow-rate baseline)");
  Serial.println("  2 - ~30 Hz, 8 LED pulses per slot (recommended starting point)");
  Serial.println("  3 - ~30 Hz, 16 LED pulses per slot (higher sensitivity)");
  Serial.println("  4 - ~533 Hz, 4 LED pulses per slot (fast comparison)");
  Serial.println("  ? - show this menu");
  Serial.println();
}

static void processSerialCommands()
{
  while (Serial.available() > 0) {
    const char command = (char)Serial.read();
    if (command == '\r' || command == '\n' || command == ' ') {
      continue;
    }
    if (command == '?') {
      printOperatingProfileMenu();
      continue;
    }
    if (command >= '1' && command <= '4') {
      const uint8_t selectedProfile = (uint8_t)(command - '1');
      if (selectedProfile == g_operatingProfileIndex) {
        Serial.println("That acquisition profile is already active.");
      } else if (!applyOperatingProfile(selectedProfile)) {
        stopWithError("Could not switch acquisition profile.");
      }
      continue;
    }
    Serial.println("Unknown command. Send ? for the acquisition profile menu.");
  }
}

// -----------------------------------------------------------------------------
// 32 kHz/sample-clock calibration
//
// The ADI no-OS sample configures GPIO0 as an active-pulse output while the
// ADC sampling rate is set to 1 kHz.  The ESP32 counts rising edges for one
// second and adjusts SAMPLE_CLK until the count is closest to 1000.
// -----------------------------------------------------------------------------
static volatile uint32_t g_gpio0PulseCount = 0;

void IRAM_ATTR onCn0569IntRise()
{
  g_gpio0PulseCount++;
}

static uint32_t countGpioPulsesForOneSecond()
{
  noInterrupts();
  g_gpio0PulseCount = 0;
  interrupts();

  const uint64_t startUs = (uint64_t)esp_timer_get_time();
  while (((uint64_t)esp_timer_get_time() - startUs) < 1000000ULL) {
    delay(1);
  }

  noInterrupts();
  const uint32_t count = g_gpio0PulseCount;
  interrupts();
  return count;
}

static bool calibrate32kClock()
{
  Serial.println("Calibrating ADPD1080 sample clock using P1 INT...");

  if (!setAdcSampleRate(1000)) {
    return false;
  }
  if (!writeRegister(REG_GPIO_DRV, GPIO0_ENABLE)) {
    return false;
  }
  if (!writeRegister(REG_GPIO_CTRL, GPIO0_ACTIVE_PULSE_FUNCTION)) {
    return false;
  }
  if (!setMode(MODE_NORMAL)) {
    return false;
  }

  pinMode(CN0569_INT_PIN, INPUT);
  g_gpio0PulseCount = 0;
  attachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN), onCn0569IntRise, RISING);

  uint16_t sampleClockReg;
  if (!readRegister(REG_SAMPLE_CLK, sampleClockReg)) {
    detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));
    return false;
  }

  uint8_t currentAdjust = (uint8_t)(sampleClockReg & SAMPLE_CLK_32K_ADJUST_MASK);
  uint8_t bestAdjust = currentAdjust;
  uint32_t bestDifference = UINT32_MAX;

  for (uint8_t step = 0; step < MAX_32K_CALIBRATION_STEPS; step++) {
    const uint32_t pulseCount = countGpioPulsesForOneSecond();
    const uint32_t difference = (pulseCount > 1000U)
                                  ? (pulseCount - 1000U)
                                  : (1000U - pulseCount);

    Serial.print("  calibration pulse count = ");
    Serial.print(pulseCount);
    Serial.print("; error = ");
    Serial.println(difference);

    if (pulseCount == 0) {
      Serial.println("No INT pulses were counted. Check P1 pin 1 -> ESP32 GPIO 6.");
      detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));
      return false;
    }

    // Retain the best trim code.  Like the ADI routine, stop as soon as a
    // one-step adjustment no longer improves the measured 1 kHz pulse count.
    if (difference >= bestDifference) {
      break;
    }

    bestDifference = difference;
    bestAdjust = currentAdjust;

    if (difference == 0) {
      break;
    }

    int16_t nextAdjust = (int16_t)currentAdjust;
    if (pulseCount < 1000U) {
      nextAdjust--;
    } else {
      nextAdjust++;
    }

    if (nextAdjust < 0 || nextAdjust > 63) {
      break;
    }

    sampleClockReg = (uint16_t)((sampleClockReg & (uint16_t)~SAMPLE_CLK_32K_ADJUST_MASK)
                                | (uint16_t)nextAdjust);
    if (!writeRegister(REG_SAMPLE_CLK, sampleClockReg)) {
      detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));
      return false;
    }
    currentAdjust = (uint8_t)nextAdjust;
    delay(5);
  }

  detachInterrupt(digitalPinToInterrupt(CN0569_INT_PIN));

  // Restore the best trim value, even if the final test was worse.
  if (!readRegister(REG_SAMPLE_CLK, sampleClockReg)) {
    return false;
  }
  sampleClockReg = (uint16_t)((sampleClockReg & (uint16_t)~SAMPLE_CLK_32K_ADJUST_MASK)
                              | bestAdjust);
  if (!writeRegister(REG_SAMPLE_CLK, sampleClockReg)) {
    return false;
  }

  if (!setMode(MODE_PROGRAM)) {
    return false;
  }
  if (!setAdcSampleRate(16)) {
    return false;
  }
  if (!writeRegister(REG_GPIO_DRV, 0x0000)) {
    return false;
  }
  if (!writeRegister(REG_GPIO_CTRL, 0x0000)) {
    return false;
  }

  Serial.print("32 kHz/sample-clock trim selected: 0x");
  Serial.println(bestAdjust, HEX);
  return true;
}

// -----------------------------------------------------------------------------
// Internal 32 MHz clock calibration.
//
// IMPORTANT: The datasheet requires REG_CLK32M_ADJUST (0x4D) to start at
// 0x98.  The calculated signed correction is an offset from that base value,
// not a replacement value.  Writing a negative correction directly as an
// unsigned byte (for example -14 -> 0xF2) grossly over-trims the oscillator.
// This was one of the problems described in the element14 CN0569 post.
// This calibration must follow the 32 kHz calibration.
// -----------------------------------------------------------------------------
static bool calibrate32MHzClock()
{
  uint16_t value;

  // Always start the 32 MHz calibration from the datasheet power-up trim.
  if (!writeRegister(REG_CLK32M_ADJUST, 0x0098)) {
    return false;
  }

  if (!readRegister(REG_DATA_ACCESS_CTL, value)) {
    return false;
  }
  if (!writeRegister(REG_DATA_ACCESS_CTL, (uint16_t)(value | 0x0001))) {
    return false;
  }

  if (!readRegister(REG_CLK32M_CAL_EN, value)) {
    return false;
  }
  if (!writeRegister(REG_CLK32M_CAL_EN, (uint16_t)(value | 0x0020))) {
    return false;
  }

  delay(1);

  if (!readRegister(REG_CLK_RATIO, value)) {
    return false;
  }
  const uint16_t clockRatio = (uint16_t)(value & 0x0FFF);
  if (clockRatio == 0) {
    Serial.println("Invalid zero CLK_RATIO result during 32 MHz calibration.");
    return false;
  }

  const float clockError = 32000000.0f * (1.0f - ((float)clockRatio / 2000.0f));
  const int32_t adjustmentDelta = (int32_t)(clockError / 112000.0f);
  const int32_t correctedTrim = 0x98 + adjustmentDelta;

  if (correctedTrim < 0 || correctedTrim > 0xFF) {
    Serial.print("32 MHz trim correction is out of range: ");
    Serial.println(correctedTrim);
    return false;
  }

  // Apply the signed correction relative to 0x98; do not cast a negative
  // delta directly to uint8_t.
  if (!writeRegister(REG_CLK32M_ADJUST, (uint16_t)correctedTrim)) {
    return false;
  }

  if (!readRegister(REG_CLK32M_CAL_EN, value)) {
    return false;
  }
  if (!writeRegister(REG_CLK32M_CAL_EN, (uint16_t)(value & (uint16_t)~0x0020))) {
    return false;
  }

  if (!readRegister(REG_DATA_ACCESS_CTL, value)) {
    return false;
  }
  if (!writeRegister(REG_DATA_ACCESS_CTL, (uint16_t)(value & (uint16_t)~0x0001))) {
    return false;
  }

  Serial.print("32 MHz CLK_RATIO: ");
  Serial.println(clockRatio);
  Serial.print("32 MHz trim delta from 0x98: ");
  Serial.println(adjustmentDelta);
  Serial.print("32 MHz clock adjustment register: 0x");
  Serial.println((uint16_t)correctedTrim, HEX);
  return true;
}

// -----------------------------------------------------------------------------
// Device setup: directly follows adpd188_iio_init() and iio_example.c.
// -----------------------------------------------------------------------------
static bool configureAdpd1080()
{
  uint16_t value;

  // Verify the silicon ID before issuing the software reset.
  if (!readRegister(REG_DEVID, value)) {
    Serial.println("Could not read ADPD1080 device ID. Check power, wiring and I2C address.");
    return false;
  }
  Serial.print("ADPD device ID: 0x");
  Serial.println(value, HEX);
  if (value != DEVICE_ID_ADPD1080) {
    Serial.println("Unexpected device ID (expected 0x0A16 for ADPD1080).");
    return false;
  }

  if (!writeRegister(REG_SW_RESET, 0x0001)) {
    return false;
  }
  delay(10);

  // Enable the ADPD1080 state-machine clock, then enter program mode.
  if (!readRegister(REG_SAMPLE_CLK, value)) {
    return false;
  }
  if (!writeRegister(REG_SAMPLE_CLK, (uint16_t)(value | SAMPLE_CLK_32K_ENABLE))) {
    return false;
  }
  if (!setMode(MODE_PROGRAM)) {
    return false;
  }

  // Enable slots A and B, each with 32-bit FIFO words for all four channels.
  if (!readRegister(REG_SLOT_EN, value)) {
    return false;
  }
  value &= (uint16_t)~(SLOT_A_ENABLE | SLOT_A_FIFO_MASK | SLOT_B_ENABLE | SLOT_B_FIFO_MASK);
  value |= SLOT_A_ENABLE | (SLOT_FIFO_32BIT_4CHAN << 2);
  value |= SLOT_B_ENABLE | (SLOT_FIFO_32BIT_4CHAN << 6);
  if (!writeRegister(REG_SLOT_EN, value)) {
    return false;
  }

  // Slot A selects photodiodes 1-4; Slot B selects photodiodes 5-8.
  // LED selector 1 selects LEDX1 (the CN0569's on-board IR LED on its default build).
  if (!readRegister(REG_PD_LED_SELECT, value)) {
    return false;
  }
  value &= (uint16_t)~0x0FFF;
  value |= (uint16_t)(1U | (1U << 2) | (5U << 4) | (4U << 8));
  if (!writeRegister(REG_PD_LED_SELECT, value)) {
    return false;
  }

  // Disable averaging / decimation for both slots.
  if (!writeRegister(REG_NUM_AVG, 0x0000)) {
    return false;
  }

  // Initial ADC rate used by the ADI example before calibration.
  if (!setAdcSampleRate(16)) {
    return false;
  }

  // Enable the readout mode and FIFO overflow-prevention feature.
  if (!updateRegister(REG_SLOT_EN, 0x0000,
                      SLOT_READOUT_MODE | SLOT_FIFO_OVERRUN_PREVENT)) {
    return false;
  }

  // Chop sequence: inverted, non-inverted, non-inverted, inverted.
  if (!updateRegister(REG_INT_SEQ_A, 0x0000, 0x0009)) {
    return false;
  }
  if (!updateRegister(REG_INT_SEQ_B, 0x0000, 0x0009)) {
    return false;
  }

  // LED1 coarse current, slew and scale settings from the ADI example.
  // The CN0569's LED1 driver sinks current for the on-board IR LED by default.
  if (!readRegister(REG_ILED1_COARSE, value)) {
    return false;
  }
  value &= (uint16_t)~(0x000F | 0x0070);
  value |= (uint16_t)(0x0006 | (0x0003 << 4) | 0x2000);
  if (!writeRegister(REG_ILED1_COARSE, value)) {
    return false;
  }

  // Establish a safe four-pulse starting value. The selected operating
  // profile overwrites the pulse count after clock calibration. Keep the
  // period at 19 us: the datasheet minimum for a 4 us AFE integration window.
  if (!writeRegister(REG_SLOTA_NUMPULSES, 0x0413)) {
    return false;
  }
  if (!writeRegister(REG_SLOTB_NUMPULSES, 0x0413)) {
    return false;
  }

  // AFE integration windows: width 4, offset 0x2F0, for both slots.
  if (!writeRegister(REG_SLOTA_AFE_WINDOW, 0x22F0)) {
    return false;
  }
  if (!writeRegister(REG_SLOTB_AFE_WINDOW, 0x22F0)) {
    return false;
  }

  // Integrator chop mode: -P1 + P2 + P3 - P4.  In this mode the chop
  // sequence itself cancels the digital ADC offsets, so all eight per-channel
  // offset registers must be zero rather than their 0x2000 reset defaults.
  // Note that 0x1C and 0x1D are not offset registers; 0x1D is INT_SEQ_B.
  static const uint8_t offsetRegisters[] = {
    0x18, 0x19, 0x1A, 0x1B,  // Slot A channels 1..4
    0x1E, 0x1F, 0x20, 0x21   // Slot B channels 1..4
  };
  for (size_t i = 0; i < sizeof(offsetRegisters) / sizeof(offsetRegisters[0]); i++) {
    if (!writeRegister(offsetRegisters[i], 0x0000)) {
      Serial.print("Failed to clear ADC offset register 0x");
      Serial.println(offsetRegisters[i], HEX);
      return false;
    }
  }

  // Apply approximately 250 mV photodiode reverse bias to both time slots.
  // 0x0AA0 sets Register 0x54 bit 7 and Bits[11:8] to 0b10_10.
  if (!writeRegister(REG_PD_REVERSE_BIAS, 0x0AA0)) {
    return false;
  }

  // The first ADPD2140 is much closer to the IR LED and can saturate at
  // 200 kOhm.  Set Slot A to 50 kOhm; retain 200 kOhm for Slot B.
  // TIA gain field is Register 0x42/0x44 Bits[1:0]: 0=200k, 1=100k,
  // 2=50k, 3=25k.  Bits[3:2] are reserved and the datasheet says to write 01.
  // Preserve all other AFE configuration fields.
  if (!updateRegister(REG_SLOTA_AFE_CONFIG, 0x000F, 0x0006)) {
    return false;
  }
  if (!updateRegister(REG_SLOTB_AFE_CONFIG, 0x000F, 0x0004)) {
    return false;
  }

  // Math/chop configuration used by the ADI example.
  if (!updateRegister(REG_MATH, 0x0F66, 0x0544)) {
    return false;
  }

  return true;
}

// -----------------------------------------------------------------------------
// FIFO acquisition: one frame contains 16 x 16-bit FIFO words:
// (low word, high word) for each of eight 32-bit photodiode values.
// -----------------------------------------------------------------------------
static bool readOneEightChannelSample(uint32_t samples[8])
{
  const uint32_t startMs = millis();
  uint16_t status;

  while (true) {
    if (!readRegister(REG_STATUS, status)) {
      return false;
    }

    const uint8_t fifoBytes = (uint8_t)((status >> 8) & 0xFF);
    if (fifoBytes >= FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE) {
      break;
    }

    if ((uint32_t)(millis() - startMs) >= FIFO_WAIT_TIMEOUT_MS) {
      Serial.println("Timed out waiting for a complete FIFO sample.");
      return false;
    }
    delay(1);
  }

  // FIFO_ACCESS supports I2C multiword reads: the FIFO pointer advances by
  // one 16-bit word after each acknowledged word.  Read the complete 32-byte
  // packet in one transaction rather than issuing sixteen separate register
  // reads, which reduces bus overhead and helps avoid filling the 128-byte FIFO.
  Wire.beginTransmission(ADPD1080_I2C_ADDRESS);
  Wire.write(REG_FIFO_ACCESS);
  if (Wire.endTransmission(false) != 0) {
    return false;
  }

  const uint8_t received = Wire.requestFrom(
      (uint8_t)ADPD1080_I2C_ADDRESS,
      (uint8_t)FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE,
      (uint8_t)true);
  if (received != FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE ||
      Wire.available() < FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE) {
    while (Wire.available()) {
      (void)Wire.read();
    }
    Serial.print("Incomplete FIFO packet: received ");
    Serial.print(received);
    Serial.print(" of ");
    Serial.print(FIFO_BYTES_PER_EIGHT_CHANNEL_SAMPLE);
    Serial.println(" bytes.");
    return false;
  }

  // Each FIFO word is transmitted most-significant byte first.  The 32-bit
  // channel sequence is low word followed by high word, matching the ADI
  // 32-bit FIFO format used by the original port.
  uint16_t fifoWords[16];
  for (uint8_t i = 0; i < 16; i++) {
    const uint8_t msb = (uint8_t)Wire.read();
    const uint8_t lsb = (uint8_t)Wire.read();
    fifoWords[i] = ((uint16_t)msb << 8) | lsb;
  }

  for (uint8_t channel = 0; channel < 8; channel++) {
    const uint32_t lowWord = (uint32_t)fifoWords[channel * 2];
    const uint32_t highWord = (uint32_t)fifoWords[channel * 2 + 1];
    // The ADI IIO channel definition uses 27 meaningful bits in 32-bit storage.
    samples[channel] = (lowWord | (highWord << 16)) & 0x07FFFFFFUL;
  }

  return true;
}

static void printSample(const uint32_t samples[8])
{
  Serial.print((uint32_t)micros());
  for (uint8_t i = 0; i < 8; i++) {
    Serial.print(',');
    Serial.print(samples[i]);
  }
  Serial.println();
}

// -----------------------------------------------------------------------------
// Arduino entry points
// -----------------------------------------------------------------------------
void setup()
{
  Serial.begin(SERIAL_BAUD);
  delay(1500);

  Serial.println();
  Serial.println("CN0569 / ADPD1080 ESP32 acquisition example");
  Serial.println("Starting I2C at 400 kHz...");

  Wire.begin(CN0569_SDA_PIN, CN0569_SCL_PIN, I2C_CLOCK_HZ);
  Wire.setClock(I2C_CLOCK_HZ);

  if (!configureAdpd1080()) {
    stopWithError("ADPD1080 initialisation/configuration failed.");
  }

  if (!calibrate32kClock()) {
    stopWithError("32 kHz/sample-clock calibration failed. Check P1 INT to GPIO 6.");
  }

  if (!calibrate32MHzClock()) {
    stopWithError("32 MHz clock calibration failed.");
  }

  // Start with the default selectable profile (30 Hz / 8 pulses per slot).
  // The same profile selector can be used later from the Serial Monitor.
  if (!applyOperatingProfile(DEFAULT_OPERATING_PROFILE)) {
    stopWithError("Could not apply the default acquisition profile.");
  }

  // Read back the settings that address the channel problems reported in the
  // element14 CN0569 post.  These values are useful when diagnosing wiring,
  // board revisions, or an unexpected register write failure.
  Serial.println("Corrected CN0569 register settings:");
  const uint8_t verifyRegisters[] = {
    0x18, 0x19, 0x1A, 0x1B, 0x1E, 0x1F, 0x20, 0x21,
    REG_FSAMPLE, REG_SLOTA_NUMPULSES, REG_SLOTB_NUMPULSES,
    REG_SLOTA_AFE_CONFIG, REG_SLOTB_AFE_CONFIG,
    REG_PD_REVERSE_BIAS, REG_CLK32M_ADJUST
  };
  for (size_t i = 0; i < sizeof(verifyRegisters) / sizeof(verifyRegisters[0]); i++) {
    uint16_t regValue;
    if (!readRegister(verifyRegisters[i], regValue)) {
      Serial.print("  register read failed: 0x");
      Serial.println(verifyRegisters[i], HEX);
      continue;
    }
    Serial.print("  0x");
    if (verifyRegisters[i] < 0x10) Serial.print('0');
    Serial.print(verifyRegisters[i], HEX);
    Serial.print(" = 0x");
    if (regValue < 0x1000) Serial.print('0');
    if (regValue < 0x0100) Serial.print('0');
    if (regValue < 0x0010) Serial.print('0');
    Serial.println(regValue, HEX);
  }

  printOperatingProfileMenu();
  Serial.println("timestamp_us,pd0,pd1,pd2,pd3,pd4,pd5,pd6,pd7");
}

void loop()
{
  processSerialCommands();

  uint32_t samples[8];
  if (!readOneEightChannelSample(samples)) {
    stopWithError("FIFO acquisition failed. Check I2C wiring and sensor power.");
  }
  printSample(samples);
}

To calibrate it, I mounted the sensor vertically on a vertically-mounted external optical drive. The sensor is mounted about 3cm above the table, to avoid table-based reflections from affecting the readings too much. I used PuTTY to capture the serial data, using Mode 3 for the best sensitivity. Initially, there was no item in the field-of-view. I then introduced and  moved a 3D printed enclosure for my own previously-designed automatic transfer switch in 5cm steps from 5cm through to 35cm.

image

I then pulled the data into Excel for a graphical analysis. Rather than summing all four channels for intensity, which Analog Devices does, I decided to take the average instead. Perhaps this is not as sensitive, but perhaps it could be a bit lower in noise.

image

It seems that the datasheet indicating the gesture sensing distance to be “up to 20cm” is borne-out when looking at the raw photodiode values which show that the values were getting a bit noisy already. The characteristic between the two photodiodes is quite different too – I think it’s not just the gain, but perhaps also stray IR light and dark-current compensation settings resulting in that one having a non-zero value when there’s even no target in front of the board. Sticking with PD-B, I think we can get away with detecting up to 30cm but perhaps a bit unreliably and very noisy.

image

Taking visually some of the readings at various distances, I can fit an equation to the data which approximates a nearly-straight line on a semi-log plot.

image

Using this equation to interpret the raw data, then taking a 30-sample moving average that approximates collecting 1s of data and averaging it out, we can see that the equation indeed works decently as long as zero is taken as not-present and samples are excluded from the averaging.

As a result, I think this approach can work, but because of the limited sensing distance, it will only really be able to tell us if the bin is 67%+ full or more (depending on the height of the bin).

Assembling the Battery Pack & Charging Circuit

Now, onto the other “P” for today, which is power. While I’ve identified a series of Li-Poly cells salvaged from broken-down Dell laptop battery packs, I’ll need to get three of them together to get enough energy storage to be sure that even an inefficient system would keep running long enough to cover a string of cloudy days as solar power is very much dependent on having good sun and sky access.

Of course, there is the obligatory warning that bare lithium-based cells can be quite dangerous. Be sure not to short them out, overcharge, overdischarge, crush or chew on them. Do not directly solder to the terminals of the cells and do not work with such cells if you aren’t confident. This is especially sage advice if you happen to be a raccoon … as some irresponsible humans may illegally dispose of batteries in household waste!

image

Thankfully, no animals (including humans) were harmed in the process of setting up the power infrastructure.

To make my life easier, I’ve chosen three cells which I’ve cut out of packs which still have flexible-PCBs attached to them. These are copper foil inside a polyimide insulating layer which can be cut and scraped off. Because of this, it is safe to solder to these sections as the heat will dissipate before reaching the pouch where it will cause cell damage and potentially catastrophic consequences. Most positive tabs on pouch cells are made of aluminium, which you can’t readily solder to, which is why I like to keep these “tails” connected where possible. Perhaps if I had a spot-welder, that wouldn’t be such an issue.

image

The next step was to add a bit of heatshrink around the connection, to insulate the connections. A short is potentially catastrophic, as such cells can often dump multiple-C-rate current which leads to a lot of heat and potentially stress to cells that might cause them to fail catastrophically.

image

At the point of assembly, all cells were discharged to a virtually identical 0% SoC state, to reduce the risk that a short would pose during construction. The three cells are to be paralleled, so I joined all the wires together and connected it into the charging module. The additional connections on the module were soldered to flying leads for later connection, but it was covered with tape to avoid potential short-circuits.

image

It’s messy, but functional. To keep my three cells together, I used some pink Nitto electrical tape – it can’t be too solid or strong since the cells can swell slightly as they age. The enclosure will have to take this into account too.

image image

To make sure the cells didn’t suffer too much, I plugged the module into a USB-C power source and let it charge overnight. The charge was successful, taking over 10 hours (as expected) and it terminated too, which is good. I’ll have to take some time in another post to attach the power input and power output wires to the appropriate connectors.

Readying the Solar Panel

As the solution itself hasn’t been developed yet, I have little idea as to how much the power consumption of the solution would be. I wouldn’t want it consuming more than about 0.333W continuously at a maximum, as that would mean 8Wh per day consumed from my ~40Wh pack meaning that it’d need to be recharged around every five days, which meets the availability requirements to ride-out five cloudy days (to ensure high availability). If I can get this down with deep-sleep, I can extend that time significantly.

But we can theoretically extend this indefinitely through the use of a solar panel, as it can collect energy from the sun and recharge the battery. If, on average, we collect more energy that is spent, we can theoretically operate indefinitely.

The panel itself is rated at 6W, but it will be situated flat on top of a bin. The sub-optimal orientation will cost efficiency, reducing the output to about 5.25W tops. I’m in a country where we average around 4.5 peak-sun-hours per day, so we can expect about 23.625Wh per day at the best. But let’s say we lose about 50% of this as reserve to make up for cloudy days, this points to about 0.49W of tolerated load. So, it turns out the solar panel is rated about right, if not a tiny bit generous. But better to have a properly made EVA+glass laminate type panel with an aluminium frame than a polymer type panel which will yellow, crack or go cloudy if used continuously.

image

The small solar panel I obtained comes without pre-installed cables, instead, having a junction box on the rear where the user is expected to install their own cable.

image

It wasn’t marked on the junction box, so I had to get some light and use a multimeter to check which connection was positive and which was negative. I decided to add a printed label to make it clear. In terms of cable, it’s only expected to carry 1A so even a relatively-thin cable would be sufficient, but instead I decided to use a more automotive-grade double-sheathed cable instead.

image

Soldering the wires to the terminals needs to be done relatively quickly, otherwise the heat will melt the junction box itself. But another way may simply to crimp to ring or fork terminals and screw them in. Rather than just connect a wire to the output, I’ve also put a diode in series, an ordinary 1N4004, simply to prevent any dark-current flow at night. I probably should have covered it with heatshrink to provide some additional assurance that it wouldn’t short out, but it’s already soldered so I guess that’ll do. Because the cable is a bit thinner than what the cable retention system is designed for, I had to turn the retention clip upside down so that it would apply pressure, but this made closing the junction box a bit trickier. How do I know this isn’t quite a quality product? Simply because the junction box isn’t waterproof! But I guess if we’re only working at low DC voltages, the worst that can happen is that it simply stops working.

image

The other end of the cable has been terminated in one of the Camdenboss CTBP92HD/4 Pluggable Terminal Block, using just the outer-two connections. This will make it easy to detach the solar panel from the rest of the electronics when it’s necessary to reprogram it or to repair it. By connecting it this way, I hope that I can also find a pin allocation that will avoid any potential damage in case a plug is plugged into the wrong receptacle, as all of the provided plugs and sockets are the same.

That being said, because of the way the pack is configured, I can chop up a USB cable and wire it up into another plug, such that if the solar panel is broken or isn’t getting enough sun, you can still plug in a USB charger or a USB power bank to top up the unit’s internal batteries. Pluggable versatility!

image

The solar panel is now ready for operation, but being a nocturnal animal, the raccoons didn’t understand that while moonlight is technically solar in nature, it’s not powerful enough to generate any appreciable power.

image

It is working … I swear! Perhaps raccoons should just stick with power banks and plug-in chargers …

Conclusion

The raccoons have had a good day getting some things built. The Analog Devices CN0569 wasn’t quite as easy to get going as I had initially expected, owing to bringing my own platform, but at least I was able to get it running with the help of AI and javagoza ’s post. While I was able to get gestures working on the ESP32-S3, that wasn’t the end-goal. Instead, I tried to get the triangulation working, but the result seemed unstable and inverted from my expectation, instead falling-back to a calibrated inverse-square intensity-based mode of proximity operation. This isn’t ideal especially if the reflectivity of the target changes, but it’s likely still good enough for an approximate bin-filling measurement, especially one which focuses on giving data about the bin when it’s approaching full.

As for power, the batteries and a solar panel have been prepared ad an approximate power budget of 0.33W is allocated. That being said, there’s still a lot of building and testing still to be done and the raccoons are itching to get it underway …

What will be the next problem the raccoons will face, I wonder?

AI Disclosure: AI has been used in the generation of a number of images in this post which involve raccoons. AI has not been used to generate or modify any of the text or photographs of products and electronic items. AI has been used to port source code from platform-to-platform, apply debugging modifications and edit/optimise operational parameters. AI has not been used to perform manual tasks (e.g. wire stripping, heatshrinking, soldering, plugging/unplugging connections - I don't have a robot handy unfortunately ...).

  • Sign in to reply
  • Cancel
Parents
  • javagoza
    javagoza 14 hours ago

    Hi Gough,

    First of all, I'm sorry the GitHub link didn't work for you. I've just tested it again and it seems to be working correctly from my side.

    To make it easier, here's the direct link to the CN0569 library used in the project:

    smart-tilting-bin/libs/cn0569 at main · javagoza/smart-tilting-bin

    I hope this one works for you. Thanks for taking the time to look at the project and for mentioning it in your post.

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • Gough Lui
    Gough Lui 3 hours ago in reply to javagoza

    Once again, my thanks to you for your notes as they helped quite a bit. I don't know why, but GitHub might have been having some issues the day I was visiting as I was getting a 404 for your repository link. It seems to be working today though ... and the direct link works too!

    That being said ... the raccoons are looking up into the sky, on alert for magpie swoops ...

    - Gough

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
Reply
  • Gough Lui
    Gough Lui 3 hours ago in reply to javagoza

    Once again, my thanks to you for your notes as they helped quite a bit. I don't know why, but GitHub might have been having some issues the day I was visiting as I was getting a 404 for your repository link. It seems to be working today though ... and the direct link works too!

    That being said ... the raccoons are looking up into the sky, on alert for magpie swoops ...

    - Gough

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
Children
No Data
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2026 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube