Passing array size

Hi guys,

Im building my first class (library) for an analog sensor. One of the features should be smoothing using an array of a certain size. I want to set the size of the array using a parameter from the main code but this doesn’t work. The code will compile, but the program acts strange.
Could somebody explain why this doesn’t work? Does it has something to do with dynamic memory allocation?

Suggestions are welcome :slight_smile:

Kind regards,

Bas

//*************************************
//Main program
//*************************************

#include "AnalogInput.h"

AnalogSensor Sensor1(A0,10); //10 samples for smoothing
AnalogSensor Sensor2(A1,10); 

void setup() {   
  Serial.begin(9600); 
}

void loop() {  

const byte NO_OFF_SENSORS = 2;
  
int sensorValues[NO_OFF_SENSORS];
int minValue;
int maxValue;

  sensorValues[0] = Sensor1.readAverageValue();
  sensorValues[1] = Sensor2.readAverageValue();  
  
  Serial.print("Average value sensor 1: ");
  Serial.println(sensorValues[0]); 
  Serial.print("Average value sensor 2: ");
  Serial.println(sensorValues[1]); 
  
  Serial.println("**********"); 
  
  delay(1000);  
}
//*************************************
//Class
//*************************************
#ifndef AnalogInput_H
#define AnalogInput_H

#include "arduino.h"

class AnalogSensor
{
  public:
     AnalogSensor(int pin, byte samples = 1); //constructor
     void begin();    
     int readAverageValue();
  
   private: //instantie variabelen
     int _pin;
     
     byte _index;
     byte _samples;
     int _samplesValues[]; //int _samplesValues[10]; 
};

#endif


//*************************************
//Members
//*************************************
AnalogSensor::AnalogSensor(int pin, byte samples) //constructor
{
 _pin = pin;
 _samples = samples;
 _samplesValues[_samples]; //Setting array size here is not working
}


//Read average value
int AnalogSensor::readAverageValue()
{  
int total; 
  
    Serial.print("Average value sensor 1: ");
  Serial.println(sensorValues[0]); 
  
  //read sensor value and put in array
  _samplesValues[_index] = analogRead(_pin); 
  
  //Add all values in array
  for(byte i=0;i<_samples;i++){
     total = total + _samplesValues[i];
  }   
   
  _index++;  
  
  // End of array? Start from beginning
  if (_index >= _samples){
    _index = 0;              
  }        
  
  //Calculate average
  return (total / _samples);    
}

You need to allocate some memory for the array first. What is the biggest number of samples you want to allow, then make that the initial size.

You can also learn about malloc, calloc, realloc and free.

Try this (to initialize your array):

  const byte NO_OFF_SENSORS = 2;
  int sensorValues[NO_OFF_SENSORS];

  for (int i = 0; i < NO_OFF_SENSORS; i++) {
    sensorValues[i] = 0;
  }