在前面学习了树莓派字符设备驱动代码编写和编译,但一直不是特别明白,现在学习100ask_imx6ull_mini的驱动框架时更加清楚了一些,所以重新记录下来。整个编写和编译流程与树莓派区别不大,思路相同。
内核模块的编译(树莓派内核模块编译)都需要提前对LINUX源码进行配置编译(树莓派linux源码配置编译)
编写驱动程序步骤:
imx-linux4.9.88\include\linux目录下fs.h中的file_operations 结构体:
可以参考imx-linux4.9.88\drivers\char目录下的misc.c文件编写驱动程序
hello_drv.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MIN(a,b) (a
hello_drv_test.c
#include
#include
#include
#include
#include
#include
/*
*./hello_drv_test -w abc
*./hello_drv_test -r
*/
int main(int argc,char **argv)
{
if(argc <2)
{
printf("Usage:%s -w \n",argv[0]);
printf("Usage:%s -r \n",argv[0]);
return -1;
}
int fd;
char buf[1024];
fd = open("/dev/hello",O_RDWR);
if(-1==fd)
{
printf("can not open /dev/hello\n");
return -1;
}
if(strcmp(argv[1],"-w")==0 && argc==3)
{
write(fd, argv[2], strlen(argv[2]));
}else
{
read(fd,buf,1024);
buf[1023] = '\n';
printf("APP get data %s",buf);
}
close(fd);
return 0;
}
以100ask_imx6ull MINI开发板为例(可以参考前面有关的博文):
编译驱动代码需要一个提前编译好的内核
make mrproper
make 100ask_imx6ull_mini_defconfig
make zImage -jN //N表示根据CPU个数,来加速编译系统
make dtbs
// 复制到网络文件系统目录备用
cp arch/arm/boot/zImage ~/nfs_rootfs
cp arch/arm/boot/dts/100ask_myir_imx6ull_mini.dtb ~/nfs_rootfs
如果执行make 100ask_imx6ull_mini_defconfig
报错显示找不到路径,需要去相应目录下查看是否有该目录,这里是将厂家提供的_defconfig配置到 .config里。
1.将驱动代码hello_drv.c 放到字符设备目录下
2.进入Makefile 文件,需要把驱动按模块编译进内核,需要添加下面一行
obj-m += hello_drv.o
3.编译内核模块(最终会生成.ko文件)
注意一定要回到内核目录下(…linux-4.4/)进行编译
make ARCH=arm CROSS_COMPILE=arm-buildroot-linux-gnueabihf- modules
4.编译测试程序
arm-buildroot-linux-gnueabihf-gcc hello_drv_test.c -o Test
拷贝到nfs目录下
也可以借助Makefile文件直接执行make命令完成编译:
Makefile
# 1. 使用不同的开发板内核时, 一定要修改KERN_DIR
# 2. KERN_DIR中的内核要事先配置、编译, 为了能编译内核, 要先设置下列环境变量:
# 2.1 ARCH, 比如: export ARCH=arm64
# 2.2 CROSS_COMPILE, 比如: export CROSS_COMPILE=aarch64-linux-gnu-
# 2.3 PATH, 比如: export PATH=$PATH:/home/book/100ask_roc-rk3399-pc/ToolChain-6.3.1/gcc-linaro-6.3.1-2017.05-x86_64_aarch64-linux-gnu/bin
# 注意: 不同的开发板不同的编译器上述3个环境变量不一定相同,
# 请参考各开发板的高级用户使用手册
KERN_DIR = /home/book/100ask/linux-4.4
all:
make -C $(KERN_DIR) M=`pwd` modules
$(CROSS_COMPILE)gcc -o hello_drv_test hello_drv_test.c
clean:
make -C $(KERN_DIR) M=`pwd` modules clean
rm -rf modules.order
rm -f hello_drv_test
obj-m += hello_drv.o
需要把程序放到ARM板子上运行,这里使用NFS挂载Ubuntu的某个目录,访问该目录中的程序。这也是前面拷贝程序到NFS目录的原因。
将编译内核模块生成的.ko拷贝到NFS目录
cp *.ko ~/nfs_rootfs/
insmod hello_drv.ko // 安装驱动程序
ls /dev/hello -l // 驱动程序会生成设备节点
运行测试程序
./hello_drv_test -w heavysea
./hello_drv_test -r
dmesg |grep hello // 查看内核态打印的有关驱动的信息
rmmod hello_drv.ko // 卸载驱动模块