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 ![]()
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); Â
}