What is a Function ?Function is a block of code that performs a specific task within a large program and relatively independent of the remaining code
what's the use of function ?1.Functions make code more readable
2.we can reuse the code without rewriting it
3.easy to debug the code
4.function can be accessed from any location within a program and name of function is unique and global
How to Write a Function ?The Syntax(technical name) of function is
returnType functionName(arguments)
{
functionBody;
return returnValue;
}
The arduino is based on c/c++ so a function declaration in arduino is same as C.
Before going to what is what in function syntax, let me remind you about function once agian.
function is a few lines of code with a separate name in a large / main program.
so we have to specify the name for the function which is
functionName
in syntax
To do a Task we need specific information and that may/may not be coming from main program... But what if Our function needed information from main program?
so we need a way to pass information to the main program if neededwhich is
arguments
in syntax and as stated before this is optional.
the few lines of code that performs specific task is called
functionName
when we call function from main program, it must have a way to return the result of the task it performed to the main program or calling function.
returnType is used to specify the datatype of the function return variable
and
return returnValue; is used to return the actual value into calling function
But what if we don't want to return anything from the function.
void is used as returnType if function returns nothing.structuring code into functional blocks is an good practice which is useful when we write the large code and it is easy to understand (if we given the specified functionNames)
Arduino Ex:
/*
Author : Kunchala Anil
Arduino code to describe the use of Functions
In this we ask the user to enter two Number and display it on serial monitor
*/
#define data_max 20
char data_buffer[data_max];
float A;
float B;
void setup(){
Serial.begin(9600);
ask_numbers();
serial_check();
}//end of setup
void loop(){
}//end of loop
void ask_numbers(){
Serial.println("Please enter A");
A = serial_check();
Serial.print("the value you entered is \t");
Serial.print(A);
Serial.println("");
Serial.println("Please enter B");
B = serial_check();
Serial.print("the value you entered is \t");
Serial.print(B);
Serial.println("");
}//end of ask_numbers
float serial_check(){
static byte index = 0;
while(!Serial.available())
{
//wait until user enters the data
}
char input = Serial.read();
if (input != '\r'){
data_buffer[index] = input;
index = index+1;
serial_check();
}else{
data_buffer[index] = 0;//terminate array with NULL to make it string
index = 0;
return atof(data_buffer); // atof --> ascii to float
}
}//end of serial_check
and the result is