I am certain that the code in your snippet would work perfectly. This means that there is other code that you did not post in your snippet that is messing up what happens.
To continue: to shift an array we do not iterate through the elements - we use memcpy(dest, src, n).
memcpy copies n bytes of memory from src to dest. To shift an array, you need to copy from element 1 to element zero (or the other way around) a number of bytes equal to the size of the array minus the size of one element.
But this won't work for you, because your array conains both temerature and humitity all mixed in together in weird slots. To adress this, use a struct or a class.
struct SensorData {
float temperature;
float humidity;
};
const int sensorSamples = 2;
SensorData sensorData[sensorSamples];
/// etc ///
memcpy(sensorData+0, sensorData+1, sizeof(sensorData) - sizeof(sensorData[0]));
sensorData[sensorSamples-1].temperature = newTemperature;
sensorData[sensorSamples-1].humidity = newHumidity;
This gives everything meaningful names, and it's easy to change how many samples you want to keep.
The other fix is to use a circular buffer, which is very slightly more complicated.
struct SensorData {
float temperature;
float humidity;
};
const int sensorSamples = 2;
int latestSensorRead = sensorSamples-1;
SensorData sensorData[sensorSamples];
/// etc ///
latestSensorRead++;
if(latestSensorRead >= sensorSamples) latestSensorRead = 0;
sensorData[latestSensorRead].temperature = newTemperature;
sensorData[latestSensorRead].humidity = newHumidity;
Again, this will adapt to any number of samples. To keep a running average, hold a sum of the temperature and humidity. When you take a new sample, subtract the old value and add the new one:
struct SensorData {
float temperature;
float humidity;
};
const int sensorSamples = 2;
int latestSensorRead = sensorSamples-1;
SensorData sensorData[sensorSamples];
SensorData runningAverage;
/// etc ///
latestSensorRead++;
if(latestSensorRead >= sensorSamples) latestSensorRead = 0;
runningAverage.temperature -= sensorData[latestSensorRead].temperature / sensorSamples;
runningAverage.humidity -= sensorData[latestSensorRead].humidity / sensorSamples;
sensorData[latestSensorRead].temperature = newTemperature;
sensorData[latestSensorRead].humidity = newHumidity;
runningAverage.temperature += sensorData[latestSensorRead].temperature / sensorSamples;
runningAverage.humidity += sensorData[latestSensorRead].humidity / sensorSamples;
Note, however, that this will accumulate errors over time. Every now and then you will want to recacluate the average from scratch.