九鼎RK3399笔记二:编译驱动模块并加载

将驱动在外部编译为模块

一、在内核源码附近新建文件夹hello

1、在hello文件夹新建hello.c

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

static int hello_init(void)
{
    printk("hello world 1019\n"); 
    return 0;
}

static void hello_exit(void)
{
    printk("bye bye\n"); 
    return;
}  

module_init(hello_init);//模块入口
module_exit(hello_exit);//模块出口
MODULE_LICENSE("GPL");

2、在hello文件夹新建Makefile

# -m 的意思是把我们的驱动编译成模块,后面接文件名.o
obj-m += hello.o
# 这里填写板子里运行的内核的源码目录,该内核源码必须是编译通过的
KDIR:=/test/doc/x3399/x3399_linux_new/kernel/
# 获取当前目录
PWD?=$(shell pwd)
#make 会进入内核源码的路径,然后把当前路径下的代码编译成模块
#make 指令前面必须按tab,不能用4个空格代替
all:
	make -C $(KDIR) M=$(PWD) modules

二、新建脚本并编译

1、在hello文件夹新建build.sh
ARCH值取决于板子,CROSS_COMPILE值取的是和编译kernel一样的编译链

export ARCH=arm64
export CROSS_COMPILE=aarch64-linux-gnu-
make

2、编译

不能执行./build.sh就改文件权限:chmod 777 -R hello
./build.sh

执行完之后,hello文件夹下应该生成hello.ko

三、TFTP发送到板子并加载

1、板子网线连接PC,输入ifconfig查看板子IP,和我们电脑假如不在一个网段,PC为192.168.1.100,那么更改板子IP:
ifconfig eth0 192.168.1.10 netmask 255.255.255.0
参考:https://blog.csdn.net/u013171226/article/details/120987572

2、板子ping 192.168.1.100,能成功才能传输文件。打开tftpd32软件,选择hello.ko所在目录,
从服务器获得文件:
tftp –g –r filename ipaddr(主机的ip)
上传文件到服务器:
tftp –p –l filename ipaddr(开发板的ip)
tftp -g -r hello.ko 192.168.1.100
就把hello.ko传到开发板文件系统中了。

3、加载模块
insmod hello.ko
卸载模块
rmmod hello
可以看到打印
image

将驱动和内核一起编译

一、在/drivers/char/路径建立一个hello文件夹

hello文件夹中新建Makefile、Kconfig、helloworld.c(helloworld.c和外部编译一样,无需修改)

Makefile:
obj-$(CONFIG_HELLO)+=helloworld.o

Kconfig:

config HELLO
	tristate "hello world"
	help
	hello

二、修改hello文件夹上一级的Makefile和Kconfig

/drivers/char/Makefile:
+obj-y +=hello/
/drivers/char/Kconfig:
+source "drivers/char/hello/Kconfig"

三、make menuconfig

在内核根目录 make menuconfig,选择将模块编译进内核(*)
image

四、重新编译内核

make
编译成功后,烧写进开发板,启动信息里可以看到模块加载打印的信息
image

posted @ 2022-10-19 16:30  solonj  阅读(461)  评论(0编辑  收藏  举报