ADS1015 ads.begin() and serial monitor not working

Hello I have been trying to use ADS1115 with my current setup, but since i added the ads.begin() the serial monitor stopped working and the code stops running.
Does anyone know what the problem could be?

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

float tempMax = 1023;             // Maximum temperature value (inverse relationship with temperature)
float tempMin = 0;                // Minimum temperature value
float currentMax = 1023;          // Maximum current reading
float currentMin = 0;             // Minimum current reading
float tempValue = 0;              // Current temperature value
float currentValue = 0;           // Current current value
float rangeCurrent = 0;           // Range of current values in bits!
float rangeTemp = 0;              // Range of temperature values in bits!
float rangeTempC = 0;             // Range of temperature values in °C
float experimentStarted = 0;      // Flag to indicate if the experiment is running
float restartExperiment = 0;      // Flag to indicate the need to restart the experiment
float experimentTime = 0;         // Experiment duration in minutes
float scalingTemp = 0;            // Scaling factor from bits to volts for temperature
float scalingCurrent = 0;         // Scaling factor from bits to volts for current
float readingsCount = 0;          // Number of reading done while waiting for 'done' in calibration process
float totalValue = 0;             // Cumulative value of the readings while waiting for 'done' in calibration process
float elapsedMinutes = 0;         // Time elapsed in the current experiment
float inputCurrent = 0;           // Current current value
float inputTemperature = 0;       // Current temperature reading
float calibrationStartTime = 0;   // Declare calibration start time
float setpointTemperature = 0;    // Setpoint temperature
float controlPWM = 0;             // PWM output
unsigned long startTime = 0;      // Start time of experiment
unsigned long lastPrintTime = 0;  // Variable to store the last time the elapsed time was printed
const int pwmPin = 3;             // PWM-capable pin for temperature control
int inputValue = 0;               // Instantaneous value read in the calibration process

Adafruit_ADS1115 ads;  // Use this for the 16-bit version

void setup() {
  Serial.begin(9600);
  ads.begin();
  delay(1000);  // Add delay after ads.begin()
  while (!Serial) {
    ;  // Wait for the serial port to connect
  }
  pinMode(pwmPin, OUTPUT);
  delay(1000);
  Serial.flush();
  // Get user input for setpointTemperature
  Serial.println("Enter the desired setpoint temperature in °C and press Enter:");
  while (!Serial.available()) {
    // Wait for user input
  }
  setpointTemperature = Serial.parseFloat();  // Read user input as a float
  Serial.read();                              // Clear the newline character from the input buffer
  Serial.println("Setpoint temperature: " + String(setpointTemperature, 2) + " °C");
  // Get user input for experimentTime
  Serial.println("Enter the duration of the experiment in minutes and press Enter:");
  while (!Serial.available()) {
    // Wait for user input
  }
  experimentTime = Serial.parseFloat();  // Read user input as a float
  Serial.read();
  Serial.println("Experiment time: " + String(experimentTime, 2) + " minutes");
  calibrateSensors();  // Perform sensor calibration
  Serial.read();
  Serial.println("To start the experiment, type 'yes' and press Enter.");
}

void loop() {
  if (restartExperiment == 1) {
    Serial.println("Do you want to start a new experiment?");
    restartExperiment = 0;
    experimentStarted = 0;
  }

  while (!experimentStarted) {
    // Waiting for experiment start or restart command
    waitForExperimentStart();
  }

  elapsedMinutes = (millis() - calibrationStartTime) / 60000;

  int16_t adc0, adc1;

  tempValue = ads.readADC_SingleEnded(0);     // Read from channel 0
  currentValue = ads.readADC_SingleEnded(1);  // Read from channel 1


  // Convert sensor reading to temperature
  inputTemperature = convertToTemperature(tempValue, scalingTemp);

  // Convert sensor reading to current
  inputCurrent = convertToCurrent(currentValue, scalingCurrent, currentMax, currentMin);

  // Create range of Temperature in °C
  rangeTempC = convertToTemperature(tempMax, scalingTemp) - convertToTemperature(tempMin, scalingTemp);

  // Perform PID control
  controlPWM = constrain(((inputTemperature - setpointTemperature) / rangeTempC) * 255, 0, 255);

  // Apply control output to the system
  analogWrite(pwmPin, controlPWM);
  // Print elapsed time every second
  if (millis() - lastPrintTime >= 1000) {
    lastPrintTime = millis();  // Update the last print time

    Serial.print("Elapsed Time: ");
    Serial.print(int(elapsedMinutes));  // Print minutes
    Serial.print(" minutes and ");
    Serial.print(int((elapsedMinutes - int(elapsedMinutes)) * 60));  // Print seconds
    Serial.println(" seconds");
    Serial.println("Temperature: " + String(inputTemperature, 2) + " °C, Current: " + String(inputCurrent, 2) + " A");
  }

  if (elapsedMinutes >= experimentTime) {
    Serial.println("Experiment Completed - " + String(experimentTime, 2) + " minutes have passed.");
    restartExperiment = 1;
  }
}

