This is an old revision of the document!


Interrupts and sub-programs

Functions

Functions are the set of statements that are executed always when the function is called. Two functions that were mentioned before are already known - setup() and loop(). The programmer is usually trying to make several functions that contain all the statements and then to call them in the setup() or loop() functions.

The structure of the function is following:

type functionName(arguments) //a return type, name and arguments of the function
{
  //the body of a function - statements to execute
}

For the example, a function that periodically turns on and off the LED is created:

void exampleFunction() 
{
  digitalWrite(13, HIGH); //the LED is ON		
  delay(1000);			
  digitalWrite(13, LOW);  //the LED is OFF				
  delay(1000);	
}

In the example code can be seen that the return type of an exampleFunction function is void that means the function does not have the return type. This function also does not have any arguments, because the brackets are empty.

This function should be called inside the loop() function in the following way:

void loop()
{
  exampleFunction(); //the call of the defined function inside loop()
}

The whole code in the Arduino environment looks like this:

void loop()
{
  exampleFunction(); //the call of the defined function inside loop()
}
 
void exampleFunction() 
{
  digitalWrite(13, HIGH); //the LED is ON		
  delay(1000);			
  digitalWrite(13, LOW);  //the LED is OFF				
  delay(1000);	
}

It can be seen that the function is defined outside the loop() or setup() functions.

When some specific result must be returned as a result of a function, then the function return type should be indicated, for example:

int  sumOfTwoNumbers(int x, int y) //the return type is "int"; arguments are still optional
{
    return (x+y); //the value next to the "return" should have the "int" type; this is what will be returned as a result.
}

In the loop() this function would be called in a following way:

void loop()
{
  int result = sumOfTwoNumbers(2, 3); //the call of the defined function inside loop()
}

Interrupts

en/iot-open/programming_fundamentals_rtu/interrupts_and_sub-programs.1516876213.txt.gz · Last modified: 2020/07/20 09:00 (external edit)
CC Attribution-Share Alike 4.0 International
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0