📘 Lesson P7 – Functions in Arduino Programming
🎯 Learning Objectives
After completing this lesson, students will be able to:
✅ Understand what functions are
✅ Understand why functions are important
✅ Create custom functions
✅ Call functions correctly
✅ Pass parameters to functions
✅ Return values from functions
✅ Organize large Arduino programs
✅ Improve code readability and reusability
1. Introduction
Imagine you are building a robot.
The robot needs to:
- Move Forward
- Move Backward
- Turn Left
- Turn Right
- Stop
One approach is to write the motor control code repeatedly whenever needed.
Example:
digitalWrite(IN1,HIGH);
digitalWrite(IN2,LOW);
digitalWrite(IN3,HIGH);
digitalWrite(IN4,LOW);
Again…
digitalWrite(IN1,HIGH);
digitalWrite(IN2,LOW);
digitalWrite(IN3,HIGH);
digitalWrite(IN4,LOW);
Again…
digitalWrite(IN1,HIGH);
digitalWrite(IN2,LOW);
digitalWrite(IN3,HIGH);
digitalWrite(IN4,LOW);
This makes programs:
❌ Long
❌ Difficult to read
❌ Difficult to maintain
Instead, we use:
Functions
2. What is a Function?
A function is a reusable block of code designed to perform a specific task.
Think of a function as a machine.
Input
↓
Processing
↓
Output
Whenever needed, we simply call the function.
Real-Life Example
Imagine a remote control.
When you press:
Volume Up
The TV performs a predefined task.
You do not manually increase the volume each time.
Similarly:
A function stores instructions that can be used repeatedly.
3. Why Functions are Important
Functions help:
✅ Reduce code duplication
✅ Improve readability
✅ Simplify debugging
✅ Make programs modular
✅ Reuse code
Professional programmers use functions extensively.
4. Functions Already Used in Arduino
You are already using functions.
Example:
void setup()
{
}
setup() is a function.
void loop()
{
}
loop() is also a function.
Other examples:
digitalWrite();
analogRead();
Serial.println();
These are built-in functions provided by Arduino.
5. Anatomy of a Function
Example:
void blinkLED()
{
digitalWrite(13,HIGH);
delay(500);
digitalWrite(13,LOW);
delay(500);
}
A function has:
Return Type
void
Function Name
blinkLED
Parentheses
()
Function Body
{
}
Contains instructions.
6. Creating Your First Function
Example:
void sayHello()
{
Serial.println("Hello Students");
}
This function prints a message.
7. Calling a Function
Creating a function does not automatically execute it.
We must call it.
Example:
void sayHello()
{
Serial.println("Hello Students");
}
void setup()
{
Serial.begin(9600);
sayHello();
}
void loop()
{
}
Output:
Hello Students
Program Flow
Power ON
↓
setup()
↓
sayHello()
↓
Print Message
↓
loop()
8. LED Blink Function Example
void blinkLED()
{
digitalWrite(13,HIGH);
delay(500);
digitalWrite(13,LOW);
delay(500);
}
Call it:
void loop()
{
blinkLED();
}
Result:
LED continuously blinks.
9. Function Parameters
Sometimes functions need input values.
These inputs are called:
Parameters
Example
Suppose we want to display different numbers.
void displayNumber(int number)
{
Serial.println(number);
}
Calling:
displayNumber(10);
Output:
10
Calling:
displayNumber(25);
Output:
25
How Parameters Work
Function:
void displayNumber(int number)
Parameter:
number
receives data sent during the function call.
10. Multiple Parameters
Functions can receive multiple values.
Example:
void addNumbers(int a, int b)
{
int result = a + b;
Serial.println(result);
}
Call:
addNumbers(5,3);
Output:
8
11. Return Values
Some functions send data back.
Example:
int addNumbers(int a, int b)
{
return a + b;
}
Call:
int result;
result = addNumbers(10,20);
Result:
30
Understanding return
The keyword:
return
sends a value back to the caller.
Example
int square(int num)
{
return num * num;
}
Call:
int result = square(5);
Output:
25
12. Void Functions
Many functions do not return anything.
Example:
void turnOnLED()
{
digitalWrite(13,HIGH);
}
Here:
void
means:
Returns nothing.
13. Functions with Return Values
Example:
int getDistance()
{
return 25;
}
This function returns an integer.
Other examples:
float getTemperature()
{
return 30.5;
}
bool isDoorOpen()
{
return true;
}
14. Variable Scope
Variables created inside a function exist only inside that function.
Example:
void test()
{
int number = 10;
}
Outside the function:
number
cannot be used.
This is called:
Local Scope
Global Variables
Variables created outside functions are available everywhere.
Example:
int count = 0;
void setup()
{
}
void loop()
{
}
This is called:
Global Scope
15. Function Prototype
Sometimes functions are written below setup() and loop().
Arduino often handles this automatically.
Example:
void blinkLED();
void setup()
{
}
This declaration is called a:
Function Prototype
16. Real Project Example
Obstacle Avoiding Robot
Instead of writing motor code repeatedly:
void moveForward()
{
// Motor code
}
void stopRobot()
{
// Motor code
}
void turnLeft()
{
// Motor code
}
Now the program becomes:
if(distance < 10)
{
stopRobot();
}
else
{
moveForward();
}
Much easier to understand.
17. Common Beginner Mistakes
Mistake 1
Creating function but never calling it.
Example:
void hello()
{
Serial.println("Hello");
}
Nothing happens unless:
hello();
is called.
Mistake 2
Missing parentheses.
Wrong:
hello;
Correct:
hello();
Mistake 3
Wrong parameter count.
Function:
addNumbers(int a,int b)
Wrong:
addNumbers(5);
Mistake 4
Forgetting return value.
Example:
int square(int x)
{
}
Must return something.
18. Best Practices
✅ Give meaningful names
Good:
moveForward()
Bad:
abc()
✅ Keep functions small
✅ One function = One task
✅ Reuse functions whenever possible
✅ Add comments for complex functions
19. Real-World Applications
Functions are used in:
Line Follower Robots
followLine()
Smart Irrigation
checkMoisture()
Home Automation
turnOnLight()
Weather Station
readTemperature()
Water Dispenser
dispenseWater()
📊 Summary
In this lesson, we learned:
✅ What functions are
✅ Creating functions
✅ Calling functions
✅ Parameters
✅ Return values
✅ Local and Global Variables
✅ Function prototypes
Functions make Arduino programs cleaner, easier to understand, and easier to maintain, especially in large projects.
📖 Key Terms
Function
A reusable block of code.
Parameter
Input value passed to a function.
Return Value
Data sent back by a function.
Void
Function returns nothing.
Local Variable
Variable available only inside a function.
Global Variable
Variable available throughout the program.
Function Call
Executing a function.
🎯 Quiz
1. What is a function?
A. Variable
B. Reusable block of code ✅
C. Sensor
D. Loop
2. Which keyword means “returns nothing”?
A. int
B. bool
C. void ✅
D. char
3. What is a parameter?
A. Output
B. Input value to a function ✅
C. Loop variable
D. Comment
4. Which keyword sends a value back?
A. send
B. output
C. return ✅
D. print
5. Why are functions useful?
A. Reduce repeated code ✅
B. Increase wiring
C. Power Arduino
D. Create sensors
🏠 Assignment
Task 1
Create a function named showName() that prints your name.
Task 2
Create a function named blinkLED() that blinks an LED once.
Task 3
Create a function that adds two numbers and displays the result.
Task 4
Create a function that returns the square of a number.
Task 5
Design functions for a robot:
- moveForward()
- moveBackward()
- turnLeft()
- turnRight()
- stopRobot()
Explain what each function should do.