void waitForExperimentStart() {
  startTime = millis();
  if (Serial.available() > 0) {
    String userInput = Serial.readStringUntil('\n');
    userInput.trim();
    if (userInput.equalsIgnoreCase("yes")) {
      experimentStarted = 1;
      Serial.println("Experiment Started.");
      calibrationStartTime = millis();  // Set the calibration start time
    }
  }
}

float convertToTemperature(float tempReading, float scalingTemp) {
  // Convert analog temperature value and scale it to temperature range 4°C-37°C
  //return 20.439 - 2.0656 * (tempReading * scalingTemp);
  return 20.439 - 2.0656 * (((((tempReading * 5) / 65535) - 2.5) * 3.7) * scalingTemp);
}

float convertToCurrent(float currentReading, float scalingCurrent, float currentMax, float currentMin) {
  // Convert the current value and scale it to the range 0A-3.9A
  //return ((currentMin - currentReading) / (currentMin - currentMax)) * scalingCurrent * 3.9;
  return ((currentMin - ((((currentReading * 5) / 65535) - 2.5) * 3.7)) / (currentMin - currentMax)) * scalingCurrent * 3.9;
}


void calibrateSensors() {
  Serial.println("Sensor Calibration Process Starting...");
  Serial.println("Follow the steps to calibrate the sensors:");

  // Temperature Calibration
  Serial.println("1. Set the temperature to 37°C and match it to -8V.");
  Serial.println("2. Set the temperature to 20.5°C and match it to 0V.");
  Serial.println("3. Repeat until you reach values with precision deemed acceptable. Type 'done' when ready.");
  waitForCalibrationStep();

  Serial.println("4. Set the temperature to 4°C. Type 'done' when ready.");
  waitForCalibrationStep();

  Serial.println("5. Recording the analog input. Type 'done' when done.");
  tempMin = waitForAnalogInput(A0);

  Serial.println("6. Set the temperature to 37°C. Type 'done' when ready.");
  waitForCalibrationStep();

  Serial.println("7. Recording the analog input. Type 'done' when done.");
  tempMax = waitForAnalogInput(A0);

  scalingTemp = (8 - (-8)) / (tempMin - tempMax);

  // Current Calibration
  Serial.println("8. Set the current to 0A and match it to 5V.");
  Serial.println("9. Set the current to 3.9A and match it to 1V.");
  Serial.println("10. Repeat until you reach values with precision deemed acceptable. Type 'done' when ready.");
  waitForCalibrationStep();

  Serial.println("11. Set the current to 0A. Type 'done' when ready.");
  waitForCalibrationStep();

  Serial.println("12. Recording the analog input. Type 'done' when done.");
  currentMin = waitForAnalogInput(A1);

  Serial.println("13. Set the current to 3.9A. Type 'done' when ready.");
  waitForCalibrationStep();

  Serial.println("14. Recording the analog input. Type 'done' when done.");
  currentMax = waitForAnalogInput(A1);

  scalingCurrent = (1 - 5) / (currentMax - currentMin);

  Serial.println("Sensor Calibration Completed");

  // Display the calibration results
  Serial.print("Calibration Results - Temperature (°C): ");
  Serial.print("Min= ");
  Serial.print(convertToTemperature(tempMin, scalingTemp));
  Serial.print(" Max= ");
  Serial.println(convertToTemperature(tempMax, scalingTemp));

  Serial.print("Calibration Results - Current (A): ");
  Serial.print("Min= ");
  Serial.print(convertToCurrent(currentMin, scalingCurrent, currentMax, currentMin));
  Serial.print(" Max= ");
  Serial.println(convertToCurrent(currentMax, scalingCurrent, currentMax, currentMin));
}

