Master Arduino Functions

Master Arduino Functions

In this chapter, we focus on Arduino functions, including essential built-in functions like setup() and loop(), as well as user-defined functions. This guide will walk you through understanding how to initialize hardware, execute repetitive tasks, and organize your code using functions.

Syntax Table: Key Arduino Functions

Topic Syntax Simple Example
void setup() void setup() { } void setup() { pinMode(13, OUTPUT); }
void loop() void loop() { } void loop() { digitalWrite(13, HIGH); }
User-defined Functions returnType functionName(params) { } void blinkLED(int pin, int delayTime) { }
return (with value) return value; return a + b;
return (no value) return; return;

void setup() (Setup Function) in Arduino

The void setup() function in Arduino is where you initialize your program. It runs once when the Arduino board is powered on or reset. This function is typically used to set the initial configurations, such as defining pin modes, starting serial communication, or configuring libraries. After setup(), the Arduino continuously runs the loop() function.

Use purpose
The setup() function is used for:

  • Setting up pin modes: Configuring digital and analog pins as inputs or outputs using pinMode().
  • Initializing hardware: Starting serial communication with Serial.begin(), configuring sensors, or initializing libraries.
  • One-time setup tasks: Performing actions that only need to be done once when the program starts, such as displaying a welcome message or setting initial variables.

Arduino Syntax use
void setup() {
    // code to run once
}

Arduino Syntax Explanation

  • void: Specifies that the function does not return a value.
  • setup(): The function name, always called setup(), is required in every Arduino sketch.
  • {}: The curly braces define the block of code that will run once when the Arduino starts.

Arduino code Example

void setup() {
  // Set pin modes
  pinMode(13, OUTPUT);  // Set pin 13 as an output
  pinMode(7, INPUT);    // Set pin 7 as an input
  // Start serial communication
  Serial.begin(9600);   // Begin serial communication at 9600 bps
  // Print a welcome message
  Serial.println("Arduino is ready!");
}
void loop() {
  // Main program code will go here and repeat
}

Code Explanation

  • The setup() function defines initial configurations for the Arduino, such as:
    • Setting pin modes: Pin 13 is set as an output and pin 7 is set as an input using pinMode().
    • Starting serial communication: Serial communication is initialized at a baud rate of 9600 using Serial.begin().
    • Printing a welcome message: A message, “Arduino is ready!”, is printed to the serial monitor as part of the initial setup.

Once setup() is completed, the Arduino moves on to continuously execute the loop() function.

Notes

  • Runs once: The setup() function only runs once at the start of the program. All the code inside it is executed before the loop() function begins.
  • Essential in every sketch: You must include the setup() function in every Arduino sketch, even if it is empty.
  • Hardware initialization: Any hardware components or libraries you need must be initialized in setup() so they are ready for use in the loop().

void loop() (Loop Function) in Arduino

The void loop() function in Arduino is where the main program code runs continuously after the setup() function completes. The code inside loop() executes in an infinite cycle, meaning once it finishes, it starts again from the top. This allows you to monitor inputs, control outputs, or repeatedly check and update conditions.

Use purpose
The loop() function is used for:

  • Continuous operations: Running code repeatedly, such as reading sensor data, updating display values, or controlling actuators.
  • Reacting to changes: Continuously checking for inputs (e.g., button presses, sensor values) and adjusting outputs (e.g., turning LEDs on or off).
  • Implementing program logic: You place the main logic of your program here, where conditions, events, or actions are repeatedly checked and executed.

Arduino Syntax use
void loop() {
    // code to run continuously
}

Arduino Syntax Explanation

  • void: Indicates that the function does not return any value.
  • loop(): The function name loop(), which is required in every Arduino sketch.
  • {}: The curly braces define the block of code that will run repeatedly.

Arduino code Example

