嵌入式学习(一)之Linux驱动基础

151 阅读1分钟

Linux 驱动的分类

  1. 字符设备驱动(可操作性最多)
  2. 块设备驱动
  3. 网络设备驱动

编译驱动成模块,然后加载进内核

  1. 把驱动编译成模块, *.ko 文件
  • 编写驱动程序,示例 hello.c
  • 编写Makefile
  • 将 hello.c 和 Makefile 文件拷贝到 Liunx环境下
  • 设置编译环境
    • 前提:内核源码已经编译通过
    • 设置芯片类型:export ARCH=arm
    • 设置编译器:export CROSS_COMPILE=arm-linux-gnueabihf-
  • 执行命令 make
  • 查看是否生成 .ko 文件
  1. 使用命令把驱动加载到内核里
  • 将 .ko 文件拷贝到挂载的开发板里
  • insmod hello.ko
    • 加载模块
  • modprode hello.ko
    • 加载模块,同时加载这个模块所依赖的模块
  1. 检查驱动
  • lsmod 查看加载的模块
  • remod hello.ko 卸载驱动模块
  • modeinfo hello.ko

cat /proc/modules

  1. hello.c 文件
#include <linux/init.h>
#include <linux/module.h>

// 实现
static int hello_init(void) {
    printk("hello init");
    return 0;
}

static void hello_exit(void) {
    printk("hello bye");
}

// 入口
module_init(hello_init);
// 退出
module_exit(hello_exit);


MODULE_LICENSE("GPL");
  1. Makefile 文件
obj-m +=hello.o

# 编译开发板使用的内核源码路径
# 且此内核源码已编译通过
KDIR:=/home/xxx/linux-xxx

# 当前路径
PWD?=$(shell pwd)

all:
    make -C $(KDIR) M=$(PWD) modules
clean:
    rm -f *.ko *.o *.mod.o *mod.c *.order *.symvers

关于内核源码

更多参考资料

把驱动编译进内核

cd drivers/char

mkdir hello

cd hello

  1. drivers/char/hello/Kconfig
config HELLO
	tristate "Hello World Support"
	help
	  hello xxx
  1. drivers/char/hello/Makefile
obj-$(CONFIG_HELLO)+=hello.o
  1. drivers/char/hello/hello.c

  1. drivers/char/Makefile

添加内容

obj-y +=hello/
  1. drivers/char/Kconfig

添加内容

# 最后一行
source "drivers/char/hello/Kconfig"
  1. make menuconfig

  2. 编译内核

cd /

vi create.sh

修改

make imx_v7_defconfig -> my_contain_hello_config

./create.sh

  1. 检查是否生成 zImage 镜像

ls arch/arm/boot

make menuconfig

图形化配置界面

  1. 问题及解决方案 image.png

  2. 选项配置

image.png

  1. 有关文件

image.png

  1. Kconfig 文件

image.png

  1. .config文件

image.png

加载模块传入参数

image.png

modeinfo hello.ko

insmod hello.ko a=1 array=1,2,3,4 str=hicat

符号表

image.png

image.png

总结

image.png