Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Arduino function


May 15, 2021 Arduino


Table of contents


Functions allow programs to be constructed in snippts to perform separate tasks. /b10> Typically, a function is created when a program needs to perform the same action multiple times.

Standardizing code snippets into functions has several advantages:

  • Functions help programmers stay organized. /b10> It usually helps to conceptualize the program.

  • The function encodes an action in one place so that the function only needs to be considered once and debugged once.

  • This also reduces the chance of errors being modified if the code needs to be changed.

  • Because snippy code is reused multiple times, functions make the entire sketch smaller and more compact.

  • By modularizing your code to make it easier to reuse it in other programs, you can make your code more readable by using functions.

There are two required functions in the Arduino sketch or program, namely setup() and loop(). /b10> Other functions must be created outside the parentheses of both functions.

The most common syntax for defining functions is:


Arduino function

Function declaration

Functions are declared outside of any other function above or below the loop function.

We can declare functions in two different ways:

The first method is to write a part of a function called a function prototype above the loop function, which includes:

  • The function returns the type
  • The name of the function
  • Function argument type, no argument name needs to be written

The function prototype must be followed by a sign (;).


The following example is a demonstration of a function declaration using the first method.

Example

int sum_func (int x, int y) // function declaration {
   int z = 0;
   z = x+y ;
   return z; // return the value
}

void setup () {
   Statements // group of statements
}

Void loop () {
   int result = 0 ;
   result = Sum_func (5,6) ; // function call
}


The second method, called a function definition or declaration, must be declared below the loop function, which includes:

  • The function returns the type
  • The name of the function
  • Function argument type, where the argument name must be added
  • Function body (statements executed inside a function when it is called)

The following example demonstrates a function declaration using the second method.

Example

int sum_func (int , int ) ; // function prototype

void setup () {
   Statements // group of statements
}

Void loop () {
   int result = 0 ;
   result = Sum_func (5,6) ; // function call
}

int sum_func (int x, int y) // function declaration {
   int z = 0;
   z = x+y ;
   return z; // return the value
}

The second method simply declares the function under the loop function.