PlatformIO Community

An object in an object

Hello,
I am using the thermocouple amplifier Adafruit_MCP9600.
In order to read the temperature I define an object (“basePlateTempSensor”) and I use “basePlateTempSensor.readThermocouple()”. It works.

But I want to do it differently. I create an object (“bottomChamberTemperature”) from the class “TemperatureControl”. Then I want to return the temperature value by using “bottomChamberTemperature.readTemperature()”.
I get 0 and sometime, the program crash.

Can someone tell me why?

Appreciate your help,
Cyril

The main.cpp:

// Sub-functions

#include <headers.hpp>

/*#include <Wire.h>
#include <Adafruit_I2CDevice.h>
#include <Adafruit_I2CRegister.h>
#include "Adafruit_MCP9600.h"*/

Adafruit_MCP9600 basePlateTempSensor;

TemperatureControl bottomChamberTemperature(HEATER_PIN, basePlateTempSensor);

void setup() {

  Serial.begin(115200);

  if (! basePlateTempSensor.begin(i2c_temp_mat)) {

        Serial.println("Sensor not found. Check wiring!"); //todo: make a special screen for this error
        while (1);

    }

  basePlateTempSensor.setADCresolution(MCP9600_ADCRESOLUTION_18);
  basePlateTempSensor.setThermocoupleType(MCP9600_TYPE_J);
  basePlateTempSensor.setFilterCoefficient(3);
  basePlateTempSensor.setAlertTemperature(1, 30);
  basePlateTempSensor.getAlertTemperature(1);
  basePlateTempSensor.configureAlert(1, true, true);
  basePlateTempSensor.enable(true);

  bottomChamberTemperature.init();
}

void loop() {
  Serial.print(bottomChamberTemperature.readTemperature());
}

TemperatureControl.hpp:

#ifndef _H_TEMPERATURE
#define _H_TEMPERATURE

#include <Arduino.h>

#include "Adafruit_MCP9600.h"

class TemperatureControl
{
private:
    int m_heaterPin;
    Adafruit_MCP9600 m_temperatureSensor;
    
public:
    TemperatureControl(/* args */);
    TemperatureControl(int heaterPin, Adafruit_MCP9600 temperatureSensor);
    ~TemperatureControl();

    int readTemperature(); 
};

#endif

TemperatureControl.cpp:

#include <TemperatureControl.hpp>
#include <Arduino.h>
#include "Adafruit_MCP9600.h"

TemperatureControl::TemperatureControl(/* args */){}

TemperatureControl::TemperatureControl(int heaterPin, Adafruit_MCP9600 temperatureSensor){
    this->m_heaterPin = heaterPin;
    this->m_temperatureSensor = temperatureSensor;
}

int TemperatureControl::readTemperature(){
  int laminatorBasePlateTemperature = m_temperatureSensor.readThermocouple();
  return (laminatorBasePlateTemperature);
}

TemperatureControl::~TemperatureControl(){}

Mhm this makes a copy. What if you change m_temperatureSensor to a Adafruit_MCP9600* and pass in &basePlateTempSensor and use -> instead of . to access the pointer?

maxgerhardt, thank you very much. It was exactly the solution.