How does the MCU program interact with the hardware?

2021-11-27 09:52:29 hongling

To interact with the hardware, the MCU program needs to communicate with the kernel, and before that, it must inform the kernel about the existence of the kernel. This is achieved through the "init" call, through which the MCU program is registered in the kernel and allocated the required memory. When the system is shut down, the "exit" call will be used to cancel the registration of the MCU program, which will also release all the resources occupied by the MCU program. The calls used to define the "init" and "exit" functions are:

module_ init(init_function_name);

module_ exit(exit_function_name);

We can write our own init and exit functions, and write the MCU programs calling the devices respectively by the above two. The simplest init function is as follows:

static int init_ function_ name(void)


printk(KERN_ALERT“ Hello”);

return 0;


Similarly, we can also write exit functions. As you can see, in order to obtain the kernel log, we use the printk() function similar to the C function printf(), but we need an optional special log level string (here kern_alert – log level 1) to indicate the severity type error message. There are eight log levels. The default value is Kern_ Warning (log level 4).

One of the most important components in the device MCU program is the file operation (FOPS) structure. This structure specifies the functions of the device for which the MCU program is written. It contains pointers to functions written for operations supported by the device. The basic FOPS structure can be described as follows:

static struct file_ operations fops =


.read = my_read;

.write = my_write;

.open = my_open;

.release = my_release;


The above definition is that whenever the device must read something, it will call my_ Read function (written by the developer). Similarly, pointers to other functions are the corresponding names for the functions they refer to.

If the device for which the MCU program is written supports the interrupt function, the MCU program must register the interrupt service program (ISR) in the init function. As long as the interrupt is received in the device, the function will be called. This is done by using the kernel function request that requires an interrupt handler_ IRQ (), and then enable the interrupt line to receive the interrupt. On the other hand, when the MCU program is unloaded, the kernel function free_ IRQ () is used to release interrupt handlers and interrupt lines. We will cover them in detail in future posts.