Arduino Functions

From robotics
Revision as of 19:56, 19 November 2014 by Jfmorrow (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Functions

Functions are basically a good way to simplify your code and make it easier to read. A function can do almost anything that you need it to. There are several steps to setup a function. It is important that this declaration is outside the setup and loop functions.


Arduinofunction.png

int 

The first part of the function declaration is the data type returned from your function. If you use void, nothing will be returned.


myMultiplyFunction 

The second part is the function name. This name can be anything you want it to be but it may not have spaces or special characters.


(int x, int y)

The third part of the function declaration is the parameters or data that you are giving the function. In this case it is the two integers that you would like to multiply.


Int result;

This is a local variable of type int named result. This variable can only be used within the function.


result = x * y;

This multiplies x by y and saves the result in the variable named result.


return result;}

This line returns the result variable from the function.


Example function program

Arduinofunctionex.png

Commenting Code

Below is a program written just for this class. This program is used to find the Hypotenuse of a right triangle. You can see that the comments help make the code understandable and are important for the other members of your team (and TA’s).

Why make the code longer with a function? The short answer is to make your main loop more readable and to make the program more modular or editable for future work. In a short function this seems tedious but it is the proper way and will pay off in the long run. Making reusable code is invaluable in any large project.

Arduinofunctionex2.png