In this tutorial, we will see what functions are and how to use them in MicroPython, and how we can use them to make our code cleaner and more modular.
A function is a block of code that performs a specific task and can be called (or invoked) from anywhere in a program.
This allows us to break a problem into smaller parts, as well as avoiding the need to repeat the same code in multiple places.
Functions are a basic feature of Python (just like in many other languages). Of course, MicroPython incorporates the same syntax and functionality.
If you want to learn more, check out,
Basic Syntax of a Function in MicroPython
In MicroPython, functions are defined using the keyword def
. The basic syntax is as follows:
def function_name(parameter1, parameter2, ...):
# Code that performs the task
return result
- def: Indicates that we are defining a function.
- function_name: Is the name we give to the function.
- parameter1, parameter2, …: Are the values that the function receives as input. They can be optional.
- return: Specifies the value that the function returns as a result. It is not mandatory, but it is common in functions that perform calculations or transformations.
It is highly advisable that the function name is descriptive and clearly indicates the task it will perform.
Let’s look at each of the components of the definition with some examples,
Simple Function Without Parameters
Let’s start with a simple example. Suppose we want to create a function that prints “Hello, world!” to the console.
def greet():
print("Hello, world!")
# Call the function
greet()
Output:
Hello, world!
In this case, the function greet
does not receive parameters and does not return any value. It simply executes the code it contains when called.
Function with Parameters
Now, let’s create a function that receives a parameter and uses it in its logic. For example, a function that greets a person by name.
def greet_person(name):
print(f"Hello, {name}!")
# Call the function
greet_person("Juan")
greet_person("Ana")
Output:
Hello, Juan!
Hello, Ana!
Here, the function greet_person
receives a parameter called name
and uses it to personalize the message.
Function with Return Value
Functions can also return values using the keyword return
. This is useful when we want the function to perform a calculation and return the result.
def add(a, b):
result = a + b
return result
# Call the function and store the result
total = add(5, 3)
print(f"The sum is: {total}")
Output:
The sum is: 8
In this example, the function add
receives two parameters (a
and b
), performs the addition, and returns the result. Then, we store that result in the variable total
and print it.
If you want to learn more, check out,
Lambda Functions (Anonymous)
Lambda functions are a very convenient syntax for defining anonymous functions in a single line. They are useful for small functions and simple operations.
square = lambda x: x ** 2
print(square(4)) # Output: 16
If you want to learn more, check out,
Functions Within Functions
In MicroPython, we can also define functions within other functions. This is known as nested functions and is useful when we want to encapsulate logic that is only relevant within a specific context.
def calculate_tax(price):
def apply_vat(price):
return price * 1.21 # VAT of 21%
price_with_vat = apply_vat(price)
return price_with_vat
# Call the function
total = calculate_tax(100)
print(f"Price with VAT: {total}")
Which would output,
Price with VAT: 121.0
Here, the function apply_vat
is defined within calculate_tax
and is only accessible within the latter.
Just because you can do it doesn’t mean you should abuse it.
Practical Examples
Control of an LED with Functions
Let’s apply what we’ve learned in a practical example. Suppose we are controlling an LED connected to a microcontroller using MicroPython. We can create functions to encapsulate the logic for turning the LED on and off.
from machine import Pin
# Configure the LED pin
led = Pin("LED", Pin.OUT)
def turn_on_led():
led.on()
def turn_off_led():
led.off()
def blink_led(times, duration):
for _ in range(times):
turn_on_led()
time.sleep(duration)
turn_off_led()
time.sleep(duration)
# Call the functions
turn_on_led()
time.sleep(1)
turn_off_led()
blink_led(5, 0.5)
In this example, we have created three functions: turn_on_led
, turn_off_led
, and blink_led
.
It’s a very simple example because each function has only one line. This may not make much sense, but it is to illustrate how functions work.