Can this code be shortened using variables?

@ragnardanneskjold perhaps an analogy.

You found some code to paint a car blue.

But you have a boat you want painted red, and a truck you want painted green.

So you take the code you found, copy and paste it, and go through it on your hands and knees replacing blue with red, and car with boat.

Presto, now you have twice the code, and you've solved 2/3 the problem.

You again take the code you found, copy and paste it, and go through it on your hands and knees replacing blue with green, and car with truck.

Now you have three times the code, and you are done.

It would have been better to change the code you found to paint <something> with <some colour>.

Now that same original code would be generalized, and you can call it with any object you want painted, along with what colour to paint it.

Leaving aside for the moment whether you needed to do it the way the code is written (I don't think so, but), this is the essence of the algorithm:

  for (ijk = 0; ijk < NUMSAMPLES; ijk++) {
   samples[ijk] = analogRead(aSensorPin);
   delay(10);
  }
  
  average = 0;
  for (ijk = 0; ijk < NUMSAMPLES; ijk++) {
     average += samples[ijk];
  }
  average /= NUMSAMPLES;
 
  average = 1023 / average - 1;
  average = SERIESRESISTOR / average;
  
  float output;
  output = average / THERMISTORNOMINAL; 
  output = log(output); 
  output /= BCOEFFICIENT;
  output += 1.0 / (TEMPERATURENOMINAL + 273.15); 
  output = 1.0 / output;
  output -= 273.15
  output = output *1.8 + 32;

which could form the body of a function called with one argument, a pin with a sensor hanging off it, which function can be made to return a floatating point result.

The italicized words should inform your googling or your work through your favorite learning source.

Try this

https://docs.arduino.cc/learn/programming/functions/

Any time you find yourself making new variables by appending a digit, it is time to consider using an array.

Any time you find yourself copy pasting code and changing things to alter the sources and destinations of the information that code uses, it is time to consider using a function.

A function would mean that when you tweak your algorithm, you have but one place to make changes, either to perfect, modify or enhance the process or calculations the code is meant to perform.

  float returnTemp = getConditionedTemperature(returnTempSensor);
 
  Serial.print("Return Temperature "); 
  Serial.print(returnTemp);
  Serial.println(" DegF");

If you went a bit further, you could pass into the function how to dress up the printing of the calculated value, but that would be too much. Better to have a function independent and usable everywhere, whether you just print the result or do the hysteresis thing or whatever.

You might also want to look into variable scope, try

HTH

a7

1 Like