Function Tutorial for Arduino Author: Alexander Brevig Contact: alexanderbrevig@gmail.com
So you want to write a Function for the Arduino?
-Great!
Here is a little tutorial on how to write and use functions.
You will learn the basic syntax rules for c++ function declaration and definitions.
For this tutorial we will implement a function called blinkLED.
It will make the LED in question blink when called.
We will make this:
In computer science, a subroutine or subprogram (also called procedure, method, function, or routine) is a portion of code within a larger program, which performs a specific task and is relatively independent of the remaining code. Wikipedia
A function is a way for programmers to reuse code without having to rewrite the code.
This is time saving, and often makes kode more readable, if the function names are well selected, that is.
A function is written as this in C/C++ and Arduino
returntype functionName( arguments ){ //function body return returntype; }
For our example we will use
//returntype functionName( arguments ){ void blinkLED(){ //function body digitalWrite(ledPin, HIGH); // sets the LED on delay(1000); // waits for a second digitalWrite(ledPin, LOW); // sets the LED off delay(1000); // waits for a second //return returntype; //implied by closing curly bracked }
An argument consists of both a datatype and a name. For instance, one could specify a function that adds two integers like this: int add( int x, int y){ return x+y; }. For our example the argument is non-existant, but the compiler will see it as a void argument.
The funciton name should clearly state what the function will do. If you can think of many names, you should select the least verbose name.
For instance, we could replace blinkLED with setAPinHighThenLow, but this is a longer name, and I would argue, less descriptive, although more detailed.
It is also important to make your API user friendly. Arduino has selected a lowercaseUppercase naming convention, and I think Arduino users should comply to this convention.
Any type that is legal for a variable can be used for the return type. The type void means that the function does not return any value.
I will argue that selecting the datatype with the least amount of size, bytewise, will be good practice.
This will produce faster code, and in my opinion makes coding more intuitive.
Try to keep the parameter list as short as possible, but be sure to require enough info for your function to execute correctly.
Part of AlphaBeta Tutorials and Resources. | |
Last Modified: | June 05, 2009, at 04:11 PM |
By: | AlphaBeta |