Functions
Functions are groups of code that always run together. They are like modules that you stack together to build programs. Programmers create functions to simplify tasks that occur often.
A function usually requires data as an input. This data is called an argument. Functions can have many arguments. When you call a function, you supply its arguments.
Imagine that you're traveling on a road trip and someone calls you and asks “What time will you get there?”. To answer that question, you have to have some information: the destination, where you are now, what time it is now, and how fast you're traveling. Those four pieces of information are like the arguments to a function. Once you have them, you can do some calculations and return the output: your estimate time of arrival.
First, we'll cover some of the types of functions that are built in to the Arduino software. Then we'll discuss how you can make your own functions.
Hardware Functions
Time Functions
Math Functions
Communication Functions
Creating your own Functions
METHODS
Hardware Functions
Arduino has a number of functions built in to help you control hardware. They give you a way to simply control the pins.
pinMode( pin, INPUT/OUTPUT/INPUT_PULLUP );
Pin mode sets up your hardware pin to receive power, allow power to flow through, or allow a resisted amount of power to flow through. Each time you use it, you have to supply the pin number you're addressing and the setting you want for that pin.
digitalWrite( pin, HIGH/LOW );
Digital write works with pins set as OUTPUTs in pinMode(). It's a function that sends either 5V or 0V to the pin you supply it. This function only has two settings: on or off. To specify on or off, though, you can use the words HIGH or LOW, true or false, 1 or 0.
digitalRead( pin );
The digitalRead() function only takes one argument: the pin number you want to read. Its job is to listen to the pin that the programmer provides and report back what its voltage level is. The voltage level that digitalRead sends back is often a trigger for a button press or other input and is used with pinMode(INPUT) and pinMode(INPUT_PULLUP) pins.
analogRead( pin );
Using analogRead() is very similar to digitalRead(), but you should expect different results. Analog signals exist on a scale. With a Maker Board, that scale is from 0 to 1024. You can use analogRead along with analog pins that are set as pinMode(INPUT) or pinMode(INPUT_PULLUP).
analogWrite( pin, value );
analogWrite sends a value between 0 and 255 to a pin with the pinMode(OUTPUT). 255 is completely on, meaning that the pin is receiving full power 100% of the time. Passing analogWrite() a value of 128 for the value, however, means that the pin is receiving full power 50% of the time. The power flickers on and off so quickly that the output (like a motor or LED) appears to be only half way powered.
tone( pin, freqhz );
Tone is a more specialized function created to work with speakers and buzzers. You supply it with a pin argument and a frequency argument measured in hertz. Using a method similar to analogWrite, tone sends a signal to the pin that creates your sound!
noTone( pin );
noTone only takes one argument: the pin you'd like to stop sending a tone to. It's not very interesting by itself, but you'll need it to stop making noise!
Time Functions
millis();
Millis is a built-in Arduino function that doesn't have any arguments. When you call millis, you simply type millis() and it returns to you the number of milliseconds since your program started running. Although not very useful by itself, millis()) is really helpful when you want to make things happen at a certain time without delaying your program. It will run for about 50 days before the variable type can't hold any more milliseconds and will overflow back to zero.
delay(milliseconds);
The delay function pauses your program for the number of milliseconds you supply it as an argument. Because the Maker Board is running the code very quickly, you'll often want to slow things down by pausing the progress of the code for a few seconds.
Math Functions
min( x, y ); max( x, y );
The min function takes in two values and returns the smaller of the two. Max returns the larger of the two. You can also enter variables as arguments and you can enter two different data types (like an int and a float) and these functions still work. When a function can accept multiple data types, it's called overloaded.
abs( x );
abs stands for absolute value, which is what this function returns when you supply it a number. You can supply it a negative or positive number, a variable with a number value, or a math equation and it will return back to you the whole number and up to two decimal places.
variable ++; variable --;
Increment or decrement a variable. The longer version of this command might look something like: (x = x + 1;) or (y = x - 1;). When assigning the value of the incremented/decremented variable, to another variable, the placement of the (++ / --) will generate a different result as it is passed to the receiving variable.
map( value, low, high, toLow, toHigh );
The map function is usually supplied a variable value or a sensor reading as the value, then the range you expect that value to have. For example you may expect light readings between 250 and 850. The last two values supplied to the function are the new scale you want to apply to the readings.
Map seems a little strange until you think of using it. Imagine you want to display the temperature on a strip of 10 LED lights. The temperature will probably range more than from 0 to 10 degrees, so you can map the temperature values of 50-85 degrees to the LED values of 0-10.
constrain ( value, lowest_value, highest_value);
Constrain adds a floor and a ceiling to the value that a variable or reading can possibly have. First, you supply it the value you want to constrain. Then you give that value a floor and a ceiling. To use the constrained value in your code, it has to have a name, so you'll often see constrain used like this:
int reading = (reading, 100,200);
where you are reassigning the value of 'reading' to a constrained value.
Constrain is useful when the value of your inputs can range more than the value of your outputs. You'll often see it used near a map command because you may want to change the scale of your variable and then limit it's range for an output. For example you may map a temperature range of 50-100 to a brightness of 0-255. Then you may constrain the temp to 50-100 so a temperature of 49 doesn't make strange things happen with your code.
random( max ); random( min, max );
random() can be used when you want to add a little surprise inside your code or generate a number without knowing exactly what it will be. This function has two arguments, but one of them is optional. If you enter only one argument, the minimum number random will return is 0 and the maximum number is (max – 1). If you enter two arguments, random() knows that the first argument is the minimum and the second is the max.
Communication Functions
The serial monitor is a window into what's happening on the Maker Board. It's a class with methods, which is why you use “Serial.” in front of the command. Printing information to the serial port will allow messages, variable values, or code checkpoints to show up on your screen.
Serial.begin(9600);
The serial port is not running by default, so use the .begin() method to start it in the void setup() section of your code. The argument 9600 has to do with the speed of communication between the Maker Board and the serial port. 9600 is the default. When you open the serial monitor by pressing the magnifying glass icon in the IDE, be sure that the bottom right-hand corner is also displaying 9600. Otherwise, the information is garbled.
Serial.print( “Message” ); Serial.print(variable); Serial.print(“:”);
Once the serial port has been started, you can use the Serial.print() method to send strings of text or variable values to the serial monitor and watch them on the screen. If you want to show a friend instructions to play a game that you created with code, you could use Serial.print(“Here's how to play: ….”) at the end of your setup() and print the instructions to the serial monitor. Remember that Maker Board has to be plugged in to the computer to be able to send any data.
Serial.println( “message” );
Serial.println() is a method similar to Serial.print except that it starts a new line after each message. This is handy when you're printing many values and you don't want them to print in a straight line with no spaces.
Creating Your Own Functions
When you find yourself copying and pasting code over and over in your program , you may want to make your own function. First you have to decide what your function will return- will it pass a value back to the loop or to another function? If not, make it void. Next, name your function. Next, open parentheses and decide what information your function will need to function. For example, if your function turns on and off a pin a few times, you need to pass the function the pin number. This is called the argument. The argument will be converted into a variable when it's passed to the function, so create a variable and name it. When you have the arguments defined, open a curly bracket and start to define what your function will do . Remember that even if you pass a variable into the function as an argument, it will be renamed to the argument while it's used within the function.
Here's a function that takes in a pin number and turns it on and off :
void blinkLight(byte _pin){ digitalWrite(_pin , HIGH); delay(500); digitalWrite(_pin, LOW); }
When you call the function in the loop, it will look like individual statements:
blinkLight(13); blinkLight(10); blinkLight(8); blinkLight(4);
and each of the lights will blink on and off without typing the digitalWrite() command eight times.
Methods
In C++, methods are a type of function. The creator of C++ doesn't even use the word method, but instead member functions.
When we refer to a method, we're referring to a function that is defined inside a library. It's easy to create your own functions in a program (see the topic just above this), but you can't create your own method in a program. You only create methods within libraries.
Think of a method as a specific function that applies to an object. For example, you may have a "speed" method for a motor or a "clear all" method for a screen.
When you use a library, you should look at the examples or the library itself to understand what methods the library programmer created for you to use!