linux驱动编程——第一个驱动Helloworld

linux驱动编程——第一个驱动Helloworld

主要概念:

linux三大驱动:

​ 字符设备、网络设备、块设备。

驱动是连接硬件和内核的桥梁
驱动编译方式:

​ 驱动编译成模块,使用的时候使用insmod命令加载

​ 驱动编译进内核,设备开机即加载好了驱动。

实验目的:

​ 熟悉驱动框架编写,编译,加载流程。

主要函数调用:

驱动主要分为四部分:

​ 头文件

​ 驱动模块的入口及出口函数

​ 声明信息

​ 功能实现

#include <linux/init.h> 		//包含宏定义的头文件
#include <linux/module.h> 		//包含初始化加载模块的头文件
module_init();					//驱动入口
module_exit();					//驱动出口
MODULE_LICENSE("GPL");			//声明开源许可证
static int hello_init(void);	//入口函数共嗯那个实现
static void hello_exit(void);	//出口函数功能实现

代码:

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

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

static void hello_exit(void)
{
	printk("byebye!\r\n");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("SIXER");	//声明作者信息
注意:

​ Linux驱动是属于内核部分的,其打印是通过 printk 函数,而不是 printf 函数。

编译运行:

​ 这里我们编写了一个 Makefile,方便我们的编译。

Makefile
KERNELDIR := /home/sixer/imx_kernel/linux-imx-rel_imx_4.1.15_2.1.0_ga
CURRENT_PATH := $(shell pwd)

export ARCH=arm
export CROSS_COMPILE=arm-linux-gnueabihf-

target := helloworld
obj-m := $(target).o
APP_NAME := $(target)_app

build: kernel_modules

kernel_modules:
	$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) modules

clean:
	$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) clean

dir_exist = $(shell if [ -d "/nfsroot/$(target)/" ]; then echo "exist"; else echo "noexist"; fi)
$(info $(dir_exist))

install:
ifeq ("$(dir_exist)", "noexist")
	$(shell mkdir /nfsroot/$(target))
	#"文件夹不存在,已重新创建文件夹"
endif
	cp *.ko  /nfsroot/$(target)/


回到Makefile目录,使用如下命令

make 将 helloworld 将 .c 编译成驱动模块 helloworld.ko

make install 这里我使用这个命令拷贝目标文件到我搭建的 nfs 目录下。

不熟悉nfs的话可以通过其他途径拷贝编译的目标文件 helloworld.ko 到开发板。

Makefile注意事项:

​ KERNELDIR 为内核源码目录,驱动编译的过程中需要使用一些内核源码,所以这个目录必须准确指定为我们开发板使用系统内核对应的内核源码目录。

​ 必须指定 arm 架构及交叉编译器 arm-linux-gnueabihf-。

​ install 为方便目标文件拷贝编写的。

实验现象:

[root@iTOP-iMX6UL]# cd /mnt/nsf_dir/
[root@iTOP-iMX6UL]# ls
02gpioled   chartest    demo.c      helloworld  misc.c      pipe1.c
[root@iTOP-iMX6UL]# cd helloworld/
[root@iTOP-iMX6UL]# ls
helloworld.ko
[root@iTOP-iMX6UL]# insmod helloworld.ko 
hello, world!
[root@iTOP-iMX6UL]# rmmod helloworld.ko 
byebye!
[root@iTOP-iMX6UL]# 

总结:

​ 通过一个 helloworld 的驱动实现,可见,驱动的基本框架真的是很容易掌握的。所以,驱动开发的知识,只是多,而不是复杂,学习的时候一定要多花笨功夫。

公众号:

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嵌入式小鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值