User Defined Functions – Jim Kenyon

This question comes from Jim Kenyon. It’s based on this lesson:

The Question:

“When writing the code for the main portion of the module I came across an issue. You state that you can just call the temperature without initializing a variable (i.e. currentTemp) first. My code doesn’t work without the currentTemp variable.”

const byte LM34Pin = A4;

void setup() {
  Serial.begin(9600);
}

void loop() {

  float currentTemp = farenheitTemp(LM34Pin);
  displayTemperature(currentTemp);

  delay(1000);
}

float farenheitTemp(int LM34Pin) {
  float rawTempData = analogRead(LM34Pin);
  float farenheitTemp = ((rawTempData * 0.0048) / 0.010);
  return farenheitTemp;
}

void displayTemperature(float farenheitTemp) {

  Serial.print("Temperature is: ");
  Serial.print(farenheitTemp);
  Serial.println(" degrees farenheit");
}

Your Challenge:

Can you rewrite this code so that you don’t use the currentTemp?

Hint:

You’ll need to pass the farenheitTemp() function to the to the displayTemperature function.

Solution:

Here is what I came up with…

Your Thoughts:

Do you like using the intermediate variable currentTemp? Or do you prefer just calling a function from a function?

4 Comments

  1. A. Smith on November 20, 2019 at 4:32 pm

    I think calling the function from within a function is better, because it eliminates more redundancy, uses up less storage, and possibly runs faster.
    Good documentation (i.e., comments) can make it clear what’s happening.

  2. Robert Hatcher on April 13, 2020 at 7:55 am

    I understand the reasons given in the comments of A. Smith above but I personally do find that returning results back to a variable makes it more readable for me.
    Each to his/her own I guess.
    A. Smith is absolutely right that good documentation/comments is what makes the code most understandable.

    • Canyon Lewis on June 15, 2020 at 10:03 am

      I prefer to be able to understand code at a quick glance rather than chase functions to the bottom of the page or read comments (though I do appreciate comments) I like variables.

  3. Javier Sanchez on January 1, 2025 at 12:40 pm

    to replace the variable currentTemp, I will use: displayTemperature (farenheitTemp(LM34Pin));

Leave a Comment