简体   繁体   中英

Arduino getting stuck in simple C++ function

I am currently working on a little Arduino project, which is using an infrared temperature sensor for measuring certain surface temperatures.

The hardware works perfectly and also simply reading analog signals with analogRead() works fine, but using this simple function for filtering the measured analog values to get better results just doesn't get along with the Arduino.

Every time the sketch running this function is uploaded to the Arduino (Pro Micro), the program just gets stuck and disables the Arduino, so that it has to be reset before appearing again in the "Ports" Menu as a COM Port.

Here is the simple function in which I cannot find the bug:

int TemperatureDifferenceSensor::measureRawFilteredTemperatureValue(int numberOfMeasurements) {
  int temperatureMeasurementValueSum = 0;
  int maxMeasuredTempValue = 0;
  int minMeasuredTempValue = 0;
  for (int i = 0; i < numberOfMeasurements; ++i) {
    int measuredTemperatureValue = analogRead(analogObjectTempPin);
    temperatureMeasurementValueSum += measuredTemperatureValue;
    if (measuredTemperatureValue > maxMeasuredTempValue) {
      maxMeasuredTempValue = measuredTemperatureValue;
    } else if (measuredTemperatureValue < minMeasuredTempValue) {
      minMeasuredTempValue = measuredTemperatureValue;
    }
    // A small delay, to not measure the same or similar value every time...
    delay(10);
  }
  temperatureMeasurementValueSum -= maxMeasuredTempValue;
  temperatureMeasurementValueSum -= minMeasuredTempValue;
  int temperatureMeasurementAverageValue = (int) (temperatureMeasurementValueSum / (numberOfMeasurements - 2));
  return temperatureMeasurementAverageValue;
}

If analogRead and delay works as you expected, it should be somewhat ok. One big issue with the function is that it can't be called with argument 2. This would cause zero-division exception and probably also a black hole. Why not something like:

... 
} // the for-loop closes here. 

if (numberOfMeasurements == 0)
  return 0;
// Must have at least 3 measurements in order to remove 2 of them.
else if (numberOfMeasurements > 2) 
{
  temperatureMeasurementValueSum -= maxMeasuredTempValue;
  temperatureMeasurementValueSum -= minMeasuredTempValue;
  numberOfMeasurements -= 2; // Compensate removing two measurements.
}

// Average is sum divided by measurements.
int temperatureMeasurementAverageValue = temperatureMeasurementValueSum / numberOfMeasurements;

return temperatureMeasurementAverageValue;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM