Hey everyone,
I'm trying to learn more about writing functions and needed some help understanding how to implement them. I've been trying to shrink the size of my void loop() in a project of mine by rewriting some lines as functions. I figured this would also make my code more modular if I decided to turn off certain features or sensors. In particular, I need help understanding return statements. Here's a sample code that I've written:
void setup() {
Serial.begin(9600);
// initialize all the readings to 0:
for (int thisReading = 0; thisReading < numReadings; thisReading++) {
readings[thisReading] = 0;
}
}
void loop() {
calc_average_v();
Serial.println(average);
delay(1); // delay in between reads for stability
}
int calc_average_v(){
// subtract the last reading:
total = total - readings[readIndex];
// read from the sensor:
readings[readIndex] = analogRead(inputPin);
// add the reading to the total:
total = total + readings[readIndex];
// advance to the next position in the array:
readIndex = readIndex + 1;
// if we're at the end of the array...
if (readIndex >= numReadings) {
// ...wrap around to the beginning:
readIndex = 0;
}
// calculate the average:
average = total / numReadings;
return average;
}
Am I calling this function correctly and would this be better as a void or a int function? I need the value of average to be present in void loop(), but I'm confused on whether the function needs to return a value or if the code just running through the function is sufficient. I'd really appreciate any links or tutorials on understanding functions.