【学习笔记】linux内核添加一个字符驱动

本文详细介绍了如何在Linux系统中编写、编译、加载和卸载一个简单的平台设备驱动模块,包括驱动文件、Makefile和Kconfig的创建,以及驱动加载和卸载的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步:编写驱动文件

#include <linux/init.h>
#include <linux/module.h>
#include <linux/of_device.h>
#include <linux/platform_device.h>

static int hello_probe(struct platform_device *pdev)
{
	printk("probe hello\n");
	return 0;
}

static int hello_remove(struct platform_device *pdev)
{
	printk("remove hello\n");
	return 0;
}

static const struct of_device_id hello_of_match[] __maybe_unused = {
	{ .compatible	= "microchip,hello", },
	{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, hello_of_match);

static struct platform_driver hello_driver = {
	.probe		= hello_probe,
	.remove		= hello_remove,
	.driver		= {
		.name	= "hello",
		.of_match_table = of_match_ptr(hello_of_match),
	},
};

module_platform_driver(hello_driver);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Star liuxing");
MODULE_DESCRIPTION("Microchip PIC32 RNG Driver");

第二步:编写 Makefile 文件

这里 Makefile 文件的内容格式基本是固定的
KVERS = $(shell uname -r)

obj-m += hello.o

build: kernel_modules

EXTRA_CFLAGS = -g -o0

kernel_modules:
	make -C /lib/modules/$(KVERS)/build M=$(CURDIR) modules
clean:
	make -C /lib/modules/$(KVERS)/build M=$(CURDIR) clean

第三步:编写 Kconfig 文件

Kconfig 文件在这个驱动里面是可有可无的,因为我们是把驱动编译成模块的
config HELLO
	bool "HELLO driver support"

第四步:在 linux 系统当前版本源码路径 如 /usr/src/linux 下面 ./drivice/char/ 目录下创建新的文件夹 char_device,并将之前编辑好的三个文件复制到该目录下即 /usr/src/linux/drivice/char/char_device/

可以在任意目录下创建 char_device 目录

在这里插入图片描述

第五步:执行 sudo make 命令,生成 hello.ko 文件

如果是在自己的目录下可以不用加 sudo

在这里插入图片描述

第六步:查看当前系统加载的驱动 lsmod

在这里插入图片描述

第七步:加载 hello 驱动

sudo insmod hello.ko

第八步:执行第六步对比加载的驱动差异

在这里插入图片描述

第九步:卸载 hello 驱动

sudo rmmod hello.ko

第十步:执行第六步对比加载的驱动差异

在这里插入图片描述

第十一步:打开 /var/log/kern.log 内核日志查看驱动加载和卸载的情况

暂时不知道什么原因,日志中可能会看不到添加的打印
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值