int ledPin = 13;  // Pin connected to an LED
int buttonPin = 7;  // Pin connected to a button
void setup() {
  pinMode(ledPin, OUTPUT);  // Set pin 13 as an output
  pinMode(buttonPin, INPUT);  // Set pin 7 as an input
}
void loop() {
  int buttonState = digitalRead(buttonPin);  // Read the state of the button
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);  // Turn the LED on if the button is pressed
  } else {
    digitalWrite(ledPin, LOW);  // Turn the LED off if the button is not pressed
  }
}

Code Explanation

  • The setup() function runs once to configure pin modes for the LED and button.
  • The loop() function continuously:
    • Reads the state of the button using digitalRead(buttonPin).
    • Checks if the button is pressed (HIGH) or not (LOW).
    • Turns the LED on or off based on the button state.
  • This process repeats indefinitely, so the Arduino continuously monitors the button and controls the LED in response.

Notes

  • Runs indefinitely: The loop() function runs in an endless cycle. Once the last line of code inside loop() is executed, it starts again from the first line.
  • Essential in every sketch: Every Arduino sketch must have a loop() function, even if it is empty, as the absence of it will cause errors.
  • Core logic location: The main logic of your program, such as reading sensor values, controlling actuators, and responding to conditions, is typically placed inside loop().

User-defined Functions (Custom Functions) in Arduino

In Arduino, user-defined functions, also known as custom functions, are functions that you create to organize your code into reusable blocks. These functions allow you to break complex programs into smaller, more manageable pieces, making your code easier to read, maintain, and debug. User-defined functions can take inputs, perform actions, and return results.

Use purpose
User-defined functions are used for:

  • Organizing code: Breaking down repetitive tasks or complex logic into smaller, modular parts.
  • Reusability: Instead of writing the same code multiple times, you can call a function whenever needed.
  • Improving readability: Makes your code more readable by logically grouping related tasks into named functions.
  • Simplifying debugging: When something goes wrong, it’s easier to debug smaller blocks of code inside functions.

Arduino Syntax use
returnType functionName(parameters) {
    // code to execute
    return result;
}

Arduino Syntax Explanation

  • returnType: The type of value that the function will return (e.g., int, float, void if no value is returned).
  • functionName: The name of your custom function.
  • parameters: The variables passed into the function (optional).
  • return: Used to return a value if the function is not void.

Arduino code Example

int ledPin = 13;  // Pin connected to an LED
void setup() {
  pinMode(ledPin, OUTPUT);  // Set pin 13 as an output
}
void loop() {
  blinkLED(ledPin, 1000);  // Call the custom function to blink the LED
}
// User-defined function to blink an LED
void blinkLED(int pin, int delayTime) {
  digitalWrite(pin, HIGH);  // Turn the LED on
  delay(delayTime);         // Wait for the specified time
  digitalWrite(pin, LOW);   // Turn the LED off
 delay(delayTime);         // Wait again before the next blink
}

Code Explanation

  • setup(): Sets pin 13 as an output for the LED.
  • loop(): Calls the custom function blinkLED() to blink the LED. The function is passed two arguments: the pin number and the delay time in milliseconds.
  • blinkLED() function: A user-defined function that controls the LED:
    • Turns the LED on using digitalWrite(pin, HIGH).
    • Waits for the specified delayTime in milliseconds.
    • Turns the LED off using digitalWrite(pin, LOW).
    • Waits again before repeating the cycle.

This makes the code more modular and reusable because you can now easily change the LED blinking pattern by just modifying the arguments passed to blinkLED().

Notes

  • Modular code: Breaking your code into functions makes it easier to manage, especially in larger programs.
  • Function parameters: You can pass variables to your functions to make them more flexible.
  • Return values: If a function needs to send data back to where it was called, you can return a value by using the return statement (e.g., returning an integer or float).
  • Void functions: If a function doesn’t need to return any value, you can declare it with the void keyword.

return (Return from Function with or without Value) in Arduino

The return statement in Arduino is used to exit a function and optionally return a value to the point where the function was called. In user-defined functions, return can be used to send a result back or to end the function early. Functions that don’t need to return a value use void as their return type and can use return; to exit the function without returning a value.

