為 raspberrypi 開發核心模組

來源:互聯網
上載者:User
有時候為了方便與硬體更好互動,可能會需要為它專門寫個驅動。這就涉及到了核心模組的開發。

其實核心模組的開發沒有想象的那麼複雜,也就是準備工作有點繁瑣,開源的東西都這樣,一切都得自己來。

## 安裝kernel header源碼
首先查看當前使用的核心版本

$ uname -r
3.6.11+

我的系統是`2013-02-09-wheezy-raspbian`,所以顯示出來的核心版本是`3.6.11+`

首先看看apt源裡面有沒有,有的話直接安裝

$ apt-cache search linux-headers

沒有找到`3.6.11+`相關的,其中的`3.6`的一些down下來也沒法用。

下面就手動把`3.6.11+`的header-src搞下來。

下載3.6.11+的核心源碼
$ wget https://github.com/raspberrypi/linux/archive/rpi-3.6.y.tar.gz

解壓
$ tar xvfz rpi-3.6.y.tar.gz

取得root許可權
$ su

將源碼移至/usr/src目錄
# mv linux-rpi-3.6.y /usr/src

建立核心模組庫目錄的連結
# ln -s /usr/src/linux-rpi-3.6.y /lib/modules/3.6.11+/build

# cd /lib/modules/3.6.11+/build

make mrproper可以看作更加強勁的make clean命令,用來清除環境變數,即清除設定檔,一般編譯核心前都要運行
# make mrproper

將當前正在使用的系統的核心配置產生核心配置資訊
# gzip -dc /proc/config.gz > .config

產生編譯核心所需要的東西
# make modules_prepare

擷取核心編譯時間產生的核心模組匯出符號檔案,因為不是從頭編譯核心,所以沒有,但是編譯核心模組需要這個
# wget https://github.com/raspberrypi/firmware/raw/master/extra/Module.symvers

退出root
# exit

## 編寫hello world 核心模組

寫一個最簡單的核心模組 `hello.c`, 這個核心只會在載入的時候輸出 `helo,word`,移除時輸出`goodbye`

在樹梅派上找個地方建立一個目錄,建立檔案`hello.c`:

#include #include MODULE_LICENSE("Dual BSD/GPL");

static int hello_init(void) {
printk(KERN_ALERT "Hello, world");
return 0;
}

static void hello_exit(void) {
printk(KERN_ALERT "Goodbye, cruel world");
}

module_init(hello_init);
module_exit(hello_exit);

建立`Makefile`檔案:

#include #include MODULE_LICENSE("Dual BSD/GPL");

static int hello_init(void) {
printk(KERN_ALERT "Hello, world");
return 0;
}

static void hello_exit(void) {
printk(KERN_ALERT "Goodbye, cruel world");
}

module_init(hello_init);
module_exit(hello_exit);

準備工作做好了,現在開始編譯

$ make

會產生以下檔案:

$ ls
hello.c hello.mod.c hello.o modules.order
hello.ko hello.mod.o Makefile Module.symvers

查看這個核心模組的資訊:

$ modinfo hello.ko
filename: /home/pi/sensors/kernel-model/hello.ko
license: Dual BSD/GPL
srcversion: 9AE281A251509460F68E55F
depends:
vermagic: 3.6.11 preempt mod_unload modversions ARMv6

載入核心:

$ sudo sudo insmod hello.ko

命令列沒有輸出,別急,繼續移除它:

$ sudo rmmod hello

現在查看輸出:

$ dmesg | tail -5
[ 7175.039569] Hello, world
[ 7199.989110] Goodbye, cruel world

可以看到,這個hello核心模組工作的很正常

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.