A critical part of learning any language is the ability to break apart your program into “subroutines”.
In C, and therefore Arduino, we use Functions.
We have already used a few – Setup and Loop are functions, and PrintLn is a function (method) of the Serial object.
Creating Arduino/C Functions
Functions are built in the form:
ReturnType functionName(InputType variableName) { // do stuff return "data"; } Eg. String hey(String name) { Serial.println("Hey " + name); return "Done!"; }
Don’t Repeat Yourself
One of the best habits to get into when coding is to create small, reusable elements, rather than rely on copy and paste.
It’s easier to understand when
As a rule of thumb, each function should exist for just one purpose.
Serial Input Demonstration
To demonstrate how functions work, let’s create a sketch that asks the user to input something into the serial monitor input box.
Did you notice the serial monitor allows input as well as showing output?
