An Introduction to Functions in Arduino | How to Make Funciton

An Arduino function is a block of code that has a name and a block of statements that are executed when the function is called. The functions void setup() and void loop() have already been discussed here.

Arduino hd image

Custom functions can be written to perform repetitive tasks and reduce clutter in a program. Functions are declared by first declaring the function type. This is the type of value to be returned by the function such as ‘int’ for an integer type function. If no value is to be returned the function type would be void. After type, declare the name given to the function and in parenthesis any parameters being passed to the function.

type functionName(parameters)
{
statements;
}

The following integer type function delayValue() is used to set a delay value in a program by reading the value of a potentiometer. It first declares a local variable v, sets v to the value of the potentiometer which gives a number between 0-1023, then divides that value by 4 for a final value between 0-255, and finally returns that value back to the main program.

int delayVal()
{
int v;                               // create temporary variable ‘v’
v  = analogRead(pot);    // read potentiometer value
v /= 4;                            // converts 0-1023 to 0-255
return v;                        // return final value
}

Curly braces
It define the beginning and end of function blocks and statement blocks such as the void loop() function and the for and if statements. type function() {   statements; }

An opening curly brace { must always be followed by a closing curly brace }. This is often referred to as the braces being balanced. Unbalanced braces can often lead to cryptic, impenetrable compiler errors that can sometimes be hard to track down in a large program.

Semicolon
A semicolon must be used to end a statement and separate elements of the program. A semicolon is also used to separate elements in a for loop.

int x = 13;   // declares variable ‘x’ as the integer 13

 

Block comments, or multi-line comments
These are areas of text ignored by the program and are used for large text descriptions of code or comments that help others understand parts of the program. They begin with /* and end with */ and can span multiple lines.

Single line comments 
They begin with // and end with the next line of code. Like block comments, they are ignored by the program and take no memory space.
Single line comments are often used after a valid statement to provide more information about what the statement accomplishes or to provide a future reminder.

Learn Simple Hello World Program

These are all the basic tools you need to create a function in Arduino.

Leave a Reply

Your email address will not be published.