05) Functions and Variables

Before I begin, I want to explain more about functions and why we use them.

Functions are very useful when programming, they take tedious repetitive tasks and turn them into, well, functions!

Before, we used only void functions. Void (which means emptiness) is the function's return value. Both setup and loop do not return anything. So why would we want to return anything? And how exactly do we make a function with arguments? Lets start out by placing this function below both the setup and loop functions. This function will be called multiply. Yes, we already have multiply built in, but for the sake of understanding functions, I will make one.

This time, we will make it return a value. This function (and every function) will return the function's answer. In this case we will be multiplying both "a" and "b" for its return. Our function will be returning a number, what kind of number though? In the computer world, there are differant kinds of numbers. Each with an allocated amount of space, with some allowing decimals, and some that don't. Most variables do not use decimals. In our case we will use "int", which has a number range from -32,768 to 32,767. Good enough for our function, so this "int" type will be used as our return type. Our arguments (a,b) also need to be defined. We will call them both int for consistency. If you were wondering, int stands for integer.

Our function will now look like:   int multiply(int a,int b)
But is not done! It still has nothing inside of it! We will now make the return value for it, that will look like.
int multiply(int a,int b)
{
  return a*b;
}
This is our finished function we can use it in loop or in setup like:
void setup()
{
}
void loop()
{
  digitalWrite(multiply(5,1),HIGH);
}
int multiply(int a,int b)
{
  return a*b;
}


Now we also need to go over variables too...
Just like how we used a returning type in functions, we can also use this as a variable. Like so: int a;
There are two places where you can place this: on the global scope (global variable), or locally.
A global variable like this:
int a;
void setup()
{
}
void loop()
{
}
A local variable looks like this:
void setup()
{
}
void loop()
{
  int b;
}
Both of them used for different reasons:
    Global variables will always be there, they can be read and written from any function at any time.
    Local variables only reside inside the function, they can only be used inside that function. And upon that, once that function is done it is deleted!

You can also set the variable at the same time by doing this:  int a=5;
and set it throughout the code like "a=3;"

This is all I will explain for now, now lets get the light to blink!
Comments