Dividing your code up into functions or methods allows you to perform similar actions multiple times without having to duplicate the code. Functions are essentially modular blocks of code which perform a defined task and then return to the area of code from where the function was initially called.
This exercise assumes that you have a basic understanding of the Arduino IDE and how to upload a sketch, if you haven’t done this before, have a look at our guide to writing and uploading your first Arduino sketch.
The advantage of using functions come in when you need to debug or modify your code. Say you use the number of times an LED blinks throughout your code to readout different values and you decide that you want the LED to blink more quickly. If you haven’t used methods, you’d have to go and change the rate each time you’ve asked the LED to blink whereas with a method, you only need to change a single line.
The predefined sections of code setup() and loop() are functions which your Arduino has been programmed to recognise. There are essentially four types of functions which you can use, we’ll go through each one, how to define it and how to call it in the order of increasing complexity.
Basic Void Functions
To demonstrate the use of functions, we will use the Arduino’s on board LED and the Serial monitor function later on to display the returned results.
The function gets defined outside of any of the other functions in the code in a similar way to the setup() and loop() functions. The basic structure is:
void functionName() { function contents }
The function is called within the code using the syntax:
functionName();
The function can be called from within the setup() function, the main loop() function or from within other functions in the code.
Here is an example of a function which blinks the on board LED once. The function is called up in the main loop to blink the LED three times.
//The DIY Life //By Michael Klements //01/03/2017 void setup() { pinMode(13, OUTPUT); //Assign the on board LED to pin 13 } void loop() { blinkLED(); blinkLED(); blinkLED(); } void blinkLED() { digitalWrite(13, HIGH); delay(1000); digitalWrite(13, LOW); delay(1000); }
Basic Return Functions
The placeholder void before the function name indicates that nothing is being returned by the function. It is often useful for a function to be able to return some type of variable to your main method. The type of variable which the function returns then replaces the void before the function name. In this example we will call a function to blink the LED a random number of times, this number will be returned to the main method and displayed in the Serial window.
The function is now declared as:
long blinkLED()
As is called using:
long noTimes = blinkLED();
The complete sketch now becomes:
//The DIY Life //By Michael Klements //01/03/2017 void setup() { pinMode(13, OUTPUT); //Assign the on board LED to pin 13 Serial.begin(9600); //Start the serial monitor } void loop() { long noTimes = blinkLED(); Serial.println(noTimes); } long blinkLED() { long randomNumber = random(15); //Creates a random number between 0 and 15 for (int i=1; i<= randomNumber; i++) //Blinks the LED the random number of times { digitalWrite(13, HIGH); delay(500); digitalWrite(13, LOW); delay(500); } return randomNumber; }
Passing Parameters To Void Functions
To increase the functionality of our function, we can pass it parameters from our main block of code. In order to pass the function parameters, we first need to tell the function what type of parameters to expect and assign variable names to them, this is done by defining the parameters in the same way you do within the code but now in the brackets after the function name. We can pass the function any variable types allowed by the Arduino IDE.
void blinkLED(int noTimes, int time)
Now, when we call the function, we will need to pass it the variable it is expecting in the same data type. You can do this by passing it actual values or passing it variables of the same data type.
Call your function using values:
blinkLED(3,1000);
Call your function using variables:
blinkLED(noTimes,time);
The complete sketch would now look like this:
//The DIY Life //By Michael Klements //01/03/2017 void setup() { pinMode(13, OUTPUT); //Assign the on board LED to pin 13 } void loop() { blinkLED(3,1000); } void blinkLED(int noTimes, int time) { for (int i=1; i<= noTimes; i++) { digitalWrite(13, HIGH); delay(time); digitalWrite(13, LOW); delay(time); } }
Passing Parameters To Return Functions
Finally, we can combine the two and pass parameters to a function which also returns a variable. In this example, we will call a function which then blink the LED a random number of times between zero and a limit we send to the function, the random number will then be displayed on the serial monitor.
The complete sketch is now:
//The DIY Life //By Michael Klements //01/03/2017 void setup() { pinMode(13, OUTPUT); //Assign the on board LED to pin 13 Serial.begin(9600); } void loop() { long noTimes = blinkLED(20); Serial.println(noTimes); } long blinkLED(int limit) { long randomNumber = random(limit); //Creates a random number between 0 and 15 for (int i=1; i<= randomNumber; i++) //Blinks the LED the random number of times { digitalWrite(13, HIGH); delay(500); digitalWrite(13, LOW); delay(500); } return randomNumber; }
And that is everything you need to know about using functions with an Arduino. If you have any questions or suggestions, let me know in the comments section below.
What if I just want to call an arg outside my loop? If I make another arg outside the loop, how do you get the Arduino to call it? Because I just get my argument name isn’t declared.
void setup(){
//setup parameters
}
void loop(){
Argument1();
Argument2();
Argument3();
}
void Argument1(){
// args called from loop
}
void Arguement2(){
//args called from loop
}
void Argument3(){
//args called from loop
}
Hi Anthony,
Your code above is correct in theory. You are getting an error because you’ve spelled Argument2 as Arguement2 in the second function.
Hi Michael, great explanation. Thanks very much.
Can you tell me, how many defining parameters can you pass into a function?
Thanks
Hi Tim,
I don’t think there is a limit, I’ve seen functions with 10+ parameters being passed to it.
I would however avoid using more than 3 or 4. More than this and your function starts losing focus and could probably be separated into smaller or separate functions. This also makes your code more readable and is more testable for fault finding.
please i have this arduino program that is not working as required. I have four laser receivers that i am monitoring its output signals with the arduino. when one laser receiver output signal is low or all becomes low, a function will be called to bring a relay on or blink a light. it functions alright but when the condition is not met i expect the light to stop blinking and the relay to go off but it doesnt. I blinks continuously. I need help please. Thanks
Hi Reuben,
Send your code through to [email protected] and we’ll have a look at it. It may be an interesting project worth sharing on our site.
Michael,
How do you return more than one variable from a function? I am parsing a long string into 5 different variables (that are globally defined) and converting them to integers in the function, but cannot get them all back into the main loop. I can get one at a time based on your method above.
Thanks for your help. Chris
Hi Chris,
There is no “easy” way, which I am aware of, to return multiple variables from a function. Your options to do this would be something like:
thanks for this! I am new to arduino and have been struggling to understand how functions work. You have made it very clear. In fact I have learnt and understood more following your examples than all the hours of reading other places. Great job.
Thanks for the great feedback Mike, glad I was able to help!
Thank you for this.
Can you tell me what determines where a function should be placed. I have found out that some functions need to be placed before/after the main void loop(). Some even seem to need to be in the setup. Is there a rule to determine the placement?
Hi Tony,
For general functions, the position doesn’t matter. They are generally written after the main loop though. The setup() and loop() are essentially both functions as well, so you can’t place other functions within these functions (apart from the code to call them). There are a couple of exceptions where you may need to declare the function before the setup(), but this is quite rare.
Thank you for your prompt reply. I have found, using a function for millis(), that it needs to be before setup and others need to be in the setup before the program recognises them. I have usually understood that functions are declared after the void loop() but my program doesn’t work if I do that.
Thanks again. I will persevere.
Is this advisable:
int variable[function()];
int function(){
// calculate
return whatever;
}
Hi Bob,
What is it that you’re trying to do with the above? It doesn’t seem like a problem to me, but I’m not sure what you’re wanting it to do.
Thank you for this very clear explanation. I am embarking on a project where I want to introduce some randomness into a set of responses. The use of functions with arguments is exactly what I was looking for. Thanks!
Thats great! Thanks for the feedback Thomas!
Wow Michael,
I was browsing for this nearly two days. You helped me a lot. Thank you very much!
That’s great! Thanks Sascha
Thank you a lot Mr.Michael,
To understand how truly function working in arduino IDE, is what I have much comment to know. So, I take this time to tell you “thank you” even if I feel is not enough to say that only. It very valuable to reach on your website.
I will be always interested to your next post.