Skip to main content

Water System Monitoring - updates

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

Adafruit_ADS1115 ads;

// Divider values (Ohms)
const float Rtop = 10000.0;   // sensor signal -> A0
const float Rbottom = 10000.0; // A0 -> GND
const float dividerGain = (Rbottom / (Rtop + Rbottom)); // = 0.5
const float dividerInverse = 1.0 / dividerGain;         // = 2.0

// Sender type: set true for 0.5–4.5 V (most common), false for 0–5 V
const bool senderIsRatiometric = true;

// ADC config
// Gain=1 => ±4.096 V full-scale (LSB ≈ 125 µV); input must still be between GND and VDD=3.3 V
const adsGain_t gain = GAIN_ONE;

// Smoothing
float psiFiltered = 0.0f;
const float alpha = 0.2f; // 0..1, higher = faster

void setup() {
  Serial.begin(115200);
  delay(100);

  Wire.begin(); // uses default SDA=21, SCL=22 on ESP32
  if (!ads.begin(0x48)) {
    Serial.println("ADS1115 not found. Check wiring/address.");
    while (1) delay(10);
  }
  ads.setGain(gain);
  ads.setDataRate(RATE_ADS1115_128SPS); // plenty for pressure

  Serial.println("ADS1115 ready. Reading pressure on A0...");
}

float countsToVolts(int16_t counts) {
  // Adafruit library helper:
  // computeVolts() converts raw counts to volts based on gain setting.
  return ads.computeVolts(counts);
}

float voltsToPsi(float v_ads) {
  // Recover sensor pin voltage before the divider
  float v_sensor = v_ads * dividerInverse;

  float psi;
  if (senderIsRatiometric) {
    // Map 0.5–4.5V to 0–100 psi
    const float vMin = 0.5f;
    const float vMax = 4.5f;
    psi = (v_sensor - vMin) * (100.0f / (vMax - vMin)); // *25
  } else {
    // Map 0–5V to 0–100 psi
    psi = (v_sensor / 5.0f) * 100.0f;
  }

  // Clamp to a sane range
  if (psi < 0.0f) psi = 0.0f;
  if (psi > 100.0f) psi = 100.0f;
  return psi;
}

void loop() {
  int16_t raw = ads.readADC_SingleEnded(0);
  float v_ads = countsToVolts(raw);
  float psi = voltsToPsi(v_ads);

  // Simple smoothing
  psiFiltered = alpha * psi + (1.0f - alpha) * psiFiltered;

  Serial.print("Raw: "); Serial.print(raw);
  Serial.print(" | Vads: "); Serial.print(v_ads, 4);
  Serial.print(" V | PSI: "); Serial.print(psi, 2);
  Serial.print(" | PSI(smoothed): "); Serial.println(psiFiltered, 2);

  delay(100);
}