Contents

Abstract:
A callback function is a very common pattern in programming, which is used to pass a function as an argument to other functions or methods. This pattern is widely applied in scenarios such as event handling, asynchronous programming, and functional programming in Python.
Original Link:
Previous Recommendations:
You who are learning embedded systems, don’t you even know Object Oriented yet? ?!
For more exciting content, you can check out:
Speed Up Your Python: A Quick Guide to Python Parallel Computing
Understand the Debugging Principle of CM3 Microcontroller in One Article
The "Martial Arts Manual" for Computer Science Competitions
Avnet ZUBoard 1CG Development Board — A New Choice for Deep learning
SenseCraft deploys models to the Grove Vision AI V2 image processing module
Document and Code Acquisition:
You can download the document via the following link:
https://github.com/leezisheng/Doc

This document mainly introduces how to use Python for Object Oriented programming, which requires readers to have a basic understanding of Python syntax and microcontroller development. Compared with other blogs or books that explain Python Object Oriented programming, this document is more detailed and focuses on embedded host computer applications, taking the common serial port data transmission and reception, data processing, dynamic graph drawing and other functions between the host computer and the slave computer as application examples. Meanwhile, it uses the Sourcetrail code software to visualize the code for reading to facilitate readers' understanding.
The link to obtain the relevant sample code is as follows:
https://github.com/leezisheng/Python-OOP-Demo
Body Text
From the perspective of the system level, callback functions are generally divided into the following two types:
- System Callbacks: These callback functions are typically used at the operating system level or in underlying libraries. They are designed to respond to system events or signals. For example:
- Interrupt Handler: In embedded systems or operating systems, an interrupt handler is a callback function that responds to hardware interrupts. When a hardware device sends an interrupt signal, the interrupt handler is invoked to process the device's request.
- Asynchronous I/O callback: In some operating systems, a callback function is triggered when an asynchronous I/O operation is completes to notify the application of the operation's completion status. For example, after a file read or write operation is finished, the operating system may invoke the callback function to process the read data.
- Application Callbacks: These callback functions are typically used at the application layer to handle application logic or user interactions. For example:
- Event Handling: In Graphical User Interface (GUI) programming, user interaction events such as button clicks and menu selections are typically handled via callback functions. These callback functions are defined by application developers to respond to user operations.
- Library function callback: When an application uses a certain library function, the library function may require the application to pass in a callback function so that it can be invoked under specific conditions. For example, in a network library, the callback function will be called to process data when a data packet is received.
From the perspective of execution timing, callback functions can be divided into the following types:
- Synchronous Callbacks: These callback functions are executed synchronously within the function that invokes them. That is, before calling the callback function, the caller function will wait for the callback function to finish executing.
- Asynchronous Callbacks: These callback functions are invoked after an asynchronous operation is completed and will not block the caller function. Asynchronous callback functions are typically used to process the results of an asynchronous task.
Definition and Usage of Callback Function
In computer programming, a callback function, or callback for short, refers to a reference to a block of executable code that is passed to other code via function parameters. This design allows low-level code to call subroutines defined at a higher level. Simply put, you define a function and use that function's name as a parameter for another function. The function named in this parameter is called a callback function.
Why do we need callbacks? The purpose is to make library functions more flexible to use. Programming falls into two categories: system programming and application programming. Simply put, system programming refers to writing libraries, while application programming refers to using various pre-written libraries to develop programs with specific functions, namely applications.System programmers leave some interfaces, namely APIs (application programming interfaces), for the libraries they write for use by application programmers. Therefore, in the diagram of the abstraction layer, the library lies underneath the application. When a program is running, under normal circumstances, the application program frequently calls the pre-prepared functions in the library through the API.However, some library functions require the application to pass a function to them first, so that they can call this function at an appropriate time to complete the target task. This function that is passed in and then called is called a callback function.

As can be seen, a callback function usually resides at the same abstraction layer as the application (since which callback function to pass is determined at the application level). Thus, a callback becomes a process where a high-level component calls a low-level one, and then the low-level component calls back to the high-level one. (In my opinion) this should be the earliest application scenario of callbacks, and also the reason why it gets such a name. In a callback, we pass the callback function into the intermediate function in a certain way just like passing a parameter. It can be understood that the intermediate function is incomplete before a callback function is passed into it.In other words, the program can determine and alter the behavior of the intermediate function by registering different callback functions at runtime, which is far more flexible than a simple function call.
For example, there is a hotel that offers wake-up calls, but it requires guests to decide for themselves how they want to be woken up. The options can be a call to the room phone, a waiter knocking on the door, or for those who sleep very deeply and fear being delayed, even a request to have a basin of water poured over their head. Here, the action of "waking someone up" is provided by the hotel, which is equivalent to a library function, while the specific way to carry out this wake-up is decided by the guest and communicated to the hotel — that is the callback function.And the action of a traveler telling the hotel how to wake them up, which is exactly the action of passing a callback function into a library function, is referred to as registering a callback function (to register a callback function).
Then, how to implement a callback function in Python? Let's look at the code:
# The callback function being called
def my_callback(input):
print("function my_callback was called with %s input" % (input,))
# Call the function
def caller(input, func):
func(input)
for i in range(5):
caller(i, my_callback)Application Scenarios of Callback Function
Callback functions are commonly used in the following scenarios:
- Event-driven programming: In GUI programming or network programming, callback functions are used to handle user events or network events; for example, a button click event can be processed via a callback function.
- Asynchronous Programming: When performing an asynchronous operation, you can use a callback function to handle the operation result or error information
- Functional programming: passing functions as arguments to other functions to enhance the flexibility and reusability of code. For example, higher-order functions such as
map,filter, andreduceall use callback functions to process data
In asynchronous programming, callback functions are used to handle the results after asynchronous operations are completed. For example, when using the asyncio module for asynchronous programming, callback functions can be used to handle the results of asynchronous tasks.
import asyncio
async def async_task(callback):
# Simulate an asynchronous operation
await asyncio.sleep(1)
# Call the callback function
callback("Async Result")
def handle_result(result):
print("Callback received result:", result)
# Execute the asynchronous task and use the callback function
async def main():
await async_task(handle_result)
asyncio.run(main())