Functions in Arduino  Step by Step Guide ▷ 2021

Arduino functions are the main tools you should use when programming a board. For this, it is useful to know some aspects so that this group of codes works correctly.

If you want to know how to do it, you will need to continue reading. We will explain to you what functions are used in free hardware programming and the uses that you can give to the functions within Arduino.

But this is not all you can read. We will tell you how this segment of the code is composed and the step by step you must do to use a function correctly.

What are functions in Arduino and what are they for in free hardware programming?

What are functions in Arduino and what are they for in free hardware programming?

So that a arduino project be completed, It is necessary to attach all the components or hardware to the board and then carry out the programming. For the latter, the Arduino IDE environment is used, which works with some criteria that must be taken into account to achieve success in the development of the program.

When you open the integrated development environment you see the following:

void setup() {

// ponga su código de configuración aquí, para que se ejecute una vez:

}

void loop() {

// ponga su código de configuración aquí, para que se ejecute una vez:

}

Being, void setup () the function where the main program settings are written and void loop () the function that will contain the commands necessary to be executed on the Arduino when the board is available. From the above, the concept of what a function is in Arduino follows. We can say then that is a block of codes that contains the program to carry out the instructions that the plate must carry out.

In this way, it is feasible to include repetitive tasks separately, in which it is also possible to divide them by modules to obtain a better administration and order within the program. A function must be accompanied by parameters, which are variables that are used to define the limits and establish the criteria that you should consider the main tool to apply the action that will perform the function.

Therefore, the syntax of a function is:

  • nombreFunción(parámetros);

What are the benefits and utilities of using functions when programming on Arduino?

What are the benefits and utilities of using functions when programming on Arduino?

When you use the functions when programming Arduino in the IDE you will get the following benefits:

  • The function can be created only once, so it is not necessary to always program the same task within the software when the Arduino is required to perform a certain action.
  • By being able to use the same function for repetitive tasks, the program is smaller. This achieves activity and improves the efficiency of the board considering the microprocessor.
  • It follows from the above that, with the use of the function, you will have a tool that will help you manage best the programming of the board.
  • By allowing better program administration, benefits understanding of general development by the IDE operator.
  • If for any reason you need to modify the code of the function, you will only have to edit a group of commands and not the whole program. This decreases the likelihood of making mistakes.
  • When you need to add some extra branch or task to a function you can do it through the module. You will also have the advantage, that when you want to eliminate some extra task you will only have to move the group of function codes and not the whole program.
  • Having repeated functions will make the IDE sketch smaller which will generate a much easier reading of the programming codes.
  • When you know that the codes inside the functions are well developed, you can use them in other projects from Arduino just by copying and pasting.
  • Being called by names makes it easy to find errors and places to edit to improve board actions.

Anatomy of an Arduino Function What are all the parts of this code segment?

Anatomy of an Arduino Function What are all the parts of this code segment?

As we told you before, the program makes the void setup () and void loop () functions, so it is possible to add more functions. But it must be taken into account that these tools must obey a criterion to be followed, which must comply with each of the parts of the function.

The anatomy of an Arduino function is:

  • The first thing to establish is the datatype that the value needs to return. In this case you can use void, string, int, double, short and more.
  • Then you have to write the name of the function. At this point it is important to clarify that, in general, the name must be written in lowercase and if two or more words need to be included, they must be separated by an underscore. For example, internet_pap. It must be borne in mind and the functions must be included within the same file with an Arduino extension (.ino) or in another, but within the same sketch or sketch. Nor can you use words that are reserved for the programming language.
  • Next, you will have to write the parameter. This tool is used to indicate the task to be performed by the function. If no parameter is used, this place is left empty.
  • Once the type of task and where to do it have been clarified it is time to incorporate the program code, which is the spirit of development and is the element that distinguishes it from other projects. The codes are written between braces in each line that is finished developing must be separated by a semicolon.
  • The last thing left of the anatomy of function is return. It has to be written Return to return the value of the function.

An example of the above is:

void setup() {

inMode(pin, OUTPUT); // Establece 'pin' como salida

}

void loop() { // Aquí comienza la función

digitalWrite(pin, HIGH); // Activa 'pin'

delay(1000); // Pausa un segundo

digitalWrite(pin, LOW); // Desactiva 'pin'

delay(1000);

} // Con esta llave termina la función

Learn step by step how to use a function when programming free hardware in Arduino from scratch

To use a function from scratch in Arduino you will have to follow this step by step to avoid making mistakes:

Determine the actions the Arduino will do

The first thing you will have to do is decide what kind of work the board will do on your project. From this the type of function you will use will come out, since a digital tool (for example, pinMode and digitalWrite) or a time tool (digitalWrite), among others, is not the same. What we will take as a model To illustrate the steps of using a function, the construction of a parking sensor. For this, you will need an ultrasonic measurement sensor that will help you detect the distance there is with nearby objects.

Sets the names to the pins on the board

The next step is to declare the name that each input that you will use from the Arduino will have. After this you will have to indicate in the command group void setup () the input and output pins.

