前言
前段时间买了一个orangepi5pro开发板,准备学习驱动开发,但是网上教程基本都需要在自己电脑安装虚拟机,下载内核源码,编译内核后才能进行驱动开发,但我想直接在【开发板】上进行开发,不采用虚拟机!!!
环境准备与编译
主要参考【腾讯元宝】和【通义千问】AI模型的回答。
(1)工具链安装
# 安装基础编译工具
sudo apt update
sudo apt install build-essential flex bison libelf-dev bc openssl libssl-dev# 安装ARM64专用编译工具(可选,用于特定场景)
sudo apt install gcc-arm-linux-gnueabihf
(2)安装linux-headers-xxx(重要)
去官方仓库下载:https://github.com/orangepi-xunlong/orangepi-build
1、使用git方法:git clone https://github.com/orangepi-xunlong/orangepi-build (代理加速的话,参考 https://gh-proxy.com
2、下载zip后解压也行
解压后进入文件夹,运行build.sh脚本
cd orangepi-build-next
./build.sh
弹出界面,依次选择【Kernel package】【Show a kernel configuration menu before compilation】【(选自己开发板的版本)】【current Recommended. Come with best support】
等待1小时左右,期间会自动去下载内核源码(下载失败的话重复几次),然后编译
编译输出在【/home/orangepi/orangepi-build-next/output】,linux-headers-xxx就在debs目录下
安装:
sudo dpkg -i linux-headers-current-rockchip-rk3588_1.0.6_arm64.deb
# 该 .deb 会被安装到类似 /usr/src/linux-headers-6.1.43-rockchip-rk3588/ 的路径
创建符号链接
sudo ln -sf /usr/src/linux-headers-$(uname -r) /lib/modules/$(uname -r)/build
# -sf表示强制创建链接,如果已有损坏的会被自动覆盖
# 使用命令 ls -l /lib/modules/$(uname -r)/build验证是否成功
创建第一个驱动
创建驱动有2种方法:
- 在内核源码中添加驱动代码,然后编译进内核源码中,再烧写到板子上
- 编写内核模块,然后在已经安装了系统的开发板中加载内核模块就行
下面使用的是第2个方法
cd ~
mkdir ~/mydriver
cd ~/mydriver
mkdir hello
cd hello
在"/home/orangepi/mydriver/hello"路径下,按照以下步骤操作
创建代码:命令 【nano hello.c】,写入以下内容
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>MODULE_LICENSE("GPL");
MODULE_AUTHOR("YourName");
MODULE_DESCRIPTION("A simple Hello World module");
MODULE_VERSION("0.1");static int __init hello_init(void)
{pr_info("Hello, Orange Pi 5 Pro! This is my first driver!\n");return 0;
}static void __exit hello_exit(void)
{pr_info("Goodbye, Orange Pi 5 Pro! Module removed.\n");
}module_init(hello_init);
module_exit(hello_exit);
创建makefile,【nano Makefile】,写入以下内容
obj-m += hello.oKDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)default:$(MAKE) -C $(KDIR) M=$(PWD) modulesclean:$(MAKE) -C $(KDIR) M=$(PWD) cleaninstall:sudo insmod hello.koremove:sudo rmmod hello
编译:make
安装(会加载内核模块):sudo make install
查看输出(内核模块加载时会执行代码__init函数):dmesg | tail -5
删除:sudo make remove
再查看输出(卸载内核模块会执行代码__exit函数):dmesg | tail -5