Ground Embedded KO Subscribe

Notes / Embedded Linux

Device drivers: writing a kernel module

Code that handles hardware inside the kernel. From the simplest module to the structure of a platform driver and an I2C driver.

GROUND EMBEDDED · NOTEEmbedded Linux 05Device drivers 1$ make ARCH=arm 2$ insmod gnd_gpio.ko 3[ 1.024] gnd: probe ok 4$ cat /dev/gnd0 50x5A 6$ _

The simplest kernel module

#include <linux/module.h>
static int __init hello_init(void) { pr_info("hello\n"); return 0; }
static void __exit hello_exit(void) { pr_info("bye\n"); }
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");

Load it with insmod hello.ko, check with dmesg, and unload it with rmmod hello.

The driver model

Appread(), write()System callKernelDriverHardware
The path an application's request takes to the hardware.
Concept Meaning
Bus platform, i2c, spi, usb
Device A device listed in the device tree
Driver probe() is called when compatible matches

For an I2C sensor driver, probe() initialises the registers and creates the interface that shows values to user space (sysfs attributes, IIO, hwmon, a character device).

RoadmapSee where this note sits in Embedded Linux→

Differences from MCU code

  • A crash in the kernel takes down the whole board (kernel panic).
  • Floating point is restricted, and the stack is small (a few KB)
  • Register access is through ioremap and readl/writel; I2C through subsystem APIs such as i2c_smbus_read_byte_data
  • Interrupt handling is split into a top half (fast handling) and a bottom half (threads, work queues)

Look first

Most common chips already have a driver in the mainline kernel. Often all you need is the right device tree.

FREE PDFGet the 3 free ebooksIf you want to keep reading this topic as one book: BLDC motor control, serial communication and sensors at book length. PDFs are in Korean.Get them free →