User Defined Functions – Jim Kenyon
This question comes from Jim Kenyon. It’s based on this lesson:
- Arduino Course for Absolute Beginners, 2nd Edition
- User Defined Functions
The Question:
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
Leave a Comment
User Defined Functions
Arduino Course for Absolute Beginners
2nd Edition
Module Progress:
User Defined Functions
Lessons in this module:
Welcome to this module.
Your Private Notes
Taking notes helps you better retain information.
Click here to enter your note
User Defined Functions
Arduino Course for Absolute Beginners,
1st Edition
Module Progress:
User Defined Functions
Lessons in this module:
Welcome to this module.
Your Private Notes
Taking notes helps you better retain information.
Click here to enter your note

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.
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.
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.
to replace the variable currentTemp, I will use: displayTemperature (farenheitTemp(LM34Pin));