Reading sensors in a loop

I would go for a small finite statemachine as shown below

enum TDS_READSTATES
{
  READING,
  PROCESSING
};

/*
  take 50 samples at 20 ms interval
  Out:
    tdsval
  Returns:
    false if sampling in progress, true if process completed and tdsval is valid
 */
bool readtds(int &tdsval)
{
  static TDS_READSTATES readState = READING;
  static int count;
  static uint32_t lastReadTime;
  static float x[50];

  switch (readState)
  {
    case READING:
      if (count == 50)
      {
        readState = PROCESSING;
      }
      else
      {
        if (millis() - lastReadTime >= 20)
        {
          lastreadTime = millis();
          x[count++] = analogRead(TdsSensorPin);
        }
      }
      break;
    case PROCESSING:
      // sort the array
      ...
      ...
      // calculate average
      ...
      ...
      // clean up
      count = 0;
      readState = READING;
      // indicate that reading is complete and tdsval is valid
      break;
  }

  // indicate that reading is in progress
  return false;
}

Call it as often as you can. In loop(), you can test the return value; if it's true, you can use tdsval.

Not compiled nor tested.

// Edit
All additional variables are decared static so they will be remembered.
Note that this costs you 50 floats extra as x needs to be static to be remembered.

// Edit2
Just realise that x does not need to be a float as analogRead() returns an int. So it only will cost you 50 integers extra.

1 Like