Enter the void loop () function

Enter the void loop () function

For the work you are doing you are going to declare the function int to call the sensor and you will use the values ​​to set the parameters.

Therefore, the example will be as follows:

// Modelo de códigos para un sensor de estacionamiento

int IPAP = 8;

int WEBSITE = 0;

void setup() {

begin(9600);

pinMode (IPAP, INPUT);

pinMode (WEBSITE, OUTPUT);

}

void loop()

{

}

int sensor(int valor) {

}

Create the sensor reading

Now you’re going to have to copy the code into the function you named sensor. Then you will have to assign a variable that you can call distance so that the sensor establishes the unit of measure of length that will be sent from the group void loop ().

Set the return

You will have to include the variable return and assign it as the distance. This will serve so that the sensor returns a value and can trigger the results of the established codes. When you have this part ready, you must choose a variable to divide the unit (in this example, will take number 10, but you can also include any other metric). We will name the latter divider (div). So that, the divisor (which is equal to 100) will be expressed What int dis = sensor (divider).

Includes reading values

What you have left to do is build a function that allows you to know the values ​​that will appear on the monitor over a period of time. It can be used Serial.println (dis) with a delay of one second delay (1000).

Therefore, the sensor example will be:

// Modelo de códigos para un sensor de estacionamiento

int IPAP = 8;

int WEBSITE = 0;

void setup() {

begin(9600);

pinMode (IPAP, INPUT);

pinMode (WEBSITE, OUTPUT);

}

void loop()

{

}

int sensor(int valor) {

}

void loop(){

int divisor= 10;

int dis = sensor(divisor);

println (dis);

delay(1000);

}

int sensor (int valor)

{

digitalWrite (IPAP, LOW);

delayMicroseconds (2);

digitalWrite (IPAP, HIGH);

delayMicroseconds (10);

digitalWrite (IPAP, LOW);

int distancia = pulseIn(IPAP, HIGH);

distancia = distancia/valor;

return distancia;

}

Learn about the most useful functions that you can apply when working with Arduino programming

Among the most useful functions that you can use in programming your Arduino board are the following:

digitalRead ()

digitalRead ()

This function will allow you to read the value of a certain digital pin, your return can be HIGH (high) or LOW (low). The syntax of this tool is digitalRead (pin), where pin It is the number assigned on the Arduino board to the digital input.

For example, if you want pin 13 to be considered output as well as input pin 7, then you would have to write:

int ledPin = 13; // LED conectado al pin digital 13

int inPin = 7; // pulsador conectado al pin digital 7

int val = 0; // variable para almacenar el valor leído

configuración vacía ()

{

pinMode (ledPin, SALIDA); // establece el pin digital 13 como salida

pinMode (inPin, INPUT); // establece el pin digital 7 como entrada

}

bucle vacío ()

{

val = digitalRead (inPin); // lee el pin de entrada

digitalWrite (ledPin, val); // establece el LED al valor del botón

}

delay ()

Among the most useful and used functions delay () is found. This tool allows you to pause the program for a while that must be set by the programmer, it is always considered in milliseconds. That is, 1000 milliseconds will equal one second. The structure of this function is delay (ms), in which ms is the number of milliseconds that you want to delay the process.

Look at this example in which you want output pin 13 to wait 1 second before the action occurs:

int ledPin = 13; // LED conectado al pin digital 13

void setup()

{

pinMode(ledPin, OUTPUT); // Establece el pin digital como salida

}

void loop()

{

digitalWrite(ledPin, HIGH); // Enciende el LED correspondiente

delay(1000); // Espera un segundo

digitalWrite(ledPin, LOW); // Apaga el LED

delay(1000); // Espera un segundo

}

attachInterrupt ()

This function is a bit more complete to use, since parameters are needed for which the digital pins are interrupted. In this way it is possible to connect the plate to a switch so that it cuts the process for a certain time. Keep in mind that according to the version of the Arduino you must connect to the different pins. To do a switch service routine correctly, you need to know its syntax. She is attachInterrupt (digitalPinToInterrupt (pin), ISR, mode).

Where:

  • interrupt is the number of interrupts you want.
  • pin is the pin number assigned on the board.
  • ISR It is the routine of the service, it is the ISR to be called by the program.
  • mode It is used in the syntax to define when the service interruption will be triggered.

An example of this function is:

const byte ledPin = 13;

const byte interruptPin = 2;

volatile byte state = LOW;

void setup() {

pinMode(ledPin, OUTPUT);

pinMode(interruptPin, INPUT_PULLUP);

attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);

}

void loop() {

digitalWrite(ledPin, state);

}

void blink() {

state = !state;

}

If you have any questions, leave them in the comments, we will answer you as soon as possible, and it will also be of great help to more members of the community. Thanks! 😉

Felix Bathrobe

Author: Félix Albornoz

I have been working in the technology sector for more than 20 years helping companies and users to develop and train in this field. Always learning new things.

You may be interested:

Leave a Comment