0

My Arduino controller reads data coming from four different sensors. After the data is read, I individually compute four input average values. I understood that I am having the same lines of code repeated four times. Instead, I want to define a function with an analog pin as input and compute the average. My code is working fine. The question I have is, will this function improve the speed, reduce memory?

My code:

// Samples average
sample_cnt = 1000;

//// Input the pin number and compute average value
float Average_input_value(int analog_pin){
  float avg_val = 0;
  for(int i=0;i<sample_cnt;i++){
    avg_val += analogRead(analog_pin);        
  }
  // Divide by Sample count to get the average value
  avg_val = avg_val/sample_cnt;  
  return avg_val;
  }

2 Answers 2

2

Writing the code out four times, in line, is a little bit faster than calling a function because the function call and return take some time, and the loop instructions take some time, and neither of those contribute to the average calculation.

Writing a function that you use four times, however, is much more readable, is much easier to fix if you've made a mistake because you can fix it once instead of four times, and is much easier to change or replace for the same reason, if that ever becomes necessary. Besides, a good optimizing compiler can often decide when to rewrite your loop as inline several repetitions of the loop contents (called "unrolling the loop"), so hand optimizing is probably not worthwhile.

Where your function will win over 4 repetitions of the calculation code is in the code-space needed. The function is more compact, but slightly slower.

1

Just adding some numbers to complement JRobert's answer.

On the Uno, the cost of calling a function and returning from it is about 0.5 µs. In contrast, calling analogRead() within a loop costs at least 112 µs per iteration. Given that you are computing the sum as a float (where a suitably sized integer would suffice), it may well be more that 112 µs in your case.

I do not know how many readings you want to average, but even if it is only a handful, the calls to analogRead() will completely dwarf the cost of using a function.

1
  • Thank you very much for your response. I have decided to use the function approach for averaging. Right now I am using a1000 sample count for averaging. Interesting to know that calling an analogRead() actually takes 1000 times more time in the loop than in the function.
    – Mainland
    Apr 21, 2021 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.