Segmenting code into functions allows a programmer to create modular pieces of code that perform a defined task and then return to the area of code from which the function was "called". The typical case for creating a function is when one needs to perform the same action multiple times in a program. (1)
Function Example:
long pingDetect(){
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
inches = inchConversion(duration);
cm = cmConversion(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
return cm; }
Code Using Function in Void Loop:
void loop() {
cm = pingDetect();
The function allows us to use a shortened version of the code in the void loop and makes correcting errors very easy.
When the Arduino reads the "cm = pingDetect();" it jumps down to the pingDetect function which is declared below the void loop. After preforming the function, the processor then returns to the code in the loop where it left off.