What are functions in Arduino programming?

Arduino is renowned for its user-friendliness and simplicity, making it an ideal choice for beginners and enthusiasts. Its intuitive interface empowers users to explore and unleash their creativity in exciting ways. With the ever-evolving technology landscape, Arduino remains a cutting-edge platform, enabling users to stay at the forefront of the latest advancements.

Previously, we delved into the essential concepts of variables, constants, and data types in Arduino programming. Now, it's the perfect moment to broaden our horizons by introducing the concept of functions.

What are functions?

Functions serve as the building blocks of Arduino programming, allowing us to organize our code into manageable and reusable segments. Using functions enables dividing the program's code into discrete task-specific sections. When an activity needs to be carried out more than once in a program, that is the typical situation in which a function is created.

They streamline the process of writing complex programs, making it easier to understand, debug, and modify our projects. By incorporating functions into our repository, we can unlock a new level of efficiency and creativity in our Arduino endeavors.

What is function?
What is function?

Advantages of functions

The benefits of standardizing code fragments into functions are numerous.

  • The programmer may keep organized by using functions. This frequently aids in conceptualizing the program.

  • Functions centralize a single activity so that it only has to be thought about and tested once.

  • This lessens the possibility of modification errors if the code needs to be altered.

  • Due to frequent code reuse, functions reduce the overall sketch’s size and increase its compactness.

  • They facilitate things.

There are two required functions in an Arduino sketch or a program i.e. setup () and loop(). Other functions must be created outside the brackets of these two functions.

Syntax of function

The basic syntax of the function must include the following:

  • Return type

  • Function name

  • Arguments

  • Function body

Basic syntax for defining a function
Basic syntax for defining a function

Functions declaration in Arduino programming

There are two ways a function can be declared in the sketch.

  • Writing a function prototype

  • Function definition or declaration

Writing a function prototype

The first method is defining a function anywhere above the loop() function. The function consists of:

  • Function return type

  • Function name

  • Function argument type, no need to write the argument name

Function prototype must be followed by a semicolon ( ; ).

int sum_func (int x, int y) // function declaration {
int z = 0;
z = x+y ;
return z; // return the value
}
void setup () {
Statements // group of statements
}
void loop () {
int result = 0 ;
result = Sum_func (5,6) ; // function call
}
Function declaration using prototype method

Function definition or declaration

In this method of function declaration, we define the body of the function after the loop() function. Using this method, you should declare the function in the beginning, such that the compiler is aware that later the definition of this function exists.

The function consists of:

  • Function return type

  • Function name

  • Function argument type, here you must add the argument name

  • The function body (statements inside the function executing when the function is called)

int sum_func (int , int ) ; // function prototype
void setup () {
Statements // group of statements
}
void loop () {
int result = 0 ;
result = Sum_func (5,6) ; // function call
}
int sum_func (int x, int y) // function declaration {
int z = 0;
z = x+y ;
return z; // return the value
}
Function declaration using second method

Implementation example

The following example demonstrates the working of a function and how a function is defined and called. For this demonstration, the required hardware and software components include:

Hardware components

We need the following:

  • 2 LEDs (can be of any color)

  • 2 Resistors (220 ohms or of closer value)

  • Arduino board

  • Jumper wires

  • Breadboard

Circuit connections

Here's the circuit connection for this project:

  1. Connect the Arduino's GND (ground) pin to the breadboard's ground rail. You can use any available Arduino's GND (ground) pin. There is no need for a 5V pin from Arduino as the high voltage is given to the LEDs through pins 9 and 10.

  2. Place one LED on the breadboard, with the longer leg (anode) connected to digital pin 9 of the Arduino using a 220-ohm resistor in series. The LED's shorter leg (cathode) should be connected to the breadboard's ground rail.

  3. Place the other LED on the breadboard, with the longer leg (anode) connected to digital pin 10 of the Arduino using a 220-ohm resistor in series. The LED's shorter leg (cathode) should be connected to the breadboard's ground rail.

  4. Double-check your connections to ensure there are no loose or misplaced wires.

Circuit diagram
Circuit diagram

For better visuals, the LED attached at pin 9 is blue, making it easier to distinguish.

Code

The code used for this example is:

void setup() {
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
}
void loop() {
blinkLED(9, 500);
blinkLED(10, 1000);
}
void blinkLED(int pin, int duration) {
digitalWrite(pin, HIGH);
delay(duration);
digitalWrite(pin, LOW);
delay(duration);
}
Function implementation

Explanation of the code

This Arduino code utilizes two functions, namely the setup() and loop(), along with a custom function the blinkLED(int pin, int duration). Let’s break down each part:

  1. setup() function: The setup() function is a standard Arduino function that runs only once when the Arduino board is powered on or reset. Its purpose is to set up the initial configuration of the pins and any other necessary settings. In this code, the setup() function defines the pin modes of pins 9 and 10 as OUTPUT. This means that these pins will be used to control external components (e.g., LEDs) by providing voltage (HIGH) or no voltage (LOW).

  2. loop() function: The loop() function is another standard Arduino function that repeatedly runs after the setup() function has completed its execution. It forms the core of the Arduino program’s functionality and is where the main code logic resides. In this code, the loop() function calls the custom function blinkLED() twice, each time with different arguments.

  3. blinkLED(int pin, int duration) function: The blinkLED() function is a user-defined function that takes two arguments: pin and duration. The pin argument specifies the pin number of the LED that will blink, and the duration argument determines the duration of each blink in milliseconds.

Upload the code

  1. Connect your Arduino board to the computer using the USB cable.

  2. Open the Arduino IDE and copy the code into a new sketch.

  3. Select the correct board and port under the "Tools" menu.

  4. Click on the checkmark icon (✓) to verify the error code. Fix any errors that appear.

  5. Click on the right-arrow icon (➔) to upload the code to your Arduino board.

Observations

When you upload this code to your Arduino board, here’s what you will observe:

  1. The LEDs connected to pins 9 and 10 will start blinking alternately.

  2. The LED connected to pin 9 will blink faster, lasting 500 milliseconds (0.5 seconds) for each ON/OFF cycle.

  3. The LED connected to pin 10 will blink slower, lasting 1000 milliseconds (1 second) for each ON/OFF cycle.

The loop() function ensures that the blinkLED() function is repeatedly called, causing the LEDs to blink continuously in their respective patterns. This simple code demonstrates the power of functions in organizing and reusing code segments, making it easy to control multiple components in complex Arduino projects.

Copyright ©2024 Educative, Inc. All rights reserved