Use purpose
The return statement is used for:

  • Returning values: When a function needs to send a result (such as an integer, float, or boolean) back to the caller.
  • Exiting functions early: Stops the function execution before reaching the end of the function block.
  • Signaling end of a function: In void functions, it simply ends the function.

Arduino Syntax use

  • return value;
    (For functions that return a value)
  • return;
    (For functions with a void return type or to exit early without a value)

Arduino Syntax Explanation

  • value: The value to be returned, such as an integer, float, boolean, or any other data type.

Arduino code Example (Returning a Value)

int addNumbers(int a, int b) {
  return a + b;  // Return the sum of a and b
}
void setup() {
  Serial.begin(9600);
  int sum = addNumbers(5, 10);  // Call the function and store the result in sum
  Serial.print("The sum is: ");
  Serial.println(sum);  // Print the sum to the serial monitor
}
void loop() {
  // No code needed here
}

Code Explanation

  • The addNumbers() function takes two integers (a and b) and returns their sum using the return statement.
  • In setup(), the function addNumbers(5, 10) is called, and the result is stored in the sum variable.
  • The Serial.println() function prints the result (sum = 15) to the serial monitor.

Arduino code Example (Without Returning a Value)

void checkTemperature(int temp) {
  if (temp > 30) {
    Serial.println("It's hot!");
    return;  // Exit the function early if temp is greater than 30
  }
  Serial.println("Temperature is normal.");
}
void setup() {
  Serial.begin(9600);
  checkTemperature(35);  // Call the function with a temperature value
}
void loop() {
  // No code needed here
}

Code Explanation

  • The checkTemperature() function checks if the temperature is above 30. If true, it prints “It’s hot!” and uses return; to exit the function early, skipping the rest of the code.
  • If the temperature is not greater than 30, the function prints “Temperature is normal.”.
  • In setup(), the function is called with a temperature of 35, triggering the early exit after printing “It’s hot!”.

Notes

  • Return type: Functions that return a value must have a matching return type (e.g., int, float, bool). The value returned with return must match this type.
  • Void functions: Functions that are declared with void as the return type do not return a value. They can still use return; to exit early if needed.
  • Early exit: You can use return; to stop the execution of a function early, even in void functions.

Common Problems and Solutions

  1. Missing setup() or loop() Function
    Problem: The code won’t run because one of these essential functions is missing.
    Solution: Always include both setup() and loop() in every Arduino sketch, even if they are empty.
  2. Returning a Value from a Void Function
    Problem: Trying to return a value from a void function.
    Solution: Make sure that void functions don’t return any values. Use return; to exit early if needed.
  3. Redundant Code in Loop()
    Problem: Repetitive code bloats your loop.
    Solution: Break repetitive tasks into smaller, reusable functions to simplify your code.

Chapter Summary

  • setup() runs once when the Arduino is powered on or reset. It’s used to initialize pins, sensors, or libraries.
  • loop() contains the core logic and runs continuously after setup() is executed.
  • User-defined functions help organize and simplify code by breaking down tasks into reusable pieces.
  • return is used to exit functions early or send values back from a function.

FAQ

  1. What is the role of the setup() function in Arduino?
    The setup() function runs once when the board powers on or resets, initializing pins and libraries.
  2. Why do we need the loop() function?
    The loop() function contains the main logic that repeats continuously, allowing your Arduino to perform ongoing tasks like monitoring sensors or controlling LEDs.
  3. How do user-defined functions improve Arduino code?
    They allow you to organize code into reusable blocks, making it easier to read, maintain, and debug.

Simple MCQ Questions and Answers

  1. What is the function of setup() in Arduino?
    a) Initializes hardware and runs once
    b) Repeats code continuously
    c) Returns values
    Answer: a) Initializes hardware and runs once
  2. What is the main purpose of loop() in Arduino?
    a) Starts the serial communication
    b) Executes code once
    c) Repeats code continuously
    Answer: c) Repeats code continuously

Which keyword is used to exit a function early in Arduino?
a) stop()
b) return
c) exit()
Answer: b) return