Tag: Embedded Systems Programming

  • How to Write an I2C Driver in Linux: Master Complete Beginner-Friendly Guide

    This guide walks you through writing an I2C driver in Linux from scratch. Whether you are a beginner touching Linux kernel driver development for the first time or preparing for an embedded systems interview, you will find practical code, clear explanations, and real-world context here.

    What Is an I2C Driver and Why Does It Matter?

    If you have been working with microcontrollers or Linux-based embedded systems for a while, you have almost certainly bumped into I2C. It stands for Inter-Integrated Circuit, and it is one of the most popular communication protocols in the embedded world. Sensors, EEPROM chips, real-time clocks, display controllers a huge chunk of the hardware you interact with on a daily basis talks over I2C.

    But here is the thing: most tutorials show you how to use I2C. Very few show you how to write an I2C driver from the ground up inside the Linux kernel. That is exactly what we are going to do today.

    By the end of this guide, you will understand what an I2C driver is, how the I2C subsystem works in Linux, how to write a basic I2C client driver, how to read and write registers on a real device, and how to test everything using common kernel debugging tools. No hand-waving, no magic just real code and real explanations.

    Understanding the I2C Protocol First

    Before you write a single line of kernel code, you need to understand what I2C actually is at the hardware level. Trust me — this saves you hours of debugging later.

    I2C is a synchronous, multi-master, multi-slave serial communication protocol. It uses just two wires: SDA (Serial Data) and SCL (Serial Clock). One device acts as the master and controls the clock. The other devices are slaves and respond when addressed.

    Each slave device has a unique 7-bit address (or sometimes 10-bit). The master kicks off every transaction by sending the slave address along with a read/write bit. If the slave acknowledges, the data transfer begins. This is the core of how I2C works.

    Why I2C Is So Common in Embedded Systems

    I2C only needs two signal lines, which makes it incredibly hardware-friendly. You can chain multiple devices on the same bus as long as each has a unique address. This matters when board space and pin count are limited which is basically always in embedded design. Common devices you would connect over I2C include temperature sensors like the LM75, accelerometers like the MPU6050, OLED displays driven by the SSD1306, and I2C EEPROMs like the AT24C series. If you are learning how to write an I2C device driver, working with one of these is a great starting point

    How the Linux I2C Subsystem Works

    Linux has a very clean layered architecture for I2C. Understanding this architecture is crucial before you write your I2C driver. Here is how it breaks down:

    The Three Layers You Need to Know

    The first layer is the I2C adapter driver. This is the low-level driver that controls the physical I2C bus controller on your SoC or board. On a Raspberry Pi, BeagleBone, or any ARM-based platform, this is already written for you. You do not need to touch it unless you are writing drivers for custom silicon.

    The second layer is the I2C core. This lives in drivers/i2c/i2c-core-base.c in the kernel source tree. It is the glue that sits between adapters and client drivers. It provides the API that you, as a driver writer, will call.

    The third layer is the I2C client driver. This is what you write. A client driver talks to a specific I2C device — your sensor, your EEPROM, your display. This is the layer we focus on in this entire guide.

    Key Data Structures in the I2C Subsystem

    There are four structures you will use constantly when writing an I2C driver. Get comfortable with all of them.

    struct i2c_adapter

    This represents the physical I2C bus controller. Think of it as the hardware that drives the SDA and SCL lines. When your driver calls i2c_transfer(), it is using the adapter underneath. You typically do not define this — the platform or SoC driver does.

    struct i2c_client

    This represents the slave device sitting on the bus. It holds the device address, the adapter it belongs to, and the device name. When the kernel instantiates your device, it creates an i2c_client for you and passes it to your probe function.

    struct i2c_client {
        unsigned short flags;
        unsigned short addr;       /* 7-bit I2C address */
        char name[I2C_NAME_SIZE];
        struct i2c_adapter *adapter;
        struct device dev;
        int irq;
        /* ... */
    };

    struct i2c_driver

    This is the structure you define in your driver. It ties your probe, remove, and id_table together. When the kernel matches a device to your driver (via the id_table or device tree), it calls your probe function.

    struct i2c_driver {
        int (*probe)(struct i2c_client *client,
                     const struct i2c_device_id *id);
        int (*remove)(struct i2c_client *client);
        struct device_driver driver;
        const struct i2c_device_id *id_table;
        /* ... */
    };

    struct i2c_msg

    This represents a single I2C message — a read or a write transaction on the bus. When you call i2c_transfer(), you pass an array of these messages. Each message has a slave address, flags, a byte count, and a buffer pointer.

    struct i2c_msg {
        __u16 addr;    /* Slave address */
        __u16 flags;   /* 0 = write, I2C_M_RD = read */
        __u16 len;     /* Data length */
        __u8 *buf;     /* Data buffer */
    };
    

    Setting Up Your Development Environment

    Before you write your I2C kernel module, you need a working kernel build environment. Here is what you need:

    • A Linux machine (native or VM — Ubuntu 22.04 or later works great)
    • Kernel headers or the full kernel source tree
    • A Makefile for building out-of-tree modules
    • Cross-compilation tools if you are targeting ARM (arm-linux-gnueabihf-gcc)
    • An actual I2C device to test with — an MPU6050 or AT24C02 EEPROM works perfectly

    Install Required Packages

    • sudo apt update
    • sudo apt install build-essential linux-headers-$(uname -r)
    • sudo apt install i2c-tools  # Very useful for testing

    Verify Your I2C Bus

    Before writing any driver code, check that your I2C bus is working and your device is detected. On a Raspberry Pi or BeagleBone:

    i2cdetect -y 1

    This command scans I2C bus 1 and prints a grid of detected device addresses. If your sensor shows up (say at address 0x68 for an MPU6050), you are good to go.

    Writing Your First I2C Driver: Step by Step

    Now we get to the real work. We are going to write a complete, working I2C client driver for a simple device. We will use the AT24C02 I2C EEPROM as our example because it is cheap, easy to get, and the register access pattern is straightforward. The full driver will have: module init/exit, an i2c_driver struct, a probe function, a remove function, basic read/write functions using i2c_transfer, and a sysfs interface so you can read/write from userspace.

    Step 1: Include the Right Headers

    #include <linux/module.h>
    
    #include <linux/init.h>
    
    #include <linux/i2c.h>
    
    #include <linux/kernel.h>
    
    #include <linux/slab.h>
    
    #include <linux/fs.h>
    
    #include <linux/device.h>

    Step 2: Define the Device ID Table

    The id_table tells the kernel which devices your driver supports. The kernel uses this to match your driver to a device — either from a platform file or from the device tree.

    static const struct i2c_device_id myeeprom_id[] = {
        { "at24c02", 0 },
        { }   /* Sentinel */
    };
    MODULE_DEVICE_TABLE(i2c, myeeprom_id);

    Step 3: Write the Probe Function

    The probe function is called by the kernel when it finds a matching device. This is where you initialize your device, allocate memory, and set up any interfaces (like sysfs or character device files). Think of probe as your driver’s constructor.

    static int myeeprom_probe(struct i2c_client *client,
    
                              const struct i2c_device_id *id)
    
    {
    
        dev_info(&client->dev, "myeeprom: probing device at 0x%02x\n",
    
                 client->addr);
    
        /* Check if adapter supports everything we need */
    
        if (!i2c_check_functionality(client->adapter,
    
                                      I2C_FUNC_SMBUS_BYTE_DATA)) {
    
            dev_err(&client->dev, "Adapter does not support SMBus\n");
    
            return -ENODEV;
    
        }
    
        return 0;  /* Probe success */
    
    }

    Step 4: Write the Remove Function

    The remove function is called when the device is removed or the driver is unloaded. Clean up whatever you allocated in probe. Release memory, unregister interfaces, and free IRQs if you grabbed any.

    static int myeeprom_remove(struct i2c_client *client)
    
    {
    
        dev_info(&client->dev, "myeeprom: removing device\n");
    
        return 0;
    
    }

    Step 5: Define the i2c_driver Struct

    static struct i2c_driver myeeprom_driver = {
    
        .driver = {
    
            .name  = "myeeprom",
    
            .owner = THIS_MODULE,
    
        },
    
        .probe    = myeeprom_probe,
    
        .remove   = myeeprom_remove,
    
        .id_table = myeeprom_id,
    
    };

    Step 6: Module Init and Exit

    These two functions register and unregister your driver with the I2C core. The module_i2c_driver macro is a shorthand that does exactly this — it expands into the init and exit boilerplate for you.

    module_i2c_driver(myeeprom_driver);
    
    MODULE_LICENSE("GPL");
    
    MODULE_AUTHOR("Raj Kumar <embeddedprep.com/>");
    
    MODULE_DESCRIPTION("Simple AT24C02 I2C EEPROM Driver");

    Reading and Writing Registers Over I2C

    Having a probe function is great, but your I2C driver needs to actually communicate with the device. Let us look at the two main ways to do that in the Linux kernel.

    Method 1: Using SMBus Functions

    SMBus is a subset of I2C, and Linux has a very clean API for it. If your device is SMBus-compatible (most simple sensors and EEPROMs are), use these. They are simpler and handle a lot of the transaction overhead for you.

    /* Read a single byte from a register */
    
    s32 i2c_smbus_read_byte_data(struct i2c_client *client, u8 command);
    
    /* Write a single byte to a register */
    
    s32 i2c_smbus_write_byte_data(struct i2c_client *client,
    
                                   u8 command, u8 value);
    
    Here is a real example. Say you want to read the temperature from an LM75 sensor (register 0x00):
    
    s32 temp_raw = i2c_smbus_read_byte_data(client, 0x00);
    
    if (temp_raw < 0) {
    
        dev_err(&client->dev, "Failed to read temperature\n");
    
        return temp_raw;
    
    }
    
    dev_info(&client->dev, "Raw temp: %d\n", temp_raw);

    Method 2: Using i2c_transfer for Raw I2C Transactions

    When SMBus functions are not enough — for example, when you need combined write-then-read transactions or non-standard protocols — you drop down to i2c_transfer. This gives you full control over every byte on the bus.

    Here is how to write a register address and then read back two bytes from it:

    int mydevice_read_register(struct i2c_client *client,
    
                                u8 reg, u8 *val, int len)
    
    {
    
        struct i2c_msg msgs[2];
    
        int ret;
    
        /* First message: write register address */
    
        msgs[0].addr  = client->addr;
    
        msgs[0].flags = 0;          /* Write */
    
        msgs[0].len   = 1;
    
        msgs[0].buf   = &reg;
    
        /* Second message: read the data back */
    
        msgs[1].addr  = client->addr;
    
        msgs[1].flags = I2C_M_RD;  /* Read */
    
        msgs[1].len   = len;
    
        msgs[1].buf   = val;
    
        ret = i2c_transfer(client->adapter, msgs, 2);
    
        if (ret != 2) {
    
            dev_err(&client->dev, "i2c_transfer failed: %d\n", ret);
    
            return ret < 0 ? ret : -EIO;
    
        }
    
        return 0;
    
    }

    The key insight here: i2c_transfer returns the number of messages successfully transferred, not the number of bytes. So for 2 messages, you check ret == 2.

    Adding Device Tree Support to Your I2C Driver

    Modern Linux systems use the device tree to describe hardware. If you want your I2C driver to work on ARM platforms (Raspberry Pi, BeagleBone, i.MX boards, etc.), you need to add device tree support. This is not optional — it is the standard approach for any driver you want to upstream or deploy on real hardware.

    Add an of_match_table

    static const struct of_device_id myeeprom_of_match[] = {
    
        { .compatible = "atmel,at24c02" },
    
        { }
    
    };
    
    MODULE_DEVICE_TABLE(of, myeeprom_of_match);
    
    Then add it to your i2c_driver struct:
    
    .driver = {
    
        .name           = "myeeprom",
    
        .of_match_table = myeeprom_of_match,
    
        .owner          = THIS_MODULE,
    
    },

    Device Tree Node Example

    In your board’s .dts or .dtsi file, add a node like this to describe your I2C device:

    &i2c1 {
    
        status = "okay";
    
        eeprom@50 {
    
            compatible = "atmel,at24c02";
    
            reg = <0x50>;
    
        };
    
    };

    When the kernel boots and parses this device tree, it will instantiate an i2c_client for your device at address 0x50 and call your probe function automatically.

    Writing the Complete Makefile

    You need a Makefile to build your kernel module. Here is a clean, minimal one that works for any out-of-tree I2C driver:

    obj-m += myeeprom.o
    
    KDIR := /lib/modules/$(shell uname -r)/build
    
    PWD  := $(shell pwd)
    
    all:
    
       $(MAKE) -C $(KDIR) M=$(PWD) modules
    
    clean:
    
       $(MAKE) -C $(KDIR) M=$(PWD) clean

    Build it with:

    make

    Load it with:

    sudo insmod myeeprom.ko

    Check kernel logs:

    dmesg | tail -20

    Testing and Debugging Your I2C Driver

    Writing the code is half the battle. Testing and debugging is where you really learn what is happening. Here are the tools and techniques that actually work.

    i2c-tools for Quick Hardware Verification

    Before you even load your driver, use i2c-tools to verify communication with the device:

    # Scan the bus for devices

    i2cdetect -y 1

    # Read a register directly

    i2cget -y 1 0x50 0x00

    # Write a value to a register

    i2cset -y 1 0x50 0x00 0xAB

    These tools bypass your driver entirely and talk to the hardware directly through the i2c-dev interface. If these work but your driver does not, the problem is in your driver code, not the hardware.

    Using dmesg for Kernel Log Messages

    Always use the dev_info, dev_warn, and dev_err macros in your driver rather than printk. They prefix your messages with the device name automatically, which makes log filtering much easier:

    dev_info(&client->dev, “Driver probed at address 0x%02x\n”, client->addr);

    dev_err(&client->dev, “Read failed with error %d\n”, ret);

    Then check your messages:

    dmesg | grep myeeprom

    Using /sys/bus/i2c/devices

    After your driver loads and probe succeeds, check the sysfs tree:

    ls /sys/bus/i2c/devices/

    cat /sys/bus/i2c/devices/1-0050/name

    This tells you that the kernel has matched your driver to the device and probe was called successfully.

    Common Errors and What They Mean

    If probe returns -ENODEV, it means either the device is not on the bus or i2c_check_functionality failed. Run i2cdetect to verify the device is present.

    If i2c_transfer returns -ETIMEDOUT, the device is not acknowledging. Check your wiring, pull-up resistors, and bus speed.

    If i2c_transfer returns -EIO, there was a bus error. This often points to missing or wrong pull-up resistors on SDA and SCL lines.

    If you see -EBUSY, something else already has the device — either another driver is bound to it or i2c-dev is holding it open.

    Adding a Sysfs Interface to Your I2C Driver

    Sysfs is the standard way to expose driver attributes to userspace in Linux. Adding a sysfs attribute to your I2C driver lets you read sensor data or write configuration values directly from the command line or a Python script — without writing a separate userspace application.

    Define a Sysfs Attribute

    static ssize_t temperature_show(struct device *dev,
    
                                      struct device_attribute *attr,
    
                                      char *buf)
    
    {
    
        struct i2c_client *client = to_i2c_client(dev);
    
        s32 val = i2c_smbus_read_byte_data(client, 0x00);
    
        if (val < 0)
    
            return val;
    
        return sprintf(buf, "%d\n", val);
    
    }
    
    static DEVICE_ATTR_RO(temperature);

    Register the Attribute in Probe

    ret = device_create_file(&client->dev, &dev_attr_temperature);
    
    if (ret) {
    
        dev_err(&client->dev, "Failed to create sysfs file\n");
    
        return ret;
    
    }

    After loading, read the value from userspace:

    cat /sys/bus/i2c/devices/1-0048/temperature

    Full Working I2C Driver Example (Complete Code)

    Here is the complete, minimal I2C driver putting everything together. You can use this as a template for any new I2C device driver you write:

    #include <linux/module.h>
    
    #include <linux/init.h>
    
    #include <linux/i2c.h>
    
    #include <linux/kernel.h>
    
    #include <linux/slab.h>
    
    struct mydevice_data {
    
        struct i2c_client *client;
    
    };
    
    static ssize_t value_show(struct device *dev,
    
                               struct device_attribute *attr, char *buf)
    
    {
    
        struct i2c_client *client = to_i2c_client(dev);
    
        s32 val = i2c_smbus_read_byte_data(client, 0x00);
    
        if (val < 0) return val;
    
        return sprintf(buf, "%d\n", val);
    
    }
    
    static DEVICE_ATTR_RO(value);
    
    static int mydevice_probe(struct i2c_client *client,
    
                               const struct i2c_device_id *id)
    
    {
    
        struct mydevice_data *data;
    
        int ret;
    
        if (!i2c_check_functionality(client->adapter,
    
                                      I2C_FUNC_SMBUS_BYTE_DATA))
    
            return -ENODEV;
    
        data = devm_kzalloc(&client->dev, sizeof(*data), GFP_KERNEL);
    
        if (!data) return -ENOMEM;
    
        data->client = client;
    
        i2c_set_clientdata(client, data);
    
        ret = device_create_file(&client->dev, &dev_attr_value);
    
        if (ret) return ret;
    
        dev_info(&client->dev, "mydevice probed at 0x%02x\n", client->addr);
    
        return 0;
    
    }
    
    static int mydevice_remove(struct i2c_client *client)
    
    {
    
        device_remove_file(&client->dev, &dev_attr_value);
    
        return 0;
    
    }
    
    static const struct i2c_device_id mydevice_id[] = {
    
        { "mydevice", 0 }, { }
    
    };
    
    MODULE_DEVICE_TABLE(i2c, mydevice_id);
    
    static const struct of_device_id mydevice_of_match[] = {
    
        { .compatible = "myvendor,mydevice" }, { }
    
    };
    
    MODULE_DEVICE_TABLE(of, mydevice_of_match);
    
    static struct i2c_driver mydevice_driver = {
    
        .driver = {
    
            .name           = "mydevice",
    
            .of_match_table = mydevice_of_match,
    
            .owner          = THIS_MODULE,
    
        },
    
        .probe    = mydevice_probe,
    
        .remove   = mydevice_remove,
    
        .id_table = mydevice_id,
    
    };
    
    module_i2c_driver(mydevice_driver);
    
    MODULE_LICENSE("GPL");
    
    MODULE_AUTHOR("Raj Kumar");
    
    MODULE_DESCRIPTION("Generic I2C Device Driver Template");

    I2C Driver vs SPI Driver: Key Differences

    A question that comes up a lot for beginners: when should you use I2C versus SPI, and how does the driver structure differ?

    I2C uses two wires and supports multiple devices on the same bus. SPI uses four wires (MOSI, MISO, SCLK, CS) per device but is faster. For I2C device driver programming, addressing is built into the protocol. For SPI, you manage chip-select lines manually.

    The driver structure in Linux is similar — both use probe/remove, both support device tree. The main difference is the bus-specific APIs: i2c_transfer and i2c_smbus_* for I2C, versus spi_transfer and spi_sync for SPI. If you understand one, picking up the other takes maybe a day.

    Common I2C Driver Interview Questions

    If you are studying for embedded Linux interviews, these are the questions you should be ready to answer about I2C driver development:

    What is the difference between i2c_transfer and i2c_smbus_read_byte_data?

    i2c_smbus_read_byte_data is a higher-level function that handles a standard SMBus read of one byte from a register. i2c_transfer is the low-level function that gives you direct control over the I2C messages sent on the bus. Use SMBus functions when they fit your device’s protocol; use i2c_transfer when you need custom multi-message transactions.

    What does i2c_check_functionality do and why is it important?

    i2c_check_functionality queries the adapter to see if it supports a specific set of features — like SMBus byte data, block reads, or I2C combined transactions. Calling it in probe before you do any transfers prevents cryptic failures later when you try to use a feature the adapter does not support.

    What is devm_kzalloc and why should you use it?

    devm_kzalloc is a device-managed version of kzalloc. Memory allocated with it is automatically freed when the device is removed or the driver is unbound. This prevents memory leaks in your driver without requiring explicit cleanup code in the remove function. Always prefer devm_ variants in modern kernel driver code.

    How does the kernel match an I2C driver to a device?

    The kernel uses three matching mechanisms: the i2c_device_id table (for platform-instantiated devices), the of_device_id table (for device tree nodes), and ACPI IDs. When a match is found, the kernel calls the driver’s probe function with the corresponding i2c_client.

    Best Practices for Writing I2C Drivers in Linux

    After writing several I2C drivers, you start to notice patterns that save you from bugs. Here are the practices worth adopting from day one:

    • Always call i2c_check_functionality in probe — do not assume the adapter supports what you need.
    • Use devm_ prefixed allocation functions (devm_kzalloc, devm_request_irq) to avoid resource leaks.
    • Store per-device state in a private structure and use i2c_set_clientdata / i2c_get_clientdata to attach and retrieve it.
    • Check return values from every i2c_smbus_ and i2c_transfer call — never ignore them.
    • Use dev_err / dev_info with &client->dev rather than plain printk — it gives you device-specific log context.
    • Handle -EPROBE_DEFER in probe if your driver depends on another driver (like a clock or regulator) that might not be ready yet.
    • Add device tree support with an of_match_table even if you are initially using i2c_device_id — it makes your driver portable.

    Registering an I2C Device Without Device Tree (Legacy Method)

    On older kernels or bare-metal-style BSPs, devices are sometimes registered programmatically using i2c_board_info. You will see this in older platform files:

    static struct i2c_board_info my_board_info[] = {
    
        {
    
            I2C_BOARD_INFO("at24c02", 0x50),
    
        },
    
    };
    
    i2c_register_board_info(1, my_board_info, ARRAY_SIZE(my_board_info));

    This approach is deprecated for new code. Use device tree on all modern Linux platforms. But you will encounter this in legacy codebases, so it is worth knowing.

    Wrapping Up: What You Have Learned

    If you followed this guide all the way through, you now understand the full picture of how to write an I2C driver in Linux. You know how the I2C protocol works at the hardware level, how the Linux I2C subsystem is layered, what the key data structures are (i2c_adapter, i2c_client, i2c_driver, i2c_msg), how to write probe and remove functions, how to perform read and write operations using both SMBus and raw i2c_transfer, how to add device tree support, how to test your driver with i2c-tools and dmesg, and how to expose your driver’s data through sysfs.

    That is not a small amount of knowledge. Most embedded developers I know learned this over months of trial and error. Now you have it in one place.

    The best next step from here: grab an I2C sensor (an MPU6050 is perfect), connect it to a Raspberry Pi or BeagleBone, and write a real driver from scratch using this guide as your reference. Nothing cements kernel driver concepts faster than actually debugging a real driver on real hardware.

    Next Steps: Check out our guides on SPI driver development, platform device drivers, and writing device tree overlays on embeddedprep.com/.
  • SPI Driver Development Guide: Master Linux SPI Driver, Code in C & Architecture Explained (2026)

    Learn how to write an SPI Driver from scratch. Step-by-step guide to Linux SPI driver, SPI controller driver, SPI device driver, SPI driver code in C, and Raspberry Pi SPI driver development.

    If you’ve ever connected a sensor, display, ADC, DAC, or flash chip to a microcontroller or Linux board, you’ve already stepped into the world of SPI. But here’s the real step forward. Learning how to write an SPI Driver from scratch.

    This guide is not just theory. It’s a practical, beginner-friendly walkthrough that shows you exactly how SPI communication works, how the SPI driver circuit is structured, and how to write clean, reliable SPI driver code in C. We’ll go deep into Linux SPI driver development, break down Linux SPI driver architecture in simple terms, and build a working Linux SPI driver example that you can actually understand and modify.

    Whether you are working on embedded systems, building a Raspberry Pi project, developing a SPI controller driver, or designing a SPI flash controller driver, this article gives you a clear roadmap. We’ll also look at spi_common.h, explain the difference between a SPI controller driver and a SPI device driver, and even touch on how to structure a C++ SPI driver properly.

    By the end of this guide, you’ll understand:

    • What an SPI Driver actually does
    • How SPI works at hardware and software level
    • How to write SPI driver code in C
    • How to build a Linux SPI driver
    • How the Linux SPI driver architecture works
    • How to handle SPI on Raspberry Pi
    • How SPI controller drivers differ from SPI device drivers
    • How SPI flash controller drivers work
    • Where spi_common.h fits in
    • Even how to structure a C++ SPI driver

    Let’s start from the basics.

    What Is an SPI Driver?

    An SPI Driver is software that allows your system to communicate with SPI devices using the Serial Peripheral Interface protocol.

    SPI is a synchronous communication protocol that uses four main lines:

    • MOSI (Master Out Slave In)
    • MISO (Master In Slave Out)
    • SCLK (Clock)
    • CS (Chip Select)

    The driver handles:

    • Initializing SPI hardware
    • Setting clock speed and mode
    • Managing data transfers
    • Handling interrupts or polling
    • Managing multiple devices

    Without a driver, your SPI hardware is just idle silicon.

    Understanding the SPI Driver Circuit

    Before writing code, you must understand the SPI driver circuit.

    At hardware level, SPI consists of:

    1. Master device (microcontroller or SoC)
    2. One or more slave devices
    3. Shared clock line
    4. Separate chip select for each slave

    The SPI driver must configure:

    • Clock polarity (CPOL)
    • Clock phase (CPHA)
    • Bit order (MSB or LSB)
    • Clock frequency
    • Chip select control

    If these are wrong, communication fails even if your code is perfect.

    So always check your device datasheet before writing the driver.

    Two Types of SPI Drivers

    When people search for SPI Driver development, they usually mean one of these:

    1. SPI Controller Driver

    This controls the SPI hardware peripheral in your SoC.

    It:

    • Configures registers
    • Manages FIFO
    • Controls clock
    • Handles interrupts

    This is hardware-specific.

    2. SPI Device Driver

    This talks to a specific SPI device like a sensor or flash chip.

    It:

    • Uses the SPI controller
    • Sends commands
    • Parses responses
    • Implements device-specific logic

    In Linux, these two are separate.

    Writing SPI Driver Code in C (Bare Metal Example)

    Let’s start simple.

    Here’s a basic SPI driver code in C for a microcontroller:

    #define SPI_CR1     (*(volatile unsigned int*)0x40013000)
    #define SPI_SR      (*(volatile unsigned int*)0x40013008)
    #define SPI_DR      (*(volatile unsigned int*)0x4001300C)
    
    void SPI_Init(void)
    {
        SPI_CR1 = (1 << 6);   // Enable SPI
    }
    
    void SPI_Transmit(uint8_t data)
    {
        while (!(SPI_SR & (1 << 1)));  // Wait TX empty
        SPI_DR = data;
    }
    
    uint8_t SPI_Receive(void)
    {
        while (!(SPI_SR & (1 << 0)));  // Wait RX not empty
        return SPI_DR;
    }
    

    This is raw register-level spi driver code. It works for microcontrollers where you directly control hardware registers.

    In real projects, you’ll add:

    • Clock configuration
    • Mode selection
    • Error handling
    • Timeout protection

    That’s how basic SPI driver development starts.

    C++ SPI Driver Structure

    If you’re working with embedded C++, you can wrap SPI into a class:

    class SPIDriver {
    public:
        void init();
        void transmit(uint8_t data);
        uint8_t receive();
    };
    

    A C++ SPI driver helps when:

    • You want abstraction
    • You’re building reusable libraries
    • You’re working in embedded Linux with OOP design

    Under the hood, it still calls low-level C functions.

    Linux SPI Driver Architecture Explained Simply

    Now let’s move to Linux.

    The Linux SPI driver architecture is layered.

    It looks like this:

    User Space
    ↓
    SPI Device Driver
    ↓
    SPI Core
    ↓
    SPI Controller Driver
    ↓
    Hardware

    Linux separates:

    • Controller drivers (hardware side)
    • Device drivers (device side)

    This makes the system modular and scalable.

    Linux SPI Driver Structure

    A typical Linux SPI driver includes:

    1. Probe function
    2. Remove function
    3. SPI device ID table
    4. SPI driver structure

    Example skeleton:

    static int my_spi_probe(struct spi_device *spi)
    {
        printk("SPI device probed\n");
        return 0;
    }
    
    static int my_spi_remove(struct spi_device *spi)
    {
        printk("SPI device removed\n");
        return 0;
    }
    
    static struct spi_driver my_spi_driver = {
        .driver = {
            .name = "my_spi_device",
            .owner = THIS_MODULE,
        },
        .probe = my_spi_probe,
        .remove = my_spi_remove,
    };
    
    module_spi_driver(my_spi_driver);
    

    That’s your minimal linux spi driver example.

    How Data Transfer Works in Linux SPI Driver

    Linux provides spi_sync() and spi_async().

    Example transfer:

    struct spi_transfer t = {
        .tx_buf = tx_buffer,
        .rx_buf = rx_buffer,
        .len = length,
    };
    
    struct spi_message m;
    spi_message_init(&m);
    spi_message_add_tail(&t, &m);
    
    spi_sync(spi, &m);
    

    That’s the clean way to move data inside a spi device driver.

    Role of spi_common.h in SPI Driver Development

    When writing kernel-level drivers, you’ll often see references to spi_common.h.

    This header:

    • Defines common SPI structures
    • Contains shared utilities
    • Avoids code duplication

    If you’re building a custom spi controller driver, this header becomes important.

    Writing a SPI Controller Driver in Linux

    A spi controller driver handles hardware registers.

    Steps:

    1. Allocate spi_controller
    2. Map I/O memory
    3. Implement transfer_one() callback
    4. Register controller with SPI core

    Example outline:

    struct spi_controller *ctlr;
    
    ctlr = spi_alloc_master(dev, sizeof(struct my_spi));
    ctlr->mode_bits = SPI_CPOL | SPI_CPHA;
    ctlr->transfer_one = my_transfer_function;
    
    spi_register_controller(ctlr);
    

    This connects your hardware to the Linux SPI subsystem.

    SPI Flash Controller Driver

    SPI Flash Controller Driver

    SPI flash is common in embedded systems.

    A spi flash controller driver manages:

    • Flash read/write commands
    • Erase sectors
    • JEDEC ID detection
    • Memory mapping

    Linux usually uses MTD subsystem with SPI NOR drivers.

    If writing custom logic, you’ll implement:

    • Write enable command
    • Page program
    • Sector erase
    • Status register polling

    Flash drivers must handle timing carefully.

    Raspberry Pi SPI Driver Development

    When working with raspberry pi spi driver projects:

    You usually don’t write a controller driver because it already exists in Linux.

    Instead, you:

    • Enable SPI via device tree
    • Write a device driver
    • Or use spidev interface

    To enable SPI:

    sudo raspi-config
    

    Then enable SPI.

    For quick testing:

    sudo apt install spi-tools
    

    For custom kernel driver, follow Linux SPI driver steps explained above.

    Complete Linux SPI Driver Development Flow

    Here’s a practical roadmap for spi driver development:

    1. Understand hardware datasheet
    2. Confirm SPI mode
    3. Enable SPI controller
    4. Write device driver skeleton
    5. Implement probe()
    6. Implement transfer logic
    7. Test with loopback
    8. Handle errors
    9. Add power management
    10. Optimize performance

    Never skip testing with a logic analyzer.

    Common Mistakes While Writing SPI Driver

    Let’s save you from painful debugging.

    1. Wrong SPI mode
    2. Incorrect clock speed
    3. Not handling chip select properly
    4. Ignoring endianness
    5. Not checking return values
    6. Blocking calls inside interrupt context

    Most SPI bugs are timing-related.

    How to Test SPI Driver

    You can test using:

    • Loopback mode
    • Logic analyzer
    • Oscilloscope
    • spidev interface in Linux

    Example Linux test:

    echo -ne "\x9F" | spidev_test -D /dev/spidev0.0
    

    For flash chips, read JEDEC ID.

    How to Package and SPI Driver Download Options

    If you’re distributing your work:

    • Provide source code
    • Include Makefile
    • Add README with hardware details
    • Mention supported kernel version

    For spi driver download, developers expect:

    • GitHub repo
    • Kernel module source
    • Clear build instructions

    Keep documentation clean and direct.

    Performance Optimization Tips

    If your SPI driver is slow:

    • Increase clock speed carefully
    • Use DMA if available
    • Reduce chip select toggling
    • Use async transfers
    • Minimize memory copies

    In high-speed flash systems, these changes matter a lot.

    When to Use User-Space vs Kernel-Space SPI Driver

    If you’re prototyping:

    Use spidev in user space.

    If you’re building production firmware:

    Write a proper spi device driver.

    Kernel drivers offer:

    • Better performance
    • Interrupt handling
    • Integration with subsystems

    Conclusion on Writing an SPI Driver

    Writing an SPI Driver is not magic. It’s a mix of:

    • Understanding hardware
    • Reading datasheets carefully
    • Writing clean C code
    • Following Linux driver model
    • Testing thoroughly

    Start small.

    Write minimal spi driver code.

    Then improve step by step.

    If you master:

    • Linux SPI driver architecture
    • SPI controller driver structure
    • SPI device driver logic
    • Flash memory handling
    • Raspberry Pi SPI setup

    You’ll be comfortable building drivers for almost any SPI device.

    And once you write your first working driver and see clean waveforms on the logic analyzer, it feels good.

    Really good.

    FAQ SPI Driver

    1. What is an SPI Driver in simple terms?

    An SPI Driver is software that allows your processor or operating system to communicate with SPI-based devices like sensors, ADCs, DACs, displays, and flash memory.

    It configures the SPI hardware, manages clock settings, handles data transfer, and ensures reliable communication between master and slave devices.

    Without it, your SPI hardware cannot talk to external chips.

    2. What is the difference between an SPI controller driver and an SPI device driver?

    Good question. Many beginners confuse this.

    • SPI controller driver controls the SPI hardware peripheral inside your microcontroller or SoC.
    • SPI device driver talks to a specific SPI device like a temperature sensor or flash chip.

    In Linux SPI driver architecture, these are separate layers. The controller handles hardware registers. The device driver sends device-specific commands.

    3. How do I start SPI driver development as a beginner?

    Start simple:

    1. Read the SPI device datasheet carefully
    2. Identify SPI mode (CPOL, CPHA)
    3. Confirm clock frequency limits
    4. Write basic SPI transmit and receive functions
    5. Test using loopback

    If you are learning Linux SPI driver development, begin with a minimal Linux SPI driver example and modify it step by step.

    4. What language is used to write SPI driver code?

    Most SPI driver code is written in C, especially for embedded systems and Linux kernel development.

    You can also build a C++ SPI driver in embedded systems if your environment supports C++, but under the hood it still interacts with C-based hardware APIs.

    Kernel-level Linux SPI drivers are written in C.

    5. How does Linux SPI driver architecture work?

    Linux SPI driver architecture has multiple layers:

    User Space
    ↓
    SPI Device Driver
    ↓
    SPI Core
    ↓
    SPI Controller Driver
    ↓
    Hardware

    This separation makes the system modular and clean. The SPI core manages communication between device drivers and controller drivers.

    6. How can I test my Linux SPI driver?

    You can test your Linux SPI driver using:

    • Loopback wiring
    • Logic analyzer
    • Oscilloscope
    • spidev utility

    For example, you can use /dev/spidevX.Y to test communication before writing a full kernel module.

    Testing early saves hours of debugging later.

    7. How do I enable SPI on Raspberry Pi?

    For raspberry pi spi driver testing:

    1. Open terminal
    2. Run sudo raspi-config
    3. Enable SPI interface
    4. Reboot

    After that, you can use spidev or write a custom SPI device driver.

    Most Raspberry Pi projects don’t require writing a new SPI controller driver because it’s already included in the kernel.

    8. What is spi_common.h used for?

    spi_common.h contains common definitions and structures used across SPI subsystems in the Linux kernel.

    If you’re working on low-level SPI controller driver development, you’ll likely interact with headers like this to share common logic and structures.

    It helps maintain clean and reusable driver code.

    9. What is an SPI flash controller driver?

    A SPI flash controller driver manages communication with SPI-based flash memory.

    It handles:

    • Read and write commands
    • Sector erase
    • Page programming
    • Status register polling

    These drivers are critical in bootloaders and embedded Linux systems where firmware is stored in SPI flash.

    10. Why is my SPI driver not working even though the code looks correct?

    Most SPI issues are hardware configuration problems, not code errors.

    Common causes:

    • Wrong SPI mode (CPOL/CPHA mismatch)
    • Incorrect clock speed
    • Chip select timing issues
    • Wrong wiring
    • Endianness mismatch

    Always verify with a logic analyzer before blaming your SPI driver code.

    11. Should I write SPI driver in user space or kernel space?

    If you are prototyping or experimenting, user space via spidev is fine.

    If you are building production firmware or need high performance and proper interrupt handling, write a kernel-level SPI device driver.

    Kernel drivers offer better control and integration.

    12. Where can I get SPI driver download examples?

    You can find SPI driver download examples in:

    • Linux kernel source tree
    • Official SoC vendor SDKs
    • Open-source repositories
    • Raspberry Pi kernel source

    Always match your driver with the correct kernel version and hardware platform to avoid compatibility issues.

    If you’re new to virtualization concepts used in modern automotive and embedded systems, this guide on What Is a Hypervisor? 7 Powerful Reasons explains the fundamentals in plain language and helps you understand how platforms like QNX SDP 8.0 handle mixed-criticality and virtualized environments.

  • Master How to Write Platform Devices and Drivers (2026)

    Learn how to write Platform Devices and Drivers from scratch using Device Tree, I2C, interrupts, and testing, explained clearly for beginners.

    If you are stepping into Linux device driver development, sooner or later you will hear one phrase again and again: Platform Devices and Drivers.
    They sound complex at first, but once you understand the flow, they are actually one of the cleanest and most structured ways to write Linux drivers for embedded systems.

    In this article, we will go from zero to a working platform driver.
    We will start with the basic idea, then move step by step through implementation, device tree integration, I2C communication, interrupt handling, and finally testing and debugging.

    What Is Platform Devices and Drivers?

    Platform Devices and Drivers are a Linux kernel mechanism used to describe and manage on-board hardware that is not discoverable dynamically.

    Unlike USB or PCI devices, platform devices do not announce themselves.
    They are usually fixed on the board, soldered directly to the SoC or connected via internal buses like I2C or SPI.

    Examples include:

    • GPIO controllers
    • I2C sensors
    • RTC chips
    • Watchdog timers
    • Custom hardware blocks

    Linux needs a way to:

    1. Describe this hardware
    2. Match it with the correct driver
    3. Initialize it safely during boot

    That is exactly what platform devices and drivers do.

    Why Platform Devices and Drivers Matter in Embedded Linux

    If you work with embedded boards, you will almost always use Platform Devices and Drivers because:

    • Hardware is board-specific
    • There is no auto-detection
    • Device Tree is used to describe hardware
    • Drivers must bind cleanly during boot

    This model separates hardware description (Device Tree) from driver logic (kernel module), which makes systems easier to maintain and port.

    High-Level Architecture

    Before writing any code, let’s understand the flow:

    1. You buy an I2C chip (for example, a temperature sensor)
    2. You connect it to your board
    3. You describe it in the Device Tree
    4. Linux creates a platform device
    5. Your platform driver registers itself
    6. Kernel matches device and driver
    7. probe() function runs
    8. Driver initializes hardware
    9. Device becomes usable from user space

    Once you understand this flow, everything else fits naturally.

    From Purchase to Product: Real-World Scenario

    Let’s make this real.

    Imagine you purchased an I2C temperature sensor that:

    • Works over I2C
    • Has an interrupt pin
    • Is connected to your SoC

    Your goal:

    • Write a Linux driver
    • Handle I2C communication
    • Handle interrupts
    • Expose data to user space

    We will build this using Platform Devices and Drivers.

    Step 1: Understand the Hardware

    Before touching the kernel:

    • Read the datasheet
    • Note the I2C address
    • Register map
    • Interrupt behavior
    • Voltage levels

    Example details:

    • I2C address: 0x48
    • Interrupt active low
    • Data register at 0x00

    Never skip this step. Drivers written without understanding hardware always fail.

    Step 2: Device Tree Basics

    In modern Linux, Device Tree describes platform devices.

    The Device Tree tells the kernel:

    • Where the device is
    • How it is connected
    • What driver should bind to it

    Example Device Tree Node

    i2c1 {
        status = "okay";
    
        temp_sensor@48 {
            compatible = "vendor,temp-sensor";
            reg = <0x48>;
            interrupt-parent = <&gpio1>;
            interrupts = <12 IRQ_TYPE_EDGE_FALLING>;
        };
    };
    

    Important properties:

    • compatible → used for driver matching
    • reg → I2C address
    • interrupts → interrupt configuration

    This node becomes a platform device internally.

    Step 3: Platform Driver Structure

    A platform driver is a kernel module that registers itself using platform_driver.

    Basic Skeleton

    static int temp_probe(struct platform_device *pdev)
    {
        return 0;
    }
    
    static int temp_remove(struct platform_device *pdev)
    {
        return 0;
    }
    
    static const struct of_device_id temp_of_match[] = {
        { .compatible = "vendor,temp-sensor" },
        { }
    };
    MODULE_DEVICE_TABLE(of, temp_of_match);
    
    static struct platform_driver temp_driver = {
        .probe = temp_probe,
        .remove = temp_remove,
        .driver = {
            .name = "temp_sensor",
            .of_match_table = temp_of_match,
        },
    };
    
    module_platform_driver(temp_driver);
    

    This is the heart of Platform Devices and Drivers.

    Step 4: Driver and Device Matching

    Matching happens using the compatible string.

    • Device Tree provides compatible = "vendor,temp-sensor"
    • Driver declares the same string
    • Kernel binds them automatically

    If probe() is not called:

    • Check compatible string
    • Check Device Tree compilation
    • Check kernel logs

    Step 5: Accessing Device Tree Data

    Inside probe(), you can read properties from Device Tree.

    struct device *dev = &pdev->dev;
    struct device_node *np = dev->of_node;
    

    This lets you:

    • Read GPIO numbers
    • Read custom properties
    • Configure behavior per board

    This is why platform drivers are flexible.

    Step 6: Integrating I2C in Platform Drivers

    Many beginners get confused here.

    Yes, the device is on I2C, but the binding still happens via platform devices when using Device Tree.

    You usually:

    • Get the I2C adapter
    • Create an I2C client
    • Communicate using I2C APIs

    Example

    struct i2c_client *client;
    
    client = i2c_new_dummy_device(adapter, 0x48);
    

    Now you can read registers:

    i2c_smbus_read_byte_data(client, 0x00);
    

    This approach keeps hardware description separate from communication logic.

    Step 7: Interrupt Handling

    Interrupts are critical for real devices.

    Get IRQ Number

    int irq = platform_get_irq(pdev, 0);
    

    Register Interrupt Handler

    request_irq(irq, temp_irq_handler,
                IRQF_TRIGGER_FALLING,
                "temp_irq", dev);
    

    Interrupt Handler

    static irqreturn_t temp_irq_handler(int irq, void *dev_id)
    {
        // Read status register
        return IRQ_HANDLED;
    }
    

    Always keep interrupt handlers short and fast.

    Step 8: Exposing Data to User Space

    A driver is useless if user space cannot talk to it.

    Common approaches:

    • sysfs
    • character device
    • IIO subsystem (for sensors)

    Simple sysfs Example

    static ssize_t temp_show(struct device *dev,
                             struct device_attribute *attr,
                             char *buf)
    {
        return sprintf(buf, "25\n");
    }
    
    DEVICE_ATTR_RO(temp);
    

    This creates:

    /sys/devices/.../temp
    

    Step 9: Error Handling and Cleanup

    Good platform drivers always clean up.

    In remove():

    • Free IRQ
    • Unregister I2C client
    • Free memory
    free_irq(irq, dev);
    

    Never assume probe() always succeeds.

    Step 10: Building and Testing

    Compile the Driver

    • Add to kernel tree or as module
    • Enable in menuconfig

    Load Module

    insmod temp_driver.ko
    

    Check Logs

    dmesg | grep temp
    

    Verify Device Tree

    ls /proc/device-tree
    

    Testing is where most learning happens.

    Common Mistakes Beginners Make

    • Wrong compatible string
    • Forgetting to enable I2C bus
    • Interrupt polarity mismatch
    • Blocking code in IRQ handler
    • Ignoring return values

    Every one of these will cost you hours if you ignore basics.

    How to Write Platform Devices and Drivers

    // SPDX-License-Identifier: GPL-2.0
    /*
     * Production-ready Platform Driver example
     * - Device Tree based
     * - I2C sensor
     * - Interrupt handling
     * - sysfs interface
     */
    
    #include <linux/module.h>
    #include <linux/kernel.h>
    #include <linux/platform_device.h>
    #include <linux/of.h>
    #include <linux/of_irq.h>
    #include <linux/i2c.h>
    #include <linux/interrupt.h>
    #include <linux/slab.h>
    #include <linux/mutex.h>
    #include <linux/pm.h>
    #include <linux/sysfs.h>
    
    /* ---------- Driver Private Data ---------- */
    struct temp_dev {
    	struct device       *dev;
    	struct i2c_client   *client;
    	int                  irq;
    	int                  temperature;
    	struct mutex         lock;
    };
    
    /* ---------- I2C Read Helper ---------- */
    static int temp_sensor_read(struct temp_dev *tdev)
    {
    	int ret;
    
    	ret = i2c_smbus_read_byte_data(tdev->client, 0x00);
    	if (ret < 0)
    		dev_err(tdev->dev, "I2C read failed\n");
    
    	return ret;
    }
    
    /* ---------- Interrupt Handler ---------- */
    static irqreturn_t temp_irq_handler(int irq, void *data)
    {
    	struct temp_dev *tdev = data;
    	int temp;
    
    	mutex_lock(&tdev->lock);
    
    	temp = temp_sensor_read(tdev);
    	if (temp >= 0)
    		tdev->temperature = temp;
    
    	mutex_unlock(&tdev->lock);
    
    	dev_info(tdev->dev, "Interrupt: temperature=%d\n",
    		 tdev->temperature);
    
    	return IRQ_HANDLED;
    }
    
    /* ---------- sysfs Interface ---------- */
    static ssize_t temperature_show(struct device *dev,
    				struct device_attribute *attr,
    				char *buf)
    {
    	struct temp_dev *tdev = dev_get_drvdata(dev);
    	int temp;
    
    	mutex_lock(&tdev->lock);
    	temp = tdev->temperature;
    	mutex_unlock(&tdev->lock);
    
    	return sysfs_emit(buf, "%d\n", temp);
    }
    
    static DEVICE_ATTR_RO(temperature);
    
    static struct attribute *temp_attrs[] = {
    	&dev_attr_temperature.attr,
    	NULL,
    };
    
    static const struct attribute_group temp_attr_group = {
    	.attrs = temp_attrs,
    };
    
    /* ---------- Probe Function ---------- */
    static int temp_probe(struct platform_device *pdev)
    {
    	struct temp_dev *tdev;
    	struct i2c_adapter *adapter;
    	struct device *dev = &pdev->dev;
    	int ret;
    
    	dev_info(dev, "Probing temperature sensor\n");
    
    	tdev = devm_kzalloc(dev, sizeof(*tdev), GFP_KERNEL);
    	if (!tdev)
    		return -ENOMEM;
    
    	tdev->dev = dev;
    	mutex_init(&tdev->lock);
    	platform_set_drvdata(pdev, tdev);
    
    	/* Get I2C adapter (from DT bus number) */
    	adapter = i2c_get_adapter(1);
    	if (!adapter) {
    		dev_err(dev, "Failed to get I2C adapter\n");
    		return -ENODEV;
    	}
    
    	/* Create I2C client */
    	tdev->client = i2c_new_dummy_device(adapter, 0x48);
    	i2c_put_adapter(adapter);
    
    	if (IS_ERR(tdev->client)) {
    		dev_err(dev, "Failed to create I2C client\n");
    		return PTR_ERR(tdev->client);
    	}
    
    	/* Read initial value */
    	ret = temp_sensor_read(tdev);
    	if (ret >= 0)
    		tdev->temperature = ret;
    
    	/* Get IRQ from Device Tree */
    	tdev->irq = platform_get_irq(pdev, 0);
    	if (tdev->irq < 0) {
    		dev_err(dev, "Failed to get IRQ\n");
    		return tdev->irq;
    	}
    
    	ret = devm_request_irq(dev,
    			       tdev->irq,
    			       temp_irq_handler,
    			       IRQF_TRIGGER_FALLING,
    			       dev_name(dev),
    			       tdev);
    	if (ret) {
    		dev_err(dev, "Failed to request IRQ\n");
    		return ret;
    	}
    
    	/* Create sysfs group */
    	ret = sysfs_create_group(&dev->kobj, &temp_attr_group);
    	if (ret) {
    		dev_err(dev, "Failed to create sysfs group\n");
    		return ret;
    	}
    
    	dev_info(dev, "Temperature sensor driver loaded\n");
    	return 0;
    }
    
    /* ---------- Remove Function ---------- */
    static int temp_remove(struct platform_device *pdev)
    {
    	struct temp_dev *tdev = platform_get_drvdata(pdev);
    
    	sysfs_remove_group(&pdev->dev.kobj, &temp_attr_group);
    
    	if (tdev->client)
    		i2c_unregister_device(tdev->client);
    
    	dev_info(&pdev->dev, "Temperature sensor removed\n");
    	return 0;
    }
    
    /* ---------- Power Management ---------- */
    #ifdef CONFIG_PM_SLEEP
    static int temp_suspend(struct device *dev)
    {
    	dev_info(dev, "Suspending temperature sensor\n");
    	return 0;
    }
    
    static int temp_resume(struct device *dev)
    {
    	dev_info(dev, "Resuming temperature sensor\n");
    	return 0;
    }
    #endif
    
    static SIMPLE_DEV_PM_OPS(temp_pm_ops,
    			 temp_suspend,
    			 temp_resume);
    
    /* ---------- Device Tree Match ---------- */
    static const struct of_device_id temp_of_match[] = {
    	{ .compatible = "demo,temp-sensor" },
    	{ }
    };
    MODULE_DEVICE_TABLE(of, temp_of_match);
    
    /* ---------- Platform Driver ---------- */
    static struct platform_driver temp_driver = {
    	.probe  = temp_probe,
    	.remove = temp_remove,
    	.driver = {
    		.name           = "temp_sensor",
    		.of_match_table = temp_of_match,
    		.pm             = &temp_pm_ops,
    	},
    };
    
    module_platform_driver(temp_driver);
    
    MODULE_LICENSE("GPL");
    MODULE_AUTHOR("Nishant Singh");
    MODULE_DESCRIPTION("Production-ready Platform Driver with I2C and Interrupt");
    

    Device Tree

    &i2c1 {
    	status = "okay";
    
    	temp_sensor@48 {
    		compatible = "demo,temp-sensor";
    		reg = <0x48>;
    		interrupt-parent = <&gpio1>;
    		interrupts = <12 IRQ_TYPE_EDGE_FALLING>;
    	};
    };
    

    User Space Test

    cat /sys/devices/platform/temp_sensor/temperature
    

    Why Platform Devices and Drivers Scale Well

    Once you master Platform Devices and Drivers, you can:

    • Port drivers across boards
    • Reuse Device Tree files
    • Support multiple variants
    • Keep drivers clean and readable

    This is why the Linux kernel strongly encourages this model.

    FAQs : Platform Devices and Drivers.

    1. What are Platform Devices and Drivers in Linux?

    Platform Devices and Drivers are a Linux kernel mechanism used for non-discoverable hardware. These are devices that are permanently attached to the board, like I2C sensors, GPIO controllers, RTCs, and on-chip peripherals. Since such hardware cannot announce itself, Linux relies on the Device Tree to describe it and platform drivers to manage it.

    2. Why do we need Platform Drivers when using Device Tree?

    Device Tree only describes hardware.
    Platform drivers contain the actual code that talks to the hardware. The kernel uses the compatible string in the Device Tree to match a platform device with the correct platform driver and then calls the driver’s probe() function.

    3. What is the role of the probe() function?

    The probe() function is where everything starts. It is called when the kernel successfully matches a platform device with its driver. In probe(), you:

    • Allocate memory
    • Read Device Tree properties
    • Initialize hardware
    • Register interrupts
    • Create sysfs or character devices

    If probe() fails, the device will not work.

    4. How does Device Tree match a Platform Driver?

    Matching is done using the compatible string.
    The Device Tree node provides a compatible property, and the platform driver provides an of_device_id table with the same string. If they match exactly, the kernel binds them together.

    5. Can Platform Drivers be used for I2C or SPI devices?

    Yes. This is very common.
    Even though the device communicates over I2C or SPI, the binding still happens through Platform Devices and Drivers when using Device Tree. Inside the platform driver, you create or access an I2C or SPI client to communicate with the hardware.

    6. What is the difference between a Platform Driver and an I2C Driver?

    An I2C driver is tied directly to the I2C subsystem and is usually auto-created by the I2C core.
    A Platform Driver is more generic and is often used when:

    • You need board-specific logic
    • The device uses multiple resources (IRQ, GPIO, regulators)
    • You want tighter control over initialization

    Both approaches are valid and used in production.

    7. How are interrupts handled in Platform Drivers?

    Interrupts are described in the Device Tree using the interrupts property.
    Inside the driver, you retrieve the IRQ number using platform_get_irq() and register a handler using request_irq() or devm_request_irq(). The interrupt handler should be fast and should avoid sleeping or heavy processing.

    8. What is devm_* and why should it be used?

    devm_* APIs automatically free resources when the device is removed.
    They reduce memory leaks and simplify error handling. In production drivers, devm_kzalloc(), devm_request_irq(), and similar APIs are strongly recommended.

    9. How do Platform Drivers expose data to user space?

    Common methods include:

    • sysfs attributes
    • character devices
    • standard kernel subsystems like IIO, input, or hwmon

    For simple data like sensor readings, sysfs is often enough. For high-performance or streaming data, character devices or IIO are better choices.

    10. What are the most common reasons probe() is not called?

    The most common reasons are:

    • Mismatch in compatible string
    • Device Tree node not compiled or loaded
    • Driver not enabled in kernel configuration
    • Incorrect Device Tree hierarchy (wrong bus node)

    Checking dmesg usually points you in the right direction.

    11. Are Platform Drivers used in real production kernels?

    Absolutely.
    Most SoC drivers, board-level drivers, and embedded peripherals in the Linux kernel are implemented using Platform Devices and Drivers. This model scales well and is heavily used by vendors and upstream kernel developers.

    12. When should I avoid using Platform Devices and Drivers?

    You should avoid platform drivers if:

    • The hardware is self-discoverable (USB, PCI)
    • The kernel already provides a dedicated subsystem driver
    • You are writing a pure user-space driver

    In those cases, platform drivers would add unnecessary complexity.

    You can also read : Linked List Coding Questions