Main Menu

search

You are here

Arduino functions

[last updated: 2024-08-08]
Arduino programming
-----

  • Functions are blocks of code that are separate from the program loop,
    but that can be called and executed from within the loop.
    • Functions are often used whenever you have a block of code that you need to execute multiple times in your program,
      and you don't want to have to re-write it in your code every time you need it.
    • Built-in functions especially are used as a short-cut for what might otherwise be very large blocks of code cluttering up your program.
      Built-in math functions are a perfect example.
        If you need a square-root operation in your program,
        you surely could write one yourself from scratch,
        which would take however many hours of research and trial-and-error development,
        then would consume however many lines of code in your program,
        or you could execute:
          var01 = sqrt(value);

        and use the build-in math function sqrt().

  • Functions are executed in your program with a line like:
      functionName();

  • "Built-in" functions:
    • millis():
      This function returns the number of milliseconds since the last program restart/reset.
      It is an unsigned long int in the range 0 to CA 4.29 X 109
      It will roll over back to zero after about 50 days.
      eg:
        unsigned long currentTime = millis();

  • User-defined functions:
    • Functions can be defined in your program.
      Your custom, user-defined function definition is generally put outside the loop routine,
      often at the bottom of your program code, that is after the loop is closed.
    • Functions are defined like this:
      void [functionName] ( [parameters to be passed into the function] ) {
          [program statements]
      }

      Parameters must be type-declared, and are separated with commas if more than one is passed, eg:
      void [functionName] ( int param01, char param02 ) {
      ...
      }

      If no parameters are passed to the function, it would be defined like this:
      void [functionName] () {
      ...
      }
      That is, with nothing between the ( )
      ----------------------------------------

    ==================================================================================

    A function will execute its command statements until it's done, then will return to its calling function.
    If you want to exit the function before it is done, use:
    return;

    The "void" at the beginning of the function declaration specifies that nothing (ie. no parameter or quantity) is returned from the function to the calling program.

    If something IS going to be returned, then the 'void' is replaced with the type of the returned quantity, eg:
    int [functionName] ( ) {
        int var01 = 5;
        return var01;
    }


    Note the last line of the function will be:
    return [parameter/quantity to be returned];

.

.

.

eof