In this tutorial, we are going to 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 down a problem into smaller parts, and also prevents us from having to repeat the same code in multiple places.
Functions are a basic feature of Python (as in many other languages). Of course, MicroPython incorporates the same syntax and functionality.
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: This is the name we give to the function.
- parameter1, parameter2, …: These are the values the function receives as input. They can be optional.
- return: Specifies the value 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 greet function receives no parameters and returns no 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 their 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 greet_person function receives a parameter called name and uses it to personalize the message.
Function With Return Value
Functions can also return values using the return keyword. This is useful when we want the function to perform a calculation and return the result to us.
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 add function 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.
Lambda (Anonymous) Functions
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
Functions Inside Functions
In MicroPython, we can also define functions inside 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 apply_vat function is defined inside calculate_tax and is only accessible within the latter.
Just because you can do it doesn’t mean you should overuse it
Practical Examples
Controlling 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. Which might not make much sense, but it’s to illustrate how functions work