void waitForCalibrationStep() {
  while (true) {
    if (Serial.available() > 0) {
      String userInput = Serial.readStringUntil('\n');
      userInput.trim();

      if (userInput.equalsIgnoreCase("done")) {
        break;
      }
    }
  }
}

float waitForAnalogInput(int analogpin) {
  readingsCount = 0;
  totalValue = 0;

  while (true) {
    if (Serial.available() > 0) {
      String userInput = Serial.readStringUntil('\n');
      userInput.trim();

      if (userInput.equalsIgnoreCase("done")) {
        break;
      }
    }

    // Read analog input
    inputValue = analogRead(analogpin);
    totalValue += inputValue;
    readingsCount++;

    delay(100);  // Add a delay to avoid rapid serial prints
  }

  // Calculate the average
  if (readingsCount > 0) {
    return totalValue / readingsCount;
  } else {
    return 0;  // Avoid division by zero
  }
}

Did you check if ads.begin(); was successful?

if (!ads.begin()) {
    Serial.println("Failed to initialize ADS.");
    while (1);
  }
else
  Serial.println( "ADS ready");

I moved your topic to an appropriate forum category @gigios098.

In the future, please take some time to pick the forum category that best suits the subject of your topic. There is an "About the _____ category" topic at the top of each category that explains its purpose.

This is an important part of responsible forum usage, as explained in the "How to get the best out of this forum" guide. The guide contains a lot of other useful information. Please read it.

Thanks in advance for your cooperation.

It doesn’t work since it isn’t printing anything to serial monitor after ads.begin() command.

Do you have a serial connection? Your code will wait forever here if there is no connection.

In theory yes, i give the command Serial.begin() which should start the serial communication. If I remove the ads.begin() the code runs normally only when I add the ads.begin() it crashes.

Strange, here is the code for begin from the library.

void Adafruit_ADS1015::begin() {
  Wire.begin();
}

What is the storage used by you program? The ram used at the end of the compile listing. The wire interface has internal buffers, but I an not sure when they are allocated.

I think your problem is elsewhere. Here's a minimal sketch running on an Uno R3 with an ADS1115 hooked up to SDA and SCL, and things behave exactly as they should.

#include <Adafruit_ADS1X15.h>

Adafruit_ADS1115 ads;

void setup() {
   Serial.begin(115200);
   Serial.println("After Serial.begin");
   ads.begin();
   Serial.println("After ads.begin");
   ads.setGain(GAIN_TWOTHIRDS);
}

int16_t adc;

void loop() {

   for( uint8_t i=0; i<4; ++i ) {
      adc = ads.readADC_SingleEnded(i);
      if( adc<0 ) {
         adc = 0;
      }
      Serial.print(F(" A"));
      Serial.print(i);
      Serial.print(F(": "));
      float v = adc*1.875e-04;
      Serial.println(v,2);
   }
   delay(5000);
}


And as you can see below, ads.begin(); does not make the serial monitor stop working, nor does it halt the code.

Monitor port settings:
baudrate=115200
Connected to /dev/ttyUSB0! Press CTRL-C to exit.
After Serial.begin
After ads.begin
 A0: 4.93
 A1: 3.27
 A2: 1.63
 A3: 2.08
 A0: 4.93
 A1: 3.27
 A2: 1.63
 A3: 2.07
 A0: 4.94
 A1: 3.27
 A2: 1.63
 A3: 2.07

Edit: And @oldcurmudgeon hit the nail on the head, I think. Here's the culprit:

Global variables use 1943 bytes (94%) of dynamic memory, leaving 105 bytes for local variables. Maximum is 2048 bytes.

105 bytes is nowhere near enough for your local variables and stack usage. Begin by putting your string literals in flash memory with the F() macro and see how much RAM you gain by doing that.

Thank you so much.

You also store most of your variables in a "float", which uses twice the memory of an "int", and can slow things down. Wasteful coding for an Arduino with a small brain.
Example
tempValue = ads.readADC_SingleEnded(0); // Read from channel 0
currentValue = ads.readADC_SingleEnded(1); // Read from channel 1
Both return an "int" (whole number) that you store in a float (value with a decimal place).
Leo..

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.